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