Move utils into its onw file
[scheme.git] / codegen.scm
1 (load "typecheck.scm")
2 (load "ast.scm")
3 (load "platform.scm")
4
5 (define target host-os)
6
7 (define (emit . s)
8   (begin
9     (apply printf s)
10     (display "\n")))
11
12 (define wordsize 8)
13
14 (define (type-size data-layouts type)
15
16   (define (adt-size adt)
17     (let ([sizes
18            (map (lambda (sum)
19                   (fold-left (lambda (acc x) (+ acc (type-size data-layouts x)))
20                              wordsize ; one word needed to store tag
21                              (cdr sum)))
22                 (cdr adt))])
23       (apply max sizes)))
24   
25   (case type
26     ['Int wordsize]
27     ['Bool wordsize]
28     [else
29      (let ([adt (assoc type data-layouts)])
30        (if adt
31            (adt-size adt)
32            (error #f "unknown size" type)))]))
33
34 (define (on-stack? expr)
35   (case (ast-type expr)
36     ['stack (cadr expr)]
37     [else #f]))
38
39                                         ; an environment consists of adt layouts in scope,
40                                         ; and any bound variables.
41                                         ; bound variables are an assoc list with their stack offset
42 (define make-env list)
43 (define env-data-layouts car)
44 (define env-bindings cadr)
45
46 (define (codegen-add xs si env)
47   (define (go ys)
48     (if (null? ys)
49         (emit "movq ~a(%rbp), %rax" si)
50         (begin
51           (let ((y (car ys)))
52             (if (integer? y)
53                 (emit "addq $~a, ~a(%rbp)" y si)
54                 (begin
55                   (codegen-expr y (- si wordsize) env)
56                   (emit "addq %rax, ~a(%rbp)" si))))
57           (go (cdr ys)))))
58   (begin
59                                         ; use si(%rbp) as the accumulator
60     (emit "movq $0, ~a(%rbp)" si)
61     (go xs)))
62
63 (define (codegen-binop opcode)
64   (lambda (a b si env)
65     (codegen-expr b si env)
66     (emit "movq %rax, ~a(%rbp)" si)
67     (codegen-expr a (- si wordsize) env)
68     (emit "~a ~a(%rbp), %rax" opcode si)))
69
70 (define codegen-sub (codegen-binop "sub"))
71
72 (define codegen-mul (codegen-binop "imul"))
73
74 (define (codegen-not x si env)
75   (codegen-expr x si env)
76   (emit "notq %rax")
77   (emit "andq $1, %rax"))
78
79 (define (codegen-eq a b si env)
80   (codegen-expr a si env)
81   (emit "movq %rax, ~a(%rbp)" si)
82   (codegen-expr b (- si wordsize) env)
83   (emit "## ~a = ~b" a b)
84   (emit "cmpq ~a(%rbp), %rax" si)
85   (emit "sete %al"))
86
87                                         ; 'write file handle addr-string num-bytes
88
89 (define (codegen-print x si env)
90   (codegen-expr x si env) ; x should be a static-string, producing a label
91
92                                         ; make a copy of string address since %rax and %rdi are clobbered
93   (emit "mov %rax, %rbx")
94   
95                                         ; get the length of the null terminated string
96   (emit "mov %rax, %rdi")
97   (emit "xor %al, %al")   ; set %al to 0
98   (emit "mov $-1, %rcx") ; max search length = max int = -1
99   (emit "cld")           ; clear direction flag, search up in memory
100   (emit "repne scasb")   ; scan string, %rcx = -strlen - 1 - 1
101   
102   (emit "not %rcx")      ; -%rcx = strlen + 1
103   (emit "dec %rcx")
104   
105   (emit "movq %rbx, %rsi") ; string addr
106   (emit "movq %rcx, %rdx") ; num bytes
107   (emit "movq $1, %rdi")   ; file handle (stdout)
108   (case target
109     ('darwin (emit "mov $0x2000004, %rax")) ; syscall 4 (write)
110     ('linux  (emit "mov $1, %rax"))) ; syscall 1 (write)
111   (emit "syscall"))
112
113 (define (codegen-let bindings body si env)
114
115                                         ; is this a closure that captures itself?
116                                         ; e.g. (let ([x 3] [f (closure lambda0 (f x))]) (f))
117   (define (self-captive-closure? name expr)
118     (and (eqv? (ast-type expr) 'closure)
119          (memv name (caddr expr))))
120
121
122   ;; (define (emit-scc scc env)
123   ;;   ; acc is a pair of the env and list of touchups
124   ;;   (define (emit-binding acc binding)
125   ;;     (let ([binding-name (car binding)]
126   ;;        [binding-body (cadr binding)]
127
128   ;;        [other-bindings (filter
129   ;;                         (lambda (x) (not (eqv? binding-name x)))
130   ;;                         scc)]
131   ;;        [mutually-recursives
132   ;;         (filter
133   ;;          (lambda (other-binding)
134   ;;            (memv other-binding (references binding-body)))
135   ;;          other-bindings)]
136
137   ;;        [new-touchups (append touchups (cdr acc))])
138
139   ;;                                    ; TODO: assert that the only mutually recursives are closures
140   ;;    (for-each
141   ;;     (lambda (binding)
142   ;;       (when (not (eqv? (ast-type (cadr binding))
143         
144   ;;    (emit "asdf")
145   ;;    (cons new-env new-touchups)
146   ;;    ))
147
148   ;;   (fold-left emit-binding (cons env '()) scc))))
149   
150   (let* ([stack-offsets (map (lambda (name x) ; assoc map of binding name to offset
151                                (cons name (- si (* x wordsize))))
152                              (map car bindings)
153                              (range 0 (length bindings)))]
154          [inner-si (- si (* (length bindings) wordsize))]
155
156          [get-offset (lambda (n) (cdr (assoc n stack-offsets)))]
157          
158          [inner-env
159           (fold-left
160            (lambda (env comps)
161              (let* ([scc-binding-offsets
162                      (fold-left
163                       (lambda (acc name)
164                         (cons (cons name (get-offset name))
165                               acc))
166                       (env-bindings env)
167                       comps)]
168                     [scc-env (make-env (env-data-layouts env) scc-binding-offsets)])
169                (for-each 
170                 (lambda (name)
171                   (let ([expr (cadr (assoc name bindings))])
172                     (emit "## generating ~a with scc-env ~a" name scc-env)
173                     (if (self-captive-closure? name expr)
174                                         ; if self-captive, insert a flag into the environment to let
175                                         ; codegen-closure realise this!
176                         (codegen-expr expr
177                                       inner-si
178                                       (make-env
179                                        (env-data-layouts scc-env)
180                                        (cons (cons name 'self-captive)
181                                              (env-bindings scc-env))))
182                         (codegen-expr expr inner-si scc-env))
183                     (emit "movq %rax, ~a(%rbp)" (get-offset name))))
184                 comps)
185                scc-env))
186            env
187            (reverse (sccs (graph bindings))))])
188     
189     (for-each (lambda (form)
190                 (codegen-expr form inner-si inner-env))
191               body)))
192
193 (define (codegen-var name si env)
194   (let ([binding (assoc name (env-bindings env))])
195     (if (not binding)
196         (error #f (format "Variable ~a is not bound" name))
197         (emit "movq ~a(%rbp), %rax" (cdr binding)))))
198
199 (define cur-lambda 0)
200 (define (fresh-lambda)
201   (set! cur-lambda (+ 1 cur-lambda))
202   (format "_lambda~a" (- cur-lambda 1)))
203
204                                         ; a closure on the heap looks like:
205                                         ; 0    8         16        24
206                                         ; addr var1....  var2....  var3....
207
208 (define (codegen-closure label captured si env)
209   (let* ((heap-offsets (map (lambda (i) (+ 8 (* 8 i)))
210                             (range 0 (length captured))))) ; 4, 12, 20, etc.
211
212     (emit "## creating closure")
213
214     (emit "movq heap_start@GOTPCREL(%rip), %rbx")
215     
216     (emit "movq (%rbx), %rax")          ; %rax = heap addr of closure
217
218
219                                         ; point heap_start to next space
220     (emit "addq $~a, (%rbx)" (+ 8 (* 8 (length captured))))
221
222     (emit "## storing address to lambda")
223                                         ; store the address to the lambda code
224     (emit "movq ~a@GOTPCREL(%rip), %rbx" label)
225     (emit "movq %rbx, 0(%rax)")
226
227     (emit "## storing captives")
228                                         ; store the captured vars
229     (for-each
230      (lambda (var-name heap-offset)
231        (let ([stack-offset (cdr (assoc var-name (env-bindings env)))])
232          (emit "### captive ~a" var-name)
233          (if (eqv? stack-offset 'self-captive)
234                                         ; captive refers to this closure:
235                                         ; move heap addr of this closure to stack! 
236              (emit "movq %rax, ~a(%rax)" heap-offset)
237              (begin
238                (emit "movq ~a(%rbp), %rbx" stack-offset)
239                (emit "movq %rbx, ~a(%rax)" heap-offset)))))
240      captured
241      heap-offsets)))
242
243                                         ; for now we can only call closures
244 (define (codegen-call f args si env)
245   (codegen-expr f si env)
246
247   (emit "## starting call")
248   
249   (emit "movq %rax, ~a(%rbp)" si) ; store address of closure first on stack
250   
251                                         ; codegen the arguments, store them intermediately
252   (for-each
253    (lambda (e i)
254      (begin
255        (emit "## arg no. ~a" (- i 1))
256        (codegen-expr e (- si (* wordsize i)) env)
257                                         ; store intermediate result on stack
258        (emit "movq %rax, ~a(%rbp)" (- si (* wordsize i)))))
259
260    args (range 1 (length args)))
261
262                                         ; now that we have everything we need on the stack,
263                                         ; move them into the param registers
264
265   (emit "## moving args into place")
266   (for-each
267    (lambda (i) (emit "movq ~a(%rbp), ~a"
268                      (- si (* wordsize i))
269                      (param-register i)))
270    (range 1 (length args)))
271
272                                         ; todo: can this be made more efficient
273   (emit "movq ~a(%rbp), %rax" si)       ; load back pointer to closure
274
275   (emit "## moving captives into place")
276   
277                                         ; move captives into first argument
278   (emit "movq %rax, %rbx")
279   (emit "addq $8, %rbx")
280   (emit "movq %rbx, ~a" (param-register 0))
281
282   (emit "## performing call")
283
284   (emit "addq $~a, %rsp" si) ; adjust the stack pointer to account all the stuff we put in the env
285   (emit "callq *(%rax)")                ; call closure function
286   (emit "subq $~a, %rsp" si))
287
288                                         ; LAMBDAS:
289                                         ; 1st param: pointer to captured args
290                                         ; 2nd param: 1st arg
291                                         ; 3rd param: 2nd arg, etc.
292
293 (define (codegen-lambda l)
294   (let* ((label (car l))
295          (stuff (cdr l))
296          (captives (car stuff))
297          (args (cadr stuff))
298          (body (caddr stuff))
299                                         ; params = what actually gets passed
300          (params (append captives args))
301
302          (stack-offsets (map (lambda (i)
303                                (* (- wordsize) (+ 1 i)))
304                              (range 0 (length params))))
305
306          [bindings (map cons params stack-offsets)]
307          [env (make-env '() bindings)])
308     (emit "~a:" label)
309
310     (display "## lambda captives: ")
311     (display captives)
312     (newline)
313     (display "## lambda args: ")
314     (display args)
315     (newline)
316     (display "## lambda body: ")
317     (display body)
318     (newline)
319     
320     (emit "push %rbp") ; preserve caller's base pointer
321     
322     (emit "movq %rsp, %rbp") ; set up our own base pointer
323
324                                         ; load the captured vars onto the stack
325     (for-each
326      (lambda (i)
327        (begin
328          (emit "# loading captive ~a" (list-ref captives i))
329          (emit "movq ~a(~a), %rbx" (* wordsize i) (param-register 0))
330          (emit "movq %rbx, ~a(%rbp)" (* (- wordsize) (+ 1 i)))))
331      (range 0 (length captives)))
332
333                                         ; load the args onto the stack
334     (for-each
335      (lambda (i)
336        (begin
337          (emit "movq ~a, %rbx" (param-register (+ 1 i)))
338          (emit "movq %rbx, ~a(%rbp)"
339                (* (- wordsize)
340                   (+ 1 (length captives) i)))))
341      (range 0 (length args)))
342     
343     (codegen-expr body (* (- wordsize) (+ 1 (length params))) env)
344
345     (emit "pop %rbp") ; restore caller's base pointer
346     (emit "ret")))
347
348 (define cur-label 0)
349 (define (fresh-label)
350   (set! cur-label (+ 1 cur-label))
351   (format "label~a" (- cur-label 1)))
352
353 (define (codegen-if cond then else si env)
354   (codegen-expr cond si env)
355   (emit "cmpq $0, %rax")
356   (let ((exit-label (fresh-label))
357         (else-label (fresh-label)))
358     (emit "je ~a" else-label)
359     (codegen-expr then si env)
360     (emit "jmp ~a" exit-label)
361     (emit "~a:" else-label)
362     (codegen-expr else si env)
363     (emit "~a:" exit-label)))
364
365 (define (data-tor env e)
366   (if (not (list? e)) #f    
367       (assoc (car e) (flat-map data-tors (env-data-layouts env)))))
368
369                                         ; returns the internal offset in bytes of a product within an ADT
370                                         ; given the constructor layout
371                                         ; constructor-layout: (foo (Int Bool))
372 (define (data-product-offset data-layouts type sum index)
373   (let* ([products (cdr (assoc sum (cdr (assoc type data-layouts))))]
374          [to-traverse (list-head products index)])
375     (fold-left
376      (lambda (acc t) (+ acc (type-size data-layouts t)))
377      wordsize ; skip the tag in the first word
378      to-traverse)))
379
380 (define (data-sum-tag data-layouts type sum)
381
382   (define (go acc sums)
383     (when (null? sums) (error #f "data-sum-tag no sum for type" sum type))
384     (if (eqv? sum (car sums))
385         acc
386         (go (+ 1 acc) (cdr sums))))
387   (let* ([type-sums (cdr (assoc type data-layouts))])
388     (go 0 (map car type-sums))))
389
390 (define (codegen-data-tor e si env)
391
392   (define (codegen-destructor tor)
393     (let* ([res (codegen-expr (cadr e) si env)]
394            [info (cadr tor)]
395            [index (caddr info)]
396            [type (car info)]
397            [sum (cadr info)])
398       (when (not (stack-expr? res))
399         (error #f "codegened something that wasn't a stack expression"))
400                                         ;TODO handle stack types
401       (emit "movq ~a(%rbp), %rax"
402             (- si (data-product-offset (env-data-layouts env) type sum index)))))                                     
403
404   (define (codegen-constructor tor)
405     (let* ([info (cadr tor)]
406            [type (car info)]
407            [sum (cadr info)]
408            [constructor (car e)]
409
410            [args (cdr e)]
411
412            [tag (data-sum-tag (env-data-layouts env)
413                               type
414                               sum)]
415            
416            [insert-product
417             (lambda (expr i)
418               (let ([res (codegen-expr expr si env)]
419                     [stack-offset (- si (data-product-offset (env-data-layouts env)
420                                                              type sum
421                                                              i))])
422                 (if (stack-expr? res)
423                     (error #f "todo: handle stack-exprs in stack exprs")
424                     (emit "movq %rax, ~a(%rbp)" stack-offset))))])
425
426                                         ; emit the tag
427       (emit "movq $~a, ~a(%rbp)" tag si)
428       
429       (for-each insert-product args (range 0 (length args)))
430       (type-size (env-data-layouts env) type)))
431   
432   (let* ([tor (data-tor env e)]
433          [constructor (eqv? 'constructor (caddr (cadr tor)))])
434     (if constructor
435         (codegen-constructor tor)
436         (codegen-destructor tor))))
437
438 (define stack-expr? number?)
439
440                                         ; returns a number if result was stored on stack 
441 (define (codegen-expr e si env)
442   (emit "# ~a" e)
443   (case (ast-type e)
444     ('closure (codegen-closure (cadr e) (caddr e) si env))
445     ('app
446      (case (car e)
447        ('+ (codegen-add (cdr e) si env))
448        ('- (codegen-sub (cadr e) (caddr e) si env))
449        ('* (codegen-mul (cadr e) (caddr e) si env))
450        ('! (codegen-not (cadr e) si env))
451        ('= (codegen-eq  (cadr e) (caddr e) si env))
452        ('bool->int (codegen-expr (cadr e) si env))
453        ('print (codegen-print (cadr e) si env))
454        (else
455         (if (data-tor env e)
456             (codegen-data-tor e si env)
457             (codegen-call (car e) (cdr e) si env)))))
458
459                                         ; this is a builtin being passed around as a variable
460                                         ; this should have been converted to a closure!
461     ('builtin (error #f "passing about a builtin!" e))
462
463     ('let (codegen-let (let-bindings e)
464                        (let-body e)
465                        si
466                        env))
467
468     ('var (codegen-var e si env))
469
470     ('if (codegen-if (cadr e) (caddr e) (cadddr e) si env))
471     
472     ('bool-literal (emit "movq $~a, %rax" (if e 1 0)))
473     ('int-literal (emit "movq $~a, %rax" e))
474     
475     ('static-string (emit "movq ~a@GOTPCREL(%rip), %rax"
476                           (cadr e)))
477
478     ('stack (codegen-expr (caddr e) si env))
479
480     (else (error #f "don't know how to codegen this"))))
481
482                                         ; takes in a expr annotated with types and returns a type-less AST
483                                         ; with stack values wrapped
484 (define (annotate-stack-values data-layout ann-e)
485   (define (stack-type? type)
486     (assoc type data-layout))
487   (define (strip e)
488     (ast-traverse strip (ann-expr e)))
489   (let* ([e (ann-expr ann-e)]
490          [type (ann-type ann-e)])
491     (if (stack-type? type)
492         `(stack ,type ,(ast-traverse strip e))
493         (ast-traverse (lambda (x)
494                         (annotate-stack-values data-layout x))
495                       e))))
496
497 (define (free-vars prog)
498   (define bound '())
499   (define (collect e)
500     (case (ast-type e)
501       ('builtin '()) ; do nothing
502       ('var (if (memv e bound) '() (list e)))
503       ('lambda
504           (begin
505             (set! bound (append (lambda-args e) bound))
506             (collect (lambda-body e))))
507
508       ('app (flat-map collect e))
509       ('if (flat-map collect (cdr e)))
510       ('let
511           (let ([bind-fvs (flat-map (lambda (a)
512                                       (begin
513                                         (set! bound (cons (car a) bound))
514                                         (collect (cdr a))))
515                                     (let-bindings e))])
516             (append bind-fvs (flat-map collect (let-body e)))))
517       (else '())))
518   (collect prog))
519
520                                         ; ((lambda (x) (+ x y)) 42) => ((closure lambda1 (y)) 42)
521                                         ;                              [(lambda1 . ((y), (x), (+ x y))]
522                                         ; for builtins, this generates a closure if it is used
523                                         ; outside of an immediate app
524                                         ; but only one closure for each builtin
525
526 (define (extract-lambdas program)
527   (define lambdas '())
528   (define (add-lambda e)
529     (let* ((label (fresh-lambda))
530            (args (lambda-args e))
531            (captured (free-vars e))
532            (body (extract (lambda-body e)))
533            (new-lambda (cons label (list captured args body))))
534       (set! lambdas (cons new-lambda lambdas))
535       `(closure ,label ,captured))) ; todo: should we string->symbol?
536
537   (define (find-builtin-lambda e)
538     (let [(l (assq (builtin-name e) lambdas))]
539       (if l `(closure ,(car l) ,(caadr l)) #f)))
540
541   (define (builtin-name e)
542     (case e
543       ('+ "_add")
544       ('- "_sub")
545       ('* "_mul")
546       ('! "_not")
547       ('= "_eq")
548       ('bool->int "_bool2int")
549       ('print "_print")
550       (else (error #f "don't know this builtin"))))
551   (define (builtin-args e)
552     (case e
553       ('+ '(x y))
554       ('- '(x y))
555       ('* '(x y))
556       ('! '(x))
557       ('= '(x y))
558       ('bool->int '(x))
559       ('print '(x))
560       (else (error #f "don't know this builtin"))))
561
562   (define (add-builtin-lambda e)
563     (let* [(label (builtin-name e))
564            (captured '())
565            (args (builtin-args e))
566            (body `(,e ,@args))
567            (new-lambda (cons label (list captured args body)))]
568       (set! lambdas (cons new-lambda lambdas))
569       `(closure ,label ,captured)))
570   
571   (define (extract e)
572     (case (ast-type e)
573       ('lambda (add-lambda e))
574       ('let `(let ,(map (lambda (b) `(,(car b) ,@(extract (cdr b)))) (let-bindings e))
575                ,@(map extract (let-body e))))
576       ('app (append
577                                         ; if a builtin is used as a function, don't generate lambda
578              (if (eqv? 'builtin (ast-type (car e)))
579                  (list (car e))
580                  (list (extract (car e))))
581              (map extract (cdr e))))
582       
583       ('builtin
584        (if (find-builtin-lambda e)
585            (find-builtin-lambda e)
586            (add-builtin-lambda e)))
587
588       
589       (else (ast-traverse extract e))))
590   (let ((transformed (extract program)))
591     (cons lambdas transformed)))
592
593 (define (extract-strings program)
594   (let ((cur-string 0)
595         (strings '())) ; assoc list of labels -> string
596     (define (fresh-string)
597       (set! cur-string (+ cur-string 1))
598       (format "string~a" (- cur-string 1)))
599     (define (extract e)
600       (case (ast-type e)
601         ('string-literal
602          (let ((label (fresh-string)))
603            (set! strings (cons (cons label e) strings))
604            `(static-string ,label)))
605         (else (ast-traverse extract e))))
606     (let ((transformed (extract program)))
607       (cons strings transformed))))
608
609 (define (emit-string-data s)
610   (emit "~a:" (car s))
611   (emit "\t.string \"~a\"" (cdr s)))
612
613                                         ; 24(%rbp) mem arg 1
614                                         ; 16(%rbp) mem arg 0          prev frame
615                                         ; -----------------------
616                                         ;  8(%rbp) return address     cur frame
617                                         ;  0(%rbp) prev %rbp
618                                         ; -8(%rbp) do what you want
619                                         ;  ...     do what you want
620                                         ;  0(%rsp) do what you want
621
622 (define (param-register n)
623   (case n
624     (0 "%rdi")
625     (1 "%rsi")
626     (2 "%rdx")
627     (3 "%rcx")
628     (4 "%r8")
629     (5 "%r9")
630     (else (error #f "need to test out the below"))
631     (else (format "~a(%rsp)" (- n 6)))))
632
633 (define (initialize-heap)
634   (let ((mmap
635          (case target
636            ('darwin "0x20000c5")
637            ('linux "9"))))
638                                         ; allocate some heap memory
639     (emit "mov $~a, %rax" mmap) ; mmap
640     (emit "xor %rdi, %rdi")  ; addr = null
641     (emit "movq $1024, %rsi")   ; length = 1kb
642     (emit "movq $0x3, %rdx") ; prot = read | write = 0x2 | 0x1
643                                         ;    flags = anonymous | private
644     (case target
645       ('darwin (emit "movq $0x1002, %r10")) ; anon = 0x1000, priv = 0x02
646       ('linux (emit "movq $0x22, %r10")))   ; anon = 0x20,   priv = 0x02
647     (emit "movq $-1, %r8") ; fd = -1
648     (emit "xor %r9, %r9") ; offset = 0
649     (emit "syscall")
650                                         ; %rax now contains pointer to the start of the heap
651                                         ; keep track of it
652
653     (emit "movq heap_start@GOTPCREL(%rip), %rsi")
654     (emit "movq %rax, (%rsi)")))
655
656 (define (codegen program)
657   (set! cur-label 0)
658   (set! cur-lambda 0)
659   (let* ([data-layouts (program-data-layouts program)]
660
661          [pattern-matched (expand-pattern-matches program)]
662          [type-annotated (annotate-types pattern-matched)]
663          [stack-annotated (annotate-stack-values data-layouts
664                                                  type-annotated)]
665          
666          (strings-res (extract-strings stack-annotated))
667          (strings (car strings-res))
668          (lambdas-res (extract-lambdas (cdr strings-res)))
669          (lambdas (car lambdas-res))
670          (xform-prog (cdr lambdas-res)))
671
672     (emit "\t.global _start")
673     (emit "\t.text")
674                                         ;    (emit ".p2align 4,,15") is this needed?
675
676     (for-each codegen-lambda lambdas)
677
678     (emit "_start:")
679
680     (initialize-heap)
681
682     (emit "movq %rsp, %rbp")            ; set up the base pointer
683     
684     (codegen-expr xform-prog (- wordsize) (make-env data-layouts '()))
685
686                                         ; exit syscall
687     (emit "mov %rax, %rdi")
688     (case target
689       ('darwin (emit "movq $0x2000001, %rax"))
690       ('linux (emit "mov $60, %rax")))
691     (emit "syscall")
692
693     (emit ".data")
694
695     (emit "heap_start:")
696     (emit "\t.quad 0")
697
698     (for-each emit-string-data strings)))
699
700 (define (compile-to-binary program output t)
701   (set! target t)
702   (when (not (eq? (typecheck program) 'Int)) (error #f "not an Int"))
703   (let ([tmp-path "/tmp/a.s"])
704     (when (file-exists? tmp-path) (delete-file tmp-path))
705     (with-output-to-file tmp-path
706       (lambda () (codegen program)))
707
708     (case target
709       ('darwin
710        (system "as /tmp/a.s -o /tmp/a.o")
711        (system (format "ld /tmp/a.o -e _start -macosx_version_min 10.14 -static -o ~a" output)))
712       ('linux
713        (system "as /tmp/a.s -o /tmp/a.o")
714        (system (format "ld /tmp/a.o -o ~a" output))))))
715
716 ; NOTES
717 ; syscalls in linux and darwin use the following arguments for syscall instruction:
718 ; %rax = syscall #
719 ; %rdi = 1st arg
720 ; %rsi = 2nd arg
721 ; %rdx = 3rd arg
722 ; %r10 = 4th arg
723 ; %r8  = 5th arg
724 ; %r9  = 6th arg
725
726 ; on darwin, unix/posix syscalls are offset by 0x2000000 (syscall classes)
727 ; https://opensource.apple.com/source/xnu/xnu-2782.20.48/bsd/kern/syscalls.master
728 ; documentation for most syscalls: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/sys