Debian Codegraph @

rpython/jit/backend/x86/test/test_rx86_32_auto_encoding.py

raw symbols SCIP
1 import sys, os, random, struct
2 import py
3 from rpython.jit.backend.x86 import rx86
4 from rpython.rlib.rarithmetic import intmask
5 from rpython.tool.udir import udir
6
7 INPUTNAME = 'checkfile_%s.s'
8 FILENAME = 'checkfile_%s.o'
9 BEGIN_TAG = '<<<rx86-test-begin>>>'
10 END_TAG = '<<<rx86-test-end>>>'
11
12 class CodeCheckerMixin(object):
13 def __init__(self, expected, accept_unnecessary_prefix):
14 self.expected = expected
15 self.accept_unnecessary_prefix = accept_unnecessary_prefix
16 self.index = 0
17
18 def begin(self, op):
19 self.op = op
20 self.instrindex = self.index
21
22 def writechar(self, char):
23 if char != self.expected[self.index:self.index+1]:
24 if (char == self.accept_unnecessary_prefix
25 and self.index == self.instrindex):
26 return # ignore the extra character '\x40'
27 print self.op
28 print "\x09from rx86.py:", hexdump(self.expected[self.instrindex:self.index] + char)+"..."
29 print "\x09from 'as': ", hexdump(self.expected[self.instrindex:self.index+15])+"..."
30 raise Exception("Differs")
31 self.index += 1
32
33 def done(self):
34 assert len(self.expected) == self.index
35
36 def stack_frame_size_delta(self, delta):
37 pass # ignored
38
39 def check_stack_size_at_ret(self):
40 pass # ignored
41
42 def hexdump(s):
43 return ' '.join(["%02X" % ord(c) for c in s])
44
45 def reduce_to_32bit(s):
46 if s[:2] != '%r':
47 return s
48 if s[2:].isdigit():
49 return s + 'd'
50 else:
51 return '%e' + s[2:]
52
53 # ____________________________________________________________
54
55 COUNT1 = 15
56 suffixes = {0:'', 1:'b', 2:'w', 4:'l', 8:'q'}
57
58
59 class TestRx86_32(object):
60 WORD = 4
61 TESTDIR = 'rx86_32'
62 X86_CodeBuilder = rx86.X86_32_CodeBuilder
63 REGNAMES = ['%eax', '%ecx', '%edx', '%ebx', '%esp', '%ebp', '%esi', '%edi']
64 REGNAMES8 = ['%al', '%cl', '%dl', '%bl', '%ah', '%ch', '%dh', '%bh']
65 XMMREGNAMES = ['%%xmm%d' % i for i in range(16)]
66 REGS = range(8)
67 REGS8 = [i|rx86.BYTE_REG_FLAG for i in range(8)]
68 NONSPECREGS = [rx86.R.eax, rx86.R.ecx, rx86.R.edx, rx86.R.ebx,
69 rx86.R.esi, rx86.R.edi]
70 accept_unnecessary_prefix = None
71 methname = '?'
72
73 def reg_tests(self):
74 return self.REGS
75
76 def reg8_tests(self):
77 return self.REGS8
78
79 def xmm_reg_tests(self):
80 return self.reg_tests()
81
82 def stack_bp_tests(self, count=COUNT1):
83 return ([0, 4, -4, 124, 128, -128, -132] +
84 [random.randrange(-0x20000000, 0x20000000) * 4
85 for i in range(count)])
86
87 def stack_sp_tests(self, count=COUNT1):
88 return ([0, 4, 124, 128] +
89 [random.randrange(0, 0x20000000) * 4
90 for i in range(count)])
91
92 def memory_tests(self):
93 return [(reg, ofs)
94 for reg in self.NONSPECREGS
95 for ofs in self.stack_bp_tests(5)
96 ]
97
98 def array_tests(self):
99 return [(reg1, reg2, scaleshift, ofs)
100 for reg1 in self.NONSPECREGS
101 for reg2 in self.NONSPECREGS
102 for scaleshift in [0, 1, 2, 3]
103 for ofs in self.stack_bp_tests(1)
104 ]
105
106 def imm8_tests(self):
107 v = ([-128,-1,0,1,127] +
108 [random.randrange(-127, 127) for i in range(COUNT1)])
109 return v
110
111 def imm32_tests(self):
112 v = ([-0x80000000, 0x7FFFFFFF, 128, 256, -129, -255] +
113 [random.randrange(-32768,32768)<<16 |
114 random.randrange(0,65536) for i in range(COUNT1)] +
115 [random.randrange(128, 256) for i in range(COUNT1)])
116 return self.imm8_tests() + v
117
118 def relative_tests(self):
119 py.test.skip("explicit test required for %r" % (self.methname,))
120
121 def get_all_tests(self):
122 return {
123 'r': self.reg_tests,
124 'r8': self.reg8_tests,
125 'x': self.xmm_reg_tests,
126 'b': self.stack_bp_tests,
127 's': self.stack_sp_tests,
128 'm': self.memory_tests,
129 'a': self.array_tests,
130 'i': self.imm32_tests,
131 'i8': self.imm8_tests,
132 'j': self.imm32_tests,
133 'l': self.relative_tests,
134 }
135
136 def assembler_operand_reg(self, regnum):
137 return self.REGNAMES[regnum]
138
139 def assembler_operand_reg8(self, regnum):
140 assert regnum & rx86.BYTE_REG_FLAG
141 return self.REGNAMES8[regnum &~ rx86.BYTE_REG_FLAG]
142
143 def assembler_operand_xmm_reg(self, regnum):
144 return self.XMMREGNAMES[regnum]
145
146 def assembler_operand_stack_bp(self, position):
147 return '%d(%s)' % (position, self.REGNAMES[5])
148
149 def assembler_operand_stack_sp(self, position):
150 return '%d(%s)' % (position, self.REGNAMES[4])
151
152 def assembler_operand_memory(self, (reg1, offset)):
153 if not offset: offset = ''
154 return '%s(%s)' % (offset, self.REGNAMES[reg1])
155
156 def assembler_operand_array(self, (reg1, reg2, scaleshift, offset)):
157 if not offset: offset = ''
158 return '%s(%s,%s,%d)' % (offset, self.REGNAMES[reg1],
159 self.REGNAMES[reg2], 1<<scaleshift)
160
161 def assembler_operand_imm(self, value):
162 return '$%d' % value
163
164 def assembler_operand_imm_addr(self, value):
165 return '%d' % value
166
167 def get_all_assembler_operands(self):
168 return {
169 'r': self.assembler_operand_reg,
170 'r8': self.assembler_operand_reg8,
171 'x': self.assembler_operand_xmm_reg,
172 'b': self.assembler_operand_stack_bp,
173 's': self.assembler_operand_stack_sp,
174 'm': self.assembler_operand_memory,
175 'a': self.assembler_operand_array,
176 'i': self.assembler_operand_imm,
177 'i8': self.assembler_operand_imm,
178 'j': self.assembler_operand_imm_addr,
179 }
180
181 def run_test(self, methname, instrname, argmodes, args_lists,
182 instr_suffix=None):
183 global labelcount
184 labelcount = 0
185 oplist = []
186 testdir = udir.ensure(self.TESTDIR, dir=1)
187 inputname = str(testdir.join(INPUTNAME % methname))
188 filename = str(testdir.join(FILENAME % methname))
189 g = open(inputname, 'w')
190 g.write('\x09.string "%s"\n' % BEGIN_TAG)
191 #
192 if instrname == 'MOVDQ':
193 if self.WORD == 8:
194 instrname = 'MOVQ'
195 else:
196 instrname = 'MOVD'
197 if argmodes == 'xb':
198 py.test.skip('"as" uses an undocumented alternate encoding??')
199 if argmodes == 'xx' and self.WORD != 8:
200 instrname = 'MOVQ'
201 #
202 for args in args_lists:
203 suffix = ""
204 if (argmodes and not self.is_xmm_insn
205 and not instrname.startswith('FSTP')
206 and not instrname.startswith('FLD')):
207 suffix = suffixes[self.WORD]
208 # Special case: On 64-bit CPUs, rx86 assumes 64-bit integer
209 # operands when converting to/from floating point, so we need to
210 # indicate that with a suffix
211 if (self.WORD == 8) and (instrname.startswith('CVT') and
212 'SI' in instrname):
213 suffix = suffixes[self.WORD]
214
215 if instr_suffix is not None:
216 suffix = instr_suffix # overwrite
217
218 following = ""
219 if False: # instr.indirect:
220 suffix = ""
221 if args[-1][0] == i386.REL32: #in (i386.REL8,i386.REL32):
222 labelcount += 1
223 following = "\nL%d:" % labelcount
224 elif args[-1][0] in (i386.IMM8,i386.IMM32):
225 args = list(args)
226 args[-1] = ("%d", args[-1][1]) # no '$' sign
227 else:
228 suffix += " *"
229 k = -1
230 else:
231 k = len(args)
232 #for m, extra in args[:k]:
233 # assert m != i386.REL32 #not in (i386.REL8,i386.REL32)
234 assembler_operand = self.get_all_assembler_operands()
235 ops = []
236 for mode, v in zip(argmodes, args):
237 ops.append(assembler_operand[mode](v))
238 ops.reverse()
239 #
240 if (instrname.lower() == 'mov' and suffix == 'q' and
241 ops[0].startswith('$') and 0 <= int(ops[0][1:]) <= 4294967295
242 and ops[1].startswith('%r')):
243 # movq $xxx, %rax => movl $xxx, %eax
244 suffix = 'l'
245 ops[1] = reduce_to_32bit(ops[1])
246 #
247 op = '\t%s%s %s%s' % (instrname.lower(), suffix,
248 ', '.join(ops), following)
249 g.write('%s\n' % op)
250 oplist.append(op)
251 g.write('\t.string "%s"\n' % END_TAG)
252 g.close()
253 f, g = os.popen4('as --%d "%s" -o "%s"' %
254 (self.WORD*8, inputname, filename), 'r')
255 f.close()
256 got = g.read()
257 g.close()
258 error = [line for line in got.splitlines() if 'error' in line.lower()]
259 if error:
260 if (sys.maxint <= 2**32 and
261 'no compiled in support for x86_64' in error[0]):
262 py.test.skip(error)
263 raise Exception("Assembler got an error: %r" % error[0])
264 error = [line for line in got.splitlines()
265 if 'warning' in line.lower()]
266 if error:
267 raise Exception("Assembler got a warning: %r" % error[0])
268 try:
269 f = open(filename, 'rb')
270 except IOError:
271 raise Exception("Assembler did not produce output?")
272 data = f.read()
273 f.close()
274 i = data.find(BEGIN_TAG)
275 assert i>=0
276 j = data.find(END_TAG, i)
277 assert j>=0
278 as_code = data[i+len(BEGIN_TAG)+1:j]
279 return oplist, as_code
280
281 def make_all_tests(self, methname, modes, args=[]):
282 if modes:
283 tests = self.get_all_tests()
284 m = modes[0]
285 if m == 'p' and self.WORD == 4:
286 return []
287 lst = tests[m]()
288 random.shuffle(lst)
289 if methname == 'PSRAD_xi' and m == 'i':
290 lst = [x for x in lst if 0 <= x <= 31]
291 result = []
292 for v in lst:
293 result += self.make_all_tests(methname, modes[1:], args+[v])
294 return result
295 else:
296 # special cases
297 if methname in ('ADD_ri', 'AND_ri', 'CMP_ri', 'OR_ri',
298 'SUB_ri', 'XOR_ri', 'SBB_ri'):
299 if args[0] == rx86.R.eax:
300 return [] # ADD EAX, constant: there is a special encoding
301 if methname in ('CMP8_ri',):
302 if args[0] == rx86.R.al:
303 return [] # CMP AL, constant: there is a special encoding
304 if methname == 'XCHG_rr' and rx86.R.eax in args:
305 return [] # special encoding
306 if methname == 'MOV_rj' and args[0] == rx86.R.eax:
307 return [] # MOV EAX, [immediate]: there is a special encoding
308 if methname == 'MOV_jr' and args[1] == rx86.R.eax:
309 return [] # MOV [immediate], EAX: there is a special encoding
310 if methname == 'MOV8_rj' and args[0] == rx86.R.al:
311 return [] # MOV AL, [immediate]: there is a special encoding
312 if methname == 'MOV8_jr' and args[1] == rx86.R.al:
313 return [] # MOV [immediate], AL: there is a special encoding
314 if methname == 'TEST_ri' and args[0] == rx86.R.eax:
315 return [] # TEST EAX, constant: there is a special encoding
316
317 return [args]
318
319 def get_code_checker_class(self):
320 class X86_CodeBuilder(CodeCheckerMixin, self.X86_CodeBuilder):
321 pass
322 return X86_CodeBuilder
323
324 def should_skip_instruction(self, instrname, argmodes):
325 is_artificial_instruction = (argmodes != '' and argmodes[-1].isdigit())
326 is_artificial_instruction |= (instrname[-1].isdigit() and
327 instrname[-1] != '8')
328 return (
329 is_artificial_instruction or
330 # XXX: Can't tests shifts automatically at the moment
331 (instrname[:3] in ('SHL', 'SAR', 'SHR')) or
332 # CALL_j is actually relative, so tricky to test
333 (instrname == 'CALL' and argmodes == 'j') or
334 # SET_ir must be tested manually
335 (instrname == 'SET' and argmodes == 'ir') or
336 # MULTIBYTE_NOPs can't easily be tested the same way
337 (instrname == 'MULTIBYTE')
338 )
339
340 def should_skip_instruction_bit32(self, instrname, argmodes):
341 if self.WORD != 8:
342 # those are tested in the 64 bit test case
343 return (
344 # the test suite uses 64 bit registers instead of 32 bit...
345 (instrname == 'PEXTRQ') or
346 (instrname == 'PINSRQ')
347 )
348
349 return False
350
351
352 def complete_test(self, methname):
353 if '_' in methname:
354 instrname, argmodes = methname.split('_')
355 else:
356 instrname, argmodes = methname, ''
357
358 if self.should_skip_instruction(instrname, argmodes) or \
359 self.should_skip_instruction_bit32(instrname, argmodes):
360 print "Skipping %s" % methname
361 return
362
363 # XXX: ugly way to deal with the differences between 32 and 64 bit
364 if not hasattr(self.X86_CodeBuilder, methname):
365 return
366
367 # XXX: hack hack hack
368 if methname == 'WORD':
369 return
370
371 if instrname.endswith('8'):
372 instrname = instrname[:-1]
373 if instrname == 'MOVSX' or instrname == 'MOVZX':
374 instr_suffix = 'b' + suffixes[self.WORD]
375 instrname = instrname[:-1]
376 if argmodes[1] == 'r':
377 argmodes = [argmodes[0], 'r8']
378 else:
379 instr_suffix = 'b'
380 realargmodes = []
381 for mode in argmodes:
382 if mode == 'r':
383 mode = 'r8'
384 elif mode == 'i':
385 mode = 'i8'
386 realargmodes.append(mode)
387 argmodes = realargmodes
388 elif instrname == 'CALL' or instrname == 'JMP':
389 instr_suffix = suffixes[self.WORD] + ' *'
390 else:
391 instr_suffix = None
392
393 if instrname.find('EXTR') != -1 or \
394 instrname.find('INSR') != -1 or \
395 instrname.find('INSERT') != -1 or \
396 instrname.find('EXTRACT') != -1 or \
397 instrname.find('SRLDQ') != -1 or \
398 instrname.find('SHUF') != -1 or \
399 instrname.find('PBLEND') != -1 or \
400 instrname.find('CMPP') != -1:
401 realargmodes = []
402 for mode in argmodes:
403 if mode == 'i':
404 mode = 'i8'
405 realargmodes.append(mode)
406 argmodes = realargmodes
407
408 print "Testing %s with argmodes=%r" % (instrname, argmodes)
409 self.methname = methname
410 self.is_xmm_insn = getattr(getattr(self.X86_CodeBuilder,
411 methname), 'is_xmm_insn', False)
412 ilist = self.make_all_tests(methname, argmodes)
413 oplist, as_code = self.run_test(methname, instrname, argmodes, ilist,
414 instr_suffix)
415 cls = self.get_code_checker_class()
416 cc = cls(as_code, self.accept_unnecessary_prefix)
417 for op, args in zip(oplist, ilist):
418 if op:
419 cc.begin(op)
420 getattr(cc, methname)(*args)
421 cc.done()
422
423 def setup_class(cls):
424 import os
425 g = os.popen('as -version </dev/null -o /dev/null 2>&1')
426 data = g.read()
427 g.close()
428 if not data.startswith('GNU assembler'):
429 py.test.skip("full tests require the GNU 'as' assembler")
430
431 def test_all(self):
432 for name in rx86.all_instructions:
433 yield self.complete_test, name