blob: 98e8e3774fc422df6c2d2360e9d98d82e76bb21f [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 Richardson0df4a8f2019-11-15 12:50:10 +000079 spell = node['name']
80 mangled = node.get('mangledName', spell)
81 ret[int(line)-1] = (spell, mangled)
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000082
Nico Weber9d49e5c2020-01-02 13:44:54 -050083 ast = json.loads(stdout)
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000084 if ast['kind'] != 'TranslationUnitDecl':
85 common.error('Clang AST dump JSON format changed?')
86 sys.exit(2)
87 parse_clang_ast_json(ast)
88
Alex Richardsond9542db2019-12-02 10:50:23 +000089 for line, func_name in sorted(ret.items()):
90 common.debug('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
Alex Richardson0df4a8f2019-11-15 12:50:10 +000091 if not ret:
92 common.warn('Did not find any functions using', ' '.join(json_dump_args))
Fangrui Song0a301a12018-03-02 17:37:04 +000093 return ret
94
95
96def config():
97 parser = argparse.ArgumentParser(
98 description=__doc__,
99 formatter_class=argparse.RawTextHelpFormatter)
Fangrui Song0a301a12018-03-02 17:37:04 +0000100 parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
101 parser.add_argument('--clang',
102 help='"clang" executable, defaults to $llvm_bin/clang')
103 parser.add_argument('--clang-args',
104 help='Space-separated extra args to clang, e.g. --clang-args=-v')
Simon Tatham109c7732019-10-10 08:25:34 +0000105 parser.add_argument('--opt',
106 help='"opt" executable, defaults to $llvm_bin/opt')
Fangrui Song0a301a12018-03-02 17:37:04 +0000107 parser.add_argument(
108 '--functions', nargs='+', help='A list of function name regexes. '
109 'If specified, update CHECK lines for functions matching at least one regex')
110 parser.add_argument(
111 '--x86_extra_scrub', action='store_true',
112 help='Use more regex for x86 matching to reduce diffs between various subtargets')
Alex Richardson50807c82019-11-20 13:20:15 +0000113 parser.add_argument('--function-signature', action='store_true',
114 help='Keep function signature information around for the check line')
Fangrui Song0a301a12018-03-02 17:37:04 +0000115 parser.add_argument('tests', nargs='+')
Alex Richardson61873942019-11-20 13:19:48 +0000116 args = common.parse_commandline_args(parser)
Fangrui Song0a301a12018-03-02 17:37:04 +0000117 args.clang_args = shlex.split(args.clang_args or '')
118
119 if args.clang is None:
120 if args.llvm_bin is None:
121 args.clang = 'clang'
122 else:
123 args.clang = os.path.join(args.llvm_bin, 'clang')
124 if not distutils.spawn.find_executable(args.clang):
125 print('Please specify --llvm-bin or --clang', file=sys.stderr)
126 sys.exit(1)
Simon Tatham109c7732019-10-10 08:25:34 +0000127
Alex Richardsond9cc7d12019-10-31 21:18:32 +0000128 # Determine the builtin includes directory so that we can update tests that
129 # depend on the builtin headers. See get_clang_builtin_include_dir() and
130 # use_clang() in llvm/utils/lit/lit/llvm/config.py.
131 try:
132 builtin_include_dir = subprocess.check_output(
133 [args.clang, '-print-file-name=include']).decode().strip()
134 SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir,
135 '-nostdsysteminc']
136 except subprocess.CalledProcessError:
137 common.warn('Could not determine clang builtins directory, some tests '
138 'might not update correctly.')
139
Simon Tatham109c7732019-10-10 08:25:34 +0000140 if args.opt is None:
141 if args.llvm_bin is None:
142 args.opt = 'opt'
143 else:
144 args.opt = os.path.join(args.llvm_bin, 'opt')
145 if not distutils.spawn.find_executable(args.opt):
146 # Many uses of this tool will not need an opt binary, because it's only
147 # needed for updating a test that runs clang | opt | FileCheck. So we
148 # defer this error message until we find that opt is actually needed.
149 args.opt = None
150
Fangrui Song0a301a12018-03-02 17:37:04 +0000151 return args
152
153
Simon Tatham109c7732019-10-10 08:25:34 +0000154def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
Fangrui Song0a301a12018-03-02 17:37:04 +0000155 # TODO Clean up duplication of asm/common build_function_body_dictionary
156 # Invoke external tool and extract function bodies.
157 raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
Simon Tatham109c7732019-10-10 08:25:34 +0000158 for extra_command in extra_commands:
159 extra_args = shlex.split(extra_command)
160 with tempfile.NamedTemporaryFile() as f:
161 f.write(raw_tool_output.encode())
162 f.flush()
163 if extra_args[0] == 'opt':
164 if args.opt is None:
165 print(filename, 'needs to run opt. '
166 'Please specify --llvm-bin or --opt', file=sys.stderr)
167 sys.exit(1)
168 extra_args[0] = args.opt
169 raw_tool_output = common.invoke_tool(extra_args[0],
170 extra_args[1:], f.name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000171 if '-emit-llvm' in clang_args:
172 common.build_function_body_dictionary(
173 common.OPT_FUNCTION_RE, common.scrub_body, [],
Alex Richardson50807c82019-11-20 13:20:15 +0000174 raw_tool_output, prefixes, func_dict, args.verbose, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000175 else:
176 print('The clang command line should include -emit-llvm as asm tests '
177 'are discouraged in Clang testsuite.', file=sys.stderr)
178 sys.exit(1)
179
180
181def main():
182 args = config()
David Bolvansky7169ea32019-08-07 14:44:50 +0000183 script_name = os.path.basename(__file__)
184 autogenerated_note = (ADVERT + 'utils/' + script_name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000185
186 for filename in args.tests:
187 with open(filename) as f:
188 input_lines = [l.rstrip() for l in f]
Johannes Doerferte67f6472019-11-01 11:17:27 -0500189
David Bolvansky7169ea32019-08-07 14:44:50 +0000190 first_line = input_lines[0] if input_lines else ""
191 if 'autogenerated' in first_line and script_name not in first_line:
192 common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
193 continue
194
195 if args.update_only:
196 if not first_line or 'autogenerated' not in first_line:
197 common.warn("Skipping test which isn't autogenerated: " + filename)
198 continue
Fangrui Song0a301a12018-03-02 17:37:04 +0000199
200 # Extract RUN lines.
Alex Richardsond9542db2019-12-02 10:50:23 +0000201 run_lines = common.find_run_lines(filename, input_lines)
Fangrui Song0a301a12018-03-02 17:37:04 +0000202
203 # Build a list of clang command lines and check prefixes from RUN lines.
204 run_list = []
205 line2spell_and_mangled_list = collections.defaultdict(list)
206 for l in run_lines:
Simon Tatham109c7732019-10-10 08:25:34 +0000207 commands = [cmd.strip() for cmd in l.split('|')]
Fangrui Song0a301a12018-03-02 17:37:04 +0000208
209 triple_in_cmd = None
210 m = common.TRIPLE_ARG_RE.search(commands[0])
211 if m:
212 triple_in_cmd = m.groups()[0]
213
214 # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
215 clang_args = shlex.split(commands[0])
216 if clang_args[0] not in SUBST:
217 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
218 continue
219 clang_args[0:1] = SUBST[clang_args[0]]
220 clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
221
Simon Tatham109c7732019-10-10 08:25:34 +0000222 # Permit piping the output through opt
223 if not (len(commands) == 2 or
224 (len(commands) == 3 and commands[1].startswith('opt'))):
225 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
226
Fangrui Song0a301a12018-03-02 17:37:04 +0000227 # Extract -check-prefix in FileCheck args
228 filecheck_cmd = commands[-1]
David Bolvansky45be5e42019-07-29 17:41:00 +0000229 common.verify_filecheck_prefixes(filecheck_cmd)
Fangrui Song0a301a12018-03-02 17:37:04 +0000230 if not filecheck_cmd.startswith('FileCheck '):
231 print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
232 continue
233 check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
234 for item in m.group(1).split(',')]
235 if not check_prefixes:
236 check_prefixes = ['CHECK']
Simon Tatham109c7732019-10-10 08:25:34 +0000237 run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
Fangrui Song0a301a12018-03-02 17:37:04 +0000238
239 # Strip CHECK lines which are in `prefix_set`, update test file.
240 prefix_set = set([prefix for p in run_list for prefix in p[0]])
241 input_lines = []
242 with open(filename, 'r+') as f:
243 for line in f:
Alex Richardson3b55eeb2019-12-02 18:18:47 +0000244 m = common.CHECK_RE.match(line)
Fangrui Song0a301a12018-03-02 17:37:04 +0000245 if not (m and m.group(1) in prefix_set) and line != '//\n':
246 input_lines.append(line)
247 f.seek(0)
248 f.writelines(input_lines)
249 f.truncate()
250
251 # Execute clang, generate LLVM IR, and extract functions.
252 func_dict = {}
253 for p in run_list:
254 prefixes = p[0]
255 for prefix in prefixes:
256 func_dict.update({prefix: dict()})
Simon Tatham109c7732019-10-10 08:25:34 +0000257 for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
Alex Richardsond9542db2019-12-02 10:50:23 +0000258 common.debug('Extracted clang cmd: clang {}'.format(clang_args))
259 common.debug('Extracted FileCheck prefixes: {}'.format(prefixes))
Fangrui Song0a301a12018-03-02 17:37:04 +0000260
Simon Tatham109c7732019-10-10 08:25:34 +0000261 get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
Fangrui Song0a301a12018-03-02 17:37:04 +0000262
Alex Richardson0df4a8f2019-11-15 12:50:10 +0000263 # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to
264 # mangled names. Forward all clang args for now.
Fangrui Song0a301a12018-03-02 17:37:04 +0000265 for k, v in get_line2spell_and_mangled(args, clang_args).items():
266 line2spell_and_mangled_list[k].append(v)
267
268 output_lines = [autogenerated_note]
269 for idx, line in enumerate(input_lines):
270 # Discard any previous script advertising.
271 if line.startswith(ADVERT):
272 continue
273 if idx in line2spell_and_mangled_list:
274 added = set()
275 for spell, mangled in line2spell_and_mangled_list[idx]:
276 # One line may contain multiple function declarations.
277 # Skip if the mangled name has been added before.
278 # The line number may come from an included file,
279 # we simply require the spelling name to appear on the line
280 # to exclude functions from other files.
281 if mangled in added or spell not in line:
282 continue
283 if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
284 if added:
285 output_lines.append('//')
286 added.add(mangled)
Alex Richardson50807c82019-11-20 13:20:15 +0000287 common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled,
288 False, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000289 output_lines.append(line.rstrip('\n'))
290
291 # Update the test file.
292 with open(filename, 'w') as f:
293 for line in output_lines:
294 f.write(line + '\n')
295
296 return 0
297
298
299if __name__ == '__main__':
300 sys.exit(main())