1 ;;; Guile RTL assembler
3 ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013 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 ;;; RTL 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 RTL VM operations.
28 ;;; Assemblers for primitive instructions are generated programmatically
29 ;;; from (rtl-instruction-list), which itself is derived from the VM
30 ;;; sources. There are also "macro-instructions" like "label" or
31 ;;; "load-constant" 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 instruction)
48 #:use-module (system vm dwarf)
49 #:use-module (system vm elf)
50 #:use-module (system vm linker)
51 #:use-module (system vm objcode)
52 #:use-module (rnrs bytevectors)
53 #:use-module (ice-9 binary-ports)
54 #:use-module (ice-9 vlist)
55 #:use-module (ice-9 match)
56 #:use-module (srfi srfi-1)
57 #:use-module (srfi srfi-4)
58 #:use-module (srfi srfi-9)
59 #:use-module (srfi srfi-11)
60 #:export (make-assembler
68 ;;; RTL code consists of 32-bit units, often subdivided in some way.
69 ;;; These helpers create one 32-bit unit from multiple components.
71 (define-syntax-rule (pack-u8-u24 x y)
74 (define-syntax-rule (pack-u8-s24 x y)
80 (else (error "out of range" y)))
83 (define-syntax-rule (pack-u1-u7-u24 x y z)
84 (logior x (ash y 1) (ash z 8)))
86 (define-syntax-rule (pack-u8-u12-u12 x y z)
87 (logior x (ash y 8) (ash z 20)))
89 (define-syntax-rule (pack-u8-u8-u16 x y z)
90 (logior x (ash y 8) (ash z 16)))
92 (define-syntax-rule (pack-u8-u8-u8-u8 x y z w)
93 (logior x (ash y 8) (ash z 16) (ash w 24)))
95 (define-syntax pack-flags
97 ;; Add clauses as needed.
98 ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
99 (if f2 (ash 2 0) 0)))))
101 ;;; Helpers to read and write 32-bit units in a buffer.
103 (define-syntax-rule (u32-ref buf n)
104 (bytevector-u32-native-ref buf (* n 4)))
106 (define-syntax-rule (u32-set! buf n val)
107 (bytevector-u32-native-set! buf (* n 4) val))
109 (define-syntax-rule (s32-ref buf n)
110 (bytevector-s32-native-ref buf (* n 4)))
112 (define-syntax-rule (s32-set! buf n val)
113 (bytevector-s32-native-set! buf (* n 4) val))
118 ;;; A <meta> entry collects metadata for one procedure. Procedures are
119 ;;; written as contiguous ranges of RTL code.
121 (define-syntax-rule (assert-match arg pattern kind)
123 (unless (match x (pattern #t) (_ #f))
124 (error (string-append "expected " kind) x))))
126 (define-record-type <meta>
127 (%make-meta label properties low-pc high-pc arities)
130 (properties meta-properties set-meta-properties!)
132 (high-pc meta-high-pc set-meta-high-pc!)
133 (arities meta-arities set-meta-arities!))
135 (define (make-meta label properties low-pc)
136 (assert-match label (? symbol?) "symbol")
137 (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
138 (%make-meta label properties low-pc #f '()))
140 (define (meta-name meta)
141 (assq-ref (meta-properties meta) 'name))
143 ;; Metadata for one <lambda-case>.
144 (define-record-type <arity>
145 (make-arity req opt rest kw-indices allow-other-keys?
151 (kw-indices arity-kw-indices)
152 (allow-other-keys? arity-allow-other-keys?)
153 (low-pc arity-low-pc)
154 (high-pc arity-high-pc set-arity-high-pc!))
156 (define-syntax *block-size* (identifier-syntax 32))
158 ;;; An assembler collects all of the words emitted during assembly, and
159 ;;; also maintains ancillary information such as the constant table, a
160 ;;; relocation list, and so on.
162 ;;; RTL code consists of 32-bit units. We emit RTL code using native
163 ;;; endianness. If we're targeting a foreign endianness, we byte-swap
164 ;;; the bytevector as a whole instead of conditionalizing each access.
166 (define-record-type <asm>
167 (make-asm cur idx start prev written
171 shstrtab next-section-number
175 ;; We write RTL code into what is logically a growable vector,
176 ;; implemented as a list of blocks. asm-cur is the current block, and
177 ;; asm-idx is the current index into that block, in 32-bit units.
179 (cur asm-cur set-asm-cur!)
180 (idx asm-idx set-asm-idx!)
182 ;; asm-start is an absolute position, indicating the offset of the
183 ;; beginning of an instruction (in u32 units). It is updated after
184 ;; writing all the words for one primitive instruction. It models the
185 ;; position of the instruction pointer during execution, given that
186 ;; the RTL VM updates the IP only at the end of executing the
187 ;; instruction, and is thus useful for computing offsets between two
188 ;; points in a program.
190 (start asm-start set-asm-start!)
192 ;; The list of previously written blocks.
194 (prev asm-prev set-asm-prev!)
196 ;; The number of u32 words written in asm-prev, which is the same as
197 ;; the offset of the current block.
199 (written asm-written set-asm-written!)
201 ;; An alist of symbol -> position pairs, indicating the labels defined
202 ;; in this compilation unit.
204 (labels asm-labels set-asm-labels!)
206 ;; A list of relocations needed by the program text. We use an
207 ;; internal representation for relocations, and handle textualn
208 ;; relative relocations in the assembler. Other kinds of relocations
209 ;; are later reified as linker relocations and resolved by the linker.
211 (relocs asm-relocs set-asm-relocs!)
213 ;; Target information.
215 (word-size asm-word-size)
216 (endianness asm-endianness)
218 ;; The constant table, as a vhash of object -> label. All constants
219 ;; get de-duplicated and written into separate sections -- either the
220 ;; .rodata section, for read-only data, or .data, for constants that
221 ;; need initialization at load-time (like symbols). Constants can
222 ;; depend on other constants (e.g. a symbol depending on a stringbuf),
223 ;; so order in this table is important.
225 (constants asm-constants set-asm-constants!)
227 ;; A list of RTL instructions needed to initialize the constants.
228 ;; Will run in a thunk with 2 local variables.
230 (inits asm-inits set-asm-inits!)
232 ;; The shstrtab, for section names.
234 (shstrtab asm-shstrtab set-asm-shstrtab!)
236 ;; The section number for the next section to be written.
238 (next-section-number asm-next-section-number set-asm-next-section-number!)
240 ;; A list of <meta>, corresponding to procedure metadata.
242 (meta asm-meta set-asm-meta!)
244 ;; A list of (pos . source) pairs, indicating source information. POS
245 ;; is relative to the beginning of the text section, and SOURCE is in
246 ;; the same format that source-properties returns.
248 (sources asm-sources set-asm-sources!))
250 (define-inlinable (fresh-block)
251 (make-u32vector *block-size*))
253 (define* (make-assembler #:key (word-size (target-word-size))
254 (endianness (target-endianness)))
255 "Create an assembler for a given target @var{word-size} and
256 @var{endianness}, falling back to appropriate values for the configured
258 (make-asm (fresh-block) 0 0 '() 0
262 (make-string-table) 1
265 (define (intern-section-name! asm string)
266 "Add a string to the section name table (shstrtab)."
267 (string-table-intern! (asm-shstrtab asm) string))
269 (define-inlinable (asm-pos asm)
270 "The offset of the next word to be written into the code buffer, in
272 (+ (asm-idx asm) (asm-written asm)))
274 (define (allocate-new-block asm)
275 "Close off the current block, and arrange for the next word to be
276 written to a fresh block."
277 (let ((new (fresh-block)))
278 (set-asm-prev! asm (cons (asm-cur asm) (asm-prev asm)))
279 (set-asm-written! asm (asm-pos asm))
280 (set-asm-cur! asm new)
281 (set-asm-idx! asm 0)))
283 (define-inlinable (emit asm u32)
284 "Emit one 32-bit word into the instruction stream. Assumes that there
285 is space for the word, and ensures that there is space for the next
287 (u32-set! (asm-cur asm) (asm-idx asm) u32)
288 (set-asm-idx! asm (1+ (asm-idx asm)))
289 (if (= (asm-idx asm) *block-size*)
290 (allocate-new-block asm)))
292 (define-inlinable (make-reloc type label base word)
293 "Make an internal relocation of type @var{type} referencing symbol
294 @var{label}, @var{word} words after position @var{start}. @var{type}
295 may be x8-s24, indicating a 24-bit relative label reference that can be
296 fixed up by the assembler, or s32, indicating a 32-bit relative
297 reference that needs to be fixed up by the linker."
298 (list type label base word))
300 (define-inlinable (reset-asm-start! asm)
301 "Reset the asm-start after writing the words for one instruction."
302 (set-asm-start! asm (asm-pos asm)))
304 (define (emit-exported-label asm label)
305 "Define a linker symbol associating @var{label} with the current
307 (set-asm-labels! asm (acons label (asm-start asm) (asm-labels asm))))
309 (define (record-label-reference asm label)
310 "Record an x8-s24 local label reference. This value will get patched
311 up later by the assembler."
312 (let* ((start (asm-start asm))
314 (reloc (make-reloc 'x8-s24 label start (- pos start))))
315 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
317 (define* (record-far-label-reference asm label #:optional (offset 0))
318 "Record an s32 far label reference. This value will get patched up
319 later by the linker."
320 (let* ((start (- (asm-start asm) offset))
322 (reloc (make-reloc 's32 label start (- pos start))))
323 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
329 ;;; Primitive assemblers are defined by expanding `assembler' for each
330 ;;; opcode in `(rtl-instruction-list)'.
333 (eval-when (expand compile load eval)
334 (define (id-append ctx a b)
335 (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b)))))
337 (define-syntax assembler
339 (define-syntax op-case
342 ((_ asm name ((type arg ...) code ...) clause ...)
343 #`(if (eq? name 'type)
344 (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
347 (op-case asm name clause ...)))
349 #'(error "unmatched name" name)))))
351 (define (pack-first-word asm opcode type)
352 (with-syntax ((opcode opcode))
358 (emit asm (pack-u8-u24 opcode arg)))
360 (record-label-reference asm label)
363 (emit asm (pack-u8-u8-u16 opcode a (object-address imm))))
365 (emit asm (pack-u8-u12-u12 opcode a b)))
367 (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
369 (define (pack-tail-word asm type)
373 (emit asm (pack-u8-u24 a b)))
375 (record-label-reference asm label)
378 (emit asm (pack-u8-u8-u16 a b (object-address imm))))
380 (emit asm (pack-u8-u12-u12 a b c)))
381 ((U8_U8_U8_U8 a b c d)
382 (emit asm (pack-u8-u8-u8-u8 a b c d)))
386 (let ((val (object-address imm)))
387 (unless (zero? (ash val -32))
388 (error "FIXME: enable truncation of negative fixnums when cross-compiling"))
391 (unless (= (asm-word-size asm) 8)
392 (error "make-long-immediate unavailable for this target"))
393 (emit asm (ash (object-address imm) -32))
394 (emit asm (logand (object-address imm) (1- (ash 1 32)))))
397 (record-far-label-reference asm label)
400 (record-far-label-reference asm label)
403 (record-far-label-reference asm label)
406 (record-far-label-reference asm label
407 (* offset (/ (asm-word-size asm) 4)))
410 (emit asm (pack-u8-u24 0 a)))
412 (emit asm (pack-u8-u12-u12 0 a b)))
414 (record-label-reference asm label)
417 (record-label-reference asm label)
418 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
419 ((B1_U7_L24 a b label)
420 (record-label-reference asm label)
421 (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
423 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
425 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))))
428 ((_ name opcode word0 word* ...)
429 (with-syntax ((((formal0 ...)
431 (pack-first-word #'asm
432 (syntax->datum #'opcode)
433 (syntax->datum #'word0)))
436 (map (lambda (word) (pack-tail-word #'asm word))
437 (syntax->datum #'(word* ...)))))
438 #'(lambda (asm formal0 ... formal* ... ...)
439 (unless (asm? asm) (error "not an asm"))
442 (reset-asm-start! asm)))))))
444 (define assemblers (make-hash-table))
446 (define-syntax define-assembler
449 ((_ name opcode kind arg ...)
450 (with-syntax ((emit (id-append #'name #'emit- #'name)))
453 (let ((emit (assembler name opcode arg ...)))
454 (hashq-set! assemblers 'name emit)
458 (define-syntax visit-opcodes
461 ((visit-opcodes macro arg ...)
462 (with-syntax (((inst ...)
463 (map (lambda (x) (datum->syntax #'macro x))
464 (rtl-instruction-list))))
466 (macro arg ... . inst)
469 (visit-opcodes define-assembler)
471 (define (emit-text asm instructions)
472 "Assemble @var{instructions} using the assembler @var{asm}.
473 @var{instructions} is a sequence of RTL instructions, expressed as a
474 list of lists. This procedure can be called many times before calling
475 @code{link-assembly}."
476 (for-each (lambda (inst)
477 (apply (or (hashq-ref assemblers (car inst))
478 (error 'bad-instruction inst))
486 ;;; The constant table records a topologically sorted set of literal
487 ;;; constants used by a program. For example, a pair uses its car and
488 ;;; cdr, a string uses its stringbuf, etc.
490 ;;; Some things we want to add to the constant table are not actually
491 ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
492 ;;; references, or cache cells for non-closure procedures. For these we
493 ;;; define special record types and add instances of those record types
497 (define-inlinable (immediate? x)
498 "Return @code{#t} if @var{x} is immediate, and @code{#f} otherwise."
499 (not (zero? (logand (object-address x) 6))))
501 (define-record-type <stringbuf>
502 (make-stringbuf string)
504 (string stringbuf-string))
506 (define-record-type <static-procedure>
507 (make-static-procedure code)
509 (code static-procedure-code))
511 (define-record-type <cache-cell>
512 (make-cache-cell scope key)
514 (scope cache-cell-scope)
515 (key cache-cell-key))
517 (define (statically-allocatable? x)
518 "Return @code{#t} if a non-immediate constant can be allocated
519 statically, and @code{#f} if it would need some kind of runtime
521 (or (pair? x) (vector? x) (string? x) (stringbuf? x) (static-procedure? x)))
523 (define (intern-constant asm obj)
524 "Add an object to the constant table, and return a label that can be
525 used to reference it. If the object is already present in the constant
526 table, its existing label is used directly."
528 (intern-constant asm obj))
529 (define (field dst n obj)
530 (let ((src (recur obj)))
532 (list (if (statically-allocatable? obj)
533 `(make-non-immediate 1 ,src)
534 `(static-ref 1 ,src))
535 `(static-set! 1 ,dst ,n))
537 (define (intern obj label)
540 (append (field label 0 (car obj))
541 (field label 1 (cdr obj))))
543 (let lp ((i 0) (inits '()))
544 (if (< i (vector-length obj))
546 (append-reverse (field label (1+ i) (vector-ref obj i))
549 ((stringbuf? obj) '())
550 ((static-procedure? obj)
551 `((make-non-immediate 1 ,label)
552 (link-procedure! 1 ,(static-procedure-code obj))))
553 ((cache-cell? obj) '())
555 `((make-non-immediate 1 ,(recur (symbol->string obj)))
557 (static-set! 1 ,label 0)))
559 `((make-non-immediate 1 ,(recur (make-stringbuf obj)))
560 (static-set! 1 ,label 1)))
562 `((static-ref 1 ,(recur (keyword->symbol obj)))
563 (symbol->keyword 1 1)
564 (static-set! 1 ,label 0)))
566 `((make-non-immediate 1 ,(recur (number->string obj)))
568 (static-set! 1 ,label 0)))
570 (error "don't know how to intern" obj))))
572 ((immediate? obj) #f)
573 ((vhash-assoc obj (asm-constants asm)) => cdr)
575 ;; Note that calling intern may mutate asm-constants and
576 ;; asm-constant-inits.
577 (let* ((label (gensym "constant"))
578 (inits (intern obj label)))
579 (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
580 (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
583 (define (intern-non-immediate asm obj)
584 "Intern a non-immediate into the constant table, and return its
586 (when (immediate? obj)
587 (error "expected a non-immediate" obj))
588 (intern-constant asm obj))
590 (define (intern-cache-cell asm scope key)
591 "Intern a cache cell into the constant table, and return its label.
592 If there is already a cache cell with the given scope and key, it is
594 (intern-constant asm (make-cache-cell scope key)))
596 ;; Return the label of the cell that holds the module for a scope.
597 (define (intern-module-cache-cell asm scope)
598 "Intern a cache cell for a module, and return its label."
599 (intern-cache-cell asm scope #t))
605 ;;; Macro assemblers bridge the gap between primitive instructions and
606 ;;; some higher-level operations.
609 (define-syntax define-macro-assembler
612 ((_ (name arg ...) body body* ...)
613 (with-syntax ((emit (id-append #'name #'emit- #'name)))
616 (let ((emit (lambda (arg ...) body body* ...)))
617 (hashq-set! assemblers 'name emit)
621 (define-macro-assembler (load-constant asm dst obj)
624 (let ((bits (object-address obj)))
626 ((and (< dst 256) (zero? (ash bits -16)))
627 (emit-make-short-immediate asm dst obj))
628 ((zero? (ash bits -32))
629 (emit-make-long-immediate asm dst obj))
631 (emit-make-long-long-immediate asm dst obj)))))
632 ((statically-allocatable? obj)
633 (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
635 (emit-static-ref asm dst (intern-non-immediate asm obj)))))
637 (define-macro-assembler (load-static-procedure asm dst label)
638 (let ((loc (intern-constant asm (make-static-procedure label))))
639 (emit-make-non-immediate asm dst loc)))
641 (define-macro-assembler (begin-program asm label properties)
642 (emit-label asm label)
643 (let ((meta (make-meta label properties (asm-start asm))))
644 (set-asm-meta! asm (cons meta (asm-meta asm)))))
646 (define-macro-assembler (end-program asm)
647 (let ((meta (car (asm-meta asm))))
648 (set-meta-high-pc! meta (asm-start asm))
649 (set-meta-arities! meta (reverse (meta-arities meta)))))
651 (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
652 (emit-begin-opt-arity asm req '() #f nlocals alternate))
654 (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
655 (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
657 (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
658 allow-other-keys? nlocals alternate)
659 (assert-match req ((? symbol?) ...) "list of symbols")
660 (assert-match opt ((? symbol?) ...) "list of symbols")
661 (assert-match rest (or #f (? symbol?)) "#f or symbol")
662 (assert-match kw-indices (((? symbol?) . (? integer?)) ...)
663 "alist of symbol -> integer")
664 (assert-match allow-other-keys? (? boolean?) "boolean")
665 (assert-match nlocals (? integer?) "integer")
666 (assert-match alternate (or #f (? symbol?)) "#f or symbol")
667 (let* ((meta (car (asm-meta asm)))
668 (arity (make-arity req opt rest kw-indices allow-other-keys?
670 ;; The procedure itself is in slot 0, in the standard calling
671 ;; convention. For procedure prologues, nreq includes the
672 ;; procedure, so here we add 1.
673 (nreq (1+ (length req)))
675 (rest? (->bool rest)))
676 (set-meta-arities! meta (cons arity (meta-arities meta)))
678 ((or allow-other-keys? (pair? kw-indices))
679 (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
681 ((or rest? (pair? opt))
682 (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
684 (emit-standard-prelude asm nreq nlocals alternate)))))
686 (define-macro-assembler (end-arity asm)
687 (let ((arity (car (meta-arities (car (asm-meta asm))))))
688 (set-arity-high-pc! arity (asm-start asm))))
690 (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
693 (emit-br-if-nargs-ne asm nreq alternate)
694 (emit-alloc-frame asm nlocals))
695 ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
696 (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
698 (emit-assert-nargs-ee asm nreq)
699 (emit-alloc-frame asm nlocals))))
701 (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
703 (emit-br-if-nargs-lt asm nreq alternate)
704 (emit-assert-nargs-ge asm nreq))
707 (emit-bind-rest asm (+ nreq nopt)))
709 (emit-br-if-nargs-gt asm (+ nreq nopt) alternate))
711 (emit-assert-nargs-le asm (+ nreq nopt))))
712 (emit-alloc-frame asm nlocals))
714 (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
715 allow-other-keys? nlocals alternate)
717 (emit-br-if-nargs-lt asm nreq alternate)
718 (emit-assert-nargs-ge asm nreq))
719 (let ((ntotal (fold (lambda (kw ntotal)
721 (((? keyword?) . idx)
722 (max (1+ idx) ntotal))))
723 (+ nreq nopt) kw-indices)))
724 ;; FIXME: port 581f410f
725 (emit-bind-kwargs asm nreq
726 (pack-flags allow-other-keys? rest?)
730 (emit-alloc-frame asm nlocals)))
732 (define-macro-assembler (label asm sym)
733 (set-asm-labels! asm (acons sym (asm-start asm) (asm-labels asm))))
735 (define-macro-assembler (source asm source)
736 (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
738 (define-macro-assembler (cache-current-module! asm module scope)
739 (let ((mod-label (intern-module-cache-cell asm scope)))
740 (emit-static-set! asm module mod-label 0)))
742 (define-macro-assembler (cached-toplevel-box asm dst scope sym bound?)
743 (let ((sym-label (intern-non-immediate asm sym))
744 (mod-label (intern-module-cache-cell asm scope))
745 (cell-label (intern-cache-cell asm scope sym)))
746 (emit-toplevel-box asm dst cell-label mod-label sym-label bound?)))
748 (define-macro-assembler (cached-module-box asm dst module-name sym public? bound?)
749 (let* ((sym-label (intern-non-immediate asm sym))
750 (key (cons public? module-name))
751 (mod-name-label (intern-constant asm key))
752 (cell-label (intern-cache-cell asm key sym)))
753 (emit-module-box asm dst cell-label mod-name-label sym-label bound?)))
759 ;;; Helper for linking objects.
762 (define (make-object asm name bv relocs labels . kwargs)
763 "Make a linker object. This helper handles interning the name in the
764 shstrtab, assigning the size, allocating a fresh index, and defining a
765 corresponding linker symbol for the start of the section."
766 (let ((name-idx (intern-section-name! asm (symbol->string name)))
767 (index (asm-next-section-number asm)))
768 (set-asm-next-section-number! asm (1+ index))
769 (make-linker-object (apply make-elf-section
772 #:size (bytevector-length bv)
775 (cons (make-linker-symbol name 0) labels))))
781 ;;; Linking the constant table. This code is somewhat intertwingled
782 ;;; with the intern-constant code above, as that procedure also
783 ;;; residualizes instructions to initialize constants at load time.
786 (define (write-immediate asm buf pos x)
787 (let ((val (object-address x))
788 (endianness (asm-endianness asm)))
789 (case (asm-word-size asm)
790 ((4) (bytevector-u32-set! buf pos val endianness))
791 ((8) (bytevector-u64-set! buf pos val endianness))
792 (else (error "bad word size" asm)))))
794 (define (emit-init-constants asm)
795 "If there is writable data that needs initialization at runtime, emit
796 a procedure to do that and return its label. Otherwise return
798 (let ((inits (asm-inits asm)))
799 (and (not (null? inits))
800 (let ((label (gensym "init-constants")))
802 `((begin-program ,label ())
803 (assert-nargs-ee/locals 1 1)
805 (load-constant 1 ,*unspecified*)
810 (define (link-data asm data name)
811 "Link the static data for a program into the @var{name} section (which
812 should be .data or .rodata), and return the resulting linker object.
813 @var{data} should be a vhash mapping objects to labels."
814 (define (align address alignment)
816 (modulo (- alignment (modulo address alignment)) alignment)))
818 (define tc7-vector 13)
819 (define stringbuf-shared-flag #x100)
820 (define stringbuf-wide-flag #x400)
821 (define tc7-stringbuf 39)
822 (define tc7-narrow-stringbuf
823 (+ tc7-stringbuf stringbuf-shared-flag))
824 (define tc7-wide-stringbuf
825 (+ tc7-stringbuf stringbuf-shared-flag stringbuf-wide-flag))
826 (define tc7-ro-string (+ 21 #x200))
827 (define tc7-rtl-program 69)
829 (let ((word-size (asm-word-size asm))
830 (endianness (asm-endianness asm)))
831 (define (byte-length x)
834 (let ((x (stringbuf-string x)))
836 (case (string-bytes-per-char x)
837 ((1) (1+ (string-length x)))
838 ((4) (* (1+ (string-length x)) 4))
839 (else (error "bad string bytes per char" x))))))
840 ((static-procedure? x)
847 (* (1+ (vector-length x)) word-size))
851 (define (write-constant-reference buf pos x)
852 ;; The asm-inits will fix up any reference to a non-immediate.
853 (write-immediate asm buf pos (if (immediate? x) x #f)))
855 (define (write buf pos obj)
858 (let* ((x (stringbuf-string obj))
859 (len (string-length x))
860 (tag (if (= (string-bytes-per-char x) 1)
862 tc7-wide-stringbuf)))
865 (bytevector-u32-set! buf pos tag endianness)
866 (bytevector-u32-set! buf (+ pos 4) len endianness))
868 (bytevector-u64-set! buf pos tag endianness)
869 (bytevector-u64-set! buf (+ pos 8) len endianness))
871 (error "bad word size" asm)))
872 (let ((pos (+ pos (* word-size 2))))
873 (case (string-bytes-per-char x)
877 (let ((u8 (char->integer (string-ref x i))))
878 (bytevector-u8-set! buf (+ pos i) u8)
880 (bytevector-u8-set! buf (+ pos i) 0))))
884 (let ((u32 (char->integer (string-ref x i))))
885 (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
887 (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
888 (else (error "bad string bytes per char" x))))))
890 ((static-procedure? obj)
893 (bytevector-u32-set! buf pos tc7-rtl-program endianness)
894 (bytevector-u32-set! buf (+ pos 4) 0 endianness))
896 (bytevector-u64-set! buf pos tc7-rtl-program endianness)
897 (bytevector-u64-set! buf (+ pos 8) 0 endianness))
898 (else (error "bad word size"))))
901 (write-immediate asm buf pos #f))
904 (let ((tag (logior tc7-ro-string (ash (string-length obj) 8))))
907 (bytevector-u32-set! buf pos tc7-ro-string endianness)
908 (write-immediate asm buf (+ pos 4) #f) ; stringbuf
909 (bytevector-u32-set! buf (+ pos 8) 0 endianness)
910 (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
912 (bytevector-u64-set! buf pos tc7-ro-string endianness)
913 (write-immediate asm buf (+ pos 8) #f) ; stringbuf
914 (bytevector-u64-set! buf (+ pos 16) 0 endianness)
915 (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
916 (else (error "bad word size")))))
919 (write-constant-reference buf pos (car obj))
920 (write-constant-reference buf (+ pos word-size) (cdr obj)))
923 (let* ((len (vector-length obj))
924 (tag (logior tc7-vector (ash len 8))))
926 ((4) (bytevector-u32-set! buf pos tag endianness))
927 ((8) (bytevector-u64-set! buf pos tag endianness))
928 (else (error "bad word size")))
930 (when (< i (vector-length obj))
931 (let ((pos (+ pos word-size (* i word-size)))
932 (elt (vector-ref obj i)))
933 (write-constant-reference buf pos elt)
937 (write-immediate asm buf pos #f))
940 (write-immediate asm buf pos #f))
943 (write-immediate asm buf pos #f))
946 (error "unrecognized object" obj))))
949 ((vlist-null? data) #f)
951 (let* ((byte-len (vhash-fold (lambda (k v len)
952 (+ (byte-length k) (align len 8)))
954 (buf (make-bytevector byte-len 0)))
955 (let lp ((i 0) (pos 0) (labels '()))
956 (if (< i (vlist-length data))
957 (let* ((pair (vlist-ref data i))
959 (obj-label (cdr pair)))
962 (align (+ (byte-length obj) pos) 8)
963 (cons (make-linker-symbol obj-label pos) labels)))
964 (make-object asm name buf '() labels
966 ('.data (logior SHF_ALLOC SHF_WRITE))
967 ('.rodata SHF_ALLOC))))))))))
969 (define (link-constants asm)
970 "Link sections to hold constants needed by the program text emitted
973 Returns three values: an object for the .rodata section, an object for
974 the .data section, and a label for an initialization procedure. Any of
975 these may be @code{#f}."
976 (define (shareable? x)
980 (and (immediate? (car x)) (immediate? (cdr x))))
983 (or (= i (vector-length x))
984 (and (immediate? (vector-ref x i))
987 (let* ((constants (asm-constants asm))
988 (len (vlist-length constants)))
993 (values (link-data asm ro '.rodata)
994 (link-data asm rw '.data)
995 (emit-init-constants asm))
996 (let ((pair (vlist-ref constants i)))
997 (if (shareable? (car pair))
998 (lp (1+ i) (vhash-consq (car pair) (cdr pair) ro) rw)
999 (lp (1+ i) ro (vhash-consq (car pair) (cdr pair) rw))))))))
1004 ;;; Linking program text.
1007 (define (process-relocs buf relocs labels)
1008 "Patch up internal x8-s24 relocations, and any s32 relocations that
1009 reference symbols in the text section. Return a list of linker
1010 relocations for references to symbols defined outside the text section."
1012 (lambda (reloc tail)
1014 ((type label base word)
1015 (let ((abs (assq-ref labels label))
1016 (dst (+ base word)))
1020 (let ((rel (- abs base)))
1021 (s32-set! buf dst rel)
1023 (cons (make-linker-reloc 'rel32/4 (* dst 4) word label)
1027 (error "unbound near relocation" reloc))
1028 (let ((rel (- abs base))
1029 (u32 (u32-ref buf dst)))
1030 (u32-set! buf dst (pack-u8-s24 (logand u32 #xff) rel))
1032 (else (error "bad relocation kind" reloc)))))))
1036 (define (process-labels labels)
1037 "Define linker symbols for the label-offset pairs in @var{labels}.
1038 The offsets are expected to be expressed in words."
1040 (make-linker-symbol (car pair) (* (cdr pair) 4)))
1043 (define (swap-bytes! buf)
1044 "Patch up the text buffer @var{buf}, swapping the endianness of each
1046 (unless (zero? (modulo (bytevector-length buf) 4))
1047 (error "unexpected length"))
1048 (let ((byte-len (bytevector-length buf)))
1050 (unless (= pos byte-len)
1051 (bytevector-u32-set!
1053 (bytevector-u32-ref buf pos (endianness big))
1054 (endianness little))
1057 (define (link-text-object asm)
1058 "Link the .rtl-text section, swapping the endianness of the bytes if
1060 (let ((buf (make-u32vector (asm-pos asm))))
1061 (let lp ((pos 0) (prev (reverse (asm-prev asm))))
1063 (let ((byte-size (* (asm-idx asm) 4)))
1064 (bytevector-copy! (asm-cur asm) 0 buf pos byte-size)
1065 (unless (eq? (asm-endianness asm) (native-endianness))
1067 (make-object asm '.rtl-text
1069 (process-relocs buf (asm-relocs asm)
1071 (process-labels (asm-labels asm))))
1072 (let ((len (* *block-size* 4)))
1073 (bytevector-copy! (car prev) 0 buf pos len)
1074 (lp (+ pos len) (cdr prev)))))))
1080 ;;; Linking other sections of the ELF file, like the dynamic segment,
1081 ;;; the symbol table, etc.
1084 (define (link-dynamic-section asm text rw rw-init)
1085 "Link the dynamic section for an ELF image with RTL text, given the
1086 writable data section @var{rw} needing fixup from the procedure with
1087 label @var{rw-init}. @var{rw-init} may be false. If @var{rw} is true,
1088 it will be added to the GC roots at runtime."
1089 (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
1090 (let* ((endianness (asm-endianness asm))
1091 (bv (make-bytevector (* word-size (if rw (if rw-init 12 10) 6)) 0))
1094 (%set-uword! bv (* i word-size) uword endianness)))
1098 (set! relocs (cons (make-linker-reloc 'reloc-type
1099 (* i word-size) 0 label)
1101 (%set-uword! bv (* i word-size) 0 endianness))))
1102 (set-uword! 0 DT_GUILE_RTL_VERSION)
1103 (set-uword! 1 #x02020000)
1104 (set-uword! 2 DT_GUILE_ENTRY)
1105 (set-label! 3 '.rtl-text)
1109 (set-uword! 4 DT_GUILE_GC_ROOT)
1110 (set-label! 5 '.data)
1111 (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
1112 (set-uword! 7 (bytevector-length (linker-object-bv rw)))
1115 (set-uword! 8 DT_INIT) ; constants
1116 (set-label! 9 rw-init)
1117 (set-uword! 10 DT_NULL)
1120 (set-uword! 8 DT_NULL)
1123 (set-uword! 4 DT_NULL)
1125 (make-object asm '.dynamic bv relocs '()
1126 #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
1127 (case (asm-word-size asm)
1128 ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
1129 ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
1130 (else (error "bad word size" asm))))
1132 (define (link-shstrtab asm)
1133 "Link the string table for the section headers."
1134 (intern-section-name! asm ".shstrtab")
1135 (make-object asm '.shstrtab
1136 (link-string-table! (asm-shstrtab asm))
1138 #:type SHT_STRTAB #:flags 0))
1140 (define (link-symtab text-section asm)
1141 (let* ((endianness (asm-endianness asm))
1142 (word-size (asm-word-size asm))
1143 (size (elf-symbol-len word-size))
1144 (meta (reverse (asm-meta asm)))
1146 (strtab (make-string-table))
1147 (bv (make-bytevector (* n size) 0)))
1148 (define (intern-string! name)
1149 (string-table-intern! strtab (if name (symbol->string name) "")))
1152 (let ((name (intern-string! (meta-name meta))))
1153 (write-elf-symbol bv (* n size) endianness word-size
1156 ;; Symbol value and size are measured in
1158 #:value (* 4 (meta-low-pc meta))
1159 #:size (* 4 (- (meta-high-pc meta)
1160 (meta-low-pc meta)))
1162 #:visibility STV_HIDDEN
1163 #:shndx (elf-section-index text-section)))))
1165 (let ((strtab (make-object asm '.strtab
1166 (link-string-table! strtab)
1168 #:type SHT_STRTAB #:flags 0)))
1169 (values (make-object asm '.symtab
1172 #:type SHT_SYMTAB #:flags 0 #:entsize size
1173 #:link (elf-section-index
1174 (linker-object-section strtab)))
1177 ;;; The .guile.arities section describes the arities that a function can
1178 ;;; have. It is in two parts: a sorted array of headers describing
1179 ;;; basic arities, and an array of links out to a string table (and in
1180 ;;; the case of keyword arguments, to the data section) for argument
1181 ;;; names. The whole thing is prefixed by a uint32 indicating the
1182 ;;; offset of the end of the headers array.
1184 ;;; The arity headers array is a packed array of structures of the form:
1186 ;;; struct arity_header {
1187 ;;; uint32_t low_pc;
1188 ;;; uint32_t high_pc;
1189 ;;; uint32_t offset;
1195 ;;; All of the offsets and addresses are 32 bits. We can expand in the
1196 ;;; future to use 64-bit offsets if appropriate, but there are other
1197 ;;; aspects of RTL that constrain us to a total image that fits in 32
1198 ;;; bits, so for the moment we'll simplify the problem space.
1200 ;;; The following flags values are defined:
1203 ;;; #x2: allow-other-keys?
1204 ;;; #x4: has-keyword-args?
1205 ;;; #x8: is-case-lambda?
1207 ;;; Functions with a single arity specify their number of required and
1208 ;;; optional arguments in nreq and nopt, and do not have the
1209 ;;; is-case-lambda? flag set. Their "offset" member links to an array
1210 ;;; of pointers into the associated .guile.arities.strtab string table,
1211 ;;; identifying the argument names. This offset is relative to the
1212 ;;; start of the .guile.arities section. Links for required arguments
1213 ;;; are first, in order, as uint32 values. Next follow the optionals,
1214 ;;; then the rest link if has-rest? is set, then a link to the "keyword
1215 ;;; indices" literal if has-keyword-args? is set. Unlike the other
1216 ;;; links, the kw-indices link points into the data section, and is
1217 ;;; relative to the ELF image as a whole.
1219 ;;; Functions with no arities have no arities information present in the
1220 ;;; .guile.arities section.
1222 ;;; Functions with multiple arities are preceded by a header with
1223 ;;; is-case-lambda? set. All other fields are 0, except low-pc and
1224 ;;; high-pc which should be the bounds of the whole function. Headers
1225 ;;; for the individual arities follow. In this way the whole headers
1226 ;;; array is sorted in increasing low-pc order, and case-lambda clauses
1227 ;;; are contained within the [low-pc, high-pc] of the case-lambda
1230 ;; Length of the prefix to the arities section, in bytes.
1231 (define arities-prefix-len 4)
1233 ;; Length of an arity header, in bytes.
1234 (define arity-header-len (* 6 4))
1236 ;; The offset of "offset" within arity header, in bytes.
1237 (define arity-header-offset-offset (* 2 4))
1239 (define-syntax-rule (pack-arity-flags has-rest? allow-other-keys?
1240 has-keyword-args? is-case-lambda?)
1241 (logior (if has-rest? (ash 1 0) 0)
1242 (if allow-other-keys? (ash 1 1) 0)
1243 (if has-keyword-args? (ash 1 2) 0)
1244 (if is-case-lambda? (ash 1 3) 0)))
1246 (define (meta-arities-size meta)
1247 (define (lambda-size arity)
1249 (* 4 ;; name pointers
1250 (+ (length (arity-req arity))
1251 (length (arity-opt arity))
1252 (if (arity-rest arity) 1 0)
1253 (if (pair? (arity-kw-indices arity)) 1 0)))))
1254 (define (case-lambda-size arities)
1256 arity-header-len ;; case-lambda header
1257 (map lambda-size arities))) ;; the cases
1258 (match (meta-arities meta)
1260 ((arity) (lambda-size arity))
1261 (arities (case-lambda-size arities))))
1263 (define (write-arity-headers metas bv endianness)
1264 (define (write-arity-header* pos low-pc high-pc flags nreq nopt)
1265 (bytevector-u32-set! bv pos low-pc endianness)
1266 (bytevector-u32-set! bv (+ pos 4) high-pc endianness)
1267 (bytevector-u32-set! bv (+ pos 8) 0 endianness) ; offset
1268 (bytevector-u32-set! bv (+ pos 12) flags endianness)
1269 (bytevector-u32-set! bv (+ pos 16) nreq endianness)
1270 (bytevector-u32-set! bv (+ pos 20) nopt endianness))
1271 (define (write-arity-header pos arity)
1272 (write-arity-header* pos (arity-low-pc arity)
1273 (arity-high-pc arity)
1274 (pack-arity-flags (arity-rest arity)
1275 (arity-allow-other-keys? arity)
1276 (pair? (arity-kw-indices arity))
1278 (length (arity-req arity))
1279 (length (arity-opt arity))))
1280 (let lp ((metas metas) (pos arities-prefix-len) (offsets '()))
1283 ;; Fill in the prefix.
1284 (bytevector-u32-set! bv 0 pos endianness)
1285 (values pos (reverse offsets)))
1287 (match (meta-arities meta)
1288 (() (lp metas pos offsets))
1290 (write-arity-header pos arity)
1292 (+ pos arity-header-len)
1293 (acons arity (+ pos arity-header-offset-offset) offsets)))
1295 ;; Write a case-lambda header, then individual arities.
1296 ;; The case-lambda header's offset link is 0.
1297 (write-arity-header* pos (meta-low-pc meta) (meta-high-pc meta)
1298 (pack-arity-flags #f #f #f #t) 0 0)
1299 (let lp* ((arities arities) (pos (+ pos arity-header-len))
1302 (() (lp metas pos offsets))
1304 (write-arity-header pos arity)
1306 (+ pos arity-header-len)
1308 (+ pos arity-header-offset-offset)
1311 (define (write-arity-links asm bv pos arity-offset-pairs strtab)
1312 (define (write-symbol sym pos)
1313 (bytevector-u32-set! bv pos
1314 (string-table-intern! strtab (symbol->string sym))
1315 (asm-endianness asm))
1317 (define (write-kw-indices pos kw-indices)
1318 ;; FIXME: Assert that kw-indices is already interned.
1319 (make-linker-reloc 'abs32/1 pos 0
1320 (intern-constant asm kw-indices)))
1321 (let lp ((pos pos) (pairs arity-offset-pairs) (relocs '()))
1324 (unless (= pos (bytevector-length bv))
1325 (error "expected to fully fill the bytevector"
1326 pos (bytevector-length bv)))
1328 (((arity . offset) . pairs)
1329 (bytevector-u32-set! bv offset pos (asm-endianness asm))
1330 (let ((pos (fold write-symbol
1332 (append (arity-req arity)
1335 ((arity-rest arity) => list)
1337 (match (arity-kw-indices arity)
1338 (() (lp pos pairs relocs))
1342 (cons (write-kw-indices pos kw-indices) relocs)))))))))
1344 (define (link-arities asm)
1345 (let* ((endianness (asm-endianness asm))
1346 (metas (reverse (asm-meta asm)))
1347 (size (fold (lambda (meta size)
1348 (+ size (meta-arities-size meta)))
1351 (strtab (make-string-table))
1352 (bv (make-bytevector size 0)))
1353 (let ((kw-indices-relocs
1356 (write-arity-headers metas bv endianness))
1357 (lambda (pos arity-offset-pairs)
1358 (write-arity-links asm bv pos arity-offset-pairs strtab)))))
1359 (let ((strtab (make-object asm '.guile.arities.strtab
1360 (link-string-table! strtab)
1362 #:type SHT_STRTAB #:flags 0)))
1363 (values (make-object asm '.guile.arities
1365 kw-indices-relocs '()
1366 #:type SHT_PROGBITS #:flags 0
1367 #:link (elf-section-index
1368 (linker-object-section strtab)))
1372 ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
1373 ;;; values. Pc and str are both 32 bits wide. (Either could change to
1374 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1375 ;;; entry to a program, relative to the start of the text section, and
1376 ;;; str is an index into the associated .guile.docstrs.strtab string
1380 ;; The size of a docstrs entry, in bytes.
1381 (define docstr-size 8)
1383 (define (link-docstrs asm)
1384 (define (find-docstrings)
1385 (filter-map (lambda (meta)
1386 (define (is-documentation? pair)
1387 (eq? (car pair) 'documentation))
1388 (let* ((props (meta-properties meta))
1389 (tail (find-tail is-documentation? props)))
1391 (not (find-tail is-documentation? (cdr tail)))
1392 (string? (cdar tail))
1393 (cons (meta-low-pc meta) (cdar tail)))))
1394 (reverse (asm-meta asm))))
1395 (let* ((endianness (asm-endianness asm))
1396 (docstrings (find-docstrings))
1397 (strtab (make-string-table))
1398 (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
1399 (fold (lambda (pair pos)
1402 (bytevector-u32-set! bv pos pc endianness)
1403 (bytevector-u32-set! bv (+ pos 4)
1404 (string-table-intern! strtab string)
1406 (+ pos docstr-size))))
1409 (let ((strtab (make-object asm '.guile.docstrs.strtab
1410 (link-string-table! strtab)
1412 #:type SHT_STRTAB #:flags 0)))
1413 (values (make-object asm '.guile.docstrs
1416 #:type SHT_PROGBITS #:flags 0
1417 #:link (elf-section-index
1418 (linker-object-section strtab)))
1422 ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
1423 ;;; values. Pc and addr are both 32 bits wide. (Either could change to
1424 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1425 ;;; entry to a program, relative to the start of the text section, and
1426 ;;; addr is the address of the associated properties alist, relative to
1427 ;;; the start of the ELF image.
1429 ;;; Since procedure properties are stored in the data sections, we need
1430 ;;; to link the procedures property section first. (Note that this
1431 ;;; constraint does not apply to the arities section, which may
1432 ;;; reference the data sections via the kw-indices literal, because
1433 ;;; assembling the text section already makes sure that the kw-indices
1437 ;; The size of a procprops entry, in bytes.
1438 (define procprops-size 8)
1440 (define (link-procprops asm)
1441 (define (assoc-remove-one alist key value-pred)
1444 ((((? (lambda (x) (eq? x key))) . value) . alist)
1445 (if (value-pred value)
1447 (acons key value alist)))
1449 (acons k v (assoc-remove-one alist key value-pred)))))
1450 (define (props-without-name-or-docstring meta)
1452 (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
1455 (define (find-procprops)
1456 (filter-map (lambda (meta)
1457 (let ((props (props-without-name-or-docstring meta)))
1459 (cons (meta-low-pc meta) props))))
1460 (reverse (asm-meta asm))))
1461 (let* ((endianness (asm-endianness asm))
1462 (procprops (find-procprops))
1463 (bv (make-bytevector (* (length procprops) procprops-size) 0)))
1464 (let lp ((procprops procprops) (pos 0) (relocs '()))
1467 (make-object asm '.guile.procprops
1470 #:type SHT_PROGBITS #:flags 0))
1471 (((pc . props) . procprops)
1472 (bytevector-u32-set! bv pos pc endianness)
1474 (+ pos procprops-size)
1475 (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
1476 (intern-constant asm props))
1480 ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
1481 ;;; sections provide line number and local variable liveness
1482 ;;; information. Their format is defined by the DWARF
1486 (define (asm-language asm)
1487 ;; FIXME: Plumb language through to the assembler.
1490 ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
1491 (define (link-debug asm)
1492 (define (put-s8 port val)
1493 (let ((bv (make-bytevector 1)))
1494 (bytevector-s8-set! bv 0 val)
1495 (put-bytevector port bv)))
1497 (define (put-u16 port val)
1498 (let ((bv (make-bytevector 2)))
1499 (bytevector-u16-set! bv 0 val (asm-endianness asm))
1500 (put-bytevector port bv)))
1502 (define (put-u32 port val)
1503 (let ((bv (make-bytevector 4)))
1504 (bytevector-u32-set! bv 0 val (asm-endianness asm))
1505 (put-bytevector port bv)))
1507 (define (put-u64 port val)
1508 (let ((bv (make-bytevector 8)))
1509 (bytevector-u64-set! bv 0 val (asm-endianness asm))
1510 (put-bytevector port bv)))
1512 (define (put-uleb128 port val)
1514 (let ((next (ash val -7)))
1518 (put-u8 port (logior #x80 (logand val #x7f)))
1521 (define (put-sleb128 port val)
1523 (if (<= 0 (+ val 64) 128)
1524 (put-u8 port (logand val #x7f))
1526 (put-u8 port (logior #x80 (logand val #x7f)))
1527 (lp (ash val -7))))))
1529 (define (port-position port)
1530 (seek port 0 SEEK_CUR))
1532 (define (meta->subprogram-die meta)
1536 => (lambda (name) `((name ,(symbol->string name)))))
1539 (low-pc ,(meta-label meta))
1540 (high-pc ,(* 4 (- (meta-high-pc meta) (meta-low-pc meta)))))))
1542 (define (make-compile-unit-die asm)
1544 (@ (producer ,(string-append "Guile " (version)))
1545 (language ,(asm-language asm))
1547 (high-pc ,(* 4 (asm-pos asm)))
1549 ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
1551 (let-values (((die-port get-die-bv) (open-bytevector-output-port))
1553 ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
1554 ;; (tag has-kids? attrs forms) -> code
1555 ((abbrevs) vlist-null)
1556 ((strtab) (make-string-table))
1557 ((line-port get-line-bv) (open-bytevector-output-port))
1560 ((files) vlist-null))
1562 (define (write-abbrev code tag has-children? attrs forms)
1563 (put-uleb128 abbrev-port code)
1564 (put-uleb128 abbrev-port (tag-name->code tag))
1565 (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
1566 (for-each (lambda (attr form)
1567 (put-uleb128 abbrev-port (attribute-name->code attr))
1568 (put-uleb128 abbrev-port (form-name->code form)))
1570 (put-uleb128 abbrev-port 0)
1571 (put-uleb128 abbrev-port 0))
1573 (define (intern-abbrev tag has-children? attrs forms)
1574 (let ((key (list tag has-children? attrs forms)))
1575 (match (vhash-assoc key abbrevs)
1577 (#f (let ((code (1+ (vlist-length abbrevs))))
1578 (set! abbrevs (vhash-cons key code abbrevs))
1579 (write-abbrev code tag has-children? attrs forms)
1582 (define (intern-file file)
1583 (match (vhash-assoc file files)
1585 (#f (let ((code (1+ (vlist-length files))))
1586 (set! files (vhash-cons file code files))
1589 (define (write-sources)
1590 ;; Choose line base and line range values that will allow for an
1591 ;; address advance range of 16 words. The special opcode range is
1592 ;; from 10 to 255, so 246 values.
1596 (let lp ((sources (asm-sources asm)) (out '()))
1598 (((pc . s) . sources)
1599 (let ((file (assq-ref s 'filename))
1600 (line (assq-ref s 'line))
1601 (col (assq-ref s 'column)))
1603 ;; Guile line and column numbers are 0-indexed, but
1604 ;; they are 1-indexed for DWARF.
1606 (if file (intern-file file) 0)
1611 ;; Compilation unit header for .debug_line. We write in
1612 ;; DWARF 2 format because more tools understand it than DWARF
1613 ;; 4, which incompatibly adds another field to this header.
1615 (put-u32 line-port 0) ; Length; will patch later.
1616 (put-u16 line-port 2) ; DWARF 2 format.
1617 (put-u32 line-port 0) ; Prologue length; will patch later.
1618 (put-u8 line-port 4) ; Minimum instruction length: 4 bytes.
1619 (put-u8 line-port 1) ; Default is-stmt: true.
1621 (put-s8 line-port base) ; Line base. See the DWARF standard.
1622 (put-u8 line-port range) ; Line range. See the DWARF standard.
1623 (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
1625 ;; A table of the number of uleb128 arguments taken by each
1626 ;; of the standard opcodes.
1627 (put-u8 line-port 0) ; 1: copy
1628 (put-u8 line-port 1) ; 2: advance-pc
1629 (put-u8 line-port 1) ; 3: advance-line
1630 (put-u8 line-port 1) ; 4: set-file
1631 (put-u8 line-port 1) ; 5: set-column
1632 (put-u8 line-port 0) ; 6: negate-stmt
1633 (put-u8 line-port 0) ; 7: set-basic-block
1634 (put-u8 line-port 0) ; 8: const-add-pc
1635 (put-u8 line-port 1) ; 9: fixed-advance-pc
1637 ;; Include directories, as a zero-terminated sequence of
1638 ;; nul-terminated strings. Nothing, for the moment.
1639 (put-u8 line-port 0)
1641 ;; File table. For each file that contributes to this
1642 ;; compilation unit, a nul-terminated file name string, and a
1643 ;; uleb128 for each of directory the file was found in, the
1644 ;; modification time, and the file's size in bytes. We pass
1645 ;; zero for the latter three fields.
1646 (vlist-for-each (match-lambda
1648 (put-bytevector line-port (string->utf8 file))
1649 (put-u8 line-port 0)
1650 (put-uleb128 line-port 0) ; directory
1651 (put-uleb128 line-port 0) ; mtime
1652 (put-uleb128 line-port 0) ; size
1655 (put-u8 line-port 0) ; 0 byte terminating file list.
1657 ;; Patch prologue length.
1658 (let ((offset (port-position line-port)))
1659 (seek line-port 6 SEEK_SET)
1660 (put-u32 line-port (- offset 10))
1661 (seek line-port offset SEEK_SET))
1663 ;; Now write the statement program.
1665 (define (extended-op opcode payload-len)
1666 (put-u8 line-port 0) ; extended op
1667 (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
1668 (put-uleb128 line-port opcode))
1669 (define (set-address sym)
1670 (define (add-reloc! kind)
1672 (cons (make-linker-reloc kind
1673 (port-position line-port)
1677 (match (asm-word-size asm)
1680 (add-reloc! 'abs32/1)
1681 (put-u32 line-port 0))
1684 (add-reloc! 'abs64/1)
1685 (put-u64 line-port 0))))
1686 (define (end-sequence pc)
1687 (let ((pc-inc (- (asm-pos asm) pc)))
1688 (put-u8 line-port 2) ; advance-pc
1689 (put-uleb128 line-port pc-inc))
1691 (define (advance-pc pc-inc line-inc)
1692 (let ((spec (+ (- line-inc base) (* pc-inc range) 10)))
1694 ((or (< line-inc base) (>= line-inc (+ base range)))
1695 (advance-line line-inc)
1696 (advance-pc pc-inc 0))
1698 (put-u8 line-port spec))
1700 (put-u8 line-port 8) ; const-advance-pc
1701 (advance-pc (- pc-inc (floor/ (- 255 10) range))
1704 (put-u8 line-port 2) ; advance-pc
1705 (put-uleb128 line-port pc-inc)
1706 (advance-pc 0 line-inc)))))
1707 (define (advance-line inc)
1708 (put-u8 line-port 3)
1709 (put-sleb128 line-port inc))
1710 (define (set-file file)
1711 (put-u8 line-port 4)
1712 (put-uleb128 line-port file))
1713 (define (set-column col)
1714 (put-u8 line-port 5)
1715 (put-uleb128 line-port col))
1717 (set-address '.rtl-text)
1719 (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
1721 (() (end-sequence pc))
1722 (((pc* file* line* col*) . in*)
1724 ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
1725 (lp in* pc file line col))
1727 (unless (eqv? col col*)
1729 (unless (eqv? file file*)
1731 (advance-pc (- pc* pc) (- line* line))
1732 (lp in* pc* file* line* col*)))))))))))
1734 (define (compute-code attr val)
1736 ('name (string-table-intern! strtab val))
1739 ('producer (string-table-intern! strtab val))
1740 ('language (language-name->code val))
1743 (define (exact-integer? val)
1744 (and (number? val) (integer? val) (exact? val)))
1746 (define (choose-form attr val code)
1748 ((string? val) 'strp)
1749 ((eq? attr 'stmt-list) 'sec-offset)
1750 ((exact-integer? code)
1752 ((< code 0) 'sleb128)
1753 ((<= code #xff) 'data1)
1754 ((<= code #xffff) 'data2)
1755 ((<= code #xffffffff) 'data4)
1756 ((<= code #xffffffffffffffff) 'data8)
1758 ((symbol? val) 'addr)
1759 (else (error "unhandled case" attr val code))))
1761 (define (add-die-relocation! kind sym)
1763 (cons (make-linker-reloc kind (port-position die-port) 0 sym)
1766 (define (write-value code form)
1768 ('data1 (put-u8 die-port code))
1769 ('data2 (put-u16 die-port code))
1770 ('data4 (put-u32 die-port code))
1771 ('data8 (put-u64 die-port code))
1772 ('uleb128 (put-uleb128 die-port code))
1773 ('sleb128 (put-sleb128 die-port code))
1775 (match (asm-word-size asm)
1777 (add-die-relocation! 'abs32/1 code)
1778 (put-u32 die-port 0))
1780 (add-die-relocation! 'abs64/1 code)
1781 (put-u64 die-port 0))))
1782 ('sec-offset (put-u32 die-port code))
1783 ('strp (put-u32 die-port code))))
1785 (define (write-die die)
1787 ((tag ('@ (attrs vals) ...) children ...)
1788 (let* ((codes (map compute-code attrs vals))
1789 (forms (map choose-form attrs vals codes))
1790 (has-children? (not (null? children)))
1791 (abbrev-code (intern-abbrev tag has-children? attrs forms)))
1792 (put-uleb128 die-port abbrev-code)
1793 (for-each write-value codes forms)
1795 (for-each write-die children)
1796 (put-uleb128 die-port 0))))))
1798 ;; Compilation unit header.
1799 (put-u32 die-port 0) ; Length; will patch later.
1800 (put-u16 die-port 4) ; DWARF 4.
1801 (put-u32 die-port 0) ; Abbrevs offset.
1802 (put-u8 die-port (asm-word-size asm)) ; Address size.
1804 (write-die (make-compile-unit-die asm))
1806 ;; Terminate the abbrevs list.
1807 (put-uleb128 abbrev-port 0)
1811 (values (let ((bv (get-die-bv)))
1812 ;; Patch DWARF32 length.
1813 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
1814 (asm-endianness asm))
1815 (make-object asm '.debug_info bv die-relocs '()
1816 #:type SHT_PROGBITS #:flags 0))
1817 (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
1818 #:type SHT_PROGBITS #:flags 0)
1819 (make-object asm '.debug_str (link-string-table! strtab) '() '()
1820 #:type SHT_PROGBITS #:flags 0)
1821 (make-object asm '.debug_loc #vu8() '() '()
1822 #:type SHT_PROGBITS #:flags 0)
1823 (let ((bv (get-line-bv)))
1824 ;; Patch DWARF32 length.
1825 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
1826 (asm-endianness asm))
1827 (make-object asm '.debug_line bv line-relocs '()
1828 #:type SHT_PROGBITS #:flags 0)))))
1830 (define (link-objects asm)
1831 (let*-values (;; Link procprops before constants, because it probably
1832 ;; interns more constants.
1833 ((procprops) (link-procprops asm))
1834 ((ro rw rw-init) (link-constants asm))
1835 ;; Link text object after constants, so that the
1836 ;; constants initializer gets included.
1837 ((text) (link-text-object asm))
1838 ((dt) (link-dynamic-section asm text rw rw-init))
1839 ((symtab strtab) (link-symtab (linker-object-section text) asm))
1840 ((arities arities-strtab) (link-arities asm))
1841 ((docstrs docstrs-strtab) (link-docstrs asm))
1842 ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
1843 ;; This needs to be linked last, because linking other
1844 ;; sections adds entries to the string table.
1845 ((shstrtab) (link-shstrtab asm)))
1847 (list text ro rw dt symtab strtab arities arities-strtab
1848 docstrs docstrs-strtab procprops
1849 dinfo dabbrev dstrtab dloc dline
1856 ;;; High-level public interfaces.
1859 (define* (link-assembly asm #:key (page-aligned? #t))
1860 "Produce an ELF image from the code and data emitted into @var{asm}.
1861 The result is a bytevector, by default linked so that read-only and
1862 writable data are on separate pages. Pass @code{#:page-aligned? #f} to
1863 disable this behavior."
1864 (link-elf (link-objects asm) #:page-aligned? page-aligned?))
1866 (define (assemble-program instructions)
1867 "Take the sequence of instructions @var{instructions}, assemble them
1868 into RTL code, link an image, and load that image from memory. Returns
1870 (let ((asm (make-assembler)))
1871 (emit-text asm instructions)
1872 (load-thunk-from-memory (link-assembly asm #:page-aligned? #f))))