Debian Codegraph @

rpython/jit/metainterp/test/support.py

raw symbols SCIP
1 import py, sys, math
2 from rpython.rtyper.lltypesystem import lltype, llmemory
3 from rpython.jit.backend.llgraph import runner
4 from rpython.jit.metainterp.warmspot import ll_meta_interp, get_stats
5 from rpython.jit.metainterp.warmspot import reset_stats
6 from rpython.jit.metainterp.warmstate import unspecialize_value
7 from rpython.jit.metainterp.optimizeopt import ALL_OPTS_DICT
8 from rpython.jit.metainterp import pyjitpl, history, jitexc
9 from rpython.jit.codewriter.policy import JitPolicy
10 from rpython.jit.codewriter import codewriter, longlong
11 from rpython.jit.backend.llsupport.vector_ext import VectorExt
12 from rpython.rlib.jit import ENABLE_ALL_OPTS
13 from rpython.translator.backendopt.all import backend_optimizations
14
15
16 def _get_jitcodes(testself, CPUClass, func, values,
17 supports_floats=True,
18 supports_longlong=False,
19 supports_singlefloats=False,
20 translationoptions={},
21 backendopt_inline_threshold=0, **kwds):
22 from rpython.jit.codewriter import support
23
24 class FakeJitCell(object):
25 __product_token = None
26 def get_procedure_token(self):
27 return self.__product_token
28 def set_procedure_token(self, token):
29 self.__product_token = token
30
31 class FakeWarmRunnerState(object):
32 def attach_procedure_to_interp(self, greenkey, procedure_token):
33 assert greenkey == []
34 self._cell.set_procedure_token(procedure_token)
35
36 def helper_func(self, FUNCPTR, func):
37 from rpython.rtyper.annlowlevel import llhelper
38 return llhelper(FUNCPTR, func)
39
40 def get_unique_id(self, *args):
41 return 0
42
43 def get_location_str(self, args):
44 return 'location'
45
46 class JitCell:
47 @staticmethod
48 def get_jit_cell_at_key(greenkey):
49 assert greenkey == []
50 return FakeWarmRunnerState._cell
51 _cell = FakeJitCell()
52
53 trace_limit = sys.maxint
54 enable_opts = ALL_OPTS_DICT
55 pureop_historylength = 16
56 vec = True
57
58 if kwds.pop('disable_optimizations', False):
59 FakeWarmRunnerState.enable_opts = {}
60
61 func._jit_unroll_safe_ = True
62 rtyper = support.annotate(func, values, inline=backendopt_inline_threshold,
63 translationoptions=translationoptions)
64 graphs = rtyper.annotator.translator.graphs
65 testself.all_graphs = graphs
66 result_kind = history.getkind(graphs[0].getreturnvar().concretetype)[0]
67
68
69 class FakeJitDriver:
70 name = 'fakejitdriver'
71
72 class FakeJitDriverSD:
73 num_green_args = 0
74 portal_graph = graphs[0]
75 virtualizable_info = None
76 greenfield_info = None
77 result_type = result_kind
78 portal_runner_ptr = "???"
79 vec = False
80 jitdriver = FakeJitDriver()
81
82 stats = history.Stats(None)
83 cpu = CPUClass(rtyper, stats, None, False)
84 cw = codewriter.CodeWriter(cpu, [FakeJitDriverSD()])
85 cw.debug = True
86 testself.cw = cw
87 if supports_floats and not cpu.supports_floats:
88 py.test.skip("this test requires supports_floats=True")
89 if supports_longlong and not cpu.supports_longlong:
90 py.test.skip("this test requires supports_longlong=True")
91 if supports_singlefloats and not cpu.supports_singlefloats:
92 py.test.skip("this test requires supports_singlefloats=True")
93 policy = JitPolicy()
94 policy.set_supports_floats(supports_floats)
95 policy.set_supports_longlong(supports_longlong)
96 policy.set_supports_singlefloats(supports_singlefloats)
97 graphs = cw.find_all_graphs(policy)
98 if kwds.get("backendopt"):
99 backend_optimizations(rtyper.annotator.translator, graphs=graphs)
100 #
101 testself.warmrunnerstate = FakeWarmRunnerState()
102 testself.warmrunnerstate.cpu = cpu
103 FakeJitDriverSD.warmstate = testself.warmrunnerstate
104 if hasattr(testself, 'finish_setup_for_interp_operations'):
105 testself.finish_setup_for_interp_operations()
106 #
107 cw.make_jitcodes(verbose=True)
108 return stats
109
110 def _run_with_blackhole(testself, args):
111 from rpython.jit.metainterp.blackhole import BlackholeInterpBuilder
112 cw = testself.cw
113 blackholeinterpbuilder = BlackholeInterpBuilder(cw)
114 blackholeinterp = blackholeinterpbuilder.acquire_interp()
115 [jitdriver_sd] = cw.callcontrol.jitdrivers_sd
116 blackholeinterp.setposition(jitdriver_sd.mainjitcode, 0)
117 count_i = count_r = count_f = 0
118 for value in args:
119 T = lltype.typeOf(value)
120 if T == lltype.Signed:
121 blackholeinterp.setarg_i(count_i, value)
122 count_i += 1
123 elif T == llmemory.GCREF:
124 blackholeinterp.setarg_r(count_r, value)
125 count_r += 1
126 elif T == lltype.Float:
127 value = longlong.getfloatstorage(value)
128 blackholeinterp.setarg_f(count_f, value)
129 count_f += 1
130 else:
131 raise TypeError(T)
132 blackholeinterp.run()
133 return blackholeinterp._final_result_anytype()
134
135 def _run_with_pyjitpl(testself, args, stats):
136 cw = testself.cw
137 opt = history.Options(listops=True)
138 metainterp_sd = pyjitpl.MetaInterpStaticData(cw.cpu, opt)
139 stats.metainterp_sd = metainterp_sd
140 metainterp_sd.finish_setup(cw)
141 metainterp_sd.finish_setup_descrs()
142
143 [jitdriver_sd] = metainterp_sd.jitdrivers_sd
144 metainterp = pyjitpl.MetaInterp(metainterp_sd, jitdriver_sd)
145 testself.metainterp = metainterp
146 try:
147 metainterp.compile_and_run_once(jitdriver_sd, *args)
148 except (jitexc.DoneWithThisFrameInt,
149 jitexc.DoneWithThisFrameRef,
150 jitexc.DoneWithThisFrameFloat) as e:
151 return e.result
152 else:
153 raise Exception("FAILED")
154
155 def _run_with_machine_code(testself, args):
156 metainterp = testself.metainterp
157 num_green_args = metainterp.jitdriver_sd.num_green_args
158 procedure_token = metainterp.get_procedure_token(args[:num_green_args])
159 # a loop was successfully created by _run_with_pyjitpl(); call it
160 cpu = metainterp.cpu
161 args1 = []
162 for i in range(len(args) - num_green_args):
163 x = args[num_green_args + i]
164 args1.append(unspecialize_value(x))
165 deadframe = cpu.execute_token(procedure_token, *args1)
166 faildescr = cpu.get_latest_descr(deadframe)
167 assert faildescr.__class__.__name__.startswith('DoneWithThisFrameDescr')
168 if metainterp.jitdriver_sd.result_type == history.INT:
169 return deadframe, cpu.get_int_value(deadframe, 0)
170 elif metainterp.jitdriver_sd.result_type == history.REF:
171 return deadframe, cpu.get_ref_value(deadframe, 0)
172 elif metainterp.jitdriver_sd.result_type == history.FLOAT:
173 return deadframe, cpu.get_float_value(deadframe, 0)
174 else:
175 return deadframe, None
176
177
178 class JitMixin:
179 basic = True
180 enable_opts = ENABLE_ALL_OPTS
181
182
183 # Basic terminology: the JIT produces "loops" and "bridges".
184 # Bridges are always attached to failing guards. Every loop is
185 # the "trunk" of a tree of compiled code, which is formed by first
186 # compiling a loop and then incrementally adding some number of
187 # bridges to it. Each loop and each bridge ends with either a
188 # FINISH or a JUMP instruction (the name "loop" is not really
189 # adapted any more). The JUMP instruction jumps to any LABEL
190 # pseudo-instruction, which can be anywhere, within the same tree
191 # or another one.
192
193 def check_resops(self, expected=None, **check):
194 """Check the instructions in all loops and bridges, ignoring
195 the ones that end in FINISH. Either pass a dictionary (then
196 the check must match exactly), or some keyword arguments (then
197 the check is only about the instructions named)."""
198 if self.enable_opts == ENABLE_ALL_OPTS:
199 get_stats().check_resops(expected=expected, **check)
200
201 def check_simple_loop(self, expected=None, **check):
202 """Useful in the simplest case when we have only one loop
203 ending with a jump back to itself and possibly a few bridges.
204 Only the operations within the loop formed by that single jump
205 will be counted; the bridges are all ignored. If several loops
206 were compiled, complains."""
207 if self.enable_opts == ENABLE_ALL_OPTS:
208 get_stats().check_simple_loop(expected=expected, **check)
209
210 def check_trace_count(self, count): # was check_loop_count
211 """Check the number of loops and bridges compiled."""
212 if self.enable_opts == ENABLE_ALL_OPTS:
213 assert get_stats().compiled_count == count
214
215 def check_trace_count_at_most(self, count):
216 """Check the number of loops and bridges compiled."""
217 if self.enable_opts == ENABLE_ALL_OPTS:
218 assert get_stats().compiled_count <= count
219
220 def check_jitcell_token_count(self, count): # was check_tree_loop_count
221 """This should check the number of independent trees of code.
222 (xxx it is not 100% clear that the count is correct)"""
223 if self.enable_opts == ENABLE_ALL_OPTS:
224 assert len(get_stats().jitcell_token_wrefs) == count
225
226 def check_target_token_count(self, count):
227 """(xxx unknown)"""
228 if self.enable_opts == ENABLE_ALL_OPTS:
229 tokens = get_stats().get_all_jitcell_tokens()
230 n = sum([len(t.target_tokens) for t in tokens])
231 assert n == count
232
233 def check_enter_count(self, count):
234 """Check the number of times pyjitpl ran. (Every time, it
235 should have produced either one loop or one bridge, or aborted;
236 but it is not 100% clear that this is still correct in the
237 presence of unrolling.)"""
238 if self.enable_opts == ENABLE_ALL_OPTS:
239 assert get_stats().enter_count == count
240
241 def check_enter_count_at_most(self, count):
242 """Check the number of times pyjitpl ran."""
243 if self.enable_opts == ENABLE_ALL_OPTS:
244 assert get_stats().enter_count <= count
245
246 def check_aborted_count(self, count):
247 """Check the number of times pyjitpl was aborted."""
248 if self.enable_opts == ENABLE_ALL_OPTS:
249 assert get_stats().aborted_count == count
250
251 def check_aborted_count_at_least(self, count):
252 """Check the number of times pyjitpl was aborted."""
253 if self.enable_opts == ENABLE_ALL_OPTS:
254 assert get_stats().aborted_count >= count
255
256 def meta_interp(self, *args, **kwds):
257 kwds['CPUClass'] = self.CPUClass
258 if "backendopt" not in kwds:
259 kwds["backendopt"] = False
260 if "enable_opts" not in kwds and hasattr(self, 'enable_opts'):
261 kwds['enable_opts'] = self.enable_opts
262 old = codewriter.CodeWriter.debug
263 try:
264 codewriter.CodeWriter.debug = True
265 return ll_meta_interp(*args, **kwds)
266 finally:
267 codewriter.CodeWriter.debug = old
268
269 def interp_operations(self, f, args, **kwds):
270 # get the JitCodes for the function f
271 stats = _get_jitcodes(self, self.CPUClass, f, args, **kwds)
272 # try to run it with blackhole.py
273 result1 = _run_with_blackhole(self, args)
274 # try to run it with pyjitpl.py
275 result2 = _run_with_pyjitpl(self, args, stats)
276 assert result1 == result2 or math.isnan(result1) and math.isnan(result2)
277 # try to run it by running the code compiled just before
278 df, result3 = _run_with_machine_code(self, args)
279 self._lastframe = df
280 assert result1 == result3 or result3 == NotImplemented or math.isnan(result1) and math.isnan(result3)
281 #
282 if (longlong.supports_longlong and
283 isinstance(result1, longlong.r_float_storage)):
284 result1 = longlong.getrealfloat(result1)
285 return result1
286
287 def check_history(self, expected=None, **isns):
288 # this can be used after calling meta_interp
289 get_stats().check_history(expected, **isns)
290
291 def check_operations_history(self, expected=None, **isns):
292 # this can be used after interp_operations
293 if expected is not None:
294 expected = dict(expected)
295 expected['finish'] = 1
296 self.metainterp.staticdata.stats.check_history(expected, **isns)
297
298
299 class LLJitMixin(JitMixin):
300 CPUClass = runner.LLGraphCPU
301
302 def supports_vector_ext(self):
303 return True
304
305 @staticmethod
306 def Ptr(T):
307 return lltype.Ptr(T)
308
309 @staticmethod
310 def GcStruct(name, *fields, **kwds):
311 S = lltype.GcStruct(name, *fields, **kwds)
312 return S
313
314 malloc = staticmethod(lltype.malloc)
315 nullptr = staticmethod(lltype.nullptr)
316
317 @staticmethod
318 def malloc_immortal(T):
319 return lltype.malloc(T, immortal=True)
320
321 def _get_NODE(self):
322 NODE = lltype.GcForwardReference()
323 NODE.become(lltype.GcStruct('NODE', ('value', lltype.Signed),
324 ('next', lltype.Ptr(NODE))))
325 return NODE
326 # ____________________________________________________________
327
328 class _Foo:
329 pass
330
331 def noConst(x):
332 """Helper function for tests, returning 'x' as a BoxInt/BoxPtr
333 even if it is a ConstInt/ConstPtr."""
334 from rpython.rlib import jit
335 return jit.hint(x, force_no_const=True)