-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler_opt.py
More file actions
88 lines (67 loc) · 2.39 KB
/
compiler_opt.py
File metadata and controls
88 lines (67 loc) · 2.39 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
from ast_nodes import *
class OptimizingCompiler:
def compile(self, ast):
condition, action = ast
program = []
# -------------------------
# PASS 1: BASE GENERATION
# -------------------------
self.emit_condition(condition, program)
program.append("FETCH R5 R0")
# -------------------------
# PASS 2: OPTIMIZATION PIPE
# -------------------------
program = self.fuse_instructions(program)
program = self.remove_redundant(program)
return program
# -------------------------
# AST → ISA
# -------------------------
def emit_condition(self, node, program):
if isinstance(node, Condition):
if node.op == "in":
program.append("IN_INDEX R1 R0")
elif isinstance(node, Not):
program.append("BLACKLIST R3 R0")
program.append("NOT R3 R3")
elif isinstance(node, And):
self.emit_condition(node.left, program)
self.emit_condition(node.right, program)
program.append("AND R4 R1 R3")
elif isinstance(node, Or):
self.emit_condition(node.left, program)
self.emit_condition(node.right, program)
program.append("OR R4 R1 R3")
# -------------------------
# PASS 3: FUSION
# -------------------------
def fuse_instructions(self, program):
fused = []
skip = False
for i in range(len(program)):
if skip:
skip = False
continue
curr = program[i]
nxt = program[i + 1] if i + 1 < len(program) else None
# FUSION RULE 1:
# IN_INDEX + BLACKLIST → single gate
if curr == "IN_INDEX R1 R0" and nxt == "BLACKLIST R3 R0":
fused.append("CHECK_WORD R1 R3 R0")
skip = True
continue
fused.append(curr)
return fused
# -------------------------
# PASS 4: DEAD CODE REMOVAL
# -------------------------
def remove_redundant(self, program):
cleaned = []
seen = set()
for instr in program:
# remove duplicate consecutive instructions
if instr in seen and instr.startswith(("IN_INDEX", "BLACKLIST")):
continue
cleaned.append(instr)
seen.add(instr)
return cleaned