1 #!/usr/bin/env python2.7
3 """A test case update script.
5 This script is a utility to update LLVM X86 'llc' based test cases with new
6 FileCheck patterns. It can either update all of the tests in the file or
7 a single test function.
12 import os # Used to advertise this file's name ("autogenerated_note").
19 # Invoke the tool that is being tested.
20 def llc(args, cmd_args, ir):
21 with open(ir) as ir_file:
22 stdout = subprocess.check_output(args.llc_binary + ' ' + cmd_args,
23 shell=True, stdin=ir_file)
24 # Fix line endings to unix CR style.
25 stdout = stdout.replace('\r\n', '\n')
29 # RegEx: this is where the magic happens.
31 SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M)
32 SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
33 SCRUB_X86_SHUFFLES_RE = (
35 r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem)( \{%k\d+\}( \{z\})?)? = .*)$',
37 SCRUB_X86_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
38 SCRUB_X86_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
39 SCRUB_X86_LCP_RE = re.compile(r'\.LCPI[0-9]+_[0-9]+')
40 SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
42 RUN_LINE_RE = re.compile('^\s*;\s*RUN:\s*(.*)$')
43 IR_FUNCTION_RE = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@(\w+)\s*\(')
44 ASM_FUNCTION_RE = re.compile(
45 r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@(?P=func)\n[^:]*?'
46 r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
47 r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)',
49 CHECK_PREFIX_RE = re.compile('--check-prefix=(\S+)')
50 CHECK_RE = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
54 # Scrub runs of whitespace out of the assembly, but leave the leading
55 # whitespace in place.
56 asm = SCRUB_WHITESPACE_RE.sub(r' ', asm)
57 # Expand the tabs used for indentation.
58 asm = string.expandtabs(asm, 2)
59 # Detect shuffle asm comments and hide the operands in favor of the comments.
60 asm = SCRUB_X86_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
61 # Generically match the stack offset of a memory operand.
62 asm = SCRUB_X86_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
63 # Generically match a RIP-relative memory operand.
64 asm = SCRUB_X86_RIP_RE.sub(r'{{.*}}(%rip)', asm)
65 # Generically match a LCP symbol.
66 asm = SCRUB_X86_LCP_RE.sub(r'{{\.LCPI.*}}', asm)
67 # Strip kill operands inserted into the asm.
68 asm = SCRUB_KILL_COMMENT_RE.sub('', asm)
69 # Strip trailing whitespace.
70 asm = SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
74 # Build up a dictionary of all the function bodies.
75 def build_function_body_dictionary(raw_tool_output, prefixes, func_dict, verbose):
76 for m in ASM_FUNCTION_RE.finditer(raw_tool_output):
79 func = m.group('func')
80 scrubbed_body = scrub_asm(m.group('body'))
81 if func.startswith('stress'):
82 # We only use the last line of the function body for stress tests.
83 scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
85 print >>sys.stderr, 'Processing function: ' + func
86 for l in scrubbed_body.splitlines():
87 print >>sys.stderr, ' ' + l
88 for prefix in prefixes:
89 if func in func_dict[prefix] and func_dict[prefix][func] != scrubbed_body:
90 if prefix == prefixes[-1]:
91 print >>sys.stderr, ('WARNING: Found conflicting asm under the '
92 'same prefix: %r!' % (prefix,))
94 func_dict[prefix][func] = None
97 func_dict[prefix][func] = scrubbed_body
100 def add_checks(output_lines, prefix_list, func_dict, func_name):
101 printed_prefixes = []
102 for checkprefixes, _ in prefix_list:
103 for checkprefix in checkprefixes:
104 if checkprefix in printed_prefixes:
106 if not func_dict[checkprefix][func_name]:
108 # Add some space between different check prefixes.
109 if len(printed_prefixes) != 0:
110 output_lines.append(';')
111 printed_prefixes.append(checkprefix)
112 output_lines.append('; %s-LABEL: %s:' % (checkprefix, func_name))
113 func_body = func_dict[checkprefix][func_name].splitlines()
114 output_lines.append('; %s: %s' % (checkprefix, func_body[0]))
115 for func_line in func_body[1:]:
116 output_lines.append('; %s-NEXT: %s' % (checkprefix, func_line))
117 # Add space between different check prefixes and the first line of code.
118 # output_lines.append(';')
123 def should_add_line_to_output(input_line, prefix_set):
124 # Skip any blank comment lines in the IR.
125 if input_line.strip() == ';':
127 # Skip any blank lines in the IR.
128 #if input_line.strip() == '':
130 # And skip any CHECK lines. We're building our own.
131 m = CHECK_RE.match(input_line)
132 if m and m.group(1) in prefix_set:
139 parser = argparse.ArgumentParser(description=__doc__)
140 parser.add_argument('-v', '--verbose', action='store_true',
141 help='Show verbose output')
142 parser.add_argument('--llc-binary', default='llc',
143 help='The "llc" binary to use to generate the test case')
145 '--function', help='The function in the test file to update')
146 parser.add_argument('tests', nargs='+')
147 args = parser.parse_args()
149 autogenerated_note = ('; NOTE: Assertions have been autogenerated by '
150 'utils/' + os.path.basename(__file__))
152 for test in args.tests:
154 print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
155 with open(test) as f:
156 input_lines = [l.rstrip() for l in f]
158 run_lines = [m.group(1)
159 for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
161 print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
163 print >>sys.stderr, ' RUN: ' + l
167 (llc_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
168 if not llc_cmd.startswith('llc '):
169 print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l
172 if not filecheck_cmd.startswith('FileCheck '):
173 print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
176 llc_cmd_args = llc_cmd[len('llc'):].strip()
177 llc_cmd_args = llc_cmd_args.replace('< %s', '').replace('%s', '').strip()
179 check_prefixes = [m.group(1)
180 for m in CHECK_PREFIX_RE.finditer(filecheck_cmd)]
181 if not check_prefixes:
182 check_prefixes = ['CHECK']
184 # FIXME: We should use multiple check prefixes to common check lines. For
185 # now, we just ignore all but the last.
186 prefix_list.append((check_prefixes, llc_cmd_args))
189 for prefixes, _ in prefix_list:
190 for prefix in prefixes:
191 func_dict.update({prefix: dict()})
192 for prefixes, llc_args in prefix_list:
194 print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args
195 print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
197 raw_tool_output = llc(args, llc_args, test)
198 build_function_body_dictionary(raw_tool_output, prefixes, func_dict, args.verbose)
200 is_in_function = False
201 is_in_function_start = False
202 prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
204 print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
206 output_lines.append(autogenerated_note)
208 for input_line in input_lines:
209 if is_in_function_start:
212 if input_line.lstrip().startswith(';'):
213 m = CHECK_RE.match(input_line)
214 if not m or m.group(1) not in prefix_set:
215 output_lines.append(input_line)
218 # Print out the various check lines here.
219 output_lines = add_checks(output_lines, prefix_list, func_dict, name)
220 is_in_function_start = False
223 if should_add_line_to_output(input_line, prefix_set) == True:
224 # This input line of the function body will go as-is into the output.
225 output_lines.append(input_line)
228 if input_line.strip() == '}':
229 is_in_function = False
232 if input_line == autogenerated_note:
235 # If it's outside a function, it just gets copied to the output.
236 output_lines.append(input_line)
238 m = IR_FUNCTION_RE.match(input_line)
242 if args.function is not None and name != args.function:
243 # When filtering on a specific function, skip all others.
245 is_in_function = is_in_function_start = True
248 print>>sys.stderr, 'Writing %d lines to %s...' % (len(output_lines), test)
250 with open(test, 'wb') as f:
251 f.writelines([l + '\n' for l in output_lines])
254 if __name__ == '__main__':