blob: 79753acaa87dcb7e792ab8132bb844c48333d1cb [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)?:')
Alex Richardson4a372092019-10-30 09:17:29 +000032RUN_LINE_RE = re.compile(r'^//\s*RUN:\s*(.*)$')
Fangrui Song0a301a12018-03-02 17:37:04 +000033
34SUBST = {
35 '%clang': [],
36 '%clang_cc1': ['-cc1'],
37 '%clangxx': ['--driver-mode=g++'],
38}
39
40def get_line2spell_and_mangled(args, clang_args):
Alex Richardson0df4a8f2019-11-15 12:50:10 +000041 def debug_mangled(*print_args, **kwargs):
42 if args.verbose:
43 print(*print_args, file=sys.stderr, **kwargs)
Fangrui Song0a301a12018-03-02 17:37:04 +000044 ret = {}
Alex Richardson0df4a8f2019-11-15 12:50:10 +000045 # Use clang's JSON AST dump to get the mangled name
46 json_dump_args = [args.clang, *clang_args, '-fsyntax-only', '-o', '-']
47 if '-cc1' not in json_dump_args:
48 # For tests that invoke %clang instead if %clang_cc1 we have to use
49 # -Xclang -ast-dump=json instead:
50 json_dump_args.append('-Xclang')
51 json_dump_args.append('-ast-dump=json')
52 debug_mangled('Running', ' '.join(json_dump_args))
53 status = subprocess.run(json_dump_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
54 if status.returncode != 0:
55 sys.stderr.write('Failed to run ' + ' '.join(json_dump_args) + '\n')
56 sys.stderr.write(status.stderr.decode())
57 sys.stderr.write(status.stdout.decode())
58 sys.exit(2)
59 ast = json.loads(status.stdout.decode())
60 if ast['kind'] != 'TranslationUnitDecl':
61 common.error('Clang AST dump JSON format changed?')
62 sys.exit(2)
David Greeneeb669852019-10-08 16:25:42 +000063
Alex Richardson0df4a8f2019-11-15 12:50:10 +000064 # Get the inner node and iterate over all children of type FunctionDecl.
65 # TODO: Should we add checks for global variables being emitted?
66 for node in ast['inner']:
67 if node['kind'] != 'FunctionDecl':
David Greeneeb669852019-10-08 16:25:42 +000068 continue
Alex Richardson0df4a8f2019-11-15 12:50:10 +000069 if node.get('isImplicit') is True and node.get('storageClass') == 'extern':
70 debug_mangled('Skipping builtin function:', node['name'], '@', node['loc'])
71 continue
72 debug_mangled('Found function:', node['kind'], node['name'], '@', node['loc'])
73 line = node['loc'].get('line')
74 # If there is no line it is probably a builtin function -> skip
75 if line is None:
76 debug_mangled('Skipping function without line number:', node['name'], '@', node['loc'])
77 continue
78 spell = node['name']
79 mangled = node.get('mangledName', spell)
80 ret[int(line)-1] = (spell, mangled)
Fangrui Song0a301a12018-03-02 17:37:04 +000081 if args.verbose:
82 for line, func_name in sorted(ret.items()):
83 print('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
Alex Richardson0df4a8f2019-11-15 12:50:10 +000084 if not ret:
85 common.warn('Did not find any functions using', ' '.join(json_dump_args))
Fangrui Song0a301a12018-03-02 17:37:04 +000086 return ret
87
88
89def config():
90 parser = argparse.ArgumentParser(
91 description=__doc__,
92 formatter_class=argparse.RawTextHelpFormatter)
93 parser.add_argument('-v', '--verbose', action='store_true')
94 parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
95 parser.add_argument('--clang',
96 help='"clang" executable, defaults to $llvm_bin/clang')
97 parser.add_argument('--clang-args',
98 help='Space-separated extra args to clang, e.g. --clang-args=-v')
Simon Tatham109c7732019-10-10 08:25:34 +000099 parser.add_argument('--opt',
100 help='"opt" executable, defaults to $llvm_bin/opt')
Fangrui Song0a301a12018-03-02 17:37:04 +0000101 parser.add_argument(
102 '--functions', nargs='+', help='A list of function name regexes. '
103 'If specified, update CHECK lines for functions matching at least one regex')
104 parser.add_argument(
105 '--x86_extra_scrub', action='store_true',
106 help='Use more regex for x86 matching to reduce diffs between various subtargets')
David Bolvansky7169ea32019-08-07 14:44:50 +0000107 parser.add_argument('-u', '--update-only', action='store_true',
108 help='Only update test if it was already autogened')
Fangrui Song0a301a12018-03-02 17:37:04 +0000109 parser.add_argument('tests', nargs='+')
110 args = parser.parse_args()
111 args.clang_args = shlex.split(args.clang_args or '')
112
113 if args.clang is None:
114 if args.llvm_bin is None:
115 args.clang = 'clang'
116 else:
117 args.clang = os.path.join(args.llvm_bin, 'clang')
118 if not distutils.spawn.find_executable(args.clang):
119 print('Please specify --llvm-bin or --clang', file=sys.stderr)
120 sys.exit(1)
Simon Tatham109c7732019-10-10 08:25:34 +0000121
Alex Richardsond9cc7d12019-10-31 21:18:32 +0000122 # Determine the builtin includes directory so that we can update tests that
123 # depend on the builtin headers. See get_clang_builtin_include_dir() and
124 # use_clang() in llvm/utils/lit/lit/llvm/config.py.
125 try:
126 builtin_include_dir = subprocess.check_output(
127 [args.clang, '-print-file-name=include']).decode().strip()
128 SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir,
129 '-nostdsysteminc']
130 except subprocess.CalledProcessError:
131 common.warn('Could not determine clang builtins directory, some tests '
132 'might not update correctly.')
133
Simon Tatham109c7732019-10-10 08:25:34 +0000134 if args.opt is None:
135 if args.llvm_bin is None:
136 args.opt = 'opt'
137 else:
138 args.opt = os.path.join(args.llvm_bin, 'opt')
139 if not distutils.spawn.find_executable(args.opt):
140 # Many uses of this tool will not need an opt binary, because it's only
141 # needed for updating a test that runs clang | opt | FileCheck. So we
142 # defer this error message until we find that opt is actually needed.
143 args.opt = None
144
Fangrui Song0a301a12018-03-02 17:37:04 +0000145 return args
146
147
Simon Tatham109c7732019-10-10 08:25:34 +0000148def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
Fangrui Song0a301a12018-03-02 17:37:04 +0000149 # TODO Clean up duplication of asm/common build_function_body_dictionary
150 # Invoke external tool and extract function bodies.
151 raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
Simon Tatham109c7732019-10-10 08:25:34 +0000152 for extra_command in extra_commands:
153 extra_args = shlex.split(extra_command)
154 with tempfile.NamedTemporaryFile() as f:
155 f.write(raw_tool_output.encode())
156 f.flush()
157 if extra_args[0] == 'opt':
158 if args.opt is None:
159 print(filename, 'needs to run opt. '
160 'Please specify --llvm-bin or --opt', file=sys.stderr)
161 sys.exit(1)
162 extra_args[0] = args.opt
163 raw_tool_output = common.invoke_tool(extra_args[0],
164 extra_args[1:], f.name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000165 if '-emit-llvm' in clang_args:
166 common.build_function_body_dictionary(
167 common.OPT_FUNCTION_RE, common.scrub_body, [],
Johannes Doerfert4de09e02019-10-31 13:37:34 -0500168 raw_tool_output, prefixes, func_dict, args.verbose, False)
Fangrui Song0a301a12018-03-02 17:37:04 +0000169 else:
170 print('The clang command line should include -emit-llvm as asm tests '
171 'are discouraged in Clang testsuite.', file=sys.stderr)
172 sys.exit(1)
173
174
175def main():
176 args = config()
David Bolvansky7169ea32019-08-07 14:44:50 +0000177 script_name = os.path.basename(__file__)
178 autogenerated_note = (ADVERT + 'utils/' + script_name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000179
180 for filename in args.tests:
181 with open(filename) as f:
182 input_lines = [l.rstrip() for l in f]
Johannes Doerferte67f6472019-11-01 11:17:27 -0500183
David Bolvansky7169ea32019-08-07 14:44:50 +0000184 first_line = input_lines[0] if input_lines else ""
185 if 'autogenerated' in first_line and script_name not in first_line:
186 common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
187 continue
188
189 if args.update_only:
190 if not first_line or 'autogenerated' not in first_line:
191 common.warn("Skipping test which isn't autogenerated: " + filename)
192 continue
Fangrui Song0a301a12018-03-02 17:37:04 +0000193
194 # Extract RUN lines.
195 raw_lines = [m.group(1)
196 for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
197 run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
198 for l in raw_lines[1:]:
199 if run_lines[-1].endswith("\\"):
200 run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
201 else:
202 run_lines.append(l)
203
204 if args.verbose:
205 print('Found {} RUN lines:'.format(len(run_lines)), file=sys.stderr)
206 for l in run_lines:
207 print(' RUN: ' + l, file=sys.stderr)
208
209 # Build a list of clang command lines and check prefixes from RUN lines.
210 run_list = []
211 line2spell_and_mangled_list = collections.defaultdict(list)
212 for l in run_lines:
Simon Tatham109c7732019-10-10 08:25:34 +0000213 commands = [cmd.strip() for cmd in l.split('|')]
Fangrui Song0a301a12018-03-02 17:37:04 +0000214
215 triple_in_cmd = None
216 m = common.TRIPLE_ARG_RE.search(commands[0])
217 if m:
218 triple_in_cmd = m.groups()[0]
219
220 # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
221 clang_args = shlex.split(commands[0])
222 if clang_args[0] not in SUBST:
223 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
224 continue
225 clang_args[0:1] = SUBST[clang_args[0]]
226 clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
227
Simon Tatham109c7732019-10-10 08:25:34 +0000228 # Permit piping the output through opt
229 if not (len(commands) == 2 or
230 (len(commands) == 3 and commands[1].startswith('opt'))):
231 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
232
Fangrui Song0a301a12018-03-02 17:37:04 +0000233 # Extract -check-prefix in FileCheck args
234 filecheck_cmd = commands[-1]
David Bolvansky45be5e42019-07-29 17:41:00 +0000235 common.verify_filecheck_prefixes(filecheck_cmd)
Fangrui Song0a301a12018-03-02 17:37:04 +0000236 if not filecheck_cmd.startswith('FileCheck '):
237 print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
238 continue
239 check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
240 for item in m.group(1).split(',')]
241 if not check_prefixes:
242 check_prefixes = ['CHECK']
Simon Tatham109c7732019-10-10 08:25:34 +0000243 run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
Fangrui Song0a301a12018-03-02 17:37:04 +0000244
245 # Strip CHECK lines which are in `prefix_set`, update test file.
246 prefix_set = set([prefix for p in run_list for prefix in p[0]])
247 input_lines = []
248 with open(filename, 'r+') as f:
249 for line in f:
250 m = CHECK_RE.match(line)
251 if not (m and m.group(1) in prefix_set) and line != '//\n':
252 input_lines.append(line)
253 f.seek(0)
254 f.writelines(input_lines)
255 f.truncate()
256
257 # Execute clang, generate LLVM IR, and extract functions.
258 func_dict = {}
259 for p in run_list:
260 prefixes = p[0]
261 for prefix in prefixes:
262 func_dict.update({prefix: dict()})
Simon Tatham109c7732019-10-10 08:25:34 +0000263 for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
Fangrui Song0a301a12018-03-02 17:37:04 +0000264 if args.verbose:
265 print('Extracted clang cmd: clang {}'.format(clang_args), file=sys.stderr)
266 print('Extracted FileCheck prefixes: {}'.format(prefixes), file=sys.stderr)
267
Simon Tatham109c7732019-10-10 08:25:34 +0000268 get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
Fangrui Song0a301a12018-03-02 17:37:04 +0000269
Alex Richardson0df4a8f2019-11-15 12:50:10 +0000270 # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to
271 # mangled names. Forward all clang args for now.
Fangrui Song0a301a12018-03-02 17:37:04 +0000272 for k, v in get_line2spell_and_mangled(args, clang_args).items():
273 line2spell_and_mangled_list[k].append(v)
274
275 output_lines = [autogenerated_note]
276 for idx, line in enumerate(input_lines):
277 # Discard any previous script advertising.
278 if line.startswith(ADVERT):
279 continue
280 if idx in line2spell_and_mangled_list:
281 added = set()
282 for spell, mangled in line2spell_and_mangled_list[idx]:
283 # One line may contain multiple function declarations.
284 # Skip if the mangled name has been added before.
285 # The line number may come from an included file,
286 # we simply require the spelling name to appear on the line
287 # to exclude functions from other files.
288 if mangled in added or spell not in line:
289 continue
290 if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
291 if added:
292 output_lines.append('//')
293 added.add(mangled)
Johannes Doerferte67f6472019-11-01 11:17:27 -0500294 common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled, False, False)
Fangrui Song0a301a12018-03-02 17:37:04 +0000295 output_lines.append(line.rstrip('\n'))
296
297 # Update the test file.
298 with open(filename, 'w') as f:
299 for line in output_lines:
300 f.write(line + '\n')
301
302 return 0
303
304
305if __name__ == '__main__':
306 sys.exit(main())