update_cc_test_checks.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. RE = re.compile(r'^FunctionDecl=(\w+):(\d+):\d+ \(Definition\) \[mangled=([^]]+)\]')
  44. for line in output.splitlines():
  45. m = RE.match(line)
  46. if not m: continue
  47. spell, line, mangled = m.groups()
  48. if mangled == '_' + spell:
  49. # HACK for MacOS (where the mangled name includes an _ for C but the IR won't):
  50. mangled = spell
  51. # Note -test-print-mangle does not print file names so if #include is used,
  52. # the line number may come from an included file.
  53. ret[int(line)-1] = (spell, mangled)
  54. if args.verbose:
  55. for line, func_name in sorted(ret.items()):
  56. print('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
  57. return ret
  58. def config():
  59. parser = argparse.ArgumentParser(
  60. description=__doc__,
  61. formatter_class=argparse.RawTextHelpFormatter)
  62. parser.add_argument('-v', '--verbose', action='store_true')
  63. parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
  64. parser.add_argument('--clang',
  65. help='"clang" executable, defaults to $llvm_bin/clang')
  66. parser.add_argument('--clang-args',
  67. help='Space-separated extra args to clang, e.g. --clang-args=-v')
  68. parser.add_argument('--c-index-test',
  69. help='"c-index-test" executable, defaults to $llvm_bin/c-index-test')
  70. parser.add_argument(
  71. '--functions', nargs='+', help='A list of function name regexes. '
  72. 'If specified, update CHECK lines for functions matching at least one regex')
  73. parser.add_argument(
  74. '--x86_extra_scrub', action='store_true',
  75. help='Use more regex for x86 matching to reduce diffs between various subtargets')
  76. parser.add_argument('-u', '--update-only', action='store_true',
  77. help='Only update test if it was already autogened')
  78. parser.add_argument('tests', nargs='+')
  79. args = parser.parse_args()
  80. args.clang_args = shlex.split(args.clang_args or '')
  81. if args.clang is None:
  82. if args.llvm_bin is None:
  83. args.clang = 'clang'
  84. else:
  85. args.clang = os.path.join(args.llvm_bin, 'clang')
  86. if not distutils.spawn.find_executable(args.clang):
  87. print('Please specify --llvm-bin or --clang', file=sys.stderr)
  88. sys.exit(1)
  89. if args.c_index_test is None:
  90. if args.llvm_bin is None:
  91. args.c_index_test = 'c-index-test'
  92. else:
  93. args.c_index_test = os.path.join(args.llvm_bin, 'c-index-test')
  94. if not distutils.spawn.find_executable(args.c_index_test):
  95. print('Please specify --llvm-bin or --c-index-test', file=sys.stderr)
  96. sys.exit(1)
  97. return args
  98. def get_function_body(args, filename, clang_args, prefixes, triple_in_cmd, func_dict):
  99. # TODO Clean up duplication of asm/common build_function_body_dictionary
  100. # Invoke external tool and extract function bodies.
  101. raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
  102. if '-emit-llvm' in clang_args:
  103. common.build_function_body_dictionary(
  104. common.OPT_FUNCTION_RE, common.scrub_body, [],
  105. raw_tool_output, prefixes, func_dict, args.verbose)
  106. else:
  107. print('The clang command line should include -emit-llvm as asm tests '
  108. 'are discouraged in Clang testsuite.', file=sys.stderr)
  109. sys.exit(1)
  110. def main():
  111. args = config()
  112. script_name = os.path.basename(__file__)
  113. autogenerated_note = (ADVERT + 'utils/' + script_name)
  114. for filename in args.tests:
  115. with open(filename) as f:
  116. input_lines = [l.rstrip() for l in f]
  117. first_line = input_lines[0] if input_lines else ""
  118. if 'autogenerated' in first_line and script_name not in first_line:
  119. common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
  120. continue
  121. if args.update_only:
  122. if not first_line or 'autogenerated' not in first_line:
  123. common.warn("Skipping test which isn't autogenerated: " + filename)
  124. continue
  125. # Extract RUN lines.
  126. raw_lines = [m.group(1)
  127. for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
  128. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  129. for l in raw_lines[1:]:
  130. if run_lines[-1].endswith("\\"):
  131. run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
  132. else:
  133. run_lines.append(l)
  134. if args.verbose:
  135. print('Found {} RUN lines:'.format(len(run_lines)), file=sys.stderr)
  136. for l in run_lines:
  137. print(' RUN: ' + l, file=sys.stderr)
  138. # Build a list of clang command lines and check prefixes from RUN lines.
  139. run_list = []
  140. line2spell_and_mangled_list = collections.defaultdict(list)
  141. for l in run_lines:
  142. commands = [cmd.strip() for cmd in l.split('|', 1)]
  143. triple_in_cmd = None
  144. m = common.TRIPLE_ARG_RE.search(commands[0])
  145. if m:
  146. triple_in_cmd = m.groups()[0]
  147. # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
  148. clang_args = shlex.split(commands[0])
  149. if clang_args[0] not in SUBST:
  150. print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
  151. continue
  152. clang_args[0:1] = SUBST[clang_args[0]]
  153. clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
  154. # Extract -check-prefix in FileCheck args
  155. filecheck_cmd = commands[-1]
  156. common.verify_filecheck_prefixes(filecheck_cmd)
  157. if not filecheck_cmd.startswith('FileCheck '):
  158. print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
  159. continue
  160. check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  161. for item in m.group(1).split(',')]
  162. if not check_prefixes:
  163. check_prefixes = ['CHECK']
  164. run_list.append((check_prefixes, clang_args, triple_in_cmd))
  165. # Strip CHECK lines which are in `prefix_set`, update test file.
  166. prefix_set = set([prefix for p in run_list for prefix in p[0]])
  167. input_lines = []
  168. with open(filename, 'r+') as f:
  169. for line in f:
  170. m = CHECK_RE.match(line)
  171. if not (m and m.group(1) in prefix_set) and line != '//\n':
  172. input_lines.append(line)
  173. f.seek(0)
  174. f.writelines(input_lines)
  175. f.truncate()
  176. # Execute clang, generate LLVM IR, and extract functions.
  177. func_dict = {}
  178. for p in run_list:
  179. prefixes = p[0]
  180. for prefix in prefixes:
  181. func_dict.update({prefix: dict()})
  182. for prefixes, clang_args, triple_in_cmd in run_list:
  183. if args.verbose:
  184. print('Extracted clang cmd: clang {}'.format(clang_args), file=sys.stderr)
  185. print('Extracted FileCheck prefixes: {}'.format(prefixes), file=sys.stderr)
  186. get_function_body(args, filename, clang_args, prefixes, triple_in_cmd, func_dict)
  187. # Invoke c-index-test to get mapping from start lines to mangled names.
  188. # Forward all clang args for now.
  189. for k, v in get_line2spell_and_mangled(args, clang_args).items():
  190. line2spell_and_mangled_list[k].append(v)
  191. output_lines = [autogenerated_note]
  192. for idx, line in enumerate(input_lines):
  193. # Discard any previous script advertising.
  194. if line.startswith(ADVERT):
  195. continue
  196. if idx in line2spell_and_mangled_list:
  197. added = set()
  198. for spell, mangled in line2spell_and_mangled_list[idx]:
  199. # One line may contain multiple function declarations.
  200. # Skip if the mangled name has been added before.
  201. # The line number may come from an included file,
  202. # we simply require the spelling name to appear on the line
  203. # to exclude functions from other files.
  204. if mangled in added or spell not in line:
  205. continue
  206. if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
  207. if added:
  208. output_lines.append('//')
  209. added.add(mangled)
  210. common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled)
  211. output_lines.append(line.rstrip('\n'))
  212. # Update the test file.
  213. with open(filename, 'w') as f:
  214. for line in output_lines:
  215. f.write(line + '\n')
  216. return 0
  217. if __name__ == '__main__':
  218. sys.exit(main())