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