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[= ]([^ ]+)')
309DEBUG_ONLY_ARG_RE = re.compile(r'-debug-only[= ]([^ ]+)')
310
311SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)')
312SCRUB_WHITESPACE_RE = re.compile(r'(?!^(|  \w))[ \t]+', flags=re.M)
313SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
314SCRUB_TRAILING_WHITESPACE_TEST_RE = SCRUB_TRAILING_WHITESPACE_RE
315SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE = re.compile(r'([ \t]|(#[0-9]+))+$', flags=re.M)
316SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
317SCRUB_LOOP_COMMENT_RE = re.compile(
318    r'# =>This Inner Loop Header:.*|# in Loop:.*', flags=re.M)
319SCRUB_TAILING_COMMENT_TOKEN_RE = re.compile(r'(?<=\S)+[ \t]*#$', flags=re.M)
320
321SEPARATOR = '.'
322
323def error(msg, test_file=None):
324  if test_file:
325    msg = '{}: {}'.format(msg, test_file)
326  print('ERROR: {}'.format(msg), file=sys.stderr)
327
328def warn(msg, test_file=None):
329  if test_file:
330    msg = '{}: {}'.format(msg, test_file)
331  print('WARNING: {}'.format(msg), file=sys.stderr)
332
333def debug(*args, **kwargs):
334  # Python2 does not allow def debug(*args, file=sys.stderr, **kwargs):
335  if 'file' not in kwargs:
336    kwargs['file'] = sys.stderr
337  if _verbose:
338    print(*args, **kwargs)
339
340def find_run_lines(test, lines):
341  debug('Scanning for RUN lines in test file:', test)
342  raw_lines = [m.group(1)
343               for m in [RUN_LINE_RE.match(l) for l in lines] if m]
344  run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
345  for l in raw_lines[1:]:
346    if run_lines[-1].endswith('\\'):
347      run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l
348    else:
349      run_lines.append(l)
350  debug('Found {} RUN lines in {}:'.format(len(run_lines), test))
351  for l in run_lines:
352    debug('  RUN: {}'.format(l))
353  return run_lines
354
355def get_triple_from_march(march):
356  triples = {
357      'amdgcn': 'amdgcn',
358      'r600': 'r600',
359      'mips': 'mips',
360      'sparc': 'sparc',
361      'hexagon': 'hexagon',
362      've': 've',
363  }
364  for prefix, triple in triples.items():
365    if march.startswith(prefix):
366      return triple
367  print("Cannot find a triple. Assume 'x86'", file=sys.stderr)
368  return 'x86'
369
370def apply_filters(line, filters):
371  has_filter = False
372  for f in filters:
373    if not f.is_filter_out:
374      has_filter = True
375    if f.search(line):
376      return False if f.is_filter_out else True
377  # If we only used filter-out, keep the line, otherwise discard it since no
378  # filter matched.
379  return False if has_filter else True
380
381def do_filter(body, filters):
382  return body if not filters else '\n'.join(filter(
383    lambda line: apply_filters(line, filters), body.splitlines()))
384
385def scrub_body(body):
386  # Scrub runs of whitespace out of the assembly, but leave the leading
387  # whitespace in place.
388  body = SCRUB_WHITESPACE_RE.sub(r' ', body)
389  # Expand the tabs used for indentation.
390  body = str.expandtabs(body, 2)
391  # Strip trailing whitespace.
392  body = SCRUB_TRAILING_WHITESPACE_TEST_RE.sub(r'', body)
393  return body
394
395def do_scrub(body, scrubber, scrubber_args, extra):
396  if scrubber_args:
397    local_args = copy.deepcopy(scrubber_args)
398    local_args[0].extra_scrub = extra
399    return scrubber(body, *local_args)
400  return scrubber(body, *scrubber_args)
401
402# Build up a dictionary of all the function bodies.
403class function_body(object):
404  def __init__(self, string, extra, args_and_sig, attrs):
405    self.scrub = string
406    self.extrascrub = extra
407    self.args_and_sig = args_and_sig
408    self.attrs = attrs
409  def is_same_except_arg_names(self, extrascrub, args_and_sig, attrs, is_backend):
410    arg_names = set()
411    def drop_arg_names(match):
412        arg_names.add(match.group(variable_group_in_ir_value_match))
413        if match.group(attribute_group_in_ir_value_match):
414            attr = match.group(attribute_group_in_ir_value_match)
415        else:
416            attr = ''
417        return match.group(1) + attr + match.group(match.lastindex)
418    def repl_arg_names(match):
419        if match.group(variable_group_in_ir_value_match) is not None and match.group(variable_group_in_ir_value_match) in arg_names:
420            return match.group(1) + match.group(match.lastindex)
421        return match.group(1) + match.group(2) + match.group(match.lastindex)
422    if self.attrs != attrs:
423      return False
424    ans0 = IR_VALUE_RE.sub(drop_arg_names, self.args_and_sig)
425    ans1 = IR_VALUE_RE.sub(drop_arg_names, args_and_sig)
426    if ans0 != ans1:
427        return False
428    if is_backend:
429        # Check without replacements, the replacements are not applied to the
430        # body for backend checks.
431        return self.extrascrub == extrascrub
432
433    es0 = IR_VALUE_RE.sub(repl_arg_names, self.extrascrub)
434    es1 = IR_VALUE_RE.sub(repl_arg_names, extrascrub)
435    es0 = SCRUB_IR_COMMENT_RE.sub(r'', es0)
436    es1 = SCRUB_IR_COMMENT_RE.sub(r'', es1)
437    return es0 == es1
438
439  def __str__(self):
440    return self.scrub
441
442class FunctionTestBuilder:
443  def __init__(self, run_list, flags, scrubber_args, path):
444    self._verbose = flags.verbose
445    self._record_args = flags.function_signature
446    self._check_attributes = flags.check_attributes
447    # Strip double-quotes if input was read by UTC_ARGS
448    self._filters = list(map(lambda f: Filter(re.compile(f.pattern().strip('"'),
449                                                         f.flags()),
450                                              f.is_filter_out),
451                             flags.filters)) if flags.filters else []
452    self._scrubber_args = scrubber_args
453    self._path = path
454    # Strip double-quotes if input was read by UTC_ARGS
455    self._replace_value_regex = list(map(lambda x: x.strip('"'), flags.replace_value_regex))
456    self._func_dict = {}
457    self._func_order = {}
458    self._global_var_dict = {}
459    for tuple in run_list:
460      for prefix in tuple[0]:
461        self._func_dict.update({prefix:dict()})
462        self._func_order.update({prefix: []})
463        self._global_var_dict.update({prefix:dict()})
464
465  def finish_and_get_func_dict(self):
466    for prefix in self._get_failed_prefixes():
467      warn('Prefix %s had conflicting output from different RUN lines for all functions in test %s' % (prefix,self._path,))
468    return self._func_dict
469
470  def func_order(self):
471    return self._func_order
472
473  def global_var_dict(self):
474    return self._global_var_dict
475
476  def is_filtered(self):
477    return bool(self._filters)
478
479  def process_run_line(self, function_re, scrubber, raw_tool_output, prefixes, is_backend):
480    build_global_values_dictionary(self._global_var_dict, raw_tool_output, prefixes)
481    for m in function_re.finditer(raw_tool_output):
482      if not m:
483        continue
484      func = m.group('func')
485      body = m.group('body')
486      attrs = m.group('attrs') if self._check_attributes else ''
487      # Determine if we print arguments, the opening brace, or nothing after the
488      # function name
489      if self._record_args and 'args_and_sig' in m.groupdict():
490          args_and_sig = scrub_body(m.group('args_and_sig').strip())
491      elif 'args_and_sig' in m.groupdict():
492          args_and_sig = '('
493      else:
494          args_and_sig = ''
495      filtered_body = do_filter(body, self._filters)
496      scrubbed_body = do_scrub(filtered_body, scrubber, self._scrubber_args,
497                               extra=False)
498      scrubbed_extra = do_scrub(filtered_body, scrubber, self._scrubber_args,
499                                extra=True)
500      if 'analysis' in m.groupdict():
501        analysis = m.group('analysis')
502        if analysis.lower() != 'cost model analysis':
503          warn('Unsupported analysis mode: %r!' % (analysis,))
504      if func.startswith('stress'):
505        # We only use the last line of the function body for stress tests.
506        scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
507      if self._verbose:
508        print('Processing function: ' + func, file=sys.stderr)
509        for l in scrubbed_body.splitlines():
510          print('  ' + l, file=sys.stderr)
511      for prefix in prefixes:
512        # Replace function names matching the regex.
513        for regex in self._replace_value_regex:
514          # Pattern that matches capture groups in the regex in leftmost order.
515          group_regex = re.compile('\(.*?\)')
516          # Replace function name with regex.
517          match = re.match(regex, func)
518          if match:
519            func_repl = regex
520            # Replace any capture groups with their matched strings.
521            for g in match.groups():
522              func_repl = group_regex.sub(re.escape(g), func_repl, count=1)
523            func = re.sub(func_repl, '{{' + func_repl + '}}', func)
524
525          # Replace all calls to regex matching functions.
526          matches = re.finditer(regex, scrubbed_body)
527          for match in matches:
528            func_repl = regex
529            # Replace any capture groups with their matched strings.
530            for g in match.groups():
531                func_repl = group_regex.sub(re.escape(g), func_repl, count=1)
532            # Substitute function call names that match the regex with the same
533            # capture groups set.
534            scrubbed_body = re.sub(func_repl, '{{' + func_repl + '}}',
535                                   scrubbed_body)
536
537        if func in self._func_dict[prefix]:
538          if (self._func_dict[prefix][func] is None or
539              str(self._func_dict[prefix][func]) != scrubbed_body or
540              self._func_dict[prefix][func].args_and_sig != args_and_sig or
541                  self._func_dict[prefix][func].attrs != attrs):
542            if (self._func_dict[prefix][func] is not None and
543                self._func_dict[prefix][func].is_same_except_arg_names(
544                scrubbed_extra,
545                args_and_sig,
546                attrs,
547                is_backend)):
548              self._func_dict[prefix][func].scrub = scrubbed_extra
549              self._func_dict[prefix][func].args_and_sig = args_and_sig
550              continue
551            else:
552              # This means a previous RUN line produced a body for this function
553              # that is different from the one produced by this current RUN line,
554              # so the body can't be common accross RUN lines. We use None to
555              # indicate that.
556              self._func_dict[prefix][func] = None
557              continue
558
559        self._func_dict[prefix][func] = function_body(
560            scrubbed_body, scrubbed_extra, args_and_sig, attrs)
561        self._func_order[prefix].append(func)
562
563  def _get_failed_prefixes(self):
564    # This returns the list of those prefixes that failed to match any function,
565    # because there were conflicting bodies produced by different RUN lines, in
566    # all instances of the prefix. Effectively, this prefix is unused and should
567    # be removed.
568    for prefix in self._func_dict:
569      if (self._func_dict[prefix] and
570          (not [fct for fct in self._func_dict[prefix]
571                if self._func_dict[prefix][fct] is not None])):
572        yield prefix
573
574
575##### Generator of LLVM IR CHECK lines
576
577SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*')
578
579# TODO: We should also derive check lines for global, debug, loop declarations, etc..
580
581class NamelessValue:
582    def __init__(self, check_prefix, check_key, ir_prefix, global_ir_prefix, global_ir_prefix_regexp,
583                 ir_regexp, global_ir_rhs_regexp, is_before_functions):
584        self.check_prefix = check_prefix
585        self.check_key = check_key
586        self.ir_prefix = ir_prefix
587        self.global_ir_prefix = global_ir_prefix
588        self.global_ir_prefix_regexp = global_ir_prefix_regexp
589        self.ir_regexp = ir_regexp
590        self.global_ir_rhs_regexp = global_ir_rhs_regexp
591        self.is_before_functions = is_before_functions
592
593# Description of the different "unnamed" values we match in the IR, e.g.,
594# (local) ssa values, (debug) metadata, etc.
595nameless_values = [
596    NamelessValue(r'TMP'  , '%' , r'%'           , None            , None                   , r'[\w$.-]+?' , None                 , False) ,
597    NamelessValue(r'ATTR' , '#' , r'#'           , None            , None                   , r'[0-9]+'    , None                 , False) ,
598    NamelessValue(r'ATTR' , '#' , None           , r'attributes #' , r'[0-9]+'              , None         , r'{[^}]*}'           , False) ,
599    NamelessValue(r'GLOB' , '@' , r'@'           , None            , None                   , r'[0-9]+'    , None                 , False) ,
600    NamelessValue(r'GLOB' , '@' , None           , r'@'            , r'[a-zA-Z0-9_$"\\.-]+' , None         , r'.+'                , True)  ,
601    NamelessValue(r'DBG'  , '!' , r'!dbg '       , None            , None                   , r'![0-9]+'   , None                 , False) ,
602    NamelessValue(r'PROF' , '!' , r'!prof '      , None            , None                   , r'![0-9]+'   , None                 , False) ,
603    NamelessValue(r'TBAA' , '!' , r'!tbaa '      , None            , None                   , r'![0-9]+'   , None                 , False) ,
604    NamelessValue(r'RNG'  , '!' , r'!range '     , None            , None                   , r'![0-9]+'   , None                 , False) ,
605    NamelessValue(r'LOOP' , '!' , r'!llvm.loop ' , None            , None                   , r'![0-9]+'   , None                 , False) ,
606    NamelessValue(r'META' , '!' , r'metadata '   , None            , None                   , r'![0-9]+'   , None                 , False) ,
607    NamelessValue(r'META' , '!' , None           , r''             , r'![0-9]+'             , None         , r'(?:distinct |)!.*' , False) ,
608]
609
610def createOrRegexp(old, new):
611    if not old:
612        return new
613    if not new:
614        return old
615    return old + '|' + new
616
617def createPrefixMatch(prefix_str, prefix_re):
618    if prefix_str is None or prefix_re is None:
619        return ''
620    return '(?:' + prefix_str + '(' + prefix_re + '))'
621
622# Build the regexp that matches an "IR value". This can be a local variable,
623# argument, global, or metadata, anything that is "named". It is important that
624# the PREFIX and SUFFIX below only contain a single group, if that changes
625# other locations will need adjustment as well.
626IR_VALUE_REGEXP_PREFIX = r'(\s*)'
627IR_VALUE_REGEXP_STRING = r''
628for nameless_value in nameless_values:
629    lcl_match = createPrefixMatch(nameless_value.ir_prefix, nameless_value.ir_regexp)
630    glb_match = createPrefixMatch(nameless_value.global_ir_prefix, nameless_value.global_ir_prefix_regexp)
631    assert((lcl_match or glb_match) and not (lcl_match and glb_match))
632    if lcl_match:
633        IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, lcl_match)
634    elif glb_match:
635        IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, '^' + glb_match)
636IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)'
637IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX)
638
639# The entire match is group 0, the prefix has one group (=1), the entire
640# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start.
641first_nameless_group_in_ir_value_match = 3
642
643# constants for the group id of special matches
644variable_group_in_ir_value_match = 3
645attribute_group_in_ir_value_match = 4
646
647# Check a match for IR_VALUE_RE and inspect it to determine if it was a local
648# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above.
649def get_idx_from_ir_value_match(match):
650    for i in range(first_nameless_group_in_ir_value_match, match.lastindex):
651        if match.group(i) is not None:
652            return i - first_nameless_group_in_ir_value_match
653    error("Unable to identify the kind of IR value from the match!")
654    return 0
655
656# See get_idx_from_ir_value_match
657def get_name_from_ir_value_match(match):
658    return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match)
659
660# Return the nameless prefix we use for this kind or IR value, see also
661# get_idx_from_ir_value_match
662def get_nameless_check_prefix_from_ir_value_match(match):
663    return nameless_values[get_idx_from_ir_value_match(match)].check_prefix
664
665# Return the IR prefix and check prefix we use for this kind or IR value, e.g., (%, TMP) for locals,
666# see also get_idx_from_ir_value_match
667def get_ir_prefix_from_ir_value_match(match):
668    idx = get_idx_from_ir_value_match(match)
669    if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix):
670        return nameless_values[idx].ir_prefix, nameless_values[idx].check_prefix
671    return nameless_values[idx].global_ir_prefix, nameless_values[idx].check_prefix
672
673def get_check_key_from_ir_value_match(match):
674    idx = get_idx_from_ir_value_match(match)
675    return nameless_values[idx].check_key
676
677# Return the IR regexp we use for this kind or IR value, e.g., [\w.-]+? for locals,
678# see also get_idx_from_ir_value_match
679def get_ir_prefix_from_ir_value_re_match(match):
680    # for backwards compatibility we check locals with '.*'
681    if is_local_def_ir_value_match(match):
682        return '.*'
683    idx = get_idx_from_ir_value_match(match)
684    if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix):
685        return nameless_values[idx].ir_regexp
686    return nameless_values[idx].global_ir_prefix_regexp
687
688# Return true if this kind of IR value is "local", basically if it matches '%{{.*}}'.
689def is_local_def_ir_value_match(match):
690    return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%'
691
692# Return true if this kind of IR value is "global", basically if it matches '#{{.*}}'.
693def is_global_scope_ir_value_match(match):
694    return nameless_values[get_idx_from_ir_value_match(match)].global_ir_prefix is not None
695
696# Return true if var clashes with the scripted FileCheck check_prefix.
697def may_clash_with_default_check_prefix_name(check_prefix, var):
698  return check_prefix and re.match(r'^' + check_prefix + r'[0-9]+?$', var, re.IGNORECASE)
699
700# Create a FileCheck variable name based on an IR name.
701def get_value_name(var, check_prefix):
702  var = var.replace('!', '')
703  # This is a nameless value, prepend check_prefix.
704  if var.isdigit():
705    var = check_prefix + var
706  else:
707    # This is a named value that clashes with the check_prefix, prepend with _prefix_filecheck_ir_name,
708    # if it has been defined.
709    if may_clash_with_default_check_prefix_name(check_prefix, var) and _prefix_filecheck_ir_name:
710      var = _prefix_filecheck_ir_name + var
711  var = var.replace('.', '_')
712  var = var.replace('-', '_')
713  return var.upper()
714
715# Create a FileCheck variable from regex.
716def get_value_definition(var, match):
717  # for backwards compatibility we check locals with '.*'
718  if is_local_def_ir_value_match(match):
719    return '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + \
720            get_ir_prefix_from_ir_value_match(match)[0] + get_ir_prefix_from_ir_value_re_match(match) + ']]'
721  prefix = get_ir_prefix_from_ir_value_match(match)[0]
722  return prefix + '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + get_ir_prefix_from_ir_value_re_match(match) + ']]'
723
724# Use a FileCheck variable.
725def get_value_use(var, match, check_prefix):
726  if is_local_def_ir_value_match(match):
727    return '[[' + get_value_name(var, check_prefix) + ']]'
728  prefix = get_ir_prefix_from_ir_value_match(match)[0]
729  return prefix + '[[' + get_value_name(var, check_prefix) + ']]'
730
731# Replace IR value defs and uses with FileCheck variables.
732def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen):
733  # This gets called for each match that occurs in
734  # a line. We transform variables we haven't seen
735  # into defs, and variables we have seen into uses.
736  def transform_line_vars(match):
737    pre, check = get_ir_prefix_from_ir_value_match(match)
738    var = get_name_from_ir_value_match(match)
739    for nameless_value in nameless_values:
740        if may_clash_with_default_check_prefix_name(nameless_value.check_prefix, var):
741          warn("Change IR value name '%s' or use --prefix-filecheck-ir-name to prevent possible conflict"
742            " with scripted FileCheck name." % (var,))
743    key = (var, get_check_key_from_ir_value_match(match))
744    is_local_def = is_local_def_ir_value_match(match)
745    if is_local_def and key in vars_seen:
746      rv = get_value_use(var, match, get_nameless_check_prefix_from_ir_value_match(match))
747    elif not is_local_def and key in global_vars_seen:
748      rv = get_value_use(var, match, global_vars_seen[key])
749    else:
750      if is_local_def:
751         vars_seen.add(key)
752      else:
753         global_vars_seen[key] = get_nameless_check_prefix_from_ir_value_match(match)
754      rv = get_value_definition(var, match)
755    # re.sub replaces the entire regex match
756    # with whatever you return, so we have
757    # to make sure to hand it back everything
758    # including the commas and spaces.
759    return match.group(1) + rv + match.group(match.lastindex)
760
761  lines_with_def = []
762
763  for i, line in enumerate(lines):
764    # An IR variable named '%.' matches the FileCheck regex string.
765    line = line.replace('%.', '%dot')
766    for regex in _global_hex_value_regex:
767      if re.match('^@' + regex + ' = ', line):
768        line = re.sub(r'\bi([0-9]+) ([0-9]+)',
769            lambda m : 'i' + m.group(1) + ' [[#' + hex(int(m.group(2))) + ']]',
770            line)
771        break
772    # Ignore any comments, since the check lines will too.
773    scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line)
774    lines[i] = scrubbed_line
775    if not is_analyze:
776      # It can happen that two matches are back-to-back and for some reason sub
777      # will not replace both of them. For now we work around this by
778      # substituting until there is no more match.
779      changed = True
780      while changed:
781          (lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1)
782  return lines
783
784
785def 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):
786  # 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.
787  prefix_exclusions = set()
788  printed_prefixes = []
789  for p in prefix_list:
790    checkprefixes = p[0]
791    # If not all checkprefixes of this run line produced the function we cannot check for it as it does not
792    # exist for this run line. A subset of the check prefixes might know about the function but only because
793    # other run lines created it.
794    if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)):
795        prefix_exclusions |= set(checkprefixes)
796        continue
797
798  # prefix_exclusions is constructed, we can now emit the output
799  for p in prefix_list:
800    global_vars_seen = {}
801    checkprefixes = p[0]
802    for checkprefix in checkprefixes:
803      if checkprefix in global_vars_seen_dict:
804        global_vars_seen.update(global_vars_seen_dict[checkprefix])
805      else:
806        global_vars_seen_dict[checkprefix] = {}
807      if checkprefix in printed_prefixes:
808        break
809
810      # Check if the prefix is excluded.
811      if checkprefix in prefix_exclusions:
812        continue
813
814      # If we do not have output for this prefix we skip it.
815      if not func_dict[checkprefix][func_name]:
816        continue
817
818      # Add some space between different check prefixes, but not after the last
819      # check line (before the test code).
820      if is_backend:
821        if len(printed_prefixes) != 0:
822          output_lines.append(comment_marker)
823
824      if checkprefix not in global_vars_seen_dict:
825          global_vars_seen_dict[checkprefix] = {}
826
827      global_vars_seen_before = [key for key in global_vars_seen.keys()]
828
829      vars_seen = set()
830      printed_prefixes.append(checkprefix)
831      attrs = str(func_dict[checkprefix][func_name].attrs)
832      attrs = '' if attrs == 'None' else attrs
833      if attrs:
834        output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs))
835      args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig)
836      args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0]
837      if '[[' in args_and_sig:
838        output_lines.append(check_label_format % (checkprefix, func_name, ''))
839        output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig))
840      else:
841        output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig))
842      func_body = str(func_dict[checkprefix][func_name]).splitlines()
843      if not func_body:
844        # We have filtered everything.
845        continue
846
847      # For ASM output, just emit the check lines.
848      if is_backend:
849        body_start = 1
850        if is_filtered:
851          # For filtered output we don't add "-NEXT" so don't add extra spaces
852          # before the first line.
853          body_start = 0
854        else:
855          output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
856        for func_line in func_body[1:]:
857          if func_line.strip() == '':
858            output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix))
859          else:
860            check_suffix = '-NEXT' if not is_filtered else ''
861            output_lines.append('%s %s%s:  %s' % (comment_marker, checkprefix,
862                                                  check_suffix, func_line))
863        break
864
865      # For IR output, change all defs to FileCheck variables, so we're immune
866      # to variable naming fashions.
867      func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen)
868
869      # This could be selectively enabled with an optional invocation argument.
870      # Disabled for now: better to check everything. Be safe rather than sorry.
871
872      # Handle the first line of the function body as a special case because
873      # it's often just noise (a useless asm comment or entry label).
874      #if func_body[0].startswith("#") or func_body[0].startswith("entry:"):
875      #  is_blank_line = True
876      #else:
877      #  output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
878      #  is_blank_line = False
879
880      is_blank_line = False
881
882      for func_line in func_body:
883        if func_line.strip() == '':
884          is_blank_line = True
885          continue
886        # Do not waste time checking IR comments.
887        func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line)
888
889        # Skip blank lines instead of checking them.
890        if is_blank_line:
891          output_lines.append('{} {}:       {}'.format(
892              comment_marker, checkprefix, func_line))
893        else:
894          check_suffix = '-NEXT' if not is_filtered else ''
895          output_lines.append('{} {}{}:  {}'.format(
896              comment_marker, checkprefix, check_suffix, func_line))
897        is_blank_line = False
898
899      # Add space between different check prefixes and also before the first
900      # line of code in the test function.
901      output_lines.append(comment_marker)
902
903      # Remembe new global variables we have not seen before
904      for key in global_vars_seen:
905          if key not in global_vars_seen_before:
906              global_vars_seen_dict[checkprefix][key] = global_vars_seen[key]
907      break
908
909def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict,
910                  func_name, preserve_names, function_sig,
911                  global_vars_seen_dict, is_filtered):
912  # Label format is based on IR string.
913  function_def_regex = 'define {{[^@]+}}' if function_sig else ''
914  check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex)
915  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
916             check_label_format, False, preserve_names, global_vars_seen_dict,
917             is_filtered)
918
919def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name):
920  check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker)
921  global_vars_seen_dict = {}
922  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
923             check_label_format, False, True, global_vars_seen_dict,
924             is_filtered = False)
925
926def build_global_values_dictionary(glob_val_dict, raw_tool_output, prefixes):
927  for nameless_value in nameless_values:
928    if nameless_value.global_ir_prefix is None:
929      continue
930
931    lhs_re_str = nameless_value.global_ir_prefix + nameless_value.global_ir_prefix_regexp
932    rhs_re_str = nameless_value.global_ir_rhs_regexp
933
934    global_ir_value_re_str = r'^' + lhs_re_str + r'\s=\s' + rhs_re_str + r'$'
935    global_ir_value_re = re.compile(global_ir_value_re_str, flags=(re.M))
936    lines = []
937    for m in global_ir_value_re.finditer(raw_tool_output):
938        lines.append(m.group(0))
939
940    for prefix in prefixes:
941      if glob_val_dict[prefix] is None:
942        continue
943      if nameless_value.check_prefix in glob_val_dict[prefix]:
944        if lines == glob_val_dict[prefix][nameless_value.check_prefix]:
945          continue
946        if prefix == prefixes[-1]:
947          warn('Found conflicting asm under the same prefix: %r!' % (prefix,))
948        else:
949          glob_val_dict[prefix][nameless_value.check_prefix] = None
950          continue
951      glob_val_dict[prefix][nameless_value.check_prefix] = lines
952
953def add_global_checks(glob_val_dict, comment_marker, prefix_list, output_lines, global_vars_seen_dict, is_analyze, is_before_functions):
954  printed_prefixes = set()
955  for nameless_value in nameless_values:
956    if nameless_value.global_ir_prefix is None:
957        continue
958    if nameless_value.is_before_functions != is_before_functions:
959        continue
960    for p in prefix_list:
961      global_vars_seen = {}
962      checkprefixes = p[0]
963      if checkprefixes is None:
964        continue
965      for checkprefix in checkprefixes:
966        if checkprefix in global_vars_seen_dict:
967            global_vars_seen.update(global_vars_seen_dict[checkprefix])
968        else:
969            global_vars_seen_dict[checkprefix] = {}
970        if (checkprefix, nameless_value.check_prefix) in printed_prefixes:
971          break
972        if not glob_val_dict[checkprefix]:
973          continue
974        if nameless_value.check_prefix not in glob_val_dict[checkprefix]:
975          continue
976        if not glob_val_dict[checkprefix][nameless_value.check_prefix]:
977          continue
978
979        check_lines = []
980        global_vars_seen_before = [key for key in global_vars_seen.keys()]
981        for line in glob_val_dict[checkprefix][nameless_value.check_prefix]:
982          if _global_value_regex:
983            matched = False
984            for regex in _global_value_regex:
985              if re.match('^@' + regex + ' = ', line):
986                matched = True
987                break
988            if not matched:
989              continue
990          tmp = generalize_check_lines([line], is_analyze, set(), global_vars_seen)
991          check_line = '%s %s: %s' % (comment_marker, checkprefix, tmp[0])
992          check_lines.append(check_line)
993        if not check_lines:
994          continue
995
996        output_lines.append(comment_marker + SEPARATOR)
997        for check_line in check_lines:
998          output_lines.append(check_line)
999
1000        printed_prefixes.add((checkprefix, nameless_value.check_prefix))
1001
1002        # Remembe new global variables we have not seen before
1003        for key in global_vars_seen:
1004            if key not in global_vars_seen_before:
1005                global_vars_seen_dict[checkprefix][key] = global_vars_seen[key]
1006        break
1007
1008  if printed_prefixes:
1009      output_lines.append(comment_marker + SEPARATOR)
1010
1011
1012def check_prefix(prefix):
1013  if not PREFIX_RE.match(prefix):
1014        hint = ""
1015        if ',' in prefix:
1016          hint = " Did you mean '--check-prefixes=" + prefix + "'?"
1017        warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) %
1018             (prefix))
1019
1020
1021def verify_filecheck_prefixes(fc_cmd):
1022  fc_cmd_parts = fc_cmd.split()
1023  for part in fc_cmd_parts:
1024    if "check-prefix=" in part:
1025      prefix = part.split('=', 1)[1]
1026      check_prefix(prefix)
1027    elif "check-prefixes=" in part:
1028      prefixes = part.split('=', 1)[1].split(',')
1029      for prefix in prefixes:
1030        check_prefix(prefix)
1031        if prefixes.count(prefix) > 1:
1032          warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,))
1033
1034
1035def get_autogennote_suffix(parser, args):
1036  autogenerated_note_args = ''
1037  for action in parser._actions:
1038    if not hasattr(args, action.dest):
1039      continue  # Ignore options such as --help that aren't included in args
1040    # Ignore parameters such as paths to the binary or the list of tests
1041    if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary',
1042                       'clang', 'opt', 'llvm_bin', 'verbose'):
1043      continue
1044    value = getattr(args, action.dest)
1045    if action.const is not None:  # action stores a constant (usually True/False)
1046      # Skip actions with different constant values (this happens with boolean
1047      # --foo/--no-foo options)
1048      if value != action.const:
1049        continue
1050    if parser.get_default(action.dest) == value:
1051      continue  # Don't add default values
1052    if action.dest == 'filters':
1053      # Create a separate option for each filter element.  The value is a list
1054      # of Filter objects.
1055      for elem in value:
1056        opt_name = 'filter-out' if elem.is_filter_out else 'filter'
1057        opt_value = elem.pattern()
1058        new_arg = '--%s "%s" ' % (opt_name, opt_value.strip('"'))
1059        if new_arg not in autogenerated_note_args:
1060          autogenerated_note_args += new_arg
1061    else:
1062      autogenerated_note_args += action.option_strings[0] + ' '
1063      if action.const is None:  # action takes a parameter
1064        if action.nargs == '+':
1065          value = ' '.join(map(lambda v: '"' + v.strip('"') + '"', value))
1066        autogenerated_note_args += '%s ' % value
1067  if autogenerated_note_args:
1068    autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1])
1069  return autogenerated_note_args
1070
1071
1072def check_for_command(line, parser, args, argv, argparse_callback):
1073    cmd_m = UTC_ARGS_CMD.match(line)
1074    if cmd_m:
1075        for option in cmd_m.group('cmd').strip().split(' '):
1076            if option:
1077                argv.append(option)
1078        args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv))
1079        if argparse_callback is not None:
1080          argparse_callback(args)
1081    return args, argv
1082
1083def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global):
1084  result = get_arg_to_check(test_info.args)
1085  if not result and is_global:
1086    # See if this has been specified via UTC_ARGS.  This is a "global" option
1087    # that affects the entire generation of test checks.  If it exists anywhere
1088    # in the test, apply it to everything.
1089    saw_line = False
1090    for line_info in test_info.ro_iterlines():
1091      line = line_info.line
1092      if not line.startswith(';') and line.strip() != '':
1093        saw_line = True
1094      result = get_arg_to_check(line_info.args)
1095      if result:
1096        if warn and saw_line:
1097          # We saw the option after already reading some test input lines.
1098          # Warn about it.
1099          print('WARNING: Found {} in line following test start: '.format(arg_string)
1100                + line, file=sys.stderr)
1101          print('WARNING: Consider moving {} to top of file'.format(arg_string),
1102                file=sys.stderr)
1103        break
1104  return result
1105
1106def dump_input_lines(output_lines, test_info, prefix_set, comment_string):
1107  for input_line_info in test_info.iterlines(output_lines):
1108    line = input_line_info.line
1109    args = input_line_info.args
1110    if line.strip() == comment_string:
1111      continue
1112    if line.strip() == comment_string + SEPARATOR:
1113      continue
1114    if line.lstrip().startswith(comment_string):
1115      m = CHECK_RE.match(line)
1116      if m and m.group(1) in prefix_set:
1117        continue
1118    output_lines.append(line.rstrip('\n'))
1119
1120def add_checks_at_end(output_lines, prefix_list, func_order,
1121                      comment_string, check_generator):
1122  added = set()
1123  for prefix in prefix_list:
1124    prefixes = prefix[0]
1125    tool_args = prefix[1]
1126    for prefix in prefixes:
1127      for func in func_order[prefix]:
1128        if added:
1129          output_lines.append(comment_string)
1130        added.add(func)
1131
1132        # The add_*_checks routines expect a run list whose items are
1133        # tuples that have a list of prefixes as their first element and
1134        # tool command args string as their second element.  They output
1135        # checks for each prefix in the list of prefixes.  By doing so, it
1136        # implicitly assumes that for each function every run line will
1137        # generate something for that function.  That is not the case for
1138        # generated functions as some run lines might not generate them
1139        # (e.g. -fopenmp vs. no -fopenmp).
1140        #
1141        # Therefore, pass just the prefix we're interested in.  This has
1142        # the effect of generating all of the checks for functions of a
1143        # single prefix before moving on to the next prefix.  So checks
1144        # are ordered by prefix instead of by function as in "normal"
1145        # mode.
1146        check_generator(output_lines,
1147                        [([prefix], tool_args)],
1148                        func)
1149