Exemplo n.º 1
0
    def test_arrayitems(self):
        TP = lltype.GcArray(lltype.Signed)
        ofs = symbolic.get_field_token(TP, 'length', False)[0]
        itemsofs = symbolic.get_field_token(TP, 'items', False)[0]
        descr = self.cpu.arraydescrof(TP)
        res = self.execute_operation(rop.NEW_ARRAY, [ConstInt(10)], 'ref',
                                     descr)
        resbuf = self._resbuf(res)
        assert resbuf[ofs / WORD] == 10
        self.execute_operation(rop.SETARRAYITEM_GC,
                               [res, ConstInt(2), BoxInt(38)], 'void', descr)
        assert resbuf[itemsofs / WORD + 2] == 38

        self.execute_operation(rop.SETARRAYITEM_GC,
                               [res, BoxInt(3), BoxInt(42)], 'void', descr)
        assert resbuf[itemsofs / WORD + 3] == 42

        r = self.execute_operation(rop.GETARRAYITEM_GC, [res, ConstInt(2)],
                                   'int', descr)
        assert r.value == 38
        r = self.execute_operation(rop.GETARRAYITEM_GC,
                                   [res.constbox(), BoxInt(2)], 'int', descr)
        assert r.value == 38
        r = self.execute_operation(
            rop.GETARRAYITEM_GC, [res.constbox(), ConstInt(2)], 'int', descr)
        assert r.value == 38
        r = self.execute_operation(rop.GETARRAYITEM_GC, [res, BoxInt(2)],
                                   'int', descr)
        assert r.value == 38

        r = self.execute_operation(rop.GETARRAYITEM_GC, [res, BoxInt(3)],
                                   'int', descr)
        assert r.value == 42
Exemplo n.º 2
0
 def getvar(self, arg):
     if not arg:
         return ConstInt(0)
     try:
         return ConstInt(int(arg))
     except ValueError:
         if self.is_float(arg):
             return ConstFloat(float(arg))
         if arg.startswith('"') or arg.startswith("'"):
             # XXX ootype
             info = arg.strip("'\"")
             return ConstPtr(
                 lltype.cast_opaque_ptr(llmemory.GCREF, llstr(info)))
         if arg.startswith('ConstClass('):
             name = arg[len('ConstClass('):-1]
             return self.get_const(name, 'class')
         elif arg == 'None':
             return None
         elif arg == 'NULL':
             if self.type_system == 'lltype':
                 return ConstPtr(ConstPtr.value)
             else:
                 return ConstObj(ConstObj.value)
         elif arg.startswith('ConstPtr('):
             name = arg[len('ConstPtr('):-1]
             return self.get_const(name, 'ptr')
         return self.vars[arg]
Exemplo n.º 3
0
    def test_virtuals_with_equal_fields(self):
        info1 = VirtualStateInfo(ConstInt(42), [1, 2])
        value = OptValue(self.nodebox)
        classbox = self.cpu.ts.cls_of_box(self.nodebox)
        value.make_constant_class(classbox, -1)
        knownclass_info = NotVirtualStateInfo(value)
        info1.fieldstate = [knownclass_info, knownclass_info]
        vstate1 = VirtualState([info1])
        assert vstate1.generalization_of(vstate1)

        info2 = VirtualStateInfo(ConstInt(42), [1, 2])
        unknown_info1 = NotVirtualStateInfo(OptValue(self.nodebox))
        info2.fieldstate = [unknown_info1, unknown_info1]
        vstate2 = VirtualState([info2])
        assert vstate2.generalization_of(vstate2)
        assert not vstate1.generalization_of(vstate2)
        assert vstate2.generalization_of(vstate1)

        info3 = VirtualStateInfo(ConstInt(42), [1, 2])
        unknown_info1 = NotVirtualStateInfo(OptValue(self.nodebox))
        unknown_info2 = NotVirtualStateInfo(OptValue(self.nodebox))
        info3.fieldstate = [unknown_info1, unknown_info2]
        vstate3 = VirtualState([info3])        
        assert vstate3.generalization_of(vstate2)
        assert vstate3.generalization_of(vstate1)
        assert not vstate2.generalization_of(vstate3)
        assert not vstate1.generalization_of(vstate3)
Exemplo n.º 4
0
 def gen_malloc_nursery(self, size, v_result):
     """Try to generate or update a CALL_MALLOC_NURSERY.
     If that fails, generate a plain CALL_MALLOC_GC instead.
     """
     size = self.round_up_for_allocation(size)
     if not self.gc_ll_descr.can_use_nursery_malloc(size):
         return False
     #
     op = None
     if self._op_malloc_nursery is not None:
         # already a MALLOC_NURSERY: increment its total size
         total_size = self._op_malloc_nursery.getarg(0).getint()
         total_size += size
         if self.gc_ll_descr.can_use_nursery_malloc(total_size):
             # if the total size is still reasonable, merge it
             self._op_malloc_nursery.setarg(0, ConstInt(total_size))
             op = ResOperation(rop.INT_ADD, [
                 self._v_last_malloced_nursery,
                 ConstInt(self._previous_size)
             ], v_result)
     if op is None:
         # if we failed to merge with a previous MALLOC_NURSERY, emit one
         self.emitting_an_operation_that_can_collect()
         op = ResOperation(rop.CALL_MALLOC_NURSERY, [ConstInt(size)],
                           v_result)
         self._op_malloc_nursery = op
     #
     self.newops.append(op)
     self._previous_size = size
     self._v_last_malloced_nursery = v_result
     self.recent_mallocs[v_result] = None
     return True
Exemplo n.º 5
0
    def test_position_generalization(self):
        def postest(info1, info2):
            info1.position = 0
            assert info1.generalization_of(info1, {}, {})
            info2.position = 0
            assert info1.generalization_of(info2, {}, {})
            info2.position = 1
            renum = {}
            assert info1.generalization_of(info2, renum, {})
            assert renum == {0:1}
            assert info1.generalization_of(info2, {0:1}, {})
            assert info1.generalization_of(info2, {1:1}, {})
            bad = {}
            assert not info1.generalization_of(info2, {0:0}, bad)
            assert info1 in bad and info2 in bad

        for BoxType in (BoxInt, BoxFloat, BoxPtr):
            info1 = NotVirtualStateInfo(OptValue(BoxType()))
            info2 = NotVirtualStateInfo(OptValue(BoxType()))
            postest(info1, info2)
            
        info1, info2 = VArrayStateInfo(42), VArrayStateInfo(42)
        info1.fieldstate = info2.fieldstate = []
        postest(info1, info2)

        info1, info2 = VStructStateInfo(42, []), VStructStateInfo(42, [])
        info1.fieldstate = info2.fieldstate = []
        postest(info1, info2)

        info1, info2 = VirtualStateInfo(ConstInt(42), []), VirtualStateInfo(ConstInt(42), [])
        info1.fieldstate = info2.fieldstate = []
        postest(info1, info2)
Exemplo n.º 6
0
def make_storage(b1, b2, b3):
    storage = Storage()
    snapshot = Snapshot(None, [b1, ConstInt(1), b1, b2])
    snapshot = Snapshot(snapshot, [ConstInt(2), ConstInt(3)])
    snapshot = Snapshot(snapshot, [b1, b2, b3])
    storage.rd_snapshot = snapshot
    return storage
Exemplo n.º 7
0
def test_virtual_adder_no_op_renaming():
    b1s, b2s, b3s = [BoxInt(1), BoxInt(2), BoxInt(3)]
    storage = make_storage(b1s, b2s, b3s)
    memo = ResumeDataLoopMemo(LLtypeMixin.cpu)
    modifier = ResumeDataVirtualAdder(storage, memo)
    b1_2 = BoxInt()

    class FakeValue(object):
        def is_virtual(self):
            return False

        def get_key_box(self):
            return b1_2

    val = FakeValue()
    values = {b1s: val, b2s: val}
    liveboxes = modifier.finish(values)
    assert storage.rd_snapshot is None
    b1t, b3t = [BoxInt(11), BoxInt(33)]
    newboxes = _resume_remap(liveboxes, [b1_2, b3s], b1t, b3t)
    metainterp = MyMetaInterp()
    reader = ResumeDataReader(storage, newboxes, metainterp)
    lst = reader.consume_boxes()
    assert lst == [b1t, b1t, b3t]
    lst = reader.consume_boxes()
    assert lst == [ConstInt(2), ConstInt(3)]
    lst = reader.consume_boxes()
    assert lst == [b1t, ConstInt(1), b1t, b1t]
    assert metainterp.trace == []
Exemplo n.º 8
0
def test_rebuild_from_resumedata_with_virtualizable():
    b1, b2, b3, b4 = [BoxInt(), BoxPtr(), BoxInt(), BoxPtr()]
    c1, c2, c3 = [ConstInt(1), ConstInt(2), ConstInt(3)]
    storage = Storage()
    fs = [
        FakeFrame("code0", 0, -1, b1, c1, b2),
        FakeFrame("code1", 3, 7, b3, c2, b1),
        FakeFrame("code2", 9, -1, c3, b2)
    ]
    capture_resumedata(fs, [b4], storage)
    memo = ResumeDataLoopMemo(LLtypeMixin.cpu)
    modifier = ResumeDataVirtualAdder(storage, memo)
    liveboxes = modifier.finish({})
    metainterp = MyMetaInterp()

    b1t, b2t, b3t, b4t = [BoxInt(), BoxPtr(), BoxInt(), BoxPtr()]
    newboxes = _resume_remap(liveboxes, [b1, b2, b3, b4], b1t, b2t, b3t, b4t)

    result = rebuild_from_resumedata(metainterp, newboxes, storage, True)
    assert result == [b4t]
    fs2 = [
        FakeFrame("code0", 0, -1, b1t, c1, b2t),
        FakeFrame("code1", 3, 7, b3t, c2, b1t),
        FakeFrame("code2", 9, -1, c3, b2t)
    ]
    assert metainterp.framestack == fs2
Exemplo n.º 9
0
 def test_ops_offset(self):
     from pypy.rlib import debug
     i0 = BoxInt()
     i1 = BoxInt()
     i2 = BoxInt()
     looptoken = JitCellToken()
     targettoken = TargetToken()
     operations = [
         ResOperation(rop.LABEL, [i0], None, descr=targettoken),
         ResOperation(rop.INT_ADD, [i0, ConstInt(1)], i1),
         ResOperation(rop.INT_LE, [i1, ConstInt(9)], i2),
         ResOperation(rop.JUMP, [i1], None, descr=targettoken),
         ]
     inputargs = [i0]
     debug._log = dlog = debug.DebugLog()
     info = self.cpu.compile_loop(inputargs, operations, looptoken)
     ops_offset = info.ops_offset
     debug._log = None
     #
     assert ops_offset is looptoken._x86_ops_offset
     # 2*(getfield_raw/int_add/setfield_raw) + ops + None
     assert len(ops_offset) == 2*3 + len(operations) + 1
     assert (ops_offset[operations[0]] <=
             ops_offset[operations[1]] <=
             ops_offset[operations[2]] <=
             ops_offset[None])
Exemplo n.º 10
0
def test_rebuild_from_resumedata_two_guards_w_shared_virtuals():
    b1, b2, b3, b4, b5, b6 = [BoxPtr(), BoxPtr(), BoxInt(), BoxPtr(), BoxInt(), BoxInt()]
    c1, c2, c3, c4 = [ConstInt(1), ConstInt(2), ConstInt(3),
                      LLtypeMixin.nodebox.constbox()]
    storage = Storage()
    fs = [FakeFrame("code0", 0, -1, c1, b2, b3)]
    capture_resumedata(fs, None, [], storage)
    
    memo = ResumeDataLoopMemo(FakeMetaInterpStaticData())
    values = {b2: virtual_value(b2, b5, c4)}
    modifier = ResumeDataVirtualAdder(storage, memo)
    liveboxes = modifier.finish(values)
    assert len(storage.rd_virtuals) == 1
    assert storage.rd_virtuals[0].fieldnums == [tag(-1, TAGBOX),
                                                tag(0, TAGCONST)]

    storage2 = Storage()
    fs = [FakeFrame("code0", 0, -1, b1, b4, b2)]
    capture_resumedata(fs, None, [], storage2)
    values[b4] = virtual_value(b4, b6, c4)
    modifier = ResumeDataVirtualAdder(storage2, memo)
    liveboxes = modifier.finish(values)
    assert len(storage2.rd_virtuals) == 2
    assert storage2.rd_virtuals[1].fieldnums == storage.rd_virtuals[0].fieldnums
    assert storage2.rd_virtuals[1] is storage.rd_virtuals[0]
Exemplo n.º 11
0
 def gen_malloc_fixedsize(self, size, v_result):
     """Generate a CALL_MALLOC_GC(malloc_fixedsize_fn, Const(size)).
     Note that with the framework GC, this should be called very rarely.
     """
     addr = self.gc_ll_descr.get_malloc_fn_addr('malloc_fixedsize')
     self._gen_call_malloc_gc(
         [ConstInt(addr), ConstInt(size)], v_result,
         self.gc_ll_descr.malloc_fixedsize_descr)
Exemplo n.º 12
0
 def gen_boehm_malloc_array(self, arraydescr, v_num_elem, v_result):
     """Generate a CALL_MALLOC_GC(malloc_array_fn, ...) for Boehm."""
     addr = self.gc_ll_descr.get_malloc_fn_addr('malloc_array')
     self._gen_call_malloc_gc([
         ConstInt(addr),
         ConstInt(arraydescr.basesize), v_num_elem,
         ConstInt(arraydescr.itemsize),
         ConstInt(arraydescr.lendescr.offset)
     ], v_result, self.gc_ll_descr.malloc_array_descr)
Exemplo n.º 13
0
 def produce_into(self, builder, r):
     v_length = builder.get_index(10, r)
     v_ptr = builder.do(self.opnum, [v_length])
     getattr(builder, self.builder_cache).append(v_ptr)
     # Initialize the string. Is there a better way to do this?
     for i in range(v_length.getint()):
         v_index = ConstInt(i)
         v_char = ConstInt(r.random_integer() % self.max)
         builder.do(self.set_char, [v_ptr, v_index, v_char])
Exemplo n.º 14
0
def test_compile_tmp_callback():
    from pypy.jit.codewriter import heaptracker
    from pypy.jit.backend.llgraph import runner
    from pypy.rpython.lltypesystem import lltype, llmemory
    from pypy.rpython.annlowlevel import llhelper
    from pypy.rpython.llinterp import LLException
    #
    cpu = runner.LLtypeCPU(None)
    FUNC = lltype.FuncType([lltype.Signed] * 4, lltype.Signed)

    def ll_portal_runner(g1, g2, r3, r4):
        assert (g1, g2, r3, r4) == (12, 34, -156, -178)
        if raiseme:
            raise raiseme
        else:
            return 54321

    #
    class FakeJitDriverSD:
        portal_runner_ptr = llhelper(lltype.Ptr(FUNC), ll_portal_runner)
        portal_runner_adr = llmemory.cast_ptr_to_adr(portal_runner_ptr)
        portal_calldescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT, None)
        portal_finishtoken = compile.DoneWithThisFrameDescrInt()
        num_red_args = 2
        result_type = INT

    #
    loop_token = compile_tmp_callback(
        cpu, FakeJitDriverSD(), [ConstInt(12), ConstInt(34)], "ii")
    #
    raiseme = None
    # only two arguments must be passed in
    fail_descr = cpu.execute_token(loop_token, -156, -178)
    assert fail_descr is FakeJitDriverSD().portal_finishtoken
    #
    EXC = lltype.GcStruct('EXC')
    llexc = lltype.malloc(EXC)
    raiseme = LLException("exception class", llexc)
    fail_descr = cpu.execute_token(loop_token, -156, -178)
    assert isinstance(fail_descr, compile.PropagateExceptionDescr)
    got = cpu.grab_exc_value()
    assert lltype.cast_opaque_ptr(lltype.Ptr(EXC), got) == llexc

    #
    class FakeMetaInterpSD:
        class ExitFrameWithExceptionRef(Exception):
            pass

    FakeMetaInterpSD.cpu = cpu
    fail_descr = cpu.execute_token(loop_token, -156, -178)
    try:
        fail_descr.handle_fail(FakeMetaInterpSD(), None)
    except FakeMetaInterpSD.ExitFrameWithExceptionRef, e:
        assert lltype.cast_opaque_ptr(lltype.Ptr(EXC), e.args[1]) == llexc
Exemplo n.º 15
0
    def test_allocations(self):
        from pypy.rpython.lltypesystem import rstr

        allocs = [None]
        all = []

        def f(size):
            allocs.insert(0, size)
            buf = ctypes.create_string_buffer(size)
            all.append(buf)
            return ctypes.cast(buf, ctypes.c_void_p).value

        func = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)(f)
        addr = ctypes.cast(func, ctypes.c_void_p).value

        try:
            saved_addr = self.cpu.assembler.malloc_func_addr
            self.cpu.assembler.malloc_func_addr = addr
            ofs = symbolic.get_field_token(rstr.STR, 'chars', False)[0]

            res = self.execute_operation(rop.NEWSTR, [ConstInt(7)], 'ref')
            assert allocs[0] == 7 + ofs + WORD
            resbuf = self._resbuf(res)
            assert resbuf[ofs / WORD] == 7

            # ------------------------------------------------------------

            res = self.execute_operation(rop.NEWSTR, [BoxInt(7)], 'ref')
            assert allocs[0] == 7 + ofs + WORD
            resbuf = self._resbuf(res)
            assert resbuf[ofs / WORD] == 7

            # ------------------------------------------------------------

            TP = lltype.GcArray(lltype.Signed)
            ofs = symbolic.get_field_token(TP, 'length', False)[0]
            descr = self.cpu.arraydescrof(TP)

            res = self.execute_operation(rop.NEW_ARRAY, [ConstInt(10)], 'ref',
                                         descr)
            assert allocs[0] == 10 * WORD + ofs + WORD
            resbuf = self._resbuf(res)
            assert resbuf[ofs / WORD] == 10

            # ------------------------------------------------------------

            res = self.execute_operation(rop.NEW_ARRAY, [BoxInt(10)], 'ref',
                                         descr)
            assert allocs[0] == 10 * WORD + ofs + WORD
            resbuf = self._resbuf(res)
            assert resbuf[ofs / WORD] == 10

        finally:
            self.cpu.assembler.malloc_func_addr = saved_addr
Exemplo n.º 16
0
def get_int_tests():
    for opnum, args, retvalue in (list(_int_binary_operations()) +
                                  list(_int_comparison_operations()) +
                                  list(_int_unary_operations())):
        yield opnum, [BoxInt(x) for x in args], retvalue
        if len(args) > 1:
            assert len(args) == 2
            yield opnum, [BoxInt(args[0]), ConstInt(args[1])], retvalue
            yield opnum, [ConstInt(args[0]), BoxInt(args[1])], retvalue
            if args[0] == args[1]:
                commonbox = BoxInt(args[0])
                yield opnum, [commonbox, commonbox], retvalue
Exemplo n.º 17
0
 def test_unicode(self):
     ofs = symbolic.get_field_token(rstr.UNICODE, 'chars', False)[0]
     u = rstr.mallocunicode(13)
     for i in range(13):
         u.chars[i] = unichr(ord(u'a') + i)
     b = BoxPtr(lltype.cast_opaque_ptr(llmemory.GCREF, u))
     r = self.execute_operation(rop.UNICODEGETITEM, [b, ConstInt(2)], 'int')
     assert r.value == ord(u'a') + 2
     self.execute_operation(rop.UNICODESETITEM, [b, ConstInt(2),
                                                 ConstInt(ord(u'z'))],
                            'void')
     assert u.chars[2] == u'z'
     assert u.chars[3] == u'd'
Exemplo n.º 18
0
def _strgetitem(string_optimizer, strbox, indexbox, mode, resbox=None):
    if isinstance(strbox, ConstPtr) and isinstance(indexbox, ConstInt):
        if mode is mode_string:
            s = strbox.getref(lltype.Ptr(rstr.STR))
            return ConstInt(ord(s.chars[indexbox.getint()]))
        else:
            s = strbox.getref(lltype.Ptr(rstr.UNICODE))
            return ConstInt(ord(s.chars[indexbox.getint()]))
    if resbox is None:
        resbox = BoxInt()
    string_optimizer.emit_operation(
        ResOperation(mode.STRGETITEM, [strbox, indexbox], resbox))
    return resbox
Exemplo n.º 19
0
    def test_stringitems(self):
        from pypy.rpython.lltypesystem.rstr import STR
        ofs = symbolic.get_field_token(STR, 'chars', False)[0]
        ofs_items = symbolic.get_field_token(STR.chars, 'items', False)[0]

        res = self.execute_operation(rop.NEWSTR, [ConstInt(10)], 'ref')
        self.execute_operation(rop.STRSETITEM, [res, ConstInt(2), ConstInt(ord('d'))], 'void')
        resbuf = self._resbuf(res, ctypes.c_char)
        assert resbuf[ofs + ofs_items + 2] == 'd'
        self.execute_operation(rop.STRSETITEM, [res, BoxInt(2), ConstInt(ord('z'))], 'void')
        assert resbuf[ofs + ofs_items + 2] == 'z'
        r = self.execute_operation(rop.STRGETITEM, [res, BoxInt(2)], 'int')
        assert r.value == ord('z')
Exemplo n.º 20
0
def test_virtual_adder_make_varray():
    b2s, b4s = [BoxPtr(), BoxInt(4)]
    c1s = ConstInt(111)
    storage = Storage()
    memo = ResumeDataLoopMemo(FakeMetaInterpStaticData())
    modifier = ResumeDataVirtualAdder(storage, memo)
    modifier.liveboxes_from_env = {}
    modifier.liveboxes = {}
    modifier.vfieldboxes = {}

    class FakeOptimizer(object):
        class cpu:
            pass
        def new_const_item(self, descr):
            return None
    v2 = VArrayValue(FakeOptimizer(), LLtypeMixin.arraydescr, 2, b2s)
    v2._items = [b4s, c1s]
    modifier.register_virtual_fields(b2s, [b4s, c1s])
    liveboxes = []
    values = {b2s: v2}
    modifier._number_virtuals(liveboxes, values, 0)
    dump_storage(storage, liveboxes)
    storage.rd_consts = memo.consts[:]
    storage.rd_numb = None
    # resume
    b1t, b3t, b4t = [BoxInt(11), BoxInt(33), BoxInt(44)]
    newboxes = _resume_remap(liveboxes, [#b2s -- virtual
                                         b4s],
                                         b4t)
    # resume
    metainterp = MyMetaInterp()
    reader = ResumeDataReader(storage, newboxes, metainterp)
    assert len(reader.virtuals) == 1
    b2t = reader._decode_box(tag(0, TAGVIRTUAL))
    trace = metainterp.trace
    expected = [
        (rop.NEW_ARRAY, [ConstInt(2)], b2t, LLtypeMixin.arraydescr),
        (rop.SETARRAYITEM_GC, [b2t,ConstInt(0), b4t],None,
                              LLtypeMixin.arraydescr),
        (rop.SETARRAYITEM_GC, [b2t,ConstInt(1), c1s], None,
                              LLtypeMixin.arraydescr),
        ]
    for x, y in zip(expected, trace):
        assert x == y
    #
    ptr = b2t.value._obj.container._as_ptr()
    assert lltype.typeOf(ptr) == lltype.Ptr(lltype.GcArray(lltype.Signed))
    assert len(ptr) == 2
    assert ptr[0] == 44
    assert ptr[1] == 111
Exemplo n.º 21
0
 def gen_malloc_array(self, arraydescr, v_num_elem, v_result):
     """Generate a CALL_MALLOC_GC(malloc_array_fn, ...) going either
     to the standard or the nonstandard version of the function."""
     #
     if (arraydescr.basesize == self.gc_ll_descr.standard_array_basesize
             and arraydescr.lendescr.offset
             == self.gc_ll_descr.standard_array_length_ofs):
         # this is a standard-looking array, common case
         addr = self.gc_ll_descr.get_malloc_fn_addr('malloc_array')
         args = [
             ConstInt(addr),
             ConstInt(arraydescr.itemsize),
             ConstInt(arraydescr.tid), v_num_elem
         ]
         calldescr = self.gc_ll_descr.malloc_array_descr
     else:
         # rare case, so don't care too much about the number of arguments
         addr = self.gc_ll_descr.get_malloc_fn_addr(
             'malloc_array_nonstandard')
         args = [
             ConstInt(addr),
             ConstInt(arraydescr.basesize),
             ConstInt(arraydescr.itemsize),
             ConstInt(arraydescr.lendescr.offset),
             ConstInt(arraydescr.tid), v_num_elem
         ]
         calldescr = self.gc_ll_descr.malloc_array_nonstandard_descr
     self._gen_call_malloc_gc(args, v_result, calldescr)
Exemplo n.º 22
0
def test_ResumeDataLoopMemo_ints():
    memo = ResumeDataLoopMemo(LLtypeMixin.cpu)
    tagged = memo.getconst(ConstInt(44))
    assert untag(tagged) == (44, TAGINT)
    tagged = memo.getconst(ConstInt(-3))
    assert untag(tagged) == (-3, TAGINT)
    const = ConstInt(50000)
    tagged = memo.getconst(const)
    index, tagbits = untag(tagged)
    assert tagbits == TAGCONST
    assert memo.consts[index] is const
    tagged = memo.getconst(ConstInt(50000))
    index2, tagbits = untag(tagged)
    assert tagbits == TAGCONST
    assert index2 == index
Exemplo n.º 23
0
    def test_we_are_jitted(self):
        def f():
            if jit.we_are_jitted():
                return 55
            else:
                return 66

        graphs = self.make_graphs(f, [])
        cw = CodeWriter(self.rtyper)
        cw.candidate_graphs = [graphs[0]]
        cw._start(self.metainterp_sd, None)
        jitcode = cw.make_one_bytecode((graphs[0], None), False)
        assert 'goto_if_not' not in jitcode._source
        assert ConstInt(55) in jitcode.constants
        assert ConstInt(66) not in jitcode.constants
Exemplo n.º 24
0
def make_args_for_op(op, a, b):
    n=opname[op]
    if n[0:3] == 'INT' or n[0:4] == 'UINT':
        arg1 = ConstInt(a)
        arg2 = ConstInt(b)
    elif n[0:5] == 'FLOAT':
        arg1 = constfloat(float(a))
        arg2 = constfloat(float(b))
    elif n[0:3] == 'PTR':
        arg1 = ConstPtr(rffi.cast(llmemory.GCREF, a))
        arg2 = ConstPtr(rffi.cast(llmemory.GCREF, b))
    else:
        raise NotImplementedError(
            "Don't know how to make args for " + n)
    return arg1, arg2
Exemplo n.º 25
0
 def make_guards(self, box, guards):
     if self.has_lower and self.lower > MININT:
         bound = self.lower
         res = BoxInt()
         op = ResOperation(rop.INT_GE, [box, ConstInt(bound)], res)
         guards.append(op)
         op = ResOperation(rop.GUARD_TRUE, [res], None)
         guards.append(op)
     if self.has_upper and self.upper < MAXINT:
         bound = self.upper
         res = BoxInt()
         op = ResOperation(rop.INT_LE, [box, ConstInt(bound)], res)
         guards.append(op)
         op = ResOperation(rop.GUARD_TRUE, [res], None)
         guards.append(op)
Exemplo n.º 26
0
    def test_getfield_setfield(self):
        TP = lltype.GcStruct('x', ('s', lltype.Signed),
                             ('i', rffi.INT),
                             ('f', lltype.Float),
                             ('u', rffi.USHORT),
                             ('c1', lltype.Char),
                             ('c2', lltype.Char),
                             ('c3', lltype.Char))
        res = self.execute_operation(rop.NEW, [],
                                     'ref', self.cpu.sizeof(TP))
        ofs_s = self.cpu.fielddescrof(TP, 's')
        ofs_i = self.cpu.fielddescrof(TP, 'i')
        #ofs_f = self.cpu.fielddescrof(TP, 'f')
        ofs_u = self.cpu.fielddescrof(TP, 'u')
        ofsc1 = self.cpu.fielddescrof(TP, 'c1')
        ofsc2 = self.cpu.fielddescrof(TP, 'c2')
        ofsc3 = self.cpu.fielddescrof(TP, 'c3')
        self.execute_operation(rop.SETFIELD_GC, [res, ConstInt(3)], 'void',
                               ofs_s)
        # XXX ConstFloat
        #self.execute_operation(rop.SETFIELD_GC, [res, ofs_f, 1e100], 'void')
        # XXX we don't support shorts (at all)
        #self.execute_operation(rop.SETFIELD_GC, [res, ofs_u, ConstInt(5)], 'void')
        s = self.execute_operation(rop.GETFIELD_GC, [res], 'int', ofs_s)
        assert s.value == 3
        self.execute_operation(rop.SETFIELD_GC, [res, BoxInt(3)], 'void',
                               ofs_s)
        s = self.execute_operation(rop.GETFIELD_GC, [res], 'int', ofs_s)
        assert s.value == 3

        self.execute_operation(rop.SETFIELD_GC, [res, BoxInt(1234)], 'void', ofs_i)
        i = self.execute_operation(rop.GETFIELD_GC, [res], 'int', ofs_i)
        assert i.value == 1234

        #u = self.execute_operation(rop.GETFIELD_GC, [res, ofs_u], 'int')
        #assert u.value == 5
        self.execute_operation(rop.SETFIELD_GC, [res, ConstInt(1)], 'void',
                               ofsc1)
        self.execute_operation(rop.SETFIELD_GC, [res, ConstInt(3)], 'void',
                               ofsc3)
        self.execute_operation(rop.SETFIELD_GC, [res, ConstInt(2)], 'void',
                               ofsc2)
        c = self.execute_operation(rop.GETFIELD_GC, [res], 'int', ofsc1)
        assert c.value == 1
        c = self.execute_operation(rop.GETFIELD_GC, [res], 'int', ofsc2)
        assert c.value == 2
        c = self.execute_operation(rop.GETFIELD_GC, [res], 'int', ofsc3)
        assert c.value == 3
Exemplo n.º 27
0
 def constant(value):
     if isinstance(lltype.typeOf(value), lltype.Ptr):
         return ConstPtr(value)
     elif isinstance(ootype.typeOf(value), ootype.OOType):
         return ConstObj(ootype.cast_to_object(value))
     else:
         return ConstInt(value)
Exemplo n.º 28
0
    def optimize_default(self, op):
        if op.is_always_pure():
            for arg in op.args:
                if self.get_constant_box(arg) is None:
                    break
            else:
                # all constant arguments: constant-fold away
                argboxes = [self.get_constant_box(arg) for arg in op.args]
                resbox = execute_nonspec(self.cpu, op.opnum, argboxes,
                                         op.descr)
                self.make_constant(op.result, resbox.constbox())
                return

            # did we do the exact same operation already?
            args = op.args[:]
            for i in range(len(args)):
                arg = args[i]
                if arg in self.values:
                    args[i] = self.values[arg].get_key_box()
            args.append(ConstInt(op.opnum))
            oldop = self.pure_operations.get(args, None)
            if oldop is not None and oldop.descr is op.descr:
                assert oldop.opnum == op.opnum
                self.make_equal_to(op.result, self.getvalue(oldop.result))
                return
            else:
                self.pure_operations[args] = op

        # otherwise, the operation remains
        self.emit_operation(op)
Exemplo n.º 29
0
 def produce_into(self, builder, r):
     if r.random() < 0.4:
         UnaryOperation.produce_into(self, builder, r)
     elif r.random() < 0.75 or not builder.cpu.supports_floats:
         self.put(builder, [ConstInt(r.random_integer())])
     else:
         self.put(builder, [ConstFloat(r.random_float())])
Exemplo n.º 30
0
 def get_index(self, length, r):
     if length == 0:
         raise test_random.CannotProduceOperation
     v_index = r.choice(self.intvars)
     if not (0 <= v_index.value < length):
         v_index = ConstInt(r.random_integer() % length)
     return v_index