Nico Weber | 9d49e5c | 2020-01-02 13:44:54 -0500 | [diff] [blame] | 1 | #!/usr/bin/env python |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 2 | '''A utility to update LLVM IR CHECK lines in C/C++ FileCheck test files. |
| 3 | |
| 4 | Example 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 | |
| 9 | Usage: |
| 10 | |
| 11 | % utils/update_cc_test_checks.py --llvm-bin=release/bin test/a.cc |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 12 | % utils/update_cc_test_checks.py --clang=release/bin/clang /tmp/c/a.cc |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 13 | ''' |
| 14 | |
Nico Weber | 9d49e5c | 2020-01-02 13:44:54 -0500 | [diff] [blame] | 15 | from __future__ import print_function |
| 16 | |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 17 | import argparse |
| 18 | import collections |
| 19 | import distutils.spawn |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 20 | import json |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 21 | import os |
| 22 | import shlex |
| 23 | import string |
| 24 | import subprocess |
| 25 | import sys |
| 26 | import re |
| 27 | import tempfile |
| 28 | |
| 29 | from UpdateTestChecks import asm, common |
| 30 | |
| 31 | ADVERT = '// NOTE: Assertions have been autogenerated by ' |
| 32 | |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 33 | SUBST = { |
| 34 | '%clang': [], |
| 35 | '%clang_cc1': ['-cc1'], |
| 36 | '%clangxx': ['--driver-mode=g++'], |
| 37 | } |
| 38 | |
| 39 | def get_line2spell_and_mangled(args, clang_args): |
| 40 | ret = {} |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 41 | # Use clang's JSON AST dump to get the mangled name |
Nico Weber | 9d49e5c | 2020-01-02 13:44:54 -0500 | [diff] [blame] | 42 | json_dump_args = [args.clang] + clang_args + ['-fsyntax-only', '-o', '-'] |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 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 Richardson | d9542db | 2019-12-02 10:50:23 +0000 | [diff] [blame] | 48 | common.debug('Running', ' '.join(json_dump_args)) |
Nico Weber | 9d49e5c | 2020-01-02 13:44:54 -0500 | [diff] [blame] | 49 | |
| 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 Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 54 | sys.stderr.write('Failed to run ' + ' '.join(json_dump_args) + '\n') |
Nico Weber | 9d49e5c | 2020-01-02 13:44:54 -0500 | [diff] [blame] | 55 | sys.stderr.write(stderr) |
| 56 | sys.stderr.write(stdout) |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 57 | sys.exit(2) |
David Greene | eb66985 | 2019-10-08 16:25:42 +0000 | [diff] [blame] | 58 | |
Alex Richardson | 8ab3b4d | 2019-12-02 10:53:57 +0000 | [diff] [blame] | 59 | # Parse the clang JSON and add all children of type FunctionDecl. |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 60 | # TODO: Should we add checks for global variables being emitted? |
Alex Richardson | 8ab3b4d | 2019-12-02 10:53:57 +0000 | [diff] [blame] | 61 | 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 Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 68 | if node['kind'] != 'FunctionDecl': |
Alex Richardson | 8ab3b4d | 2019-12-02 10:53:57 +0000 | [diff] [blame] | 69 | return |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 70 | if node.get('isImplicit') is True and node.get('storageClass') == 'extern': |
Alex Richardson | d9542db | 2019-12-02 10:50:23 +0000 | [diff] [blame] | 71 | common.debug('Skipping builtin function:', node['name'], '@', node['loc']) |
Alex Richardson | 8ab3b4d | 2019-12-02 10:53:57 +0000 | [diff] [blame] | 72 | return |
Alex Richardson | d9542db | 2019-12-02 10:50:23 +0000 | [diff] [blame] | 73 | common.debug('Found function:', node['kind'], node['name'], '@', node['loc']) |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 74 | line = node['loc'].get('line') |
| 75 | # If there is no line it is probably a builtin function -> skip |
| 76 | if line is None: |
Alex Richardson | d9542db | 2019-12-02 10:50:23 +0000 | [diff] [blame] | 77 | common.debug('Skipping function without line number:', node['name'], '@', node['loc']) |
Alex Richardson | 8ab3b4d | 2019-12-02 10:53:57 +0000 | [diff] [blame] | 78 | return |
Alex Richardson | 1132f87 | 2020-02-04 08:40:56 +0000 | [diff] [blame] | 79 | # If there is no 'inner' object, it is a function declaration -> skip |
| 80 | if 'inner' not in node: |
| 81 | common.debug('Skipping function without body:', node['name'], '@', node['loc']) |
| 82 | return |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 83 | spell = node['name'] |
| 84 | mangled = node.get('mangledName', spell) |
| 85 | ret[int(line)-1] = (spell, mangled) |
Alex Richardson | 8ab3b4d | 2019-12-02 10:53:57 +0000 | [diff] [blame] | 86 | |
Nico Weber | 9d49e5c | 2020-01-02 13:44:54 -0500 | [diff] [blame] | 87 | ast = json.loads(stdout) |
Alex Richardson | 8ab3b4d | 2019-12-02 10:53:57 +0000 | [diff] [blame] | 88 | if ast['kind'] != 'TranslationUnitDecl': |
| 89 | common.error('Clang AST dump JSON format changed?') |
| 90 | sys.exit(2) |
| 91 | parse_clang_ast_json(ast) |
| 92 | |
Alex Richardson | d9542db | 2019-12-02 10:50:23 +0000 | [diff] [blame] | 93 | for line, func_name in sorted(ret.items()): |
| 94 | common.debug('line {}: found function {}'.format(line+1, func_name), file=sys.stderr) |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 95 | if not ret: |
| 96 | common.warn('Did not find any functions using', ' '.join(json_dump_args)) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 97 | return ret |
| 98 | |
| 99 | |
| 100 | def config(): |
| 101 | parser = argparse.ArgumentParser( |
| 102 | description=__doc__, |
| 103 | formatter_class=argparse.RawTextHelpFormatter) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 104 | parser.add_argument('--llvm-bin', help='llvm $prefix/bin path') |
| 105 | parser.add_argument('--clang', |
| 106 | help='"clang" executable, defaults to $llvm_bin/clang') |
| 107 | parser.add_argument('--clang-args', |
| 108 | help='Space-separated extra args to clang, e.g. --clang-args=-v') |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 109 | parser.add_argument('--opt', |
| 110 | help='"opt" executable, defaults to $llvm_bin/opt') |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 111 | parser.add_argument( |
| 112 | '--functions', nargs='+', help='A list of function name regexes. ' |
| 113 | 'If specified, update CHECK lines for functions matching at least one regex') |
| 114 | parser.add_argument( |
| 115 | '--x86_extra_scrub', action='store_true', |
| 116 | help='Use more regex for x86 matching to reduce diffs between various subtargets') |
Alex Richardson | 50807c8 | 2019-11-20 13:20:15 +0000 | [diff] [blame] | 117 | parser.add_argument('--function-signature', action='store_true', |
| 118 | help='Keep function signature information around for the check line') |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 119 | parser.add_argument('tests', nargs='+') |
Alex Richardson | 6187394 | 2019-11-20 13:19:48 +0000 | [diff] [blame] | 120 | args = common.parse_commandline_args(parser) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 121 | args.clang_args = shlex.split(args.clang_args or '') |
| 122 | |
| 123 | if args.clang is None: |
| 124 | if args.llvm_bin is None: |
| 125 | args.clang = 'clang' |
| 126 | else: |
| 127 | args.clang = os.path.join(args.llvm_bin, 'clang') |
| 128 | if not distutils.spawn.find_executable(args.clang): |
| 129 | print('Please specify --llvm-bin or --clang', file=sys.stderr) |
| 130 | sys.exit(1) |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 131 | |
Alex Richardson | d9cc7d1 | 2019-10-31 21:18:32 +0000 | [diff] [blame] | 132 | # Determine the builtin includes directory so that we can update tests that |
| 133 | # depend on the builtin headers. See get_clang_builtin_include_dir() and |
| 134 | # use_clang() in llvm/utils/lit/lit/llvm/config.py. |
| 135 | try: |
| 136 | builtin_include_dir = subprocess.check_output( |
| 137 | [args.clang, '-print-file-name=include']).decode().strip() |
| 138 | SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir, |
| 139 | '-nostdsysteminc'] |
| 140 | except subprocess.CalledProcessError: |
| 141 | common.warn('Could not determine clang builtins directory, some tests ' |
| 142 | 'might not update correctly.') |
| 143 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 144 | if args.opt is None: |
| 145 | if args.llvm_bin is None: |
| 146 | args.opt = 'opt' |
| 147 | else: |
| 148 | args.opt = os.path.join(args.llvm_bin, 'opt') |
| 149 | if not distutils.spawn.find_executable(args.opt): |
| 150 | # Many uses of this tool will not need an opt binary, because it's only |
| 151 | # needed for updating a test that runs clang | opt | FileCheck. So we |
| 152 | # defer this error message until we find that opt is actually needed. |
| 153 | args.opt = None |
| 154 | |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 155 | return args |
| 156 | |
| 157 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 158 | def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict): |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 159 | # TODO Clean up duplication of asm/common build_function_body_dictionary |
| 160 | # Invoke external tool and extract function bodies. |
| 161 | raw_tool_output = common.invoke_tool(args.clang, clang_args, filename) |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 162 | for extra_command in extra_commands: |
| 163 | extra_args = shlex.split(extra_command) |
| 164 | with tempfile.NamedTemporaryFile() as f: |
| 165 | f.write(raw_tool_output.encode()) |
| 166 | f.flush() |
| 167 | if extra_args[0] == 'opt': |
| 168 | if args.opt is None: |
| 169 | print(filename, 'needs to run opt. ' |
| 170 | 'Please specify --llvm-bin or --opt', file=sys.stderr) |
| 171 | sys.exit(1) |
| 172 | extra_args[0] = args.opt |
| 173 | raw_tool_output = common.invoke_tool(extra_args[0], |
| 174 | extra_args[1:], f.name) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 175 | if '-emit-llvm' in clang_args: |
| 176 | common.build_function_body_dictionary( |
| 177 | common.OPT_FUNCTION_RE, common.scrub_body, [], |
Alex Richardson | 50807c8 | 2019-11-20 13:20:15 +0000 | [diff] [blame] | 178 | raw_tool_output, prefixes, func_dict, args.verbose, args.function_signature) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 179 | else: |
| 180 | print('The clang command line should include -emit-llvm as asm tests ' |
| 181 | 'are discouraged in Clang testsuite.', file=sys.stderr) |
| 182 | sys.exit(1) |
| 183 | |
| 184 | |
| 185 | def main(): |
| 186 | args = config() |
David Bolvansky | 7169ea3 | 2019-08-07 14:44:50 +0000 | [diff] [blame] | 187 | script_name = os.path.basename(__file__) |
| 188 | autogenerated_note = (ADVERT + 'utils/' + script_name) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 189 | |
| 190 | for filename in args.tests: |
| 191 | with open(filename) as f: |
| 192 | input_lines = [l.rstrip() for l in f] |
Johannes Doerfert | e67f647 | 2019-11-01 11:17:27 -0500 | [diff] [blame] | 193 | |
David Bolvansky | 7169ea3 | 2019-08-07 14:44:50 +0000 | [diff] [blame] | 194 | first_line = input_lines[0] if input_lines else "" |
| 195 | if 'autogenerated' in first_line and script_name not in first_line: |
| 196 | common.warn("Skipping test which wasn't autogenerated by " + script_name, filename) |
| 197 | continue |
| 198 | |
| 199 | if args.update_only: |
| 200 | if not first_line or 'autogenerated' not in first_line: |
| 201 | common.warn("Skipping test which isn't autogenerated: " + filename) |
| 202 | continue |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 203 | |
| 204 | # Extract RUN lines. |
Alex Richardson | d9542db | 2019-12-02 10:50:23 +0000 | [diff] [blame] | 205 | run_lines = common.find_run_lines(filename, input_lines) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 206 | |
| 207 | # Build a list of clang command lines and check prefixes from RUN lines. |
| 208 | run_list = [] |
| 209 | line2spell_and_mangled_list = collections.defaultdict(list) |
| 210 | for l in run_lines: |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 211 | commands = [cmd.strip() for cmd in l.split('|')] |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 212 | |
| 213 | triple_in_cmd = None |
| 214 | m = common.TRIPLE_ARG_RE.search(commands[0]) |
| 215 | if m: |
| 216 | triple_in_cmd = m.groups()[0] |
| 217 | |
| 218 | # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args |
| 219 | clang_args = shlex.split(commands[0]) |
| 220 | if clang_args[0] not in SUBST: |
| 221 | print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr) |
| 222 | continue |
| 223 | clang_args[0:1] = SUBST[clang_args[0]] |
| 224 | clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args |
| 225 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 226 | # Permit piping the output through opt |
| 227 | if not (len(commands) == 2 or |
| 228 | (len(commands) == 3 and commands[1].startswith('opt'))): |
| 229 | print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr) |
| 230 | |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 231 | # Extract -check-prefix in FileCheck args |
| 232 | filecheck_cmd = commands[-1] |
David Bolvansky | 45be5e4 | 2019-07-29 17:41:00 +0000 | [diff] [blame] | 233 | common.verify_filecheck_prefixes(filecheck_cmd) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 234 | if not filecheck_cmd.startswith('FileCheck '): |
| 235 | print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr) |
| 236 | continue |
| 237 | check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd) |
| 238 | for item in m.group(1).split(',')] |
| 239 | if not check_prefixes: |
| 240 | check_prefixes = ['CHECK'] |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 241 | run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd)) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 242 | |
| 243 | # Strip CHECK lines which are in `prefix_set`, update test file. |
| 244 | prefix_set = set([prefix for p in run_list for prefix in p[0]]) |
| 245 | input_lines = [] |
| 246 | with open(filename, 'r+') as f: |
| 247 | for line in f: |
Alex Richardson | 3b55eeb | 2019-12-02 18:18:47 +0000 | [diff] [blame] | 248 | m = common.CHECK_RE.match(line) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 249 | if not (m and m.group(1) in prefix_set) and line != '//\n': |
| 250 | input_lines.append(line) |
| 251 | f.seek(0) |
| 252 | f.writelines(input_lines) |
| 253 | f.truncate() |
| 254 | |
| 255 | # Execute clang, generate LLVM IR, and extract functions. |
| 256 | func_dict = {} |
| 257 | for p in run_list: |
| 258 | prefixes = p[0] |
| 259 | for prefix in prefixes: |
| 260 | func_dict.update({prefix: dict()}) |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 261 | for prefixes, clang_args, extra_commands, triple_in_cmd in run_list: |
Alex Richardson | d9542db | 2019-12-02 10:50:23 +0000 | [diff] [blame] | 262 | common.debug('Extracted clang cmd: clang {}'.format(clang_args)) |
| 263 | common.debug('Extracted FileCheck prefixes: {}'.format(prefixes)) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 264 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 265 | get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 266 | |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame] | 267 | # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to |
| 268 | # mangled names. Forward all clang args for now. |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 269 | 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) |
Alex Richardson | 50807c8 | 2019-11-20 13:20:15 +0000 | [diff] [blame] | 291 | common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled, |
| 292 | False, args.function_signature) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 293 | output_lines.append(line.rstrip('\n')) |
| 294 | |
| 295 | # Update the test file. |
| 296 | with open(filename, 'w') as f: |
| 297 | for line in output_lines: |
| 298 | f.write(line + '\n') |
| 299 | |
| 300 | return 0 |
| 301 | |
| 302 | |
| 303 | if __name__ == '__main__': |
| 304 | sys.exit(main()) |