1 ;;; Guile bytecode assembler
3 ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013, 2014, 2015 Free Software Foundation, Inc.
5 ;;; This library is free software; you can redistribute it and/or
6 ;;; modify it under the terms of the GNU Lesser General Public
7 ;;; License as published by the Free Software Foundation; either
8 ;;; version 3 of the License, or (at your option) any later version.
10 ;;; This library is distributed in the hope that it will be useful,
11 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;; Lesser General Public License for more details.
15 ;;; You should have received a copy of the GNU Lesser General Public
16 ;;; License along with this library; if not, write to the Free Software
17 ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 ;;; This module implements an assembler that creates an ELF image from
22 ;;; bytecode assembly and macro-assembly. The input can be given in
23 ;;; s-expression form, like ((OP ARG ...) ...). Internally there is a
24 ;;; procedural interface, the emit-OP procedures, but that is not
25 ;;; currently exported.
27 ;;; "Primitive instructions" correspond to VM operations. Assemblers
28 ;;; for primitive instructions are generated programmatically from
29 ;;; (instruction-list), which itself is derived from the VM sources.
30 ;;; There are also "macro-instructions" like "label" or "load-constant"
31 ;;; that expand to 0 or more primitive instructions.
33 ;;; The assembler also handles some higher-level tasks, like creating
34 ;;; the symbol table, other metadata sections, creating a constant table
35 ;;; for the whole compilation unit, and writing the dynamic section of
36 ;;; the ELF file along with the appropriate initialization routines.
38 ;;; Most compilers will want to use the trio of make-assembler,
39 ;;; emit-text, and link-assembly. That will result in the creation of
40 ;;; an ELF image as a bytevector, which can then be loaded using
41 ;;; load-thunk-from-memory, or written to disk as a .go file.
45 (define-module (system vm assembler)
46 #:use-module (system base target)
47 #:use-module (system vm dwarf)
48 #:use-module (system vm elf)
49 #:use-module (system vm linker)
50 #:use-module (language bytecode)
51 #:use-module (rnrs bytevectors)
52 #:use-module (ice-9 binary-ports)
53 #:use-module (ice-9 vlist)
54 #:use-module (ice-9 match)
55 #:use-module (srfi srfi-1)
56 #:use-module (srfi srfi-4)
57 #:use-module (srfi srfi-9)
58 #:use-module (srfi srfi-11)
59 #:export (make-assembler
65 (emit-receive* . emit-receive)
71 (emit-builtin-ref* . emit-builtin-ref)
80 emit-assert-nargs-ee/locals
92 (emit-br-if-eq* . emit-br-if-eq)
93 (emit-br-if-eqv* . emit-br-if-eqv)
94 (emit-br-if-equal* . emit-br-if-equal)
95 (emit-br-if-=* . emit-br-if-=)
96 (emit-br-if-<* . emit-br-if-<)
97 (emit-br-if-<=* . emit-br-if-<=)
98 (emit-br-if-logtest* . emit-br-if-logtest)
99 (emit-mov* . emit-mov)
100 (emit-box* . emit-box)
101 (emit-box-ref* . emit-box-ref)
102 (emit-box-set!* . emit-box-set!)
104 (emit-free-ref* . emit-free-ref)
105 (emit-free-set!* . emit-free-set!)
108 (emit-define!* . emit-define!)
112 (emit-wind* . emit-wind)
114 (emit-push-fluid* . emit-push-fluid)
116 (emit-fluid-ref* . emit-fluid-ref)
117 (emit-fluid-set* . emit-fluid-set)
118 (emit-string-length* . emit-string-length)
119 (emit-string-ref* . emit-string-ref)
120 (emit-string->number* . emit-string->number)
121 (emit-string->symbol* . emit-string->symbol)
122 (emit-symbol->keyword* . emit-symbol->keyword)
123 (emit-cons* . emit-cons)
124 (emit-car* . emit-car)
125 (emit-cdr* . emit-cdr)
126 (emit-set-car!* . emit-set-car!)
127 (emit-set-cdr!* . emit-set-cdr!)
128 (emit-add* . emit-add)
129 (emit-add1* . emit-add1)
130 (emit-sub* . emit-sub)
131 (emit-sub1* . emit-sub1)
132 (emit-mul* . emit-mul)
133 (emit-div* . emit-div)
134 (emit-quo* . emit-quo)
135 (emit-rem* . emit-rem)
136 (emit-mod* . emit-mod)
137 (emit-ash* . emit-ash)
138 (emit-logand* . emit-logand)
139 (emit-logior* . emit-logior)
140 (emit-logxor* . emit-logxor)
141 (emit-make-vector* . emit-make-vector)
142 (emit-make-vector/immediate* . emit-make-vector/immediate)
143 (emit-vector-length* . emit-vector-length)
144 (emit-vector-ref* . emit-vector-ref)
145 (emit-vector-ref/immediate* . emit-vector-ref/immediate)
146 (emit-vector-set!* . emit-vector-set!)
147 (emit-vector-set!/immediate* . emit-vector-set!/immediate)
148 (emit-struct-vtable* . emit-struct-vtable)
149 (emit-allocate-struct/immediate* . emit-allocate-struct/immediate)
150 (emit-struct-ref/immediate* . emit-struct-ref/immediate)
151 (emit-struct-set!/immediate* . emit-struct-set!/immediate)
152 (emit-allocate-struct* . emit-allocate-struct)
153 (emit-struct-ref* . emit-struct-ref)
154 (emit-struct-set!* . emit-struct-set!)
155 (emit-class-of* . emit-class-of)
156 (emit-make-array* . emit-make-array)
157 (emit-bv-u8-ref* . emit-bv-u8-ref)
158 (emit-bv-s8-ref* . emit-bv-s8-ref)
159 (emit-bv-u16-ref* . emit-bv-u16-ref)
160 (emit-bv-s16-ref* . emit-bv-s16-ref)
161 (emit-bv-u32-ref* . emit-bv-u32-ref)
162 (emit-bv-s32-ref* . emit-bv-s32-ref)
163 (emit-bv-u64-ref* . emit-bv-u64-ref)
164 (emit-bv-s64-ref* . emit-bv-s64-ref)
165 (emit-bv-f32-ref* . emit-bv-f32-ref)
166 (emit-bv-f64-ref* . emit-bv-f64-ref)
167 (emit-bv-u8-set!* . emit-bv-u8-set!)
168 (emit-bv-s8-set!* . emit-bv-s8-set!)
169 (emit-bv-u16-set!* . emit-bv-u16-set!)
170 (emit-bv-s16-set!* . emit-bv-s16-set!)
171 (emit-bv-u32-set!* . emit-bv-u32-set!)
172 (emit-bv-s32-set!* . emit-bv-s32-set!)
173 (emit-bv-u64-set!* . emit-bv-u64-set!)
174 (emit-bv-s64-set!* . emit-bv-s64-set!)
175 (emit-bv-f32-set!* . emit-bv-f32-set!)
176 (emit-bv-f64-set!* . emit-bv-f64-set!)
184 ;; Like define-inlinable, but only for first-order uses of the defined
185 ;; routine. Should residualize less code.
187 (define-syntax define-inline
190 ((_ (name arg ...) body ...)
191 (with-syntax (((temp ...) (generate-temporaries #'(arg ...))))
192 #`(eval-when (expand)
193 (define-syntax-rule (name temp ...)
194 (let ((arg temp) ...)
197 ;;; Bytecode consists of 32-bit units, often subdivided in some way.
198 ;;; These helpers create one 32-bit unit from multiple components.
200 (define-inline (pack-u8-u24 x y)
202 (error "out of range" x))
203 (logior x (ash y 8)))
205 (define-inline (pack-u8-s24 x y)
207 (error "out of range" x))
209 ((< 0 (- y) #x800000)
213 (else (error "out of range" y)))
216 (define-inline (pack-u1-u7-u24 x y z)
218 (error "out of range" x))
220 (error "out of range" y))
221 (logior x (ash y 1) (ash z 8)))
223 (define-inline (pack-u8-u12-u12 x y z)
225 (error "out of range" x))
226 (unless (<= 0 y 4095)
227 (error "out of range" y))
228 (logior x (ash y 8) (ash z 20)))
230 (define-inline (pack-u8-u8-u16 x y z)
232 (error "out of range" x))
234 (error "out of range" y))
235 (logior x (ash y 8) (ash z 16)))
237 (define-inline (pack-u8-u8-u8-u8 x y z w)
239 (error "out of range" x))
241 (error "out of range" y))
243 (error "out of range" z))
244 (logior x (ash y 8) (ash z 16) (ash w 24)))
247 (define-syntax pack-flags
249 ;; Add clauses as needed.
250 ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
251 (if f2 (ash 2 0) 0))))))
253 ;;; Helpers to read and write 32-bit units in a buffer.
255 (define-inline (u32-ref buf n)
256 (bytevector-u32-native-ref buf (* n 4)))
258 (define-inline (u32-set! buf n val)
259 (bytevector-u32-native-set! buf (* n 4) val))
261 (define-inline (s32-ref buf n)
262 (bytevector-s32-native-ref buf (* n 4)))
264 (define-inline (s32-set! buf n val)
265 (bytevector-s32-native-set! buf (* n 4) val))
270 ;;; A <meta> entry collects metadata for one procedure. Procedures are
271 ;;; written as contiguous ranges of bytecode.
274 (define-syntax-rule (assert-match arg pattern kind)
276 (unless (match x (pattern #t) (_ #f))
277 (error (string-append "expected " kind) x)))))
279 (define-record-type <meta>
280 (%make-meta label properties low-pc high-pc arities)
283 (properties meta-properties set-meta-properties!)
285 (high-pc meta-high-pc set-meta-high-pc!)
286 (arities meta-arities set-meta-arities!))
288 (define (make-meta label properties low-pc)
289 (assert-match label (or (? exact-integer?) (? symbol?)) "symbol")
290 (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
291 (%make-meta label properties low-pc #f '()))
293 (define (meta-name meta)
294 (assq-ref (meta-properties meta) 'name))
296 ;; Metadata for one <lambda-case>.
297 (define-record-type <arity>
298 (make-arity req opt rest kw-indices allow-other-keys?
299 low-pc high-pc definitions)
304 (kw-indices arity-kw-indices)
305 (allow-other-keys? arity-allow-other-keys?)
306 (low-pc arity-low-pc)
307 (high-pc arity-high-pc set-arity-high-pc!)
308 (definitions arity-definitions set-arity-definitions!))
311 (define-syntax *block-size* (identifier-syntax 32)))
313 ;;; An assembler collects all of the words emitted during assembly, and
314 ;;; also maintains ancillary information such as the constant table, a
315 ;;; relocation list, and so on.
317 ;;; Bytecode consists of 32-bit units. We emit bytecode using native
318 ;;; endianness. If we're targeting a foreign endianness, we byte-swap
319 ;;; the bytevector as a whole instead of conditionalizing each access.
321 (define-record-type <asm>
322 (make-asm cur idx start prev written
326 shstrtab next-section-number
331 ;; We write bytecode into what is logically a growable vector,
332 ;; implemented as a list of blocks. asm-cur is the current block, and
333 ;; asm-idx is the current index into that block, in 32-bit units.
335 (cur asm-cur set-asm-cur!)
336 (idx asm-idx set-asm-idx!)
338 ;; asm-start is an absolute position, indicating the offset of the
339 ;; beginning of an instruction (in u32 units). It is updated after
340 ;; writing all the words for one primitive instruction. It models the
341 ;; position of the instruction pointer during execution, given that
342 ;; the VM updates the IP only at the end of executing the instruction,
343 ;; and is thus useful for computing offsets between two points in a
346 (start asm-start set-asm-start!)
348 ;; The list of previously written blocks.
350 (prev asm-prev set-asm-prev!)
352 ;; The number of u32 words written in asm-prev, which is the same as
353 ;; the offset of the current block.
355 (written asm-written set-asm-written!)
357 ;; An alist of symbol -> position pairs, indicating the labels defined
358 ;; in this compilation unit.
360 (labels asm-labels set-asm-labels!)
362 ;; A list of relocations needed by the program text. We use an
363 ;; internal representation for relocations, and handle textualn
364 ;; relative relocations in the assembler. Other kinds of relocations
365 ;; are later reified as linker relocations and resolved by the linker.
367 (relocs asm-relocs set-asm-relocs!)
369 ;; Target information.
371 (word-size asm-word-size)
372 (endianness asm-endianness)
374 ;; The constant table, as a vhash of object -> label. All constants
375 ;; get de-duplicated and written into separate sections -- either the
376 ;; .rodata section, for read-only data, or .data, for constants that
377 ;; need initialization at load-time (like symbols). Constants can
378 ;; depend on other constants (e.g. a symbol depending on a stringbuf),
379 ;; so order in this table is important.
381 (constants asm-constants set-asm-constants!)
383 ;; A list of instructions needed to initialize the constants. Will
384 ;; run in a thunk with 2 local variables.
386 (inits asm-inits set-asm-inits!)
388 ;; The shstrtab, for section names.
390 (shstrtab asm-shstrtab set-asm-shstrtab!)
392 ;; The section number for the next section to be written.
394 (next-section-number asm-next-section-number set-asm-next-section-number!)
396 ;; A list of <meta>, corresponding to procedure metadata.
398 (meta asm-meta set-asm-meta!)
400 ;; A list of (pos . source) pairs, indicating source information. POS
401 ;; is relative to the beginning of the text section, and SOURCE is in
402 ;; the same format that source-properties returns.
404 (sources asm-sources set-asm-sources!)
406 ;; A list of (pos . dead-slot-map) pairs, indicating dead slot maps.
407 ;; POS is relative to the beginning of the text section.
408 ;; DEAD-SLOT-MAP is a bitfield of slots that are dead at call sites,
411 (dead-slot-maps asm-dead-slot-maps set-asm-dead-slot-maps!))
413 (define-inline (fresh-block)
414 (make-u32vector *block-size*))
416 (define* (make-assembler #:key (word-size (target-word-size))
417 (endianness (target-endianness)))
418 "Create an assembler for a given target @var{word-size} and
419 @var{endianness}, falling back to appropriate values for the configured
421 (make-asm (fresh-block) 0 0 '() 0
422 (make-hash-table) '()
425 (make-string-table) 1
428 (define (intern-section-name! asm string)
429 "Add a string to the section name table (shstrtab)."
430 (string-table-intern! (asm-shstrtab asm) string))
432 (define-inline (asm-pos asm)
433 "The offset of the next word to be written into the code buffer, in
435 (+ (asm-idx asm) (asm-written asm)))
437 (define (allocate-new-block asm)
438 "Close off the current block, and arrange for the next word to be
439 written to a fresh block."
440 (let ((new (fresh-block)))
441 (set-asm-prev! asm (cons (asm-cur asm) (asm-prev asm)))
442 (set-asm-written! asm (asm-pos asm))
443 (set-asm-cur! asm new)
444 (set-asm-idx! asm 0)))
446 (define-inline (emit asm u32)
447 "Emit one 32-bit word into the instruction stream. Assumes that there
448 is space for the word, and ensures that there is space for the next
450 (u32-set! (asm-cur asm) (asm-idx asm) u32)
451 (set-asm-idx! asm (1+ (asm-idx asm)))
452 (if (= (asm-idx asm) *block-size*)
453 (allocate-new-block asm)))
455 (define-inline (make-reloc type label base word)
456 "Make an internal relocation of type @var{type} referencing symbol
457 @var{label}, @var{word} words after position @var{start}. @var{type}
458 may be x8-s24, indicating a 24-bit relative label reference that can be
459 fixed up by the assembler, or s32, indicating a 32-bit relative
460 reference that needs to be fixed up by the linker."
461 (list type label base word))
463 (define-inline (reset-asm-start! asm)
464 "Reset the asm-start after writing the words for one instruction."
465 (set-asm-start! asm (asm-pos asm)))
467 (define (record-label-reference asm label)
468 "Record an x8-s24 local label reference. This value will get patched
469 up later by the assembler."
470 (let* ((start (asm-start asm))
472 (reloc (make-reloc 'x8-s24 label start (- pos start))))
473 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
475 (define* (record-far-label-reference asm label #:optional (offset 0))
476 "Record an s32 far label reference. This value will get patched up
477 later by the linker."
478 (let* ((start (- (asm-start asm) offset))
480 (reloc (make-reloc 's32 label start (- pos start))))
481 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
487 ;;; Primitive assemblers are defined by expanding `assembler' for each
488 ;;; opcode in `(instruction-list)'.
492 (define (id-append ctx a b)
493 (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b))))
495 (define-syntax assembler
497 (define-syntax op-case
500 ((_ asm name ((type arg ...) code ...) clause ...)
501 #`(if (eq? name 'type)
502 (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
505 (op-case asm name clause ...)))
507 #'(error "unmatched name" name)))))
509 (define (pack-first-word asm opcode type)
510 (with-syntax ((opcode opcode))
516 (emit asm (pack-u8-u24 opcode arg)))
518 (record-label-reference asm label)
521 (emit asm (pack-u8-u8-u16 opcode a (object-address imm))))
523 (emit asm (pack-u8-u12-u12 opcode a b)))
525 (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
527 (define (pack-tail-word asm type)
531 (emit asm (pack-u8-u24 a b)))
533 (record-label-reference asm label)
538 (let ((val (object-address imm)))
539 (unless (zero? (ash val -32))
540 (error "FIXME: enable truncation of negative fixnums when cross-compiling"))
543 (unless (= (asm-word-size asm) 8)
544 (error "make-long-immediate unavailable for this target"))
545 (emit asm (ash (object-address imm) -32))
546 (emit asm (logand (object-address imm) (1- (ash 1 32)))))
549 (record-far-label-reference asm label)
552 (record-far-label-reference asm label)
555 (record-far-label-reference asm label)
558 (record-far-label-reference asm label
559 (* offset (/ (asm-word-size asm) 4)))
562 (emit asm (pack-u8-u24 0 a)))
564 (record-label-reference asm label)
567 (record-label-reference asm label)
568 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
569 ((B1_U7_L24 a b label)
570 (record-label-reference asm label)
571 (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
573 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
575 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))))
578 ((_ name opcode word0 word* ...)
579 (with-syntax ((((formal0 ...)
581 (pack-first-word #'asm
582 (syntax->datum #'opcode)
583 (syntax->datum #'word0)))
586 (map (lambda (word) (pack-tail-word #'asm word))
587 (syntax->datum #'(word* ...)))))
588 #'(lambda (asm formal0 ... formal* ... ...)
589 (unless (asm? asm) (error "not an asm"))
592 (reset-asm-start! asm))))))))
594 (define assemblers (make-hash-table))
597 (define-syntax define-assembler
600 ((_ name opcode kind arg ...)
601 (with-syntax ((emit (id-append #'name #'emit- #'name)))
603 (let ((emit (assembler name opcode arg ...)))
604 (hashq-set! assemblers 'name emit)
607 (define-syntax visit-opcodes
610 ((visit-opcodes macro arg ...)
611 (with-syntax (((inst ...)
612 (map (lambda (x) (datum->syntax #'macro x))
613 (instruction-list))))
615 (macro arg ... . inst)
618 (visit-opcodes define-assembler)
622 ;; Some operands are encoded using a restricted subset of the full
623 ;; 24-bit local address space, in order to make the bytecode more
624 ;; dense in the usual case that there are few live locals. Here we
625 ;; define wrapper emitters that shuffle out-of-range operands into and
626 ;; out of the reserved range of locals [233,255]. This range is
627 ;; sufficient because these restricted operands are only present in
628 ;; the first word of an instruction. Since 8 bits is the smallest
629 ;; slot-addressing operand size, that means we can fit 3 operands in
630 ;; the 24 bits of payload of the first word (the lower 8 bits being
631 ;; taken by the opcode).
633 ;; The result are wrapper emitters with the same arity,
634 ;; e.g. emit-cons* that wraps emit-cons. We expose these wrappers as
635 ;; the public interface for emitting `cons' instructions. That way we
636 ;; solve the problem fully and in just one place. The only manual
637 ;; care that need be taken is in the exports list at the top of the
638 ;; file -- to be sure that we export the wrapper and not the wrapped
641 (define (shuffling-assembler name kind word0 word*)
642 (define (analyze-first-word)
643 (define-syntax op-case
645 ((_ type ((%type %kind arg ...) values) clause ...)
646 (if (and (eq? type '%type) (eq? kind '%kind))
647 (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
648 #'((arg ...) values))
649 (op-case type clause ...)))
655 (values (if (< a (ash 1 8)) a (begin (emit-mov* asm 253 a) 253))
657 ((U8_U8_I16 <- a imm)
658 (values (if (< a (ash 1 8)) a 253)
661 (values (if (< a (ash 1 12)) a (begin (emit-mov* asm 253 a) 253))
662 (if (< b (ash 1 12)) b (begin (emit-mov* asm 254 b) 254))))
664 (values (if (< a (ash 1 12)) a 253)
665 (if (< b (ash 1 12)) b (begin (emit-mov* asm 254 b) 254))))
666 ((U8_U8_U8_U8 ! a b c)
667 (values (if (< a (ash 1 8)) a (begin (emit-mov* asm 253 a) 253))
668 (if (< b (ash 1 8)) b (begin (emit-mov* asm 254 b) 254))
669 (if (< c (ash 1 8)) c (begin (emit-mov* asm 255 c) 255))))
670 ((U8_U8_U8_U8 <- a b c)
671 (values (if (< a (ash 1 8)) a 253)
672 (if (< b (ash 1 8)) b (begin (emit-mov* asm 254 b) 254))
673 (if (< c (ash 1 8)) c (begin (emit-mov* asm 255 c) 255))))))
675 (define (tail-formals type)
676 (define-syntax op-case
678 ((op-case type (%type arg ...) clause ...)
679 (if (eq? type '%type)
680 (generate-temporaries #'(arg ...))
681 (op-case type clause ...)))
683 (error "unmatched type" type))))
698 (B1_U7_L24 a b label)
702 (define (shuffle-up dst)
703 (define-syntax op-case
705 ((_ type ((%type ...) exp) clause ...)
706 (if (memq type '(%type ...))
708 (op-case type clause ...)))
710 (error "unexpected type" type))))
711 (with-syntax ((dst dst))
714 ((U8_U8_I16 U8_U8_U8_U8)
715 (unless (< dst (ash 1 8))
716 (emit-mov* asm dst 253)))
718 (unless (< dst (ash 1 12))
719 (emit-mov* asm dst 253))))))
723 (lambda (formals+shuffle)
724 (with-syntax ((emit-name (id-append name #'emit- name))
725 (((formal0 ...) shuffle) formals+shuffle)
726 (((formal* ...) ...) (map tail-formals word*)))
727 (with-syntax (((shuffle-up-dst ...)
729 (syntax-case #'(formal0 ...) ()
731 (list (shuffle-up #'dst))))
733 #'(lambda (asm formal0 ... formal* ... ...)
734 (call-with-values (lambda () shuffle)
735 (lambda (formal0 ...)
736 (emit-name asm formal0 ... formal* ... ...)))
737 shuffle-up-dst ...))))))
739 (define-syntax define-shuffling-assembler
742 ((_ #:except (except ...) name opcode kind word0 word* ...)
744 ((or-map (lambda (op) (eq? (syntax->datum #'name) op))
745 (map syntax->datum #'(except ...)))
747 ((shuffling-assembler #'name (syntax->datum #'kind)
748 (syntax->datum #'word0)
749 (map syntax->datum #'(word* ...)))
751 (with-syntax ((emit (id-append #'name
752 (id-append #'name #'emit- #'name)
757 (hashq-set! assemblers 'name emit)
759 (else #'(begin))))))))
761 (visit-opcodes define-shuffling-assembler #:except (receive mov))
763 ;; Mov and receive are two special cases that can work without wrappers.
764 ;; Indeed it is important that they do so.
766 (define (emit-mov* asm dst src)
767 (if (and (< dst (ash 1 12)) (< src (ash 1 12)))
768 (emit-mov asm dst src)
769 (emit-long-mov asm dst src)))
771 (define (emit-receive* asm dst proc nlocals)
772 (if (and (< dst (ash 1 12)) (< proc (ash 1 12)))
773 (emit-receive asm dst proc nlocals)
775 (emit-receive-values asm proc #t 1)
776 (emit-mov* asm dst (1+ proc))
777 (emit-reset-frame asm nlocals))))
779 (define (emit-text asm instructions)
780 "Assemble @var{instructions} using the assembler @var{asm}.
781 @var{instructions} is a sequence of instructions, expressed as a list of
782 lists. This procedure can be called many times before calling
783 @code{link-assembly}."
784 (for-each (lambda (inst)
785 (apply (or (hashq-ref assemblers (car inst))
786 (error 'bad-instruction inst))
794 ;;; The constant table records a topologically sorted set of literal
795 ;;; constants used by a program. For example, a pair uses its car and
796 ;;; cdr, a string uses its stringbuf, etc.
798 ;;; Some things we want to add to the constant table are not actually
799 ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
800 ;;; references, or cache cells for non-closure procedures. For these we
801 ;;; define special record types and add instances of those record types
805 (define-inline (immediate? x)
806 "Return @code{#t} if @var{x} is immediate, and @code{#f} otherwise."
807 (not (zero? (logand (object-address x) 6))))
809 (define-record-type <stringbuf>
810 (make-stringbuf string)
812 (string stringbuf-string))
814 (define-record-type <static-procedure>
815 (make-static-procedure code)
817 (code static-procedure-code))
819 (define-record-type <uniform-vector-backing-store>
820 (make-uniform-vector-backing-store bytes element-size)
821 uniform-vector-backing-store?
822 (bytes uniform-vector-backing-store-bytes)
823 (element-size uniform-vector-backing-store-element-size))
825 (define-record-type <cache-cell>
826 (make-cache-cell scope key)
828 (scope cache-cell-scope)
829 (key cache-cell-key))
831 (define (simple-vector? obj)
833 (equal? (array-shape obj) (list (list 0 (1- (vector-length obj)))))))
835 (define (simple-uniform-vector? obj)
837 (symbol? (array-type obj))
838 (equal? (array-shape obj) (list (list 0 (1- (array-length obj)))))))
840 (define (statically-allocatable? x)
841 "Return @code{#t} if a non-immediate constant can be allocated
842 statically, and @code{#f} if it would need some kind of runtime
844 (or (pair? x) (string? x) (stringbuf? x) (static-procedure? x) (array? x)))
846 (define (intern-constant asm obj)
847 "Add an object to the constant table, and return a label that can be
848 used to reference it. If the object is already present in the constant
849 table, its existing label is used directly."
851 (intern-constant asm obj))
852 (define (field dst n obj)
853 (let ((src (recur obj)))
855 (if (statically-allocatable? obj)
856 `((static-patch! ,dst ,n ,src))
857 `((static-ref 1 ,src)
858 (static-set! 1 ,dst ,n)))
860 (define (intern obj label)
863 (append (field label 0 (car obj))
864 (field label 1 (cdr obj))))
865 ((simple-vector? obj)
866 (let lp ((i 0) (inits '()))
867 (if (< i (vector-length obj))
869 (append-reverse (field label (1+ i) (vector-ref obj i))
872 ((stringbuf? obj) '())
873 ((static-procedure? obj)
874 `((static-patch! ,label 1 ,(static-procedure-code obj))))
875 ((cache-cell? obj) '())
877 `((make-non-immediate 1 ,(recur (symbol->string obj)))
879 (static-set! 1 ,label 0)))
881 `((static-patch! ,label 1 ,(recur (make-stringbuf obj)))))
883 `((static-ref 1 ,(recur (keyword->symbol obj)))
884 (symbol->keyword 1 1)
885 (static-set! 1 ,label 0)))
887 `((make-non-immediate 1 ,(recur (number->string obj)))
889 (static-set! 1 ,label 0)))
890 ((uniform-vector-backing-store? obj) '())
891 ((simple-uniform-vector? obj)
892 (let ((width (case (array-type obj)
895 ;; Bitvectors are addressed in 32-bit units.
896 ;; Although a complex number is 8 or 16 bytes wide,
897 ;; it should be byteswapped in 4 or 8 byte units.
898 ((u32 s32 f32 c32 b) 4)
899 ((u64 s64 f64 c64) 8)
901 (error "unhandled array type" obj)))))
902 `((static-patch! ,label 2
903 ,(recur (make-uniform-vector-backing-store
904 (uniform-array->bytevector obj)
907 `((static-patch! ,label 1 ,(recur (shared-array-root obj)))))
909 (error "don't know how to intern" obj))))
911 ((immediate? obj) #f)
912 ((vhash-assoc obj (asm-constants asm)) => cdr)
914 ;; Note that calling intern may mutate asm-constants and asm-inits.
915 (let* ((label (gensym "constant"))
916 (inits (intern obj label)))
917 (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
918 (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
921 (define (intern-non-immediate asm obj)
922 "Intern a non-immediate into the constant table, and return its
924 (when (immediate? obj)
925 (error "expected a non-immediate" obj))
926 (intern-constant asm obj))
928 (define (intern-cache-cell asm scope key)
929 "Intern a cache cell into the constant table, and return its label.
930 If there is already a cache cell with the given scope and key, it is
932 (intern-constant asm (make-cache-cell scope key)))
934 ;; Return the label of the cell that holds the module for a scope.
935 (define (intern-module-cache-cell asm scope)
936 "Intern a cache cell for a module, and return its label."
937 (intern-cache-cell asm scope #t))
943 ;;; Macro assemblers bridge the gap between primitive instructions and
944 ;;; some higher-level operations.
948 (define-syntax define-macro-assembler
951 ((_ (name arg ...) body body* ...)
952 (with-syntax ((emit (id-append #'name #'emit- #'name)))
955 (let ((emit (lambda (arg ...) body body* ...)))
956 (hashq-set! assemblers 'name emit)
960 (define-macro-assembler (load-constant asm dst obj)
963 (let ((bits (object-address obj)))
965 ((and (< dst 256) (zero? (ash bits -16)))
966 (emit-make-short-immediate asm dst obj))
967 ((zero? (ash bits -32))
968 (emit-make-long-immediate asm dst obj))
970 (emit-make-long-long-immediate asm dst obj)))))
971 ((statically-allocatable? obj)
972 (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
974 (emit-static-ref asm dst (intern-non-immediate asm obj)))))
976 (define-macro-assembler (load-static-procedure asm dst label)
977 (let ((loc (intern-constant asm (make-static-procedure label))))
978 (emit-make-non-immediate asm dst loc)))
980 (define-syntax-rule (define-tc7-macro-assembler name tc7)
981 (define-macro-assembler (name asm slot invert? label)
982 (emit-br-if-tc7 asm slot invert? tc7 label)))
984 ;; Keep in sync with tags.h. Part of Guile's ABI. Currently unused
985 ;; macro assemblers are commented out. See also
986 ;; *branching-primcall-arities* in (language cps primitives), the set of
987 ;; macro-instructions in assembly.scm, and
988 ;; disassembler.scm:code-annotation.
990 ;; FIXME: Define all tc7 values in Scheme in one place, derived from
992 (define-tc7-macro-assembler br-if-symbol 5)
993 (define-tc7-macro-assembler br-if-variable 7)
994 (define-tc7-macro-assembler br-if-vector 13)
995 ;(define-tc7-macro-assembler br-if-weak-vector 13)
996 (define-tc7-macro-assembler br-if-string 21)
997 ;(define-tc7-macro-assembler br-if-heap-number 23)
998 ;(define-tc7-macro-assembler br-if-stringbuf 39)
999 (define-tc7-macro-assembler br-if-bytevector 77)
1000 ;(define-tc7-macro-assembler br-if-pointer 31)
1001 ;(define-tc7-macro-assembler br-if-hashtable 29)
1002 ;(define-tc7-macro-assembler br-if-fluid 37)
1003 ;(define-tc7-macro-assembler br-if-dynamic-state 45)
1004 ;(define-tc7-macro-assembler br-if-frame 47)
1005 (define-tc7-macro-assembler br-if-keyword 53)
1006 ;(define-tc7-macro-assembler br-if-vm 55)
1007 ;(define-tc7-macro-assembler br-if-vm-cont 71)
1008 ;(define-tc7-macro-assembler br-if-rtl-program 69)
1009 ;(define-tc7-macro-assembler br-if-weak-set 85)
1010 ;(define-tc7-macro-assembler br-if-weak-table 87)
1011 ;(define-tc7-macro-assembler br-if-array 93)
1012 (define-tc7-macro-assembler br-if-bitvector 95)
1013 ;(define-tc7-macro-assembler br-if-port 125)
1014 ;(define-tc7-macro-assembler br-if-smob 127)
1016 (define-macro-assembler (begin-program asm label properties)
1017 (emit-label asm label)
1018 (let ((meta (make-meta label properties (asm-start asm))))
1019 (set-asm-meta! asm (cons meta (asm-meta asm)))))
1021 (define-macro-assembler (end-program asm)
1022 (let ((meta (car (asm-meta asm))))
1023 (set-meta-high-pc! meta (asm-start asm))
1024 (set-meta-arities! meta (reverse (meta-arities meta)))))
1026 (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
1027 (emit-begin-opt-arity asm req '() #f nlocals alternate))
1029 (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
1030 (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
1032 (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
1033 allow-other-keys? nlocals alternate)
1034 (assert-match req ((? symbol?) ...) "list of symbols")
1035 (assert-match opt ((? symbol?) ...) "list of symbols")
1036 (assert-match rest (or #f (? symbol?)) "#f or symbol")
1037 (assert-match kw-indices (((? keyword?) . (? integer?)) ...)
1038 "alist of keyword -> integer")
1039 (assert-match allow-other-keys? (? boolean?) "boolean")
1040 (assert-match nlocals (? integer?) "integer")
1041 (assert-match alternate (or #f (? exact-integer?) (? symbol?)) "#f or symbol")
1042 (let* ((meta (car (asm-meta asm)))
1043 (arity (make-arity req opt rest kw-indices allow-other-keys?
1044 (asm-start asm) #f '()))
1045 ;; The procedure itself is in slot 0, in the standard calling
1046 ;; convention. For procedure prologues, nreq includes the
1047 ;; procedure, so here we add 1.
1048 (nreq (1+ (length req)))
1050 (rest? (->bool rest)))
1051 (set-meta-arities! meta (cons arity (meta-arities meta)))
1053 ((or allow-other-keys? (pair? kw-indices))
1054 (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
1056 ((or rest? (pair? opt))
1057 (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
1059 (emit-standard-prelude asm nreq nlocals alternate)))))
1061 (define-macro-assembler (end-arity asm)
1062 (let ((arity (car (meta-arities (car (asm-meta asm))))))
1063 (set-arity-definitions! arity (reverse (arity-definitions arity)))
1064 (set-arity-high-pc! arity (asm-start asm))))
1066 ;; As noted above, we reserve locals 253 through 255 for shuffling large
1067 ;; operands. However the calling convention has all arguments passed in
1068 ;; a contiguous block. This helper, called after the clause has been
1069 ;; chosen and the keyword/optional/rest arguments have been processed,
1070 ;; shuffles up arguments from slot 253 and higher into their final
1073 (define (shuffle-up-args asm nargs)
1075 (let ((slot (1- nargs)))
1076 (emit-mov asm (+ slot 3) slot)
1077 (shuffle-up-args asm (1- nargs)))))
1079 (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
1082 (emit-br-if-nargs-ne asm nreq alternate)
1083 (emit-alloc-frame asm nlocals))
1084 ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
1085 (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
1087 (emit-assert-nargs-ee asm nreq)
1088 (emit-alloc-frame asm nlocals)))
1089 (shuffle-up-args asm nreq))
1091 (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
1093 (emit-br-if-nargs-lt asm nreq alternate)
1094 (emit-assert-nargs-ge asm nreq))
1097 (emit-bind-rest asm (+ nreq nopt)))
1099 (emit-br-if-nargs-gt asm (+ nreq nopt) alternate))
1101 (emit-assert-nargs-le asm (+ nreq nopt))))
1102 (emit-alloc-frame asm nlocals)
1103 (shuffle-up-args asm (+ nreq nopt (if rest? 1 0))))
1105 (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
1106 allow-other-keys? nlocals alternate)
1109 (emit-br-if-nargs-lt asm nreq alternate)
1111 (emit-br-if-npos-gt asm nreq (+ nreq nopt) alternate)))
1112 (emit-assert-nargs-ge asm nreq))
1113 (let ((ntotal (fold (lambda (kw ntotal)
1115 (((? keyword?) . idx)
1116 (max (1+ idx) ntotal))))
1117 (+ nreq nopt) kw-indices)))
1118 ;; FIXME: port 581f410f
1119 (emit-bind-kwargs asm nreq
1120 (pack-flags allow-other-keys? rest?)
1123 (intern-constant asm kw-indices))
1124 (emit-alloc-frame asm nlocals)
1125 (shuffle-up-args asm ntotal)))
1127 (define-macro-assembler (label asm sym)
1128 (hashq-set! (asm-labels asm) sym (asm-start asm)))
1130 (define-macro-assembler (source asm source)
1131 (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
1133 (define-macro-assembler (definition asm name slot)
1134 (let* ((arity (car (meta-arities (car (asm-meta asm)))))
1137 (* (- (asm-start asm) (arity-low-pc arity)) 4))))
1138 (set-arity-definitions! arity (cons def (arity-definitions arity)))))
1140 (define-macro-assembler (cache-current-module! asm module scope)
1141 (let ((mod-label (intern-module-cache-cell asm scope)))
1142 (emit-static-set! asm module mod-label 0)))
1144 (define-macro-assembler (cached-toplevel-box asm dst scope sym bound?)
1145 (let ((sym-label (intern-non-immediate asm sym))
1146 (mod-label (intern-module-cache-cell asm scope))
1147 (cell-label (intern-cache-cell asm scope sym)))
1148 (emit-toplevel-box asm dst cell-label mod-label sym-label bound?)))
1150 (define-macro-assembler (cached-module-box asm dst module-name sym public? bound?)
1151 (let* ((sym-label (intern-non-immediate asm sym))
1152 (key (cons public? module-name))
1153 (mod-name-label (intern-constant asm key))
1154 (cell-label (intern-cache-cell asm key sym)))
1155 (emit-module-box asm dst cell-label mod-name-label sym-label bound?)))
1157 (define-macro-assembler (dead-slot-map asm proc-slot dead-slot-map)
1158 (unless (zero? dead-slot-map)
1159 (set-asm-dead-slot-maps! asm
1161 (cons* (asm-start asm) proc-slot dead-slot-map)
1162 (asm-dead-slot-maps asm)))))
1167 ;;; Helper for linking objects.
1170 (define (make-object asm name bv relocs labels . kwargs)
1171 "Make a linker object. This helper handles interning the name in the
1172 shstrtab, assigning the size, allocating a fresh index, and defining a
1173 corresponding linker symbol for the start of the section."
1174 (let ((name-idx (intern-section-name! asm (symbol->string name)))
1175 (index (asm-next-section-number asm)))
1176 (set-asm-next-section-number! asm (1+ index))
1177 (make-linker-object (apply make-elf-section
1180 #:size (bytevector-length bv)
1183 (cons (make-linker-symbol name 0) labels))))
1189 ;;; Linking the constant table. This code is somewhat intertwingled
1190 ;;; with the intern-constant code above, as that procedure also
1191 ;;; residualizes instructions to initialize constants at load time.
1194 (define (write-immediate asm buf pos x)
1195 (let ((val (object-address x))
1196 (endianness (asm-endianness asm)))
1197 (case (asm-word-size asm)
1198 ((4) (bytevector-u32-set! buf pos val endianness))
1199 ((8) (bytevector-u64-set! buf pos val endianness))
1200 (else (error "bad word size" asm)))))
1202 (define (emit-init-constants asm)
1203 "If there is writable data that needs initialization at runtime, emit
1204 a procedure to do that and return its label. Otherwise return
1206 (let ((inits (asm-inits asm)))
1207 (and (not (null? inits))
1208 (let ((label (gensym "init-constants")))
1210 `((begin-program ,label ())
1211 (assert-nargs-ee/locals 1 1)
1213 (load-constant 1 ,*unspecified*)
1218 (define (link-data asm data name)
1219 "Link the static data for a program into the @var{name} section (which
1220 should be .data or .rodata), and return the resulting linker object.
1221 @var{data} should be a vhash mapping objects to labels."
1222 (define (align address alignment)
1224 (modulo (- alignment (modulo address alignment)) alignment)))
1226 (define tc7-vector 13)
1227 (define stringbuf-shared-flag #x100)
1228 (define stringbuf-wide-flag #x400)
1229 (define tc7-stringbuf 39)
1230 (define tc7-narrow-stringbuf
1231 (+ tc7-stringbuf stringbuf-shared-flag))
1232 (define tc7-wide-stringbuf
1233 (+ tc7-stringbuf stringbuf-shared-flag stringbuf-wide-flag))
1234 (define tc7-ro-string (+ 21 #x200))
1235 (define tc7-program 69)
1236 (define tc7-bytevector 77)
1237 (define tc7-bitvector 95)
1238 (define tc7-array 93)
1240 (let ((word-size (asm-word-size asm))
1241 (endianness (asm-endianness asm)))
1242 (define (byte-length x)
1245 (let ((x (stringbuf-string x)))
1247 (case (string-bytes-per-char x)
1248 ((1) (1+ (string-length x)))
1249 ((4) (* (1+ (string-length x)) 4))
1250 (else (error "bad string bytes per char" x))))))
1251 ((static-procedure? x)
1258 (* (1+ (vector-length x)) word-size))
1259 ((simple-uniform-vector? x)
1261 ((uniform-vector-backing-store? x)
1262 (bytevector-length (uniform-vector-backing-store-bytes x)))
1264 (* word-size (+ 3 (* 3 (array-rank x)))))
1268 (define (write-constant-reference buf pos x)
1269 ;; The asm-inits will fix up any reference to a non-immediate.
1270 (write-immediate asm buf pos (if (immediate? x) x #f)))
1272 (define (write buf pos obj)
1275 (let* ((x (stringbuf-string obj))
1276 (len (string-length x))
1277 (tag (if (= (string-bytes-per-char x) 1)
1278 tc7-narrow-stringbuf
1279 tc7-wide-stringbuf)))
1282 (bytevector-u32-set! buf pos tag endianness)
1283 (bytevector-u32-set! buf (+ pos 4) len endianness))
1285 (bytevector-u64-set! buf pos tag endianness)
1286 (bytevector-u64-set! buf (+ pos 8) len endianness))
1288 (error "bad word size" asm)))
1289 (let ((pos (+ pos (* word-size 2))))
1290 (case (string-bytes-per-char x)
1294 (let ((u8 (char->integer (string-ref x i))))
1295 (bytevector-u8-set! buf (+ pos i) u8)
1297 (bytevector-u8-set! buf (+ pos i) 0))))
1301 (let ((u32 (char->integer (string-ref x i))))
1302 (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
1304 (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
1305 (else (error "bad string bytes per char" x))))))
1307 ((static-procedure? obj)
1310 (bytevector-u32-set! buf pos tc7-program endianness)
1311 (bytevector-u32-set! buf (+ pos 4) 0 endianness))
1313 (bytevector-u64-set! buf pos tc7-program endianness)
1314 (bytevector-u64-set! buf (+ pos 8) 0 endianness))
1315 (else (error "bad word size"))))
1318 (write-immediate asm buf pos #f))
1321 (let ((tag (logior tc7-ro-string (ash (string-length obj) 8)))) ; FIXME: unused?
1324 (bytevector-u32-set! buf pos tc7-ro-string endianness)
1325 (write-immediate asm buf (+ pos 4) #f) ; stringbuf
1326 (bytevector-u32-set! buf (+ pos 8) 0 endianness)
1327 (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
1329 (bytevector-u64-set! buf pos tc7-ro-string endianness)
1330 (write-immediate asm buf (+ pos 8) #f) ; stringbuf
1331 (bytevector-u64-set! buf (+ pos 16) 0 endianness)
1332 (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
1333 (else (error "bad word size")))))
1336 (write-constant-reference buf pos (car obj))
1337 (write-constant-reference buf (+ pos word-size) (cdr obj)))
1339 ((simple-vector? obj)
1340 (let* ((len (vector-length obj))
1341 (tag (logior tc7-vector (ash len 8))))
1343 ((4) (bytevector-u32-set! buf pos tag endianness))
1344 ((8) (bytevector-u64-set! buf pos tag endianness))
1345 (else (error "bad word size")))
1347 (when (< i (vector-length obj))
1348 (let ((pos (+ pos word-size (* i word-size)))
1349 (elt (vector-ref obj i)))
1350 (write-constant-reference buf pos elt)
1354 (write-immediate asm buf pos #f))
1357 (write-immediate asm buf pos #f))
1360 (write-immediate asm buf pos #f))
1362 ((simple-uniform-vector? obj)
1363 (let ((tag (if (bitvector? obj)
1365 (let ((type-code (array-type-code obj)))
1366 (logior tc7-bytevector (ash type-code 7))))))
1369 (bytevector-u32-set! buf pos tag endianness)
1370 (bytevector-u32-set! buf (+ pos 4)
1371 (if (bitvector? obj)
1372 (bitvector-length obj)
1373 (bytevector-length obj))
1374 endianness) ; length
1375 (bytevector-u32-set! buf (+ pos 8) 0 endianness) ; pointer
1376 (write-immediate asm buf (+ pos 12) #f)) ; owner
1378 (bytevector-u64-set! buf pos tag endianness)
1379 (bytevector-u64-set! buf (+ pos 8)
1380 (if (bitvector? obj)
1381 (bitvector-length obj)
1382 (bytevector-length obj))
1383 endianness) ; length
1384 (bytevector-u64-set! buf (+ pos 16) 0 endianness) ; pointer
1385 (write-immediate asm buf (+ pos 24) #f)) ; owner
1386 (else (error "bad word size")))))
1388 ((uniform-vector-backing-store? obj)
1389 (let ((bv (uniform-vector-backing-store-bytes obj)))
1390 (bytevector-copy! bv 0 buf pos (bytevector-length bv))
1391 (unless (or (= 1 (uniform-vector-backing-store-element-size obj))
1392 (eq? endianness (native-endianness)))
1393 ;; Need to swap units of element-size bytes
1394 (error "FIXME: Implement byte order swap"))))
1398 ;; array tag + rank + contp flag: see libguile/arrays.h .
1399 (((tag) (logior tc7-array (ash (array-rank obj) 17) (ash 1 16)))
1402 ((4) (values bytevector-u32-set! bytevector-s32-set!))
1403 ((8) (values bytevector-u64-set! bytevector-s64-set!))
1404 (else (error "bad word size")))))
1405 (bv-set! buf pos tag endianness)
1406 (write-immediate asm buf (+ pos word-size) #f) ; root vector (fixed later)
1407 (bv-set! buf (+ pos (* word-size 2)) 0 endianness) ; base
1408 (let lp ((pos (+ pos (* word-size 3)))
1409 (bounds (array-shape obj))
1410 (incs (shared-array-increments obj)))
1411 (when (pair? bounds)
1412 (bvs-set! buf pos (first (first bounds)) endianness)
1413 (bvs-set! buf (+ pos word-size) (second (first bounds)) endianness)
1414 (bvs-set! buf (+ pos (* word-size 2)) (first incs) endianness)
1415 (lp (+ pos (* 3 word-size)) (cdr bounds) (cdr incs))))))
1418 (error "unrecognized object" obj))))
1421 ((vlist-null? data) #f)
1423 (let* ((byte-len (vhash-fold (lambda (k v len)
1424 (+ (byte-length k) (align len 8)))
1426 (buf (make-bytevector byte-len 0)))
1427 (let lp ((i 0) (pos 0) (symbols '()))
1428 (if (< i (vlist-length data))
1429 (let* ((pair (vlist-ref data i))
1431 (obj-label (cdr pair)))
1434 (align (+ (byte-length obj) pos) 8)
1435 (cons (make-linker-symbol obj-label pos) symbols)))
1436 (make-object asm name buf '() symbols
1438 ('.data (logior SHF_ALLOC SHF_WRITE))
1439 ('.rodata SHF_ALLOC))))))))))
1441 (define (link-constants asm)
1442 "Link sections to hold constants needed by the program text emitted
1445 Returns three values: an object for the .rodata section, an object for
1446 the .data section, and a label for an initialization procedure. Any of
1447 these may be @code{#f}."
1448 (define (shareable? x)
1452 (and (immediate? (car x)) (immediate? (cdr x))))
1455 (or (= i (vector-length x))
1456 (and (immediate? (vector-ref x i))
1458 ((uniform-vector-backing-store? x) #t)
1460 (let* ((constants (asm-constants asm))
1461 (len (vlist-length constants)))
1466 (values (link-data asm ro '.rodata)
1467 (link-data asm rw '.data)
1468 (emit-init-constants asm))
1469 (let ((pair (vlist-ref constants i)))
1470 (if (shareable? (car pair))
1471 (lp (1+ i) (vhash-consq (car pair) (cdr pair) ro) rw)
1472 (lp (1+ i) ro (vhash-consq (car pair) (cdr pair) rw))))))))
1477 ;;; Linking program text.
1480 (define (process-relocs buf relocs labels)
1481 "Patch up internal x8-s24 relocations, and any s32 relocations that
1482 reference symbols in the text section. Return a list of linker
1483 relocations for references to symbols defined outside the text section."
1485 (lambda (reloc tail)
1487 ((type label base word)
1488 (let ((abs (hashq-ref labels label))
1489 (dst (+ base word)))
1493 (let ((rel (- abs base)))
1494 (s32-set! buf dst rel)
1496 (cons (make-linker-reloc 'rel32/4 (* dst 4) word label)
1500 (error "unbound near relocation" reloc))
1501 (let ((rel (- abs base))
1502 (u32 (u32-ref buf dst)))
1503 (u32-set! buf dst (pack-u8-s24 (logand u32 #xff) rel))
1505 (else (error "bad relocation kind" reloc)))))))
1509 (define (process-labels labels)
1510 "Define linker symbols for the label-offset map in @var{labels}.
1511 The offsets are expected to be expressed in words."
1512 (hash-map->list (lambda (label loc)
1513 (make-linker-symbol label (* loc 4)))
1516 (define (swap-bytes! buf)
1517 "Patch up the text buffer @var{buf}, swapping the endianness of each
1519 (unless (zero? (modulo (bytevector-length buf) 4))
1520 (error "unexpected length"))
1521 (let ((byte-len (bytevector-length buf)))
1523 (unless (= pos byte-len)
1524 (bytevector-u32-set!
1526 (bytevector-u32-ref buf pos (endianness big))
1527 (endianness little))
1530 (define (link-text-object asm)
1531 "Link the .rtl-text section, swapping the endianness of the bytes if
1533 (let ((buf (make-u32vector (asm-pos asm))))
1534 (let lp ((pos 0) (prev (reverse (asm-prev asm))))
1536 (let ((byte-size (* (asm-idx asm) 4)))
1537 (bytevector-copy! (asm-cur asm) 0 buf pos byte-size)
1538 (unless (eq? (asm-endianness asm) (native-endianness))
1540 (make-object asm '.rtl-text
1542 (process-relocs buf (asm-relocs asm)
1544 (process-labels (asm-labels asm))))
1545 (let ((len (* *block-size* 4)))
1546 (bytevector-copy! (car prev) 0 buf pos len)
1547 (lp (+ pos len) (cdr prev)))))))
1553 ;;; Create the frame maps. These maps are used by GC to identify dead
1554 ;;; slots in pending call frames, to avoid marking them. We only do
1555 ;;; this when frame makes a non-tail call, as that is the common case.
1556 ;;; Only the topmost frame will see a GC at any other point, but we mark
1557 ;;; top frames conservatively as serializing live slot maps at every
1558 ;;; instruction would take up too much space in the object file.
1561 ;; The .guile.frame-maps section starts with two packed u32 values: one
1562 ;; indicating the offset of the first byte of the .rtl-text section, and
1563 ;; another indicating the relative offset in bytes of the slots data.
1564 (define frame-maps-prefix-len 8)
1566 ;; Each header is 8 bytes: 4 for the offset from .rtl_text, and 4 for
1567 ;; the offset of the slot map from the beginning of the
1568 ;; .guile.frame-maps section. The length of a frame map depends on the
1569 ;; frame size at the call site, and is not encoded into this section as
1570 ;; it is available at run-time.
1571 (define frame-map-header-len 8)
1573 (define (link-frame-maps asm)
1574 (define (map-byte-length proc-slot)
1575 (ceiling-quotient (- proc-slot 2) 8))
1576 (define (make-frame-maps maps count map-len)
1577 (let* ((endianness (asm-endianness asm))
1578 (header-pos frame-maps-prefix-len)
1579 (map-pos (+ header-pos (* count frame-map-header-len)))
1580 (bv (make-bytevector (+ map-pos map-len) 0)))
1581 (bytevector-u32-set! bv 4 map-pos endianness)
1582 (let lp ((maps maps) (header-pos header-pos) (map-pos map-pos))
1585 (make-object asm '.guile.frame-maps bv
1586 (list (make-linker-reloc 'abs32/1 0 0 '.rtl-text))
1587 '() #:type SHT_PROGBITS #:flags SHF_ALLOC))
1588 (((pos proc-slot . map) . maps)
1589 (bytevector-u32-set! bv header-pos (* pos 4) endianness)
1590 (bytevector-u32-set! bv (+ header-pos 4) map-pos endianness)
1591 (let write-bytes ((map-pos map-pos)
1593 (byte-length (map-byte-length proc-slot)))
1594 (if (zero? byte-length)
1595 (lp maps (+ header-pos frame-map-header-len) map-pos)
1597 (bytevector-u8-set! bv map-pos (logand map #xff))
1598 (write-bytes (1+ map-pos) (ash map -8)
1599 (1- byte-length))))))))))
1600 (match (asm-dead-slot-maps asm)
1603 (let lp ((in in) (out '()) (count 0) (map-len 0))
1605 (() (make-frame-maps out count map-len))
1606 (((and head (pos proc-slot . map)) . in)
1607 (lp in (cons head out)
1609 (+ (map-byte-length proc-slot) map-len))))))))
1614 ;;; Linking other sections of the ELF file, like the dynamic segment,
1615 ;;; the symbol table, etc.
1618 ;; FIXME: Define these somewhere central, shared with C.
1619 (define *bytecode-major-version* #x0202)
1620 (define *bytecode-minor-version* 6)
1622 (define (link-dynamic-section asm text rw rw-init frame-maps)
1623 "Link the dynamic section for an ELF image with bytecode @var{text},
1624 given the writable data section @var{rw} needing fixup from the
1625 procedure with label @var{rw-init}. @var{rw-init} may be false. If
1626 @var{rw} is true, it will be added to the GC roots at runtime."
1627 (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
1628 (let* ((endianness (asm-endianness asm))
1630 (words (if rw (+ words 4) words))
1631 (words (if rw-init (+ words 2) words))
1632 (words (if frame-maps (+ words 2) words))
1633 (bv (make-bytevector (* word-size words) 0))
1636 (%set-uword! bv (* i word-size) uword endianness)))
1640 (set! relocs (cons (make-linker-reloc 'reloc-type
1641 (* i word-size) 0 label)
1643 (%set-uword! bv (* i word-size) 0 endianness))))
1644 (set-uword! 0 DT_GUILE_VM_VERSION)
1645 (set-uword! 1 (logior (ash *bytecode-major-version* 16)
1646 *bytecode-minor-version*))
1647 (set-uword! 2 DT_GUILE_ENTRY)
1648 (set-label! 3 '.rtl-text)
1651 (set-uword! 4 DT_GUILE_GC_ROOT)
1652 (set-label! 5 '.data)
1653 (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
1654 (set-uword! 7 (bytevector-length (linker-object-bv rw)))
1656 (set-uword! 8 DT_INIT) ; constants
1657 (set-label! 9 rw-init)))
1659 (set-uword! (- words 4) DT_GUILE_FRAME_MAPS)
1660 (set-label! (- words 3) '.guile.frame-maps))
1661 (set-uword! (- words 2) DT_NULL)
1662 (set-uword! (- words 1) 0)
1663 (make-object asm '.dynamic bv relocs '()
1664 #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
1665 (case (asm-word-size asm)
1666 ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
1667 ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
1668 (else (error "bad word size" asm))))
1670 (define (link-shstrtab asm)
1671 "Link the string table for the section headers."
1672 (intern-section-name! asm ".shstrtab")
1673 (make-object asm '.shstrtab
1674 (link-string-table! (asm-shstrtab asm))
1676 #:type SHT_STRTAB #:flags 0))
1678 (define (link-symtab text-section asm)
1679 (let* ((endianness (asm-endianness asm))
1680 (word-size (asm-word-size asm))
1681 (size (elf-symbol-len word-size))
1682 (meta (reverse (asm-meta asm)))
1684 (strtab (make-string-table))
1685 (bv (make-bytevector (* n size) 0)))
1686 (define (intern-string! name)
1687 (string-table-intern! strtab (if name (symbol->string name) "")))
1690 (let ((name (intern-string! (meta-name meta))))
1691 (write-elf-symbol bv (* n size) endianness word-size
1694 ;; Symbol value and size are measured in
1696 #:value (* 4 (meta-low-pc meta))
1697 #:size (* 4 (- (meta-high-pc meta)
1698 (meta-low-pc meta)))
1700 #:visibility STV_HIDDEN
1701 #:shndx (elf-section-index text-section)))))
1703 (let ((strtab (make-object asm '.strtab
1704 (link-string-table! strtab)
1706 #:type SHT_STRTAB #:flags 0)))
1707 (values (make-object asm '.symtab
1710 #:type SHT_SYMTAB #:flags 0 #:entsize size
1711 #:link (elf-section-index
1712 (linker-object-section strtab)))
1715 ;;; The .guile.arities section describes the arities that a function can
1716 ;;; have. It is in two parts: a sorted array of headers describing
1717 ;;; basic arities, and an array of links out to a string table (and in
1718 ;;; the case of keyword arguments, to the data section) for argument
1719 ;;; names. The whole thing is prefixed by a uint32 indicating the
1720 ;;; offset of the end of the headers array.
1722 ;;; The arity headers array is a packed array of structures of the form:
1724 ;;; struct arity_header {
1725 ;;; uint32_t low_pc;
1726 ;;; uint32_t high_pc;
1727 ;;; uint32_t offset;
1731 ;;; uint32_t nlocals;
1734 ;;; All of the offsets and addresses are 32 bits. We can expand in the
1735 ;;; future to use 64-bit offsets if appropriate, but there are other
1736 ;;; aspects of bytecode that constrain us to a total image that fits in
1737 ;;; 32 bits, so for the moment we'll simplify the problem space.
1739 ;;; The following flags values are defined:
1742 ;;; #x2: allow-other-keys?
1743 ;;; #x4: has-keyword-args?
1744 ;;; #x8: is-case-lambda?
1745 ;;; #x10: is-in-case-lambda?
1747 ;;; Functions with a single arity specify their number of required and
1748 ;;; optional arguments in nreq and nopt, and do not have the
1749 ;;; is-case-lambda? flag set. Their "offset" member links to an array
1750 ;;; of pointers into the associated .guile.arities.strtab string table,
1751 ;;; identifying the argument names. This offset is relative to the
1752 ;;; start of the .guile.arities section.
1754 ;;; If the arity has keyword arguments -- if has-keyword-args? is set in
1755 ;;; the flags -- the first uint32 pointed to by offset encodes a link to
1756 ;;; the "keyword indices" literal, in the data section. Then follow the
1757 ;;; names for all locals, in order, as uleb128 values. The required
1758 ;;; arguments will be the first locals, followed by the optionals,
1759 ;;; followed by the rest argument if if has-rest? is set. The names
1760 ;;; point into the associated string table section.
1762 ;;; Functions with no arities have no arities information present in the
1763 ;;; .guile.arities section.
1765 ;;; Functions with multiple arities are preceded by a header with
1766 ;;; is-case-lambda? set. All other fields are 0, except low-pc and
1767 ;;; high-pc which should be the bounds of the whole function. Headers
1768 ;;; for the individual arities follow, with the is-in-case-lambda? flag
1769 ;;; set. In this way the whole headers array is sorted in increasing
1770 ;;; low-pc order, and case-lambda clauses are contained within the
1771 ;;; [low-pc, high-pc] of the case-lambda header.
1773 ;; Length of the prefix to the arities section, in bytes.
1774 (define arities-prefix-len 4)
1776 ;; Length of an arity header, in bytes.
1777 (define arity-header-len (* 7 4))
1780 (define (put-uleb128 port val)
1782 (let ((next (ash val -7)))
1786 (put-u8 port (logior #x80 (logand val #x7f)))
1789 (define (put-sleb128 port val)
1791 (if (<= 0 (+ val 64) 127)
1792 (put-u8 port (logand val #x7f))
1794 (put-u8 port (logior #x80 (logand val #x7f)))
1795 (lp (ash val -7))))))
1797 (define (port-position port)
1798 (seek port 0 SEEK_CUR))
1800 (define-inline (pack-arity-flags has-rest? allow-other-keys?
1801 has-keyword-args? is-case-lambda?
1803 (logior (if has-rest? (ash 1 0) 0)
1804 (if allow-other-keys? (ash 1 1) 0)
1805 (if has-keyword-args? (ash 1 2) 0)
1806 (if is-case-lambda? (ash 1 3) 0)
1807 (if is-in-case-lambda? (ash 1 4) 0)))
1809 (define (write-arities asm metas headers names-port strtab)
1810 (define (write-header pos low-pc high-pc offset flags nreq nopt nlocals)
1811 (unless (<= (+ nreq nopt) nlocals)
1812 (error "forgot to emit definition instructions?"))
1813 (bytevector-u32-set! headers pos (* low-pc 4) (asm-endianness asm))
1814 (bytevector-u32-set! headers (+ pos 4) (* high-pc 4) (asm-endianness asm))
1815 (bytevector-u32-set! headers (+ pos 8) offset (asm-endianness asm))
1816 (bytevector-u32-set! headers (+ pos 12) flags (asm-endianness asm))
1817 (bytevector-u32-set! headers (+ pos 16) nreq (asm-endianness asm))
1818 (bytevector-u32-set! headers (+ pos 20) nopt (asm-endianness asm))
1819 (bytevector-u32-set! headers (+ pos 24) nlocals (asm-endianness asm)))
1820 (define (write-kw-indices kw-indices relocs)
1821 ;; FIXME: Assert that kw-indices is already interned.
1822 (if (pair? kw-indices)
1823 (let ((pos (+ (bytevector-length headers)
1824 (port-position names-port)))
1825 (label (intern-constant asm kw-indices)))
1826 (put-bytevector names-port #vu8(0 0 0 0))
1827 (cons (make-linker-reloc 'abs32/1 pos 0 label) relocs))
1829 (define (write-arity pos arity in-case-lambda? relocs)
1830 (write-header pos (arity-low-pc arity)
1831 (arity-high-pc arity)
1832 ;; FIXME: Seems silly to add on bytevector-length of
1833 ;; headers, given the arities-prefix.
1834 (+ (bytevector-length headers) (port-position names-port))
1835 (pack-arity-flags (arity-rest arity)
1836 (arity-allow-other-keys? arity)
1837 (pair? (arity-kw-indices arity))
1840 (length (arity-req arity))
1841 (length (arity-opt arity))
1842 (length (arity-definitions arity)))
1843 (let ((relocs (write-kw-indices (arity-kw-indices arity) relocs)))
1844 ;; Write local names.
1845 (let lp ((definitions (arity-definitions arity)))
1848 ((#(name slot def) . definitions)
1849 (let ((sym (if (symbol? name)
1850 (string-table-intern! strtab (symbol->string name))
1852 (put-uleb128 names-port sym)
1853 (lp definitions)))))
1854 ;; Now write their definitions.
1855 (let lp ((definitions (arity-definitions arity)))
1858 ((#(name slot def) . definitions)
1859 (put-uleb128 names-port def)
1860 (put-uleb128 names-port slot)
1861 (lp definitions))))))
1862 (let lp ((metas metas) (pos arities-prefix-len) (relocs '()))
1865 (unless (= pos (bytevector-length headers))
1866 (error "expected to fully fill the bytevector"
1867 pos (bytevector-length headers)))
1870 (match (meta-arities meta)
1871 (() (lp metas pos relocs))
1874 (+ pos arity-header-len)
1875 (write-arity pos arity #f relocs)))
1877 ;; Write a case-lambda header, then individual arities.
1878 ;; The case-lambda header's offset link is 0.
1879 (write-header pos (meta-low-pc meta) (meta-high-pc meta) 0
1880 (pack-arity-flags #f #f #f #t #f) 0 0 0)
1881 (let lp* ((arities arities) (pos (+ pos arity-header-len))
1884 (() (lp metas pos relocs))
1887 (+ pos arity-header-len)
1888 (write-arity pos arity #t relocs)))))))))))
1890 (define (link-arities asm)
1891 (define (meta-arities-header-size meta)
1892 (define (lambda-size arity)
1894 (define (case-lambda-size arities)
1896 arity-header-len ;; case-lambda header
1897 (map lambda-size arities))) ;; the cases
1898 (match (meta-arities meta)
1900 ((arity) (lambda-size arity))
1901 (arities (case-lambda-size arities))))
1903 (define (bytevector-append a b)
1904 (let ((out (make-bytevector (+ (bytevector-length a)
1905 (bytevector-length b)))))
1906 (bytevector-copy! a 0 out 0 (bytevector-length a))
1907 (bytevector-copy! b 0 out (bytevector-length a) (bytevector-length b))
1910 (let* ((endianness (asm-endianness asm))
1911 (metas (reverse (asm-meta asm)))
1912 (header-size (fold (lambda (meta size)
1913 (+ size (meta-arities-header-size meta)))
1916 (strtab (make-string-table))
1917 (headers (make-bytevector header-size 0)))
1918 (bytevector-u32-set! headers 0 (bytevector-length headers) endianness)
1919 (let-values (((names-port get-name-bv) (open-bytevector-output-port)))
1920 (let* ((relocs (write-arities asm metas headers names-port strtab))
1921 (strtab (make-object asm '.guile.arities.strtab
1922 (link-string-table! strtab)
1924 #:type SHT_STRTAB #:flags 0)))
1925 (values (make-object asm '.guile.arities
1926 (bytevector-append headers (get-name-bv))
1928 #:type SHT_PROGBITS #:flags 0
1929 #:link (elf-section-index
1930 (linker-object-section strtab)))
1934 ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
1935 ;;; values. Pc and str are both 32 bits wide. (Either could change to
1936 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1937 ;;; entry to a program, relative to the start of the text section, in
1938 ;;; bytes, and str is an index into the associated .guile.docstrs.strtab
1939 ;;; string table section.
1942 ;; The size of a docstrs entry, in bytes.
1943 (define docstr-size 8)
1945 (define (link-docstrs asm)
1946 (define (find-docstrings)
1947 (filter-map (lambda (meta)
1948 (define (is-documentation? pair)
1949 (eq? (car pair) 'documentation))
1950 (let* ((props (meta-properties meta))
1951 (tail (find-tail is-documentation? props)))
1953 (not (find-tail is-documentation? (cdr tail)))
1954 (string? (cdar tail))
1955 (cons (* 4 (meta-low-pc meta)) (cdar tail)))))
1956 (reverse (asm-meta asm))))
1957 (let* ((endianness (asm-endianness asm))
1958 (docstrings (find-docstrings))
1959 (strtab (make-string-table))
1960 (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
1961 (fold (lambda (pair pos)
1964 (bytevector-u32-set! bv pos pc endianness)
1965 (bytevector-u32-set! bv (+ pos 4)
1966 (string-table-intern! strtab string)
1968 (+ pos docstr-size))))
1971 (let ((strtab (make-object asm '.guile.docstrs.strtab
1972 (link-string-table! strtab)
1974 #:type SHT_STRTAB #:flags 0)))
1975 (values (make-object asm '.guile.docstrs
1978 #:type SHT_PROGBITS #:flags 0
1979 #:link (elf-section-index
1980 (linker-object-section strtab)))
1984 ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
1985 ;;; values. Pc and addr are both 32 bits wide. (Either could change to
1986 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1987 ;;; entry to a program, relative to the start of the text section, and
1988 ;;; addr is the address of the associated properties alist, relative to
1989 ;;; the start of the ELF image.
1991 ;;; Since procedure properties are stored in the data sections, we need
1992 ;;; to link the procedures property section first. (Note that this
1993 ;;; constraint does not apply to the arities section, which may
1994 ;;; reference the data sections via the kw-indices literal, because
1995 ;;; assembling the text section already makes sure that the kw-indices
1999 ;; The size of a procprops entry, in bytes.
2000 (define procprops-size 8)
2002 (define (link-procprops asm)
2003 (define (assoc-remove-one alist key value-pred)
2006 ((((? (lambda (x) (eq? x key))) . value) . alist)
2007 (if (value-pred value)
2009 (acons key value alist)))
2011 (acons k v (assoc-remove-one alist key value-pred)))))
2012 (define (props-without-name-or-docstring meta)
2014 (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
2017 (define (find-procprops)
2018 (filter-map (lambda (meta)
2019 (let ((props (props-without-name-or-docstring meta)))
2021 (cons (* 4 (meta-low-pc meta)) props))))
2022 (reverse (asm-meta asm))))
2023 (let* ((endianness (asm-endianness asm))
2024 (procprops (find-procprops))
2025 (bv (make-bytevector (* (length procprops) procprops-size) 0)))
2026 (let lp ((procprops procprops) (pos 0) (relocs '()))
2029 (make-object asm '.guile.procprops
2032 #:type SHT_PROGBITS #:flags 0))
2033 (((pc . props) . procprops)
2034 (bytevector-u32-set! bv pos pc endianness)
2036 (+ pos procprops-size)
2037 (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
2038 (intern-constant asm props))
2042 ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
2043 ;;; sections provide line number and local variable liveness
2044 ;;; information. Their format is defined by the DWARF
2048 (define (asm-language asm)
2049 ;; FIXME: Plumb language through to the assembler.
2052 ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
2053 (define (link-debug asm)
2054 (define (put-s8 port val)
2055 (let ((bv (make-bytevector 1)))
2056 (bytevector-s8-set! bv 0 val)
2057 (put-bytevector port bv)))
2059 (define (put-u16 port val)
2060 (let ((bv (make-bytevector 2)))
2061 (bytevector-u16-set! bv 0 val (asm-endianness asm))
2062 (put-bytevector port bv)))
2064 (define (put-u32 port val)
2065 (let ((bv (make-bytevector 4)))
2066 (bytevector-u32-set! bv 0 val (asm-endianness asm))
2067 (put-bytevector port bv)))
2069 (define (put-u64 port val)
2070 (let ((bv (make-bytevector 8)))
2071 (bytevector-u64-set! bv 0 val (asm-endianness asm))
2072 (put-bytevector port bv)))
2074 (define (meta->subprogram-die meta)
2078 => (lambda (name) `((name ,(symbol->string name)))))
2081 (low-pc ,(meta-label meta))
2082 (high-pc ,(* 4 (- (meta-high-pc meta) (meta-low-pc meta)))))))
2084 (define (make-compile-unit-die asm)
2086 (@ (producer ,(string-append "Guile " (version)))
2087 (language ,(asm-language asm))
2089 (high-pc ,(* 4 (asm-pos asm)))
2091 ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
2093 (let-values (((die-port get-die-bv) (open-bytevector-output-port))
2095 ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
2096 ;; (tag has-kids? attrs forms) -> code
2097 ((abbrevs) vlist-null)
2098 ((strtab) (make-string-table))
2099 ((line-port get-line-bv) (open-bytevector-output-port))
2102 ((files) vlist-null))
2104 (define (write-abbrev code tag has-children? attrs forms)
2105 (put-uleb128 abbrev-port code)
2106 (put-uleb128 abbrev-port (tag-name->code tag))
2107 (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
2108 (for-each (lambda (attr form)
2109 (put-uleb128 abbrev-port (attribute-name->code attr))
2110 (put-uleb128 abbrev-port (form-name->code form)))
2112 (put-uleb128 abbrev-port 0)
2113 (put-uleb128 abbrev-port 0))
2115 (define (intern-abbrev tag has-children? attrs forms)
2116 (let ((key (list tag has-children? attrs forms)))
2117 (match (vhash-assoc key abbrevs)
2119 (#f (let ((code (1+ (vlist-length abbrevs))))
2120 (set! abbrevs (vhash-cons key code abbrevs))
2121 (write-abbrev code tag has-children? attrs forms)
2124 (define (intern-file file)
2125 (match (vhash-assoc file files)
2127 (#f (let ((code (1+ (vlist-length files))))
2128 (set! files (vhash-cons file code files))
2131 (define (write-sources)
2132 ;; Choose line base and line range values that will allow for an
2133 ;; address advance range of 16 words. The special opcode range is
2134 ;; from 10 to 255, so 246 values.
2138 (let lp ((sources (asm-sources asm)) (out '()))
2140 (((pc . s) . sources)
2141 (let ((file (assq-ref s 'filename))
2142 (line (assq-ref s 'line))
2143 (col (assq-ref s 'column)))
2145 ;; Guile line and column numbers are 0-indexed, but
2146 ;; they are 1-indexed for DWARF.
2148 (if (string? file) (intern-file file) 0)
2153 ;; Compilation unit header for .debug_line. We write in
2154 ;; DWARF 2 format because more tools understand it than DWARF
2155 ;; 4, which incompatibly adds another field to this header.
2157 (put-u32 line-port 0) ; Length; will patch later.
2158 (put-u16 line-port 2) ; DWARF 2 format.
2159 (put-u32 line-port 0) ; Prologue length; will patch later.
2160 (put-u8 line-port 4) ; Minimum instruction length: 4 bytes.
2161 (put-u8 line-port 1) ; Default is-stmt: true.
2163 (put-s8 line-port base) ; Line base. See the DWARF standard.
2164 (put-u8 line-port range) ; Line range. See the DWARF standard.
2165 (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
2167 ;; A table of the number of uleb128 arguments taken by each
2168 ;; of the standard opcodes.
2169 (put-u8 line-port 0) ; 1: copy
2170 (put-u8 line-port 1) ; 2: advance-pc
2171 (put-u8 line-port 1) ; 3: advance-line
2172 (put-u8 line-port 1) ; 4: set-file
2173 (put-u8 line-port 1) ; 5: set-column
2174 (put-u8 line-port 0) ; 6: negate-stmt
2175 (put-u8 line-port 0) ; 7: set-basic-block
2176 (put-u8 line-port 0) ; 8: const-add-pc
2177 (put-u8 line-port 1) ; 9: fixed-advance-pc
2179 ;; Include directories, as a zero-terminated sequence of
2180 ;; nul-terminated strings. Nothing, for the moment.
2181 (put-u8 line-port 0)
2183 ;; File table. For each file that contributes to this
2184 ;; compilation unit, a nul-terminated file name string, and a
2185 ;; uleb128 for each of directory the file was found in, the
2186 ;; modification time, and the file's size in bytes. We pass
2187 ;; zero for the latter three fields.
2192 (put-bytevector line-port (string->utf8 file))
2193 (put-u8 line-port 0)
2194 (put-uleb128 line-port 0) ; directory
2195 (put-uleb128 line-port 0) ; mtime
2196 (put-uleb128 line-port 0))) ; size
2200 (put-u8 line-port 0) ; 0 byte terminating file list.
2202 ;; Patch prologue length.
2203 (let ((offset (port-position line-port)))
2204 (seek line-port 6 SEEK_SET)
2205 (put-u32 line-port (- offset 10))
2206 (seek line-port offset SEEK_SET))
2208 ;; Now write the statement program.
2210 (define (extended-op opcode payload-len)
2211 (put-u8 line-port 0) ; extended op
2212 (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
2213 (put-uleb128 line-port opcode))
2214 (define (set-address sym)
2215 (define (add-reloc! kind)
2217 (cons (make-linker-reloc kind
2218 (port-position line-port)
2222 (match (asm-word-size asm)
2225 (add-reloc! 'abs32/1)
2226 (put-u32 line-port 0))
2229 (add-reloc! 'abs64/1)
2230 (put-u64 line-port 0))))
2231 (define (end-sequence pc)
2232 (let ((pc-inc (- (asm-pos asm) pc)))
2233 (put-u8 line-port 2) ; advance-pc
2234 (put-uleb128 line-port pc-inc))
2236 (define (advance-pc pc-inc line-inc)
2237 (let ((spec (+ (- line-inc base) (* pc-inc range) 10)))
2239 ((or (< line-inc base) (>= line-inc (+ base range)))
2240 (advance-line line-inc)
2241 (advance-pc pc-inc 0))
2243 (put-u8 line-port spec))
2245 (put-u8 line-port 8) ; const-advance-pc
2246 (advance-pc (- pc-inc (floor/ (- 255 10) range))
2249 (put-u8 line-port 2) ; advance-pc
2250 (put-uleb128 line-port pc-inc)
2251 (advance-pc 0 line-inc)))))
2252 (define (advance-line inc)
2253 (put-u8 line-port 3)
2254 (put-sleb128 line-port inc))
2255 (define (set-file file)
2256 (put-u8 line-port 4)
2257 (put-uleb128 line-port file))
2258 (define (set-column col)
2259 (put-u8 line-port 5)
2260 (put-uleb128 line-port col))
2262 (set-address '.rtl-text)
2264 (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
2268 ;; There was no source info in the first place. Set
2269 ;; file register to 0 before adding final row.
2272 (((pc* file* line* col*) . in*)
2274 ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
2275 (lp in* pc file line col))
2277 (unless (eqv? col col*)
2279 (unless (eqv? file file*)
2281 (advance-pc (- pc* pc) (- line* line))
2282 (lp in* pc* file* line* col*)))))))))))
2284 (define (compute-code attr val)
2286 ('name (string-table-intern! strtab val))
2289 ('producer (string-table-intern! strtab val))
2290 ('language (language-name->code val))
2293 (define (choose-form attr val code)
2295 ((string? val) 'strp)
2296 ((eq? attr 'stmt-list) 'sec-offset)
2297 ((eq? attr 'low-pc) 'addr)
2298 ((exact-integer? code)
2300 ((< code 0) 'sleb128)
2301 ((<= code #xff) 'data1)
2302 ((<= code #xffff) 'data2)
2303 ((<= code #xffffffff) 'data4)
2304 ((<= code #xffffffffffffffff) 'data8)
2306 (else (error "unhandled case" attr val code))))
2308 (define (add-die-relocation! kind sym)
2310 (cons (make-linker-reloc kind (port-position die-port) 0 sym)
2313 (define (write-value code form)
2315 ('data1 (put-u8 die-port code))
2316 ('data2 (put-u16 die-port code))
2317 ('data4 (put-u32 die-port code))
2318 ('data8 (put-u64 die-port code))
2319 ('uleb128 (put-uleb128 die-port code))
2320 ('sleb128 (put-sleb128 die-port code))
2322 (match (asm-word-size asm)
2324 (add-die-relocation! 'abs32/1 code)
2325 (put-u32 die-port 0))
2327 (add-die-relocation! 'abs64/1 code)
2328 (put-u64 die-port 0))))
2329 ('sec-offset (put-u32 die-port code))
2330 ('strp (put-u32 die-port code))))
2332 (define (write-die die)
2334 ((tag ('@ (attrs vals) ...) children ...)
2335 (let* ((codes (map compute-code attrs vals))
2336 (forms (map choose-form attrs vals codes))
2337 (has-children? (not (null? children)))
2338 (abbrev-code (intern-abbrev tag has-children? attrs forms)))
2339 (put-uleb128 die-port abbrev-code)
2340 (for-each write-value codes forms)
2342 (for-each write-die children)
2343 (put-uleb128 die-port 0))))))
2345 ;; Compilation unit header.
2346 (put-u32 die-port 0) ; Length; will patch later.
2347 (put-u16 die-port 4) ; DWARF 4.
2348 (put-u32 die-port 0) ; Abbrevs offset.
2349 (put-u8 die-port (asm-word-size asm)) ; Address size.
2351 (write-die (make-compile-unit-die asm))
2353 ;; Terminate the abbrevs list.
2354 (put-uleb128 abbrev-port 0)
2358 (values (let ((bv (get-die-bv)))
2359 ;; Patch DWARF32 length.
2360 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
2361 (asm-endianness asm))
2362 (make-object asm '.debug_info bv die-relocs '()
2363 #:type SHT_PROGBITS #:flags 0))
2364 (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
2365 #:type SHT_PROGBITS #:flags 0)
2366 (make-object asm '.debug_str (link-string-table! strtab) '() '()
2367 #:type SHT_PROGBITS #:flags 0)
2368 (make-object asm '.debug_loc #vu8() '() '()
2369 #:type SHT_PROGBITS #:flags 0)
2370 (let ((bv (get-line-bv)))
2371 ;; Patch DWARF32 length.
2372 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
2373 (asm-endianness asm))
2374 (make-object asm '.debug_line bv line-relocs '()
2375 #:type SHT_PROGBITS #:flags 0)))))
2377 (define (link-objects asm)
2378 (let*-values (;; Link procprops before constants, because it probably
2379 ;; interns more constants.
2380 ((procprops) (link-procprops asm))
2381 ((ro rw rw-init) (link-constants asm))
2382 ;; Link text object after constants, so that the
2383 ;; constants initializer gets included.
2384 ((text) (link-text-object asm))
2385 ((frame-maps) (link-frame-maps asm))
2386 ((dt) (link-dynamic-section asm text rw rw-init frame-maps))
2387 ((symtab strtab) (link-symtab (linker-object-section text) asm))
2388 ((arities arities-strtab) (link-arities asm))
2389 ((docstrs docstrs-strtab) (link-docstrs asm))
2390 ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
2391 ;; This needs to be linked last, because linking other
2392 ;; sections adds entries to the string table.
2393 ((shstrtab) (link-shstrtab asm)))
2395 (list text ro frame-maps rw dt symtab strtab
2396 arities arities-strtab
2397 docstrs docstrs-strtab procprops
2398 dinfo dabbrev dstrtab dloc dline
2405 ;;; High-level public interfaces.
2408 (define* (link-assembly asm #:key (page-aligned? #t))
2409 "Produce an ELF image from the code and data emitted into @var{asm}.
2410 The result is a bytevector, by default linked so that read-only and
2411 writable data are on separate pages. Pass @code{#:page-aligned? #f} to
2412 disable this behavior."
2413 (link-elf (link-objects asm) #:page-aligned? page-aligned?))