1from __future__ import print_function 2 3import copy 4import glob 5import os 6import re 7import subprocess 8import sys 9 10if sys.version_info[0] > 2: 11 class string: 12 expandtabs = str.expandtabs 13else: 14 import string 15 16##### Common utilities for update_*test_checks.py 17 18 19_verbose = False 20_prefix_filecheck_ir_name = '' 21 22def parse_commandline_args(parser): 23 parser.add_argument('--include-generated-funcs', action='store_true', 24 help='Output checks for functions not in source') 25 parser.add_argument('-v', '--verbose', action='store_true', 26 help='Show verbose output') 27 parser.add_argument('-u', '--update-only', action='store_true', 28 help='Only update test if it was already autogened') 29 parser.add_argument('--force-update', action='store_true', 30 help='Update test even if it was autogened by a different script') 31 parser.add_argument('--enable', action='store_true', dest='enabled', default=True, 32 help='Activate CHECK line generation from this point forward') 33 parser.add_argument('--disable', action='store_false', dest='enabled', 34 help='Deactivate CHECK line generation from this point forward') 35 parser.add_argument('--replace-function-regex', nargs='+', default=[], 36 help='List of regular expressions to replace matching function names') 37 parser.add_argument('--prefix-filecheck-ir-name', default='', 38 help='Add a prefix to FileCheck IR value names to avoid conflicts with scripted names') 39 args = parser.parse_args() 40 global _verbose 41 _verbose = args.verbose 42 return args 43 44 45class InputLineInfo(object): 46 def __init__(self, line, line_number, args, argv): 47 self.line = line 48 self.line_number = line_number 49 self.args = args 50 self.argv = argv 51 52 53class TestInfo(object): 54 def __init__(self, test, parser, script_name, input_lines, args, argv, 55 comment_prefix, argparse_callback): 56 self.parser = parser 57 self.argparse_callback = argparse_callback 58 self.path = test 59 self.args = args 60 if args.prefix_filecheck_ir_name: 61 global _prefix_filecheck_ir_name 62 _prefix_filecheck_ir_name = args.prefix_filecheck_ir_name 63 self.argv = argv 64 self.input_lines = input_lines 65 self.run_lines = find_run_lines(test, self.input_lines) 66 self.comment_prefix = comment_prefix 67 if self.comment_prefix is None: 68 if self.path.endswith('.mir'): 69 self.comment_prefix = '#' 70 else: 71 self.comment_prefix = ';' 72 self.autogenerated_note_prefix = self.comment_prefix + ' ' + UTC_ADVERT 73 self.test_autogenerated_note = self.autogenerated_note_prefix + script_name 74 self.test_autogenerated_note += get_autogennote_suffix(parser, self.args) 75 76 def ro_iterlines(self): 77 for line_num, input_line in enumerate(self.input_lines): 78 args, argv = check_for_command(input_line, self.parser, 79 self.args, self.argv, self.argparse_callback) 80 yield InputLineInfo(input_line, line_num, args, argv) 81 82 def iterlines(self, output_lines): 83 output_lines.append(self.test_autogenerated_note) 84 for line_info in self.ro_iterlines(): 85 input_line = line_info.line 86 # Discard any previous script advertising. 87 if input_line.startswith(self.autogenerated_note_prefix): 88 continue 89 self.args = line_info.args 90 self.argv = line_info.argv 91 if not self.args.enabled: 92 output_lines.append(input_line) 93 continue 94 yield line_info 95 96def itertests(test_patterns, parser, script_name, comment_prefix=None, argparse_callback=None): 97 for pattern in test_patterns: 98 # On Windows we must expand the patterns ourselves. 99 tests_list = glob.glob(pattern) 100 if not tests_list: 101 warn("Test file pattern '%s' was not found. Ignoring it." % (pattern,)) 102 continue 103 for test in tests_list: 104 with open(test) as f: 105 input_lines = [l.rstrip() for l in f] 106 args = parser.parse_args() 107 if argparse_callback is not None: 108 argparse_callback(args) 109 argv = sys.argv[:] 110 first_line = input_lines[0] if input_lines else "" 111 if UTC_ADVERT in first_line: 112 if script_name not in first_line and not args.force_update: 113 warn("Skipping test which wasn't autogenerated by " + script_name, test) 114 continue 115 args, argv = check_for_command(first_line, parser, args, argv, argparse_callback) 116 elif args.update_only: 117 assert UTC_ADVERT not in first_line 118 warn("Skipping test which isn't autogenerated: " + test) 119 continue 120 yield TestInfo(test, parser, script_name, input_lines, args, argv, 121 comment_prefix, argparse_callback) 122 123 124def should_add_line_to_output(input_line, prefix_set, skip_global_checks = False): 125 # Skip any blank comment lines in the IR. 126 if not skip_global_checks and input_line.strip() == ';': 127 return False 128 # Skip a special double comment line we use as a separator. 129 if input_line.strip() == SEPARATOR: 130 return False 131 # Skip any blank lines in the IR. 132 #if input_line.strip() == '': 133 # return False 134 # And skip any CHECK lines. We're building our own. 135 m = CHECK_RE.match(input_line) 136 if m and m.group(1) in prefix_set: 137 if skip_global_checks: 138 global_ir_value_re = re.compile('\[\[', flags=(re.M)) 139 return not global_ir_value_re.search(input_line) 140 return False 141 142 return True 143 144# Invoke the tool that is being tested. 145def invoke_tool(exe, cmd_args, ir, preprocess_cmd=None, verbose=False): 146 with open(ir) as ir_file: 147 # TODO Remove the str form which is used by update_test_checks.py and 148 # update_llc_test_checks.py 149 # The safer list form is used by update_cc_test_checks.py 150 if preprocess_cmd: 151 # Allow pre-processing the IR file (e.g. using sed): 152 assert isinstance(preprocess_cmd, str) # TODO: use a list instead of using shell 153 preprocess_cmd = preprocess_cmd.replace('%s', ir).strip() 154 if verbose: 155 print('Pre-processing input file: ', ir, " with command '", 156 preprocess_cmd, "'", sep="", file=sys.stderr) 157 # Python 2.7 doesn't have subprocess.DEVNULL: 158 with open(os.devnull, 'w') as devnull: 159 pp = subprocess.Popen(preprocess_cmd, shell=True, stdin=devnull, 160 stdout=subprocess.PIPE) 161 ir_file = pp.stdout 162 if isinstance(cmd_args, list): 163 stdout = subprocess.check_output([exe] + cmd_args, stdin=ir_file) 164 else: 165 stdout = subprocess.check_output(exe + ' ' + cmd_args, 166 shell=True, stdin=ir_file) 167 if sys.version_info[0] > 2: 168 stdout = stdout.decode() 169 # Fix line endings to unix CR style. 170 return stdout.replace('\r\n', '\n') 171 172##### LLVM IR parser 173RUN_LINE_RE = re.compile(r'^\s*(?://|[;#])\s*RUN:\s*(.*)$') 174CHECK_PREFIX_RE = re.compile(r'--?check-prefix(?:es)?[= ](\S+)') 175PREFIX_RE = re.compile('^[a-zA-Z0-9_-]+$') 176CHECK_RE = re.compile(r'^\s*(?://|[;#])\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL|-SAME|-EMPTY)?:') 177 178UTC_ARGS_KEY = 'UTC_ARGS:' 179UTC_ARGS_CMD = re.compile(r'.*' + UTC_ARGS_KEY + '\s*(?P<cmd>.*)\s*$') 180UTC_ADVERT = 'NOTE: Assertions have been autogenerated by ' 181 182OPT_FUNCTION_RE = re.compile( 183 r'^(\s*;\s*Function\sAttrs:\s(?P<attrs>[\w\s]+?))?\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w.$-]+?)\s*' 184 r'(?P<args_and_sig>\((\)|(.*?[\w.-]+?)\))[^{]*\{)\n(?P<body>.*?)^\}$', 185 flags=(re.M | re.S)) 186 187ANALYZE_FUNCTION_RE = re.compile( 188 r'^\s*\'(?P<analysis>[\w\s-]+?)\'\s+for\s+function\s+\'(?P<func>[\w.$-]+?)\':' 189 r'\s*\n(?P<body>.*)$', 190 flags=(re.X | re.S)) 191 192IR_FUNCTION_RE = re.compile(r'^\s*define\s+(?:internal\s+)?[^@]*@"?([\w.$-]+)"?\s*\(') 193TRIPLE_IR_RE = re.compile(r'^\s*target\s+triple\s*=\s*"([^"]+)"$') 194TRIPLE_ARG_RE = re.compile(r'-mtriple[= ]([^ ]+)') 195MARCH_ARG_RE = re.compile(r'-march[= ]([^ ]+)') 196 197SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)') 198SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M) 199SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M) 200SCRUB_TRAILING_WHITESPACE_TEST_RE = SCRUB_TRAILING_WHITESPACE_RE 201SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE = re.compile(r'([ \t]|(#[0-9]+))+$', flags=re.M) 202SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n') 203SCRUB_LOOP_COMMENT_RE = re.compile( 204 r'# =>This Inner Loop Header:.*|# in Loop:.*', flags=re.M) 205SCRUB_TAILING_COMMENT_TOKEN_RE = re.compile(r'(?<=\S)+[ \t]*#$', flags=re.M) 206 207SEPARATOR = ';.' 208 209def error(msg, test_file=None): 210 if test_file: 211 msg = '{}: {}'.format(msg, test_file) 212 print('ERROR: {}'.format(msg), file=sys.stderr) 213 214def warn(msg, test_file=None): 215 if test_file: 216 msg = '{}: {}'.format(msg, test_file) 217 print('WARNING: {}'.format(msg), file=sys.stderr) 218 219def debug(*args, **kwargs): 220 # Python2 does not allow def debug(*args, file=sys.stderr, **kwargs): 221 if 'file' not in kwargs: 222 kwargs['file'] = sys.stderr 223 if _verbose: 224 print(*args, **kwargs) 225 226def find_run_lines(test, lines): 227 debug('Scanning for RUN lines in test file:', test) 228 raw_lines = [m.group(1) 229 for m in [RUN_LINE_RE.match(l) for l in lines] if m] 230 run_lines = [raw_lines[0]] if len(raw_lines) > 0 else [] 231 for l in raw_lines[1:]: 232 if run_lines[-1].endswith('\\'): 233 run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l 234 else: 235 run_lines.append(l) 236 debug('Found {} RUN lines in {}:'.format(len(run_lines), test)) 237 for l in run_lines: 238 debug(' RUN: {}'.format(l)) 239 return run_lines 240 241def scrub_body(body): 242 # Scrub runs of whitespace out of the assembly, but leave the leading 243 # whitespace in place. 244 body = SCRUB_WHITESPACE_RE.sub(r' ', body) 245 # Expand the tabs used for indentation. 246 body = string.expandtabs(body, 2) 247 # Strip trailing whitespace. 248 body = SCRUB_TRAILING_WHITESPACE_TEST_RE.sub(r'', body) 249 return body 250 251def do_scrub(body, scrubber, scrubber_args, extra): 252 if scrubber_args: 253 local_args = copy.deepcopy(scrubber_args) 254 local_args[0].extra_scrub = extra 255 return scrubber(body, *local_args) 256 return scrubber(body, *scrubber_args) 257 258# Build up a dictionary of all the function bodies. 259class function_body(object): 260 def __init__(self, string, extra, args_and_sig, attrs): 261 self.scrub = string 262 self.extrascrub = extra 263 self.args_and_sig = args_and_sig 264 self.attrs = attrs 265 def is_same_except_arg_names(self, extrascrub, args_and_sig, attrs): 266 arg_names = set() 267 def drop_arg_names(match): 268 arg_names.add(match.group(variable_group_in_ir_value_match)) 269 if match.group(attribute_group_in_ir_value_match): 270 attr = match.group(attribute_group_in_ir_value_match) 271 else: 272 attr = '' 273 return match.group(1) + attr + match.group(match.lastindex) 274 def repl_arg_names(match): 275 if match.group(variable_group_in_ir_value_match) is not None and match.group(variable_group_in_ir_value_match) in arg_names: 276 return match.group(1) + match.group(match.lastindex) 277 return match.group(1) + match.group(2) + match.group(match.lastindex) 278 if self.attrs != attrs: 279 return False 280 ans0 = IR_VALUE_RE.sub(drop_arg_names, self.args_and_sig) 281 ans1 = IR_VALUE_RE.sub(drop_arg_names, args_and_sig) 282 if ans0 != ans1: 283 return False 284 es0 = IR_VALUE_RE.sub(repl_arg_names, self.extrascrub) 285 es1 = IR_VALUE_RE.sub(repl_arg_names, extrascrub) 286 es0 = SCRUB_IR_COMMENT_RE.sub(r'', es0) 287 es1 = SCRUB_IR_COMMENT_RE.sub(r'', es1) 288 return es0 == es1 289 290 def __str__(self): 291 return self.scrub 292 293class FunctionTestBuilder: 294 def __init__(self, run_list, flags, scrubber_args): 295 self._verbose = flags.verbose 296 self._record_args = flags.function_signature 297 self._check_attributes = flags.check_attributes 298 self._scrubber_args = scrubber_args 299 # Strip double-quotes if input was read by UTC_ARGS 300 self._replace_function_regex = list(map(lambda x: x.strip('"'), flags.replace_function_regex)) 301 self._func_dict = {} 302 self._func_order = {} 303 self._global_var_dict = {} 304 for tuple in run_list: 305 for prefix in tuple[0]: 306 self._func_dict.update({prefix:dict()}) 307 self._func_order.update({prefix: []}) 308 self._global_var_dict.update({prefix:dict()}) 309 310 def finish_and_get_func_dict(self): 311 for prefix in self._get_failed_prefixes(): 312 warn('Prefix %s had conflicting output from different RUN lines for all functions' % (prefix,)) 313 return self._func_dict 314 315 def func_order(self): 316 return self._func_order 317 318 def global_var_dict(self): 319 return self._global_var_dict 320 321 def process_run_line(self, function_re, scrubber, raw_tool_output, prefixes): 322 build_global_values_dictionary(self._global_var_dict, raw_tool_output, prefixes) 323 for m in function_re.finditer(raw_tool_output): 324 if not m: 325 continue 326 func = m.group('func') 327 body = m.group('body') 328 attrs = m.group('attrs') if self._check_attributes else '' 329 # Determine if we print arguments, the opening brace, or nothing after the 330 # function name 331 if self._record_args and 'args_and_sig' in m.groupdict(): 332 args_and_sig = scrub_body(m.group('args_and_sig').strip()) 333 elif 'args_and_sig' in m.groupdict(): 334 args_and_sig = '(' 335 else: 336 args_and_sig = '' 337 scrubbed_body = do_scrub(body, scrubber, self._scrubber_args, 338 extra=False) 339 scrubbed_extra = do_scrub(body, scrubber, self._scrubber_args, 340 extra=True) 341 if 'analysis' in m.groupdict(): 342 analysis = m.group('analysis') 343 if analysis.lower() != 'cost model analysis': 344 warn('Unsupported analysis mode: %r!' % (analysis,)) 345 if func.startswith('stress'): 346 # We only use the last line of the function body for stress tests. 347 scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:]) 348 if self._verbose: 349 print('Processing function: ' + func, file=sys.stderr) 350 for l in scrubbed_body.splitlines(): 351 print(' ' + l, file=sys.stderr) 352 for prefix in prefixes: 353 if func in self._func_dict[prefix]: 354 if (self._func_dict[prefix][func] is None or 355 str(self._func_dict[prefix][func]) != scrubbed_body or 356 self._func_dict[prefix][func].args_and_sig != args_and_sig or 357 self._func_dict[prefix][func].attrs != attrs): 358 if (self._func_dict[prefix][func] is not None and 359 self._func_dict[prefix][func].is_same_except_arg_names( 360 scrubbed_extra, 361 args_and_sig, 362 attrs)): 363 self._func_dict[prefix][func].scrub = scrubbed_extra 364 self._func_dict[prefix][func].args_and_sig = args_and_sig 365 continue 366 else: 367 # This means a previous RUN line produced a body for this function 368 # that is different from the one produced by this current RUN line, 369 # so the body can't be common accross RUN lines. We use None to 370 # indicate that. 371 self._func_dict[prefix][func] = None 372 continue 373 374 # Replace function names matching the regex. 375 for regex in self._replace_function_regex: 376 # Pattern that matches capture groups in the regex in leftmost order. 377 group_regex = re.compile('\(.*?\)') 378 # Replace function name with regex. 379 match = re.match(regex, func) 380 if match: 381 func_repl = regex 382 # Replace any capture groups with their matched strings. 383 for g in match.groups(): 384 func_repl = group_regex.sub(re.escape(g), func_repl, count=1) 385 func = re.sub(func_repl, '{{' + func_repl + '}}', func) 386 387 # Replace all calls to regex matching functions. 388 matches = re.finditer(regex, scrubbed_body) 389 for match in matches: 390 func_repl = regex 391 # Replace any capture groups with their matched strings. 392 for g in match.groups(): 393 func_repl = group_regex.sub(re.escape(g), func_repl, count=1) 394 # Substitute function call names that match the regex with the same 395 # capture groups set. 396 scrubbed_body = re.sub(func_repl, '{{' + func_repl + '}}', scrubbed_body) 397 398 self._func_dict[prefix][func] = function_body( 399 scrubbed_body, scrubbed_extra, args_and_sig, attrs) 400 self._func_order[prefix].append(func) 401 402 def _get_failed_prefixes(self): 403 # This returns the list of those prefixes that failed to match any function, 404 # because there were conflicting bodies produced by different RUN lines, in 405 # all instances of the prefix. Effectively, this prefix is unused and should 406 # be removed. 407 for prefix in self._func_dict: 408 if (self._func_dict[prefix] and 409 (not [fct for fct in self._func_dict[prefix] 410 if self._func_dict[prefix][fct] is not None])): 411 yield prefix 412 413 414##### Generator of LLVM IR CHECK lines 415 416SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*') 417 418# TODO: We should also derive check lines for global, debug, loop declarations, etc.. 419 420class NamelessValue: 421 def __init__(self, check_prefix, check_key, ir_prefix, global_ir_prefix, global_ir_prefix_regexp, 422 ir_regexp, global_ir_rhs_regexp, is_before_functions): 423 self.check_prefix = check_prefix 424 self.check_key = check_key 425 self.ir_prefix = ir_prefix 426 self.global_ir_prefix = global_ir_prefix 427 self.global_ir_prefix_regexp = global_ir_prefix_regexp 428 self.ir_regexp = ir_regexp 429 self.global_ir_rhs_regexp = global_ir_rhs_regexp 430 self.is_before_functions = is_before_functions 431 432# Description of the different "unnamed" values we match in the IR, e.g., 433# (local) ssa values, (debug) metadata, etc. 434nameless_values = [ 435 NamelessValue(r'TMP' , '%' , r'%' , None , None , r'[\w$.-]+?' , None , False) , 436 NamelessValue(r'ATTR' , '#' , r'#' , None , None , r'[0-9]+' , None , False) , 437 NamelessValue(r'ATTR' , '#' , None , r'attributes #' , r'[0-9]+' , None , r'{[^}]*}' , False) , 438 NamelessValue(r'GLOB' , '@' , r'@' , None , None , r'[0-9]+' , None , False) , 439 NamelessValue(r'GLOB' , '@' , None , r'@' , r'[a-zA-Z0-9_$"\\.-]+' , None , r'.+' , True) , 440 NamelessValue(r'DBG' , '!' , r'!dbg ' , None , None , r'![0-9]+' , None , False) , 441 NamelessValue(r'TBAA' , '!' , r'!tbaa ' , None , None , r'![0-9]+' , None , False) , 442 NamelessValue(r'RNG' , '!' , r'!range ' , None , None , r'![0-9]+' , None , False) , 443 NamelessValue(r'LOOP' , '!' , r'!llvm.loop ' , None , None , r'![0-9]+' , None , False) , 444 NamelessValue(r'META' , '!' , r'metadata ' , None , None , r'![0-9]+' , None , False) , 445 NamelessValue(r'META' , '!' , None , r'' , r'![0-9]+' , None , r'(?:distinct |)!.*' , False) , 446] 447 448def createOrRegexp(old, new): 449 if not old: 450 return new 451 if not new: 452 return old 453 return old + '|' + new 454 455def createPrefixMatch(prefix_str, prefix_re): 456 if prefix_str is None or prefix_re is None: 457 return '' 458 return '(?:' + prefix_str + '(' + prefix_re + '))' 459 460# Build the regexp that matches an "IR value". This can be a local variable, 461# argument, global, or metadata, anything that is "named". It is important that 462# the PREFIX and SUFFIX below only contain a single group, if that changes 463# other locations will need adjustment as well. 464IR_VALUE_REGEXP_PREFIX = r'(\s*)' 465IR_VALUE_REGEXP_STRING = r'' 466for nameless_value in nameless_values: 467 lcl_match = createPrefixMatch(nameless_value.ir_prefix, nameless_value.ir_regexp) 468 glb_match = createPrefixMatch(nameless_value.global_ir_prefix, nameless_value.global_ir_prefix_regexp) 469 assert((lcl_match or glb_match) and not (lcl_match and glb_match)) 470 if lcl_match: 471 IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, lcl_match) 472 elif glb_match: 473 IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, '^' + glb_match) 474IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)' 475IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX) 476 477# The entire match is group 0, the prefix has one group (=1), the entire 478# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start. 479first_nameless_group_in_ir_value_match = 3 480 481# constants for the group id of special matches 482variable_group_in_ir_value_match = 3 483attribute_group_in_ir_value_match = 4 484 485# Check a match for IR_VALUE_RE and inspect it to determine if it was a local 486# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above. 487def get_idx_from_ir_value_match(match): 488 for i in range(first_nameless_group_in_ir_value_match, match.lastindex): 489 if match.group(i) is not None: 490 return i - first_nameless_group_in_ir_value_match 491 error("Unable to identify the kind of IR value from the match!") 492 return 0 493 494# See get_idx_from_ir_value_match 495def get_name_from_ir_value_match(match): 496 return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match) 497 498# Return the nameless prefix we use for this kind or IR value, see also 499# get_idx_from_ir_value_match 500def get_nameless_check_prefix_from_ir_value_match(match): 501 return nameless_values[get_idx_from_ir_value_match(match)].check_prefix 502 503# Return the IR prefix and check prefix we use for this kind or IR value, e.g., (%, TMP) for locals, 504# see also get_idx_from_ir_value_match 505def get_ir_prefix_from_ir_value_match(match): 506 idx = get_idx_from_ir_value_match(match) 507 if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix): 508 return nameless_values[idx].ir_prefix, nameless_values[idx].check_prefix 509 return nameless_values[idx].global_ir_prefix, nameless_values[idx].check_prefix 510 511def get_check_key_from_ir_value_match(match): 512 idx = get_idx_from_ir_value_match(match) 513 return nameless_values[idx].check_key 514 515# Return the IR regexp we use for this kind or IR value, e.g., [\w.-]+? for locals, 516# see also get_idx_from_ir_value_match 517def get_ir_prefix_from_ir_value_re_match(match): 518 # for backwards compatibility we check locals with '.*' 519 if is_local_def_ir_value_match(match): 520 return '.*' 521 idx = get_idx_from_ir_value_match(match) 522 if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix): 523 return nameless_values[idx].ir_regexp 524 return nameless_values[idx].global_ir_prefix_regexp 525 526# Return true if this kind of IR value is "local", basically if it matches '%{{.*}}'. 527def is_local_def_ir_value_match(match): 528 return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%' 529 530# Return true if this kind of IR value is "global", basically if it matches '#{{.*}}'. 531def is_global_scope_ir_value_match(match): 532 return nameless_values[get_idx_from_ir_value_match(match)].global_ir_prefix is not None 533 534# Return true if var clashes with the scripted FileCheck check_prefix. 535def may_clash_with_default_check_prefix_name(check_prefix, var): 536 return check_prefix and re.match(r'^' + check_prefix + r'[0-9]+?$', var, re.IGNORECASE) 537 538# Create a FileCheck variable name based on an IR name. 539def get_value_name(var, check_prefix): 540 var = var.replace('!', '') 541 # This is a nameless value, prepend check_prefix. 542 if var.isdigit(): 543 var = check_prefix + var 544 else: 545 # This is a named value that clashes with the check_prefix, prepend with _prefix_filecheck_ir_name, 546 # if it has been defined. 547 if may_clash_with_default_check_prefix_name(check_prefix, var) and _prefix_filecheck_ir_name: 548 var = _prefix_filecheck_ir_name + var 549 var = var.replace('.', '_') 550 var = var.replace('-', '_') 551 return var.upper() 552 553# Create a FileCheck variable from regex. 554def get_value_definition(var, match): 555 # for backwards compatibility we check locals with '.*' 556 if is_local_def_ir_value_match(match): 557 return '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + \ 558 get_ir_prefix_from_ir_value_match(match)[0] + get_ir_prefix_from_ir_value_re_match(match) + ']]' 559 prefix = get_ir_prefix_from_ir_value_match(match)[0] 560 return prefix + '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + get_ir_prefix_from_ir_value_re_match(match) + ']]' 561 562# Use a FileCheck variable. 563def get_value_use(var, match, check_prefix): 564 if is_local_def_ir_value_match(match): 565 return '[[' + get_value_name(var, check_prefix) + ']]' 566 prefix = get_ir_prefix_from_ir_value_match(match)[0] 567 return prefix + '[[' + get_value_name(var, check_prefix) + ']]' 568 569# Replace IR value defs and uses with FileCheck variables. 570def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen): 571 # This gets called for each match that occurs in 572 # a line. We transform variables we haven't seen 573 # into defs, and variables we have seen into uses. 574 def transform_line_vars(match): 575 pre, check = get_ir_prefix_from_ir_value_match(match) 576 var = get_name_from_ir_value_match(match) 577 for nameless_value in nameless_values: 578 if may_clash_with_default_check_prefix_name(nameless_value.check_prefix, var): 579 warn("Change IR value name '%s' or use -prefix-ir-filecheck-name to prevent possible conflict" 580 " with scripted FileCheck name." % (var,)) 581 key = (var, get_check_key_from_ir_value_match(match)) 582 is_local_def = is_local_def_ir_value_match(match) 583 if is_local_def and key in vars_seen: 584 rv = get_value_use(var, match, get_nameless_check_prefix_from_ir_value_match(match)) 585 elif not is_local_def and key in global_vars_seen: 586 rv = get_value_use(var, match, global_vars_seen[key]) 587 else: 588 if is_local_def: 589 vars_seen.add(key) 590 else: 591 global_vars_seen[key] = get_nameless_check_prefix_from_ir_value_match(match) 592 rv = get_value_definition(var, match) 593 # re.sub replaces the entire regex match 594 # with whatever you return, so we have 595 # to make sure to hand it back everything 596 # including the commas and spaces. 597 return match.group(1) + rv + match.group(match.lastindex) 598 599 lines_with_def = [] 600 601 for i, line in enumerate(lines): 602 # An IR variable named '%.' matches the FileCheck regex string. 603 line = line.replace('%.', '%dot') 604 # Ignore any comments, since the check lines will too. 605 scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line) 606 lines[i] = scrubbed_line 607 if not is_analyze: 608 # It can happen that two matches are back-to-back and for some reason sub 609 # will not replace both of them. For now we work around this by 610 # substituting until there is no more match. 611 changed = True 612 while changed: 613 (lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1) 614 return lines 615 616 617def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze, global_vars_seen_dict): 618 # prefix_exclusions are prefixes we cannot use to print the function because it doesn't exist in run lines that use these prefixes as well. 619 prefix_exclusions = set() 620 printed_prefixes = [] 621 for p in prefix_list: 622 checkprefixes = p[0] 623 # If not all checkprefixes of this run line produced the function we cannot check for it as it does not 624 # exist for this run line. A subset of the check prefixes might know about the function but only because 625 # other run lines created it. 626 if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)): 627 prefix_exclusions |= set(checkprefixes) 628 continue 629 630 # prefix_exclusions is constructed, we can now emit the output 631 for p in prefix_list: 632 global_vars_seen = {} 633 checkprefixes = p[0] 634 for checkprefix in checkprefixes: 635 if checkprefix in global_vars_seen_dict: 636 global_vars_seen.update(global_vars_seen_dict[checkprefix]) 637 else: 638 global_vars_seen_dict[checkprefix] = {} 639 if checkprefix in printed_prefixes: 640 break 641 642 # Check if the prefix is excluded. 643 if checkprefix in prefix_exclusions: 644 continue 645 646 # If we do not have output for this prefix we skip it. 647 if not func_dict[checkprefix][func_name]: 648 continue 649 650 # Add some space between different check prefixes, but not after the last 651 # check line (before the test code). 652 if is_asm: 653 if len(printed_prefixes) != 0: 654 output_lines.append(comment_marker) 655 656 if checkprefix not in global_vars_seen_dict: 657 global_vars_seen_dict[checkprefix] = {} 658 659 global_vars_seen_before = [key for key in global_vars_seen.keys()] 660 661 vars_seen = set() 662 printed_prefixes.append(checkprefix) 663 attrs = str(func_dict[checkprefix][func_name].attrs) 664 attrs = '' if attrs == 'None' else attrs 665 if attrs: 666 output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs)) 667 args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig) 668 args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0] 669 if '[[' in args_and_sig: 670 output_lines.append(check_label_format % (checkprefix, func_name, '')) 671 output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig)) 672 else: 673 output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig)) 674 func_body = str(func_dict[checkprefix][func_name]).splitlines() 675 676 # For ASM output, just emit the check lines. 677 if is_asm: 678 output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 679 for func_line in func_body[1:]: 680 if func_line.strip() == '': 681 output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix)) 682 else: 683 output_lines.append('%s %s-NEXT: %s' % (comment_marker, checkprefix, func_line)) 684 break 685 686 # For IR output, change all defs to FileCheck variables, so we're immune 687 # to variable naming fashions. 688 func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen) 689 690 # This could be selectively enabled with an optional invocation argument. 691 # Disabled for now: better to check everything. Be safe rather than sorry. 692 693 # Handle the first line of the function body as a special case because 694 # it's often just noise (a useless asm comment or entry label). 695 #if func_body[0].startswith("#") or func_body[0].startswith("entry:"): 696 # is_blank_line = True 697 #else: 698 # output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 699 # is_blank_line = False 700 701 is_blank_line = False 702 703 for func_line in func_body: 704 if func_line.strip() == '': 705 is_blank_line = True 706 continue 707 # Do not waste time checking IR comments. 708 func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line) 709 710 # Skip blank lines instead of checking them. 711 if is_blank_line: 712 output_lines.append('{} {}: {}'.format( 713 comment_marker, checkprefix, func_line)) 714 else: 715 output_lines.append('{} {}-NEXT: {}'.format( 716 comment_marker, checkprefix, func_line)) 717 is_blank_line = False 718 719 # Add space between different check prefixes and also before the first 720 # line of code in the test function. 721 output_lines.append(comment_marker) 722 723 # Remembe new global variables we have not seen before 724 for key in global_vars_seen: 725 if key not in global_vars_seen_before: 726 global_vars_seen_dict[checkprefix][key] = global_vars_seen[key] 727 break 728 729def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict, 730 func_name, preserve_names, function_sig, global_vars_seen_dict): 731 # Label format is based on IR string. 732 function_def_regex = 'define {{[^@]+}}' if function_sig else '' 733 check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex) 734 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, 735 check_label_format, False, preserve_names, global_vars_seen_dict) 736 737def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name): 738 check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker) 739 global_vars_seen_dict = {} 740 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, 741 check_label_format, False, True, global_vars_seen_dict) 742 743def build_global_values_dictionary(glob_val_dict, raw_tool_output, prefixes): 744 for nameless_value in nameless_values: 745 if nameless_value.global_ir_prefix is None: 746 continue 747 748 lhs_re_str = nameless_value.global_ir_prefix + nameless_value.global_ir_prefix_regexp 749 rhs_re_str = nameless_value.global_ir_rhs_regexp 750 751 global_ir_value_re_str = r'^' + lhs_re_str + r'\s=\s' + rhs_re_str + r'$' 752 global_ir_value_re = re.compile(global_ir_value_re_str, flags=(re.M)) 753 lines = [] 754 for m in global_ir_value_re.finditer(raw_tool_output): 755 lines.append(m.group(0)) 756 757 for prefix in prefixes: 758 if glob_val_dict[prefix] is None: 759 continue 760 if nameless_value.check_prefix in glob_val_dict[prefix]: 761 if lines == glob_val_dict[prefix][nameless_value.check_prefix]: 762 continue 763 if prefix == prefixes[-1]: 764 warn('Found conflicting asm under the same prefix: %r!' % (prefix,)) 765 else: 766 glob_val_dict[prefix][nameless_value.check_prefix] = None 767 continue 768 glob_val_dict[prefix][nameless_value.check_prefix] = lines 769 770def add_global_checks(glob_val_dict, comment_marker, prefix_list, output_lines, global_vars_seen_dict, is_analyze, is_before_functions): 771 printed_prefixes = set() 772 for nameless_value in nameless_values: 773 if nameless_value.global_ir_prefix is None: 774 continue 775 if nameless_value.is_before_functions != is_before_functions: 776 continue 777 for p in prefix_list: 778 global_vars_seen = {} 779 checkprefixes = p[0] 780 for checkprefix in checkprefixes: 781 if checkprefix in global_vars_seen_dict: 782 global_vars_seen.update(global_vars_seen_dict[checkprefix]) 783 else: 784 global_vars_seen_dict[checkprefix] = {} 785 if (checkprefix, nameless_value.check_prefix) in printed_prefixes: 786 break 787 if not glob_val_dict[checkprefix]: 788 continue 789 if nameless_value.check_prefix not in glob_val_dict[checkprefix]: 790 continue 791 if not glob_val_dict[checkprefix][nameless_value.check_prefix]: 792 continue 793 794 output_lines.append(SEPARATOR) 795 796 global_vars_seen_before = [key for key in global_vars_seen.keys()] 797 for line in glob_val_dict[checkprefix][nameless_value.check_prefix]: 798 tmp = generalize_check_lines([line], is_analyze, set(), global_vars_seen) 799 check_line = '%s %s: %s' % (comment_marker, checkprefix, tmp[0]) 800 output_lines.append(check_line) 801 printed_prefixes.add((checkprefix, nameless_value.check_prefix)) 802 803 # Remembe new global variables we have not seen before 804 for key in global_vars_seen: 805 if key not in global_vars_seen_before: 806 global_vars_seen_dict[checkprefix][key] = global_vars_seen[key] 807 break 808 809 if printed_prefixes: 810 output_lines.append(SEPARATOR) 811 812 813def check_prefix(prefix): 814 if not PREFIX_RE.match(prefix): 815 hint = "" 816 if ',' in prefix: 817 hint = " Did you mean '--check-prefixes=" + prefix + "'?" 818 warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) % 819 (prefix)) 820 821 822def verify_filecheck_prefixes(fc_cmd): 823 fc_cmd_parts = fc_cmd.split() 824 for part in fc_cmd_parts: 825 if "check-prefix=" in part: 826 prefix = part.split('=', 1)[1] 827 check_prefix(prefix) 828 elif "check-prefixes=" in part: 829 prefixes = part.split('=', 1)[1].split(',') 830 for prefix in prefixes: 831 check_prefix(prefix) 832 if prefixes.count(prefix) > 1: 833 warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,)) 834 835 836def get_autogennote_suffix(parser, args): 837 autogenerated_note_args = '' 838 for action in parser._actions: 839 if not hasattr(args, action.dest): 840 continue # Ignore options such as --help that aren't included in args 841 # Ignore parameters such as paths to the binary or the list of tests 842 if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary', 843 'clang', 'opt', 'llvm_bin', 'verbose'): 844 continue 845 value = getattr(args, action.dest) 846 if action.const is not None: # action stores a constant (usually True/False) 847 # Skip actions with different constant values (this happens with boolean 848 # --foo/--no-foo options) 849 if value != action.const: 850 continue 851 if parser.get_default(action.dest) == value: 852 continue # Don't add default values 853 autogenerated_note_args += action.option_strings[0] + ' ' 854 if action.const is None: # action takes a parameter 855 if action.nargs == '+': 856 value = ' '.join(map(lambda v: '"' + v.strip('"') + '"', value)) 857 autogenerated_note_args += '%s ' % value 858 if autogenerated_note_args: 859 autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1]) 860 return autogenerated_note_args 861 862 863def check_for_command(line, parser, args, argv, argparse_callback): 864 cmd_m = UTC_ARGS_CMD.match(line) 865 if cmd_m: 866 for option in cmd_m.group('cmd').strip().split(' '): 867 if option: 868 argv.append(option) 869 args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv)) 870 if argparse_callback is not None: 871 argparse_callback(args) 872 return args, argv 873 874def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global): 875 result = get_arg_to_check(test_info.args) 876 if not result and is_global: 877 # See if this has been specified via UTC_ARGS. This is a "global" option 878 # that affects the entire generation of test checks. If it exists anywhere 879 # in the test, apply it to everything. 880 saw_line = False 881 for line_info in test_info.ro_iterlines(): 882 line = line_info.line 883 if not line.startswith(';') and line.strip() != '': 884 saw_line = True 885 result = get_arg_to_check(line_info.args) 886 if result: 887 if warn and saw_line: 888 # We saw the option after already reading some test input lines. 889 # Warn about it. 890 print('WARNING: Found {} in line following test start: '.format(arg_string) 891 + line, file=sys.stderr) 892 print('WARNING: Consider moving {} to top of file'.format(arg_string), 893 file=sys.stderr) 894 break 895 return result 896 897def dump_input_lines(output_lines, test_info, prefix_set, comment_string): 898 for input_line_info in test_info.iterlines(output_lines): 899 line = input_line_info.line 900 args = input_line_info.args 901 if line.strip() == comment_string: 902 continue 903 if line.strip() == SEPARATOR: 904 continue 905 if line.lstrip().startswith(comment_string): 906 m = CHECK_RE.match(line) 907 if m and m.group(1) in prefix_set: 908 continue 909 output_lines.append(line.rstrip('\n')) 910 911def add_checks_at_end(output_lines, prefix_list, func_order, 912 comment_string, check_generator): 913 added = set() 914 for prefix in prefix_list: 915 prefixes = prefix[0] 916 tool_args = prefix[1] 917 for prefix in prefixes: 918 for func in func_order[prefix]: 919 if added: 920 output_lines.append(comment_string) 921 added.add(func) 922 923 # The add_*_checks routines expect a run list whose items are 924 # tuples that have a list of prefixes as their first element and 925 # tool command args string as their second element. They output 926 # checks for each prefix in the list of prefixes. By doing so, it 927 # implicitly assumes that for each function every run line will 928 # generate something for that function. That is not the case for 929 # generated functions as some run lines might not generate them 930 # (e.g. -fopenmp vs. no -fopenmp). 931 # 932 # Therefore, pass just the prefix we're interested in. This has 933 # the effect of generating all of the checks for functions of a 934 # single prefix before moving on to the next prefix. So checks 935 # are ordered by prefix instead of by function as in "normal" 936 # mode. 937 check_generator(output_lines, 938 [([prefix], tool_args)], 939 func) 940