PageRenderTime 66ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/jit/backend/llgraph/llimpl.py

http://github.com/pypy/pypy
Python | 1949 lines | 1748 code | 130 blank | 71 comment | 105 complexity | 76ca5850b749c784c84f99515ffed2e7 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. """
  2. The non-RPythonic part of the llgraph backend.
  3. This contains all the code that is directly run
  4. when executing on top of the llinterpreter.
  5. """
  6. import weakref
  7. from pypy.objspace.flow.model import Variable, Constant
  8. from pypy.annotation import model as annmodel
  9. from pypy.jit.metainterp.history import REF, INT, FLOAT
  10. from pypy.jit.metainterp import history
  11. from pypy.jit.codewriter import heaptracker
  12. from pypy.rpython.lltypesystem import lltype, llmemory, rclass, rstr, rffi
  13. from pypy.rpython.ootypesystem import ootype
  14. from pypy.rpython.module.support import LLSupport, OOSupport
  15. from pypy.rpython.llinterp import LLException
  16. from pypy.rpython.extregistry import ExtRegistryEntry
  17. from pypy.jit.metainterp import resoperation
  18. from pypy.jit.metainterp.resoperation import rop
  19. from pypy.jit.backend.llgraph import symbolic
  20. from pypy.jit.codewriter import longlong
  21. from pypy.rlib import libffi, clibffi
  22. from pypy.rlib.objectmodel import ComputedIntSymbolic, we_are_translated
  23. from pypy.rlib.rarithmetic import ovfcheck
  24. from pypy.rlib.rarithmetic import r_longlong, r_ulonglong, r_uint
  25. from pypy.rlib.rtimer import read_timestamp
  26. import py
  27. from pypy.tool.ansi_print import ansi_log
  28. log = py.log.Producer('runner')
  29. py.log.setconsumer('runner', ansi_log)
  30. IS_32_BIT = r_ulonglong is not r_uint
  31. def _from_opaque(opq):
  32. return opq._obj.externalobj
  33. _TO_OPAQUE = {}
  34. def _to_opaque(value):
  35. try:
  36. return value._the_opaque_pointer
  37. except AttributeError:
  38. op = lltype.opaqueptr(_TO_OPAQUE[value.__class__], 'opaque',
  39. externalobj=value)
  40. value._the_opaque_pointer = op
  41. return op
  42. def _normalize(value):
  43. if isinstance(value, lltype._ptr):
  44. value = lltype.top_container(value._obj)
  45. return value
  46. def from_opaque_string(s):
  47. if isinstance(s, str):
  48. return s
  49. elif isinstance(s, ootype._string):
  50. return OOSupport.from_rstr(s)
  51. else:
  52. return LLSupport.from_rstr(s)
  53. FLOAT_ARRAY_TP = lltype.Ptr(lltype.Array(lltype.Float, hints={"nolength": True}))
  54. def maybe_uncast(TP, array):
  55. if array._TYPE.TO._hints.get("uncast_on_llgraph"):
  56. array = rffi.cast(TP, array)
  57. return array
  58. # a list of argtypes of all operations - couldn't find any and it's
  59. # very useful. Note however that the table is half-broken here and
  60. # there, in ways that are sometimes a bit hard to fix; that's why
  61. # it is not "official".
  62. TYPES = {
  63. 'int_add' : (('int', 'int'), 'int'),
  64. 'int_sub' : (('int', 'int'), 'int'),
  65. 'int_mul' : (('int', 'int'), 'int'),
  66. 'int_floordiv' : (('int', 'int'), 'int'),
  67. 'int_mod' : (('int', 'int'), 'int'),
  68. 'int_and' : (('int', 'int'), 'int'),
  69. 'int_or' : (('int', 'int'), 'int'),
  70. 'int_xor' : (('int', 'int'), 'int'),
  71. 'int_lshift' : (('int', 'int'), 'int'),
  72. 'int_rshift' : (('int', 'int'), 'int'),
  73. 'int_lt' : (('int', 'int'), 'bool'),
  74. 'int_gt' : (('int', 'int'), 'bool'),
  75. 'int_ge' : (('int', 'int'), 'bool'),
  76. 'int_le' : (('int', 'int'), 'bool'),
  77. 'int_eq' : (('int', 'int'), 'bool'),
  78. 'int_ne' : (('int', 'int'), 'bool'),
  79. 'int_is_true' : (('int',), 'bool'),
  80. 'int_is_zero' : (('int',), 'bool'),
  81. 'int_neg' : (('int',), 'int'),
  82. 'int_invert' : (('int',), 'int'),
  83. 'int_add_ovf' : (('int', 'int'), 'int'),
  84. 'int_sub_ovf' : (('int', 'int'), 'int'),
  85. 'int_mul_ovf' : (('int', 'int'), 'int'),
  86. 'uint_add' : (('int', 'int'), 'int'),
  87. 'uint_sub' : (('int', 'int'), 'int'),
  88. 'uint_mul' : (('int', 'int'), 'int'),
  89. 'uint_lt' : (('int', 'int'), 'bool'),
  90. 'uint_le' : (('int', 'int'), 'bool'),
  91. 'uint_eq' : (('int', 'int'), 'bool'),
  92. 'uint_ne' : (('int', 'int'), 'bool'),
  93. 'uint_gt' : (('int', 'int'), 'bool'),
  94. 'uint_ge' : (('int', 'int'), 'bool'),
  95. 'uint_xor' : (('int', 'int'), 'int'),
  96. 'uint_rshift' : (('int', 'int'), 'int'),
  97. 'uint_floordiv' : (('int', 'int'), 'int'),
  98. 'float_add' : (('float', 'float'), 'float'),
  99. 'float_sub' : (('float', 'float'), 'float'),
  100. 'float_mul' : (('float', 'float'), 'float'),
  101. 'float_truediv' : (('float', 'float'), 'float'),
  102. 'float_lt' : (('float', 'float'), 'bool'),
  103. 'float_le' : (('float', 'float'), 'bool'),
  104. 'float_eq' : (('float', 'float'), 'bool'),
  105. 'float_ne' : (('float', 'float'), 'bool'),
  106. 'float_gt' : (('float', 'float'), 'bool'),
  107. 'float_ge' : (('float', 'float'), 'bool'),
  108. 'float_neg' : (('float',), 'float'),
  109. 'float_abs' : (('float',), 'float'),
  110. 'cast_float_to_int':(('float',), 'int'),
  111. 'cast_int_to_float':(('int',), 'float'),
  112. 'same_as' : (('int',), 'int'), # could also be ptr=>ptr
  113. 'new_with_vtable' : (('ref',), 'ref'),
  114. 'new' : ((), 'ref'),
  115. 'new_array' : (('int',), 'ref'),
  116. 'oois' : (('ref', 'ref'), 'bool'),
  117. 'ooisnot' : (('ref', 'ref'), 'bool'),
  118. 'instanceof' : (('ref',), 'bool'),
  119. 'subclassof' : (('ref', 'ref'), 'bool'),
  120. 'runtimenew' : (('ref',), 'ref'),
  121. 'setfield_gc' : (('ref', 'intorptr'), None),
  122. 'getfield_gc' : (('ref',), 'intorptr'),
  123. 'getfield_gc_pure': (('ref',), 'intorptr'),
  124. 'setfield_raw' : (('ref', 'intorptr'), None),
  125. 'getfield_raw' : (('ref',), 'intorptr'),
  126. 'getfield_raw_pure': (('ref',), 'intorptr'),
  127. 'setarrayitem_gc' : (('ref', 'int', 'intorptr'), None),
  128. 'getarrayitem_gc' : (('ref', 'int'), 'intorptr'),
  129. 'getarrayitem_gc_pure' : (('ref', 'int'), 'intorptr'),
  130. 'setarrayitem_raw' : (('ref', 'int', 'intorptr'), None),
  131. 'getarrayitem_raw' : (('ref', 'int'), 'intorptr'),
  132. 'getarrayitem_raw_pure' : (('ref', 'int'), 'intorptr'),
  133. 'arraylen_gc' : (('ref',), 'int'),
  134. 'call' : (('ref', 'varargs'), 'intorptr'),
  135. 'call_assembler' : (('varargs',), 'intorptr'),
  136. 'cond_call_gc_wb' : (('ptr', 'ptr'), None),
  137. 'cond_call_gc_wb_array': (('ptr', 'int', 'ptr'), None),
  138. 'oosend' : (('varargs',), 'intorptr'),
  139. 'oosend_pure' : (('varargs',), 'intorptr'),
  140. 'guard_true' : (('bool',), None),
  141. 'guard_false' : (('bool',), None),
  142. 'guard_value' : (('int', 'int'), None),
  143. 'guard_class' : (('ref', 'ref'), None),
  144. 'guard_no_exception' : ((), None),
  145. 'guard_exception' : (('ref',), 'ref'),
  146. 'guard_no_overflow' : ((), None),
  147. 'guard_overflow' : ((), None),
  148. 'guard_nonnull' : (('ref',), None),
  149. 'guard_isnull' : (('ref',), None),
  150. 'guard_nonnull_class' : (('ref', 'ref'), None),
  151. 'newstr' : (('int',), 'ref'),
  152. 'strlen' : (('ref',), 'int'),
  153. 'strgetitem' : (('ref', 'int'), 'int'),
  154. 'strsetitem' : (('ref', 'int', 'int'), None),
  155. 'newunicode' : (('int',), 'ref'),
  156. 'unicodelen' : (('ref',), 'int'),
  157. 'unicodegetitem' : (('ref', 'int'), 'int'),
  158. 'unicodesetitem' : (('ref', 'int', 'int'), 'int'),
  159. 'cast_ptr_to_int' : (('ref',), 'int'),
  160. 'cast_int_to_ptr' : (('int',), 'ref'),
  161. 'debug_merge_point': (('ref', 'int', 'int'), None),
  162. 'force_token' : ((), 'int'),
  163. 'call_may_force' : (('int', 'varargs'), 'intorptr'),
  164. 'guard_not_forced': ((), None),
  165. }
  166. # ____________________________________________________________
  167. class CompiledLoop(object):
  168. has_been_freed = False
  169. invalid = False
  170. def __init__(self):
  171. self.inputargs = []
  172. self.operations = []
  173. def getargtypes(self):
  174. return [v.concretetype for v in self.inputargs]
  175. def __repr__(self):
  176. lines = []
  177. self.as_text(lines, 1)
  178. return 'CompiledLoop %s:\n%s' % (self.inputargs, '\n'.join(lines))
  179. def as_text(self, lines, indent):
  180. for op in self.operations:
  181. lines.append('\t'*indent + repr(op))
  182. class Operation(object):
  183. result = None
  184. descr = None
  185. jump_target = None
  186. fail_args = None
  187. def __init__(self, opnum):
  188. self.opnum = opnum
  189. self.args = []
  190. def __repr__(self):
  191. if self.result is not None:
  192. sres = repr0(self.result) + ' = '
  193. else:
  194. sres = ''
  195. return '{%s%s(%s)}' % (sres, self.getopname(),
  196. ', '.join(map(repr0, self.args)))
  197. def getopname(self):
  198. try:
  199. return resoperation.opname[self.opnum]
  200. except KeyError:
  201. return '<%d>' % self.opnum
  202. def is_guard(self):
  203. return rop._GUARD_FIRST <= self.opnum <= rop._GUARD_LAST
  204. def is_final(self):
  205. return rop._FINAL_FIRST <= self.opnum <= rop._FINAL_LAST
  206. def repr0(x):
  207. if isinstance(x, list):
  208. return '[' + ', '.join(repr0(y) for y in x) + ']'
  209. elif isinstance(x, Constant):
  210. return '(' + repr0(x.value) + ')'
  211. elif isinstance(x, lltype._ptr):
  212. x = llmemory.cast_ptr_to_adr(x)
  213. if x.ptr:
  214. try:
  215. container = x.ptr._obj._normalizedcontainer()
  216. return '* %s' % (container._TYPE._short_name(),)
  217. except AttributeError:
  218. return repr(x)
  219. else:
  220. return 'NULL'
  221. else:
  222. return repr(x)
  223. def repr_list(lst, types):
  224. res_l = []
  225. if types and types[-1] == 'varargs':
  226. types = types[:-1] + ('int',) * (len(lst) - len(types) + 1)
  227. assert len(types) == len(lst)
  228. for elem, tp in zip(lst, types):
  229. if isinstance(elem, Constant):
  230. res_l.append('(%s)' % repr1(elem, tp))
  231. else:
  232. res_l.append(repr1(elem, tp))
  233. return '[%s]' % (', '.join(res_l))
  234. def repr1(x, tp):
  235. if tp == "intorptr":
  236. TYPE = lltype.typeOf(x)
  237. if isinstance(TYPE, lltype.Ptr) and TYPE.TO._gckind == 'gc':
  238. tp = "ref"
  239. else:
  240. tp = "int"
  241. if tp == 'int':
  242. return str(x)
  243. elif tp == 'void':
  244. return '---'
  245. elif tp == 'ref':
  246. if not x:
  247. return '(* None)'
  248. if isinstance(x, int):
  249. # XXX normalize?
  250. ptr = str(llmemory.cast_int_to_adr(x))
  251. elif isinstance(ootype.typeOf(x), ootype.OOType):
  252. return repr(x)
  253. else:
  254. if getattr(x, '_fake', None):
  255. return repr(x)
  256. if lltype.typeOf(x) == llmemory.GCREF:
  257. TP = lltype.Ptr(lltype.typeOf(x._obj.container))
  258. ptr = lltype.cast_opaque_ptr(TP, x)
  259. else:
  260. ptr = x
  261. try:
  262. container = ptr._obj._normalizedcontainer()
  263. return '(* %s)' % (container._TYPE._short_name(),)
  264. except AttributeError:
  265. return '(%r)' % (ptr,)
  266. elif tp == 'bool':
  267. assert x == 0 or x == 1
  268. return str(bool(x))
  269. #elif tp == 'fieldname':
  270. # return str(symbolic.TokenToField[x...][1])
  271. elif tp == 'float':
  272. return str(x)
  273. else:
  274. raise NotImplementedError("tp = %s" % tp)
  275. _variables = []
  276. def compile_start():
  277. del _variables[:]
  278. return _to_opaque(CompiledLoop())
  279. def mark_as_free(loop):
  280. loop = _from_opaque(loop)
  281. assert not loop.has_been_freed
  282. loop.has_been_freed = True
  283. def compile_start_int_var(loop):
  284. return compile_start_ref_var(loop, lltype.Signed)
  285. def compile_start_float_var(loop):
  286. return compile_start_ref_var(loop, longlong.FLOATSTORAGE)
  287. def compile_start_ref_var(loop, TYPE):
  288. loop = _from_opaque(loop)
  289. assert not loop.operations
  290. v = Variable()
  291. v.concretetype = TYPE
  292. loop.inputargs.append(v)
  293. r = len(_variables)
  294. _variables.append(v)
  295. return r
  296. def compile_started_vars(clt):
  297. if not hasattr(clt, '_debug_argtypes'): # only when compiling the loop
  298. argtypes = [v.concretetype for v in _variables]
  299. try:
  300. clt._debug_argtypes = argtypes
  301. except AttributeError: # when 'clt' is actually a translated
  302. pass # GcStruct
  303. def compile_add(loop, opnum):
  304. loop = _from_opaque(loop)
  305. loop.operations.append(Operation(opnum))
  306. def compile_add_descr(loop, ofs, type, arg_types, extrainfo, width):
  307. from pypy.jit.backend.llgraph.runner import Descr
  308. loop = _from_opaque(loop)
  309. op = loop.operations[-1]
  310. assert isinstance(type, str) and len(type) == 1
  311. op.descr = Descr(ofs, type, arg_types=arg_types, extrainfo=extrainfo, width=width)
  312. def compile_add_descr_arg(loop, ofs, type, arg_types):
  313. from pypy.jit.backend.llgraph.runner import Descr
  314. loop = _from_opaque(loop)
  315. op = loop.operations[-1]
  316. assert isinstance(type, str) and len(type) == 1
  317. op.args.append(Descr(ofs, type, arg_types=arg_types))
  318. def compile_add_loop_token(loop, descr):
  319. if we_are_translated():
  320. raise ValueError("CALL_ASSEMBLER not supported")
  321. loop = _from_opaque(loop)
  322. op = loop.operations[-1]
  323. op.descr = weakref.ref(descr)
  324. TARGET_TOKENS = weakref.WeakKeyDictionary()
  325. def compile_add_target_token(loop, descr, clt):
  326. # here, 'clt' is the compiled_loop_token of the original loop that
  327. # we are compiling
  328. loop = _from_opaque(loop)
  329. op = loop.operations[-1]
  330. descrobj = _normalize(descr)
  331. TARGET_TOKENS[descrobj] = loop, len(loop.operations), op.args, clt
  332. def compile_add_var(loop, intvar):
  333. loop = _from_opaque(loop)
  334. op = loop.operations[-1]
  335. op.args.append(_variables[intvar])
  336. def compile_add_int_const(loop, value):
  337. compile_add_ref_const(loop, value, lltype.Signed)
  338. def compile_add_float_const(loop, value):
  339. compile_add_ref_const(loop, value, longlong.FLOATSTORAGE)
  340. def compile_add_ref_const(loop, value, TYPE):
  341. loop = _from_opaque(loop)
  342. const = Constant(value)
  343. const.concretetype = TYPE
  344. op = loop.operations[-1]
  345. op.args.append(const)
  346. def compile_add_int_result(loop):
  347. return compile_add_ref_result(loop, lltype.Signed)
  348. def compile_add_float_result(loop):
  349. return compile_add_ref_result(loop, longlong.FLOATSTORAGE)
  350. def compile_add_ref_result(loop, TYPE):
  351. loop = _from_opaque(loop)
  352. v = Variable()
  353. v.concretetype = TYPE
  354. op = loop.operations[-1]
  355. op.result = v
  356. r = len(_variables)
  357. _variables.append(v)
  358. return r
  359. def compile_add_jump_target(loop, targettoken, source_clt):
  360. loop = _from_opaque(loop)
  361. descrobj = _normalize(targettoken)
  362. (loop_target, target_opindex, target_inputargs, target_clt
  363. ) = TARGET_TOKENS[descrobj]
  364. #
  365. try:
  366. assert source_clt._debug_argtypes == target_clt._debug_argtypes
  367. except AttributeError: # when translated
  368. pass
  369. #
  370. op = loop.operations[-1]
  371. op.jump_target = loop_target
  372. op.jump_target_opindex = target_opindex
  373. op.jump_target_inputargs = target_inputargs
  374. assert op.opnum == rop.JUMP
  375. assert [v.concretetype for v in op.args] == (
  376. [v.concretetype for v in target_inputargs])
  377. #
  378. if loop_target == loop:
  379. log.info("compiling new loop")
  380. else:
  381. log.info("compiling new bridge")
  382. def compile_add_guard_jump_target(loop, loop_target):
  383. loop = _from_opaque(loop)
  384. loop_target = _from_opaque(loop_target)
  385. op = loop.operations[-1]
  386. assert op.is_guard()
  387. op.jump_target = loop_target
  388. def compile_add_fail(loop, fail_index):
  389. loop = _from_opaque(loop)
  390. index = len(loop.operations)-1
  391. op = loop.operations[index]
  392. op.fail_index = fail_index
  393. return index
  394. def compile_add_fail_arg(loop, intvar):
  395. loop = _from_opaque(loop)
  396. op = loop.operations[-1]
  397. if op.fail_args is None:
  398. op.fail_args = []
  399. if intvar == -1:
  400. op.fail_args.append(None)
  401. else:
  402. op.fail_args.append(_variables[intvar])
  403. def compile_redirect_fail(old_loop, old_index, new_loop):
  404. old_loop = _from_opaque(old_loop)
  405. new_loop = _from_opaque(new_loop)
  406. guard_op = old_loop.operations[old_index]
  407. assert guard_op.is_guard()
  408. guard_op.jump_target = new_loop
  409. # check that the bridge's inputargs are of the correct number and
  410. # kind for the guard
  411. if guard_op.fail_args is not None:
  412. argkinds = [v.concretetype for v in guard_op.fail_args if v]
  413. else:
  414. argkinds = []
  415. assert argkinds == [v.concretetype for v in new_loop.inputargs]
  416. # ------------------------------
  417. class Frame(object):
  418. OPHANDLERS = [None] * (rop._LAST+1)
  419. def __init__(self, cpu):
  420. self.verbose = False
  421. self.cpu = cpu
  422. self.opindex = 1
  423. self._forced = False
  424. self._may_force = -1
  425. def getenv(self, v):
  426. from pypy.jit.backend.llgraph.runner import Descr
  427. if isinstance(v, Constant):
  428. return v.value
  429. elif isinstance(v, Descr):
  430. return v
  431. else:
  432. return self.env[v]
  433. def _populate_fail_args(self, op, skip=None):
  434. fail_args = []
  435. if op.fail_args:
  436. for fail_arg in op.fail_args:
  437. if fail_arg is None:
  438. fail_args.append(None)
  439. elif fail_arg is skip:
  440. fail_args.append(fail_arg.concretetype._defl())
  441. else:
  442. fail_args.append(self.getenv(fail_arg))
  443. self.fail_args = fail_args
  444. self.fail_index = op.fail_index
  445. def execute(self):
  446. """Execute all operations in a loop,
  447. possibly following to other loops as well.
  448. """
  449. global _last_exception
  450. assert _last_exception is None, "exception left behind"
  451. verbose = True
  452. self.opindex = 0
  453. while True:
  454. assert not self.loop.has_been_freed
  455. op = self.loop.operations[self.opindex]
  456. args = [self.getenv(v) for v in op.args]
  457. if not op.is_final():
  458. try:
  459. result = self.execute_operation(op.opnum, args, op.descr,
  460. verbose)
  461. except GuardFailed:
  462. assert op.is_guard()
  463. _stats.exec_conditional_jumps += 1
  464. if op.jump_target is not None:
  465. # a patched guard, pointing to further code
  466. if op.fail_args:
  467. args = [self.getenv(v) for v in op.fail_args if v]
  468. else:
  469. args = []
  470. assert len(op.jump_target.inputargs) == len(args)
  471. self.env = dict(zip(op.jump_target.inputargs, args))
  472. self.loop = op.jump_target
  473. self.opindex = 0
  474. continue
  475. else:
  476. self._populate_fail_args(op)
  477. # a non-patched guard
  478. if self.verbose:
  479. log.trace('failed: %s' % (
  480. ', '.join(map(str, fail_args)),))
  481. return op.fail_index
  482. #verbose = self.verbose
  483. assert (result is None) == (op.result is None)
  484. if op.result is not None:
  485. RESTYPE = op.result.concretetype
  486. if RESTYPE is lltype.Signed:
  487. x = self.as_int(result)
  488. elif RESTYPE is llmemory.GCREF:
  489. x = self.as_ptr(result)
  490. elif RESTYPE is ootype.Object:
  491. x = self.as_object(result)
  492. elif RESTYPE is longlong.FLOATSTORAGE:
  493. x = self.as_floatstorage(result)
  494. else:
  495. raise Exception("op.result.concretetype is %r"
  496. % (RESTYPE,))
  497. self.env[op.result] = x
  498. self.opindex += 1
  499. continue
  500. if op.opnum == rop.JUMP:
  501. inputargs = op.jump_target_inputargs
  502. assert len(inputargs) == len(args)
  503. self.env = dict(zip(inputargs, args))
  504. self.loop = op.jump_target
  505. self.opindex = op.jump_target_opindex
  506. _stats.exec_jumps += 1
  507. elif op.opnum == rop.FINISH:
  508. if self.verbose:
  509. log.trace('finished: %s' % (
  510. ', '.join(map(str, args)),))
  511. self.fail_args = args
  512. return op.fail_index
  513. else:
  514. assert 0, "unknown final operation %d" % (op.opnum,)
  515. def execute_operation(self, opnum, values, descr, verbose):
  516. """Execute a single operation.
  517. """
  518. ophandler = self.OPHANDLERS[opnum]
  519. if ophandler is None:
  520. self._define_impl(opnum)
  521. ophandler = self.OPHANDLERS[opnum]
  522. assert ophandler is not None, "missing impl for op %d" % opnum
  523. opname = resoperation.opname[opnum].lower()
  524. exec_counters = _stats.exec_counters
  525. exec_counters[opname] = exec_counters.get(opname, 0) + 1
  526. for i in range(len(values)):
  527. if isinstance(values[i], ComputedIntSymbolic):
  528. values[i] = values[i].compute_fn()
  529. res = NotImplemented
  530. try:
  531. res = ophandler(self, descr, *values)
  532. finally:
  533. if 0: # if verbose:
  534. argtypes, restype = TYPES[opname]
  535. if res is None:
  536. resdata = ''
  537. elif res is NotImplemented:
  538. resdata = '*fail*'
  539. else:
  540. resdata = '-> ' + repr1(res, restype)
  541. # fish the types
  542. log.cpu('\t%s %s %s' % (opname, repr_list(values, argtypes),
  543. resdata))
  544. return res
  545. def as_int(self, x):
  546. return cast_to_int(x)
  547. def as_ptr(self, x):
  548. return cast_to_ptr(x)
  549. def as_object(self, x):
  550. return ootype.cast_to_object(x)
  551. def as_floatstorage(self, x):
  552. return cast_to_floatstorage(x)
  553. def log_progress(self):
  554. count = sum(_stats.exec_counters.values())
  555. count_jumps = _stats.exec_jumps
  556. log.trace('ran %d operations, %d jumps' % (count, count_jumps))
  557. # ----------
  558. @classmethod
  559. def _define_impl(cls, opnum):
  560. opname = resoperation.opname[opnum]
  561. try:
  562. op = getattr(cls, 'op_' + opname.lower()) # op_guard_true etc.
  563. except AttributeError:
  564. try:
  565. impl = globals()['do_' + opname.lower()] # do_arraylen_gc etc.
  566. def op(self, descr, *args):
  567. if descr is None:
  568. return impl(*args)
  569. else:
  570. return impl(descr, *args)
  571. except KeyError:
  572. op = cls._make_impl_from_blackhole_interp(opname)
  573. cls.OPHANDLERS[opnum] = op
  574. @classmethod
  575. def _make_impl_from_blackhole_interp(cls, opname):
  576. from pypy.jit.metainterp.blackhole import BlackholeInterpreter
  577. name = 'bhimpl_' + opname.lower()
  578. func = BlackholeInterpreter.__dict__[name]
  579. for argtype in func.argtypes:
  580. assert argtype in ('i', 'r', 'f')
  581. #
  582. def _op_default_implementation(self, descr, *args):
  583. # for all operations implemented in the blackhole interpreter
  584. return func(*args)
  585. #
  586. return _op_default_implementation
  587. def op_label(self, _, *args):
  588. op = self.loop.operations[self.opindex]
  589. assert op.opnum == rop.LABEL
  590. assert len(op.args) == len(args)
  591. newenv = {}
  592. for v, value in zip(op.args, args):
  593. newenv[v] = value
  594. self.env = newenv
  595. def op_debug_merge_point(self, _, *args):
  596. from pypy.jit.metainterp.warmspot import get_stats
  597. try:
  598. stats = get_stats()
  599. except AttributeError:
  600. pass
  601. else:
  602. stats.add_merge_point_location(args[1:])
  603. pass
  604. def op_guard_true(self, _, value):
  605. if not value:
  606. raise GuardFailed
  607. def op_guard_false(self, _, value):
  608. if value:
  609. raise GuardFailed
  610. op_guard_nonnull = op_guard_true
  611. op_guard_isnull = op_guard_false
  612. def op_guard_class(self, _, value, expected_class):
  613. value = lltype.cast_opaque_ptr(rclass.OBJECTPTR, value)
  614. expected_class = llmemory.cast_adr_to_ptr(
  615. llmemory.cast_int_to_adr(expected_class),
  616. rclass.CLASSTYPE)
  617. if value.typeptr != expected_class:
  618. raise GuardFailed
  619. def op_guard_nonnull_class(self, _, value, expected_class):
  620. if not value:
  621. raise GuardFailed
  622. self.op_guard_class(_, value, expected_class)
  623. def op_guard_value(self, _, value, expected_value):
  624. if value != expected_value:
  625. raise GuardFailed
  626. def op_guard_no_exception(self, _):
  627. if _last_exception:
  628. raise GuardFailed
  629. def _check_exception(self, expected_exception):
  630. global _last_exception
  631. expected_exception = self._cast_exception(expected_exception)
  632. assert expected_exception
  633. exc = _last_exception
  634. if exc:
  635. got = exc.args[0]
  636. # exact match!
  637. if got != expected_exception:
  638. return False
  639. return True
  640. else:
  641. return False
  642. def _cast_exception(self, exception):
  643. return llmemory.cast_adr_to_ptr(
  644. llmemory.cast_int_to_adr(exception),
  645. rclass.CLASSTYPE)
  646. def _issubclass(self, cls1, cls2):
  647. return rclass.ll_issubclass(cls1, cls2)
  648. def op_guard_exception(self, _, expected_exception):
  649. global _last_exception
  650. if not self._check_exception(expected_exception):
  651. raise GuardFailed
  652. res = _last_exception[1]
  653. _last_exception = None
  654. return res
  655. def op_guard_no_overflow(self, _):
  656. flag = self.overflow_flag
  657. del self.overflow_flag
  658. if flag:
  659. raise GuardFailed
  660. def op_guard_overflow(self, _):
  661. flag = self.overflow_flag
  662. del self.overflow_flag
  663. if not flag:
  664. raise GuardFailed
  665. def op_int_add_ovf(self, _, x, y):
  666. try:
  667. z = ovfcheck(x + y)
  668. except OverflowError:
  669. ovf = True
  670. z = 0
  671. else:
  672. ovf = False
  673. self.overflow_flag = ovf
  674. return z
  675. def op_int_sub_ovf(self, _, x, y):
  676. try:
  677. z = ovfcheck(x - y)
  678. except OverflowError:
  679. ovf = True
  680. z = 0
  681. else:
  682. ovf = False
  683. self.overflow_flag = ovf
  684. return z
  685. def op_int_mul_ovf(self, _, x, y):
  686. try:
  687. z = ovfcheck(x * y)
  688. except OverflowError:
  689. ovf = True
  690. z = 0
  691. else:
  692. ovf = False
  693. self.overflow_flag = ovf
  694. return z
  695. def op_keepalive(self, _, x):
  696. pass
  697. # ----------
  698. # delegating to the builtins do_xxx() (done automatically for simple cases)
  699. def op_getarrayitem_gc(self, arraydescr, array, index):
  700. if arraydescr.typeinfo == REF:
  701. return do_getarrayitem_gc_ptr(array, index)
  702. elif arraydescr.typeinfo == INT:
  703. return do_getarrayitem_gc_int(array, index)
  704. elif arraydescr.typeinfo == FLOAT:
  705. return do_getarrayitem_gc_float(array, index)
  706. else:
  707. raise NotImplementedError
  708. op_getarrayitem_gc_pure = op_getarrayitem_gc
  709. def op_getarrayitem_raw(self, arraydescr, array, index):
  710. if arraydescr.typeinfo == REF:
  711. raise NotImplementedError("getarrayitem_raw -> gcref")
  712. elif arraydescr.typeinfo == INT:
  713. return do_getarrayitem_raw_int(array, index)
  714. elif arraydescr.typeinfo == FLOAT:
  715. return do_getarrayitem_raw_float(array, index)
  716. else:
  717. raise NotImplementedError
  718. op_getarrayitem_raw_pure = op_getarrayitem_raw
  719. def op_getfield_gc(self, fielddescr, struct):
  720. if fielddescr.typeinfo == REF:
  721. return do_getfield_gc_ptr(struct, fielddescr.ofs)
  722. elif fielddescr.typeinfo == INT:
  723. return do_getfield_gc_int(struct, fielddescr.ofs)
  724. elif fielddescr.typeinfo == FLOAT:
  725. return do_getfield_gc_float(struct, fielddescr.ofs)
  726. else:
  727. raise NotImplementedError
  728. op_getfield_gc_pure = op_getfield_gc
  729. def op_getfield_raw(self, fielddescr, struct):
  730. if fielddescr.arg_types == 'dynamic': # abuse of .arg_types
  731. return do_getfield_raw_dynamic(struct, fielddescr)
  732. elif fielddescr.typeinfo == REF:
  733. return do_getfield_raw_ptr(struct, fielddescr.ofs)
  734. elif fielddescr.typeinfo == INT:
  735. return do_getfield_raw_int(struct, fielddescr.ofs)
  736. elif fielddescr.typeinfo == FLOAT:
  737. return do_getfield_raw_float(struct, fielddescr.ofs)
  738. else:
  739. raise NotImplementedError
  740. op_getfield_raw_pure = op_getfield_raw
  741. def op_new(self, size):
  742. return do_new(size.ofs)
  743. def op_new_with_vtable(self, descr, vtable):
  744. assert descr is None
  745. descr = heaptracker.vtable2descr(self.cpu, vtable)
  746. result = do_new(descr.ofs)
  747. value = lltype.cast_opaque_ptr(rclass.OBJECTPTR, result)
  748. value.typeptr = cast_from_int(rclass.CLASSTYPE, vtable)
  749. return result
  750. def op_setarrayitem_gc(self, arraydescr, array, index, newvalue):
  751. if arraydescr.typeinfo == REF:
  752. do_setarrayitem_gc_ptr(array, index, newvalue)
  753. elif arraydescr.typeinfo == INT:
  754. do_setarrayitem_gc_int(array, index, newvalue)
  755. elif arraydescr.typeinfo == FLOAT:
  756. do_setarrayitem_gc_float(array, index, newvalue)
  757. else:
  758. raise NotImplementedError
  759. def op_setarrayitem_raw(self, arraydescr, array, index, newvalue):
  760. if arraydescr.typeinfo == REF:
  761. raise NotImplementedError("setarrayitem_raw <- gcref")
  762. elif arraydescr.typeinfo == INT:
  763. do_setarrayitem_raw_int(array, index, newvalue)
  764. elif arraydescr.typeinfo == FLOAT:
  765. do_setarrayitem_raw_float(array, index, newvalue)
  766. else:
  767. raise NotImplementedError
  768. def op_getinteriorfield_gc(self, descr, array, index):
  769. if descr.typeinfo == REF:
  770. return do_getinteriorfield_gc_ptr(array, index, descr.ofs)
  771. elif descr.typeinfo == INT:
  772. return do_getinteriorfield_gc_int(array, index, descr.ofs)
  773. elif descr.typeinfo == FLOAT:
  774. return do_getinteriorfield_gc_float(array, index, descr.ofs)
  775. else:
  776. raise NotImplementedError
  777. def op_getinteriorfield_raw(self, descr, array, index):
  778. if descr.typeinfo == REF:
  779. return do_getinteriorfield_raw_ptr(array, index, descr.width, descr.ofs)
  780. elif descr.typeinfo == INT:
  781. return do_getinteriorfield_raw_int(array, index, descr.width, descr.ofs)
  782. elif descr.typeinfo == FLOAT:
  783. return do_getinteriorfield_raw_float(array, index, descr.width, descr.ofs)
  784. else:
  785. raise NotImplementedError
  786. def op_setinteriorfield_gc(self, descr, array, index, newvalue):
  787. if descr.typeinfo == REF:
  788. return do_setinteriorfield_gc_ptr(array, index, descr.ofs,
  789. newvalue)
  790. elif descr.typeinfo == INT:
  791. return do_setinteriorfield_gc_int(array, index, descr.ofs,
  792. newvalue)
  793. elif descr.typeinfo == FLOAT:
  794. return do_setinteriorfield_gc_float(array, index, descr.ofs,
  795. newvalue)
  796. else:
  797. raise NotImplementedError
  798. def op_setinteriorfield_raw(self, descr, array, index, newvalue):
  799. if descr.typeinfo == REF:
  800. return do_setinteriorfield_raw_ptr(array, index, newvalue, descr.width, descr.ofs)
  801. elif descr.typeinfo == INT:
  802. return do_setinteriorfield_raw_int(array, index, newvalue, descr.width, descr.ofs)
  803. elif descr.typeinfo == FLOAT:
  804. return do_setinteriorfield_raw_float(array, index, newvalue, descr.width, descr.ofs)
  805. else:
  806. raise NotImplementedError
  807. def op_setfield_gc(self, fielddescr, struct, newvalue):
  808. if fielddescr.typeinfo == REF:
  809. do_setfield_gc_ptr(struct, fielddescr.ofs, newvalue)
  810. elif fielddescr.typeinfo == INT:
  811. do_setfield_gc_int(struct, fielddescr.ofs, newvalue)
  812. elif fielddescr.typeinfo == FLOAT:
  813. do_setfield_gc_float(struct, fielddescr.ofs, newvalue)
  814. else:
  815. raise NotImplementedError
  816. def op_setfield_raw(self, fielddescr, struct, newvalue):
  817. if fielddescr.arg_types == 'dynamic': # abuse of .arg_types
  818. do_setfield_raw_dynamic(struct, fielddescr, newvalue)
  819. elif fielddescr.typeinfo == REF:
  820. do_setfield_raw_ptr(struct, fielddescr.ofs, newvalue)
  821. elif fielddescr.typeinfo == INT:
  822. do_setfield_raw_int(struct, fielddescr.ofs, newvalue)
  823. elif fielddescr.typeinfo == FLOAT:
  824. do_setfield_raw_float(struct, fielddescr.ofs, newvalue)
  825. else:
  826. raise NotImplementedError
  827. def op_call(self, calldescr, func, *args):
  828. return self._do_call(calldescr, func, args, call_with_llptr=False)
  829. def op_call_release_gil(self, calldescr, func, *args):
  830. return self._do_call(calldescr, func, args, call_with_llptr=True)
  831. def _do_call(self, calldescr, func, args, call_with_llptr):
  832. global _last_exception
  833. assert _last_exception is None, "exception left behind"
  834. assert _call_args_i == _call_args_r == _call_args_f == []
  835. args_in_order = []
  836. for x in args:
  837. T = lltype.typeOf(x)
  838. if T is lltype.Signed:
  839. args_in_order.append('i')
  840. _call_args_i.append(x)
  841. elif T == llmemory.GCREF:
  842. args_in_order.append('r')
  843. _call_args_r.append(x)
  844. elif T is longlong.FLOATSTORAGE:
  845. args_in_order.append('f')
  846. _call_args_f.append(x)
  847. else:
  848. raise TypeError(x)
  849. try:
  850. return _do_call_common(func, args_in_order, calldescr,
  851. call_with_llptr)
  852. except LLException, lle:
  853. _last_exception = lle
  854. d = {'v': None,
  855. REF: lltype.nullptr(llmemory.GCREF.TO),
  856. INT: 0,
  857. FLOAT: 0.0}
  858. return d[calldescr.typeinfo]
  859. def op_cond_call_gc_wb(self, descr, a, b):
  860. py.test.skip("cond_call_gc_wb not supported")
  861. def op_cond_call_gc_wb_array(self, descr, a, b, c):
  862. py.test.skip("cond_call_gc_wb_array not supported")
  863. def op_oosend(self, descr, obj, *args):
  864. raise NotImplementedError("oosend for lltype backend??")
  865. op_oosend_pure = op_oosend
  866. def op_new_array(self, arraydescr, count):
  867. return do_new_array(arraydescr.ofs, count)
  868. def op_force_token(self, descr):
  869. opaque_frame = _to_opaque(self)
  870. return llmemory.cast_ptr_to_adr(opaque_frame)
  871. def op_read_timestamp(self, descr):
  872. return read_timestamp()
  873. def op_call_may_force(self, calldescr, func, *args):
  874. assert not self._forced
  875. self._may_force = self.opindex
  876. try:
  877. return self.op_call(calldescr, func, *args)
  878. finally:
  879. self._may_force = -1
  880. def op_call_assembler(self, wref_loop_token, *args):
  881. if we_are_translated():
  882. raise ValueError("CALL_ASSEMBLER not supported")
  883. return self._do_call_assembler(wref_loop_token, *args)
  884. def _do_call_assembler(self, wref_loop_token, *args):
  885. global _last_exception
  886. loop_token = wref_loop_token()
  887. assert loop_token, "CALL_ASSEMBLER to a target that already died"
  888. ctl = loop_token.compiled_loop_token
  889. if hasattr(ctl, 'redirected'):
  890. return self._do_call_assembler(ctl.redirected, *args)
  891. assert not self._forced
  892. self._may_force = self.opindex
  893. try:
  894. inpargs = _from_opaque(ctl.compiled_version).inputargs
  895. assert len(inpargs) == len(args)
  896. for i, inparg in enumerate(inpargs):
  897. TYPE = inparg.concretetype
  898. if TYPE is lltype.Signed:
  899. set_future_value_int(i, args[i])
  900. elif isinstance(TYPE, lltype.Ptr):
  901. set_future_value_ref(i, args[i])
  902. elif TYPE is longlong.FLOATSTORAGE:
  903. set_future_value_float(i, args[i])
  904. else:
  905. raise Exception("Nonsense type %s" % TYPE)
  906. failindex = self.cpu._execute_token(loop_token)
  907. jd = loop_token.outermost_jitdriver_sd
  908. assert jd is not None, ("call_assembler(): the loop_token needs "
  909. "to have 'outermost_jitdriver_sd'")
  910. if jd.index_of_virtualizable != -1:
  911. vable = args[jd.index_of_virtualizable]
  912. else:
  913. vable = lltype.nullptr(llmemory.GCREF.TO)
  914. #
  915. # Emulate the fast path
  916. if failindex == self.cpu.done_with_this_frame_int_v:
  917. reset_vable(jd, vable)
  918. return self.cpu.get_latest_value_int(0)
  919. if failindex == self.cpu.done_with_this_frame_ref_v:
  920. reset_vable(jd, vable)
  921. return self.cpu.get_latest_value_ref(0)
  922. if failindex == self.cpu.done_with_this_frame_float_v:
  923. reset_vable(jd, vable)
  924. return self.cpu.get_latest_value_float(0)
  925. if failindex == self.cpu.done_with_this_frame_void_v:
  926. reset_vable(jd, vable)
  927. return None
  928. #
  929. assembler_helper_ptr = jd.assembler_helper_adr.ptr # fish
  930. try:
  931. return assembler_helper_ptr(failindex, vable)
  932. except LLException, lle:
  933. assert _last_exception is None, "exception left behind"
  934. _last_exception = lle
  935. # fish op
  936. op = self.loop.operations[self.opindex]
  937. if op.result is not None:
  938. return 0
  939. finally:
  940. self._may_force = -1
  941. def op_guard_not_forced(self, descr):
  942. forced = self._forced
  943. self._forced = False
  944. if forced:
  945. raise GuardFailed
  946. def op_guard_not_invalidated(self, descr):
  947. if self.loop.invalid:
  948. raise GuardFailed
  949. class OOFrame(Frame):
  950. OPHANDLERS = [None] * (rop._LAST+1)
  951. def op_new_with_vtable(self, descr, vtable):
  952. assert descr is None
  953. typedescr = get_class_size(self.memocast, vtable)
  954. return ootype.cast_to_object(ootype.new(typedescr.TYPE))
  955. def op_new_array(self, typedescr, count):
  956. res = ootype.oonewarray(typedescr.ARRAY, count)
  957. return ootype.cast_to_object(res)
  958. def op_getfield_gc(self, fielddescr, obj):
  959. TYPE = fielddescr.TYPE
  960. fieldname = fielddescr.fieldname
  961. _, T = TYPE._lookup_field(fieldname)
  962. obj = ootype.cast_from_object(TYPE, obj)
  963. res = getattr(obj, fieldname)
  964. if isinstance(T, ootype.OOType):
  965. return ootype.cast_to_object(res)
  966. return res
  967. op_getfield_gc_pure = op_getfield_gc
  968. def op_setfield_gc(self, fielddescr, obj, newvalue):
  969. TYPE = fielddescr.TYPE
  970. fieldname = fielddescr.fieldname
  971. _, T = TYPE._lookup_field(fieldname)
  972. obj = ootype.cast_from_object(TYPE, obj)
  973. if isinstance(ootype.typeOf(newvalue), ootype.OOType):
  974. newvalue = ootype.cast_from_object(T, newvalue)
  975. elif isinstance(T, lltype.Primitive):
  976. newvalue = lltype.cast_primitive(T, newvalue)
  977. setattr(obj, fieldname, newvalue)
  978. def op_getarrayitem_gc(self, typedescr, obj, index):
  979. array = ootype.cast_from_object(typedescr.ARRAY, obj)
  980. res = array.ll_getitem_fast(index)
  981. if isinstance(typedescr.TYPE, ootype.OOType):
  982. return ootype.cast_to_object(res)
  983. return res
  984. op_getarrayitem_gc_pure = op_getarrayitem_gc
  985. def op_setarrayitem_gc(self, typedescr, obj, index, objnewvalue):
  986. array = ootype.cast_from_object(typedescr.ARRAY, obj)
  987. if ootype.typeOf(objnewvalue) == ootype.Object:
  988. newvalue = ootype.cast_from_object(typedescr.TYPE, objnewvalue)
  989. else:
  990. newvalue = objnewvalue
  991. array.ll_setitem_fast(index, newvalue)
  992. def op_arraylen_gc(self, typedescr, obj):
  993. array = ootype.cast_from_object(typedescr.ARRAY, obj)
  994. return array.ll_length()
  995. def op_call(self, calldescr, func, *args):
  996. sm = ootype.cast_from_object(calldescr.FUNC, func)
  997. newargs = cast_call_args(calldescr.FUNC.ARGS, args)
  998. res = call_maybe_on_top_of_llinterp(sm, newargs)
  999. if isinstance(calldescr.FUNC.RESULT, ootype.OOType):
  1000. return ootype.cast_to_object(res)
  1001. return res
  1002. def op_oosend(self, descr, obj, *args):
  1003. METH = descr.METH
  1004. obj = ootype.cast_from_object(descr.SELFTYPE, obj)
  1005. meth = getattr(obj, descr.methname)
  1006. newargs = cast_call_args(METH.ARGS, args)
  1007. res = call_maybe_on_top_of_llinterp(meth, newargs)
  1008. if isinstance(METH.RESULT, ootype.OOType):
  1009. return ootype.cast_to_object(res)
  1010. return res
  1011. op_oosend_pure = op_oosend
  1012. def op_guard_class(self, _, value, expected_class):
  1013. value = ootype.cast_from_object(ootype.ROOT, value)
  1014. expected_class = ootype.cast_from_object(ootype.Class, expected_class)
  1015. if ootype.classof(value) is not expected_class:
  1016. raise GuardFailed
  1017. def op_runtimenew(self, _, cls):
  1018. cls = ootype.cast_from_object(ootype.Class, cls)
  1019. res = ootype.runtimenew(cls)
  1020. return ootype.cast_to_object(res)
  1021. def op_instanceof(self, typedescr, obj):
  1022. inst = ootype.cast_from_object(ootype.ROOT, obj)
  1023. return ootype.instanceof(inst, typedescr.TYPE)
  1024. def op_subclassof(self, _, obj1, obj2):
  1025. cls1 = ootype.cast_from_object(ootype.Class, obj1)
  1026. cls2 = ootype.cast_from_object(ootype.Class, obj2)
  1027. return ootype.subclassof(cls1, cls2)
  1028. def _cast_exception(self, exception):
  1029. return ootype.cast_from_object(ootype.Class, exception)
  1030. def _issubclass(self, cls1, cls2):
  1031. return ootype.subclassof(cls1, cls2)
  1032. # ____________________________________________________________
  1033. def cast_to_int(x):
  1034. TP = lltype.typeOf(x)
  1035. if isinstance(TP, lltype.Ptr):
  1036. return heaptracker.adr2int(llmemory.cast_ptr_to_adr(x))
  1037. if TP == llmemory.Address:
  1038. return heaptracker.adr2int(x)
  1039. if TP is lltype.SingleFloat:
  1040. return longlong.singlefloat2int(x)
  1041. return lltype.cast_primitive(lltype.Signed, x)
  1042. def cast_from_int(TYPE, x):
  1043. if isinstance(TYPE, lltype.Ptr):
  1044. if isinstance(x, (int, long, llmemory.AddressAsInt)):
  1045. x = llmemory.cast_int_to_adr(x)
  1046. if TYPE is rffi.VOIDP or (
  1047. hasattr(TYPE.TO, '_hints') and
  1048. TYPE.TO._hints.get("uncast_on_llgraph")):
  1049. # assume that we want a "C-style" cast, without typechecking the value
  1050. return rffi.cast(TYPE, x)
  1051. return llmemory.cast_adr_to_ptr(x, TYPE)
  1052. elif TYPE == llmemory.Address:
  1053. if isinstance(x, (int, long, llmemory.AddressAsInt)):
  1054. x = llmemory.cast_int_to_adr(x)
  1055. assert lltype.typeOf(x) == llmemory.Address
  1056. return x
  1057. elif TYPE is lltype.SingleFloat:
  1058. assert lltype.typeOf(x) is lltype.Signed
  1059. return longlong.int2singlefloat(x)
  1060. else:
  1061. if lltype.typeOf(x) == llmemory.Address:
  1062. x = heaptracker.adr2int(x)
  1063. return lltype.cast_primitive(TYPE, x)
  1064. def cast_to_ptr(x):
  1065. assert isinstance(lltype.typeOf(x), lltype.Ptr)
  1066. return lltype.cast_opaque_ptr(llmemory.GCREF, x)
  1067. def cast_from_ptr(TYPE, x):
  1068. return lltype.cast_opaque_ptr(TYPE, x)
  1069. def cast_to_floatstorage(x):
  1070. if isinstance(x, float):
  1071. return longlong.getfloatstorage(x) # common case
  1072. if IS_32_BIT:
  1073. assert longlong.supports_longlong
  1074. if isinstance(x, r_longlong):
  1075. return x
  1076. if isinstance(x, r_ulonglong):
  1077. return rffi.cast(lltype.SignedLongLong, x)
  1078. raise TypeError(type(x))
  1079. def cast_from_floatstorage(TYPE, x):
  1080. assert isinstance(x, longlong.r_float_storage)
  1081. if TYPE is lltype.Float:
  1082. return longlong.getrealfloat(x)
  1083. if longlong.is_longlong(TYPE):
  1084. return rffi.cast(TYPE, x)
  1085. raise TypeError(TYPE)
  1086. def new_frame(is_oo, cpu):
  1087. if is_oo:
  1088. frame = OOFrame(cpu)
  1089. else:
  1090. frame = Frame(cpu)
  1091. return _to_opaque(frame)
  1092. _future_values = []
  1093. def frame_clear(frame, loop):
  1094. frame = _from_opaque(frame)
  1095. loop = _from_opaque(loop)
  1096. assert len(_future_values) == len(loop.inputargs)
  1097. frame.loop = loop
  1098. frame.env = {}
  1099. for i in range(len(loop.inputargs)):
  1100. expected_type = loop.inputargs[i].concretetype
  1101. assert lltype.typeOf(_future_values[i]) == expected_type
  1102. frame.env[loop.inputargs[i]] = _future_values[i]
  1103. del _future_values[:]
  1104. def set_future_value_int(index, value):
  1105. assert lltype.typeOf(value) is lltype.Signed
  1106. set_future_value_ref(index, value)
  1107. def set_future_value_float(index, value):
  1108. assert isinstance(value, longlong.r_float_storage)
  1109. set_future_value_ref(index, value)
  1110. def set_future_value_ref(index, value):
  1111. del _future_values[index:]
  1112. assert len(_future_values) == index
  1113. _future_values.append(value)
  1114. def frame_execute(frame):
  1115. frame = _from_opaque(frame)
  1116. if frame.verbose:
  1117. values = [frame.env[v] for v in frame.loop.inputargs]
  1118. log.trace('Entering CPU frame <- %r' % (values,))
  1119. try:
  1120. result = frame.execute()
  1121. if frame.verbose:
  1122. log.trace('Leaving CPU frame -> #%d' % (result,))
  1123. frame.log_progress()
  1124. except Exception, e:
  1125. log.ERROR('%s in CPU frame: %s' % (e.__class__.__name__, e))
  1126. # Only invoke pdb when io capturing is not on otherwise py.io complains.
  1127. if py.test.config.option.capture == 'no':
  1128. import sys, pdb
  1129. pdb.post_mortem(sys.exc_info()[2])
  1130. raise
  1131. del frame.env
  1132. return result
  1133. def frame_int_getvalue(frame, num):
  1134. frame = _from_opaque(frame)
  1135. assert num >= 0
  1136. x = frame.fail_args[num]
  1137. assert lltype.typeOf(x) is lltype.Signed
  1138. return x
  1139. def frame_float_getvalue(frame, num):
  1140. frame = _from_opaque(frame)
  1141. assert num >= 0
  1142. x = frame.fail_args[num]
  1143. assert lltype.typeOf(x) is longlong.FLOATSTORAGE
  1144. return x
  1145. def frame_ptr_getvalue(frame, num):
  1146. frame = _from_opaque(frame)
  1147. assert num >= 0
  1148. x = frame.fail_args[num]
  1149. assert lltype.typeOf(x) == llmemory.GCREF
  1150. return x
  1151. def frame_get_value_count(frame):
  1152. frame = _from_opaque(frame)
  1153. return len(frame.fail_args)
  1154. def frame_clear_latest_values(frame, count):
  1155. frame = _from_opaque(frame)
  1156. assert count == len(frame.fail_args)
  1157. del frame.fail_args
  1158. _last_exception = None
  1159. def grab_exc_value():
  1160. global _last_exception
  1161. if _last_exception is not None:
  1162. result = _last_exception.args[1]
  1163. _last_exception = None
  1164. return lltype.cast_opaque_ptr(llmemory.GCREF, result)
  1165. else:
  1166. return lltype.nullptr(llmemory.GCREF.TO)
  1167. ##_pseudo_exceptions = {}
  1168. ##def _get_error(Class):
  1169. ## if _llinterp.typer is not None:
  1170. ## llframe = _llinterp.frame_class(None, None, _llinterp)
  1171. ## try:
  1172. ## llframe.make_llexception(Class())
  1173. ## except LLException, e:
  1174. ## return e
  1175. ## else:
  1176. ## assert 0, "should have raised"
  1177. ## else:
  1178. ## # for tests, a random emulated ll_inst will do
  1179. ## if Class not in _pseudo_exceptions:
  1180. ## ll_inst = lltype.malloc(rclass.OBJECT, zero=True)
  1181. ## ll_inst.typeptr = lltype.malloc(rclass.OBJECT_VTABLE,
  1182. ## immortal=True)
  1183. ## _pseudo_exceptions[Class] = LLException(ll_inst.typeptr, ll_inst)
  1184. ## return _pseudo_exceptions[Class]
  1185. ##def get_overflow_error_value():
  1186. ## return lltype.cast_opaque_ptr(llmemory.GCREF,
  1187. ## _get_error(OverflowError).args[1])
  1188. def force(opaque_frame):
  1189. frame = _from_opaque(opaque_frame)
  1190. assert not frame._forced
  1191. frame._forced = True
  1192. assert frame._may_force >= 0
  1193. call_op = frame.loop.operations[frame._may_force]
  1194. guard_op = frame.loop.operations[frame._may_force+1]
  1195. opnum = call_op.opnum
  1196. assert opnum == rop.CALL_MAY_FORCE or opnum == rop.CALL_ASSEMBLER
  1197. frame._populate_fail_args(guard_op, skip=call_op.result)
  1198. return frame.fail_index
  1199. def get_forced_token_frame(force_token):
  1200. opaque_frame = llmemory.cast_adr_to_ptr(force_token,
  1201. lltype.Ptr(_TO_OPAQUE[Frame]))
  1202. return opaque_frame
  1203. def get_frame_forced_token(opaque_frame):
  1204. return llmemory.cast_ptr_to_adr(opaque_frame)
  1205. ##def cast_adr_to_int(memocast, adr):
  1206. ## # xxx slow
  1207. ## assert lltype.typeOf(adr) == llmemory.Address
  1208. ## memocast = _from_opaque(memocast)
  1209. ## addresses = memocast.addresses
  1210. ## for i in xrange(len(addresses)-1, -1, -1):
  1211. ## if addresses[i] == adr:
  1212. ## return i
  1213. ## i = len(addresses)
  1214. ## addresses.append(adr)
  1215. ## return i
  1216. ##def cast_int_to_adr(memocast, int):
  1217. ## memocast = _from_opaque(memocast)
  1218. ## assert 0 <= int < len(memocast.addresses)
  1219. ## return memocast.addresses[int]
  1220. ##def get_class_size(memocast, vtable):
  1221. ## memocast = _from_opaque(memocast)
  1222. ## retur

Large files files are truncated, but you can click here to view the full file