-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.c
More file actions
1885 lines (1655 loc) · 70.2 KB
/
Copy pathgenerator.c
File metadata and controls
1885 lines (1655 loc) · 70.2 KB
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
#include "generator.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ----------------------------------------------------------------
// Memory map
// ----------------------------------------------------------------
#define RAM_START 0x0200 // 6502 hardware stack occupies 0x0100 - 0x01FF
#define RAM_TOP 0x3FFF // see docs/memmap.md
#define ROM_START 0x8000
#define ROM_SIZE 0x8000
#define FP 0x00
#define RET 0x02
#define REG_START 0x04
#define PARAM_START 0xEF
// ABI zone: fixed 2-byte slots per parameter ($EF/$F0, $F1/$F2, ..., $FD/$FE).
// Using fixed 2-byte slots simplifies caller/callee agreement at the cost of 1 byte
// per u8 parameter. Callee-saves via PHA/PLA preserves the caller's ZP slots across
// the call, which also enables bounded recursion (limited by the 256-byte hw stack).
// NOTE: signed narrower→wider widening (e.g. i8 arg into i16 param) is zero-extended
// at the call site, not sign-extended. The IR does not insert explicit cast nodes for
// implicit widening in call arguments. For now this means negative i8 args passed to
// i16 params produce wrong values; a future IR pass should insert TAC_CAST nodes here.
#define ABI_SLOT_SIZE 2
#define ABI_MAX_PARAMS 8
// Fixed ZP slots for arithmetic helper subroutines ($E8–$EB, below PARAM_START).
#define HELPER_ARG1 0xE8 // dividend / multiplicand (modified by helpers)
#define HELPER_ARG2 0xE9 // divisor / multiplier (modified by helpers)
#define HELPER_RES 0xEA // quotient / product
#define HELPER_REM 0xEB // remainder (division only)
#define HELPER_SIGN 0xEC // sign flags for __sdiv8/__sdiv16 (bit7=negate quotient, bit6=negate remainder)
// 16-bit helper ZP slots ($E0–$E7, below the 8-bit helper zone at $E8)
#define HELPER16_ARG1 0xE0 // 2 bytes: dividend/multiplicand (lo=$E0, hi=$E1)
#define HELPER16_ARG2 0xE2 // 2 bytes: divisor/multiplier (lo=$E2, hi=$E3)
#define HELPER16_RES 0xE4 // 2 bytes: quotient/product (lo=$E4, hi=$E5)
#define HELPER16_REM 0xE6 // 2 bytes: remainder (lo=$E6, hi=$E7)
// ----------------------------------------------------------------
// Zero-page operand map
// ----------------------------------------------------------------
// Return byte width for a type (1 for u8/i8, 2 for u16/i16/pointers).
static unsigned codegen_type_size(type_t type) {
if (type.is_ptr) return 2;
switch (type.kind) {
case TYPE_U8: case TYPE_I8: return 1;
case TYPE_U16: case TYPE_I16: return 2;
default: return 1;
}
}
static unsigned full_type_size(emitter_t *e, type_t type) {
if (type.is_ptr) return 2;
if (type.kind == TYPE_STRUCT && e->gen) {
for (unsigned i = 0; i < e->gen->module.struct_count; i++) {
if (strcmp(e->gen->module.structs[i].name, type.struct_name) == 0)
return e->gen->module.structs[i].total_size;
}
}
return codegen_type_size(type);
}
static ir_field_def_t *lookup_struct_field(emitter_t *e,
const char *struct_name,
const char *field_name) {
for (unsigned i = 0; i < e->gen->module.struct_count; i++) {
ir_struct_def_t *s = &e->gen->module.structs[i];
if (strcmp(s->name, struct_name) != 0) continue;
for (unsigned j = 0; j < s->field_count; j++) {
if (strcmp(s->fields[j].name, field_name) == 0)
return &s->fields[j];
}
}
return NULL;
}
// True if the type requires signed comparison semantics.
static int is_signed_type(type_t type) {
return type.kind == TYPE_I8 || type.kind == TYPE_I16;
}
// Sentinel for "operand not in ZP map". Must be a ZP address that is never
// assigned by the map — $FF lives in the ABI param zone ($EF–$FF).
#define ZP_NOT_FOUND 0xFF
// Find the ZP slot assigned to a var/temp operand. Returns ZP_NOT_FOUND if not found.
static uint8_t zp_map_lookup(zp_map_t *map, tac_operand_t *op) {
for (unsigned i = 0; i < map->count; i++) {
zp_entry_t *e = &map->entries[i];
if (e->kind != op->kind) continue;
if (e->kind == OPERAND_VAR && strcmp(e->name, op->name) == 0) return e->zp_addr;
if (e->kind == OPERAND_TEMP && e->temp_id == op->temp_id) return e->zp_addr;
}
return ZP_NOT_FOUND;
}
// Assign the next available ZP slot to an operand (deduped, type-stride-aware).
static int zp_map_add(emitter_t *e, zp_map_t *map, tac_operand_kind_t kind,
char *name, unsigned temp_id, type_t type) {
tac_operand_t probe = { .kind = kind };
if (kind == OPERAND_VAR) probe.name = name;
else probe.temp_id = temp_id;
if (zp_map_lookup(map, &probe) != ZP_NOT_FOUND)
return 1;
if (map->count >= ZP_MAP_MAX) {
fprintf(stderr, "codegen: ZP map overflow (>%d operands)\n", ZP_MAP_MAX);
return 0;
}
unsigned size = full_type_size(e, type);
if ((unsigned)map->next_addr + size > HELPER16_ARG1) {
fprintf(stderr, "codegen: ZP space exhausted (next=$%02X, need %u bytes, limit=$%02X)\n",
map->next_addr, size, HELPER16_ARG1);
return 0;
}
zp_entry_t *entry = &map->entries[map->count++];
entry->kind = kind;
if (kind == OPERAND_VAR) entry->name = name;
else entry->temp_id = temp_id;
entry->zp_addr = map->next_addr;
entry->size = (uint8_t)size;
map->next_addr += (uint8_t)size;
return 1;
}
// Register a TAC operand in the ZP map (dispatches var vs temp).
static int zp_map_add_operand(emitter_t *e, zp_map_t *map, tac_operand_t *op) {
if (op->kind == OPERAND_VAR)
return zp_map_add(e, map, OPERAND_VAR, op->name, 0, op->type);
if (op->kind == OPERAND_TEMP)
return zp_map_add(e, map, OPERAND_TEMP, NULL, op->temp_id, op->type);
return 1;
}
// Build the per-function ZP map: params first, then all referenced operands.
static int zp_map_build(emitter_t *e, zp_map_t *map, cfg_t *cfg) {
map->count = 0;
map->next_addr = REG_START;
for (unsigned i = 0; i < cfg->params.count; i++) {
if (!zp_map_add(e, map, OPERAND_VAR, cfg->params.items[i].name, 0,
cfg->params.items[i].type))
return 0;
}
for (unsigned i = 0; i < cfg->block_count; i++) {
basic_block_t *block = cfg->blocks[i];
for (unsigned j = 0; j < block->instr_count; j++) {
tac_instr_t *inst = &block->instrs[j];
if (!zp_map_add_operand(e, map, &inst->dst)) return 0;
if (!zp_map_add_operand(e, map, &inst->src1)) return 0;
if (!zp_map_add_operand(e, map, &inst->src2)) return 0;
}
}
return 1;
}
// ----------------------------------------------------------------
// Label resolution
// ----------------------------------------------------------------
// Record a function's ROM address for JSR fixup resolution.
static void register_func_label(emitter_t *e, char *name, uint16_t addr) {
if (e->func_label_count >= e->func_label_capacity) {
unsigned cap = e->func_label_capacity ? e->func_label_capacity * 2 : 8;
func_label_t *grown = arena_alloc(&e->arena, cap * sizeof(func_label_t));
if (e->func_labels)
memcpy(grown, e->func_labels, e->func_label_count * sizeof(func_label_t));
e->func_labels = grown;
e->func_label_capacity = cap;
}
func_label_t *l = &e->func_labels[e->func_label_count++];
l->name = name;
l->addr = addr;
}
// Backpatch all JSR placeholders with resolved function addresses.
static int resolve_func_fixups(emitter_t *e) {
if (e->overflow) return 1; // ROM already corrupt; generate_rom will catch it
for (unsigned i = 0; i < e->fixup_count; i++) {
fixup_t *f = &e->fixups[i];
uint16_t addr = 0;
int found = 0;
for (unsigned j = 0; j < e->func_label_count; j++) {
if (strcmp(e->func_labels[j].name, f->func_name) == 0) {
addr = e->func_labels[j].addr;
found = 1;
break;
}
}
if (!found) {
fprintf(stderr, "codegen: unresolved function '%s'\n", f->func_name);
return 0;
}
e->rom[f->patch_pos] = (uint8_t)(addr & 0xFF);
e->rom[f->patch_pos + 1] = (uint8_t)(addr >> 8);
}
return 1;
}
// Queue a forward-reference fixup for a JSR to an unresolved function.
static void add_fixup(emitter_t *e, char *func_name) {
if (e->fixup_count >= e->fixup_capacity) {
unsigned cap = e->fixup_capacity ? e->fixup_capacity * 2 : 8;
fixup_t *grown = arena_alloc(&e->arena, cap * sizeof(fixup_t));
if (e->fixups)
memcpy(grown, e->fixups, e->fixup_count * sizeof(fixup_t));
e->fixups = grown;
e->fixup_capacity = cap;
}
fixup_t *f = &e->fixups[e->fixup_count++];
f->patch_pos = e->code_pos;
f->func_name = func_name;
f->label_id = 0;
}
// Backpatch all local label placeholders (JMP/COND_JUMP) within a function.
static int resolve_local_fixups(emitter_t *e) {
if (e->overflow) return 1; // ROM already corrupt; generate_rom will catch it
for (unsigned i = 0; i < e->local_fixup_count; i++) {
fixup_t *f = &e->local_fixups[i];
uint16_t addr = e->local_labels[f->label_id];
if (!addr) {
fprintf(stderr, "codegen: unresolved local label L%u\n", f->label_id);
return 0;
}
e->rom[f->patch_pos] = (uint8_t)(addr & 0xFF);
e->rom[f->patch_pos + 1] = (uint8_t)(addr >> 8);
}
return 1;
}
// Queue a forward-reference fixup for a local control-flow label.
static void add_local_fixup(emitter_t *e, unsigned label_id) {
if (e->local_fixup_count >= e->local_fixup_capacity) {
unsigned cap = e->local_fixup_capacity ? e->local_fixup_capacity * 2 : 8;
fixup_t *grown = arena_alloc(&e->arena, cap * sizeof(fixup_t));
if (e->local_fixups)
memcpy(grown, e->local_fixups, e->local_fixup_count * sizeof(fixup_t));
e->local_fixups = grown;
e->local_fixup_capacity = cap;
}
fixup_t *f = &e->local_fixups[e->local_fixup_count++];
f->patch_pos = e->code_pos;
f->label_id = label_id;
}
// ----------------------------------------------------------------
// Global symbol support
// ----------------------------------------------------------------
// Look up a global variable by name; returns NULL for locals/temps.
static global_entry_t *lookup_global(emitter_t *e, char *name) {
for (unsigned i = 0; i < e->global_entry_count; i++) {
if (strcmp(e->global_entries[i].name, name) == 0)
return &e->global_entries[i];
}
return NULL;
}
// Assign RAM addresses ($0200+) to each global variable with type-aware stride.
static void allocate_globals(emitter_t *e, ir_gen_t *gen) {
unsigned count = gen->module.global_count;
if (count == 0) return;
e->global_entries = arena_alloc(&e->arena, count * sizeof(global_entry_t));
e->global_entry_count = count;
for (unsigned i = 0; i < count; i++) {
ir_global_t *g = &gen->module.globals[i];
unsigned size = full_type_size(e, g->type);
global_entry_t *entry = &e->global_entries[i];
entry->name = g->name;
entry->ram_addr = e->ram_pos;
entry->size = (uint8_t)size;
entry->type = g->type;
e->ram_pos += (uint16_t)size;
}
}
// ----------------------------------------------------------------
// Op code emitters
// ----------------------------------------------------------------
#define EMIT(OP_CODE) do { \
if (e->code_pos >= ROM_SIZE) { e->overflow = 1; } \
else { e->rom[e->code_pos++] = (uint8_t)(OP_CODE); } \
} while (0)
// Write one byte to an already-emitted position (branch offset backpatch).
// Guards against positions recorded after an overflow (which would be >= ROM_SIZE).
#define PATCH_BYTE(POS, VAL) do { \
if ((POS) < ROM_SIZE) e->rom[(POS)] = (uint8_t)(VAL); \
else e->overflow = 1; \
} while (0)
#define OP_EMITTER_SINGLE_ARG(NAME, OP_CODE) \
static void NAME(emitter_t *e, uint8_t byte) { \
EMIT(OP_CODE); \
EMIT(byte); \
}
#define OP_EMITTER_NO_ARG(NAME, OP_CODE) \
static void NAME(emitter_t *e) { \
EMIT(OP_CODE); \
}
#define OP_EMITTER_ABS(NAME, OP_CODE) \
static void NAME(emitter_t *e, uint16_t addr) { \
EMIT(OP_CODE); \
EMIT((uint8_t)(addr & 0xFF)); \
EMIT((uint8_t)(addr >> 8)); \
}
OP_EMITTER_SINGLE_ARG(lda_imm, 0xA9)
OP_EMITTER_SINGLE_ARG(lda_zpg, 0xA5)
OP_EMITTER_SINGLE_ARG(lda_ind_y, 0xB1)
OP_EMITTER_SINGLE_ARG(sta_ind_y, 0x91)
OP_EMITTER_SINGLE_ARG(ldx_imm, 0xA2)
OP_EMITTER_SINGLE_ARG(ldy_imm, 0xA0)
OP_EMITTER_SINGLE_ARG(sta_zpg, 0x85)
OP_EMITTER_SINGLE_ARG(ora_imm, 0x09)
OP_EMITTER_SINGLE_ARG(ora_zpg, 0x05)
OP_EMITTER_SINGLE_ARG(and_imm, 0x29)
OP_EMITTER_SINGLE_ARG(and_zpg, 0x25)
OP_EMITTER_SINGLE_ARG(eor_imm, 0x49)
OP_EMITTER_SINGLE_ARG(eor_zpg, 0x45)
OP_EMITTER_SINGLE_ARG(asl_zpg, 0x06)
OP_EMITTER_SINGLE_ARG(rol_zpg, 0x26)
OP_EMITTER_SINGLE_ARG(lsr_zpg, 0x46)
OP_EMITTER_SINGLE_ARG(ror_zpg, 0x66)
OP_EMITTER_SINGLE_ARG(cmp_imm, 0xC9)
OP_EMITTER_SINGLE_ARG(cmp_zpg, 0xC5)
OP_EMITTER_SINGLE_ARG(beq_rel, 0xF0)
OP_EMITTER_SINGLE_ARG(bne_rel, 0xD0)
OP_EMITTER_SINGLE_ARG(bcs_rel, 0xB0)
OP_EMITTER_SINGLE_ARG(bcc_rel, 0x90)
OP_EMITTER_SINGLE_ARG(bpl_rel, 0x10)
OP_EMITTER_SINGLE_ARG(inc_zpg, 0xE6)
OP_EMITTER_SINGLE_ARG(dec_zpg, 0xC6)
OP_EMITTER_SINGLE_ARG(adc_imm, 0x69)
OP_EMITTER_SINGLE_ARG(adc_zpg, 0x65)
OP_EMITTER_SINGLE_ARG(sbc_imm, 0xE9)
OP_EMITTER_SINGLE_ARG(sbc_zpg, 0xE5)
OP_EMITTER_SINGLE_ARG(bvc_rel, 0x50)
OP_EMITTER_NO_ARG(txs, 0x9A)
OP_EMITTER_NO_ARG(rts, 0x60)
OP_EMITTER_NO_ARG(clc, 0x18)
OP_EMITTER_NO_ARG(sec, 0x38)
OP_EMITTER_NO_ARG(tax, 0xAA)
OP_EMITTER_NO_ARG(dex, 0xCA)
OP_EMITTER_NO_ARG(pha, 0x48)
OP_EMITTER_NO_ARG(pla, 0x68)
OP_EMITTER_ABS(jmp_abs, 0x4C)
OP_EMITTER_ABS(sta_abs, 0x8D)
OP_EMITTER_ABS(lda_abs, 0xAD)
OP_EMITTER_ABS(ora_abs, 0x0D)
OP_EMITTER_ABS(and_abs, 0x2D)
OP_EMITTER_ABS(eor_abs, 0x4D)
OP_EMITTER_ABS(cmp_abs, 0xCD)
OP_EMITTER_ABS(inc_abs, 0xEE)
OP_EMITTER_ABS(dec_abs, 0xCE)
OP_EMITTER_ABS(adc_abs, 0x6D)
OP_EMITTER_ABS(sbc_abs, 0xED)
#undef OP_EMITTER_SINGLE_ARG
#undef OP_EMITTER_NO_ARG
#undef OP_EMITTER_ABS
// Emit JSR with a placeholder address and queue a fixup for later resolution.
static void jsr(emitter_t *e, char *func_name) {
EMIT(0x20);
add_fixup(e, func_name);
EMIT(0x00);
EMIT(0x00);
}
// ----------------------------------------------------------------
// Global init & data section
// ----------------------------------------------------------------
// Queue a fixup for a string ROM address (resolved after data section is emitted).
static void add_data_fixup(emitter_t *e, const char *str_val, uint8_t byte) {
if (e->data_fixup_count >= e->data_fixup_capacity) {
unsigned cap = e->data_fixup_capacity ? e->data_fixup_capacity * 2 : 8;
data_fixup_t *grown = arena_alloc(&e->arena, cap * sizeof(data_fixup_t));
if (e->data_fixups)
memcpy(grown, e->data_fixups, e->data_fixup_count * sizeof(data_fixup_t));
e->data_fixups = grown;
e->data_fixup_capacity = cap;
}
data_fixup_t *f = &e->data_fixups[e->data_fixup_count++];
f->patch_pos = e->code_pos;
f->str_val = str_val;
f->byte = byte;
}
// Emit bootstrap code to initialize each global variable at its RAM address.
static void emit_global_init(emitter_t *e, ir_gen_t *gen) {
for (unsigned i = 0; i < gen->module.global_count; i++) {
ir_global_t *g = &gen->module.globals[i];
global_entry_t *entry = &e->global_entries[i];
unsigned width = entry->size;
switch (g->init_kind) {
case IR_INIT_INT:
for (unsigned b = 0; b < width; b++) {
lda_imm(e, (uint8_t)((g->int_val >> (8 * b)) & 0xFF));
sta_abs(e, (uint16_t)(entry->ram_addr + b));
}
break;
case IR_INIT_STR:
for (unsigned b = 0; b < width; b++) {
EMIT(0xA9);
add_data_fixup(e, g->str_val, (uint8_t)b);
EMIT(0x00);
sta_abs(e, (uint16_t)(entry->ram_addr + b));
}
break;
case IR_INIT_NONE:
break;
}
}
}
// Write string literals into ROM after code and resolve data fixups.
// Each unique string value is written once; fixups for both global and local
// string pointers are patched with the correct ROM address.
static void emit_data_section(emitter_t *e, ir_gen_t *gen) {
(void)gen;
e->data_pos = e->code_pos;
if (e->data_fixup_count == 0) return;
const char **unique_strs = malloc(e->data_fixup_count * sizeof(char *));
uint16_t *unique_addrs = malloc(e->data_fixup_count * sizeof(uint16_t));
unsigned unique_count = 0;
for (unsigned i = 0; i < e->data_fixup_count; i++) {
const char *s = e->data_fixups[i].str_val;
unsigned found = unique_count;
for (unsigned j = 0; j < unique_count; j++) {
if (strcmp(unique_strs[j], s) == 0) { found = j; break; }
}
if (found == unique_count) {
unique_strs[unique_count] = s;
unique_addrs[unique_count] = (uint16_t)(ROM_START + e->code_pos);
size_t len = strlen(s);
for (size_t k = 0; k <= len; k++)
EMIT((uint8_t)s[k]);
unique_count++;
}
}
if (e->overflow) { free(unique_strs); free(unique_addrs); return; }
for (unsigned i = 0; i < e->data_fixup_count; i++) {
data_fixup_t *f = &e->data_fixups[i];
for (unsigned j = 0; j < unique_count; j++) {
if (strcmp(unique_strs[j], f->str_val) == 0) {
e->rom[f->patch_pos] = (uint8_t)((unique_addrs[j] >> (8 * f->byte)) & 0xFF);
break;
}
}
}
free(unique_strs);
free(unique_addrs);
}
// ----------------------------------------------------------------
// High level emitters
// ----------------------------------------------------------------
// Write NMI, Reset, and IRQ vectors at $FFFA-$FFFF.
static void emit_vectors(emitter_t *e) {
unsigned pos = 0xFFFA - ROM_START;
e->rom[pos++] = 0x00; // NMI low (unused)
e->rom[pos++] = 0x00; // NMI high (unused)
e->rom[pos++] = ROM_START & 0xFF; // Reset low
e->rom[pos++] = ROM_START >> 8; // Reset high
e->rom[pos++] = 0x00; // IRQ low (unused)
e->rom[pos++] = 0x00; // IRQ high (unused)
}
// Emit the reset stub: SEI, CLD, stack init, frame pointer init.
static void emit_bootstrap(emitter_t *e) {
EMIT(0x78); // SEI
EMIT(0xD8); // CLD
ldx_imm(e, 0XFF); // Init hardware stack
txs(e);
lda_imm(e, 0xFF); // init fp to point to top of hardware stack
sta_zpg(e, FP);
lda_imm(e, 0x01);
sta_zpg(e, FP + 1);
}
// Emit JSR main followed by an infinite halt loop (JMP to self).
static void emit_call_main(emitter_t *e) {
jsr(e, "main");
// halt loop
uint16_t halt_addr = (uint16_t)(ROM_START + e->code_pos);
jmp_abs(e, halt_addr);
}
// Load byte N of an operand into A. Global-aware: uses abs for globals, zpg for locals.
static void emit_load_byte(emitter_t *e, zp_map_t *map,
tac_operand_t *op, unsigned byte) {
switch (op->kind) {
case OPERAND_CONST_INT:
lda_imm(e, (uint8_t)((op->int_val >> (8 * byte)) & 0xFF));
break;
case OPERAND_CONST_STR:
// Emit LDA #placeholder; the immediate byte is patched by emit_data_section
// once the string's ROM address is known.
EMIT(0xA9);
add_data_fixup(e, op->str_val, (uint8_t)byte);
EMIT(0x00);
break;
case OPERAND_VAR: {
if (byte >= full_type_size(e, op->type)) { lda_imm(e, 0); break; }
global_entry_t *g = lookup_global(e, op->name);
if (g)
lda_abs(e, (uint16_t)(g->ram_addr + byte));
else
lda_zpg(e, (uint8_t)(zp_map_lookup(map, op) + byte));
break;
}
case OPERAND_TEMP:
if (byte >= full_type_size(e, op->type)) { lda_imm(e, 0); break; }
lda_zpg(e, (uint8_t)(zp_map_lookup(map, op) + byte));
break;
default: break;
}
}
// Store A into byte N of a destination. Global-aware: uses abs for globals, zpg for locals.
static void emit_store_byte(emitter_t *e, zp_map_t *map,
tac_operand_t *dst, unsigned byte) {
if (dst->kind == OPERAND_VAR) {
global_entry_t *g = lookup_global(e, dst->name);
if (g) {
sta_abs(e, (uint16_t)(g->ram_addr + byte));
return;
}
}
sta_zpg(e, (uint8_t)(zp_map_lookup(map, dst) + byte));
}
#define GLOBAL_AWARE_ALU_HELPER(NAME, IMM_FN, ZPG_FN, ABS_FN) \
static void NAME(emitter_t *e, zp_map_t *map, \
tac_operand_t *op, unsigned byte) { \
switch (op->kind) { \
case OPERAND_CONST_INT: \
IMM_FN(e, (uint8_t)((op->int_val >> (8 * byte)) & 0xFF)); \
break; \
case OPERAND_VAR: { \
if (byte >= full_type_size(e, op->type)) { IMM_FN(e, 0); break; } \
global_entry_t *g = lookup_global(e, op->name); \
if (g) \
ABS_FN(e, (uint16_t)(g->ram_addr + byte)); \
else \
ZPG_FN(e, (uint8_t)(zp_map_lookup(map, op) + byte)); \
break; \
} \
case OPERAND_TEMP: \
if (byte >= full_type_size(e, op->type)) { IMM_FN(e, 0); break; } \
ZPG_FN(e, (uint8_t)(zp_map_lookup(map, op) + byte)); \
break; \
default: break; \
} \
}
GLOBAL_AWARE_ALU_HELPER(emit_ora_byte, ora_imm, ora_zpg, ora_abs)
GLOBAL_AWARE_ALU_HELPER(emit_and_byte, and_imm, and_zpg, and_abs)
GLOBAL_AWARE_ALU_HELPER(emit_eor_byte, eor_imm, eor_zpg, eor_abs)
GLOBAL_AWARE_ALU_HELPER(emit_cmp_byte, cmp_imm, cmp_zpg, cmp_abs)
GLOBAL_AWARE_ALU_HELPER(emit_adc_byte, adc_imm, adc_zpg, adc_abs)
GLOBAL_AWARE_ALU_HELPER(emit_sbc_byte, sbc_imm, sbc_zpg, sbc_abs)
// Emit conditional jump: LDA src; [ORA src+1]; BEQ skip; JMP target. Jumps when nonzero.
static void emit_cond_jump(emitter_t *e, zp_map_t *map,
tac_operand_t *src, unsigned label_id) {
unsigned width = codegen_type_size(src->type);
emit_load_byte(e, map, src, 0);
if (width > 1)
emit_ora_byte(e, map, src, 1);
beq_rel(e, 3);
if (e->local_labels[label_id]) {
jmp_abs(e, e->local_labels[label_id]);
} else {
EMIT(0x4C);
add_local_fixup(e, label_id);
EMIT(0x00);
EMIT(0x00);
}
}
// Push every byte of every ZP slot this function uses onto the hardware stack.
// Called at function entry (before the ABI-zone copy) so that whatever the caller
// had at those ZP addresses is preserved across the call.
static void emit_zp_save(emitter_t *e, zp_map_t *map) {
for (unsigned i = 0; i < map->count; i++) {
for (unsigned b = 0; b < map->entries[i].size; b++) {
lda_zpg(e, (uint8_t)(map->entries[i].zp_addr + b));
pha(e);
}
}
}
// Pop every byte back in reverse order (LIFO) and store into the ZP slots.
// Called before every RTS so the caller's ZP values are restored on return.
static void emit_zp_restore(emitter_t *e, zp_map_t *map) {
unsigned i = map->count;
while (i--) {
unsigned b = map->entries[i].size;
while (b--) {
pla(e);
sta_zpg(e, (uint8_t)(map->entries[i].zp_addr + b));
}
}
}
// Copy each argument from the fixed ABI zone into the function's own ZP slots.
// Skipped when param_count == 0 (covers main and any no-arg function).
static int emit_function_prologue(emitter_t *e, zp_map_t *map, cfg_t *cfg) {
if (cfg->params.count > ABI_MAX_PARAMS) {
fprintf(stderr, "codegen: function '%s' has %u parameters, max is %d\n",
cfg->name, cfg->params.count, ABI_MAX_PARAMS);
return 0;
}
for (unsigned i = 0; i < cfg->params.count; i++) {
param_t *param = &cfg->params.items[i];
unsigned size = codegen_type_size(param->type);
tac_operand_t op = { .kind = OPERAND_VAR, .name = param->name, .type = param->type };
uint8_t zp = zp_map_lookup(map, &op);
for (unsigned b = 0; b < size; b++) {
lda_zpg(e, (uint8_t)(PARAM_START + i * ABI_SLOT_SIZE + b));
sta_zpg(e, (uint8_t)(zp + b));
}
}
return 1;
}
// Lower a function's TAC instruction stream to 65C02 machine code.
static int emit_function_from_cfg(emitter_t *e, cfg_t *cfg) {
register_func_label(e, cfg->name, (uint16_t)(ROM_START + e->code_pos));
zp_map_t map;
if (!zp_map_build(e, &map, cfg)) return 0;
// main is only called by the bootstrap, which has no ZP state to preserve.
// Every other callee saves the caller's ZP slots on entry and restores on return.
int is_main = (strcmp(cfg->name, "main") == 0);
if (!is_main)
emit_zp_save(e, &map);
if (cfg->params.count > 0 && !emit_function_prologue(e, &map, cfg))
return 0;
e->local_label_count = cfg->next_label;
e->local_fixup_count = 0;
e->local_labels = arena_alloc(&e->arena, cfg->next_label * sizeof(uint16_t));
for (unsigned i = 0; i < cfg->block_count; ++i) {
basic_block_t *block = cfg->blocks[i];
for (unsigned j = 0; j < block->instr_count; ++j) {
tac_instr_t *instruction = &block->instrs[j];
switch (instruction->op) {
// -- data movement --
case TAC_COPY: {
unsigned src_size = full_type_size(e, instruction->src1.type);
unsigned dst_size = full_type_size(e, instruction->dst.type);
unsigned copy_size = src_size < dst_size ? src_size : dst_size;
for (unsigned b = 0; b < copy_size; b++) {
emit_load_byte(e, &map, &instruction->src1, b);
emit_store_byte(e, &map, &instruction->dst, b);
}
// Implicit widening: extend hi bytes (A holds hi byte of src after loop)
if (dst_size > src_size) {
if (is_signed_type(instruction->src1.type)) {
cmp_imm(e, 0x80);
lda_imm(e, 0xFF);
bcs_rel(e, 2);
lda_imm(e, 0);
} else {
lda_imm(e, 0);
}
for (unsigned b = src_size; b < dst_size; b++)
emit_store_byte(e, &map, &instruction->dst, b);
}
break;
}
case TAC_CAST: {
unsigned src_size = codegen_type_size(instruction->src1.type);
unsigned dst_size = codegen_type_size(instruction->cast_type);
uint8_t dst_zp = zp_map_lookup(&map, &instruction->dst);
unsigned copy_size = src_size < dst_size ? src_size : dst_size;
for (unsigned b = 0; b < copy_size; b++) {
emit_load_byte(e, &map, &instruction->src1, b);
sta_zpg(e, (uint8_t)(dst_zp + b));
}
if (dst_size > src_size) {
// After the loop, A holds the high byte of src. Use it to extend.
if (is_signed_type(instruction->src1.type)) {
// Sign-extend: CMP #$80 sets C if src is negative (bit 7 = 1).
// A = $FF if negative, $00 if positive; BCS skips the LDA #0.
cmp_imm(e, 0x80);
lda_imm(e, 0xFF);
bcs_rel(e, 2); // skip LDA #0 (2 bytes) if carry set (negative)
lda_imm(e, 0);
} else {
lda_imm(e, 0);
}
for (unsigned b = src_size; b < dst_size; b++)
sta_zpg(e, (uint8_t)(dst_zp + b));
}
break;
}
case TAC_LOAD: {
unsigned width = codegen_type_size(instruction->dst.type);
uint8_t dst_addr = zp_map_lookup(&map, &instruction->dst);
if (instruction->src1.kind == OPERAND_CONST_INT) {
uint16_t addr = (uint16_t)instruction->src1.int_val;
for (unsigned b = 0; b < width; b++) {
lda_abs(e, (uint16_t)(addr + b));
sta_zpg(e, (uint8_t)(dst_addr + b));
}
} else {
uint8_t ptr_zp = zp_map_lookup(&map, &instruction->src1);
if (instruction->src1.kind == OPERAND_VAR) {
global_entry_t *g = lookup_global(e, instruction->src1.name);
if (g) {
for (unsigned b = 0; b < 2; b++) {
lda_abs(e, (uint16_t)(g->ram_addr + b));
sta_zpg(e, (uint8_t)(ptr_zp + b));
}
}
}
for (unsigned b = 0; b < width; b++) {
ldy_imm(e, (uint8_t)b);
lda_ind_y(e, ptr_zp);
sta_zpg(e, (uint8_t)(dst_addr + b));
}
}
break;
}
case TAC_STORE: {
unsigned width = codegen_type_size(instruction->src1.type);
if (instruction->dst.kind == OPERAND_CONST_INT) {
uint16_t base_addr = (uint16_t)instruction->dst.int_val;
for (unsigned b = 0; b < width; b++) {
emit_load_byte(e, &map, &instruction->src1, b);
sta_abs(e, (uint16_t)(base_addr + b));
}
} else {
uint8_t ptr_zp = zp_map_lookup(&map, &instruction->dst);
if (instruction->dst.kind == OPERAND_VAR) {
global_entry_t *g = lookup_global(e, instruction->dst.name);
if (g) {
for (unsigned b = 0; b < 2; b++) {
lda_abs(e, (uint16_t)(g->ram_addr + b));
sta_zpg(e, (uint8_t)(ptr_zp + b));
}
}
}
for (unsigned b = 0; b < width; b++) {
ldy_imm(e, (uint8_t)b);
emit_load_byte(e, &map, &instruction->src1, b);
sta_ind_y(e, ptr_zp);
}
}
break;
}
case TAC_ADDR_OF: {
uint8_t dst_zp = zp_map_lookup(&map, &instruction->dst);
uint16_t addr;
global_entry_t *g = lookup_global(e, instruction->src1.name);
if (g) {
addr = g->ram_addr;
} else {
addr = (uint16_t)zp_map_lookup(&map, &instruction->src1);
}
lda_imm(e, (uint8_t)(addr & 0xFF));
sta_zpg(e, dst_zp);
lda_imm(e, (uint8_t)(addr >> 8));
sta_zpg(e, (uint8_t)(dst_zp + 1));
break;
}
// -- control flow --
case TAC_LABEL: e->local_labels[instruction->label] = (uint16_t)(ROM_START + e->code_pos); break;
case TAC_JUMP: {
if (e->local_labels[instruction->label]) {
jmp_abs(e, e->local_labels[instruction->label]);
} else {
EMIT(0x4c);
add_local_fixup(e, instruction->label);
EMIT(0x00);
EMIT(0x00);
}
break;
}
case TAC_COND_JUMP: emit_cond_jump(e, &map, &instruction->src1, instruction->label); break;
case TAC_RETURN: {
if (instruction->src1.kind != OPERAND_NONE) {
unsigned width = codegen_type_size(cfg->return_type);
for (unsigned b = 0; b < width; b++) {
emit_load_byte(e, &map, &instruction->src1, b);
sta_zpg(e, (uint8_t)(RET + b));
}
}
// Restore the caller's ZP slots before returning (balances emit_zp_save).
// Return value is already in RET ($02/$03) above the restored region.
if (!is_main)
emit_zp_restore(e, &map);
rts(e);
break;
}
case TAC_CALL: {
if (instruction->call_arg_count > ABI_MAX_PARAMS) {
fprintf(stderr, "codegen: call to '%s' passes %u arguments, max is %d\n",
instruction->call_name, instruction->call_arg_count, ABI_MAX_PARAMS);
return 0;
}
// Copy each argument into its fixed 2-byte ABI zone slot. emit_load_byte
// zero-extends naturally for byte indices past the operand's type width.
for (unsigned ai = 0; ai < instruction->call_arg_count; ai++) {
tac_operand_t *arg = &instruction->call_args[ai];
for (unsigned ab = 0; ab < ABI_SLOT_SIZE; ab++) {
emit_load_byte(e, &map, arg, ab);
sta_zpg(e, (uint8_t)(PARAM_START + ai * ABI_SLOT_SIZE + ab));
}
}
jsr(e, instruction->call_name);
// Copy return value from ZP_RET into the destination temp (skip for void).
if (instruction->dst.type.kind != TYPE_VOID) {
unsigned ret_size = codegen_type_size(instruction->dst.type);
for (unsigned rb = 0; rb < ret_size; rb++) {
lda_zpg(e, (uint8_t)(RET + rb));
emit_store_byte(e, &map, &instruction->dst, rb);
}
}
break;
}
// -- comparisons & boolean --
case TAC_NOT: {
uint8_t dst_addr = zp_map_lookup(&map, &instruction->dst);
unsigned width = codegen_type_size(instruction->src1.type);
emit_load_byte(e, &map, &instruction->src1, 0);
if (width > 1)
emit_ora_byte(e, &map, &instruction->src1, 1);
// A is now nonzero iff the original value was truthy.
// Convert to boolean: 0 → 1, nonzero → 0.
beq_rel(e, 4); // +4: skip LDA #0 + BEQ +2
lda_imm(e, 0);
beq_rel(e, 2); // +2: skip LDA #1 (always taken, Z=1)
lda_imm(e, 1);
sta_zpg(e, dst_addr);
break;
}
case TAC_LT: case TAC_GTE: case TAC_GT: case TAC_LTE:
case TAC_EQ: case TAC_NEQ: {
uint8_t dst_addr = zp_map_lookup(&map, &instruction->dst);
tac_operand_t *left, *right;
uint8_t branch_op;
switch (instruction->op) {
case TAC_GT: left = &instruction->src2; right = &instruction->src1; branch_op = 0x90; break;
case TAC_LTE: left = &instruction->src2; right = &instruction->src1; branch_op = 0xB0; break;
case TAC_LT: left = &instruction->src1; right = &instruction->src2; branch_op = 0x90; break;
case TAC_GTE: left = &instruction->src1; right = &instruction->src2; branch_op = 0xB0; break;
case TAC_EQ: left = &instruction->src1; right = &instruction->src2; branch_op = 0xF0; break;
case TAC_NEQ: left = &instruction->src1; right = &instruction->src2; branch_op = 0xD0; break;
default: left = &instruction->src1; right = &instruction->src2; branch_op = 0x90; break;
}
unsigned cmp_width = codegen_type_size(left->type);
int is_signed = is_signed_type(left->type);
int is_ordering = (instruction->op != TAC_EQ && instruction->op != TAC_NEQ);
if (cmp_width == 1 && (!is_signed || !is_ordering)) {
// u8 unsigned ordering, or u8/i8 EQ/NEQ (sign-agnostic)
emit_load_byte(e, &map, left, 0);
emit_cmp_byte(e, &map, right, 0);
EMIT(branch_op); EMIT(4);
lda_imm(e, 0);
EMIT(0xF0); EMIT(2);
lda_imm(e, 1);
} else if (cmp_width == 1 && is_signed) {
// i8 signed ordering: N XOR V pattern
size_t p_true, p_done;
emit_load_byte(e, &map, left, 0);
sec(e);
emit_sbc_byte(e, &map, right, 0);
bvc_rel(e, 2);
eor_imm(e, 0x80);
// N flag = (left < right)
EMIT(0x30); p_true = e->code_pos; EMIT(0); // BMI true
// false:
lda_imm(e, 0);
EMIT(0xF0); p_done = e->code_pos; EMIT(0); // BEQ done
// true:
PATCH_BYTE(p_true, e->code_pos - p_true - 1);
lda_imm(e, 1);
// done:
PATCH_BYTE(p_done, e->code_pos - p_done - 1);
if (branch_op == 0xB0) {
eor_imm(e, 0x01);
}
} else if (!is_ordering) {
// u16/i16 EQ/NEQ (sign-agnostic)
size_t p1, p2, p3;
if (instruction->op == TAC_EQ) {
emit_load_byte(e, &map, left, 1);
emit_cmp_byte(e, &map, right, 1);
EMIT(0xD0); p1 = e->code_pos; EMIT(0); // BNE false
emit_load_byte(e, &map, left, 0);
emit_cmp_byte(e, &map, right, 0);
EMIT(0xF0); p2 = e->code_pos; EMIT(0); // BEQ true
// false:
PATCH_BYTE(p1, e->code_pos - p1 - 1);
lda_imm(e, 0);
EMIT(0xF0); p3 = e->code_pos; EMIT(0); // BEQ done
// true:
PATCH_BYTE(p2, e->code_pos - p2 - 1);
lda_imm(e, 1);
// done: