blob: e251ff0b8f54989e1deeb92dc3d9c7896ed64fab [file] [log] [blame]
Fangrui Song0a301a12018-03-02 17:37:04 +00001#!/usr/bin/env python3
2'''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
15import argparse
16import collections
17import distutils.spawn
Alex Richardson0df4a8f2019-11-15 12:50:10 +000018import json
Fangrui Song0a301a12018-03-02 17:37:04 +000019import os
20import shlex
21import string
22import subprocess
23import sys
24import re
25import tempfile
26
27from UpdateTestChecks import asm, common
28
29ADVERT = '// NOTE: Assertions have been autogenerated by '
30
Fangrui Song0a301a12018-03-02 17:37:04 +000031SUBST = {
32 '%clang': [],
33 '%clang_cc1': ['-cc1'],
34 '%clangxx': ['--driver-mode=g++'],
35}
36
37def get_line2spell_and_mangled(args, clang_args):
38 ret = {}
Alex Richardson0df4a8f2019-11-15 12:50:10 +000039 # Use clang's JSON AST dump to get the mangled name
40 json_dump_args = [args.clang, *clang_args, '-fsyntax-only', '-o', '-']
41 if '-cc1' not in json_dump_args:
42 # For tests that invoke %clang instead if %clang_cc1 we have to use
43 # -Xclang -ast-dump=json instead:
44 json_dump_args.append('-Xclang')
45 json_dump_args.append('-ast-dump=json')
Alex Richardsond9542db2019-12-02 10:50:23 +000046 common.debug('Running', ' '.join(json_dump_args))
Alex Richardson0df4a8f2019-11-15 12:50:10 +000047 status = subprocess.run(json_dump_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
48 if status.returncode != 0:
49 sys.stderr.write('Failed to run ' + ' '.join(json_dump_args) + '\n')
50 sys.stderr.write(status.stderr.decode())
51 sys.stderr.write(status.stdout.decode())
52 sys.exit(2)
David Greeneeb669852019-10-08 16:25:42 +000053
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000054 # Parse the clang JSON and add all children of type FunctionDecl.
Alex Richardson0df4a8f2019-11-15 12:50:10 +000055 # TODO: Should we add checks for global variables being emitted?
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000056 def parse_clang_ast_json(node):
57 node_kind = node['kind']
58 # Recurse for the following nodes that can contain nested function decls:
59 if node_kind in ('NamespaceDecl', 'LinkageSpecDecl', 'TranslationUnitDecl'):
60 for inner in node['inner']:
61 parse_clang_ast_json(inner)
62 # Otherwise we ignore everything except functions:
Alex Richardson0df4a8f2019-11-15 12:50:10 +000063 if node['kind'] != 'FunctionDecl':
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000064 return
Alex Richardson0df4a8f2019-11-15 12:50:10 +000065 if node.get('isImplicit') is True and node.get('storageClass') == 'extern':
Alex Richardsond9542db2019-12-02 10:50:23 +000066 common.debug('Skipping builtin function:', node['name'], '@', node['loc'])
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000067 return
Alex Richardsond9542db2019-12-02 10:50:23 +000068 common.debug('Found function:', node['kind'], node['name'], '@', node['loc'])
Alex Richardson0df4a8f2019-11-15 12:50:10 +000069 line = node['loc'].get('line')
70 # If there is no line it is probably a builtin function -> skip
71 if line is None:
Alex Richardsond9542db2019-12-02 10:50:23 +000072 common.debug('Skipping function without line number:', node['name'], '@', node['loc'])
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000073 return
Alex Richardson0df4a8f2019-11-15 12:50:10 +000074 spell = node['name']
75 mangled = node.get('mangledName', spell)
76 ret[int(line)-1] = (spell, mangled)
Alex Richardson8ab3b4d2019-12-02 10:53:57 +000077
78 ast = json.loads(status.stdout.decode())
79 if ast['kind'] != 'TranslationUnitDecl':
80 common.error('Clang AST dump JSON format changed?')
81 sys.exit(2)
82 parse_clang_ast_json(ast)
83
Alex Richardsond9542db2019-12-02 10:50:23 +000084 for line, func_name in sorted(ret.items()):
85 common.debug('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
Alex Richardson0df4a8f2019-11-15 12:50:10 +000086 if not ret:
87 common.warn('Did not find any functions using', ' '.join(json_dump_args))
Fangrui Song0a301a12018-03-02 17:37:04 +000088 return ret
89
90
91def config():
92 parser = argparse.ArgumentParser(
93 description=__doc__,
94 formatter_class=argparse.RawTextHelpFormatter)
Fangrui Song0a301a12018-03-02 17:37:04 +000095 parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
96 parser.add_argument('--clang',
97 help='"clang" executable, defaults to $llvm_bin/clang')
98 parser.add_argument('--clang-args',
99 help='Space-separated extra args to clang, e.g. --clang-args=-v')
Simon Tatham109c7732019-10-10 08:25:34 +0000100 parser.add_argument('--opt',
101 help='"opt" executable, defaults to $llvm_bin/opt')
Fangrui Song0a301a12018-03-02 17:37:04 +0000102 parser.add_argument(
103 '--functions', nargs='+', help='A list of function name regexes. '
104 'If specified, update CHECK lines for functions matching at least one regex')
105 parser.add_argument(
106 '--x86_extra_scrub', action='store_true',
107 help='Use more regex for x86 matching to reduce diffs between various subtargets')
Alex Richardson50807c82019-11-20 13:20:15 +0000108 parser.add_argument('--function-signature', action='store_true',
109 help='Keep function signature information around for the check line')
Fangrui Song0a301a12018-03-02 17:37:04 +0000110 parser.add_argument('tests', nargs='+')
Alex Richardson61873942019-11-20 13:19:48 +0000111 args = common.parse_commandline_args(parser)
Fangrui Song0a301a12018-03-02 17:37:04 +0000112 args.clang_args = shlex.split(args.clang_args or '')
113
114 if args.clang is None:
115 if args.llvm_bin is None:
116 args.clang = 'clang'
117 else:
118 args.clang = os.path.join(args.llvm_bin, 'clang')
119 if not distutils.spawn.find_executable(args.clang):
120 print('Please specify --llvm-bin or --clang', file=sys.stderr)
121 sys.exit(1)
Simon Tatham109c7732019-10-10 08:25:34 +0000122
Alex Richardsond9cc7d12019-10-31 21:18:32 +0000123 # Determine the builtin includes directory so that we can update tests that
124 # depend on the builtin headers. See get_clang_builtin_include_dir() and
125 # use_clang() in llvm/utils/lit/lit/llvm/config.py.
126 try:
127 builtin_include_dir = subprocess.check_output(
128 [args.clang, '-print-file-name=include']).decode().strip()
129 SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir,
130 '-nostdsysteminc']
131 except subprocess.CalledProcessError:
132 common.warn('Could not determine clang builtins directory, some tests '
133 'might not update correctly.')
134
Simon Tatham109c7732019-10-10 08:25:34 +0000135 if args.opt is None:
136 if args.llvm_bin is None:
137 args.opt = 'opt'
138 else:
139 args.opt = os.path.join(args.llvm_bin, 'opt')
140 if not distutils.spawn.find_executable(args.opt):
141 # Many uses of this tool will not need an opt binary, because it's only
142 # needed for updating a test that runs clang | opt | FileCheck. So we
143 # defer this error message until we find that opt is actually needed.
144 args.opt = None
145
Fangrui Song0a301a12018-03-02 17:37:04 +0000146 return args
147
148
Simon Tatham109c7732019-10-10 08:25:34 +0000149def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
Fangrui Song0a301a12018-03-02 17:37:04 +0000150 # TODO Clean up duplication of asm/common build_function_body_dictionary
151 # Invoke external tool and extract function bodies.
152 raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
Simon Tatham109c7732019-10-10 08:25:34 +0000153 for extra_command in extra_commands:
154 extra_args = shlex.split(extra_command)
155 with tempfile.NamedTemporaryFile() as f:
156 f.write(raw_tool_output.encode())
157 f.flush()
158 if extra_args[0] == 'opt':
159 if args.opt is None:
160 print(filename, 'needs to run opt. '
161 'Please specify --llvm-bin or --opt', file=sys.stderr)
162 sys.exit(1)
163 extra_args[0] = args.opt
164 raw_tool_output = common.invoke_tool(extra_args[0],
165 extra_args[1:], f.name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000166 if '-emit-llvm' in clang_args:
167 common.build_function_body_dictionary(
168 common.OPT_FUNCTION_RE, common.scrub_body, [],
Alex Richardson50807c82019-11-20 13:20:15 +0000169 raw_tool_output, prefixes, func_dict, args.verbose, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000170 else:
171 print('The clang command line should include -emit-llvm as asm tests '
172 'are discouraged in Clang testsuite.', file=sys.stderr)
173 sys.exit(1)
174
175
176def main():
177 args = config()
David Bolvansky7169ea32019-08-07 14:44:50 +0000178 script_name = os.path.basename(__file__)
179 autogenerated_note = (ADVERT + 'utils/' + script_name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000180
181 for filename in args.tests:
182 with open(filename) as f:
183 input_lines = [l.rstrip() for l in f]
Johannes Doerferte67f6472019-11-01 11:17:27 -0500184
David Bolvansky7169ea32019-08-07 14:44:50 +0000185 first_line = input_lines[0] if input_lines else ""
186 if 'autogenerated' in first_line and script_name not in first_line:
187 common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
188 continue
189
190 if args.update_only:
191 if not first_line or 'autogenerated' not in first_line:
192 common.warn("Skipping test which isn't autogenerated: " + filename)
193 continue
Fangrui Song0a301a12018-03-02 17:37:04 +0000194
195 # Extract RUN lines.
Alex Richardsond9542db2019-12-02 10:50:23 +0000196 run_lines = common.find_run_lines(filename, input_lines)
Fangrui Song0a301a12018-03-02 17:37:04 +0000197
198 # Build a list of clang command lines and check prefixes from RUN lines.
199 run_list = []
200 line2spell_and_mangled_list = collections.defaultdict(list)
201 for l in run_lines:
Simon Tatham109c7732019-10-10 08:25:34 +0000202 commands = [cmd.strip() for cmd in l.split('|')]
Fangrui Song0a301a12018-03-02 17:37:04 +0000203
204 triple_in_cmd = None
205 m = common.TRIPLE_ARG_RE.search(commands[0])
206 if m:
207 triple_in_cmd = m.groups()[0]
208
209 # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
210 clang_args = shlex.split(commands[0])
211 if clang_args[0] not in SUBST:
212 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
213 continue
214 clang_args[0:1] = SUBST[clang_args[0]]
215 clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
216
Simon Tatham109c7732019-10-10 08:25:34 +0000217 # Permit piping the output through opt
218 if not (len(commands) == 2 or
219 (len(commands) == 3 and commands[1].startswith('opt'))):
220 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
221
Fangrui Song0a301a12018-03-02 17:37:04 +0000222 # Extract -check-prefix in FileCheck args
223 filecheck_cmd = commands[-1]
David Bolvansky45be5e42019-07-29 17:41:00 +0000224 common.verify_filecheck_prefixes(filecheck_cmd)
Fangrui Song0a301a12018-03-02 17:37:04 +0000225 if not filecheck_cmd.startswith('FileCheck '):
226 print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
227 continue
228 check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
229 for item in m.group(1).split(',')]
230 if not check_prefixes:
231 check_prefixes = ['CHECK']
Simon Tatham109c7732019-10-10 08:25:34 +0000232 run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
Fangrui Song0a301a12018-03-02 17:37:04 +0000233
234 # Strip CHECK lines which are in `prefix_set`, update test file.
235 prefix_set = set([prefix for p in run_list for prefix in p[0]])
236 input_lines = []
237 with open(filename, 'r+') as f:
238 for line in f:
Alex Richardson3b55eeb2019-12-02 18:18:47 +0000239 m = common.CHECK_RE.match(line)
Fangrui Song0a301a12018-03-02 17:37:04 +0000240 if not (m and m.group(1) in prefix_set) and line != '//\n':
241 input_lines.append(line)
242 f.seek(0)
243 f.writelines(input_lines)
244 f.truncate()
245
246 # Execute clang, generate LLVM IR, and extract functions.
247 func_dict = {}
248 for p in run_list:
249 prefixes = p[0]
250 for prefix in prefixes:
251 func_dict.update({prefix: dict()})
Simon Tatham109c7732019-10-10 08:25:34 +0000252 for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
Alex Richardsond9542db2019-12-02 10:50:23 +0000253 common.debug('Extracted clang cmd: clang {}'.format(clang_args))
254 common.debug('Extracted FileCheck prefixes: {}'.format(prefixes))
Fangrui Song0a301a12018-03-02 17:37:04 +0000255
Simon Tatham109c7732019-10-10 08:25:34 +0000256 get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
Fangrui Song0a301a12018-03-02 17:37:04 +0000257
Alex Richardson0df4a8f2019-11-15 12:50:10 +0000258 # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to
259 # mangled names. Forward all clang args for now.
Fangrui Song0a301a12018-03-02 17:37:04 +0000260 for k, v in get_line2spell_and_mangled(args, clang_args).items():
261 line2spell_and_mangled_list[k].append(v)
262
263 output_lines = [autogenerated_note]
264 for idx, line in enumerate(input_lines):
265 # Discard any previous script advertising.
266 if line.startswith(ADVERT):
267 continue
268 if idx in line2spell_and_mangled_list:
269 added = set()
270 for spell, mangled in line2spell_and_mangled_list[idx]:
271 # One line may contain multiple function declarations.
272 # Skip if the mangled name has been added before.
273 # The line number may come from an included file,
274 # we simply require the spelling name to appear on the line
275 # to exclude functions from other files.
276 if mangled in added or spell not in line:
277 continue
278 if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
279 if added:
280 output_lines.append('//')
281 added.add(mangled)
Alex Richardson50807c82019-11-20 13:20:15 +0000282 common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled,
283 False, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000284 output_lines.append(line.rstrip('\n'))
285
286 # Update the test file.
287 with open(filename, 'w') as f:
288 for line in output_lines:
289 f.write(line + '\n')
290
291 return 0
292
293
294if __name__ == '__main__':
295 sys.exit(main())