blob: 4125ea981ec1543ae00dfb71ebe65ced9c399180 [file] [log] [blame]
Chandler Carruth06a5dd62015-01-12 04:43:18 +00001#!/usr/bin/env python2.7
2
3"""A test case update script.
4
5This script is a utility to update LLVM X86 'llc' based test cases with new
6FileCheck patterns. It can either update all of the tests in the file or
7a single test function.
8"""
9
10import argparse
11import itertools
12import string
13import subprocess
14import sys
15import tempfile
16import re
17
18
19def llc(args, cmd_args, ir):
20 with open(ir) as ir_file:
21 stdout = subprocess.check_output(args.llc_binary + ' ' + cmd_args,
22 shell=True, stdin=ir_file)
23 return stdout
24
25
26ASM_SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M)
27ASM_SCRUB_SHUFFLES_RE = (
28 re.compile(
29 r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem) = .*)$',
30 flags=re.M))
31ASM_SCRUB_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
32ASM_SCRUB_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
33ASM_SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
34
35
36def scrub_asm(asm):
37 # Scrub runs of whitespace out of the assembly, but leave the leading
38 # whitespace in place.
39 asm = ASM_SCRUB_WHITESPACE_RE.sub(r' ', asm)
40 # Expand the tabs used for indentation.
41 asm = string.expandtabs(asm, 2)
42 # Detect shuffle asm comments and hide the operands in favor of the comments.
43 asm = ASM_SCRUB_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
44 # Generically match the stack offset of a memory operand.
45 asm = ASM_SCRUB_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
46 # Generically match a RIP-relative memory operand.
47 asm = ASM_SCRUB_RIP_RE.sub(r'{{.*}}(%rip)', asm)
48 # Strip kill operands inserted into the asm.
49 asm = ASM_SCRUB_KILL_COMMENT_RE.sub('', asm)
50 return asm
51
52
53def main():
54 parser = argparse.ArgumentParser(description=__doc__)
55 parser.add_argument('-v', '--verbose', action='store_true',
56 help='Show verbose output')
57 parser.add_argument('--llc-binary', default='llc',
58 help='The "llc" binary to use to generate the test case')
59 parser.add_argument(
60 '--function', help='The function in the test file to update')
61 parser.add_argument('tests', nargs='+')
62 args = parser.parse_args()
63
64 run_line_re = re.compile('^\s*;\s*RUN:\s*(.*)$')
65 ir_function_re = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@(\w+)\s*\(')
66 asm_function_re = re.compile(
67 r'^_?(?P<f>[^:]+):[ \t]*#+[ \t]*@(?P=f)\n[^:]*?'
68 r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
69 r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.(?:sub)?section)',
70 flags=(re.M | re.S))
71 check_prefix_re = re.compile('--check-prefix=(\S+)')
72 check_re = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
73
74 for test in args.tests:
75 if args.verbose:
76 print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
77 with open(test) as f:
78 test_lines = [l.rstrip() for l in f]
79
80 run_lines = [m.group(1)
81 for m in [run_line_re.match(l) for l in test_lines] if m]
82 if args.verbose:
83 print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
84 for l in run_lines:
85 print >>sys.stderr, ' RUN: ' + l
86
87 checks = []
88 for l in run_lines:
89 (llc_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
90 if not llc_cmd.startswith('llc '):
91 print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l
92 continue
93
94 if not filecheck_cmd.startswith('FileCheck '):
95 print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
96 continue
97
98 llc_cmd_args = llc_cmd[len('llc'):].strip()
99 llc_cmd_args = llc_cmd_args.replace('< %s', '').replace('%s', '').strip()
100
101 check_prefixes = [m.group(1)
102 for m in check_prefix_re.finditer(filecheck_cmd)]
103 if not check_prefixes:
104 check_prefixes = ['CHECK']
105
106 # FIXME: We should use multiple check prefixes to common check lines. For
107 # now, we just ignore all but the last.
108 checks.append((check_prefixes, llc_cmd_args))
109
110 asm = {}
111 for prefixes, _ in checks:
112 for prefix in prefixes:
113 asm.update({prefix: dict()})
114 for prefixes, llc_args in checks:
115 if args.verbose:
116 print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args
117 print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
118 raw_asm = llc(args, llc_args, test)
119 # Build up a dictionary of all the function bodies.
120 for m in asm_function_re.finditer(raw_asm):
121 if not m:
122 continue
123 f = m.group('f')
124 f_asm = scrub_asm(m.group('body'))
125 if args.verbose:
126 print >>sys.stderr, 'Processing asm for function: ' + f
127 for l in f_asm.splitlines():
128 print >>sys.stderr, ' ' + l
129 for prefix in prefixes:
130 if f in asm[prefix] and asm[prefix][f] != f_asm:
131 if prefix == prefixes[-1]:
132 print >>sys.stderr, ('WARNING: Found conflicting asm under the '
133 'same prefix!')
134 else:
135 asm[prefix][f] = None
136 continue
137
138 asm[prefix][f] = f_asm
139
140 is_in_function = False
141 is_in_function_start = False
142 prefix_set = set([prefix for prefixes, _ in checks for prefix in prefixes])
143 if args.verbose:
144 print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
145 fixed_lines = []
146 for l in test_lines:
147 if is_in_function_start:
148 if l.lstrip().startswith(';'):
149 m = check_re.match(l)
150 if not m or m.group(1) not in prefix_set:
151 fixed_lines.append(l)
152 continue
153
154 # Print out the various check lines here
155 printed_prefixes = []
156 for prefixes, _ in checks:
157 for prefix in prefixes:
158 if prefix in printed_prefixes:
159 break
160 if not asm[prefix][name]:
161 continue
162 if len(printed_prefixes) != 0:
163 fixed_lines.append(';')
164 printed_prefixes.append(prefix)
165 fixed_lines.append('; %s-LABEL: %s:' % (prefix, name))
166 asm_lines = asm[prefix][name].splitlines()
167 fixed_lines.append('; %s: %s' % (prefix, asm_lines[0]))
168 for asm_line in asm_lines[1:]:
169 fixed_lines.append('; %s-NEXT: %s' % (prefix, asm_line))
170 break
171 is_in_function_start = False
172
173 if is_in_function:
174 # Skip any blank comment lines in the IR.
175 if l.strip() == ';':
176 continue
177 # And skip any CHECK lines. We'll build our own.
178 m = check_re.match(l)
179 if m and m.group(1) in prefix_set:
180 continue
181 # Collect the remaining lines in the function body and look for the end
182 # of the function.
183 fixed_lines.append(l)
184 if l.strip() == '}':
185 is_in_function = False
186 continue
187
188 fixed_lines.append(l)
189
190 m = ir_function_re.match(l)
191 if not m:
192 continue
193 name = m.group(1)
194 if args.function is not None and name != args.function:
195 # When filtering on a specific function, skip all others.
196 continue
197 is_in_function = is_in_function_start = True
198
199 if args.verbose:
200 print>>sys.stderr, 'Writing %d fixed lines to %s...' % (
201 len(fixed_lines), test)
202 with open(test, 'w') as f:
203 f.writelines([l + '\n' for l in fixed_lines])
204
205
206if __name__ == '__main__':
207 main()