5 (define target host-os)
12 (define (codegen-add xs si env)
15 (emit "movq ~a(%rbp), %rax" si)
19 (emit "addq $~a, ~a(%rbp)" y si)
21 (codegen-expr y (- si wordsize) env)
22 (emit "addq %rax, ~a(%rbp)" si))))
25 ; use si(%rbp) as the accumulator
26 (emit "movq $0, ~a(%rbp)" si)
29 (define (codegen-binop opcode)
31 (codegen-expr b si env)
32 (emit "movq %rax, ~a(%rbp)" si)
33 (codegen-expr a (- si wordsize) env)
34 (emit "~a ~a(%rbp), %rax" opcode si)))
36 (define codegen-sub (codegen-binop "sub"))
38 (define codegen-mul (codegen-binop "imul"))
40 (define (codegen-not x si env)
41 (codegen-expr x si env)
43 (emit "andq $1, %rax"))
45 (define (codegen-eq a b si env)
46 (codegen-expr a si env)
47 (emit "movq %rax, ~a(%rbp)" si)
48 (codegen-expr b (- si wordsize) env)
49 (emit "## ~a = ~b" a b)
50 (emit "cmpq ~a(%rbp), %rax" si)
53 ; 'write file handle addr-string num-bytes
55 (define (codegen-print x si env)
56 (codegen-expr x si env) ; x should be a static-string, producing a label
58 ; make a copy of string address since %rax and %rdi are clobbered
59 (emit "mov %rax, %rbx")
61 ; get the length of the null terminated string
62 (emit "mov %rax, %rdi")
63 (emit "xor %al, %al") ; set %al to 0
64 (emit "mov $-1, %rcx") ; max search length = max int = -1
65 (emit "cld") ; clear direction flag, search up in memory
66 (emit "repne scasb") ; scan string, %rcx = -strlen - 1 - 1
68 (emit "not %rcx") ; -%rcx = strlen + 1
71 (emit "movq %rbx, %rsi") ; string addr
72 (emit "movq %rcx, %rdx") ; num bytes
73 (emit "movq $1, %rdi") ; file handle (stdout)
75 ('darwin (emit "mov $0x2000004, %rax")) ; syscall 4 (write)
76 ('linux (emit "mov $1, %rax"))) ; syscall 1 (write)
81 (define (codegen-let bindings body si env)
83 ; is this a closure that captures itself?
84 ; e.g. (let ([x 3] [f (closure lambda0 (f x))]) (f))
85 (define (self-captive-closure? name expr)
86 (and (eqv? (ast-type expr) 'closure)
87 (memv name (caddr expr))))
89 (let* ((stack-offsets (map (lambda (name x) ; assoc map of binding name to offset
90 (cons name (- si (* x wordsize))))
92 (range 0 (length bindings))))
93 (inner-si (- si (* (length bindings) wordsize)))
95 (get-offset (lambda (n) (cdr (assoc n stack-offsets))))
103 (cons (cons name (get-offset name))
109 (let ([expr (cadr (assoc name bindings))])
110 (emit "## generating ~a with scc-env ~a" name scc-env)
111 (if (self-captive-closure? name expr)
112 ; if self-captive, insert a flag into the environment to let
113 ; codegen-closure realise this!
116 (cons (cons name 'self-captive)
118 (codegen-expr expr inner-si scc-env))
119 (emit "movq %rax, ~a(%rbp)" (get-offset name))))
122 env (reverse (sccs (graph bindings))))])
124 (for-each (lambda (form)
125 (codegen-expr form inner-si inner-env))
128 (define (codegen-var name si env)
129 (when (not (assoc name env))
130 (error #f (format "Variable ~a is not bound" name)))
131 (let ((offset (cdr (assoc name env))))
132 (emit "movq ~a(%rbp), %rax" offset)))
134 (define cur-lambda 0)
135 (define (fresh-lambda)
136 (set! cur-lambda (+ 1 cur-lambda))
137 (format "_lambda~a" (- cur-lambda 1)))
139 ; a closure on the heap looks like:
141 ; addr var1.... var2.... var3....
143 (define (codegen-closure label captured si env)
144 (let* ((heap-offsets (map (lambda (i) (+ 8 (* 8 i)))
145 (range 0 (length captured))))) ; 4, 12, 20, etc.
147 (emit "## creating closure")
149 (emit "movq heap_start@GOTPCREL(%rip), %rbx")
151 (emit "movq (%rbx), %rax") ; %rax = heap addr of closure
154 ; point heap_start to next space
155 (emit "addq $~a, (%rbx)" (+ 8 (* 8 (length captured))))
157 (emit "## storing address to lambda")
158 ; store the address to the lambda code
159 (emit "movq ~a@GOTPCREL(%rip), %rbx" label)
160 (emit "movq %rbx, 0(%rax)")
162 (emit "## storing captives")
163 ; store the captured vars
165 (lambda (var-name heap-offset)
166 (let ([stack-offset (cdr (assoc var-name env))])
167 (emit "### captive ~a" var-name)
168 (if (eqv? stack-offset 'self-captive)
169 ; captive refers to this closure:
170 ; move heap addr of this closure to stack!
171 (emit "movq %rax, ~a(%rax)" heap-offset)
173 (emit "movq ~a(%rbp), %rbx" stack-offset)
174 (emit "movq %rbx, ~a(%rax)" heap-offset)))))
178 ; for now we can only call closures
179 (define (codegen-call f args si env)
180 (codegen-expr f si env)
182 (emit "## starting call")
184 (emit "movq %rax, ~a(%rbp)" si) ; store address of closure first on stack
186 ; codegen the arguments, store them intermediately
190 (emit "## arg no. ~a" (- i 1))
191 (codegen-expr e (- si (* wordsize i)) env)
192 ; store intermediate result on stack
193 (emit "movq %rax, ~a(%rbp)" (- si (* wordsize i)))))
195 args (range 1 (length args)))
197 ; now that we have everything we need on the stack,
198 ; move them into the param registers
200 (emit "## moving args into place")
202 (lambda (i) (emit "movq ~a(%rbp), ~a"
203 (- si (* wordsize i))
205 (range 1 (length args)))
207 ; todo: can this be made more efficient
208 (emit "movq ~a(%rbp), %rax" si) ; load back pointer to closure
210 (emit "## moving captives into place")
212 ; move captives into first argument
213 (emit "movq %rax, %rbx")
214 (emit "addq $8, %rbx")
215 (emit "movq %rbx, ~a" (param-register 0))
217 (emit "## performing call")
219 (emit "addq $~a, %rsp" si) ; adjust the stack pointer to account all the stuff we put in the env
220 (emit "callq *(%rax)") ; call closure function
221 (emit "subq $~a, %rsp" si))
224 ; 1st param: pointer to captured args
226 ; 3rd param: 2nd arg, etc.
228 (define (codegen-lambda l)
229 (let* ((label (car l))
231 (captives (car stuff))
234 ; params = what actually gets passed
235 (params (append captives args))
237 (stack-offsets (map (lambda (i)
238 (* (- wordsize) (+ 1 i)))
239 (range 0 (length params))))
241 (env (map cons params stack-offsets)))
244 (display "## lambda captives: ")
247 (display "## lambda args: ")
250 (display "## lambda body: ")
254 (emit "push %rbp") ; preserve caller's base pointer
256 (emit "movq %rsp, %rbp") ; set up our own base pointer
258 ; load the captured vars onto the stack
262 (emit "# loading captive ~a" (list-ref captives i))
263 (emit "movq ~a(~a), %rbx" (* wordsize i) (param-register 0))
264 (emit "movq %rbx, ~a(%rbp)" (* (- wordsize) (+ 1 i)))))
265 (range 0 (length captives)))
267 ; load the args onto the stack
271 (emit "movq ~a, %rbx" (param-register (+ 1 i)))
272 (emit "movq %rbx, ~a(%rbp)"
274 (+ 1 (length captives) i)))))
275 (range 0 (length args)))
277 (codegen-expr body (* (- wordsize) (+ 1 (length params))) env)
279 (emit "pop %rbp") ; restore caller's base pointer
283 (define (fresh-label)
284 (set! cur-label (+ 1 cur-label))
285 (format "label~a" (- cur-label 1)))
287 (define (codegen-if cond then else si env)
288 (codegen-expr cond si env)
289 (emit "cmpq $0, %rax")
290 (let ((exit-label (fresh-label))
291 (else-label (fresh-label)))
292 (emit "je ~a" else-label)
293 (codegen-expr then si env)
294 (emit "jmp ~a" exit-label)
295 (emit "~a:" else-label)
296 (codegen-expr else si env)
297 (emit "~a:" exit-label)))
299 (define (codegen-expr e si env)
302 ('closure (codegen-closure (cadr e) (caddr e) si env))
305 ('+ (codegen-add (cdr e) si env))
306 ('- (codegen-sub (cadr e) (caddr e) si env))
307 ('* (codegen-mul (cadr e) (caddr e) si env))
308 ('! (codegen-not (cadr e) si env))
309 ('= (codegen-eq (cadr e) (caddr e) si env))
310 ('bool->int (codegen-expr (cadr e) si env))
311 ('print (codegen-print (cadr e) si env))
312 (else (codegen-call (car e) (cdr e) si env))))
314 ; this is a builtin being passed around as a variable
315 ('builtin (emit "movq $~a, %rax" (builtin-id e)))
317 ('let (codegen-let (let-bindings e)
322 ('var (codegen-var e si env))
324 ('if (codegen-if (cadr e) (caddr e) (cadddr e) si env))
326 ('bool-literal (emit "movq $~a, %rax" (if e 1 0)))
327 ('int-literal (emit "movq $~a, %rax" e))
329 ('static-string (emit "movq ~a@GOTPCREL(%rip), %rax"
332 (else (error #f "don't know how to codegen this"))))
336 (define (free-vars prog)
340 ('builtin '()) ; do nothing
341 ('var (if (memv e bound) '() (list e)))
344 (set! bound (append (lambda-args e) bound))
345 (collect (lambda-body e))))
347 ('app (flat-map collect e))
348 ('if (flat-map collect (cdr e)))
350 (let ([bind-fvs (flat-map (lambda (a)
352 (set! bound (cons (car a) bound))
355 (append bind-fvs (flat-map collect (let-body e)))))
359 ; ((lambda (x) (+ x y)) 42) => ((closure lambda1 (y)) 42)
360 ; [(lambda1 . ((y), (x), (+ x y))]
361 ; for builtins, this generates a closure if it is used
362 ; outside of an immediate app
363 ; but only one closure for each builtin
365 (define (extract-lambdas program)
367 (define (add-lambda e)
368 (let* ((label (fresh-lambda))
369 (args (lambda-args e))
370 (captured (free-vars e))
371 (body (extract (lambda-body e)))
372 (new-lambda (cons label (list captured args body))))
373 (set! lambdas (cons new-lambda lambdas))
374 `(closure ,label ,captured))) ; todo: should we string->symbol?
376 (define (find-builtin-lambda e)
377 (let [(l (assq (builtin-name e) lambdas))]
378 (if l `(closure ,(car l) ,(caadr l)) #f)))
380 (define (builtin-name e)
387 ('bool->int "_bool2int")
389 (else (error #f "don't know this builtin"))))
390 (define (builtin-args e)
399 (else (error #f "don't know this builtin"))))
401 (define (add-builtin-lambda e)
402 (let* [(label (builtin-name e))
404 (args (builtin-args e))
406 (new-lambda (cons label (list captured args body)))]
407 (set! lambdas (cons new-lambda lambdas))
408 `(closure ,label ,captured)))
412 ('lambda (add-lambda e))
413 ('let `(let ,(map (lambda (b) `(,(car b) ,@(extract (cdr b)))) (let-bindings e))
414 ,@(map extract (let-body e))))
416 ; if a builtin is used as a function, don't generate lambda
417 (if (eqv? 'builtin (ast-type (car e)))
419 (list (extract (car e))))
420 (map extract (cdr e))))
423 (if (find-builtin-lambda e)
424 (find-builtin-lambda e)
425 (add-builtin-lambda e)))
428 (else (ast-traverse extract e))))
429 (let ((transformed (extract program)))
430 (cons lambdas transformed)))
432 (define (extract-strings program)
434 (strings '())) ; assoc list of labels -> string
435 (define (fresh-string)
436 (set! cur-string (+ cur-string 1))
437 (format "string~a" (- cur-string 1)))
441 (let ((label (fresh-string)))
442 (set! strings (cons (cons label e) strings))
443 `(static-string ,label)))
444 (else (ast-traverse extract e))))
445 (let ((transformed (extract program)))
446 (cons strings transformed))))
448 (define (emit-string-data s)
450 (emit "\t.string \"~a\"" (cdr s)))
452 ;; (define (amd64-abi f)
453 ;; ; preserve registers
454 ;; (emit "push %rbp")
455 ;; ;; (emit "push %rbx")
456 ;; ;; (for-each (lambda (i)
457 ;; ;; (emit (string-append
459 ;; ;; (number->string i))))
460 ;; ;; '(12 13 14 15))
462 ;; (emit "movq %rsp, %rbp") ; set up the base pointer
465 ;; ; restore preserved registers
466 ;; ;; (for-each (lambda (i)
467 ;; ;; (emit (string-append
469 ;; ;; (number->string i))))
470 ;; ;; '(15 14 13 12))
471 ;; ;; (emit "pop %rbx")
476 ; 16(%rbp) mem arg 0 prev frame
477 ; -----------------------
478 ; 8(%rbp) return address cur frame
480 ; -8(%rbp) do what you want
481 ; ... do what you want
482 ; 0(%rsp) do what you want
484 (define (param-register n)
492 (else (error #f "need to test out the below"))
493 (else (format "~a(%rsp)" (- n 6)))))
495 (define (initialize-heap)
498 ('darwin "0x20000c5")
500 ; allocate some heap memory
501 (emit "mov $~a, %rax" mmap) ; mmap
502 (emit "xor %rdi, %rdi") ; addr = null
503 (emit "movq $1024, %rsi") ; length = 1kb
504 (emit "movq $0x3, %rdx") ; prot = read | write = 0x2 | 0x1
505 ; flags = anonymous | private
507 ('darwin (emit "movq $0x1002, %r10")) ; anon = 0x1000, priv = 0x02
508 ('linux (emit "movq $0x22, %r10"))) ; anon = 0x20, priv = 0x02
509 (emit "movq $-1, %r8") ; fd = -1
510 (emit "xor %r9, %r9") ; offset = 0
512 ; %rax now contains pointer to the start of the heap
515 (emit "movq heap_start@GOTPCREL(%rip), %rsi")
516 (emit "movq %rax, (%rsi)")))
518 (define (codegen program)
521 (let* ([body (program-body program)]
523 (extract-res-0 (extract-strings body))
524 (strings (car extract-res-0))
525 (extract-res-1 (extract-lambdas (cdr extract-res-0)))
526 (lambdas (car extract-res-1))
527 (xform-prog (cdr extract-res-1)))
529 (emit "\t.global _start")
531 ; (emit ".p2align 4,,15") is this needed?
533 (for-each codegen-lambda lambdas)
539 (emit "movq %rsp, %rbp") ; set up the base pointer
541 (codegen-expr xform-prog (- wordsize) '())
544 (emit "mov %rax, %rdi")
546 ('darwin (emit "movq $0x2000001, %rax"))
547 ('linux (emit "mov $60, %rax")))
555 (for-each emit-string-data strings)))
557 (define (compile-to-binary program output t)
559 (when (not (eq? (typecheck program) 'Int)) (error #f "not an Int"))
560 (let ([tmp-path "/tmp/a.s"])
561 (when (file-exists? tmp-path) (delete-file tmp-path))
562 (with-output-to-file tmp-path
563 (lambda () (codegen program)))
567 (system "as /tmp/a.s -o /tmp/a.o")
568 (system (format "ld /tmp/a.o -e _start -macosx_version_min 10.14 -static -o ~a" output)))
570 (system "as /tmp/a.s -o /tmp/a.o")
571 (system (format "ld /tmp/a.o -o ~a" output))))))
574 ; syscalls in linux and darwin use the following arguments for syscall instruction:
583 ; on darwin, the syscall is offset by 0x2000000
584 ; https://opensource.apple.com/source/xnu/xnu-2782.20.48/bsd/kern/syscalls.master
585 ; documentation for most syscalls: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys