1from __future__ import print_function 2import re 3import string 4import subprocess 5import sys 6import copy 7 8if sys.version_info[0] > 2: 9 class string: 10 expandtabs = str.expandtabs 11else: 12 import string 13 14##### Common utilities for update_*test_checks.py 15 16 17_verbose = False 18 19def parse_commandline_args(parser): 20 parser.add_argument('-v', '--verbose', action='store_true', 21 help='Show verbose output') 22 parser.add_argument('-u', '--update-only', action='store_true', 23 help='Only update test if it was already autogened') 24 args = parser.parse_args() 25 global _verbose 26 _verbose = args.verbose 27 return args 28 29def should_add_line_to_output(input_line, prefix_set): 30 # Skip any blank comment lines in the IR. 31 if input_line.strip() == ';': 32 return False 33 # Skip any blank lines in the IR. 34 #if input_line.strip() == '': 35 # return False 36 # And skip any CHECK lines. We're building our own. 37 m = CHECK_RE.match(input_line) 38 if m and m.group(1) in prefix_set: 39 return False 40 41 return True 42 43# Invoke the tool that is being tested. 44def invoke_tool(exe, cmd_args, ir): 45 with open(ir) as ir_file: 46 # TODO Remove the str form which is used by update_test_checks.py and 47 # update_llc_test_checks.py 48 # The safer list form is used by update_cc_test_checks.py 49 if isinstance(cmd_args, list): 50 stdout = subprocess.check_output([exe] + cmd_args, stdin=ir_file) 51 else: 52 stdout = subprocess.check_output(exe + ' ' + cmd_args, 53 shell=True, stdin=ir_file) 54 if sys.version_info[0] > 2: 55 stdout = stdout.decode() 56 # Fix line endings to unix CR style. 57 return stdout.replace('\r\n', '\n') 58 59##### LLVM IR parser 60 61RUN_LINE_RE = re.compile(r'^\s*(?://|[;#])\s*RUN:\s*(.*)$') 62CHECK_PREFIX_RE = re.compile(r'--?check-prefix(?:es)?[= ](\S+)') 63PREFIX_RE = re.compile('^[a-zA-Z0-9_-]+$') 64CHECK_RE = re.compile(r'^\s*(?://|[;#])\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL|-SAME|-EMPTY)?:') 65 66UTC_ARGS_KEY = 'UTC_ARGS:' 67UTC_ARGS_CMD = re.compile(r'.*' + UTC_ARGS_KEY + '\s*(?P<cmd>.*)\s*$') 68 69OPT_FUNCTION_RE = re.compile( 70 r'^\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w.-]+?)\s*' 71 r'(?P<args_and_sig>\((\)|(.*?[\w.-]+?)\))[^{]*)\{\n(?P<body>.*?)^\}$', 72 flags=(re.M | re.S)) 73 74ANALYZE_FUNCTION_RE = re.compile( 75 r'^\s*\'(?P<analysis>[\w\s-]+?)\'\s+for\s+function\s+\'(?P<func>[\w.-]+?)\':' 76 r'\s*\n(?P<body>.*)$', 77 flags=(re.X | re.S)) 78 79IR_FUNCTION_RE = re.compile(r'^\s*define\s+(?:internal\s+)?[^@]*@([\w.-]+)\s*\(') 80TRIPLE_IR_RE = re.compile(r'^\s*target\s+triple\s*=\s*"([^"]+)"$') 81TRIPLE_ARG_RE = re.compile(r'-mtriple[= ]([^ ]+)') 82MARCH_ARG_RE = re.compile(r'-march[= ]([^ ]+)') 83 84SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)') 85SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M) 86SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M) 87SCRUB_TRAILING_WHITESPACE_TEST_RE = SCRUB_TRAILING_WHITESPACE_RE 88SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE = re.compile(r'([ \t]|(#[0-9]+))+$', flags=re.M) 89SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n') 90SCRUB_LOOP_COMMENT_RE = re.compile( 91 r'# =>This Inner Loop Header:.*|# in Loop:.*', flags=re.M) 92 93 94def error(msg, test_file=None): 95 if test_file: 96 msg = '{}: {}'.format(msg, test_file) 97 print('ERROR: {}'.format(msg), file=sys.stderr) 98 99def warn(msg, test_file=None): 100 if test_file: 101 msg = '{}: {}'.format(msg, test_file) 102 print('WARNING: {}'.format(msg), file=sys.stderr) 103 104def debug(*args, **kwargs): 105 # Python2 does not allow def debug(*args, file=sys.stderr, **kwargs): 106 if 'file' not in kwargs: 107 kwargs['file'] = sys.stderr 108 if _verbose: 109 print(*args, **kwargs) 110 111def find_run_lines(test, lines): 112 debug('Scanning for RUN lines in test file:', test) 113 raw_lines = [m.group(1) 114 for m in [RUN_LINE_RE.match(l) for l in lines] if m] 115 run_lines = [raw_lines[0]] if len(raw_lines) > 0 else [] 116 for l in raw_lines[1:]: 117 if run_lines[-1].endswith('\\'): 118 run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l 119 else: 120 run_lines.append(l) 121 debug('Found {} RUN lines in {}:'.format(len(run_lines), test)) 122 for l in run_lines: 123 debug(' RUN: {}'.format(l)) 124 return run_lines 125 126def scrub_body(body): 127 # Scrub runs of whitespace out of the assembly, but leave the leading 128 # whitespace in place. 129 body = SCRUB_WHITESPACE_RE.sub(r' ', body) 130 # Expand the tabs used for indentation. 131 body = string.expandtabs(body, 2) 132 # Strip trailing whitespace. 133 body = SCRUB_TRAILING_WHITESPACE_TEST_RE.sub(r'', body) 134 return body 135 136def do_scrub(body, scrubber, scrubber_args, extra): 137 if scrubber_args: 138 local_args = copy.deepcopy(scrubber_args) 139 local_args[0].extra_scrub = extra 140 return scrubber(body, *local_args) 141 return scrubber(body, *scrubber_args) 142 143# Build up a dictionary of all the function bodies. 144class function_body(object): 145 def __init__(self, string, extra, args_and_sig): 146 self.scrub = string 147 self.extrascrub = extra 148 self.args_and_sig = args_and_sig 149 def is_same_except_arg_names(self, extrascrub, args_and_sig): 150 arg_names = set() 151 def drop_arg_names(match): 152 arg_names.add(match.group(2)) 153 return match.group(1) + match.group(3) 154 def repl_arg_names(match): 155 if match.group(2) in arg_names: 156 return match.group(1) + match.group(3) 157 return match.group(1) + match.group(2) + match.group(3) 158 ans0 = IR_VALUE_RE.sub(drop_arg_names, self.args_and_sig) 159 ans1 = IR_VALUE_RE.sub(drop_arg_names, args_and_sig) 160 if ans0 != ans1: 161 return False 162 es0 = IR_VALUE_RE.sub(repl_arg_names, self.extrascrub) 163 es1 = IR_VALUE_RE.sub(repl_arg_names, extrascrub) 164 es0 = SCRUB_IR_COMMENT_RE.sub(r'', es0) 165 es1 = SCRUB_IR_COMMENT_RE.sub(r'', es1) 166 return es0 == es1 167 168 def __str__(self): 169 return self.scrub 170 171def build_function_body_dictionary(function_re, scrubber, scrubber_args, raw_tool_output, prefixes, func_dict, verbose, record_args): 172 for m in function_re.finditer(raw_tool_output): 173 if not m: 174 continue 175 func = m.group('func') 176 body = m.group('body') 177 # Determine if we print arguments, the opening brace, or nothing after the function name 178 if record_args and 'args_and_sig' in m.groupdict(): 179 args_and_sig = scrub_body(m.group('args_and_sig').strip()) 180 elif 'args_and_sig' in m.groupdict(): 181 args_and_sig = '(' 182 else: 183 args_and_sig = '' 184 scrubbed_body = do_scrub(body, scrubber, scrubber_args, extra = False) 185 scrubbed_extra = do_scrub(body, scrubber, scrubber_args, extra = True) 186 if 'analysis' in m.groupdict(): 187 analysis = m.group('analysis') 188 if analysis.lower() != 'cost model analysis': 189 warn('Unsupported analysis mode: %r!' % (analysis,)) 190 if func.startswith('stress'): 191 # We only use the last line of the function body for stress tests. 192 scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:]) 193 if verbose: 194 print('Processing function: ' + func, file=sys.stderr) 195 for l in scrubbed_body.splitlines(): 196 print(' ' + l, file=sys.stderr) 197 for prefix in prefixes: 198 if func in func_dict[prefix] and (str(func_dict[prefix][func]) != scrubbed_body or (func_dict[prefix][func] and func_dict[prefix][func].args_and_sig != args_and_sig)): 199 if func_dict[prefix][func] and func_dict[prefix][func].is_same_except_arg_names(scrubbed_extra, args_and_sig): 200 func_dict[prefix][func].scrub = scrubbed_extra 201 func_dict[prefix][func].args_and_sig = args_and_sig 202 continue 203 else: 204 if prefix == prefixes[-1]: 205 warn('Found conflicting asm under the same prefix: %r!' % (prefix,)) 206 else: 207 func_dict[prefix][func] = None 208 continue 209 210 func_dict[prefix][func] = function_body(scrubbed_body, scrubbed_extra, args_and_sig) 211 212##### Generator of LLVM IR CHECK lines 213 214SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*') 215 216# Match things that look at identifiers, but only if they are followed by 217# spaces, commas, paren, or end of the string 218IR_VALUE_RE = re.compile(r'(\s+)%([\w.-]+?)([,\s\(\)]|\Z)') 219 220# Create a FileCheck variable name based on an IR name. 221def get_value_name(var): 222 if var.isdigit(): 223 var = 'TMP' + var 224 var = var.replace('.', '_') 225 var = var.replace('-', '_') 226 return var.upper() 227 228 229# Create a FileCheck variable from regex. 230def get_value_definition(var): 231 return '[[' + get_value_name(var) + ':%.*]]' 232 233 234# Use a FileCheck variable. 235def get_value_use(var): 236 return '[[' + get_value_name(var) + ']]' 237 238# Replace IR value defs and uses with FileCheck variables. 239def genericize_check_lines(lines, is_analyze, vars_seen): 240 # This gets called for each match that occurs in 241 # a line. We transform variables we haven't seen 242 # into defs, and variables we have seen into uses. 243 def transform_line_vars(match): 244 var = match.group(2) 245 if var in vars_seen: 246 rv = get_value_use(var) 247 else: 248 vars_seen.add(var) 249 rv = get_value_definition(var) 250 # re.sub replaces the entire regex match 251 # with whatever you return, so we have 252 # to make sure to hand it back everything 253 # including the commas and spaces. 254 return match.group(1) + rv + match.group(3) 255 256 lines_with_def = [] 257 258 for i, line in enumerate(lines): 259 # An IR variable named '%.' matches the FileCheck regex string. 260 line = line.replace('%.', '%dot') 261 # Ignore any comments, since the check lines will too. 262 scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line) 263 if is_analyze: 264 lines[i] = scrubbed_line 265 else: 266 lines[i] = IR_VALUE_RE.sub(transform_line_vars, scrubbed_line) 267 return lines 268 269 270def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze): 271 # prefix_blacklist are prefixes we cannot use to print the function because it doesn't exist in run lines that use these prefixes as well. 272 prefix_blacklist = set() 273 printed_prefixes = [] 274 for p in prefix_list: 275 checkprefixes = p[0] 276 # If not all checkprefixes of this run line produced the function we cannot check for it as it does not 277 # exist for this run line. A subset of the check prefixes might know about the function but only because 278 # other run lines created it. 279 if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)): 280 prefix_blacklist |= set(checkprefixes) 281 continue 282 283 # prefix_blacklist is constructed, we can now emit the output 284 for p in prefix_list: 285 checkprefixes = p[0] 286 for checkprefix in checkprefixes: 287 if checkprefix in printed_prefixes: 288 break 289 290 # Check if the prefix is blacklisted. 291 if checkprefix in prefix_blacklist: 292 continue 293 294 # If we do not have output for this prefix we skip it. 295 if not func_dict[checkprefix][func_name]: 296 continue 297 298 # Add some space between different check prefixes, but not after the last 299 # check line (before the test code). 300 if is_asm: 301 if len(printed_prefixes) != 0: 302 output_lines.append(comment_marker) 303 304 vars_seen = set() 305 printed_prefixes.append(checkprefix) 306 args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig) 307 args_and_sig = genericize_check_lines([args_and_sig], is_analyze, vars_seen)[0] 308 if '[[' in args_and_sig: 309 output_lines.append(check_label_format % (checkprefix, func_name, '')) 310 output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig)) 311 else: 312 output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig)) 313 func_body = str(func_dict[checkprefix][func_name]).splitlines() 314 315 # For ASM output, just emit the check lines. 316 if is_asm: 317 output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 318 for func_line in func_body[1:]: 319 if func_line.strip() == '': 320 output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix)) 321 else: 322 output_lines.append('%s %s-NEXT: %s' % (comment_marker, checkprefix, func_line)) 323 break 324 325 # For IR output, change all defs to FileCheck variables, so we're immune 326 # to variable naming fashions. 327 func_body = genericize_check_lines(func_body, is_analyze, vars_seen) 328 329 # This could be selectively enabled with an optional invocation argument. 330 # Disabled for now: better to check everything. Be safe rather than sorry. 331 332 # Handle the first line of the function body as a special case because 333 # it's often just noise (a useless asm comment or entry label). 334 #if func_body[0].startswith("#") or func_body[0].startswith("entry:"): 335 # is_blank_line = True 336 #else: 337 # output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 338 # is_blank_line = False 339 340 is_blank_line = False 341 342 for func_line in func_body: 343 if func_line.strip() == '': 344 is_blank_line = True 345 continue 346 # Do not waste time checking IR comments. 347 func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line) 348 349 # Skip blank lines instead of checking them. 350 if is_blank_line: 351 output_lines.append('{} {}: {}'.format( 352 comment_marker, checkprefix, func_line)) 353 else: 354 output_lines.append('{} {}-NEXT: {}'.format( 355 comment_marker, checkprefix, func_line)) 356 is_blank_line = False 357 358 # Add space between different check prefixes and also before the first 359 # line of code in the test function. 360 output_lines.append(comment_marker) 361 break 362 363def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict, 364 func_name, preserve_names, function_sig): 365 # Label format is based on IR string. 366 function_def_regex = 'define {{[^@]+}}' if function_sig else '' 367 check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex) 368 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, 369 check_label_format, False, preserve_names) 370 371def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name): 372 check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker) 373 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, False, True) 374 375 376def check_prefix(prefix): 377 if not PREFIX_RE.match(prefix): 378 hint = "" 379 if ',' in prefix: 380 hint = " Did you mean '--check-prefixes=" + prefix + "'?" 381 warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) % 382 (prefix)) 383 384 385def verify_filecheck_prefixes(fc_cmd): 386 fc_cmd_parts = fc_cmd.split() 387 for part in fc_cmd_parts: 388 if "check-prefix=" in part: 389 prefix = part.split('=', 1)[1] 390 check_prefix(prefix) 391 elif "check-prefixes=" in part: 392 prefixes = part.split('=', 1)[1].split(',') 393 for prefix in prefixes: 394 check_prefix(prefix) 395 if prefixes.count(prefix) > 1: 396 warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,)) 397 398def get_autogennote_suffix(parser, args): 399 autogenerated_note_args = '' 400 for k, v in args._get_kwargs(): 401 if parser.get_default(k) == v or k == 'tests' or k == 'update_only' or k == 'opt_binary': 402 continue 403 k = k.replace('_', '-') 404 if type(v) is bool: 405 autogenerated_note_args += '--%s ' % (k) 406 else: 407 autogenerated_note_args += '--%s %s ' % (k, v) 408 if autogenerated_note_args: 409 autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1]) 410 return autogenerated_note_args 411 412 413def check_for_command(line, parser, args, argv): 414 cmd_m = UTC_ARGS_CMD.match(line) 415 if cmd_m: 416 cmd = cmd_m.group('cmd').strip().split(' ') 417 argv = argv + cmd 418 args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv)) 419 return args, argv 420