-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcodegen.py
More file actions
executable file
·3734 lines (3409 loc) · 203 KB
/
Copy pathcodegen.py
File metadata and controls
executable file
·3734 lines (3409 loc) · 203 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
import re
import dataclasses
from . import peepholeopt
from . import ast
from . import codegen_utils
from .macro_expander import MacroExpander
from .asm_substitution import substitute_asm_vars
class CodeGenError(Exception):
"""Raised when codegen encounters irrecoverable semantic issues (e.g., unknown symbols)."""
pass
class CodeGen:
def __init__(self, module: ast.Module):
self.print_debug = False # Set to True to enable debug printing
self.module = module
self.lines = []
self.proc_sigs = self._build_proc_signatures(module)
self.array_dims = self._build_array_dimensions(module)
self.macro_expander = MacroExpander(module, ast, self._normalize_expr)
self.macros = self.macro_expander.macros # Keep compatibility with existing call sites
self.constants = self._build_constants(module) # Collect constant definitions
self.globals = self._build_globals(module) # Collect global definitions
self.struct_info = self._build_struct_info(module) # Struct sizes and field layouts
self.extern_vars = self._build_extern_vars(module) # Collect external variables
self.extern_funcs = self._build_extern_funcs(module) # Collect external functions
self.locked_regs = self._build_locked_regs(module) # Collect locked registers from pragmas
self.strict_word_arith = self._build_strict_word_arith(module)
self.label_counter = 0
self.push_stack = [] # Track PUSH/POP register lists
self.loop_stack = [] # Stack of (continue_label, end_label) for nested loops
self.dbra_depth = 0 # Nesting depth of active dbra-counter loops (RepeatLoop / fast-path ForLoop); they share d7
def _fail(self, message: str):
"""Abort codegen with a clear, user-facing error."""
raise CodeGenError(message)
def _fits_signed_word(self, value: int) -> bool:
return -32768 <= value <= 32767
def _require_signed_word_const(self, expr, op_name: str, side: str):
"""Ensure constant arithmetic operands fit 68000 word-based MULS/DIVS ops."""
if isinstance(expr, ast.Number) and not self._fits_signed_word(expr.value):
self._fail(
f"{op_name} uses 68000 word arithmetic; {side} constant {expr.value} "
f"is outside signed 16-bit range (-32768..32767)."
)
def _is_word_arith_operand_safe(self, expr, locals_info, params=None) -> bool:
"""Best-effort proof that expr is always representable as signed 16-bit."""
if isinstance(expr, ast.Number):
return self._fits_signed_word(expr.value)
if isinstance(expr, ast.VarRef):
name = expr.name
local_info = next((l for l in locals_info if l[0] == name), None)
if local_info:
_, vtype, _ = local_info
if vtype is None:
return False
size = ast.type_size(vtype)
if size == 1:
return True
if size == 2:
# Unsigned word may exceed signed 16-bit upper bound.
return ast.is_signed(vtype)
return False
if params:
param_info = next((p for p in params if p.name == name), None)
if param_info and param_info.ptype:
ptype = param_info.ptype
size = ast.type_size(ptype)
if size == 1:
return True
if size == 2:
return ast.is_signed(ptype)
return False
return False
def _require_word_arith_operand(self, expr, op_name: str, side: str, locals_info, params=None):
"""Validate operand width assumptions for MULS.W / DIVS.W operations."""
self._require_signed_word_const(expr, op_name, side)
if self.strict_word_arith and not self._is_word_arith_operand_safe(expr, locals_info, params):
self._fail(
f"{op_name} with strict16arith(on) requires provably signed 16-bit operands; "
f"{side} operand cannot be proven safe at compile time."
)
def _is_unsigned_expr(self, expr, locals_info, params=None) -> bool:
"""Best-effort check if expr should be treated as unsigned for comparisons.
Uses declared local/parameter types (u8/u16/u32/UBYTE/UWORD/ULONG).
Globals lack signedness metadata, so default to signed there.
"""
try:
from .ast import is_signed
except Exception:
return False
# Variable with explicit unsigned type in locals/params.
if isinstance(expr, ast.VarRef):
name = expr.name
local_info = next((l for l in locals_info if l[0] == name), None)
if local_info:
_, vtype, _ = local_info
if vtype is None:
return False
return not is_signed(vtype)
if params:
param_info = next((p for p in params if p.name == name), None)
if param_info and param_info.ptype:
return not is_signed(param_info.ptype)
return False
# For now, other expressions default to signed behavior
return False
def _next_label(self, prefix="L"):
"""Generate a unique label for branches."""
self.label_counter += 1
return f"{prefix}{self.label_counter}"
def _evaluate_const_expr(self, expr):
"""Try to evaluate an expression at compile time using available constants.
Returns (success, value) where success=True if evaluation succeeded."""
return codegen_utils.evaluate_const_expr(expr, self.constants)
def _build_proc_signatures(self, module: ast.Module):
"""Collect call signatures so call sites know register vs stack params.
Includes:
- Internal proc definitions (`proc`)
- Forward declarations (`func`)
- External declarations (`extern func`)
Precedence:
- Implemented `proc` signatures override declaration-only signatures.
"""
sigs = {}
# First pass: collect declaration-only signatures.
for item in module.items:
if isinstance(item, ast.CodeSection):
for it in item.items:
if isinstance(it, ast.FuncDecl):
sigs[it.name] = it.params
elif isinstance(it, ast.ExternDecl) and it.kind == 'func':
sig = it.signature
if isinstance(sig, dict) and 'params' in sig:
sigs[it.name] = sig['params']
else:
sigs[it.name] = []
elif isinstance(item, ast.ExternDecl) and item.kind == 'func':
sig = item.signature
if isinstance(sig, dict) and 'params' in sig:
sigs[item.name] = sig['params']
else:
sigs[item.name] = []
# Second pass: proc definitions override declaration-only signatures.
for item in module.items:
if isinstance(item, ast.CodeSection):
for it in item.items:
if isinstance(it, ast.Proc):
sigs[it.name] = it.params
return sigs
def _build_array_dimensions(self, module: ast.Module):
"""Collect array dimensions and element size for global arrays."""
array_info = {}
for item in module.items:
if isinstance(item, (ast.DataSection, ast.BssSection)):
for var in item.variables:
if isinstance(var, ast.StructVarDecl):
continue
if getattr(var, 'is_array', False):
elem_size = var.size_suffix if var.size_suffix else (var.size if var.size in ('b', 'w', 'l') else 'l')
if elem_size not in ('b', 'w', 'l'):
elem_size = 'l'
dims = var.dimensions if var.dimensions else []
array_info[var.name] = {'dims': dims, 'size': elem_size}
return array_info
def _build_macros(self, module: ast.Module):
"""Collect macro definitions from module.
Returns dict: {name: MacroDef}
"""
return MacroExpander.build_macros(module, ast)
def _build_constants(self, module: ast.Module):
"""Collect constant definitions from module.
Returns dict: {name: value}
"""
constants = {}
for item in module.items:
if isinstance(item, ast.ConstDecl):
constants[item.name] = item.value
elif isinstance(item, (ast.DataSection, ast.BssSection)):
# Add struct-derived constants: name__size, name__stride, and field offsets
for var in getattr(item, 'variables', []):
if isinstance(var, ast.StructVarDecl):
struct_size, offsets = self._struct_size_and_offsets(var)
constants[f"{var.name}__size"] = struct_size
constants[f"{var.name}__stride"] = struct_size
for field, off in offsets:
fname = None
try:
fname = field.name
except AttributeError:
if isinstance(field, str):
# parse name from "name.suffix" if present
fname = field.split('.')[0]
if fname:
constants[f"{var.name}_{fname}"] = off
return constants
def _build_globals(self, module: ast.Module):
globals_map = {}
for item in module.items:
if isinstance(item, ast.DataSection) or isinstance(item, ast.BssSection):
for var in item.variables:
if isinstance(var, ast.StructVarDecl):
globals_map[var.name] = 'l' # default width when used as scalar
else:
# Prioritize size_suffix over size (size is byte count, size_suffix is 'b'/'w'/'l')
size = var.size_suffix if hasattr(var, 'size_suffix') and var.size_suffix else (var.size if var.size else 'l')
if size not in ('b', 'w', 'l'):
size = 'l'
globals_map[var.name] = size
return globals_map
def _build_struct_info(self, module: ast.Module):
"""Collect struct sizes and field layouts for struct variables.
Returns dict: { name: { 'size': bytes, 'fields': { field: { 'offset': off, 'size_suffix': 'b'|'w'|'l' } } } }
"""
info = {}
for item in module.items:
if isinstance(item, (ast.DataSection, ast.BssSection)):
for var in item.variables:
if isinstance(var, ast.StructVarDecl):
size, offsets = self._struct_size_and_offsets(var)
fields = {}
for field, off in offsets:
# Defensive: handle StructField or string spec
if hasattr(field, 'name'):
fname = field.name
fsuf = field.size_suffix if field.size_suffix in ('b', 'w', 'l') else 'l'
else:
spec = str(field)
if '.' in spec:
fname, fsuf = spec.split('.', 1)
if fsuf not in ('b', 'w', 'l'):
fsuf = 'l'
else:
fname, fsuf = (spec, 'l')
fields[fname] = {
'offset': off,
'size_suffix': fsuf
}
info[var.name] = {'size': size, 'fields': fields, 'is_array': bool(var.dimensions)}
return info
def _build_extern_vars(self, module: ast.Module):
"""Collect extern variable declarations with their sizes."""
extern_vars = {}
for item in module.items:
if isinstance(item, ast.CodeSection):
for code_item in item.items:
if isinstance(code_item, ast.ExternDecl) and code_item.kind == 'var':
# Extract size from signature if available (e.g., "u8", "int", etc.)
size = 'l' # default to long
if code_item.signature:
sig = code_item.signature
if sig in ('u8', 'i8', 'byte', 'UBYTE', 'BYTE'):
size = 'b'
elif sig in ('u16', 'i16', 'word', 'UWORD', 'WORD'):
size = 'w'
extern_vars[code_item.name] = size
elif isinstance(item, ast.ExternDecl) and item.kind == 'var':
size = 'l'
if item.signature:
sig = item.signature
if sig in ('u8', 'i8', 'byte', 'UBYTE', 'BYTE'):
size = 'b'
elif sig in ('u16', 'i16', 'word', 'UWORD', 'WORD'):
size = 'w'
extern_vars[item.name] = size
return extern_vars
def _build_extern_funcs(self, module: ast.Module):
"""Collect extern function declarations."""
extern_funcs = set()
for item in module.items:
if isinstance(item, ast.CodeSection):
for code_item in item.items:
if isinstance(code_item, ast.ExternDecl) and code_item.kind == 'func':
extern_funcs.add(code_item.name)
elif isinstance(code_item, ast.FuncDecl):
# Forward declarations (func without body)
extern_funcs.add(code_item.name)
elif isinstance(item, ast.ExternDecl) and item.kind == 'func':
extern_funcs.add(item.name)
return extern_funcs
def _build_locked_regs(self, module: ast.Module):
"""Collect locked registers from #pragma lockreg directives.
Returns set of register names to lock (e.g., {'a5', 'a4'})
"""
locked = set()
for item in module.items:
if isinstance(item, ast.PragmaDirective):
if item.name == 'lockreg':
locked.update(item.args)
return locked
def _build_strict_word_arith(self, module: ast.Module) -> bool:
"""Collect strict16arith pragma mode. Default is permissive (off)."""
strict = False
for item in module.items:
if isinstance(item, ast.PragmaDirective) and item.name == 'strict16arith':
if item.args:
strict = (item.args[0] == 'on')
return strict
def _expand_macro(self, macro: ast.MacroDef, args: list, params: list, locals_info: list):
"""Expand a macro by substituting arguments into the macro body.
Returns list of expanded statements.
"""
return self.macro_expander.expand_macro(macro, args, print_debug=self.print_debug)
def _substitute_in_stmt(self, stmt, substitutions):
"""Recursively substitute macro parameters in statements."""
return self.macro_expander.substitute_in_stmt(stmt, substitutions, print_debug=self.print_debug)
def _substitute_in_expr(self, expr, substitutions):
"""Recursively substitute macro parameters in expressions."""
return self.macro_expander.substitute_in_expr(expr, substitutions)
def emit(self, s=""):
self.lines.append(s)
def _normalize_expr(self, expr):
"""Normalize parser-specific or placeholder nodes into our AST types.
- Converts Lark `Tree(op, [left, right])` into `ast.BinOp`.
- Converts `None` into a zero literal to avoid unsupported exprs.
- Recursively normalizes children.
"""
return codegen_utils.normalize_expr(expr)
def _analyze_proc(self, proc: ast.Proc):
# collect params and locals; params are now Param objects
# params is a list of Param objects with name, ptype, and optional register
params = proc.params # Keep the full Param objects
# locals is now a list of tuples: (name, type, offset)
locals_info = []
offset = 0
# CRITICAL FIX: Allocate stack space for data register parameters (d0-d7)
# These must be saved immediately in prologue before they can be clobbered
# EXCEPT for native functions - they use registers directly without stack
# IMPORTANT: All register params use fixed 4-byte slots (move.l always stores 4 bytes)
# regardless of their declared type (byte/word/long). This prevents overwriting adjacent frame data.
saved_reg_params = {} # Maps param name -> (register, offset)
if not proc.native:
for param in params:
reg = param.register
if reg and reg != 'None' and reg.startswith('d'):
# Data register parameter - needs 4-byte stack slot (always, for safety)
# We store via move.l regardless of type, so always reserve 4 bytes
offset += 4 # Fixed 4-byte allocation for register params
# Align offset to 4-byte boundary for safety
if offset & 3:
offset += (4 - (offset & 3))
saved_reg_params[param.name] = (reg, offset)
# Add to locals_info so VarRef lookups find it
locals_info.append((param.name, param.ptype, offset))
# Collect all local variables and for loop counters
def collect_locals(stmts):
nonlocal offset
for stmt in stmts:
if isinstance(stmt, ast.VarDecl):
size = ast.type_size(stmt.vtype) if stmt.vtype else 4
offset += size
# Align offset to even boundary for 68000 (word/long access requires even addresses)
if offset & 1:
offset += 1
locals_info.append((stmt.name, stmt.vtype, offset))
elif isinstance(stmt, ast.ForLoop):
# For loop counter - only allocate if not already declared
existing = next((l for l in locals_info if l[0] == stmt.var), None)
if not existing:
size = 4 # int is 4 bytes
offset += size
# Align offset to even boundary
if offset & 1:
offset += 1
locals_info.append((stmt.var, 'int', offset))
# Recursively collect locals in loop body
collect_locals(stmt.body)
elif isinstance(stmt, ast.While):
# Recursively collect locals in loop body
collect_locals(stmt.body)
elif isinstance(stmt, ast.DoWhile):
# Recursively collect locals in loop body
collect_locals(stmt.body)
elif isinstance(stmt, ast.RepeatLoop):
# Recursively collect locals in loop body
collect_locals(stmt.body)
elif isinstance(stmt, ast.If):
# Recursively collect locals in both branches
collect_locals(stmt.then_body)
if stmt.else_body:
collect_locals(stmt.else_body)
collect_locals(proc.body)
# Round up offset to maintain alignment
total_local_size = (offset + 3) & ~3 # Align to 4 bytes
return params, locals_info, total_local_size, saved_reg_params
def _substitute_asm_vars(self, asm_content, params, locals_info, frame_reg="a6"):
"""Substitute @varname references in asm blocks with actual addresses/registers.
Substitution rules:
- @param_name: Register parameter -> register name; Stack parameter -> offset(frame_reg)
- @local_var: -> -offset(frame_reg)
- @global_var: -> label name
Returns tuple of (substituted_content, comments) where comments document substitutions.
"""
return substitute_asm_vars(
asm_content,
params,
locals_info,
self.globals,
self.extern_vars,
frame_reg,
self._fail,
)
def _emit_expr(self, expr, params, locals_info, reg_left="d0", reg_right="d1", target_type=None, frame_reg="a6"):
# Evaluate expr into reg_left (d0). If needing second register, use reg_right (d1).
# params is now a list of Param objects
# locals_info is list of (name, type, offset) tuples
# target_type is the expected type for this expression (for sizing)
# frame_reg is the register used for frame pointer (default a6, but may be a4 etc if using optimization)
# Defensive: ensure register names are never None
if reg_left is None:
reg_left = "d0"
if reg_right is None:
reg_right = "d1"
# Additional safety: assert registers are valid
assert reg_left is not None and isinstance(reg_left, str), f"Invalid reg_left: {reg_left}"
assert reg_right is not None and isinstance(reg_right, str), f"Invalid reg_right: {reg_right}"
# Normalize non-AST or None expressions first
expr = self._normalize_expr(expr)
if isinstance(expr, ast.Number):
return [f" move.l #{expr.value},{reg_left}"]
if isinstance(expr, ast.MemberAccess):
# Read struct member: var.field, arr[idx].field, or (*ptr).field
code = []
base = expr.base
field = expr.field
# Handle dereferenced pointer: (*ptr).field
if isinstance(base, ast.UnaryOp) and base.op == '*':
# Dereference pointer and access member
ptr_operand = base.operand
# CRITICAL FIX: If pointer is a simple variable reference, load it directly
# from memory to avoid issues with stale register values after function calls
if isinstance(ptr_operand, ast.VarRef):
var_name = ptr_operand.name
local_info = next((l for l in locals_info if l[0] == var_name), None)
if local_info:
# Load pointer directly from local variable into a0
_, _, offset = local_info
code.append(f" move.l {self._frame_offset(offset, frame_reg)},a0")
else:
# Not a local variable, might be parameter - use normal evaluation
ptr_code = self._emit_expr(ptr_operand, params, locals_info, "a0", "d0", target_type=None, frame_reg=frame_reg)
code.extend(ptr_code)
if ptr_code and "a0" not in ptr_code[-1]:
code.append(f" move.l d0,a0")
else:
# Complex expression for pointer - evaluate it
ptr_code = self._emit_expr(ptr_operand, params, locals_info, "a0", "d0", target_type=None, frame_reg=frame_reg)
code.extend(ptr_code)
# Move result to a0 if not already there
if ptr_code and "a0" not in ptr_code[-1]:
code.append(f" move.l d0,a0")
# Try to infer struct type from various sources
struct_type = None
# Try to get type info from locals (variables have vtype info in locals_info)
if isinstance(ptr_operand, ast.VarRef):
var_name = ptr_operand.name
# Look in locals_info which has (name, vtype, offset)
local_info = next((l for l in locals_info if l[0] == var_name), None)
if local_info and len(local_info) > 1:
vtype = local_info[1]
# vtype might be like "bullet*" or "Enemy*"
if vtype and vtype.endswith('*'):
struct_type = vtype.rstrip('*').strip()
# Check function parameters if not found in locals
if not struct_type:
param_obj = next((p for p in params if p.name == var_name), None)
if param_obj and param_obj.ptype and param_obj.ptype.endswith('*'):
struct_type = param_obj.ptype.rstrip('*').strip()
# Fallback: try name-based inference
if not struct_type:
for sname in self.struct_info:
if var_name.startswith(sname.lower()) or var_name.endswith('_' + sname.lower()):
struct_type = sname
break
if struct_type and struct_type in self.struct_info:
sinfo = self.struct_info[struct_type]
if field in sinfo['fields']:
fs = sinfo['fields'][field]
offset = fs['offset']
suffix = { 'b': '.b', 'w': '.w', 'l': '.l' }.get(fs['size_suffix'], '.l')
# Dereference pointer with offset: field at (a0, offset)
# Clear register first for byte/word to avoid garbage in upper bits
if suffix in ('.b', '.w'):
code.append(f" clr.l {reg_left}")
if offset == 0:
code.append(f" move{suffix} (a0),{reg_left}")
else:
code.append(f" move{suffix} {offset}(a0),{reg_left}")
return code
else:
return [f" ; unknown field {field} in dereferenced struct", f" move.l #0,{reg_left}"]
else:
# Last resort: assume x.l at 0, y.l at 4, active.b at 8 (common pattern)
offset = 0
if field == 'x':
offset = 0
suffix = '.l'
elif field == 'y':
offset = 4
suffix = '.l'
elif field == 'active':
offset = 8
suffix = '.b'
elif field == 'dir':
offset = 9
suffix = '.b'
else:
return [f" ; unknown field {field} in dereferenced struct", f" move.l #0,{reg_left}"]
# Generate code with guessed offset (clear register for byte/word)
if suffix in ('.b', '.w'):
code.append(f" clr.l {reg_left}")
if offset == 0:
code.append(f" move{suffix} (a0),{reg_left}")
else:
code.append(f" move{suffix} {offset}(a0),{reg_left}")
return code
# Handle simple variable member access
elif isinstance(base, ast.VarRef):
name = base.name
sinfo = self.struct_info.get(name)
if not sinfo or field not in sinfo['fields']:
self._fail(f"Unknown struct member '{name}.{field}'")
fs = sinfo['fields'][field]
suffix = { 'b': '.b', 'w': '.w', 'l': '.l' }.get(fs['size_suffix'], '.l')
# Direct absolute access using equate emitted: name_field equ name+off
# Clear register first for byte/word to avoid garbage in upper bits
if suffix in ('.b', '.w'):
code.append(f" clr.l {reg_left}")
code.append(f" move{suffix} {name}_{field},{reg_left}")
return code
# Handle array element member access
elif isinstance(base, ast.ArrayAccess):
name = base.name
sinfo = self.struct_info.get(name)
if not sinfo or field not in sinfo['fields']:
return [f" ; unknown struct array/member {name}.{field}", f" move.l #0,{reg_left}"]
fs = sinfo['fields'][field]
stride = sinfo['size']
suffix = { 'b': '.b', 'w': '.w', 'l': '.l' }.get(fs['size_suffix'], '.l')
# Base address
code.append(f" lea {name},a0")
# Evaluate index into d1 (support only 1D for now)
if len(base.indices) != 1:
self._fail(f"Only 1D array indexing supported for structs; '{name}' has {len(base.indices)} dimensions")
idx_code = self._emit_expr(base.indices[0], params, locals_info, "d1", "d2", target_type="int", frame_reg=frame_reg)
code.extend(idx_code)
# Scale index by stride
if stride and (stride & (stride - 1)) == 0:
# power of two -> shift
shift = 0
tmp = stride
while tmp > 1:
shift += 1
tmp >>= 1
# split shifts into max 8 per instruction for 68000
while shift >= 8:
code.append(f" lsl.l #8,d1")
shift -= 8
if shift > 0:
code.append(f" lsl.l #{shift},d1")
elif stride <= 32767:
code.append(f" mulu.w #{stride},d1")
else:
# Fallback: multiply by constant using shifts/adds
code.append(f" move.l d1,d2")
code.append(f" clr.l d1")
k = stride
bit = 0
while k:
if k & 1:
if bit == 0:
code.append(f" add.l d2,d1")
else:
# shift temp d3 = d2 << bit, then add
code.append(f" move.l d2,d3")
sb = bit
while sb >= 8:
code.append(f" lsl.l #8,d3")
sb -= 8
if sb > 0:
code.append(f" lsl.l #{sb},d3")
code.append(f" add.l d3,d1")
bit += 1
k >>= 1
# Add field offset
off = sinfo['fields'][field]['offset']
if off:
code.append(self._emit_add_immediate(" ", "d1", off))
# Load value (clear destination register first for byte/word to avoid garbage in upper bits)
# CRITICAL: Don't clear if reg_left == d1 (index reg), clear after the load instead
if suffix in ('.b', '.w'):
if reg_left == 'd1':
# Index is in d1, must load first then extend
code.append(f" move{suffix} (a0,d1.l),d1")
if suffix == '.b':
code.append(f" and.l #$FF,d1")
else: # .w
code.append(f" and.l #$FFFF,d1")
else:
# Normal case: clear dest then load
code.append(f" clr.l {reg_left}")
code.append(f" move{suffix} (a0,d1.l),{reg_left}")
else:
# Long: no clearing needed
code.append(f" move{suffix} (a0,d1.l),{reg_left}")
return code
else:
return [f" ; unsupported member access base: {base}", f" move.l #0,{reg_left}"]
if isinstance(expr, ast.ArrayAccess):
# Array element access: arr[i] or matrix[row][col]
code = []
name = expr.name
# Find array in locals or globals
local_info = next((l for l in locals_info if l[0] == name), None)
if local_info:
var_name, var_type, var_offset = local_info
# Check if this is a pointer variable (not an array)
if var_type and var_type.endswith('*'):
# Pointer indexing: ptr[index]
# 1. Load the pointer value
# 2. Calculate offset based on element size
# 3. Load element from pointer + offset
# Determine element size from pointer type (e.g., "byte*" -> 1 byte)
base_type = var_type[:-1] # Remove the '*'
elem_bytes = 1 # default to byte
if base_type == 'word':
elem_bytes = 2
elif base_type in ('long', 'int'):
elem_bytes = 4
shift_amount = 0
if elem_bytes == 2:
shift_amount = 1
elif elem_bytes == 4:
shift_amount = 2
# Load pointer into a0
code.append(f" move.l {self._frame_offset(var_offset, frame_reg)},a0")
if len(expr.indices) == 1:
# Single index: ptr[index]
if isinstance(expr.indices[0], ast.Number):
# Constant index
index_val = expr.indices[0].value
offset = index_val * elem_bytes
size_suffix = ast.size_suffix(elem_bytes)
if offset == 0:
code.append(f" move{size_suffix} (a0),{reg_left}")
else:
code.append(f" move{size_suffix} {offset}(a0),{reg_left}")
else:
# Variable index
index_code = self._emit_expr(expr.indices[0], params, locals_info, "d1", "d2", target_type="int", frame_reg=frame_reg)
code.extend(index_code)
# Scale index by element size if needed
if shift_amount > 0:
code.append(f" lsl.l #{shift_amount},d1 ; multiply index by {elem_bytes}")
# Load element
size_suffix = ast.size_suffix(elem_bytes)
code.append(f" move{size_suffix} (a0,d1.l),{reg_left}")
else:
# Multi-dimensional indexing through pointer (not common, but handle it)
code.append(f" ; multidimensional pointer indexing not yet supported")
code.append(f" move.l #0,{reg_left}")
return code
else:
# Local array (not yet supported - would need to allocate on stack)
code.append(f" ; local arrays not yet supported: {name}")
code.append(f" move.l #0,{reg_left}")
return code
# Global array or pointer access
if len(expr.indices) == 1:
# 1D array: arr[index] OR pointer dereference: ptr[index]
# Distinguish between true arrays and pointer variables
is_array = name in self.array_dims
if is_array:
# TRUE ARRAY: Calculate base_address + index * element_size
elem_size_suffix = self.array_dims[name]['size']
if elem_size_suffix == 'b':
elem_bytes = 1
shift_amount = 0 # no shift for bytes
elif elem_size_suffix == 'w':
elem_bytes = 2
shift_amount = 1 # shift by 1 for words
else: # 'l'
elem_bytes = 4
shift_amount = 2
# Check if index is a constant
if isinstance(expr.indices[0], ast.Number):
# Constant index: generate direct offset
index_val = expr.indices[0].value
offset = index_val * elem_bytes
size_suffix = ast.size_suffix(elem_bytes)
if offset == 0:
code.append(f" move{size_suffix} {name},{reg_left}")
else:
code.append(f" move{size_suffix} {name}+{offset},{reg_left}")
else:
# Variable index: generate runtime calculation
code.append(f" lea {name},a0")
# Evaluate index into d1
index_code = self._emit_expr(expr.indices[0], params, locals_info, "d1", "d2", target_type="int", frame_reg=frame_reg)
code.extend(index_code)
# Scale index by element size if needed
if shift_amount > 0:
code.append(f" lsl.l #{shift_amount},d1 ; multiply index by {elem_bytes}")
# Load element with correct size
size_suffix = ast.size_suffix(elem_bytes)
code.append(f" move{size_suffix} (a0,d1.l),{reg_left}")
else:
# POINTER VARIABLE: Load pointer value, then dereference
# When a non-array global is indexed, treat it as a byte pointer by default
# (since there's no type information about what it points to)
elem_bytes = 1 # Default to byte pointer
shift_amount = 0 # No shift for bytes
# Load the pointer value into a0
code.append(f" move.l {name},a0")
# Evaluate index into d1
index_code = self._emit_expr(expr.indices[0], params, locals_info, "d1", "d2", target_type="int", frame_reg=frame_reg)
code.extend(index_code)
# For byte pointers, no scaling needed (shift_amount = 0)
# Load byte element through pointer
code.append(f" move.b (a0,d1.l),{reg_left}")
# Zero-extend byte to long
code.append(f" andi.l #$FF,{reg_left}")
elif len(expr.indices) == 2:
# 2D array: matrix[row][col]
# Calculate: base + (row * col_count + col) * element_size
# Get array dimensions and element size
elem_size = 'l'
elem_bytes = 4
col_count = None
if name in self.array_dims:
array_info = self.array_dims[name]
dims = array_info['dims']
elem_size = array_info.get('size', 'l')
if elem_size == 'b':
elem_bytes = 1
elif elem_size == 'w':
elem_bytes = 2
else:
elem_bytes = 4
if len(dims) >= 2:
col_count = dims[1]
# Check if both indices are constants
if isinstance(expr.indices[0], ast.Number) and isinstance(expr.indices[1], ast.Number):
# Both constant: compute offset at compile time
row_val = expr.indices[0].value
col_val = expr.indices[1].value
if col_count is None:
self._fail(f"Cannot determine column count for 2D array '{name}' - declare with explicit dimensions like 'int[3][5]'")
offset = (row_val * col_count + col_val) * elem_bytes
size_suffix = ast.size_suffix(elem_bytes)
if offset == 0:
code.append(f" move{size_suffix} {name},{reg_left}")
else:
code.append(f" move{size_suffix} {name}+{offset},{reg_left}")
else:
# At least one variable index: generate runtime calculation
code.append(f" ; 2D array access: {name}")
# Evaluate row index into d1
row_code = self._emit_expr(expr.indices[0], params, locals_info, "d1", "d2", target_type="int", frame_reg=frame_reg)
code.extend(row_code)
# Save row in d2
code.append(f" move.l d1,d2 ; save row")
# Evaluate col index into d1
col_code = self._emit_expr(expr.indices[1], params, locals_info, "d1", "a0", target_type="int", frame_reg=frame_reg)
code.extend(col_code)
# Get column count
if col_count is not None:
# Calculate offset: row * col_count + col
code.append(f" mulu.w #{col_count},d2 ; row * col_count")
else:
self._fail(f"Cannot determine column count for 2D array '{name}'; declare with explicit dimensions like 'int[3][5]' or use 1D arrays")
code.append(f" add.l d1,d2 ; + col")
# Element size scaling based on type
shift_map = {'b': 0, 'w': 1, 'l': 2}
shift = shift_map.get(elem_size, 2)
if shift > 0:
code.append(f" lsl.l #{shift},d2 ; * {1 << shift} (element size)")
# Now load base address and access element
move_suffix = {'b': '.b', 'w': '.w', 'l': '.l'}.get(elem_size, '.l')
code.append(f" lea {name},a0")
code.append(f" move{move_suffix} (a0,d2.l),{reg_left}")
else:
code.append(f" ; arrays with >2 dimensions not supported")
code.append(f" move.l #0,{reg_left}")
return code
if isinstance(expr, ast.VarRef):
name = expr.name
# Check if it's a constant first
if name in self.constants:
const_value = self.constants[name]
return [f" move.l #{const_value},{reg_left}"]
# Check if it's a local variable first (this includes saved register parameters)
local_info = next((l for l in locals_info if l[0] == name), None)
if local_info:
name, vtype, offset = local_info
size = ast.type_size(vtype) if vtype else 4
suffix = ast.size_suffix(size)
code = []
if size == 1:
# 8-bit load with sign/zero extension based on type
code.append(f" move.b {-offset}({frame_reg}),{reg_left}")
if vtype and ast.is_signed(vtype):
code.append(f" ext.w {reg_left}")
code.append(f" ext.l {reg_left}")
else:
code.append(f" andi.l #$FF,{reg_left}")
return code
elif size == 2:
# 16-bit load with sign/zero extension based on type
code.append(f" move.w {-offset}({frame_reg}),{reg_left}")
if vtype and ast.is_signed(vtype):
code.append(f" ext.l {reg_left}")
else:
code.append(f" andi.l #$FFFF,{reg_left}")
return code
else:
code.append(f" move.l {-offset}({frame_reg}),{reg_left}")
return code
# Check if it's a parameter (for address register parameters that aren't saved)
param_obj = next((p for p in params if p.name == name), None)
if param_obj:
reg = param_obj.register
if reg == 'None':
reg = None
if reg:
# Parameter is in a register (only for address registers like a0-a3)
# Data register parameters are saved to locals_info and handled above
if reg != reg_left:
return [f" move.l {reg},{reg_left}"]
else:
return []
else:
# Stack parameter (no register specified)
stack_params = [p for p in params if not (p.register and p.register != 'None')]
if param_obj in stack_params:
idx = stack_params.index(param_obj)
off = 8 + 4 * idx
# Get parameter type and size
param_type = param_obj.ptype if param_obj.ptype else 'long'
param_size = ast.type_size(param_type) if param_type else 4
if param_size == 1:
# Byte parameter packed in low byte of pushed long.
# Use signed/unsigned extension based on declared type.
if param_type and ast.is_signed(param_type):
return [
f" move.l {off}(a6),{reg_left}",
f" ext.w {reg_left}",
f" ext.l {reg_left}"
]
return [
f" move.l {off}(a6),{reg_left}",
f" andi.l #$FF,{reg_left}"
]
elif param_size == 2:
# Word parameter packed in low word of pushed long.
if param_type and ast.is_signed(param_type):
return [
f" move.l {off}(a6),{reg_left}",
f" ext.l {reg_left}"
]
return [
f" move.l {off}(a6),{reg_left}",
f" andi.l #$FFFF,{reg_left}"
]
else:
return [f" move.l {off}(a6),{reg_left}"]
else:
return [f" ; parameter {name} not found in stack_params", f" move.l #0,{reg_left}"]
# Check globals (moved outside param_obj block so globals are checked even if not a parameter)
if name in self.globals:
size = self.globals.get(name, 'l')
suffix = {'b': '.b', 'w': '.w', 'l': '.l'}.get(size, '.l')
if suffix == '.b':
return [
f" move.b {name},{reg_left}",
f" andi.l #$FF,{reg_left}"
]
elif suffix == '.w':
return [
f" move.w {name},{reg_left}",
f" andi.l #$FFFF,{reg_left}"
]
else:
return [f" move.l {name},{reg_left}"]
# Check extern vars
if name in self.extern_vars:
size = self.extern_vars.get(name, 'l')
suffix = {'b': '.b', 'w': '.w', 'l': '.l'}.get(size, '.l')
if suffix == '.b':
return [
f" move.b {name},{reg_left}",
f" andi.l #$FF,{reg_left}"
]
elif suffix == '.w':
return [
f" move.w {name},{reg_left}",
f" andi.l #$FFFF,{reg_left}"
]
else: