update_mca_test_checks.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. #!/usr/bin/env python2.7
  2. """A test case update script.
  3. This script is a utility to update LLVM 'llvm-mca' based test cases with new
  4. FileCheck patterns.
  5. """
  6. import argparse
  7. from collections import defaultdict
  8. import difflib
  9. import glob
  10. import os
  11. import sys
  12. import warnings
  13. from UpdateTestChecks import common
  14. COMMENT_CHAR = '#'
  15. ADVERT_PREFIX = '{} NOTE: Assertions have been autogenerated by '.format(
  16. COMMENT_CHAR)
  17. ADVERT = '{}utils/{}'.format(ADVERT_PREFIX, os.path.basename(__file__))
  18. class Error(Exception):
  19. """ Generic Error to be raised without printing a traceback.
  20. """
  21. pass
  22. def _warn(msg):
  23. """ Log a user warning to stderr.
  24. """
  25. warnings.warn(msg, Warning, stacklevel=2)
  26. def _configure_warnings(args):
  27. warnings.resetwarnings()
  28. if args.w:
  29. warnings.simplefilter('ignore')
  30. if args.Werror:
  31. warnings.simplefilter('error')
  32. def _showwarning(message, category, filename, lineno, file=None, line=None):
  33. """ Version of warnings.showwarning that won't attempt to print out the
  34. line at the location of the warning if the line text is not explicitly
  35. specified.
  36. """
  37. if file is None:
  38. file = sys.stderr
  39. if line is None:
  40. line = ''
  41. file.write(warnings.formatwarning(message, category, filename, lineno, line))
  42. def _parse_args():
  43. parser = argparse.ArgumentParser(description=__doc__)
  44. parser.add_argument('-v', '--verbose',
  45. action='store_true',
  46. help='show verbose output')
  47. parser.add_argument('-w',
  48. action='store_true',
  49. help='suppress warnings')
  50. parser.add_argument('-Werror',
  51. action='store_true',
  52. help='promote warnings to errors')
  53. parser.add_argument('--llvm-mca-binary',
  54. metavar='<path>',
  55. default='llvm-mca',
  56. help='the binary to use to generate the test case '
  57. '(default: llvm-mca)')
  58. parser.add_argument('tests',
  59. metavar='<test-path>',
  60. nargs='+')
  61. args = parser.parse_args()
  62. _configure_warnings(args)
  63. if os.path.basename(args.llvm_mca_binary) != 'llvm-mca':
  64. _warn('unexpected binary name: {}'.format(args.llvm_mca_binary))
  65. return args
  66. def _find_run_lines(input_lines, args):
  67. raw_lines = [m.group(1)
  68. for m in [common.RUN_LINE_RE.match(l) for l in input_lines]
  69. if m]
  70. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  71. for l in raw_lines[1:]:
  72. if run_lines[-1].endswith(r'\\'):
  73. run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l
  74. else:
  75. run_lines.append(l)
  76. if args.verbose:
  77. sys.stderr.write('Found {} RUN line{}:\n'.format(
  78. len(run_lines), '' if len(run_lines) == 1 else 's'))
  79. for line in run_lines:
  80. sys.stderr.write(' RUN: {}\n'.format(line))
  81. return run_lines
  82. def _get_run_infos(run_lines, args):
  83. run_infos = []
  84. for run_line in run_lines:
  85. try:
  86. (tool_cmd, filecheck_cmd) = tuple([cmd.strip()
  87. for cmd in run_line.split('|', 1)])
  88. except ValueError:
  89. _warn('could not split tool and filecheck commands: {}'.format(run_line))
  90. continue
  91. tool_basename = os.path.basename(args.llvm_mca_binary)
  92. if not tool_cmd.startswith(tool_basename + ' '):
  93. _warn('skipping non-{} RUN line: {}'.format(tool_basename, run_line))
  94. continue
  95. if not filecheck_cmd.startswith('FileCheck '):
  96. _warn('skipping non-FileCheck RUN line: {}'.format(run_line))
  97. continue
  98. tool_cmd_args = tool_cmd[len(tool_basename):].strip()
  99. tool_cmd_args = tool_cmd_args.replace('< %s', '').replace('%s', '').strip()
  100. check_prefixes = [item
  101. for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  102. for item in m.group(1).split(',')]
  103. if not check_prefixes:
  104. check_prefixes = ['CHECK']
  105. run_infos.append((check_prefixes, tool_cmd_args))
  106. return run_infos
  107. def _get_block_infos(run_infos, test_path, args): # noqa
  108. """ For each run line, run the tool with the specified args and collect the
  109. output. We use the concept of 'blocks' for uniquing, where a block is
  110. a series of lines of text with no more than one newline character between
  111. each one. For example:
  112. This
  113. is
  114. one
  115. block
  116. This is
  117. another block
  118. This is yet another block
  119. We then build up a 'block_infos' structure containing a dict where the
  120. text of each block is the key and a list of the sets of prefixes that may
  121. generate that particular block. This then goes through a series of
  122. transformations to minimise the amount of CHECK lines that need to be
  123. written by taking advantage of common prefixes.
  124. """
  125. def _block_key(tool_args, prefixes):
  126. """ Get a hashable key based on the current tool_args and prefixes.
  127. """
  128. return ' '.join([tool_args] + prefixes)
  129. all_blocks = {}
  130. max_block_len = 0
  131. # Run the tool for each run line to generate all of the blocks.
  132. for prefixes, tool_args in run_infos:
  133. key = _block_key(tool_args, prefixes)
  134. raw_tool_output = common.invoke_tool(args.llvm_mca_binary,
  135. tool_args,
  136. test_path)
  137. # Replace any lines consisting of purely whitespace with empty lines.
  138. raw_tool_output = '\n'.join(line if line.strip() else ''
  139. for line in raw_tool_output.splitlines())
  140. # Split blocks, stripping all trailing whitespace, but keeping preceding
  141. # whitespace except for newlines so that columns will line up visually.
  142. all_blocks[key] = [b.lstrip('\n').rstrip()
  143. for b in raw_tool_output.split('\n\n')]
  144. max_block_len = max(max_block_len, len(all_blocks[key]))
  145. # If necessary, pad the lists of blocks with empty blocks so that they are
  146. # all the same length.
  147. for key in all_blocks:
  148. len_to_pad = max_block_len - len(all_blocks[key])
  149. all_blocks[key] += [''] * len_to_pad
  150. # Create the block_infos structure where it is a nested dict in the form of:
  151. # block number -> block text -> list of prefix sets
  152. block_infos = defaultdict(lambda: defaultdict(list))
  153. for prefixes, tool_args in run_infos:
  154. key = _block_key(tool_args, prefixes)
  155. for block_num, block_text in enumerate(all_blocks[key]):
  156. block_infos[block_num][block_text].append(set(prefixes))
  157. # Now go through the block_infos structure and attempt to smartly prune the
  158. # number of prefixes per block to the minimal set possible to output.
  159. for block_num in range(len(block_infos)):
  160. # When there are multiple block texts for a block num, remove any
  161. # prefixes that are common to more than one of them.
  162. # E.g. [ [{ALL,FOO}] , [{ALL,BAR}] ] -> [ [{FOO}] , [{BAR}] ]
  163. all_sets = [s for s in block_infos[block_num].values()]
  164. pruned_sets = []
  165. for i, setlist in enumerate(all_sets):
  166. other_set_values = set([elem for j, setlist2 in enumerate(all_sets)
  167. for set_ in setlist2 for elem in set_
  168. if i != j])
  169. pruned_sets.append([s - other_set_values for s in setlist])
  170. for i, block_text in enumerate(block_infos[block_num]):
  171. # When a block text matches multiple sets of prefixes, try removing any
  172. # prefixes that aren't common to all of them.
  173. # E.g. [ {ALL,FOO} , {ALL,BAR} ] -> [{ALL}]
  174. common_values = pruned_sets[i][0].copy()
  175. for s in pruned_sets[i][1:]:
  176. common_values &= s
  177. if common_values:
  178. pruned_sets[i] = [common_values]
  179. # Everything should be uniqued as much as possible by now. Apply the
  180. # newly pruned sets to the block_infos structure.
  181. # If there are any blocks of text that still match multiple prefixes,
  182. # output a warning.
  183. current_set = set()
  184. for s in pruned_sets[i]:
  185. s = sorted(list(s))
  186. if s:
  187. current_set.add(s[0])
  188. if len(s) > 1:
  189. _warn('Multiple prefixes generating same output: {} '
  190. '(discarding {})'.format(','.join(s), ','.join(s[1:])))
  191. block_infos[block_num][block_text] = sorted(list(current_set))
  192. return block_infos
  193. def _write_output(test_path, input_lines, prefix_list, block_infos, # noqa
  194. args):
  195. prefix_set = set([prefix for prefixes, _ in prefix_list
  196. for prefix in prefixes])
  197. not_prefix_set = set()
  198. output_lines = []
  199. for input_line in input_lines:
  200. if input_line.startswith(ADVERT_PREFIX):
  201. continue
  202. if input_line.startswith(COMMENT_CHAR):
  203. m = common.CHECK_RE.match(input_line)
  204. try:
  205. prefix = m.group(1)
  206. except AttributeError:
  207. prefix = None
  208. if '{}-NOT:'.format(prefix) in input_line:
  209. not_prefix_set.add(prefix)
  210. if prefix not in prefix_set or prefix in not_prefix_set:
  211. output_lines.append(input_line)
  212. continue
  213. if common.should_add_line_to_output(input_line, prefix_set):
  214. # This input line of the function body will go as-is into the output.
  215. # Except make leading whitespace uniform: 2 spaces.
  216. input_line = common.SCRUB_LEADING_WHITESPACE_RE.sub(r' ', input_line)
  217. # Skip empty lines if the previous output line is also empty.
  218. if input_line or output_lines[-1]:
  219. output_lines.append(input_line)
  220. else:
  221. continue
  222. # Add a blank line before the new checks if required.
  223. if output_lines[-1]:
  224. output_lines.append('')
  225. output_check_lines = []
  226. for block_num in range(len(block_infos)):
  227. for block_text in sorted(block_infos[block_num]):
  228. if not block_text:
  229. continue
  230. if block_infos[block_num][block_text]:
  231. lines = block_text.split('\n')
  232. for prefix in block_infos[block_num][block_text]:
  233. if prefix in not_prefix_set:
  234. _warn('not writing for prefix {0} due to presence of "{0}-NOT:" '
  235. 'in input file.'.format(prefix))
  236. continue
  237. output_check_lines.append(
  238. '{} {}: {}'.format(COMMENT_CHAR, prefix, lines[0]).rstrip())
  239. for line in lines[1:]:
  240. output_check_lines.append(
  241. '{} {}-NEXT: {}'.format(COMMENT_CHAR, prefix, line).rstrip())
  242. output_check_lines.append('')
  243. if output_check_lines:
  244. output_lines.insert(0, ADVERT)
  245. output_lines.extend(output_check_lines)
  246. if input_lines == output_lines:
  247. sys.stderr.write(' [unchanged]\n')
  248. return
  249. diff = list(difflib.Differ().compare(input_lines, output_lines))
  250. sys.stderr.write(
  251. ' [{} lines total ({} added, {} removed)]\n'.format(
  252. len(output_lines),
  253. len([l for l in diff if l[0] == '+']),
  254. len([l for l in diff if l[0] == '-'])))
  255. if args.verbose:
  256. sys.stderr.write(
  257. 'Writing {} lines to {}...\n\n'.format(len(output_lines), test_path))
  258. with open(test_path, 'wb') as f:
  259. for line in output_lines:
  260. f.write('{}\n'.format(line.rstrip()).encode())
  261. def main():
  262. args = _parse_args()
  263. test_paths = [test for pattern in args.tests for test in glob.glob(pattern)]
  264. for test_path in test_paths:
  265. sys.stderr.write('Test: {}\n'.format(test_path))
  266. # Call this per test. By default each warning will only be written once
  267. # per source location. Reset the warning filter so that now each warning
  268. # will be written once per source location per test.
  269. _configure_warnings(args)
  270. if args.verbose:
  271. sys.stderr.write(
  272. 'Scanning for RUN lines in test file: {}\n'.format(test_path))
  273. if not os.path.isfile(test_path):
  274. raise Error('could not find test file: {}'.format(test_path))
  275. with open(test_path) as f:
  276. input_lines = [l.rstrip() for l in f]
  277. run_lines = _find_run_lines(input_lines, args)
  278. run_infos = _get_run_infos(run_lines, args)
  279. block_infos = _get_block_infos(run_infos, test_path, args)
  280. _write_output(test_path, input_lines, run_infos, block_infos, args)
  281. return 0
  282. if __name__ == '__main__':
  283. try:
  284. warnings.showwarning = _showwarning
  285. sys.exit(main())
  286. except Error as e:
  287. sys.stdout.write('error: {}\n'.format(e))
  288. sys.exit(1)