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