blob: 414056fa6fdd88749b081881a0543213b078fa89 [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
31CHECK_RE = re.compile(r'^\s*//\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
Fangrui Song0a301a12018-03-02 17:37:04 +000032
33SUBST = {
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
42 json_dump_args = [args.clang, *clang_args, '-fsyntax-only', '-o', '-']
43 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))
Alex Richardson0df4a8f2019-11-15 12:50:10 +000049 status = subprocess.run(json_dump_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
50 if status.returncode != 0:
51 sys.stderr.write('Failed to run ' + ' '.join(json_dump_args) + '\n')
52 sys.stderr.write(status.stderr.decode())
53 sys.stderr.write(status.stdout.decode())
54 sys.exit(2)
55 ast = json.loads(status.stdout.decode())
56 if ast['kind'] != 'TranslationUnitDecl':
57 common.error('Clang AST dump JSON format changed?')
58 sys.exit(2)
David Greeneeb669852019-10-08 16:25:42 +000059
Alex Richardson0df4a8f2019-11-15 12:50:10 +000060 # Get the inner node and iterate over all children of type FunctionDecl.
61 # TODO: Should we add checks for global variables being emitted?
62 for node in ast['inner']:
63 if node['kind'] != 'FunctionDecl':
David Greeneeb669852019-10-08 16:25:42 +000064 continue
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 Richardson0df4a8f2019-11-15 12:50:10 +000067 continue
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 Richardson0df4a8f2019-11-15 12:50:10 +000073 continue
74 spell = node['name']
75 mangled = node.get('mangledName', spell)
76 ret[int(line)-1] = (spell, mangled)
Alex Richardsond9542db2019-12-02 10:50:23 +000077 for line, func_name in sorted(ret.items()):
78 common.debug('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
Alex Richardson0df4a8f2019-11-15 12:50:10 +000079 if not ret:
80 common.warn('Did not find any functions using', ' '.join(json_dump_args))
Fangrui Song0a301a12018-03-02 17:37:04 +000081 return ret
82
83
84def config():
85 parser = argparse.ArgumentParser(
86 description=__doc__,
87 formatter_class=argparse.RawTextHelpFormatter)
Fangrui Song0a301a12018-03-02 17:37:04 +000088 parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
89 parser.add_argument('--clang',
90 help='"clang" executable, defaults to $llvm_bin/clang')
91 parser.add_argument('--clang-args',
92 help='Space-separated extra args to clang, e.g. --clang-args=-v')
Simon Tatham109c7732019-10-10 08:25:34 +000093 parser.add_argument('--opt',
94 help='"opt" executable, defaults to $llvm_bin/opt')
Fangrui Song0a301a12018-03-02 17:37:04 +000095 parser.add_argument(
96 '--functions', nargs='+', help='A list of function name regexes. '
97 'If specified, update CHECK lines for functions matching at least one regex')
98 parser.add_argument(
99 '--x86_extra_scrub', action='store_true',
100 help='Use more regex for x86 matching to reduce diffs between various subtargets')
Alex Richardson50807c82019-11-20 13:20:15 +0000101 parser.add_argument('--function-signature', action='store_true',
102 help='Keep function signature information around for the check line')
Fangrui Song0a301a12018-03-02 17:37:04 +0000103 parser.add_argument('tests', nargs='+')
Alex Richardson61873942019-11-20 13:19:48 +0000104 args = common.parse_commandline_args(parser)
Fangrui Song0a301a12018-03-02 17:37:04 +0000105 args.clang_args = shlex.split(args.clang_args or '')
106
107 if args.clang is None:
108 if args.llvm_bin is None:
109 args.clang = 'clang'
110 else:
111 args.clang = os.path.join(args.llvm_bin, 'clang')
112 if not distutils.spawn.find_executable(args.clang):
113 print('Please specify --llvm-bin or --clang', file=sys.stderr)
114 sys.exit(1)
Simon Tatham109c7732019-10-10 08:25:34 +0000115
Alex Richardsond9cc7d12019-10-31 21:18:32 +0000116 # Determine the builtin includes directory so that we can update tests that
117 # depend on the builtin headers. See get_clang_builtin_include_dir() and
118 # use_clang() in llvm/utils/lit/lit/llvm/config.py.
119 try:
120 builtin_include_dir = subprocess.check_output(
121 [args.clang, '-print-file-name=include']).decode().strip()
122 SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir,
123 '-nostdsysteminc']
124 except subprocess.CalledProcessError:
125 common.warn('Could not determine clang builtins directory, some tests '
126 'might not update correctly.')
127
Simon Tatham109c7732019-10-10 08:25:34 +0000128 if args.opt is None:
129 if args.llvm_bin is None:
130 args.opt = 'opt'
131 else:
132 args.opt = os.path.join(args.llvm_bin, 'opt')
133 if not distutils.spawn.find_executable(args.opt):
134 # Many uses of this tool will not need an opt binary, because it's only
135 # needed for updating a test that runs clang | opt | FileCheck. So we
136 # defer this error message until we find that opt is actually needed.
137 args.opt = None
138
Fangrui Song0a301a12018-03-02 17:37:04 +0000139 return args
140
141
Simon Tatham109c7732019-10-10 08:25:34 +0000142def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
Fangrui Song0a301a12018-03-02 17:37:04 +0000143 # TODO Clean up duplication of asm/common build_function_body_dictionary
144 # Invoke external tool and extract function bodies.
145 raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
Simon Tatham109c7732019-10-10 08:25:34 +0000146 for extra_command in extra_commands:
147 extra_args = shlex.split(extra_command)
148 with tempfile.NamedTemporaryFile() as f:
149 f.write(raw_tool_output.encode())
150 f.flush()
151 if extra_args[0] == 'opt':
152 if args.opt is None:
153 print(filename, 'needs to run opt. '
154 'Please specify --llvm-bin or --opt', file=sys.stderr)
155 sys.exit(1)
156 extra_args[0] = args.opt
157 raw_tool_output = common.invoke_tool(extra_args[0],
158 extra_args[1:], f.name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000159 if '-emit-llvm' in clang_args:
160 common.build_function_body_dictionary(
161 common.OPT_FUNCTION_RE, common.scrub_body, [],
Alex Richardson50807c82019-11-20 13:20:15 +0000162 raw_tool_output, prefixes, func_dict, args.verbose, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000163 else:
164 print('The clang command line should include -emit-llvm as asm tests '
165 'are discouraged in Clang testsuite.', file=sys.stderr)
166 sys.exit(1)
167
168
169def main():
170 args = config()
David Bolvansky7169ea32019-08-07 14:44:50 +0000171 script_name = os.path.basename(__file__)
172 autogenerated_note = (ADVERT + 'utils/' + script_name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000173
174 for filename in args.tests:
175 with open(filename) as f:
176 input_lines = [l.rstrip() for l in f]
Johannes Doerferte67f6472019-11-01 11:17:27 -0500177
David Bolvansky7169ea32019-08-07 14:44:50 +0000178 first_line = input_lines[0] if input_lines else ""
179 if 'autogenerated' in first_line and script_name not in first_line:
180 common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
181 continue
182
183 if args.update_only:
184 if not first_line or 'autogenerated' not in first_line:
185 common.warn("Skipping test which isn't autogenerated: " + filename)
186 continue
Fangrui Song0a301a12018-03-02 17:37:04 +0000187
188 # Extract RUN lines.
Alex Richardsond9542db2019-12-02 10:50:23 +0000189 run_lines = common.find_run_lines(filename, input_lines)
Fangrui Song0a301a12018-03-02 17:37:04 +0000190
191 # Build a list of clang command lines and check prefixes from RUN lines.
192 run_list = []
193 line2spell_and_mangled_list = collections.defaultdict(list)
194 for l in run_lines:
Simon Tatham109c7732019-10-10 08:25:34 +0000195 commands = [cmd.strip() for cmd in l.split('|')]
Fangrui Song0a301a12018-03-02 17:37:04 +0000196
197 triple_in_cmd = None
198 m = common.TRIPLE_ARG_RE.search(commands[0])
199 if m:
200 triple_in_cmd = m.groups()[0]
201
202 # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
203 clang_args = shlex.split(commands[0])
204 if clang_args[0] not in SUBST:
205 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
206 continue
207 clang_args[0:1] = SUBST[clang_args[0]]
208 clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
209
Simon Tatham109c7732019-10-10 08:25:34 +0000210 # Permit piping the output through opt
211 if not (len(commands) == 2 or
212 (len(commands) == 3 and commands[1].startswith('opt'))):
213 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
214
Fangrui Song0a301a12018-03-02 17:37:04 +0000215 # Extract -check-prefix in FileCheck args
216 filecheck_cmd = commands[-1]
David Bolvansky45be5e42019-07-29 17:41:00 +0000217 common.verify_filecheck_prefixes(filecheck_cmd)
Fangrui Song0a301a12018-03-02 17:37:04 +0000218 if not filecheck_cmd.startswith('FileCheck '):
219 print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
220 continue
221 check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
222 for item in m.group(1).split(',')]
223 if not check_prefixes:
224 check_prefixes = ['CHECK']
Simon Tatham109c7732019-10-10 08:25:34 +0000225 run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
Fangrui Song0a301a12018-03-02 17:37:04 +0000226
227 # Strip CHECK lines which are in `prefix_set`, update test file.
228 prefix_set = set([prefix for p in run_list for prefix in p[0]])
229 input_lines = []
230 with open(filename, 'r+') as f:
231 for line in f:
232 m = CHECK_RE.match(line)
233 if not (m and m.group(1) in prefix_set) and line != '//\n':
234 input_lines.append(line)
235 f.seek(0)
236 f.writelines(input_lines)
237 f.truncate()
238
239 # Execute clang, generate LLVM IR, and extract functions.
240 func_dict = {}
241 for p in run_list:
242 prefixes = p[0]
243 for prefix in prefixes:
244 func_dict.update({prefix: dict()})
Simon Tatham109c7732019-10-10 08:25:34 +0000245 for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
Alex Richardsond9542db2019-12-02 10:50:23 +0000246 common.debug('Extracted clang cmd: clang {}'.format(clang_args))
247 common.debug('Extracted FileCheck prefixes: {}'.format(prefixes))
Fangrui Song0a301a12018-03-02 17:37:04 +0000248
Simon Tatham109c7732019-10-10 08:25:34 +0000249 get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
Fangrui Song0a301a12018-03-02 17:37:04 +0000250
Alex Richardson0df4a8f2019-11-15 12:50:10 +0000251 # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to
252 # mangled names. Forward all clang args for now.
Fangrui Song0a301a12018-03-02 17:37:04 +0000253 for k, v in get_line2spell_and_mangled(args, clang_args).items():
254 line2spell_and_mangled_list[k].append(v)
255
256 output_lines = [autogenerated_note]
257 for idx, line in enumerate(input_lines):
258 # Discard any previous script advertising.
259 if line.startswith(ADVERT):
260 continue
261 if idx in line2spell_and_mangled_list:
262 added = set()
263 for spell, mangled in line2spell_and_mangled_list[idx]:
264 # One line may contain multiple function declarations.
265 # Skip if the mangled name has been added before.
266 # The line number may come from an included file,
267 # we simply require the spelling name to appear on the line
268 # to exclude functions from other files.
269 if mangled in added or spell not in line:
270 continue
271 if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
272 if added:
273 output_lines.append('//')
274 added.add(mangled)
Alex Richardson50807c82019-11-20 13:20:15 +0000275 common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled,
276 False, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000277 output_lines.append(line.rstrip('\n'))
278
279 # Update the test file.
280 with open(filename, 'w') as f:
281 for line in output_lines:
282 f.write(line + '\n')
283
284 return 0
285
286
287if __name__ == '__main__':
288 sys.exit(main())