xref: /llvm-project/llvm/utils/UpdateTestChecks/common.py (revision 38b7b1d4a2930cc82e69a8069fad4b363f73a212)
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-value-regex', nargs='+', default=[],
36                      help='List of regular expressions to replace matching value 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, comment_marker = ';'):
125  # Skip any blank comment lines in the IR.
126  if not skip_global_checks and input_line.strip() == comment_marker:
127    return False
128  # Skip a special double comment line we use as a separator.
129  if input_line.strip() == comment_marker + 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, path):
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    self._path = path
300    # Strip double-quotes if input was read by UTC_ARGS
301    self._replace_value_regex = list(map(lambda x: x.strip('"'), flags.replace_value_regex))
302    self._func_dict = {}
303    self._func_order = {}
304    self._global_var_dict = {}
305    for tuple in run_list:
306      for prefix in tuple[0]:
307        self._func_dict.update({prefix:dict()})
308        self._func_order.update({prefix: []})
309        self._global_var_dict.update({prefix:dict()})
310
311  def finish_and_get_func_dict(self):
312    for prefix in self._get_failed_prefixes():
313      warn('Prefix %s had conflicting output from different RUN lines for all functions in test %s' % (prefix,self._path,))
314    return self._func_dict
315
316  def func_order(self):
317    return self._func_order
318
319  def global_var_dict(self):
320    return self._global_var_dict
321
322  def process_run_line(self, function_re, scrubber, raw_tool_output, prefixes):
323    build_global_values_dictionary(self._global_var_dict, raw_tool_output, prefixes)
324    for m in function_re.finditer(raw_tool_output):
325      if not m:
326        continue
327      func = m.group('func')
328      body = m.group('body')
329      attrs = m.group('attrs') if self._check_attributes else ''
330      # Determine if we print arguments, the opening brace, or nothing after the
331      # function name
332      if self._record_args and 'args_and_sig' in m.groupdict():
333          args_and_sig = scrub_body(m.group('args_and_sig').strip())
334      elif 'args_and_sig' in m.groupdict():
335          args_and_sig = '('
336      else:
337          args_and_sig = ''
338      scrubbed_body = do_scrub(body, scrubber, self._scrubber_args,
339                               extra=False)
340      scrubbed_extra = do_scrub(body, scrubber, self._scrubber_args,
341                                extra=True)
342      if 'analysis' in m.groupdict():
343        analysis = m.group('analysis')
344        if analysis.lower() != 'cost model analysis':
345          warn('Unsupported analysis mode: %r!' % (analysis,))
346      if func.startswith('stress'):
347        # We only use the last line of the function body for stress tests.
348        scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
349      if self._verbose:
350        print('Processing function: ' + func, file=sys.stderr)
351        for l in scrubbed_body.splitlines():
352          print('  ' + l, file=sys.stderr)
353      for prefix in prefixes:
354        # Replace function names matching the regex.
355        for regex in self._replace_value_regex:
356          # Pattern that matches capture groups in the regex in leftmost order.
357          group_regex = re.compile('\(.*?\)')
358          # Replace function name with regex.
359          match = re.match(regex, func)
360          if match:
361            func_repl = regex
362            # Replace any capture groups with their matched strings.
363            for g in match.groups():
364              func_repl = group_regex.sub(re.escape(g), func_repl, count=1)
365            func = re.sub(func_repl, '{{' + func_repl + '}}', func)
366
367          # Replace all calls to regex matching functions.
368          matches = re.finditer(regex, scrubbed_body)
369          for match in matches:
370            func_repl = regex
371            # Replace any capture groups with their matched strings.
372            for g in match.groups():
373                func_repl = group_regex.sub(re.escape(g), func_repl, count=1)
374            # Substitute function call names that match the regex with the same
375            # capture groups set.
376            scrubbed_body = re.sub(func_repl, '{{' + func_repl + '}}',
377                                   scrubbed_body)
378
379        if func in self._func_dict[prefix]:
380          if (self._func_dict[prefix][func] is None or
381              str(self._func_dict[prefix][func]) != scrubbed_body or
382              self._func_dict[prefix][func].args_and_sig != args_and_sig or
383                  self._func_dict[prefix][func].attrs != attrs):
384            if (self._func_dict[prefix][func] is not None and
385                self._func_dict[prefix][func].is_same_except_arg_names(
386                scrubbed_extra,
387                args_and_sig,
388                attrs)):
389              self._func_dict[prefix][func].scrub = scrubbed_extra
390              self._func_dict[prefix][func].args_and_sig = args_and_sig
391              continue
392            else:
393              # This means a previous RUN line produced a body for this function
394              # that is different from the one produced by this current RUN line,
395              # so the body can't be common accross RUN lines. We use None to
396              # indicate that.
397              self._func_dict[prefix][func] = None
398              continue
399
400        self._func_dict[prefix][func] = function_body(
401            scrubbed_body, scrubbed_extra, args_and_sig, attrs)
402        self._func_order[prefix].append(func)
403
404  def _get_failed_prefixes(self):
405    # This returns the list of those prefixes that failed to match any function,
406    # because there were conflicting bodies produced by different RUN lines, in
407    # all instances of the prefix. Effectively, this prefix is unused and should
408    # be removed.
409    for prefix in self._func_dict:
410      if (self._func_dict[prefix] and
411          (not [fct for fct in self._func_dict[prefix]
412                if self._func_dict[prefix][fct] is not None])):
413        yield prefix
414
415
416##### Generator of LLVM IR CHECK lines
417
418SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*')
419
420# TODO: We should also derive check lines for global, debug, loop declarations, etc..
421
422class NamelessValue:
423    def __init__(self, check_prefix, check_key, ir_prefix, global_ir_prefix, global_ir_prefix_regexp,
424                 ir_regexp, global_ir_rhs_regexp, is_before_functions):
425        self.check_prefix = check_prefix
426        self.check_key = check_key
427        self.ir_prefix = ir_prefix
428        self.global_ir_prefix = global_ir_prefix
429        self.global_ir_prefix_regexp = global_ir_prefix_regexp
430        self.ir_regexp = ir_regexp
431        self.global_ir_rhs_regexp = global_ir_rhs_regexp
432        self.is_before_functions = is_before_functions
433
434# Description of the different "unnamed" values we match in the IR, e.g.,
435# (local) ssa values, (debug) metadata, etc.
436nameless_values = [
437    NamelessValue(r'TMP'  , '%' , r'%'           , None            , None                   , r'[\w$.-]+?' , None                 , False) ,
438    NamelessValue(r'ATTR' , '#' , r'#'           , None            , None                   , r'[0-9]+'    , None                 , False) ,
439    NamelessValue(r'ATTR' , '#' , None           , r'attributes #' , r'[0-9]+'              , None         , r'{[^}]*}'           , False) ,
440    NamelessValue(r'GLOB' , '@' , r'@'           , None            , None                   , r'[0-9]+'    , None                 , False) ,
441    NamelessValue(r'GLOB' , '@' , None           , r'@'            , r'[a-zA-Z0-9_$"\\.-]+' , None         , r'.+'                , True)  ,
442    NamelessValue(r'DBG'  , '!' , r'!dbg '       , None            , None                   , r'![0-9]+'   , None                 , False) ,
443    NamelessValue(r'PROF' , '!' , r'!prof '      , None            , None                   , r'![0-9]+'   , None                 , False) ,
444    NamelessValue(r'TBAA' , '!' , r'!tbaa '      , None            , None                   , r'![0-9]+'   , None                 , False) ,
445    NamelessValue(r'RNG'  , '!' , r'!range '     , None            , None                   , r'![0-9]+'   , None                 , False) ,
446    NamelessValue(r'LOOP' , '!' , r'!llvm.loop ' , None            , None                   , r'![0-9]+'   , None                 , False) ,
447    NamelessValue(r'META' , '!' , r'metadata '   , None            , None                   , r'![0-9]+'   , None                 , False) ,
448    NamelessValue(r'META' , '!' , None           , r''             , r'![0-9]+'             , None         , r'(?:distinct |)!.*' , False) ,
449]
450
451def createOrRegexp(old, new):
452    if not old:
453        return new
454    if not new:
455        return old
456    return old + '|' + new
457
458def createPrefixMatch(prefix_str, prefix_re):
459    if prefix_str is None or prefix_re is None:
460        return ''
461    return '(?:' + prefix_str + '(' + prefix_re + '))'
462
463# Build the regexp that matches an "IR value". This can be a local variable,
464# argument, global, or metadata, anything that is "named". It is important that
465# the PREFIX and SUFFIX below only contain a single group, if that changes
466# other locations will need adjustment as well.
467IR_VALUE_REGEXP_PREFIX = r'(\s*)'
468IR_VALUE_REGEXP_STRING = r''
469for nameless_value in nameless_values:
470    lcl_match = createPrefixMatch(nameless_value.ir_prefix, nameless_value.ir_regexp)
471    glb_match = createPrefixMatch(nameless_value.global_ir_prefix, nameless_value.global_ir_prefix_regexp)
472    assert((lcl_match or glb_match) and not (lcl_match and glb_match))
473    if lcl_match:
474        IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, lcl_match)
475    elif glb_match:
476        IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, '^' + glb_match)
477IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)'
478IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX)
479
480# The entire match is group 0, the prefix has one group (=1), the entire
481# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start.
482first_nameless_group_in_ir_value_match = 3
483
484# constants for the group id of special matches
485variable_group_in_ir_value_match = 3
486attribute_group_in_ir_value_match = 4
487
488# Check a match for IR_VALUE_RE and inspect it to determine if it was a local
489# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above.
490def get_idx_from_ir_value_match(match):
491    for i in range(first_nameless_group_in_ir_value_match, match.lastindex):
492        if match.group(i) is not None:
493            return i - first_nameless_group_in_ir_value_match
494    error("Unable to identify the kind of IR value from the match!")
495    return 0
496
497# See get_idx_from_ir_value_match
498def get_name_from_ir_value_match(match):
499    return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match)
500
501# Return the nameless prefix we use for this kind or IR value, see also
502# get_idx_from_ir_value_match
503def get_nameless_check_prefix_from_ir_value_match(match):
504    return nameless_values[get_idx_from_ir_value_match(match)].check_prefix
505
506# Return the IR prefix and check prefix we use for this kind or IR value, e.g., (%, TMP) for locals,
507# see also get_idx_from_ir_value_match
508def get_ir_prefix_from_ir_value_match(match):
509    idx = get_idx_from_ir_value_match(match)
510    if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix):
511        return nameless_values[idx].ir_prefix, nameless_values[idx].check_prefix
512    return nameless_values[idx].global_ir_prefix, nameless_values[idx].check_prefix
513
514def get_check_key_from_ir_value_match(match):
515    idx = get_idx_from_ir_value_match(match)
516    return nameless_values[idx].check_key
517
518# Return the IR regexp we use for this kind or IR value, e.g., [\w.-]+? for locals,
519# see also get_idx_from_ir_value_match
520def get_ir_prefix_from_ir_value_re_match(match):
521    # for backwards compatibility we check locals with '.*'
522    if is_local_def_ir_value_match(match):
523        return '.*'
524    idx = get_idx_from_ir_value_match(match)
525    if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix):
526        return nameless_values[idx].ir_regexp
527    return nameless_values[idx].global_ir_prefix_regexp
528
529# Return true if this kind of IR value is "local", basically if it matches '%{{.*}}'.
530def is_local_def_ir_value_match(match):
531    return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%'
532
533# Return true if this kind of IR value is "global", basically if it matches '#{{.*}}'.
534def is_global_scope_ir_value_match(match):
535    return nameless_values[get_idx_from_ir_value_match(match)].global_ir_prefix is not None
536
537# Return true if var clashes with the scripted FileCheck check_prefix.
538def may_clash_with_default_check_prefix_name(check_prefix, var):
539  return check_prefix and re.match(r'^' + check_prefix + r'[0-9]+?$', var, re.IGNORECASE)
540
541# Create a FileCheck variable name based on an IR name.
542def get_value_name(var, check_prefix):
543  var = var.replace('!', '')
544  # This is a nameless value, prepend check_prefix.
545  if var.isdigit():
546    var = check_prefix + var
547  else:
548    # This is a named value that clashes with the check_prefix, prepend with _prefix_filecheck_ir_name,
549    # if it has been defined.
550    if may_clash_with_default_check_prefix_name(check_prefix, var) and _prefix_filecheck_ir_name:
551      var = _prefix_filecheck_ir_name + var
552  var = var.replace('.', '_')
553  var = var.replace('-', '_')
554  return var.upper()
555
556# Create a FileCheck variable from regex.
557def get_value_definition(var, match):
558  # for backwards compatibility we check locals with '.*'
559  if is_local_def_ir_value_match(match):
560    return '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + \
561            get_ir_prefix_from_ir_value_match(match)[0] + get_ir_prefix_from_ir_value_re_match(match) + ']]'
562  prefix = get_ir_prefix_from_ir_value_match(match)[0]
563  return prefix + '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + get_ir_prefix_from_ir_value_re_match(match) + ']]'
564
565# Use a FileCheck variable.
566def get_value_use(var, match, check_prefix):
567  if is_local_def_ir_value_match(match):
568    return '[[' + get_value_name(var, check_prefix) + ']]'
569  prefix = get_ir_prefix_from_ir_value_match(match)[0]
570  return prefix + '[[' + get_value_name(var, check_prefix) + ']]'
571
572# Replace IR value defs and uses with FileCheck variables.
573def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen):
574  # This gets called for each match that occurs in
575  # a line. We transform variables we haven't seen
576  # into defs, and variables we have seen into uses.
577  def transform_line_vars(match):
578    pre, check = get_ir_prefix_from_ir_value_match(match)
579    var = get_name_from_ir_value_match(match)
580    for nameless_value in nameless_values:
581        if may_clash_with_default_check_prefix_name(nameless_value.check_prefix, var):
582          warn("Change IR value name '%s' or use -prefix-ir-filecheck-name to prevent possible conflict"
583            " with scripted FileCheck name." % (var,))
584    key = (var, get_check_key_from_ir_value_match(match))
585    is_local_def = is_local_def_ir_value_match(match)
586    if is_local_def and key in vars_seen:
587      rv = get_value_use(var, match, get_nameless_check_prefix_from_ir_value_match(match))
588    elif not is_local_def and key in global_vars_seen:
589      rv = get_value_use(var, match, global_vars_seen[key])
590    else:
591      if is_local_def:
592         vars_seen.add(key)
593      else:
594         global_vars_seen[key] = get_nameless_check_prefix_from_ir_value_match(match)
595      rv = get_value_definition(var, match)
596    # re.sub replaces the entire regex match
597    # with whatever you return, so we have
598    # to make sure to hand it back everything
599    # including the commas and spaces.
600    return match.group(1) + rv + match.group(match.lastindex)
601
602  lines_with_def = []
603
604  for i, line in enumerate(lines):
605    # An IR variable named '%.' matches the FileCheck regex string.
606    line = line.replace('%.', '%dot')
607    # Ignore any comments, since the check lines will too.
608    scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line)
609    lines[i] = scrubbed_line
610    if not is_analyze:
611      # It can happen that two matches are back-to-back and for some reason sub
612      # will not replace both of them. For now we work around this by
613      # substituting until there is no more match.
614      changed = True
615      while changed:
616          (lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1)
617  return lines
618
619
620def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze, global_vars_seen_dict):
621  # 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.
622  prefix_exclusions = set()
623  printed_prefixes = []
624  for p in prefix_list:
625    checkprefixes = p[0]
626    # If not all checkprefixes of this run line produced the function we cannot check for it as it does not
627    # exist for this run line. A subset of the check prefixes might know about the function but only because
628    # other run lines created it.
629    if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)):
630        prefix_exclusions |= set(checkprefixes)
631        continue
632
633  # prefix_exclusions is constructed, we can now emit the output
634  for p in prefix_list:
635    global_vars_seen = {}
636    checkprefixes = p[0]
637    for checkprefix in checkprefixes:
638      if checkprefix in global_vars_seen_dict:
639        global_vars_seen.update(global_vars_seen_dict[checkprefix])
640      else:
641        global_vars_seen_dict[checkprefix] = {}
642      if checkprefix in printed_prefixes:
643        break
644
645      # Check if the prefix is excluded.
646      if checkprefix in prefix_exclusions:
647        continue
648
649      # If we do not have output for this prefix we skip it.
650      if not func_dict[checkprefix][func_name]:
651        continue
652
653      # Add some space between different check prefixes, but not after the last
654      # check line (before the test code).
655      if is_asm:
656        if len(printed_prefixes) != 0:
657          output_lines.append(comment_marker)
658
659      if checkprefix not in global_vars_seen_dict:
660          global_vars_seen_dict[checkprefix] = {}
661
662      global_vars_seen_before = [key for key in global_vars_seen.keys()]
663
664      vars_seen = set()
665      printed_prefixes.append(checkprefix)
666      attrs = str(func_dict[checkprefix][func_name].attrs)
667      attrs = '' if attrs == 'None' else attrs
668      if attrs:
669        output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs))
670      args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig)
671      args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0]
672      if '[[' in args_and_sig:
673        output_lines.append(check_label_format % (checkprefix, func_name, ''))
674        output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig))
675      else:
676        output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig))
677      func_body = str(func_dict[checkprefix][func_name]).splitlines()
678
679      # For ASM output, just emit the check lines.
680      if is_asm:
681        output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
682        for func_line in func_body[1:]:
683          if func_line.strip() == '':
684            output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix))
685          else:
686            output_lines.append('%s %s-NEXT:  %s' % (comment_marker, checkprefix, func_line))
687        break
688
689      # For IR output, change all defs to FileCheck variables, so we're immune
690      # to variable naming fashions.
691      func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen)
692
693      # This could be selectively enabled with an optional invocation argument.
694      # Disabled for now: better to check everything. Be safe rather than sorry.
695
696      # Handle the first line of the function body as a special case because
697      # it's often just noise (a useless asm comment or entry label).
698      #if func_body[0].startswith("#") or func_body[0].startswith("entry:"):
699      #  is_blank_line = True
700      #else:
701      #  output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
702      #  is_blank_line = False
703
704      is_blank_line = False
705
706      for func_line in func_body:
707        if func_line.strip() == '':
708          is_blank_line = True
709          continue
710        # Do not waste time checking IR comments.
711        func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line)
712
713        # Skip blank lines instead of checking them.
714        if is_blank_line:
715          output_lines.append('{} {}:       {}'.format(
716              comment_marker, checkprefix, func_line))
717        else:
718          output_lines.append('{} {}-NEXT:  {}'.format(
719              comment_marker, checkprefix, func_line))
720        is_blank_line = False
721
722      # Add space between different check prefixes and also before the first
723      # line of code in the test function.
724      output_lines.append(comment_marker)
725
726      # Remembe new global variables we have not seen before
727      for key in global_vars_seen:
728          if key not in global_vars_seen_before:
729              global_vars_seen_dict[checkprefix][key] = global_vars_seen[key]
730      break
731
732def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict,
733                  func_name, preserve_names, function_sig, global_vars_seen_dict):
734  # Label format is based on IR string.
735  function_def_regex = 'define {{[^@]+}}' if function_sig else ''
736  check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex)
737  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
738             check_label_format, False, preserve_names, global_vars_seen_dict)
739
740def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name):
741  check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker)
742  global_vars_seen_dict = {}
743  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
744             check_label_format, False, True, global_vars_seen_dict)
745
746def build_global_values_dictionary(glob_val_dict, raw_tool_output, prefixes):
747  for nameless_value in nameless_values:
748    if nameless_value.global_ir_prefix is None:
749      continue
750
751    lhs_re_str = nameless_value.global_ir_prefix + nameless_value.global_ir_prefix_regexp
752    rhs_re_str = nameless_value.global_ir_rhs_regexp
753
754    global_ir_value_re_str = r'^' + lhs_re_str + r'\s=\s' + rhs_re_str + r'$'
755    global_ir_value_re = re.compile(global_ir_value_re_str, flags=(re.M))
756    lines = []
757    for m in global_ir_value_re.finditer(raw_tool_output):
758        lines.append(m.group(0))
759
760    for prefix in prefixes:
761      if glob_val_dict[prefix] is None:
762        continue
763      if nameless_value.check_prefix in glob_val_dict[prefix]:
764        if lines == glob_val_dict[prefix][nameless_value.check_prefix]:
765          continue
766        if prefix == prefixes[-1]:
767          warn('Found conflicting asm under the same prefix: %r!' % (prefix,))
768        else:
769          glob_val_dict[prefix][nameless_value.check_prefix] = None
770          continue
771      glob_val_dict[prefix][nameless_value.check_prefix] = lines
772
773def add_global_checks(glob_val_dict, comment_marker, prefix_list, output_lines, global_vars_seen_dict, is_analyze, is_before_functions):
774  printed_prefixes = set()
775  for nameless_value in nameless_values:
776    if nameless_value.global_ir_prefix is None:
777        continue
778    if nameless_value.is_before_functions != is_before_functions:
779        continue
780    for p in prefix_list:
781      global_vars_seen = {}
782      checkprefixes = p[0]
783      for checkprefix in checkprefixes:
784        if checkprefix in global_vars_seen_dict:
785            global_vars_seen.update(global_vars_seen_dict[checkprefix])
786        else:
787            global_vars_seen_dict[checkprefix] = {}
788        if (checkprefix, nameless_value.check_prefix) in printed_prefixes:
789          break
790        if not glob_val_dict[checkprefix]:
791          continue
792        if nameless_value.check_prefix not in glob_val_dict[checkprefix]:
793          continue
794        if not glob_val_dict[checkprefix][nameless_value.check_prefix]:
795          continue
796
797        output_lines.append(comment_marker + SEPARATOR)
798
799        global_vars_seen_before = [key for key in global_vars_seen.keys()]
800        for line in glob_val_dict[checkprefix][nameless_value.check_prefix]:
801          tmp = generalize_check_lines([line], is_analyze, set(), global_vars_seen)
802          check_line = '%s %s: %s' % (comment_marker, checkprefix, tmp[0])
803          output_lines.append(check_line)
804        printed_prefixes.add((checkprefix, nameless_value.check_prefix))
805
806        # Remembe new global variables we have not seen before
807        for key in global_vars_seen:
808            if key not in global_vars_seen_before:
809                global_vars_seen_dict[checkprefix][key] = global_vars_seen[key]
810        break
811
812  if printed_prefixes:
813      output_lines.append(comment_marker + SEPARATOR)
814
815
816def check_prefix(prefix):
817  if not PREFIX_RE.match(prefix):
818        hint = ""
819        if ',' in prefix:
820          hint = " Did you mean '--check-prefixes=" + prefix + "'?"
821        warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) %
822             (prefix))
823
824
825def verify_filecheck_prefixes(fc_cmd):
826  fc_cmd_parts = fc_cmd.split()
827  for part in fc_cmd_parts:
828    if "check-prefix=" in part:
829      prefix = part.split('=', 1)[1]
830      check_prefix(prefix)
831    elif "check-prefixes=" in part:
832      prefixes = part.split('=', 1)[1].split(',')
833      for prefix in prefixes:
834        check_prefix(prefix)
835        if prefixes.count(prefix) > 1:
836          warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,))
837
838
839def get_autogennote_suffix(parser, args):
840  autogenerated_note_args = ''
841  for action in parser._actions:
842    if not hasattr(args, action.dest):
843      continue  # Ignore options such as --help that aren't included in args
844    # Ignore parameters such as paths to the binary or the list of tests
845    if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary',
846                       'clang', 'opt', 'llvm_bin', 'verbose'):
847      continue
848    value = getattr(args, action.dest)
849    if action.const is not None:  # action stores a constant (usually True/False)
850      # Skip actions with different constant values (this happens with boolean
851      # --foo/--no-foo options)
852      if value != action.const:
853        continue
854    if parser.get_default(action.dest) == value:
855      continue  # Don't add default values
856    autogenerated_note_args += action.option_strings[0] + ' '
857    if action.const is None:  # action takes a parameter
858      if action.nargs == '+':
859        value = ' '.join(map(lambda v: '"' + v.strip('"') + '"', value))
860      autogenerated_note_args += '%s ' % value
861  if autogenerated_note_args:
862    autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1])
863  return autogenerated_note_args
864
865
866def check_for_command(line, parser, args, argv, argparse_callback):
867    cmd_m = UTC_ARGS_CMD.match(line)
868    if cmd_m:
869        for option in cmd_m.group('cmd').strip().split(' '):
870            if option:
871                argv.append(option)
872        args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv))
873        if argparse_callback is not None:
874          argparse_callback(args)
875    return args, argv
876
877def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global):
878  result = get_arg_to_check(test_info.args)
879  if not result and is_global:
880    # See if this has been specified via UTC_ARGS.  This is a "global" option
881    # that affects the entire generation of test checks.  If it exists anywhere
882    # in the test, apply it to everything.
883    saw_line = False
884    for line_info in test_info.ro_iterlines():
885      line = line_info.line
886      if not line.startswith(';') and line.strip() != '':
887        saw_line = True
888      result = get_arg_to_check(line_info.args)
889      if result:
890        if warn and saw_line:
891          # We saw the option after already reading some test input lines.
892          # Warn about it.
893          print('WARNING: Found {} in line following test start: '.format(arg_string)
894                + line, file=sys.stderr)
895          print('WARNING: Consider moving {} to top of file'.format(arg_string),
896                file=sys.stderr)
897        break
898  return result
899
900def dump_input_lines(output_lines, test_info, prefix_set, comment_string):
901  for input_line_info in test_info.iterlines(output_lines):
902    line = input_line_info.line
903    args = input_line_info.args
904    if line.strip() == comment_string:
905      continue
906    if line.strip() == comment_string + SEPARATOR:
907      continue
908    if line.lstrip().startswith(comment_string):
909      m = CHECK_RE.match(line)
910      if m and m.group(1) in prefix_set:
911        continue
912    output_lines.append(line.rstrip('\n'))
913
914def add_checks_at_end(output_lines, prefix_list, func_order,
915                      comment_string, check_generator):
916  added = set()
917  for prefix in prefix_list:
918    prefixes = prefix[0]
919    tool_args = prefix[1]
920    for prefix in prefixes:
921      for func in func_order[prefix]:
922        if added:
923          output_lines.append(comment_string)
924        added.add(func)
925
926        # The add_*_checks routines expect a run list whose items are
927        # tuples that have a list of prefixes as their first element and
928        # tool command args string as their second element.  They output
929        # checks for each prefix in the list of prefixes.  By doing so, it
930        # implicitly assumes that for each function every run line will
931        # generate something for that function.  That is not the case for
932        # generated functions as some run lines might not generate them
933        # (e.g. -fopenmp vs. no -fopenmp).
934        #
935        # Therefore, pass just the prefix we're interested in.  This has
936        # the effect of generating all of the checks for functions of a
937        # single prefix before moving on to the next prefix.  So checks
938        # are ordered by prefix instead of by function as in "normal"
939        # mode.
940        check_generator(output_lines,
941                        [([prefix], tool_args)],
942                        func)
943