当前位置: 首页>>代码示例>>Python>>正文


Python Builder.at_front方法代码示例

本文整理汇总了Python中pykit.ir.Builder.at_front方法的典型用法代码示例。如果您正苦于以下问题:Python Builder.at_front方法的具体用法?Python Builder.at_front怎么用?Python Builder.at_front使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pykit.ir.Builder的用法示例。


在下文中一共展示了Builder.at_front方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TestBuilder

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
class TestBuilder(unittest.TestCase):

    def setUp(self):
        self.f = Function("testfunc", ['a'],
                          types.Function(types.Float32, [types.Int32]))
        self.b = Builder(self.f)
        self.b.position_at_end(self.f.add_block('entry'))
        self.a = self.f.get_arg('a')

    def test_basic_builder(self):
        v = self.b.alloca(types.Pointer(types.Float32), [])
        result = self.b.mul(types.Int32, [self.a, self.a], result='r')
        c = self.b.convert(types.Float32, [result])
        self.b.store(c, v)
        val = self.b.load(types.Float32, [v])
        self.b.ret(val)
        # print(string(self.f))
        self.assertEqual(str(self.f).strip(), basic_expected)

    def test_splitblock(self):
        old, new = self.b.splitblock('newblock')
        with self.b.at_front(old):
            self.b.add(types.Int32, [self.a, self.a])
        with self.b.at_end(new):
            self.b.div(types.Int32, [self.a, self.a])
        # print(string(self.f))
        self.assertEqual(split_expected, string(self.f))

    def test_loop_builder(self):
        square = self.b.mul(types.Int32, [self.a, self.a])
        c = self.b.convert(types.Float32, [square])
        self.b.position_after(square)
        _, block = self.b.splitblock('start', terminate=True)
        self.b.position_at_end(block)

        const = partial(Const, type=types.Int32)
        cond, body, exit = self.b.gen_loop(const(5), const(10), const(2))
        with self.b.at_front(body):
            self.b.print_(c)
        with self.b.at_end(exit):
            self.b.ret(c)

        # print(string(self.f))
        # verify.verify(self.f)
        # self.assertEqual(loop_expected, string(self.f))

# TestBuilder('test_basic_builder').debug()
# TestBuilder('test_splitblock').debug()
# TestBuilder('test_loop_builder').debug()
# unittest.main()
开发者ID:aburan28,项目名称:pykit,代码行数:52,代码来源:test_builder.py

示例2: test_exc_rewrite

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
    def test_exc_rewrite(self):
        func = Function("foo", [], types.Function(types.Void, ()))
        entry = func.new_block("entry")
        catch_block = func.new_block("catch")
        b = Builder(func)

        with b.at_front(entry):
            b.exc_setup([catch_block])
            b.exc_throw(Const(StopIteration, types.Exception))
        with b.at_front(catch_block):
            b.exc_catch([Const(Exception, types.Exception)])

        local_exceptions.run(func, {})
        print(func)
开发者ID:aterrel,项目名称:pykit,代码行数:16,代码来源:test_opt_local_exception.py

示例3: run

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
def run(func, env=None, return_block=None):
    """
    Rewrite 'ret' operations into jumps to a return block and assignments
    to a return variable.
    """
    b = Builder(func)
    return_block = return_block or func.new_block("pykit.return")

    # Allocate return variable
    if not func.type.restype.is_void:
        with b.at_front(func.startblock):
            return_var = b.alloca(types.Pointer(func.type.restype))
            b.store(Undef(func.type.restype), return_var)
    else:
        return_var = None

    # Repace 'ret' instructions with jumps and assignments
    for op in func.ops:
        if op.opcode == "ret":
            b.position_after(op)
            if return_var:
                b.store(op.args[0], return_var)
            b.jump(return_block)
            op.delete()

    with b.at_end(return_block):
        if return_var:
            result = b.load(return_var)
        else:
            result = None

        b.ret(result)
开发者ID:flypy,项目名称:pykit,代码行数:34,代码来源:ret.py

示例4: TestBuilder

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
class TestBuilder(unittest.TestCase):

    def setUp(self):
        self.f = Function("testfunc", ['a'],
                          types.Function(types.Float32, [types.Int32]))
        self.b = Builder(self.f)
        self.b.position_at_end(self.f.new_block('entry'))
        self.a = self.f.get_arg('a')

    def test_basic_builder(self):
        v = self.b.alloca(types.Pointer(types.Float32), [])
        result = self.b.mul(types.Int32, [self.a, self.a], result='r')
        c = self.b.convert(types.Float32, [result])
        self.b.store(c, v)
        val = self.b.load(types.Float32, [v])
        self.b.ret(val)
        # print(string(self.f))
        assert interp.run(self.f, args=[10]) == 100

    def test_splitblock(self):
        old, new = self.b.splitblock('newblock')
        with self.b.at_front(old):
            self.b.add(types.Int32, [self.a, self.a])
        with self.b.at_end(new):
            self.b.div(types.Int32, [self.a, self.a])
        self.assertEqual(opcodes(self.f), ['add', 'div'])

    def test_loop_builder(self):
        square = self.b.mul(types.Int32, [self.a, self.a])
        c = self.b.convert(types.Float32, [square])
        self.b.position_after(square)
        _, block = self.b.splitblock('start', terminate=True)
        self.b.position_at_end(block)

        const = partial(Const, type=types.Int32)
        cond, body, exit = self.b.gen_loop(const(5), const(10), const(2))
        with self.b.at_front(body):
            self.b.print(c)
        with self.b.at_end(exit):
            self.b.ret(c)

        self.assertEqual(interp.run(self.f, args=[10]), 100.0)
开发者ID:pombredanne,项目名称:pykit,代码行数:44,代码来源:test_builder.py

示例5: insert_phis

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
def insert_phis(func, cfg, allocas):
    """Insert φs in the function given the set of promotable stack variables"""
    builder = Builder(func)
    phis = {} # phi -> alloca
    for block in func.blocks:
        if len(cfg.predecessors(block)) > 1:
            with builder.at_front(block):
                for alloca in allocas:
                    phi = builder.phi(alloca.type.base, [], [])
                    phis[phi] = alloca

    return phis
开发者ID:markflorisson,项目名称:pykit,代码行数:14,代码来源:cfa.py

示例6: insert_phis

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
def insert_phis(func, cfg, allocas):
    """Insert φs in the function given the set of promotable stack variables"""
    builder = Builder(func)
    predecessors = cfg.T # transpose CFG, block -> predecessors
    phis = {} # phi -> alloca
    for block in func.blocks:
        if len(predecessors[block]) > 1:
            with builder.at_front(block):
                for alloca in allocas:
                    args = [[], []] # predecessors, incoming_values
                    phi = builder.phi(alloca.type.base, args)
                    phis[phi] = alloca

    return phis
开发者ID:pombredanne,项目名称:pykit,代码行数:16,代码来源:cfa.py

示例7: Translate

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]

#.........这里部分代码省略.........
        op = Op(opcode, type, list(args))
        op.add_metadata({'lineno': self.lineno})
        self.builder.emit(op)
        return op

    def push_insert(self, opcode, *args):
        inst = self.insert(opcode, *args)
        self.push(inst)
        return inst

    def push(self, val):
        self.stack.append(val)

    def peek(self):
        """
        Take a peek at the top of stack.
        """
        if not self.stack:
            # Assuming the bytecode is valid, our predecessors must have left
            # some values on the stack.
            # return self._insert_phi()
            raise EmptyStackError
        else:
            return self.stack[-1]

    def pop(self):
        if not self.stack:
            # return self._insert_phi()
            raise EmptyStackError
        else:
            return self.stack.pop()

    def _insert_phi(self):
        with self.builder.at_front(self.curblock):
            phi = self.insert('phi', [], [])

        self.phis[self.curblock].append(phi)
        return phi

    def call(self, func, args=()):
        if not isinstance(func, Value):
            func = const(func)
        return self.push_insert('call', func, list(args))

    def call_pop(self, func, args=()):
        self.call(func, args)
        return self.pop()

    def binary_op(self, op):
        rhs = self.pop()
        lhs = self.pop()
        self.call(op, args=(lhs, rhs))

    def unary_op(self, op):
        tos = self.pop()
        self.call(op, args=(tos,))

    def jump(self, target):
        self.predecessors[target].add(self.curblock)
        self.insert('jump', target)

    def jump_if(self, cond, truebr, falsebr):
        self.predecessors[truebr].add(self.curblock)
        self.predecessors[falsebr].add(self.curblock)
        self.insert('cbranch', cond, truebr, falsebr)
开发者ID:flypy,项目名称:flypy,代码行数:69,代码来源:translation.py

示例8: PykitIRVisitor

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
class PykitIRVisitor(c_ast.NodeVisitor):
    """
    Map pykit IR in the form of polymorphic C to in-memory pykit IR.

        int function(float x) {
            int i = 0;        /* I am a comment */
            while (i < 10) {  /*: { "unroll": true } :*/
                x = call_external("sqrt", x * x);
            }
            return (int) x;
        }

    Attributes:
    """

    in_function = False

    def __init__(self, type_env=None):
        self.mod = Module()
        self.type_env = type_env or {}

        self.func = None
        self.builder = None
        self.local_vars = None
        self.allocas = None

        self.global_vars = {}
        self.functions = {}

    # ______________________________________________________________________

    @property
    def vars(self):
        if self.in_function:
            return self.local_vars
        else:
            return self.global_vars

    def enter_func(self):
        self.in_function = True
        self.local_vars = {}
        self.allocas = {}

    def leave_func(self):
        self.in_function = False
        self.mod.add_function(self.func)
        self.local_vars = None
        self.allocas = None
        self.func = None

    def visit(self, node, type=None):
        """
        Visit a node.

        :type: Whether we have a type for this opcode, which is an LHS type
               or a cast. E.g.:

              (Int) call(...)    // cast
              result = call(...) // assmnt, assuming 'result' is declared
              result = call(..., call(...)) // second 'call' isn't typed

        """
        self.type = type
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        # if visitor is None:
        #     raise SyntaxError(
        #         "Node %s not supported in %s:%s" % (node, node.coord.file,
        #                                             node.coord.line))
        return visitor(node)

    def visitif(self, node):
        if node:
            return self.visit(node)

    def visits(self, node):
        return list(map(self.visit, node))

    # ______________________________________________________________________

    def alloca(self, varname):
        if varname not in self.allocas:
            # Allocate variable with alloca
            with self.builder.at_front(self.func.startblock):
                type = types.Pointer(self.local_vars[varname])
                result = self.func.temp(varname)
                self.allocas[varname] = self.builder.alloca(type, [], result)

        return self.allocas[varname]

    def assignvar(self, varname, rhs):
        self.builder.store(rhs, self.alloca(varname))

    def assign(self, varname, rhs):
        if self.in_function:
            # Local variable
            type = self.local_vars[varname]
            self.assignvar(varname, self.visit(rhs, type=type))
        else:
            # Global variable
#.........这里部分代码省略.........
开发者ID:B-Rich,项目名称:pykit,代码行数:103,代码来源:cirparser.py

示例9: TestBuilder

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
class TestBuilder(unittest.TestCase):

    def setUp(self):
        self.f = Function("testfunc", ['a'],
                          types.Function(types.Float32, [types.Int32], False))
        self.b = Builder(self.f)
        self.b.position_at_end(self.f.new_block('entry'))
        self.a = self.f.get_arg('a')

    def test_basic_builder(self):
        v = self.b.alloca(types.Pointer(types.Float32))
        result = self.b.mul(self.a, self.a, result='r')
        c = self.b.convert(types.Float32, result)
        self.b.store(c, v)
        val = self.b.load(v)
        self.b.ret(val)
        # print(string(self.f))
        assert interp.run(self.f, args=[10]) == 100

    def test_splitblock(self):
        old, new = self.b.splitblock('newblock')
        with self.b.at_front(old):
            self.b.add(self.a, self.a)
        with self.b.at_end(new):
            self.b.div(self.a, self.a)
        self.assertEqual(opcodes(self.f), ['add', 'div'])

    def test_loop_builder(self):
        square = self.b.mul(self.a, self.a)
        c = self.b.convert(types.Float32, square)
        self.b.position_after(square)
        _, block = self.b.splitblock('start', terminate=True)
        self.b.position_at_end(block)

        const = partial(Const, type=types.Int32)
        cond, body, exit = self.b.gen_loop(const(5), const(10), const(2))
        with self.b.at_front(body):
            self.b.print(c)
        with self.b.at_end(exit):
            self.b.ret(c)

        self.assertEqual(interp.run(self.f, args=[10]), 100.0)

    def test_splitblock_preserve_phis(self):
        """
        block1:
            %0 = mul a a
            jump(newblock)

        newblock:
            %1 = phi([block1], [%0])
            ret %1
        """
        square = self.b.mul(self.a, self.a)
        old, new = self.b.splitblock('newblock', terminate=True)
        with self.b.at_front(new):
            phi = self.b.phi(types.Int32, [self.f.startblock], [square])
            self.b.ret(phi)

        # Now split block1
        self.b.position_after(square)
        block1, split = self.b.splitblock(terminate=True)

        phi, ret = new.ops
        blocks, values = phi.args
        self.assertEqual(blocks, [split])
开发者ID:flypy,项目名称:pykit,代码行数:68,代码来源:test_builder.py

示例10: PykitIRVisitor

# 需要导入模块: from pykit.ir import Builder [as 别名]
# 或者: from pykit.ir.Builder import at_front [as 别名]
class PykitIRVisitor(c_ast.NodeVisitor):
    """
    Map pykit IR in the form of polymorphic C to in-memory pykit IR.

        int function(float x) {
            int i = 0;        /* I am a comment */
            while (i < 10) {  /*: { "unroll": true } :*/
                x = call_external("sqrt", x * x);
            }
            return (int) x;
        }

    Attributes:
    """

    in_function = False

    def __init__(self, type_env=None):
        self.mod = Module()
        self.type_env = type_env or {}

        self.func = None
        self.builder = None
        self.local_vars = None
        self.allocas = None

        self.global_vars = {}
        self.functions = {}

    # ______________________________________________________________________

    @property
    def vars(self):
        if self.in_function:
            return self.local_vars
        else:
            return self.global_vars

    def enter_func(self):
        self.in_function = True
        self.local_vars = {}
        self.allocas = {}

    def leave_func(self):
        self.in_function = False
        self.mod.add_function(self.func)
        self.local_vars = None
        self.allocas = None
        self.func = None

    def visit(self, node, type=None):
        """
        Visit a node.

        :type: Whether we have a type for this opcode, which is an LHS type
               or a cast. E.g.:

              (Int) call(...)    // cast
              result = call(...) // assmnt, assuming 'result' is declared
              result = call(..., call(...)) // second 'call' isn't typed

        """
        self.type = type
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        # if visitor is None:
        #     raise SyntaxError(
        #         "Node %s not supported in %s:%s" % (node, node.coord.file,
        #                                             node.coord.line))
        return visitor(node)

    def visitif(self, node):
        if node:
            return self.visit(node)

    def visits(self, node):
        return list(map(self.visit, node))

    # ______________________________________________________________________

    def alloca(self, varname):
        if varname not in self.allocas:
            # Allocate variable with alloca
            with self.builder.at_front(self.func.blocks[0]):
                type = self.local_vars[varname]
                self.allocas[varname] = self.builder.alloca(type, [], varname)

        return self.allocas[varname]

    def assign(self, varname, rhs):
        if not self.in_function:
            error(rhs, "Assignment only allowed in functions")

        if varname not in self.allocas:
            # Allocate variable with alloca
            with self.builder.at_front(self.func.blocks[0]):
                type = self.local_vars[varname]
                self.allocas[varname] = self.builder.alloca(type, [], varname)

        self.builder.store(self.visit(rhs), self.alloca(varname))
#.........这里部分代码省略.........
开发者ID:aburan28,项目名称:pykit,代码行数:103,代码来源:cirparser.py


注:本文中的pykit.ir.Builder.at_front方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。