Debian Codegraph @

rpython/jit/backend/test/runner_test.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import py
4 import sys
5 import random
6 import os
7 import struct
8 import operator
9 import math
10 from rpython.jit.metainterp.history import (
11 AbstractFailDescr, AbstractDescr, BasicFailDescr, BasicFinalDescr,
12 JitCellToken, TargetToken, ConstInt, ConstPtr, ConstFloat, Const)
13 from rpython.jit.metainterp.resoperation import (
14 ResOperation, rop, InputArgInt, InputArgFloat, InputArgRef)
15 from rpython.jit.metainterp.executor import wrap_constant
16 from rpython.jit.metainterp.support import ptr2int, int_signext
17 from rpython.jit.codewriter.effectinfo import EffectInfo
18 from rpython.jit.tool.oparser import parse
19 from rpython.rtyper.lltypesystem import lltype, llmemory, rstr, rffi
20 from rpython.rtyper import rclass
21 from rpython.rtyper.annlowlevel import llhelper
22 from rpython.rtyper.llinterp import LLException
23 from rpython.jit.codewriter import longlong
24 from rpython.rlib import longlong2float
25 from rpython.rlib.rarithmetic import intmask, is_valid_int
26 from rpython.jit.backend.detect_cpu import autodetect
27 from rpython.jit.backend.llsupport import jitframe
28 from rpython.jit.backend.llsupport.llmodel import AbstractLLCPU
29 from rpython.jit.backend.llsupport.llmodel import MissingLatestDescrError
30 from rpython.jit.backend.llsupport.rewrite import GcRewriterAssembler
31
32
33 IS_32_BIT = sys.maxint < 2**32
34 IS_64_BIT = sys.maxint > 2**32
35
36 boxfloat = InputArgFloat.fromfloat
37 constfloat = ConstFloat.fromfloat
38
39 def clone(op):
40 if op.type == 'i':
41 return InputArgInt(op.getint())
42 elif op.type == 'r':
43 return InputArgRef(op.getref_base())
44 return InputArgFloat(op.getfloatstorage())
45
46 def boxlonglong(ll):
47 if longlong.is_64_bit:
48 return InputArgInt(ll)
49 else:
50 return InputArgFloat(ll)
51
52 STUFF = lltype.GcStruct('STUFF')
53 random_gcref = lltype.cast_opaque_ptr(llmemory.GCREF,
54 lltype.malloc(STUFF, immortal=True))
55
56
57 class Runner(object):
58
59 add_loop_instructions = ['overload for a specific cpu']
60 bridge_loop_instructions = ['overload for a specific cpu']
61
62
63 def execute_operation(self, opname, valueboxes, result_type, descr=None):
64 inputargs, operations = self._get_single_operation_list(opname,
65 result_type,
66 valueboxes,
67 descr)
68 return self.execute_operations(inputargs, operations, result_type)
69
70 def _prepare_reuse(self, inputargs, operations):
71 # clean Lifetime instances for repeatedly passing them to the backend
72 for arg in inputargs:
73 arg.set_forwarded(None)
74 for op in operations:
75 op.set_forwarded(None)
76
77 def execute_operations(self, inputargs, operations, result_type):
78 self._prepare_reuse(inputargs, operations)
79 looptoken = JitCellToken()
80 self.cpu.compile_loop(inputargs, operations, looptoken)
81 args = []
82 for box in inputargs:
83 if box.type == 'i':
84 args.append(box.getint())
85 elif box.type == 'r':
86 args.append(box.getref_base())
87 elif box.type == 'f':
88 args.append(box.getfloatstorage())
89 else:
90 raise NotImplementedError(box)
91 deadframe = self.cpu.execute_token(looptoken, *args)
92 if self.cpu.get_latest_descr(deadframe) is operations[-1].getdescr():
93 self.guard_failed = False
94 else:
95 self.guard_failed = True
96 if result_type == 'int':
97 return self.cpu.get_int_value(deadframe, 0)
98 elif result_type == 'ref':
99 return self.cpu.get_ref_value(deadframe, 0)
100 elif result_type == 'float':
101 return self.cpu.get_float_value(deadframe, 0)
102 elif result_type == 'void':
103 return None
104 else:
105 assert False
106
107 def _get_operation_list(self, operations, result_type):
108 inputargs = []
109 blacklist = set()
110 for op in operations:
111 for arg in op.getarglist():
112 if not isinstance(arg, Const) and arg not in inputargs and \
113 arg not in blacklist:
114 inputargs.append(arg)
115 if op.type != 'v':
116 blacklist.add(op)
117 if result_type == 'void':
118 op1 = ResOperation(rop.FINISH, [], descr=BasicFinalDescr(0))
119 else:
120 op1 = ResOperation(rop.FINISH, [operations[-1]], descr=BasicFinalDescr(0))
121 operations.append(op1)
122 return inputargs, operations
123
124 def _get_single_operation_list(self, opnum, result_type, valueboxes,
125 descr):
126 op0 = ResOperation(opnum, valueboxes)
127 if result_type == 'void':
128 op1 = ResOperation(rop.FINISH, [], descr=BasicFinalDescr(0))
129 else:
130 op1 = ResOperation(rop.FINISH, [op0], descr=BasicFinalDescr(0))
131 operations = [op0, op1]
132 if operations[0].is_guard():
133 operations[0].setfailargs([])
134 if not descr:
135 descr = BasicFailDescr(1)
136 if descr is not None:
137 operations[0].setdescr(descr)
138 inputargs = []
139 for box in valueboxes:
140 if not isinstance(box, Const) and box not in inputargs:
141 inputargs.append(box)
142 return inputargs, operations
143
144 class BaseBackendTest(Runner):
145
146 avoid_instances = False
147
148 def setup_method(self, _):
149 self.cpu = self.get_cpu()
150 self.cpu.done_with_this_frame_descr_int = None
151 self.cpu.done_with_this_frame_descr_ref = None
152 self.cpu.done_with_this_frame_descr_float = None
153 self.cpu.done_with_this_frame_descr_void = None
154
155 def test_compile_linear_loop(self):
156 loop = parse("""
157 [i0]
158 i1 = int_add(i0, 1)
159 finish(i1, descr=faildescr)
160 """, namespace={"faildescr": BasicFinalDescr(1)})
161 looptoken = JitCellToken()
162 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
163 deadframe = self.cpu.execute_token(looptoken, 2)
164 fail = self.cpu.get_latest_descr(deadframe)
165 res = self.cpu.get_int_value(deadframe, 0)
166 assert res == 3
167 assert fail.identifier == 1
168
169 def test_compile_linear_float_loop(self):
170 if not self.cpu.supports_floats:
171 py.test.skip("requires floats")
172 loop = parse("""
173 [f0]
174 f1 = float_add(f0, 2.3)
175 finish(f1, descr=fdescr)
176 """, namespace={'fdescr': BasicFinalDescr(1)})
177 looptoken = JitCellToken()
178 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
179 deadframe = self.cpu.execute_token(looptoken,
180 longlong.getfloatstorage(2.8))
181 fail = self.cpu.get_latest_descr(deadframe)
182 res = self.cpu.get_float_value(deadframe, 0)
183 assert longlong.getrealfloat(res) == 5.1
184 fail = self.cpu.get_latest_descr(deadframe)
185 assert fail.identifier == 1
186
187 def test_compile_loop(self):
188 looptoken = JitCellToken()
189 targettoken = TargetToken()
190 loop = parse("""
191 [i0]
192 label(i0, descr=targettoken)
193 i1 = int_add(i0, 1)
194 i2 = int_le(i1, 9)
195 guard_true(i2, descr=fdescr) [i1]
196 jump(i1, descr=targettoken)
197 """, namespace={'targettoken': targettoken,
198 'fdescr': BasicFailDescr(2)})
199 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
200 deadframe = self.cpu.execute_token(looptoken, 10)
201 fail = self.cpu.get_latest_descr(deadframe)
202 assert fail.identifier == 2
203 deadframe = self.cpu.execute_token(looptoken, 2)
204 fail = self.cpu.get_latest_descr(deadframe)
205 assert fail.identifier == 2
206 res = self.cpu.get_int_value(deadframe, 0)
207 assert res == 10
208
209 def test_compile_with_holes_in_fail_args(self):
210 targettoken = TargetToken()
211 loop = parse("""
212 [i3]
213 i0 = int_sub(i3, 42)
214 label(i0, descr=targettoken)
215 i1 = int_add(i0, 1)
216 i2 = int_le(i1, 9)
217 guard_true(i2, descr=fdescr) []
218 jump(i1, descr=targettoken)
219 """, namespace={'targettoken': targettoken,
220 'fdescr': BasicFailDescr(2)})
221 looptoken = JitCellToken()
222 loop.operations[4].setfailargs([None, None, loop.operations[2], None])
223
224 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
225 deadframe = self.cpu.execute_token(looptoken, 44)
226 fail = self.cpu.get_latest_descr(deadframe)
227 assert fail.identifier == 2
228 res = self.cpu.get_int_value(deadframe, 2)
229 assert res == 10
230
231 def test_backends_dont_keep_loops_alive(self):
232 import weakref, gc
233 self.cpu.dont_keepalive_stuff = True
234 targettoken = TargetToken()
235 loop = parse("""
236 [i0]
237 label(i0, descr=targettoken)
238 i1 = int_add(i0, 1)
239 i2 = int_le(i1, 9)
240 guard_true(i2, descr=fdescr) [i1]
241 jump(i1, descr=targettoken)
242 """, namespace={'targettoken': targettoken, 'fdescr': BasicFailDescr()})
243 looptoken = JitCellToken()
244 wr_i1 = weakref.ref(loop.operations[1])
245 wr_guard = weakref.ref(loop.operations[3])
246 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
247 if hasattr(looptoken, '_x86_ops_offset'):
248 del looptoken._x86_ops_offset # else it's kept alive
249 if hasattr(looptoken, '_ppc_ops_offset'):
250 del looptoken._ppc_ops_offset # else it's kept alive
251 if hasattr(looptoken, '_zarch_ops_offset'):
252 del looptoken._zarch_ops_offset # else it's kept alive
253 del loop
254 gc.collect()
255 assert not wr_i1() and not wr_guard()
256
257 def test_compile_bridge(self):
258 self.cpu.tracker.total_compiled_loops = 0
259 self.cpu.tracker.total_compiled_bridges = 0
260 targettoken = TargetToken()
261 faildescr1 = BasicFailDescr(1)
262 faildescr2 = BasicFailDescr(2)
263 loop = parse("""
264 [i0]
265 label(i0, descr=targettoken)
266 i1 = int_add(i0, 1)
267 i2 = int_le(i1, 9)
268 guard_true(i2, descr=faildescr1) [i1]
269 jump(i1, descr=targettoken)
270 """, namespace={'targettoken': targettoken,
271 'faildescr1': faildescr1})
272 looptoken = JitCellToken()
273 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
274
275 bridge = parse("""
276 [i1]
277 i3 = int_le(i1, 19)
278 guard_true(i3, descr=faildescr2) [i1]
279 jump(i1, descr=targettoken)
280 """, namespace={"targettoken": targettoken,
281 'faildescr2': faildescr2})
282
283 self.cpu.compile_bridge(faildescr1, bridge.inputargs,
284 bridge.operations, looptoken)
285
286 deadframe = self.cpu.execute_token(looptoken, 2)
287 fail = self.cpu.get_latest_descr(deadframe)
288 assert fail.identifier == 2
289 res = self.cpu.get_int_value(deadframe, 0)
290 assert res == 20
291
292 assert self.cpu.tracker.total_compiled_loops == 1
293 assert self.cpu.tracker.total_compiled_bridges == 1
294 return looptoken
295
296 def test_compile_bridge_with_holes(self):
297 faildescr1 = BasicFailDescr(1)
298 faildescr2 = BasicFailDescr(2)
299 looptoken = JitCellToken()
300 targettoken = TargetToken()
301 loop = parse("""
302 [i3]
303 i0 = int_sub(i3, 42)
304 label(i0, descr=targettoken)
305 i1 = int_add(i0, 1)
306 i2 = int_le(i1, 9)
307 guard_true(i2, descr=faildescr1) []
308 jump(i1, descr=targettoken)
309 """, namespace={'targettoken': targettoken,
310 'faildescr1': faildescr1})
311 loop.operations[-2].setfailargs([None, loop.operations[2], None])
312 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
313
314 bridge = parse("""
315 [i1]
316 i3 = int_le(i1, 19)
317 guard_true(i3, descr=faildescr2) [i1]
318 jump(i1, descr=targettoken)
319 """, namespace={'targettoken': targettoken,
320 'faildescr2': faildescr2})
321 self.cpu.compile_bridge(faildescr1, bridge.inputargs,
322 bridge.operations, looptoken)
323
324 deadframe = self.cpu.execute_token(looptoken, 2)
325 fail = self.cpu.get_latest_descr(deadframe)
326 assert fail.identifier == 2
327 res = self.cpu.get_int_value(deadframe, 0)
328 assert res == 20
329
330 def test_compile_big_bridge_out_of_small_loop(self):
331 faildescr1 = BasicFailDescr(1)
332 loop = parse("""
333 [i0]
334 guard_false(i0, descr=faildescr1) [i0]
335 finish(descr=finaldescr)
336 """, namespace={'faildescr1': faildescr1,
337 'finaldescr': BasicFinalDescr(2)})
338 looptoken = JitCellToken()
339 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
340
341 bridge = []
342 i0 = InputArgInt()
343 iprev = i0
344 for i in range(150):
345 iprev = ResOperation(rop.INT_ADD, [iprev, ConstInt(1)])
346 bridge.append(iprev)
347 bridge.append(ResOperation(rop.GUARD_FALSE, [i0],
348 descr=BasicFailDescr(3)))
349 bridge.append(ResOperation(rop.FINISH, [],
350 descr=BasicFinalDescr(4)))
351 bridge[-2].setfailargs(bridge[:-2])
352
353 self.cpu.compile_bridge(faildescr1, [i0], bridge, looptoken)
354
355 deadframe = self.cpu.execute_token(looptoken, 0)
356 fail = self.cpu.get_latest_descr(deadframe)
357 assert fail.identifier == 2
358 deadframe = self.cpu.execute_token(looptoken, 1)
359 fail = self.cpu.get_latest_descr(deadframe)
360 assert fail.identifier == 3
361 for i in range(150):
362 res = self.cpu.get_int_value(deadframe, i)
363 assert res == 2 + i
364
365 def test_finish(self):
366 from rpython.jit.backend.llsupport.llmodel import final_descr_rd_locs
367
368 class UntouchableFailDescr(AbstractFailDescr):
369 final_descr = True
370 rd_locs = final_descr_rd_locs
371
372 def __setattr__(self, name, value):
373 if (name == 'index' or name == '_carry_around_for_tests'
374 or name == '_TYPE' or name == '_cpu'):
375 return AbstractFailDescr.__setattr__(self, name, value)
376 py.test.fail("finish descrs should not be touched")
377 faildescr = UntouchableFailDescr() # to check that is not touched
378 looptoken = JitCellToken()
379 loop = parse("""
380 [i0]
381 finish(i0, descr=faildescr)
382 """, namespace={'faildescr': faildescr})
383 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
384 deadframe = self.cpu.execute_token(looptoken, 99)
385 fail = self.cpu.get_latest_descr(deadframe)
386 assert fail is faildescr
387 res = self.cpu.get_int_value(deadframe, 0)
388 assert res == 99
389
390 looptoken = JitCellToken()
391 operations = [
392 ResOperation(rop.FINISH, [ConstInt(42)], descr=faildescr)
393 ]
394 self.cpu.compile_loop([], operations, looptoken)
395 deadframe = self.cpu.execute_token(looptoken)
396 fail = self.cpu.get_latest_descr(deadframe)
397 assert fail is faildescr
398 res = self.cpu.get_int_value(deadframe, 0)
399 assert res == 42
400
401 looptoken = JitCellToken()
402 operations = [
403 ResOperation(rop.FINISH, [], descr=faildescr)
404 ]
405 self.cpu.compile_loop([], operations, looptoken)
406 deadframe = self.cpu.execute_token(looptoken)
407 fail = self.cpu.get_latest_descr(deadframe)
408 assert fail is faildescr
409
410 if self.cpu.supports_floats:
411 looptoken = JitCellToken()
412 f0 = InputArgFloat()
413 operations = [
414 ResOperation(rop.FINISH, [f0], descr=faildescr)
415 ]
416 self.cpu.compile_loop([f0], operations, looptoken)
417 value = longlong.getfloatstorage(-61.25)
418 deadframe = self.cpu.execute_token(looptoken, value)
419 fail = self.cpu.get_latest_descr(deadframe)
420 assert fail is faildescr
421 res = self.cpu.get_float_value(deadframe, 0)
422 assert longlong.getrealfloat(res) == -61.25
423
424 looptoken = JitCellToken()
425 operations = [
426 ResOperation(rop.FINISH, [constfloat(42.5)], descr=faildescr)
427 ]
428 self.cpu.compile_loop([], operations, looptoken)
429 deadframe = self.cpu.execute_token(looptoken)
430 fail = self.cpu.get_latest_descr(deadframe)
431 assert fail is faildescr
432 res = self.cpu.get_float_value(deadframe, 0)
433 assert longlong.getrealfloat(res) == 42.5
434
435 def test_execute_operations_in_env(self):
436 cpu = self.cpu
437 targettoken = TargetToken()
438 loop = parse("""
439 [i1, i0]
440 label(i0, i1, descr=targettoken)
441 i2 = int_add(i1, i0)
442 i3 = int_sub(i0, 1)
443 i4 = int_eq(i3, 0)
444 guard_false(i4, descr=fdescr) [i3, i2]
445 jump(i3, i2, descr=targettoken)
446 """, namespace={'targettoken': targettoken,
447 'fdescr': BasicFailDescr()})
448 looptoken = JitCellToken()
449 cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
450 deadframe = self.cpu.execute_token(looptoken, 0, 10)
451 assert self.cpu.get_int_value(deadframe, 0) == 0
452 assert self.cpu.get_int_value(deadframe, 1) == 55
453
454 def test_int_operations(self):
455 from rpython.jit.metainterp.test.test_executor import get_int_tests
456 for opnum, boxargs, retvalue in get_int_tests():
457 print(opnum)
458 res = self.execute_operation(opnum, boxargs, 'int')
459 assert res == retvalue
460
461 def test_float_operations(self):
462 from rpython.jit.metainterp.test.test_executor import get_float_tests
463 from rpython.jit.metainterp.resoperation import opname
464 for opnum, boxargs, rettype, retvalue in get_float_tests(self.cpu):
465 print(("testing", opname[opnum]))
466 res = self.execute_operation(opnum, boxargs, rettype)
467 if rettype == 'float':
468 res = longlong.getrealfloat(res)
469 assert res == retvalue
470
471 def test_ovf_operations(self, reversed=False):
472 minint = -sys.maxint-1
473 boom = 'boom'
474 for opnum, testcases in [
475 (rop.INT_ADD_OVF, [(10, -2, 8),
476 (-1, minint, boom),
477 (sys.maxint//2, sys.maxint//2+2, boom)]),
478 (rop.INT_SUB_OVF, [(-20, -23, 3),
479 (-2, sys.maxint, boom),
480 (sys.maxint//2, -(sys.maxint//2+2), boom)]),
481 (rop.INT_MUL_OVF, [(minint/2, 2, minint),
482 (-2, -(minint/2), minint),
483 (minint/2, -2, boom)]),
484 ]:
485 v1 = InputArgInt(testcases[0][0])
486 v2 = InputArgInt(testcases[0][1])
487 #
488 if not reversed:
489 op0 = ResOperation(opnum, [v1, v2])
490 op1 = ResOperation(rop.GUARD_NO_OVERFLOW, [],
491 descr=BasicFailDescr(1))
492 op2 = ResOperation(rop.FINISH, [op0], descr=BasicFinalDescr(2))
493 ops = [op0, op1, op2]
494 op1.setfailargs([])
495 else:
496 op0 = ResOperation(opnum, [v1, v2])
497 op1 = ResOperation(rop.GUARD_OVERFLOW, [],
498 descr=BasicFailDescr(1))
499 op2 = ResOperation(rop.FINISH, [], descr=BasicFinalDescr(2))
500 ops = [op0, op1, op2]
501 op1.setfailargs([op0])
502 #
503 looptoken = JitCellToken()
504 self.cpu.compile_loop([v1, v2], ops, looptoken)
505 for x, y, z in testcases:
506 deadframe = self.cpu.execute_token(looptoken, x, y)
507 fail = self.cpu.get_latest_descr(deadframe)
508 if (z == boom) ^ reversed:
509 assert fail.identifier == 1
510 else:
511 assert fail.identifier == 2
512 if z != boom:
513 assert self.cpu.get_int_value(deadframe, 0) == z
514 excvalue = self.cpu.grab_exc_value(deadframe)
515 assert not excvalue
516
517 def test_ovf_operations_reversed(self):
518 self.test_ovf_operations(reversed=True)
519
520 def test_bh_call(self):
521 cpu = self.cpu
522 #
523 def func(c):
524 return chr(ord(c) + 1)
525 FPTR = self.Ptr(self.FuncType([lltype.Char], lltype.Char))
526 func_ptr = llhelper(FPTR, func)
527 calldescr = cpu.calldescrof(FPTR.TO, (lltype.Char,), lltype.Char,
528 EffectInfo.MOST_GENERAL)
529 x = cpu.bh_call_i(self.get_funcbox(cpu, func_ptr).value,
530 [ord('A')], None, None, calldescr)
531 assert x == ord('B')
532 if cpu.supports_floats:
533 def func(f, i):
534 assert isinstance(f, float)
535 assert is_valid_int(i)
536 return f - float(i)
537 FPTR = self.Ptr(self.FuncType([lltype.Float, lltype.Signed],
538 lltype.Float))
539 func_ptr = llhelper(FPTR, func)
540 FTP = FPTR.TO
541 calldescr = cpu.calldescrof(FTP, FTP.ARGS, FTP.RESULT,
542 EffectInfo.MOST_GENERAL)
543 x = cpu.bh_call_f(self.get_funcbox(cpu, func_ptr).value,
544 [42], None, [longlong.getfloatstorage(3.5)],
545 calldescr)
546 assert longlong.getrealfloat(x) == 3.5 - 42
547
548 def test_call(self):
549 from rpython.rlib.jit_libffi import types
550
551 def func_int(a, b):
552 return a + b
553 def func_char(c, c1):
554 return chr(ord(c) + ord(c1))
555
556 functions = [
557 (func_int, lltype.Signed, types.signed, 655360, 655360),
558 (func_int, lltype.Signed, types.signed, 655360, -293999429),
559 (func_int, rffi.INT, types.sint, 655360, 655360),
560 (func_int, rffi.INT, types.sint, 655360, -293999429),
561 (func_int, rffi.SHORT, types.sint16, 1213, 1213),
562 (func_int, rffi.SHORT, types.sint16, 1213, -12020),
563 (func_char, lltype.Char, types.uchar, 12, 12),
564 ]
565
566 cpu = self.cpu
567 for func, TP, ffi_type, num, num1 in functions:
568 #
569 FPTR = self.Ptr(self.FuncType([TP, TP], TP))
570 func_ptr = llhelper(FPTR, func)
571 FUNC = FPTR.TO
572 funcbox = self.get_funcbox(cpu, func_ptr)
573 # first, try it with the "normal" calldescr
574 calldescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
575 EffectInfo.MOST_GENERAL)
576 res = self.execute_operation(rop.CALL_I,
577 [funcbox, InputArgInt(num),
578 InputArgInt(num1)],
579 'int', descr=calldescr)
580 assert res == num + num1
581 # then, try it with the dynamic calldescr
582 dyn_calldescr = cpu._calldescr_dynamic_for_tests(
583 [ffi_type, ffi_type], ffi_type)
584 res = self.execute_operation(rop.CALL_I,
585 [funcbox, InputArgInt(num),
586 InputArgInt(num1)],
587 'int', descr=dyn_calldescr)
588 assert res == num + num1
589
590 # last, try it with one constant argument
591 calldescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT, EffectInfo.MOST_GENERAL)
592 res = self.execute_operation(rop.CALL_I,
593 [funcbox, ConstInt(num),
594 InputArgInt(num1)],
595 'int', descr=calldescr)
596 assert res == num + num1
597
598 if cpu.supports_floats:
599 def func(f0, f1, f2, f3, f4, f5, f6, i0, f7, i1, f8, f9):
600 seen.append((f0, f1, f2, f3, f4, f5, f6, i0, f7, i1, f8, f9))
601 return f0 + f1 + f2 + f3 + f4 + f5 + f6 + float(i0 + i1) + f7 + f8 + f9
602 seen = []
603 F = lltype.Float
604 I = lltype.Signed
605 FUNC = self.FuncType([F] * 7 + [I] + [F] + [I] + [F]* 2, F)
606 FPTR = self.Ptr(FUNC)
607 func_ptr = llhelper(FPTR, func)
608 calldescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
609 EffectInfo.MOST_GENERAL)
610 funcbox = self.get_funcbox(cpu, func_ptr)
611 args = ([boxfloat(.0), boxfloat(.1), boxfloat(.2), boxfloat(.3),
612 boxfloat(.4), boxfloat(.5), boxfloat(.6),
613 InputArgInt(1), boxfloat(.7), InputArgInt(2), boxfloat(.8),
614 boxfloat(.9)])
615 res = self.execute_operation(rop.CALL_F,
616 [funcbox] + args,
617 'float', descr=calldescr)
618 assert seen == [(.0, .1, .2, .3, .4, .5, .6, 1, .7, 2, .8, .9)]
619 assert abs(longlong.getrealfloat(res) - 7.5) < 0.0001
620
621 def test_call_many_arguments(self):
622 # Test calling a function with a large number of arguments (more than
623 # 6, which will force passing some arguments on the stack on 64-bit)
624
625 def func(*args):
626 assert len(args) == 16
627 # Try to sum up args in a way that would probably detect a
628 # transposed argument
629 return sum(arg * (2**i) for i, arg in enumerate(args))
630
631 FUNC = self.FuncType([lltype.Signed]*16, lltype.Signed)
632 FPTR = self.Ptr(FUNC)
633 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
634 EffectInfo.MOST_GENERAL)
635 func_ptr = llhelper(FPTR, func)
636 args = range(16)
637 funcbox = self.get_funcbox(self.cpu, func_ptr)
638 res = self.execute_operation(rop.CALL_I, [funcbox] + map(InputArgInt, args), 'int', descr=calldescr)
639 assert res == func(*args)
640
641 def test_call_box_func(self):
642 def a(a1, a2):
643 return a1 + a2
644 def b(b1, b2):
645 return b1 * b2
646
647 arg1 = 40
648 arg2 = 2
649 for f in [a, b]:
650 TP = lltype.Signed
651 FPTR = self.Ptr(self.FuncType([TP, TP], TP))
652 func_ptr = llhelper(FPTR, f)
653 FUNC = FPTR.TO
654 funcconst = self.get_funcbox(self.cpu, func_ptr)
655 funcbox = InputArgInt(funcconst.getint())
656 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
657 EffectInfo.MOST_GENERAL)
658 res = self.execute_operation(rop.CALL_I,
659 [funcbox, InputArgInt(arg1),
660 InputArgInt(arg2)],
661 'int', descr=calldescr)
662 assert res == f(arg1, arg2)
663
664 def test_call_stack_alignment(self):
665 # test stack alignment issues, notably for Mac OS/X.
666 # also test the ordering of the arguments.
667
668 def func_ints(*ints):
669 s = str(ints) + '\n'
670 os.write(1, s) # don't remove -- crash if the stack is misaligned
671 return sum([(10+i)*(5+j) for i, j in enumerate(ints)])
672
673 for nb_args in range(0, 35):
674 cpu = self.cpu
675 TP = lltype.Signed
676 #
677 FPTR = self.Ptr(self.FuncType([TP] * nb_args, TP))
678 func_ptr = llhelper(FPTR, func_ints)
679 FUNC = FPTR.TO
680 calldescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
681 EffectInfo.MOST_GENERAL)
682 funcbox = self.get_funcbox(cpu, func_ptr)
683 args = [280-24*i for i in range(nb_args)]
684 res = self.execute_operation(rop.CALL_I,
685 [funcbox] + map(InputArgInt, args),
686 'int', descr=calldescr)
687 assert res == func_ints(*args)
688
689 def test_call_with_const_floats(self):
690 if not self.cpu.supports_floats:
691 py.test.skip("requires floats")
692 def func(f1, f2):
693 return f1 + f2
694
695 FUNC = self.FuncType([lltype.Float, lltype.Float], lltype.Float)
696 FPTR = self.Ptr(FUNC)
697 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
698 EffectInfo.MOST_GENERAL)
699 func_ptr = llhelper(FPTR, func)
700 funcbox = self.get_funcbox(self.cpu, func_ptr)
701 res = self.execute_operation(rop.CALL_F, [funcbox, constfloat(1.5),
702 constfloat(2.5)], 'float',
703 descr=calldescr)
704 assert longlong.getrealfloat(res) == 4.0
705
706
707 def test_field_basic(self):
708 t_box, T_box, d = self.alloc_instance(self.T)
709 fielddescr = self.cpu.fielddescrof(self.S, 'value')
710 assert not fielddescr.is_pointer_field()
711 #
712 res = self.execute_operation(rop.SETFIELD_GC, [t_box, InputArgInt(39082)],
713 'void', descr=fielddescr)
714 assert res is None
715 res = self.execute_operation(rop.GETFIELD_GC_I, [t_box],
716 'int', descr=fielddescr)
717 assert res == 39082
718 #
719 fielddescr1 = self.cpu.fielddescrof(self.S, 'chr1')
720 fielddescr2 = self.cpu.fielddescrof(self.S, 'chr2')
721 shortdescr = self.cpu.fielddescrof(self.S, 'short')
722 self.execute_operation(rop.SETFIELD_GC, [t_box, InputArgInt(250)],
723 'void', descr=fielddescr2)
724
725 self.execute_operation(rop.SETFIELD_GC, [t_box, InputArgInt(133)],
726 'void', descr=fielddescr1)
727 self.execute_operation(rop.SETFIELD_GC, [t_box, InputArgInt(1331)],
728 'void', descr=shortdescr)
729 res = self.execute_operation(rop.GETFIELD_GC_I, [t_box],
730 'int', descr=fielddescr2)
731 assert res == 250
732 res = self.execute_operation(rop.GETFIELD_GC_I, [t_box],
733 'int', descr=fielddescr1)
734 assert res == 133
735 res = self.execute_operation(rop.GETFIELD_GC_I, [t_box],
736 'int', descr=shortdescr)
737 assert res == 1331
738
739 #
740 u_box, U_box, d = self.alloc_instance(self.U)
741 fielddescr2 = self.cpu.fielddescrof(self.S, 'next')
742 assert fielddescr2.is_pointer_field()
743 res = self.execute_operation(rop.SETFIELD_GC, [t_box, u_box],
744 'void', descr=fielddescr2)
745 assert res is None
746 res = self.execute_operation(rop.GETFIELD_GC_R, [t_box],
747 'ref', descr=fielddescr2)
748 assert res == u_box.getref_base()
749 #
750 null_const = wrap_constant(self.null_instance().getref_base())
751 res = self.execute_operation(rop.SETFIELD_GC, [t_box, null_const],
752 'void', descr=fielddescr2)
753 assert res is None
754 res = self.execute_operation(rop.GETFIELD_GC_R, [t_box],
755 'ref', descr=fielddescr2)
756 assert not res
757 if self.cpu.supports_floats:
758 floatdescr = self.cpu.fielddescrof(self.S, 'float')
759 self.execute_operation(rop.SETFIELD_GC, [t_box, boxfloat(3.4)],
760 'void', descr=floatdescr)
761 res = self.execute_operation(rop.GETFIELD_GC_F, [t_box],
762 'float', descr=floatdescr)
763 assert longlong.getrealfloat(res) == 3.4
764 #
765 self.execute_operation(rop.SETFIELD_GC, [t_box, constfloat(-3.6)],
766 'void', descr=floatdescr)
767 res = self.execute_operation(rop.GETFIELD_GC_F, [t_box],
768 'float', descr=floatdescr)
769 assert longlong.getrealfloat(res) == -3.6
770
771
772 def test_passing_guards(self):
773 t_box, T_box, d = self.alloc_instance(self.T)
774 nullbox = self.null_instance()
775 all = [(rop.GUARD_TRUE, [InputArgInt(1)]),
776 (rop.GUARD_FALSE, [InputArgInt(0)]),
777 (rop.GUARD_VALUE, [InputArgInt(42), ConstInt(42)]),
778 ]
779 if not self.avoid_instances:
780 all.extend([
781 (rop.GUARD_NONNULL, [t_box]),
782 (rop.GUARD_ISNULL, [nullbox])
783 ])
784 if self.cpu.supports_floats:
785 all.append((rop.GUARD_VALUE, [boxfloat(3.5), constfloat(3.5)]))
786 for (opname, args) in all:
787 assert self.execute_operation(opname, args, 'void') == None
788 assert not self.guard_failed
789
790
791 def test_passing_guard_class(self):
792 t_box, T_box, d = self.alloc_instance(self.T)
793 #null_box = ConstPtr(lltype.cast_opaque_ptr(llmemory.GCREF, lltype.nullptr(T)))
794 self.execute_operation(rop.GUARD_CLASS, [t_box, T_box], 'void')
795 assert not self.guard_failed
796 self.execute_operation(rop.GUARD_NONNULL_CLASS, [t_box, T_box], 'void')
797 assert not self.guard_failed
798
799 def test_failing_guards(self):
800 t_box, T_box, d = self.alloc_instance(self.T)
801 nullbox = self.null_instance()
802 all = [(rop.GUARD_TRUE, [InputArgInt(0)]),
803 (rop.GUARD_FALSE, [InputArgInt(1)]),
804 (rop.GUARD_VALUE, [InputArgInt(42), ConstInt(41)]),
805 ]
806 if not self.avoid_instances:
807 all.extend([
808 (rop.GUARD_NONNULL, [nullbox]),
809 (rop.GUARD_ISNULL, [t_box])])
810 if self.cpu.supports_floats:
811 all.append((rop.GUARD_VALUE, [boxfloat(-1.0), constfloat(1.0)]))
812 for opname, args in all:
813 assert self.execute_operation(opname, args, 'void') == None
814 assert self.guard_failed
815
816 def test_failing_guard_class(self):
817 t_box, T_box, _ = self.alloc_instance(self.T)
818 u_box, U_box, _ = self.alloc_instance(self.U)
819 null_box = self.null_instance()
820 for opname, args in [(rop.GUARD_CLASS, [t_box, U_box]),
821 (rop.GUARD_CLASS, [u_box, T_box]),
822 (rop.GUARD_NONNULL_CLASS, [t_box, U_box]),
823 (rop.GUARD_NONNULL_CLASS, [u_box, T_box]),
824 (rop.GUARD_NONNULL_CLASS, [null_box, T_box]),
825 ]:
826 assert self.execute_operation(opname, args, 'void') == None
827 assert self.guard_failed
828
829 def test_ooops(self):
830 u1_box, U_box, _ = self.alloc_instance(self.U)
831 u2_box, U_box, _ = self.alloc_instance(self.U)
832 r = self.execute_operation(rop.PTR_EQ, [u1_box,
833 clone(u1_box)], 'int')
834 assert r == 1
835 r = self.execute_operation(rop.PTR_NE, [u2_box,
836 clone(u2_box)], 'int')
837 assert r == 0
838 r = self.execute_operation(rop.PTR_EQ, [u1_box, u2_box], 'int')
839 assert r == 0
840 r = self.execute_operation(rop.PTR_NE, [u2_box, u1_box], 'int')
841 assert r == 1
842 #
843 null_box = self.null_instance()
844 r = self.execute_operation(rop.PTR_EQ, [null_box,
845 clone(null_box)], 'int')
846 assert r == 1
847 r = self.execute_operation(rop.PTR_EQ, [u1_box, null_box], 'int')
848 assert r == 0
849 r = self.execute_operation(rop.PTR_EQ, [null_box, u2_box], 'int')
850 assert r == 0
851 r = self.execute_operation(rop.PTR_NE, [null_box,
852 clone(null_box)], 'int')
853 assert r == 0
854 r = self.execute_operation(rop.PTR_NE, [u2_box, null_box], 'int')
855 assert r == 1
856 r = self.execute_operation(rop.PTR_NE, [null_box, u1_box], 'int')
857 assert r == 1
858
859 # These operations are supposed to be the same as PTR_EQ/PTR_NE
860 # just checking that the operations are defined in the backend.
861 r = self.execute_operation(rop.INSTANCE_PTR_EQ, [u1_box, u2_box], 'int')
862 assert r == 0
863 r = self.execute_operation(rop.INSTANCE_PTR_NE, [u2_box, u1_box], 'int')
864 assert r == 1
865
866 def test_array_basic(self):
867 a_box, A = self.alloc_array_of(rffi.SHORT, 342)
868 arraydescr = self.cpu.arraydescrof(A)
869 assert not arraydescr.is_array_of_pointers()
870 #
871 r = self.execute_operation(rop.ARRAYLEN_GC, [a_box],
872 'int', descr=arraydescr)
873 assert r == 342
874 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(310),
875 InputArgInt(744)],
876 'void', descr=arraydescr)
877 assert r is None
878 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(310)],
879 'int', descr=arraydescr)
880 assert r == 744
881
882 a_box, A = self.alloc_array_of(lltype.Signed, 342)
883 arraydescr = self.cpu.arraydescrof(A)
884 assert not arraydescr.is_array_of_pointers()
885 #
886 r = self.execute_operation(rop.ARRAYLEN_GC, [a_box],
887 'int', descr=arraydescr)
888 assert r == 342
889 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(310),
890 InputArgInt(7441)],
891 'void', descr=arraydescr)
892 assert r is None
893 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(310)],
894 'int', descr=arraydescr)
895 assert r == 7441
896 #
897 a_box, A = self.alloc_array_of(lltype.Char, 11)
898 arraydescr = self.cpu.arraydescrof(A)
899 assert not arraydescr.is_array_of_pointers()
900 r = self.execute_operation(rop.ARRAYLEN_GC, [a_box],
901 'int', descr=arraydescr)
902 assert r == 11
903 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(4),
904 InputArgInt(150)],
905 'void', descr=arraydescr)
906 assert r is None
907 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(3),
908 InputArgInt(160)],
909 'void', descr=arraydescr)
910 assert r is None
911 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(4)],
912 'int', descr=arraydescr)
913 assert r == 150
914 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(3)],
915 'int', descr=arraydescr)
916 assert r == 160
917
918 #
919 if isinstance(A, lltype.GcArray):
920 A = lltype.Ptr(A)
921 b_box, B = self.alloc_array_of(A, 3)
922 arraydescr = self.cpu.arraydescrof(B)
923 assert arraydescr.is_array_of_pointers()
924 r = self.execute_operation(rop.ARRAYLEN_GC, [b_box],
925 'int', descr=arraydescr)
926 assert r == 3
927 r = self.execute_operation(rop.SETARRAYITEM_GC, [b_box, InputArgInt(1),
928 a_box],
929 'void', descr=arraydescr)
930 assert r is None
931 r = self.execute_operation(rop.GETARRAYITEM_GC_R, [b_box, InputArgInt(1)],
932 'ref', descr=arraydescr)
933 assert r == a_box.getvalue()
934 #
935 # Unsigned should work the same as Signed
936 a_box, A = self.alloc_array_of(lltype.Unsigned, 342)
937 arraydescr = self.cpu.arraydescrof(A)
938 assert not arraydescr.is_array_of_pointers()
939 r = self.execute_operation(rop.ARRAYLEN_GC, [a_box],
940 'int', descr=arraydescr)
941 assert r == 342
942 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(310),
943 InputArgInt(7441)],
944 'void', descr=arraydescr)
945 assert r is None
946 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(310)],
947 'int', descr=arraydescr)
948 assert r == 7441
949 #
950 # Bool should work the same as Char
951 a_box, A = self.alloc_array_of(lltype.Bool, 311)
952 arraydescr = self.cpu.arraydescrof(A)
953 assert not arraydescr.is_array_of_pointers()
954 r = self.execute_operation(rop.ARRAYLEN_GC, [a_box],
955 'int', descr=arraydescr)
956 assert r == 311
957 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(304),
958 InputArgInt(1)],
959 'void', descr=arraydescr)
960 assert r is None
961 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(303),
962 InputArgInt(0)],
963 'void', descr=arraydescr)
964 assert r is None
965 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(302),
966 InputArgInt(1)],
967 'void', descr=arraydescr)
968 assert r is None
969 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(304)],
970 'int', descr=arraydescr)
971 assert r == 1
972 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(303)],
973 'int', descr=arraydescr)
974 assert r == 0
975 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(302)],
976 'int', descr=arraydescr)
977 assert r == 1
978
979 if self.cpu.supports_floats:
980 a_box, A = self.alloc_array_of(lltype.Float, 31)
981 arraydescr = self.cpu.arraydescrof(A)
982 self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(1),
983 boxfloat(3.5)],
984 'void', descr=arraydescr)
985 self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(2),
986 constfloat(4.5)],
987 'void', descr=arraydescr)
988 r = self.execute_operation(rop.GETARRAYITEM_GC_F, [a_box, InputArgInt(1)],
989 'float', descr=arraydescr)
990 assert longlong.getrealfloat(r) == 3.5
991 r = self.execute_operation(rop.GETARRAYITEM_GC_F, [a_box, InputArgInt(2)],
992 'float', descr=arraydescr)
993 assert longlong.getrealfloat(r) == 4.5
994
995 # For platforms where sizeof(INT) != sizeof(Signed) (ie, x86-64)
996 a_box, A = self.alloc_array_of(rffi.INT, 342)
997 arraydescr = self.cpu.arraydescrof(A)
998 assert not arraydescr.is_array_of_pointers()
999 r = self.execute_operation(rop.ARRAYLEN_GC, [a_box],
1000 'int', descr=arraydescr)
1001 assert r == 342
1002 r = self.execute_operation(rop.SETARRAYITEM_GC, [a_box, InputArgInt(310),
1003 InputArgInt(7441)],
1004 'void', descr=arraydescr)
1005 assert r is None
1006 r = self.execute_operation(rop.GETARRAYITEM_GC_I, [a_box, InputArgInt(310)],
1007 'int', descr=arraydescr)
1008 assert r == 7441
1009
1010 def test_array_of_structs(self):
1011 TP = lltype.GcStruct('x')
1012 ITEM = lltype.Struct('x',
1013 ('vs', lltype.Signed),
1014 ('vu', lltype.Unsigned),
1015 ('vsc', rffi.SIGNEDCHAR),
1016 ('vuc', rffi.UCHAR),
1017 ('vss', rffi.SHORT),
1018 ('vus', rffi.USHORT),
1019 ('vsi', rffi.INT),
1020 ('vui', rffi.UINT),
1021 ('k', lltype.Float),
1022 ('p', lltype.Ptr(TP)))
1023 a_box, A = self.alloc_array_of(ITEM, 15)
1024 s_box, S, _ = self.alloc_instance(TP)
1025 vsdescr = self.cpu.interiorfielddescrof(A, 'vs')
1026 kdescr = self.cpu.interiorfielddescrof(A, 'k')
1027 pdescr = self.cpu.interiorfielddescrof(A, 'p')
1028 if self.cpu.supports_floats:
1029
1030 self.execute_operation(rop.SETINTERIORFIELD_GC, [a_box, InputArgInt(3),
1031 boxfloat(1.5)],
1032 'void', descr=kdescr)
1033 f = self.cpu.bh_getinteriorfield_gc_f(a_box.getref_base(), 3, kdescr)
1034 assert longlong.getrealfloat(f) == 1.5
1035 self.cpu.bh_setinteriorfield_gc_f(a_box.getref_base(), 3, longlong.getfloatstorage(2.5), kdescr)
1036 r = self.execute_operation(rop.GETINTERIORFIELD_GC_F, [a_box, InputArgInt(3)],
1037 'float', descr=kdescr)
1038 assert longlong.getrealfloat(r) == 2.5
1039 #
1040 NUMBER_FIELDS = [('vs', lltype.Signed),
1041 ('vu', lltype.Unsigned),
1042 ('vsc', rffi.SIGNEDCHAR),
1043 ('vuc', rffi.UCHAR),
1044 ('vss', rffi.SHORT),
1045 ('vus', rffi.USHORT),
1046 ('vsi', rffi.INT),
1047 ('vui', rffi.UINT)]
1048 for name, TYPE in NUMBER_FIELDS[::-1]:
1049 vdescr = self.cpu.interiorfielddescrof(A, name)
1050 self.execute_operation(rop.SETINTERIORFIELD_GC, [a_box, InputArgInt(3),
1051 InputArgInt(-15)],
1052 'void', descr=vdescr)
1053 for name, TYPE in NUMBER_FIELDS:
1054 vdescr = self.cpu.interiorfielddescrof(A, name)
1055 i = self.cpu.bh_getinteriorfield_gc_i(a_box.getref_base(), 3,
1056 vdescr)
1057 assert i == rffi.cast(lltype.Signed, rffi.cast(TYPE, -15))
1058 for name, TYPE in NUMBER_FIELDS[::-1]:
1059 vdescr = self.cpu.interiorfielddescrof(A, name)
1060 self.cpu.bh_setinteriorfield_gc_i(a_box.getref_base(), 3,
1061 -25, vdescr)
1062 for name, TYPE in NUMBER_FIELDS:
1063 vdescr = self.cpu.interiorfielddescrof(A, name)
1064 r = self.execute_operation(rop.GETINTERIORFIELD_GC_I,
1065 [a_box, InputArgInt(3)],
1066 'int', descr=vdescr)
1067 assert r == rffi.cast(lltype.Signed, rffi.cast(TYPE, -25))
1068 #
1069 self.execute_operation(rop.SETINTERIORFIELD_GC, [a_box, InputArgInt(4),
1070 s_box],
1071 'void', descr=pdescr)
1072 r = self.cpu.bh_getinteriorfield_gc_r(a_box.getref_base(), 4, pdescr)
1073 assert r == s_box.getref_base()
1074 self.cpu.bh_setinteriorfield_gc_r(a_box.getref_base(), 3,
1075 s_box.getref_base(), pdescr)
1076 r = self.execute_operation(rop.GETINTERIORFIELD_GC_R, [a_box, InputArgInt(3)],
1077 'ref', descr=pdescr)
1078 assert r == s_box.getref_base()
1079 #
1080 # test a corner case that used to fail on x86
1081 i4 = InputArgInt(4)
1082 self.execute_operation(rop.SETINTERIORFIELD_GC, [a_box, i4, i4],
1083 'void', descr=vsdescr)
1084 r = self.cpu.bh_getinteriorfield_gc_i(a_box.getref_base(), 4, vsdescr)
1085 assert r == 4
1086
1087 def test_array_of_structs_all_sizes(self):
1088 # x86 has special support that can be used for sizes
1089 # 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 16, 18, 20, 24, 32, 36, 40, 64, 72
1090 for length in range(1, 75):
1091 ITEM = lltype.FixedSizeArray(lltype.Char, length)
1092 a_box, A = self.alloc_array_of(ITEM, 5)
1093 a = lltype.cast_opaque_ptr(lltype.Ptr(A), a_box.getref_base())
1094 middle = length // 2
1095 a[3][middle] = chr(65 + length)
1096 fdescr = self.cpu.interiorfielddescrof(A, 'item%d' % middle)
1097 r = self.execute_operation(rop.GETINTERIORFIELD_GC_I,
1098 [a_box, InputArgInt(3)],
1099 'int', descr=fdescr)
1100 assert r == 65 + length
1101 self.execute_operation(rop.SETINTERIORFIELD_GC,
1102 [a_box, InputArgInt(2), InputArgInt(r + 1)],
1103 'void', descr=fdescr)
1104 r1 = self.cpu.bh_getinteriorfield_gc_i(a_box.getref_base(), 2,
1105 fdescr)
1106 assert r1 == r + 1
1107
1108 def test_string_basic(self):
1109 s_box = self.alloc_string("hello\xfe")
1110 r = self.execute_operation(rop.STRLEN, [s_box], 'int')
1111 assert r == 6
1112 r = self.execute_operation(rop.STRGETITEM, [s_box, InputArgInt(5)], 'int')
1113 assert r == 254
1114 r = self.execute_operation(rop.STRSETITEM, [s_box, InputArgInt(4),
1115 InputArgInt(153)], 'void')
1116 assert r is None
1117 r = self.execute_operation(rop.STRGETITEM, [s_box, InputArgInt(5)], 'int')
1118 assert r == 254
1119 r = self.execute_operation(rop.STRGETITEM, [s_box, InputArgInt(4)], 'int')
1120 assert r == 153
1121
1122 def test_copystrcontent(self):
1123 s_box = self.alloc_string("abcdef")
1124 for s_box in [s_box, wrap_constant(s_box.getref_base())]:
1125 for srcstart_box in [InputArgInt(2), ConstInt(2)]:
1126 for dststart_box in [InputArgInt(3), ConstInt(3)]:
1127 for length_box in [InputArgInt(4), ConstInt(4)]:
1128 for r_box_is_const in [False, True]:
1129 r_box = self.alloc_string("!???????!")
1130 if r_box_is_const:
1131 r_box = wrap_constant(r_box.getref_base())
1132 self.execute_operation(rop.COPYSTRCONTENT,
1133 [s_box, r_box,
1134 srcstart_box,
1135 dststart_box,
1136 length_box], 'void')
1137 assert self.look_string(r_box) == "!??cdef?!"
1138
1139 def test_copyunicodecontent(self):
1140 s_box = self.alloc_unicode(u"abcdef")
1141 for s_box in [s_box, wrap_constant(s_box.getref_base())]:
1142 for srcstart_box in [InputArgInt(2), ConstInt(2)]:
1143 for dststart_box in [InputArgInt(3), ConstInt(3)]:
1144 for length_box in [InputArgInt(4), ConstInt(4)]:
1145 for r_box_is_const in [False, True]:
1146 r_box = self.alloc_unicode(u"!???????!")
1147 if r_box_is_const:
1148 r_box = wrap_constant(r_box.getref_base())
1149 self.execute_operation(rop.COPYUNICODECONTENT,
1150 [s_box, r_box,
1151 srcstart_box,
1152 dststart_box,
1153 length_box], 'void')
1154 assert self.look_unicode(r_box) == u"!??cdef?!"
1155
1156 def test_do_unicode_basic(self):
1157 u = self.cpu.bh_newunicode(5)
1158 self.cpu.bh_unicodesetitem(u, 4, 123)
1159 r = self.cpu.bh_unicodegetitem(u, 4)
1160 assert r == 123
1161
1162 def test_unicode_basic(self):
1163 u_box = self.alloc_unicode(u"hello\u1234")
1164 r = self.execute_operation(rop.UNICODELEN, [u_box], 'int')
1165 assert r == 6
1166 r = self.execute_operation(rop.UNICODEGETITEM, [u_box, InputArgInt(5)],
1167 'int')
1168 assert r == 0x1234
1169 r = self.execute_operation(rop.UNICODESETITEM, [u_box, InputArgInt(4),
1170 InputArgInt(31313)], 'void')
1171 assert r is None
1172 r = self.execute_operation(rop.UNICODEGETITEM, [u_box, InputArgInt(5)],
1173 'int')
1174 assert r == 0x1234
1175 r = self.execute_operation(rop.UNICODEGETITEM, [u_box, InputArgInt(4)],
1176 'int')
1177 assert r == 31313
1178
1179 def test_same_as(self):
1180 r = self.execute_operation(rop.SAME_AS_I, [ConstInt(5)], 'int')
1181 assert r == 5
1182 r = self.execute_operation(rop.SAME_AS_I, [InputArgInt(5)], 'int')
1183 assert r == 5
1184 u_box = self.alloc_unicode(u"hello\u1234")
1185 r = self.execute_operation(rop.SAME_AS_R, [wrap_constant(u_box.getref_base())], 'ref')
1186 assert r == u_box.getref_base()
1187 r = self.execute_operation(rop.SAME_AS_R, [u_box], 'ref')
1188 assert r == u_box.getref_base()
1189
1190 if self.cpu.supports_floats:
1191 r = self.execute_operation(rop.SAME_AS_F, [constfloat(5.5)], 'float')
1192 assert longlong.getrealfloat(r) == 5.5
1193 r = self.execute_operation(rop.SAME_AS_F, [boxfloat(5.5)], 'float')
1194 assert longlong.getrealfloat(r) == 5.5
1195
1196 def test_virtual_ref(self):
1197 pass # VIRTUAL_REF must not reach the backend nowadays
1198
1199 def test_virtual_ref_finish(self):
1200 pass # VIRTUAL_REF_FINISH must not reach the backend nowadays
1201
1202 def test_arguments_to_execute_token(self):
1203 # this test checks that execute_token() can be called with any
1204 # variant of ints and floats as arguments
1205 if self.cpu.supports_floats:
1206 numkinds = 2
1207 else:
1208 numkinds = 1
1209 seed = random.randrange(0, 10000)
1210 print('Seed is', seed) # or choose it by changing the previous line
1211 r = random.Random()
1212 r.seed(seed)
1213 for nb_args in range(50):
1214 print('Passing %d arguments to execute_token...' % nb_args)
1215 #
1216 inputargs = []
1217 values = []
1218 for k in range(nb_args):
1219 kind = r.randrange(0, numkinds)
1220 if kind == 0:
1221 inputargs.append(InputArgInt())
1222 values.append(r.randrange(-100000, 100000))
1223 else:
1224 inputargs.append(InputArgFloat())
1225 values.append(longlong.getfloatstorage(r.random()))
1226 #
1227 looptoken = JitCellToken()
1228 guarddescr = BasicFailDescr(42)
1229 faildescr = BasicFinalDescr(43)
1230 operations = []
1231 retboxes = []
1232 retvalues = []
1233 #
1234 ks = range(nb_args)
1235 random.shuffle(ks)
1236 for k in ks:
1237 if isinstance(inputargs[k], InputArgInt):
1238 x = r.randrange(-100000, 100000)
1239 operations.append(
1240 ResOperation(rop.INT_ADD, [inputargs[k],
1241 ConstInt(x)])
1242 )
1243 y = values[k] + x
1244 else:
1245 x = r.random()
1246 operations.append(
1247 ResOperation(rop.FLOAT_ADD, [inputargs[k],
1248 constfloat(x)])
1249 )
1250 y = longlong.getrealfloat(values[k]) + x
1251 y = longlong.getfloatstorage(y)
1252 kk = r.randrange(0, len(retboxes)+1)
1253 retboxes.insert(kk, operations[-1])
1254 retvalues.insert(kk, y)
1255 #
1256 op0 = ResOperation(rop.SAME_AS_I, [ConstInt(0)])
1257 op1 = ResOperation(rop.GUARD_TRUE, [op0], descr=guarddescr)
1258 op2 = ResOperation(rop.FINISH, [], descr=faildescr)
1259 operations += [op0, op1, op2]
1260 operations[-2].setfailargs(retboxes)
1261 print(inputargs)
1262 for op in operations:
1263 print(op)
1264 self.cpu.compile_loop(inputargs, operations, looptoken)
1265 #
1266 deadframe = self.cpu.execute_token(looptoken, *values)
1267 fail = self.cpu.get_latest_descr(deadframe)
1268 assert fail.identifier == 42
1269 #
1270 for k in range(len(retvalues)):
1271 if retboxes[k].type == 'i':
1272 got = self.cpu.get_int_value(deadframe, k)
1273 else:
1274 got = self.cpu.get_float_value(deadframe, k)
1275 assert got == retvalues[k]
1276
1277 def test_jump(self):
1278 # this test generates small loops where the JUMP passes many
1279 # arguments of various types, shuffling them around.
1280 if self.cpu.supports_floats:
1281 numkinds = 3
1282 else:
1283 numkinds = 2
1284 seed = random.randrange(0, 10000)
1285 print('Seed is', seed) # or choose it by changing the previous line
1286 r = random.Random()
1287 r.seed(seed)
1288 for nb_args in range(50):
1289 print('Passing %d arguments around...' % nb_args)
1290 #
1291 inputargs = []
1292 for k in range(nb_args):
1293 kind = r.randrange(0, numkinds)
1294 if kind == 0:
1295 inputargs.append(InputArgInt())
1296 elif kind == 1:
1297 inputargs.append(InputArgRef())
1298 else:
1299 inputargs.append(InputArgFloat())
1300 jumpargs = []
1301 remixing = []
1302 for srcbox in inputargs:
1303 n = r.randrange(0, len(inputargs))
1304 otherbox = inputargs[n]
1305 if otherbox.type == srcbox.type:
1306 remixing.append((srcbox, otherbox))
1307 else:
1308 otherbox = srcbox
1309 jumpargs.append(otherbox)
1310 #
1311 index_counter = r.randrange(0, len(inputargs)+1)
1312 i0 = InputArgInt()
1313 inputargs.insert(index_counter, i0)
1314 #
1315 looptoken = JitCellToken()
1316 targettoken = TargetToken()
1317 faildescr = BasicFailDescr(15)
1318 op0 = ResOperation(rop.LABEL, inputargs, descr=targettoken)
1319 op1 = ResOperation(rop.INT_SUB, [i0, ConstInt(1)])
1320 op2 = ResOperation(rop.INT_GE, [op1, ConstInt(0)])
1321 op3 = ResOperation(rop.GUARD_TRUE, [op2])
1322 jumpargs.insert(index_counter, op1)
1323 op4 = ResOperation(rop.JUMP, jumpargs, descr=targettoken)
1324 operations = [op0, op1, op2, op3, op4]
1325 operations[3].setfailargs(inputargs[:])
1326 operations[3].setdescr(faildescr)
1327 #
1328 self.cpu.compile_loop(inputargs, operations, looptoken)
1329 #
1330 values = []
1331 S = lltype.GcStruct('S')
1332 for box in inputargs:
1333 if box.type == 'i':
1334 values.append(r.randrange(-10000, 10000))
1335 elif box.type == 'r':
1336 p = lltype.malloc(S)
1337 values.append(lltype.cast_opaque_ptr(llmemory.GCREF, p))
1338 elif box.type == 'f':
1339 values.append(longlong.getfloatstorage(r.random()))
1340 else:
1341 assert 0
1342 values[index_counter] = 11
1343 #
1344 deadframe = self.cpu.execute_token(looptoken, *values)
1345 fail = self.cpu.get_latest_descr(deadframe)
1346 assert fail.identifier == 15
1347 #
1348 dstvalues = values[:]
1349 for _ in range(11):
1350 expected = dstvalues[:]
1351 for tgtbox, srcbox in remixing:
1352 v = dstvalues[inputargs.index(srcbox)]
1353 expected[inputargs.index(tgtbox)] = v
1354 dstvalues = expected
1355 #
1356 assert dstvalues[index_counter] == 11
1357 dstvalues[index_counter] = 0
1358 for i, (box, val) in enumerate(zip(inputargs, dstvalues)):
1359 if box.type == 'i':
1360 got = self.cpu.get_int_value(deadframe, i)
1361 elif box.type == 'r':
1362 got = self.cpu.get_ref_value(deadframe, i)
1363 elif box.type == 'f':
1364 got = self.cpu.get_float_value(deadframe, i)
1365 else:
1366 assert 0
1367 assert type(got) == type(val)
1368 assert got == val
1369
1370 def test_compile_bridge_float(self):
1371 if not self.cpu.supports_floats:
1372 py.test.skip("requires floats")
1373 targettoken = TargetToken()
1374 faildescr1 = BasicFailDescr(1)
1375 faildescr2 = BasicFailDescr(2)
1376 faildescr3 = BasicFinalDescr(3)
1377 loop = parse("""
1378 [f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11]
1379 label(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, descr=targettoken)
1380 i2 = float_le(f0, 9.2)
1381 guard_true(i2, descr=faildescr1) [f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11]
1382 guard_false(i2, descr=faildescr2) [f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11]
1383 finish(descr=faildescr3)
1384 """, namespace=locals())
1385 looptoken = JitCellToken()
1386 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
1387
1388 bridge = parse("""
1389 [f0, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11]
1390 f15 = float_sub(f0, 1.0)
1391 jump(f15, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, descr=targettoken)
1392 """, namespace=locals())
1393
1394 self.cpu.compile_bridge(faildescr1, bridge.inputargs,
1395 bridge.operations, looptoken)
1396
1397 args = []
1398 for i in range(len(loop.inputargs)):
1399 x = 13.5 + 6.73 * i
1400 args.append(longlong.getfloatstorage(x))
1401 deadframe = self.cpu.execute_token(looptoken, *args)
1402 fail = self.cpu.get_latest_descr(deadframe)
1403 assert fail.identifier == 2
1404 res = self.cpu.get_float_value(deadframe, 0)
1405 assert longlong.getrealfloat(res) == 8.5
1406 for i in range(1, len(loop.inputargs)):
1407 got = longlong.getrealfloat(self.cpu.get_float_value(
1408 deadframe, i))
1409 assert got == 13.5 + 6.73 * i
1410
1411 def test_compile_bridge_spilled_float(self):
1412 if not self.cpu.supports_floats:
1413 py.test.skip("requires floats")
1414 faildescr1 = BasicFailDescr(100)
1415 faildescr2 = BasicFinalDescr(102)
1416 loopops = """
1417 [i0,f1, f2]
1418 f3 = float_add(f1, f2)
1419 force_spill(f3)
1420 force_spill(f1)
1421 force_spill(f2)
1422 guard_false(i0) [f1, f2, f3]
1423 finish()"""
1424 loop = parse(loopops)
1425 looptoken = JitCellToken()
1426 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
1427 args = [1]
1428 args.append(longlong.getfloatstorage(132.25))
1429 args.append(longlong.getfloatstorage(0.75))
1430 deadframe = self.cpu.execute_token(looptoken, *args) #xxx check
1431 fail = self.cpu.get_latest_descr(deadframe)
1432 assert loop.operations[-2].getdescr() == fail
1433 f1 = self.cpu.get_float_value(deadframe, 0)
1434 f2 = self.cpu.get_float_value(deadframe, 1)
1435 f3 = self.cpu.get_float_value(deadframe, 2)
1436 assert longlong.getrealfloat(f1) == 132.25
1437 assert longlong.getrealfloat(f2) == 0.75
1438 assert longlong.getrealfloat(f3) == 133.0
1439
1440 bridge = parse("""
1441 [f1, f2, f3]
1442 i0 = same_as_i(0)
1443 guard_true(i0, descr=faildescr1) [f1, f2, f3]
1444 finish(descr=faildescr2)
1445 """, namespace=locals())
1446 self.cpu.compile_bridge(loop.operations[-2].getdescr(),
1447 bridge.inputargs, bridge.operations,
1448 looptoken)
1449 args = [1,
1450 longlong.getfloatstorage(132.25),
1451 longlong.getfloatstorage(0.75)]
1452 deadframe = self.cpu.execute_token(looptoken, *args)
1453 fail = self.cpu.get_latest_descr(deadframe)
1454 assert fail.identifier == 100
1455 f1 = self.cpu.get_float_value(deadframe, 0)
1456 f2 = self.cpu.get_float_value(deadframe, 1)
1457 f3 = self.cpu.get_float_value(deadframe, 2)
1458 assert longlong.getrealfloat(f1) == 132.25
1459 assert longlong.getrealfloat(f2) == 0.75
1460 assert longlong.getrealfloat(f3) == 133.0
1461
1462 def test_integers_and_guards2(self, extra_op=False):
1463 for opname, compare in [
1464 (rop.INT_IS_TRUE, lambda x: bool(x)),
1465 (rop.INT_IS_ZERO, lambda x: not bool(x))]:
1466 for opguard, guard_case in [
1467 (rop.GUARD_FALSE, False),
1468 (rop.GUARD_TRUE, True),
1469 ]:
1470 box = InputArgInt()
1471 faildescr1 = BasicFailDescr(1)
1472 faildescr2 = BasicFinalDescr(2)
1473 inputargs = [box]
1474 op0 = ResOperation(opname, [box])
1475 op1 = ResOperation(opguard, [op0], descr=faildescr1)
1476 op2 = ResOperation(rop.FINISH, [], descr=faildescr2)
1477 operations = [op0, op1, op2]
1478 if extra_op:
1479 operations.insert(1, ResOperation(rop.SAME_AS_I,
1480 [ConstInt(42)]))
1481 op1.setfailargs([])
1482 looptoken = JitCellToken()
1483 self.cpu.compile_loop(inputargs, operations, looptoken)
1484 #
1485 for value in [-42, 0, 1, 10]:
1486 deadframe = self.cpu.execute_token(looptoken, value)
1487 fail = self.cpu.get_latest_descr(deadframe)
1488 #
1489 expected = compare(value)
1490 expected ^= guard_case
1491 assert fail.identifier == 2 - expected
1492
1493 def test_integers_and_guards2_x(self):
1494 self.test_integers_and_guards2(extra_op=True)
1495
1496 def test_integers_and_guards(self, extra_op=False):
1497 for opname, compare in [
1498 (rop.INT_LT, lambda x, y: x < y),
1499 (rop.INT_LE, lambda x, y: x <= y),
1500 (rop.INT_EQ, lambda x, y: x == y),
1501 (rop.INT_NE, lambda x, y: x != y),
1502 (rop.INT_GT, lambda x, y: x > y),
1503 (rop.INT_GE, lambda x, y: x >= y),
1504 ]:
1505 for opguard, guard_case in [
1506 (rop.GUARD_FALSE, False),
1507 (rop.GUARD_TRUE, True),
1508 ]:
1509 for combinaison in ["bb", "bc", "cb"]:
1510 #
1511 if combinaison[0] == 'b':
1512 ibox1 = InputArgInt()
1513 else:
1514 ibox1 = ConstInt(-42)
1515 if combinaison[1] == 'b':
1516 ibox2 = InputArgInt()
1517 else:
1518 ibox2 = ConstInt(-42)
1519 faildescr1 = BasicFailDescr(1)
1520 faildescr2 = BasicFinalDescr(2)
1521 inputargs = [ib for ib in [ibox1, ibox2]
1522 if isinstance(ib, InputArgInt)]
1523 op0 = ResOperation(opname, [ibox1, ibox2])
1524 op1 = ResOperation(opguard, [op0], descr=faildescr1)
1525 op2 = ResOperation(rop.FINISH, [], descr=faildescr2)
1526 operations = [op0, op1, op2]
1527 if extra_op:
1528 operations.insert(1, ResOperation(rop.SAME_AS_I,
1529 [ConstInt(42)]))
1530 operations[-2].setfailargs([])
1531 looptoken = JitCellToken()
1532 self.cpu.compile_loop(inputargs, operations, looptoken)
1533 #
1534 for test1 in [-65, -42, -11, 0, 1, 10]:
1535 if test1 == -42 or combinaison[0] == 'b':
1536 for test2 in [-65, -42, -11, 0, 1, 10]:
1537 if test2 == -42 or combinaison[1] == 'b':
1538 args = []
1539 if combinaison[0] == 'b':
1540 args.append(test1)
1541 if combinaison[1] == 'b':
1542 args.append(test2)
1543 deadframe = self.cpu.execute_token(
1544 looptoken, *args)
1545 fail = self.cpu.get_latest_descr(deadframe)
1546 #
1547 expected = compare(test1, test2)
1548 expected ^= guard_case
1549 assert fail.identifier == 2 - expected
1550
1551 def test_integers_and_guards_x(self):
1552 self.test_integers_and_guards(extra_op=True)
1553
1554 def test_integers_and_guards_uint(self, extra_op=False):
1555 for opname, compare in [
1556 (rop.UINT_LE, lambda x, y: (x) <= (y)),
1557 (rop.UINT_GT, lambda x, y: (x) > (y)),
1558 (rop.UINT_LT, lambda x, y: (x) < (y)),
1559 (rop.UINT_GE, lambda x, y: (x) >= (y)),
1560 ]:
1561 for opguard, guard_case in [
1562 (rop.GUARD_FALSE, False),
1563 (rop.GUARD_TRUE, True),
1564 ]:
1565 for combinaison in ["bb", "bc", "cb"]:
1566 #
1567 if combinaison[0] == 'b':
1568 ibox1 = InputArgInt()
1569 else:
1570 ibox1 = ConstInt(42)
1571 if combinaison[1] == 'b':
1572 ibox2 = InputArgInt()
1573 else:
1574 ibox2 = ConstInt(42)
1575 faildescr1 = BasicFailDescr(1)
1576 faildescr2 = BasicFinalDescr(2)
1577 inputargs = [ib for ib in [ibox1, ibox2]
1578 if isinstance(ib, InputArgInt)]
1579 op0 = ResOperation(opname, [ibox1, ibox2])
1580 op1 = ResOperation(opguard, [op0], descr=faildescr1)
1581 op2 = ResOperation(rop.FINISH, [], descr=faildescr2)
1582 operations = [op0, op1, op2]
1583 if extra_op:
1584 operations.insert(1, ResOperation(rop.SAME_AS_I,
1585 [ConstInt(42)]))
1586 operations[-2].setfailargs([])
1587 looptoken = JitCellToken()
1588 self.cpu.compile_loop(inputargs, operations, looptoken)
1589 #
1590 for test1 in [65, 42, 11, 0, 1]:
1591 if test1 == 42 or combinaison[0] == 'b':
1592 for test2 in [65, 42, 11, 0, 1]:
1593 if test2 == 42 or combinaison[1] == 'b':
1594 args = []
1595 if combinaison[0] == 'b':
1596 args.append(test1)
1597 if combinaison[1] == 'b':
1598 args.append(test2)
1599 deadframe = self.cpu.execute_token(
1600 looptoken, *args)
1601 fail = self.cpu.get_latest_descr(deadframe)
1602 #
1603 expected = compare(test1, test2)
1604 expected ^= guard_case
1605 assert fail.identifier == 2 - expected
1606
1607 def test_integers_and_guards_uint_x(self):
1608 self.test_integers_and_guards_uint(extra_op=True)
1609
1610 def test_floats_and_guards(self, extra_op=False):
1611 if not self.cpu.supports_floats:
1612 py.test.skip("requires floats")
1613 for opname, compare in [
1614 (rop.FLOAT_LT, lambda x, y: x < y),
1615 (rop.FLOAT_LE, lambda x, y: x <= y),
1616 (rop.FLOAT_EQ, lambda x, y: x == y),
1617 (rop.FLOAT_NE, lambda x, y: x != y),
1618 (rop.FLOAT_GT, lambda x, y: x > y),
1619 (rop.FLOAT_GE, lambda x, y: x >= y),
1620 ]:
1621 for opguard, guard_case in [
1622 (rop.GUARD_FALSE, False),
1623 (rop.GUARD_TRUE, True),
1624 ]:
1625 for combinaison in ["bb", "bc", "cb"]:
1626 #
1627 if combinaison[0] == 'b':
1628 fbox1 = InputArgFloat()
1629 else:
1630 fbox1 = constfloat(-4.5)
1631 if combinaison[1] == 'b':
1632 fbox2 = InputArgFloat()
1633 else:
1634 fbox2 = constfloat(-4.5)
1635 faildescr1 = BasicFailDescr(1)
1636 faildescr2 = BasicFinalDescr(2)
1637 inputargs = [fb for fb in [fbox1, fbox2]
1638 if not isinstance(fb, Const)]
1639 op0 = ResOperation(opname, [fbox1, fbox2])
1640 op1 = ResOperation(opguard, [op0], descr=faildescr1)
1641 op2 = ResOperation(rop.FINISH, [], descr=faildescr2)
1642 operations = [op0, op1, op2]
1643 if extra_op:
1644 operations.insert(1, ResOperation(rop.SAME_AS_I,
1645 [ConstInt(42)]))
1646 operations[-2].setfailargs([])
1647 looptoken = JitCellToken()
1648 self.cpu.compile_loop(inputargs, operations, looptoken)
1649 #
1650 nan = 1e200 * 1e200
1651 nan /= nan
1652 for test1 in [-6.5, -4.5, -2.5, nan]:
1653 if test1 == -4.5 or combinaison[0] == 'b':
1654 for test2 in [-6.5, -4.5, -2.5, nan]:
1655 if test2 == -4.5 or combinaison[1] == 'b':
1656 args = []
1657 if combinaison[0] == 'b':
1658 args.append(
1659 longlong.getfloatstorage(test1))
1660 if combinaison[1] == 'b':
1661 args.append(
1662 longlong.getfloatstorage(test2))
1663 deadframe = self.cpu.execute_token(
1664 looptoken, *args)
1665 fail = self.cpu.get_latest_descr(deadframe)
1666 #
1667 expected = compare(test1, test2)
1668 expected ^= guard_case
1669 assert fail.identifier == 2 - expected
1670
1671 def test_floats_and_guards_x(self):
1672 self.test_floats_and_guards(extra_op=True)
1673
1674 def test_unused_result_int(self):
1675 # test pure operations on integers whose result is not used
1676 from rpython.jit.metainterp.test.test_executor import get_int_tests
1677 int_tests = list(get_int_tests())
1678 int_tests = [(opnum, boxargs, 'int', retvalue)
1679 for opnum, boxargs, retvalue in int_tests]
1680 self._test_unused_result(int_tests)
1681
1682 def test_unused_result_float(self):
1683 # same as test_unused_result_int, for float operations
1684 from rpython.jit.metainterp.test.test_executor import get_float_tests
1685 float_tests = list(get_float_tests(self.cpu))
1686 self._test_unused_result(float_tests)
1687
1688 def _test_unused_result(self, tests):
1689 while len(tests) > 50: # only up to 50 tests at once
1690 self._test_unused_result(tests[:50])
1691 tests = tests[50:]
1692 inputargs = []
1693 operations = []
1694 for opnum, boxargs, rettype, retvalue in tests:
1695 inputargs += [box for box in boxargs if not isinstance(box, Const)]
1696 operations.append(ResOperation(opnum, boxargs))
1697 # Unique-ify inputargs
1698 inputargs = list(set(inputargs))
1699 faildescr = BasicFinalDescr(1)
1700 operations.append(ResOperation(rop.FINISH, [], descr=faildescr))
1701 looptoken = JitCellToken()
1702 #
1703 self.cpu.compile_loop(inputargs, operations, looptoken)
1704 #
1705 args = []
1706 for box in inputargs:
1707 if isinstance(box, InputArgInt):
1708 args.append(box.getint())
1709 elif isinstance(box, InputArgFloat):
1710 args.append(box.getfloatstorage())
1711 else:
1712 assert 0
1713 #
1714 deadframe = self.cpu.execute_token(looptoken, *args)
1715 fail = self.cpu.get_latest_descr(deadframe)
1716 assert fail.identifier == 1
1717
1718 def test_nan_and_infinity(self):
1719 if not self.cpu.supports_floats:
1720 py.test.skip("requires floats")
1721
1722 from rpython.rlib.rfloat import INFINITY, NAN
1723 from rpython.jit.metainterp.resoperation import opname
1724
1725 fzer = 0.0
1726 fone = 1.0
1727 fmqr = -0.25
1728 finf = INFINITY
1729 fmnf = -INFINITY
1730 fnan = NAN
1731
1732 all_cases_unary = [(a,) for a in [fzer,fone,fmqr,finf,fmnf,fnan]]
1733 all_cases_binary = [(a, b) for a in [fzer,fone,fmqr,finf,fmnf,fnan]
1734 for b in [fzer,fone,fmqr,finf,fmnf,fnan]]
1735 no_zero_divison = [(a, b) for a in [fzer,fone,fmqr,finf,fmnf,fnan]
1736 for b in [ fone,fmqr,finf,fmnf,fnan]]
1737
1738 def nan_and_infinity(opnum, realoperation, testcases):
1739 for testcase in testcases:
1740 expected = realoperation(*testcase)
1741 inputargs = [boxfloat(x) for x in testcase]
1742 if isinstance(expected, float):
1743 expectedtype = 'float'
1744 else:
1745 expectedtype = 'int'
1746 got = self.execute_operation(opnum, inputargs,
1747 expectedtype)
1748 if not isinstance(expected, bool):
1749 got = longlong.getrealfloat(got)
1750 if math.isnan(expected):
1751 ok = math.isnan(got)
1752 elif math.isinf(expected):
1753 ok = math.isinf(got)
1754 else:
1755 ok = got == expected
1756 if not ok:
1757 raise AssertionError("%s(%s): got %r, expected %r" % (
1758 opname[opnum], ', '.join(map(repr, testcase)),
1759 got, expected))
1760 # if we expect a boolean, also check the combination with
1761 # a GUARD_TRUE or GUARD_FALSE
1762 if isinstance(expected, bool):
1763 for extra_op in (False, True):
1764 for guard_opnum, expected_id in [(rop.GUARD_TRUE, 1),
1765 (rop.GUARD_FALSE, 0)]:
1766 op0 = ResOperation(opnum, inputargs)
1767 op1 = ResOperation(guard_opnum, [op0],
1768 descr=BasicFailDescr(4))
1769 op2 = ResOperation(rop.FINISH, [],
1770 descr=BasicFinalDescr(5))
1771 operations = [op0, op1, op2]
1772 if extra_op:
1773 operations.insert(1, ResOperation(rop.SAME_AS_I,
1774 [ConstInt(42)]))
1775 operations[-2].setfailargs([])
1776 looptoken = JitCellToken()
1777 # Use "set" to unique-ify inputargs
1778 unique_testcase_list = list(set(inputargs))
1779 self._prepare_reuse(unique_testcase_list, operations)
1780 self.cpu.compile_loop(unique_testcase_list, operations,
1781 looptoken)
1782 args = [box.getfloatstorage() for box in
1783 unique_testcase_list]
1784 deadframe = self.cpu.execute_token(looptoken, *args)
1785 fail = self.cpu.get_latest_descr(deadframe)
1786 if fail.identifier != 5 - (expected_id^expected):
1787 if fail.identifier == 4:
1788 msg = "was taken"
1789 else:
1790 msg = "was not taken"
1791 raise AssertionError(
1792 "%s(%s)/%s took the wrong path: "
1793 "the failure path of the guard %s" % (
1794 opname[opnum],
1795 ', '.join(map(repr, testcase)),
1796 opname[guard_opnum], msg))
1797
1798 yield nan_and_infinity, rop.FLOAT_ADD, operator.add, all_cases_binary
1799 yield nan_and_infinity, rop.FLOAT_SUB, operator.sub, all_cases_binary
1800 yield nan_and_infinity, rop.FLOAT_MUL, operator.mul, all_cases_binary
1801 yield nan_and_infinity, rop.FLOAT_TRUEDIV, \
1802 operator.truediv, no_zero_divison
1803 yield nan_and_infinity, rop.FLOAT_NEG, operator.neg, all_cases_unary
1804 yield nan_and_infinity, rop.FLOAT_ABS, abs, all_cases_unary
1805 yield nan_and_infinity, rop.FLOAT_LT, operator.lt, all_cases_binary
1806 yield nan_and_infinity, rop.FLOAT_LE, operator.le, all_cases_binary
1807 yield nan_and_infinity, rop.FLOAT_EQ, operator.eq, all_cases_binary
1808 yield nan_and_infinity, rop.FLOAT_NE, operator.ne, all_cases_binary
1809 yield nan_and_infinity, rop.FLOAT_GT, operator.gt, all_cases_binary
1810 yield nan_and_infinity, rop.FLOAT_GE, operator.ge, all_cases_binary
1811
1812 def test_noops(self):
1813 c_box = wrap_constant(self.alloc_string("hi there").getref_base())
1814 c_nest = ConstInt(0)
1815 c_id = ConstInt(0)
1816 self.execute_operation(rop.DEBUG_MERGE_POINT, [c_box, c_nest, c_id, c_nest], 'void')
1817 self.execute_operation(rop.JIT_DEBUG, [c_box, c_nest, c_nest,
1818 c_nest, c_nest], 'void')
1819
1820 def test_read_timestamp(self):
1821 if IS_32_BIT and not self.cpu.supports_longlong:
1822 py.test.skip("read_timestamp returns a longlong")
1823 if sys.platform == 'win32':
1824 # windows quite often is very inexact (like the old Intel 8259 PIC),
1825 # so we stretch the time a little bit.
1826 # On my virtual Parallels machine in a 2GHz Core i7 Mac Mini,
1827 # the test starts working at delay == 21670 and stops at 20600000.
1828 # We take the geometric mean value.
1829 from math import log, exp
1830 delay_min = 21670
1831 delay_max = 20600000
1832 delay = int(exp((log(delay_min)+log(delay_max))/2))
1833 def wait_a_bit():
1834 for i in xrange(delay): pass
1835 else:
1836 def wait_a_bit():
1837 pass
1838
1839 from rpython.jit.codewriter.effectinfo import EffectInfo
1840 from rpython.rlib import rtimer
1841
1842 effectinfo = EffectInfo([], [], [], [], [], [],
1843 EffectInfo.EF_CANNOT_RAISE,
1844 EffectInfo.OS_MATH_READ_TIMESTAMP)
1845 FPTR = self.Ptr(self.FuncType([], lltype.SignedLongLong))
1846 func_ptr = llhelper(FPTR, rtimer.read_timestamp)
1847 FUNC = FPTR.TO
1848 funcbox = self.get_funcbox(self.cpu, func_ptr)
1849
1850 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT, effectinfo)
1851 if longlong.is_64_bit:
1852 res1 = self.execute_operation(rop.CALL_I, [funcbox], 'int', calldescr)
1853 wait_a_bit()
1854 res2 = self.execute_operation(rop.CALL_I, [funcbox], 'int', calldescr)
1855 else:
1856 res1 = self.execute_operation(rop.CALL_F, [funcbox],'float',calldescr)
1857 wait_a_bit()
1858 res2 = self.execute_operation(rop.CALL_F, [funcbox],'float',calldescr)
1859 assert res1 < res2 < res1 + 2**32
1860
1861
1862 class LLtypeBackendTest(BaseBackendTest):
1863
1864 Ptr = lltype.Ptr
1865 FuncType = lltype.FuncType
1866 malloc = staticmethod(lltype.malloc)
1867 nullptr = staticmethod(lltype.nullptr)
1868
1869 @classmethod
1870 def get_funcbox(cls, cpu, func_ptr):
1871 return ConstInt(ptr2int(func_ptr))
1872
1873
1874 MY_VTABLE = rclass.OBJECT_VTABLE # for tests only
1875
1876 S = lltype.GcForwardReference()
1877 S.become(lltype.GcStruct('S', ('parent', rclass.OBJECT),
1878 ('value', lltype.Signed),
1879 ('chr1', lltype.Char),
1880 ('chr2', lltype.Char),
1881 ('short', rffi.SHORT),
1882 ('next', lltype.Ptr(S)),
1883 ('float', lltype.Float)))
1884 T = lltype.GcStruct('T', ('parent', S),
1885 ('next', lltype.Ptr(S)))
1886 U = lltype.GcStruct('U', ('parent', T),
1887 ('next', lltype.Ptr(S)))
1888
1889
1890 def alloc_instance(self, T):
1891 if hasattr(T, 'parent'):
1892 vtable_for_T = lltype.malloc(self.MY_VTABLE, immortal=True)
1893 else:
1894 vtable_for_T = lltype.nullptr(rclass.OBJECT_VTABLE)
1895 cpu = self.cpu
1896 class FakeGCCache(object):
1897 pass
1898
1899 if hasattr(cpu, 'gc_ll_descr'):
1900 if not hasattr(cpu.gc_ll_descr, '_cache_gcstruct2vtable'):
1901 cpu.gc_ll_descr._cache_gcstruct2vtable = {}
1902 cpu.gc_ll_descr._cache_gcstruct2vtable.update({T: vtable_for_T})
1903 p = T
1904 while hasattr(p, 'parent'):
1905 vtable_for_parent = lltype.malloc(self.MY_VTABLE, immortal=True)
1906 cpu.gc_ll_descr._cache_gcstruct2vtable[p.parent] = vtable_for_parent
1907 p = p.parent
1908 else:
1909 descr = cpu.sizeof(T, vtable_for_T)
1910 t = lltype.malloc(T)
1911 if T == self.T:
1912 t.parent.parent.typeptr = vtable_for_T
1913 elif T == self.U:
1914 t.parent.parent.parent.typeptr = vtable_for_T
1915 t_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, t))
1916 if not hasattr(T, 'parent'):
1917 vtable = lltype.nullptr(rclass.OBJECT_VTABLE)
1918 T_box = None
1919 else:
1920 vtable = vtable_for_T
1921 T_box = ConstInt(ptr2int(vtable_for_T))
1922 descr = cpu.sizeof(T, vtable)
1923 return t_box, T_box, descr
1924
1925 def null_instance(self):
1926 return InputArgRef(lltype.nullptr(llmemory.GCREF.TO))
1927
1928 def alloc_array_of(self, ITEM, length):
1929 A = lltype.GcArray(ITEM)
1930 a = lltype.malloc(A, length)
1931 a_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, a))
1932 return a_box, A
1933
1934 def alloc_string(self, string):
1935 s = rstr.mallocstr(len(string))
1936 for i in range(len(string)):
1937 s.chars[i] = string[i]
1938 s_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, s))
1939 return s_box
1940
1941 def look_string(self, string_box):
1942 s = string_box.getref(lltype.Ptr(rstr.STR))
1943 return ''.join(s.chars)
1944
1945 def alloc_unicode(self, unicode):
1946 u = rstr.mallocunicode(len(unicode))
1947 for i in range(len(unicode)):
1948 u.chars[i] = unicode[i]
1949 u_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, u))
1950 return u_box
1951
1952 def look_unicode(self, unicode_box):
1953 u = unicode_box.getref(lltype.Ptr(rstr.UNICODE))
1954 return u''.join(u.chars)
1955
1956
1957 def test_cast_int_to_ptr(self):
1958 res = self.execute_operation(rop.CAST_INT_TO_PTR,
1959 [InputArgInt(-17)], 'ref')
1960 assert lltype.cast_ptr_to_int(res) == -17
1961
1962 def test_cast_ptr_to_int(self):
1963 x = lltype.cast_int_to_ptr(llmemory.GCREF, -19)
1964 res = self.execute_operation(rop.CAST_PTR_TO_INT,
1965 [InputArgRef(x)], 'int')
1966 assert res == -19
1967
1968 def test_cast_int_to_float(self):
1969 if not self.cpu.supports_floats:
1970 py.test.skip("requires floats")
1971 for x in [-10, -1, 0, 3, 42, sys.maxint-1]:
1972 res = self.execute_operation(rop.CAST_INT_TO_FLOAT,
1973 [InputArgInt(x)], 'float')
1974 assert longlong.getrealfloat(res) == float(x)
1975 # --- the front-end never generates CAST_INT_TO_FLOAT(Const)
1976 #res = self.execute_operation(rop.CAST_INT_TO_FLOAT,
1977 # [ConstInt(x)], 'float').value
1978 #assert longlong.getrealfloat(res) == float(x)
1979
1980 def test_cast_float_to_int(self):
1981 if not self.cpu.supports_floats:
1982 py.test.skip("requires floats")
1983 for x in [-24.23, -5.3, 0.0, 3.1234, 11.1, 0.1]:
1984 v = longlong.getfloatstorage(x)
1985 res = self.execute_operation(rop.CAST_FLOAT_TO_INT,
1986 [InputArgFloat(v)], 'int')
1987 assert res == int(x)
1988 # --- the front-end never generates CAST_FLOAT_TO_INT(Const)
1989 #res = self.execute_operation(rop.CAST_FLOAT_TO_INT,
1990 # [ConstFloat(v)], 'int').value
1991 #assert res == int(x)
1992
1993 def test_convert_float_bytes(self):
1994 if not self.cpu.supports_floats:
1995 py.test.skip("requires floats")
1996 if IS_32_BIT and not self.cpu.supports_longlong:
1997 py.test.skip("longlong test")
1998 t = 'int' if longlong.is_64_bit else 'float'
1999 res = self.execute_operation(rop.CONVERT_FLOAT_BYTES_TO_LONGLONG,
2000 [boxfloat(2.5)], t)
2001 assert res == longlong2float.float2longlong(2.5)
2002
2003 bytes = longlong2float.float2longlong(2.5)
2004 res = self.execute_operation(rop.CONVERT_LONGLONG_BYTES_TO_FLOAT,
2005 [boxlonglong(bytes)], 'float')
2006 assert longlong.getrealfloat(res) == 2.5
2007
2008 def test_ooops_non_gc(self):
2009 x = lltype.malloc(lltype.Struct('x'), flavor='raw')
2010 v = ptr2int(x)
2011 r = self.execute_operation(rop.PTR_EQ, [InputArgInt(v), InputArgInt(v)], 'int')
2012 assert r == 1
2013 r = self.execute_operation(rop.PTR_NE, [InputArgInt(v), InputArgInt(v)], 'int')
2014 assert r == 0
2015 lltype.free(x, flavor='raw')
2016
2017 def test_new_plain_struct(self):
2018 cpu = self.cpu
2019 S = lltype.GcStruct('S', ('x', lltype.Char), ('y', lltype.Char))
2020 sizedescr = cpu.sizeof(S)
2021 r1 = self.execute_operation(rop.NEW, [], 'ref', descr=sizedescr)
2022 r2 = self.execute_operation(rop.NEW, [], 'ref', descr=sizedescr)
2023 assert r1 != r2
2024 xdescr = cpu.fielddescrof(S, 'x')
2025 ydescr = cpu.fielddescrof(S, 'y')
2026 self.execute_operation(rop.SETFIELD_GC, [InputArgRef(r1),
2027 InputArgInt(150)],
2028 'void', descr=ydescr)
2029 self.execute_operation(rop.SETFIELD_GC, [InputArgRef(r1),
2030 InputArgInt(190)],
2031 'void', descr=xdescr)
2032 s = lltype.cast_opaque_ptr(lltype.Ptr(S), r1)
2033 assert s.x == chr(190)
2034 assert s.y == chr(150)
2035
2036 def test_new_with_vtable(self):
2037 cpu = self.cpu
2038 t_box, T_box, descr = self.alloc_instance(self.T)
2039 vtable = llmemory.cast_adr_to_ptr(
2040 llmemory.cast_int_to_adr(T_box.getint()), rclass.CLASSTYPE)
2041 r1 = self.execute_operation(rop.NEW_WITH_VTABLE, [], 'ref', descr)
2042 r2 = self.execute_operation(rop.NEW_WITH_VTABLE, [], 'ref', descr)
2043 assert r1 != r2
2044 descr1 = cpu.fielddescrof(self.S, 'chr1')
2045 descr2 = cpu.fielddescrof(self.S, 'chr2')
2046 descrshort = cpu.fielddescrof(self.S, 'short')
2047 descrshort.parent_descr.vtable = vtable
2048 self.execute_operation(rop.SETFIELD_GC, [InputArgRef(r1),
2049 InputArgInt(150)],
2050 'void', descr=descr2)
2051 self.execute_operation(rop.SETFIELD_GC, [InputArgRef(r1),
2052 InputArgInt(190)],
2053 'void', descr=descr1)
2054 self.execute_operation(rop.SETFIELD_GC, [InputArgRef(r1),
2055 InputArgInt(1313)],
2056 'void', descr=descrshort)
2057 s = lltype.cast_opaque_ptr(lltype.Ptr(self.T), r1)
2058 assert s.parent.chr1 == chr(190)
2059 assert s.parent.chr2 == chr(150)
2060 r = self.cpu.bh_getfield_gc_i(r1, descrshort)
2061 assert r == 1313
2062 self.cpu.bh_setfield_gc_i(r1, 1333, descrshort)
2063 r = self.cpu.bh_getfield_gc_i(r1, descrshort)
2064 assert r == 1333
2065 r = self.execute_operation(rop.GETFIELD_GC_I, [InputArgRef(r1)], 'int',
2066 descr=descrshort)
2067 assert r == 1333
2068 t = lltype.cast_opaque_ptr(lltype.Ptr(self.T), t_box.getref_base())
2069 assert s.parent.parent.typeptr == t.parent.parent.typeptr
2070
2071 def test_new_array(self):
2072 A = lltype.GcArray(lltype.Signed)
2073 arraydescr = self.cpu.arraydescrof(A)
2074 r1 = self.execute_operation(rop.NEW_ARRAY, [InputArgInt(342)],
2075 'ref', descr=arraydescr)
2076 r2 = self.execute_operation(rop.NEW_ARRAY, [InputArgInt(342)],
2077 'ref', descr=arraydescr)
2078 assert r1 != r2
2079 a = lltype.cast_opaque_ptr(lltype.Ptr(A), r1)
2080 assert len(a) == 342
2081
2082 def test_new_array_clear(self):
2083 A = lltype.GcArray(lltype.Signed)
2084 arraydescr = self.cpu.arraydescrof(A)
2085 r1 = self.execute_operation(rop.NEW_ARRAY_CLEAR, [InputArgInt(342)],
2086 'ref', descr=arraydescr)
2087 a = lltype.cast_opaque_ptr(lltype.Ptr(A), r1)
2088 assert a[0] == 0
2089 assert len(a) == 342
2090
2091 def test_new_string(self):
2092 r1 = self.execute_operation(rop.NEWSTR, [InputArgInt(342)], 'ref')
2093 r2 = self.execute_operation(rop.NEWSTR, [InputArgInt(342)], 'ref')
2094 assert r1 != r2
2095 a = lltype.cast_opaque_ptr(lltype.Ptr(rstr.STR), r1)
2096 assert len(a.chars) == 342
2097
2098 def test_new_unicode(self):
2099 r1 = self.execute_operation(rop.NEWUNICODE, [InputArgInt(342)], 'ref')
2100 r2 = self.execute_operation(rop.NEWUNICODE, [InputArgInt(342)], 'ref')
2101 assert r1 != r2
2102 a = lltype.cast_opaque_ptr(lltype.Ptr(rstr.UNICODE), r1)
2103 assert len(a.chars) == 342
2104
2105 def test_exceptions(self):
2106 exc_tp = None
2107 exc_ptr = None
2108 def func(i):
2109 if i:
2110 raise LLException(exc_tp, exc_ptr)
2111
2112 ops = '''
2113 [i0]
2114 i1 = same_as_i(1)
2115 call_n(ConstClass(fptr), i0, descr=calldescr)
2116 p0 = guard_exception(ConstClass(xtp)) [i1]
2117 finish(p0)
2118 '''
2119 FPTR = lltype.Ptr(lltype.FuncType([lltype.Signed], lltype.Void))
2120 fptr = llhelper(FPTR, func)
2121 calldescr = self.cpu.calldescrof(FPTR.TO, FPTR.TO.ARGS, FPTR.TO.RESULT,
2122 EffectInfo.MOST_GENERAL)
2123
2124 xtp = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
2125 xtp.subclassrange_min = 1
2126 xtp.subclassrange_max = 3
2127 X = lltype.GcStruct('X', ('parent', rclass.OBJECT),
2128 hints={'vtable': xtp._obj})
2129 xptr = lltype.cast_opaque_ptr(llmemory.GCREF, lltype.malloc(X))
2130
2131
2132 exc_tp = xtp
2133 exc_ptr = xptr
2134 loop = parse(ops, self.cpu, namespace=locals())
2135 looptoken = JitCellToken()
2136 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2137 deadframe = self.cpu.execute_token(looptoken, 1)
2138 assert self.cpu.get_ref_value(deadframe, 0) == xptr
2139 excvalue = self.cpu.grab_exc_value(deadframe)
2140 assert not excvalue
2141 deadframe = self.cpu.execute_token(looptoken, 0)
2142 assert self.cpu.get_int_value(deadframe, 0) == 1
2143 excvalue = self.cpu.grab_exc_value(deadframe)
2144 assert not excvalue
2145
2146 ytp = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
2147 ytp.subclassrange_min = 2
2148 ytp.subclassrange_max = 2
2149 assert rclass.ll_issubclass(ytp, xtp)
2150 Y = lltype.GcStruct('Y', ('parent', rclass.OBJECT),
2151 hints={'vtable': ytp._obj})
2152 yptr = lltype.cast_opaque_ptr(llmemory.GCREF, lltype.malloc(Y))
2153
2154 # guard_exception uses an exact match
2155 exc_tp = ytp
2156 exc_ptr = yptr
2157 loop = parse(ops, self.cpu, namespace=locals())
2158 looptoken = JitCellToken()
2159 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2160 deadframe = self.cpu.execute_token(looptoken, 1)
2161 assert self.cpu.get_int_value(deadframe, 0) == 1
2162 excvalue = self.cpu.grab_exc_value(deadframe)
2163 assert excvalue == yptr
2164
2165 exc_tp = xtp
2166 exc_ptr = xptr
2167 ops = '''
2168 [i0]
2169 i1 = same_as_i(1)
2170 call_n(ConstClass(fptr), i0, descr=calldescr)
2171 guard_no_exception() [i1]
2172 finish(0)
2173 '''
2174 loop = parse(ops, self.cpu, namespace=locals())
2175 looptoken = JitCellToken()
2176 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2177 deadframe = self.cpu.execute_token(looptoken, 1)
2178 assert self.cpu.get_int_value(deadframe, 0) == 1
2179 excvalue = self.cpu.grab_exc_value(deadframe)
2180 assert excvalue == xptr
2181 deadframe = self.cpu.execute_token(looptoken, 0)
2182 assert self.cpu.get_int_value(deadframe, 0) == 0
2183 excvalue = self.cpu.grab_exc_value(deadframe)
2184 assert not excvalue
2185
2186 def test_save_restore_exceptions(self):
2187 exc_tp = None
2188 exc_ptr = None
2189 def func(i):
2190 if hasattr(self.cpu, '_exception_emulator'):
2191 assert not self.cpu._exception_emulator[0]
2192 assert not self.cpu._exception_emulator[1]
2193 called.append(i)
2194 if i:
2195 raise LLException(exc_tp, exc_ptr)
2196
2197 ops = '''
2198 [i0]
2199 i1 = same_as_i(1)
2200 call_n(ConstClass(fptr), i0, descr=calldescr)
2201 i2 = save_exc_class()
2202 p2 = save_exception()
2203 call_n(ConstClass(fptr), 0, descr=calldescr)
2204 restore_exception(i2, p2)
2205 p0 = guard_exception(ConstClass(xtp)) [i1]
2206 finish(p0)
2207 '''
2208 FPTR = lltype.Ptr(lltype.FuncType([lltype.Signed], lltype.Void))
2209 fptr = llhelper(FPTR, func)
2210 calldescr = self.cpu.calldescrof(FPTR.TO, FPTR.TO.ARGS, FPTR.TO.RESULT,
2211 EffectInfo.MOST_GENERAL)
2212
2213 xtp = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
2214 xtp.subclassrange_min = 1
2215 xtp.subclassrange_max = 3
2216 X = lltype.GcStruct('X', ('parent', rclass.OBJECT),
2217 hints={'vtable': xtp._obj})
2218 xx = lltype.malloc(X)
2219 xx.parent.typeptr = xtp
2220 xptr = lltype.cast_opaque_ptr(llmemory.GCREF, xx)
2221
2222 exc_tp = xtp
2223 exc_ptr = xptr
2224 loop = parse(ops, self.cpu, namespace=locals())
2225 looptoken = JitCellToken()
2226 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2227 called = []
2228 deadframe = self.cpu.execute_token(looptoken, 5)
2229 assert called == [5, 0]
2230 assert self.cpu.get_ref_value(deadframe, 0) == xptr
2231 excvalue = self.cpu.grab_exc_value(deadframe)
2232 assert not excvalue
2233 called = []
2234 deadframe = self.cpu.execute_token(looptoken, 0)
2235 assert called == [0, 0]
2236 assert self.cpu.get_int_value(deadframe, 0) == 1
2237 excvalue = self.cpu.grab_exc_value(deadframe)
2238 assert not excvalue
2239
2240 def test_cond_call_gc_wb(self):
2241 def func_void(a):
2242 record.append(rffi.cast(lltype.Signed, a))
2243 record = []
2244 #
2245 S = lltype.GcStruct('S', ('tid', lltype.Signed))
2246 FUNC = self.FuncType([lltype.Ptr(S)], lltype.Void)
2247 func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
2248 funcbox = self.get_funcbox(self.cpu, func_ptr)
2249 class WriteBarrierDescr(AbstractDescr):
2250 jit_wb_if_flag = 4096
2251 jit_wb_if_flag_byteofs = struct.pack("l", 4096).index('\x10')
2252 jit_wb_if_flag_singlebyte = 0x10
2253 def get_write_barrier_fn(self, cpu):
2254 return funcbox.getint()
2255 #
2256 for cond in [False, True]:
2257 value = random.randrange(-sys.maxint, sys.maxint)
2258 if cond:
2259 value |= 4096
2260 else:
2261 value &= ~4096
2262 s = lltype.malloc(S)
2263 s.tid = value
2264 sgcref = lltype.cast_opaque_ptr(llmemory.GCREF, s)
2265 del record[:]
2266 self.execute_operation(rop.COND_CALL_GC_WB,
2267 [InputArgRef(sgcref)],
2268 'void', descr=WriteBarrierDescr())
2269 if cond:
2270 assert record == [rffi.cast(lltype.Signed, sgcref)]
2271 else:
2272 assert record == []
2273
2274 def test_cond_call_gc_wb_array(self):
2275 def func_void(a):
2276 record.append(rffi.cast(lltype.Signed, a))
2277 record = []
2278 #
2279 S = lltype.GcStruct('S', ('tid', lltype.Signed))
2280 FUNC = self.FuncType([lltype.Ptr(S)], lltype.Void)
2281 func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
2282 funcbox = self.get_funcbox(self.cpu, func_ptr)
2283 class WriteBarrierDescr(AbstractDescr):
2284 jit_wb_if_flag = 4096
2285 jit_wb_if_flag_byteofs = struct.pack("l", 4096).index('\x10')
2286 jit_wb_if_flag_singlebyte = 0x10
2287 jit_wb_cards_set = 0 # <= without card marking
2288 def get_write_barrier_fn(self, cpu):
2289 return funcbox.getint()
2290 #
2291 for cond in [False, True]:
2292 value = random.randrange(-sys.maxint, sys.maxint)
2293 if cond:
2294 value |= 4096
2295 else:
2296 value &= ~4096
2297 s = lltype.malloc(S)
2298 s.tid = value
2299 sgcref = lltype.cast_opaque_ptr(llmemory.GCREF, s)
2300 del record[:]
2301 self.execute_operation(rop.COND_CALL_GC_WB_ARRAY,
2302 [InputArgRef(sgcref), ConstInt(123)],
2303 'void', descr=WriteBarrierDescr())
2304 if cond:
2305 assert record == [rffi.cast(lltype.Signed, sgcref)]
2306 else:
2307 assert record == []
2308
2309 def test_cond_call_gc_wb_array_card_marking_fast_path(self):
2310 def func_void(a):
2311 record.append(rffi.cast(lltype.Signed, a))
2312 if cond == 1: # the write barrier sets the flag
2313 s.data.tid |= 32768
2314 record = []
2315 #
2316 S = lltype.Struct('S', ('tid', lltype.Signed))
2317 S_WITH_CARDS = lltype.Struct('S_WITH_CARDS',
2318 ('card0', lltype.Char),
2319 ('card1', lltype.Char),
2320 ('card2', lltype.Char),
2321 ('card3', lltype.Char),
2322 ('card4', lltype.Char),
2323 ('card5', lltype.Char),
2324 ('card6', lltype.Char),
2325 ('card7', lltype.Char),
2326 ('data', S))
2327 FUNC = self.FuncType([lltype.Ptr(S)], lltype.Void)
2328 func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
2329 funcbox = self.get_funcbox(self.cpu, func_ptr)
2330 class WriteBarrierDescr(AbstractDescr):
2331 jit_wb_if_flag = 4096
2332 jit_wb_if_flag_byteofs = struct.pack("l", 4096).index('\x10')
2333 jit_wb_if_flag_singlebyte = 0x10
2334 jit_wb_cards_set = 32768
2335 jit_wb_cards_set_byteofs = struct.pack("l", 32768).index('\x80')
2336 jit_wb_cards_set_singlebyte = -0x80
2337 jit_wb_card_page_shift = 7
2338 def get_write_barrier_from_array_fn(self, cpu):
2339 return funcbox.getint()
2340 #
2341 for BoxIndexCls in [InputArgInt, ConstInt]*3:
2342 for cond in [-1, 0, 1, 2]:
2343 # cond=-1:GCFLAG_TRACK_YOUNG_PTRS, GCFLAG_CARDS_SET are not set
2344 # cond=0: GCFLAG_CARDS_SET is never set
2345 # cond=1: GCFLAG_CARDS_SET is not set, but the wb sets it
2346 # cond=2: GCFLAG_CARDS_SET is already set
2347 print()
2348 print('_'*79)
2349 print('BoxIndexCls =', BoxIndexCls)
2350 print('testing cond =', cond)
2351 print()
2352 value = random.randrange(-sys.maxint, sys.maxint)
2353 if cond >= 0:
2354 value |= 4096
2355 else:
2356 value &= ~4096
2357 if cond == 2:
2358 value |= 32768
2359 else:
2360 value &= ~32768
2361 s = lltype.malloc(S_WITH_CARDS, immortal=True, zero=True)
2362 s.data.tid = value
2363 sgcref = rffi.cast(llmemory.GCREF, s.data)
2364 del record[:]
2365 box_index = BoxIndexCls((9<<7) + 17)
2366 self.execute_operation(rop.COND_CALL_GC_WB_ARRAY,
2367 [InputArgRef(sgcref), box_index],
2368 'void', descr=WriteBarrierDescr())
2369 if cond in [0, 1]:
2370 assert record == [rffi.cast(lltype.Signed, s.data)]
2371 else:
2372 assert record == []
2373 if cond in [1, 2]:
2374 assert s.card6 == '\x02'
2375 else:
2376 assert s.card6 == '\x00'
2377 assert s.card0 == '\x00'
2378 assert s.card1 == '\x00'
2379 assert s.card2 == '\x00'
2380 assert s.card3 == '\x00'
2381 assert s.card4 == '\x00'
2382 assert s.card5 == '\x00'
2383 assert s.card7 == '\x00'
2384 if cond == 1:
2385 value |= 32768
2386 assert s.data.tid == value
2387
2388 def test_cond_call_1(self):
2389 def func_void(*args):
2390 called.append(args)
2391
2392 for i in range(5):
2393 called = []
2394
2395 FUNC = self.FuncType([lltype.Signed] * i, lltype.Void)
2396 func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
2397 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
2398 EffectInfo.MOST_GENERAL)
2399
2400 ops = '''
2401 [i0, i1, i2, i3, i4, i5, i6, f0, f1]
2402 cond_call(i1, ConstClass(func_ptr), %s)
2403 guard_false(i0, descr=faildescr) [i1, i2, i3, i4, i5, i6, f0, f1]
2404 ''' % ', '.join(['i%d' % (j + 2) for j in range(i)] + ["descr=calldescr"])
2405 loop = parse(ops, namespace={'faildescr': BasicFailDescr(),
2406 'func_ptr': func_ptr,
2407 'calldescr': calldescr})
2408 looptoken = JitCellToken()
2409 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2410 f1 = longlong.getfloatstorage(1.2)
2411 f2 = longlong.getfloatstorage(3.4)
2412 frame = self.cpu.execute_token(looptoken, 1, 0, 1, 2, 3, 4, 5, f1, f2)
2413 assert not called
2414 for j in range(6):
2415 assert self.cpu.get_int_value(frame, j) == j
2416 assert longlong.getrealfloat(self.cpu.get_float_value(frame, 6)) == 1.2
2417 assert longlong.getrealfloat(self.cpu.get_float_value(frame, 7)) == 3.4
2418 frame = self.cpu.execute_token(looptoken, 1, 1, 1, 2, 3, 4, 5, f1, f2)
2419 assert called == [tuple(range(1, i + 1))]
2420 for j in range(4):
2421 assert self.cpu.get_int_value(frame, j + 1) == j + 1
2422 assert longlong.getrealfloat(self.cpu.get_float_value(frame, 6)) == 1.2
2423 assert longlong.getrealfloat(self.cpu.get_float_value(frame, 7)) == 3.4
2424
2425 def test_cond_call_2(self):
2426 def func_void(*args):
2427 called.append(args)
2428
2429 FUNC = self.FuncType([lltype.Signed, lltype.Signed], lltype.Void)
2430 func_ptr = llhelper(lltype.Ptr(FUNC), func_void)
2431 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
2432 EffectInfo.MOST_GENERAL)
2433 gfs = longlong.getfloatstorage
2434
2435 for (operation, arg1, arg2_if_true, arg2_if_false) in [
2436 ('int_lt', -5, 2, -5),
2437 ('int_le', 5, 5, -6),
2438 ('int_eq', 11, 11, 12),
2439 ('int_ne', 11, 12, 11),
2440 ('int_gt', 8, -1, 8),
2441 ('int_xor', 7, 3, 7), # test without a comparison at all
2442 ('int_is_true', 4242, 1, 0),
2443 ('int_is_zero', 4242, 0, 1),
2444 ('float_lt', gfs(-0.5), gfs(0.2), gfs(-0.5)),
2445 ('float_eq', gfs(1.1), gfs(1.1), gfs(1.2)),
2446 ]:
2447 called = []
2448
2449 ops = '''
2450 [%s, %s, i3, i4]
2451 i2 = %s(%s)
2452 cond_call(i2, ConstClass(func_ptr), i3, i4, descr=calldescr)
2453 guard_no_exception(descr=faildescr) []
2454 finish()
2455 ''' % ("i0" if operation.startswith('int') else "f0",
2456 "i1" if operation.startswith('int') else "f1",
2457 operation,
2458 ("i1" if operation.startswith('int_is_') else
2459 "i0, i1" if operation.startswith('int') else
2460 "f0, f1"))
2461 loop = parse(ops, namespace={'func_ptr': func_ptr,
2462 'calldescr': calldescr,
2463 'faildescr': BasicFailDescr()})
2464 looptoken = JitCellToken()
2465 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2466 frame = self.cpu.execute_token(looptoken, arg1, arg2_if_false, 0, 0)
2467 assert called == []
2468 frame = self.cpu.execute_token(looptoken, arg1, arg2_if_true,
2469 67, 89)
2470 assert called == [(67, 89)]
2471
2472 def test_cond_call_value(self):
2473 def func_int(*args):
2474 called.append(args)
2475 return len(args) * 100 + 1000
2476
2477 for i in range(5):
2478 called = []
2479
2480 FUNC = self.FuncType([lltype.Signed] * i, lltype.Signed)
2481 func_ptr = llhelper(lltype.Ptr(FUNC), func_int)
2482 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
2483 EffectInfo.MOST_GENERAL)
2484
2485 ops = '''
2486 [i0, i1, i2, i3, i4, i5, i6, f0, f1]
2487 i15 = cond_call_value_i(i1, ConstClass(func_ptr), %s)
2488 guard_false(i0, descr=faildescr) [i1,i2,i3,i4,i5,i6,i15, f0,f1]
2489 finish(i15)
2490 ''' % ', '.join(['i%d' % (j + 2) for j in range(i)] +
2491 ["descr=calldescr"])
2492 loop = parse(ops, namespace={'faildescr': BasicFailDescr(),
2493 'func_ptr': func_ptr,
2494 'calldescr': calldescr})
2495 looptoken = JitCellToken()
2496 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2497 f1 = longlong.getfloatstorage(1.2)
2498 f2 = longlong.getfloatstorage(3.4)
2499 frame = self.cpu.execute_token(looptoken, 1, 50, 1, 2, 3, 4, 5,
2500 f1, f2)
2501 assert not called
2502 assert [self.cpu.get_int_value(frame, j) for j in range(7)] == [
2503 50, 1, 2, 3, 4, 5, 50]
2504 assert longlong.getrealfloat(
2505 self.cpu.get_float_value(frame, 7)) == 1.2
2506 assert longlong.getrealfloat(
2507 self.cpu.get_float_value(frame, 8)) == 3.4
2508 #
2509 frame = self.cpu.execute_token(looptoken, 1, 0, 1, 2, 3, 4, 5,
2510 f1, f2)
2511 assert called == [(1, 2, 3, 4)[:i]]
2512 assert [self.cpu.get_int_value(frame, j) for j in range(7)] == [
2513 0, 1, 2, 3, 4, 5, i * 100 + 1000]
2514 assert longlong.getrealfloat(self.cpu.get_float_value(frame, 7)) == 1.2
2515 assert longlong.getrealfloat(self.cpu.get_float_value(frame, 8)) == 3.4
2516
2517 def test_force_operations_returning_void(self):
2518 values = []
2519 def maybe_force(token, flag):
2520 print("CALLED WITH " + str(flag))
2521 if flag:
2522 deadframe = self.cpu.force(token)
2523 values.append(self.cpu.get_latest_descr(deadframe))
2524 values.append(self.cpu.get_int_value(deadframe, 0))
2525 values.append(self.cpu.get_int_value(deadframe, 1))
2526 self.cpu.set_savedata_ref(deadframe, random_gcref)
2527
2528 FUNC = self.FuncType([llmemory.GCREF, lltype.Signed], lltype.Void)
2529 func_ptr = llhelper(lltype.Ptr(FUNC), maybe_force)
2530 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
2531 EffectInfo.MOST_GENERAL)
2532 cpu = self.cpu
2533 faildescr = BasicFailDescr(1)
2534 finaldescr = BasicFinalDescr(0)
2535 loop = parse("""
2536 [i0, i1]
2537 p2 = force_token()
2538 call_may_force_n(ConstClass(func_ptr), p2, i1, descr=calldescr)
2539 guard_not_forced(descr=faildescr) [i1, i0]
2540 finish(i0, descr=finaldescr)
2541 """, namespace=locals())
2542 looptoken = JitCellToken()
2543 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2544 deadframe = self.cpu.execute_token(looptoken, 20, 0)
2545 fail = self.cpu.get_latest_descr(deadframe)
2546 assert fail.identifier == 0
2547 assert self.cpu.get_int_value(deadframe, 0) == 20
2548 assert values == []
2549
2550 deadframe = self.cpu.execute_token(looptoken, 10, 1)
2551 fail = self.cpu.get_latest_descr(deadframe)
2552 assert fail.identifier == 1
2553 assert self.cpu.get_int_value(deadframe, 0) == 1
2554 assert self.cpu.get_int_value(deadframe, 1) == 10
2555 assert values == [faildescr, 1, 10]
2556 assert self.cpu.get_savedata_ref(deadframe) # not NULL
2557 assert self.cpu.get_savedata_ref(deadframe) == random_gcref
2558
2559 def test_force_operations_returning_int(self):
2560 values = []
2561 def maybe_force(token, flag):
2562 if flag:
2563 deadframe = self.cpu.force(token)
2564 values.append(self.cpu.get_int_value(deadframe, 0))
2565 values.append(self.cpu.get_int_value(deadframe, 2))
2566 self.cpu.set_savedata_ref(deadframe, random_gcref)
2567 return 42
2568
2569 FUNC = self.FuncType([llmemory.GCREF, lltype.Signed], lltype.Signed)
2570 func_ptr = llhelper(lltype.Ptr(FUNC), maybe_force)
2571 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
2572 EffectInfo.MOST_GENERAL)
2573 cpu = self.cpu
2574 faildescr = BasicFailDescr(1)
2575 finaldescr = BasicFinalDescr(0)
2576 loop = parse("""
2577 [i0, i1]
2578 p3 = force_token()
2579 i2 = call_may_force_i(ConstClass(func_ptr), p3, i1, descr=calldescr)
2580 guard_not_forced(descr=faildescr) [i1, i2, i0]
2581 finish(i2, descr=finaldescr)
2582 """, namespace=locals())
2583 looptoken = JitCellToken()
2584 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2585 deadframe = self.cpu.execute_token(looptoken, 20, 0)
2586 fail = self.cpu.get_latest_descr(deadframe)
2587 assert fail.identifier == 0
2588 assert self.cpu.get_int_value(deadframe, 0) == 42
2589 assert values == []
2590
2591 deadframe = self.cpu.execute_token(looptoken, 10, 1)
2592 fail = self.cpu.get_latest_descr(deadframe)
2593 assert fail.identifier == 1
2594 assert self.cpu.get_int_value(deadframe, 0) == 1
2595 assert self.cpu.get_int_value(deadframe, 1) == 42
2596 assert self.cpu.get_int_value(deadframe, 2) == 10
2597 assert values == [1, 10]
2598 assert self.cpu.get_savedata_ref(deadframe) == random_gcref
2599
2600 def test_force_operations_returning_float(self):
2601 if not self.cpu.supports_floats:
2602 py.test.skip("requires floats")
2603 values = []
2604 def maybe_force(token, flag):
2605 if flag:
2606 deadframe = self.cpu.force(token)
2607 values.append(self.cpu.get_int_value(deadframe, 0))
2608 values.append(self.cpu.get_int_value(deadframe, 2))
2609 self.cpu.set_savedata_ref(deadframe, random_gcref)
2610 return 42.5
2611
2612 FUNC = self.FuncType([llmemory.GCREF, lltype.Signed], lltype.Float)
2613 func_ptr = llhelper(lltype.Ptr(FUNC), maybe_force)
2614 funcbox = self.get_funcbox(self.cpu, func_ptr).constbox()
2615 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
2616 EffectInfo.MOST_GENERAL)
2617 cpu = self.cpu
2618 faildescr = BasicFailDescr(1)
2619 finaldescr = BasicFinalDescr(0)
2620 loop = parse("""
2621 [i0, i1]
2622 p3 = force_token()
2623 f2 = call_may_force_f(ConstClass(func_ptr), p3, i1, descr=calldescr)
2624 guard_not_forced(descr=faildescr) [i1, f2, i0]
2625 finish(f2, descr=finaldescr)
2626 """, namespace=locals())
2627 looptoken = JitCellToken()
2628 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2629 deadframe = self.cpu.execute_token(looptoken, 20, 0)
2630 fail = self.cpu.get_latest_descr(deadframe)
2631 assert fail.identifier == 0
2632 x = self.cpu.get_float_value(deadframe, 0)
2633 assert longlong.getrealfloat(x) == 42.5
2634 assert values == []
2635
2636 deadframe = self.cpu.execute_token(looptoken, 10, 1)
2637 fail = self.cpu.get_latest_descr(deadframe)
2638 assert fail.identifier == 1
2639 assert self.cpu.get_int_value(deadframe, 0) == 1
2640 x = self.cpu.get_float_value(deadframe, 1)
2641 assert longlong.getrealfloat(x) == 42.5
2642 assert self.cpu.get_int_value(deadframe, 2) == 10
2643 assert values == [1, 10]
2644 assert self.cpu.get_savedata_ref(deadframe) == random_gcref
2645
2646 def test_guard_not_forced_2(self):
2647 cpu = self.cpu
2648 faildescr = BasicFailDescr(1)
2649 finaldescr = BasicFinalDescr(0)
2650 loop = parse("""
2651 [i0]
2652 i1 = int_add(i0, 10)
2653 p2 = force_token()
2654 guard_not_forced_2(descr=faildescr) [i1]
2655 finish(p2, descr=finaldescr)
2656 """, namespace=locals())
2657 looptoken = JitCellToken()
2658 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2659 deadframe = self.cpu.execute_token(looptoken, 20)
2660 fail = self.cpu.get_latest_descr(deadframe)
2661 assert fail.identifier == 0
2662 frame = self.cpu.get_ref_value(deadframe, 0)
2663 # actually, we should get the same pointer in 'frame' and 'deadframe'
2664 # but it is not the case on LLGraph
2665 if not getattr(self.cpu, 'is_llgraph', False):
2666 assert frame == deadframe
2667 deadframe2 = self.cpu.force(frame)
2668 assert self.cpu.get_int_value(deadframe2, 0) == 30
2669
2670 def test_guard_not_forced_2_float(self):
2671 cpu = self.cpu
2672 if not cpu.supports_floats:
2673 py.test.skip("requires floats")
2674 faildescr = BasicFailDescr(1)
2675 finaldescr = BasicFinalDescr(0)
2676 loop = parse("""
2677 [f0]
2678 f1 = float_add(f0, 2.5)
2679 p2 = force_token()
2680 guard_not_forced_2(descr=faildescr) [f1]
2681 finish(p2, descr=finaldescr)
2682 """, namespace=locals())
2683 looptoken = JitCellToken()
2684 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2685 x = longlong.getfloatstorage(20.25)
2686 deadframe = self.cpu.execute_token(looptoken, x)
2687 fail = self.cpu.get_latest_descr(deadframe)
2688 assert fail.identifier == 0
2689 frame = self.cpu.get_ref_value(deadframe, 0)
2690 # actually, we should get the same pointer in 'frame' and 'deadframe'
2691 # but it is not the case on LLGraph
2692 if not getattr(self.cpu, 'is_llgraph', False):
2693 assert frame == deadframe
2694 deadframe2 = self.cpu.force(frame)
2695 x = self.cpu.get_float_value(deadframe2, 0)
2696 assert longlong.getrealfloat(x) == 22.75
2697
2698 def test_call_to_c_function(self):
2699 from rpython.rlib.libffi import CDLL, types, ArgChain, FUNCFLAG_CDECL
2700 from rpython.rtyper.lltypesystem.ll2ctypes import libc_name
2701 libc = CDLL(libc_name)
2702 c_tolower = libc.getpointer('tolower', [types.uchar], types.sint)
2703 argchain = ArgChain().arg(ord('A'))
2704 assert c_tolower.call(argchain, rffi.INT) == ord('a')
2705
2706 cpu = self.cpu
2707 func_adr = c_tolower.funcsym
2708 calldescr = cpu._calldescr_dynamic_for_tests([types.uchar], types.sint)
2709 faildescr = BasicFailDescr(1)
2710 finaldescr = BasicFinalDescr(0)
2711 loop = parse("""
2712 [i1]
2713 i2 = call_release_gil_i(0, ConstClass(func_adr), i1, descr=calldescr)
2714 guard_not_forced(descr=faildescr) [i1, i2]
2715 finish(i2, descr=finaldescr)
2716 """, namespace=locals())
2717 looptoken = JitCellToken()
2718 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2719 deadframe = self.cpu.execute_token(looptoken, ord('G'))
2720 fail = self.cpu.get_latest_descr(deadframe)
2721 assert fail.identifier == 0
2722 assert self.cpu.get_int_value(deadframe, 0) == ord('g')
2723
2724 def test_call_to_c_function_with_callback(self):
2725 from rpython.rlib.libffi import CDLL, types, ArgChain, clibffi
2726 from rpython.rtyper.lltypesystem.ll2ctypes import libc_name
2727 libc = CDLL(libc_name)
2728 types_size_t = clibffi.cast_type_to_ffitype(rffi.SIZE_T)
2729 c_qsort = libc.getpointer('qsort', [types.pointer, types_size_t,
2730 types_size_t, types.pointer],
2731 types.void)
2732 class Glob(object):
2733 pass
2734 glob = Glob()
2735 class X(object):
2736 pass
2737 #
2738 def callback(p1, p2):
2739 glob.lst.append(X())
2740 return rffi.cast(rffi.INT, 1)
2741 CALLBACK = lltype.Ptr(lltype.FuncType([lltype.Signed,
2742 lltype.Signed], rffi.INT))
2743 fn = llhelper(CALLBACK, callback)
2744 S = lltype.Struct('S', ('x', rffi.INT), ('y', rffi.INT))
2745 raw = lltype.malloc(S, flavor='raw')
2746 argchain = ArgChain()
2747 argchain = argchain.arg(rffi.cast(lltype.Signed, raw))
2748 argchain = argchain.arg(rffi.cast(rffi.SIZE_T, 2))
2749 argchain = argchain.arg(rffi.cast(rffi.SIZE_T, 4))
2750 argchain = argchain.arg(rffi.cast(lltype.Signed, fn))
2751 glob.lst = []
2752 c_qsort.call(argchain, lltype.Void)
2753 assert len(glob.lst) > 0
2754 del glob.lst[:]
2755
2756 cpu = self.cpu
2757 func_adr = c_qsort.funcsym
2758 calldescr = cpu._calldescr_dynamic_for_tests(
2759 [types.pointer, types_size_t, types_size_t, types.pointer],
2760 types.void)
2761 faildescr = BasicFailDescr(1)
2762 finaldescr = BasicFinalDescr(0)
2763 loop = parse("""
2764 [i0, i1, i2, i3]
2765 call_release_gil_n(0, ConstClass(func_adr), i0, i1, i2, i3, descr=calldescr)
2766 guard_not_forced(descr=faildescr) []
2767 finish(descr=finaldescr)
2768 """, namespace=locals())
2769 looptoken = JitCellToken()
2770 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
2771 args = [rffi.cast(lltype.Signed, raw),
2772 2,
2773 4,
2774 rffi.cast(lltype.Signed, fn)]
2775 assert glob.lst == []
2776 deadframe = self.cpu.execute_token(looptoken, *args)
2777 fail = self.cpu.get_latest_descr(deadframe)
2778 assert fail.identifier == 0
2779 assert len(glob.lst) > 0
2780 lltype.free(raw, flavor='raw')
2781
2782 def test_call_to_winapi_function(self):
2783 from rpython.rlib.clibffi import _WIN32
2784 if not _WIN32:
2785 py.test.skip("Windows test only")
2786 if sys.maxint > 2 ** 32:
2787 py.test.skip("Windows 32-bit test only")
2788 from rpython.rlib.libffi import WinDLL, types, ArgChain
2789 from rpython.rlib.rwin32 import DWORD
2790 libc = WinDLL('KERNEL32')
2791 c_GetCurrentDir = libc.getpointer('GetCurrentDirectoryA',
2792 [types.ulong, types.pointer],
2793 types.ulong)
2794
2795 cwd = os.getcwd()
2796 buflen = len(cwd) + 10
2797 buffer = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw')
2798 argchain = ArgChain().arg(rffi.cast(DWORD, buflen)).arg(buffer)
2799 res = c_GetCurrentDir.call(argchain, DWORD)
2800 assert rffi.cast(lltype.Signed, res) == len(cwd)
2801 assert rffi.charp2strn(buffer, buflen) == cwd
2802 lltype.free(buffer, flavor='raw')
2803
2804 cpu = self.cpu
2805 funcbox = ConstInt(ptr2int(c_GetCurrentDir.funcsym))
2806 calldescr = cpu._calldescr_dynamic_for_tests(
2807 [types.ulong, types.pointer],
2808 types.ulong,
2809 abiname='FFI_STDCALL')
2810 i1 = InputArgInt()
2811 i2 = InputArgInt()
2812 faildescr = BasicFailDescr(1)
2813 # if the stdcall convention is ignored, then ESP is wrong after the
2814 # call: 8 bytes too much. If we repeat the call often enough, crash.
2815 ops = []
2816 for i in range(50):
2817 ops += [
2818 ResOperation(rop.CALL_RELEASE_GIL_I,
2819 [ConstInt(0), funcbox, i1, i2],
2820 descr=calldescr),
2821 ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr),
2822 ]
2823 i3 = ops[-2]
2824 ops[-1].setfailargs([])
2825 ops += [
2826 ResOperation(rop.FINISH, [i3], descr=BasicFinalDescr(0))
2827 ]
2828 looptoken = JitCellToken()
2829 self.cpu.compile_loop([i1, i2], ops, looptoken)
2830
2831 buffer = lltype.malloc(rffi.CCHARP.TO, buflen, flavor='raw')
2832 args = [buflen, rffi.cast(lltype.Signed, buffer)]
2833 deadframe = self.cpu.execute_token(looptoken, *args)
2834 fail = self.cpu.get_latest_descr(deadframe)
2835 assert fail.identifier == 0
2836 assert self.cpu.get_int_value(deadframe, 0) == len(cwd)
2837 assert rffi.charp2strn(buffer, buflen) == cwd
2838 lltype.free(buffer, flavor='raw')
2839
2840 def test_call_release_gil_return_types(self):
2841 from rpython.rlib.libffi import types
2842 from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong
2843 from rpython.rlib.rarithmetic import r_singlefloat
2844 cpu = self.cpu
2845
2846 for ffitype, result, TP in [
2847 (types.unsigned, r_uint(sys.maxint + 10), lltype.Unsigned),
2848 (types.signed, -4321, lltype.Signed),
2849 (types.uint8, 200, rffi.UCHAR),
2850 (types.sint8, -42, rffi.SIGNEDCHAR),
2851 (types.uint16, 50000, rffi.USHORT),
2852 (types.sint16, -20000, rffi.SHORT),
2853 (types.uint32, r_uint(3000000000), rffi.UINT),
2854 (types.sint32, -2000000000, rffi.INT),
2855 (types.uint64, r_ulonglong(9999999999999999999),
2856 lltype.UnsignedLongLong),
2857 (types.sint64, r_longlong(-999999999999999999),
2858 lltype.SignedLongLong),
2859 (types.double, 12.3475226, rffi.DOUBLE),
2860 (types.float, r_singlefloat(-592.75), rffi.FLOAT),
2861 ]:
2862 if IS_32_BIT and TP in (lltype.SignedLongLong,
2863 lltype.UnsignedLongLong):
2864 if not cpu.supports_longlong:
2865 continue
2866 if TP == rffi.DOUBLE:
2867 if not cpu.supports_floats:
2868 continue
2869 if TP == rffi.FLOAT:
2870 if not cpu.supports_singlefloats:
2871 continue
2872 #
2873 result = rffi.cast(TP, result)
2874 #
2875 def pseudo_c_function():
2876 return result
2877 #
2878 FPTR = self.Ptr(self.FuncType([], TP))
2879 func_ptr = llhelper(FPTR, pseudo_c_function)
2880 funcbox = self.get_funcbox(cpu, func_ptr)
2881 calldescr = cpu._calldescr_dynamic_for_tests([], ffitype)
2882 faildescr = BasicFailDescr(1)
2883 kind = types.getkind(ffitype)
2884 if kind in 'uis':
2885 opnum = rop.CALL_RELEASE_GIL_I
2886 elif kind in 'fUI':
2887 opnum = rop.CALL_RELEASE_GIL_F
2888 else:
2889 assert 0, kind
2890 #
2891 op0 = ResOperation(opnum, [ConstInt(0), funcbox], descr=calldescr)
2892 op1 = ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr)
2893 op2 = ResOperation(rop.FINISH, [op0], BasicFinalDescr(0))
2894 ops = [op0, op1, op2]
2895 ops[1].setfailargs([])
2896 looptoken = JitCellToken()
2897 self.cpu.compile_loop([], ops, looptoken)
2898
2899 deadframe = self.cpu.execute_token(looptoken)
2900 fail = self.cpu.get_latest_descr(deadframe)
2901 assert fail.identifier == 0
2902 if kind in 'uis':
2903 r = self.cpu.get_int_value(deadframe, 0)
2904 if isinstance(result, r_singlefloat):
2905 assert -sys.maxint-1 <= r <= 0xFFFFFFFF
2906 r, = struct.unpack("f", struct.pack("I", r & 0xFFFFFFFF))
2907 result = float(result)
2908 else:
2909 r = rffi.cast(TP, r)
2910 assert r == result
2911 elif kind in 'fUI':
2912 r = self.cpu.get_float_value(deadframe, 0)
2913 if isinstance(result, float):
2914 r = longlong.getrealfloat(r)
2915 else:
2916 r = rffi.cast(TP, r)
2917 assert r == result
2918
2919 def test_call_release_gil_variable_function_and_arguments(self):
2920 from rpython.translator.tool.cbuild import ExternalCompilationInfo
2921 from rpython.rlib.libffi import types
2922 from rpython.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong
2923 from rpython.rlib.rarithmetic import r_singlefloat
2924 from rpython.translator.c import primitive
2925
2926
2927 def same_as_for_box(b):
2928 if b.type == 'i':
2929 return rop.SAME_AS_I
2930 elif b.type == 'f':
2931 return rop.SAME_AS_F
2932 else:
2933 assert False
2934
2935 cpu = self.cpu
2936 rnd = random.Random(525)
2937 seed = py.test.config.option.randomseed
2938 print("random seed %d" % seed)
2939
2940 ALL_TYPES = [
2941 (types.unsigned, lltype.Unsigned),
2942 (types.signed, lltype.Signed),
2943 (types.uint8, rffi.UCHAR),
2944 (types.sint8, rffi.SIGNEDCHAR),
2945 (types.uint16, rffi.USHORT),
2946 (types.sint16, rffi.SHORT),
2947 (types.uint32, rffi.UINT),
2948 (types.sint32, rffi.INT),
2949 ]
2950 if IS_32_BIT and cpu.supports_longlong:
2951 ALL_TYPES += [
2952 (types.uint64, lltype.UnsignedLongLong),
2953 (types.sint64, lltype.SignedLongLong),
2954 ] * 2
2955 if cpu.supports_floats:
2956 ALL_TYPES += [
2957 (types.double, rffi.DOUBLE),
2958 ] * 4
2959 if cpu.supports_singlefloats:
2960 ALL_TYPES += [
2961 (types.float, rffi.FLOAT),
2962 ] * 4
2963
2964 NB_TESTS = 100
2965 c_source = []
2966 all_tests = []
2967
2968 def prepare_c_source():
2969 """Pick a random choice of argument types and length,
2970 and build a C function with these arguments. The C
2971 function will simply copy them all into static global
2972 variables. There are then additional functions to fetch
2973 them, one per argument, with a signature 'void(ARG *)'.
2974 """
2975 POSSIBLE_TYPES = [rnd.choice(ALL_TYPES)
2976 for i in range(random.randrange(2, 5))]
2977 load_factor = rnd.random()
2978 keepalive_factor = rnd.random()
2979 #
2980 ffitypes = []
2981 ARGTYPES = []
2982 for i in range(rnd.randrange(4, 20)):
2983 ffitype, TP = rnd.choice(POSSIBLE_TYPES)
2984 ffitypes.append(ffitype)
2985 ARGTYPES.append(TP)
2986 fn_name = 'vartest%d' % k
2987 all_tests.append((ARGTYPES, ffitypes, fn_name))
2988 #
2989 fn_args = []
2990 for i, ARG in enumerate(ARGTYPES):
2991 arg_decl = primitive.cdecl(primitive.PrimitiveType[ARG],
2992 'x%d' % i)
2993 fn_args.append(arg_decl)
2994 var_name = 'argcopy_%s_x%d' % (fn_name, i)
2995 var_decl = primitive.cdecl(primitive.PrimitiveType[ARG],
2996 var_name)
2997 c_source.append('static %s;' % var_decl)
2998 getter_name = '%s_get%d' % (fn_name, i)
2999 c_source.append('RPY_EXPORTED void %s(%s) { *p = %s; }' % (
3000 getter_name,
3001 primitive.cdecl(primitive.PrimitiveType[ARG], '*p'),
3002 var_name))
3003 c_source.append('#include <stdio.h>')
3004 c_source.append('')
3005 c_source.append('static void real%s(%s)' % (
3006 fn_name, ', '.join(fn_args)))
3007 c_source.append('{')
3008 for i in range(len(ARGTYPES)):
3009 if ARGTYPES[i] is lltype.Float:
3010 c_source.append(' fprintf(stderr, "x%d = %%f\\n", x%d);' % (i, i))
3011 elif ARGTYPES[i] is lltype.Signed:
3012 c_source.append(' fprintf(stderr, "x%d = %%ld\\n", x%d);' % (i, i))
3013 elif ARGTYPES[i] is rffi.UINT:
3014 c_source.append(' fprintf(stderr, "x%d = %%u\\n", x%d);' % (i, i))
3015 for i in range(len(ARGTYPES)):
3016 c_source.append(' argcopy_%s_x%d = x%d;' % (fn_name, i, i))
3017 c_source.append('}')
3018 c_source.append('RPY_EXPORTED void *%s(void)' % fn_name)
3019 c_source.append('{')
3020 c_source.append(' return (void *)&real%s;' % fn_name)
3021 c_source.append('}')
3022 c_source.append('')
3023
3024 for k in range(NB_TESTS):
3025 prepare_c_source()
3026
3027 eci = ExternalCompilationInfo(
3028 separate_module_sources=['\n'.join(c_source)])
3029
3030 for k in range(NB_TESTS):
3031 ARGTYPES, ffitypes, fn_name = all_tests[k]
3032 func_getter_ptr = rffi.llexternal(fn_name, [], lltype.Signed,
3033 compilation_info=eci, _nowrapper=True)
3034 load_factor = rnd.random()
3035 keepalive_factor = rnd.random()
3036 #
3037 func_raw = func_getter_ptr()
3038 calldescr = cpu._calldescr_dynamic_for_tests(ffitypes, types.void)
3039 faildescr = BasicFailDescr(1)
3040 #
3041 argboxes = [InputArgInt()] # for the function to call
3042 codes = ['X']
3043 for ffitype in ffitypes:
3044 kind = types.getkind(ffitype)
3045 codes.append(kind)
3046 if kind in 'uis':
3047 b1 = InputArgInt()
3048 elif kind in 'fUI':
3049 b1 = InputArgFloat()
3050 else:
3051 assert 0, kind
3052 argboxes.append(b1)
3053 codes = ''.join(codes) # useful for pdb
3054 print()
3055 print(codes)
3056 #
3057 argvalues = [func_raw]
3058 for TP in ARGTYPES:
3059 r = (rnd.random() - 0.5) * 999999999999.9
3060 r = rffi.cast(TP, r)
3061 argvalues.append(r)
3062 #
3063 argvalues_normal = argvalues[:1]
3064 for ffitype, r in zip(ffitypes, argvalues[1:]):
3065 kind = types.getkind(ffitype)
3066 if kind in 'ui':
3067 r = rffi.cast(lltype.Signed, r)
3068 elif kind in 's':
3069 r, = struct.unpack("i", struct.pack("f", float(r)))
3070 elif kind in 'f':
3071 r = longlong.getfloatstorage(r)
3072 elif kind in 'UI': # 32-bit only
3073 r = rffi.cast(lltype.SignedLongLong, r)
3074 else:
3075 assert 0
3076 argvalues_normal.append(r)
3077 #
3078 ops = []
3079 loadcodes = []
3080 insideboxes = []
3081 for b1 in argboxes:
3082 load = rnd.random() < load_factor
3083 loadcodes.append(' ^'[load])
3084 if load:
3085 b2 = ResOperation(same_as_for_box(b1), [b1])
3086 ops.insert(rnd.randrange(0, len(ops)+1), b2)
3087 b1 = b2
3088 insideboxes.append(b1)
3089 loadcodes = ''.join(loadcodes)
3090 print(loadcodes)
3091 ops += [
3092 ResOperation(rop.CALL_RELEASE_GIL_N,
3093 [ConstInt(0)] + insideboxes,
3094 descr=calldescr),
3095 ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr),
3096 ResOperation(rop.FINISH, [], descr=BasicFinalDescr(0))
3097 ]
3098 ops[-2].setfailargs([])
3099 # keep alive a random subset of the insideboxes
3100 for b1 in insideboxes:
3101 if rnd.random() < keepalive_factor:
3102 ops.insert(-1, ResOperation(same_as_for_box(b1), [b1]))
3103 looptoken = JitCellToken()
3104 self.cpu.compile_loop(argboxes, ops, looptoken)
3105 #
3106 deadframe = self.cpu.execute_token(looptoken, *argvalues_normal)
3107 fail = self.cpu.get_latest_descr(deadframe)
3108 assert fail.identifier == 0
3109 expected = argvalues[1:]
3110 got = []
3111 for i, ARG in enumerate(ARGTYPES):
3112 PARG = rffi.CArrayPtr(ARG)
3113 getter_name = '%s_get%d' % (fn_name, i)
3114 getter_ptr = rffi.llexternal(getter_name, [PARG], lltype.Void,
3115 compilation_info=eci,
3116 _nowrapper=True)
3117 my_arg = lltype.malloc(PARG.TO, 1, zero=True, flavor='raw')
3118 getter_ptr(my_arg)
3119 got.append(my_arg[0])
3120 lltype.free(my_arg, flavor='raw')
3121 different_values = ['x%d: got %r, expected %r' % (i, a, b)
3122 for i, (a, b) in enumerate(zip(got, expected))
3123 if a != b]
3124 assert got == expected, '\n'.join(
3125 ['bad args, signature %r' % codes[1:]] + different_values)
3126
3127 def test_call_release_gil_save_errno(self):
3128 from rpython.translator.tool.cbuild import ExternalCompilationInfo
3129 from rpython.rlib.libffi import types
3130 from rpython.jit.backend.llsupport import llerrno
3131 #
3132 if not isinstance(self.cpu, AbstractLLCPU):
3133 py.test.skip("not on LLGraph")
3134 eci = ExternalCompilationInfo(
3135 separate_module_sources=['''
3136 #include <errno.h>
3137 static Signed f1(Signed a, Signed b, Signed c, Signed d,
3138 Signed e, Signed f, Signed g) {
3139 errno = 42;
3140 return (a + 10*b + 100*c + 1000*d +
3141 10000*e + 100000*f + 1000000*g);
3142 }
3143 RPY_EXPORTED
3144 Signed test_call_release_gil_save_errno(void) {
3145 return (Signed)&f1;
3146 }
3147 '''])
3148 fn_name = 'test_call_release_gil_save_errno'
3149 getter_ptr = rffi.llexternal(fn_name, [], lltype.Signed,
3150 compilation_info=eci, _nowrapper=True)
3151 func1_adr = getter_ptr()
3152 calldescr = self.cpu._calldescr_dynamic_for_tests([types.signed]*7,
3153 types.signed)
3154 #
3155 for saveerr in [rffi.RFFI_ERR_NONE,
3156 rffi.RFFI_SAVE_ERRNO,
3157 rffi.RFFI_ERR_NONE | rffi.RFFI_ALT_ERRNO,
3158 rffi.RFFI_SAVE_ERRNO | rffi.RFFI_ALT_ERRNO,
3159 ]:
3160 faildescr = BasicFailDescr(1)
3161 inputargs = [InputArgInt() for i in range(7)]
3162 op0 = ResOperation(rop.CALL_RELEASE_GIL_I,
3163 [ConstInt(saveerr), ConstInt(func1_adr)]
3164 + inputargs,
3165 descr=calldescr)
3166
3167 ops = [
3168 op0,
3169 ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr),
3170 ResOperation(rop.FINISH, [op0], descr=BasicFinalDescr(0))
3171 ]
3172 ops[-2].setfailargs([])
3173 looptoken = JitCellToken()
3174 self.cpu.compile_loop(inputargs, ops, looptoken)
3175 #
3176 llerrno.set_debug_saved_errno(self.cpu, 24)
3177 llerrno.set_debug_saved_alterrno(self.cpu, 25)
3178 deadframe = self.cpu.execute_token(looptoken, 9, 8, 7, 6, 5, 4, 3)
3179 original_result = self.cpu.get_int_value(deadframe, 0)
3180 result = llerrno.get_debug_saved_errno(self.cpu)
3181 altresult = llerrno.get_debug_saved_alterrno(self.cpu)
3182 print('saveerr =', saveerr, ': got result =', result,
3183 'altresult =', altresult)
3184 #
3185 expected = {
3186 rffi.RFFI_ERR_NONE: (24, 25),
3187 rffi.RFFI_SAVE_ERRNO: (42, 25),
3188 rffi.RFFI_ERR_NONE | rffi.RFFI_ALT_ERRNO: (24, 25),
3189 rffi.RFFI_SAVE_ERRNO | rffi.RFFI_ALT_ERRNO: (24, 42),
3190 }
3191 # expected (24, 25) as originally set, with possibly one
3192 # of the two changed to 42 by the assembler code
3193 assert (result, altresult) == expected[saveerr]
3194 assert original_result == 3456789
3195
3196 def test_call_release_gil_readsaved_errno(self):
3197 from rpython.translator.tool.cbuild import ExternalCompilationInfo
3198 from rpython.rlib.libffi import types
3199 from rpython.jit.backend.llsupport import llerrno
3200 #
3201 if not isinstance(self.cpu, AbstractLLCPU):
3202 py.test.skip("not on LLGraph")
3203 eci = ExternalCompilationInfo(
3204 separate_module_sources=[r'''
3205 #include <stdio.h>
3206 #include <errno.h>
3207 static Signed f1(Signed a, Signed b, Signed c, Signed d,
3208 Signed e, Signed f, Signed g) {
3209 Signed r = errno;
3210 printf("read saved errno: %ld\n", (long)r);
3211 r += 100 * (a + 10*b + 100*c + 1000*d +
3212 10000*e + 100000*f + 1000000*g);
3213 return r;
3214 }
3215 RPY_EXPORTED
3216 Signed test_call_release_gil_readsaved_errno(void) {
3217 return (Signed)&f1;
3218 }
3219 '''])
3220 fn_name = 'test_call_release_gil_readsaved_errno'
3221 getter_ptr = rffi.llexternal(fn_name, [], lltype.Signed,
3222 compilation_info=eci, _nowrapper=True)
3223 func1_adr = getter_ptr()
3224 calldescr = self.cpu._calldescr_dynamic_for_tests([types.signed]*7,
3225 types.signed)
3226 #
3227 for saveerr in [rffi.RFFI_READSAVED_ERRNO,
3228 rffi.RFFI_ZERO_ERRNO_BEFORE,
3229 rffi.RFFI_READSAVED_ERRNO | rffi.RFFI_ALT_ERRNO,
3230 rffi.RFFI_ZERO_ERRNO_BEFORE | rffi.RFFI_ALT_ERRNO,
3231 ]:
3232 faildescr = BasicFailDescr(1)
3233 inputargs = [InputArgInt() for i in range(7)]
3234 op0 = ResOperation(rop.CALL_RELEASE_GIL_I,
3235 [ConstInt(saveerr), ConstInt(func1_adr)]
3236 + inputargs,
3237 descr=calldescr)
3238
3239 ops = [
3240 op0,
3241 ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr),
3242 ResOperation(rop.FINISH, [op0], descr=BasicFinalDescr(0))
3243 ]
3244 ops[-2].setfailargs([])
3245 looptoken = JitCellToken()
3246 self.cpu.compile_loop(inputargs, ops, looptoken)
3247 #
3248 llerrno.set_debug_saved_errno(self.cpu, 24)
3249 llerrno.set_debug_saved_alterrno(self.cpu, 25)
3250 deadframe = self.cpu.execute_token(looptoken, 9, 8, 7, 6, 5, 4, 3)
3251 result = self.cpu.get_int_value(deadframe, 0)
3252 assert llerrno.get_debug_saved_errno(self.cpu) == 24
3253 assert llerrno.get_debug_saved_alterrno(self.cpu) == 25
3254 #
3255 if saveerr & rffi.RFFI_READSAVED_ERRNO:
3256 if saveerr & rffi.RFFI_ALT_ERRNO:
3257 assert result == 25 + 345678900
3258 else:
3259 assert result == 24 + 345678900
3260 else:
3261 assert result == 0 + 345678900
3262
3263 def test_call_release_gil_save_lasterror(self):
3264 from rpython.translator.tool.cbuild import ExternalCompilationInfo
3265 from rpython.rlib.libffi import types
3266 from rpython.jit.backend.llsupport import llerrno
3267 #
3268 if not isinstance(self.cpu, AbstractLLCPU):
3269 py.test.skip("not on LLGraph")
3270 if sys.platform != 'win32':
3271 py.test.skip("Windows test only")
3272 eci = ExternalCompilationInfo(
3273 separate_module_sources=['''
3274 #include <windows.h>
3275 static Signed f1(Signed a, Signed b, Signed c, Signed d,
3276 Signed e, Signed f, Signed g) {
3277 SetLastError(42);
3278 return (a + 10*b + 100*c + 1000*d +
3279 10000*e + 100000*f + 1000000*g);
3280 }
3281 RPY_EXPORTED
3282 Signed test_call_release_gil_save_lasterror(void) {
3283 return (Signed)&f1;
3284 }
3285 '''])
3286 fn_name = 'test_call_release_gil_save_lasterror'
3287 getter_ptr = rffi.llexternal(fn_name, [], lltype.Signed,
3288 compilation_info=eci, _nowrapper=True)
3289 func1_adr = getter_ptr()
3290 calldescr = self.cpu._calldescr_dynamic_for_tests([types.signed]*7,
3291 types.signed)
3292 #
3293 for saveerr in [rffi.RFFI_SAVE_ERRNO, # but not _LASTERROR
3294 rffi.RFFI_SAVE_ERRNO | rffi.RFFI_ALT_ERRNO,
3295 rffi.RFFI_SAVE_LASTERROR,
3296 rffi.RFFI_SAVE_LASTERROR | rffi.RFFI_ALT_ERRNO,
3297 ]:
3298 faildescr = BasicFailDescr(1)
3299 inputargs = [InputArgInt() for i in range(7)]
3300 ops = [
3301 ResOperation(rop.CALL_RELEASE_GIL_I,
3302 [ConstInt(saveerr), ConstInt(func1_adr)]
3303 + inputargs,
3304 descr=calldescr),
3305 ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr),
3306 ]
3307 i1 = ops[0]
3308 ops += [ResOperation(rop.FINISH, [i1], descr=BasicFinalDescr(0))]
3309 ops[-2].setfailargs([])
3310 looptoken = JitCellToken()
3311 self.cpu.compile_loop(inputargs, ops, looptoken)
3312 #
3313 llerrno.set_debug_saved_lasterror(self.cpu, 24)
3314 llerrno.set_debug_saved_altlasterror(self.cpu, 25)
3315 deadframe = self.cpu.execute_token(looptoken, 9, 8, 7, 6, 5, 4, 3)
3316 original_result = self.cpu.get_int_value(deadframe, 0)
3317 result = llerrno.get_debug_saved_lasterror(self.cpu)
3318 altresult = llerrno.get_debug_saved_altlasterror(self.cpu)
3319 print('saveerr =', saveerr, ': got result =', result, end=" ")
3320 print('and altresult =', altresult)
3321 #
3322 if saveerr & rffi.RFFI_SAVE_LASTERROR:
3323 # one from the C code, the other not touched
3324 if saveerr & rffi.RFFI_ALT_ERRNO:
3325 assert (result, altresult) == (24, 42)
3326 else:
3327 assert (result, altresult) == (42, 25)
3328 else:
3329 assert (result, altresult) == (24, 25) # not touched
3330 assert original_result == 3456789
3331
3332 def test_call_release_gil_readsaved_lasterror(self):
3333 from rpython.translator.tool.cbuild import ExternalCompilationInfo
3334 from rpython.rlib.libffi import types
3335 from rpython.jit.backend.llsupport import llerrno
3336 #
3337 if not isinstance(self.cpu, AbstractLLCPU):
3338 py.test.skip("not on LLGraph")
3339 if sys.platform != 'win32':
3340 py.test.skip("Windows test only")
3341 eci = ExternalCompilationInfo(
3342 separate_module_sources=[r'''
3343 #include <windows.h>
3344 #include <stdio.h>
3345 static Signed f1(Signed a, Signed b, Signed c, Signed d,
3346 Signed e, Signed f, Signed g) {
3347 Signed r = GetLastError();
3348 printf("GetLastError() result: %ld\n", (long)r);
3349 printf("%ld %ld %ld %ld %ld %ld %ld\n", (long)a, (long)b,
3350 (long)c, (long)d, (long)e, (long)f, (long)g);
3351 r += 100 * (a + 10*b + 100*c + 1000*d +
3352 10000*e + 100000*f + 1000000*g);
3353 return r;
3354 }
3355 RPY_EXPORTED
3356 Signed test_call_release_gil_readsaved_lasterror(void) {
3357 return (Signed)&f1;
3358 }
3359 '''])
3360 fn_name = 'test_call_release_gil_readsaved_lasterror'
3361 getter_ptr = rffi.llexternal(fn_name, [], lltype.Signed,
3362 compilation_info=eci, _nowrapper=True)
3363 func1_adr = getter_ptr()
3364 calldescr = self.cpu._calldescr_dynamic_for_tests([types.signed]*7,
3365 types.signed)
3366 #
3367 for saveerr in [rffi.RFFI_READSAVED_LASTERROR,
3368 rffi.RFFI_READSAVED_LASTERROR | rffi.RFFI_ALT_ERRNO,
3369 ]:
3370 faildescr = BasicFailDescr(1)
3371 inputargs = [InputArgInt() for i in range(7)]
3372 ops = [
3373 ResOperation(rop.CALL_RELEASE_GIL_I,
3374 [ConstInt(saveerr), ConstInt(func1_adr)]
3375 + inputargs,
3376 descr=calldescr),
3377 ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr),
3378 ]
3379 i1 = ops[-2]
3380 ops += [ResOperation(rop.FINISH, [i1], descr=BasicFinalDescr(0))]
3381 ops[-2].setfailargs([])
3382 looptoken = JitCellToken()
3383 self.cpu.compile_loop(inputargs, ops, looptoken)
3384 #
3385 llerrno.set_debug_saved_lasterror(self.cpu, 24)
3386 llerrno.set_debug_saved_altlasterror(self.cpu, 25)
3387 deadframe = self.cpu.execute_token(looptoken, 9, 8, 7, 6, 5, 4, 3)
3388 result = self.cpu.get_int_value(deadframe, 0)
3389 assert llerrno.get_debug_saved_lasterror(self.cpu) == 24
3390 assert llerrno.get_debug_saved_altlasterror(self.cpu) == 25
3391 #
3392 if saveerr & rffi.RFFI_ALT_ERRNO:
3393 expected_lasterror = 25
3394 else:
3395 expected_lasterror = 24
3396 assert result == expected_lasterror + 345678900
3397
3398 def test_call_release_gil_err_all(self):
3399 from rpython.translator.tool.cbuild import ExternalCompilationInfo
3400 from rpython.rlib.libffi import types
3401 from rpython.jit.backend.llsupport import llerrno
3402 #
3403 if not isinstance(self.cpu, AbstractLLCPU):
3404 py.test.skip("not on LLGraph")
3405 if sys.platform != 'win32':
3406 eci = ExternalCompilationInfo(
3407 separate_module_sources=[r'''
3408 #include <errno.h>
3409 static Signed f1(Signed a, Signed b, Signed c, Signed d,
3410 Signed e, Signed f, Signed g) {
3411 Signed r = errno;
3412 errno = 42;
3413 r += 100 * (a + 10*b + 100*c + 1000*d +
3414 10000*e + 100000*f + 1000000*g);
3415 return r;
3416 }
3417 RPY_EXPORTED
3418 Signed test_call_release_gil_err_all(void) {
3419 return (Signed)&f1;
3420 }
3421 '''])
3422 else:
3423 eci = ExternalCompilationInfo(
3424 separate_module_sources=[r'''
3425 #include <windows.h>
3426 #include <errno.h>
3427 static Signed f1(Signed a, Signed b, Signed c, Signed d,
3428 Signed e, Signed f, Signed g) {
3429 Signed r = errno + 10 * GetLastError();
3430 errno = 42;
3431 SetLastError(43);
3432 r += 100 * (a + 10*b + 100*c + 1000*d +
3433 10000*e + 100000*f + 1000000*g);
3434 return r;
3435 }
3436 RPY_EXPORTED
3437 Signed test_call_release_gil_err_all(void) {
3438 return (Signed)&f1;
3439 }
3440 '''])
3441 fn_name = 'test_call_release_gil_err_all'
3442 getter_ptr = rffi.llexternal(fn_name, [], lltype.Signed,
3443 compilation_info=eci, _nowrapper=True)
3444 func1_adr = getter_ptr()
3445 calldescr = self.cpu._calldescr_dynamic_for_tests([types.signed]*7,
3446 types.signed)
3447 #
3448 for saveerr in [rffi.RFFI_ERR_ALL,
3449 rffi.RFFI_ERR_ALL | rffi.RFFI_ALT_ERRNO,
3450 ]:
3451 faildescr = BasicFailDescr(1)
3452 inputargs = [InputArgInt() for i in range(7)]
3453 op0 = ResOperation(rop.CALL_RELEASE_GIL_I,
3454 [ConstInt(saveerr), ConstInt(func1_adr)]
3455 + inputargs,
3456 descr=calldescr)
3457
3458 ops = [
3459 op0,
3460 ResOperation(rop.GUARD_NOT_FORCED, [], descr=faildescr),
3461 ResOperation(rop.FINISH, [op0], descr=BasicFinalDescr(0))
3462 ]
3463 ops[-2].setfailargs([])
3464 looptoken = JitCellToken()
3465 self.cpu.compile_loop(inputargs, ops, looptoken)
3466 #
3467 llerrno.set_debug_saved_errno(self.cpu, 8)
3468 llerrno.set_debug_saved_alterrno(self.cpu, 5)
3469 llerrno.set_debug_saved_lasterror(self.cpu, 9)
3470 llerrno.set_debug_saved_altlasterror(self.cpu, 4)
3471 deadframe = self.cpu.execute_token(looptoken, 1, 2, 3, 4, 5, 6, 7)
3472 result = self.cpu.get_int_value(deadframe, 0)
3473 got_errno = llerrno.get_debug_saved_errno(self.cpu)
3474 got_alter = llerrno.get_debug_saved_alterrno(self.cpu)
3475 if saveerr & rffi.RFFI_ALT_ERRNO:
3476 assert (got_errno, got_alter) == (8, 42)
3477 else:
3478 assert (got_errno, got_alter) == (42, 5)
3479 if sys.platform != 'win32':
3480 if saveerr & rffi.RFFI_ALT_ERRNO:
3481 assert result == 765432105
3482 else:
3483 assert result == 765432108
3484 else:
3485 if saveerr & rffi.RFFI_ALT_ERRNO:
3486 assert result == 765432145
3487 else:
3488 assert result == 765432198
3489 got_lasterror = llerrno.get_debug_saved_lasterror(self.cpu)
3490 got_altlaster = llerrno.get_debug_saved_altlasterror(self.cpu)
3491 if saveerr & rffi.RFFI_ALT_ERRNO:
3492 assert (got_lasterror, got_altlaster) == (9, 43)
3493 else:
3494 assert (got_lasterror, got_altlaster) == (43, 4)
3495
3496 def test_guard_not_invalidated(self):
3497 cpu = self.cpu
3498 faildescr = BasicFailDescr(1)
3499 finaldescr = BasicFinalDescr(0)
3500 loop = parse("""
3501 [i0, i1]
3502 guard_not_invalidated(descr=faildescr) [i1]
3503 finish(i0, descr=finaldescr)
3504 """, namespace=locals())
3505 looptoken = JitCellToken()
3506 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
3507
3508 deadframe = self.cpu.execute_token(looptoken, -42, 9)
3509 fail = self.cpu.get_latest_descr(deadframe)
3510 assert fail.identifier == 0
3511 assert self.cpu.get_int_value(deadframe, 0) == -42
3512 print('step 1 ok')
3513 print('-'*79)
3514
3515 # mark as failing
3516 self.cpu.invalidate_loop(looptoken)
3517
3518 deadframe = self.cpu.execute_token(looptoken, -42, 9)
3519 fail = self.cpu.get_latest_descr(deadframe)
3520 assert fail is faildescr
3521 assert self.cpu.get_int_value(deadframe, 0) == 9
3522 print('step 2 ok')
3523 print('-'*79)
3524
3525 # attach a bridge
3526 faildescr2 = BasicFailDescr(2)
3527 finaldescr2 = BasicFinalDescr(3)
3528 bridge = parse("""
3529 [i2]
3530 guard_not_invalidated(descr=faildescr2) []
3531 finish(i2, descr=finaldescr2)
3532 """, namespace=locals())
3533 self.cpu.compile_bridge(faildescr, bridge.inputargs,
3534 bridge.operations, looptoken)
3535
3536 deadframe = self.cpu.execute_token(looptoken, -42, 9)
3537 fail = self.cpu.get_latest_descr(deadframe)
3538 assert fail.identifier == 3
3539 assert self.cpu.get_int_value(deadframe, 0) == 9
3540 print('step 3 ok')
3541 print('-'*79)
3542
3543 # mark as failing again
3544 self.cpu.invalidate_loop(looptoken)
3545
3546 deadframe = self.cpu.execute_token(looptoken, -42, 9)
3547 fail = self.cpu.get_latest_descr(deadframe)
3548 assert fail is faildescr2
3549 print('step 4 ok')
3550 print('-'*79)
3551
3552 def test_guard_not_invalidated_and_label(self):
3553 # test that the guard_not_invalidated reserves enough room before
3554 # the label. If it doesn't, then in this example after we invalidate
3555 # the guard, jumping to the label will hit the invalidation code too
3556 cpu = self.cpu
3557 faildescr = BasicFailDescr(1)
3558 labeldescr = TargetToken()
3559 finaldescr = BasicFinalDescr(3)
3560 loop = parse("""
3561 [i0]
3562 guard_not_invalidated(descr=faildescr) []
3563 label(i0, descr=labeldescr)
3564 finish(i0, descr=finaldescr)
3565 """, namespace=locals())
3566 looptoken = JitCellToken()
3567 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
3568 # mark as failing
3569 self.cpu.invalidate_loop(looptoken)
3570 # attach a bridge
3571 i2 = InputArgInt()
3572 ops2 = [
3573 ResOperation(rop.JUMP, [ConstInt(333)], descr=labeldescr),
3574 ]
3575 self.cpu.compile_bridge(faildescr, [], ops2, looptoken)
3576 # run: must not be caught in an infinite loop
3577 deadframe = self.cpu.execute_token(looptoken, 16)
3578 fail = self.cpu.get_latest_descr(deadframe)
3579 assert fail.identifier == 3
3580 assert self.cpu.get_int_value(deadframe, 0) == 333
3581
3582 # pure do_ / descr features
3583
3584 def test_do_operations(self):
3585 cpu = self.cpu
3586 #
3587 A = lltype.GcArray(lltype.Char)
3588 descr_A = cpu.arraydescrof(A)
3589 a = lltype.malloc(A, 5)
3590 x = cpu.bh_arraylen_gc(lltype.cast_opaque_ptr(llmemory.GCREF, a),
3591 descr_A)
3592 assert x == 5
3593 #
3594 a[2] = 'Y'
3595 x = cpu.bh_getarrayitem_gc_i(
3596 lltype.cast_opaque_ptr(llmemory.GCREF, a), 2, descr_A)
3597 assert x == ord('Y')
3598 #
3599 B = lltype.GcArray(lltype.Ptr(A))
3600 descr_B = cpu.arraydescrof(B)
3601 b = lltype.malloc(B, 4)
3602 b[3] = a
3603 x = cpu.bh_getarrayitem_gc_r(
3604 lltype.cast_opaque_ptr(llmemory.GCREF, b), 3, descr_B)
3605 assert lltype.cast_opaque_ptr(lltype.Ptr(A), x) == a
3606 if self.cpu.supports_floats:
3607 C = lltype.GcArray(lltype.Float)
3608 c = lltype.malloc(C, 6)
3609 c[3] = 3.5
3610 descr_C = cpu.arraydescrof(C)
3611 x = cpu.bh_getarrayitem_gc_f(
3612 lltype.cast_opaque_ptr(llmemory.GCREF, c), 3, descr_C)
3613 assert longlong.getrealfloat(x) == 3.5
3614 cpu.bh_setarrayitem_gc_f(
3615 lltype.cast_opaque_ptr(llmemory.GCREF, c), 4,
3616 longlong.getfloatstorage(4.5), descr_C)
3617 assert c[4] == 4.5
3618 s = rstr.mallocstr(6)
3619 x = cpu.bh_strlen(lltype.cast_opaque_ptr(llmemory.GCREF, s))
3620 assert x == 6
3621 #
3622 s.chars[3] = 'X'
3623 x = cpu.bh_strgetitem(lltype.cast_opaque_ptr(llmemory.GCREF, s), 3)
3624 assert x == ord('X')
3625 #
3626 S = lltype.GcStruct('S', ('x', lltype.Char), ('y', lltype.Ptr(A)),
3627 ('z', lltype.Float))
3628 descrfld_x = cpu.fielddescrof(S, 'x')
3629 s = lltype.malloc(S)
3630 s.x = 'Z'
3631 x = cpu.bh_getfield_gc_i(lltype.cast_opaque_ptr(llmemory.GCREF, s),
3632 descrfld_x)
3633 assert x == ord('Z')
3634 #
3635 cpu.bh_setfield_gc_i(lltype.cast_opaque_ptr(llmemory.GCREF, s),
3636 ord('4'), descrfld_x)
3637 assert s.x == '4'
3638 #
3639 descrfld_y = cpu.fielddescrof(S, 'y')
3640 s.y = a
3641 x = cpu.bh_getfield_gc_r(lltype.cast_opaque_ptr(llmemory.GCREF, s),
3642 descrfld_y)
3643 assert lltype.cast_opaque_ptr(lltype.Ptr(A), x) == a
3644 #
3645 s.y = lltype.nullptr(A)
3646 cpu.bh_setfield_gc_r(lltype.cast_opaque_ptr(llmemory.GCREF, s),
3647 x, descrfld_y)
3648 assert s.y == a
3649 #
3650 RS = lltype.Struct('S', ('x', lltype.Char)) #, ('y', lltype.Ptr(A)))
3651 descrfld_rx = cpu.fielddescrof(RS, 'x')
3652 rs = lltype.malloc(RS, immortal=True)
3653 rs.x = '?'
3654 x = cpu.bh_getfield_raw_i(ptr2int(rs), descrfld_rx)
3655 assert x == ord('?')
3656 #
3657 cpu.bh_setfield_raw_i(ptr2int(rs), ord('!'), descrfld_rx)
3658 assert rs.x == '!'
3659 #
3660
3661 if self.cpu.supports_floats:
3662 descrfld_z = cpu.fielddescrof(S, 'z')
3663 cpu.bh_setfield_gc_f(
3664 lltype.cast_opaque_ptr(llmemory.GCREF, s),
3665 longlong.getfloatstorage(3.5), descrfld_z)
3666 assert s.z == 3.5
3667 s.z = 3.2
3668 x = cpu.bh_getfield_gc_f(
3669 lltype.cast_opaque_ptr(llmemory.GCREF, s),
3670 descrfld_z)
3671 assert longlong.getrealfloat(x) == 3.2
3672 ### we don't support in the JIT for now GC pointers
3673 ### stored inside non-GC structs.
3674 #descrfld_ry = cpu.fielddescrof(RS, 'y')
3675 #rs.y = a
3676 #x = cpu.do_getfield_raw(
3677 # InputArgInt(cpu.cast_adr_to_int(llmemory.cast_ptr_to_adr(rs))),
3678 # descrfld_ry)
3679 #assert isinstance(x, BoxPtr)
3680 #assert x.getref(lltype.Ptr(A)) == a
3681 #
3682 #rs.y = lltype.nullptr(A)
3683 #cpu.do_setfield_raw(
3684 # InputArgInt(cpu.cast_adr_to_int(llmemory.cast_ptr_to_adr(rs))), x,
3685 # descrfld_ry)
3686 #assert rs.y == a
3687 #
3688 descrsize = cpu.sizeof(S)
3689 x = cpu.bh_new(descrsize)
3690 lltype.cast_opaque_ptr(lltype.Ptr(S), x) # type check
3691 #
3692 X = lltype.GcStruct('X', ('parent', rclass.OBJECT))
3693 _, T, descrsize2 = self.alloc_instance(X)
3694 x = cpu.bh_new_with_vtable(descrsize2)
3695 lltype.cast_opaque_ptr(lltype.Ptr(rclass.OBJECT), x) # type check
3696 # well...
3697 #assert x.getref(rclass.OBJECTPTR).typeptr == vtable2
3698 #
3699 arraydescr = cpu.arraydescrof(A)
3700 x = cpu.bh_new_array(7, arraydescr)
3701 array = lltype.cast_opaque_ptr(lltype.Ptr(A), x)
3702 assert len(array) == 7
3703 #
3704 cpu.bh_setarrayitem_gc_i(x, 5, ord('*'), descr_A)
3705 assert array[5] == '*'
3706 #
3707 cpu.bh_setarrayitem_gc_r(
3708 lltype.cast_opaque_ptr(llmemory.GCREF, b), 1, x, descr_B)
3709 assert b[1] == array
3710 #
3711 x = cpu.bh_newstr(5)
3712 str = lltype.cast_opaque_ptr(lltype.Ptr(rstr.STR), x)
3713 assert len(str.chars) == 5
3714 #
3715 cpu.bh_strsetitem(x, 4, ord('/'))
3716 assert str.chars[4] == '/'
3717
3718 def test_sorting_of_fields(self):
3719 S = lltype.GcStruct('S', ('parent', rclass.OBJECT),
3720 ('value', lltype.Signed),
3721 ('chr1', lltype.Char),
3722 ('chr2', lltype.Char))
3723 self.alloc_instance(S)
3724 chr1 = self.cpu.fielddescrof(S, 'chr1').sort_key()
3725 value = self.cpu.fielddescrof(S, 'value').sort_key()
3726 chr2 = self.cpu.fielddescrof(S, 'chr2').sort_key()
3727 assert len(set([value, chr1, chr2])) == 3
3728
3729 def test_guards_nongc(self):
3730 x = lltype.malloc(lltype.Struct('x'), flavor='raw')
3731 v = ptr2int(x)
3732 vbox = InputArgInt(v)
3733 ops = [
3734 (rop.GUARD_NONNULL, vbox, False),
3735 (rop.GUARD_ISNULL, vbox, True),
3736 (rop.GUARD_NONNULL, InputArgInt(0), True),
3737 (rop.GUARD_ISNULL, InputArgInt(0), False),
3738 ]
3739 for opname, arg, res in ops:
3740 self.execute_operation(opname, [arg], 'void')
3741 assert self.guard_failed == res
3742
3743 lltype.free(x, flavor='raw')
3744
3745 def test_assembler_call(self):
3746 called = []
3747 def assembler_helper(deadframe, virtualizable):
3748 print("CALLED ASSEMBLER HELPER")
3749 called.append(self.cpu.get_int_value(deadframe, 0))
3750 called.append(self.cpu.get_latest_descr(deadframe))
3751 return 4 + 9
3752
3753 FUNCPTR = lltype.Ptr(lltype.FuncType([llmemory.GCREF,
3754 llmemory.GCREF],
3755 lltype.Signed))
3756 class FakeJitDriverSD:
3757 index_of_virtualizable = -1
3758 _assembler_helper_ptr = llhelper(FUNCPTR, assembler_helper)
3759 assembler_helper_adr = llmemory.cast_ptr_to_adr(
3760 _assembler_helper_ptr)
3761
3762 ops = '''
3763 [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9]
3764 i10 = int_add(i0, i1)
3765 i11 = int_add(i10, i2)
3766 i12 = int_add(i11, i3)
3767 i13 = int_add(i12, i4)
3768 i14 = int_add(i13, i5)
3769 i15 = int_add(i14, i6)
3770 i16 = int_add(i15, i7)
3771 i17 = int_add(i16, i8)
3772 i18 = int_add(i17, i9)
3773 finish(i18)'''
3774 loop = parse(ops)
3775 looptoken = JitCellToken()
3776 looptoken.outermost_jitdriver_sd = FakeJitDriverSD()
3777 finish_descr = loop.operations[-1].getdescr()
3778 self.cpu.done_with_this_frame_descr_int = BasicFinalDescr()
3779 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
3780 ARGS = [lltype.Signed] * 10
3781 RES = lltype.Signed
3782 FakeJitDriverSD.portal_calldescr = self.cpu.calldescrof(
3783 lltype.Ptr(lltype.FuncType(ARGS, RES)), ARGS, RES,
3784 EffectInfo.MOST_GENERAL)
3785 args = [i+1 for i in range(10)]
3786 deadframe = self.cpu.execute_token(looptoken, *args)
3787 assert self.cpu.get_int_value(deadframe, 0) == 55
3788 ops = '''
3789 [i0, i1, i2, i3, i4, i5, i6, i7, i8, i9]
3790 i10 = int_add(i0, 42)
3791 i11 = call_assembler_i(i10, i1, i2, i3, i4, i5, i6, i7, i8, i9, descr=looptoken)
3792 # NOTE: call_assembler_i() is turned into a single-argument version
3793 # by rewrite.py
3794 guard_not_forced()[]
3795 finish(i11)
3796 '''
3797 loop = parse(ops, namespace=locals())
3798 othertoken = JitCellToken()
3799 self.cpu.compile_loop(loop.inputargs, loop.operations, othertoken)
3800 args = [i+1 for i in range(10)]
3801 deadframe = self.cpu.execute_token(othertoken, *args)
3802 assert self.cpu.get_int_value(deadframe, 0) == 13
3803 assert called == [97, finish_descr]
3804
3805 # test the fast path, which should not call assembler_helper()
3806 del called[:]
3807 self.cpu.done_with_this_frame_descr_int = finish_descr
3808 othertoken = JitCellToken()
3809 loop = parse(ops, namespace=locals())
3810 self.cpu.compile_loop(loop.inputargs, loop.operations, othertoken)
3811 args = [i+1 for i in range(10)]
3812 deadframe = self.cpu.execute_token(othertoken, *args)
3813 assert self.cpu.get_int_value(deadframe, 0) == 97
3814 assert not called
3815
3816 def test_assembler_call_propagate_exc(self):
3817 # WARNING: this test depends on test_memoryerror first passing
3818 if not isinstance(self.cpu, AbstractLLCPU):
3819 py.test.skip("llgraph can't fake exceptions well enough, give up")
3820
3821 excdescr = BasicFailDescr(666)
3822 self.cpu.propagate_exception_descr = excdescr
3823 self.cpu.setup_once() # xxx redo it, because we added
3824 # propagate_exception
3825
3826 def assembler_helper(deadframe, virtualizable):
3827 assert self.cpu.get_latest_descr(deadframe) is excdescr
3828 # let's assume we handled that
3829 return 3
3830
3831 FUNCPTR = lltype.Ptr(lltype.FuncType([llmemory.GCREF,
3832 llmemory.GCREF],
3833 lltype.Signed))
3834 class FakeJitDriverSD:
3835 index_of_virtualizable = -1
3836 _assembler_helper_ptr = llhelper(FUNCPTR, assembler_helper)
3837 assembler_helper_adr = llmemory.cast_ptr_to_adr(
3838 _assembler_helper_ptr)
3839
3840 ops = '''
3841 [i0]
3842 p0 = newunicode(i0)
3843 finish(p0)'''
3844 loop = parse(ops)
3845 looptoken = JitCellToken()
3846 looptoken.outermost_jitdriver_sd = FakeJitDriverSD()
3847 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
3848 ARGS = [lltype.Signed] * 10
3849 RES = lltype.Signed
3850 FakeJitDriverSD.portal_calldescr = self.cpu.calldescrof(
3851 lltype.Ptr(lltype.FuncType(ARGS, RES)), ARGS, RES,
3852 EffectInfo.MOST_GENERAL)
3853 ops = '''
3854 [i0]
3855 i11 = call_assembler_i(i0, descr=looptoken)
3856 guard_not_forced()[]
3857 finish(i11)
3858 '''
3859 loop = parse(ops, namespace=locals())
3860 othertoken = JitCellToken()
3861 self.cpu.compile_loop(loop.inputargs, loop.operations, othertoken)
3862 deadframe = self.cpu.execute_token(othertoken, sys.maxint - 1)
3863 assert self.cpu.get_int_value(deadframe, 0) == 3
3864
3865 def test_assembler_call_float(self):
3866 if not self.cpu.supports_floats:
3867 py.test.skip("requires floats")
3868 called = []
3869 def assembler_helper(deadframe, virtualizable):
3870 x = self.cpu.get_float_value(deadframe, 0)
3871 assert longlong.getrealfloat(x) == 1.2 + 3.2
3872 called.append(self.cpu.get_latest_descr(deadframe))
3873 print('!' * 30 + 'assembler_helper')
3874 return 13.5
3875
3876 FUNCPTR = lltype.Ptr(lltype.FuncType([llmemory.GCREF,
3877 llmemory.GCREF],
3878 lltype.Float))
3879 class FakeJitDriverSD:
3880 index_of_virtualizable = -1
3881 _assembler_helper_ptr = llhelper(FUNCPTR, assembler_helper)
3882 assembler_helper_adr = llmemory.cast_ptr_to_adr(
3883 _assembler_helper_ptr)
3884
3885 ARGS = [lltype.Float, lltype.Float]
3886 RES = lltype.Float
3887 FakeJitDriverSD.portal_calldescr = self.cpu.calldescrof(
3888 lltype.Ptr(lltype.FuncType(ARGS, RES)), ARGS, RES,
3889 EffectInfo.MOST_GENERAL)
3890 ops = '''
3891 [f0, f1]
3892 f2 = float_add(f0, f1)
3893 finish(f2)'''
3894 loop = parse(ops)
3895 finish_descr = loop.operations[-1].getdescr()
3896 looptoken = JitCellToken()
3897 looptoken.outermost_jitdriver_sd = FakeJitDriverSD()
3898 self.cpu.done_with_this_frame_descr_float = BasicFinalDescr()
3899 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
3900 args = [longlong.getfloatstorage(1.2),
3901 longlong.getfloatstorage(2.3)]
3902 deadframe = self.cpu.execute_token(looptoken, *args)
3903 x = self.cpu.get_float_value(deadframe, 0)
3904 assert longlong.getrealfloat(x) == 1.2 + 2.3
3905 ops = '''
3906 [f4, f5]
3907 f3 = call_assembler_f(f4, f5, descr=looptoken)
3908 guard_not_forced()[]
3909 finish(f3)
3910 '''
3911 loop = parse(ops, namespace=locals())
3912 othertoken = JitCellToken()
3913 self.cpu.compile_loop(loop.inputargs, loop.operations, othertoken)
3914 args = [longlong.getfloatstorage(1.2),
3915 longlong.getfloatstorage(3.2)]
3916 deadframe = self.cpu.execute_token(othertoken, *args)
3917 x = self.cpu.get_float_value(deadframe, 0)
3918 assert longlong.getrealfloat(x) == 13.5
3919 assert called == [finish_descr]
3920
3921 # test the fast path, which should not call assembler_helper()
3922 del called[:]
3923 self.cpu.done_with_this_frame_descr_float = finish_descr
3924 othertoken = JitCellToken()
3925 loop = parse(ops, namespace=locals())
3926 self.cpu.compile_loop(loop.inputargs, loop.operations, othertoken)
3927 args = [longlong.getfloatstorage(1.2),
3928 longlong.getfloatstorage(4.2)]
3929 deadframe = self.cpu.execute_token(othertoken, *args)
3930 x = self.cpu.get_float_value(deadframe, 0)
3931 assert longlong.getrealfloat(x) == 1.2 + 4.2
3932 assert not called
3933
3934 def test_raw_malloced_getarrayitem(self):
3935 ARRAY = rffi.CArray(lltype.Signed)
3936 descr = self.cpu.arraydescrof(ARRAY)
3937 a = lltype.malloc(ARRAY, 10, flavor='raw')
3938 a[7] = -4242
3939 abox = InputArgInt(ptr2int(a))
3940 r1 = self.execute_operation(rop.GETARRAYITEM_RAW_I, [abox, InputArgInt(7)],
3941 'int', descr=descr)
3942 assert r1 == -4242
3943 lltype.free(a, flavor='raw')
3944
3945 def test_raw_malloced_setarrayitem(self):
3946 ARRAY = rffi.CArray(lltype.Signed)
3947 descr = self.cpu.arraydescrof(ARRAY)
3948 a = lltype.malloc(ARRAY, 10, flavor='raw')
3949 abox = InputArgInt(ptr2int(a))
3950 self.execute_operation(rop.SETARRAYITEM_RAW, [abox, InputArgInt(5),
3951 InputArgInt(12345)],
3952 'void', descr=descr)
3953 assert a[5] == 12345
3954 lltype.free(a, flavor='raw')
3955
3956 def test_redirect_call_assembler(self):
3957 if not self.cpu.supports_floats:
3958 py.test.skip("requires floats")
3959 called = []
3960 def assembler_helper(deadframe, virtualizable):
3961 x = self.cpu.get_float_value(deadframe, 0)
3962 assert longlong.getrealfloat(x) == 1.25 + 3.25
3963 called.append(self.cpu.get_latest_descr(deadframe))
3964 return 13.5
3965
3966 FUNCPTR = lltype.Ptr(lltype.FuncType([llmemory.GCREF, llmemory.GCREF],
3967 lltype.Float))
3968 class FakeJitDriverSD:
3969 index_of_virtualizable = -1
3970 _assembler_helper_ptr = llhelper(FUNCPTR, assembler_helper)
3971 assembler_helper_adr = llmemory.cast_ptr_to_adr(
3972 _assembler_helper_ptr)
3973
3974 ARGS = [lltype.Float, lltype.Float]
3975 RES = lltype.Float
3976 FakeJitDriverSD.portal_calldescr = self.cpu.calldescrof(
3977 lltype.Ptr(lltype.FuncType(ARGS, RES)), ARGS, RES,
3978 EffectInfo.MOST_GENERAL)
3979 ops = '''
3980 [f0, f1]
3981 f2 = float_add(f0, f1)
3982 finish(f2)'''
3983 loop = parse(ops)
3984 looptoken = JitCellToken()
3985 looptoken.outermost_jitdriver_sd = FakeJitDriverSD()
3986 self.cpu.done_with_this_frame_descr_float = BasicFinalDescr()
3987 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
3988 finish_descr = loop.operations[-1].getdescr()
3989 args = [longlong.getfloatstorage(1.25),
3990 longlong.getfloatstorage(2.35)]
3991 deadframe = self.cpu.execute_token(looptoken, *args)
3992 x = self.cpu.get_float_value(deadframe, 0)
3993 assert longlong.getrealfloat(x) == 1.25 + 2.35
3994 assert not called
3995
3996 ops = '''
3997 [f4, f5]
3998 f3 = call_assembler_f(f4, f5, descr=looptoken)
3999 guard_not_forced()[]
4000 finish(f3)
4001 '''
4002 loop = parse(ops, namespace=locals())
4003 othertoken = JitCellToken()
4004 self.cpu.compile_loop(loop.inputargs, loop.operations, othertoken)
4005
4006 # normal call_assembler: goes to looptoken
4007 args = [longlong.getfloatstorage(1.25),
4008 longlong.getfloatstorage(3.25)]
4009 deadframe = self.cpu.execute_token(othertoken, *args)
4010 x = self.cpu.get_float_value(deadframe, 0)
4011 assert longlong.getrealfloat(x) == 13.5
4012 assert called == [finish_descr]
4013 del called[:]
4014
4015 # compile a replacement which needs more jitframe stack space
4016 ops = '''
4017 [f0, f1]
4018 f2 = float_sub(f0, f1)
4019 f3 = float_sub(f0, f1)
4020 f4 = float_sub(f0, f1)
4021 f5 = float_sub(f0, f1)
4022 f6 = float_sub(f0, f1)
4023 f7 = float_sub(f0, f1)
4024 f8 = float_sub(f0, f1)
4025 f9 = float_sub(f0, f1)
4026 f10 = float_sub(f0, f1)
4027 f11 = float_sub(f0, f1)
4028 f12 = float_sub(f0, f1)
4029 f13 = float_sub(f0, f1)
4030 f14 = float_sub(f0, f1)
4031 f15 = float_sub(f0, f1)
4032 f16 = float_sub(f0, f1)
4033 f17 = float_sub(f0, f1)
4034 f18 = float_sub(f0, f1)
4035 f19 = float_sub(f0, f1)
4036 f20 = float_sub(f0, f1)
4037 f21 = float_sub(f0, f1)
4038 f22 = float_sub(f0, f1)
4039 f23 = float_sub(f0, f1)
4040 f24 = float_sub(f0, f1)
4041 f25 = float_sub(f0, f1)
4042 f26 = float_sub(f0, f1)
4043 f27 = float_sub(f0, f1)
4044 f28 = float_sub(f0, f1)
4045 f29 = float_sub(f0, f1)
4046 f30 = float_sub(f0, f1)
4047 f31 = float_sub(f0, f1)
4048 f32 = float_sub(f0, f1)
4049 i3 = float_eq(f2, f3)
4050 i4 = float_eq(f2, f4)
4051 i5 = float_eq(f2, f5)
4052 i6 = float_eq(f2, f6)
4053 i7 = float_eq(f2, f7)
4054 i8 = float_eq(f2, f8)
4055 i9 = float_eq(f2, f9)
4056 i10 = float_eq(f2, f10)
4057 i11 = float_eq(f2, f11)
4058 i12 = float_eq(f2, f12)
4059 i13 = float_eq(f2, f13)
4060 i14 = float_eq(f2, f14)
4061 i15 = float_eq(f2, f15)
4062 i16 = float_eq(f2, f16)
4063 i17 = float_eq(f2, f17)
4064 i18 = float_eq(f2, f18)
4065 i19 = float_eq(f2, f19)
4066 i20 = float_eq(f2, f20)
4067 i21 = float_eq(f2, f21)
4068 i22 = float_eq(f2, f22)
4069 i23 = float_eq(f2, f23)
4070 i24 = float_eq(f2, f24)
4071 i25 = float_eq(f2, f25)
4072 i26 = float_eq(f2, f26)
4073 i27 = float_eq(f2, f27)
4074 i28 = float_eq(f2, f28)
4075 i29 = float_eq(f2, f29)
4076 i30 = float_eq(f2, f30)
4077 i31 = float_eq(f2, f31)
4078 i32 = float_eq(f2, f32)
4079 guard_true(i3) []
4080 guard_true(i4) []
4081 guard_true(i5) []
4082 guard_true(i6) []
4083 guard_true(i7) []
4084 guard_true(i8) []
4085 guard_true(i9) []
4086 guard_true(i10) []
4087 guard_true(i11) []
4088 guard_true(i12) []
4089 guard_true(i13) []
4090 guard_true(i14) []
4091 guard_true(i15) []
4092 guard_true(i16) []
4093 guard_true(i17) []
4094 guard_true(i18) []
4095 guard_true(i19) []
4096 guard_true(i20) []
4097 guard_true(i21) []
4098 guard_true(i22) []
4099 guard_true(i23) []
4100 guard_true(i24) []
4101 guard_true(i25) []
4102 guard_true(i26) []
4103 guard_true(i27) []
4104 guard_true(i28) []
4105 guard_true(i29) []
4106 guard_true(i30) []
4107 guard_true(i31) []
4108 guard_true(i32) []
4109 finish(f2)'''
4110 loop2 = parse(ops)
4111 looptoken2 = JitCellToken()
4112 looptoken2.outermost_jitdriver_sd = FakeJitDriverSD()
4113 self.cpu.compile_loop(loop2.inputargs, loop2.operations, looptoken2)
4114 finish_descr2 = loop2.operations[-1].getdescr()
4115
4116 # check the jitframeinfo
4117 if isinstance(self.cpu, AbstractLLCPU):
4118 num1 = looptoken.compiled_loop_token.frame_info.jfi_frame_depth
4119 num2 = looptoken2.compiled_loop_token.frame_info.jfi_frame_depth
4120 assert num1 < num2
4121
4122 # install it
4123 self.cpu.redirect_call_assembler(looptoken, looptoken2)
4124
4125 # check that the jitframeinfo was updated
4126 if isinstance(self.cpu, AbstractLLCPU):
4127 num1 = looptoken.compiled_loop_token.frame_info.jfi_frame_depth
4128 num2 = looptoken2.compiled_loop_token.frame_info.jfi_frame_depth
4129 assert num1 == num2
4130
4131 # now, our call_assembler should go to looptoken2
4132 args = [longlong.getfloatstorage(6.0),
4133 longlong.getfloatstorage(1.5)] # 6.0-1.5 == 1.25+3.25
4134 deadframe = self.cpu.execute_token(othertoken, *args)
4135 x = self.cpu.get_float_value(deadframe, 0)
4136 assert longlong.getrealfloat(x) == 13.5
4137 assert called == [finish_descr2]
4138 del called[:]
4139
4140 # compile a second replacement
4141 ops = '''
4142 [f0, f1]
4143 f2 = float_mul(f0, f1)
4144 finish(f2)'''
4145 loop3 = parse(ops)
4146 looptoken3 = JitCellToken()
4147 looptoken3.outermost_jitdriver_sd = FakeJitDriverSD()
4148 self.cpu.compile_loop(loop3.inputargs, loop3.operations, looptoken3)
4149 finish_descr3 = loop3.operations[-1].getdescr()
4150
4151 # install it
4152 self.cpu.redirect_call_assembler(looptoken2, looptoken3)
4153
4154 # now, our call_assembler should go to looptoken3
4155 args = [longlong.getfloatstorage(0.5),
4156 longlong.getfloatstorage(9.0)] # 0.5*9.0 == 1.25+3.25
4157 deadframe = self.cpu.execute_token(othertoken, *args)
4158 x = self.cpu.get_float_value(deadframe, 0)
4159 assert longlong.getrealfloat(x) == 13.5
4160 assert called == [finish_descr3]
4161 del called[:]
4162
4163 def test_short_result_of_getfield_direct(self):
4164 # Test that a getfield that returns a CHAR, SHORT or INT, signed
4165 # or unsigned, properly gets zero-extended or sign-extended.
4166 # Direct bh_xxx test.
4167 cpu = self.cpu
4168 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4169 rffi.SHORT, rffi.USHORT,
4170 rffi.INT, rffi.UINT,
4171 rffi.SIGNED, rffi.UNSIGNED]:
4172 S = lltype.GcStruct('S', ('x', RESTYPE))
4173 descrfld_x = cpu.fielddescrof(S, 'x')
4174 s = lltype.malloc(S)
4175 value = intmask(0xFFEEDDCCBBAA9988)
4176 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value))
4177 s.x = rffi.cast(RESTYPE, value)
4178 x = cpu.bh_getfield_gc_i(lltype.cast_opaque_ptr(llmemory.GCREF, s),
4179 descrfld_x)
4180 assert x == expected, (
4181 "%r: got %r, expected %r" % (RESTYPE, x, expected))
4182
4183 def test_short_result_of_getfield_compiled(self):
4184 # Test that a getfield that returns a CHAR, SHORT or INT, signed
4185 # or unsigned, properly gets zero-extended or sign-extended.
4186 # Machine code compilation test.
4187 cpu = self.cpu
4188 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4189 rffi.SHORT, rffi.USHORT,
4190 rffi.INT, rffi.UINT,
4191 rffi.SIGNED, rffi.UNSIGNED]:
4192 S = lltype.GcStruct('S', ('x', RESTYPE))
4193 descrfld_x = cpu.fielddescrof(S, 'x')
4194 s = lltype.malloc(S)
4195 value = intmask(0xFFEEDDCCBBAA9988)
4196 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value))
4197 s.x = rffi.cast(RESTYPE, value)
4198 s_gcref = lltype.cast_opaque_ptr(llmemory.GCREF, s)
4199 res = self.execute_operation(rop.GETFIELD_GC_I,
4200 [InputArgRef(s_gcref)],
4201 'int', descr=descrfld_x)
4202 assert res == expected, (
4203 "%r: got %r, expected %r" % (RESTYPE, res, expected))
4204
4205 def test_short_result_of_getarrayitem_direct(self):
4206 # Test that a getarrayitem that returns a CHAR, SHORT or INT, signed
4207 # or unsigned, properly gets zero-extended or sign-extended.
4208 # Direct bh_xxx test.
4209 cpu = self.cpu
4210 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4211 rffi.SHORT, rffi.USHORT,
4212 rffi.INT, rffi.UINT,
4213 rffi.SIGNED, rffi.UNSIGNED]:
4214 A = lltype.GcArray(RESTYPE)
4215 descrarray = cpu.arraydescrof(A)
4216 a = lltype.malloc(A, 5)
4217 value = intmask(0xFFEEDDCCBBAA9988)
4218 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value))
4219 a[3] = rffi.cast(RESTYPE, value)
4220 x = cpu.bh_getarrayitem_gc_i(
4221 lltype.cast_opaque_ptr(llmemory.GCREF, a), 3, descrarray)
4222 assert x == expected, (
4223 "%r: got %r, expected %r" % (RESTYPE, x, expected))
4224
4225 def test_short_result_of_getarrayitem_compiled(self):
4226 # Test that a getarrayitem that returns a CHAR, SHORT or INT, signed
4227 # or unsigned, properly gets zero-extended or sign-extended.
4228 # Machine code compilation test.
4229 cpu = self.cpu
4230 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4231 rffi.SHORT, rffi.USHORT,
4232 rffi.INT, rffi.UINT,
4233 rffi.SIGNED, rffi.UNSIGNED]:
4234 A = lltype.GcArray(RESTYPE)
4235 descrarray = cpu.arraydescrof(A)
4236 a = lltype.malloc(A, 5)
4237 value = intmask(0xFFEEDDCCBBAA9988)
4238 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value))
4239 a[3] = rffi.cast(RESTYPE, value)
4240 a_gcref = lltype.cast_opaque_ptr(llmemory.GCREF, a)
4241 res = self.execute_operation(rop.GETARRAYITEM_GC_I,
4242 [InputArgRef(a_gcref), InputArgInt(3)],
4243 'int', descr=descrarray)
4244 assert res == expected, (
4245 "%r: got %r, expected %r" % (RESTYPE, res, expected))
4246
4247 def test_short_result_of_getarrayitem_raw_direct(self):
4248 # Test that a getarrayitem that returns a CHAR, SHORT or INT, signed
4249 # or unsigned, properly gets zero-extended or sign-extended.
4250 # Direct bh_xxx test.
4251 cpu = self.cpu
4252 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4253 rffi.SHORT, rffi.USHORT,
4254 rffi.INT, rffi.UINT,
4255 rffi.SIGNED, rffi.UNSIGNED]:
4256 A = rffi.CArray(RESTYPE)
4257 descrarray = cpu.arraydescrof(A)
4258 a = lltype.malloc(A, 5, flavor='raw')
4259 value = intmask(0xFFEEDDCCBBAA9988)
4260 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value))
4261 a[3] = rffi.cast(RESTYPE, value)
4262 a_rawint = ptr2int(a)
4263 x = cpu.bh_getarrayitem_raw_i(a_rawint, 3, descrarray)
4264 assert x == expected, (
4265 "%r: got %r, expected %r" % (RESTYPE, x, expected))
4266 lltype.free(a, flavor='raw')
4267
4268 def test_short_result_of_getarrayitem_raw_compiled(self):
4269 # Test that a getarrayitem that returns a CHAR, SHORT or INT, signed
4270 # or unsigned, properly gets zero-extended or sign-extended.
4271 # Machine code compilation test.
4272 cpu = self.cpu
4273 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4274 rffi.SHORT, rffi.USHORT,
4275 rffi.INT, rffi.UINT,
4276 rffi.SIGNED, rffi.UNSIGNED]:
4277 A = rffi.CArray(RESTYPE)
4278 descrarray = cpu.arraydescrof(A)
4279 a = lltype.malloc(A, 5, flavor='raw')
4280 value = intmask(0xFFEEDDCCBBAA9988)
4281 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value))
4282 a[3] = rffi.cast(RESTYPE, value)
4283 a_rawint = ptr2int(a)
4284 res = self.execute_operation(rop.GETARRAYITEM_RAW_I,
4285 [InputArgInt(a_rawint), InputArgInt(3)],
4286 'int', descr=descrarray)
4287 assert res == expected, (
4288 "%r: got %r, expected %r" % (RESTYPE, res, expected))
4289 lltype.free(a, flavor='raw')
4290
4291 def test_short_result_of_call_direct(self):
4292 # Test that calling a function that returns a CHAR, SHORT or INT,
4293 # signed or unsigned, properly gets zero-extended or sign-extended.
4294 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4295 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4296 rffi.SHORT, rffi.USHORT,
4297 rffi.INT, rffi.UINT,
4298 rffi.SIGNED, rffi.UNSIGNED]:
4299 # Tested with a function that intentionally does not cast the
4300 # result to RESTYPE, but makes sure that we return the whole
4301 # value in eax or rax.
4302 eci = ExternalCompilationInfo(
4303 separate_module_sources=["""
4304 RPY_EXPORTED Signed fn_test_result_of_call(Signed x)
4305 {
4306 return x + 1;
4307 }
4308 """])
4309 f = rffi.llexternal('fn_test_result_of_call', [lltype.Signed],
4310 RESTYPE, compilation_info=eci, _nowrapper=True)
4311 value = intmask(0xFFEEDDCCBBAA9988)
4312 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value + 1))
4313 assert intmask(f(value)) == expected
4314 #
4315 FUNC = self.FuncType([lltype.Signed], RESTYPE)
4316 FPTR = self.Ptr(FUNC)
4317 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
4318 EffectInfo.MOST_GENERAL)
4319 x = self.cpu.bh_call_i(self.get_funcbox(self.cpu, f).value,
4320 [value], None, None, calldescr)
4321 assert x == expected, (
4322 "%r: got %r, expected %r" % (RESTYPE, x, expected))
4323
4324 def test_short_result_of_call_compiled(self):
4325 # Test that calling a function that returns a CHAR, SHORT or INT,
4326 # signed or unsigned, properly gets zero-extended or sign-extended.
4327 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4328 for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR,
4329 rffi.SHORT, rffi.USHORT,
4330 rffi.INT, rffi.UINT,
4331 rffi.SIGNED, rffi.UNSIGNED]:
4332 # Tested with a function that intentionally does not cast the
4333 # result to RESTYPE, but makes sure that we return the whole
4334 # value in eax or rax.
4335 eci = ExternalCompilationInfo(
4336 separate_module_sources=["""
4337 RPY_EXPORTED Signed fn_test_result_of_call(Signed x)
4338 {
4339 return x + 1;
4340 }
4341 """])
4342 f = rffi.llexternal('fn_test_result_of_call', [lltype.Signed],
4343 RESTYPE, compilation_info=eci, _nowrapper=True)
4344 value = intmask(0xFFEEDDCCBBAA9988)
4345 expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value + 1))
4346 assert intmask(f(value)) == expected
4347 #
4348 FUNC = self.FuncType([lltype.Signed], RESTYPE)
4349 FPTR = self.Ptr(FUNC)
4350 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
4351 EffectInfo.MOST_GENERAL)
4352 funcbox = self.get_funcbox(self.cpu, f)
4353 res = self.execute_operation(rop.CALL_I, [funcbox, InputArgInt(value)],
4354 'int', descr=calldescr)
4355 assert res == expected, (
4356 "%r: got %r, expected %r" % (RESTYPE, res, expected))
4357
4358 def test_supports_longlong(self):
4359 if IS_64_BIT:
4360 assert not self.cpu.supports_longlong, (
4361 "supports_longlong should be False on 64-bit platforms")
4362
4363 def test_longlong_result_of_call_direct(self):
4364 if not self.cpu.supports_longlong:
4365 py.test.skip("longlong test")
4366 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4367 from rpython.rlib.rarithmetic import r_longlong
4368 eci = ExternalCompilationInfo(
4369 separate_module_sources=["""
4370 RPY_EXPORTED long long fn_test_result_of_call(long long x)
4371 {
4372 return x - 100000000000000;
4373 }
4374 """])
4375 f = rffi.llexternal('fn_test_result_of_call', [lltype.SignedLongLong],
4376 lltype.SignedLongLong,
4377 compilation_info=eci, _nowrapper=True)
4378 value = r_longlong(0x7ff05af3307a3fff)
4379 expected = r_longlong(0x7ff000001fffffff)
4380 assert f(value) == expected
4381 #
4382 FUNC = self.FuncType([lltype.SignedLongLong], lltype.SignedLongLong)
4383 FPTR = self.Ptr(FUNC)
4384 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
4385 EffectInfo.MOST_GENERAL)
4386 x = self.cpu.bh_call_f(self.get_funcbox(self.cpu, f).value,
4387 None, None, [value], calldescr)
4388 assert x == expected
4389
4390 def test_longlong_result_of_call_compiled(self):
4391 if not self.cpu.supports_longlong:
4392 py.test.skip("test of longlong result")
4393 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4394 from rpython.rlib.rarithmetic import r_longlong
4395 eci = ExternalCompilationInfo(
4396 separate_module_sources=["""
4397 RPY_EXPORTED long long fn_test_result_of_call(long long x)
4398 {
4399 return x - 100000000000000;
4400 }
4401 """])
4402 f = rffi.llexternal('fn_test_result_of_call', [lltype.SignedLongLong],
4403 lltype.SignedLongLong,
4404 compilation_info=eci, _nowrapper=True)
4405 value = r_longlong(0x7ff05af3307a3fff)
4406 expected = r_longlong(0x7ff000001fffffff)
4407 assert f(value) == expected
4408 #
4409 FUNC = self.FuncType([lltype.SignedLongLong], lltype.SignedLongLong)
4410 FPTR = self.Ptr(FUNC)
4411 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
4412 EffectInfo.MOST_GENERAL)
4413 funcbox = self.get_funcbox(self.cpu, f)
4414 res = self.execute_operation(rop.CALL_F,
4415 [funcbox, InputArgFloat(value)],
4416 'float', descr=calldescr)
4417 assert res == expected
4418
4419 def test_singlefloat_result_of_call_direct(self):
4420 if not self.cpu.supports_singlefloats:
4421 py.test.skip("singlefloat test")
4422 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4423 from rpython.rlib.rarithmetic import r_singlefloat
4424 eci = ExternalCompilationInfo(
4425 separate_module_sources=["""
4426 RPY_EXPORTED float fn_test_result_of_call(float x)
4427 {
4428 return x / 2.0f;
4429 }
4430 """])
4431 f = rffi.llexternal('fn_test_result_of_call', [lltype.SingleFloat],
4432 lltype.SingleFloat,
4433 compilation_info=eci, _nowrapper=True)
4434 value = r_singlefloat(-42.5)
4435 expected = r_singlefloat(-21.25)
4436 assert f(value) == expected
4437 #
4438 FUNC = self.FuncType([lltype.SingleFloat], lltype.SingleFloat)
4439 FPTR = self.Ptr(FUNC)
4440 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
4441 EffectInfo.MOST_GENERAL)
4442 ivalue = longlong.singlefloat2int(value)
4443 iexpected = longlong.singlefloat2int(expected)
4444 x = self.cpu.bh_call_i(self.get_funcbox(self.cpu, f).value,
4445 [ivalue], None, None, calldescr)
4446 assert x == iexpected
4447
4448 def test_singlefloat_result_of_call_compiled(self):
4449 if not self.cpu.supports_singlefloats:
4450 py.test.skip("test of singlefloat result")
4451 from rpython.translator.tool.cbuild import ExternalCompilationInfo
4452 from rpython.rlib.rarithmetic import r_singlefloat
4453 eci = ExternalCompilationInfo(
4454 separate_module_sources=["""
4455 RPY_EXPORTED float fn_test_result_of_call(float x)
4456 {
4457 return x / 2.0f;
4458 }
4459 """])
4460 f = rffi.llexternal('fn_test_result_of_call', [lltype.SingleFloat],
4461 lltype.SingleFloat,
4462 compilation_info=eci, _nowrapper=True)
4463 value = r_singlefloat(-42.5)
4464 expected = r_singlefloat(-21.25)
4465 assert f(value) == expected
4466 #
4467 FUNC = self.FuncType([lltype.SingleFloat], lltype.SingleFloat)
4468 FPTR = self.Ptr(FUNC)
4469 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
4470 EffectInfo.MOST_GENERAL)
4471 funcbox = self.get_funcbox(self.cpu, f)
4472 ivalue = longlong.singlefloat2int(value)
4473 iexpected = longlong.singlefloat2int(expected)
4474 res = self.execute_operation(rop.CALL_I, [funcbox, InputArgInt(ivalue)],
4475 'int', descr=calldescr)
4476 assert res == iexpected
4477
4478 def test_free_loop_and_bridges(self):
4479 if not isinstance(self.cpu, AbstractLLCPU):
4480 py.test.skip("not a subclass of llmodel.AbstractLLCPU")
4481 if hasattr(self.cpu, 'setup_once'):
4482 self.cpu.setup_once()
4483 mem0 = self.cpu.asmmemmgr.total_mallocs
4484 looptoken = self.test_compile_bridge()
4485 mem1 = self.cpu.asmmemmgr.total_mallocs
4486 self.cpu.free_loop_and_bridges(looptoken.compiled_loop_token)
4487 mem2 = self.cpu.asmmemmgr.total_mallocs
4488 assert mem2 < mem1
4489 assert mem2 == mem0
4490
4491 def test_memoryerror(self):
4492 excdescr = BasicFailDescr(666)
4493 self.cpu.propagate_exception_descr = excdescr
4494 self.cpu.setup_once() # xxx redo it, because we added
4495 # propagate_exception
4496 i0 = InputArgInt()
4497 p0 = ResOperation(rop.NEWUNICODE, [i0])
4498 operations = [
4499 p0,
4500 ResOperation(rop.FINISH, [p0], descr=BasicFinalDescr(1))
4501 ]
4502 inputargs = [i0]
4503 looptoken = JitCellToken()
4504 self.cpu.compile_loop(inputargs, operations, looptoken)
4505 # overflowing value:
4506 unisize = self.cpu.gc_ll_descr.unicode_descr.itemsize
4507 assert unisize in (2, 4)
4508 deadframe = self.cpu.execute_token(looptoken, sys.maxint // unisize + 1)
4509 fail = self.cpu.get_latest_descr(deadframe)
4510 assert fail.identifier == excdescr.identifier
4511 exc = self.cpu.grab_exc_value(deadframe)
4512 assert not exc
4513
4514 def test_math_sqrt(self):
4515 if not self.cpu.supports_floats:
4516 py.test.skip("requires floats")
4517
4518 def math_sqrt(a):
4519 assert False, 'should not be called'
4520 from rpython.jit.codewriter.effectinfo import EffectInfo
4521
4522 effectinfo = EffectInfo([], [], [], [], [], [], EffectInfo.EF_CANNOT_RAISE, EffectInfo.OS_MATH_SQRT)
4523 FPTR = self.Ptr(self.FuncType([lltype.Float], lltype.Float))
4524 func_ptr = llhelper(FPTR, math_sqrt)
4525 FUNC = FPTR.TO
4526 funcbox = self.get_funcbox(self.cpu, func_ptr)
4527
4528 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT, effectinfo)
4529 testcases = [(4.0, 2.0), (6.25, 2.5)]
4530 for arg, expected in testcases:
4531 res = self.execute_operation(rop.CALL_F,
4532 [funcbox, boxfloat(arg)],
4533 'float', descr=calldescr)
4534 assert longlong.getrealfloat(res) == expected
4535
4536 def test_check_memory_error(self):
4537 self.execute_operation(
4538 rop.CHECK_MEMORY_ERROR, [InputArgInt(12345)], 'void')
4539 py.test.raises(MissingLatestDescrError, self.execute_operation,
4540 rop.CHECK_MEMORY_ERROR, [InputArgInt(0)], 'void')
4541
4542 def test_compile_loop_with_target(self):
4543 looptoken = JitCellToken()
4544 targettoken1 = TargetToken()
4545 targettoken2 = TargetToken()
4546 faildescr = BasicFailDescr(2)
4547 faildescr3 = BasicFailDescr(3)
4548 loop = parse("""
4549 [i0]
4550 label(i0, descr=targettoken1)
4551 i1 = int_add(i0, 1)
4552 i2 = int_le(i1, 9)
4553 guard_true(i2, descr=faildescr) [i1]
4554 label(i1, descr=targettoken2)
4555 i3 = int_ge(i1, 0)
4556 guard_true(i3, descr=faildescr3) [i1]
4557 jump(i1, descr=targettoken1)
4558 """, namespace=locals())
4559
4560 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4561 deadframe = self.cpu.execute_token(looptoken, 2)
4562 fail = self.cpu.get_latest_descr(deadframe)
4563 assert fail.identifier == 2
4564 res = self.cpu.get_int_value(deadframe, 0)
4565 assert res == 10
4566
4567 bridge = parse("""
4568 [i0]
4569 i2 = int_sub(i0, 20)
4570 jump(i2, descr=targettoken2)
4571 """, namespace=locals())
4572
4573 self.cpu.compile_bridge(faildescr, bridge.inputargs,
4574 bridge.operations, looptoken)
4575
4576 deadframe = self.cpu.execute_token(looptoken, 2)
4577 fail = self.cpu.get_latest_descr(deadframe)
4578 assert fail.identifier == 3
4579 res = self.cpu.get_int_value(deadframe, 0)
4580 assert res == -10
4581
4582 def test_int_force_ge_zero(self):
4583 ops = """
4584 [i0]
4585 i1 = int_force_ge_zero(i0) # but forced to be in a register
4586 finish(i1, descr=descr)
4587 """
4588 descr = BasicFinalDescr()
4589 loop = parse(ops, self.cpu, namespace=locals())
4590 looptoken = JitCellToken()
4591 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4592 for inp, outp in [(2,2), (-3, 0)]:
4593 deadframe = self.cpu.execute_token(looptoken, inp)
4594 assert outp == self.cpu.get_int_value(deadframe, 0)
4595
4596 def test_int_signext(self):
4597 numbytes_cases = [1, 2] if IS_32_BIT else [1, 2, 4]
4598 for spill in ["", "force_spill(i1)"]:
4599 for numbytes in numbytes_cases:
4600 print((spill, numbytes))
4601 ops = """
4602 [i0]
4603 i1 = int_sub(i0, 0) # force in register
4604 %s
4605 i2 = int_signext(i1, %d)
4606 finish(i2, descr=descr)
4607 """ % (spill, numbytes)
4608 descr = BasicFinalDescr()
4609 loop = parse(ops, self.cpu, namespace=locals())
4610 looptoken = JitCellToken()
4611 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4612 test_cases = [random.randrange(-sys.maxint-1, sys.maxint+1)
4613 for _ in range(100)]
4614 for test_case in test_cases:
4615 deadframe = self.cpu.execute_token(looptoken, test_case)
4616 got = self.cpu.get_int_value(deadframe, 0)
4617 expected = int_signext(test_case, numbytes)
4618 assert got == expected
4619
4620 def test_compile_asmlen(self):
4621 if not isinstance(self.cpu, AbstractLLCPU):
4622 py.test.skip("pointless test on non-asm")
4623 from rpython.jit.backend.tool.viewcode import machine_code_dump, ObjdumpNotFound
4624 import ctypes
4625 targettoken = TargetToken()
4626 ops = """
4627 [i2]
4628 i0 = same_as_i(i2) # but forced to be in a register
4629 label(i0, descr=targettoken)
4630 i1 = int_add(i0, i0)
4631 guard_true(i1, descr=faildescr) [i1]
4632 jump(i1, descr=targettoken)
4633 """
4634 faildescr = BasicFailDescr(2)
4635 loop = parse(ops, self.cpu, namespace=locals())
4636 bridge_ops = """
4637 [i0]
4638 jump(i0, descr=targettoken)
4639 """
4640 bridge = parse(bridge_ops, self.cpu, namespace=locals())
4641 looptoken = JitCellToken()
4642 self.cpu.assembler.set_debug(False)
4643 info = self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4644 bridge_info = self.cpu.compile_bridge(faildescr, bridge.inputargs,
4645 bridge.operations,
4646 looptoken)
4647 self.cpu.assembler.set_debug(True) # always on untranslated
4648 assert info.asmlen != 0
4649 cpuname = autodetect()
4650 # XXX we have to check the precise assembler, otherwise
4651 # we don't quite know if borders are correct
4652
4653 def checkops(mc, ops_regexp):
4654 import re
4655 words = []
4656 print('----- checkops -----')
4657 for line in mc:
4658 print(line.rstrip())
4659 t = line.split("\t")
4660 if len(t) <= 2:
4661 continue
4662 w = t[2].split()
4663 if len(w) == 0:
4664 if '<UNDEFINED>' in line:
4665 w = ['UNDEFINED']
4666 else:
4667 continue
4668 words.append(w[0] + ';')
4669 print('[[%s]]' % (w[0],))
4670 text = ' '.join(words)
4671 assert re.compile(ops_regexp).match(text)
4672
4673 data = ctypes.string_at(info.asmaddr, info.asmlen)
4674 try:
4675 mc = list(machine_code_dump(data, info.asmaddr, cpuname))
4676 checkops(mc, self.add_loop_instructions)
4677 data = ctypes.string_at(bridge_info.asmaddr, bridge_info.asmlen)
4678 mc = list(machine_code_dump(data, bridge_info.asmaddr, cpuname))
4679 checkops(mc, self.bridge_loop_instructions)
4680 except ObjdumpNotFound:
4681 py.test.skip("requires (g)objdump")
4682
4683
4684
4685 def test_compile_bridge_with_target(self):
4686 # This test creates a loopy piece of code in a bridge, and builds another
4687 # unrelated loop that ends in a jump directly to this loopy bit of code.
4688 # It catches a case in which we underestimate the needed frame_depth across
4689 # the cross-loop JUMP, because we estimate it based on the frame_depth stored
4690 # in the original loop.
4691 looptoken1 = JitCellToken()
4692 targettoken1 = TargetToken()
4693 faildescr1 = BasicFailDescr(2)
4694 finaldescr1 = BasicFinalDescr(1234)
4695 loop = parse("""
4696 [i0]
4697 i1 = int_le(i0, 1)
4698 guard_true(i1, descr=faildescr1) [i0]
4699 finish(i0, descr=finaldescr1)
4700 """, namespace=locals())
4701 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken1)
4702
4703 def func(a, b, c, d, e, f, g, h, i):
4704 assert a + 2 == b
4705 assert a + 4 == c
4706 assert a + 6 == d
4707 assert a + 8 == e
4708 assert a + 10 == f
4709 assert a + 12 == g
4710 assert a + 14 == h
4711 assert a + 16 == i
4712 FPTR = self.Ptr(self.FuncType([lltype.Signed] * 9, lltype.Void))
4713 func_ptr = llhelper(FPTR, func)
4714 cpu = self.cpu
4715 calldescr = cpu.calldescrof(FPTR.TO, (lltype.Signed,) * 9, lltype.Void,
4716 EffectInfo.MOST_GENERAL)
4717 faildescr = BasicFailDescr(42)
4718 loop = parse("""
4719 [i0]
4720 label(i0, descr=targettoken1)
4721 i1 = int_add(i0, 1)
4722 i2 = int_add(i1, 1)
4723 i3 = int_add(i2, 1)
4724 i4 = int_add(i3, 1)
4725 i5 = int_add(i4, 1)
4726 i6 = int_add(i5, 1)
4727 i7 = int_add(i6, 1)
4728 i8 = int_add(i7, 1)
4729 i9 = int_add(i8, 1)
4730 i10 = int_add(i9, 1)
4731 i11 = int_add(i10, 1)
4732 i12 = int_add(i11, 1)
4733 i13 = int_add(i12, 1)
4734 i14 = int_add(i13, 1)
4735 i15 = int_add(i14, 1)
4736 i16 = int_add(i15, 1)
4737 i17 = int_add(i16, 1)
4738 i18 = int_add(i17, 1)
4739 i19 = int_add(i18, 1)
4740 call_n(ConstClass(func_ptr), i2, i4, i6, i8, i10, i12, i14, i16, i18, descr=calldescr)
4741 call_n(ConstClass(func_ptr), i2, i4, i6, i8, i10, i12, i14, i16, i18, descr=calldescr)
4742 i20 = int_lt(i19, 100)
4743 guard_true(i20, descr=faildescr) []
4744 jump(i19, descr=targettoken1)
4745 """, namespace=locals())
4746 self.cpu.compile_bridge(faildescr1, loop.inputargs,
4747 loop.operations, looptoken1)
4748
4749 looptoken2 = JitCellToken()
4750 inputargs = [InputArgInt()]
4751 operations3 = [
4752 ResOperation(rop.JUMP, [ConstInt(0)], descr=targettoken1),
4753 ]
4754 self.cpu.compile_loop(inputargs, operations3, looptoken2)
4755
4756 deadframe = self.cpu.execute_token(looptoken2, -9)
4757 fail = self.cpu.get_latest_descr(deadframe)
4758 assert fail.identifier == 42
4759
4760 def test_wrong_guard_nonnull_class(self):
4761 t_box, T_box, _ = self.alloc_instance(self.T)
4762 null_box = self.null_instance()
4763 faildescr = BasicFailDescr(42)
4764 operations = [
4765 ResOperation(rop.GUARD_NONNULL_CLASS, [t_box, T_box],
4766 descr=faildescr),
4767 ResOperation(rop.FINISH, [], descr=BasicFinalDescr(1))]
4768 operations[0].setfailargs([])
4769 looptoken = JitCellToken()
4770 inputargs = [t_box]
4771 self.cpu.compile_loop(inputargs, operations, looptoken)
4772 operations = [
4773 ResOperation(rop.FINISH, [], descr=BasicFinalDescr(99))
4774 ]
4775 self.cpu.compile_bridge(faildescr, [], operations, looptoken)
4776 deadframe = self.cpu.execute_token(looptoken, null_box.getref_base())
4777 fail = self.cpu.get_latest_descr(deadframe)
4778 assert fail.identifier == 99
4779
4780 def test_raw_load_int(self):
4781 from rpython.rlib import rawstorage
4782 from rpython.rlib.rarithmetic import r_longlong
4783 for T in [rffi.UCHAR, rffi.SIGNEDCHAR,
4784 rffi.USHORT, rffi.SHORT,
4785 rffi.UINT, rffi.INT,
4786 rffi.UNSIGNED, rffi.SIGNED]:
4787 ops = """
4788 [i0, i1]
4789 i2 = raw_load_i(i0, i1, descr=arraydescr)
4790 finish(i2)
4791 """
4792 arraydescr = self.cpu.arraydescrof(rffi.CArray(T))
4793 p = rawstorage.alloc_raw_storage(31)
4794 for i in range(31):
4795 p[i] = '\xDD'
4796 value = rffi.cast(T, r_longlong(-0x4243444546474849))
4797 rawstorage.raw_storage_setitem(p, 16, value)
4798 got = self.cpu.bh_raw_load_i(rffi.cast(lltype.Signed, p), 16,
4799 arraydescr)
4800 assert got == rffi.cast(lltype.Signed, value)
4801 #
4802 loop = parse(ops, self.cpu, namespace=locals())
4803 looptoken = JitCellToken()
4804 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4805 deadframe = self.cpu.execute_token(looptoken,
4806 rffi.cast(lltype.Signed, p), 16)
4807 result = self.cpu.get_int_value(deadframe, 0)
4808 assert result == rffi.cast(lltype.Signed, value)
4809 rawstorage.free_raw_storage(p)
4810
4811 def test_raw_load_float(self):
4812 if not self.cpu.supports_floats:
4813 py.test.skip("requires floats")
4814 from rpython.rlib import rawstorage
4815 for T in [rffi.DOUBLE]:
4816 ops = """
4817 [i0, i1]
4818 f2 = raw_load_f(i0, i1, descr=arraydescr)
4819 finish(f2)
4820 """
4821 arraydescr = self.cpu.arraydescrof(rffi.CArray(T))
4822 p = rawstorage.alloc_raw_storage(31)
4823 for i in range(31):
4824 p[i] = '\xDD'
4825 value = rffi.cast(T, 1.12e20)
4826 rawstorage.raw_storage_setitem(p, 16, value)
4827 got = self.cpu.bh_raw_load_f(rffi.cast(lltype.Signed, p), 16,
4828 arraydescr)
4829 got = longlong.getrealfloat(got)
4830 assert got == rffi.cast(lltype.Float, value)
4831 #
4832 loop = parse(ops, self.cpu, namespace=locals())
4833 looptoken = JitCellToken()
4834 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4835 deadframe = self.cpu.execute_token(looptoken,
4836 rffi.cast(lltype.Signed, p), 16)
4837 result = self.cpu.get_float_value(deadframe, 0)
4838 result = longlong.getrealfloat(result)
4839 assert result == rffi.cast(lltype.Float, value)
4840 rawstorage.free_raw_storage(p)
4841
4842 def test_raw_load_singlefloat(self):
4843 if not self.cpu.supports_singlefloats:
4844 py.test.skip("requires singlefloats")
4845 from rpython.rlib import rawstorage
4846 for T in [rffi.FLOAT]:
4847 ops = """
4848 [i0, i1]
4849 i2 = raw_load_i(i0, i1, descr=arraydescr)
4850 finish(i2)
4851 """
4852 arraydescr = self.cpu.arraydescrof(rffi.CArray(T))
4853 p = rawstorage.alloc_raw_storage(31)
4854 for i in range(31):
4855 p[i] = '\xDD'
4856 value = rffi.cast(T, 1.12e20)
4857 rawstorage.raw_storage_setitem(p, 16, value)
4858 got = self.cpu.bh_raw_load_i(rffi.cast(lltype.Signed, p), 16,
4859 arraydescr)
4860 assert got == longlong.singlefloat2int(value)
4861 #
4862 loop = parse(ops, self.cpu, namespace=locals())
4863 looptoken = JitCellToken()
4864 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4865 deadframe = self.cpu.execute_token(looptoken,
4866 rffi.cast(lltype.Signed, p), 16)
4867 result = self.cpu.get_int_value(deadframe, 0)
4868 assert result == longlong.singlefloat2int(value)
4869 rawstorage.free_raw_storage(p)
4870
4871 def test_raw_store_int(self):
4872 from rpython.rlib import rawstorage
4873 for T in [rffi.UCHAR, rffi.SIGNEDCHAR,
4874 rffi.USHORT, rffi.SHORT,
4875 rffi.UINT, rffi.INT,
4876 rffi.UNSIGNED, rffi.SIGNED]:
4877 arraydescr = self.cpu.arraydescrof(rffi.CArray(T))
4878 p = rawstorage.alloc_raw_storage(31)
4879 value = (-0x4243444546474849) & sys.maxint
4880 self.cpu.bh_raw_store_i(rffi.cast(lltype.Signed, p), 16, value,
4881 arraydescr)
4882 result = rawstorage.raw_storage_getitem(T, p, 16)
4883 assert result == rffi.cast(T, value)
4884 rawstorage.free_raw_storage(p)
4885 #
4886 ops = """
4887 [i0, i1, i2]
4888 raw_store(i0, i1, i2, descr=arraydescr)
4889 finish()
4890 """
4891 p = rawstorage.alloc_raw_storage(31)
4892 for i in range(31):
4893 p[i] = '\xDD'
4894 loop = parse(ops, self.cpu, namespace=locals())
4895 looptoken = JitCellToken()
4896 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4897 self.cpu.execute_token(looptoken,
4898 rffi.cast(lltype.Signed, p), 16, value)
4899 result = rawstorage.raw_storage_getitem(T, p, 16)
4900 assert result == rffi.cast(T, value)
4901 rawstorage.free_raw_storage(p)
4902
4903 def test_raw_store_float(self):
4904 if not self.cpu.supports_floats:
4905 py.test.skip("requires floats")
4906 from rpython.rlib import rawstorage
4907 for T in [rffi.DOUBLE]:
4908 arraydescr = self.cpu.arraydescrof(rffi.CArray(T))
4909 p = rawstorage.alloc_raw_storage(31)
4910 value = 1.23e20
4911 self.cpu.bh_raw_store_f(rffi.cast(lltype.Signed, p), 16,
4912 longlong.getfloatstorage(value),
4913 arraydescr)
4914 result = rawstorage.raw_storage_getitem(T, p, 16)
4915 assert result == rffi.cast(T, value)
4916 rawstorage.free_raw_storage(p)
4917 #
4918 ops = """
4919 [i0, i1, f2]
4920 raw_store(i0, i1, f2, descr=arraydescr)
4921 finish()
4922 """
4923 p = rawstorage.alloc_raw_storage(31)
4924 for i in range(31):
4925 p[i] = '\xDD'
4926 loop = parse(ops, self.cpu, namespace=locals())
4927 looptoken = JitCellToken()
4928 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4929 self.cpu.execute_token(looptoken,
4930 rffi.cast(lltype.Signed, p), 16,
4931 longlong.getfloatstorage(value))
4932 result = rawstorage.raw_storage_getitem(T, p, 16)
4933 assert result == rffi.cast(T, value)
4934 rawstorage.free_raw_storage(p)
4935
4936 def test_raw_store_singlefloat(self):
4937 if not self.cpu.supports_singlefloats:
4938 py.test.skip("requires singlefloats")
4939 from rpython.rlib import rawstorage
4940 for T in [rffi.FLOAT]:
4941 arraydescr = self.cpu.arraydescrof(rffi.CArray(T))
4942 p = rawstorage.alloc_raw_storage(31)
4943 value = rffi.cast(T, 1.23e20)
4944 self.cpu.bh_raw_store_i(rffi.cast(lltype.Signed, p), 16,
4945 longlong.singlefloat2int(value),
4946 arraydescr)
4947 result = rawstorage.raw_storage_getitem(T, p, 16)
4948 assert (rffi.cast(lltype.Float, result) ==
4949 rffi.cast(lltype.Float, value))
4950 rawstorage.free_raw_storage(p)
4951 #
4952 ops = """
4953 [i0, i1, i2]
4954 raw_store(i0, i1, i2, descr=arraydescr)
4955 finish()
4956 """
4957 p = rawstorage.alloc_raw_storage(31)
4958 for i in range(31):
4959 p[i] = '\xDD'
4960 loop = parse(ops, self.cpu, namespace=locals())
4961 looptoken = JitCellToken()
4962 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4963 self.cpu.execute_token(looptoken,
4964 rffi.cast(lltype.Signed, p), 16,
4965 longlong.singlefloat2int(value))
4966 result = rawstorage.raw_storage_getitem(T, p, 16)
4967 assert (rffi.cast(lltype.Float, result) ==
4968 rffi.cast(lltype.Float, value))
4969 rawstorage.free_raw_storage(p)
4970
4971 def test_forcing_op_with_fail_arg_in_reg(self):
4972 values = []
4973 def maybe_force(token, flag):
4974 deadframe = self.cpu.force(token)
4975 values.append(self.cpu.get_int_value(deadframe, 0))
4976 return 42
4977
4978 FUNC = self.FuncType([llmemory.GCREF, lltype.Signed], lltype.Signed)
4979 func_ptr = llhelper(lltype.Ptr(FUNC), maybe_force)
4980 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
4981 EffectInfo.MOST_GENERAL)
4982 finaldescr=BasicFinalDescr(0)
4983 faildescr = BasicFailDescr(23)
4984 loop = parse("""
4985 [i0, i1]
4986 p2 = force_token()
4987 i3 = call_may_force_i(ConstClass(func_ptr), p2, i1, descr=calldescr)
4988 guard_not_forced(descr=faildescr) [i3]
4989 finish(i3, descr=finaldescr)
4990 """, namespace=locals())
4991 looptoken = JitCellToken()
4992 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
4993 deadframe = self.cpu.execute_token(looptoken, 20, 0)
4994 fail = self.cpu.get_latest_descr(deadframe)
4995 assert fail.identifier == 23
4996 assert self.cpu.get_int_value(deadframe, 0) == 42
4997
4998 def test_compile_bridge_while_running(self):
4999 def func():
5000 bridge = parse("""
5001 [i1, i2, px]
5002 i3 = int_add(i1, i2)
5003 i4 = int_add(i1, i3)
5004 i5 = int_add(i1, i4)
5005 i6 = int_add(i4, i5)
5006 i7 = int_add(i6, i5)
5007 i8 = int_add(i5, 1)
5008 i9 = int_add(i8, 1)
5009 force_spill(i1)
5010 force_spill(i2)
5011 force_spill(i3)
5012 force_spill(i4)
5013 force_spill(i5)
5014 force_spill(i6)
5015 force_spill(i7)
5016 force_spill(i8)
5017 force_spill(i9)
5018 call_n(ConstClass(func2_ptr), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, descr=calldescr2)
5019 guard_true(i1, descr=guarddescr) [i1, i2, i3, i4, i5, i6, i7, i8, i9, px]
5020 finish(i1, descr=finaldescr)
5021 """, namespace={'finaldescr': finaldescr, 'calldescr2': calldescr2,
5022 'guarddescr': guarddescr, 'func2_ptr': func2_ptr})
5023 self.cpu.compile_bridge(faildescr, bridge.inputargs,
5024 bridge.operations, looptoken)
5025
5026 cpu = self.cpu
5027 finaldescr = BasicFinalDescr(13)
5028 finaldescr2 = BasicFinalDescr(133)
5029 guarddescr = BasicFailDescr(8)
5030
5031 FUNC = self.FuncType([], lltype.Void)
5032 FPTR = self.Ptr(FUNC)
5033 func_ptr = llhelper(FPTR, func)
5034 calldescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
5035 EffectInfo.MOST_GENERAL)
5036
5037 def func2(a, b, c, d, e, f, g, h, i, j, k, l):
5038 print("CALLED")
5039
5040 FUNC2 = self.FuncType([lltype.Signed] * 12, lltype.Void)
5041 FPTR2 = self.Ptr(FUNC2)
5042 func2_ptr = llhelper(FPTR2, func2)
5043 calldescr2 = cpu.calldescrof(FUNC2, FUNC2.ARGS, FUNC2.RESULT,
5044 EffectInfo.MOST_GENERAL)
5045
5046 faildescr = BasicFailDescr(0)
5047
5048 looptoken = JitCellToken()
5049 loop = parse("""
5050 [i0, i1, i2]
5051 call_n(ConstClass(func_ptr), descr=calldescr)
5052 px = force_token()
5053 guard_true(i0, descr=faildescr) [i1, i2, px]
5054 finish(i2, descr=finaldescr2)
5055 """, namespace=locals())
5056 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
5057 frame = self.cpu.execute_token(looptoken, 0, 0, 3)
5058 assert self.cpu.get_latest_descr(frame) is guarddescr
5059
5060 if not isinstance(self.cpu, AbstractLLCPU):
5061 py.test.skip("pointless test on non-asm")
5062
5063 frame = lltype.cast_opaque_ptr(jitframe.JITFRAMEPTR, frame)
5064 assert len(frame.jf_frame) == frame.jf_frame_info.jfi_frame_depth
5065 ref = self.cpu.get_ref_value(frame, 9)
5066 token = lltype.cast_opaque_ptr(jitframe.JITFRAMEPTR, ref)
5067 assert token != frame
5068 token = token.resolve()
5069 assert token == frame
5070
5071 def test_compile_bridge_while_running_guard_no_exc(self):
5072 xtp = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
5073 xtp.subclassrange_min = 1
5074 xtp.subclassrange_max = 3
5075 X = lltype.GcStruct('X', ('parent', rclass.OBJECT),
5076 hints={'vtable': xtp._obj})
5077 xptr = lltype.cast_opaque_ptr(llmemory.GCREF, lltype.malloc(X))
5078 def raising():
5079 bridge = parse("""
5080 [i1, i2]
5081 px = guard_exception(ConstClass(xtp), descr=faildescr2) [i1, i2]
5082 i3 = int_add(i1, i2)
5083 i4 = int_add(i1, i3)
5084 i5 = int_add(i1, i4)
5085 i6 = int_add(i4, i5)
5086 i7 = int_add(i6, i5)
5087 i8 = int_add(i5, 1)
5088 i9 = int_add(i8, 1)
5089 force_spill(i1)
5090 force_spill(i2)
5091 force_spill(i3)
5092 force_spill(i4)
5093 force_spill(i5)
5094 force_spill(i6)
5095 force_spill(i7)
5096 force_spill(i8)
5097 force_spill(i9)
5098 i10 = int_is_true(i9)
5099 guard_true(i10) [i3, i4, i5, i6, i7, i8, i9]
5100 finish(i9, descr=finaldescr)
5101 """, namespace={'finaldescr': BasicFinalDescr(42),
5102 'faildescr2': BasicFailDescr(1),
5103 'xtp': xtp
5104 })
5105 self.cpu.compile_bridge(faildescr, bridge.inputargs,
5106 bridge.operations, looptoken)
5107 raise LLException(xtp, xptr)
5108
5109 faildescr = BasicFailDescr(0)
5110 FUNC = self.FuncType([], lltype.Void)
5111 raising_ptr = llhelper(lltype.Ptr(FUNC), raising)
5112 calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT,
5113 EffectInfo.MOST_GENERAL)
5114
5115 looptoken = JitCellToken()
5116 loop = parse("""
5117 [i0, i1, i2]
5118 call_n(ConstClass(raising_ptr), descr=calldescr)
5119 guard_no_exception(descr=faildescr) [i1, i2]
5120 finish(i2, descr=finaldescr2)
5121 """, namespace={'raising_ptr': raising_ptr,
5122 'calldescr': calldescr,
5123 'faildescr': faildescr,
5124 'finaldescr2': BasicFinalDescr(1)})
5125
5126 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
5127 frame = self.cpu.execute_token(looptoken, 1, 2, 3)
5128 descr = self.cpu.get_latest_descr(frame)
5129 assert descr.identifier == 42
5130 assert not self.cpu.grab_exc_value(frame)
5131
5132 def test_setarrayitem_raw_short(self):
5133 # setarrayitem_raw(140737353744432, 0, 30583, descr=<ArrayS 2>)
5134 A = rffi.CArray(rffi.SHORT)
5135 arraydescr = self.cpu.arraydescrof(A)
5136 a = lltype.malloc(A, 2, flavor='raw')
5137 a[0] = rffi.cast(rffi.SHORT, 666)
5138 a[1] = rffi.cast(rffi.SHORT, 777)
5139 a_int = ptr2int(a)
5140 print('a_int:', a_int)
5141 self.execute_operation(rop.SETARRAYITEM_RAW,
5142 [ConstInt(a_int), ConstInt(0), ConstInt(-7654)],
5143 'void', descr=arraydescr)
5144 assert rffi.cast(lltype.Signed, a[0]) == -7654
5145 assert rffi.cast(lltype.Signed, a[1]) == 777
5146 lltype.free(a, flavor='raw')
5147
5148 def test_gc_indexed_box_plus_large_offset(self):
5149 A = lltype.GcArray(lltype.Signed)
5150 arraydescr = self.cpu.arraydescrof(A)
5151 for offset in [10**8, -10**8]:
5152 loop = parse("""
5153 [p0, i0]
5154 i1 = int_add(i0, %d)
5155 i2 = getarrayitem_gc_i(p0, i1, descr=arraydescr)
5156 finish(i2, descr=finaldescr)
5157 """ % offset, namespace={"finaldescr": BasicFinalDescr(1),
5158 "arraydescr": arraydescr})
5159 looptoken = JitCellToken()
5160 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
5161 a = lltype.malloc(A, 100)
5162 a[42] = 102030
5163 a_ref = lltype.cast_opaque_ptr(llmemory.GCREF, a)
5164 deadframe = self.cpu.execute_token(looptoken, a_ref, 42 - offset)
5165 assert self.cpu.get_int_value(deadframe, 0) == 102030
5166 #
5167 for offset in [10**8, -10**8]:
5168 loop = parse("""
5169 [p0, i0]
5170 i1 = int_add(i0, %d)
5171 setarrayitem_gc(p0, i1, 102030, descr=arraydescr)
5172 finish(0, descr=finaldescr)
5173 """ % offset, namespace={"finaldescr": BasicFinalDescr(1),
5174 "arraydescr": arraydescr})
5175 looptoken = JitCellToken()
5176 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
5177 a = lltype.malloc(A, 100)
5178 a_ref = lltype.cast_opaque_ptr(llmemory.GCREF, a)
5179 self.cpu.execute_token(looptoken, a_ref, 42 - offset)
5180 assert a[42] == 102030
5181
5182 def test_increment_debug_counter(self):
5183 foo = lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw')
5184 foo[0] = 1789200
5185 self.execute_operation(rop.INCREMENT_DEBUG_COUNTER,
5186 [ConstInt(rffi.cast(lltype.Signed, foo))],
5187 'void')
5188 assert foo[0] == 1789201
5189 lltype.free(foo, flavor='raw')
5190
5191 def test_cast_float_to_singlefloat(self):
5192 if not self.cpu.supports_singlefloats:
5193 py.test.skip("requires singlefloats")
5194 res = self.execute_operation(rop.CAST_FLOAT_TO_SINGLEFLOAT,
5195 [boxfloat(12.5)], 'int')
5196 assert res == struct.unpack("I", struct.pack("f", 12.5))[0]
5197
5198 def test_zero_array(self):
5199 if not isinstance(self.cpu, AbstractLLCPU):
5200 py.test.skip("llgraph does not do zero_array")
5201
5202 PAIR = lltype.Struct('PAIR', ('a', lltype.Signed), ('b', lltype.Signed))
5203 for OF in [lltype.Signed, rffi.INT, rffi.SHORT, rffi.UCHAR, PAIR]:
5204 A = lltype.GcArray(OF)
5205 arraydescr = self.cpu.arraydescrof(A)
5206 a = lltype.malloc(A, 100)
5207 a_int = ptr2int(a)
5208 a_ref = lltype.cast_opaque_ptr(llmemory.GCREF, a)
5209 for (start, length) in [(0, 100), (49, 49), (1, 98),
5210 (15, 9), (10, 10), (47, 0),
5211 (0, 4)]:
5212 for cls1 in [ConstInt, InputArgInt]:
5213 for cls2 in [ConstInt, InputArgInt]:
5214 print('a_int:', a_int)
5215 print('of:', OF)
5216 print('start:', cls1.__name__, start)
5217 print('length:', cls2.__name__, length)
5218 for i in range(100):
5219 if OF == PAIR:
5220 a[i].a = a[i].b = -123456789
5221 else:
5222 a[i] = rffi.cast(OF, -123456789)
5223 startbox = cls1(start)
5224 lengthbox = cls2(length)
5225 if cls1 == cls2 and start == length:
5226 lengthbox = startbox # same box!
5227 scale = arraydescr.itemsize
5228 ops = []
5229 def emit(op):
5230 ops.append(op)
5231 helper = GcRewriterAssembler(None, self.cpu)
5232 helper.emit_op = emit
5233 offset = 0
5234 scale_start, s_offset, v_start = \
5235 helper._emit_mul_if_factor_offset_not_supported(
5236 startbox, scale, offset)
5237 if v_start is None:
5238 v_start = ConstInt(s_offset)
5239 scale_len, e_offset, v_len = \
5240 helper._emit_mul_if_factor_offset_not_supported(
5241 lengthbox, scale, offset)
5242 if v_len is None:
5243 v_len = ConstInt(e_offset)
5244 args = [InputArgRef(a_ref), v_start, v_len,
5245 ConstInt(scale_start), ConstInt(scale_len)]
5246 ops.append(ResOperation(rop.ZERO_ARRAY, args,
5247 descr=arraydescr))
5248
5249 scalebox = ConstInt(arraydescr.itemsize)
5250 inputargs, oplist = self._get_operation_list(ops,'void')
5251 self.execute_operations(inputargs, oplist, 'void')
5252 assert len(a) == 100
5253 for i in range(100):
5254 val = (0 if start <= i < start + length
5255 else -123456789)
5256 if OF == PAIR:
5257 assert a[i].a == a[i].b == val
5258 else:
5259 assert a[i] == rffi.cast(OF, val)
5260
5261 def test_jump_float_constant(self):
5262 loop = parse("""
5263 [f0, f1]
5264 label(f0, f1, descr=targettoken)
5265 i2 = cast_float_to_int(f1)
5266 guard_value(i2, 123456, descr=faildescr6) []
5267 f3 = float_add(f0, -0.5)
5268 i4 = float_gt(f3, 9.12)
5269 guard_true(i4, descr=faildescr2) [f1, f3]
5270 jump(f3, 123456.78912, descr=targettoken)
5271 """, namespace={'targettoken': TargetToken(),
5272 'faildescr2': BasicFailDescr(2),
5273 'faildescr6': BasicFailDescr(6)})
5274 looptoken = JitCellToken()
5275 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
5276 deadframe = self.cpu.execute_token(looptoken,
5277 longlong.getfloatstorage(12.25),
5278 longlong.getfloatstorage(123456.01))
5279 fail = self.cpu.get_latest_descr(deadframe)
5280 assert fail.identifier == 2
5281 res = longlong.getrealfloat(self.cpu.get_float_value(deadframe, 0))
5282 assert res == 123456.78912
5283 res = longlong.getrealfloat(self.cpu.get_float_value(deadframe, 1))
5284 assert res == 8.75
5285
5286 def test_passing_guard_gc_type_struct(self):
5287 if not self.cpu.supports_guard_gc_type:
5288 py.test.skip("guard_gc_type not available")
5289 t_box, _, descr = self.alloc_instance(self.T)
5290 c_typeid = ConstInt(descr.get_type_id())
5291 self.execute_operation(rop.GUARD_GC_TYPE, [t_box, c_typeid], 'void')
5292 assert not self.guard_failed
5293 #
5294 got_typeid = self.cpu.get_actual_typeid(t_box.getref_base())
5295 assert got_typeid == c_typeid.getint()
5296
5297 def test_passing_guard_gc_type_array(self):
5298 if not self.cpu.supports_guard_gc_type:
5299 py.test.skip("guard_gc_type not available")
5300 a_box, A = self.alloc_array_of(rffi.SHORT, 342)
5301 arraydescr = self.cpu.arraydescrof(A)
5302 c_typeid = ConstInt(arraydescr.get_type_id())
5303 self.execute_operation(rop.GUARD_GC_TYPE, [a_box, c_typeid], 'void')
5304 assert not self.guard_failed
5305 #
5306 got_typeid = self.cpu.get_actual_typeid(a_box.getref_base())
5307 assert got_typeid == c_typeid.getint()
5308
5309 def test_failing_guard_gc_type(self):
5310 if not self.cpu.supports_guard_gc_type:
5311 py.test.skip("guard_gc_type not available")
5312 t_box, _, tdescr = self.alloc_instance(self.T)
5313 u_box, _, udescr = self.alloc_instance(self.U)
5314 a_box, A = self.alloc_array_of(rffi.SHORT, 342)
5315 adescr = self.cpu.arraydescrof(A)
5316 c_ttypeid = ConstInt(tdescr.get_type_id())
5317 c_utypeid = ConstInt(udescr.get_type_id())
5318 c_atypeid = ConstInt(adescr.get_type_id())
5319 for opname, args in [(rop.GUARD_GC_TYPE, [t_box, c_utypeid]),
5320 (rop.GUARD_GC_TYPE, [u_box, c_ttypeid]),
5321 (rop.GUARD_GC_TYPE, [a_box, c_utypeid]),
5322 (rop.GUARD_GC_TYPE, [t_box, c_atypeid]),
5323 ]:
5324 assert self.execute_operation(opname, args, 'void') == None
5325 assert self.guard_failed
5326 #
5327 got_typeid = self.cpu.get_actual_typeid(args[0].getref_base())
5328 assert got_typeid != args[1].getint()
5329
5330 def test_guard_is_object(self):
5331 if not self.cpu.supports_guard_gc_type:
5332 py.test.skip("guard_gc_type not available")
5333 t_box, _, _ = self.alloc_instance(self.T)
5334 self.execute_operation(rop.GUARD_IS_OBJECT, [t_box], 'void')
5335 assert not self.guard_failed
5336 assert self.cpu.check_is_object(t_box.getref_base())
5337 #
5338 a_box, _ = self.alloc_array_of(rffi.SHORT, 342)
5339 self.execute_operation(rop.GUARD_IS_OBJECT, [a_box], 'void')
5340 assert self.guard_failed
5341 assert not self.cpu.check_is_object(a_box.getref_base())
5342 #
5343 S = lltype.GcStruct('S')
5344 s = lltype.malloc(S, immortal=True, zero=True)
5345 s_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, s))
5346 self.execute_operation(rop.GUARD_IS_OBJECT, [s_box], 'void')
5347 assert self.guard_failed
5348 assert not self.cpu.check_is_object(s_box.getref_base())
5349
5350 def test_guard_subclass(self):
5351 if not self.cpu.supports_guard_gc_type:
5352 py.test.skip("guard_gc_type not available")
5353
5354 xtp = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
5355 xtp.subclassrange_min = 1
5356 xtp.subclassrange_max = 3
5357 X = lltype.GcStruct('X', ('parent', rclass.OBJECT),
5358 hints={'vtable': xtp._obj})
5359 xptr = lltype.malloc(X)
5360 xptr.parent.typeptr = xtp
5361 x_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, xptr))
5362 X_box = ConstInt(ptr2int(xtp))
5363
5364 ytp = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
5365 ytp.subclassrange_min = 2
5366 ytp.subclassrange_max = 2
5367 assert rclass.ll_issubclass(ytp, xtp)
5368 Y = lltype.GcStruct('Y', ('parent', X),
5369 hints={'vtable': ytp._obj})
5370 yptr = lltype.malloc(Y)
5371 yptr.parent.parent.typeptr = ytp
5372 y_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, yptr))
5373 Y_box = ConstInt(ptr2int(ytp))
5374
5375 ztp = lltype.malloc(rclass.OBJECT_VTABLE, immortal=True)
5376 ztp.subclassrange_min = 4
5377 ztp.subclassrange_max = 5
5378 assert not rclass.ll_issubclass(ztp, xtp)
5379 assert not rclass.ll_issubclass(xtp, ztp)
5380 Z = lltype.GcStruct('Z', ('parent', rclass.OBJECT),
5381 hints={'vtable': ztp._obj})
5382 zptr = lltype.malloc(Z)
5383 zptr.parent.typeptr = ztp
5384 z_box = InputArgRef(lltype.cast_opaque_ptr(llmemory.GCREF, zptr))
5385 Z_box = ConstInt(ptr2int(ztp))
5386
5387 for num, arg, klass, is_subclass in [
5388 (1, x_box, X_box, True),
5389 (2, x_box, Y_box, False),
5390 (3, x_box, Z_box, False),
5391 (4, y_box, X_box, True),
5392 (5, y_box, Y_box, True),
5393 (6, y_box, Z_box, False),
5394 (7, z_box, X_box, False),
5395 (8, z_box, Y_box, False),
5396 (9, z_box, Z_box, True),
5397 ]:
5398 self.execute_operation(rop.GUARD_SUBCLASS, [arg, klass], 'void')
5399 assert self.guard_failed == (not is_subclass)
5400
5401 def test_bug_from_optimize_cond_call(self):
5402 loop = parse("""
5403 [i0, i1]
5404 i99 = int_sub(i0, i0)
5405 force_spill(i99)
5406 i2 = int_add(i0, i1)
5407 i3 = int_add(i0, i1)
5408 i4 = int_add(i0, i1)
5409 i5 = int_add(i0, i1)
5410 i6 = int_add(i0, i1)
5411 i7 = int_add(i0, i1)
5412 i8 = int_add(i0, i1)
5413 i9 = int_add(i0, i1)
5414 i10 = int_add(i0, i1)
5415 i11 = int_add(i0, i1)
5416 i12 = int_add(i0, i1)
5417 i13 = int_add(i0, i1)
5418 i14 = int_add(i0, i1)
5419 i15 = int_add(i0, i1)
5420 i16 = int_add(i0, i1)
5421 i17 = int_add(i0, i1)
5422 i18 = int_add(i0, i1)
5423 i19 = int_add(i0, i1)
5424 i20 = int_is_true(i99)
5425 force_spill(i0)
5426 force_spill(i1)
5427 force_spill(i2)
5428 force_spill(i3)
5429 force_spill(i4)
5430 force_spill(i5)
5431 force_spill(i6)
5432 force_spill(i7)
5433 force_spill(i8)
5434 force_spill(i9)
5435 force_spill(i10)
5436 force_spill(i11)
5437 force_spill(i12)
5438 force_spill(i13)
5439 force_spill(i14)
5440 force_spill(i15)
5441 force_spill(i16)
5442 force_spill(i17)
5443 force_spill(i18)
5444 force_spill(i19)
5445 finish(i20, descr=finaldescr)
5446 """, namespace={"finaldescr": BasicFinalDescr(1)})
5447 looptoken = JitCellToken()
5448 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
5449 deadframe = self.cpu.execute_token(looptoken, 40, 2)
5450 fail = self.cpu.get_latest_descr(deadframe)
5451 res = self.cpu.get_int_value(deadframe, 0)
5452 assert res == 0
5453
5454 def test_load_from_gc_table_many(self):
5455 # Test that 'load_from_gc_table' handles a table of NUM entries.
5456 # Done by writing NUM setfield_gc on constants. Each one
5457 # requires a load_from_gc_table. The value of NUM is choosen
5458 # so that not all of them fit into the ARM's 4096-bytes offset.
5459 NUM = 1025
5460 S = lltype.GcStruct('S', ('x', lltype.Signed))
5461 fielddescr = self.cpu.fielddescrof(S, 'x')
5462 table = [lltype.malloc(S) for i in range(NUM)]
5463 looptoken = JitCellToken()
5464 targettoken = TargetToken()
5465 ops = [
5466 '[]',
5467 ]
5468 namespace = {'fielddescr': fielddescr,
5469 'finaldescr': BasicFinalDescr(5)}
5470 for i, s in enumerate(table):
5471 ops.append('setfield_gc(ConstPtr(ptr%d), %d, descr=fielddescr)'
5472 % (i, i))
5473 namespace['ptr%d' % i] = lltype.cast_opaque_ptr(llmemory.GCREF, s)
5474 ops.append('finish(descr=finaldescr)')
5475
5476 loop = parse('\n'.join(ops), namespace=namespace)
5477
5478 self.cpu.compile_loop(loop.inputargs, loop.operations, looptoken)
5479 deadframe = self.cpu.execute_token(looptoken)
5480 fail = self.cpu.get_latest_descr(deadframe)
5481 assert fail.identifier == 5
5482
5483 # check that all setfield_gc() worked
5484 for i, s in enumerate(table):
5485 assert s.x == i