コード例 #1
0
ファイル: test_rptr.py プロジェクト: e2pluginss/plexnet
def test_runtime_type_info():
    S = GcStruct('s', ('x', Signed))
    attachRuntimeTypeInfo(S)
    def ll_example(p):
        return (runtime_type_info(p),
                runtime_type_info(p) == getRuntimeTypeInfo(S))

    assert ll_example(malloc(S)) == (getRuntimeTypeInfo(S), True)
    s, t = ll_rtype(ll_example, [annmodel.SomePtr(Ptr(S))])
    assert s == annmodel.SomeTuple([annmodel.SomePtr(Ptr(RuntimeTypeInfo)),
                                    annmodel.SomeBool()])
コード例 #2
0
ファイル: test_rptr.py プロジェクト: e2pluginss/plexnet
def test_cast_pointer():
    S = GcStruct('s', ('x', Signed))
    S1 = GcStruct('s1', ('sub', S))
    S2 = GcStruct('s2', ('sub', S1))
    PS = Ptr(S)
    PS2 = Ptr(S2)
    def lldown(p):
        return cast_pointer(PS, p)
    s, t = ll_rtype(lldown, [annmodel.SomePtr(PS2)])
    assert s.ll_ptrtype == PS
    def llup(p):
        return cast_pointer(PS2, p)
    s, t = ll_rtype(llup, [annmodel.SomePtr(PS)])
    assert s.ll_ptrtype == PS2
コード例 #3
0
ファイル: test_llann.py プロジェクト: griels/pypy-sc
 def test_funcptr(self):
     F = FuncType((Signed,), Signed)
     PF = Ptr(F)
     def llf(p):
         return p(0)
     s = self.annotate(llf, [annmodel.SomePtr(PF)])
     assert s.knowntype == int
コード例 #4
0
 def compute_result_annotation(self, s_PTR, s_object):
     assert s_PTR.is_constant()
     if isinstance(s_PTR.const, lltype.Ptr):
         return annmodel.SomePtr(s_PTR.const)
     elif isinstance(s_PTR.const, ootype.Instance):
         return annmodel.SomeOOInstance(s_PTR.const)
     else:
         assert False
コード例 #5
0
ファイル: test_llann.py プロジェクト: griels/pypy-sc
 def test_runtime_type_info(self):
     S = GcStruct('s', ('x', Signed))
     attachRuntimeTypeInfo(S)
     def llf(p):
         return runtime_type_info(p)
     s = self.annotate(llf, [annmodel.SomePtr(Ptr(S))])
     assert isinstance(s, annmodel.SomePtr)
     assert s.ll_ptrtype == Ptr(RuntimeTypeInfo)
コード例 #6
0
ファイル: test_genc.py プロジェクト: griels/pypy-sc
def test_rptr_array():
    A = GcArray(Ptr(PyObject))
    def f(i, x):
        p = malloc(A, i)
        p[1] = x
        return p[1]
    f1 = compile(f, [int, annmodel.SomePtr(Ptr(PyObject))])
    assert f1(5, 123) == 123
    assert f1(12, "hello") == "hello"
コード例 #7
0
ファイル: annlowlevel.py プロジェクト: chyyuu/pygirl
 def compute_result_annotation(self, s_F, s_callable):
     assert s_F.is_constant()
     assert s_callable.is_constant()
     F = s_F.const
     args_s = [annmodel.lltype_to_annotation(T) for T in F.TO.ARGS]
     key = (llhelper, s_callable.const)
     s_res = self.bookkeeper.emulate_pbc_call(key, s_callable, args_s)
     assert annmodel.lltype_to_annotation(F.TO.RESULT).contains(s_res)
     return annmodel.SomePtr(F)
コード例 #8
0
ファイル: rgc.py プロジェクト: purepython/pypy
def s_list_of_gcrefs():
    global _cache_s_list_of_gcrefs
    if _cache_s_list_of_gcrefs is None:
        from pypy.annotation import model as annmodel
        from pypy.annotation.listdef import ListDef
        s_gcref = annmodel.SomePtr(llmemory.GCREF)
        _cache_s_list_of_gcrefs = annmodel.SomeList(
            ListDef(None, s_gcref, mutated=True, resized=False))
    return _cache_s_list_of_gcrefs
コード例 #9
0
ファイル: rgc.py プロジェクト: e2pluginss/plexnet
 def compute_result_annotation(self, s_T, s_init_size):
     from pypy.annotation import model as annmodel
     from pypy.rpython.lltypesystem import rffi, lltype
     assert s_T.is_constant()
     assert isinstance(s_init_size, annmodel.SomeInteger)
     T = s_T.const
     # limit ourselves to structs and to a fact that var-sized element
     # does not contain pointers.
     assert isinstance(T, lltype.Struct)
     assert isinstance(getattr(T, T._arrayfld).OF, lltype.Primitive)
     return annmodel.SomePtr(lltype.Ptr(T))
コード例 #10
0
 def undecided_relevance_test_invalid_hint_2(self):
     S = lltype.GcStruct('S', ('x', lltype.Signed))
     def ll_getitem_switch(s):
         if s.x > 0:   # variable exitswitch
             sign = 1
         else:
             sign = -1
         return hint(sign, concrete=True)
     py.test.skip("in-progress: I think we expect a HintError here, do we?")
     py.test.raises(HintError, hannotate,
                    ll_getitem_switch, [annmodel.SomePtr(lltype.Ptr(S))])
コード例 #11
0
ファイル: test_llann.py プロジェクト: griels/pypy-sc
 def test_cast_simple_widening(self):
     S2 = Struct("s2", ('a', Signed))
     S1 = Struct("s1", ('sub1', S2), ('sub2', S2))
     PS1 = Ptr(S1)
     PS2 = Ptr(S2)
     def llf(p1):
         p2 = p1.sub1
         p3 = cast_pointer(PS1, p2)
         return p3
     s = self.annotate(llf, [annmodel.SomePtr(PS1)])
     assert isinstance(s, annmodel.SomePtr)
     assert s.ll_ptrtype == PS1
コード例 #12
0
    def runner(self, f, nbargs=0, statistics=False, transformer=False,
               **extraconfigopts):
        if nbargs == 2:
            def entrypoint(args):
                x = args[0]
                y = args[1]
                r = f(x, y)
                return r
        elif nbargs == 0:
            def entrypoint(args):
                return f()
        else:
            raise NotImplementedError("pure laziness")

        from pypy.rpython.llinterp import LLInterpreter
        from pypy.translator.c.genc import CStandaloneBuilder

        ARGS = lltype.FixedSizeArray(lltype.Signed, nbargs)
        s_args = annmodel.SomePtr(lltype.Ptr(ARGS))
        t = rtype(entrypoint, [s_args], gcname=self.gcname,
                                        stacklessgc=self.stacklessgc,
                                        **extraconfigopts)
        cbuild = CStandaloneBuilder(t, entrypoint, config=t.config,
                                    gcpolicy=self.gcpolicy)
        db = cbuild.generate_graphs_for_llinterp()
        entrypointptr = cbuild.getentrypointptr()
        entrygraph = entrypointptr._obj.graph
        if conftest.option.view:
            t.viewcg()

        llinterp = LLInterpreter(t.rtyper)

        # FIIIIISH
        setupgraph = db.gctransformer.frameworkgc_setup_ptr.value._obj.graph
        llinterp.eval_graph(setupgraph, [])
        def run(args):
            ll_args = lltype.malloc(ARGS, immortal=True)
            for i in range(nbargs):
                ll_args[i] = args[i]
            res = llinterp.eval_graph(entrygraph, [ll_args])
            return res

        if statistics:
            statisticsgraph = db.gctransformer.statistics_ptr.value._obj.graph
            ll_gc = db.gctransformer.c_const_gc.value
            def statistics(index):
                return llinterp.eval_graph(statisticsgraph, [ll_gc, index])
            return run, statistics
        elif transformer:
            return run, db.gctransformer
        else:
            return run
コード例 #13
0
    def test_deepfreeze(self):

        A = lltype.GcArray(lltype.Signed)

        def ll_function(a, i):
            a = hint(a, deepfreeze=True)
            res = a[i]
            res = hint(res, concrete=True)

            res = hint(res, variable=True)
            return res

        hs = self.hannotate(ll_function, [annmodel.SomePtr(lltype.Ptr(A)), int])
        assert type(hs) is SomeLLAbstractVariable
        assert hs.concretetype == lltype.Signed
コード例 #14
0
ファイル: rtyper.py プロジェクト: purepython/pypy
 def attachRuntimeTypeInfoFunc(self,
                               GCSTRUCT,
                               func,
                               ARG_GCSTRUCT=None,
                               destrptr=None):
     self.call_all_setups()  # compute ForwardReferences now
     if ARG_GCSTRUCT is None:
         ARG_GCSTRUCT = GCSTRUCT
     args_s = [annmodel.SomePtr(Ptr(ARG_GCSTRUCT))]
     graph = self.annotate_helper(func, args_s)
     s = self.annotator.binding(graph.getreturnvar())
     if (not isinstance(s, annmodel.SomePtr)
             or s.ll_ptrtype != Ptr(RuntimeTypeInfo)):
         raise TyperError("runtime type info function %r returns %r, "
                          "excepted Ptr(RuntimeTypeInfo)" % (func, s))
     funcptr = self.getcallable(graph)
     attachRuntimeTypeInfo(GCSTRUCT, funcptr, destrptr, None)
コード例 #15
0
    def replace_promote_virtualizable(self, rtyper, graphs):
        from pypy.annotation import model as annmodel
        from pypy.rpython.annlowlevel import MixLevelHelperAnnotator
        graph = graphs[0]

        for block, op in graph.iterblockops():
            if op.opname == 'promote_virtualizable':
                v_inst_ll_type = op.args[0].concretetype
                break

        def mycall(vinst_ll):
            pass

        annhelper = MixLevelHelperAnnotator(rtyper)
        if self.type_system == 'lltype':
            s_vinst = annmodel.SomePtr(v_inst_ll_type)
        else:
            s_vinst = annmodel.SomeOOInstance(v_inst_ll_type)
        funcptr = annhelper.delayedfunction(mycall, [s_vinst], annmodel.s_None)
        annhelper.finish()
        replace_promote_virtualizable_with_call(graphs, v_inst_ll_type,
                                                funcptr)
        return funcptr
コード例 #16
0
ファイル: annlowlevel.py プロジェクト: chyyuu/pygirl
 def compute_result_annotation(self, s_PTR, s_object):
     assert s_PTR.is_constant()
     assert isinstance(s_PTR.const, lltype.Ptr)
     return annmodel.SomePtr(s_PTR.const)
コード例 #17
0
    def make_pyexcclass2exc(self, rtyper):
        # ll_pyexcclass2exc(python_exception_class) -> exception_instance
        table = {}
        Exception_def = rtyper.annotator.bookkeeper.getuniqueclassdef(
            Exception)
        for clsdef in rtyper.class_reprs:
            if (clsdef and clsdef is not Exception_def
                    and clsdef.issubclass(Exception_def)):
                if not hasattr(clsdef.classdesc, 'pyobj'):
                    continue
                cls = clsdef.classdesc.pyobj
                if cls in self.standardexceptions and cls not in FORCE_ATTRIBUTES_INTO_CLASSES:
                    is_standard = True
                    assert not clsdef.attrs, (
                        "%r should not have grown attributes" % (cls, ))
                else:
                    is_standard = (cls.__module__ == 'exceptions'
                                   and not clsdef.attrs)
                if is_standard:
                    example = self.get_standard_ll_exc_instance(rtyper, clsdef)
                    table[cls] = example
                #else:
                #    assert cls.__module__ != 'exceptions', (
                #        "built-in exceptions should not grow attributes")
        r_inst = rclass.getinstancerepr(rtyper, None)
        r_inst.setup()
        default_excinst = malloc(self.lltype_of_exception_value.TO,
                                 immortal=True)
        default_excinst.typeptr = r_inst.rclass.getvtable()

        # build the table in order base classes first, subclasses last
        sortedtable = []

        def add_class(cls):
            if cls in table:
                for base in cls.__bases__:
                    add_class(base)
                sortedtable.append((cls, table[cls]))
                del table[cls]

        for cls in table.keys():
            add_class(cls)
        assert table == {}
        #print sortedtable

        A = Array(('pycls', Ptr(PyObject)),
                  ('excinst', self.lltype_of_exception_value))
        pycls2excinst = malloc(A, len(sortedtable), immortal=True)
        for i in range(len(sortedtable)):
            cls, example = sortedtable[i]
            pycls2excinst[i].pycls = pyobjectptr(cls)
            pycls2excinst[i].excinst = example

        FUNCTYPE = FuncType([Ptr(PyObject), Ptr(PyObject)], Signed)
        PyErr_GivenExceptionMatches = functionptr(
            FUNCTYPE,
            "PyErr_GivenExceptionMatches",
            external="C",
            _callable=lambda pyobj1, pyobj2: int(
                issubclass(pyobj1._obj.value, pyobj2._obj.value)))

        initial_value_of_i = len(pycls2excinst) - 1

        def ll_pyexcclass2exc(python_exception_class):
            """Return an RPython instance of the best approximation of the
            Python exception identified by its Python class.
            """
            i = initial_value_of_i
            while i >= 0:
                if PyErr_GivenExceptionMatches(python_exception_class,
                                               pycls2excinst[i].pycls):
                    return pycls2excinst[i].excinst
                i -= 1
            return default_excinst

        s_pyobj = annmodel.SomePtr(Ptr(PyObject))
        helper_fn = rtyper.annotate_helper_fn(ll_pyexcclass2exc, [s_pyobj])
        return helper_fn
コード例 #18
0
ファイル: framework.py プロジェクト: griels/pypy-sc
    def __init__(self, translator):
        from pypy.rpython.memory.gc.base import choose_gc_from_config
        super(FrameworkGCTransformer, self).__init__(translator, inline=True)
        if hasattr(self, 'GC_PARAMS'):
            # for tests: the GC choice can be specified as class attributes
            from pypy.rpython.memory.gc.marksweep import MarkSweepGC
            GCClass = getattr(self, 'GCClass', MarkSweepGC)
            GC_PARAMS = self.GC_PARAMS
        else:
            # for regular translation: pick the GC from the config
            GCClass, GC_PARAMS = choose_gc_from_config(translator.config)

        self.layoutbuilder = TransformerLayoutBuilder(self)
        self.get_type_id = self.layoutbuilder.get_type_id

        # set up dummy a table, to be overwritten with the real one in finish()
        type_info_table = lltype._ptr(
            lltype.Ptr(gctypelayout.GCData.TYPE_INFO_TABLE),
            "delayed!type_info_table", solid=True)
        gcdata = gctypelayout.GCData(type_info_table)

        # initialize the following two fields with a random non-NULL address,
        # to make the annotator happy.  The fields are patched in finish()
        # to point to a real array.
        foo = lltype.malloc(lltype.FixedSizeArray(llmemory.Address, 1),
                            immortal=True, zero=True)
        a_random_address = llmemory.cast_ptr_to_adr(foo)
        gcdata.static_root_start = a_random_address      # patched in finish()
        gcdata.static_root_nongcend = a_random_address   # patched in finish()
        gcdata.static_root_end = a_random_address        # patched in finish()
        self.gcdata = gcdata
        self.malloc_fnptr_cache = {}

        gcdata.gc = GCClass(**GC_PARAMS)
        root_walker = self.build_root_walker()
        gcdata.set_query_functions(gcdata.gc)
        gcdata.gc.set_root_walker(root_walker)
        self.num_pushs = 0
        self.write_barrier_calls = 0

        def frameworkgc_setup():
            # run-time initialization code
            root_walker.setup_root_walker()
            gcdata.gc.setup()

        bk = self.translator.annotator.bookkeeper

        # the point of this little dance is to not annotate
        # self.gcdata.static_root_xyz as constants. XXX is it still needed??
        data_classdef = bk.getuniqueclassdef(gctypelayout.GCData)
        data_classdef.generalize_attr(
            'static_root_start',
            annmodel.SomeAddress())
        data_classdef.generalize_attr(
            'static_root_nongcend',
            annmodel.SomeAddress())
        data_classdef.generalize_attr(
            'static_root_end',
            annmodel.SomeAddress())

        annhelper = annlowlevel.MixLevelHelperAnnotator(self.translator.rtyper)

        def getfn(ll_function, args_s, s_result, inline=False,
                  minimal_transform=True):
            graph = annhelper.getgraph(ll_function, args_s, s_result)
            if minimal_transform:
                self.need_minimal_transform(graph)
            if inline:
                self.graphs_to_inline[graph] = True
            return annhelper.graph2const(graph)

        self.frameworkgc_setup_ptr = getfn(frameworkgc_setup, [],
                                           annmodel.s_None)
        if root_walker.need_root_stack:
            self.incr_stack_ptr = getfn(root_walker.incr_stack,
                                       [annmodel.SomeInteger()],
                                       annmodel.SomeAddress(),
                                       inline = True)
            self.decr_stack_ptr = getfn(root_walker.decr_stack,
                                       [annmodel.SomeInteger()],
                                       annmodel.SomeAddress(),
                                       inline = True)
        else:
            self.incr_stack_ptr = None
            self.decr_stack_ptr = None
        self.weakref_deref_ptr = self.inittime_helper(
            ll_weakref_deref, [llmemory.WeakRefPtr], llmemory.Address)
        
        classdef = bk.getuniqueclassdef(GCClass)
        s_gc = annmodel.SomeInstance(classdef)
        s_gcref = annmodel.SomePtr(llmemory.GCREF)

        malloc_fixedsize_clear_meth = GCClass.malloc_fixedsize_clear.im_func
        self.malloc_fixedsize_clear_ptr = getfn(
            malloc_fixedsize_clear_meth,
            [s_gc, annmodel.SomeInteger(nonneg=True),
             annmodel.SomeInteger(nonneg=True),
             annmodel.SomeBool(), annmodel.SomeBool(),
             annmodel.SomeBool()], s_gcref,
            inline = False)
        if hasattr(GCClass, 'malloc_fixedsize'):
            malloc_fixedsize_meth = GCClass.malloc_fixedsize.im_func
            self.malloc_fixedsize_ptr = getfn(
                malloc_fixedsize_meth,
                [s_gc, annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeBool(), annmodel.SomeBool(),
                 annmodel.SomeBool()], s_gcref,
                inline = False)
        else:
            malloc_fixedsize_meth = None
            self.malloc_fixedsize_ptr = self.malloc_fixedsize_clear_ptr
##         self.malloc_varsize_ptr = getfn(
##             GCClass.malloc_varsize.im_func,
##             [s_gc] + [annmodel.SomeInteger(nonneg=True) for i in range(5)]
##             + [annmodel.SomeBool(), annmodel.SomeBool()], s_gcref)
        self.malloc_varsize_clear_ptr = getfn(
            GCClass.malloc_varsize_clear.im_func,
            [s_gc] + [annmodel.SomeInteger(nonneg=True) for i in range(5)]
            + [annmodel.SomeBool(), annmodel.SomeBool()], s_gcref)
        self.collect_ptr = getfn(GCClass.collect.im_func,
            [s_gc], annmodel.s_None)
        self.can_move_ptr = getfn(GCClass.can_move.im_func,
                                  [s_gc, annmodel.SomeAddress()],
                                  annmodel.SomeBool())

        # in some GCs we can inline the common case of
        # malloc_fixedsize(typeid, size, True, False, False)
        if getattr(GCClass, 'inline_simple_malloc', False):
            # make a copy of this function so that it gets annotated
            # independently and the constants are folded inside
            if malloc_fixedsize_meth is None:
                malloc_fast_meth = malloc_fixedsize_clear_meth
                self.malloc_fast_is_clearing = True
            else:
                malloc_fast_meth = malloc_fixedsize_meth
                self.malloc_fast_is_clearing = False
            malloc_fast = func_with_new_name(
                malloc_fast_meth,
                "malloc_fast")
            s_False = annmodel.SomeBool(); s_False.const = False
            s_True  = annmodel.SomeBool(); s_True .const = True
            self.malloc_fast_ptr = getfn(
                malloc_fast,
                [s_gc, annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True),
                 s_True, s_False,
                 s_False], s_gcref,
                inline = True)
        else:
            self.malloc_fast_ptr = None

        # in some GCs we can also inline the common case of
        # malloc_varsize(typeid, length, (3 constant sizes), True, False)
        if getattr(GCClass, 'inline_simple_malloc_varsize', False):
            # make a copy of this function so that it gets annotated
            # independently and the constants are folded inside
            malloc_varsize_clear_fast = func_with_new_name(
                GCClass.malloc_varsize_clear.im_func,
                "malloc_varsize_clear_fast")
            s_False = annmodel.SomeBool(); s_False.const = False
            s_True  = annmodel.SomeBool(); s_True .const = True
            self.malloc_varsize_clear_fast_ptr = getfn(
                malloc_varsize_clear_fast,
                [s_gc, annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True),
                 s_True, s_False], s_gcref,
                inline = True)
        else:
            self.malloc_varsize_clear_fast_ptr = None

        if getattr(GCClass, 'malloc_varsize_nonmovable', False):
            malloc_nonmovable = func_with_new_name(
                GCClass.malloc_varsize_nonmovable.im_func,
                "malloc_varsize_nonmovable")
            self.malloc_varsize_nonmovable_ptr = getfn(
                malloc_nonmovable,
                [s_gc, annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True)], s_gcref)
        else:
            self.malloc_varsize_nonmovable_ptr = None

        if getattr(GCClass, 'malloc_varsize_resizable', False):
            malloc_resizable = func_with_new_name(
                GCClass.malloc_varsize_resizable.im_func,
                "malloc_varsize_resizable")
            self.malloc_varsize_resizable_ptr = getfn(
                malloc_resizable,
                [s_gc, annmodel.SomeInteger(nonneg=True),
                 annmodel.SomeInteger(nonneg=True)], s_gcref)
        else:
            self.malloc_varsize_resizable_ptr = None

        if getattr(GCClass, 'realloc', False):
            self.realloc_ptr = getfn(
                GCClass.realloc.im_func,
                [s_gc, s_gcref] +
                [annmodel.SomeInteger(nonneg=True)] * 4 +
                [annmodel.SomeBool()],
                s_gcref)

        if GCClass.moving_gc:
            self.id_ptr = getfn(GCClass.id.im_func,
                                [s_gc, s_gcref], annmodel.SomeInteger(),
                                inline = False,
                                minimal_transform = False)
        else:
            self.id_ptr = None

        self.set_max_heap_size_ptr = getfn(GCClass.set_max_heap_size.im_func,
                                           [s_gc,
                                            annmodel.SomeInteger(nonneg=True)],
                                           annmodel.s_None)

        if GCClass.needs_write_barrier:
            self.write_barrier_ptr = getfn(GCClass.write_barrier.im_func,
                                           [s_gc,
                                            annmodel.SomeAddress(),
                                            annmodel.SomeAddress()],
                                           annmodel.s_None,
                                           inline=True)
        else:
            self.write_barrier_ptr = None
        self.statistics_ptr = getfn(GCClass.statistics.im_func,
                                    [s_gc, annmodel.SomeInteger()],
                                    annmodel.SomeInteger())

        # experimental gc_x_* operations
        s_x_pool  = annmodel.SomePtr(marksweep.X_POOL_PTR)
        s_x_clone = annmodel.SomePtr(marksweep.X_CLONE_PTR)
        # the x_*() methods use some regular mallocs that must be
        # transformed in the normal way
        self.x_swap_pool_ptr = getfn(GCClass.x_swap_pool.im_func,
                                     [s_gc, s_x_pool],
                                     s_x_pool,
                                     minimal_transform = False)
        self.x_clone_ptr = getfn(GCClass.x_clone.im_func,
                                 [s_gc, s_x_clone],
                                 annmodel.s_None,
                                 minimal_transform = False)

        # thread support
        if translator.config.translation.thread:
            if not hasattr(root_walker, "need_thread_support"):
                raise Exception("%s does not support threads" % (
                    root_walker.__class__.__name__,))
            root_walker.need_thread_support()
            self.thread_prepare_ptr = getfn(root_walker.thread_prepare,
                                            [], annmodel.s_None)
            self.thread_run_ptr = getfn(root_walker.thread_run,
                                        [], annmodel.s_None,
                                        inline=True)
            self.thread_die_ptr = getfn(root_walker.thread_die,
                                        [], annmodel.s_None)

        annhelper.finish()   # at this point, annotate all mix-level helpers
        annhelper.backend_optimize()

        self.collect_analyzer = CollectAnalyzer(self.translator)
        self.collect_analyzer.analyze_all()

        s_gc = self.translator.annotator.bookkeeper.valueoftype(GCClass)
        r_gc = self.translator.rtyper.getrepr(s_gc)
        self.c_const_gc = rmodel.inputconst(r_gc, self.gcdata.gc)
        self.malloc_zero_filled = GCClass.malloc_zero_filled

        HDR = self._gc_HDR = self.gcdata.gc.gcheaderbuilder.HDR
        self._gc_fields = fields = []
        for fldname in HDR._names:
            FLDTYPE = getattr(HDR, fldname)
            fields.append(('_' + fldname, FLDTYPE))
コード例 #19
0
ファイル: jit_hooks.py プロジェクト: purepython/pypy
    ptr = lltype.cast_opaque_ptr(rclass.OBJECTPTR, llref)
    return cast_base_ptr_to_instance(AbstractResOp, ptr)


@specialize.argtype(0)
def _cast_to_gcref(obj):
    return lltype.cast_opaque_ptr(llmemory.GCREF,
                                  cast_instance_to_base_ptr(obj))


def emptyval():
    return lltype.nullptr(llmemory.GCREF.TO)


@register_helper(annmodel.SomePtr(llmemory.GCREF))
def resop_new(no, llargs, llres):
    from pypy.jit.metainterp.history import ResOperation

    args = [_cast_to_box(llargs[i]) for i in range(len(llargs))]
    res = _cast_to_box(llres)
    return _cast_to_gcref(ResOperation(no, args, res))


@register_helper(annmodel.SomePtr(llmemory.GCREF))
def boxint_new(no):
    from pypy.jit.metainterp.history import BoxInt
    return _cast_to_gcref(BoxInt(no))


@register_helper(annmodel.SomeInteger())
コード例 #20
0
    def need_stacklet_support(self, gctransformer, getfn):
        shadow_stack_pool = self.shadow_stack_pool
        SHADOWSTACKREF = get_shadowstackref(gctransformer)

        def gc_shadowstackref_new():
            ssref = shadow_stack_pool.allocate(SHADOWSTACKREF)
            return lltype.cast_opaque_ptr(llmemory.GCREF, ssref)

        def gc_shadowstackref_context(gcref):
            ssref = lltype.cast_opaque_ptr(lltype.Ptr(SHADOWSTACKREF), gcref)
            return ssref.context

        def gc_shadowstackref_destroy(gcref):
            ssref = lltype.cast_opaque_ptr(lltype.Ptr(SHADOWSTACKREF), gcref)
            shadow_stack_pool.destroy(ssref)

        def gc_save_current_state_away(gcref, ncontext):
            ssref = lltype.cast_opaque_ptr(lltype.Ptr(SHADOWSTACKREF), gcref)
            shadow_stack_pool.save_current_state_away(ssref, ncontext)

        def gc_forget_current_state():
            shadow_stack_pool.forget_current_state()

        def gc_restore_state_from(gcref):
            ssref = lltype.cast_opaque_ptr(lltype.Ptr(SHADOWSTACKREF), gcref)
            shadow_stack_pool.restore_state_from(ssref)

        def gc_start_fresh_new_state():
            shadow_stack_pool.start_fresh_new_state()

        s_gcref = annmodel.SomePtr(llmemory.GCREF)
        s_addr = annmodel.SomeAddress()
        self.gc_shadowstackref_new_ptr = getfn(gc_shadowstackref_new, [],
                                               s_gcref,
                                               minimal_transform=False)
        self.gc_shadowstackref_context_ptr = getfn(gc_shadowstackref_context,
                                                   [s_gcref],
                                                   s_addr,
                                                   inline=True)
        self.gc_shadowstackref_destroy_ptr = getfn(gc_shadowstackref_destroy,
                                                   [s_gcref],
                                                   annmodel.s_None,
                                                   inline=True)
        self.gc_save_current_state_away_ptr = getfn(gc_save_current_state_away,
                                                    [s_gcref, s_addr],
                                                    annmodel.s_None,
                                                    inline=True)
        self.gc_forget_current_state_ptr = getfn(gc_forget_current_state, [],
                                                 annmodel.s_None,
                                                 inline=True)
        self.gc_restore_state_from_ptr = getfn(gc_restore_state_from,
                                               [s_gcref],
                                               annmodel.s_None,
                                               inline=True)
        self.gc_start_fresh_new_state_ptr = getfn(gc_start_fresh_new_state, [],
                                                  annmodel.s_None,
                                                  inline=True)
        # fish...
        translator = gctransformer.translator
        if hasattr(translator, '_jit2gc'):
            from pypy.rlib._rffi_stacklet import _translate_pointer
            root_iterator = translator._jit2gc['root_iterator']
            root_iterator.translateptr = _translate_pointer
コード例 #21
0
 def annotate_struct(self, S):
     return annmodel.SomePtr(lltype.Ptr(S))
コード例 #22
0
                                                 _debugexc=True)
                    cfunc = hop.inputconst(lltype.Ptr(FUNCTYPE), funcptr)
                else:
                    FUNCTYPE = ootype.StaticMethod(ARGS, RESULT)
                    sm = ootype._static_meth(FUNCTYPE,
                                             _name=func.__name__,
                                             _callable=func)
                    cfunc = hop.inputconst(FUNCTYPE, sm)
                args_v = hop.inputargs(*hop.args_r)
                return hop.genop('direct_call', [cfunc] + args_v, hop.r_result)


# annotations
from pypy.annotation import model as annmodel

s_ConstOrVar = annmodel.SomePtr(CONSTORVAR)
s_Link = annmodel.SomePtr(LINK)
s_LinkPair = annmodel.SomeTuple([s_Link, s_Link])
s_Block = annmodel.SomePtr(BLOCK)
s_Graph = annmodel.SomePtr(GRAPH)

setannotation(newblock, s_Block)
setannotation(newgraph, s_ConstOrVar)
setannotation(getstartblock, s_Block)
setannotation(geninputarg, s_ConstOrVar)
setannotation(getinputarg, s_ConstOrVar)
setannotation(genop, s_ConstOrVar)
setannotation(gengetsubstruct, s_ConstOrVar)
setannotation(gengetarraysubstruct, s_ConstOrVar)
setannotation(gensetfield, None)
setannotation(gengetfield, s_ConstOrVar)
コード例 #23
0
ファイル: rgc.py プロジェクト: purepython/pypy
 def compute_result_annotation(self):
     from pypy.annotation import model as annmodel
     from pypy.rpython.memory.gc.base import ARRAY_TYPEID_MAP
     return annmodel.SomePtr(lltype.Ptr(ARRAY_TYPEID_MAP))
コード例 #24
0
 def compute_result_annotation(self, s_type, **s_fields):
     TP = s_type.const
     if not isinstance(TP, lltype.Struct):
         raise TypeError("make called with %s instead of Struct as first argument" % TP)
     return annmodel.SomePtr(lltype.Ptr(TP))
コード例 #25
0
 def make_type_of_exc_inst(self, rtyper):
     # ll_type_of_exc_inst(exception_instance) -> exception_vtable
     s_excinst = annmodel.SomePtr(self.lltype_of_exception_value)
     helper_fn = rtyper.annotate_helper_fn(rclass.ll_type, [s_excinst])
     return helper_fn
コード例 #26
0
ファイル: rgc.py プロジェクト: purepython/pypy
 def compute_result_annotation(self, s_gcref):
     from pypy.annotation import model as annmodel
     assert annmodel.SomePtr(llmemory.GCREF).contains(s_gcref)
     return s_list_of_gcrefs()
コード例 #27
0
ファイル: rgc.py プロジェクト: purepython/pypy
 def compute_result_annotation(self, s_Class):
     from pypy.annotation import model as annmodel
     from pypy.rpython.lltypesystem import rclass
     assert s_Class.is_constant()
     return annmodel.SomePtr(rclass.CLASSTYPE)
コード例 #28
0
    def setup_class(cls):
        funcs0 = []
        funcs2 = []
        cleanups = []
        name_to_func = {}
        mixlevelstuff = []
        for fullname in dir(cls):
            if not fullname.startswith('define'):
                continue
            definefunc = getattr(cls, fullname)
            _, name = fullname.split('_', 1)
            func_fixup = definefunc.im_func(cls)
            cleanup = None
            if isinstance(func_fixup, tuple):
                func, cleanup, fixup = func_fixup
                mixlevelstuff.append(fixup)
            else:
                func = func_fixup
            func.func_name = "f_%s" % name
            if cleanup:
                cleanup.func_name = "clean_%s" % name

            nargs = len(inspect.getargspec(func)[0])
            name_to_func[name] = len(funcs0)
            if nargs == 2:
                funcs2.append(func)
                funcs0.append(None)
            elif nargs == 0:
                funcs0.append(func)
                funcs2.append(None)
            else:
                raise NotImplementedError(
                         "defined test functions should have 0/2 arguments")
            # used to let test cleanup static root pointing to runtime
            # allocated stuff
            cleanups.append(cleanup)

        def entrypoint(args):
            num = args[0]
            func = funcs0[num]
            if func:
                res = func()
            else:
                func = funcs2[num]
                res = func(args[1], args[2])
            cleanup = cleanups[num]
            if cleanup:
                cleanup()
            return res

        from pypy.translator.c.genc import CStandaloneBuilder

        s_args = annmodel.SomePtr(lltype.Ptr(ARGS))
        t = rtype(entrypoint, [s_args], gcname=cls.gcname,
                  stacklessgc=cls.stacklessgc,
                  taggedpointers=cls.taggedpointers)

        for fixup in mixlevelstuff:
            if fixup:
                fixup(t)

        cbuild = CStandaloneBuilder(t, entrypoint, config=t.config,
                                    gcpolicy=cls.gcpolicy)
        db = cbuild.generate_graphs_for_llinterp()
        entrypointptr = cbuild.getentrypointptr()
        entrygraph = entrypointptr._obj.graph
        if conftest.option.view:
            t.viewcg()

        cls.name_to_func = name_to_func
        cls.entrygraph = entrygraph
        cls.rtyper = t.rtyper
        cls.db = db
コード例 #29
0
 def make_exception_matcher(self, rtyper):
     # ll_exception_matcher(real_exception_vtable, match_exception_vtable)
     s_typeptr = annmodel.SomePtr(self.lltype_of_exception_type)
     helper_fn = rtyper.annotate_helper_fn(rclass.ll_issubclass,
                                           [s_typeptr, s_typeptr])
     return helper_fn