github/workflows/pycopy-test: Upgrade Pycopy to 3.6.1.
[ScratchABlock.git] / cprinter.py
blob712d1661c49c73185366b54e1d8a78f09d9a0d21
1 import sys
3 from utils import pairwise, natural_sort_key
4 from cfgutils import swap_if_branches
5 import progdb
7 no_dead = False
9 def find_used_labels(cfg):
10 labels = set()
11 for addr, nxt in pairwise(cfg.iter_rev_postorder()):
12 info = cfg[addr]
13 bblock = info["val"]
14 succs = cfg.sorted_succ(addr)
15 if len(succs) > 1 and nxt == succs[0]:
16 swap_if_branches(cfg, addr)
17 succs = cfg.sorted_succ(addr)
18 for succ in succs:
19 cond = cfg.edge(addr, succ).get("cond")
20 if not cond and nxt and succ == nxt:
21 continue
22 labels.add(succ)
23 return labels
26 def print_inst(inst):
27 if inst.op == "DEAD" and no_dead:
28 return
29 return str(inst)
31 def dump_c(cfg, stream=sys.stdout):
32 labels = find_used_labels(cfg)
33 func_start = True
34 for addr, nxt in pairwise(cfg.iter_rev_postorder()):
35 info = cfg[addr]
36 bblock = info["val"]
37 if func_start:
38 label = cfg.props["name"]
39 if not label:
40 label = cfg.parser.label_from_addr(bblock.addr)
41 if label[0].isdigit():
42 label = "fun_" + label
43 if ("estimated_params" in cfg.props):
44 print("// Estimated params: %s" % sorted(list(cfg.props["estimated_params"])), file=stream)
45 if cfg.props["trailing_jumps"]:
46 print("// Trailing jumps not removed, not rendering CFG edges as jumps", file=stream)
48 func_props = progdb.FUNC_DB.get(label, {})
49 params = ""
50 if "params" in func_props:
51 params = sorted(func_props["params"], key=natural_sort_key)
52 params = ", ".join(["u32 " + str(r) + "_0" for r in params])
53 print("void %s(%s)\n{" % (label, params), file=stream)
54 func_start = False
55 if addr in labels:
56 print("\nl%s:" % addr, file=stream)
57 bblock.dump(stream, indent=1, printer=print_inst)
58 if not cfg.props["trailing_jumps"]:
59 for succ in cfg.succ(addr):
60 cond = cfg.edge(addr, succ).get("cond")
61 if not cond and nxt and succ == nxt:
62 continue
63 stream.write(" ")
64 if cond:
65 stream.write("if %s " % cond)
66 print("goto l%s;" % succ, file=stream)
68 print("}", file=stream)