Skip to content

Commit d9542db

Browse files
committed
[UpdateTestChecks] Share the code to parse RUN: lines between all scripts
Summary: This commit also introduces a common.debug() function to avoid many `if args.verbose:` statements. Depends on D70428. Reviewers: xbolva00, MaskRay, jdoerfert Reviewed By: MaskRay Subscribers: llvm-commits Tags: #llvm Differential Revision: https://reviews.llvm.org/D70432
1 parent 160a504 commit d9542db

7 files changed

+62
-150
lines changed

llvm/utils/UpdateTestChecks/common.py

+29-2
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,17 @@ class string:
1414
##### Common utilities for update_*test_checks.py
1515

1616

17+
_verbose = False
18+
1719
def parse_commandline_args(parser):
1820
parser.add_argument('-v', '--verbose', action='store_true',
1921
help='Show verbose output')
2022
parser.add_argument('-u', '--update-only', action='store_true',
2123
help='Only update test if it was already autogened')
22-
return parser.parse_args()
24+
args = parser.parse_args()
25+
global _verbose
26+
_verbose = args.verbose
27+
return args
2328

2429
def should_add_line_to_output(input_line, prefix_set):
2530
# Skip any blank comment lines in the IR.
@@ -53,7 +58,7 @@ def invoke_tool(exe, cmd_args, ir):
5358

5459
##### LLVM IR parser
5560

56-
RUN_LINE_RE = re.compile(r'^\s*[;#]\s*RUN:\s*(.*)$')
61+
RUN_LINE_RE = re.compile(r'^\s*(?://|[;#])\s*RUN:\s*(.*)$')
5762
CHECK_PREFIX_RE = re.compile(r'--?check-prefix(?:es)?[= ](\S+)')
5863
PREFIX_RE = re.compile('^[a-zA-Z0-9_-]+$')
5964
CHECK_RE = re.compile(r'^\s*[;#]\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL|-SAME)?:')
@@ -91,6 +96,28 @@ def warn(msg, test_file=None):
9196
msg = '{}: {}'.format(msg, test_file)
9297
print('WARNING: {}'.format(msg), file=sys.stderr)
9398

99+
def debug(*args, **kwargs):
100+
# Python2 does not allow def debug(*args, file=sys.stderr, **kwargs):
101+
if 'file' not in kwargs:
102+
kwargs['file'] = sys.stderr
103+
if _verbose:
104+
print(*args, **kwargs)
105+
106+
def find_run_lines(test, lines):
107+
debug('Scanning for RUN lines in test file:', test)
108+
raw_lines = [m.group(1)
109+
for m in [RUN_LINE_RE.match(l) for l in lines] if m]
110+
run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
111+
for l in raw_lines[1:]:
112+
if run_lines[-1].endswith('\\'):
113+
run_lines[-1] = run_lines[-1].rstrip('\\' + ' ' + l)
114+
else:
115+
run_lines.append(l)
116+
debug('Found {} RUN lines in {}:'.format(len(run_lines), test))
117+
for l in run_lines:
118+
debug(' RUN: {}'.format(l))
119+
return run_lines
120+
94121
def scrub_body(body):
95122
# Scrub runs of whitespace out of the assembly, but leave the leading
96123
# whitespace in place.

llvm/utils/update_analyze_test_checks.py

+5-23
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,6 @@ def main():
6969

7070
test_paths = [test for pattern in args.tests for test in glob.glob(pattern)]
7171
for test in test_paths:
72-
if args.verbose:
73-
print('Scanning for RUN lines in test file: %s' % (test,), file=sys.stderr)
7472
with open(test) as f:
7573
input_lines = [l.rstrip() for l in f]
7674

@@ -84,20 +82,7 @@ def main():
8482
common.warn("Skipping test which isn't autogenerated: " + test)
8583
continue
8684

87-
raw_lines = [m.group(1)
88-
for m in [common.RUN_LINE_RE.match(l) for l in input_lines] if m]
89-
run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
90-
for l in raw_lines[1:]:
91-
if run_lines[-1].endswith("\\"):
92-
run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
93-
else:
94-
run_lines.append(l)
95-
96-
if args.verbose:
97-
print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
98-
for l in run_lines:
99-
print(' RUN: ' + l, file=sys.stderr)
100-
85+
run_lines = common.find_run_lines(test, input_lines)
10186
prefix_list = []
10287
for l in run_lines:
10388
if '|' not in l:
@@ -132,9 +117,8 @@ def main():
132117
for prefix in prefixes:
133118
func_dict.update({prefix: dict()})
134119
for prefixes, opt_args in prefix_list:
135-
if args.verbose:
136-
print('Extracted opt cmd: ' + opt_basename + ' ' + opt_args, file=sys.stderr)
137-
print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
120+
common.debug('Extracted opt cmd:', opt_basename, opt_args, file=sys.stderr)
121+
common.debug('Extracted FileCheck prefixes:', str(prefixes), file=sys.stderr)
138122

139123
raw_tool_outputs = common.invoke_tool(args.opt_binary, opt_args, test)
140124

@@ -147,8 +131,7 @@ def main():
147131
is_in_function = False
148132
is_in_function_start = False
149133
prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
150-
if args.verbose:
151-
print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
134+
common.debug('Rewriting FileCheck prefixes:', str(prefix_set), file=sys.stderr)
152135
output_lines = []
153136
output_lines.append(autogenerated_note)
154137

@@ -194,8 +177,7 @@ def main():
194177
continue
195178
is_in_function = is_in_function_start = True
196179

197-
if args.verbose:
198-
print('Writing %d lines to %s...' % (len(output_lines), test), file=sys.stderr)
180+
common.debug('Writing %d lines to %s...' % (len(output_lines), test))
199181

200182
with open(test, 'wb') as f:
201183
f.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines])

llvm/utils/update_cc_test_checks.py

+9-27
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
ADVERT = '// NOTE: Assertions have been autogenerated by '
3030

3131
CHECK_RE = re.compile(r'^\s*//\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
32-
RUN_LINE_RE = re.compile(r'^//\s*RUN:\s*(.*)$')
3332

3433
SUBST = {
3534
'%clang': [],
@@ -38,9 +37,6 @@
3837
}
3938

4039
def get_line2spell_and_mangled(args, clang_args):
41-
def debug_mangled(*print_args, **kwargs):
42-
if args.verbose:
43-
print(*print_args, file=sys.stderr, **kwargs)
4440
ret = {}
4541
# Use clang's JSON AST dump to get the mangled name
4642
json_dump_args = [args.clang, *clang_args, '-fsyntax-only', '-o', '-']
@@ -49,7 +45,7 @@ def debug_mangled(*print_args, **kwargs):
4945
# -Xclang -ast-dump=json instead:
5046
json_dump_args.append('-Xclang')
5147
json_dump_args.append('-ast-dump=json')
52-
debug_mangled('Running', ' '.join(json_dump_args))
48+
common.debug('Running', ' '.join(json_dump_args))
5349
status = subprocess.run(json_dump_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
5450
if status.returncode != 0:
5551
sys.stderr.write('Failed to run ' + ' '.join(json_dump_args) + '\n')
@@ -67,20 +63,19 @@ def debug_mangled(*print_args, **kwargs):
6763
if node['kind'] != 'FunctionDecl':
6864
continue
6965
if node.get('isImplicit') is True and node.get('storageClass') == 'extern':
70-
debug_mangled('Skipping builtin function:', node['name'], '@', node['loc'])
66+
common.debug('Skipping builtin function:', node['name'], '@', node['loc'])
7167
continue
72-
debug_mangled('Found function:', node['kind'], node['name'], '@', node['loc'])
68+
common.debug('Found function:', node['kind'], node['name'], '@', node['loc'])
7369
line = node['loc'].get('line')
7470
# If there is no line it is probably a builtin function -> skip
7571
if line is None:
76-
debug_mangled('Skipping function without line number:', node['name'], '@', node['loc'])
72+
common.debug('Skipping function without line number:', node['name'], '@', node['loc'])
7773
continue
7874
spell = node['name']
7975
mangled = node.get('mangledName', spell)
8076
ret[int(line)-1] = (spell, mangled)
81-
if args.verbose:
82-
for line, func_name in sorted(ret.items()):
83-
print('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
77+
for line, func_name in sorted(ret.items()):
78+
common.debug('line {}: found function {}'.format(line+1, func_name), file=sys.stderr)
8479
if not ret:
8580
common.warn('Did not find any functions using', ' '.join(json_dump_args))
8681
return ret
@@ -191,19 +186,7 @@ def main():
191186
continue
192187

193188
# Extract RUN lines.
194-
raw_lines = [m.group(1)
195-
for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
196-
run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
197-
for l in raw_lines[1:]:
198-
if run_lines[-1].endswith("\\"):
199-
run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
200-
else:
201-
run_lines.append(l)
202-
203-
if args.verbose:
204-
print('Found {} RUN lines:'.format(len(run_lines)), file=sys.stderr)
205-
for l in run_lines:
206-
print(' RUN: ' + l, file=sys.stderr)
189+
run_lines = common.find_run_lines(filename, input_lines)
207190

208191
# Build a list of clang command lines and check prefixes from RUN lines.
209192
run_list = []
@@ -260,9 +243,8 @@ def main():
260243
for prefix in prefixes:
261244
func_dict.update({prefix: dict()})
262245
for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
263-
if args.verbose:
264-
print('Extracted clang cmd: clang {}'.format(clang_args), file=sys.stderr)
265-
print('Extracted FileCheck prefixes: {}'.format(prefixes), file=sys.stderr)
246+
common.debug('Extracted clang cmd: clang {}'.format(clang_args))
247+
common.debug('Extracted FileCheck prefixes: {}'.format(prefixes))
266248

267249
get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
268250

llvm/utils/update_llc_test_checks.py

+11-29
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,6 @@ def main():
4343

4444
test_paths = [test for pattern in args.tests for test in glob.glob(pattern)]
4545
for test in test_paths:
46-
if args.verbose:
47-
print('Scanning for RUN lines in test file: %s' % (test,), file=sys.stderr)
4846
with open(test) as f:
4947
input_lines = [l.rstrip() for l in f]
5048

@@ -65,20 +63,7 @@ def main():
6563
triple_in_ir = m.groups()[0]
6664
break
6765

68-
raw_lines = [m.group(1)
69-
for m in [common.RUN_LINE_RE.match(l) for l in input_lines] 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("\\"):
73-
run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
74-
else:
75-
run_lines.append(l)
76-
77-
if args.verbose:
78-
print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
79-
for l in run_lines:
80-
print(' RUN: ' + l, file=sys.stderr)
81-
66+
run_lines = common.find_run_lines(test, input_lines)
8267
run_list = []
8368
for l in run_lines:
8469
if '|' not in l:
@@ -115,12 +100,6 @@ def main():
115100
llc_cmd_args = llc_cmd_args.replace('< %s', '').replace('%s', '').strip()
116101
if test.endswith('.mir'):
117102
llc_cmd_args += ' -x mir'
118-
comment_sym = '#'
119-
check_indent = ' '
120-
else:
121-
comment_sym = ';'
122-
check_indent = ''
123-
124103
check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
125104
for item in m.group(1).split(',')]
126105
if not check_prefixes:
@@ -130,6 +109,12 @@ def main():
130109
# now, we just ignore all but the last.
131110
run_list.append((check_prefixes, llc_cmd_args, triple_in_cmd, march_in_cmd))
132111

112+
if test.endswith('.mir'):
113+
comment_sym = '#'
114+
check_indent = ' '
115+
else:
116+
comment_sym = ';'
117+
check_indent = ''
133118
autogenerated_note = (comment_sym + ADVERT + 'utils/' + script_name)
134119

135120
func_dict = {}
@@ -138,9 +123,8 @@ def main():
138123
for prefix in prefixes:
139124
func_dict.update({prefix: dict()})
140125
for prefixes, llc_args, triple_in_cmd, march_in_cmd in run_list:
141-
if args.verbose:
142-
print('Extracted LLC cmd: ' + llc_tool + ' ' + llc_args, file=sys.stderr)
143-
print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
126+
common.debug('Extracted LLC cmd:', llc_tool, llc_args)
127+
common.debug('Extracted FileCheck prefixes:', str(prefixes))
144128

145129
raw_tool_output = common.invoke_tool(args.llc_binary, llc_args, test)
146130
triple = triple_in_cmd or triple_in_ir
@@ -154,8 +138,7 @@ def main():
154138
is_in_function_start = False
155139
func_name = None
156140
prefix_set = set([prefix for p in run_list for prefix in p[0]])
157-
if args.verbose:
158-
print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
141+
common.debug('Rewriting FileCheck prefixes:', str(prefix_set))
159142
output_lines = []
160143
output_lines.append(autogenerated_note)
161144

@@ -199,8 +182,7 @@ def main():
199182
continue
200183
is_in_function = is_in_function_start = True
201184

202-
if args.verbose:
203-
print('Writing %d lines to %s...' % (len(output_lines), test), file=sys.stderr)
185+
common.debug('Writing %d lines to %s...' % (len(output_lines), test))
204186

205187
with open(test, 'wb') as f:
206188
f.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines])

llvm/utils/update_mca_test_checks.py

+2-28
Original file line numberDiff line numberDiff line change
@@ -83,26 +83,6 @@ def _parse_args():
8383
return args
8484

8585

86-
def _find_run_lines(input_lines, args):
87-
raw_lines = [m.group(1)
88-
for m in [common.RUN_LINE_RE.match(l) for l in input_lines]
89-
if m]
90-
run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
91-
for l in raw_lines[1:]:
92-
if run_lines[-1].endswith(r'\\'):
93-
run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l
94-
else:
95-
run_lines.append(l)
96-
97-
if args.verbose:
98-
sys.stderr.write('Found {} RUN line{}:\n'.format(
99-
len(run_lines), '' if len(run_lines) == 1 else 's'))
100-
for line in run_lines:
101-
sys.stderr.write(' RUN: {}\n'.format(line))
102-
103-
return run_lines
104-
105-
10686
def _get_run_infos(run_lines, args):
10787
run_infos = []
10888
for run_line in run_lines:
@@ -544,9 +524,7 @@ def _write_output(test_path, input_lines, prefix_list, block_infos, # noqa
544524
return
545525
sys.stderr.write(' [{} lines total]\n'.format(len(output_lines)))
546526

547-
if args.verbose:
548-
sys.stderr.write(
549-
'Writing {} lines to {}...\n\n'.format(len(output_lines), test_path))
527+
common.debug('Writing', len(output_lines), 'lines to', test_path, '..\n\n')
550528

551529
with open(test_path, 'wb') as f:
552530
f.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines])
@@ -562,17 +540,13 @@ def main():
562540
# will be written once per source location per test.
563541
_configure_warnings(args)
564542

565-
if args.verbose:
566-
sys.stderr.write(
567-
'Scanning for RUN lines in test file: {}\n'.format(test_path))
568-
569543
if not os.path.isfile(test_path):
570544
raise Error('could not find test file: {}'.format(test_path))
571545

572546
with open(test_path) as f:
573547
input_lines = [l.rstrip() for l in f]
574548

575-
run_lines = _find_run_lines(input_lines, args)
549+
run_lines = common.find_run_lines(test_path, input_lines)
576550
run_infos = _get_run_infos(run_lines, args)
577551
common_prefix, prefix_pad = _get_useful_prefix_info(run_infos)
578552
block_infos = _get_block_infos(run_infos, test_path, args, common_prefix)

llvm/utils/update_mir_test_checks.py

+1-18
Original file line numberDiff line numberDiff line change
@@ -96,22 +96,6 @@ def find_triple_in_ir(lines, verbose=False):
9696
return None
9797

9898

99-
def find_run_lines(test, lines, verbose=False):
100-
raw_lines = [m.group(1)
101-
for m in [common.RUN_LINE_RE.match(l) for l in lines] if m]
102-
run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
103-
for l in raw_lines[1:]:
104-
if run_lines[-1].endswith("\\"):
105-
run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
106-
else:
107-
run_lines.append(l)
108-
if verbose:
109-
log('Found {} RUN lines:'.format(len(run_lines)))
110-
for l in run_lines:
111-
log(' RUN: {}'.format(l))
112-
return run_lines
113-
114-
11599
def build_run_list(test, run_lines, verbose=False):
116100
run_list = []
117101
all_prefixes = []
@@ -296,7 +280,6 @@ def should_add_line_to_output(input_line, prefix_set):
296280

297281

298282
def update_test_file(args, test):
299-
log('Scanning for RUN lines in test file: {}'.format(test), args.verbose)
300283
with open(test) as fd:
301284
input_lines = [l.rstrip() for l in fd]
302285

@@ -313,7 +296,7 @@ def update_test_file(args, test):
313296
return
314297

315298
triple_in_ir = find_triple_in_ir(input_lines, args.verbose)
316-
run_lines = find_run_lines(test, input_lines, args.verbose)
299+
run_lines = common.find_run_lines(test, input_lines)
317300
run_list, common_prefixes = build_run_list(test, run_lines, args.verbose)
318301

319302
simple_functions = find_functions_with_one_bb(input_lines, args.verbose)

0 commit comments

Comments
 (0)