X-Git-Url: http://git.lukelau.me/?a=blobdiff_plain;f=codegen.scm;h=9b3878a2e947f3d3314c8c9c4bc96bca38a83a7f;hb=6f699d1ddbb1cd33ec3095a0e6e9a6eee157d708;hp=25d99a199da43889ef289b1e6af1292595aa4af0;hpb=2d16419b1556917b7c73d5dffe546124bb8ed534;p=scheme.git diff --git a/codegen.scm b/codegen.scm index 25d99a1..9b3878a 100644 --- a/codegen.scm +++ b/codegen.scm @@ -50,6 +50,9 @@ (define (codegen-print x si env) (codegen-expr x si env) ; x should be a static-string, producing a label + ; make a copy of string address since %rax and %rdi are clobbered + (emit "mov %rax, %rbx") + ; get the length of the null terminated string (emit "mov %rax, %rdi") (emit "xor %al, %al") ; set %al to 0 @@ -61,7 +64,7 @@ (emit "dec %rcx") (emit "mov %rcx, %rdx") ; number of bytes - (emit "mov %rax, %rsi") ; addr of string + (emit "mov %rbx, %rsi") ; addr of string (emit "mov $1, %rax") ; file handle 1 (stdout) (emit "mov $1, %rdi") ; syscall 1 (write) (emit "syscall")) @@ -118,7 +121,6 @@ (param-register i))) captured (range 0 (length captured))) - ; then codegen the arguments and move them into the next param registers (for-each (lambda (e i) @@ -213,7 +215,7 @@ ('bool-literal (emit "movq $~a, %rax" (if e 1 0))) ('int-literal (emit "movq $~a, %rax" e)) - ('static-string (emit "movq (~a), %rax" (cadr e))) ; move label + ('static-string (emit "lea ~a, %rax" (cadr e))) ; move label (else (error #f "don't know how to codegen this")))) @@ -340,6 +342,21 @@ (for-each codegen-lambda lambdas) (emit "_start:") + + ; allocate some heap memory + (emit "mov $9, %rax") ; mmap + (emit "xor %rdi, %rdi") ; addr = null + (emit "movq $1024, %rsi") ; length = 1kb + (emit "movq $0x3, %rdx") ; prot = read | write = 0x2 | 0x1 + (emit "movq $0x22, %r10") ; flags = anonymous | private = 0x20 | 0x02 + (emit "movq $-1, %r8") ; fd = -1 + (emit "xor %r9, %r9") ; offset = 0 + (emit "syscall") + + ; %rax now contains pointer to the start of the heap + ; keep track of it + (emit "movq %rax, (heap_start)") + (emit "movq %rsp, %rbp") ; set up the base pointer (codegen-expr xform-prog 0 '()) @@ -348,7 +365,10 @@ (emit "mov $60, %rax") (emit "syscall") - (emit "\t.data") + (emit ".data") + + (emit "heap_start:") + (emit "\t.quad 0") (for-each emit-string-data strings))) @@ -359,3 +379,13 @@ (with-output-to-file tmp-path (lambda () (codegen program))) (system (format "clang -nostdlib /tmp/a.s -o ~a" output)))) + +; NOTES +; syscalls in linux use the following arguments for syscall instruction: +; %rax = syscall # +; %rdi = 1st arg +; %rsi = 2nd arg +; %rdx = 3rd arg +; %r10 = 4th arg +; %r8 = 5th arg +; %r9 = 6th arg