1#!/usr/bin/env python2.7
2
3"""A test case update script.
4
5This script is a utility to update LLVM X86 'llc' based test cases with new
6FileCheck patterns. It can either update all of the tests in the file or
7a single test function.
8"""
9
10import argparse
11import itertools
12import string
13import subprocess
14import sys
15import tempfile
16import re
17
18
19def llc(args, cmd_args, ir):
20  with open(ir) as ir_file:
21    stdout = subprocess.check_output(args.llc_binary + ' ' + cmd_args,
22                                     shell=True, stdin=ir_file)
23  return stdout
24
25
26ASM_SCRUB_WHITESPACE_RE = re.compile(r'(?!^(|  \w))[ \t]+', flags=re.M)
27ASM_SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
28ASM_SCRUB_SHUFFLES_RE = (
29    re.compile(
30        r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem) = .*)$',
31        flags=re.M))
32ASM_SCRUB_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
33ASM_SCRUB_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
34ASM_SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
35
36
37def scrub_asm(asm):
38  # Scrub runs of whitespace out of the assembly, but leave the leading
39  # whitespace in place.
40  asm = ASM_SCRUB_WHITESPACE_RE.sub(r' ', asm)
41  # Expand the tabs used for indentation.
42  asm = string.expandtabs(asm, 2)
43  # Detect shuffle asm comments and hide the operands in favor of the comments.
44  asm = ASM_SCRUB_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
45  # Generically match the stack offset of a memory operand.
46  asm = ASM_SCRUB_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
47  # Generically match a RIP-relative memory operand.
48  asm = ASM_SCRUB_RIP_RE.sub(r'{{.*}}(%rip)', asm)
49  # Strip kill operands inserted into the asm.
50  asm = ASM_SCRUB_KILL_COMMENT_RE.sub('', asm)
51  # Strip trailing whitespace.
52  asm = ASM_SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
53  return asm
54
55
56def main():
57  parser = argparse.ArgumentParser(description=__doc__)
58  parser.add_argument('-v', '--verbose', action='store_true',
59                      help='Show verbose output')
60  parser.add_argument('--llc-binary', default='llc',
61                      help='The "llc" binary to use to generate the test case')
62  parser.add_argument(
63      '--function', help='The function in the test file to update')
64  parser.add_argument('tests', nargs='+')
65  args = parser.parse_args()
66
67  run_line_re = re.compile('^\s*;\s*RUN:\s*(.*)$')
68  ir_function_re = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@(\w+)\s*\(')
69  asm_function_re = re.compile(
70      r'^_?(?P<f>[^:]+):[ \t]*#+[ \t]*@(?P=f)\n[^:]*?'
71      r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
72      r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)',
73      flags=(re.M | re.S))
74  check_prefix_re = re.compile('--check-prefix=(\S+)')
75  check_re = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
76
77  for test in args.tests:
78    if args.verbose:
79      print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
80    with open(test) as f:
81      test_lines = [l.rstrip() for l in f]
82
83    run_lines = [m.group(1)
84                 for m in [run_line_re.match(l) for l in test_lines] if m]
85    if args.verbose:
86      print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
87      for l in run_lines:
88        print >>sys.stderr, '  RUN: ' + l
89
90    checks = []
91    for l in run_lines:
92      (llc_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
93      if not llc_cmd.startswith('llc '):
94        print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l
95        continue
96
97      if not filecheck_cmd.startswith('FileCheck '):
98        print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
99        continue
100
101      llc_cmd_args = llc_cmd[len('llc'):].strip()
102      llc_cmd_args = llc_cmd_args.replace('< %s', '').replace('%s', '').strip()
103
104      check_prefixes = [m.group(1)
105                        for m in check_prefix_re.finditer(filecheck_cmd)]
106      if not check_prefixes:
107        check_prefixes = ['CHECK']
108
109      # FIXME: We should use multiple check prefixes to common check lines. For
110      # now, we just ignore all but the last.
111      checks.append((check_prefixes, llc_cmd_args))
112
113    asm = {}
114    for prefixes, _ in checks:
115      for prefix in prefixes:
116        asm.update({prefix: dict()})
117    for prefixes, llc_args in checks:
118      if args.verbose:
119        print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args
120        print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
121      raw_asm = llc(args, llc_args, test)
122      # Build up a dictionary of all the function bodies.
123      for m in asm_function_re.finditer(raw_asm):
124        if not m:
125          continue
126        f = m.group('f')
127        f_asm = scrub_asm(m.group('body'))
128        if f.startswith('stress'):
129          # We only use the last line of the asm for stress tests.
130          f_asm = '\n'.join(f_asm.splitlines()[-1:])
131        if args.verbose:
132          print >>sys.stderr, 'Processing asm for function: ' + f
133          for l in f_asm.splitlines():
134            print >>sys.stderr, '  ' + l
135        for prefix in prefixes:
136          if f in asm[prefix] and asm[prefix][f] != f_asm:
137            if prefix == prefixes[-1]:
138              print >>sys.stderr, ('WARNING: Found conflicting asm under the '
139                                   'same prefix!')
140            else:
141              asm[prefix][f] = None
142              continue
143
144          asm[prefix][f] = f_asm
145
146    is_in_function = False
147    is_in_function_start = False
148    prefix_set = set([prefix for prefixes, _ in checks for prefix in prefixes])
149    if args.verbose:
150      print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
151    fixed_lines = []
152    for l in test_lines:
153      if is_in_function_start:
154        if l.lstrip().startswith(';'):
155          m = check_re.match(l)
156          if not m or m.group(1) not in prefix_set:
157            fixed_lines.append(l)
158            continue
159
160        # Print out the various check lines here
161        printed_prefixes = []
162        for prefixes, _ in checks:
163          for prefix in prefixes:
164            if prefix in printed_prefixes:
165              break
166            if not asm[prefix][name]:
167              continue
168            if len(printed_prefixes) != 0:
169              fixed_lines.append(';')
170            printed_prefixes.append(prefix)
171            fixed_lines.append('; %s-LABEL: %s:' % (prefix, name))
172            asm_lines = asm[prefix][name].splitlines()
173            fixed_lines.append('; %s:       %s' % (prefix, asm_lines[0]))
174            for asm_line in asm_lines[1:]:
175              fixed_lines.append('; %s-NEXT:  %s' % (prefix, asm_line))
176            break
177        is_in_function_start = False
178
179      if is_in_function:
180        # Skip any blank comment lines in the IR.
181        if l.strip() == ';':
182          continue
183        # And skip any CHECK lines. We'll build our own.
184        m = check_re.match(l)
185        if m and m.group(1) in prefix_set:
186          continue
187        # Collect the remaining lines in the function body and look for the end
188        # of the function.
189        fixed_lines.append(l)
190        if l.strip() == '}':
191          is_in_function = False
192        continue
193
194      fixed_lines.append(l)
195
196      m = ir_function_re.match(l)
197      if not m:
198        continue
199      name = m.group(1)
200      if args.function is not None and name != args.function:
201        # When filtering on a specific function, skip all others.
202        continue
203      is_in_function = is_in_function_start = True
204
205    if args.verbose:
206      print>>sys.stderr, 'Writing %d fixed lines to %s...' % (
207          len(fixed_lines), test)
208    with open(test, 'w') as f:
209      f.writelines([l + '\n' for l in fixed_lines])
210
211
212if __name__ == '__main__':
213  main()
214