-
Notifications
You must be signed in to change notification settings - Fork 0
/
c-backend.scm
1551 lines (1430 loc) · 52.8 KB
/
c-backend.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; c-backend.scm - C-generating backend for the CHICKEN compiler
;
; Copyright (c) 2008-2022, The CHICKEN Team
; Copyright (c) 2000-2007, Felix L. Winkelmann
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
; conditions are met:
;
; Redistributions of source code must retain the above copyright notice, this list of conditions and the following
; disclaimer.
; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
; disclaimer in the documentation and/or other materials provided with the distribution.
; Neither the name of the author nor the names of its contributors may be used to endorse or promote
; products derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
(declare
(unit c-backend)
(uses data-structures extras c-platform compiler internal support))
(module chicken.compiler.c-backend
(generate-code
;; For "foreign" (aka chicken-ffi-syntax):
foreign-type-declaration)
(import scheme
chicken.base
chicken.bitwise
chicken.fixnum
chicken.flonum
chicken.foreign
chicken.format
chicken.internal
chicken.keyword
chicken.platform
chicken.sort
chicken.string
chicken.time
chicken.compiler.core
chicken.compiler.c-platform
chicken.compiler.support)
(include "mini-srfi-1.scm")
;;; Write atoms to output-port:
(define output #f)
(define (gen . data)
(for-each
(lambda (x)
(if (eq? #t x)
(newline output)
(display x output) ) )
data) )
(define (gen-list lst)
(for-each
(lambda (x) (display x output))
(intersperse lst #\space) ) )
;; Hacky procedures to make certain names more suitable for use in C.
(define (backslashify s) (string-translate* (->string s) '(("\\" . "\\\\"))))
(define (uncommentify s) (string-translate* (->string s) '(("*/" . "*_/"))))
(define (c-identifier s) (string->c-identifier (->string s)))
;; Generate a sorted alist out of a symbol table
(define (table->sorted-alist t)
(let ((alist '()))
(hash-table-for-each
(lambda (id ll)
(set! alist
(cons (cons id ll) alist)))
t)
(sort! alist (lambda (p1 p2) (string<? (symbol->string (car p1))
(symbol->string (car p2)))))))
;;; Generate target code:
(define (generate-code literals lliterals lambda-table out source-file user-supplied-options dynamic db dbg-info-table)
(let ((lambda-table* (table->sorted-alist lambda-table)) ;; sort the symbol table to make the compiler output deterministic.
(non-av-proc #f))
;; Don't truncate floating-point precision!
(flonum-print-precision (+ flonum-maximum-decimal-exponent 1))
;; Some helper procedures
(define (find-lambda id)
(or (hash-table-ref lambda-table id)
(bomb "can't find lambda" id) ) )
;; Compile a single expression
(define (expression node temps ll)
(define (expr n i)
(let ((subs (node-subexpressions n))
(params (node-parameters n)) )
(case (node-class n)
((##core#immediate)
(case (first params)
((bool) (gen (if (second params) "C_SCHEME_TRUE" "C_SCHEME_FALSE")))
((char) (gen "C_make_character(" (char->integer (second params)) #\)))
((nil) (gen "C_SCHEME_END_OF_LIST"))
((fix) (gen "C_fix(" (second params) #\)))
((eof) (gen "C_SCHEME_END_OF_FILE"))
(else (bomb "bad immediate")) ) )
((##core#literal)
(let ((lit (first params)))
(if (vector? lit)
(gen "((C_word)li" (vector-ref lit 0) ")")
(gen "lf[" (first params) #\])) ) )
((##core#float)
(let ((n (first params)))
(gen "(double)")
(cond ((nan? n) (gen "NAN"))
((infinite? n)
(when (negative? n) (gen #\-))
(gen "INFINITY"))
(else (gen n)))))
((if)
(gen #t "if(C_truep(")
(expr (car subs) i)
(gen ")){")
(expr (cadr subs) i)
(gen #\} #t "else{")
(expr (caddr subs) i)
(gen #\}) )
((##core#proc)
(gen "(C_word)" (first params)) )
((##core#bind)
(let loop ((bs subs) (i i) (count (first params)))
(cond [(> count 0)
(gen #t #\t i #\=)
(expr (car bs) i)
(gen #\;)
(loop (cdr bs) (add1 i) (sub1 count)) ]
[else (expr (car bs) i)] ) ) )
((##core#let_float)
(let ((fi (first params)))
(gen #t #\f fi #\=)
(expr (first subs) i)
(gen #\;)
(expr (second subs) i)))
((##core#float-variable)
(gen #\f (first params)))
((##core#unbox_float)
(gen "C_flonum_magnitude(")
(expr (first subs) i)
(gen ")"))
((##core#box_float)
(gen "C_flonum(&a,")
(expr (first subs) i)
(gen ")"))
((##core#ref)
(gen "((C_word*)")
(expr (car subs) i)
(gen ")[" (+ (first params) 1) #\]) )
((##core#rest-car)
(let* ((n (lambda-literal-argument-count ll))
(depth (second params))
(have-av? (not (or (lambda-literal-customizable ll)
(lambda-literal-direct ll)))))
(if have-av?
(gen "C_get_rest_arg(c," (+ depth n) ",av," n ",t0)")
(gen "C_u_i_list_ref(t" (sub1 n) "," depth ")"))))
((##core#rest-null?)
(let* ((n (lambda-literal-argument-count ll))
(depth (second params))
(have-av? (not (or (lambda-literal-customizable ll)
(lambda-literal-direct ll)))))
(if have-av?
(gen "C_rest_nullp(c," (+ depth n) ")")
(gen "C_mk_bool(C_unfix(C_i_length(t" (sub1 n) ")) >= " depth ")"))))
((##core#rest-length)
(let* ((n (lambda-literal-argument-count ll))
(depth (second params))
(have-av? (not (or (lambda-literal-customizable ll)
(lambda-literal-direct ll)))))
(if have-av?
(gen "C_fix(c - " (+ depth n) ")")
(gen "C_u_i_length(t" (sub1 n) ")"))))
((##core#unbox)
(gen "((C_word*)")
(expr (car subs) i)
(gen ")[1]") )
((##core#update_i)
(gen "C_set_block_item(")
(expr (car subs) i)
(gen #\, (first params) #\,)
(expr (cadr subs) i)
(gen #\)) )
((##core#update)
(gen "C_mutate(((C_word *)")
(expr (car subs) i)
(gen ")+" (+ (first params) 1) ",")
(expr (cadr subs) i)
(gen #\)) )
((##core#updatebox_i)
(gen "C_set_block_item(")
(expr (car subs) i)
(gen ",0,")
(expr (cadr subs) i)
(gen #\)) )
((##core#updatebox)
(gen "C_mutate(((C_word *)")
(expr (car subs) i)
(gen ")+1,")
(expr (cadr subs) i)
(gen #\)) )
((##core#closure)
(let ((n (first params)))
(gen "(*a=C_CLOSURE_TYPE|" n #\,)
(for-each
(lambda (x j)
(gen "a[" j "]=")
(expr x i)
(gen #\,) )
subs (list-tabulate n add1))
(gen "tmp=(C_word)a,a+=" (add1 n) ",tmp)") ) )
((##core#box)
(gen "(*a=C_VECTOR_TYPE|1,a[1]=")
(expr (car subs) i)
(gen ",tmp=(C_word)a,a+=2,tmp)") )
((##core#local) (gen #\t (first params)))
((##core#setlocal)
(gen #\t (first params) #\=)
(expr (car subs) i) )
((##core#global)
(let ((index (first params))
(safe (second params))
(block (third params)) )
(cond [block
(if safe
(gen "lf[" index "]")
(gen "C_retrieve2(lf[" index "],C_text("
(c-ify-string (##sys#symbol->string
(fourth params))) "))"))]
[safe (gen "*((C_word*)lf[" index "]+1)")]
[else (gen "C_fast_retrieve(lf[" index "])")] ) ) )
((##core#setglobal)
(let ((index (first params))
(block (second params))
(var (third params)))
(if block
(gen "C_mutate(&lf[" index "]")
(gen "C_mutate((C_word*)lf[" index "]+1"))
(gen " /* (set! " (uncommentify (##sys#symbol->string var)) " ...) */,")
(expr (car subs) i)
(gen #\)) ) )
((##core#setglobal_i)
(let ((index (first params))
(block (second params))
(var (third params)) )
(cond [block
(gen "lf[" index "] /* "
(uncommentify (##sys#symbol->string var)) " */ =")
(expr (car subs) i)
(gen #\;) ]
[else
(gen "C_set_block_item(lf[" index "] /* "
(uncommentify (##sys#symbol->string var)) " */,0,")
(expr (car subs) i)
(gen #\)) ] ) ) )
((##core#undefined) (gen "C_SCHEME_UNDEFINED"))
((##core#call)
(let* ((args (cdr subs))
(n (length args))
(nc i)
(nf (add1 n))
(dbi (first params))
(safe-to-call (second params))
(p2 (pair? (cddr params)))
(name (and p2 (third params)))
(name-str (source-info->string name))
(call-id (and p2 (pair? (cdddr params)) (fourth params)))
(customizable (and call-id (fifth params)))
(empty-closure (and customizable (zero? (lambda-literal-closure-size (find-lambda call-id)))))
(fn (car subs)) )
(when name
(if emit-trace-info
(gen #t "C_trace(C_text(\"" (backslashify name-str) "\"));")
(gen #t "/* " (uncommentify name-str) " */"))
(when (and emit-debug-info dbi)
(gen #t "C_debugger(&(C_debug_info[" dbi "]),"
(if non-av-proc "0,NULL" "c,av") ");")))
(cond ((eq? '##core#proc (node-class fn))
(gen #\{)
(push-args args i "0")
(let ([fpars (node-parameters fn)])
(gen #t (first fpars) #\( nf ",av2);}") ))
(call-id
(cond ((and (eq? call-id (lambda-literal-id ll))
(lambda-literal-looping ll) )
(let* ((temps (lambda-literal-temporaries ll))
(ts (list-tabulate n (lambda (i) (+ temps nf i)))))
(for-each
(lambda (arg tr)
(gen #t #\t tr #\=)
(expr arg i)
(gen #\;) )
args ts)
(for-each
(lambda (from to) (gen #t #\t to "=t" from #\;))
ts (list-tabulate n add1))
(unless customizable (gen #t "c=" nf #\;))
(gen #t "goto loop;") ) )
(else
(unless empty-closure
(gen #t #\t nc #\=)
(expr fn i)
(gen #\;) )
(cond (customizable
(gen #t call-id #\()
(unless empty-closure (gen #\t nc #\,))
(expr-args args i)
(gen ");") )
(else
(gen #\{)
(push-args args i (and (not empty-closure) (string-append "t" (number->string nc))))
(gen #t call-id #\()
(unless customizable (gen nf #\,))
(gen "av2);}") ) ) )))
((and (eq? '##core#global (node-class fn))
(not unsafe)
(not no-procedure-checks)
(not safe-to-call))
(let* ((gparams (node-parameters fn))
(index (first gparams))
(safe (second gparams))
(block (third gparams))
(carg #f))
(gen #t "{C_proc tp=(C_proc)")
(cond (no-global-procedure-checks
(set! carg
(if block
(string-append "lf[" (number->string index) "]")
(string-append "*((C_word*)lf[" (number->string index) "]+1)")))
(gen "(void*)(*((C_word*)(" carg ")+1))"))
(block
(set! carg (string-append "lf[" (number->string index) "]"))
(if safe
(gen "C_fast_retrieve_proc(" carg ")")
(gen "C_retrieve2_symbol_proc(" carg ",C_text("
(c-ify-string (##sys#symbol->string (fourth gparams))) "))")))
(safe
(set! carg
(string-append "*((C_word*)lf[" (number->string index) "]+1)"))
(gen "C_fast_retrieve_proc(" carg ")"))
(else
(set! carg
(string-append "*((C_word*)lf[" (number->string index) "]+1)"))
(gen "C_fast_retrieve_symbol_proc(lf[" index "])") ))
(gen #\;)
(push-args args i carg)
(gen #t "tp(" nf ",av2);}")))
(else
(gen #t #\t nc #\=)
(expr fn i)
(gen ";{")
(push-args args i (string-append "t" (number->string nc)))
(gen #t "((C_proc)")
(if (or unsafe no-procedure-checks safe-to-call)
(gen "(void*)(*((C_word*)t" nc "+1))")
(gen "C_fast_retrieve_proc(t" nc ")") )
(gen ")(" nf ",av2);}") ) ) ) )
((##core#recurse)
(let* ([n (length subs)]
[nf (add1 n)]
[tailcall (first params)]
[call-id (second params)]
[empty-closure (zero? (lambda-literal-closure-size ll))] )
(cond (tailcall
(let* ((temps (lambda-literal-temporaries ll))
(ts (list-tabulate n (cut + temps nf <>))))
(for-each
(lambda (arg tr)
(gen #t #\t tr #\=)
(expr arg i)
(gen #\;) )
subs ts)
(for-each
(lambda (from to) (gen #t #\t to "=t" from #\;))
ts (list-tabulate n add1))
(gen #t "goto loop;") ) )
(else
(gen call-id #\()
(unless empty-closure (gen "t0,"))
(expr-args subs i)
(gen #\)) ) ) ) )
((##core#direct_call)
(let* ((args (cdr subs))
(n (length args))
(nf (add1 n))
(dbi (first params))
;; (safe-to-call (second params))
(name (third params))
(name-str (source-info->string name))
(call-id (fourth params))
(demand (fifth params))
(allocating (not (zero? demand)))
(empty-closure (zero? (lambda-literal-closure-size (find-lambda call-id))))
(fn (car subs)) )
(gen #\()
(when name
(if emit-trace-info
(gen #t "C_trace(\"" (backslashify name-str) "\"),")
(gen #t "/* " (uncommentify name-str) " */"))
(when (and emit-debug-info dbi)
(gen #t "C_debugger(&(C_debug_info[" dbi "]),"
(if non-av-proc "0,NULL" "c,av") "),")))
(gen #t " " call-id #\()
(when allocating
(gen "C_a_i(&a," demand #\))
(when (or (not empty-closure) (pair? args)) (gen #\,)) )
(unless empty-closure
(expr fn i)
(when (pair? args) (gen #\,)) )
(when (pair? args) (expr-args args i))
(gen #\)) ; function call
(gen #t #\)))) ; complete expression
((##core#provide)
(gen "C_a_i_provide(&a,1,lf[" (first params) "])"))
((##core#callunit)
;; The code generated here does not use the extra temporary needed for standard calls, so we have
;; one unused variable:
(let* ((n (length subs))
(nf (+ n 1)) )
(gen #\{)
(push-args subs i "C_SCHEME_UNDEFINED")
(gen #t "C_" (toplevel (first params)) "(" nf ",av2);}")))
((##core#return)
(gen #t "return(")
(expr (first subs) i)
(gen ");") )
((##core#inline)
(gen (first params) #\()
(expr-args subs i)
(gen #\)) )
((##core#debug-event)
(gen "C_debugger(&(C_debug_info[" (first params) "]),"
(if non-av-proc "0,NULL" "c,av") ")"))
((##core#inline_allocate)
(gen (first params) "(&a," (length subs))
(if (pair? subs)
(begin
(gen #\,)
(expr-args subs i) ) )
(gen #\)) )
((##core#inline_ref)
(gen (foreign-result-conversion (second params) "a") (first params) #\)) )
((##core#inline_update)
(let ([t (second params)])
(gen #\( (first params) "=(" (foreign-type-declaration t "") #\) (foreign-argument-conversion t))
(expr (first subs) i)
(gen "),C_SCHEME_UNDEFINED)") ) )
((##core#inline_loc_ref)
(let ([t (first params)])
(gen (foreign-result-conversion t "a") "*((" (foreign-type-declaration t "") "*)C_data_pointer(")
(expr (first subs) i)
(gen ")))") ) )
((##core#inline_loc_update)
(let ([t (first params)])
(gen "((*(" (foreign-type-declaration t "") "*)C_data_pointer(")
(expr (first subs) i)
(gen "))=" (foreign-argument-conversion t))
(expr (second subs) i)
(gen "),C_SCHEME_UNDEFINED)") ) )
((##core#switch)
(gen #t "switch(")
(expr (first subs) i)
(gen "){")
(do ([j (first params) (sub1 j)]
[ps (cdr subs) (cddr ps)] )
((zero? j)
(gen #t "default:")
(expr (car ps) i)
(gen #\}) )
(gen #t "case ")
(expr (car ps) i)
(gen #\:)
(expr (cadr ps) i) ) )
((##core#cond)
(gen "(C_truep(")
(expr (first subs) i)
(gen ")?")
(expr (second subs) i)
(gen #\:)
(expr (third subs) i)
(gen #\)) )
(else (bomb "bad form" (node-class n))) ) ) )
(define (expr-args args i)
(let loop ((xs args))
(unless (null? xs)
(unless (eq? xs args) (gen #\,))
(expr (car xs) i)
(loop (cdr xs)))))
(define (contains-restop? args)
(let loop ((args args))
(if (null? args)
#f
(let ((node (car args)))
;; Only rest-car accesses av
(or (eq? (node-class node) '##core#rest-car)
(contains-restop? (node-subexpressions node))
(loop (cdr args)))))))
(define (push-args args i selfarg)
(let* ((n (length args))
(avl (+ n (if selfarg 1 0)))
(caller-has-av? (not (or (lambda-literal-customizable ll)
(lambda-literal-direct ll))))
(caller-argcount (lambda-literal-argument-count ll))
(caller-rest-mode (lambda-literal-rest-argument-mode ll)))
;; Try to re-use argvector from current function if it is
;; large enough. push-args gets used only for functions in
;; CPS context, so callee never returns to current function.
;; And even so, av[] is already copied into temporaries.
(cond
((or (not caller-has-av?) ; Argvec missing or
(and (< caller-argcount avl) ; known to be too small?
(eq? caller-rest-mode 'none))
(contains-restop? args)) ; Restops work on original av
(gen #t "C_word av2[" avl "];"))
((>= caller-argcount avl) ; Argvec known to be re-usable?
(gen #t "C_word *av2=av;")) ; Re-use our own argvector
(else ; Need to determine dynamically. This is slower.
(gen #t "C_word *av2;")
(gen #t "if(c >= " avl ") {")
(gen #t " av2=av;") ; Re-use our own argvector
(gen #t "} else {")
(gen #t " av2=C_alloc(" avl ");")
(gen #t "}")))
(when selfarg (gen #t "av2[0]=" selfarg ";"))
(do ((j (if selfarg 1 0) (add1 j))
(args args (cdr args)))
((null? args))
(gen #t "av2[" j "]=")
(expr (car args) i)
(gen ";"))))
(expr node temps) )
(define (header)
(gen "/* Generated from " source-file " by the CHICKEN compiler" #t
" http://www.call-cc.org" #t
(string-intersperse
(map (cut string-append " " <> "\n")
(string-split (chicken-version #t) "\n") )
"")
" command line: ")
(gen-list user-supplied-options)
(unless (not unit-name)
(gen #t " unit: " unit-name))
(unless (null? used-units)
(gen #t " uses: ")
(gen-list used-units))
(gen #t "*/")
(gen #t "#include \"" target-include-file "\"")
(when external-protos-first
(generate-foreign-callback-stub-prototypes foreign-callback-stubs) )
(when (pair? foreign-declarations)
(gen #t)
(for-each (lambda (decl) (gen #t decl)) foreign-declarations) )
(unless external-protos-first
(generate-foreign-callback-stub-prototypes foreign-callback-stubs) ) )
(define (trailer)
(gen #t #t "/*" #t
(uncommentify
(get-output-string
collected-debugging-output))
"*/"
#t "/* end of file */" #t))
(define (declarations)
(let ((n (length literals)))
(gen #t #t "static C_PTABLE_ENTRY *create_ptable(void);")
(for-each
(lambda (uu)
(gen #t "C_noret_decl(C_" uu ")"
#t "C_externimport void C_ccall C_" uu "(C_word c,C_word *av) C_noret;"))
(map toplevel used-units))
(unless (zero? n)
(gen #t #t "static C_TLS C_word lf[" n "];") )
(gen #t "static double C_possibly_force_alignment;")
(do ((i 0 (add1 i))
(llits lliterals (cdr llits)))
((null? llits))
(let* ((ll (##sys#lambda-info->string (car llits)))
(llen (string-length ll)))
(gen #t "static C_char C_TLS li" i "[] C_aligned={C_lihdr("
(arithmetic-shift llen -16) #\,
(bitwise-and #xff (arithmetic-shift llen -8)) #\,
(bitwise-and #xff llen)
#\))
(do ((n 0 (add1 n)))
((>= n llen))
(gen #\, (char->integer (string-ref ll n))) )
(do ((n (- (bitwise-and #xfffff8 (+ llen 7)) llen) (sub1 n))) ; fill up with zeros to align following entry
((zero? n))
(gen ",0") )
(gen "};")))))
(define (prototypes)
(gen #t)
(for-each
(lambda (p)
(let* ((id (car p))
(ll (cdr p))
(n (lambda-literal-argument-count ll))
(customizable (lambda-literal-customizable ll))
(empty-closure (and customizable (zero? (lambda-literal-closure-size ll))))
(varlist (intersperse (make-variable-list (if empty-closure (sub1 n) n) "t") #\,))
(direct (lambda-literal-direct ll))
(allocated (lambda-literal-allocated ll)) )
(gen #t)
(cond ((not (eq? 'toplevel id))
(gen "C_noret_decl(" id ")" #t)
(gen "static ")
(gen (if direct "C_word " "void "))
(if customizable
(gen "C_fcall ")
(gen "C_ccall ") )
(gen id) )
(else
(let ((uname (toplevel unit-name)))
(gen "C_noret_decl(C_" uname ")" #t) ;XXX what's this for?
(gen "C_externexport void C_ccall ")
(gen "C_" uname) ) ) )
(gen #\()
(unless customizable (gen "C_word c,"))
(when (and direct (not (zero? allocated)))
(gen "C_word *a")
(when (pair? varlist) (gen #\,)) )
(if (or customizable direct)
(apply gen varlist)
(gen "C_word *av"))
(gen #\))
(unless direct (gen " C_noret"))
(gen #\;) ))
lambda-table*) )
(define (trampolines)
(let ([ns '()]
[nsr '()]
[nsrv '()] )
(define (restore n)
(do ((i 0 (add1 i))
(j (sub1 n) (sub1 j)))
((>= i n))
(gen #t "C_word t" i "=av[" j "];")))
(for-each
(lambda (p)
(let* ([id (car p)]
[ll (cdr p)]
[argc (lambda-literal-argument-count ll)]
[customizable (lambda-literal-customizable ll)]
[empty-closure (and customizable (zero? (lambda-literal-closure-size ll)))] )
(when empty-closure (set! argc (sub1 argc)))
(when (and (not (lambda-literal-direct ll)) customizable)
(gen #t #t "C_noret_decl(tr" id ")"
#t "static void C_ccall tr" id "(C_word c,C_word *av) C_noret;")
(gen #t "static void C_ccall tr" id "(C_word c,C_word *av){")
(restore argc)
(gen #t id #\()
(let ([al (make-argument-list argc "t")])
(apply gen (intersperse al #\,)) )
(gen ");}") )))
lambda-table*)))
(define (literal-frame)
(do ([i 0 (add1 i)]
[lits literals (cdr lits)] )
((null? lits))
(gen-lit (car lits) (sprintf "lf[~s]" i)) ) )
(define (bad-literal lit)
(bomb "type of literal not supported" lit) )
(define (literal-size lit)
(cond ((immediate? lit) 0)
((big-fixnum? lit) 2) ; immediate if fixnum, bignum see below
((string? lit) 0) ; statically allocated
((bignum? lit) 2) ; internal vector statically allocated
((flonum? lit) words-per-flonum)
((symbol? lit) 7) ; size of symbol, and possibly a bucket
((keyword? lit) 7) ; size of keyword (symbol), and possibly a bucket
((pair? lit) (+ 3 (literal-size (car lit)) (literal-size (cdr lit))))
((vector? lit)
(+ 1 (vector-length lit)
(foldl + 0 (map literal-size (vector->list lit)))))
((block-variable-literal? lit) 0) ; excluded from generated code
((##sys#immediate? lit) (bad-literal lit))
((##core#inline "C_lambdainfop" lit) 0) ; statically allocated
((##sys#bytevector? lit) (+ 2 (bytes->words (##sys#size lit))) ) ; drops "permanent" property!
((##sys#generic-structure? lit)
(let ([n (##sys#size lit)])
(let loop ([i 0] [s (+ 2 n)])
(if (>= i n)
s
(loop (add1 i) (+ s (literal-size (##sys#slot lit i)))) ) ) ) )
;; We could access rat/cplx slots directly, but let's not.
((ratnum? lit) (+ (##sys#size lit)
(literal-size (numerator lit))
(literal-size (denominator lit))))
((cplxnum? lit) (+ (##sys#size lit)
(literal-size (real-part lit))
(literal-size (imag-part lit))))
(else (bad-literal lit))) )
(define (gen-lit lit to)
;; we do simple immediate literals directly to avoid a function call:
(cond ((and (fixnum? lit) (not (big-fixnum? lit)))
(gen #t to "=C_fix(" lit ");") )
((block-variable-literal? lit))
((eq? lit (void))
(gen #t to "=C_SCHEME_UNDEFINED;") )
((boolean? lit)
(gen #t to #\= (if lit "C_SCHEME_TRUE" "C_SCHEME_FALSE") #\;) )
((char? lit)
(gen #t to "=C_make_character(" (char->integer lit) ");") )
((or (keyword? lit) (symbol? lit)) ; handled slightly specially (see C_h_intern_in)
(let* ((str (##sys#slot lit 1))
(cstr (c-ify-string str))
(len (##sys#size str))
(intern (if (keyword? lit)
"C_h_intern_kw"
"C_h_intern")))
(gen #t to "=")
(gen intern "(&" to #\, len ", C_text(" cstr "));")))
((null? lit)
(gen #t to "=C_SCHEME_END_OF_LIST;") )
((and (not (##sys#immediate? lit)) ; nop
(##core#inline "C_lambdainfop" lit)))
((or (fixnum? lit) (not (##sys#immediate? lit)))
(gen #t to "=C_decode_literal(C_heaptop,C_text(")
(gen-string-constant (encode-literal lit))
(gen "));"))
(else (bad-literal lit))))
(define (gen-string-constant str)
(let* ([len (##sys#size str)]
[ns (fx/ len 80)]
[srest (modulo len 80)] )
(do ([i ns (sub1 i)]
[offset 0 (+ offset 80)] )
((zero? i)
(when (or (zero? len) (not (zero? srest)))
(gen (c-ify-string (string-like-substring str offset len))) ) )
(gen (c-ify-string (string-like-substring str offset (+ offset 80))) #t) ) ) )
(define (string-like-substring s start end)
(let* ([len (- end start)]
[s2 (make-string len)] )
(##sys#copy-bytes s s2 start 0 len)
s2) )
(define (procedures)
(for-each
(lambda (p)
(let* ((id (car p))
(ll (cdr p))
(n (lambda-literal-argument-count ll))
(rname (real-name id db))
(demand (lambda-literal-allocated ll))
(max-av (apply max 0 (lambda-literal-callee-signatures ll)))
(rest (lambda-literal-rest-argument ll))
(customizable (lambda-literal-customizable ll))
(empty-closure (and customizable (zero? (lambda-literal-closure-size ll))))
(nec (- n (if empty-closure 1 0)))
(vlist0 (make-variable-list n "t"))
(alist0 (make-argument-list n "t"))
(varlist (intersperse (if empty-closure (cdr vlist0) vlist0) #\,))
(arglist (intersperse (if empty-closure (cdr alist0) alist0) #\,))
(external (lambda-literal-external ll))
(looping (lambda-literal-looping ll))
(direct (lambda-literal-direct ll))
(rest-mode (lambda-literal-rest-argument-mode ll))
(temps (lambda-literal-temporaries ll))
(ftemps (lambda-literal-float-temporaries ll))
(topname (toplevel unit-name)))
(when empty-closure (debugging 'o "dropping unused closure argument" id))
(gen #t #t)
(gen "/* " (cleanup rname) " */" #t)
(cond [(not (eq? 'toplevel id))
(gen "static ")
(gen (if direct "C_word " "void "))
(if customizable
(gen "C_fcall ")
(gen "C_ccall ") )
(gen id) ]
[else
(gen "static C_TLS int toplevel_initialized=0;")
(unless unit-name
(gen #t "C_main_entry_point") )
(gen #t #t "void C_ccall C_" topname) ] )
(gen #\()
(unless customizable (gen "C_word c,"))
(when (and direct (not (zero? demand)))
(gen "C_word *a")
(when (pair? varlist) (gen #\,)) )
(if (or customizable direct)
(apply gen varlist)
(gen "C_word *av"))
(gen "){")
(when (eq? rest-mode 'none) (set! rest #f))
(gen #t "C_word tmp;")
(unless (or customizable direct)
(do ((i 0 (add1 i)))
((>= i n))
(gen #t "C_word t" i "=av[" i "];")))
(if rest
(gen #t "C_word t" n #\;) ; To hold rest-list if demand is met
(begin
(do ([i n (add1 i)]
[j (+ temps (if looping (sub1 n) 0)) (sub1 j)] )
((zero? j))
(gen #t "C_word t" i #\;))
(for-each
(lambda (i)
(gen #t "double f" i #\;))
ftemps)))
(cond ((eq? 'toplevel id)
(let ([ldemand (foldl (lambda (n lit) (+ n (literal-size lit))) 0 literals)]
[llen (length literals)] )
(gen #t "C_word *a;"
#t "if(toplevel_initialized) {C_kontinue(t1,C_SCHEME_UNDEFINED);}"
#t "else C_toplevel_entry(C_text(\"" (or unit-name topname) "\"));")
(when emit-debug-info
(gen #t "C_register_debug_info(C_debug_info);"))
(when disable-stack-overflow-checking
(gen #t "C_disable_overflow_check=1;") )
(unless unit-name
(when target-heap-size
(gen #t "C_set_or_change_heap_size(" target-heap-size ",1);"
#t "C_heap_size_is_fixed=1;"))
(when target-stack-size
(gen #t "C_resize_stack(" target-stack-size ");") ) )
(gen #t "C_check_nursery_minimum(C_calculate_demand(" demand ",c," max-av "));"
#t "if(C_unlikely(!C_demand(C_calculate_demand(" demand ",c," max-av ")))){"
#t "C_save_and_reclaim((void*)C_" topname ",c,av);}"
#t "toplevel_initialized=1;"
#t "if(C_unlikely(!C_demand_2(" ldemand "))){"
#t "C_save(t1);"
#t "C_rereclaim2(" ldemand "*sizeof(C_word),1);"
#t "t1=C_restore;}"
#t "a=C_alloc(" demand ");")
(when (not (zero? llen))
(gen #t "C_initialize_lf(lf," llen ");")
(literal-frame)
(gen #t "C_register_lf2(lf," llen ",create_ptable());"))
(gen #\{)))
(rest
(gen #t "C_word *a;")
(when (and (not unsafe) (not no-argc-checks) (> n 2) (not empty-closure))
(gen #t "if(c<" n ") C_bad_min_argc_2(c," n ",t0);") )
(when insert-timer-checks (gen #t "C_check_for_interrupt;"))
(gen #t "if(C_unlikely(!C_demand(C_calculate_demand((c-" n ")*C_SIZEOF_PAIR +" demand ",c," max-av ")))){"))
(else
(unless direct (gen #t "C_word *a;"))
(when (and direct (not unsafe) (not disable-stack-overflow-checking))
(gen #t "C_stack_overflow_check;"))
(when looping (gen #t "loop:"))
(when (and external (not unsafe) (not no-argc-checks) (not customizable))
;; (not customizable) implies empty-closure
(if (eq? rest-mode 'none)
(when (> n 2) (gen #t "if(c<" n ") C_bad_min_argc_2(c," n ",t0);"))
(gen #t "if(c!=" n ") C_bad_argc_2(c," n ",t0);") ) )
(cond ((not direct)
;; The interrupt handler may fill the stack, so we only
;; check for an interrupt when the procedure is restartable
(when insert-timer-checks (gen #t "C_check_for_interrupt;"))
(gen #t "if(C_unlikely(!C_demand(C_calculate_demand("
demand
(if customizable ",0," ",c,")
max-av ")))){"))
(else
(gen #\{)))))
(cond ((and (not (eq? 'toplevel id)) (not direct))
(when (and looping (not customizable))
;; Loop will update t_n copy of av[n]; refresh av.
(do ((i 0 (add1 i)))
((>= i n))
(gen #t "av[" i "]=t" i ";")))
(cond (rest
(gen #t "C_save_and_reclaim((void*)" id ",c,av);}"
#t "a=C_alloc((c-" n ")*C_SIZEOF_PAIR+" demand ");")
(gen #t "t" n "=C_build_rest(&a,c," n ",av);")
(do ((i (+ n 1) (+ i 1))
(j temps (- j 1)))
((zero? j))
(gen #t "C_word t" i #\;)))
(else
(cond ((and customizable (> nec 0))
(gen #t "C_save_and_reclaim_args((void *)tr" id #\, nec #\,)
(apply gen arglist)
(gen ");}"))
(else
(gen #t "C_save_and_reclaim((void *)" id ",c,av);}")))
(when (> demand 0)
(gen #t "a=C_alloc(" demand ");")))))
(else (gen #\})))
(set! non-av-proc customizable)
(expression
(lambda-literal-body ll)
(if rest
(add1 n) ; One temporary is needed to hold the rest-list
n)
ll)
(gen #\}) ) )
lambda-table*) )
(debugging 'p "code generation phase...")
(set! output out)
(header)
(declarations)
(generate-external-variables external-variables)
(generate-foreign-stubs foreign-lambda-stubs db)
(prototypes)
(generate-foreign-callback-stubs foreign-callback-stubs db)
(trampolines)
(when emit-debug-info
(emit-debug-table dbg-info-table))
(procedures)
(emit-procedure-table lambda-table* source-file)
(trailer) ) )
;;; Emit global tables for debug-info
(define (emit-debug-table dbg-info-table)
(gen #t #t "static C_DEBUG_INFO C_debug_info[]={")
(for-each
(lambda (info)
(gen #t "{" (second info) ",0,")
(for-each
(lambda (x)
(if (not x)
(gen "NULL,")