update_cc_test_checks.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #!/usr/bin/env python3
  2. '''A utility to update LLVM IR CHECK lines in C/C++ FileCheck test files.
  3. Example RUN lines in .c/.cc test files:
  4. // RUN: %clang -emit-llvm -S %s -o - -O2 | FileCheck %s
  5. // RUN: %clangxx -emit-llvm -S %s -o - -O2 | FileCheck -check-prefix=CHECK-A %s
  6. Usage:
  7. % utils/update_cc_test_checks.py --llvm-bin=release/bin test/a.cc
  8. % utils/update_cc_test_checks.py --c-index-test=release/bin/c-index-test \
  9. --clang=release/bin/clang /tmp/c/a.cc
  10. '''
  11. import argparse
  12. import collections
  13. import distutils.spawn
  14. import os
  15. import shlex
  16. import string
  17. import subprocess
  18. import sys
  19. import re
  20. import tempfile
  21. from UpdateTestChecks import asm, common
  22. ADVERT = '// NOTE: Assertions have been autogenerated by '
  23. CHECK_RE = re.compile(r'^\s*//\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
  24. RUN_LINE_RE = re.compile('^//\s*RUN:\s*(.*)$')
  25. SUBST = {
  26. '%clang': [],
  27. '%clang_cc1': ['-cc1'],
  28. '%clangxx': ['--driver-mode=g++'],
  29. }
  30. def get_line2spell_and_mangled(args, clang_args):
  31. ret = {}
  32. with tempfile.NamedTemporaryFile() as f:
  33. # TODO Make c-index-test print mangled names without circumventing through precompiled headers
  34. status = subprocess.run([args.c_index_test, '-write-pch', f.name, *clang_args],
  35. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  36. if status.returncode:
  37. sys.stderr.write(status.stdout.decode())
  38. sys.exit(2)
  39. output = subprocess.check_output([args.c_index_test,
  40. '-test-print-mangle', f.name])
  41. if sys.version_info[0] > 2:
  42. output = output.decode()
  43. DeclRE = re.compile(r'^FunctionDecl=(\w+):(\d+):\d+ \(Definition\)')
  44. MangleRE = re.compile(r'.*\[mangled=([^]]+)\]')
  45. MatchedDecl = False
  46. for line in output.splitlines():
  47. # Get the function source name, line number and mangled name. Sometimes
  48. # c-index-test outputs the mangled name on a separate line (this can happen
  49. # with block comments in front of functions). Keep scanning until we see
  50. # the mangled name.
  51. decl_m = DeclRE.match(line)
  52. mangle_m = MangleRE.match(line)
  53. if decl_m:
  54. MatchedDecl = True
  55. spell, lineno = decl_m.groups()
  56. if MatchedDecl and mangle_m:
  57. mangled = mangle_m.group(1)
  58. MatchedDecl = False
  59. else:
  60. continue
  61. if mangled == '_' + spell:
  62. # HACK for MacOS (where the mangled name includes an _ for C but the IR won't):
  63. mangled = spell
  64. # Note -test-print-mangle does not print file names so if #include is used,
  65. # the line number may come from an included file.
  66. ret[int(lineno)-1] = (spell, mangled)
  67. if args.verbose:
  68. for line, func_name in sorted(ret.items()):
  69. print('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
  70. return ret
  71. def config():
  72. parser = argparse.ArgumentParser(
  73. description=__doc__,
  74. formatter_class=argparse.RawTextHelpFormatter)
  75. parser.add_argument('-v', '--verbose', action='store_true')
  76. parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
  77. parser.add_argument('--clang',
  78. help='"clang" executable, defaults to $llvm_bin/clang')
  79. parser.add_argument('--clang-args',
  80. help='Space-separated extra args to clang, e.g. --clang-args=-v')
  81. parser.add_argument('--c-index-test',
  82. help='"c-index-test" executable, defaults to $llvm_bin/c-index-test')
  83. parser.add_argument('--opt',
  84. help='"opt" executable, defaults to $llvm_bin/opt')
  85. parser.add_argument(
  86. '--functions', nargs='+', help='A list of function name regexes. '
  87. 'If specified, update CHECK lines for functions matching at least one regex')
  88. parser.add_argument(
  89. '--x86_extra_scrub', action='store_true',
  90. help='Use more regex for x86 matching to reduce diffs between various subtargets')
  91. parser.add_argument('-u', '--update-only', action='store_true',
  92. help='Only update test if it was already autogened')
  93. parser.add_argument('tests', nargs='+')
  94. args = parser.parse_args()
  95. args.clang_args = shlex.split(args.clang_args or '')
  96. if args.clang is None:
  97. if args.llvm_bin is None:
  98. args.clang = 'clang'
  99. else:
  100. args.clang = os.path.join(args.llvm_bin, 'clang')
  101. if not distutils.spawn.find_executable(args.clang):
  102. print('Please specify --llvm-bin or --clang', file=sys.stderr)
  103. sys.exit(1)
  104. if args.opt is None:
  105. if args.llvm_bin is None:
  106. args.opt = 'opt'
  107. else:
  108. args.opt = os.path.join(args.llvm_bin, 'opt')
  109. if not distutils.spawn.find_executable(args.opt):
  110. # Many uses of this tool will not need an opt binary, because it's only
  111. # needed for updating a test that runs clang | opt | FileCheck. So we
  112. # defer this error message until we find that opt is actually needed.
  113. args.opt = None
  114. if args.c_index_test is None:
  115. if args.llvm_bin is None:
  116. args.c_index_test = 'c-index-test'
  117. else:
  118. args.c_index_test = os.path.join(args.llvm_bin, 'c-index-test')
  119. if not distutils.spawn.find_executable(args.c_index_test):
  120. print('Please specify --llvm-bin or --c-index-test', file=sys.stderr)
  121. sys.exit(1)
  122. return args
  123. def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
  124. # TODO Clean up duplication of asm/common build_function_body_dictionary
  125. # Invoke external tool and extract function bodies.
  126. raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
  127. for extra_command in extra_commands:
  128. extra_args = shlex.split(extra_command)
  129. with tempfile.NamedTemporaryFile() as f:
  130. f.write(raw_tool_output.encode())
  131. f.flush()
  132. if extra_args[0] == 'opt':
  133. if args.opt is None:
  134. print(filename, 'needs to run opt. '
  135. 'Please specify --llvm-bin or --opt', file=sys.stderr)
  136. sys.exit(1)
  137. extra_args[0] = args.opt
  138. raw_tool_output = common.invoke_tool(extra_args[0],
  139. extra_args[1:], f.name)
  140. if '-emit-llvm' in clang_args:
  141. common.build_function_body_dictionary(
  142. common.OPT_FUNCTION_RE, common.scrub_body, [],
  143. raw_tool_output, prefixes, func_dict, args.verbose)
  144. else:
  145. print('The clang command line should include -emit-llvm as asm tests '
  146. 'are discouraged in Clang testsuite.', file=sys.stderr)
  147. sys.exit(1)
  148. def main():
  149. args = config()
  150. script_name = os.path.basename(__file__)
  151. autogenerated_note = (ADVERT + 'utils/' + script_name)
  152. for filename in args.tests:
  153. with open(filename) as f:
  154. input_lines = [l.rstrip() for l in f]
  155. first_line = input_lines[0] if input_lines else ""
  156. if 'autogenerated' in first_line and script_name not in first_line:
  157. common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
  158. continue
  159. if args.update_only:
  160. if not first_line or 'autogenerated' not in first_line:
  161. common.warn("Skipping test which isn't autogenerated: " + filename)
  162. continue
  163. # Extract RUN lines.
  164. raw_lines = [m.group(1)
  165. for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
  166. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  167. for l in raw_lines[1:]:
  168. if run_lines[-1].endswith("\\"):
  169. run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
  170. else:
  171. run_lines.append(l)
  172. if args.verbose:
  173. print('Found {} RUN lines:'.format(len(run_lines)), file=sys.stderr)
  174. for l in run_lines:
  175. print(' RUN: ' + l, file=sys.stderr)
  176. # Build a list of clang command lines and check prefixes from RUN lines.
  177. run_list = []
  178. line2spell_and_mangled_list = collections.defaultdict(list)
  179. for l in run_lines:
  180. commands = [cmd.strip() for cmd in l.split('|')]
  181. triple_in_cmd = None
  182. m = common.TRIPLE_ARG_RE.search(commands[0])
  183. if m:
  184. triple_in_cmd = m.groups()[0]
  185. # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
  186. clang_args = shlex.split(commands[0])
  187. if clang_args[0] not in SUBST:
  188. print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
  189. continue
  190. clang_args[0:1] = SUBST[clang_args[0]]
  191. clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
  192. # Permit piping the output through opt
  193. if not (len(commands) == 2 or
  194. (len(commands) == 3 and commands[1].startswith('opt'))):
  195. print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
  196. # Extract -check-prefix in FileCheck args
  197. filecheck_cmd = commands[-1]
  198. common.verify_filecheck_prefixes(filecheck_cmd)
  199. if not filecheck_cmd.startswith('FileCheck '):
  200. print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
  201. continue
  202. check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  203. for item in m.group(1).split(',')]
  204. if not check_prefixes:
  205. check_prefixes = ['CHECK']
  206. run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
  207. # Strip CHECK lines which are in `prefix_set`, update test file.
  208. prefix_set = set([prefix for p in run_list for prefix in p[0]])
  209. input_lines = []
  210. with open(filename, 'r+') as f:
  211. for line in f:
  212. m = CHECK_RE.match(line)
  213. if not (m and m.group(1) in prefix_set) and line != '//\n':
  214. input_lines.append(line)
  215. f.seek(0)
  216. f.writelines(input_lines)
  217. f.truncate()
  218. # Execute clang, generate LLVM IR, and extract functions.
  219. func_dict = {}
  220. for p in run_list:
  221. prefixes = p[0]
  222. for prefix in prefixes:
  223. func_dict.update({prefix: dict()})
  224. for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
  225. if args.verbose:
  226. print('Extracted clang cmd: clang {}'.format(clang_args), file=sys.stderr)
  227. print('Extracted FileCheck prefixes: {}'.format(prefixes), file=sys.stderr)
  228. get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
  229. # Invoke c-index-test to get mapping from start lines to mangled names.
  230. # Forward all clang args for now.
  231. for k, v in get_line2spell_and_mangled(args, clang_args).items():
  232. line2spell_and_mangled_list[k].append(v)
  233. output_lines = [autogenerated_note]
  234. for idx, line in enumerate(input_lines):
  235. # Discard any previous script advertising.
  236. if line.startswith(ADVERT):
  237. continue
  238. if idx in line2spell_and_mangled_list:
  239. added = set()
  240. for spell, mangled in line2spell_and_mangled_list[idx]:
  241. # One line may contain multiple function declarations.
  242. # Skip if the mangled name has been added before.
  243. # The line number may come from an included file,
  244. # we simply require the spelling name to appear on the line
  245. # to exclude functions from other files.
  246. if mangled in added or spell not in line:
  247. continue
  248. if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
  249. if added:
  250. output_lines.append('//')
  251. added.add(mangled)
  252. common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled, False)
  253. output_lines.append(line.rstrip('\n'))
  254. # Update the test file.
  255. with open(filename, 'w') as f:
  256. for line in output_lines:
  257. f.write(line + '\n')
  258. return 0
  259. if __name__ == '__main__':
  260. sys.exit(main())