update_mir_test_checks.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. #!/usr/bin/env python
  2. """Updates FileCheck checks in MIR tests.
  3. This script is a utility to update MIR based tests with new FileCheck
  4. patterns.
  5. The checks added by this script will cover the entire body of each
  6. function it handles. Virtual registers used are given names via
  7. FileCheck patterns, so if you do want to check a subset of the body it
  8. should be straightforward to trim out the irrelevant parts. None of
  9. the YAML metadata will be checked, other than function names.
  10. If there are multiple llc commands in a test, the full set of checks
  11. will be repeated for each different check pattern. Checks for patterns
  12. that are common between different commands will be left as-is by
  13. default, or removed if the --remove-common-prefixes flag is provided.
  14. """
  15. from __future__ import print_function
  16. import argparse
  17. import collections
  18. import glob
  19. import os
  20. import re
  21. import subprocess
  22. import sys
  23. from UpdateTestChecks import common
  24. MIR_FUNC_NAME_RE = re.compile(r' *name: *(?P<func>[A-Za-z0-9_.-]+)')
  25. MIR_BODY_BEGIN_RE = re.compile(r' *body: *\|')
  26. MIR_BASIC_BLOCK_RE = re.compile(r' *bb\.[0-9]+.*:$')
  27. VREG_RE = re.compile(r'(%[0-9]+)(?::[a-z0-9_]+)?(?:\([<>a-z0-9 ]+\))?')
  28. MI_FLAGS_STR= (
  29. r'(frame-setup |frame-destroy |nnan |ninf |nsz |arcp |contract |afn '
  30. r'|reassoc |nuw |nsw |exact |fpexcept )*')
  31. VREG_DEF_RE = re.compile(
  32. r'^ *(?P<vregs>{0}(?:, {0})*) = '
  33. r'{1}(?P<opcode>[A-Zt][A-Za-z0-9_]+)'.format(VREG_RE.pattern, MI_FLAGS_STR))
  34. MIR_PREFIX_DATA_RE = re.compile(r'^ *(;|bb.[0-9].*: *$|[a-z]+:( |$)|$)')
  35. IR_FUNC_NAME_RE = re.compile(
  36. r'^\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[A-Za-z0-9_.]+)\s*\(')
  37. IR_PREFIX_DATA_RE = re.compile(r'^ *(;|$)')
  38. MIR_FUNC_RE = re.compile(
  39. r'^---$'
  40. r'\n'
  41. r'^ *name: *(?P<func>[A-Za-z0-9_.-]+)$'
  42. r'.*?'
  43. r'^ *body: *\|\n'
  44. r'(?P<body>.*?)\n'
  45. r'^\.\.\.$',
  46. flags=(re.M | re.S))
  47. class LLC:
  48. def __init__(self, bin):
  49. self.bin = bin
  50. def __call__(self, args, ir):
  51. if ir.endswith('.mir'):
  52. args = '{} -x mir'.format(args)
  53. with open(ir) as ir_file:
  54. stdout = subprocess.check_output('{} {}'.format(self.bin, args),
  55. shell=True, stdin=ir_file)
  56. if sys.version_info[0] > 2:
  57. stdout = stdout.decode()
  58. # Fix line endings to unix CR style.
  59. stdout = stdout.replace('\r\n', '\n')
  60. return stdout
  61. class Run:
  62. def __init__(self, prefixes, cmd_args, triple):
  63. self.prefixes = prefixes
  64. self.cmd_args = cmd_args
  65. self.triple = triple
  66. def __getitem__(self, index):
  67. return [self.prefixes, self.cmd_args, self.triple][index]
  68. def log(msg, verbose=True):
  69. if verbose:
  70. print(msg, file=sys.stderr)
  71. def find_triple_in_ir(lines, verbose=False):
  72. for l in lines:
  73. m = common.TRIPLE_IR_RE.match(l)
  74. if m:
  75. return m.group(1)
  76. return None
  77. def find_run_lines(test, lines, verbose=False):
  78. raw_lines = [m.group(1)
  79. for m in [common.RUN_LINE_RE.match(l) for l in lines] if m]
  80. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  81. for l in raw_lines[1:]:
  82. if run_lines[-1].endswith("\\"):
  83. run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
  84. else:
  85. run_lines.append(l)
  86. if verbose:
  87. log('Found {} RUN lines:'.format(len(run_lines)))
  88. for l in run_lines:
  89. log(' RUN: {}'.format(l))
  90. return run_lines
  91. def build_run_list(test, run_lines, verbose=False):
  92. run_list = []
  93. all_prefixes = []
  94. for l in run_lines:
  95. if '|' not in l:
  96. common.warn('Skipping unparseable RUN line: ' + l)
  97. continue
  98. commands = [cmd.strip() for cmd in l.split('|', 1)]
  99. llc_cmd = commands[0]
  100. filecheck_cmd = commands[1] if len(commands) > 1 else ''
  101. common.verify_filecheck_prefixes(filecheck_cmd)
  102. if not llc_cmd.startswith('llc '):
  103. common.warn('Skipping non-llc RUN line: {}'.format(l), test_file=test)
  104. continue
  105. if not filecheck_cmd.startswith('FileCheck '):
  106. common.warn('Skipping non-FileChecked RUN line: {}'.format(l),
  107. test_file=test)
  108. continue
  109. triple = None
  110. m = common.TRIPLE_ARG_RE.search(llc_cmd)
  111. if m:
  112. triple = m.group(1)
  113. # If we find -march but not -mtriple, use that.
  114. m = common.MARCH_ARG_RE.search(llc_cmd)
  115. if m and not triple:
  116. triple = '{}--'.format(m.group(1))
  117. cmd_args = llc_cmd[len('llc'):].strip()
  118. cmd_args = cmd_args.replace('< %s', '').replace('%s', '').strip()
  119. check_prefixes = [
  120. item
  121. for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  122. for item in m.group(1).split(',')]
  123. if not check_prefixes:
  124. check_prefixes = ['CHECK']
  125. all_prefixes += check_prefixes
  126. run_list.append(Run(check_prefixes, cmd_args, triple))
  127. # Remove any common prefixes. We'll just leave those entirely alone.
  128. common_prefixes = set([prefix for prefix in all_prefixes
  129. if all_prefixes.count(prefix) > 1])
  130. for run in run_list:
  131. run.prefixes = [p for p in run.prefixes if p not in common_prefixes]
  132. return run_list, common_prefixes
  133. def find_functions_with_one_bb(lines, verbose=False):
  134. result = []
  135. cur_func = None
  136. bbs = 0
  137. for line in lines:
  138. m = MIR_FUNC_NAME_RE.match(line)
  139. if m:
  140. if bbs == 1:
  141. result.append(cur_func)
  142. cur_func = m.group('func')
  143. bbs = 0
  144. m = MIR_BASIC_BLOCK_RE.match(line)
  145. if m:
  146. bbs += 1
  147. if bbs == 1:
  148. result.append(cur_func)
  149. return result
  150. def build_function_body_dictionary(test, raw_tool_output, triple, prefixes,
  151. func_dict, verbose):
  152. for m in MIR_FUNC_RE.finditer(raw_tool_output):
  153. func = m.group('func')
  154. body = m.group('body')
  155. if verbose:
  156. log('Processing function: {}'.format(func))
  157. for l in body.splitlines():
  158. log(' {}'.format(l))
  159. for prefix in prefixes:
  160. if func in func_dict[prefix] and func_dict[prefix][func] != body:
  161. common.warn('Found conflicting asm for prefix: {}'.format(prefix),
  162. test_file=test)
  163. func_dict[prefix][func] = body
  164. def add_checks_for_function(test, output_lines, run_list, func_dict, func_name,
  165. single_bb, verbose=False):
  166. printed_prefixes = set()
  167. for run in run_list:
  168. for prefix in run.prefixes:
  169. if prefix in printed_prefixes:
  170. continue
  171. if not func_dict[prefix][func_name]:
  172. continue
  173. # if printed_prefixes:
  174. # # Add some space between different check prefixes.
  175. # output_lines.append('')
  176. printed_prefixes.add(prefix)
  177. log('Adding {} lines for {}'.format(prefix, func_name), verbose)
  178. add_check_lines(test, output_lines, prefix, func_name, single_bb,
  179. func_dict[prefix][func_name].splitlines())
  180. break
  181. return output_lines
  182. def add_check_lines(test, output_lines, prefix, func_name, single_bb,
  183. func_body):
  184. if single_bb:
  185. # Don't bother checking the basic block label for a single BB
  186. func_body.pop(0)
  187. if not func_body:
  188. common.warn('Function has no instructions to check: {}'.format(func_name),
  189. test_file=test)
  190. return
  191. first_line = func_body[0]
  192. indent = len(first_line) - len(first_line.lstrip(' '))
  193. # A check comment, indented the appropriate amount
  194. check = '{:>{}}; {}'.format('', indent, prefix)
  195. output_lines.append('{}-LABEL: name: {}'.format(check, func_name))
  196. vreg_map = {}
  197. for func_line in func_body:
  198. if not func_line.strip():
  199. continue
  200. m = VREG_DEF_RE.match(func_line)
  201. if m:
  202. for vreg in VREG_RE.finditer(m.group('vregs')):
  203. name = mangle_vreg(m.group('opcode'), vreg_map.values())
  204. vreg_map[vreg.group(1)] = name
  205. func_line = func_line.replace(
  206. vreg.group(1), '[[{}:%[0-9]+]]'.format(name), 1)
  207. for number, name in vreg_map.items():
  208. func_line = re.sub(r'{}\b'.format(number), '[[{}]]'.format(name),
  209. func_line)
  210. check_line = '{}: {}'.format(check, func_line[indent:]).rstrip()
  211. output_lines.append(check_line)
  212. def mangle_vreg(opcode, current_names):
  213. base = opcode
  214. # Simplify some common prefixes and suffixes
  215. if opcode.startswith('G_'):
  216. base = base[len('G_'):]
  217. if opcode.endswith('_PSEUDO'):
  218. base = base[:len('_PSEUDO')]
  219. # Shorten some common opcodes with long-ish names
  220. base = dict(IMPLICIT_DEF='DEF',
  221. GLOBAL_VALUE='GV',
  222. CONSTANT='C',
  223. FCONSTANT='C',
  224. MERGE_VALUES='MV',
  225. UNMERGE_VALUES='UV',
  226. INTRINSIC='INT',
  227. INTRINSIC_W_SIDE_EFFECTS='INT',
  228. INSERT_VECTOR_ELT='IVEC',
  229. EXTRACT_VECTOR_ELT='EVEC',
  230. SHUFFLE_VECTOR='SHUF').get(base, base)
  231. # Avoid ambiguity when opcodes end in numbers
  232. if len(base.rstrip('0123456789')) < len(base):
  233. base += '_'
  234. i = 0
  235. for name in current_names:
  236. if name.rstrip('0123456789') == base:
  237. i += 1
  238. if i:
  239. return '{}{}'.format(base, i)
  240. return base
  241. def should_add_line_to_output(input_line, prefix_set):
  242. # Skip any check lines that we're handling.
  243. m = common.CHECK_RE.match(input_line)
  244. if m and m.group(1) in prefix_set:
  245. return False
  246. return True
  247. def update_test_file(args, test):
  248. log('Scanning for RUN lines in test file: {}'.format(test), args.verbose)
  249. with open(test) as fd:
  250. input_lines = [l.rstrip() for l in fd]
  251. script_name = os.path.basename(__file__)
  252. first_line = input_lines[0] if input_lines else ""
  253. if 'autogenerated' in first_line and script_name not in first_line:
  254. common.warn("Skipping test which wasn't autogenerated by " +
  255. script_name + ": " + test)
  256. return
  257. if args.update_only:
  258. if not first_line or 'autogenerated' not in first_line:
  259. common.warn("Skipping test which isn't autogenerated: " + test)
  260. return
  261. triple_in_ir = find_triple_in_ir(input_lines, args.verbose)
  262. run_lines = find_run_lines(test, input_lines, args.verbose)
  263. run_list, common_prefixes = build_run_list(test, run_lines, args.verbose)
  264. simple_functions = find_functions_with_one_bb(input_lines, args.verbose)
  265. func_dict = {}
  266. for run in run_list:
  267. for prefix in run.prefixes:
  268. func_dict.update({prefix: dict()})
  269. for prefixes, llc_args, triple_in_cmd in run_list:
  270. log('Extracted LLC cmd: llc {}'.format(llc_args), args.verbose)
  271. log('Extracted FileCheck prefixes: {}'.format(prefixes), args.verbose)
  272. raw_tool_output = args.llc(llc_args, test)
  273. if not triple_in_cmd and not triple_in_ir:
  274. common.warn('No triple found: skipping file', test_file=test)
  275. return
  276. build_function_body_dictionary(test, raw_tool_output,
  277. triple_in_cmd or triple_in_ir,
  278. prefixes, func_dict, args.verbose)
  279. state = 'toplevel'
  280. func_name = None
  281. prefix_set = set([prefix for run in run_list for prefix in run.prefixes])
  282. log('Rewriting FileCheck prefixes: {}'.format(prefix_set), args.verbose)
  283. if args.remove_common_prefixes:
  284. prefix_set.update(common_prefixes)
  285. elif common_prefixes:
  286. common.warn('Ignoring common prefixes: {}'.format(common_prefixes),
  287. test_file=test)
  288. comment_char = '#' if test.endswith('.mir') else ';'
  289. autogenerated_note = ('{} NOTE: Assertions have been autogenerated by '
  290. 'utils/{}'.format(comment_char, script_name))
  291. output_lines = []
  292. output_lines.append(autogenerated_note)
  293. for input_line in input_lines:
  294. if input_line == autogenerated_note:
  295. continue
  296. if state == 'toplevel':
  297. m = IR_FUNC_NAME_RE.match(input_line)
  298. if m:
  299. state = 'ir function prefix'
  300. func_name = m.group('func')
  301. if input_line.rstrip('| \r\n') == '---':
  302. state = 'document'
  303. output_lines.append(input_line)
  304. elif state == 'document':
  305. m = MIR_FUNC_NAME_RE.match(input_line)
  306. if m:
  307. state = 'mir function metadata'
  308. func_name = m.group('func')
  309. if input_line.strip() == '...':
  310. state = 'toplevel'
  311. func_name = None
  312. if should_add_line_to_output(input_line, prefix_set):
  313. output_lines.append(input_line)
  314. elif state == 'mir function metadata':
  315. if should_add_line_to_output(input_line, prefix_set):
  316. output_lines.append(input_line)
  317. m = MIR_BODY_BEGIN_RE.match(input_line)
  318. if m:
  319. if func_name in simple_functions:
  320. # If there's only one block, put the checks inside it
  321. state = 'mir function prefix'
  322. continue
  323. state = 'mir function body'
  324. add_checks_for_function(test, output_lines, run_list,
  325. func_dict, func_name, single_bb=False,
  326. verbose=args.verbose)
  327. elif state == 'mir function prefix':
  328. m = MIR_PREFIX_DATA_RE.match(input_line)
  329. if not m:
  330. state = 'mir function body'
  331. add_checks_for_function(test, output_lines, run_list,
  332. func_dict, func_name, single_bb=True,
  333. verbose=args.verbose)
  334. if should_add_line_to_output(input_line, prefix_set):
  335. output_lines.append(input_line)
  336. elif state == 'mir function body':
  337. if input_line.strip() == '...':
  338. state = 'toplevel'
  339. func_name = None
  340. if should_add_line_to_output(input_line, prefix_set):
  341. output_lines.append(input_line)
  342. elif state == 'ir function prefix':
  343. m = IR_PREFIX_DATA_RE.match(input_line)
  344. if not m:
  345. state = 'ir function body'
  346. add_checks_for_function(test, output_lines, run_list,
  347. func_dict, func_name, single_bb=False,
  348. verbose=args.verbose)
  349. if should_add_line_to_output(input_line, prefix_set):
  350. output_lines.append(input_line)
  351. elif state == 'ir function body':
  352. if input_line.strip() == '}':
  353. state = 'toplevel'
  354. func_name = None
  355. if should_add_line_to_output(input_line, prefix_set):
  356. output_lines.append(input_line)
  357. log('Writing {} lines to {}...'.format(len(output_lines), test), args.verbose)
  358. with open(test, 'wb') as fd:
  359. fd.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines])
  360. def main():
  361. parser = argparse.ArgumentParser(
  362. description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
  363. parser.add_argument('-v', '--verbose', action='store_true',
  364. help='Show verbose output')
  365. parser.add_argument('--llc-binary', dest='llc', default='llc', type=LLC,
  366. help='The "llc" binary to generate the test case with')
  367. parser.add_argument('--remove-common-prefixes', action='store_true',
  368. help='Remove existing check lines whose prefixes are '
  369. 'shared between multiple commands')
  370. parser.add_argument('-u', '--update-only', action='store_true',
  371. help='Only update test if it was already autogened')
  372. parser.add_argument('tests', nargs='+')
  373. args = parser.parse_args()
  374. test_paths = [test for pattern in args.tests for test in glob.glob(pattern)]
  375. for test in test_paths:
  376. try:
  377. update_test_file(args, test)
  378. except Exception:
  379. common.warn('Error processing file', test_file=test)
  380. raise
  381. if __name__ == '__main__':
  382. main()