blob: 9458273a5953691d01c12c81bae206dae7c327d5 [file] [log] [blame]
Sanjay Patelfff7a3d2016-03-24 23:19:26 +00001#!/usr/bin/env python2.7
2
3"""A test case update script.
4
5This script is a utility to update LLVM opt or llc 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 os # Used to advertise this file's name ("autogenerated_note").
13import string
14import subprocess
15import sys
16import tempfile
17import re
18
19
20# RegEx: this is where the magic happens.
21
Sanjay Pateld8592712016-03-27 20:43:02 +000022SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)')
Sanjay Patelfff7a3d2016-03-24 23:19:26 +000023SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M)
24SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
25SCRUB_X86_SHUFFLES_RE = (
26 re.compile(
27 r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem) = .*)$',
28 flags=re.M))
29SCRUB_X86_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
30SCRUB_X86_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
31SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
32SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*')
33
34RUN_LINE_RE = re.compile('^\s*;\s*RUN:\s*(.*)$')
Sanjay Patele54e6f52016-03-25 17:00:12 +000035IR_FUNCTION_RE = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@([\w-]+)\s*\(')
Sanjay Patelfff7a3d2016-03-24 23:19:26 +000036LLC_FUNCTION_RE = re.compile(
37 r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@(?P=func)\n[^:]*?'
38 r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
39 r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)',
40 flags=(re.M | re.S))
41OPT_FUNCTION_RE = re.compile(
Sanjay Patele54e6f52016-03-25 17:00:12 +000042 r'^\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w-]+?)\s*\('
Sanjay Patelfff7a3d2016-03-24 23:19:26 +000043 r'(\s+)?[^{]*\{\n(?P<body>.*?)\}',
44 flags=(re.M | re.S))
45CHECK_PREFIX_RE = re.compile('--check-prefix=(\S+)')
46CHECK_RE = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
47IR_VALUE_DEF_RE = re.compile(r'\s+%(.*) =')
48
49
50# Invoke the tool that is being tested.
51def invoke_tool(args, cmd_args, ir):
52 with open(ir) as ir_file:
53 stdout = subprocess.check_output(args.tool_binary + ' ' + cmd_args,
54 shell=True, stdin=ir_file)
55 # Fix line endings to unix CR style.
56 stdout = stdout.replace('\r\n', '\n')
57 return stdout
58
59
60# FIXME: Separate the x86-specific scrubbers, so this can be used for other targets.
61def scrub_asm(asm):
62 # Detect shuffle asm comments and hide the operands in favor of the comments.
63 asm = SCRUB_X86_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
64 # Generically match the stack offset of a memory operand.
65 asm = SCRUB_X86_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
66 # Generically match a RIP-relative memory operand.
67 asm = SCRUB_X86_RIP_RE.sub(r'{{.*}}(%rip)', asm)
68 # Strip kill operands inserted into the asm.
69 asm = SCRUB_KILL_COMMENT_RE.sub('', asm)
70 return asm
71
72
73def scrub_body(body, tool_basename):
74 # Scrub runs of whitespace out of the assembly, but leave the leading
75 # whitespace in place.
76 body = SCRUB_WHITESPACE_RE.sub(r' ', body)
77 # Expand the tabs used for indentation.
78 body = string.expandtabs(body, 2)
79 # Strip trailing whitespace.
80 body = SCRUB_TRAILING_WHITESPACE_RE.sub(r'', body)
81 if tool_basename == "llc":
82 body = scrub_asm(body)
83 return body
84
85
86# Build up a dictionary of all the function bodies.
87def build_function_body_dictionary(raw_tool_output, prefixes, func_dict, verbose, tool_basename):
88 if tool_basename == "llc":
89 func_regex = LLC_FUNCTION_RE
90 else:
91 func_regex = OPT_FUNCTION_RE
92 for m in func_regex.finditer(raw_tool_output):
93 if not m:
94 continue
95 func = m.group('func')
96 scrubbed_body = scrub_body(m.group('body'), tool_basename)
97 if func.startswith('stress'):
98 # We only use the last line of the function body for stress tests.
99 scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
100 if verbose:
101 print >>sys.stderr, 'Processing function: ' + func
102 for l in scrubbed_body.splitlines():
103 print >>sys.stderr, ' ' + l
104 for prefix in prefixes:
105 if func in func_dict[prefix] and func_dict[prefix][func] != scrubbed_body:
106 if prefix == prefixes[-1]:
107 print >>sys.stderr, ('WARNING: Found conflicting asm under the '
108 'same prefix: %r!' % (prefix,))
109 else:
110 func_dict[prefix][func] = None
111 continue
112
113 func_dict[prefix][func] = scrubbed_body
114
115
116# Create a FileCheck variable name based on an IR name.
117def get_value_name(var):
118 if var.isdigit():
119 var = 'TMP' + var
120 var = var.replace('.', '_')
121 return var.upper()
122
123
124# Create a FileCheck variable from regex.
125def get_value_definition(var):
126 return '[[' + get_value_name(var) + ':%.*]]'
127
128
129# Use a FileCheck variable.
130def get_value_use(var):
131 return '[[' + get_value_name(var) + ']]'
132
133
134# Replace IR value defs and uses with FileCheck variables.
135def genericize_check_lines(lines):
136 lines_with_def = []
137 vars_seen = []
138 for line in lines:
Sanjay Patel17681172016-03-27 20:44:35 +0000139 # An IR variable named '%.' matches the FileCheck regex string.
140 line = line.replace('%.', '%dot')
Sanjay Patelfff7a3d2016-03-24 23:19:26 +0000141 m = IR_VALUE_DEF_RE.match(line)
142 if m:
143 vars_seen.append(m.group(1))
144 line = line.replace('%' + m.group(1), get_value_definition(m.group(1)))
145
146 lines_with_def.append(line)
147
148 # A single def isn't worth replacing?
149 #if len(vars_seen) < 2:
150 # return lines
151
152 output_lines = []
153 vars_seen.sort(key=len, reverse=True)
154 for line in lines_with_def:
155 for var in vars_seen:
156 line = line.replace('%' + var, get_value_use(var))
157 output_lines.append(line)
158
159 return output_lines
160
161
162def add_checks(output_lines, prefix_list, func_dict, func_name, tool_basename):
163 # Select a label format based on the whether we're checking asm or IR.
164 if tool_basename == "llc":
165 check_label_format = "; %s-LABEL: %s:"
166 else:
167 check_label_format = "; %s-LABEL: @%s("
168
169 printed_prefixes = []
170 for checkprefixes, _ in prefix_list:
171 for checkprefix in checkprefixes:
172 if checkprefix in printed_prefixes:
173 break
174 if not func_dict[checkprefix][func_name]:
175 continue
176 # Add some space between different check prefixes, but not after the last
177 # check line (before the test code).
178 #if len(printed_prefixes) != 0:
179 # output_lines.append(';')
180 printed_prefixes.append(checkprefix)
181 output_lines.append(check_label_format % (checkprefix, func_name))
182 func_body = func_dict[checkprefix][func_name].splitlines()
183
184 # For IR output, change all defs to FileCheck variables, so we're immune
185 # to variable naming fashions.
186 if tool_basename == "opt":
187 func_body = genericize_check_lines(func_body)
188
Sanjay Patel96241e72016-04-05 16:49:07 +0000189 # This could be selectively enabled with an optional invocation argument.
190 # Disabled for now: better to check everything. Be safe rather than sorry.
191
Sanjay Patelfff7a3d2016-03-24 23:19:26 +0000192 # Handle the first line of the function body as a special case because
193 # it's often just noise (a useless asm comment or entry label).
Sanjay Patel96241e72016-04-05 16:49:07 +0000194 #if func_body[0].startswith("#") or func_body[0].startswith("entry:"):
195 # is_blank_line = True
196 #else:
197 # output_lines.append('; %s: %s' % (checkprefix, func_body[0]))
198 # is_blank_line = False
Sanjay Patelfff7a3d2016-03-24 23:19:26 +0000199
Sanjay Patel96241e72016-04-05 16:49:07 +0000200 # For llc tests, there may be asm directives between the label and the
201 # first checked line (most likely that first checked line is "# BB#0").
202 if tool_basename == "opt":
203 is_blank_line = False
204 else:
205 is_blank_line = True;
206
207 for func_line in func_body:
Sanjay Patelfff7a3d2016-03-24 23:19:26 +0000208 if func_line.strip() == '':
209 is_blank_line = True
210 continue
211 # Do not waste time checking IR comments.
212 if tool_basename == "opt":
213 func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line)
214
215 # Skip blank lines instead of checking them.
216 if is_blank_line == True:
217 output_lines.append('; %s: %s' % (checkprefix, func_line))
218 else:
219 output_lines.append('; %s-NEXT: %s' % (checkprefix, func_line))
220 is_blank_line = False
221
222 # Add space between different check prefixes and also before the first
223 # line of code in the test function.
224 output_lines.append(';')
225 break
226 return output_lines
227
228
229def should_add_line_to_output(input_line, prefix_set):
230 # Skip any blank comment lines in the IR.
231 if input_line.strip() == ';':
232 return False
233 # Skip any blank lines in the IR.
234 #if input_line.strip() == '':
235 # return False
236 # And skip any CHECK lines. We're building our own.
237 m = CHECK_RE.match(input_line)
238 if m and m.group(1) in prefix_set:
239 return False
240
241 return True
242
243
244def main():
245 parser = argparse.ArgumentParser(description=__doc__)
246 parser.add_argument('-v', '--verbose', action='store_true',
247 help='Show verbose output')
248 parser.add_argument('--tool-binary', default='llc',
249 help='The tool used to generate the test case')
250 parser.add_argument(
251 '--function', help='The function in the test file to update')
252 parser.add_argument('tests', nargs='+')
253 args = parser.parse_args()
254
255 autogenerated_note = ('; NOTE: Assertions have been autogenerated by '
256 + os.path.basename(__file__))
257
258 tool_basename = os.path.basename(args.tool_binary)
259 if (tool_basename != "llc" and tool_basename != "opt"):
260 print >>sys.stderr, 'ERROR: Unexpected tool name: ' + tool_basename
261 sys.exit(1)
262
263 for test in args.tests:
264 if args.verbose:
265 print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
266 with open(test) as f:
267 input_lines = [l.rstrip() for l in f]
268
269 run_lines = [m.group(1)
270 for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
271 if args.verbose:
272 print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
273 for l in run_lines:
274 print >>sys.stderr, ' RUN: ' + l
275
276 prefix_list = []
277 for l in run_lines:
278 (tool_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
279
280 if not tool_cmd.startswith(tool_basename + ' '):
281 print >>sys.stderr, 'WARNING: Skipping non-%s RUN line: %s' % (tool_basename, l)
282 continue
283
284 if not filecheck_cmd.startswith('FileCheck '):
285 print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
286 continue
287
288 tool_cmd_args = tool_cmd[len(tool_basename):].strip()
289 tool_cmd_args = tool_cmd_args.replace('< %s', '').replace('%s', '').strip()
290
291 check_prefixes = [m.group(1)
292 for m in CHECK_PREFIX_RE.finditer(filecheck_cmd)]
293 if not check_prefixes:
294 check_prefixes = ['CHECK']
295
296 # FIXME: We should use multiple check prefixes to common check lines. For
297 # now, we just ignore all but the last.
298 prefix_list.append((check_prefixes, tool_cmd_args))
299
300 func_dict = {}
301 for prefixes, _ in prefix_list:
302 for prefix in prefixes:
303 func_dict.update({prefix: dict()})
304 for prefixes, tool_args in prefix_list:
305 if args.verbose:
306 print >>sys.stderr, 'Extracted tool cmd: ' + tool_basename + ' ' + tool_args
307 print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
308
309 raw_tool_output = invoke_tool(args, tool_args, test)
310 build_function_body_dictionary(raw_tool_output, prefixes, func_dict, args.verbose, tool_basename)
311
312 is_in_function = False
313 is_in_function_start = False
314 prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
315 if args.verbose:
316 print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
317 output_lines = []
318 output_lines.append(autogenerated_note)
319
320 for input_line in input_lines:
321 if is_in_function_start:
322 if input_line == '':
323 continue
324 if input_line.lstrip().startswith(';'):
325 m = CHECK_RE.match(input_line)
326 if not m or m.group(1) not in prefix_set:
327 output_lines.append(input_line)
328 continue
329
330 # Print out the various check lines here.
331 output_lines = add_checks(output_lines, prefix_list, func_dict, name, tool_basename)
332 is_in_function_start = False
333
334 if is_in_function:
335 if should_add_line_to_output(input_line, prefix_set) == True:
336 # This input line of the function body will go as-is into the output.
Sanjay Pateld8592712016-03-27 20:43:02 +0000337 # Except make leading whitespace uniform: 2 spaces.
338 input_line = SCRUB_LEADING_WHITESPACE_RE.sub(r' ', input_line)
Sanjay Patelfff7a3d2016-03-24 23:19:26 +0000339 output_lines.append(input_line)
340 else:
341 continue
342 if input_line.strip() == '}':
343 is_in_function = False
344 continue
345
346 if input_line == autogenerated_note:
347 continue
348
349 # If it's outside a function, it just gets copied to the output.
350 output_lines.append(input_line)
351
352 m = IR_FUNCTION_RE.match(input_line)
353 if not m:
354 continue
355 name = m.group(1)
356 if args.function is not None and name != args.function:
357 # When filtering on a specific function, skip all others.
358 continue
359 is_in_function = is_in_function_start = True
360
361 if args.verbose:
362 print>>sys.stderr, 'Writing %d lines to %s...' % (len(output_lines), test)
363
364 with open(test, 'wb') as f:
365 f.writelines([l + '\n' for l in output_lines])
366
367
368if __name__ == '__main__':
369 main()
370