Skip to content
This repository was archived by the owner on Apr 25, 2026. It is now read-only.

Commit 7c9792c

Browse files
committed
add basic DCE
1 parent ac47541 commit 7c9792c

1 file changed

Lines changed: 59 additions & 5 deletions

File tree

hypergl/hgl_ir.py

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,72 @@ def __init__(self, cmd: CommandBuffer, env: dict):
2424
self.defines = {}
2525

2626
def compile(self, source_code: str):
27-
# Preprocessing
27+
# 1. Preprocess
2828
expanded = self._preprocess(source_code)
2929
final_source = self._apply_defines(expanded)
3030

31-
# Setup for error reporting
32-
self.source = final_source
33-
self.source_lines = final_source.split('\n')
31+
# 2. Tokenize
32+
raw_tokens = self._tokenize(final_source)
3433

35-
self.tokens = self._tokenize(final_source)
34+
# 3. Optimize (Dead Code Elimination)
35+
self.tokens = self._dce_tokens(raw_tokens)
36+
37+
# 4. Parse / Emit
3638
self.pos = 0
3739
while self.pos < len(self.tokens):
3840
self._parse_statement()
41+
42+
def _dce_tokens(self, tokens):
43+
"""
44+
Performs basic Dead Code Elimination.
45+
Removes instructions that are unreachable.
46+
"""
47+
optimized = []
48+
i = 0
49+
depth = 0 # Track block depth for control flow
50+
is_dead = False # Flag for unreachable code
51+
52+
while i < len(tokens):
53+
tk = tokens[i]
54+
55+
# If we are in a dead block, we only look for the closing brace or a label
56+
# Note: HGL-IR doesn't have explicit GOTO in source, so labels are implicit in blocks.
57+
# But 'ret' makes subsequent code in the same block dead.
58+
59+
if is_dead:
60+
# If we see a closing brace, we might be exiting the dead block scope
61+
if tk.type == 'RBRACE':
62+
depth -= 1
63+
if depth < 0: # Should not happen in valid code, but safety check
64+
is_dead = False
65+
# Keep the brace to maintain structure integrity for the parser
66+
optimized.append(tk)
67+
elif tk.type == 'LBRACE':
68+
depth += 1 # Nested dead code
69+
70+
# Skip everything else
71+
i += 1
72+
continue
73+
74+
# --- Check for Terminators ---
75+
if tk.type == 'ID' and tk.value == 'ret':
76+
optimized.append(tk)
77+
# Everything after 'ret' in the current block is dead
78+
is_dead = True
79+
depth = 0 # Reset depth tracking for the dead region
80+
i += 1
81+
continue
82+
83+
# --- Normal Flow ---
84+
if tk.type == 'LBRACE':
85+
depth += 1
86+
elif tk.type == 'RBRACE':
87+
depth -= 1
88+
89+
optimized.append(tk)
90+
i += 1
91+
92+
return optimized
3993

4094
# --- Error Reporting ---
4195
def _fail(self, msg: str, token: Token | None = None):

0 commit comments

Comments
 (0)