1from __future__ import print_function
2
3import copy
4import glob
5import re
6import subprocess
7import sys
8
9if sys.version_info[0] > 2:
10  class string:
11    expandtabs = str.expandtabs
12else:
13  import string
14
15##### Common utilities for update_*test_checks.py
16
17
18_verbose = False
19
20def parse_commandline_args(parser):
21  parser.add_argument('--include-generated-funcs', action='store_true',
22                      help='Output checks for functions not in source')
23  parser.add_argument('-v', '--verbose', action='store_true',
24                      help='Show verbose output')
25  parser.add_argument('-u', '--update-only', action='store_true',
26                      help='Only update test if it was already autogened')
27  parser.add_argument('--force-update', action='store_true',
28                      help='Update test even if it was autogened by a different script')
29  parser.add_argument('--enable', action='store_true', dest='enabled', default=True,
30                       help='Activate CHECK line generation from this point forward')
31  parser.add_argument('--disable', action='store_false', dest='enabled',
32                      help='Deactivate CHECK line generation from this point forward')
33  args = parser.parse_args()
34  global _verbose
35  _verbose = args.verbose
36  return args
37
38
39class InputLineInfo(object):
40  def __init__(self, line, line_number, args, argv):
41    self.line = line
42    self.line_number = line_number
43    self.args = args
44    self.argv = argv
45
46
47class TestInfo(object):
48  def __init__(self, test, parser, script_name, input_lines, args, argv,
49               comment_prefix, argparse_callback):
50    self.parser = parser
51    self.argparse_callback = argparse_callback
52    self.path = test
53    self.args = args
54    self.argv = argv
55    self.input_lines = input_lines
56    self.run_lines = find_run_lines(test, self.input_lines)
57    self.comment_prefix = comment_prefix
58    if self.comment_prefix is None:
59      if self.path.endswith('.mir'):
60        self.comment_prefix = '#'
61      else:
62        self.comment_prefix = ';'
63    self.autogenerated_note_prefix = self.comment_prefix + ' ' + UTC_ADVERT
64    self.test_autogenerated_note = self.autogenerated_note_prefix + script_name
65    self.test_autogenerated_note += get_autogennote_suffix(parser, self.args)
66
67  def ro_iterlines(self):
68    for line_num, input_line in enumerate(self.input_lines):
69      args, argv = check_for_command(input_line, self.parser,
70                                     self.args, self.argv, self.argparse_callback)
71      yield InputLineInfo(input_line, line_num, args, argv)
72
73  def iterlines(self, output_lines):
74    output_lines.append(self.test_autogenerated_note)
75    for line_info in self.ro_iterlines():
76      input_line = line_info.line
77      # Discard any previous script advertising.
78      if input_line.startswith(self.autogenerated_note_prefix):
79        continue
80      self.args = line_info.args
81      self.argv = line_info.argv
82      if not self.args.enabled:
83        output_lines.append(input_line)
84        continue
85      yield line_info
86
87def itertests(test_patterns, parser, script_name, comment_prefix=None, argparse_callback=None):
88  for pattern in test_patterns:
89    # On Windows we must expand the patterns ourselves.
90    tests_list = glob.glob(pattern)
91    if not tests_list:
92      warn("Test file pattern '%s' was not found. Ignoring it." % (pattern,))
93      continue
94    for test in tests_list:
95      with open(test) as f:
96        input_lines = [l.rstrip() for l in f]
97      args = parser.parse_args()
98      if argparse_callback is not None:
99        argparse_callback(args)
100      argv = sys.argv[:]
101      first_line = input_lines[0] if input_lines else ""
102      if UTC_ADVERT in first_line:
103        if script_name not in first_line and not args.force_update:
104          warn("Skipping test which wasn't autogenerated by " + script_name, test)
105          continue
106        args, argv = check_for_command(first_line, parser, args, argv, argparse_callback)
107      elif args.update_only:
108        assert UTC_ADVERT not in first_line
109        warn("Skipping test which isn't autogenerated: " + test)
110        continue
111      yield TestInfo(test, parser, script_name, input_lines, args, argv,
112                     comment_prefix, argparse_callback)
113
114
115def should_add_line_to_output(input_line, prefix_set):
116  # Skip any blank comment lines in the IR.
117  if input_line.strip() == ';':
118    return False
119  # Skip any blank lines in the IR.
120  #if input_line.strip() == '':
121  #  return False
122  # And skip any CHECK lines. We're building our own.
123  m = CHECK_RE.match(input_line)
124  if m and m.group(1) in prefix_set:
125    return False
126
127  return True
128
129# Invoke the tool that is being tested.
130def invoke_tool(exe, cmd_args, ir):
131  with open(ir) as ir_file:
132    # TODO Remove the str form which is used by update_test_checks.py and
133    # update_llc_test_checks.py
134    # The safer list form is used by update_cc_test_checks.py
135    if isinstance(cmd_args, list):
136      stdout = subprocess.check_output([exe] + cmd_args, stdin=ir_file)
137    else:
138      stdout = subprocess.check_output(exe + ' ' + cmd_args,
139                                       shell=True, stdin=ir_file)
140    if sys.version_info[0] > 2:
141      stdout = stdout.decode()
142  # Fix line endings to unix CR style.
143  return stdout.replace('\r\n', '\n')
144
145##### LLVM IR parser
146RUN_LINE_RE = re.compile(r'^\s*(?://|[;#])\s*RUN:\s*(.*)$')
147CHECK_PREFIX_RE = re.compile(r'--?check-prefix(?:es)?[= ](\S+)')
148PREFIX_RE = re.compile('^[a-zA-Z0-9_-]+$')
149CHECK_RE = re.compile(r'^\s*(?://|[;#])\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL|-SAME|-EMPTY)?:')
150
151UTC_ARGS_KEY = 'UTC_ARGS:'
152UTC_ARGS_CMD = re.compile(r'.*' + UTC_ARGS_KEY + '\s*(?P<cmd>.*)\s*$')
153UTC_ADVERT = 'NOTE: Assertions have been autogenerated by '
154
155OPT_FUNCTION_RE = re.compile(
156    r'^(\s*;\s*Function\sAttrs:\s(?P<attrs>[\w\s]+?))?\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w.$-]+?)\s*'
157    r'(?P<args_and_sig>\((\)|(.*?[\w.-]+?)\))[^{]*\{)\n(?P<body>.*?)^\}$',
158    flags=(re.M | re.S))
159
160ANALYZE_FUNCTION_RE = re.compile(
161    r'^\s*\'(?P<analysis>[\w\s-]+?)\'\s+for\s+function\s+\'(?P<func>[\w.$-]+?)\':'
162    r'\s*\n(?P<body>.*)$',
163    flags=(re.X | re.S))
164
165IR_FUNCTION_RE = re.compile(r'^\s*define\s+(?:internal\s+)?[^@]*@"?([\w.$-]+)"?\s*\(')
166TRIPLE_IR_RE = re.compile(r'^\s*target\s+triple\s*=\s*"([^"]+)"$')
167TRIPLE_ARG_RE = re.compile(r'-mtriple[= ]([^ ]+)')
168MARCH_ARG_RE = re.compile(r'-march[= ]([^ ]+)')
169
170SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)')
171SCRUB_WHITESPACE_RE = re.compile(r'(?!^(|  \w))[ \t]+', flags=re.M)
172SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
173SCRUB_TRAILING_WHITESPACE_TEST_RE = SCRUB_TRAILING_WHITESPACE_RE
174SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE = re.compile(r'([ \t]|(#[0-9]+))+$', flags=re.M)
175SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
176SCRUB_LOOP_COMMENT_RE = re.compile(
177    r'# =>This Inner Loop Header:.*|# in Loop:.*', flags=re.M)
178SCRUB_TAILING_COMMENT_TOKEN_RE = re.compile(r'(?<=\S)+[ \t]*#$', flags=re.M)
179
180
181def error(msg, test_file=None):
182  if test_file:
183    msg = '{}: {}'.format(msg, test_file)
184  print('ERROR: {}'.format(msg), file=sys.stderr)
185
186def warn(msg, test_file=None):
187  if test_file:
188    msg = '{}: {}'.format(msg, test_file)
189  print('WARNING: {}'.format(msg), file=sys.stderr)
190
191def debug(*args, **kwargs):
192  # Python2 does not allow def debug(*args, file=sys.stderr, **kwargs):
193  if 'file' not in kwargs:
194    kwargs['file'] = sys.stderr
195  if _verbose:
196    print(*args, **kwargs)
197
198def find_run_lines(test, lines):
199  debug('Scanning for RUN lines in test file:', test)
200  raw_lines = [m.group(1)
201               for m in [RUN_LINE_RE.match(l) for l in lines] if m]
202  run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
203  for l in raw_lines[1:]:
204    if run_lines[-1].endswith('\\'):
205      run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l
206    else:
207      run_lines.append(l)
208  debug('Found {} RUN lines in {}:'.format(len(run_lines), test))
209  for l in run_lines:
210    debug('  RUN: {}'.format(l))
211  return run_lines
212
213def scrub_body(body):
214  # Scrub runs of whitespace out of the assembly, but leave the leading
215  # whitespace in place.
216  body = SCRUB_WHITESPACE_RE.sub(r' ', body)
217  # Expand the tabs used for indentation.
218  body = string.expandtabs(body, 2)
219  # Strip trailing whitespace.
220  body = SCRUB_TRAILING_WHITESPACE_TEST_RE.sub(r'', body)
221  return body
222
223def do_scrub(body, scrubber, scrubber_args, extra):
224  if scrubber_args:
225    local_args = copy.deepcopy(scrubber_args)
226    local_args[0].extra_scrub = extra
227    return scrubber(body, *local_args)
228  return scrubber(body, *scrubber_args)
229
230# Build up a dictionary of all the function bodies.
231class function_body(object):
232  def __init__(self, string, extra, args_and_sig, attrs):
233    self.scrub = string
234    self.extrascrub = extra
235    self.args_and_sig = args_and_sig
236    self.attrs = attrs
237  def is_same_except_arg_names(self, extrascrub, args_and_sig, attrs):
238    arg_names = set()
239    def drop_arg_names(match):
240        arg_names.add(match.group(3))
241        return match.group(1) + match.group(match.lastindex)
242    def repl_arg_names(match):
243        if match.group(3) is not None and match.group(3) in arg_names:
244            return match.group(1) + match.group(match.lastindex)
245        return match.group(1) + match.group(2) + match.group(match.lastindex)
246    if self.attrs != attrs:
247      return False
248    ans0 = IR_VALUE_RE.sub(drop_arg_names, self.args_and_sig)
249    ans1 = IR_VALUE_RE.sub(drop_arg_names, args_and_sig)
250    if ans0 != ans1:
251        return False
252    es0 = IR_VALUE_RE.sub(repl_arg_names, self.extrascrub)
253    es1 = IR_VALUE_RE.sub(repl_arg_names, extrascrub)
254    es0 = SCRUB_IR_COMMENT_RE.sub(r'', es0)
255    es1 = SCRUB_IR_COMMENT_RE.sub(r'', es1)
256    return es0 == es1
257
258  def __str__(self):
259    return self.scrub
260
261def get_failed_prefixes(func_dict):
262  # This returns the list of those prefixes that failed to match any function,
263  # because there were conflicting bodies produced by different RUN lines, in
264  # all instances of the prefix. Effectively, this prefix is unused and should
265  # be removed.
266  for prefix in func_dict:
267    if func_dict[prefix] and (not [fct for fct in func_dict[prefix]
268         if func_dict[prefix][fct] is not None]):
269      yield prefix
270
271def warn_on_failed_prefixes(func_dict):
272  for prefix in get_failed_prefixes(func_dict):
273      warn('Prefix %s had conflicting output from different RUN lines for all functions' % (prefix,))
274
275def build_function_body_dictionary(function_re, scrubber, scrubber_args, raw_tool_output, prefixes, func_dict, func_order, verbose, record_args, check_attributes):
276  for m in function_re.finditer(raw_tool_output):
277    if not m:
278      continue
279    func = m.group('func')
280    body = m.group('body')
281    attrs = m.group('attrs') if check_attributes else ''
282    # Determine if we print arguments, the opening brace, or nothing after the function name
283    if record_args and 'args_and_sig' in m.groupdict():
284        args_and_sig = scrub_body(m.group('args_and_sig').strip())
285    elif 'args_and_sig' in m.groupdict():
286        args_and_sig = '('
287    else:
288        args_and_sig = ''
289    scrubbed_body = do_scrub(body, scrubber, scrubber_args, extra = False)
290    scrubbed_extra = do_scrub(body, scrubber, scrubber_args, extra = True)
291    if 'analysis' in m.groupdict():
292      analysis = m.group('analysis')
293      if analysis.lower() != 'cost model analysis':
294        warn('Unsupported analysis mode: %r!' % (analysis,))
295    if func.startswith('stress'):
296      # We only use the last line of the function body for stress tests.
297      scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
298    if verbose:
299      print('Processing function: ' + func, file=sys.stderr)
300      for l in scrubbed_body.splitlines():
301        print('  ' + l, file=sys.stderr)
302    for prefix in prefixes:
303      if func in func_dict[prefix]:
304        if (func_dict[prefix][func] is None or
305            str(func_dict[prefix][func]) != scrubbed_body or
306            func_dict[prefix][func].args_and_sig != args_and_sig or
307                func_dict[prefix][func].attrs != attrs):
308          if (func_dict[prefix][func] is not None and
309              func_dict[prefix][func].is_same_except_arg_names(scrubbed_extra,
310                                                               args_and_sig,
311                                                               attrs)):
312            func_dict[prefix][func].scrub = scrubbed_extra
313            func_dict[prefix][func].args_and_sig = args_and_sig
314            continue
315          else:
316            # This means a previous RUN line produced a body for this function
317            # that is different from the one produced by this current RUN line,
318            # so the body can't be common accross RUN lines. We use None to
319            # indicate that.
320            func_dict[prefix][func] = None
321            continue
322
323      func_dict[prefix][func] = function_body(scrubbed_body, scrubbed_extra, args_and_sig, attrs)
324      func_order[prefix].append(func)
325  warn_on_failed_prefixes(func_dict)
326
327##### Generator of LLVM IR CHECK lines
328
329SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*')
330
331# TODO: We should also derive check lines for global, debug, loop declarations, etc..
332
333class NamelessValue:
334    def __init__(self, check_prefix, ir_prefix, ir_regexp):
335        self.check_prefix = check_prefix
336        self.ir_prefix = ir_prefix
337        self.ir_regexp = ir_regexp
338
339# Description of the different "unnamed" values we match in the IR, e.g.,
340# (local) ssa values, (debug) metadata, etc.
341nameless_values = [
342    NamelessValue(r'TMP',   r'%',            r'[\w.-]+?'),
343    NamelessValue(r'GLOB',  r'@',            r'[0-9]+?'),
344    NamelessValue(r'ATTR',  r'#',            r'[0-9]+?'),
345    NamelessValue(r'DBG',   r'!dbg !',       r'[0-9]+?'),
346    NamelessValue(r'TBAA',  r'!tbaa !',      r'[0-9]+?'),
347    NamelessValue(r'RNG',   r'!range !',     r'[0-9]+?'),
348    NamelessValue(r'LOOP',  r'!llvm.loop !', r'[0-9]+?'),
349    NamelessValue(r'META',  r'metadata !',   r'[0-9]+?'),
350]
351
352# Build the regexp that matches an "IR value". This can be a local variable,
353# argument, global, or metadata, anything that is "named". It is important that
354# the PREFIX and SUFFIX below only contain a single group, if that changes
355# other locations will need adjustment as well.
356IR_VALUE_REGEXP_PREFIX = r'(\s+)'
357IR_VALUE_REGEXP_STRING = r''
358for nameless_value in nameless_values:
359    if IR_VALUE_REGEXP_STRING:
360        IR_VALUE_REGEXP_STRING += '|'
361    IR_VALUE_REGEXP_STRING += nameless_value.ir_prefix + r'(' + nameless_value.ir_regexp + r')'
362IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)'
363IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX)
364
365# The entire match is group 0, the prefix has one group (=1), the entire
366# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start.
367first_nameless_group_in_ir_value_match = 3
368
369# Check a match for IR_VALUE_RE and inspect it to determine if it was a local
370# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above.
371def get_idx_from_ir_value_match(match):
372    for i in range(first_nameless_group_in_ir_value_match, match.lastindex):
373        if match.group(i) is not None:
374            return i - first_nameless_group_in_ir_value_match
375    error("Unable to identify the kind of IR value from the match!")
376    return 0;
377
378# See get_idx_from_ir_value_match
379def get_name_from_ir_value_match(match):
380    return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match)
381
382# Return the nameless prefix we use for this kind or IR value, see also
383# get_idx_from_ir_value_match
384def get_nameless_check_prefix_from_ir_value_match(match):
385    return nameless_values[get_idx_from_ir_value_match(match)].check_prefix
386
387# Return the IR prefix we use for this kind or IR value, e.g., % for locals,
388# see also get_idx_from_ir_value_match
389def get_ir_prefix_from_ir_value_match(match):
390    return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix
391
392# Return true if this kind or IR value is "local", basically if it matches '%{{.*}}'.
393def is_local_ir_value_match(match):
394    return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%'
395
396# Create a FileCheck variable name based on an IR name.
397def get_value_name(var, match):
398  if var.isdigit():
399    var = get_nameless_check_prefix_from_ir_value_match(match) + var
400  var = var.replace('.', '_')
401  var = var.replace('-', '_')
402  return var.upper()
403
404# Create a FileCheck variable from regex.
405def get_value_definition(var, match):
406  return '[[' + get_value_name(var, match) + ':' + get_ir_prefix_from_ir_value_match(match) + '.*]]'
407
408# Use a FileCheck variable.
409def get_value_use(var, match):
410  return '[[' + get_value_name(var, match) + ']]'
411
412# Replace IR value defs and uses with FileCheck variables.
413def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen):
414  # This gets called for each match that occurs in
415  # a line. We transform variables we haven't seen
416  # into defs, and variables we have seen into uses.
417  def transform_line_vars(match):
418    pre = get_ir_prefix_from_ir_value_match(match)
419    var = get_name_from_ir_value_match(match)
420    for nameless_value in nameless_values:
421        if re.match(r'^' + nameless_value.check_prefix + r'[0-9]+?$', var, re.IGNORECASE):
422            warn("Change IR value name '%s' to prevent possible conflict with scripted FileCheck name." % (var,))
423    if (pre, var) in vars_seen or (pre, var) in global_vars_seen:
424      rv = get_value_use(var, match)
425    else:
426      if is_local_ir_value_match(match):
427         vars_seen.add((pre, var))
428      else:
429         global_vars_seen.add((pre, var))
430      rv = get_value_definition(var, match)
431    # re.sub replaces the entire regex match
432    # with whatever you return, so we have
433    # to make sure to hand it back everything
434    # including the commas and spaces.
435    return match.group(1) + rv + match.group(match.lastindex)
436
437  lines_with_def = []
438
439  for i, line in enumerate(lines):
440    # An IR variable named '%.' matches the FileCheck regex string.
441    line = line.replace('%.', '%dot')
442    # Ignore any comments, since the check lines will too.
443    scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line)
444    lines[i] = scrubbed_line
445    if not is_analyze:
446      # It can happen that two matches are back-to-back and for some reason sub
447      # will not replace both of them. For now we work around this by
448      # substituting until there is no more match.
449      changed = True
450      while changed:
451          (lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1)
452  return lines
453
454
455def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze, global_vars_seen_dict):
456  # 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.
457  prefix_exclusions = set()
458  printed_prefixes = []
459  for p in prefix_list:
460    checkprefixes = p[0]
461    # If not all checkprefixes of this run line produced the function we cannot check for it as it does not
462    # exist for this run line. A subset of the check prefixes might know about the function but only because
463    # other run lines created it.
464    if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)):
465        prefix_exclusions |= set(checkprefixes)
466        continue
467
468  # prefix_exclusions is constructed, we can now emit the output
469  for p in prefix_list:
470    checkprefixes = p[0]
471    for checkprefix in checkprefixes:
472      if checkprefix in printed_prefixes:
473        break
474
475      # Check if the prefix is excluded.
476      if checkprefix in prefix_exclusions:
477        continue
478
479      # If we do not have output for this prefix we skip it.
480      if not func_dict[checkprefix][func_name]:
481        continue
482
483      # Add some space between different check prefixes, but not after the last
484      # check line (before the test code).
485      if is_asm:
486        if len(printed_prefixes) != 0:
487          output_lines.append(comment_marker)
488
489      if checkprefix not in global_vars_seen_dict:
490          global_vars_seen_dict[checkprefix] = set()
491      global_vars_seen = global_vars_seen_dict[checkprefix]
492
493      vars_seen = set()
494      printed_prefixes.append(checkprefix)
495      attrs = str(func_dict[checkprefix][func_name].attrs)
496      attrs = '' if attrs == 'None' else attrs
497      if attrs:
498        output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs))
499      args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig)
500      args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0]
501      if '[[' in args_and_sig:
502        output_lines.append(check_label_format % (checkprefix, func_name, ''))
503        output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig))
504      else:
505        output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig))
506      func_body = str(func_dict[checkprefix][func_name]).splitlines()
507
508      # For ASM output, just emit the check lines.
509      if is_asm:
510        output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
511        for func_line in func_body[1:]:
512          if func_line.strip() == '':
513            output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix))
514          else:
515            output_lines.append('%s %s-NEXT:  %s' % (comment_marker, checkprefix, func_line))
516        break
517
518      # For IR output, change all defs to FileCheck variables, so we're immune
519      # to variable naming fashions.
520      func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen)
521
522      # This could be selectively enabled with an optional invocation argument.
523      # Disabled for now: better to check everything. Be safe rather than sorry.
524
525      # Handle the first line of the function body as a special case because
526      # it's often just noise (a useless asm comment or entry label).
527      #if func_body[0].startswith("#") or func_body[0].startswith("entry:"):
528      #  is_blank_line = True
529      #else:
530      #  output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
531      #  is_blank_line = False
532
533      is_blank_line = False
534
535      for func_line in func_body:
536        if func_line.strip() == '':
537          is_blank_line = True
538          continue
539        # Do not waste time checking IR comments.
540        func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line)
541
542        # Skip blank lines instead of checking them.
543        if is_blank_line:
544          output_lines.append('{} {}:       {}'.format(
545              comment_marker, checkprefix, func_line))
546        else:
547          output_lines.append('{} {}-NEXT:  {}'.format(
548              comment_marker, checkprefix, func_line))
549        is_blank_line = False
550
551      # Add space between different check prefixes and also before the first
552      # line of code in the test function.
553      output_lines.append(comment_marker)
554      break
555
556def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict,
557                  func_name, preserve_names, function_sig, global_vars_seen_dict):
558  # Label format is based on IR string.
559  function_def_regex = 'define {{[^@]+}}' if function_sig else ''
560  check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex)
561  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
562             check_label_format, False, preserve_names, global_vars_seen_dict)
563
564def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name):
565  check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker)
566  global_vars_seen_dict = {}
567  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
568             check_label_format, False, True, global_vars_seen_dict)
569
570
571def check_prefix(prefix):
572  if not PREFIX_RE.match(prefix):
573        hint = ""
574        if ',' in prefix:
575          hint = " Did you mean '--check-prefixes=" + prefix + "'?"
576        warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) %
577             (prefix))
578
579
580def verify_filecheck_prefixes(fc_cmd):
581  fc_cmd_parts = fc_cmd.split()
582  for part in fc_cmd_parts:
583    if "check-prefix=" in part:
584      prefix = part.split('=', 1)[1]
585      check_prefix(prefix)
586    elif "check-prefixes=" in part:
587      prefixes = part.split('=', 1)[1].split(',')
588      for prefix in prefixes:
589        check_prefix(prefix)
590        if prefixes.count(prefix) > 1:
591          warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,))
592
593
594def get_autogennote_suffix(parser, args):
595  autogenerated_note_args = ''
596  for action in parser._actions:
597    if not hasattr(args, action.dest):
598      continue  # Ignore options such as --help that aren't included in args
599    # Ignore parameters such as paths to the binary or the list of tests
600    if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary',
601                       'clang', 'opt', 'llvm_bin', 'verbose'):
602      continue
603    value = getattr(args, action.dest)
604    if action.const is not None:  # action stores a constant (usually True/False)
605      # Skip actions with different constant values (this happens with boolean
606      # --foo/--no-foo options)
607      if value != action.const:
608        continue
609    if parser.get_default(action.dest) == value:
610      continue  # Don't add default values
611    autogenerated_note_args += action.option_strings[0] + ' '
612    if action.const is None:  # action takes a parameter
613      autogenerated_note_args += '%s ' % value
614  if autogenerated_note_args:
615    autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1])
616  return autogenerated_note_args
617
618
619def check_for_command(line, parser, args, argv, argparse_callback):
620    cmd_m = UTC_ARGS_CMD.match(line)
621    if cmd_m:
622        cmd = cmd_m.group('cmd').strip().split(' ')
623        argv = argv + cmd
624        args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv))
625        if argparse_callback is not None:
626          argparse_callback(args)
627    return args, argv
628
629def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global):
630  result = get_arg_to_check(test_info.args)
631  if not result and is_global:
632    # See if this has been specified via UTC_ARGS.  This is a "global" option
633    # that affects the entire generation of test checks.  If it exists anywhere
634    # in the test, apply it to everything.
635    saw_line = False
636    for line_info in test_info.ro_iterlines():
637      line = line_info.line
638      if not line.startswith(';') and line.strip() != '':
639        saw_line = True
640      result = get_arg_to_check(line_info.args)
641      if result:
642        if warn and saw_line:
643          # We saw the option after already reading some test input lines.
644          # Warn about it.
645          print('WARNING: Found {} in line following test start: '.format(arg_string)
646                + line, file=sys.stderr)
647          print('WARNING: Consider moving {} to top of file'.format(arg_string),
648                file=sys.stderr)
649        break
650  return result
651
652def dump_input_lines(output_lines, test_info, prefix_set, comment_string):
653  for input_line_info in test_info.iterlines(output_lines):
654    line = input_line_info.line
655    args = input_line_info.args
656    if line.strip() == comment_string:
657      continue
658    if line.lstrip().startswith(comment_string):
659      m = CHECK_RE.match(line)
660      if m and m.group(1) in prefix_set:
661        continue
662    output_lines.append(line.rstrip('\n'))
663
664def add_checks_at_end(output_lines, prefix_list, func_order,
665                      comment_string, check_generator):
666  added = set()
667  for prefix in prefix_list:
668    prefixes = prefix[0]
669    tool_args = prefix[1]
670    for prefix in prefixes:
671      for func in func_order[prefix]:
672        if added:
673          output_lines.append(comment_string)
674        added.add(func)
675
676        # The add_*_checks routines expect a run list whose items are
677        # tuples that have a list of prefixes as their first element and
678        # tool command args string as their second element.  They output
679        # checks for each prefix in the list of prefixes.  By doing so, it
680        # implicitly assumes that for each function every run line will
681        # generate something for that function.  That is not the case for
682        # generated functions as some run lines might not generate them
683        # (e.g. -fopenmp vs. no -fopenmp).
684        #
685        # Therefore, pass just the prefix we're interested in.  This has
686        # the effect of generating all of the checks for functions of a
687        # single prefix before moving on to the next prefix.  So checks
688        # are ordered by prefix instead of by function as in "normal"
689        # mode.
690        check_generator(output_lines,
691                        [([prefix], tool_args)],
692                        func)
693