blob: 21cc5b4e5e30204c10dd2ce6657c12ae4cbdda63 [file] [log] [blame]
Nico Weber9d49e5c2020-01-02 13:44:54 -05001#!/usr/bin/env python
Fangrui Song0a301a12018-03-02 17:37:04 +00002'''A utility to update LLVM IR CHECK lines in C/C++ FileCheck test files.
3
4Example RUN lines in .c/.cc test files:
5
6// RUN: %clang -emit-llvm -S %s -o - -O2 | FileCheck %s
7// RUN: %clangxx -emit-llvm -S %s -o - -O2 | FileCheck -check-prefix=CHECK-A %s
8
9Usage:
10
11% utils/update_cc_test_checks.py --llvm-bin=release/bin test/a.cc
Alex Richardson0df4a8f2019-11-15 12:50:10 +000012% utils/update_cc_test_checks.py --clang=release/bin/clang /tmp/c/a.cc
Fangrui Song0a301a12018-03-02 17:37:04 +000013'''
14
Nico Weber9d49e5c2020-01-02 13:44:54 -050015from __future__ import print_function
16
Fangrui Song0a301a12018-03-02 17:37:04 +000017import argparse
18import collections
19import distutils.spawn
Alex Richardson0df4a8f2019-11-15 12:50:10 +000020import json
Fangrui Song0a301a12018-03-02 17:37:04 +000021import os
22import shlex
23import string
24import subprocess
25import sys
26import re
27import tempfile
28
29from UpdateTestChecks import asm, common
30
31ADVERT = '// NOTE: Assertions have been autogenerated by '
32
Fangrui Song0a301a12018-03-02 17:37:04 +000033SUBST = {
34 '%clang': [],
35 '%clang_cc1': ['-cc1'],
36 '%clangxx': ['--driver-mode=g++'],
37}
38
39def get_line2spell_and_mangled(args, clang_args):
40 ret = {}
Alex Richardson0df4a8f2019-11-15 12:50:10 +000041 # Use clang's JSON AST dump to get the mangled name
Nico Weber9d49e5c2020-01-02 13:44:54 -050042 json_dump_args = [args.clang] + clang_args + ['-fsyntax-only', '-o', '-']
Alex Richardson0df4a8f2019-11-15 12:50:10 +000043 if '-cc1' not in json_dump_args:
44 # For tests that invoke %clang instead if %clang_cc1 we have to use
45 # -Xclang -ast-dump=json instead:
46 json_dump_args.append('-Xclang')
47 json_dump_args.append('-ast-dump=json')
Alex Richardsond9542db2019-12-02 10:50:23 +000048 common.debug('Running', ' '.join(json_dump_args))
Nico Weber9d49e5c2020-01-02 13:44:54 -050049
50 popen = subprocess.Popen(json_dump_args, stdout=subprocess.PIPE,
51 stderr=subprocess.PIPE, universal_newlines=True)
52 stdout, stderr = popen.communicate()
53 if popen.returncode != 0:
Alex Richardson0df4a8f2019-11-15 12:50:10 +000054 sys.stderr.write('Failed to run ' + ' '.join(json_dump_args) + '\n')
Nico Weber9d49e5c2020-01-02 13:44:54 -050055 sys.stderr.write(stderr)
56 sys.stderr.write(stdout)
Alex Richardson0df4a8f2019-11-15 12:50:10 +000057 sys.exit(2)
David Greeneeb669852019-10-08 16:25:42 +000058
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000059 # Parse the clang JSON and add all children of type FunctionDecl.
Alex Richardson0df4a8f2019-11-15 12:50:10 +000060 # TODO: Should we add checks for global variables being emitted?
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000061 def parse_clang_ast_json(node):
62 node_kind = node['kind']
63 # Recurse for the following nodes that can contain nested function decls:
64 if node_kind in ('NamespaceDecl', 'LinkageSpecDecl', 'TranslationUnitDecl'):
65 for inner in node['inner']:
66 parse_clang_ast_json(inner)
67 # Otherwise we ignore everything except functions:
Alex Richardson0df4a8f2019-11-15 12:50:10 +000068 if node['kind'] != 'FunctionDecl':
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000069 return
Alex Richardson0df4a8f2019-11-15 12:50:10 +000070 if node.get('isImplicit') is True and node.get('storageClass') == 'extern':
Alex Richardsond9542db2019-12-02 10:50:23 +000071 common.debug('Skipping builtin function:', node['name'], '@', node['loc'])
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000072 return
Alex Richardsond9542db2019-12-02 10:50:23 +000073 common.debug('Found function:', node['kind'], node['name'], '@', node['loc'])
Alex Richardson0df4a8f2019-11-15 12:50:10 +000074 line = node['loc'].get('line')
75 # If there is no line it is probably a builtin function -> skip
76 if line is None:
Alex Richardsond9542db2019-12-02 10:50:23 +000077 common.debug('Skipping function without line number:', node['name'], '@', node['loc'])
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000078 return
Alex Richardson1132f872020-02-04 08:40:56 +000079 # If there is no 'inner' object, it is a function declaration -> skip
80 if 'inner' not in node:
81 common.debug('Skipping function without body:', node['name'], '@', node['loc'])
82 return
Alex Richardson0df4a8f2019-11-15 12:50:10 +000083 spell = node['name']
84 mangled = node.get('mangledName', spell)
85 ret[int(line)-1] = (spell, mangled)
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000086
Nico Weber9d49e5c2020-01-02 13:44:54 -050087 ast = json.loads(stdout)
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000088 if ast['kind'] != 'TranslationUnitDecl':
89 common.error('Clang AST dump JSON format changed?')
90 sys.exit(2)
91 parse_clang_ast_json(ast)
92
Alex Richardsond9542db2019-12-02 10:50:23 +000093 for line, func_name in sorted(ret.items()):
94 common.debug('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
Alex Richardson0df4a8f2019-11-15 12:50:10 +000095 if not ret:
96 common.warn('Did not find any functions using', ' '.join(json_dump_args))
Fangrui Song0a301a12018-03-02 17:37:04 +000097 return ret
98
99
100def config():
101 parser = argparse.ArgumentParser(
102 description=__doc__,
103 formatter_class=argparse.RawTextHelpFormatter)
Fangrui Song0a301a12018-03-02 17:37:04 +0000104 parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
105 parser.add_argument('--clang',
106 help='"clang" executable, defaults to $llvm_bin/clang')
107 parser.add_argument('--clang-args',
108 help='Space-separated extra args to clang, e.g. --clang-args=-v')
Simon Tatham109c7732019-10-10 08:25:34 +0000109 parser.add_argument('--opt',
110 help='"opt" executable, defaults to $llvm_bin/opt')
Fangrui Song0a301a12018-03-02 17:37:04 +0000111 parser.add_argument(
112 '--functions', nargs='+', help='A list of function name regexes. '
113 'If specified, update CHECK lines for functions matching at least one regex')
114 parser.add_argument(
115 '--x86_extra_scrub', action='store_true',
116 help='Use more regex for x86 matching to reduce diffs between various subtargets')
Alex Richardson50807c82019-11-20 13:20:15 +0000117 parser.add_argument('--function-signature', action='store_true',
118 help='Keep function signature information around for the check line')
Fangrui Song0a301a12018-03-02 17:37:04 +0000119 parser.add_argument('tests', nargs='+')
Alex Richardson61873942019-11-20 13:19:48 +0000120 args = common.parse_commandline_args(parser)
Fangrui Song0a301a12018-03-02 17:37:04 +0000121 args.clang_args = shlex.split(args.clang_args or '')
122
123 if args.clang is None:
124 if args.llvm_bin is None:
125 args.clang = 'clang'
126 else:
127 args.clang = os.path.join(args.llvm_bin, 'clang')
128 if not distutils.spawn.find_executable(args.clang):
129 print('Please specify --llvm-bin or --clang', file=sys.stderr)
130 sys.exit(1)
Simon Tatham109c7732019-10-10 08:25:34 +0000131
Alex Richardsond9cc7d12019-10-31 21:18:32 +0000132 # Determine the builtin includes directory so that we can update tests that
133 # depend on the builtin headers. See get_clang_builtin_include_dir() and
134 # use_clang() in llvm/utils/lit/lit/llvm/config.py.
135 try:
136 builtin_include_dir = subprocess.check_output(
137 [args.clang, '-print-file-name=include']).decode().strip()
138 SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir,
139 '-nostdsysteminc']
140 except subprocess.CalledProcessError:
141 common.warn('Could not determine clang builtins directory, some tests '
142 'might not update correctly.')
143
Simon Tatham109c7732019-10-10 08:25:34 +0000144 if args.opt is None:
145 if args.llvm_bin is None:
146 args.opt = 'opt'
147 else:
148 args.opt = os.path.join(args.llvm_bin, 'opt')
149 if not distutils.spawn.find_executable(args.opt):
150 # Many uses of this tool will not need an opt binary, because it's only
151 # needed for updating a test that runs clang | opt | FileCheck. So we
152 # defer this error message until we find that opt is actually needed.
153 args.opt = None
154
Fangrui Song0a301a12018-03-02 17:37:04 +0000155 return args
156
157
Simon Tatham109c7732019-10-10 08:25:34 +0000158def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
Fangrui Song0a301a12018-03-02 17:37:04 +0000159 # TODO Clean up duplication of asm/common build_function_body_dictionary
160 # Invoke external tool and extract function bodies.
161 raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
Simon Tatham109c7732019-10-10 08:25:34 +0000162 for extra_command in extra_commands:
163 extra_args = shlex.split(extra_command)
164 with tempfile.NamedTemporaryFile() as f:
165 f.write(raw_tool_output.encode())
166 f.flush()
167 if extra_args[0] == 'opt':
168 if args.opt is None:
169 print(filename, 'needs to run opt. '
170 'Please specify --llvm-bin or --opt', file=sys.stderr)
171 sys.exit(1)
172 extra_args[0] = args.opt
173 raw_tool_output = common.invoke_tool(extra_args[0],
174 extra_args[1:], f.name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000175 if '-emit-llvm' in clang_args:
176 common.build_function_body_dictionary(
177 common.OPT_FUNCTION_RE, common.scrub_body, [],
Alex Richardson50807c82019-11-20 13:20:15 +0000178 raw_tool_output, prefixes, func_dict, args.verbose, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000179 else:
180 print('The clang command line should include -emit-llvm as asm tests '
181 'are discouraged in Clang testsuite.', file=sys.stderr)
182 sys.exit(1)
183
184
185def main():
186 args = config()
David Bolvansky7169ea32019-08-07 14:44:50 +0000187 script_name = os.path.basename(__file__)
188 autogenerated_note = (ADVERT + 'utils/' + script_name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000189
190 for filename in args.tests:
191 with open(filename) as f:
192 input_lines = [l.rstrip() for l in f]
Johannes Doerferte67f6472019-11-01 11:17:27 -0500193
David Bolvansky7169ea32019-08-07 14:44:50 +0000194 first_line = input_lines[0] if input_lines else ""
195 if 'autogenerated' in first_line and script_name not in first_line:
196 common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
197 continue
198
199 if args.update_only:
200 if not first_line or 'autogenerated' not in first_line:
201 common.warn("Skipping test which isn't autogenerated: " + filename)
202 continue
Fangrui Song0a301a12018-03-02 17:37:04 +0000203
204 # Extract RUN lines.
Alex Richardsond9542db2019-12-02 10:50:23 +0000205 run_lines = common.find_run_lines(filename, input_lines)
Fangrui Song0a301a12018-03-02 17:37:04 +0000206
207 # Build a list of clang command lines and check prefixes from RUN lines.
208 run_list = []
209 line2spell_and_mangled_list = collections.defaultdict(list)
210 for l in run_lines:
Simon Tatham109c7732019-10-10 08:25:34 +0000211 commands = [cmd.strip() for cmd in l.split('|')]
Fangrui Song0a301a12018-03-02 17:37:04 +0000212
213 triple_in_cmd = None
214 m = common.TRIPLE_ARG_RE.search(commands[0])
215 if m:
216 triple_in_cmd = m.groups()[0]
217
218 # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
219 clang_args = shlex.split(commands[0])
220 if clang_args[0] not in SUBST:
221 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
222 continue
223 clang_args[0:1] = SUBST[clang_args[0]]
224 clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
225
Simon Tatham109c7732019-10-10 08:25:34 +0000226 # Permit piping the output through opt
227 if not (len(commands) == 2 or
228 (len(commands) == 3 and commands[1].startswith('opt'))):
229 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
230
Fangrui Song0a301a12018-03-02 17:37:04 +0000231 # Extract -check-prefix in FileCheck args
232 filecheck_cmd = commands[-1]
David Bolvansky45be5e42019-07-29 17:41:00 +0000233 common.verify_filecheck_prefixes(filecheck_cmd)
Fangrui Song0a301a12018-03-02 17:37:04 +0000234 if not filecheck_cmd.startswith('FileCheck '):
235 print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
236 continue
237 check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
238 for item in m.group(1).split(',')]
239 if not check_prefixes:
240 check_prefixes = ['CHECK']
Simon Tatham109c7732019-10-10 08:25:34 +0000241 run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
Fangrui Song0a301a12018-03-02 17:37:04 +0000242
243 # Strip CHECK lines which are in `prefix_set`, update test file.
244 prefix_set = set([prefix for p in run_list for prefix in p[0]])
245 input_lines = []
246 with open(filename, 'r+') as f:
247 for line in f:
Alex Richardson3b55eeb2019-12-02 18:18:47 +0000248 m = common.CHECK_RE.match(line)
Fangrui Song0a301a12018-03-02 17:37:04 +0000249 if not (m and m.group(1) in prefix_set) and line != '//\n':
250 input_lines.append(line)
251 f.seek(0)
252 f.writelines(input_lines)
253 f.truncate()
254
255 # Execute clang, generate LLVM IR, and extract functions.
256 func_dict = {}
257 for p in run_list:
258 prefixes = p[0]
259 for prefix in prefixes:
260 func_dict.update({prefix: dict()})
Simon Tatham109c7732019-10-10 08:25:34 +0000261 for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
Alex Richardsond9542db2019-12-02 10:50:23 +0000262 common.debug('Extracted clang cmd: clang {}'.format(clang_args))
263 common.debug('Extracted FileCheck prefixes: {}'.format(prefixes))
Fangrui Song0a301a12018-03-02 17:37:04 +0000264
Simon Tatham109c7732019-10-10 08:25:34 +0000265 get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
Fangrui Song0a301a12018-03-02 17:37:04 +0000266
Alex Richardson0df4a8f2019-11-15 12:50:10 +0000267 # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to
268 # mangled names. Forward all clang args for now.
Fangrui Song0a301a12018-03-02 17:37:04 +0000269 for k, v in get_line2spell_and_mangled(args, clang_args).items():
270 line2spell_and_mangled_list[k].append(v)
271
272 output_lines = [autogenerated_note]
273 for idx, line in enumerate(input_lines):
274 # Discard any previous script advertising.
275 if line.startswith(ADVERT):
276 continue
277 if idx in line2spell_and_mangled_list:
278 added = set()
279 for spell, mangled in line2spell_and_mangled_list[idx]:
280 # One line may contain multiple function declarations.
281 # Skip if the mangled name has been added before.
282 # The line number may come from an included file,
283 # we simply require the spelling name to appear on the line
284 # to exclude functions from other files.
285 if mangled in added or spell not in line:
286 continue
287 if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
288 if added:
289 output_lines.append('//')
290 added.add(mangled)
Alex Richardson50807c82019-11-20 13:20:15 +0000291 common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled,
292 False, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000293 output_lines.append(line.rstrip('\n'))
294
295 # Update the test file.
296 with open(filename, 'w') as f:
297 for line in output_lines:
298 f.write(line + '\n')
299
300 return 0
301
302
303if __name__ == '__main__':
304 sys.exit(main())