PageRenderTime 69ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/jit/metainterp/pyjitpl.py

https://bitbucket.org/evelyn559/pypy
Python | 2675 lines | 2442 code | 96 blank | 137 comment | 86 complexity | e70a31b9203c650ea8451dc7833a149b MD5 | raw file
  1. import py, sys
  2. from pypy.rpython.lltypesystem import lltype, rclass
  3. from pypy.rlib.objectmodel import we_are_translated
  4. from pypy.rlib.unroll import unrolling_iterable
  5. from pypy.rlib.debug import debug_start, debug_stop, debug_print
  6. from pypy.rlib.debug import make_sure_not_resized
  7. from pypy.rlib import nonconst, rstack
  8. from pypy.jit.metainterp import history, compile, resume
  9. from pypy.jit.metainterp.history import Const, ConstInt, ConstPtr, ConstFloat
  10. from pypy.jit.metainterp.history import Box, TargetToken
  11. from pypy.jit.metainterp.resoperation import rop
  12. from pypy.jit.metainterp import executor
  13. from pypy.jit.metainterp.logger import Logger
  14. from pypy.jit.metainterp.jitprof import EmptyProfiler
  15. from pypy.jit.metainterp.jitprof import GUARDS, RECORDED_OPS, ABORT_ESCAPE
  16. from pypy.jit.metainterp.jitprof import ABORT_TOO_LONG, ABORT_BRIDGE, \
  17. ABORT_FORCE_QUASIIMMUT, ABORT_BAD_LOOP
  18. from pypy.jit.metainterp.jitexc import JitException, get_llexception
  19. from pypy.jit.metainterp.heapcache import HeapCache
  20. from pypy.rlib.objectmodel import specialize
  21. from pypy.jit.codewriter.jitcode import JitCode, SwitchDictDescr
  22. from pypy.jit.codewriter import heaptracker
  23. from pypy.jit.metainterp.optimizeopt.util import args_dict_box
  24. # ____________________________________________________________
  25. def arguments(*args):
  26. def decorate(func):
  27. func.argtypes = args
  28. return func
  29. return decorate
  30. # ____________________________________________________________
  31. class MIFrame(object):
  32. debug = False
  33. def __init__(self, metainterp):
  34. self.metainterp = metainterp
  35. self.registers_i = [None] * 256
  36. self.registers_r = [None] * 256
  37. self.registers_f = [None] * 256
  38. def setup(self, jitcode, greenkey=None):
  39. assert isinstance(jitcode, JitCode)
  40. self.jitcode = jitcode
  41. self.bytecode = jitcode.code
  42. # this is not None for frames that are recursive portal calls
  43. self.greenkey = greenkey
  44. # copy the constants in place
  45. self.copy_constants(self.registers_i, jitcode.constants_i, ConstInt)
  46. self.copy_constants(self.registers_r, jitcode.constants_r, ConstPtr)
  47. self.copy_constants(self.registers_f, jitcode.constants_f, ConstFloat)
  48. self._result_argcode = 'v'
  49. # for resume.py operation
  50. self.parent_resumedata_snapshot = None
  51. self.parent_resumedata_frame_info_list = None
  52. # counter for unrolling inlined loops
  53. self.unroll_iterations = 1
  54. @specialize.arg(3)
  55. def copy_constants(self, registers, constants, ConstClass):
  56. """Copy jitcode.constants[0] to registers[255],
  57. jitcode.constants[1] to registers[254],
  58. jitcode.constants[2] to registers[253], etc."""
  59. if nonconst.NonConstant(0): # force the right type
  60. constants[0] = ConstClass.value # (useful for small tests)
  61. i = len(constants) - 1
  62. while i >= 0:
  63. j = 255 - i
  64. assert j >= 0
  65. registers[j] = ConstClass(constants[i])
  66. i -= 1
  67. def cleanup_registers(self):
  68. # To avoid keeping references alive, this cleans up the registers_r.
  69. # It does not clear the references set by copy_constants(), but
  70. # these are all prebuilt constants anyway.
  71. for i in range(self.jitcode.num_regs_r()):
  72. self.registers_r[i] = None
  73. # ------------------------------
  74. # Decoding of the JitCode
  75. @specialize.arg(4)
  76. def prepare_list_of_boxes(self, outvalue, startindex, position, argcode):
  77. assert argcode in 'IRF'
  78. code = self.bytecode
  79. length = ord(code[position])
  80. position += 1
  81. for i in range(length):
  82. index = ord(code[position+i])
  83. if argcode == 'I': reg = self.registers_i[index]
  84. elif argcode == 'R': reg = self.registers_r[index]
  85. elif argcode == 'F': reg = self.registers_f[index]
  86. else: raise AssertionError(argcode)
  87. outvalue[startindex+i] = reg
  88. def _put_back_list_of_boxes(self, outvalue, startindex, position):
  89. code = self.bytecode
  90. length = ord(code[position])
  91. position += 1
  92. for i in range(length):
  93. index = ord(code[position+i])
  94. box = outvalue[startindex+i]
  95. if box.type == history.INT: self.registers_i[index] = box
  96. elif box.type == history.REF: self.registers_r[index] = box
  97. elif box.type == history.FLOAT: self.registers_f[index] = box
  98. else: raise AssertionError(box.type)
  99. def get_current_position_info(self):
  100. return self.jitcode.get_live_vars_info(self.pc)
  101. def get_list_of_active_boxes(self, in_a_call):
  102. if in_a_call:
  103. # If we are not the topmost frame, self._result_argcode contains
  104. # the type of the result of the call instruction in the bytecode.
  105. # We use it to clear the box that will hold the result: this box
  106. # is not defined yet.
  107. argcode = self._result_argcode
  108. index = ord(self.bytecode[self.pc - 1])
  109. if argcode == 'i': self.registers_i[index] = history.CONST_FALSE
  110. elif argcode == 'r': self.registers_r[index] = history.CONST_NULL
  111. elif argcode == 'f': self.registers_f[index] = history.CONST_FZERO
  112. self._result_argcode = '?' # done
  113. #
  114. info = self.get_current_position_info()
  115. start_i = 0
  116. start_r = start_i + info.get_register_count_i()
  117. start_f = start_r + info.get_register_count_r()
  118. total = start_f + info.get_register_count_f()
  119. # allocate a list of the correct size
  120. env = [None] * total
  121. make_sure_not_resized(env)
  122. # fill it now
  123. for i in range(info.get_register_count_i()):
  124. index = info.get_register_index_i(i)
  125. env[start_i + i] = self.registers_i[index]
  126. for i in range(info.get_register_count_r()):
  127. index = info.get_register_index_r(i)
  128. env[start_r + i] = self.registers_r[index]
  129. for i in range(info.get_register_count_f()):
  130. index = info.get_register_index_f(i)
  131. env[start_f + i] = self.registers_f[index]
  132. return env
  133. def replace_active_box_in_frame(self, oldbox, newbox):
  134. if isinstance(oldbox, history.BoxInt):
  135. count = self.jitcode.num_regs_i()
  136. registers = self.registers_i
  137. elif isinstance(oldbox, history.BoxPtr):
  138. count = self.jitcode.num_regs_r()
  139. registers = self.registers_r
  140. elif isinstance(oldbox, history.BoxFloat):
  141. count = self.jitcode.num_regs_f()
  142. registers = self.registers_f
  143. else:
  144. assert 0, oldbox
  145. for i in range(count):
  146. if registers[i] is oldbox:
  147. registers[i] = newbox
  148. if not we_are_translated():
  149. for b in registers[count:]:
  150. assert not oldbox.same_box(b)
  151. def make_result_of_lastop(self, resultbox):
  152. got_type = resultbox.type
  153. # XXX disabled for now, conflicts with str_guard_value
  154. #if not we_are_translated():
  155. # typeof = {'i': history.INT,
  156. # 'r': history.REF,
  157. # 'f': history.FLOAT}
  158. # assert typeof[self.jitcode._resulttypes[self.pc]] == got_type
  159. target_index = ord(self.bytecode[self.pc-1])
  160. if got_type == history.INT:
  161. self.registers_i[target_index] = resultbox
  162. elif got_type == history.REF:
  163. #debug_print(' ->',
  164. # llmemory.cast_ptr_to_adr(resultbox.getref_base()))
  165. self.registers_r[target_index] = resultbox
  166. elif got_type == history.FLOAT:
  167. self.registers_f[target_index] = resultbox
  168. else:
  169. raise AssertionError("bad result box type")
  170. # ------------------------------
  171. for _opimpl in ['int_add', 'int_sub', 'int_mul', 'int_floordiv', 'int_mod',
  172. 'int_lt', 'int_le', 'int_eq',
  173. 'int_ne', 'int_gt', 'int_ge',
  174. 'int_and', 'int_or', 'int_xor',
  175. 'int_rshift', 'int_lshift', 'uint_rshift',
  176. 'uint_lt', 'uint_le', 'uint_gt', 'uint_ge',
  177. 'uint_floordiv',
  178. 'float_add', 'float_sub', 'float_mul', 'float_truediv',
  179. 'float_lt', 'float_le', 'float_eq',
  180. 'float_ne', 'float_gt', 'float_ge',
  181. 'ptr_eq', 'ptr_ne', 'instance_ptr_eq', 'instance_ptr_ne',
  182. ]:
  183. exec py.code.Source('''
  184. @arguments("box", "box")
  185. def opimpl_%s(self, b1, b2):
  186. return self.execute(rop.%s, b1, b2)
  187. ''' % (_opimpl, _opimpl.upper())).compile()
  188. for _opimpl in ['int_add_ovf', 'int_sub_ovf', 'int_mul_ovf']:
  189. exec py.code.Source('''
  190. @arguments("box", "box")
  191. def opimpl_%s(self, b1, b2):
  192. self.metainterp.clear_exception()
  193. resbox = self.execute(rop.%s, b1, b2)
  194. self.make_result_of_lastop(resbox) # same as execute_varargs()
  195. if not isinstance(resbox, Const):
  196. self.metainterp.handle_possible_overflow_error()
  197. return resbox
  198. ''' % (_opimpl, _opimpl.upper())).compile()
  199. for _opimpl in ['int_is_true', 'int_is_zero', 'int_neg', 'int_invert',
  200. 'cast_float_to_int', 'cast_int_to_float',
  201. 'cast_float_to_singlefloat', 'cast_singlefloat_to_float',
  202. 'float_neg', 'float_abs',
  203. 'cast_ptr_to_int', 'cast_int_to_ptr',
  204. 'convert_float_bytes_to_longlong',
  205. ]:
  206. exec py.code.Source('''
  207. @arguments("box")
  208. def opimpl_%s(self, b):
  209. return self.execute(rop.%s, b)
  210. ''' % (_opimpl, _opimpl.upper())).compile()
  211. @arguments("box")
  212. def opimpl_ptr_nonzero(self, box):
  213. return self.execute(rop.PTR_NE, box, history.CONST_NULL)
  214. @arguments("box")
  215. def opimpl_ptr_iszero(self, box):
  216. return self.execute(rop.PTR_EQ, box, history.CONST_NULL)
  217. @arguments("box")
  218. def opimpl_mark_opaque_ptr(self, box):
  219. return self.execute(rop.MARK_OPAQUE_PTR, box)
  220. @arguments("box", "box")
  221. def opimpl_record_known_class(self, box, clsbox):
  222. from pypy.rpython.lltypesystem import llmemory
  223. if self.metainterp.heapcache.is_class_known(box):
  224. return
  225. adr = clsbox.getaddr()
  226. bounding_class = llmemory.cast_adr_to_ptr(adr, rclass.CLASSTYPE)
  227. if bounding_class.subclassrange_max - bounding_class.subclassrange_min == 1:
  228. # precise class knowledge, this can be used
  229. self.execute(rop.RECORD_KNOWN_CLASS, box, clsbox)
  230. self.metainterp.heapcache.class_now_known(box)
  231. @arguments("box")
  232. def _opimpl_any_return(self, box):
  233. self.metainterp.finishframe(box)
  234. opimpl_int_return = _opimpl_any_return
  235. opimpl_ref_return = _opimpl_any_return
  236. opimpl_float_return = _opimpl_any_return
  237. @arguments()
  238. def opimpl_void_return(self):
  239. self.metainterp.finishframe(None)
  240. @arguments("box")
  241. def _opimpl_any_copy(self, box):
  242. return box
  243. opimpl_int_copy = _opimpl_any_copy
  244. opimpl_ref_copy = _opimpl_any_copy
  245. opimpl_float_copy = _opimpl_any_copy
  246. @arguments("box")
  247. def _opimpl_any_push(self, box):
  248. self.pushed_box = box
  249. opimpl_int_push = _opimpl_any_push
  250. opimpl_ref_push = _opimpl_any_push
  251. opimpl_float_push = _opimpl_any_push
  252. @arguments()
  253. def _opimpl_any_pop(self):
  254. box = self.pushed_box
  255. self.pushed_box = None
  256. return box
  257. opimpl_int_pop = _opimpl_any_pop
  258. opimpl_ref_pop = _opimpl_any_pop
  259. opimpl_float_pop = _opimpl_any_pop
  260. @arguments("label")
  261. def opimpl_catch_exception(self, target):
  262. """This is a no-op when run normally. We can check that
  263. last_exc_value_box is None; it should have been set to None
  264. by the previous instruction. If the previous instruction
  265. raised instead, finishframe_exception() should have been
  266. called and we would not be there."""
  267. assert self.metainterp.last_exc_value_box is None
  268. @arguments("label")
  269. def opimpl_goto(self, target):
  270. self.pc = target
  271. @arguments("box", "label")
  272. def opimpl_goto_if_not(self, box, target):
  273. switchcase = box.getint()
  274. if switchcase:
  275. opnum = rop.GUARD_TRUE
  276. else:
  277. opnum = rop.GUARD_FALSE
  278. self.generate_guard(opnum, box)
  279. if not switchcase:
  280. self.pc = target
  281. @arguments("box", "label")
  282. def opimpl_goto_if_not_int_is_true(self, box, target):
  283. condbox = self.execute(rop.INT_IS_TRUE, box)
  284. self.opimpl_goto_if_not(condbox, target)
  285. @arguments("box", "label")
  286. def opimpl_goto_if_not_int_is_zero(self, box, target):
  287. condbox = self.execute(rop.INT_IS_ZERO, box)
  288. self.opimpl_goto_if_not(condbox, target)
  289. for _opimpl in ['int_lt', 'int_le', 'int_eq', 'int_ne', 'int_gt', 'int_ge',
  290. 'ptr_eq', 'ptr_ne']:
  291. exec py.code.Source('''
  292. @arguments("box", "box", "label")
  293. def opimpl_goto_if_not_%s(self, b1, b2, target):
  294. condbox = self.execute(rop.%s, b1, b2)
  295. self.opimpl_goto_if_not(condbox, target)
  296. ''' % (_opimpl, _opimpl.upper())).compile()
  297. def _establish_nullity(self, box, orgpc):
  298. value = box.nonnull()
  299. if value:
  300. if not self.metainterp.heapcache.is_class_known(box):
  301. self.generate_guard(rop.GUARD_NONNULL, box, resumepc=orgpc)
  302. else:
  303. if not isinstance(box, Const):
  304. self.generate_guard(rop.GUARD_ISNULL, box, resumepc=orgpc)
  305. promoted_box = box.constbox()
  306. self.metainterp.replace_box(box, promoted_box)
  307. return value
  308. @arguments("orgpc", "box", "label")
  309. def opimpl_goto_if_not_ptr_nonzero(self, orgpc, box, target):
  310. if not self._establish_nullity(box, orgpc):
  311. self.pc = target
  312. @arguments("orgpc", "box", "label")
  313. def opimpl_goto_if_not_ptr_iszero(self, orgpc, box, target):
  314. if self._establish_nullity(box, orgpc):
  315. self.pc = target
  316. @arguments("box", "box", "box")
  317. def opimpl_int_between(self, b1, b2, b3):
  318. b5 = self.execute(rop.INT_SUB, b3, b1)
  319. if isinstance(b5, ConstInt) and b5.getint() == 1:
  320. # the common case of int_between(a, b, a+1) turns into just INT_EQ
  321. return self.execute(rop.INT_EQ, b2, b1)
  322. else:
  323. b4 = self.execute(rop.INT_SUB, b2, b1)
  324. return self.execute(rop.UINT_LT, b4, b5)
  325. @arguments("box", "descr", "orgpc")
  326. def opimpl_switch(self, valuebox, switchdict, orgpc):
  327. box = self.implement_guard_value(orgpc, valuebox)
  328. search_value = box.getint()
  329. assert isinstance(switchdict, SwitchDictDescr)
  330. try:
  331. self.pc = switchdict.dict[search_value]
  332. except KeyError:
  333. pass
  334. @arguments()
  335. def opimpl_unreachable(self):
  336. raise AssertionError("unreachable")
  337. @arguments("descr")
  338. def opimpl_new(self, sizedescr):
  339. resbox = self.execute_with_descr(rop.NEW, sizedescr)
  340. self.metainterp.heapcache.new(resbox)
  341. return resbox
  342. @arguments("descr")
  343. def opimpl_new_with_vtable(self, sizedescr):
  344. cpu = self.metainterp.cpu
  345. cls = heaptracker.descr2vtable(cpu, sizedescr)
  346. resbox = self.execute(rop.NEW_WITH_VTABLE, ConstInt(cls))
  347. self.metainterp.heapcache.new(resbox)
  348. self.metainterp.heapcache.class_now_known(resbox)
  349. return resbox
  350. ## @FixME #arguments("box")
  351. ## def opimpl_runtimenew(self, classbox):
  352. ## self.execute(rop.RUNTIMENEW, classbox)
  353. ## @FixME #arguments("orgpc", "box", "descr")
  354. ## def opimpl_instanceof(self, pc, objbox, typedescr):
  355. ## clsbox = self.cls_of_box(objbox)
  356. ## if isinstance(objbox, Box):
  357. ## self.generate_guard(pc, rop.GUARD_CLASS, objbox, [clsbox])
  358. ## self.execute_with_descr(rop.INSTANCEOF, typedescr, objbox)
  359. ## @FixME #arguments("box", "box")
  360. ## def opimpl_subclassof(self, box1, box2):
  361. ## self.execute(rop.SUBCLASSOF, box1, box2)
  362. @arguments("descr", "box")
  363. def opimpl_new_array(self, itemsizedescr, lengthbox):
  364. resbox = self.execute_with_descr(rop.NEW_ARRAY, itemsizedescr, lengthbox)
  365. self.metainterp.heapcache.new_array(resbox, lengthbox)
  366. return resbox
  367. @specialize.arg(1)
  368. def _do_getarrayitem_gc_any(self, op, arraybox, arraydescr, indexbox):
  369. tobox = self.metainterp.heapcache.getarrayitem(
  370. arraybox, arraydescr, indexbox)
  371. if tobox:
  372. # sanity check: see whether the current array value
  373. # corresponds to what the cache thinks the value is
  374. resbox = executor.execute(self.metainterp.cpu, self.metainterp, op,
  375. arraydescr, arraybox, indexbox)
  376. assert resbox.constbox().same_constant(tobox.constbox())
  377. return tobox
  378. resbox = self.execute_with_descr(op, arraydescr, arraybox, indexbox)
  379. self.metainterp.heapcache.getarrayitem_now_known(
  380. arraybox, arraydescr, indexbox, resbox)
  381. return resbox
  382. @arguments("box", "descr", "box")
  383. def _opimpl_getarrayitem_gc_any(self, arraybox, arraydescr, indexbox):
  384. return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC, arraybox, arraydescr, indexbox)
  385. opimpl_getarrayitem_gc_i = _opimpl_getarrayitem_gc_any
  386. opimpl_getarrayitem_gc_r = _opimpl_getarrayitem_gc_any
  387. opimpl_getarrayitem_gc_f = _opimpl_getarrayitem_gc_any
  388. @arguments("box", "descr", "box")
  389. def _opimpl_getarrayitem_raw_any(self, arraybox, arraydescr, indexbox):
  390. return self.execute_with_descr(rop.GETARRAYITEM_RAW,
  391. arraydescr, arraybox, indexbox)
  392. opimpl_getarrayitem_raw_i = _opimpl_getarrayitem_raw_any
  393. opimpl_getarrayitem_raw_f = _opimpl_getarrayitem_raw_any
  394. @arguments("box", "descr", "box")
  395. def _opimpl_getarrayitem_gc_pure_any(self, arraybox, arraydescr, indexbox):
  396. return self._do_getarrayitem_gc_any(rop.GETARRAYITEM_GC_PURE, arraybox, arraydescr, indexbox)
  397. opimpl_getarrayitem_gc_pure_i = _opimpl_getarrayitem_gc_pure_any
  398. opimpl_getarrayitem_gc_pure_r = _opimpl_getarrayitem_gc_pure_any
  399. opimpl_getarrayitem_gc_pure_f = _opimpl_getarrayitem_gc_pure_any
  400. @arguments("box", "descr", "box", "box")
  401. def _opimpl_setarrayitem_gc_any(self, arraybox, arraydescr,
  402. indexbox, itembox):
  403. self.execute_with_descr(rop.SETARRAYITEM_GC, arraydescr, arraybox,
  404. indexbox, itembox)
  405. self.metainterp.heapcache.setarrayitem(
  406. arraybox, arraydescr, indexbox, itembox)
  407. opimpl_setarrayitem_gc_i = _opimpl_setarrayitem_gc_any
  408. opimpl_setarrayitem_gc_r = _opimpl_setarrayitem_gc_any
  409. opimpl_setarrayitem_gc_f = _opimpl_setarrayitem_gc_any
  410. @arguments("box", "descr", "box", "box")
  411. def _opimpl_setarrayitem_raw_any(self, arraybox, arraydescr,
  412. indexbox, itembox):
  413. self.execute_with_descr(rop.SETARRAYITEM_RAW, arraydescr, arraybox,
  414. indexbox, itembox)
  415. opimpl_setarrayitem_raw_i = _opimpl_setarrayitem_raw_any
  416. opimpl_setarrayitem_raw_f = _opimpl_setarrayitem_raw_any
  417. @arguments("box", "descr")
  418. def opimpl_arraylen_gc(self, arraybox, arraydescr):
  419. lengthbox = self.metainterp.heapcache.arraylen(arraybox)
  420. if lengthbox is None:
  421. lengthbox = self.execute_with_descr(
  422. rop.ARRAYLEN_GC, arraydescr, arraybox)
  423. self.metainterp.heapcache.arraylen_now_known(arraybox, lengthbox)
  424. return lengthbox
  425. @arguments("orgpc", "box", "descr", "box")
  426. def opimpl_check_neg_index(self, orgpc, arraybox, arraydescr, indexbox):
  427. negbox = self.metainterp.execute_and_record(
  428. rop.INT_LT, None, indexbox, history.CONST_FALSE)
  429. negbox = self.implement_guard_value(orgpc, negbox)
  430. if negbox.getint():
  431. # the index is < 0; add the array length to it
  432. lengthbox = self.opimpl_arraylen_gc(arraybox, arraydescr)
  433. indexbox = self.metainterp.execute_and_record(
  434. rop.INT_ADD, None, indexbox, lengthbox)
  435. return indexbox
  436. @arguments("descr", "descr", "descr", "descr", "box")
  437. def opimpl_newlist(self, structdescr, lengthdescr, itemsdescr, arraydescr,
  438. sizebox):
  439. sbox = self.opimpl_new(structdescr)
  440. self._opimpl_setfield_gc_any(sbox, lengthdescr, sizebox)
  441. abox = self.opimpl_new_array(arraydescr, sizebox)
  442. self._opimpl_setfield_gc_any(sbox, itemsdescr, abox)
  443. return sbox
  444. @arguments("descr", "descr", "descr", "descr", "box")
  445. def opimpl_newlist_hint(self, structdescr, lengthdescr, itemsdescr,
  446. arraydescr, sizehintbox):
  447. sbox = self.opimpl_new(structdescr)
  448. self._opimpl_setfield_gc_any(sbox, lengthdescr, history.CONST_FALSE)
  449. abox = self.opimpl_new_array(arraydescr, sizehintbox)
  450. self._opimpl_setfield_gc_any(sbox, itemsdescr, abox)
  451. return sbox
  452. @arguments("box", "descr", "descr", "box")
  453. def _opimpl_getlistitem_gc_any(self, listbox, itemsdescr, arraydescr,
  454. indexbox):
  455. arraybox = self._opimpl_getfield_gc_any(listbox, itemsdescr)
  456. return self._opimpl_getarrayitem_gc_any(arraybox, arraydescr, indexbox)
  457. opimpl_getlistitem_gc_i = _opimpl_getlistitem_gc_any
  458. opimpl_getlistitem_gc_r = _opimpl_getlistitem_gc_any
  459. opimpl_getlistitem_gc_f = _opimpl_getlistitem_gc_any
  460. @arguments("box", "descr", "descr", "box", "box")
  461. def _opimpl_setlistitem_gc_any(self, listbox, itemsdescr, arraydescr,
  462. indexbox, valuebox):
  463. arraybox = self._opimpl_getfield_gc_any(listbox, itemsdescr)
  464. self._opimpl_setarrayitem_gc_any(arraybox, arraydescr, indexbox,
  465. valuebox)
  466. opimpl_setlistitem_gc_i = _opimpl_setlistitem_gc_any
  467. opimpl_setlistitem_gc_r = _opimpl_setlistitem_gc_any
  468. opimpl_setlistitem_gc_f = _opimpl_setlistitem_gc_any
  469. @arguments("orgpc", "box", "descr", "box")
  470. def opimpl_check_resizable_neg_index(self, orgpc, listbox, lengthdescr,
  471. indexbox):
  472. negbox = self.metainterp.execute_and_record(
  473. rop.INT_LT, None, indexbox, history.CONST_FALSE)
  474. negbox = self.implement_guard_value(orgpc, negbox)
  475. if negbox.getint():
  476. # the index is < 0; add the array length to it
  477. lenbox = self.metainterp.execute_and_record(
  478. rop.GETFIELD_GC, lengthdescr, listbox)
  479. indexbox = self.metainterp.execute_and_record(
  480. rop.INT_ADD, None, indexbox, lenbox)
  481. return indexbox
  482. @arguments("box", "descr")
  483. def _opimpl_getfield_gc_any(self, box, fielddescr):
  484. return self._opimpl_getfield_gc_any_pureornot(
  485. rop.GETFIELD_GC, box, fielddescr)
  486. opimpl_getfield_gc_i = _opimpl_getfield_gc_any
  487. opimpl_getfield_gc_r = _opimpl_getfield_gc_any
  488. opimpl_getfield_gc_f = _opimpl_getfield_gc_any
  489. @arguments("box", "descr")
  490. def _opimpl_getfield_gc_pure_any(self, box, fielddescr):
  491. return self._opimpl_getfield_gc_any_pureornot(
  492. rop.GETFIELD_GC_PURE, box, fielddescr)
  493. opimpl_getfield_gc_i_pure = _opimpl_getfield_gc_pure_any
  494. opimpl_getfield_gc_r_pure = _opimpl_getfield_gc_pure_any
  495. opimpl_getfield_gc_f_pure = _opimpl_getfield_gc_pure_any
  496. @arguments("box", "box", "descr")
  497. def _opimpl_getinteriorfield_gc_any(self, array, index, descr):
  498. return self.execute_with_descr(rop.GETINTERIORFIELD_GC, descr,
  499. array, index)
  500. opimpl_getinteriorfield_gc_i = _opimpl_getinteriorfield_gc_any
  501. opimpl_getinteriorfield_gc_f = _opimpl_getinteriorfield_gc_any
  502. opimpl_getinteriorfield_gc_r = _opimpl_getinteriorfield_gc_any
  503. @specialize.arg(1)
  504. def _opimpl_getfield_gc_any_pureornot(self, opnum, box, fielddescr):
  505. tobox = self.metainterp.heapcache.getfield(box, fielddescr)
  506. if tobox is not None:
  507. # sanity check: see whether the current struct value
  508. # corresponds to what the cache thinks the value is
  509. resbox = executor.execute(self.metainterp.cpu, self.metainterp,
  510. rop.GETFIELD_GC, fielddescr, box)
  511. return tobox
  512. resbox = self.execute_with_descr(opnum, fielddescr, box)
  513. self.metainterp.heapcache.getfield_now_known(box, fielddescr, resbox)
  514. return resbox
  515. @arguments("orgpc", "box", "descr")
  516. def _opimpl_getfield_gc_greenfield_any(self, pc, box, fielddescr):
  517. ginfo = self.metainterp.jitdriver_sd.greenfield_info
  518. if (ginfo is not None and fielddescr in ginfo.green_field_descrs
  519. and not self._nonstandard_virtualizable(pc, box)):
  520. # fetch the result, but consider it as a Const box and don't
  521. # record any operation
  522. resbox = executor.execute(self.metainterp.cpu, self.metainterp,
  523. rop.GETFIELD_GC_PURE, fielddescr, box)
  524. return resbox.constbox()
  525. # fall-back
  526. return self.execute_with_descr(rop.GETFIELD_GC_PURE, fielddescr, box)
  527. opimpl_getfield_gc_i_greenfield = _opimpl_getfield_gc_greenfield_any
  528. opimpl_getfield_gc_r_greenfield = _opimpl_getfield_gc_greenfield_any
  529. opimpl_getfield_gc_f_greenfield = _opimpl_getfield_gc_greenfield_any
  530. @arguments("box", "descr", "box")
  531. def _opimpl_setfield_gc_any(self, box, fielddescr, valuebox):
  532. tobox = self.metainterp.heapcache.getfield(box, fielddescr)
  533. if tobox is valuebox:
  534. return
  535. self.execute_with_descr(rop.SETFIELD_GC, fielddescr, box, valuebox)
  536. self.metainterp.heapcache.setfield(box, fielddescr, valuebox)
  537. opimpl_setfield_gc_i = _opimpl_setfield_gc_any
  538. opimpl_setfield_gc_r = _opimpl_setfield_gc_any
  539. opimpl_setfield_gc_f = _opimpl_setfield_gc_any
  540. @arguments("box", "box", "box", "descr")
  541. def _opimpl_setinteriorfield_gc_any(self, array, index, value, descr):
  542. self.execute_with_descr(rop.SETINTERIORFIELD_GC, descr,
  543. array, index, value)
  544. opimpl_setinteriorfield_gc_i = _opimpl_setinteriorfield_gc_any
  545. opimpl_setinteriorfield_gc_f = _opimpl_setinteriorfield_gc_any
  546. opimpl_setinteriorfield_gc_r = _opimpl_setinteriorfield_gc_any
  547. @arguments("box", "descr")
  548. def _opimpl_getfield_raw_any(self, box, fielddescr):
  549. return self.execute_with_descr(rop.GETFIELD_RAW, fielddescr, box)
  550. opimpl_getfield_raw_i = _opimpl_getfield_raw_any
  551. opimpl_getfield_raw_r = _opimpl_getfield_raw_any
  552. opimpl_getfield_raw_f = _opimpl_getfield_raw_any
  553. @arguments("box", "descr")
  554. def _opimpl_getfield_raw_pure_any(self, box, fielddescr):
  555. return self.execute_with_descr(rop.GETFIELD_RAW_PURE, fielddescr, box)
  556. opimpl_getfield_raw_i_pure = _opimpl_getfield_raw_pure_any
  557. opimpl_getfield_raw_r_pure = _opimpl_getfield_raw_pure_any
  558. opimpl_getfield_raw_f_pure = _opimpl_getfield_raw_pure_any
  559. @arguments("box", "descr", "box")
  560. def _opimpl_setfield_raw_any(self, box, fielddescr, valuebox):
  561. self.execute_with_descr(rop.SETFIELD_RAW, fielddescr, box, valuebox)
  562. opimpl_setfield_raw_i = _opimpl_setfield_raw_any
  563. opimpl_setfield_raw_r = _opimpl_setfield_raw_any
  564. opimpl_setfield_raw_f = _opimpl_setfield_raw_any
  565. @arguments("box", "descr", "descr", "orgpc")
  566. def opimpl_record_quasiimmut_field(self, box, fielddescr,
  567. mutatefielddescr, orgpc):
  568. from pypy.jit.metainterp.quasiimmut import QuasiImmutDescr
  569. cpu = self.metainterp.cpu
  570. descr = QuasiImmutDescr(cpu, box, fielddescr, mutatefielddescr)
  571. self.metainterp.history.record(rop.QUASIIMMUT_FIELD, [box],
  572. None, descr=descr)
  573. self.generate_guard(rop.GUARD_NOT_INVALIDATED, resumepc=orgpc)
  574. @arguments("box", "descr", "orgpc")
  575. def opimpl_jit_force_quasi_immutable(self, box, mutatefielddescr, orgpc):
  576. # During tracing, a 'jit_force_quasi_immutable' usually turns into
  577. # the operations that check that the content of 'mutate_xxx' is null.
  578. # If it is actually not null already now, then we abort tracing.
  579. # The idea is that if we use 'jit_force_quasi_immutable' on a freshly
  580. # allocated object, then the GETFIELD_GC will know that the answer is
  581. # null, and the guard will be removed. So the fact that the field is
  582. # quasi-immutable will have no effect, and instead it will work as a
  583. # regular, probably virtual, structure.
  584. mutatebox = self.execute_with_descr(rop.GETFIELD_GC,
  585. mutatefielddescr, box)
  586. if mutatebox.nonnull():
  587. from pypy.jit.metainterp.quasiimmut import do_force_quasi_immutable
  588. do_force_quasi_immutable(self.metainterp.cpu, box.getref_base(),
  589. mutatefielddescr)
  590. raise SwitchToBlackhole(ABORT_FORCE_QUASIIMMUT)
  591. self.generate_guard(rop.GUARD_ISNULL, mutatebox, resumepc=orgpc)
  592. def _nonstandard_virtualizable(self, pc, box):
  593. # returns True if 'box' is actually not the "standard" virtualizable
  594. # that is stored in metainterp.virtualizable_boxes[-1]
  595. if (self.metainterp.jitdriver_sd.virtualizable_info is None and
  596. self.metainterp.jitdriver_sd.greenfield_info is None):
  597. return True # can occur in case of multiple JITs
  598. standard_box = self.metainterp.virtualizable_boxes[-1]
  599. if standard_box is box:
  600. return False
  601. if self.metainterp.heapcache.is_nonstandard_virtualizable(box):
  602. return True
  603. eqbox = self.metainterp.execute_and_record(rop.PTR_EQ, None,
  604. box, standard_box)
  605. eqbox = self.implement_guard_value(pc, eqbox)
  606. isstandard = eqbox.getint()
  607. if isstandard:
  608. self.metainterp.replace_box(box, standard_box)
  609. else:
  610. self.metainterp.heapcache.nonstandard_virtualizables_now_known(box)
  611. return not isstandard
  612. def _get_virtualizable_field_index(self, fielddescr):
  613. # Get the index of a fielddescr. Must only be called for
  614. # the "standard" virtualizable.
  615. vinfo = self.metainterp.jitdriver_sd.virtualizable_info
  616. return vinfo.static_field_by_descrs[fielddescr]
  617. @arguments("orgpc", "box", "descr")
  618. def _opimpl_getfield_vable(self, pc, box, fielddescr):
  619. if self._nonstandard_virtualizable(pc, box):
  620. return self._opimpl_getfield_gc_any(box, fielddescr)
  621. self.metainterp.check_synchronized_virtualizable()
  622. index = self._get_virtualizable_field_index(fielddescr)
  623. return self.metainterp.virtualizable_boxes[index]
  624. opimpl_getfield_vable_i = _opimpl_getfield_vable
  625. opimpl_getfield_vable_r = _opimpl_getfield_vable
  626. opimpl_getfield_vable_f = _opimpl_getfield_vable
  627. @arguments("orgpc", "box", "descr", "box")
  628. def _opimpl_setfield_vable(self, pc, box, fielddescr, valuebox):
  629. if self._nonstandard_virtualizable(pc, box):
  630. return self._opimpl_setfield_gc_any(box, fielddescr, valuebox)
  631. index = self._get_virtualizable_field_index(fielddescr)
  632. self.metainterp.virtualizable_boxes[index] = valuebox
  633. self.metainterp.synchronize_virtualizable()
  634. # XXX only the index'th field needs to be synchronized, really
  635. opimpl_setfield_vable_i = _opimpl_setfield_vable
  636. opimpl_setfield_vable_r = _opimpl_setfield_vable
  637. opimpl_setfield_vable_f = _opimpl_setfield_vable
  638. def _get_arrayitem_vable_index(self, pc, arrayfielddescr, indexbox):
  639. # Get the index of an array item: the index'th of the array
  640. # described by arrayfielddescr. Must only be called for
  641. # the "standard" virtualizable.
  642. indexbox = self.implement_guard_value(pc, indexbox)
  643. vinfo = self.metainterp.jitdriver_sd.virtualizable_info
  644. virtualizable_box = self.metainterp.virtualizable_boxes[-1]
  645. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  646. arrayindex = vinfo.array_field_by_descrs[arrayfielddescr]
  647. index = indexbox.getint()
  648. # Support for negative index: disabled
  649. # (see codewriter/jtransform.py, _check_no_vable_array).
  650. #if index < 0:
  651. # index += vinfo.get_array_length(virtualizable, arrayindex)
  652. assert 0 <= index < vinfo.get_array_length(virtualizable, arrayindex)
  653. return vinfo.get_index_in_array(virtualizable, arrayindex, index)
  654. @arguments("orgpc", "box", "descr", "descr", "box")
  655. def _opimpl_getarrayitem_vable(self, pc, box, fdescr, adescr, indexbox):
  656. if self._nonstandard_virtualizable(pc, box):
  657. arraybox = self._opimpl_getfield_gc_any(box, fdescr)
  658. return self._opimpl_getarrayitem_gc_any(arraybox, adescr, indexbox)
  659. self.metainterp.check_synchronized_virtualizable()
  660. index = self._get_arrayitem_vable_index(pc, fdescr, indexbox)
  661. return self.metainterp.virtualizable_boxes[index]
  662. opimpl_getarrayitem_vable_i = _opimpl_getarrayitem_vable
  663. opimpl_getarrayitem_vable_r = _opimpl_getarrayitem_vable
  664. opimpl_getarrayitem_vable_f = _opimpl_getarrayitem_vable
  665. @arguments("orgpc", "box", "descr", "descr", "box", "box")
  666. def _opimpl_setarrayitem_vable(self, pc, box, fdescr, adescr, indexbox,
  667. valuebox):
  668. if self._nonstandard_virtualizable(pc, box):
  669. arraybox = self._opimpl_getfield_gc_any(box, fdescr)
  670. self._opimpl_setarrayitem_gc_any(arraybox, adescr,
  671. indexbox, valuebox)
  672. return
  673. index = self._get_arrayitem_vable_index(pc, fdescr, indexbox)
  674. self.metainterp.virtualizable_boxes[index] = valuebox
  675. self.metainterp.synchronize_virtualizable()
  676. # XXX only the index'th field needs to be synchronized, really
  677. opimpl_setarrayitem_vable_i = _opimpl_setarrayitem_vable
  678. opimpl_setarrayitem_vable_r = _opimpl_setarrayitem_vable
  679. opimpl_setarrayitem_vable_f = _opimpl_setarrayitem_vable
  680. @arguments("orgpc", "box", "descr", "descr")
  681. def opimpl_arraylen_vable(self, pc, box, fdescr, adescr):
  682. if self._nonstandard_virtualizable(pc, box):
  683. arraybox = self._opimpl_getfield_gc_any(box, fdescr)
  684. return self.opimpl_arraylen_gc(arraybox, adescr)
  685. vinfo = self.metainterp.jitdriver_sd.virtualizable_info
  686. virtualizable_box = self.metainterp.virtualizable_boxes[-1]
  687. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  688. arrayindex = vinfo.array_field_by_descrs[fdescr]
  689. result = vinfo.get_array_length(virtualizable, arrayindex)
  690. return ConstInt(result)
  691. @arguments("jitcode", "boxes")
  692. def _opimpl_inline_call1(self, jitcode, argboxes):
  693. return self.metainterp.perform_call(jitcode, argboxes)
  694. @arguments("jitcode", "boxes2")
  695. def _opimpl_inline_call2(self, jitcode, argboxes):
  696. return self.metainterp.perform_call(jitcode, argboxes)
  697. @arguments("jitcode", "boxes3")
  698. def _opimpl_inline_call3(self, jitcode, argboxes):
  699. return self.metainterp.perform_call(jitcode, argboxes)
  700. opimpl_inline_call_r_i = _opimpl_inline_call1
  701. opimpl_inline_call_r_r = _opimpl_inline_call1
  702. opimpl_inline_call_r_v = _opimpl_inline_call1
  703. opimpl_inline_call_ir_i = _opimpl_inline_call2
  704. opimpl_inline_call_ir_r = _opimpl_inline_call2
  705. opimpl_inline_call_ir_v = _opimpl_inline_call2
  706. opimpl_inline_call_irf_i = _opimpl_inline_call3
  707. opimpl_inline_call_irf_r = _opimpl_inline_call3
  708. opimpl_inline_call_irf_f = _opimpl_inline_call3
  709. opimpl_inline_call_irf_v = _opimpl_inline_call3
  710. @arguments("box", "descr", "boxes")
  711. def _opimpl_residual_call1(self, funcbox, calldescr, argboxes):
  712. return self.do_residual_or_indirect_call(funcbox, calldescr, argboxes)
  713. @arguments("box", "descr", "boxes2")
  714. def _opimpl_residual_call2(self, funcbox, calldescr, argboxes):
  715. return self.do_residual_or_indirect_call(funcbox, calldescr, argboxes)
  716. @arguments("box", "descr", "boxes3")
  717. def _opimpl_residual_call3(self, funcbox, calldescr, argboxes):
  718. return self.do_residual_or_indirect_call(funcbox, calldescr, argboxes)
  719. opimpl_residual_call_r_i = _opimpl_residual_call1
  720. opimpl_residual_call_r_r = _opimpl_residual_call1
  721. opimpl_residual_call_r_v = _opimpl_residual_call1
  722. opimpl_residual_call_ir_i = _opimpl_residual_call2
  723. opimpl_residual_call_ir_r = _opimpl_residual_call2
  724. opimpl_residual_call_ir_v = _opimpl_residual_call2
  725. opimpl_residual_call_irf_i = _opimpl_residual_call3
  726. opimpl_residual_call_irf_r = _opimpl_residual_call3
  727. opimpl_residual_call_irf_f = _opimpl_residual_call3
  728. opimpl_residual_call_irf_v = _opimpl_residual_call3
  729. @arguments("int", "boxes3", "boxes3")
  730. def _opimpl_recursive_call(self, jdindex, greenboxes, redboxes):
  731. targetjitdriver_sd = self.metainterp.staticdata.jitdrivers_sd[jdindex]
  732. allboxes = greenboxes + redboxes
  733. warmrunnerstate = targetjitdriver_sd.warmstate
  734. assembler_call = False
  735. if warmrunnerstate.inlining:
  736. if warmrunnerstate.can_inline_callable(greenboxes):
  737. portal_code = targetjitdriver_sd.mainjitcode
  738. return self.metainterp.perform_call(portal_code, allboxes,
  739. greenkey=greenboxes)
  740. assembler_call = True
  741. # verify that we have all green args, needed to make sure
  742. # that assembler that we call is still correct
  743. self.verify_green_args(targetjitdriver_sd, greenboxes)
  744. #
  745. return self.do_recursive_call(targetjitdriver_sd, allboxes,
  746. assembler_call)
  747. def do_recursive_call(self, targetjitdriver_sd, allboxes,
  748. assembler_call=False):
  749. portal_code = targetjitdriver_sd.mainjitcode
  750. k = targetjitdriver_sd.portal_runner_adr
  751. funcbox = ConstInt(heaptracker.adr2int(k))
  752. return self.do_residual_call(funcbox, portal_code.calldescr, allboxes,
  753. assembler_call=assembler_call,
  754. assembler_call_jd=targetjitdriver_sd)
  755. opimpl_recursive_call_i = _opimpl_recursive_call
  756. opimpl_recursive_call_r = _opimpl_recursive_call
  757. opimpl_recursive_call_f = _opimpl_recursive_call
  758. opimpl_recursive_call_v = _opimpl_recursive_call
  759. ## @FixME #arguments("orgpc", "methdescr", "varargs")
  760. ## def opimpl_oosend(self, pc, methdescr, varargs):
  761. ## objbox = varargs[0]
  762. ## clsbox = self.cls_of_box(objbox)
  763. ## if isinstance(objbox, Box):
  764. ## self.generate_guard(pc, rop.GUARD_CLASS, objbox, [clsbox])
  765. ## oocls = clsbox.getref(ootype.Class)
  766. ## jitcode = methdescr.get_jitcode_for_class(oocls)
  767. ## if jitcode is not None:
  768. ## # we should follow calls to this graph
  769. ## return self.perform_call(jitcode, varargs)
  770. ## else:
  771. ## # but we should not follow calls to that graph
  772. ## return self.execute_varargs(rop.OOSEND, varargs,
  773. ## descr=methdescr, exc=True)
  774. @arguments("box")
  775. def opimpl_strlen(self, strbox):
  776. return self.execute(rop.STRLEN, strbox)
  777. @arguments("box")
  778. def opimpl_unicodelen(self, unicodebox):
  779. return self.execute(rop.UNICODELEN, unicodebox)
  780. @arguments("box", "box")
  781. def opimpl_strgetitem(self, strbox, indexbox):
  782. return self.execute(rop.STRGETITEM, strbox, indexbox)
  783. @arguments("box", "box")
  784. def opimpl_unicodegetitem(self, unicodebox, indexbox):
  785. return self.execute(rop.UNICODEGETITEM, unicodebox, indexbox)
  786. @arguments("box", "box", "box")
  787. def opimpl_strsetitem(self, strbox, indexbox, newcharbox):
  788. return self.execute(rop.STRSETITEM, strbox, indexbox, newcharbox)
  789. @arguments("box", "box", "box")
  790. def opimpl_unicodesetitem(self, unicodebox, indexbox, newcharbox):
  791. self.execute(rop.UNICODESETITEM, unicodebox, indexbox, newcharbox)
  792. @arguments("box")
  793. def opimpl_newstr(self, lengthbox):
  794. return self.execute(rop.NEWSTR, lengthbox)
  795. @arguments("box")
  796. def opimpl_newunicode(self, lengthbox):
  797. return self.execute(rop.NEWUNICODE, lengthbox)
  798. @arguments("box", "box", "box", "box", "box")
  799. def opimpl_copystrcontent(self, srcbox, dstbox, srcstartbox, dststartbox, lengthbox):
  800. return self.execute(rop.COPYSTRCONTENT, srcbox, dstbox, srcstartbox, dststartbox, lengthbox)
  801. @arguments("box", "box", "box", "box", "box")
  802. def opimpl_copyunicodecontent(self, srcbox, dstbox, srcstartbox, dststartbox, lengthbox):
  803. return self.execute(rop.COPYUNICODECONTENT, srcbox, dstbox, srcstartbox, dststartbox, lengthbox)
  804. ## @FixME #arguments("descr", "varargs")
  805. ## def opimpl_residual_oosend_canraise(self, methdescr, varargs):
  806. ## return self.execute_varargs(rop.OOSEND, varargs, descr=methdescr,
  807. ## exc=True)
  808. ## @FixME #arguments("descr", "varargs")
  809. ## def opimpl_residual_oosend_noraise(self, methdescr, varargs):
  810. ## return self.execute_varargs(rop.OOSEND, varargs, descr=methdescr,
  811. ## exc=False)
  812. ## @FixME #arguments("descr", "varargs")
  813. ## def opimpl_residual_oosend_pure(self, methdescr, boxes):
  814. ## return self.execute_varargs(rop.OOSEND_PURE, boxes, descr=methdescr,
  815. ## exc=False)
  816. @arguments("orgpc", "box",)
  817. def _opimpl_guard_value(self, orgpc, box):
  818. self.implement_guard_value(orgpc, box)
  819. @arguments("orgpc", "box", "box", "descr")
  820. def opimpl_str_guard_value(self, orgpc, box, funcbox, descr):
  821. if isinstance(box, Const):
  822. return box # no promotion needed, already a Const
  823. else:
  824. constbox = box.constbox()
  825. resbox = self.do_residual_call(funcbox, descr, [box, constbox])
  826. promoted_box = resbox.constbox()
  827. # This is GUARD_VALUE because GUARD_TRUE assumes the existance
  828. # of a label when computing resumepc
  829. self.generate_guard(rop.GUARD_VALUE, resbox, [promoted_box],
  830. resumepc=orgpc)
  831. self.metainterp.replace_box(box, constbox)
  832. return constbox
  833. opimpl_int_guard_value = _opimpl_guard_value
  834. opimpl_ref_guard_value = _opimpl_guard_value
  835. opimpl_float_guard_value = _opimpl_guard_value
  836. @arguments("orgpc", "box")
  837. def opimpl_guard_class(self, orgpc, box):
  838. clsbox = self.cls_of_box(box)
  839. if not self.metainterp.heapcache.is_class_known(box):
  840. self.generate_guard(rop.GUARD_CLASS, box, [clsbox], resumepc=orgpc)
  841. self.metainterp.heapcache.class_now_known(box)
  842. return clsbox
  843. @arguments("int", "orgpc")
  844. def opimpl_loop_header(self, jdindex, orgpc):
  845. self.metainterp.seen_loop_header_for_jdindex = jdindex
  846. def verify_green_args(self, jitdriver_sd, varargs):
  847. num_green_args = jitdriver_sd.num_green_args
  848. assert len(varargs) == num_green_args
  849. for i in range(num_green_args):
  850. assert isinstance(varargs[i], Const)
  851. @arguments("orgpc", "int", "boxes3", "jitcode_position", "boxes3")
  852. def opimpl_jit_merge_point(self, orgpc, jdindex, greenboxes,
  853. jcposition, redboxes):
  854. resumedescr = compile.ResumeAtPositionDescr()
  855. self.capture_resumedata(resumedescr, orgpc)
  856. any_operation = len(self.metainterp.history.operations) > 0
  857. jitdriver_sd = self.metainterp.staticdata.jitdrivers_sd[jdindex]
  858. self.verify_green_args(jitdriver_sd, greenboxes)
  859. self.debug_merge_point(jitdriver_sd, jdindex,
  860. self.metainterp.portal_call_depth,
  861. self.metainterp.call_ids[-1],
  862. greenboxes)
  863. if self.metainterp.seen_loop_header_for_jdindex < 0:
  864. if not any_operation:
  865. return
  866. if self.metainterp.portal_call_depth or not self.metainterp.get_procedure_token(greenboxes, True):
  867. if not jitdriver_sd.no_loop_header:
  868. return
  869. # automatically add a loop_header if there is none
  870. self.metainterp.seen_loop_header_for_jdindex = jdindex
  871. #
  872. assert self.metainterp.seen_loop_header_for_jdindex == jdindex, (
  873. "found a loop_header for a JitDriver that does not match "
  874. "the following jit_merge_point's")
  875. self.metainterp.seen_loop_header_for_jdindex = -1
  876. #
  877. if not self.metainterp.portal_call_depth:
  878. assert jitdriver_sd is self.metainterp.jitdriver_sd
  879. # Set self.pc to point to jit_merge_point instead of just after:
  880. # if reached_loop_header() raises SwitchToBlackhole, then the
  881. # pc is still at the jit_merge_point, which is a point that is
  882. # much less expensive to blackhole out of.
  883. saved_pc = self.pc
  884. self.pc = orgpc
  885. self.metainterp.reached_loop_header(greenboxes, redboxes, resumedescr)
  886. self.pc = saved_pc
  887. # no exception, which means that the jit_merge_point did not
  888. # close the loop. We have to put the possibly-modified list
  889. # 'redboxes' back into the registers where it comes from.
  890. put_back_list_of_boxes3(self, jcposition, redboxes)
  891. else:
  892. if jitdriver_sd.warmstate.should_unroll_one_iteration(greenboxes):
  893. if self.unroll_iterations > 0:
  894. self.unroll_iterations -= 1
  895. return
  896. # warning! careful here. We have to return from the current
  897. # frame containing the jit_merge_point, and then use
  898. # do_recursive_call() to follow the recursive call. This is
  899. # needed because do_recursive_call() will write its result
  900. # with make_result_of_lastop(), so the lastop must be right:
  901. # it must be the call to 'self', and not the jit_merge_point
  902. # itself, which has no result at all.
  903. assert len(self.metainterp.framestack) >= 2
  904. try:
  905. self.metainterp.finishframe(None)
  906. except ChangeFrame:
  907. pass
  908. frame = self.metainterp.framestack[-1]
  909. frame.do_recursive_call(jitdriver_sd, greenboxes + redboxes,
  910. assembler_call=True)
  911. raise ChangeFrame
  912. def debug_merge_point(self, jitdriver_sd, jd_index, portal_call_depth, current_call_id, greenkey):
  913. # debugging: produce a DEBUG_MERGE_POINT operation
  914. loc = jitdriver_sd.warmstate.get_location_str(greenkey)
  915. debug_print(loc)
  916. args = [ConstInt(jd_index), ConstInt(portal_call_depth), ConstInt(current_call_id)] + greenkey
  917. self.metainterp.history.record(rop.DEBUG_MERGE_POINT, args, None)
  918. @arguments("box", "label")
  919. def opimpl_goto_if_exception_mismatch(self, vtablebox, next_exc_target):
  920. metainterp = self.metainterp
  921. last_exc_value_box = metainterp.last_exc_value_box
  922. assert last_exc_value_box is not None
  923. assert metainterp.class_of_last_exc_is_const
  924. if not metainterp.cpu.ts.instanceOf(last_exc_value_box, vtablebox):
  925. self.pc = next_exc_target
  926. @arguments("orgpc", "box")
  927. def opimpl_raise(self, orgpc, exc_value_box):
  928. # xxx hack
  929. clsbox = self.cls_of_box(exc_value_box)
  930. self.generate_guard(rop.GUARD_CLASS, exc_value_box, [clsbox],
  931. resumepc=orgpc)
  932. self.metainterp.class_of_last_exc_is_const = True
  933. self.metainterp.last_exc_value_box = exc_value_box
  934. self.metainterp.popframe()
  935. self.metainterp.finishframe_exception()
  936. @arguments()
  937. def opimpl_reraise(self):
  938. assert self.metainterp.last_exc_value_box is not None
  939. self.metainterp.popframe()
  940. self.metainterp.finishframe_exception()
  941. @arguments()
  942. def opimpl_last_exception(self):
  943. # Same comment as in opimpl_goto_if_exception_mismatch().
  944. exc_value_box = self.metainterp.last_exc_value_box
  945. assert exc_value_box is not None
  946. assert self.metainterp.class_of_last_exc_is_const
  947. return self.metainterp.cpu.ts.cls_of_box(exc_value_box)
  948. @arguments()
  949. def opimpl_last_exc_value(self):
  950. exc_value_box = self.metainterp.last_exc_value_box
  951. assert exc_value_box is not None
  952. return exc_value_box
  953. @arguments("box")
  954. def opimpl_debug_fatalerror(self, box):
  955. from pypy.rpython.lltypesystem import rstr, lloperation
  956. msg = box.getref(lltype.Ptr(rstr.STR))
  957. lloperation.llop.debug_fatalerror(msg)
  958. @arguments("box", "box", "box", "box", "box")
  959. def opimpl_jit_debug(self, stringbox, arg1box, arg2box, arg3box, arg4box):
  960. from pypy.rpython.lltypesystem import rstr
  961. from pypy.rpython.annlowlevel import hlstr
  962. msg = stringbox.getref(lltype.Ptr(rstr.STR))
  963. debug_print('jit_debug:', hlstr(msg),
  964. arg1box.getint(), arg2box.getint(),
  965. arg3box.getint(), arg4box.getint())
  966. args = [stringbox, arg1box, arg2box, arg3box, arg4box]
  967. i = 4
  968. while i > 0 and args[i].getint() == -sys.maxint-1:
  969. i -= 1
  970. assert i >= 0
  971. op = self.metainterp.history.record(rop.JIT_DEBUG, args[:i+1], None)
  972. self.metainterp.attach_debug_info(op)
  973. @arguments("box")
  974. def _opimpl_assert_green(self, box):
  975. if not isinstance(box, Const):
  976. msg = "assert_green failed at %s:%d" % (
  977. self.jitcode.name,
  978. self.pc)
  979. if we_are_translated():
  980. from pypy.rpython.annlowlevel import llstr
  981. from pypy.rpython.lltypesystem import lloperation
  982. lloperation.llop.debug_fatalerror(lltype.Void, llstr(msg))
  983. else:
  984. from pypy.rlib.jit import AssertGreenFailed
  985. raise AssertGreenFailed(msg)
  986. opimpl_int_assert_green = _opimpl_assert_green
  987. opimpl_ref_assert_green = _opimpl_assert_green
  988. opimpl_float_assert_green = _opimpl_assert_green
  989. @arguments()
  990. def opimpl_current_trace_length(self):
  991. trace_length = len(self.metainterp.history.operations)
  992. return ConstInt(trace_length)
  993. @arguments("box")
  994. def _opimpl_isconstant(self, box):
  995. return ConstInt(isinstance(box, Const))
  996. opimpl_int_isconstant = opimpl_ref_isconstant = _opimpl_isconstant
  997. @arguments("box")
  998. def _opimpl_isvirtual(self, box):
  999. return ConstInt(self.metainterp.heapcache.is_unescaped(box))
  1000. opimpl_ref_isvirtual = _opimpl_isvirtual
  1001. @arguments("box")
  1002. def opimpl_virtual_ref(self, box):
  1003. # Details on the content of metainterp.virtualref_boxes:
  1004. #
  1005. # * it's a list whose items go two by two, containing first the
  1006. # virtual box (e.g. the PyFrame) and then the vref box (e.g.
  1007. # the 'virtual_ref(frame)').
  1008. #
  1009. # * if we detect that the virtual box escapes during tracing
  1010. # already (by generating a CALL_MAY_FORCE that marks the flags
  1011. # in the vref), then we replace the vref in the list with
  1012. # ConstPtr(NULL).
  1013. #
  1014. metainterp = self.metainterp
  1015. vrefinfo = metainterp.staticdata.virtualref_info
  1016. obj = box.getref_base()
  1017. vref = vrefinfo.virtual_ref_during_tracing(obj)
  1018. resbox = history.BoxPtr(vref)
  1019. cindex = history.ConstInt(len(metainterp.virtualref_boxes) // 2)
  1020. metainterp.history.record(rop.VIRTUAL_REF, [box, cindex], resbox)
  1021. # Note: we allocate a JIT_VIRTUAL_REF here
  1022. # (in virtual_ref_during_tracing()), in order to detect when
  1023. # the virtual escapes during tracing already. We record it as a
  1024. # VIRTUAL_REF operation. Later, optimizeopt.py should either kill
  1025. # that operation or replace it with a NEW_WITH_VTABLE followed by
  1026. # SETFIELD_GCs.
  1027. metainterp.virtualref_boxes.append(box)
  1028. metainterp.virtualref_boxes.append(resbox)
  1029. return resbox
  1030. @arguments("box")
  1031. def opimpl_virtual_ref_finish(self, box):
  1032. # virtual_ref_finish() assumes that we have a stack-like, last-in
  1033. # first-out order.
  1034. metainterp = self.metainterp
  1035. vrefbox = metainterp.virtualref_boxes.pop()
  1036. lastbox = metainterp.virtualref_boxes.pop()
  1037. assert box.getref_base() == lastbox.getref_base()
  1038. vrefinfo = metainterp.staticdata.virtualref_info
  1039. vref = vrefbox.getref_base()
  1040. if vrefinfo.is_virtual_ref(vref):
  1041. # XXX write a comment about nullbox
  1042. nullbox = self.metainterp.cpu.ts.CONST_NULL
  1043. metainterp.history.record(rop.VIRTUAL_REF_FINISH,
  1044. [vrefbox, nullbox], None)
  1045. @arguments()
  1046. def opimpl_ll_read_timestamp(self):
  1047. return self.metainterp.execute_and_record(rop.READ_TIMESTAMP, None)
  1048. # ------------------------------
  1049. def setup_call(self, argboxes):
  1050. self.pc = 0
  1051. count_i = count_r = count_f = 0
  1052. for box in argboxes:
  1053. if box.type == history.INT:
  1054. self.registers_i[count_i] = box
  1055. count_i += 1
  1056. elif box.type == history.REF:
  1057. self.registers_r[count_r] = box
  1058. count_r += 1
  1059. elif box.type == history.FLOAT:
  1060. self.registers_f[count_f] = box
  1061. count_f += 1
  1062. else:
  1063. raise AssertionError(box.type)
  1064. def setup_resume_at_op(self, pc):
  1065. self.pc = pc
  1066. ## values = ' '.join([box.repr_rpython() for box in self.env])
  1067. ## log('setup_resume_at_op %s:%d [%s] %d' % (self.jitcode.name,
  1068. ## self.pc, values,
  1069. ## self.exception_target))
  1070. def run_one_step(self):
  1071. # Execute the frame forward. This method contains a loop that leaves
  1072. # whenever the 'opcode_implementations' (which is one of the 'opimpl_'
  1073. # methods) returns True. This is the case when the current frame
  1074. # changes, due to a call or a return.
  1075. try:
  1076. staticdata = self.metainterp.staticdata
  1077. while True:
  1078. pc = self.pc
  1079. op = ord(self.bytecode[pc])
  1080. #debug_print(self.jitcode.name, pc)
  1081. #print staticdata.opcode_names[op]
  1082. staticdata.opcode_implementations[op](self, pc)
  1083. except ChangeFrame:
  1084. pass
  1085. def generate_guard(self, opnum, box=None, extraargs=[], resumepc=-1):
  1086. if isinstance(box, Const): # no need for a guard
  1087. return
  1088. metainterp = self.metainterp
  1089. if box is not None:
  1090. moreargs = [box] + extraargs
  1091. else:
  1092. moreargs = list(extraargs)
  1093. metainterp_sd = metainterp.staticdata
  1094. if opnum == rop.GUARD_NOT_FORCED:
  1095. resumedescr = compile.ResumeGuardForcedDescr(metainterp_sd,
  1096. metainterp.jitdriver_sd)
  1097. elif opnum == rop.GUARD_NOT_INVALIDATED:
  1098. resumedescr = compile.ResumeGuardNotInvalidated()
  1099. else:
  1100. resumedescr = compile.ResumeGuardDescr()
  1101. guard_op = metainterp.history.record(opnum, moreargs, None,
  1102. descr=resumedescr)
  1103. self.capture_resumedata(resumedescr, resumepc)
  1104. self.metainterp.staticdata.profiler.count_ops(opnum, GUARDS)
  1105. # count
  1106. metainterp.attach_debug_info(guard_op)
  1107. return guard_op
  1108. def capture_resumedata(self, resumedescr, resumepc=-1):
  1109. metainterp = self.metainterp
  1110. virtualizable_boxes = None
  1111. if (metainterp.jitdriver_sd.virtualizable_info is not None or
  1112. metainterp.jitdriver_sd.greenfield_info is not None):
  1113. virtualizable_boxes = metainterp.virtualizable_boxes
  1114. saved_pc = self.pc
  1115. if resumepc >= 0:
  1116. self.pc = resumepc
  1117. resume.capture_resumedata(metainterp.framestack, virtualizable_boxes,
  1118. metainterp.virtualref_boxes, resumedescr)
  1119. self.pc = saved_pc
  1120. def implement_guard_value(self, orgpc, box):
  1121. """Promote the given Box into a Const. Note: be careful, it's a
  1122. bit unclear what occurs if a single opcode needs to generate
  1123. several ones and/or ones not near the beginning."""
  1124. if isinstance(box, Const):
  1125. return box # no promotion needed, already a Const
  1126. else:
  1127. promoted_box = box.constbox()
  1128. self.generate_guard(rop.GUARD_VALUE, box, [promoted_box],
  1129. resumepc=orgpc)
  1130. self.metainterp.replace_box(box, promoted_box)
  1131. return promoted_box
  1132. def cls_of_box(self, box):
  1133. return self.metainterp.cpu.ts.cls_of_box(box)
  1134. @specialize.arg(1)
  1135. def execute(self, opnum, *argboxes):
  1136. return self.metainterp.execute_and_record(opnum, None, *argboxes)
  1137. @specialize.arg(1)
  1138. def execute_with_descr(self, opnum, descr, *argboxes):
  1139. return self.metainterp.execute_and_record(opnum, descr, *argboxes)
  1140. @specialize.arg(1)
  1141. def execute_varargs(self, opnum, argboxes, descr, exc, pure):
  1142. self.metainterp.clear_exception()
  1143. resbox = self.metainterp.execute_and_record_varargs(opnum, argboxes,
  1144. descr=descr)
  1145. if resbox is not None:
  1146. self.make_result_of_lastop(resbox)
  1147. # ^^^ this is done before handle_possible_exception() because we
  1148. # need the box to show up in get_list_of_active_boxes()
  1149. if pure and self.metainterp.last_exc_value_box is None:
  1150. resbox = self.metainterp.record_result_of_call_pure(resbox)
  1151. exc = exc and not isinstance(resbox, Const)
  1152. if exc:
  1153. self.metainterp.handle_possible_exception()
  1154. else:
  1155. self.metainterp.assert_no_exception()
  1156. return resbox
  1157. def do_residual_call(self, funcbox, descr, argboxes,
  1158. assembler_call=False,
  1159. assembler_call_jd=None):
  1160. # First build allboxes: it may need some reordering from the
  1161. # list provided in argboxes, depending on the order in which
  1162. # the arguments are expected by the function
  1163. allboxes = [None] * (len(argboxes)+1)
  1164. allboxes[0] = funcbox
  1165. src_i = src_r = src_f = 0
  1166. i = 1
  1167. for kind in descr.get_arg_types():
  1168. if kind == history.INT or kind == 'S': # single float
  1169. while True:
  1170. box = argboxes[src_i]
  1171. src_i += 1
  1172. if box.type == history.INT:
  1173. break
  1174. elif kind == history.REF:
  1175. while True:
  1176. box = argboxes[src_r]
  1177. src_r += 1
  1178. if box.type == history.REF:
  1179. break
  1180. elif kind == history.FLOAT or kind == 'L': # long long
  1181. while True:
  1182. box = argboxes[src_f]
  1183. src_f += 1
  1184. if box.type == history.FLOAT:
  1185. break
  1186. else:
  1187. raise AssertionError
  1188. allboxes[i] = box
  1189. i += 1
  1190. assert i == len(allboxes)
  1191. #
  1192. effectinfo = descr.get_extra_info()
  1193. if (assembler_call or
  1194. effectinfo.check_forces_virtual_or_virtualizable()):
  1195. # residual calls require attention to keep virtualizables in-sync
  1196. self.metainterp.clear_exception()
  1197. self.metainterp.vable_and_vrefs_before_residual_call()
  1198. resbox = self.metainterp.execute_and_record_varargs(
  1199. rop.CALL_MAY_FORCE, allboxes, descr=descr)
  1200. self.metainterp.vrefs_after_residual_call()
  1201. vablebox = None
  1202. if assembler_call:
  1203. vablebox = self.metainterp.direct_assembler_call(
  1204. assembler_call_jd)
  1205. if resbox is not None:
  1206. self.make_result_of_lastop(resbox)
  1207. self.metainterp.vable_after_residual_call()
  1208. self.generate_guard(rop.GUARD_NOT_FORCED, None)
  1209. if vablebox is not None:
  1210. self.metainterp.history.record(rop.KEEPALIVE, [vablebox], None)
  1211. self.metainterp.handle_possible_exception()
  1212. return resbox
  1213. else:
  1214. effect = effectinfo.extraeffect
  1215. if effect == effectinfo.EF_LOOPINVARIANT:
  1216. return self.execute_varargs(rop.CALL_LOOPINVARIANT, allboxes,
  1217. descr, False, False)
  1218. exc = effectinfo.check_can_raise()
  1219. pure = effectinfo.check_is_elidable()
  1220. return self.execute_varargs(rop.CALL, allboxes, descr, exc, pure)
  1221. def do_residual_or_indirect_call(self, funcbox, calldescr, argboxes):
  1222. """The 'residual_call' operation is emitted in two cases:
  1223. when we have to generate a residual CALL operation, but also
  1224. to handle an indirect_call that may need to be inlined."""
  1225. assert isinstance(funcbox, Const)
  1226. sd = self.metainterp.staticdata
  1227. key = sd.cpu.ts.getaddr_for_box(funcbox)
  1228. jitcode = sd.bytecode_for_address(key)
  1229. if jitcode is not None:
  1230. # we should follow calls to this graph
  1231. return self.metainterp.perform_call(jitcode, argboxes)
  1232. else:
  1233. # but we should not follow calls to that graph
  1234. return self.do_residual_call(funcbox, calldescr, argboxes)
  1235. # ____________________________________________________________
  1236. class MetaInterpStaticData(object):
  1237. logger_noopt = None
  1238. logger_ops = None
  1239. def __init__(self, cpu, options,
  1240. ProfilerClass=EmptyProfiler, warmrunnerdesc=None):
  1241. self.cpu = cpu
  1242. self.stats = self.cpu.stats
  1243. self.options = options
  1244. self.logger_noopt = Logger(self)
  1245. self.logger_ops = Logger(self, guard_number=True)
  1246. self.profiler = ProfilerClass()
  1247. self.profiler.cpu = cpu
  1248. self.warmrunnerdesc = warmrunnerdesc
  1249. if warmrunnerdesc:
  1250. self.config = warmrunnerdesc.translator.config
  1251. else:
  1252. from pypy.config.pypyoption import get_pypy_config
  1253. self.config = get_pypy_config(translating=True)
  1254. backendmodule = self.cpu.__module__
  1255. backendmodule = backendmodule.split('.')[-2]
  1256. self.jit_starting_line = 'JIT starting (%s)' % backendmodule
  1257. self._addr2name_keys = []
  1258. self._addr2name_values = []
  1259. self.__dict__.update(compile.make_done_loop_tokens())
  1260. def _freeze_(self):
  1261. return True
  1262. def setup_insns(self, insns):
  1263. self.opcode_names = ['?'] * len(insns)
  1264. self.opcode_implementations = [None] * len(insns)
  1265. for key, value in insns.items():
  1266. assert self.opcode_implementations[value] is None
  1267. self.opcode_names[value] = key
  1268. name, argcodes = key.split('/')
  1269. opimpl = _get_opimpl_method(name, argcodes)
  1270. self.opcode_implementations[value] = opimpl
  1271. self.op_catch_exception = insns.get('catch_exception/L', -1)
  1272. def setup_descrs(self, descrs):
  1273. self.opcode_descrs = descrs
  1274. def setup_indirectcalltargets(self, indirectcalltargets):
  1275. self.indirectcalltargets = list(indirectcalltargets)
  1276. def setup_list_of_addr2name(self, list_of_addr2name):
  1277. self._addr2name_keys = [key for key, value in list_of_addr2name]
  1278. self._addr2name_values = [value for key, value in list_of_addr2name]
  1279. def finish_setup(self, codewriter, optimizer=None):
  1280. from pypy.jit.metainterp.blackhole import BlackholeInterpBuilder
  1281. self.blackholeinterpbuilder = BlackholeInterpBuilder(codewriter, self)
  1282. #
  1283. asm = codewriter.assembler
  1284. self.setup_insns(asm.insns)
  1285. self.setup_descrs(asm.descrs)
  1286. self.setup_indirectcalltargets(asm.indirectcalltargets)
  1287. self.setup_list_of_addr2name(asm.list_of_addr2name)
  1288. #
  1289. self.jitdrivers_sd = codewriter.callcontrol.jitdrivers_sd
  1290. self.virtualref_info = codewriter.callcontrol.virtualref_info
  1291. self.callinfocollection = codewriter.callcontrol.callinfocollection
  1292. #
  1293. # store this information for fastpath of call_assembler
  1294. # (only the paths that can actually be taken)
  1295. for jd in self.jitdrivers_sd:
  1296. name = {history.INT: 'int',
  1297. history.REF: 'ref',
  1298. history.FLOAT: 'float',
  1299. history.VOID: 'void'}[jd.result_type]
  1300. tokens = getattr(self, 'loop_tokens_done_with_this_frame_%s' % name)
  1301. jd.portal_finishtoken = tokens[0].finishdescr
  1302. num = self.cpu.get_fail_descr_number(tokens[0].finishdescr)
  1303. setattr(self.cpu, 'done_with_this_frame_%s_v' % name, num)
  1304. #
  1305. exc_descr = compile.PropagateExceptionDescr()
  1306. num = self.cpu.get_fail_descr_number(exc_descr)
  1307. self.cpu.propagate_exception_v = num
  1308. #
  1309. self.globaldata = MetaInterpGlobalData(self)
  1310. def _setup_once(self):
  1311. """Runtime setup needed by the various components of the JIT."""
  1312. if not self.globaldata.initialized:
  1313. debug_print(self.jit_starting_line)
  1314. self.cpu.setup_once()
  1315. if not self.profiler.initialized:
  1316. self.profiler.start()
  1317. self.profiler.initialized = True
  1318. self.globaldata.initialized = True
  1319. def get_name_from_address(self, addr):
  1320. # for debugging only
  1321. if we_are_translated():
  1322. d = self.globaldata.addr2name
  1323. if d is None:
  1324. # Build the dictionary at run-time. This is needed
  1325. # because the keys are function/class addresses, so they
  1326. # can change from run to run.
  1327. d = {}
  1328. keys = self._addr2name_keys
  1329. values = self._addr2name_values
  1330. for i in range(len(keys)):
  1331. d[keys[i]] = values[i]
  1332. self.globaldata.addr2name = d
  1333. return d.get(addr, '')
  1334. else:
  1335. for i in range(len(self._addr2name_keys)):
  1336. if addr == self._addr2name_keys[i]:
  1337. return self._addr2name_values[i]
  1338. return ''
  1339. def bytecode_for_address(self, fnaddress):
  1340. if we_are_translated():
  1341. d = self.globaldata.indirectcall_dict
  1342. if d is None:
  1343. # Build the dictionary at run-time. This is needed
  1344. # because the keys are function addresses, so they
  1345. # can change from run to run.
  1346. d = {}
  1347. for jitcode in self.indirectcalltargets:
  1348. assert jitcode.fnaddr not in d
  1349. d[jitcode.fnaddr] = jitcode
  1350. self.globaldata.indirectcall_dict = d
  1351. return d.get(fnaddress, None)
  1352. else:
  1353. for jitcode in self.indirectcalltargets:
  1354. if jitcode.fnaddr == fnaddress:
  1355. return jitcode
  1356. return None
  1357. def try_to_free_some_loops(self):
  1358. # Increase here the generation recorded by the memory manager.
  1359. if self.warmrunnerdesc is not None: # for tests
  1360. self.warmrunnerdesc.memory_manager.next_generation()
  1361. # ---------------- logging ------------------------
  1362. def log(self, msg):
  1363. debug_print(msg)
  1364. # ____________________________________________________________
  1365. class MetaInterpGlobalData(object):
  1366. """This object contains the JIT's global, mutable data.
  1367. Warning: for any data that you put here, think that there might be
  1368. multiple MetaInterps accessing it at the same time. As usual we are
  1369. safe from corruption thanks to the GIL, but keep in mind that any
  1370. MetaInterp might modify any of these fields while another MetaInterp
  1371. is, say, currently in a residual call to a function. Multiple
  1372. MetaInterps occur either with threads or, in single-threaded cases,
  1373. with recursion. This is a case that is not well-tested, so please
  1374. be careful :-( But thankfully this is one of the very few places
  1375. where multiple concurrent MetaInterps may interact with each other.
  1376. """
  1377. def __init__(self, staticdata):
  1378. self.initialized = False
  1379. self.indirectcall_dict = None
  1380. self.addr2name = None
  1381. self.loopnumbering = 0
  1382. self.resume_virtuals = {}
  1383. self.resume_virtuals_not_translated = []
  1384. # ____________________________________________________________
  1385. class MetaInterp(object):
  1386. portal_call_depth = 0
  1387. cancel_count = 0
  1388. def __init__(self, staticdata, jitdriver_sd):
  1389. self.staticdata = staticdata
  1390. self.cpu = staticdata.cpu
  1391. self.jitdriver_sd = jitdriver_sd
  1392. # Note: self.jitdriver_sd is the JitDriverStaticData that corresponds
  1393. # to the current loop -- the outermost one. Be careful, because
  1394. # during recursion we can also see other jitdrivers.
  1395. self.portal_trace_positions = []
  1396. self.free_frames_list = []
  1397. self.last_exc_value_box = None
  1398. self.partial_trace = None
  1399. self.retracing_from = -1
  1400. self.call_pure_results = args_dict_box()
  1401. self.heapcache = HeapCache()
  1402. self.call_ids = []
  1403. self.current_call_id = 0
  1404. def retrace_needed(self, trace):
  1405. self.partial_trace = trace
  1406. self.retracing_from = len(self.history.operations) - 1
  1407. self.heapcache.reset()
  1408. def perform_call(self, jitcode, boxes, greenkey=None):
  1409. # causes the metainterp to enter the given subfunction
  1410. f = self.newframe(jitcode, greenkey)
  1411. f.setup_call(boxes)
  1412. raise ChangeFrame
  1413. def is_main_jitcode(self, jitcode):
  1414. return self.jitdriver_sd is not None and jitcode is self.jitdriver_sd.mainjitcode
  1415. def newframe(self, jitcode, greenkey=None):
  1416. if jitcode.is_portal:
  1417. self.portal_call_depth += 1
  1418. self.call_ids.append(self.current_call_id)
  1419. self.current_call_id += 1
  1420. if greenkey is not None and self.is_main_jitcode(jitcode):
  1421. self.portal_trace_positions.append(
  1422. (greenkey, len(self.history.operations)))
  1423. if len(self.free_frames_list) > 0:
  1424. f = self.free_frames_list.pop()
  1425. else:
  1426. f = MIFrame(self)
  1427. f.setup(jitcode, greenkey)
  1428. self.framestack.append(f)
  1429. return f
  1430. def popframe(self):
  1431. frame = self.framestack.pop()
  1432. jitcode = frame.jitcode
  1433. if jitcode.is_portal:
  1434. self.portal_call_depth -= 1
  1435. self.call_ids.pop()
  1436. if frame.greenkey is not None and self.is_main_jitcode(jitcode):
  1437. self.portal_trace_positions.append(
  1438. (None, len(self.history.operations)))
  1439. # we save the freed MIFrames to avoid needing to re-create new
  1440. # MIFrame objects all the time; they are a bit big, with their
  1441. # 3*256 register entries.
  1442. frame.cleanup_registers()
  1443. self.free_frames_list.append(frame)
  1444. def finishframe(self, resultbox):
  1445. # handle a non-exceptional return from the current frame
  1446. self.last_exc_value_box = None
  1447. self.popframe()
  1448. if self.framestack:
  1449. if resultbox is not None:
  1450. self.framestack[-1].make_result_of_lastop(resultbox)
  1451. raise ChangeFrame
  1452. else:
  1453. try:
  1454. self.compile_done_with_this_frame(resultbox)
  1455. except SwitchToBlackhole, stb:
  1456. self.aborted_tracing(stb.reason)
  1457. sd = self.staticdata
  1458. result_type = self.jitdriver_sd.result_type
  1459. if result_type == history.VOID:
  1460. assert resultbox is None
  1461. raise sd.DoneWithThisFrameVoid()
  1462. elif result_type == history.INT:
  1463. raise sd.DoneWithThisFrameInt(resultbox.getint())
  1464. elif result_type == history.REF:
  1465. raise sd.DoneWithThisFrameRef(self.cpu, resultbox.getref_base())
  1466. elif result_type == history.FLOAT:
  1467. raise sd.DoneWithThisFrameFloat(resultbox.getfloatstorage())
  1468. else:
  1469. assert False
  1470. def finishframe_exception(self):
  1471. excvaluebox = self.last_exc_value_box
  1472. while self.framestack:
  1473. frame = self.framestack[-1]
  1474. code = frame.bytecode
  1475. position = frame.pc # <-- just after the insn that raised
  1476. if position < len(code):
  1477. opcode = ord(code[position])
  1478. if opcode == self.staticdata.op_catch_exception:
  1479. # found a 'catch_exception' instruction;
  1480. # jump to the handler
  1481. target = ord(code[position+1]) | (ord(code[position+2])<<8)
  1482. frame.pc = target
  1483. raise ChangeFrame
  1484. self.popframe()
  1485. try:
  1486. self.compile_exit_frame_with_exception(excvaluebox)
  1487. except SwitchToBlackhole, stb:
  1488. self.aborted_tracing(stb.reason)
  1489. raise self.staticdata.ExitFrameWithExceptionRef(self.cpu, excvaluebox.getref_base())
  1490. def check_recursion_invariant(self):
  1491. portal_call_depth = -1
  1492. for frame in self.framestack:
  1493. jitcode = frame.jitcode
  1494. assert jitcode.is_portal == len([
  1495. jd for jd in self.staticdata.jitdrivers_sd
  1496. if jd.mainjitcode is jitcode])
  1497. if jitcode.is_portal:
  1498. portal_call_depth += 1
  1499. if portal_call_depth != self.portal_call_depth:
  1500. print "portal_call_depth problem!!!"
  1501. print portal_call_depth, self.portal_call_depth
  1502. for frame in self.framestack:
  1503. jitcode = frame.jitcode
  1504. if jitcode.is_portal:
  1505. print "P",
  1506. else:
  1507. print " ",
  1508. print jitcode.name
  1509. raise AssertionError
  1510. def create_empty_history(self):
  1511. self.history = history.History()
  1512. self.staticdata.stats.set_history(self.history)
  1513. def _all_constants(self, *boxes):
  1514. if len(boxes) == 0:
  1515. return True
  1516. return isinstance(boxes[0], Const) and self._all_constants(*boxes[1:])
  1517. def _all_constants_varargs(self, boxes):
  1518. for box in boxes:
  1519. if not isinstance(box, Const):
  1520. return False
  1521. return True
  1522. @specialize.arg(1)
  1523. def execute_and_record(self, opnum, descr, *argboxes):
  1524. history.check_descr(descr)
  1525. assert not (rop._CANRAISE_FIRST <= opnum <= rop._CANRAISE_LAST)
  1526. # execute the operation
  1527. profiler = self.staticdata.profiler
  1528. profiler.count_ops(opnum)
  1529. resbox = executor.execute(self.cpu, self, opnum, descr, *argboxes)
  1530. if rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST:
  1531. return self._record_helper_pure(opnum, resbox, descr, *argboxes)
  1532. else:
  1533. return self._record_helper_nonpure_varargs(opnum, resbox, descr,
  1534. list(argboxes))
  1535. @specialize.arg(1)
  1536. def execute_and_record_varargs(self, opnum, argboxes, descr=None):
  1537. history.check_descr(descr)
  1538. # execute the operation
  1539. profiler = self.staticdata.profiler
  1540. profiler.count_ops(opnum)
  1541. resbox = executor.execute_varargs(self.cpu, self,
  1542. opnum, argboxes, descr)
  1543. # check if the operation can be constant-folded away
  1544. argboxes = list(argboxes)
  1545. if rop._ALWAYS_PURE_FIRST <= opnum <= rop._ALWAYS_PURE_LAST:
  1546. resbox = self._record_helper_pure_varargs(opnum, resbox, descr, argboxes)
  1547. else:
  1548. resbox = self._record_helper_nonpure_varargs(opnum, resbox, descr, argboxes)
  1549. return resbox
  1550. def _record_helper_pure(self, opnum, resbox, descr, *argboxes):
  1551. canfold = self._all_constants(*argboxes)
  1552. if canfold:
  1553. resbox = resbox.constbox() # ensure it is a Const
  1554. return resbox
  1555. else:
  1556. resbox = resbox.nonconstbox() # ensure it is a Box
  1557. return self._record_helper_nonpure_varargs(opnum, resbox, descr, list(argboxes))
  1558. def _record_helper_pure_varargs(self, opnum, resbox, descr, argboxes):
  1559. canfold = self._all_constants_varargs(argboxes)
  1560. if canfold:
  1561. resbox = resbox.constbox() # ensure it is a Const
  1562. return resbox
  1563. else:
  1564. resbox = resbox.nonconstbox() # ensure it is a Box
  1565. return self._record_helper_nonpure_varargs(opnum, resbox, descr, argboxes)
  1566. def _record_helper_nonpure_varargs(self, opnum, resbox, descr, argboxes):
  1567. assert resbox is None or isinstance(resbox, Box)
  1568. if (rop._OVF_FIRST <= opnum <= rop._OVF_LAST and
  1569. self.last_exc_value_box is None and
  1570. self._all_constants_varargs(argboxes)):
  1571. return resbox.constbox()
  1572. # record the operation
  1573. profiler = self.staticdata.profiler
  1574. profiler.count_ops(opnum, RECORDED_OPS)
  1575. self.heapcache.invalidate_caches(opnum, descr, argboxes)
  1576. op = self.history.record(opnum, argboxes, resbox, descr)
  1577. self.attach_debug_info(op)
  1578. return resbox
  1579. def attach_debug_info(self, op):
  1580. if (not we_are_translated() and op is not None
  1581. and getattr(self, 'framestack', None)):
  1582. op.pc = self.framestack[-1].pc
  1583. op.name = self.framestack[-1].jitcode.name
  1584. def execute_raised(self, exception, constant=False):
  1585. if isinstance(exception, JitException):
  1586. raise JitException, exception # go through
  1587. llexception = get_llexception(self.cpu, exception)
  1588. self.execute_ll_raised(llexception, constant)
  1589. def execute_ll_raised(self, llexception, constant=False):
  1590. # Exception handling: when execute.do_call() gets an exception it
  1591. # calls metainterp.execute_raised(), which puts it into
  1592. # 'self.last_exc_value_box'. This is used shortly afterwards
  1593. # to generate either GUARD_EXCEPTION or GUARD_NO_EXCEPTION, and also
  1594. # to handle the following opcodes 'goto_if_exception_mismatch'.
  1595. llexception = self.cpu.ts.cast_to_ref(llexception)
  1596. exc_value_box = self.cpu.ts.get_exc_value_box(llexception)
  1597. if constant:
  1598. exc_value_box = exc_value_box.constbox()
  1599. self.last_exc_value_box = exc_value_box
  1600. self.class_of_last_exc_is_const = constant
  1601. # 'class_of_last_exc_is_const' means that the class of the value
  1602. # stored in the exc_value Box can be assumed to be a Const. This
  1603. # is only True after a GUARD_EXCEPTION or GUARD_CLASS.
  1604. def clear_exception(self):
  1605. self.last_exc_value_box = None
  1606. def aborted_tracing(self, reason):
  1607. self.staticdata.profiler.count(reason)
  1608. debug_print('~~~ ABORTING TRACING')
  1609. jd_sd = self.jitdriver_sd
  1610. if not self.current_merge_points:
  1611. greenkey = None # we're in the bridge
  1612. else:
  1613. greenkey = self.current_merge_points[0][0][:jd_sd.num_green_args]
  1614. self.staticdata.warmrunnerdesc.hooks.on_abort(reason,
  1615. jd_sd.jitdriver,
  1616. greenkey,
  1617. jd_sd.warmstate.get_location_str(greenkey))
  1618. self.staticdata.stats.aborted()
  1619. def blackhole_if_trace_too_long(self):
  1620. warmrunnerstate = self.jitdriver_sd.warmstate
  1621. if len(self.history.operations) > warmrunnerstate.trace_limit:
  1622. greenkey_of_huge_function = self.find_biggest_function()
  1623. self.staticdata.stats.record_aborted(greenkey_of_huge_function)
  1624. self.portal_trace_positions = None
  1625. if greenkey_of_huge_function is not None:
  1626. warmrunnerstate.disable_noninlinable_function(
  1627. greenkey_of_huge_function)
  1628. raise SwitchToBlackhole(ABORT_TOO_LONG)
  1629. def _interpret(self):
  1630. # Execute the frames forward until we raise a DoneWithThisFrame,
  1631. # a ExitFrameWithException, or a ContinueRunningNormally exception.
  1632. self.staticdata.stats.entered()
  1633. while True:
  1634. self.framestack[-1].run_one_step()
  1635. self.blackhole_if_trace_too_long()
  1636. if not we_are_translated():
  1637. self.check_recursion_invariant()
  1638. def interpret(self):
  1639. if we_are_translated():
  1640. self._interpret()
  1641. else:
  1642. try:
  1643. self._interpret()
  1644. except:
  1645. import sys
  1646. if sys.exc_info()[0] is not None:
  1647. self.staticdata.log(sys.exc_info()[0].__name__)
  1648. raise
  1649. @specialize.arg(1)
  1650. def compile_and_run_once(self, jitdriver_sd, *args):
  1651. # NB. we pass explicity 'jitdriver_sd' around here, even though it
  1652. # is also available as 'self.jitdriver_sd', because we need to
  1653. # specialize this function and a few other ones for the '*args'.
  1654. debug_start('jit-tracing')
  1655. self.staticdata._setup_once()
  1656. self.staticdata.profiler.start_tracing()
  1657. assert jitdriver_sd is self.jitdriver_sd
  1658. self.staticdata.try_to_free_some_loops()
  1659. self.create_empty_history()
  1660. try:
  1661. original_boxes = self.initialize_original_boxes(jitdriver_sd, *args)
  1662. return self._compile_and_run_once(original_boxes)
  1663. finally:
  1664. self.staticdata.profiler.end_tracing()
  1665. debug_stop('jit-tracing')
  1666. def _compile_and_run_once(self, original_boxes):
  1667. self.initialize_state_from_start(original_boxes)
  1668. self.current_merge_points = [(original_boxes, 0)]
  1669. num_green_args = self.jitdriver_sd.num_green_args
  1670. original_greenkey = original_boxes[:num_green_args]
  1671. self.resumekey = compile.ResumeFromInterpDescr(original_greenkey)
  1672. self.history.inputargs = original_boxes[num_green_args:]
  1673. self.seen_loop_header_for_jdindex = -1
  1674. try:
  1675. self.interpret()
  1676. except SwitchToBlackhole, stb:
  1677. self.run_blackhole_interp_to_cancel_tracing(stb)
  1678. assert False, "should always raise"
  1679. def handle_guard_failure(self, key):
  1680. debug_start('jit-tracing')
  1681. self.staticdata.profiler.start_tracing()
  1682. assert isinstance(key, compile.ResumeGuardDescr)
  1683. # store the resumekey.wref_original_loop_token() on 'self' to make
  1684. # sure that it stays alive as long as this MetaInterp
  1685. self.resumekey_original_loop_token = key.wref_original_loop_token()
  1686. self.staticdata.try_to_free_some_loops()
  1687. self.initialize_state_from_guard_failure(key)
  1688. try:
  1689. return self._handle_guard_failure(key)
  1690. finally:
  1691. self.resumekey_original_loop_token = None
  1692. self.staticdata.profiler.end_tracing()
  1693. debug_stop('jit-tracing')
  1694. def _handle_guard_failure(self, key):
  1695. self.current_merge_points = []
  1696. self.resumekey = key
  1697. self.seen_loop_header_for_jdindex = -1
  1698. if isinstance(key, compile.ResumeAtPositionDescr):
  1699. self.seen_loop_header_for_jdindex = self.jitdriver_sd.index
  1700. dont_change_position = True
  1701. else:
  1702. dont_change_position = False
  1703. try:
  1704. self.prepare_resume_from_failure(key.guard_opnum, dont_change_position)
  1705. if self.resumekey_original_loop_token is None: # very rare case
  1706. raise SwitchToBlackhole(ABORT_BRIDGE)
  1707. self.interpret()
  1708. except SwitchToBlackhole, stb:
  1709. self.run_blackhole_interp_to_cancel_tracing(stb)
  1710. assert False, "should always raise"
  1711. def run_blackhole_interp_to_cancel_tracing(self, stb):
  1712. # We got a SwitchToBlackhole exception. Convert the framestack into
  1713. # a stack of blackhole interpreters filled with the same values, and
  1714. # run it.
  1715. from pypy.jit.metainterp.blackhole import convert_and_run_from_pyjitpl
  1716. self.aborted_tracing(stb.reason)
  1717. convert_and_run_from_pyjitpl(self, stb.raising_exception)
  1718. assert False # ^^^ must raise
  1719. def remove_consts_and_duplicates(self, boxes, endindex, duplicates):
  1720. for i in range(endindex):
  1721. box = boxes[i]
  1722. if isinstance(box, Const) or box in duplicates:
  1723. oldbox = box
  1724. box = oldbox.clonebox()
  1725. boxes[i] = box
  1726. self.history.record(rop.SAME_AS, [oldbox], box)
  1727. else:
  1728. duplicates[box] = None
  1729. def reached_loop_header(self, greenboxes, redboxes, resumedescr):
  1730. self.heapcache.reset()
  1731. duplicates = {}
  1732. self.remove_consts_and_duplicates(redboxes, len(redboxes),
  1733. duplicates)
  1734. live_arg_boxes = greenboxes + redboxes
  1735. if self.jitdriver_sd.virtualizable_info is not None:
  1736. # we use pop() to remove the last item, which is the virtualizable
  1737. # itself
  1738. self.remove_consts_and_duplicates(self.virtualizable_boxes,
  1739. len(self.virtualizable_boxes)-1,
  1740. duplicates)
  1741. live_arg_boxes += self.virtualizable_boxes
  1742. live_arg_boxes.pop()
  1743. #
  1744. assert len(self.virtualref_boxes) == 0, "missing virtual_ref_finish()?"
  1745. # Called whenever we reach the 'loop_header' hint.
  1746. # First, attempt to make a bridge:
  1747. # - if self.resumekey is a ResumeGuardDescr, it starts from a guard
  1748. # that failed;
  1749. # - if self.resumekey is a ResumeFromInterpDescr, it starts directly
  1750. # from the interpreter.
  1751. if not self.partial_trace:
  1752. # FIXME: Support a retrace to be a bridge as well as a loop
  1753. self.compile_trace(live_arg_boxes, resumedescr)
  1754. # raises in case it works -- which is the common case, hopefully,
  1755. # at least for bridges starting from a guard.
  1756. # Search in current_merge_points for original_boxes with compatible
  1757. # green keys, representing the beginning of the same loop as the one
  1758. # we end now.
  1759. num_green_args = self.jitdriver_sd.num_green_args
  1760. for j in range(len(self.current_merge_points)-1, -1, -1):
  1761. original_boxes, start = self.current_merge_points[j]
  1762. assert len(original_boxes) == len(live_arg_boxes)
  1763. for i in range(num_green_args):
  1764. box1 = original_boxes[i]
  1765. box2 = live_arg_boxes[i]
  1766. assert isinstance(box1, Const)
  1767. if not box1.same_constant(box2):
  1768. break
  1769. else:
  1770. # Found! Compile it as a loop.
  1771. # raises in case it works -- which is the common case
  1772. if self.partial_trace:
  1773. if start != self.retracing_from:
  1774. raise SwitchToBlackhole(ABORT_BAD_LOOP) # For now
  1775. self.compile_loop(original_boxes, live_arg_boxes, start, resumedescr)
  1776. # creation of the loop was cancelled!
  1777. self.cancel_count += 1
  1778. if self.staticdata.warmrunnerdesc:
  1779. memmgr = self.staticdata.warmrunnerdesc.memory_manager
  1780. if memmgr:
  1781. if self.cancel_count > memmgr.max_unroll_loops:
  1782. self.staticdata.log('cancelled too many times!')
  1783. raise SwitchToBlackhole(ABORT_BAD_LOOP)
  1784. self.staticdata.log('cancelled, tracing more...')
  1785. # Otherwise, no loop found so far, so continue tracing.
  1786. start = len(self.history.operations)
  1787. self.current_merge_points.append((live_arg_boxes, start))
  1788. def _unpack_boxes(self, boxes, start, stop):
  1789. ints = []; refs = []; floats = []
  1790. for i in range(start, stop):
  1791. box = boxes[i]
  1792. if box.type == history.INT: ints.append(box.getint())
  1793. elif box.type == history.REF: refs.append(box.getref_base())
  1794. elif box.type == history.FLOAT:floats.append(box.getfloatstorage())
  1795. else: assert 0
  1796. return ints[:], refs[:], floats[:]
  1797. def raise_continue_running_normally(self, live_arg_boxes, loop_token):
  1798. self.history.inputargs = None
  1799. self.history.operations = None
  1800. # For simplicity, we just raise ContinueRunningNormally here and
  1801. # ignore the loop_token passed in. It means that we go back to
  1802. # interpreted mode, but it should come back very quickly to the
  1803. # JIT, find probably the same 'loop_token', and execute it.
  1804. if we_are_translated():
  1805. num_green_args = self.jitdriver_sd.num_green_args
  1806. gi, gr, gf = self._unpack_boxes(live_arg_boxes, 0, num_green_args)
  1807. ri, rr, rf = self._unpack_boxes(live_arg_boxes, num_green_args,
  1808. len(live_arg_boxes))
  1809. CRN = self.staticdata.ContinueRunningNormally
  1810. raise CRN(gi, gr, gf, ri, rr, rf)
  1811. else:
  1812. # However, in order to keep the existing tests working
  1813. # (which are based on the assumption that 'loop_token' is
  1814. # directly used here), a bit of custom non-translatable code...
  1815. self._nontranslated_run_directly(live_arg_boxes, loop_token)
  1816. assert 0, "unreachable"
  1817. def _nontranslated_run_directly(self, live_arg_boxes, loop_token):
  1818. "NOT_RPYTHON"
  1819. args = []
  1820. num_green_args = self.jitdriver_sd.num_green_args
  1821. num_red_args = self.jitdriver_sd.num_red_args
  1822. for box in live_arg_boxes[num_green_args:num_green_args+num_red_args]:
  1823. if box.type == history.INT: args.append(box.getint())
  1824. elif box.type == history.REF: args.append(box.getref_base())
  1825. elif box.type == history.FLOAT: args.append(box.getfloatstorage())
  1826. else: assert 0
  1827. self.jitdriver_sd.warmstate.execute_assembler(loop_token, *args)
  1828. def prepare_resume_from_failure(self, opnum, dont_change_position=False):
  1829. frame = self.framestack[-1]
  1830. if opnum == rop.GUARD_TRUE: # a goto_if_not that jumps only now
  1831. if not dont_change_position:
  1832. frame.pc = frame.jitcode.follow_jump(frame.pc)
  1833. elif opnum == rop.GUARD_FALSE: # a goto_if_not that stops jumping
  1834. pass
  1835. elif opnum == rop.GUARD_VALUE or opnum == rop.GUARD_CLASS:
  1836. pass # the pc is already set to the *start* of the opcode
  1837. elif (opnum == rop.GUARD_NONNULL or
  1838. opnum == rop.GUARD_ISNULL or
  1839. opnum == rop.GUARD_NONNULL_CLASS):
  1840. pass # the pc is already set to the *start* of the opcode
  1841. elif opnum == rop.GUARD_NO_EXCEPTION or opnum == rop.GUARD_EXCEPTION:
  1842. exception = self.cpu.grab_exc_value()
  1843. if exception:
  1844. self.execute_ll_raised(lltype.cast_opaque_ptr(rclass.OBJECTPTR,
  1845. exception))
  1846. else:
  1847. self.clear_exception()
  1848. try:
  1849. self.handle_possible_exception()
  1850. except ChangeFrame:
  1851. pass
  1852. elif opnum == rop.GUARD_NOT_INVALIDATED:
  1853. pass # XXX we want to do something special in resume descr,
  1854. # but not now
  1855. elif opnum == rop.GUARD_NO_OVERFLOW: # an overflow now detected
  1856. if not dont_change_position:
  1857. self.execute_raised(OverflowError(), constant=True)
  1858. try:
  1859. self.finishframe_exception()
  1860. except ChangeFrame:
  1861. pass
  1862. elif opnum == rop.GUARD_OVERFLOW: # no longer overflowing
  1863. self.clear_exception()
  1864. else:
  1865. from pypy.jit.metainterp.resoperation import opname
  1866. raise NotImplementedError(opname[opnum])
  1867. def get_procedure_token(self, greenkey, with_compiled_targets=False):
  1868. cell = self.jitdriver_sd.warmstate.jit_cell_at_key(greenkey)
  1869. token = cell.get_procedure_token()
  1870. if with_compiled_targets:
  1871. if not token:
  1872. return None
  1873. if not token.target_tokens:
  1874. return None
  1875. return token
  1876. def compile_loop(self, original_boxes, live_arg_boxes, start, resume_at_jump_descr):
  1877. num_green_args = self.jitdriver_sd.num_green_args
  1878. greenkey = original_boxes[:num_green_args]
  1879. if not self.partial_trace:
  1880. assert self.get_procedure_token(greenkey) is None or \
  1881. self.get_procedure_token(greenkey).target_tokens is None
  1882. if self.partial_trace:
  1883. target_token = compile.compile_retrace(self, greenkey, start,
  1884. original_boxes[num_green_args:],
  1885. live_arg_boxes[num_green_args:],
  1886. resume_at_jump_descr, self.partial_trace,
  1887. self.resumekey)
  1888. else:
  1889. target_token = compile.compile_loop(self, greenkey, start,
  1890. original_boxes[num_green_args:],
  1891. live_arg_boxes[num_green_args:],
  1892. resume_at_jump_descr)
  1893. if target_token is not None:
  1894. assert isinstance(target_token, TargetToken)
  1895. self.jitdriver_sd.warmstate.attach_procedure_to_interp(greenkey, target_token.targeting_jitcell_token)
  1896. self.staticdata.stats.add_jitcell_token(target_token.targeting_jitcell_token)
  1897. if target_token is not None: # raise if it *worked* correctly
  1898. assert isinstance(target_token, TargetToken)
  1899. jitcell_token = target_token.targeting_jitcell_token
  1900. self.raise_continue_running_normally(live_arg_boxes, jitcell_token)
  1901. def compile_trace(self, live_arg_boxes, resume_at_jump_descr):
  1902. num_green_args = self.jitdriver_sd.num_green_args
  1903. greenkey = live_arg_boxes[:num_green_args]
  1904. target_jitcell_token = self.get_procedure_token(greenkey, True)
  1905. if not target_jitcell_token:
  1906. return
  1907. self.history.record(rop.JUMP, live_arg_boxes[num_green_args:], None,
  1908. descr=target_jitcell_token)
  1909. try:
  1910. target_token = compile.compile_trace(self, self.resumekey, resume_at_jump_descr)
  1911. finally:
  1912. self.history.operations.pop() # remove the JUMP
  1913. if target_token is not None: # raise if it *worked* correctly
  1914. assert isinstance(target_token, TargetToken)
  1915. jitcell_token = target_token.targeting_jitcell_token
  1916. self.raise_continue_running_normally(live_arg_boxes, jitcell_token)
  1917. def compile_done_with_this_frame(self, exitbox):
  1918. self.gen_store_back_in_virtualizable()
  1919. # temporarily put a JUMP to a pseudo-loop
  1920. sd = self.staticdata
  1921. result_type = self.jitdriver_sd.result_type
  1922. if result_type == history.VOID:
  1923. assert exitbox is None
  1924. exits = []
  1925. loop_tokens = sd.loop_tokens_done_with_this_frame_void
  1926. elif result_type == history.INT:
  1927. exits = [exitbox]
  1928. loop_tokens = sd.loop_tokens_done_with_this_frame_int
  1929. elif result_type == history.REF:
  1930. exits = [exitbox]
  1931. loop_tokens = sd.loop_tokens_done_with_this_frame_ref
  1932. elif result_type == history.FLOAT:
  1933. exits = [exitbox]
  1934. loop_tokens = sd.loop_tokens_done_with_this_frame_float
  1935. else:
  1936. assert False
  1937. # FIXME: kill TerminatingLoopToken?
  1938. # FIXME: can we call compile_trace?
  1939. token = loop_tokens[0].finishdescr
  1940. self.history.record(rop.FINISH, exits, None, descr=token)
  1941. target_token = compile.compile_trace(self, self.resumekey)
  1942. if target_token is not token:
  1943. compile.giveup()
  1944. def compile_exit_frame_with_exception(self, valuebox):
  1945. self.gen_store_back_in_virtualizable()
  1946. sd = self.staticdata
  1947. token = sd.loop_tokens_exit_frame_with_exception_ref[0].finishdescr
  1948. self.history.record(rop.FINISH, [valuebox], None, descr=token)
  1949. target_token = compile.compile_trace(self, self.resumekey)
  1950. if target_token is not token:
  1951. compile.giveup()
  1952. @specialize.arg(1)
  1953. def initialize_original_boxes(self, jitdriver_sd, *args):
  1954. original_boxes = []
  1955. self._fill_original_boxes(jitdriver_sd, original_boxes,
  1956. jitdriver_sd.num_green_args, *args)
  1957. return original_boxes
  1958. @specialize.arg(1)
  1959. def _fill_original_boxes(self, jitdriver_sd, original_boxes,
  1960. num_green_args, *args):
  1961. if args:
  1962. from pypy.jit.metainterp.warmstate import wrap
  1963. box = wrap(self.cpu, args[0], num_green_args > 0)
  1964. original_boxes.append(box)
  1965. self._fill_original_boxes(jitdriver_sd, original_boxes,
  1966. num_green_args-1, *args[1:])
  1967. def initialize_state_from_start(self, original_boxes):
  1968. # ----- make a new frame -----
  1969. self.portal_call_depth = -1 # always one portal around
  1970. self.framestack = []
  1971. f = self.newframe(self.jitdriver_sd.mainjitcode)
  1972. f.setup_call(original_boxes)
  1973. assert self.portal_call_depth == 0
  1974. self.virtualref_boxes = []
  1975. self.initialize_withgreenfields(original_boxes)
  1976. self.initialize_virtualizable(original_boxes)
  1977. def initialize_state_from_guard_failure(self, resumedescr):
  1978. # guard failure: rebuild a complete MIFrame stack
  1979. # This is stack-critical code: it must not be interrupted by StackOverflow,
  1980. # otherwise the jit_virtual_refs are left in a dangling state.
  1981. rstack._stack_criticalcode_start()
  1982. try:
  1983. self.portal_call_depth = -1 # always one portal around
  1984. self.history = history.History()
  1985. inputargs_and_holes = self.rebuild_state_after_failure(resumedescr)
  1986. self.history.inputargs = [box for box in inputargs_and_holes if box]
  1987. finally:
  1988. rstack._stack_criticalcode_stop()
  1989. def initialize_virtualizable(self, original_boxes):
  1990. vinfo = self.jitdriver_sd.virtualizable_info
  1991. if vinfo is not None:
  1992. index = (self.jitdriver_sd.num_green_args +
  1993. self.jitdriver_sd.index_of_virtualizable)
  1994. virtualizable_box = original_boxes[index]
  1995. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  1996. # The field 'virtualizable_boxes' is not even present
  1997. # if 'virtualizable_info' is None. Check for that first.
  1998. self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
  1999. virtualizable)
  2000. original_boxes += self.virtualizable_boxes
  2001. self.virtualizable_boxes.append(virtualizable_box)
  2002. self.initialize_virtualizable_enter()
  2003. def initialize_withgreenfields(self, original_boxes):
  2004. ginfo = self.jitdriver_sd.greenfield_info
  2005. if ginfo is not None:
  2006. assert self.jitdriver_sd.virtualizable_info is None
  2007. index = (self.jitdriver_sd.num_green_args +
  2008. ginfo.red_index)
  2009. self.virtualizable_boxes = [original_boxes[index]]
  2010. def initialize_virtualizable_enter(self):
  2011. vinfo = self.jitdriver_sd.virtualizable_info
  2012. virtualizable_box = self.virtualizable_boxes[-1]
  2013. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2014. vinfo.clear_vable_token(virtualizable)
  2015. def vable_and_vrefs_before_residual_call(self):
  2016. vrefinfo = self.staticdata.virtualref_info
  2017. for i in range(1, len(self.virtualref_boxes), 2):
  2018. vrefbox = self.virtualref_boxes[i]
  2019. vref = vrefbox.getref_base()
  2020. vrefinfo.tracing_before_residual_call(vref)
  2021. # the FORCE_TOKEN is already set at runtime in each vref when
  2022. # it is created, by optimizeopt.py.
  2023. #
  2024. vinfo = self.jitdriver_sd.virtualizable_info
  2025. if vinfo is not None:
  2026. virtualizable_box = self.virtualizable_boxes[-1]
  2027. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2028. vinfo.tracing_before_residual_call(virtualizable)
  2029. #
  2030. force_token_box = history.BoxInt()
  2031. self.history.record(rop.FORCE_TOKEN, [], force_token_box)
  2032. self.history.record(rop.SETFIELD_GC, [virtualizable_box,
  2033. force_token_box],
  2034. None, descr=vinfo.vable_token_descr)
  2035. def vrefs_after_residual_call(self):
  2036. vrefinfo = self.staticdata.virtualref_info
  2037. for i in range(0, len(self.virtualref_boxes), 2):
  2038. vrefbox = self.virtualref_boxes[i+1]
  2039. vref = vrefbox.getref_base()
  2040. if vrefinfo.tracing_after_residual_call(vref):
  2041. # this vref was really a virtual_ref, but it escaped
  2042. # during this CALL_MAY_FORCE. Mark this fact by
  2043. # generating a VIRTUAL_REF_FINISH on it and replacing
  2044. # it by ConstPtr(NULL).
  2045. self.stop_tracking_virtualref(i)
  2046. def vable_after_residual_call(self):
  2047. vinfo = self.jitdriver_sd.virtualizable_info
  2048. if vinfo is not None:
  2049. virtualizable_box = self.virtualizable_boxes[-1]
  2050. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2051. if vinfo.tracing_after_residual_call(virtualizable):
  2052. # the virtualizable escaped during CALL_MAY_FORCE.
  2053. self.load_fields_from_virtualizable()
  2054. raise SwitchToBlackhole(ABORT_ESCAPE, raising_exception=True)
  2055. # ^^^ we set 'raising_exception' to True because we must still
  2056. # have the eventual exception raised (this is normally done
  2057. # after the call to vable_after_residual_call()).
  2058. def stop_tracking_virtualref(self, i):
  2059. virtualbox = self.virtualref_boxes[i]
  2060. vrefbox = self.virtualref_boxes[i+1]
  2061. # record VIRTUAL_REF_FINISH just before the current CALL_MAY_FORCE
  2062. call_may_force_op = self.history.operations.pop()
  2063. assert call_may_force_op.getopnum() == rop.CALL_MAY_FORCE
  2064. self.history.record(rop.VIRTUAL_REF_FINISH,
  2065. [vrefbox, virtualbox], None)
  2066. self.history.operations.append(call_may_force_op)
  2067. # mark by replacing it with ConstPtr(NULL)
  2068. self.virtualref_boxes[i+1] = self.cpu.ts.CONST_NULL
  2069. def handle_possible_exception(self):
  2070. frame = self.framestack[-1]
  2071. if self.last_exc_value_box is not None:
  2072. exception_box = self.cpu.ts.cls_of_box(self.last_exc_value_box)
  2073. op = frame.generate_guard(rop.GUARD_EXCEPTION,
  2074. None, [exception_box])
  2075. assert op is not None
  2076. op.result = self.last_exc_value_box
  2077. self.class_of_last_exc_is_const = True
  2078. self.finishframe_exception()
  2079. else:
  2080. frame.generate_guard(rop.GUARD_NO_EXCEPTION, None, [])
  2081. def handle_possible_overflow_error(self):
  2082. frame = self.framestack[-1]
  2083. if self.last_exc_value_box is not None:
  2084. frame.generate_guard(rop.GUARD_OVERFLOW, None)
  2085. assert isinstance(self.last_exc_value_box, Const)
  2086. assert self.class_of_last_exc_is_const
  2087. self.finishframe_exception()
  2088. else:
  2089. frame.generate_guard(rop.GUARD_NO_OVERFLOW, None)
  2090. def assert_no_exception(self):
  2091. assert self.last_exc_value_box is None
  2092. def rebuild_state_after_failure(self, resumedescr):
  2093. vinfo = self.jitdriver_sd.virtualizable_info
  2094. ginfo = self.jitdriver_sd.greenfield_info
  2095. self.framestack = []
  2096. boxlists = resume.rebuild_from_resumedata(self, resumedescr, vinfo,
  2097. ginfo)
  2098. inputargs_and_holes, virtualizable_boxes, virtualref_boxes = boxlists
  2099. #
  2100. # virtual refs: make the vrefs point to the freshly allocated virtuals
  2101. self.virtualref_boxes = virtualref_boxes
  2102. vrefinfo = self.staticdata.virtualref_info
  2103. for i in range(0, len(virtualref_boxes), 2):
  2104. virtualbox = virtualref_boxes[i]
  2105. vrefbox = virtualref_boxes[i+1]
  2106. vrefinfo.continue_tracing(vrefbox.getref_base(),
  2107. virtualbox.getref_base())
  2108. #
  2109. # virtualizable: synchronize the real virtualizable and the local
  2110. # boxes, in whichever direction is appropriate
  2111. if vinfo is not None:
  2112. self.virtualizable_boxes = virtualizable_boxes
  2113. # just jumped away from assembler (case 4 in the comment in
  2114. # virtualizable.py) into tracing (case 2); check that vable_token
  2115. # is and stays 0. Note the call to reset_vable_token() in
  2116. # warmstate.py.
  2117. virtualizable_box = self.virtualizable_boxes[-1]
  2118. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2119. assert not vinfo.is_token_nonnull_gcref(virtualizable)
  2120. # fill the virtualizable with the local boxes
  2121. self.synchronize_virtualizable()
  2122. #
  2123. elif self.jitdriver_sd.greenfield_info:
  2124. self.virtualizable_boxes = virtualizable_boxes
  2125. else:
  2126. assert not virtualizable_boxes
  2127. #
  2128. return inputargs_and_holes
  2129. def check_synchronized_virtualizable(self):
  2130. if not we_are_translated():
  2131. vinfo = self.jitdriver_sd.virtualizable_info
  2132. virtualizable_box = self.virtualizable_boxes[-1]
  2133. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2134. vinfo.check_boxes(virtualizable, self.virtualizable_boxes)
  2135. def synchronize_virtualizable(self):
  2136. vinfo = self.jitdriver_sd.virtualizable_info
  2137. virtualizable_box = self.virtualizable_boxes[-1]
  2138. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2139. vinfo.write_boxes(virtualizable, self.virtualizable_boxes)
  2140. def load_fields_from_virtualizable(self):
  2141. # Force a reload of the virtualizable fields into the local
  2142. # boxes (called only in escaping cases). Only call this function
  2143. # just before SwitchToBlackhole.
  2144. vinfo = self.jitdriver_sd.virtualizable_info
  2145. if vinfo is not None:
  2146. virtualizable_box = self.virtualizable_boxes[-1]
  2147. virtualizable = vinfo.unwrap_virtualizable_box(virtualizable_box)
  2148. self.virtualizable_boxes = vinfo.read_boxes(self.cpu,
  2149. virtualizable)
  2150. self.virtualizable_boxes.append(virtualizable_box)
  2151. def gen_store_back_in_virtualizable(self):
  2152. vinfo = self.jitdriver_sd.virtualizable_info
  2153. if vinfo is not None:
  2154. # xxx only write back the fields really modified
  2155. vbox = self.virtualizable_boxes[-1]
  2156. for i in range(vinfo.num_static_extra_boxes):
  2157. fieldbox = self.virtualizable_boxes[i]
  2158. descr = vinfo.static_field_descrs[i]
  2159. self.execute_and_record(rop.SETFIELD_GC, descr, vbox, fieldbox)
  2160. i = vinfo.num_static_extra_boxes
  2161. virtualizable = vinfo.unwrap_virtualizable_box(vbox)
  2162. for k in range(vinfo.num_arrays):
  2163. descr = vinfo.array_field_descrs[k]
  2164. abox = self.execute_and_record(rop.GETFIELD_GC, descr, vbox)
  2165. descr = vinfo.array_descrs[k]
  2166. for j in range(vinfo.get_array_length(virtualizable, k)):
  2167. itembox = self.virtualizable_boxes[i]
  2168. i += 1
  2169. self.execute_and_record(rop.SETARRAYITEM_GC, descr,
  2170. abox, ConstInt(j), itembox)
  2171. assert i + 1 == len(self.virtualizable_boxes)
  2172. def replace_box(self, oldbox, newbox):
  2173. assert isinstance(oldbox, Box)
  2174. for frame in self.framestack:
  2175. frame.replace_active_box_in_frame(oldbox, newbox)
  2176. boxes = self.virtualref_boxes
  2177. for i in range(len(boxes)):
  2178. if boxes[i] is oldbox:
  2179. boxes[i] = newbox
  2180. if (self.jitdriver_sd.virtualizable_info is not None or
  2181. self.jitdriver_sd.greenfield_info is not None):
  2182. boxes = self.virtualizable_boxes
  2183. for i in range(len(boxes)):
  2184. if boxes[i] is oldbox:
  2185. boxes[i] = newbox
  2186. self.heapcache.replace_box(oldbox, newbox)
  2187. def find_biggest_function(self):
  2188. start_stack = []
  2189. max_size = 0
  2190. max_key = None
  2191. for pair in self.portal_trace_positions:
  2192. key, pos = pair
  2193. if key is not None:
  2194. start_stack.append(pair)
  2195. else:
  2196. greenkey, startpos = start_stack.pop()
  2197. size = pos - startpos
  2198. if size > max_size:
  2199. max_size = size
  2200. max_key = greenkey
  2201. if start_stack:
  2202. key, pos = start_stack[0]
  2203. size = len(self.history.operations) - pos
  2204. if size > max_size:
  2205. max_size = size
  2206. max_key = key
  2207. return max_key
  2208. def record_result_of_call_pure(self, resbox):
  2209. """ Patch a CALL into a CALL_PURE.
  2210. """
  2211. op = self.history.operations[-1]
  2212. assert op.getopnum() == rop.CALL
  2213. resbox_as_const = resbox.constbox()
  2214. for i in range(op.numargs()):
  2215. if not isinstance(op.getarg(i), Const):
  2216. break
  2217. else:
  2218. # all-constants: remove the CALL operation now and propagate a
  2219. # constant result
  2220. self.history.operations.pop()
  2221. return resbox_as_const
  2222. # not all constants (so far): turn CALL into CALL_PURE, which might
  2223. # be either removed later by optimizeopt or turned back into CALL.
  2224. arg_consts = [a.constbox() for a in op.getarglist()]
  2225. self.call_pure_results[arg_consts] = resbox_as_const
  2226. newop = op.copy_and_change(rop.CALL_PURE, args=op.getarglist())
  2227. self.history.operations[-1] = newop
  2228. return resbox
  2229. def direct_assembler_call(self, targetjitdriver_sd):
  2230. """ Generate a direct call to assembler for portal entry point,
  2231. patching the CALL_MAY_FORCE that occurred just now.
  2232. """
  2233. op = self.history.operations.pop()
  2234. assert op.getopnum() == rop.CALL_MAY_FORCE
  2235. num_green_args = targetjitdriver_sd.num_green_args
  2236. arglist = op.getarglist()
  2237. greenargs = arglist[1:num_green_args+1]
  2238. args = arglist[num_green_args+1:]
  2239. assert len(args) == targetjitdriver_sd.num_red_args
  2240. warmrunnerstate = targetjitdriver_sd.warmstate
  2241. token = warmrunnerstate.get_assembler_token(greenargs)
  2242. op = op.copy_and_change(rop.CALL_ASSEMBLER, args=args, descr=token)
  2243. self.history.operations.append(op)
  2244. #
  2245. # To fix an obscure issue, make sure the vable stays alive
  2246. # longer than the CALL_ASSEMBLER operation. We do it by
  2247. # inserting explicitly an extra KEEPALIVE operation.
  2248. jd = token.outermost_jitdriver_sd
  2249. if jd.index_of_virtualizable >= 0:
  2250. return args[jd.index_of_virtualizable]
  2251. else:
  2252. return None
  2253. # ____________________________________________________________
  2254. class ChangeFrame(JitException):
  2255. """Raised after we mutated metainterp.framestack, in order to force
  2256. it to reload the current top-of-stack frame that gets interpreted."""
  2257. class SwitchToBlackhole(JitException):
  2258. def __init__(self, reason, raising_exception=False):
  2259. self.reason = reason
  2260. self.raising_exception = raising_exception
  2261. # ^^^ must be set to True if the SwitchToBlackhole is raised at a
  2262. # point where the exception on metainterp.last_exc_value_box
  2263. # is supposed to be raised. The default False means that it
  2264. # should just be copied into the blackhole interp, but not raised.
  2265. # ____________________________________________________________
  2266. def _get_opimpl_method(name, argcodes):
  2267. from pypy.jit.metainterp.blackhole import signedord
  2268. #
  2269. def handler(self, position):
  2270. assert position >= 0
  2271. args = ()
  2272. next_argcode = 0
  2273. code = self.bytecode
  2274. orgpc = position
  2275. position += 1
  2276. for argtype in argtypes:
  2277. if argtype == "box": # a box, of whatever type
  2278. argcode = argcodes[next_argcode]
  2279. next_argcode = next_argcode + 1
  2280. if argcode == 'i':
  2281. value = self.registers_i[ord(code[position])]
  2282. elif argcode == 'c':
  2283. value = ConstInt(signedord(code[position]))
  2284. elif argcode == 'r':
  2285. value = self.registers_r[ord(code[position])]
  2286. elif argcode == 'f':
  2287. value = self.registers_f[ord(code[position])]
  2288. else:
  2289. raise AssertionError("bad argcode")
  2290. position += 1
  2291. elif argtype == "descr" or argtype == "jitcode":
  2292. assert argcodes[next_argcode] == 'd'
  2293. next_argcode = next_argcode + 1
  2294. index = ord(code[position]) | (ord(code[position+1])<<8)
  2295. value = self.metainterp.staticdata.opcode_descrs[index]
  2296. if argtype == "jitcode":
  2297. assert isinstance(value, JitCode)
  2298. position += 2
  2299. elif argtype == "label":
  2300. assert argcodes[next_argcode] == 'L'
  2301. next_argcode = next_argcode + 1
  2302. value = ord(code[position]) | (ord(code[position+1])<<8)
  2303. position += 2
  2304. elif argtype == "boxes": # a list of boxes of some type
  2305. length = ord(code[position])
  2306. value = [None] * length
  2307. self.prepare_list_of_boxes(value, 0, position,
  2308. argcodes[next_argcode])
  2309. next_argcode = next_argcode + 1
  2310. position += 1 + length
  2311. elif argtype == "boxes2": # two lists of boxes merged into one
  2312. length1 = ord(code[position])
  2313. position2 = position + 1 + length1
  2314. length2 = ord(code[position2])
  2315. value = [None] * (length1 + length2)
  2316. self.prepare_list_of_boxes(value, 0, position,
  2317. argcodes[next_argcode])
  2318. self.prepare_list_of_boxes(value, length1, position2,
  2319. argcodes[next_argcode + 1])
  2320. next_argcode = next_argcode + 2
  2321. position = position2 + 1 + length2
  2322. elif argtype == "boxes3": # three lists of boxes merged into one
  2323. length1 = ord(code[position])
  2324. position2 = position + 1 + length1
  2325. length2 = ord(code[position2])
  2326. position3 = position2 + 1 + length2
  2327. length3 = ord(code[position3])
  2328. value = [None] * (length1 + length2 + length3)
  2329. self.prepare_list_of_boxes(value, 0, position,
  2330. argcodes[next_argcode])
  2331. self.prepare_list_of_boxes(value, length1, position2,
  2332. argcodes[next_argcode + 1])
  2333. self.prepare_list_of_boxes(value, length1 + length2, position3,
  2334. argcodes[next_argcode + 2])
  2335. next_argcode = next_argcode + 3
  2336. position = position3 + 1 + length3
  2337. elif argtype == "orgpc":
  2338. value = orgpc
  2339. elif argtype == "int":
  2340. argcode = argcodes[next_argcode]
  2341. next_argcode = next_argcode + 1
  2342. if argcode == 'i':
  2343. value = self.registers_i[ord(code[position])].getint()
  2344. elif argcode == 'c':
  2345. value = signedord(code[position])
  2346. else:
  2347. raise AssertionError("bad argcode")
  2348. position += 1
  2349. elif argtype == "jitcode_position":
  2350. value = position
  2351. else:
  2352. raise AssertionError("bad argtype: %r" % (argtype,))
  2353. args += (value,)
  2354. #
  2355. num_return_args = len(argcodes) - next_argcode
  2356. assert num_return_args == 0 or num_return_args == 2
  2357. if num_return_args:
  2358. # Save the type of the resulting box. This is needed if there is
  2359. # a get_list_of_active_boxes(). See comments there.
  2360. self._result_argcode = argcodes[next_argcode + 1]
  2361. position += 1
  2362. else:
  2363. self._result_argcode = 'v'
  2364. self.pc = position
  2365. #
  2366. if not we_are_translated():
  2367. if self.debug:
  2368. print '\tpyjitpl: %s(%s)' % (name, ', '.join(map(repr, args))),
  2369. try:
  2370. resultbox = unboundmethod(self, *args)
  2371. except Exception, e:
  2372. if self.debug:
  2373. print '-> %s!' % e.__class__.__name__
  2374. raise
  2375. if num_return_args == 0:
  2376. if self.debug:
  2377. print
  2378. assert resultbox is None
  2379. else:
  2380. if self.debug:
  2381. print '-> %r' % (resultbox,)
  2382. assert argcodes[next_argcode] == '>'
  2383. result_argcode = argcodes[next_argcode + 1]
  2384. assert resultbox.type == {'i': history.INT,
  2385. 'r': history.REF,
  2386. 'f': history.FLOAT}[result_argcode]
  2387. else:
  2388. resultbox = unboundmethod(self, *args)
  2389. #
  2390. if resultbox is not None:
  2391. self.make_result_of_lastop(resultbox)
  2392. elif not we_are_translated():
  2393. assert self._result_argcode in 'v?'
  2394. #
  2395. unboundmethod = getattr(MIFrame, 'opimpl_' + name).im_func
  2396. argtypes = unrolling_iterable(unboundmethod.argtypes)
  2397. handler.func_name = 'handler_' + name
  2398. return handler
  2399. def put_back_list_of_boxes3(frame, position, newvalue):
  2400. code = frame.bytecode
  2401. length1 = ord(code[position])
  2402. position2 = position + 1 + length1
  2403. length2 = ord(code[position2])
  2404. position3 = position2 + 1 + length2
  2405. length3 = ord(code[position3])
  2406. assert len(newvalue) == length1 + length2 + length3
  2407. frame._put_back_list_of_boxes(newvalue, 0, position)
  2408. frame._put_back_list_of_boxes(newvalue, length1, position2)
  2409. frame._put_back_list_of_boxes(newvalue, length1 + length2, position3)