blob: 4358acce016e46ba7a3ac2c3762e889c54f5d515 [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)
Fangrui Song0a301a12018-03-02 17:37:04 +000093 parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
94 parser.add_argument('--clang',
95 help='"clang" executable, defaults to $llvm_bin/clang')
96 parser.add_argument('--clang-args',
97 help='Space-separated extra args to clang, e.g. --clang-args=-v')
Simon Tatham109c7732019-10-10 08:25:34 +000098 parser.add_argument('--opt',
99 help='"opt" executable, defaults to $llvm_bin/opt')
Fangrui Song0a301a12018-03-02 17:37:04 +0000100 parser.add_argument(
101 '--functions', nargs='+', help='A list of function name regexes. '
102 'If specified, update CHECK lines for functions matching at least one regex')
103 parser.add_argument(
104 '--x86_extra_scrub', action='store_true',
105 help='Use more regex for x86 matching to reduce diffs between various subtargets')
106 parser.add_argument('tests', nargs='+')
Alex Richardson61873942019-11-20 13:19:48 +0000107 args = common.parse_commandline_args(parser)
Fangrui Song0a301a12018-03-02 17:37:04 +0000108 args.clang_args = shlex.split(args.clang_args or '')
109
110 if args.clang is None:
111 if args.llvm_bin is None:
112 args.clang = 'clang'
113 else:
114 args.clang = os.path.join(args.llvm_bin, 'clang')
115 if not distutils.spawn.find_executable(args.clang):
116 print('Please specify --llvm-bin or --clang', file=sys.stderr)
117 sys.exit(1)
Simon Tatham109c7732019-10-10 08:25:34 +0000118
Alex Richardsond9cc7d12019-10-31 21:18:32 +0000119 # Determine the builtin includes directory so that we can update tests that
120 # depend on the builtin headers. See get_clang_builtin_include_dir() and
121 # use_clang() in llvm/utils/lit/lit/llvm/config.py.
122 try:
123 builtin_include_dir = subprocess.check_output(
124 [args.clang, '-print-file-name=include']).decode().strip()
125 SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir,
126 '-nostdsysteminc']
127 except subprocess.CalledProcessError:
128 common.warn('Could not determine clang builtins directory, some tests '
129 'might not update correctly.')
130
Simon Tatham109c7732019-10-10 08:25:34 +0000131 if args.opt is None:
132 if args.llvm_bin is None:
133 args.opt = 'opt'
134 else:
135 args.opt = os.path.join(args.llvm_bin, 'opt')
136 if not distutils.spawn.find_executable(args.opt):
137 # Many uses of this tool will not need an opt binary, because it's only
138 # needed for updating a test that runs clang | opt | FileCheck. So we
139 # defer this error message until we find that opt is actually needed.
140 args.opt = None
141
Fangrui Song0a301a12018-03-02 17:37:04 +0000142 return args
143
144
Simon Tatham109c7732019-10-10 08:25:34 +0000145def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
Fangrui Song0a301a12018-03-02 17:37:04 +0000146 # TODO Clean up duplication of asm/common build_function_body_dictionary
147 # Invoke external tool and extract function bodies.
148 raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
Simon Tatham109c7732019-10-10 08:25:34 +0000149 for extra_command in extra_commands:
150 extra_args = shlex.split(extra_command)
151 with tempfile.NamedTemporaryFile() as f:
152 f.write(raw_tool_output.encode())
153 f.flush()
154 if extra_args[0] == 'opt':
155 if args.opt is None:
156 print(filename, 'needs to run opt. '
157 'Please specify --llvm-bin or --opt', file=sys.stderr)
158 sys.exit(1)
159 extra_args[0] = args.opt
160 raw_tool_output = common.invoke_tool(extra_args[0],
161 extra_args[1:], f.name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000162 if '-emit-llvm' in clang_args:
163 common.build_function_body_dictionary(
164 common.OPT_FUNCTION_RE, common.scrub_body, [],
Johannes Doerfert4de09e02019-10-31 13:37:34 -0500165 raw_tool_output, prefixes, func_dict, args.verbose, False)
Fangrui Song0a301a12018-03-02 17:37:04 +0000166 else:
167 print('The clang command line should include -emit-llvm as asm tests '
168 'are discouraged in Clang testsuite.', file=sys.stderr)
169 sys.exit(1)
170
171
172def main():
173 args = config()
David Bolvansky7169ea32019-08-07 14:44:50 +0000174 script_name = os.path.basename(__file__)
175 autogenerated_note = (ADVERT + 'utils/' + script_name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000176
177 for filename in args.tests:
178 with open(filename) as f:
179 input_lines = [l.rstrip() for l in f]
Johannes Doerferte67f6472019-11-01 11:17:27 -0500180
David Bolvansky7169ea32019-08-07 14:44:50 +0000181 first_line = input_lines[0] if input_lines else ""
182 if 'autogenerated' in first_line and script_name not in first_line:
183 common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
184 continue
185
186 if args.update_only:
187 if not first_line or 'autogenerated' not in first_line:
188 common.warn("Skipping test which isn't autogenerated: " + filename)
189 continue
Fangrui Song0a301a12018-03-02 17:37:04 +0000190
191 # Extract RUN lines.
192 raw_lines = [m.group(1)
193 for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
194 run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
195 for l in raw_lines[1:]:
196 if run_lines[-1].endswith("\\"):
197 run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
198 else:
199 run_lines.append(l)
200
201 if args.verbose:
202 print('Found {} RUN lines:'.format(len(run_lines)), file=sys.stderr)
203 for l in run_lines:
204 print(' RUN: ' + l, file=sys.stderr)
205
206 # Build a list of clang command lines and check prefixes from RUN lines.
207 run_list = []
208 line2spell_and_mangled_list = collections.defaultdict(list)
209 for l in run_lines:
Simon Tatham109c7732019-10-10 08:25:34 +0000210 commands = [cmd.strip() for cmd in l.split('|')]
Fangrui Song0a301a12018-03-02 17:37:04 +0000211
212 triple_in_cmd = None
213 m = common.TRIPLE_ARG_RE.search(commands[0])
214 if m:
215 triple_in_cmd = m.groups()[0]
216
217 # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
218 clang_args = shlex.split(commands[0])
219 if clang_args[0] not in SUBST:
220 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
221 continue
222 clang_args[0:1] = SUBST[clang_args[0]]
223 clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
224
Simon Tatham109c7732019-10-10 08:25:34 +0000225 # Permit piping the output through opt
226 if not (len(commands) == 2 or
227 (len(commands) == 3 and commands[1].startswith('opt'))):
228 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
229
Fangrui Song0a301a12018-03-02 17:37:04 +0000230 # Extract -check-prefix in FileCheck args
231 filecheck_cmd = commands[-1]
David Bolvansky45be5e42019-07-29 17:41:00 +0000232 common.verify_filecheck_prefixes(filecheck_cmd)
Fangrui Song0a301a12018-03-02 17:37:04 +0000233 if not filecheck_cmd.startswith('FileCheck '):
234 print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
235 continue
236 check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
237 for item in m.group(1).split(',')]
238 if not check_prefixes:
239 check_prefixes = ['CHECK']
Simon Tatham109c7732019-10-10 08:25:34 +0000240 run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
Fangrui Song0a301a12018-03-02 17:37:04 +0000241
242 # Strip CHECK lines which are in `prefix_set`, update test file.
243 prefix_set = set([prefix for p in run_list for prefix in p[0]])
244 input_lines = []
245 with open(filename, 'r+') as f:
246 for line in f:
247 m = CHECK_RE.match(line)
248 if not (m and m.group(1) in prefix_set) and line != '//\n':
249 input_lines.append(line)
250 f.seek(0)
251 f.writelines(input_lines)
252 f.truncate()
253
254 # Execute clang, generate LLVM IR, and extract functions.
255 func_dict = {}
256 for p in run_list:
257 prefixes = p[0]
258 for prefix in prefixes:
259 func_dict.update({prefix: dict()})
Simon Tatham109c7732019-10-10 08:25:34 +0000260 for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
Fangrui Song0a301a12018-03-02 17:37:04 +0000261 if args.verbose:
262 print('Extracted clang cmd: clang {}'.format(clang_args), file=sys.stderr)
263 print('Extracted FileCheck prefixes: {}'.format(prefixes), file=sys.stderr)
264
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)
Johannes Doerferte67f6472019-11-01 11:17:27 -0500291 common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled, False, False)
Fangrui Song0a301a12018-03-02 17:37:04 +0000292 output_lines.append(line.rstrip('\n'))
293
294 # Update the test file.
295 with open(filename, 'w') as f:
296 for line in output_lines:
297 f.write(line + '\n')
298
299 return 0
300
301
302if __name__ == '__main__':
303 sys.exit(main())