520cc8
Partial backport of:
520cc8
520cc8
commit 7e1d42400c1b8f03316fe14176133c8853cd3bbe
520cc8
Author: Joseph Myers <joseph@codesourcery.com>
520cc8
Date:   Fri Nov 30 15:20:41 2018 +0000
520cc8
520cc8
    Replace gen-as-const.awk by gen-as-const.py.
520cc8
    
520cc8
    This patch replaces gen-as-const.awk, and some fragments of the
520cc8
    Makefile code that used it, by a Python script.  The point is not such
520cc8
    much that awk is problematic for this particular script, as that I'd
520cc8
    like to build up a general Python infrastructure for extracting
520cc8
    information from C headers, for use in writing tests of such headers.
520cc8
    Thus, although this patch does not set up such infrastructure, the
520cc8
    compute_c_consts function in gen-as-const.py might be moved to a
520cc8
    separate Python module in a subsequent patch as a starting point for
520cc8
    such infrastructure.
520cc8
    
520cc8
    The general idea of the code is the same as in the awk version, but no
520cc8
    attempt is made to make the output files textually identical.  When
520cc8
    generating a header, a dict of constant names and values is generated
520cc8
    internally then defines are printed in sorted order (rather than the
520cc8
    order in the .sym file, which would have been used before).  When
520cc8
    generating a test that the values computed match those from a normal
520cc8
    header inclusion, the test code is made into a compilation test using
520cc8
    _Static_assert, where previously the comparisons were done only when
520cc8
    the test was executed.  One fragment of test generation (converting
520cc8
    the previously generated header to use asconst_* prefixes on its macro
520cc8
    names) is still in awk code in the makefiles; only the .sym processing
520cc8
    and subsequent execution of the compiler to extract constants have
520cc8
    moved to the Python script.
520cc8
    
520cc8
    Tested for x86_64, and with build-many-glibcs.py.
520cc8
    
520cc8
            * scripts/gen-as-const.py: New file.
520cc8
            * scripts/gen-as-const.awk: Remove.
520cc8
            * Makerules ($(common-objpfx)%.h $(common-objpfx)%.h.d): Use
520cc8
            gen-as-const.py.
520cc8
            ($(objpfx)test-as-const-%.c): Likewise.
520cc8
520cc8
In the downstream version, scripts/gen-as-const.awk is not removed and
520cc8
still used in Makerules.
520cc8
520cc8
diff --git a/scripts/gen-as-const.py b/scripts/gen-as-const.py
520cc8
new file mode 100644
520cc8
index 0000000000000000..b7a5744bb192dd67
520cc8
--- /dev/null
520cc8
+++ b/scripts/gen-as-const.py
520cc8
@@ -0,0 +1,159 @@
520cc8
+#!/usr/bin/python3
520cc8
+# Produce headers of assembly constants from C expressions.
520cc8
+# Copyright (C) 2018 Free Software Foundation, Inc.
520cc8
+# This file is part of the GNU C Library.
520cc8
+#
520cc8
+# The GNU C Library is free software; you can redistribute it and/or
520cc8
+# modify it under the terms of the GNU Lesser General Public
520cc8
+# License as published by the Free Software Foundation; either
520cc8
+# version 2.1 of the License, or (at your option) any later version.
520cc8
+#
520cc8
+# The GNU C Library is distributed in the hope that it will be useful,
520cc8
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
520cc8
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
520cc8
+# Lesser General Public License for more details.
520cc8
+#
520cc8
+# You should have received a copy of the GNU Lesser General Public
520cc8
+# License along with the GNU C Library; if not, see
520cc8
+# <http://www.gnu.org/licenses/>.
520cc8
+
520cc8
+# The input to this script looks like:
520cc8
+#       #cpp-directive ...
520cc8
+#       NAME1
520cc8
+#       NAME2 expression ...
520cc8
+# A line giving just a name implies an expression consisting of just that name.
520cc8
+
520cc8
+import argparse
520cc8
+import os.path
520cc8
+import re
520cc8
+import subprocess
520cc8
+import tempfile
520cc8
+
520cc8
+
520cc8
+def compute_c_consts(sym_data, cc):
520cc8
+    """Compute the values of some C constants.
520cc8
+
520cc8
+    The first argument is a list whose elements are either strings
520cc8
+    (preprocessor directives) or pairs of strings (a name and a C
520cc8
+    expression for the corresponding value).  Preprocessor directives
520cc8
+    in the middle of the list may be used to select which constants
520cc8
+    end up being evaluated using which expressions.
520cc8
+
520cc8
+    """
520cc8
+    out_lines = []
520cc8
+    started = False
520cc8
+    for arg in sym_data:
520cc8
+        if isinstance(arg, str):
520cc8
+            out_lines.append(arg)
520cc8
+            continue
520cc8
+        name = arg[0]
520cc8
+        value = arg[1]
520cc8
+        if not started:
520cc8
+            out_lines.append('void\ndummy (void)\n{')
520cc8
+            started = True
520cc8
+        out_lines.append('asm ("@@@name@@@%s@@@value@@@%%0@@@end@@@" '
520cc8
+                         ': : \"i\" ((long int) (%s)));'
520cc8
+                         % (name, value))
520cc8
+    if started:
520cc8
+        out_lines.append('}')
520cc8
+    out_lines.append('')
520cc8
+    out_text = '\n'.join(out_lines)
520cc8
+    with tempfile.TemporaryDirectory() as temp_dir:
520cc8
+        c_file_name = os.path.join(temp_dir, 'test.c')
520cc8
+        s_file_name = os.path.join(temp_dir, 'test.s')
520cc8
+        with open(c_file_name, 'w') as c_file:
520cc8
+            c_file.write(out_text)
520cc8
+        # Compilation has to be from stdin to avoid the temporary file
520cc8
+        # name being written into the generated dependencies.
520cc8
+        cmd = ('%s -S -o %s -x c - < %s' % (cc, s_file_name, c_file_name))
520cc8
+        subprocess.check_call(cmd, shell=True)
520cc8
+        consts = {}
520cc8
+        with open(s_file_name, 'r') as s_file:
520cc8
+            for line in s_file:
520cc8
+                match = re.search('@@@name@@@([^@]*)'
520cc8
+                                  '@@@value@@@[^0-9Xxa-fA-F-]*'
520cc8
+                                  '([0-9Xxa-fA-F-]+).*@@@end@@@', line)
520cc8
+                if match:
520cc8
+                    if (match.group(1) in consts
520cc8
+                        and match.group(2) != consts[match.group(1)]):
520cc8
+                        raise ValueError('duplicate constant %s'
520cc8
+                                         % match.group(1))
520cc8
+                    consts[match.group(1)] = match.group(2)
520cc8
+        return consts
520cc8
+
520cc8
+
520cc8
+def gen_test(sym_data):
520cc8
+    """Generate a test for the values of some C constants.
520cc8
+
520cc8
+    The first argument is as for compute_c_consts.
520cc8
+
520cc8
+    """
520cc8
+    out_lines = []
520cc8
+    started = False
520cc8
+    for arg in sym_data:
520cc8
+        if isinstance(arg, str):
520cc8
+            out_lines.append(arg)
520cc8
+            continue
520cc8
+        name = arg[0]
520cc8
+        value = arg[1]
520cc8
+        if not started:
520cc8
+            out_lines.append('#include <stdint.h>\n'
520cc8
+                             '#include <stdio.h>\n'
520cc8
+                             '#include <bits/wordsize.h>\n'
520cc8
+                             '#if __WORDSIZE == 64\n'
520cc8
+                             'typedef uint64_t c_t;\n'
520cc8
+                             '# define U(n) UINT64_C (n)\n'
520cc8
+                             '#else\n'
520cc8
+                             'typedef uint32_t c_t;\n'
520cc8
+                             '# define U(n) UINT32_C (n)\n'
520cc8
+                             '#endif\n'
520cc8
+                             'static int\n'
520cc8
+                             'do_test (void)\n'
520cc8
+                             '{\n'
520cc8
+                             # Compilation test only, using static assertions.
520cc8
+                             '  return 0;\n'
520cc8
+                             '}\n'
520cc8
+                             '#include <support/test-driver.c>')
520cc8
+            started = True
520cc8
+        out_lines.append('_Static_assert (U (asconst_%s) == (c_t) (%s), '
520cc8
+                         '"value of %s");'
520cc8
+                         % (name, value, name))
520cc8
+    return '\n'.join(out_lines)
520cc8
+
520cc8
+
520cc8
+def main():
520cc8
+    """The main entry point."""
520cc8
+    parser = argparse.ArgumentParser(
520cc8
+        description='Produce headers of assembly constants.')
520cc8
+    parser.add_argument('--cc', metavar='CC',
520cc8
+                        help='C compiler (including options) to use')
520cc8
+    parser.add_argument('--test', action='store_true',
520cc8
+                        help='Generate test case instead of header')
520cc8
+    parser.add_argument('sym_file',
520cc8
+                        help='.sym file to process')
520cc8
+    args = parser.parse_args()
520cc8
+    sym_data = []
520cc8
+    with open(args.sym_file, 'r') as sym_file:
520cc8
+        for line in sym_file:
520cc8
+            line = line.strip()
520cc8
+            if line == '':
520cc8
+                continue
520cc8
+            # Pass preprocessor directives through.
520cc8
+            if line.startswith('#'):
520cc8
+                sym_data.append(line)
520cc8
+                continue
520cc8
+            words = line.split(maxsplit=1)
520cc8
+            # Separator.
520cc8
+            if words[0] == '--':
520cc8
+                continue
520cc8
+            name = words[0]
520cc8
+            value = words[1] if len(words) > 1 else words[0]
520cc8
+            sym_data.append((name, value))
520cc8
+    if args.test:
520cc8
+        print(gen_test(sym_data))
520cc8
+    else:
520cc8
+        consts = compute_c_consts(sym_data, args.cc)
520cc8
+        print('\n'.join('#define %s %s' % c for c in sorted(consts.items())))
520cc8
+
520cc8
+if __name__ == '__main__':
520cc8
+    main()