PageRenderTime 64ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/rpython/jit/codewriter/jtransform.py

https://bitbucket.org/pypy/pypy/
Python | 2170 lines | 2044 code | 67 blank | 59 comment | 101 complexity | fd99a2f9e14c94d81b1ce8e9274c221b MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. import py
  2. from rpython.jit.codewriter import support, heaptracker, longlong
  3. from rpython.jit.codewriter.effectinfo import EffectInfo
  4. from rpython.jit.codewriter.flatten import ListOfKind, IndirectCallTargets
  5. from rpython.jit.codewriter.policy import log
  6. from rpython.jit.metainterp import quasiimmut
  7. from rpython.jit.metainterp.history import getkind
  8. from rpython.jit.metainterp.typesystem import deref, arrayItem
  9. from rpython.jit.metainterp.blackhole import BlackholeInterpreter
  10. from rpython.flowspace.model import SpaceOperation, Variable, Constant,\
  11. c_last_exception
  12. from rpython.rlib import objectmodel
  13. from rpython.rlib.jit import _we_are_jitted
  14. from rpython.rlib.rgc import lltype_is_gc
  15. from rpython.rtyper.lltypesystem import lltype, llmemory, rstr, rffi
  16. from rpython.rtyper.lltypesystem import rbytearray
  17. from rpython.rtyper import rclass
  18. from rpython.rtyper.rclass import IR_QUASIIMMUTABLE, IR_QUASIIMMUTABLE_ARRAY
  19. from rpython.translator.unsimplify import varoftype
  20. class UnsupportedMallocFlags(Exception):
  21. pass
  22. def transform_graph(graph, cpu=None, callcontrol=None, portal_jd=None):
  23. """Transform a control flow graph to make it suitable for
  24. being flattened in a JitCode.
  25. """
  26. constant_fold_ll_issubclass(graph, cpu)
  27. t = Transformer(cpu, callcontrol, portal_jd)
  28. t.transform(graph)
  29. def constant_fold_ll_issubclass(graph, cpu):
  30. # ll_issubclass can be inserted by the inliner to check exception types.
  31. # See corner case metainterp.test.test_exception:test_catch_different_class
  32. if cpu is None:
  33. return
  34. excmatch = cpu.rtyper.exceptiondata.fn_exception_match
  35. for block in list(graph.iterblocks()):
  36. for i, op in enumerate(block.operations):
  37. if (op.opname == 'direct_call' and
  38. all(isinstance(a, Constant) for a in op.args) and
  39. op.args[0].value._obj is excmatch._obj):
  40. constant_result = excmatch(*[a.value for a in op.args[1:]])
  41. block.operations[i] = SpaceOperation(
  42. 'same_as',
  43. [Constant(constant_result, lltype.Bool)],
  44. op.result)
  45. if block.exitswitch is op.result:
  46. block.exitswitch = None
  47. block.recloseblock(*[link for link in block.exits
  48. if link.exitcase == constant_result])
  49. def integer_bounds(size, unsigned):
  50. if unsigned:
  51. return 0, 1 << (8 * size)
  52. else:
  53. return -(1 << (8 * size - 1)), 1 << (8 * size - 1)
  54. class Transformer(object):
  55. vable_array_vars = None
  56. def __init__(self, cpu=None, callcontrol=None, portal_jd=None):
  57. self.cpu = cpu
  58. self.callcontrol = callcontrol
  59. self.portal_jd = portal_jd # non-None only for the portal graph(s)
  60. def transform(self, graph):
  61. self.graph = graph
  62. for block in list(graph.iterblocks()):
  63. self.optimize_block(block)
  64. def optimize_block(self, block):
  65. if block.operations == ():
  66. return
  67. self.vable_array_vars = {}
  68. self.vable_flags = {}
  69. renamings = {}
  70. renamings_constants = {} # subset of 'renamings', {Var:Const} only
  71. newoperations = []
  72. #
  73. def do_rename(var, var_or_const):
  74. if var.concretetype is lltype.Void:
  75. renamings[var] = Constant(None, lltype.Void)
  76. return
  77. renamings[var] = var_or_const
  78. if isinstance(var_or_const, Constant):
  79. value = var_or_const.value
  80. value = lltype._cast_whatever(var.concretetype, value)
  81. renamings_constants[var] = Constant(value, var.concretetype)
  82. #
  83. for op in block.operations:
  84. if renamings_constants:
  85. op = self._do_renaming(renamings_constants, op)
  86. oplist = self.rewrite_operation(op)
  87. #
  88. count_before_last_operation = len(newoperations)
  89. if not isinstance(oplist, list):
  90. oplist = [oplist]
  91. for op1 in oplist:
  92. if isinstance(op1, SpaceOperation):
  93. newoperations.append(self._do_renaming(renamings, op1))
  94. elif op1 is None:
  95. # rewrite_operation() returns None to mean "has no real
  96. # effect, the result should just be renamed to args[0]"
  97. if op.result is not None:
  98. do_rename(op.result, renamings.get(op.args[0],
  99. op.args[0]))
  100. elif isinstance(op1, Constant):
  101. do_rename(op.result, op1)
  102. else:
  103. raise TypeError(repr(op1))
  104. #
  105. if block.canraise:
  106. if len(newoperations) == count_before_last_operation:
  107. self._killed_exception_raising_operation(block)
  108. block.operations = newoperations
  109. block.exitswitch = renamings.get(block.exitswitch, block.exitswitch)
  110. self.follow_constant_exit(block)
  111. self.optimize_goto_if_not(block)
  112. if isinstance(block.exitswitch, tuple):
  113. self._check_no_vable_array(block.exitswitch)
  114. for link in block.exits:
  115. self._check_no_vable_array(link.args)
  116. self._do_renaming_on_link(renamings, link)
  117. def _do_renaming(self, rename, op):
  118. op = SpaceOperation(op.opname, op.args[:], op.result)
  119. for i, v in enumerate(op.args):
  120. if isinstance(v, Variable):
  121. if v in rename:
  122. op.args[i] = rename[v]
  123. elif isinstance(v, ListOfKind):
  124. newlst = []
  125. for x in v:
  126. if x in rename:
  127. x = rename[x]
  128. newlst.append(x)
  129. op.args[i] = ListOfKind(v.kind, newlst)
  130. return op
  131. def _check_no_vable_array(self, list):
  132. if not self.vable_array_vars:
  133. return
  134. for v in list:
  135. if v in self.vable_array_vars:
  136. vars = self.vable_array_vars[v]
  137. (v_base, arrayfielddescr, arraydescr) = vars
  138. raise AssertionError(
  139. "A virtualizable array is passed around; it should\n"
  140. "only be used immediately after being read. Note\n"
  141. "that a possible cause is indexing with an index not\n"
  142. "known non-negative, or catching IndexError, or\n"
  143. "not inlining at all (for tests: use listops=True).\n"
  144. "This is about: %r\n"
  145. "Occurred in: %r" % (arrayfielddescr, self.graph))
  146. # extra explanation: with the way things are organized in
  147. # rpython/rlist.py, the ll_getitem becomes a function call
  148. # that is typically meant to be inlined by the JIT, but
  149. # this does not work with vable arrays because
  150. # jtransform.py expects the getfield and the getarrayitem
  151. # to be in the same basic block. It works a bit as a hack
  152. # for simple cases where we performed the backendopt
  153. # inlining before (even with a very low threshold, because
  154. # there is _always_inline_ on the relevant functions).
  155. def _do_renaming_on_link(self, rename, link):
  156. for i, v in enumerate(link.args):
  157. if isinstance(v, Variable):
  158. if v in rename:
  159. link.args[i] = rename[v]
  160. def _killed_exception_raising_operation(self, block):
  161. assert block.exits[0].exitcase is None
  162. block.exits = block.exits[:1]
  163. block.exitswitch = None
  164. # ----------
  165. def follow_constant_exit(self, block):
  166. v = block.exitswitch
  167. if isinstance(v, Constant) and not block.canraise:
  168. llvalue = v.value
  169. for link in block.exits:
  170. if link.llexitcase == llvalue:
  171. break
  172. else:
  173. assert link.exitcase == 'default'
  174. block.exitswitch = None
  175. link.exitcase = link.llexitcase = None
  176. block.recloseblock(link)
  177. def optimize_goto_if_not(self, block):
  178. """Replace code like 'v = int_gt(x,y); exitswitch = v'
  179. with just 'exitswitch = ('int_gt',x,y)'."""
  180. if len(block.exits) != 2:
  181. return False
  182. v = block.exitswitch
  183. if (block.canraise or isinstance(v, tuple)
  184. or v.concretetype != lltype.Bool):
  185. return False
  186. for op in block.operations[::-1]:
  187. if v in op.args:
  188. return False # variable is also used in cur block
  189. if v is op.result:
  190. if op.opname not in ('int_lt', 'int_le', 'int_eq', 'int_ne',
  191. 'int_gt', 'int_ge',
  192. 'float_lt', 'float_le', 'float_eq',
  193. 'float_ne', 'float_gt', 'float_ge',
  194. 'int_is_zero', 'int_is_true',
  195. 'ptr_eq', 'ptr_ne',
  196. 'ptr_iszero', 'ptr_nonzero'):
  197. return False # not a supported operation
  198. # ok! optimize this case
  199. block.operations.remove(op)
  200. block.exitswitch = (op.opname,) + tuple(op.args)
  201. #if op.opname in ('ptr_iszero', 'ptr_nonzero'):
  202. block.exitswitch += ('-live-before',)
  203. # if the variable escape to the next block along a link,
  204. # replace it with a constant, because we know its value
  205. for link in block.exits:
  206. while v in link.args:
  207. index = link.args.index(v)
  208. link.args[index] = Constant(link.llexitcase,
  209. lltype.Bool)
  210. return True
  211. return False
  212. # ----------
  213. def rewrite_operation(self, op):
  214. try:
  215. rewrite = _rewrite_ops[op.opname]
  216. except KeyError:
  217. raise Exception("the JIT doesn't support the operation %r"
  218. " in %r" % (op, getattr(self, 'graph', '?')))
  219. return rewrite(self, op)
  220. def rewrite_op_same_as(self, op):
  221. if op.args[0] in self.vable_array_vars:
  222. self.vable_array_vars[op.result]= self.vable_array_vars[op.args[0]]
  223. def rewrite_op_cast_ptr_to_adr(self, op):
  224. if lltype_is_gc(op.args[0].concretetype):
  225. raise Exception("cast_ptr_to_adr for GC types unsupported")
  226. def rewrite_op_cast_pointer(self, op):
  227. newop = self.rewrite_op_same_as(op)
  228. assert newop is None
  229. return
  230. # disabled for now
  231. if (self._is_rclass_instance(op.args[0]) and
  232. self._is_rclass_instance(op.result)):
  233. FROM = op.args[0].concretetype.TO
  234. TO = op.result.concretetype.TO
  235. if lltype._castdepth(TO, FROM) > 0:
  236. vtable = heaptracker.get_vtable_for_gcstruct(self.cpu, TO)
  237. if vtable.subclassrange_max - vtable.subclassrange_min == 1:
  238. # it's a precise class check
  239. const_vtable = Constant(vtable, lltype.typeOf(vtable))
  240. return [None, # hack, do the right renaming from op.args[0] to op.result
  241. SpaceOperation("record_exact_class", [op.args[0], const_vtable], None)]
  242. def rewrite_op_likely(self, op):
  243. return None # "no real effect"
  244. def rewrite_op_unlikely(self, op):
  245. return None # "no real effect"
  246. def rewrite_op_raw_malloc_usage(self, op):
  247. if self.cpu.translate_support_code or isinstance(op.args[0], Variable):
  248. return # the operation disappears
  249. else:
  250. # only for untranslated tests: get a real integer estimate
  251. arg = op.args[0].value
  252. arg = llmemory.raw_malloc_usage(arg)
  253. return [Constant(arg, lltype.Signed)]
  254. def rewrite_op_jit_record_exact_class(self, op):
  255. return SpaceOperation("record_exact_class", [op.args[0], op.args[1]], None)
  256. def rewrite_op_cast_bool_to_int(self, op): pass
  257. def rewrite_op_cast_bool_to_uint(self, op): pass
  258. def rewrite_op_cast_char_to_int(self, op): pass
  259. def rewrite_op_cast_unichar_to_int(self, op): pass
  260. def rewrite_op_cast_int_to_char(self, op): pass
  261. def rewrite_op_cast_int_to_unichar(self, op): pass
  262. def rewrite_op_cast_int_to_uint(self, op): pass
  263. def rewrite_op_cast_uint_to_int(self, op): pass
  264. def _rewrite_symmetric(self, op):
  265. """Rewrite 'c1+v2' into 'v2+c1' in an attempt to avoid generating
  266. too many variants of the bytecode."""
  267. if (isinstance(op.args[0], Constant) and
  268. isinstance(op.args[1], Variable)):
  269. reversename = {'int_lt': 'int_gt',
  270. 'int_le': 'int_ge',
  271. 'int_gt': 'int_lt',
  272. 'int_ge': 'int_le',
  273. 'uint_lt': 'uint_gt',
  274. 'uint_le': 'uint_ge',
  275. 'uint_gt': 'uint_lt',
  276. 'uint_ge': 'uint_le',
  277. 'float_lt': 'float_gt',
  278. 'float_le': 'float_ge',
  279. 'float_gt': 'float_lt',
  280. 'float_ge': 'float_le',
  281. }.get(op.opname, op.opname)
  282. return SpaceOperation(reversename,
  283. [op.args[1], op.args[0]] + op.args[2:],
  284. op.result)
  285. else:
  286. return op
  287. rewrite_op_int_add = _rewrite_symmetric
  288. rewrite_op_int_mul = _rewrite_symmetric
  289. rewrite_op_int_and = _rewrite_symmetric
  290. rewrite_op_int_or = _rewrite_symmetric
  291. rewrite_op_int_xor = _rewrite_symmetric
  292. rewrite_op_int_lt = _rewrite_symmetric
  293. rewrite_op_int_le = _rewrite_symmetric
  294. rewrite_op_int_gt = _rewrite_symmetric
  295. rewrite_op_int_ge = _rewrite_symmetric
  296. rewrite_op_uint_lt = _rewrite_symmetric
  297. rewrite_op_uint_le = _rewrite_symmetric
  298. rewrite_op_uint_gt = _rewrite_symmetric
  299. rewrite_op_uint_ge = _rewrite_symmetric
  300. rewrite_op_float_add = _rewrite_symmetric
  301. rewrite_op_float_mul = _rewrite_symmetric
  302. rewrite_op_float_lt = _rewrite_symmetric
  303. rewrite_op_float_le = _rewrite_symmetric
  304. rewrite_op_float_gt = _rewrite_symmetric
  305. rewrite_op_float_ge = _rewrite_symmetric
  306. def rewrite_op_int_add_ovf(self, op):
  307. op0 = self._rewrite_symmetric(op)
  308. op1 = SpaceOperation('-live-', [], None)
  309. return [op1, op0]
  310. rewrite_op_int_mul_ovf = rewrite_op_int_add_ovf
  311. def rewrite_op_int_sub_ovf(self, op):
  312. op1 = SpaceOperation('-live-', [], None)
  313. return [op1, op]
  314. def _noop_rewrite(self, op):
  315. return op
  316. rewrite_op_convert_float_bytes_to_longlong = _noop_rewrite
  317. rewrite_op_convert_longlong_bytes_to_float = _noop_rewrite
  318. cast_ptr_to_weakrefptr = _noop_rewrite
  319. cast_weakrefptr_to_ptr = _noop_rewrite
  320. # ----------
  321. # Various kinds of calls
  322. def rewrite_op_direct_call(self, op):
  323. kind = self.callcontrol.guess_call_kind(op)
  324. return getattr(self, 'handle_%s_call' % kind)(op)
  325. def rewrite_op_indirect_call(self, op):
  326. kind = self.callcontrol.guess_call_kind(op)
  327. return getattr(self, 'handle_%s_indirect_call' % kind)(op)
  328. def rewrite_call(self, op, namebase, initialargs, args=None,
  329. calldescr=None):
  330. """Turn 'i0 = direct_call(fn, i1, i2, ref1, ref2)'
  331. into 'i0 = xxx_call_ir_i(fn, descr, [i1,i2], [ref1,ref2])'.
  332. The name is one of '{residual,direct}_call_{r,ir,irf}_{i,r,f,v}'."""
  333. if args is None:
  334. args = op.args[1:]
  335. self._check_no_vable_array(args)
  336. lst_i, lst_r, lst_f = self.make_three_lists(args)
  337. reskind = getkind(op.result.concretetype)[0]
  338. if lst_f or reskind == 'f': kinds = 'irf'
  339. elif lst_i: kinds = 'ir'
  340. else: kinds = 'r'
  341. sublists = []
  342. if 'i' in kinds: sublists.append(lst_i)
  343. if 'r' in kinds: sublists.append(lst_r)
  344. if 'f' in kinds: sublists.append(lst_f)
  345. if calldescr is not None:
  346. sublists.append(calldescr)
  347. return SpaceOperation('%s_%s_%s' % (namebase, kinds, reskind),
  348. initialargs + sublists, op.result)
  349. def make_three_lists(self, vars):
  350. args_i = []
  351. args_r = []
  352. args_f = []
  353. for v in vars:
  354. self.add_in_correct_list(v, args_i, args_r, args_f)
  355. return [ListOfKind('int', args_i),
  356. ListOfKind('ref', args_r),
  357. ListOfKind('float', args_f)]
  358. def add_in_correct_list(self, v, lst_i, lst_r, lst_f):
  359. kind = getkind(v.concretetype)
  360. if kind == 'void': return
  361. elif kind == 'int': lst = lst_i
  362. elif kind == 'ref': lst = lst_r
  363. elif kind == 'float': lst = lst_f
  364. else: raise AssertionError(kind)
  365. lst.append(v)
  366. def handle_residual_call(self, op, extraargs=[], may_call_jitcodes=False,
  367. oopspecindex=EffectInfo.OS_NONE,
  368. extraeffect=None,
  369. extradescr=None):
  370. """A direct_call turns into the operation 'residual_call_xxx' if it
  371. is calling a function that we don't want to JIT. The initial args
  372. of 'residual_call_xxx' are the function to call, and its calldescr."""
  373. calldescr = self.callcontrol.getcalldescr(op, oopspecindex=oopspecindex,
  374. extraeffect=extraeffect,
  375. extradescr=extradescr)
  376. op1 = self.rewrite_call(op, 'residual_call',
  377. [op.args[0]] + extraargs, calldescr=calldescr)
  378. if may_call_jitcodes or self.callcontrol.calldescr_canraise(calldescr):
  379. op1 = [op1, SpaceOperation('-live-', [], None)]
  380. return op1
  381. def handle_regular_call(self, op):
  382. """A direct_call turns into the operation 'inline_call_xxx' if it
  383. is calling a function that we want to JIT. The initial arg of
  384. 'inline_call_xxx' is the JitCode of the called function."""
  385. [targetgraph] = self.callcontrol.graphs_from(op)
  386. jitcode = self.callcontrol.get_jitcode(targetgraph,
  387. called_from=self.graph)
  388. op0 = self.rewrite_call(op, 'inline_call', [jitcode])
  389. op1 = SpaceOperation('-live-', [], None)
  390. return [op0, op1]
  391. def handle_builtin_call(self, op):
  392. oopspec_name, args = support.decode_builtin_call(op)
  393. # dispatch to various implementations depending on the oopspec_name
  394. if oopspec_name.startswith('list.') or oopspec_name.startswith('newlist'):
  395. prepare = self._handle_list_call
  396. elif oopspec_name.startswith('int.'):
  397. prepare = self._handle_int_special
  398. elif oopspec_name.startswith('stroruni.'):
  399. prepare = self._handle_stroruni_call
  400. elif oopspec_name == 'str.str2unicode':
  401. prepare = self._handle_str2unicode_call
  402. elif oopspec_name.startswith('virtual_ref'):
  403. prepare = self._handle_virtual_ref_call
  404. elif oopspec_name.startswith('jit.'):
  405. prepare = self._handle_jit_call
  406. elif oopspec_name.startswith('libffi_'):
  407. prepare = self._handle_libffi_call
  408. elif oopspec_name.startswith('math.sqrt'):
  409. prepare = self._handle_math_sqrt_call
  410. elif oopspec_name.startswith('rgc.'):
  411. prepare = self._handle_rgc_call
  412. elif oopspec_name.startswith('rvmprof.'):
  413. prepare = self._handle_rvmprof_call
  414. elif oopspec_name.endswith('dict.lookup'):
  415. # also ordereddict.lookup
  416. prepare = self._handle_dict_lookup_call
  417. else:
  418. prepare = self.prepare_builtin_call
  419. try:
  420. op1 = prepare(op, oopspec_name, args)
  421. except NotSupported:
  422. op1 = op
  423. # If the resulting op1 is still a direct_call, turn it into a
  424. # residual_call.
  425. if isinstance(op1, SpaceOperation) and op1.opname == 'direct_call':
  426. op1 = self.handle_residual_call(op1)
  427. return op1
  428. def handle_recursive_call(self, op):
  429. jitdriver_sd = self.callcontrol.jitdriver_sd_from_portal_runner_ptr(
  430. op.args[0].value)
  431. assert jitdriver_sd is not None
  432. ops = self.promote_greens(op.args[1:], jitdriver_sd.jitdriver)
  433. num_green_args = len(jitdriver_sd.jitdriver.greens)
  434. args = ([Constant(jitdriver_sd.index, lltype.Signed)] +
  435. self.make_three_lists(op.args[1:1+num_green_args]) +
  436. self.make_three_lists(op.args[1+num_green_args:]))
  437. kind = getkind(op.result.concretetype)[0]
  438. op0 = SpaceOperation('recursive_call_%s' % kind, args, op.result)
  439. op1 = SpaceOperation('-live-', [], None)
  440. return ops + [op0, op1]
  441. handle_residual_indirect_call = handle_residual_call
  442. def handle_regular_indirect_call(self, op):
  443. """An indirect call where at least one target has a JitCode."""
  444. lst = []
  445. for targetgraph in self.callcontrol.graphs_from(op):
  446. jitcode = self.callcontrol.get_jitcode(targetgraph,
  447. called_from=self.graph)
  448. lst.append(jitcode)
  449. op0 = SpaceOperation('-live-', [], None)
  450. op1 = SpaceOperation('int_guard_value', [op.args[0]], None)
  451. op2 = self.handle_residual_call(op, [IndirectCallTargets(lst)], True)
  452. result = [op0, op1]
  453. if isinstance(op2, list):
  454. result += op2
  455. else:
  456. result.append(op2)
  457. return result
  458. def prepare_builtin_call(self, op, oopspec_name, args,
  459. extra=None, extrakey=None):
  460. argtypes = [v.concretetype for v in args]
  461. resulttype = op.result.concretetype
  462. c_func, TP = support.builtin_func_for_spec(self.cpu.rtyper,
  463. oopspec_name, argtypes,
  464. resulttype, extra, extrakey)
  465. return SpaceOperation('direct_call', [c_func] + args, op.result)
  466. def _do_builtin_call(self, op, oopspec_name=None, args=None,
  467. extra=None, extrakey=None):
  468. if oopspec_name is None: oopspec_name = op.opname
  469. if args is None: args = op.args
  470. op1 = self.prepare_builtin_call(op, oopspec_name, args,
  471. extra, extrakey)
  472. return self.rewrite_op_direct_call(op1)
  473. # XXX some of the following functions should not become residual calls
  474. # but be really compiled
  475. rewrite_op_int_abs = _do_builtin_call
  476. rewrite_op_int_floordiv = _do_builtin_call
  477. rewrite_op_int_mod = _do_builtin_call
  478. rewrite_op_llong_abs = _do_builtin_call
  479. rewrite_op_llong_floordiv = _do_builtin_call
  480. rewrite_op_llong_mod = _do_builtin_call
  481. rewrite_op_ullong_floordiv = _do_builtin_call
  482. rewrite_op_ullong_mod = _do_builtin_call
  483. rewrite_op_gc_identityhash = _do_builtin_call
  484. rewrite_op_gc_id = _do_builtin_call
  485. rewrite_op_gc_pin = _do_builtin_call
  486. rewrite_op_gc_unpin = _do_builtin_call
  487. rewrite_op_cast_float_to_uint = _do_builtin_call
  488. rewrite_op_cast_uint_to_float = _do_builtin_call
  489. rewrite_op_weakref_create = _do_builtin_call
  490. rewrite_op_weakref_deref = _do_builtin_call
  491. rewrite_op_gc_add_memory_pressure = _do_builtin_call
  492. # ----------
  493. # getfield/setfield/mallocs etc.
  494. def rewrite_op_hint(self, op):
  495. hints = op.args[1].value
  496. # hack: if there are both 'promote' and 'promote_string', kill
  497. # one of them based on the type of the value
  498. if hints.get('promote_string') and hints.get('promote'):
  499. hints = hints.copy()
  500. if op.args[0].concretetype == lltype.Ptr(rstr.STR):
  501. del hints['promote']
  502. else:
  503. del hints['promote_string']
  504. if hints.get('promote') and op.args[0].concretetype is not lltype.Void:
  505. assert op.args[0].concretetype != lltype.Ptr(rstr.STR)
  506. kind = getkind(op.args[0].concretetype)
  507. op0 = SpaceOperation('-live-', [], None)
  508. op1 = SpaceOperation('%s_guard_value' % kind, [op.args[0]], None)
  509. # the special return value None forces op.result to be considered
  510. # equal to op.args[0]
  511. return [op0, op1, None]
  512. if (hints.get('promote_string') and
  513. op.args[0].concretetype is not lltype.Void):
  514. S = lltype.Ptr(rstr.STR)
  515. assert op.args[0].concretetype == S
  516. self._register_extra_helper(EffectInfo.OS_STREQ_NONNULL,
  517. "str.eq_nonnull",
  518. [S, S],
  519. lltype.Signed,
  520. EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
  521. descr, p = self.callcontrol.callinfocollection.callinfo_for_oopspec(
  522. EffectInfo.OS_STREQ_NONNULL)
  523. # XXX this is fairly ugly way of creating a constant,
  524. # however, callinfocollection has no better interface
  525. c = Constant(p.adr.ptr, lltype.typeOf(p.adr.ptr))
  526. op1 = SpaceOperation('str_guard_value', [op.args[0], c, descr],
  527. op.result)
  528. return [SpaceOperation('-live-', [], None), op1, None]
  529. if hints.get('force_virtualizable'):
  530. return SpaceOperation('hint_force_virtualizable', [op.args[0]], None)
  531. if hints.get('force_no_const'): # for tests only
  532. assert getkind(op.args[0].concretetype) == 'int'
  533. return SpaceOperation('int_same_as', [op.args[0]], op.result)
  534. log.WARNING('ignoring hint %r at %r' % (hints, self.graph))
  535. def _rewrite_raw_malloc(self, op, name, args):
  536. d = op.args[1].value.copy()
  537. d.pop('flavor')
  538. add_memory_pressure = d.pop('add_memory_pressure', False)
  539. zero = d.pop('zero', False)
  540. track_allocation = d.pop('track_allocation', True)
  541. if d:
  542. raise UnsupportedMallocFlags(d)
  543. if zero:
  544. name += '_zero'
  545. if add_memory_pressure:
  546. name += '_add_memory_pressure'
  547. if not track_allocation:
  548. name += '_no_track_allocation'
  549. TYPE = op.args[0].value
  550. op1 = self.prepare_builtin_call(op, name, args, (TYPE,), TYPE)
  551. if name.startswith('raw_malloc_varsize') and TYPE.OF == lltype.Char:
  552. return self._handle_oopspec_call(op1, args,
  553. EffectInfo.OS_RAW_MALLOC_VARSIZE_CHAR,
  554. EffectInfo.EF_CAN_RAISE)
  555. return self.rewrite_op_direct_call(op1)
  556. def rewrite_op_malloc_varsize(self, op):
  557. if op.args[1].value['flavor'] == 'raw':
  558. return self._rewrite_raw_malloc(op, 'raw_malloc_varsize',
  559. [op.args[2]])
  560. if op.args[0].value == rstr.STR:
  561. return SpaceOperation('newstr', [op.args[2]], op.result)
  562. elif op.args[0].value == rstr.UNICODE:
  563. return SpaceOperation('newunicode', [op.args[2]], op.result)
  564. else:
  565. # XXX only strings or simple arrays for now
  566. ARRAY = op.args[0].value
  567. arraydescr = self.cpu.arraydescrof(ARRAY)
  568. if op.args[1].value.get('zero', False):
  569. opname = 'new_array_clear'
  570. elif ((isinstance(ARRAY.OF, lltype.Ptr) and ARRAY.OF._needsgc()) or
  571. isinstance(ARRAY.OF, lltype.Struct)):
  572. opname = 'new_array_clear'
  573. else:
  574. opname = 'new_array'
  575. return SpaceOperation(opname, [op.args[2], arraydescr], op.result)
  576. def zero_contents(self, ops, v, TYPE):
  577. if isinstance(TYPE, lltype.Struct):
  578. for name, FIELD in TYPE._flds.iteritems():
  579. if isinstance(FIELD, lltype.Struct):
  580. # substruct
  581. self.zero_contents(ops, v, FIELD)
  582. else:
  583. c_name = Constant(name, lltype.Void)
  584. c_null = Constant(FIELD._defl(), FIELD)
  585. op = SpaceOperation('setfield', [v, c_name, c_null],
  586. None)
  587. self.extend_with(ops, self.rewrite_op_setfield(op,
  588. override_type=TYPE))
  589. elif isinstance(TYPE, lltype.Array):
  590. assert False # this operation disappeared
  591. else:
  592. raise TypeError("Expected struct or array, got '%r'", (TYPE,))
  593. if len(ops) == 1:
  594. return ops[0]
  595. return ops
  596. def extend_with(self, l, ops):
  597. if ops is None:
  598. return
  599. if isinstance(ops, list):
  600. l.extend(ops)
  601. else:
  602. l.append(ops)
  603. def rewrite_op_free(self, op):
  604. d = op.args[1].value.copy()
  605. assert d['flavor'] == 'raw'
  606. d.pop('flavor')
  607. track_allocation = d.pop('track_allocation', True)
  608. if d:
  609. raise UnsupportedMallocFlags(d)
  610. STRUCT = op.args[0].concretetype.TO
  611. name = 'raw_free'
  612. if not track_allocation:
  613. name += '_no_track_allocation'
  614. op1 = self.prepare_builtin_call(op, name, [op.args[0]], (STRUCT,),
  615. STRUCT)
  616. if name.startswith('raw_free'):
  617. return self._handle_oopspec_call(op1, [op.args[0]],
  618. EffectInfo.OS_RAW_FREE,
  619. EffectInfo.EF_CANNOT_RAISE)
  620. return self.rewrite_op_direct_call(op1)
  621. def rewrite_op_getarrayitem(self, op):
  622. ARRAY = op.args[0].concretetype.TO
  623. if self._array_of_voids(ARRAY):
  624. return []
  625. if isinstance(ARRAY, lltype.FixedSizeArray):
  626. raise NotImplementedError(
  627. "%r uses %r, which is not supported by the JIT codewriter"
  628. % (self.graph, ARRAY))
  629. if op.args[0] in self.vable_array_vars: # for virtualizables
  630. vars = self.vable_array_vars[op.args[0]]
  631. (v_base, arrayfielddescr, arraydescr) = vars
  632. kind = getkind(op.result.concretetype)
  633. return [SpaceOperation('-live-', [], None),
  634. SpaceOperation('getarrayitem_vable_%s' % kind[0],
  635. [v_base, op.args[1], arrayfielddescr,
  636. arraydescr], op.result)]
  637. # normal case follows
  638. pure = ''
  639. immut = ARRAY._immutable_field(None)
  640. if immut:
  641. pure = '_pure'
  642. arraydescr = self.cpu.arraydescrof(ARRAY)
  643. kind = getkind(op.result.concretetype)
  644. if ARRAY._gckind != 'gc':
  645. assert ARRAY._gckind == 'raw'
  646. if kind == 'r':
  647. raise Exception("getarrayitem_raw_r not supported")
  648. pure = '' # always redetected from pyjitpl.py: we don't need
  649. # a '_pure' version of getarrayitem_raw
  650. return SpaceOperation('getarrayitem_%s_%s%s' % (ARRAY._gckind,
  651. kind[0], pure),
  652. [op.args[0], op.args[1], arraydescr],
  653. op.result)
  654. def rewrite_op_setarrayitem(self, op):
  655. ARRAY = op.args[0].concretetype.TO
  656. if self._array_of_voids(ARRAY):
  657. return []
  658. if isinstance(ARRAY, lltype.FixedSizeArray):
  659. raise NotImplementedError(
  660. "%r uses %r, which is not supported by the JIT codewriter"
  661. % (self.graph, ARRAY))
  662. if op.args[0] in self.vable_array_vars: # for virtualizables
  663. vars = self.vable_array_vars[op.args[0]]
  664. (v_base, arrayfielddescr, arraydescr) = vars
  665. kind = getkind(op.args[2].concretetype)
  666. return [SpaceOperation('-live-', [], None),
  667. SpaceOperation('setarrayitem_vable_%s' % kind[0],
  668. [v_base, op.args[1], op.args[2],
  669. arrayfielddescr, arraydescr], None)]
  670. arraydescr = self.cpu.arraydescrof(ARRAY)
  671. kind = getkind(op.args[2].concretetype)
  672. return SpaceOperation('setarrayitem_%s_%s' % (ARRAY._gckind, kind[0]),
  673. [op.args[0], op.args[1], op.args[2], arraydescr],
  674. None)
  675. def rewrite_op_getarraysize(self, op):
  676. ARRAY = op.args[0].concretetype.TO
  677. assert ARRAY._gckind == 'gc'
  678. if op.args[0] in self.vable_array_vars: # for virtualizables
  679. vars = self.vable_array_vars[op.args[0]]
  680. (v_base, arrayfielddescr, arraydescr) = vars
  681. return [SpaceOperation('-live-', [], None),
  682. SpaceOperation('arraylen_vable',
  683. [v_base, arrayfielddescr, arraydescr],
  684. op.result)]
  685. # normal case follows
  686. arraydescr = self.cpu.arraydescrof(ARRAY)
  687. return SpaceOperation('arraylen_gc', [op.args[0], arraydescr],
  688. op.result)
  689. def rewrite_op_getarraysubstruct(self, op):
  690. ARRAY = op.args[0].concretetype.TO
  691. assert ARRAY._gckind == 'raw'
  692. assert ARRAY._hints.get('nolength') is True
  693. return self.rewrite_op_direct_ptradd(op)
  694. def _array_of_voids(self, ARRAY):
  695. return ARRAY.OF == lltype.Void
  696. def rewrite_op_getfield(self, op):
  697. if self.is_typeptr_getset(op):
  698. return self.handle_getfield_typeptr(op)
  699. # turn the flow graph 'getfield' operation into our own version
  700. [v_inst, c_fieldname] = op.args
  701. RESULT = op.result.concretetype
  702. if RESULT is lltype.Void:
  703. return
  704. # check for virtualizable
  705. try:
  706. if self.is_virtualizable_getset(op):
  707. descr = self.get_virtualizable_field_descr(op)
  708. kind = getkind(RESULT)[0]
  709. return [SpaceOperation('-live-', [], None),
  710. SpaceOperation('getfield_vable_%s' % kind,
  711. [v_inst, descr], op.result)]
  712. except VirtualizableArrayField as e:
  713. # xxx hack hack hack
  714. vinfo = e.args[1]
  715. arrayindex = vinfo.array_field_counter[op.args[1].value]
  716. arrayfielddescr = vinfo.array_field_descrs[arrayindex]
  717. arraydescr = vinfo.array_descrs[arrayindex]
  718. self.vable_array_vars[op.result] = (op.args[0],
  719. arrayfielddescr,
  720. arraydescr)
  721. return []
  722. # check for _immutable_fields_ hints
  723. immut = v_inst.concretetype.TO._immutable_field(c_fieldname.value)
  724. need_live = False
  725. if immut:
  726. if (self.callcontrol is not None and
  727. self.callcontrol.could_be_green_field(v_inst.concretetype.TO,
  728. c_fieldname.value)):
  729. pure = '_greenfield'
  730. need_live = True
  731. else:
  732. pure = '_pure'
  733. else:
  734. pure = ''
  735. self.check_field_access(v_inst.concretetype.TO)
  736. argname = getattr(v_inst.concretetype.TO, '_gckind', 'gc')
  737. descr = self.cpu.fielddescrof(v_inst.concretetype.TO,
  738. c_fieldname.value)
  739. kind = getkind(RESULT)[0]
  740. if argname != 'gc':
  741. assert argname == 'raw'
  742. if (kind, pure) == ('r', ''):
  743. # note: a pure 'getfield_raw_r' is used e.g. to load class
  744. # attributes that are GC objects, so that one is supported.
  745. raise Exception("getfield_raw_r (without _pure) not supported")
  746. pure = '' # always redetected from pyjitpl.py: we don't need
  747. # a '_pure' version of getfield_raw
  748. #
  749. op1 = SpaceOperation('getfield_%s_%s%s' % (argname, kind, pure),
  750. [v_inst, descr], op.result)
  751. #
  752. if immut in (IR_QUASIIMMUTABLE, IR_QUASIIMMUTABLE_ARRAY):
  753. op1.opname += "_pure"
  754. descr1 = self.cpu.fielddescrof(
  755. v_inst.concretetype.TO,
  756. quasiimmut.get_mutate_field_name(c_fieldname.value))
  757. return [SpaceOperation('-live-', [], None),
  758. SpaceOperation('record_quasiimmut_field',
  759. [v_inst, descr, descr1], None),
  760. op1]
  761. if need_live:
  762. return [SpaceOperation('-live-', [], None), op1]
  763. return op1
  764. def rewrite_op_setfield(self, op, override_type=None):
  765. if self.is_typeptr_getset(op):
  766. # ignore the operation completely -- instead, it's done by 'new'
  767. return
  768. self._check_no_vable_array(op.args)
  769. # turn the flow graph 'setfield' operation into our own version
  770. [v_inst, c_fieldname, v_value] = op.args
  771. RESULT = v_value.concretetype
  772. if override_type is not None:
  773. TYPE = override_type
  774. else:
  775. TYPE = v_inst.concretetype.TO
  776. if RESULT is lltype.Void:
  777. return
  778. # check for virtualizable
  779. if self.is_virtualizable_getset(op):
  780. descr = self.get_virtualizable_field_descr(op)
  781. kind = getkind(RESULT)[0]
  782. return [SpaceOperation('-live-', [], None),
  783. SpaceOperation('setfield_vable_%s' % kind,
  784. [v_inst, v_value, descr], None)]
  785. self.check_field_access(TYPE)
  786. if override_type:
  787. argname = 'gc'
  788. else:
  789. argname = getattr(TYPE, '_gckind', 'gc')
  790. descr = self.cpu.fielddescrof(TYPE, c_fieldname.value)
  791. kind = getkind(RESULT)[0]
  792. if argname == 'raw' and kind == 'r':
  793. raise Exception("setfield_raw_r not supported")
  794. return SpaceOperation('setfield_%s_%s' % (argname, kind),
  795. [v_inst, v_value, descr],
  796. None)
  797. def rewrite_op_getsubstruct(self, op):
  798. STRUCT = op.args[0].concretetype.TO
  799. argname = getattr(STRUCT, '_gckind', 'gc')
  800. if argname != 'raw':
  801. raise Exception("%r: only supported for gckind=raw" % (op,))
  802. ofs = llmemory.offsetof(STRUCT, op.args[1].value)
  803. return SpaceOperation('int_add',
  804. [op.args[0], Constant(ofs, lltype.Signed)],
  805. op.result)
  806. def is_typeptr_getset(self, op):
  807. return (op.args[1].value == 'typeptr' and
  808. op.args[0].concretetype.TO._hints.get('typeptr'))
  809. def check_field_access(self, STRUCT):
  810. # check against a GcStruct with a nested GcStruct as a first argument
  811. # but which is not an object at all; see metainterp/test/test_loop,
  812. # test_regular_pointers_in_short_preamble.
  813. if not isinstance(STRUCT, lltype.GcStruct):
  814. return
  815. if STRUCT._first_struct() == (None, None):
  816. return
  817. PARENT = STRUCT
  818. while not PARENT._hints.get('typeptr'):
  819. _, PARENT = PARENT._first_struct()
  820. if PARENT is None:
  821. raise NotImplementedError("%r is a GcStruct using nesting but "
  822. "not inheriting from object" %
  823. (STRUCT,))
  824. def get_vinfo(self, v_virtualizable):
  825. if self.callcontrol is None: # for tests
  826. return None
  827. return self.callcontrol.get_vinfo(v_virtualizable.concretetype)
  828. def is_virtualizable_getset(self, op):
  829. # every access of an object of exactly the type VTYPEPTR is
  830. # likely to be a virtualizable access, but we still have to
  831. # check it in pyjitpl.py.
  832. vinfo = self.get_vinfo(op.args[0])
  833. if vinfo is None:
  834. return False
  835. res = False
  836. if op.args[1].value in vinfo.static_field_to_extra_box:
  837. res = True
  838. if op.args[1].value in vinfo.array_fields:
  839. res = VirtualizableArrayField(self.graph, vinfo)
  840. if res:
  841. flags = self.vable_flags[op.args[0]]
  842. if 'fresh_virtualizable' in flags:
  843. return False
  844. if isinstance(res, Exception):
  845. raise res
  846. return res
  847. def get_virtualizable_field_descr(self, op):
  848. fieldname = op.args[1].value
  849. vinfo = self.get_vinfo(op.args[0])
  850. index = vinfo.static_field_to_extra_box[fieldname]
  851. return vinfo.static_field_descrs[index]
  852. def handle_getfield_typeptr(self, op):
  853. if isinstance(op.args[0], Constant):
  854. cls = op.args[0].value.typeptr
  855. return Constant(cls, concretetype=rclass.CLASSTYPE)
  856. op0 = SpaceOperation('-live-', [], None)
  857. op1 = SpaceOperation('guard_class', [op.args[0]], op.result)
  858. return [op0, op1]
  859. def rewrite_op_malloc(self, op):
  860. d = op.args[1].value
  861. if d.get('nonmovable', False):
  862. raise UnsupportedMallocFlags(d)
  863. if d['flavor'] == 'raw':
  864. return self._rewrite_raw_malloc(op, 'raw_malloc_fixedsize', [])
  865. #
  866. if d.get('zero', False):
  867. zero = True
  868. else:
  869. zero = False
  870. STRUCT = op.args[0].value
  871. vtable = heaptracker.get_vtable_for_gcstruct(self.cpu, STRUCT)
  872. if vtable:
  873. # do we have a __del__?
  874. try:
  875. rtti = lltype.getRuntimeTypeInfo(STRUCT)
  876. except ValueError:
  877. pass
  878. else:
  879. if hasattr(rtti._obj, 'destructor_funcptr'):
  880. RESULT = lltype.Ptr(STRUCT)
  881. assert RESULT == op.result.concretetype
  882. return self._do_builtin_call(op, 'alloc_with_del', [],
  883. extra=(RESULT, vtable),
  884. extrakey=STRUCT)
  885. opname = 'new_with_vtable'
  886. else:
  887. opname = 'new'
  888. vtable = lltype.nullptr(rclass.OBJECT_VTABLE)
  889. sizedescr = self.cpu.sizeof(STRUCT, vtable)
  890. op1 = SpaceOperation(opname, [sizedescr], op.result)
  891. if zero:
  892. return self.zero_contents([op1], op.result, STRUCT)
  893. return op1
  894. def _has_gcptrs_in(self, STRUCT):
  895. if isinstance(STRUCT, lltype.Array):
  896. ITEM = STRUCT.OF
  897. if isinstance(ITEM, lltype.Struct):
  898. STRUCT = ITEM
  899. else:
  900. return isinstance(ITEM, lltype.Ptr) and ITEM._needsgc()
  901. for FIELD in STRUCT._flds.values():
  902. if isinstance(FIELD, lltype.Ptr) and FIELD._needsgc():
  903. return True
  904. elif isinstance(FIELD, lltype.Struct):
  905. if self._has_gcptrs_in(FIELD):
  906. return True
  907. return False
  908. def rewrite_op_getinteriorarraysize(self, op):
  909. # only supports strings and unicodes
  910. assert len(op.args) == 2
  911. assert op.args[1].value == 'chars'
  912. optype = op.args[0].concretetype
  913. if optype == lltype.Ptr(rstr.STR):
  914. opname = "strlen"
  915. elif optype == lltype.Ptr(rstr.UNICODE):
  916. opname = "unicodelen"
  917. elif optype == lltype.Ptr(rbytearray.BYTEARRAY):
  918. bytearraydescr = self.cpu.arraydescrof(rbytearray.BYTEARRAY)
  919. return SpaceOperation('arraylen_gc', [op.args[0], bytearraydescr],
  920. op.result)
  921. else:
  922. assert 0, "supported type %r" % (optype,)
  923. return SpaceOperation(opname, [op.args[0]], op.result)
  924. def rewrite_op_getinteriorfield(self, op):
  925. assert len(op.args) == 3
  926. optype = op.args[0].concretetype
  927. if optype == lltype.Ptr(rstr.STR):
  928. opname = "strgetitem"
  929. return SpaceOperation(opname, [op.args[0], op.args[2]], op.result)
  930. elif optype == lltype.Ptr(rstr.UNICODE):
  931. opname = "unicodegetitem"
  932. return SpaceOperation(opname, [op.args[0], op.args[2]], op.result)
  933. elif optype == lltype.Ptr(rbytearray.BYTEARRAY):
  934. bytearraydescr = self.cpu.arraydescrof(rbytearray.BYTEARRAY)
  935. v_index = op.args[2]
  936. return SpaceOperation('getarrayitem_gc_i',
  937. [op.args[0], v_index, bytearraydescr],
  938. op.result)
  939. elif op.result.concretetype is lltype.Void:
  940. return
  941. elif isinstance(op.args[0].concretetype.TO, lltype.GcArray):
  942. # special-case 1: GcArray of Struct
  943. v_inst, v_index, c_field = op.args
  944. STRUCT = v_inst.concretetype.TO.OF
  945. assert isinstance(STRUCT, lltype.Struct)
  946. descr = self.cpu.interiorfielddescrof(v_inst.concretetype.TO,
  947. c_field.value)
  948. args = [v_inst, v_index, descr]
  949. kind = getkind(op.result.concretetype)[0]
  950. return SpaceOperation('getinteriorfield_gc_%s' % kind, args,
  951. op.result)
  952. #elif isinstance(op.args[0].concretetype.TO, lltype.GcStruct):
  953. # # special-case 2: GcStruct with Array field
  954. # ---was added in the faster-rstruct branch,---
  955. # ---no longer directly supported---
  956. # v_inst, c_field, v_index = op.args
  957. # STRUCT = v_inst.concretetype.TO
  958. # ARRAY = getattr(STRUCT, c_field.value)
  959. # assert isinstance(ARRAY, lltype.Array)
  960. # arraydescr = self.cpu.arraydescrof(STRUCT)
  961. # kind = getkind(op.result.concretetype)[0]
  962. # assert kind in ('i', 'f')
  963. # return SpaceOperation('getarrayitem_gc_%s' % kind,
  964. # [op.args[0], v_index, arraydescr],
  965. # op.result)
  966. else:
  967. assert False, 'not supported'
  968. def rewrite_op_setinteriorfield(self, op):
  969. assert len(op.args) == 4
  970. optype = op.args[0].concretetype
  971. if optype == lltype.Ptr(rstr.STR):
  972. opname = "strsetitem"
  973. return SpaceOperation(opname, [op.args[0], op.args[2], op.args[3]],
  974. op.result)
  975. elif optype == lltype.Ptr(rstr.UNICODE):
  976. opname = "unicodesetitem"
  977. return SpaceOperation(opname, [op.args[0], op.args[2], op.args[3]],
  978. op.result)
  979. elif optype == lltype.Ptr(rbytearray.BYTEARRAY):
  980. bytearraydescr = self.cpu.arraydescrof(rbytearray.BYTEARRAY)
  981. opname = "setarrayitem_gc_i"
  982. return SpaceOperation(opname, [op.args[0], op.args[2], op.args[3],
  983. bytearraydescr], op.result)
  984. else:
  985. v_inst, v_index, c_field, v_value = op.args
  986. if v_value.concretetype is lltype.Void:
  987. return
  988. # only GcArray of Struct supported
  989. assert isinstance(v_inst.concretetype.TO, lltype.GcArray)
  990. STRUCT = v_inst.concretetype.TO.OF
  991. assert isinstance(STRUCT, lltype.Struct)
  992. descr = self.cpu.interiorfielddescrof(v_inst.concretetype.TO,
  993. c_field.value)
  994. kind = getkind(v_value.concretetype)[0]
  995. args = [v_inst, v_index, v_value, descr]
  996. return SpaceOperation('setinteriorfield_gc_%s' % kind, args,
  997. op.result)
  998. def rewrite_op_raw_store(self, op):
  999. T = op.args[2].concretetype
  1000. kind = getkind(T)[0]
  1001. assert kind != 'r'
  1002. descr = self.cpu.arraydescrof(rffi.CArray(T))
  1003. return SpaceOperation('raw_store_%s' % kind,
  1004. [op.args[0], op.args[1], op.args[2], descr],
  1005. None)
  1006. def rewrite_op_raw_load(self, op):
  1007. T = op.result.concretetype
  1008. kind = getkind(T)[0]
  1009. assert kind != 'r'
  1010. descr = self.cpu.arraydescrof(rffi.CArray(T))
  1011. return SpaceOperation('raw_load_%s' % kind,
  1012. [op.args[0], op.args[1], descr], op.result)
  1013. def rewrite_op_gc_load_indexed(self, op):
  1014. T = op.result.concretetype
  1015. kind = getkind(T)[0]
  1016. assert kind != 'r'
  1017. descr = self.cpu.arraydescrof(rffi.CArray(T))
  1018. if (not isinstance(op.args[2], Constant) or
  1019. not isinstance(op.args[3], Constant)):
  1020. raise NotImplementedError("gc_load_indexed: 'scale' and 'base_ofs'"
  1021. " should be constants")
  1022. # xxx hard-code the size in bytes at translation time, which is
  1023. # probably fine and avoids lots of issues later
  1024. bytes = descr.get_item_size_in_bytes()
  1025. if descr.is_item_signed():
  1026. bytes = -bytes
  1027. c_bytes = Constant(bytes, lltype.Signed)
  1028. return SpaceOperation('gc_load_indexed_%s' % kind,
  1029. [op.args[0], op.args[1],
  1030. op.args[2], op.args[3], c_bytes], op.result)
  1031. def _rewrite_equality(self, op, opname):
  1032. arg0, arg1 = op.args
  1033. if isinstance(arg0, Constant) and not arg0.value:
  1034. return SpaceOperation(opname, [arg1], op.result)
  1035. elif isinstance(arg1, Constant) and not arg1.value:
  1036. return SpaceOperation(opname, [arg0], op.result)
  1037. else:
  1038. return self._rewrite_symmetric(op)
  1039. def _is_gc(self, v):
  1040. return lltype_is_gc(v.concretetype)
  1041. def _is_rclass_instance(self, v):
  1042. return lltype._castdepth(v.concretetype.TO, rclass.OBJECT) >= 0
  1043. def _rewrite_cmp_ptrs(self, op):
  1044. if self._is_gc(op.args[0]):
  1045. return op
  1046. else:
  1047. opname = {'ptr_eq': 'int_eq',
  1048. 'ptr_ne': 'int_ne',
  1049. 'ptr_iszero': 'int_is_zero',
  1050. 'ptr_nonzero': 'int_is_true'}[op.opname]
  1051. return SpaceOperation(opname, op.args, op.result)
  1052. def rewrite_op_int_eq(self, op):
  1053. return self._rewrite_equality(op, 'int_is_zero')
  1054. def rewrite_op_int_ne(self, op):
  1055. return self._rewrite_equality(op, 'int_is_true')
  1056. def rewrite_op_ptr_eq(self, op):
  1057. if self._is_rclass_instance(op.args[0]):
  1058. assert self._is_rclass_instance(op.args[1])
  1059. op = SpaceOperation('instance_ptr_eq', op.args, op.result)
  1060. op1 = self._rewrite_equality(op, 'ptr_iszero')
  1061. return self._rewrite_cmp_ptrs(op1)
  1062. def rewrite_op_ptr_ne(self, op):
  1063. if self._is_rclass_instance(op.args[0]):
  1064. assert self._is_rclass_instance(op.args[1])
  1065. op = SpaceOperation('instance_ptr_ne', op.args, op.result)
  1066. op1 = self._rewrite_equality(op, 'ptr_nonzero')
  1067. return self._rewrite_cmp_ptrs(op1)
  1068. rewrite_op_ptr_iszero = _rewrite_cmp_ptrs
  1069. rewrite_op_ptr_nonzero = _rewrite_cmp_ptrs
  1070. def rewrite_op_cast_ptr_to_int(self, op):
  1071. if self._is_gc(op.args[0]):
  1072. return op
  1073. def rewrite_op_cast_opaque_ptr(self, op):
  1074. # None causes the result of this op to get aliased to op.args[0]
  1075. return None
  1076. def rewrite_op_force_cast(self, op):
  1077. v_arg = op.args[0]
  1078. v_result = op.result
  1079. if v_arg.concretetype == v_result.concretetype:
  1080. return
  1081. elif self._is_gc(v_arg) and self._is_gc(v_result):
  1082. # cast from GC to GC is always fine
  1083. return
  1084. else:
  1085. assert not self._is_gc(v_arg)
  1086. float_arg = v_arg.concretetype in [lltype.Float, lltype.SingleFloat]
  1087. float_res = v_result.concretetype in [lltype.Float, lltype.SingleFloat]
  1088. if not float_arg and not float_res:
  1089. # some int -> some int cast
  1090. return self._int_to_int_cast(v_arg, v_result)
  1091. elif float_arg and float_res:
  1092. # some float -> some float cast
  1093. return self._float_to_float_cast(v_arg, v_result)
  1094. elif not float_arg and float_res:
  1095. # some int -> some float
  1096. ops = []
  1097. v2 = varoftype(lltype.Float)
  1098. sizesign = rffi.size_and_sign(v_arg.concretetype)
  1099. if sizesign <= rffi.size_and_sign(lltype.Signed):
  1100. # cast from a type that fits in an int: either the size is
  1101. # smaller, or it is equal and it is not unsigned
  1102. v1 = varoftype(lltype.Signed)
  1103. oplist = self.rewrite_operation(
  1104. SpaceOperation('force_cast', [v_arg], v1)
  1105. )
  1106. if oplist:
  1107. ops.extend(oplist)
  1108. else:
  1109. v1 = v_arg
  1110. op = self.rewrite_operation(
  1111. SpaceOperation('cast_int_to_float', [v1], v2)
  1112. )
  1113. ops.append(op)
  1114. else:
  1115. if sizesign == rffi.size_and_sign(lltype.Unsigned):
  1116. opname = 'cast_uint_to_float'
  1117. elif sizesign == rffi.size_and_sign(lltype.SignedLongLong):
  1118. opname = 'cast_longlong_to_float'
  1119. elif sizesign == rffi.size_and_sign(lltype.UnsignedLongLong):
  1120. opname = 'cast_ulonglong_to_float'
  1121. else:
  1122. raise AssertionError('cast_x_to_float: %r' % (sizesign,))
  1123. ops1 = self.rewrite_operation(
  1124. SpaceOperation(opname, [v_arg], v2)
  1125. )
  1126. if not isinstance(ops1, list): ops1 = [ops1]
  1127. ops.extend(ops1)
  1128. op2 = self.rewrite_operation(
  1129. SpaceOperation('force_cast', [v2], v_result)
  1130. )
  1131. if op2:
  1132. ops.append(op2)
  1133. else:
  1134. ops[-1].result = v_result
  1135. return ops
  1136. elif float_arg and not float_res:
  1137. # some float -> some int
  1138. ops = []
  1139. v1 = varoftype(lltype.Float)
  1140. op1 = self.rewrite_operation(
  1141. SpaceOperation('force_cast', [v_arg], v1)
  1142. )
  1143. if op1:
  1144. ops.append(op1)
  1145. else:
  1146. v1 = v_arg
  1147. sizesign = rffi.size_and_sign(v_result.concretetype)
  1148. if v_result.concretetype is lltype.Bool:
  1149. op = self.rewrite_operation(
  1150. SpaceOperation('float_is_true', [v1], v_result)
  1151. )
  1152. ops.append(op)
  1153. elif sizesign <= rffi.size_and_sign(lltype.Signed):
  1154. # cast to a type that fits in an int: either the size is
  1155. # smaller, or it is equal and it is not unsigned
  1156. v2 = varoftype(lltype.Signed)
  1157. op = self.rewrite_operation(
  1158. SpaceOperation('cast_float_to_int', [v1], v2)
  1159. )
  1160. ops.append(op)
  1161. oplist = self.rewrite_operation(
  1162. SpaceOperation('force_cast', [v2], v_result)
  1163. )
  1164. if oplist:
  1165. ops.extend(oplist)
  1166. else:
  1167. op.result = v_result
  1168. else:
  1169. if sizesign == rffi.size_and_sign(lltype.Unsigned):
  1170. opname = 'cast_float_to_uint'
  1171. elif sizesign == rffi.size_and_sign(lltype.SignedLongLong):
  1172. opname = 'cast_float_to_longlong'
  1173. elif sizesign == rffi.size_and_sign(lltype.UnsignedLongLong):
  1174. opname = 'cast_float_to_ulonglong'
  1175. else:
  1176. raise AssertionError('cast_float_to_x: %r' % (sizesign,))
  1177. ops1 = self.rewrite_operation(
  1178. SpaceOperation(opname, [v1], v_result)
  1179. )
  1180. if not isinstance(ops1, list): ops1 = [ops1]
  1181. ops.extend(ops1)
  1182. return ops
  1183. else:
  1184. assert False
  1185. def _int_to_int_cast(self, v_arg, v_result):
  1186. longlong_arg = longlong.is_longlong(v_arg.concretetype)
  1187. longlong_res = longlong.is_longlong(v_result.concretetype)
  1188. size1, unsigned1 = rffi.size_and_sign(v_arg.concretetype)
  1189. size2, unsigned2 = rffi.size_and_sign(v_result.concretetype)
  1190. if longlong_arg and longlong_res:
  1191. return
  1192. elif longlong_arg:
  1193. if v_result.concretetype is lltype.Bool:
  1194. longlong_zero = rffi.cast(v_arg.concretetype, 0)
  1195. c_longlong_zero = Constant(longlong_zero, v_arg.concretetype)
  1196. if unsigned1:
  1197. name = 'ullong_ne'
  1198. else:
  1199. name = 'llong_ne'
  1200. op1 = SpaceOperation(name, [v_arg, c_longlong_zero], v_result)
  1201. return self.rewrite_operation(op1)
  1202. v = varoftype(lltype.Signed)
  1203. op1 = self.rewrite_operation(
  1204. SpaceOperation('truncate_longlong_to_int', [v_arg], v)
  1205. )
  1206. op2 = SpaceOperation('force_cast', [v], v_result)
  1207. oplist = self.rewrite_operation(op2)
  1208. if not oplist:
  1209. op1.result = v_result
  1210. oplist = []
  1211. return [op1] + oplist
  1212. elif longlong_res:
  1213. if unsigned1:
  1214. INTERMEDIATE = lltype.Unsigned
  1215. else:
  1216. INTERMEDIATE = lltype.Signed
  1217. v = varoftype(INTERMEDIATE)
  1218. op1 = SpaceOperation('force_cast', [v_arg], v)
  1219. oplist = self.rewrite_operation(op1)
  1220. if not oplist:
  1221. v = v_arg
  1222. oplist = []
  1223. if unsigned1:
  1224. if unsigned2:
  1225. opname = 'cast_uint_to_ulonglong'
  1226. else:
  1227. opname = 'cast_uint_to_longlong'
  1228. else:
  1229. if unsigned2:
  1230. opname = 'cast_int_to_ulonglong'
  1231. else:
  1232. opname = 'cast_int_to_longlong'
  1233. op2 = self.rewrite_operation(
  1234. SpaceOperation(opname, [v], v_result)
  1235. )
  1236. return oplist + [op2]
  1237. # We've now, ostensibly, dealt with the longlongs, everything should be
  1238. # a Signed or smaller
  1239. assert size1 <= rffi.sizeof(lltype.Signed)
  1240. assert size2 <= rffi.sizeof(lltype.Signed)
  1241. # the target type is LONG or ULONG
  1242. if size2 == rffi.sizeof(lltype.Signed):
  1243. return
  1244. min1, max1 = integer_bounds(size1, unsigned1)
  1245. min2, max2 = integer_bounds(size2, unsigned2)
  1246. # the target type includes the source range
  1247. if min2 <= min1 <= max1 <= max2:
  1248. return
  1249. result = []
  1250. if v_result.concretetype is lltype.Bool:
  1251. result.append(SpaceOperation('int_is_true', [v_arg], v_result))
  1252. elif min2:
  1253. c_bytes = Constant(size2, lltype.Signed)
  1254. result.append(SpaceOperation('int_signext', [v_arg, c_bytes],
  1255. v_result))
  1256. else:
  1257. c_mask = Constant(int((1 << (8 * size2)) - 1), lltype.Signed)
  1258. result.append(SpaceOperation('int_and', [v_arg, c_mask], v_result))
  1259. return result
  1260. def _float_to_float_cast(self, v_arg, v_result):
  1261. if v_arg.concretetype == lltype.SingleFloat:
  1262. assert v_result.concretetype == lltype.Float, "cast %s -> %s" % (
  1263. v_arg.concretetype, v_result.concretetype)
  1264. return SpaceOperation('cast_singlefloat_to_float', [v_arg],
  1265. v_result)
  1266. if v_result.concretetype == lltype.SingleFloat:
  1267. assert v_arg.concretetype == lltype.Float, "cast %s -> %s" % (
  1268. v_arg.concretetype, v_result.concretetype)
  1269. return SpaceOperation('cast_float_to_singlefloat', [v_arg],
  1270. v_result)
  1271. def rewrite_op_direct_ptradd(self, op):
  1272. v_shift = op.args[1]
  1273. assert v_shift.concretetype == lltype.Signed
  1274. ops = []
  1275. #
  1276. if op.args[0].concretetype != rffi.CCHARP:
  1277. v_prod = varoftype(lltype.Signed)
  1278. by = llmemory.sizeof(op.args[0].concretetype.TO.OF)
  1279. c_by = Constant(by, lltype.Signed)
  1280. ops.append(SpaceOperation('int_mul', [v_shift, c_by], v_prod))
  1281. v_shift = v_prod
  1282. #
  1283. ops.append(SpaceOperation('int_add', [op.args[0], v_shift], op.result))
  1284. return ops
  1285. # ----------
  1286. # Long longs, for 32-bit only. Supported operations are left unmodified,
  1287. # and unsupported ones are turned into a call to a function from
  1288. # jit.codewriter.support.
  1289. for _op, _oopspec in [('llong_invert', 'INVERT'),
  1290. ('llong_lt', 'LT'),
  1291. ('llong_le', 'LE'),
  1292. ('llong_eq', 'EQ'),
  1293. ('llong_ne', 'NE'),
  1294. ('llong_gt', 'GT'),
  1295. ('llong_ge', 'GE'),
  1296. ('llong_add', 'ADD'),
  1297. ('llong_sub', 'SUB'),
  1298. ('llong_mul', 'MUL'),
  1299. ('llong_and', 'AND'),
  1300. ('llong_or', 'OR'),
  1301. ('llong_xor', 'XOR'),
  1302. ('llong_lshift', 'LSHIFT'),
  1303. ('llong_rshift', 'RSHIFT'),
  1304. ('cast_int_to_longlong', 'FROM_INT'),
  1305. ('truncate_longlong_to_int', 'TO_INT'),
  1306. ('cast_float_to_longlong', 'FROM_FLOAT'),
  1307. ('cast_longlong_to_float', 'TO_FLOAT'),
  1308. ('cast_uint_to_longlong', 'FROM_UINT'),
  1309. ]:
  1310. exec py.code.Source('''
  1311. def rewrite_op_%s(self, op):
  1312. args = op.args
  1313. op1 = self.prepare_builtin_call(op, "llong_%s", args)
  1314. op2 = self._handle_oopspec_call(op1, args,
  1315. EffectInfo.OS_LLONG_%s,
  1316. EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
  1317. if %r == "TO_INT":
  1318. assert op2.result.concretetype == lltype.Signed
  1319. return op2
  1320. ''' % (_op, _oopspec.lower(), _oopspec, _oopspec)).compile()
  1321. for _op, _oopspec in [('cast_int_to_ulonglong', 'FROM_INT'),
  1322. ('cast_uint_to_ulonglong', 'FROM_UINT'),
  1323. ('cast_float_to_ulonglong', 'FROM_FLOAT'),
  1324. ('cast_ulonglong_to_float', 'U_TO_FLOAT'),
  1325. ('ullong_invert', 'INVERT'),
  1326. ('ullong_lt', 'ULT'),
  1327. ('ullong_le', 'ULE'),
  1328. ('ullong_eq', 'EQ'),
  1329. ('ullong_ne', 'NE'),
  1330. ('ullong_gt', 'UGT'),
  1331. ('ullong_ge', 'UGE'),
  1332. ('ullong_add', 'ADD'),
  1333. ('ullong_sub', 'SUB'),
  1334. ('ullong_mul', 'MUL'),
  1335. ('ullong_and', 'AND'),
  1336. ('ullong_or', 'OR'),
  1337. ('ullong_xor', 'XOR'),
  1338. ('ullong_lshift', 'LSHIFT'),
  1339. ('ullong_rshift', 'URSHIFT'),
  1340. ]:
  1341. exec py.code.Source('''
  1342. def rewrite_op_%s(self, op):
  1343. args = op.args
  1344. op1 = self.prepare_builtin_call(op, "ullong_%s", args)
  1345. op2 = self._handle_oopspec_call(op1, args,
  1346. EffectInfo.OS_LLONG_%s,
  1347. EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
  1348. return op2
  1349. ''' % (_op, _oopspec.lower(), _oopspec)).compile()
  1350. def _normalize(self, oplist):
  1351. if isinstance(oplist, SpaceOperation):
  1352. return [oplist]
  1353. else:
  1354. assert type(oplist) is list
  1355. return oplist
  1356. def rewrite_op_llong_neg(self, op):
  1357. v = varoftype(lltype.SignedLongLong)
  1358. op0 = SpaceOperation('cast_int_to_longlong',
  1359. [Constant(0, lltype.Signed)],
  1360. v)
  1361. args = [v, op.args[0]]
  1362. op1 = SpaceOperation('llong_sub', args, op.result)
  1363. return (self._normalize(self.rewrite_operation(op0)) +
  1364. self._normalize(self.rewrite_operation(op1)))
  1365. def rewrite_op_llong_is_true(self, op):
  1366. v = varoftype(op.args[0].concretetype)
  1367. op0 = SpaceOperation('cast_primitive',
  1368. [Constant(0, lltype.Signed)],
  1369. v)
  1370. args = [op.args[0], v]
  1371. op1 = SpaceOperation('llong_ne', args, op.result)
  1372. return (self._normalize(self.rewrite_operation(op0)) +
  1373. self._normalize(self.rewrite_operation(op1)))
  1374. rewrite_op_ullong_is_true = rewrite_op_llong_is_true
  1375. def rewrite_op_cast_primitive(self, op):
  1376. return self.rewrite_op_force_cast(op)
  1377. # ----------
  1378. # Renames, from the _old opname to the _new one.
  1379. # The new operation is optionally further processed by rewrite_operation().
  1380. for _old, _new in [('bool_not', 'int_is_zero'),
  1381. ('cast_bool_to_float', 'cast_int_to_float'),
  1382. ('int_add_nonneg_ovf', 'int_add_ovf'),
  1383. ('keepalive', '-live-'),
  1384. ('char_lt', 'int_lt'),
  1385. ('char_le', 'int_le'),
  1386. ('char_eq', 'int_eq'),
  1387. ('char_ne', 'int_ne'),
  1388. ('char_gt', 'int_gt'),
  1389. ('char_ge', 'int_ge'),
  1390. ('unichar_eq', 'int_eq'),
  1391. ('unichar_ne', 'int_ne'),
  1392. ('uint_is_true', 'int_is_true'),
  1393. ('uint_invert', 'int_invert'),
  1394. ('uint_add', 'int_add'),
  1395. ('uint_sub', 'int_sub'),
  1396. ('uint_mul', 'int_mul'),
  1397. ('uint_eq', 'int_eq'),
  1398. ('uint_ne', 'int_ne'),
  1399. ('uint_and', 'int_and'),
  1400. ('uint_or', 'int_or'),
  1401. ('uint_lshift', 'int_lshift'),
  1402. ('uint_xor', 'int_xor'),
  1403. ('adr_add', 'int_add'),
  1404. ]:
  1405. assert _old not in locals()
  1406. exec py.code.Source('''
  1407. def rewrite_op_%s(self, op):
  1408. op1 = SpaceOperation(%r, op.args, op.result)
  1409. return self.rewrite_operation(op1)
  1410. ''' % (_old, _new)).compile()
  1411. def rewrite_op_float_is_true(self, op):
  1412. op1 = SpaceOperation('float_ne',
  1413. [op.args[0], Constant(0.0, lltype.Float)],
  1414. op.result)
  1415. return self.rewrite_operation(op1)
  1416. def rewrite_op_int_is_true(self, op):
  1417. if isinstance(op.args[0], Constant):
  1418. value = op.args[0].value
  1419. if value is objectmodel.malloc_zero_filled:
  1420. value = True
  1421. elif value is _we_are_jitted:
  1422. value = True
  1423. else:
  1424. raise AssertionError("don't know the truth value of %r"
  1425. % (value,))
  1426. return Constant(value, lltype.Bool)
  1427. return op
  1428. def promote_greens(self, args, jitdriver):
  1429. ops = []
  1430. num_green_args = len(jitdriver.greens)
  1431. assert len(args) == num_green_args + jitdriver.numreds
  1432. for v in args[:num_green_args]:
  1433. if isinstance(v, Variable) and v.concretetype is not lltype.Void:
  1434. kind = getkind(v.concretetype)
  1435. ops.append(SpaceOperation('-live-', [], None))
  1436. ops.append(SpaceOperation('%s_guard_value' % kind,
  1437. [v], None))
  1438. return ops
  1439. def rewrite_op_jit_marker(self, op):
  1440. key = op.args[0].value
  1441. jitdriver = op.args[1].value
  1442. if not jitdriver.active:
  1443. return []
  1444. return getattr(self, 'handle_jit_marker__%s' % key)(op, jitdriver)
  1445. def rewrite_op_jit_conditional_call(self, op):
  1446. have_floats = False
  1447. for arg in op.args:
  1448. if getkind(arg.concretetype) == 'float':
  1449. have_floats = True
  1450. break
  1451. if len(op.args) > 4 + 2 or have_floats:
  1452. raise Exception("Conditional call does not support floats or more than 4 arguments")
  1453. callop = SpaceOperation('direct_call', op.args[1:], op.result)
  1454. calldescr = self.callcontrol.getcalldescr(callop)
  1455. assert not calldescr.get_extra_info().check_forces_virtual_or_virtualizable()
  1456. op1 = self.rewrite_call(op, 'conditional_call',
  1457. op.args[:2], args=op.args[2:],
  1458. calldescr=calldescr)
  1459. if self.callcontrol.calldescr_canraise(calldescr):
  1460. op1 = [op1, SpaceOperation('-live-', [], None)]
  1461. return op1
  1462. def handle_jit_marker__jit_merge_point(self, op, jitdriver):
  1463. assert self.portal_jd is not None, (
  1464. "'jit_merge_point' in non-portal graph!")
  1465. assert jitdriver is self.portal_jd.jitdriver, (
  1466. "general mix-up of jitdrivers?")
  1467. ops = self.promote_greens(op.args[2:], jitdriver)
  1468. num_green_args = len(jitdriver.greens)
  1469. redlists = self.make_three_lists(op.args[2+num_green_args:])
  1470. for redlist in redlists:
  1471. for v in redlist:
  1472. assert isinstance(v, Variable), (
  1473. "Constant specified red in jit_merge_point()")
  1474. assert len(dict.fromkeys(redlist)) == len(list(redlist)), (
  1475. "duplicate red variable on jit_merge_point()")
  1476. args = ([Constant(self.portal_jd.index, lltype.Signed)] +
  1477. self.make_three_lists(op.args[2:2+num_green_args]) +
  1478. redlists)
  1479. op1 = SpaceOperation('jit_merge_point', args, None)
  1480. op2 = SpaceOperation('-live-', [], None)
  1481. # ^^^ we need a -live- for the case of do_recursive_call()
  1482. op3 = SpaceOperation('-live-', [], None)
  1483. # and one for inlined short preambles
  1484. return ops + [op3, op1, op2]
  1485. def handle_jit_marker__loop_header(self, op, jitdriver):
  1486. jd = self.callcontrol.jitdriver_sd_from_jitdriver(jitdriver)
  1487. assert jd is not None
  1488. c_index = Constant(jd.index, lltype.Signed)
  1489. return SpaceOperation('loop_header', [c_index], None)
  1490. # a 'can_enter_jit' in the source graph becomes a 'loop_header'
  1491. # operation in the transformed graph, as its only purpose in
  1492. # the transformed graph is to detect loops.
  1493. handle_jit_marker__can_enter_jit = handle_jit_marker__loop_header
  1494. def rewrite_op_debug_assert(self, op):
  1495. log.WARNING("found debug_assert in %r; should have be removed" %
  1496. (self.graph,))
  1497. return []
  1498. def _handle_jit_call(self, op, oopspec_name, args):
  1499. if oopspec_name == 'jit.debug':
  1500. return SpaceOperation('jit_debug', args, None)
  1501. elif oopspec_name == 'jit.assert_green':
  1502. kind = getkind(args[0].concretetype)
  1503. return SpaceOperation('%s_assert_green' % kind, args, None)
  1504. elif oopspec_name == 'jit.current_trace_length':
  1505. return SpaceOperation('current_trace_length', [], op.result)
  1506. elif oopspec_name == 'jit.isconstant':
  1507. kind = getkind(args[0].concretetype)
  1508. return SpaceOperation('%s_isconstant' % kind, args, op.result)
  1509. elif oopspec_name == 'jit.isvirtual':
  1510. kind = getkind(args[0].concretetype)
  1511. return SpaceOperation('%s_isvirtual' % kind, args, op.result)
  1512. elif oopspec_name == 'jit.force_virtual':
  1513. return self._handle_oopspec_call(op, args,
  1514. EffectInfo.OS_JIT_FORCE_VIRTUAL,
  1515. EffectInfo.EF_FORCES_VIRTUAL_OR_VIRTUALIZABLE)
  1516. elif oopspec_name == 'jit.not_in_trace':
  1517. # ignore 'args' and use the original 'op.args'
  1518. if op.result.concretetype is not lltype.Void:
  1519. raise Exception(
  1520. "%r: jit.not_in_trace() function must return None"
  1521. % (op.args[0],))
  1522. return self._handle_oopspec_call(op, op.args[1:],
  1523. EffectInfo.OS_NOT_IN_TRACE)
  1524. else:
  1525. raise AssertionError("missing support for %r" % oopspec_name)
  1526. # ----------
  1527. # Lists.
  1528. def _handle_list_call(self, op, oopspec_name, args):
  1529. """Try to transform the call to a list-handling helper.
  1530. If no transformation is available, raise NotSupported
  1531. (in which case the original call is written as a residual call).
  1532. """
  1533. if oopspec_name.startswith('new'):
  1534. LIST = deref(op.result.concretetype)
  1535. else:
  1536. LIST = deref(args[0].concretetype)
  1537. resizable = isinstance(LIST, lltype.GcStruct)
  1538. assert resizable == (not isinstance(LIST, lltype.GcArray))
  1539. if resizable:
  1540. prefix = 'do_resizable_'
  1541. ARRAY = LIST.items.TO
  1542. if self._array_of_voids(ARRAY):
  1543. prefix += 'void_'
  1544. descrs = ()
  1545. else:
  1546. descrs = (self.cpu.arraydescrof(ARRAY),
  1547. self.cpu.fielddescrof(LIST, 'length'),
  1548. self.cpu.fielddescrof(LIST, 'items'),
  1549. self.cpu.sizeof(LIST, None))
  1550. else:
  1551. prefix = 'do_fixed_'
  1552. if self._array_of_voids(LIST):
  1553. prefix += 'void_'
  1554. descrs = ()
  1555. else:
  1556. arraydescr = self.cpu.arraydescrof(LIST)
  1557. descrs = (arraydescr,)
  1558. #
  1559. try:
  1560. meth = getattr(self, prefix + oopspec_name.replace('.', '_'))
  1561. except AttributeError:
  1562. raise NotSupported(prefix + oopspec_name)
  1563. return meth(op, args, *descrs)
  1564. def _get_list_nonneg_canraise_flags(self, op):
  1565. # XXX as far as I can see, this function will always return True
  1566. # because functions that are neither nonneg nor fast don't have an
  1567. # oopspec any more
  1568. # xxx break of abstraction:
  1569. func = op.args[0].value._obj._callable
  1570. # base hints on the name of the ll function, which is a bit xxx-ish
  1571. # but which is safe for now
  1572. assert func.func_name.startswith('ll_')
  1573. # check that we have carefully placed the oopspec in
  1574. # pypy/rpython/rlist.py. There should not be an oopspec on
  1575. # a ll_getitem or ll_setitem that expects a 'func' argument.
  1576. # The idea is that a ll_getitem/ll_setitem with dum_checkidx
  1577. # should get inlined by the JIT, so that we see the potential
  1578. # 'raise IndexError'.
  1579. assert 'func' not in func.func_code.co_varnames
  1580. non_negative = '_nonneg' in func.func_name
  1581. fast = '_fast' in func.func_name
  1582. return non_negative or fast
  1583. def _prepare_list_getset(self, op, descr, args, checkname):
  1584. non_negative = self._get_list_nonneg_canraise_flags(op)
  1585. if non_negative:
  1586. return args[1], []
  1587. else:
  1588. v_posindex = Variable('posindex')
  1589. v_posindex.concretetype = lltype.Signed
  1590. op0 = SpaceOperation('-live-', [], None)
  1591. op1 = SpaceOperation(checkname, [args[0], args[1],
  1592. descr], v_posindex)
  1593. return v_posindex, [op0, op1]
  1594. def _prepare_void_list_getset(self, op):
  1595. # sanity check:
  1596. self._get_list_nonneg_canraise_flags(op)
  1597. def _get_initial_newlist_length(self, op, args):
  1598. assert len(args) <= 1
  1599. if len(args) == 1:
  1600. v_length = args[0]
  1601. assert v_length.concretetype is lltype.Signed
  1602. return v_length
  1603. else:
  1604. return Constant(0, lltype.Signed) # length: default to 0
  1605. # ---------- fixed lists ----------
  1606. def do_fixed_newlist(self, op, args, arraydescr):
  1607. # corresponds to rtyper.lltypesystem.rlist.newlist:
  1608. # the items may be uninitialized.
  1609. v_length = self._get_initial_newlist_length(op, args)
  1610. ARRAY = op.result.concretetype.TO
  1611. if ((isinstance(ARRAY.OF, lltype.Ptr) and ARRAY.OF._needsgc()) or
  1612. isinstance(ARRAY.OF, lltype.Struct)):
  1613. opname = 'new_array_clear'
  1614. else:
  1615. opname = 'new_array'
  1616. return SpaceOperation(opname, [v_length, arraydescr], op.result)
  1617. def do_fixed_newlist_clear(self, op, args, arraydescr):
  1618. # corresponds to rtyper.rlist.ll_alloc_and_clear:
  1619. # needs to clear the items.
  1620. v_length = self._get_initial_newlist_length(op, args)
  1621. return SpaceOperation('new_array_clear', [v_length, arraydescr],
  1622. op.result)
  1623. def do_fixed_list_len(self, op, args, arraydescr):
  1624. if args[0] in self.vable_array_vars: # virtualizable array
  1625. vars = self.vable_array_vars[args[0]]
  1626. (v_base, arrayfielddescr, arraydescr) = vars
  1627. return [SpaceOperation('-live-', [], None),
  1628. SpaceOperation('arraylen_vable',
  1629. [v_base, arrayfielddescr, arraydescr],
  1630. op.result)]
  1631. return SpaceOperation('arraylen_gc', [args[0], arraydescr], op.result)
  1632. do_fixed_list_len_foldable = do_fixed_list_len
  1633. def do_fixed_list_getitem(self, op, args, arraydescr, pure=False):
  1634. if args[0] in self.vable_array_vars: # virtualizable array
  1635. vars = self.vable_array_vars[args[0]]
  1636. (v_base, arrayfielddescr, arraydescr) = vars
  1637. kind = getkind(op.result.concretetype)
  1638. return [SpaceOperation('-live-', [], None),
  1639. SpaceOperation('getarrayitem_vable_%s' % kind[0],
  1640. [v_base, args[1], arrayfielddescr,
  1641. arraydescr], op.result)]
  1642. v_index, extraop = self._prepare_list_getset(op, arraydescr, args,
  1643. 'check_neg_index')
  1644. extra = getkind(op.result.concretetype)[0]
  1645. if pure:
  1646. extra += '_pure'
  1647. op = SpaceOperation('getarrayitem_gc_%s' % extra,
  1648. [args[0], v_index, arraydescr], op.result)
  1649. return extraop + [op]
  1650. def do_fixed_list_getitem_foldable(self, op, args, arraydescr):
  1651. return self.do_fixed_list_getitem(op, args, arraydescr, pure=True)
  1652. def do_fixed_list_setitem(self, op, args, arraydescr):
  1653. if args[0] in self.vable_array_vars: # virtualizable array
  1654. vars = self.vable_array_vars[args[0]]
  1655. (v_base, arrayfielddescr, arraydescr) = vars
  1656. kind = getkind(args[2].concretetype)
  1657. return [SpaceOperation('-live-', [], None),
  1658. SpaceOperation('setarrayitem_vable_%s' % kind[0],
  1659. [v_base, args[1], args[2],
  1660. arrayfielddescr, arraydescr], None)]
  1661. v_index, extraop = self._prepare_list_getset(op, arraydescr, args,
  1662. 'check_neg_index')
  1663. kind = getkind(args[2].concretetype)[0]
  1664. op = SpaceOperation('setarrayitem_gc_%s' % kind,
  1665. [args[0], v_index, args[2], arraydescr], None)
  1666. return extraop + [op]
  1667. def do_fixed_list_ll_arraycopy(self, op, args, arraydescr):
  1668. return self._handle_oopspec_call(op, args, EffectInfo.OS_ARRAYCOPY)
  1669. def do_fixed_void_list_getitem(self, op, args):
  1670. self._prepare_void_list_getset(op)
  1671. return []
  1672. do_fixed_void_list_getitem_foldable = do_fixed_void_list_getitem
  1673. do_fixed_void_list_setitem = do_fixed_void_list_getitem
  1674. # ---------- resizable lists ----------
  1675. def do_resizable_newlist(self, op, args, arraydescr, lengthdescr,
  1676. itemsdescr, structdescr):
  1677. v_length = self._get_initial_newlist_length(op, args)
  1678. return SpaceOperation('newlist',
  1679. [v_length, structdescr, lengthdescr, itemsdescr,
  1680. arraydescr],
  1681. op.result)
  1682. def do_resizable_newlist_clear(self, op, args, arraydescr, lengthdescr,
  1683. itemsdescr, structdescr):
  1684. v_length = self._get_initial_newlist_length(op, args)
  1685. return SpaceOperation('newlist_clear',
  1686. [v_length, structdescr, lengthdescr, itemsdescr,
  1687. arraydescr],
  1688. op.result)
  1689. def do_resizable_newlist_hint(self, op, args, arraydescr, lengthdescr,
  1690. itemsdescr, structdescr):
  1691. v_hint = self._get_initial_newlist_length(op, args)
  1692. return SpaceOperation('newlist_hint',
  1693. [v_hint, structdescr, lengthdescr, itemsdescr,
  1694. arraydescr],
  1695. op.result)
  1696. def do_resizable_list_getitem(self, op, args, arraydescr, lengthdescr,
  1697. itemsdescr, structdescr):
  1698. v_index, extraop = self._prepare_list_getset(op, lengthdescr, args,
  1699. 'check_resizable_neg_index')
  1700. kind = getkind(op.result.concretetype)[0]
  1701. op = SpaceOperation('getlistitem_gc_%s' % kind,
  1702. [args[0], v_index, itemsdescr, arraydescr],
  1703. op.result)
  1704. return extraop + [op]
  1705. def do_resizable_list_setitem(self, op, args, arraydescr, lengthdescr,
  1706. itemsdescr, structdescr):
  1707. v_index, extraop = self._prepare_list_getset(op, lengthdescr, args,
  1708. 'check_resizable_neg_index')
  1709. kind = getkind(args[2].concretetype)[0]
  1710. op = SpaceOperation('setlistitem_gc_%s' % kind,
  1711. [args[0], v_index, args[2],
  1712. itemsdescr, arraydescr], None)
  1713. return extraop + [op]
  1714. def do_resizable_list_len(self, op, args, arraydescr, lengthdescr,
  1715. itemsdescr, structdescr):
  1716. return SpaceOperation('getfield_gc_i',
  1717. [args[0], lengthdescr], op.result)
  1718. def do_resizable_void_list_getitem(self, op, args):
  1719. self._prepare_void_list_getset(op)
  1720. return []
  1721. do_resizable_void_list_getitem_foldable = do_resizable_void_list_getitem
  1722. do_resizable_void_list_setitem = do_resizable_void_list_getitem
  1723. # ----------
  1724. # Strings and Unicodes.
  1725. def _handle_oopspec_call(self, op, args, oopspecindex, extraeffect=None,
  1726. extradescr=None):
  1727. calldescr = self.callcontrol.getcalldescr(op, oopspecindex,
  1728. extraeffect,
  1729. extradescr=extradescr)
  1730. if extraeffect is not None:
  1731. assert (is_test_calldescr(calldescr) # for tests
  1732. or calldescr.get_extra_info().extraeffect == extraeffect)
  1733. if isinstance(op.args[0].value, str):
  1734. pass # for tests only
  1735. else:
  1736. func = heaptracker.adr2int(
  1737. llmemory.cast_ptr_to_adr(op.args[0].value))
  1738. self.callcontrol.callinfocollection.add(oopspecindex,
  1739. calldescr, func)
  1740. op1 = self.rewrite_call(op, 'residual_call',
  1741. [op.args[0]],
  1742. args=args, calldescr=calldescr)
  1743. if self.callcontrol.calldescr_canraise(calldescr):
  1744. op1 = [op1, SpaceOperation('-live-', [], None)]
  1745. return op1
  1746. def _register_extra_helper(self, oopspecindex, oopspec_name,
  1747. argtypes, resulttype, effectinfo):
  1748. # a bit hackish
  1749. if self.callcontrol.callinfocollection.has_oopspec(oopspecindex):
  1750. return
  1751. c_func, TP = support.builtin_func_for_spec(self.cpu.rtyper,
  1752. oopspec_name, argtypes,
  1753. resulttype)
  1754. op = SpaceOperation('pseudo_call_cannot_raise',
  1755. [c_func] + [varoftype(T) for T in argtypes],
  1756. varoftype(resulttype))
  1757. calldescr = self.callcontrol.getcalldescr(op, oopspecindex,
  1758. effectinfo)
  1759. if isinstance(c_func.value, str): # in tests only
  1760. func = c_func.value
  1761. else:
  1762. func = heaptracker.adr2int(
  1763. llmemory.cast_ptr_to_adr(c_func.value))
  1764. self.callcontrol.callinfocollection.add(oopspecindex, calldescr, func)
  1765. def _handle_int_special(self, op, oopspec_name, args):
  1766. if oopspec_name == 'int.neg_ovf':
  1767. [v_x] = args
  1768. op0 = SpaceOperation('int_sub_ovf',
  1769. [Constant(0, lltype.Signed), v_x],
  1770. op.result)
  1771. return self.rewrite_operation(op0)
  1772. else:
  1773. # int.py_div, int.udiv, int.py_mod, int.umod
  1774. opname = oopspec_name.replace('.', '_')
  1775. os = getattr(EffectInfo, 'OS_' + opname.upper())
  1776. return self._handle_oopspec_call(op, args, os,
  1777. EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
  1778. def _handle_stroruni_call(self, op, oopspec_name, args):
  1779. SoU = args[0].concretetype # Ptr(STR) or Ptr(UNICODE)
  1780. can_raise_memoryerror = {
  1781. "stroruni.concat": True,
  1782. "stroruni.slice": True,
  1783. "stroruni.equal": False,
  1784. "stroruni.cmp": False,
  1785. "stroruni.copy_string_to_raw": False,
  1786. }
  1787. if SoU.TO == rstr.STR:
  1788. dict = {"stroruni.concat": EffectInfo.OS_STR_CONCAT,
  1789. "stroruni.slice": EffectInfo.OS_STR_SLICE,
  1790. "stroruni.equal": EffectInfo.OS_STR_EQUAL,
  1791. "stroruni.cmp": EffectInfo.OS_STR_CMP,
  1792. "stroruni.copy_string_to_raw": EffectInfo.OS_STR_COPY_TO_RAW,
  1793. }
  1794. CHR = lltype.Char
  1795. elif SoU.TO == rstr.UNICODE:
  1796. dict = {"stroruni.concat": EffectInfo.OS_UNI_CONCAT,
  1797. "stroruni.slice": EffectInfo.OS_UNI_SLICE,
  1798. "stroruni.equal": EffectInfo.OS_UNI_EQUAL,
  1799. "stroruni.cmp": EffectInfo.OS_UNI_CMP,
  1800. "stroruni.copy_string_to_raw": EffectInfo.OS_UNI_COPY_TO_RAW
  1801. }
  1802. CHR = lltype.UniChar
  1803. elif SoU.TO == rbytearray.BYTEARRAY:
  1804. raise NotSupported("bytearray operation")
  1805. else:
  1806. assert 0, "args[0].concretetype must be STR or UNICODE"
  1807. #
  1808. if oopspec_name == 'stroruni.copy_contents':
  1809. if SoU.TO == rstr.STR:
  1810. new_op = 'copystrcontent'
  1811. elif SoU.TO == rstr.UNICODE:
  1812. new_op = 'copyunicodecontent'
  1813. else:
  1814. assert 0
  1815. return SpaceOperation(new_op, args, op.result)
  1816. if oopspec_name == "stroruni.equal":
  1817. for otherindex, othername, argtypes, resulttype in [
  1818. (EffectInfo.OS_STREQ_SLICE_CHECKNULL,
  1819. "str.eq_slice_checknull",
  1820. [SoU, lltype.Signed, lltype.Signed, SoU],
  1821. lltype.Signed),
  1822. (EffectInfo.OS_STREQ_SLICE_NONNULL,
  1823. "str.eq_slice_nonnull",
  1824. [SoU, lltype.Signed, lltype.Signed, SoU],
  1825. lltype.Signed),
  1826. (EffectInfo.OS_STREQ_SLICE_CHAR,
  1827. "str.eq_slice_char",
  1828. [SoU, lltype.Signed, lltype.Signed, CHR],
  1829. lltype.Signed),
  1830. (EffectInfo.OS_STREQ_NONNULL,
  1831. "str.eq_nonnull",
  1832. [SoU, SoU],
  1833. lltype.Signed),
  1834. (EffectInfo.OS_STREQ_NONNULL_CHAR,
  1835. "str.eq_nonnull_char",
  1836. [SoU, CHR],
  1837. lltype.Signed),
  1838. (EffectInfo.OS_STREQ_CHECKNULL_CHAR,
  1839. "str.eq_checknull_char",
  1840. [SoU, CHR],
  1841. lltype.Signed),
  1842. (EffectInfo.OS_STREQ_LENGTHOK,
  1843. "str.eq_lengthok",
  1844. [SoU, SoU],
  1845. lltype.Signed),
  1846. ]:
  1847. if args[0].concretetype.TO == rstr.UNICODE:
  1848. otherindex += EffectInfo._OS_offset_uni
  1849. self._register_extra_helper(otherindex, othername,
  1850. argtypes, resulttype,
  1851. EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
  1852. #
  1853. if can_raise_memoryerror[oopspec_name]:
  1854. extra = EffectInfo.EF_ELIDABLE_OR_MEMORYERROR
  1855. else:
  1856. extra = EffectInfo.EF_ELIDABLE_CANNOT_RAISE
  1857. return self._handle_oopspec_call(op, args, dict[oopspec_name], extra)
  1858. def _handle_str2unicode_call(self, op, oopspec_name, args):
  1859. # ll_str2unicode can raise UnicodeDecodeError
  1860. return self._handle_oopspec_call(op, args, EffectInfo.OS_STR2UNICODE,
  1861. EffectInfo.EF_ELIDABLE_CAN_RAISE)
  1862. # ----------
  1863. # VirtualRefs.
  1864. def _handle_virtual_ref_call(self, op, oopspec_name, args):
  1865. return SpaceOperation(oopspec_name, list(args), op.result)
  1866. # -----------
  1867. # rlib.libffi
  1868. def _handle_libffi_call(self, op, oopspec_name, args):
  1869. if oopspec_name == 'libffi_call':
  1870. oopspecindex = EffectInfo.OS_LIBFFI_CALL
  1871. extraeffect = EffectInfo.EF_RANDOM_EFFECTS
  1872. self.callcontrol.has_libffi_call = True
  1873. else:
  1874. assert False, 'unsupported oopspec: %s' % oopspec_name
  1875. return self._handle_oopspec_call(op, args, oopspecindex, extraeffect)
  1876. def rewrite_op_jit_force_virtual(self, op):
  1877. op0 = SpaceOperation('-live-', [], None)
  1878. op1 = self._do_builtin_call(op)
  1879. if isinstance(op1, list):
  1880. return [op0] + op1
  1881. else:
  1882. return [op0, op1]
  1883. def rewrite_op_jit_is_virtual(self, op):
  1884. raise Exception("'vref.virtual' should not be used from jit-visible code")
  1885. def rewrite_op_jit_force_virtualizable(self, op):
  1886. # this one is for virtualizables
  1887. vinfo = self.get_vinfo(op.args[0])
  1888. assert vinfo is not None, (
  1889. "%r is a class with _virtualizable_, but no jitdriver was found"
  1890. " with a 'virtualizable' argument naming a variable of that class"
  1891. % op.args[0].concretetype)
  1892. self.vable_flags[op.args[0]] = op.args[2].value
  1893. return []
  1894. def rewrite_op_jit_enter_portal_frame(self, op):
  1895. return [op]
  1896. def rewrite_op_jit_leave_portal_frame(self, op):
  1897. return [op]
  1898. # ---------
  1899. # ll_math.sqrt_nonneg()
  1900. def _handle_math_sqrt_call(self, op, oopspec_name, args):
  1901. return self._handle_oopspec_call(op, args, EffectInfo.OS_MATH_SQRT,
  1902. EffectInfo.EF_ELIDABLE_CANNOT_RAISE)
  1903. def _handle_dict_lookup_call(self, op, oopspec_name, args):
  1904. extradescr1 = self.cpu.fielddescrof(op.args[1].concretetype.TO,
  1905. 'entries')
  1906. extradescr2 = self.cpu.arraydescrof(op.args[1].concretetype.TO.entries.TO)
  1907. return self._handle_oopspec_call(op, args, EffectInfo.OS_DICT_LOOKUP,
  1908. extradescr=[extradescr1, extradescr2])
  1909. def _handle_rgc_call(self, op, oopspec_name, args):
  1910. if oopspec_name == 'rgc.ll_shrink_array':
  1911. return self._handle_oopspec_call(op, args, EffectInfo.OS_SHRINK_ARRAY, EffectInfo.EF_CAN_RAISE)
  1912. else:
  1913. raise NotImplementedError(oopspec_name)
  1914. def _handle_rvmprof_call(self, op, oopspec_name, args):
  1915. if oopspec_name != 'rvmprof.jitted':
  1916. raise NotImplementedError(oopspec_name)
  1917. c_entering = Constant(0, lltype.Signed)
  1918. c_leaving = Constant(1, lltype.Signed)
  1919. v_uniqueid = args[0]
  1920. op1 = SpaceOperation('rvmprof_code', [c_entering, v_uniqueid], None)
  1921. op2 = SpaceOperation('rvmprof_code', [c_leaving, v_uniqueid], None)
  1922. #
  1923. # fish fish inside the oopspec's graph for the ll_func pointer
  1924. block = op.args[0].value._obj.graph.startblock
  1925. while True:
  1926. assert len(block.exits) == 1
  1927. nextblock = block.exits[0].target
  1928. if nextblock.operations == ():
  1929. break
  1930. block = nextblock
  1931. last_op = block.operations[-1]
  1932. assert last_op.opname == 'direct_call'
  1933. c_ll_func = last_op.args[0]
  1934. #
  1935. args = [c_ll_func] + op.args[2:]
  1936. ops = self.rewrite_op_direct_call(SpaceOperation('direct_call',
  1937. args, op.result))
  1938. return [op1] + ops + [op2]
  1939. def rewrite_op_ll_read_timestamp(self, op):
  1940. op1 = self.prepare_builtin_call(op, "ll_read_timestamp", [])
  1941. return self.handle_residual_call(op1,
  1942. oopspecindex=EffectInfo.OS_MATH_READ_TIMESTAMP,
  1943. extraeffect=EffectInfo.EF_CANNOT_RAISE)
  1944. def rewrite_op_jit_force_quasi_immutable(self, op):
  1945. v_inst, c_fieldname = op.args
  1946. descr1 = self.cpu.fielddescrof(v_inst.concretetype.TO,
  1947. c_fieldname.value)
  1948. op0 = SpaceOperation('-live-', [], None)
  1949. op1 = SpaceOperation('jit_force_quasi_immutable', [v_inst, descr1],
  1950. None)
  1951. return [op0, op1]
  1952. def rewrite_op_threadlocalref_get(self, op):
  1953. c_offset, = op.args
  1954. op1 = self.prepare_builtin_call(op, 'threadlocalref_get', [c_offset])
  1955. if c_offset.value.loop_invariant:
  1956. effect = EffectInfo.EF_LOOPINVARIANT
  1957. else:
  1958. effect = EffectInfo.EF_CANNOT_RAISE
  1959. return self.handle_residual_call(op1,
  1960. oopspecindex=EffectInfo.OS_THREADLOCALREF_GET,
  1961. extraeffect=effect)
  1962. # ____________________________________________________________
  1963. class NotSupported(Exception):
  1964. pass
  1965. class VirtualizableArrayField(Exception):
  1966. def __str__(self):
  1967. return "using virtualizable array in illegal way in %r" % (
  1968. self.args[0],)
  1969. def is_test_calldescr(calldescr):
  1970. return type(calldescr) is str or getattr(calldescr, '_for_tests_only', False)
  1971. def _with_prefix(prefix):
  1972. result = {}
  1973. for name in dir(Transformer):
  1974. if name.startswith(prefix):
  1975. result[name[len(prefix):]] = getattr(Transformer, name)
  1976. return result
  1977. def keep_operation_unchanged(jtransform, op):
  1978. return op
  1979. def _add_default_ops(rewrite_ops):
  1980. # All operations present in the BlackholeInterpreter as bhimpl_xxx
  1981. # but not explicitly listed in this file are supposed to be just
  1982. # passed in unmodified. All other operations are forbidden.
  1983. for key, value in BlackholeInterpreter.__dict__.items():
  1984. if key.startswith('bhimpl_'):
  1985. opname = key[len('bhimpl_'):]
  1986. rewrite_ops.setdefault(opname, keep_operation_unchanged)
  1987. rewrite_ops.setdefault('-live-', keep_operation_unchanged)
  1988. _rewrite_ops = _with_prefix('rewrite_op_')
  1989. _add_default_ops(_rewrite_ops)