PageRenderTime 86ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/jit/metainterp/pyjitpl.py

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