def wrap(cpu, value, in_const_box=False): if isinstance(lltype.typeOf(value), lltype.Ptr): if lltype.typeOf(value).TO._gckind == 'gc': value = lltype.cast_opaque_ptr(llmemory.GCREF, value) if in_const_box: return history.ConstPtr(value) else: return resoperation.InputArgRef(value) else: adr = llmemory.cast_ptr_to_adr(value) value = heaptracker.adr2int(adr) # fall through to the end of the function elif (isinstance(value, float) or longlong.is_longlong(lltype.typeOf(value))): if isinstance(value, float): value = longlong.getfloatstorage(value) else: value = rffi.cast(lltype.SignedLongLong, value) if in_const_box: return history.ConstFloat(value) else: return resoperation.InputArgFloat(value) elif isinstance(value, str) or isinstance(value, unicode): assert len(value) == 1 # must be a character value = ord(value) elif lltype.typeOf(value) is lltype.SingleFloat: value = longlong.singlefloat2int(value) else: value = intmask(value) if in_const_box: return history.ConstInt(value) else: return resoperation.InputArgInt(value)
def generic_initializationexpr(db, value, access_expr, decoration): if isinstance(typeOf(value), ContainerType): node = db.getcontainernode(value) lines = list(node.initializationexpr(decoration+'.')) lines[-1] += ',' return lines else: comma = ',' if typeOf(value) == Float and not isfinite(value): db.late_initializations.append(('%s' % access_expr, db.get(value))) if isinf(value): name = '-+'[value > 0] + 'inf' else: name = 'NaN' expr = '0.0 /* patched later with %s */' % (name,) else: expr = db.get(value) if typeOf(value) is Void: comma = '' expr += comma i = expr.find('\n') if i < 0: i = len(expr) expr = '%s\t/* %s */%s' % (expr[:i], decoration, expr[i:]) return expr.split('\n')
def ll_dict_copy(dict): DICT = lltype.typeOf(dict).TO newdict = DICT.allocate() newdict.entries = DICT.entries.TO.allocate(len(dict.entries)) newdict.num_live_items = dict.num_live_items newdict.num_ever_used_items = dict.num_ever_used_items if hasattr(DICT, "fnkeyeq"): newdict.fnkeyeq = dict.fnkeyeq if hasattr(DICT, "fnkeyhash"): newdict.fnkeyhash = dict.fnkeyhash i = 0 while i < newdict.num_ever_used_items: d_entry = newdict.entries[i] entry = dict.entries[i] ENTRY = lltype.typeOf(newdict.entries).TO.OF d_entry.key = entry.key if hasattr(ENTRY, "f_valid"): d_entry.f_valid = entry.f_valid d_entry.value = entry.value if hasattr(ENTRY, "f_hash"): d_entry.f_hash = entry.f_hash i += 1 ll_dict_reindex(newdict, _ll_len_of_d_indexes(dict)) return newdict
def verify(*args): for a, exp_a in zip(args, avalues): if (lltype.typeOf(exp_a) == rffi.ULONG and lltype.typeOf(a) == lltype.Signed): a = rffi.cast(rffi.ULONG, a) assert a == exp_a return rvalue
def dispatcher(self, shape, index, argtypes, resulttype): key = shape, index, tuple(argtypes), resulttype if key in self._dispatch_cache: return self._dispatch_cache[key] from rpython.translator.unsimplify import varoftype from rpython.flowspace.model import FunctionGraph, Link, Block, SpaceOperation inputargs = [varoftype(t) for t in [Char] + argtypes] startblock = Block(inputargs) startblock.exitswitch = inputargs[0] graph = FunctionGraph("dispatcher", startblock, varoftype(resulttype)) row_of_graphs = self.callfamily.calltables[shape][index] links = [] descs = list(self.s_pbc.descriptions) if self.s_pbc.can_be_None: descs.insert(0, None) for desc in descs: if desc is None: continue args_v = [varoftype(t) for t in argtypes] b = Block(args_v) llfn = self.rtyper.getcallable(row_of_graphs[desc]) v_fn = inputconst(typeOf(llfn), llfn) v_result = varoftype(resulttype) b.operations.append( SpaceOperation("direct_call", [v_fn] + args_v, v_result)) b.closeblock(Link([v_result], graph.returnblock)) i = self.descriptions.index(desc) links.append(Link(inputargs[1:], b, chr(i))) links[-1].llexitcase = chr(i) startblock.closeblock(*links) self.rtyper.annotator.translator.graphs.append(graph) ll_ret = getfunctionptr(graph) #FTYPE = FuncType c_ret = self._dispatch_cache[key] = inputconst(typeOf(ll_ret), ll_ret) return c_ret
def finish_rtype(self): rtyper = self.rtyper translator = rtyper.annotator.translator original_graph_count = len(translator.graphs) perform_normalizations(rtyper) for r in self.delayedreprs: r.set_setup_delayed(False) rtyper.call_all_setups() for p, repr, obj in self.delayedconsts: p._become(repr.convert_const(obj)) rtyper.call_all_setups() for p, graph in self.delayedfuncs: self.newgraphs.add(graph) real_p = rtyper.getcallable(graph) REAL = lltype.typeOf(real_p).TO FUNCTYPE = lltype.typeOf(p).TO if isinstance(FUNCTYPE, lltype.ForwardReference): FUNCTYPE.become(REAL) assert FUNCTYPE == REAL p._become(real_p) rtyper.specialize_more_blocks() self.delayedreprs.clear() del self.delayedconsts[:] del self.delayedfuncs[:] for graph in translator.graphs[original_graph_count:]: self.newgraphs.add(graph)
def add_operators(space, dict_w, pto): # XXX support PyObject_HashNotImplemented for method_name, slot_names, wrapper_func, wrapper_func_kwds, doc in slotdefs_for_wrappers: if method_name in dict_w: continue offset = [rffi.offsetof(lltype.typeOf(pto).TO, slot_names[0])] if len(slot_names) == 1: func = getattr(pto, slot_names[0]) else: assert len(slot_names) == 2 struct = getattr(pto, slot_names[0]) if not struct: continue offset.append(rffi.offsetof(lltype.typeOf(struct).TO, slot_names[1])) func = getattr(struct, slot_names[1]) func_voidp = rffi.cast(rffi.VOIDP, func) if not func: continue if wrapper_func is None and wrapper_func_kwds is None: continue w_obj = W_PyCWrapperObject(space, pto, method_name, wrapper_func, wrapper_func_kwds, doc, func_voidp, offset=offset) dict_w[method_name] = space.wrap(w_obj) if pto.c_tp_doc: dict_w['__doc__'] = space.newbytes(rffi.charp2str(pto.c_tp_doc)) if pto.c_tp_new: add_tp_new_wrapper(space, dict_w, pto)
def gendirectcall(self, ll_function, *args_v): rtyper = self.rtyper args_s = [] newargs_v = [] for v in args_v: if v.concretetype is Void: s_value = rtyper.binding(v, default=annmodel.s_None) if not s_value.is_constant(): raise TyperError("non-constant variable of type Void") if not isinstance(s_value, annmodel.SomePBC): raise TyperError("non-PBC Void argument: %r", (s_value,)) args_s.append(s_value) else: args_s.append(annmodel.lltype_to_annotation(v.concretetype)) newargs_v.append(v) self.rtyper.call_all_setups() # compute ForwardReferences now # hack for bound methods if hasattr(ll_function, 'im_func'): bk = rtyper.annotator.bookkeeper args_s.insert(0, bk.immutablevalue(ll_function.im_self)) newargs_v.insert(0, inputconst(Void, ll_function.im_self)) ll_function = ll_function.im_func graph = annotate_lowlevel_helper(rtyper.annotator, ll_function, args_s, rtyper.lowlevel_ann_policy) self.record_extra_call(graph) # build the 'direct_call' operation f = self.rtyper.getcallable(graph) c = inputconst(typeOf(f), f) fobj = self.rtyper.type_system_deref(f) return self.genop('direct_call', [c]+newargs_v, resulttype = typeOf(fobj).RESULT)
def ref(self, firstitemptr): A = lltype.typeOf(firstitemptr).TO if A == self.TYPE: # for array of containers parent, index = lltype.parentlink(firstitemptr._obj) assert parent, "%r is not within a container" % (firstitemptr,) assert isinstance(lltype.typeOf(parent), (lltype.Array, lltype.FixedSizeArray)), ( "%r is not within an array" % (firstitemptr,)) if isinstance(index, str): assert index.startswith('item') # itemN => N index = int(index[4:]) index += self.repeat if index == parent.getlength(): # for references exactly to the end of the array try: endmarker = _end_markers[parent] except KeyError: endmarker = _endmarker_struct(A, parent=parent, parentindex=index) _end_markers[parent] = endmarker return endmarker._as_ptr() else: return parent.getitem(index)._as_ptr() elif ((isinstance(A, lltype.FixedSizeArray) or (isinstance(A, lltype.Array) and A._hints.get('nolength', False))) and array_item_type_match(A.OF, self.TYPE)): # for array of primitives or pointers return lltype.direct_ptradd(firstitemptr, self.repeat) else: raise TypeError('got %r, expected %r' % (A, self.TYPE))
def _reccopy(source, dest): # copy recursively a structure or array onto another. T = lltype.typeOf(source).TO assert T == lltype.typeOf(dest).TO if isinstance(T, (lltype.Array, lltype.FixedSizeArray)): sourcelgt = source._obj.getlength() destlgt = dest._obj.getlength() lgt = min(sourcelgt, destlgt) ITEMTYPE = T.OF for i in range(lgt): if isinstance(ITEMTYPE, lltype.ContainerType): subsrc = source._obj.getitem(i)._as_ptr() subdst = dest._obj.getitem(i)._as_ptr() _reccopy(subsrc, subdst) else: # this is a hack XXX de-hack this llvalue = source._obj.getitem(i, uninitialized_ok=True) dest._obj.setitem(i, llvalue) elif isinstance(T, lltype.Struct): for name in T._names: FIELDTYPE = getattr(T, name) if isinstance(FIELDTYPE, lltype.ContainerType): subsrc = source._obj._getattr(name)._as_ptr() subdst = dest._obj._getattr(name)._as_ptr() _reccopy(subsrc, subdst) else: # this is a hack XXX de-hack this llvalue = source._obj._getattr(name, uninitialized_ok=True) setattr(dest._obj, name, llvalue) else: raise TypeError(T)
def foo(): # a bit hard to test, really a = llop.get_exception_addr(llmemory.Address) assert lltype.typeOf(a) is llmemory.Address a = llop.get_exc_value_addr(llmemory.Address) assert lltype.typeOf(a) is llmemory.Address return 42
def generic_initializationexpr(db, value, access_expr, decoration): if isinstance(typeOf(value), ContainerType): node = db.getcontainernode(value) lines = list(node.initializationexpr(decoration + ".")) lines[-1] += "," return lines else: comma = "," if typeOf(value) == Float and not isfinite(value): db.late_initializations.append(("%s" % access_expr, db.get(value))) if isinf(value): name = "-+"[value > 0] + "inf" else: name = "NaN" expr = "0.0 /* patched later with %s */" % (name,) else: expr = db.get(value) if typeOf(value) is Void: comma = "" expr += comma i = expr.find("\n") if i < 0: i = len(expr) expr = "%s\t/* %s */%s" % (expr[:i], decoration, expr[i:]) return expr.split("\n")
def get(self, obj, funcgen=None): if isinstance(obj, CConstant): return obj.c_name # without further checks T = typeOf(obj) if isinstance(T, Primitive) or T == GCREF: return PrimitiveName[T](obj, self) elif isinstance(T, Ptr): if (isinstance(T.TO, OpaqueType) and T.TO.hints.get('c_pointer_typedef') is not None): if obj._obj is not None: value = rffi.cast(rffi.SSIZE_T, obj) return '((%s) %s)' % (cdecl(self.gettype(T), ''), self.get(value)) if obj: # test if the ptr is non-NULL try: container = obj._obj except lltype.DelayedPointer: # hack hack hack name = obj._obj0 assert name.startswith('delayed!') n = len('delayed!') if len(name) == n: raise if isinstance(lltype.typeOf(obj).TO, lltype.FuncType): if obj in self.idelayedfunctionnames: return self.idelayedfunctionnames[obj][0] funcname = name[n:] funcname = self.namespace.uniquename('g_'+funcname) self.idelayedfunctionnames[obj] = funcname, obj else: funcname = None # can't use the name of a # delayed non-function ptr self.delayedfunctionptrs.append(obj) return funcname # /hack hack hack else: # hack hack hack if obj in self.idelayedfunctionnames: # this used to be a delayed function, # make sure we use the same name forcename = self.idelayedfunctionnames[obj][0] node = self.getcontainernode(container, forcename=forcename) assert node.getptrname() == forcename return forcename # /hack hack hack if isinstance(container, int): # special case for tagged odd-valued pointers return '((%s) %d)' % (cdecl(self.gettype(T), ''), obj._obj) node = self.getcontainernode(container) if node._funccodegen_owner is None: node._funccodegen_owner = funcgen return node.getptrname() else: return '((%s) NULL)' % (cdecl(self.gettype(T), ''), ) else: raise Exception("don't know about %r" % (obj,))
def op_check_and_clear_exc(self): exc_data = self.llinterpreter.get_transformed_exc_data(self.graph) assert exc_data etype = exc_data.exc_type evalue = exc_data.exc_value exc_data.exc_type = lltype.typeOf(etype)._defl() exc_data.exc_value = lltype.typeOf(evalue)._defl() return bool(etype)
def fn(n): s = lltype.cast_int_to_ptr(PS, n) assert lltype.typeOf(s) == PS assert lltype.cast_ptr_to_int(s) == n t = lltype.cast_pointer(PT, s) assert lltype.typeOf(t) == PT assert lltype.cast_ptr_to_int(t) == n assert s == lltype.cast_pointer(PS, t)
def _get_offset(self, cppinstance): if cppinstance: assert lltype.typeOf(cppinstance.cppclass.handle) == lltype.typeOf(self.scope.handle) offset = self.offset + capi.c_base_offset(self.space, cppinstance.cppclass, self.scope, cppinstance.get_rawobject(), 1) else: offset = self.offset return offset
def enum_content(self, o, name='', with_header=True): # XXX clean up T = lltype.typeOf(o) if (self.size_gc_header is not None and with_header and isinstance(T, lltype.ContainerType) and T._gckind == 'gc'): adr = llmemory.cast_ptr_to_adr(o._as_ptr()) adr -= self.size_gc_header o = adr.get()._obj T = lltype.typeOf(o) if isinstance(T, lltype.Struct): try: gcobjptr = header2obj[o] fmt = '(%s)' except KeyError: gcobjptr = None fmt = '%s' for name in T._names: for name, value in self.enum_content(getattr(o, name), name, with_header=False): yield fmt % (name,), value if gcobjptr: if self.size_gc_header is not None: for sub in self.enum_content(gcobjptr._obj, with_header=False): yield sub else: # display as a link to avoid the same data showing up # twice in the graph yield 'header of', gcobjptr._obj elif isinstance(T, lltype.Array): for index, o1 in enumerate(o.items): for sub in self.enum_content(o1, str(index)): yield sub elif isinstance(T, lltype.Ptr): if not o: yield name, 'null' else: yield name, self.normalize(lltype.normalizeptr(o)._obj) elif isinstance(T, lltype.OpaqueType) and hasattr(o, 'container'): T = lltype.typeOf(o.container) yield 'container', '<%s>' % (shorttypename(T),) for sub in self.enum_content(o.container, name, with_header=False): yield sub elif T == llmemory.Address: if not o: yield name, 'NULL' else: addrof = o.ref() T1 = lltype.typeOf(addrof) if (isinstance(T1, lltype.Ptr) and isinstance(T1.TO, lltype.Struct) and addrof._obj in header2obj): yield name + ' @hdr', self.normalize(addrof._obj) else: yield name + ' @', self.normalize(o.ptr._obj) else: yield name, str(o)
def cast_weakrefptr_to_ptr(PTRTYPE, pwref): assert lltype.typeOf(pwref) == WeakRefPtr if pwref: assert isinstance(pwref._obj, _gctransformed_wref) if PTRTYPE is not None: assert PTRTYPE == lltype.typeOf(pwref._obj._ptr) return pwref._obj._ptr else: return lltype.nullptr(PTRTYPE.TO)
def test_ptradd(): data = "hello, world!" a = lltype.malloc(ARRAY_OF_CHAR, len(data), flavor='raw') for i in xrange(len(data)): a[i] = data[i] a2 = ptradd(a, 2) assert lltype.typeOf(a2) == lltype.typeOf(a) == lltype.Ptr(ARRAY_OF_CHAR) for i in xrange(len(data) - 2): assert a2[i] == a[i + 2] lltype.free(a, flavor='raw')
def raw_str(self): value = lltype.malloc(rffi.CArray(lltype.typeOf(self.value)), 1, flavor="raw") value[0] = self.value builder = StringBuilder() builder.append_charpsize(rffi.cast(rffi.CCHARP, value), rffi.sizeof(lltype.typeOf(self.value))) ret = builder.build() lltype.free(value, flavor="raw") return ret
def setintfield(pdst, fieldname, value): """Maybe temporary: a helper to set an integer field into a structure, transparently casting between the various integer types. """ STRUCT = lltype.typeOf(pdst).TO TSRC = lltype.typeOf(value) TDST = getattr(STRUCT, fieldname) assert isinstance(TSRC, lltype.Number) assert isinstance(TDST, lltype.Number) setattr(pdst, fieldname, cast(TDST, value))
def test_externalvsinternal(self): class A: pass class B: pass class C: pass class D: pass def func(): d1 = self.newdict(); d1[A()] = B() d2 = self.newdict2(); d2[C()] = D() return (d1, d2) res = self.interpret(func, []) assert lltype.typeOf(res.item0) == lltype.typeOf(res.item1)
def ll_striter(string): if typeOf(string) == string_repr.lowleveltype: TP = string_repr.iterator_repr.lowleveltype.TO elif typeOf(string) == unicode_repr.lowleveltype: TP = unicode_repr.iterator_repr.lowleveltype.TO else: raise TypeError("Unknown string type %s" % (typeOf(string),)) iter = malloc(TP) iter.string = string iter.index = 0 return iter
def values_to_nodes(database, values): nodes = [] for value in values: if isinstance(typeOf(value), Ptr): container = value._obj if isinstance(typeOf(container), ContainerType): node = database.getcontainernode(container) if node.nodekind != 'func': nodes.append(node) elif isinstance(typeOf(value), ContainerType): # inlined container nodes.extend(values_to_nodes(database, database.getcontainernode(value).enum_dependencies())) return nodes
def newconst(value): if value is None: return ConstPtr(lltype.nullptr(llmemory.GCREF.TO)) elif lltype.typeOf(value) == lltype.Signed: return ConstInt(value) elif isinstance(value, bool): return ConstInt(int(value)) elif lltype.typeOf(value) == longlong.FLOATSTORAGE: return ConstFloat(value) else: assert lltype.typeOf(value) == llmemory.GCREF return ConstPtr(value)
def set_op_value(self, op, value): if value is None: return elif isinstance(value, bool): op.setint(int(value)) elif lltype.typeOf(value) == lltype.Signed: op.setint(value) elif lltype.typeOf(value) is longlong.FLOATSTORAGE: op.setfloatstorage(value) else: assert lltype.typeOf(value) == llmemory.GCREF op.setref_base(value)
def ll_to_annotation(v): if v is None: # i think we can only get here in the case of void-returning # functions return s_None if isinstance(v, lltype._interior_ptr): ob = v._parent if ob is None: raise RuntimeError T = lltype.InteriorPtr(lltype.typeOf(ob), v._T, v._offsets) return SomeInteriorPtr(T) return lltype_to_annotation(lltype.typeOf(v))
def wrap_constant(value): if lltype.typeOf(value) == lltype.Signed: return ConstInt(value) elif isinstance(value, bool): return ConstInt(int(value)) elif lltype.typeOf(value) == longlong.FLOATSTORAGE: return ConstFloat(value) elif isinstance(value, float): return ConstFloat(longlong.getfloatstorage(value)) else: assert lltype.typeOf(value) == llmemory.GCREF return ConstPtr(value)
def unspecialize_value(value): """Casts 'value' to a Signed, a GCREF or a FLOATSTORAGE.""" if isinstance(lltype.typeOf(value), lltype.Ptr): if lltype.typeOf(value).TO._gckind == 'gc': return lltype.cast_opaque_ptr(llmemory.GCREF, value) else: adr = llmemory.cast_ptr_to_adr(value) return heaptracker.adr2int(adr) elif isinstance(value, float): return longlong.getfloatstorage(value) else: return lltype.cast_primitive(lltype.Signed, value)
def ll_striter(string): if typeOf(string) == string_repr.lowleveltype: TP = string_repr.iterator_repr.lowleveltype.TO elif typeOf(string) == unicode_repr.lowleveltype: TP = unicode_repr.iterator_repr.lowleveltype.TO else: raise TypeError("Unknown string type %s" % (typeOf(string),)) iter = malloc(TP) iter.string = string iter.length = len(string.chars) # load this value only once iter.index = 0 return iter
def op_getfield(p, name): checkptr(p) TYPE = lltype.typeOf(p).TO if not TYPE._immutable_field(name): raise TypeError("cannot fold getfield on mutable struct") return getattr(p, name)
def _run(self, atypes, rtype, avalues, rvalue, expected_call_release_gil=1, supports_floats=True, supports_longlong=True, supports_singlefloats=True): cif_description = get_description(atypes, rtype) def verify(*args): assert args == tuple(avalues) return rvalue FUNC = lltype.FuncType([lltype.typeOf(avalue) for avalue in avalues], lltype.typeOf(rvalue)) func = lltype.functionptr(FUNC, 'verify', _callable=verify) func_addr = rffi.cast(rffi.VOIDP, func) for i in range(len(avalues)): cif_description.exchange_args[i] = (i + 1) * 16 cif_description.exchange_result = (len(avalues) + 1) * 16 unroll_avalues = unrolling_iterable(avalues) def fake_call_impl_any(cif_description, func_addr, exchange_buffer): ofs = 16 for avalue in unroll_avalues: TYPE = rffi.CArray(lltype.typeOf(avalue)) data = rffi.ptradd(exchange_buffer, ofs) got = rffi.cast(lltype.Ptr(TYPE), data)[0] if lltype.typeOf(avalue) is lltype.SingleFloat: got = float(got) avalue = float(avalue) assert got == avalue ofs += 16 if rvalue is not None: write_rvalue = rvalue else: write_rvalue = 12923 # ignored TYPE = rffi.CArray(lltype.typeOf(write_rvalue)) data = rffi.ptradd(exchange_buffer, ofs) rffi.cast(lltype.Ptr(TYPE), data)[0] = write_rvalue def f(i): exbuf = lltype.malloc(rffi.CCHARP.TO, (len(avalues) + 2) * 16, flavor='raw') targetptr = rffi.ptradd(exbuf, 16) for avalue in unroll_avalues: TYPE = rffi.CArray(lltype.typeOf(avalue)) if i >= 9: # a guard that can fail pass rffi.cast(lltype.Ptr(TYPE), targetptr)[0] = avalue targetptr = rffi.ptradd(targetptr, 16) jit_ffi_call(cif_description, func_addr, exbuf) if rvalue is None: res = 654321 else: TYPE = rffi.CArray(lltype.typeOf(rvalue)) res = rffi.cast(lltype.Ptr(TYPE), targetptr)[0] lltype.free(exbuf, flavor='raw') if lltype.typeOf(res) is lltype.SingleFloat: res = float(res) return res def matching_result(res, rvalue): if rvalue is None: return res == 654321 if isinstance(rvalue, r_singlefloat): rvalue = float(rvalue) return res == rvalue with FakeFFI(fake_call_impl_any): res = f(-42) assert matching_result(res, rvalue) res = self.interp_operations( f, [-42], supports_floats=supports_floats, supports_longlong=supports_longlong, supports_singlefloats=supports_singlefloats) if is_longlong(FUNC.RESULT): # longlongs are returned as floats, but that's just # an inconvenience of interp_operations(). Normally both # longlong and floats are passed around as longlongs. res = float2longlong(res) assert matching_result(res, rvalue) self.check_operations_history( call_may_force=0, call_release_gil=expected_call_release_gil) ################################################## driver = jit.JitDriver(reds=['i'], greens=[]) def main(): i = 0 while 1: driver.jit_merge_point(i=i) res = f(i) i += 1 if i == 12: return res self.meta_interp(main, [])
def listItemType(lst): LIST = typeOf(lst) return LIST.TO.ITEM
def op_debug_fatalerror(ll_msg): from rpython.rtyper.lltypesystem import lltype, rstr from rpython.rtyper.llinterp import LLFatalError assert lltype.typeOf(ll_msg) == lltype.Ptr(rstr.STR) msg = ''.join(ll_msg.chars) raise LLFatalError(msg)
def PyPy_TypedefTest1(space, arg): assert lltype.typeOf(arg) == Py_ssize_t return 0
def test_virtual_adder_make_virtual(): b2s, b3s, b4s, b5s = [ RefFrontendOp(0), IntFrontendOp(0), RefFrontendOp(0), RefFrontendOp(0) ] c1s = ConstInt(111) storage = Storage() memo = ResumeDataLoopMemo(FakeMetaInterpStaticData()) modifier = ResumeDataVirtualAdder(FakeOptimizer(), storage, storage, None, memo) modifier.liveboxes_from_env = {} modifier.liveboxes = {} modifier.vfieldboxes = {} vdescr = LLtypeMixin.nodesize2 ca = ConstInt(ptr2int(LLtypeMixin.node_vtable2)) v4 = info.InstancePtrInfo(vdescr, ca, True) b4s.set_forwarded(v4) v4.setfield(LLtypeMixin.nextdescr, ca, b2s) v4.setfield(LLtypeMixin.valuedescr, ca, b3s) v4.setfield(LLtypeMixin.otherdescr, ca, b5s) ca = ConstInt(ptr2int(LLtypeMixin.node_vtable)) v2 = info.InstancePtrInfo(LLtypeMixin.nodesize, ca, True) v2.setfield(LLtypeMixin.nextdescr, b4s, ca) v2.setfield(LLtypeMixin.valuedescr, c1s, ca) b2s.set_forwarded(v2) modifier.register_virtual_fields(b2s, [c1s, None, None, None, b4s]) modifier.register_virtual_fields(b4s, [b3s, None, None, None, b2s, b5s]) liveboxes = [] modifier._number_virtuals(liveboxes, 0) storage.rd_consts = memo.consts[:] storage.rd_numb = Numbering([0]) # resume b3t, b5t = [IntFrontendOp(0), RefFrontendOp(0)] b5t.setref_base(demo55o) b3t.setint(33) newboxes = _resume_remap( liveboxes, [ #b2s -- virtual b3s, #b4s -- virtual #b2s -- again, shared #b3s -- again, shared b5s ], b3t, b5t) metainterp = MyMetaInterp() reader = ResumeDataFakeReader(storage, newboxes, metainterp) assert len(reader.virtuals_cache.virtuals_ptr_cache) == 2 b2t = reader.decode_ref(modifier._gettagged(b2s)) b4t = reader.decode_ref(modifier._gettagged(b4s)) trace = metainterp.trace b2new = (rop.NEW_WITH_VTABLE, [], b2t.getref_base(), LLtypeMixin.nodesize) b4new = (rop.NEW_WITH_VTABLE, [], b4t.getref_base(), LLtypeMixin.nodesize2) b2set = [(rop.SETFIELD_GC, [b2t, b4t], None, LLtypeMixin.nextdescr), (rop.SETFIELD_GC, [b2t, c1s], None, LLtypeMixin.valuedescr)] b4set = [(rop.SETFIELD_GC, [b4t, b2t], None, LLtypeMixin.nextdescr), (rop.SETFIELD_GC, [b4t, b3t], None, LLtypeMixin.valuedescr), (rop.SETFIELD_GC, [b4t, b5t], None, LLtypeMixin.otherdescr)] expected = [b2new, b4new] + b4set + b2set # check that we get the operations in 'expected', in a possibly different # order. assert len(trace) == len(expected) orig = trace[:] with CompareableConsts(): for x in trace: assert x in expected expected.remove(x) ptr = b2t.getref_base()._obj.container._as_ptr() assert lltype.typeOf(ptr) == lltype.Ptr(LLtypeMixin.NODE) assert ptr.value == 111 ptr2 = ptr.next ptr2 = lltype.cast_pointer(lltype.Ptr(LLtypeMixin.NODE2), ptr2) assert ptr2.other == demo55 assert ptr2.parent.value == 33 assert ptr2.parent.next == ptr
def op_int_between(a, b, c): assert lltype.typeOf(a) is lltype.Signed assert lltype.typeOf(b) is lltype.Signed assert lltype.typeOf(c) is lltype.Signed return a <= b < c
def op_int_force_ge_zero(a): assert lltype.typeOf(a) is lltype.Signed if a < 0: return 0 return a
def op_cast_primitive(TYPE, value): assert isinstance(lltype.typeOf(value), lltype.Primitive) return lltype.cast_primitive(TYPE, value)
def most_pos_value_of_same_type(x): from rpython.rtyper.lltypesystem import lltype return most_pos_value_of(lltype.typeOf(x))
def op_raw_store(p, ofs, newvalue): from rpython.rtyper.lltypesystem import rffi p = rffi.cast(llmemory.Address, p) TVAL = lltype.typeOf(newvalue) p = rffi.cast(rffi.CArrayPtr(TVAL), p + ofs) p[0] = newvalue
def op_getsubstruct(obj, field): checkptr(obj) # check the difference between op_getfield and op_getsubstruct: assert isinstance(getattr(lltype.typeOf(obj).TO, field), lltype.ContainerType) return getattr(obj, field)
def setfield(self, struct, fieldnum, descr): assert lltype.typeOf(struct) is lltype.Signed assert lltype.typeOf(fieldnum) is rffi.SHORT fieldnum = rffi.cast(lltype.Signed, fieldnum) self.got.append((descr, struct, fieldnum))
def __getitem__(self, key): F = lltype.FuncType([lltype.Signed, lltype.Signed], lltype.Signed) f = lltype.functionptr(F, key[0]) c_func = Constant(f, lltype.typeOf(f)) return c_func, lltype.Signed
def PyPy_TypedefTest2(space, arg): assert lltype.typeOf(arg) == Py_ssize_tP return None
def getTYPE(self): return typeOf(self.obj)
def PyPy_GetReference(space, arg): assert lltype.typeOf(arg) == PyObject
def op_getarrayitem(p, index): checkptr(p) ARRAY = lltype.typeOf(p).TO if not ARRAY._immutable_field(index): raise TypeError("cannot fold getarrayitem on mutable array") return p[index]
def newconst(x): return Constant(x, lltype.typeOf(x))
def checkadr(adr): if lltype.typeOf(adr) is not llmemory.Address: raise TypeError("arg must be an address, got %r instead" % (lltype.typeOf(adr), ))
def inittime_helper(self, ll_helper, ll_args, ll_result, inline=True): ptr = self.annotate_helper(ll_helper, ll_args, ll_result, inline=inline) return Constant(ptr, lltype.typeOf(ptr))
def checkptr(ptr): if not isinstance(lltype.typeOf(ptr), lltype.Ptr): raise TypeError("arg must be a pointer, got %r instead" % (lltype.typeOf(ptr), ))
def ll_arraycopy(source, dest, source_start, dest_start, length): SRCTYPE = typeOf(source) # lltype rgc.ll_arraycopy(source.ll_items(), dest.ll_items(), source_start, dest_start, length)
def ll_bool(ll_builder): return ll_builder != nullptr(lltype.typeOf(ll_builder).TO)
def _ll_1_jit_force_virtual(inst): return llop.jit_force_virtual(lltype.typeOf(inst), inst)
def setarrayitem(self, array, index, fieldnum, arraydescr): assert lltype.typeOf(array) is lltype.Signed assert lltype.typeOf(index) is lltype.Signed assert lltype.typeOf(fieldnum) is rffi.SHORT fieldnum = rffi.cast(lltype.Signed, fieldnum) self.got_array.append((arraydescr, array, index, fieldnum))
def direct_ptradd(ptr, offset): offset = rffi.cast(rffi.SIZE_T, offset) jit.promote(offset) assert lltype.typeOf(ptr) == C_OBJECT address = rffi.cast(rffi.CCHARP, ptr) return rffi.cast(C_OBJECT, lltype.direct_ptradd(address, offset))
def op_adr_sub(addr, offset): checkadr(addr) assert lltype.typeOf(offset) is lltype.Signed return addr - offset
def annotation(x): T = typeOf(x) return lltype_to_annotation(T)
def widen(n): from rpython.rtyper.lltypesystem import lltype if _should_widen_type(lltype.typeOf(n)): return intmask(n) else: return n