-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcfg.scm
1393 lines (1283 loc) · 47.3 KB
/
cfg.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
;;; generation of control flow graph
;; list of all conditional branching generic instructions
(define conditional-instrs ;; TODO add as we add specialized instructions
'(x==y x!=y x<y x>y branch-if-carry))
;; generic instructions that end up generating machine instructions that affect
;; the carry flag
(define carry-affecting-instrs
'(add addc sub subb rlcf rrcf))
;; special variables whose contents are located in the FSR registers
(define fsr-variables '(SIXPIC_FSR0 SIXPIC_FSR1 SIXPIC_FSR2))
(define-type cfg
bbs
next-label-num)
(define (new-cfg)
(make-cfg '() 0))
(define-type bb
label-num
label-name ; if the block had a label
label
rev-instrs
unprintable:
preds
succs
live-before) ; bitset
(define (bb-name bb)
(asm-label-id (bb-label bb)))
(define-type instr
extender: define-type-of-instr
(live-before unprintable:) ; bitset
(live-after unprintable:) ; bitset
(hash unprintable:)
id
src1
src2
dst)
(define-type-of-instr call-instr
unprintable:
def-proc)
(define-type-of-instr return-instr
unprintable:
def-proc)
(define (new-instr id src1 src2 dst)
(make-instr #f #f #f id src1 src2 dst))
(define (new-call-instr def-proc)
(make-call-instr '() '() #f 'call #f #f #f def-proc))
(define (new-return-instr def-proc)
(make-return-instr '() '() #f 'return #f #f #f def-proc))
(define (add-bb cfg proc id) ;; TODO maybe have the name in the label for named-bbs ? would help debugging
(let* ((label-num (cfg-next-label-num cfg))
(bb (make-bb label-num #f #f '() '() '() #f)))
(bb-label-set!
bb
(asm-make-label
(string->symbol
(string-append "$"
(number->string label-num)
"$"
(if proc (symbol->string proc) "")
"$"
(if proc (number->string id) "")))))
(cfg-bbs-set! cfg (cons bb (cfg-bbs cfg)))
(cfg-next-label-num-set! cfg (+ 1 (cfg-next-label-num cfg)))
bb))
(define (add-instr bb instr)
(let ((rev-instrs (bb-rev-instrs bb)))
(bb-rev-instrs-set! bb (cons instr rev-instrs))))
(define (add-succ bb succ)
(bb-succs-set! bb (cons succ (bb-succs bb)))
(bb-preds-set! succ (cons bb (bb-preds succ))))
;; for statistics
(define virtual-instructions-counts (make-table))
(define concrete-instructions-counts (make-table))
(define byte-cell-src1-counts (make-table))
(define byte-cell-src2-counts (make-table))
(define byte-cell-dst-counts (make-table))
(define byte-cell-all-counts (make-table))
(define (generate-cfg ast)
(define cfg (new-cfg))
(define bb #f) ; current bb
(define (in x) (set! bb x))
(define current-def-proc #f)
(define (current-def-proc-id)
(if current-def-proc
(def-id current-def-proc)
#f))
(define current-def-proc-bb-id 0)
(define (new-bb)
(let ((bb (add-bb cfg (current-def-proc-id) current-def-proc-bb-id)))
(set! current-def-proc-bb-id (+ current-def-proc-bb-id 1))
bb))
(define (emit instr)
;; keep statistics
(let ((id (instr-id instr)))
(table-set! virtual-instructions-counts id
(+ (table-ref virtual-instructions-counts id 0) 1)))
(let ((src1 (instr-src1 instr))) ;; TODO have a macro for that
(if (byte-cell? src1)
(let ((src1 (byte-cell-name src1))) ;; TODO also include the id, in the case of multiple vars with the same name, or maybe the bb (though it is not defined everywhere
(table-set! byte-cell-src1-counts src1
(+ (table-ref byte-cell-src1-counts src1 0) 1))
(table-set! byte-cell-all-counts src1
(+ (table-ref byte-cell-all-counts src1 0) 1)))))
(let ((src2 (instr-src2 instr)))
(if (byte-cell? src2)
(let ((src2 (byte-cell-name src2)))
(table-set! byte-cell-src2-counts src2
(+ (table-ref byte-cell-src2-counts src2 0) 1))
(table-set! byte-cell-all-counts src2
(+ (table-ref byte-cell-all-counts src2 0) 1)))))
(let ((dst (instr-dst instr)))
(if (byte-cell? dst)
(let ((dst (byte-cell-name dst)))
(table-set! byte-cell-dst-counts dst
(+ (table-ref byte-cell-dst-counts dst 0) 1))
(table-set! byte-cell-all-counts dst
(+ (table-ref byte-cell-all-counts dst 0) 1)))))
(add-instr bb instr))
(define break-stack '())
(define continue-stack '())
(define delayed-post-incdec '())
(define (push-break x) (set! break-stack (cons x break-stack)))
(define (pop-break) (set! break-stack (cdr break-stack)))
(define (push-continue x) (set! continue-stack (cons x continue-stack)))
(define (pop-continue) (set! continue-stack (cdr continue-stack)))
(define (push-delayed-post-incdec ast)
(set! delayed-post-incdec (cons ast delayed-post-incdec))
;; moves the original value to a new location (so it won't be modified)
;; and returns that location to the original expression
(let ((x (subast1 ast)))
(if (not (ref? x))
(error "assignment target must be a variable")
(let* ((def-var (ref-def-var x))
(result (alloc-value (def-variable-type def-var)
(current-def-proc-id)
#f (bb-name bb))))
(move-value (def-variable-value def-var) result)
result))))
;; TODO instead of carrying types around, use the length instead, or even better, just pass the value-bytes, and calculate the length as needed
(define (extend value type)
;; literals must be extended with literal 0s, while variables must be
;; extended with byte cells
(let* ((bytes (value-bytes value))
(lit? (byte-lit? (car bytes))))
(let loop ((rev-bytes (reverse bytes))
(n (max 0 (- (type->bytes type) (length bytes)))))
(if (= n 0)
(new-value (reverse rev-bytes))
(loop (cons (new-byte-lit 0) ;; TODO used to extend with empty byte cells when it expanded a variable. caused weird bugs.
rev-bytes)
(- n 1))))))
(define (program ast)
(let loop ((asts (ast-subasts ast)))
(if (not (null? asts))
(let ((ast (car asts)))
(if (null? (cdr asts))
(let ((value (expression ast)))
(return-with-no-new-bb value))
(begin
(toplevel ast)
(loop (cdr asts))))))))
(define (toplevel ast)
(cond ((def-variable? ast)
(def-variable ast))
((def-procedure? ast)
(def-procedure ast))
(else
(statement ast))))
(define (def-variable ast) ;; TODO set the fun for each byte-cell
(let ((subasts (ast-subasts ast)))
(if (not (null? subasts)) ; if needed, set the variable
(let ((value (expression (subast1 ast))))
(let ((ext-value (extend value (def-variable-type ast))))
(move-value value (def-variable-value ast)))))))
;; resolve the C gotos by setting the appropriate successor to their bb
(define (resolve-all-gotos start table)
(let loop ((start start)
(visited (new-empty-set)))
(if (not (set-member? visited start)) ; not visited
(begin (for-each
(lambda (x)
(if (and (eq? (instr-id x) 'goto)
(instr-dst x)) ; unresolved label
(let ((target (assoc (instr-dst x) table))) ;; TODO use a set, but not urgent, not a bottleneck
(if target
(begin (add-succ start (cdr target))
(instr-dst-set! x #f))
(error "invalid goto target" (instr-dst x))))))
(bb-rev-instrs start))
(for-each (lambda (x)
(set-add! visited start)
(loop x visited))
(bb-succs start))))))
(define (def-procedure ast) ;; TODO set the fun for the parameters, and maybe also return value
(set! current-def-proc-bb-id 0)
(set! current-def-proc ast)
(let ((old-bb bb)
(entry (new-bb)))
(def-procedure-entry-set! ast entry)
(in entry)
(for-each statement (ast-subasts ast))
(return-with-no-new-bb ast)
(set! current-def-proc #f)
(resolve-all-gotos entry (list-named-bbs entry))
(in old-bb)))
;; returns a list of all named bbs in the successor-tree of a given bb
(define (list-named-bbs start)
(let ((visited (new-empty-set)))
(let loop ((start start) ;; TODO not really a loop, it's tree recursion
(named '()))
(if (set-member? visited start)
named
(let ((succs
(apply append
(map (lambda (bb)
(set-add! visited start)
(loop bb named))
(bb-succs start)))))
(if (bb-label-name start)
(cons (cons (bb-label-name start) start) succs)
succs))))))
(define (statement ast)
(cond ((def-variable? ast) (def-variable ast))
((block? ast) (block ast))
((return? ast) (return ast))
((if? ast) (if (null? (cddr (ast-subasts ast)))
(if1 ast)
(if2 ast)))
((while? ast) (while ast))
((do-while? ast) (do-while ast))
((for? ast) (for ast))
((switch? ast) (switch ast))
((break? ast) (break ast))
((continue? ast) (continue ast))
((goto? ast) (goto ast))
(else (expression ast))))
(define (block ast)
(if (block-name ast) ; named block ?
(begin (let ((new (new-bb)))
(gen-goto new)
(in new))
(bb-label-name-set! bb (block-name ast))))
(for-each statement (ast-subasts ast)))
(define (move from to)
(emit (new-instr 'move from #f to)))
(define (move-value from to)
(let loop ((from (value-bytes from))
(to (value-bytes to)))
(cond ((null? to)) ; done, we truncate the rest
((null? from) ; promote the value by padding
(move (new-byte-lit 0) (car to))
(loop from (cdr to)))
(else
(move (car from) (car to))
(loop (cdr from) (cdr to))))))
(define (return-with-no-new-bb def-proc)
(emit (new-return-instr def-proc)))
(define (return ast)
(if (null? (ast-subasts ast))
(return-with-no-new-bb current-def-proc)
(let ((value (expression (subast1 ast))))
(let ((ext-value (extend value (def-procedure-type current-def-proc))))
(move-value value (def-procedure-value current-def-proc))
(return-with-no-new-bb current-def-proc))))
(in (new-bb)))
(define (if1 ast)
(let* ((bb-join (new-bb))
(bb-then (new-bb)))
(test-expression (subast1 ast) bb-then bb-join)
(in bb-then)
(statement (subast2 ast))
(gen-goto bb-join)
(in bb-join)))
(define (if2 ast)
(let* ((bb-join (new-bb))
(bb-then (new-bb))
(bb-else (new-bb)))
(test-expression (subast1 ast) bb-then bb-else)
(in bb-then)
(statement (subast2 ast))
(gen-goto bb-join)
(in bb-else)
(statement (subast3 ast))
(gen-goto bb-join)
(in bb-join)))
(define (while ast)
(let* ((bb-cont (new-bb))
(bb-exit (new-bb))
(bb-body (new-bb)))
(push-continue bb-cont)
(push-break bb-exit)
(gen-goto bb-cont)
(in bb-cont)
(test-expression (subast1 ast) bb-body bb-exit)
(in bb-body)
(statement (subast2 ast))
(gen-goto bb-cont)
(in bb-exit)
(pop-continue)
(pop-break)))
(define (do-while ast)
(let* ((bb-body (new-bb))
(bb-cont (new-bb))
(bb-exit (new-bb)))
(push-continue bb-cont)
(push-break bb-exit)
(gen-goto bb-body)
(in bb-body)
(statement (subast1 ast))
(gen-goto bb-cont)
(in bb-cont)
(test-expression (subast2 ast) bb-body bb-exit)
(in bb-exit)
(pop-continue)
(pop-break)))
(define (for ast)
(let* ((bb-loop (new-bb))
(bb-body (new-bb))
(bb-cont (new-bb))
(bb-exit (new-bb)))
(statement (subast1 ast))
(gen-goto bb-loop)
(push-continue bb-cont)
(push-break bb-exit)
(in bb-loop)
(test-expression (subast2 ast) bb-body bb-exit)
(in bb-body)
(statement (subast4 ast))
(gen-goto bb-cont)
(in bb-cont)
(statement (subast3 ast))
(gen-goto bb-loop)
(in bb-exit)
(pop-continue)
(pop-break)))
;; switchs with branch tables
;; since offsets are calculated using one byte, switches are limited to
;; 60 cases or so (slightly below 64)
(define (switch ast)
(let* ((var (subast1 ast))
(entry-bb bb)
(exit-bb (new-bb)))
(push-break exit-bb)
(let loop ((asts (cdr (ast-subasts ast))) ; car is the tested variable
(bbs '()) ; first bb of each case
(end-bbs '()) ; last bb of each case
(cases '())) ; case labels
(if (not (null? asts))
(let ((x (car asts))
(case-bb (new-bb)))
(in case-bb)
(block x)
(if (or (null? (bb-succs case-bb))
(not (bb-label-name (car (bb-succs case-bb)))))
;; the first block inside the body of a switch might not
;; have a label, in which case it ill be skipped
;; to have a valid CFG, it must still contain an instruction
(begin (gen-goto exit-bb)
(loop (cdr asts) bbs end-bbs cases))
(loop (cdr asts)
(cons case-bb bbs)
(cons bb end-bbs)
;; blocks create their own bb, which contains the case label
(cons (bb-label-name (car (bb-succs case-bb)))
cases))))
(let ((bbs (reverse bbs))
(end-bbs (reverse end-bbs))
(cases (reverse cases))
(l (length bbs)))
;; add the case names to the bb names
(for-each ;; TODO do it for all named bbs, not just switch (but, since the name is on the successor, might be lost)
(lambda (bb case)
(vector-set!
(bb-label (car (bb-succs bb))) 2
(string->symbol
(string-append (symbol->string (bb-name bb))
"$"
(if (symbol? case)
;; default
(symbol->string case)
;; (case n)
(string-append
(symbol->string (car case))
(number->string (cadr case))))))))
bbs
cases)
;; handle fall-throughs
(for-each
(lambda (i)
(let ((case-bb (list-ref end-bbs i)))
(if (null? (bb-succs case-bb))
;; fall through
(begin (in case-bb)
(gen-goto (if (= i (- l 1)) ; last bb
exit-bb
(list-ref bbs (+ i 1))))))))
(iota l))
(let* ((default (memq 'default cases)) ;; TODO if default, since we can't know the domain of possible values (at least, not with enough precision for it to be interesting), revert to naive switch
;; cases are lists (case n) and we want the numbers
(cases (map cadr (filter list? cases)))
(case-max (foldl max 0 cases))
(case-min (foldl min case-max cases))
(n-entries (+ (- case-max case-min) 1)))
(if default (error "default is not supported with switch"))
(in entry-bb)
(bb-succs-set! bb
(map (lambda (i)
(cond ((pos-in-list (+ i case-min) cases)
=> (lambda (j) (list-ref bbs j)))
;; no label, jump to the exit TODO would jump to default, eventually
(else exit-bb)))
(iota n-entries)))
;; the branch-table virtual instruction takes the byte to check
;; to choose the branch
(emit
(new-instr
'branch-table
;; the cases now start from 0, so we might have to
;; adjust the checked variable
(car (value-bytes
(expression
(if (= case-min 0)
var
(let* ((op (operation? '(six.x-y)))
(ast (new-oper
(list var (new-literal 'uint8
case-min))
#f
op)))
(expr-type-set! ast ((op-type-rule op) ast))
ast)))))
;; working space to calculate addresses
(new-byte-cell (current-def-proc-id) #f (bb-name bb))
#f))))))
(in exit-bb)
(pop-break)))
;; ;; naive switch with if cascade ;; TODO revert to that if there's a case we can't handle with branch tables
;; (define (switch ast)
;; (let* ((var (subast1 ast))
;; (case-list #f)
;; (default #f)
;; (decision-bb bb)
;; (exit-bb (new-bb))
;; (prev-bb decision-bb))
;; (push-break exit-bb)
;; (for-each (lambda (x) ; generate each case
;; (in (new-bb)) ; this bb will be given the name of the case
;; (add-succ decision-bb bb)
;; ;; if the previous case didn't end in a break, fall through
;; (if (null? (bb-succs prev-bb))
;; (let ((curr bb))
;; (in prev-bb)
;; (gen-goto curr)
;; (in curr)))
;; (statement x)
;; (set! prev-bb bb))
;; (cdr (ast-subasts ast)))
;; (if (null? (bb-succs prev-bb)) ; if the last case didn't end in a break, fall through to the exit
;; (gen-goto exit-bb))
;; (bb-succs-set! decision-bb (reverse (bb-succs decision-bb))) ; preserving the order is important in the absence of break
;; (set! case-list (list-named-bbs decision-bb))
;; (set! default (filter (lambda (x) (eq? (car x) 'default))
;; (list-named-bbs decision-bb)))
;; (set! case-list (filter (lambda (x) (and (list? (car x))
;; (eq? (caar x) 'case)))
;; case-list))
;; (bb-succs-set! decision-bb '()) ; now that we have the list of cases we don't need the successors anymore
;; (let loop ((case-list case-list)
;; (decision-bb decision-bb))
;; (in decision-bb)
;; (if (not (null? case-list))
;; (let* ((next-bb (new-bb))
;; (curr-case (car case-list))
;; (curr-case-id (cadar curr-case))
;; (curr-case-bb (cdr curr-case)))
;; (emit (new-instr 'x==y
;; (car (value-bytes (expression var)))
;; (new-byte-lit curr-case-id) #f))
;; (add-succ bb next-bb) ; if false, keep looking
;; (add-succ bb curr-case-bb) ; if true, go to the case
;; (loop (cdr case-list)
;; next-bb))
;; (gen-goto (if (not (null? default))
;; (cdar default)
;; exit-bb))))
;; (in exit-bb)
;; (pop-break)))
(define (break ast)
(gen-goto (car break-stack)))
(define (continue ast)
(gen-goto (car continue-stack)))
;; generates a goto with a target label. once the current function definition
;; is over, all these labels are resolved. therefore, we don't have any gotos
;; that jump from a function to another
(define (goto ast)
(emit (new-instr 'goto #f #f (subast1 ast))))
(define (gen-goto dest)
(if (null? (bb-succs bb))
;; since this is an unconditional goto, we want only one
(begin (add-succ bb dest)
(emit (new-instr 'goto #f #f #f)))))
(define (test-expression ast bb-true bb-false)
(define (test-byte id byte1 byte2 bb-true bb-false)
(define (test-lit id x y)
((case id
((x==y) =)
((x<y) <)
((x>y) >)
(else (error "invalid test")))
x
y))
(cond ((and (byte-lit? byte1) (byte-lit? byte2))
(if (test-lit id (byte-lit-val byte1) (byte-lit-val byte2))
(gen-goto bb-true)
(gen-goto bb-false)))
((byte-lit? byte2)
;; since we cons each new successor at the front, true has to be
;; added last
(add-succ bb bb-false)
(add-succ bb bb-true)
(emit (new-instr id byte1 byte2 #f)))
((byte-lit? byte1)
(let ((id
(case id
((x==y) 'x==y)
((x<y) 'x>y)
((x>y) 'x<y)
(else (error "invalid test")))))
(add-succ bb bb-false)
(add-succ bb bb-true)
(emit (new-instr id byte2 byte1 #f))))
(else
(add-succ bb bb-false)
(add-succ bb bb-true)
(emit (new-instr id byte1 byte2 #f)))))
(define (test-value id value1 value2 bb-true bb-false)
(let loop ((bytes1 (value-bytes value1)) ; lsb first
(bytes2 (value-bytes value2))
(padded1 '())
(padded2 '()))
(if (not (and (null? bytes1) (null? bytes2)))
;; note: won't work with signed types, as the padding is done
;; with 0s only
(loop (if (null? bytes1) bytes1 (cdr bytes1))
(if (null? bytes2) bytes2 (cdr bytes2))
(cons (if (null? bytes1) (new-byte-lit 0) (car bytes1))
padded1)
(cons (if (null? bytes2) (new-byte-lit 0) (car bytes2))
padded2))
;; now so the test itself, using the padded values
(let ((padded1 (reverse padded1))
(padded2 (reverse padded2)))
(case id
((x==y) ; unlike < and >, must check all bytes, so is simpler
(let loop2 ((bytes1 padded1) ;; TODO ior the xors, but increases PICOBIT's size
(bytes2 padded2))
(let ((byte1 (car bytes1))
(byte2 (car bytes2)))
(if (null? (cdr bytes1))
(test-byte 'x==y byte1 byte2 bb-true bb-false)
(let ((bb-true2 (new-bb)))
(test-byte 'x==y byte1 byte2 bb-true2 bb-false)
(in bb-true2)
(loop2 (cdr bytes1) (cdr bytes2)))))))
(else ; < and >
(if (= (length padded1) 1)
(test-byte id (car padded1) (car padded2)
bb-true bb-false)
;; more than one byte, we subtract, then see if we had
;; to borrow
(let ((scratch (new-byte-cell
(current-def-proc-id)
"cmp-scratch" (bb-name bb))))
;; our values might contain literal bytes and sub and
;; subb can't have literals in their first argument,
;; allocate it somewhere if needed
(if (and (foldl (lambda (acc new)
(or acc (byte-lit? new)))
#f padded2)
(eq? id 'x>y))
(let ((tmp (alloc-value
(bytes->type (length padded2))
(current-def-proc-id)
#f (bb-name bb))))
(move-value (new-value padded2) tmp)
(set! padded2 (value-bytes tmp))))
(if (and (foldl (lambda (acc new) ;; TODO abstract both cases
(or acc (byte-lit? new)))
#f padded1)
(eq? id 'x<y))
(let ((tmp (alloc-value
(bytes->type (length padded1))
(current-def-proc-id)
#f (bb-name bb))))
(move-value (new-value padded1) tmp)
(set! padded1 (value-bytes tmp))))
(let loop ((bytes1 padded1)
(bytes2 padded2)
(borrow? #f))
(if (not (null? bytes1))
(let ((b1 (car bytes1))
(b2 (car bytes2)))
(case id
((x<y)
(emit (new-instr
(if borrow? 'subb 'sub)
b1 b2 scratch)))
((x>y)
(emit (new-instr
(if borrow? 'subb 'sub)
b2 b1 scratch))))
(loop (cdr bytes1) (cdr bytes2) #t))))
(add-succ bb bb-false)
(add-succ bb bb-true)
(emit (new-instr 'branch-if-carry scratch #f #f))))))))))
(define (test-relation id x y bb-true bb-false)
(cond ((and (literal? x) (not (literal? y)))
;; literals must be in the last argument for code generation
;; flip the relation if needed
(test-relation (case id
((x==y x!=y) id) ; commutative, no change
((x<y) 'x>y)
((x>y) 'x<y)
((x<=y) 'x>=y)
((x>=y) 'x<=y)
(else (error "relation error")))
y
x
bb-true
bb-false))
((assq id '((x!=y . x==y) (x<=y . x>y) (x>=y . x<y)))
;; flip the destination blocks to have a simpler comparison
=>
(lambda (z) (test-relation (cdr z) x y bb-false bb-true)))
(else
;; normal case
;; ' ;; TODO use these special cases, but fall back on the current implementation for default
;; (case id
;; ((x==y)
;; (cond ((and (literal? y) (= (literal-val y) 0))
;; (test-zero x bb-true bb-false))
;; ((literal? y)
;; (test-eq-lit x (literal-val y) bb-true bb-false))
;; (else
;; (error "unhandled case"))))
;; ((x<y)
;; (cond ((and (literal? y) (= (literal-val y) 0))
;; (test-negative x bb-true bb-false))
;; (else
;; (error "unhandled case"))))
;; ((x>y)
;; (cond ((and (literal? y) (= (literal-val y) 0))
;; (test-positive x bb-true bb-false))
;; (else
;; (error "unhandled case"))))
;; (else
;; (error "unexpected operator")))
(let* ((value1 (expression x))
(value2 (expression y)))
(test-value id value1 value2 bb-true bb-false))
)))
(define (test-zero ast bb-true bb-false)
(define (default)
(let ((type (expr-type ast))
(value (expression ast)))
;; since nonzero is true, we must swap the destinations to use ==
(test-value 'x==y value (int->value 0 type) bb-false bb-true)))
(cond ((oper? ast)
(let* ((op (oper-op ast))
(id (op-id op)))
(case id
((!x)
(test-zero (subast1 ast) bb-false bb-true))
((x&&y)
(let ((bb-true2 (new-bb)))
(test-zero (subast1 ast) bb-true2 bb-false)
(in bb-true2)
(test-zero (subast2 ast) bb-true bb-false)))
((|x\|\|y|)
(let ((bb-false2 (new-bb)))
(test-zero (subast1 ast) bb-true bb-false2)
(in bb-false2)
(test-zero (subast2 ast) bb-true bb-false)))
((x==y x!=y x<y x>y x<=y x>=y)
(test-relation id
(subast1 ast)
(subast2 ast)
bb-true
bb-false))
(else (default)))))
(else (default))))
(test-zero ast bb-true bb-false))
;; checks if an expression has already been computed in the current procedure
;; TODO maybe stock all the available expressions not in the def-procedure, but in each node ? as variables are mutated, or functions called, we remove from it ? calls could really harm us, since to be conservative, all calls can be considered to mutate all globals
;; TODO if we end up doing dataflow analysis for cse, also use it for dead-code elimination, if possible
(define (computed-expression? ast) ;; TODO to distinguish between global and local, look at the def-proc-id, if #f, it's global
;; TODO reject if it has side effects (++, --) or calls (or extend the analyis to calls ?), a complete mutability analysis would probably be needed for every variable in the expression... checking only in the procedure won't work, since a called function might change a global that's inside the expression in the time between 2 of its uses. maybe SSA (single static assignment) would help ? ALSO REJECT IF IT READS FROM MEMORY (since we can't really know if what we read has not changed. Or maybe consider the memory as a global for this ?)
;; TODO when we see calls and assignments, remove from the set of expressions what is not valid anymore (lhs for assignments, globals for calls)
(and current-def-proc
(table-ref
(def-procedure-computed-expressions current-def-proc) ast #f)))
(define (expression ast)
(let ((result
(or #;
(computed-expression? ast) ;; TODO breaks something in register allocation, possibly due to the ++ and -- ?
(cond ((literal? ast) (literal ast))
((ref? ast) (ref ast))
((oper? ast) (oper ast))
((call? ast) (call ast))
(else (error "unexpected ast" ast))))))
(if current-def-proc
(table-set! (def-procedure-computed-expressions current-def-proc)
ast result)) ; cache the result
(do-delayed-post-incdec)
result))
(define (literal ast)
(let ((val (literal-val ast)))
(int->value val (expr-type ast))))
(define (ref ast)
(let* ((def-var (ref-def-var ast))
(value (def-variable-value def-var)))
value))
(define (add-sub id value1 value2 result)
(let loop ((bytes1 (value-bytes value1)) ; car is lsb
(bytes2 (value-bytes value2))
(bytes3 (value-bytes result))
(ignore-carry-borrow? #t))
(if (not (null? bytes3))
;; if we would add or subtract 0 and not use the carry, just move
;; the value
(let ((b1 (car bytes1)) (b2 (car bytes2)) (b3 (car bytes3)))
(emit (new-instr
(if ignore-carry-borrow?
(case id ((x+y) 'add) ((x-y) 'sub))
(case id ((x+y) 'addc) ((x-y) 'subb)))
b1 b2 b3))
(loop (cdr bytes1) (cdr bytes2) (cdr bytes3) #f))
result)))
(define (mul value-x value-y type result)
(let* ((bytes-x (value-bytes value-x))
(bytes-y (value-bytes value-y))
;; to determine the length of the operands, we ignore the padding
(lx (length (filter (lambda (x) (not (and (byte-lit? x)
(= (byte-lit-val x) 0))))
bytes-x)))
(ly (length (filter (lambda (x) (not (and (byte-lit? x)
(= (byte-lit-val x) 0))))
bytes-y))))
;; if this a multiplication by 2 or 4, we use additions instead
;; at this point, only y (or both x and y) can contain a literal
(if (and (= ly 1)
(byte-lit? (car bytes-y))
(let ((v (byte-lit-val (car bytes-y))))
(or (= v 2) (= v 4))))
(case (byte-lit-val (car bytes-y))
((2) (add-sub 'x+y value-x value-x result)) ; simple addition
((4) (let ((tmp (alloc-value (bytes->type
(length (value-bytes result)))
(current-def-proc-id)
#f (bb-name bb))))
(add-sub 'x+y value-x value-x tmp)
(add-sub 'x+y tmp tmp result))))
;; if not, we have to do it the long way
(begin
;; finds the appropriate multiplication routine (depending on the
;; length of each argument) and turns the multiplication into a
;; call to the routine
;; the arguments must be the asts of the 2 arguments (x and y) and
;; the type of the returned value, since these are what are
;; expected by the call function
;; to avoid code duplication (i.e. having a routine for 8 by 16
;; multplication and one for 16 by 8), the longest operand goes first
(if (> ly lx)
(let ((tmp1 y)
(tmp2 ly))
(set! y x)
(set! x tmp1)
(set! ly lx)
(set! lx tmp2)))
(routine-call
(string->symbol ; mul8_8, mul8_16, etc
;; for now, only unsigned multiplications are supported
(string-append "__mul"
(number->string (* lx 8)) "_"
(number->string (* ly 8))))
(list value-x value-y)
type)))))
(define (mod x y result)
(let* ((bytes1 (value-bytes x))
(bytes2 (value-bytes y))
(bytes3 (value-bytes result))
(y0 (car bytes2)))
;; if y is a literal and a power of 2, we can do a bitwise and
(if (and (byte-lit? y0)
(let ((x (/ (log (value->int y)) (log 2))))
(= (floor x) x)))
;; bitwise and with y - 1
(let ((tmp (alloc-value (bytes->type (length bytes2))
(current-def-proc-id)
#f (bb-name bb))))
(move-value (int->value (- (value->int y) 1)
(bytes->type (length bytes2)))
tmp)
(bitwise 'x&y x tmp result))
;; TODO for the general case, try to optimise the case where division and modulo are used together, since they are calculated together
(error "modulo is only supported for powers of 2"))
result))
(define (shift id value-x value-y type result)
(let ((bytes1 (value-bytes value-x))
(bytes2 (value-bytes value-y))
(bytes3 (value-bytes result)))
;; if the second argument is a literal and a multiple of 8, we can simply
;; move the bytes around
(let ((y0 (car bytes2)))
(if (and (byte-lit? y0) (= (modulo (byte-lit-val y0) 8) 0))
;; uses only the first byte, but shifting by 255 should be enough
(let ((n (/ (byte-lit-val y0) 8))
(l (length bytes1))) ; same length for x and result
(let loop ((i 0)
(x bytes1))
(if (< i l)
(case id
((x<<y)
(move (if (< i n)
(new-byte-lit 0) ; padding
(car x))
(list-ref bytes3 i))
(loop (+ i 1) (if (< i n) x (cdr x))))
((x>>y)
(move (if (<= l (+ i n))
(new-byte-lit 0)
(list-ref x (+ i n)))
(list-ref bytes3 i))
(loop (+ i 1) x)))
result)))
(routine-call
(string->symbol
(string-append "__sh"
(case id ((x<<y) "l") ((x>>y) "r"))
(number->string (* 8 (length bytes1)))))
(list value-x value-y)
type)))))
;; bitwise and, or, xor
;; TODO similar to add-sub and probably others, abstract multi-byte ops
;; TODO use bit set, clear and toggle for some shortcuts
(define (bitwise id value1 value2 result)
(let loop ((bytes1 (value-bytes value1))
(bytes2 (value-bytes value2))
(bytes3 (value-bytes result)))
(if (not (null? bytes3)) ;; TODO check for cases like or 0, or ff, and 0, and ff, ...
(begin
(emit (new-instr (case id ((x&y) 'and) ((|x\|y|) 'ior) ((x^y) 'xor))
(car bytes1) (car bytes2) (car bytes3)))
(loop (cdr bytes1) (cdr bytes2) (cdr bytes3)))
result)))
(define (bitwise-negation x result)
(let loop ((bytes1 (value-bytes x))
(bytes2 (value-bytes result)))
(if (not (null? bytes2))
(begin (emit (new-instr 'not (car bytes1) #f (car bytes2)))
(loop (cdr bytes1) (cdr bytes2))))))
(define (do-delayed-post-incdec)
(if (not (null? delayed-post-incdec))
(let* ((ast (car delayed-post-incdec))
(type (expr-type ast))
(op (oper-op ast))
(id (op-id op)))
(set! delayed-post-incdec (cdr delayed-post-incdec))
(let ((x (subast1 ast)))
(if (not (ref? x))
(error "assignment target must be a variable"))
(let ((result (def-variable-value (ref-def-var x))))
;; clobbers the original value, which is fine, since it
;; was moved somewhere else for the expression
(add-sub (if (eq? id 'x++) 'x+y 'x-y)
result
(int->value 1 type)
result)))
(do-delayed-post-incdec))))
;; calculates an address in an array by adding the base pointer and the offset
;; and puts the answer in FSR0 so that changes to INDF0 change the array
;; location
(define (calculate-address ast)
;; if we have a special FSR variable, no need to calculate the address as
;; it is already in the register
(let ((base-name (array-base-name ast))
(index? (eq? (op-id (oper-op ast)) 'index)))
(if (not (and base-name
(memq base-name fsr-variables)))
(let ((base (expression (subast1 ast)))
;; NB: actual addresses are 12 bits, not 16
(address (new-value (list (get-register FSR0L)
(get-register FSR0H)))))
(if index?
;; we pad up to uint16, since it is the size of the addresses
(let ((value1 (extend base 'uint16))
(value2 (extend (expression (subast2 ast)) 'uint16)))
(add-sub 'x+y value1 value2 address))
;; no offset with simple dereference
(move-value base address)))
(error "You used the array index syntax with a FSR variable, didn't you? I told you not to."))))
(define (array-base-name ast)
;; returns #f if the lhs is not a direct variable reference
;; eg : *x++ ; (x+y)* ; ...
(let ((lhs (subast1 ast)))
(and (ref? lhs)
(def-id (ref-def-var lhs)))))
(define (get-indf base-name)
;; INDF0 is not here, since it's already used for regular array accesses
(if (eq? base-name 'SIXPIC_FSR1)
(new-value (list (get-register INDF1)))
(new-value (list (get-register INDF2)))))
(define (oper ast)
(let* ((type (expr-type ast))
(op (oper-op ast))
(id (op-id op)))
(define (arith-op id x y value-x value-y)
;; since code generation does not accept literals as first