PageRenderTime 75ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/jit/metainterp/pyjitpl.py

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