有几条能被窥孔化简

👁️ 2 人浏览 💬 0 人评论 ❤️ 添加收藏

按模型,[y=x*1, z=x*0, r=a+b]count_simplified 交回几?

贯穿本节的 IR 模型(判题机没 gcc,这是它的确定模型):程序是三地址码元组列表,每条 (dst, op, a, b)——opconst/copy/+/-/*,操作数 a/b 是整数(常量)或字符串(变量名)。

窥孔优化:peep1 单条化简(x*1/x+0copy xx*0const 0);peephole 逐条化简;is_nopx=copy x 空操作、strip_nops 删空操作、count_simplified 数能化简的。

def peep1(ins):
    """单条窥孔化简:x*1 或 x+0 -> copy x;x*0 -> const 0;其它原样。"""
    (dst, op, a, b) = ins
    if op == "*" and b == 1:
        return (dst, "copy", a, None)
    if op == "+" and b == 0:
        return (dst, "copy", a, None)
    if op == "*" and b == 0:
        return (dst, "const", 0, None)
    return ins


def peephole(prog):
    """对每条指令做一次窥孔化简。"""
    return [peep1(ins) for ins in prog]


def is_nop(ins):
    """x = copy x 是空操作(什么也没做)。"""
    return ins[1] == "copy" and ins[0] == ins[2]


def strip_nops(prog):
    """把空操作删掉。"""
    return [ins for ins in prog if not is_nop(ins)]


def count_simplified(prog):
    """有几条能被窥孔化简(化简后和原来不一样)。"""
    return sum(1 for ins in prog if peep1(ins) != ins)

print(count_simplified([("y", "*", "x", 1), ("z", "*", "x", 0), ("r", "+", "a", "b")]))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论