Debian Codegraph @

contrib/utilities/generate_lapack_templates

raw
1 #!/usr/bin/env python3
2 """This script parses the documentation provided by LAPACK to generate a header
3 file declaring prototypes for BLAS and LAPACK functions and definitions of some
4 type-generic wrappers (e.g., four overloads for GEMM based on the input types).
5
6 To use this file: running
7
8 ./generate_lapack_templates --help
9
10 prints descriptions of the different command line arguments. In brief: this file
11 reads the three text files in lapack_templates_data/ to determine which wrappers
12 it should generate. It generates the wrappers by parsing LAPACK's documentation:
13 the location of the library must be provided (with the --lapack-root-directory
14 argument).
15
16 To add more files: simply put the name of the subroutine (without the type
17 prefix, i.e., gemv instead of dgemv) in lapack_templates_data/blas_subroutines
18 (for BLAS routines) or lapack_templates_data/lapack_subroutines (for LAPACK
19 routines). If any subroutines need to be run with floating point exceptions
20 disabled then also add them to lapack_templates_data/fp_exceptions.
21
22 """
23
24 import argparse
25 import glob
26 import os
27 import os.path as osp
28 import re
29 import sys
30 import time
31
32
33 def fortran_to_cpp_type(regex):
34 """Return a C++ type corresponding to the provided regular expression that
35 matches a FORTRAN type.
36 """
37 # TODO surely there is a better way to do this...
38 if isinstance(regex, str):
39 if regex == 'CHARACTER*1':
40 return 'char'
41 if regex == 'CHARACTER':
42 return 'char'
43 if regex == 'INTEGER':
44 return 'dealii::types::blas_int'
45 # TODO the FORTRAN standard states that LOGICAL (default KIND) should have
46 # the same storage size as INTEGER and REAL. Its not clear what happens
47 # when we have 64 bit BLAS and those are no longer equal, so this choice
48 # might not work on big-endian machines.
49 if regex == 'LOGICAL':
50 return 'dealii::types::blas_int'
51 if regex == 'REAL':
52 return 'float'
53 if regex == 'DOUBLE':
54 return 'double'
55 if regex == 'DOUBLE PRECISION':
56 return 'double'
57 if regex == 'COMPLEX':
58 return 'std::complex<float>'
59 if regex == 'COMPLEX*16':
60 return 'std::complex<double>'
61 else:
62 if regex.pattern == 'CHARACTER\\*1':
63 return 'char'
64 if regex.pattern == 'CHARACTER':
65 return 'char'
66 if regex.pattern == 'INTEGER':
67 return 'dealii::types::blas_int'
68 # TODO the FORTRAN standard states that LOGICAL (default KIND) should have
69 # the same storage size as INTEGER and REAL. Its not clear what happens
70 # when we have 64 bit BLAS and those are no longer equal, so this choice
71 # might not work on big-endian machines.
72 if regex.pattern == 'LOGICAL':
73 return 'dealii::types::blas_int'
74 if regex.pattern == 'REAL':
75 return 'float'
76 if regex.pattern == 'DOUBLE (PRECISION)?':
77 return 'double'
78 if regex.pattern == 'COMPLEX[^*]':
79 return 'std::complex<float>'
80 if regex.pattern == 'COMPLEX\\*16':
81 return 'std::complex<double>'
82
83 assert False
84 return None
85
86
87 def field_code_to_cpp(string):
88 """Convert a field code (s, d, c, or z) to a C++ type.
89 """
90 if string == 's':
91 return 'float'
92 if string == 'd':
93 return 'double'
94 if string == 'c':
95 return 'std::complex<float>'
96 if string == 'z':
97 return 'std::complex<double>'
98 assert False
99 return None
100
101
102 def field_code_to_numeric_ranking(string):
103 """Convert field codes (s, d, c, or z) to a numerical ranking that puts them in
104 that order (rather than alphabetical).
105 """
106 if string == 's':
107 return 0
108 if string == 'd':
109 return 1
110 if string == 'c':
111 return 2
112 if string == 'z':
113 return 3
114 assert False
115 return None
116
117
118 def parse_argument_constness(file_name):
119 """Read the given file to determine which arguments are const (i.e.,
120 INTENT(IN)). Since FORTRAN-77 does not support this directly we examine the
121 documentation and consider anything labeled as 'parameter[in]' as const.
122 """
123 store_line = False
124 lines = list()
125 with open(file_name, 'r') as handle:
126 for line in handle:
127 if "Arguments" in line:
128 store_line = True
129 elif "Authors" in line:
130 break
131 if store_line and "param" in line:
132 lines.append(line[3:-1])
133
134 const_parameters = list()
135 for line in lines:
136 # The LAPACK documentation might not be synchronized with the
137 # implementation, but this is the best we can do
138 if "[in]" in line:
139 const_parameters.append(line.split(' ')[-1])
140 return const_parameters
141
142
143 def parse_arguments(file_name):
144 """Parse the input arguments to a subroutine by reading its documentation.
145 """
146 store_line = False
147 lines = list()
148 with open(file_name, 'r') as handle:
149 for line in handle:
150 if "Definition" in line:
151 store_line = True
152 elif "Purpose" in line:
153 assert store_line
154 break # we are done
155
156 if store_line:
157 # remove the prepended '*'
158 lines.append(line[1:].strip())
159
160 # remove lines before 'SUBROUTINE'
161 line = lines[0]
162 while ("SUBROUTINE " not in line and "FUNCTION" not in line):
163 lines.pop(0)
164 line = lines[0]
165
166 # remove blanks and lines with dots
167 lines = list(filter(lambda u: ".." not in u and u != "", lines))
168
169 # get all subroutine arguments in one set of parentheses
170 while ')' not in lines[0]:
171 next_line = lines[1].replace('$', ' ')
172 lines[0] += ' ' + next_line
173 lines.pop(1)
174
175 # join lines that start with '$'s or when the previous line ends in ','
176 line_n = 0
177 while line_n < len(lines):
178 if '$' in lines[line_n]:
179 assert line_n > 0
180 lines[line_n - 1] += ' ' + lines[line_n][1:].strip()
181 lines.pop(line_n)
182 elif line_n > 0 and lines[line_n - 1][-1] == ',':
183 lines[line_n - 1] += ' ' + lines[line_n][1:].strip()
184 lines.pop(line_n)
185 else:
186 line_n += 1
187
188 # since everything is passed by pointer in Fortran, go ahead and delete
189 # array descriptions
190 def remove_text_in_parentheses(string):
191 """Remove all text in parentheses and parentheses themselves.
192 """
193 left_index = string.find('(')
194 if left_index != -1:
195 right_index = string.find(')')
196 assert right_index != -1
197 return remove_text_in_parentheses(string[:left_index]
198 + string[right_index + 1:])
199 return string
200
201 return [lines[0]] + list(map(remove_text_in_parentheses, lines[1:]))
202
203
204 class FortranRoutine:
205 """Class storing information about a FORTRAN subroutine or function with methods
206 to print it. Has the following members:
207
208 self.file_name : original provided file name
209
210 self.disable_floating_point_exceptions : whether or not to disable floating
211 point exceptions for the duration of the routine call
212
213 self.lines : Lightly edited (preceding '*'s removed, '$' lines joined, etc.)
214 lines from the documentation of the given function that completely describe
215 its function arguments and, if relevant, return type.
216
217 self.const_arguments : List of function arguments that correspond to const
218 pointers: this is derived from 'intent[in]' statements in the FORTRAN
219 function documentation.
220
221 self.return_type : the return type of the subroutine (always void) or
222 function (never void).
223
224 self.field_code : One-letter code ('s', 'd', 'c', or 'z') describing the
225 type of floating point inputs the function expects.
226
227 self.general_name : string containing the general name (i.e., name without
228 field code) of the subroutine or function.
229
230 self.macro_name : string containing a macro that will expand to the correct
231 symbol name.
232
233 self.arguments_by_type : A dictionary (with regular expression keys) mapping
234 regular expressions matching FORTRAN types to input arguments.
235 """
236 def __init__(self, file_name, disable_floating_point_exceptions=False):
237 self.file_name = file_name
238 self.disable_floating_point_exceptions = disable_floating_point_exceptions
239 self.lines = parse_arguments(file_name)
240 self.const_arguments = parse_argument_constness(file_name)
241
242 assert "SUBROUTINE" in self.lines[0] or "FUNCTION" in self.lines[0]
243 if "SUBROUTINE" in self.lines[0]:
244 self.return_type = "void"
245 name = self.lines[0].split()[1]
246 else:
247 function_start = self.lines[0].find("FUNCTION")
248 self.return_type = fortran_to_cpp_type(self.lines[0][:function_start].strip())
249 words = self.lines[0].split(' ')
250 while words[0] != "FUNCTION":
251 words.pop(0)
252 name = words[1]
253 parentheses_location = name.find('(')
254 if parentheses_location != -1:
255 name = name[:parentheses_location]
256
257 self.field_code = name[0].lower()
258 self.general_name = name[1:].strip().lower()
259
260 # we need a different macro for mangling FORTRAN names with underscores:
261 fortran_name = self.field_code + self.general_name
262 if "_" in fortran_name:
263 self.macro_name = "DEAL_II_FORTRAN_MANGLE_UNDERSCORE({}, {})".format(
264 fortran_name, fortran_name.upper())
265 else:
266 self.macro_name = "DEAL_II_FORTRAN_MANGLE({}, {})".format(
267 fortran_name, fortran_name.upper())
268
269 self.arguments_by_type = dict()
270 self.arguments_by_type[re.compile("CHARACTER")] = list()
271 self.arguments_by_type[re.compile("LOGICAL")] = list()
272 self.arguments_by_type[re.compile("INTEGER")] = list()
273 self.arguments_by_type[re.compile("REAL")] = list()
274 self.arguments_by_type[re.compile("DOUBLE (PRECISION)?")] = list()
275 self.arguments_by_type[re.compile("COMPLEX[^*]")] = list()
276 self.arguments_by_type[re.compile("COMPLEX\\*16")] = list()
277 # TODO one day we should support EXTERNAL
278
279 for line in self.lines:
280 found_type = False
281 if line.split() == ["IMPLICIT", "NONE"]:
282 continue
283 if "SUBROUTINE" in line or "FUNCTION" in line:
284 start = line.find('(') + 1
285 end = line.find(')')
286 self.arguments = [u.strip() for u in line[start:end].strip().split(',')]
287 found_type = True
288 else:
289 for key in self.arguments_by_type:
290 match = key.match(line)
291 if match is not None:
292 self.arguments_by_type[key] += [u.strip() for u in
293 line[match.end():].split(',')]
294 found_type = True
295 if not found_type:
296 if "EXTERNAL" in line:
297 raise NotImplementedError(
298 "The parser cannot handle EXTERNAL declarations since "
299 "FORTRAN does not provide type information in that case.")
300
301 assert found_type
302
303 def is_subroutine(self):
304 """Return whether or not the routine is a SUBROUTINE. It might also be a
305 FUNCTION, which is not yet implemented.
306 """
307 for line in self.lines:
308 if "SUBROUTINE" in line:
309 return True
310 return False
311
312 def print_prototype(self, file=sys.stdout):
313 """Print a deal.II-compatible function prototype.
314 """
315 print("", file=file)
316
317 print(self.return_type, self.macro_name, "(",
318 sep=os.linesep, end='', file=file)
319 for index, argument in enumerate(self.arguments):
320 found_type = False
321 if argument in self.const_arguments:
322 print("const ", end='', file=file)
323 for (key, arguments) in self.arguments_by_type.items():
324 if argument in arguments:
325 print(fortran_to_cpp_type(key), end='', file=file)
326 found_type = True
327
328 if not found_type:
329 import pdb
330 pdb.set_trace()
331 print(" *" + argument.lower(), end='', file=file)
332
333 if index < len(self.arguments) - 1:
334 print(", ", end='', file=file)
335 print(");", file=file)
336
337 def print_base_case_template(self, file=sys.stdout):
338 """Print a deal.II-compatible template base case. Each floating point type is
339 converting to a template parameter. This template will always throw an
340 exception, but is useful as a base case.
341
342 If there are no floating point arguments to the function (e.g., dlamch)
343 then nothing is printed."""
344 excluded_keys = [re.compile("CHARACTER"), re.compile("LOGICAL"),
345 re.compile("INTEGER")]
346 template_n = 1
347 argument_to_template_type = dict()
348
349 # assign new template types to floating point arguments:
350 for argument in self.arguments:
351 found_type = False
352 for (key, arguments) in self.arguments_by_type.items():
353 if argument in arguments:
354 if key in excluded_keys:
355 argument_to_template_type[argument] = fortran_to_cpp_type(key)
356 else:
357 argument_to_template_type[argument] = "number" + str(template_n)
358 template_n += 1
359 found_type = True
360 assert found_type
361
362 # we number templates from 1, so if we are still at 1 there are no
363 # template arguments. We add one that will also be the return type. To
364 # the best of my knowledge this only happens with DLAMCH and SLAMCH.
365 if template_n == 1:
366 n_template_types = 1
367 assert self.return_type != "void"
368 else:
369 n_template_types = template_n - 1
370
371 print("\n\n", file=file)
372 # print template signature
373 print("template <", end='', file=file)
374 for template_n in range(1, n_template_types + 1):
375 if template_n < n_template_types:
376 print("typename number" + str(template_n) + ", ", end='', file=file)
377 else:
378 print("typename number" + str(template_n) + ">", file=file)
379 print("inline ", file=file)
380 if self.return_type == "void":
381 print(self.return_type, file=file)
382 # since this function will just throw an exception whenever its called
383 # the return type is not important. This also covers the DLAMCH-like
384 # case.
385 else:
386 print("number1", file=file)
387
388 print(self.general_name, file=file)
389 print("(", end='', file=file)
390
391 # print types but not argument names
392 for index, argument in enumerate(self.arguments):
393 if argument in self.const_arguments:
394 print("const ", end='', file=file)
395 print(argument_to_template_type[argument], end='', file=file)
396
397 print(" *", end='', file=file)
398
399 if index < len(self.arguments) - 1:
400 print(", ", end='', file=file)
401
402 print(")", file=file)
403 print("{", file=file)
404 print(" Assert(false, ExcNotImplemented());", file=file)
405 if self.return_type == "void":
406 pass
407 else:
408 print(" return number1();", file=file)
409 print("}", file=file)
410
411 def print_overload_definition(self, file=sys.stdout):
412 """Print a definition of an overload for the present subroutine.
413 """
414 excluded_keys = [re.compile("CHARACTER"), re.compile("LOGICAL"),
415 re.compile("INTEGER")]
416 # We only specialize the template if there are no function arguments
417 # with which we could deduce the correct function
418 need_template = True
419 for argument in self.arguments:
420 for (key, arguments) in self.arguments_by_type.items():
421 if argument in arguments and key not in excluded_keys:
422 need_template = False
423 break
424
425 print("\n\n", file=file)
426 if need_template:
427 print("template <>", file=file)
428 print("inline {}".format(self.return_type), file=file)
429 print(self.general_name, file=file)
430 print("(", end='', file=file)
431
432 # print arguments
433 for index, argument in enumerate(self.arguments):
434 found_type = False
435 if argument in self.const_arguments:
436 print("const ", end='', file=file)
437 for (key, arguments) in self.arguments_by_type.items():
438 if argument in arguments:
439 print(fortran_to_cpp_type(key), end='', file=file)
440 found_type = True
441
442 assert found_type
443 print(" *" + argument.lower(), end='', file=file)
444
445 if index < len(self.arguments) - 1:
446 print(", ", end='', file=file)
447 print(")", file=file)
448
449 print("{", file=file)
450 print("#ifdef DEAL_II_WITH_LAPACK", file=file)
451 if self.disable_floating_point_exceptions:
452 print(" // Netlib and Atlas Lapack perform floating point ", end='', file=file)
453 print("tests (e.g. divide-by-zero)", file=file)
454 print(" // within calls to some functions, which cause ", end='', file=file)
455 print("floating point exceptions to be thrown", file=file)
456 print(" // (at least in debug mode). Therefore, we wrap the ", end='', file=file)
457 print("calls into the following ", file=file)
458 print(" // code to suppress the exception.", file=file)
459 print("#ifdef DEAL_II_HAVE_FP_EXCEPTIONS", file=file)
460 print("fenv_t fp_exceptions;", file=file)
461 print("feholdexcept(&fp_exceptions);", file=file)
462 print("#endif // DEAL_II_HAVE_FP_EXCEPTIONS", file=file)
463 # call the Fortran function
464 if self.return_type == "void":
465 print(" ", end='', file=file)
466 else:
467 print(" return ", end='', file=file)
468 print(self.macro_name + "(", end='', file=file)
469 for index, argument in enumerate(self.arguments):
470 print(argument.lower(), end='', file=file)
471
472 if index < len(self.arguments) - 1:
473 print(", ", end='', file=file)
474 print(");", file=file)
475
476 if self.disable_floating_point_exceptions:
477 print("#ifdef DEAL_II_HAVE_FP_EXCEPTIONS", file=file)
478 print("fesetenv(&fp_exceptions);", file=file)
479 print("#endif // DEAL_II_HAVE_FP_EXCEPTIONS", file=file)
480
481 print("#else", file=file)
482 for argument in self.arguments:
483 print(" (void){};".format(argument.lower()), file=file)
484 print(" Assert(false, LAPACKSupport::ExcMissing(\"{}\"));"
485 .format(self.field_code + self.general_name), file=file)
486 if self.return_type != "void":
487 print(" return {}();".format(self.return_type), file=file)
488 print("#endif // DEAL_II_WITH_LAPACK", file=file)
489 print("}", file=file)
490
491 def __repr__(self):
492 """Representation of the object.
493 """
494 return self.field_code + self.general_name
495
496
497 def main():
498 """Determine the subroutines and then print needed declarations and definitions
499 to the header.
500 """
501 parser = argparse.ArgumentParser(
502 description=("Automatically generate deal.II-compatible template BLAS "
503 + "and LAPACK wrappers by parsing the documentation provided "
504 + " by each library. The best way to get this documentation "
505 + "is to clone the LAPACK development sources available at "
506 + "https://github.com/Reference-LAPACK and then pass the "
507 + "root directory location to this program with the "
508 + "--lapack-root-directory option."))
509 lapack_subroutines = list()
510 blas_subroutines = list()
511 fp_guarded_subroutines = list()
512 parser.add_argument("--lapack-root-directory", type=str,
513 help="Path of the LAPACK source root directory.")
514 parser.add_argument("--lapack-subroutines", type=str,
515 help="file listing which LAPACK subroutines we should "
516 "wrap. Defaults to 'lapack_templates_data/lapack_subroutines' "
517 "in the current directory.")
518 parser.add_argument("--blas-subroutines", type=str,
519 help="file listing which BLAS subroutines we should "
520 "wrap. Defaults to 'lapack_templates_data/blas_subroutines' "
521 "in the current directory.")
522 parser.add_argument("--fp-guarded-subroutines", type=str,
523 help="Subroutines which should be wrapped with "
524 "disabling and enabling of floating point exceptions. "
525 "Defaults to 'lapack_templates_data/fp_subroutines' in "
526 "the current directory.")
527 parser.add_argument("--output-file", type=str,
528 help="File to which we write. Defaults to "
529 "'lapack_templates.h' in the current directory.")
530 args = vars(parser.parse_args())
531
532 if args["lapack_root_directory"] is None:
533 raise ValueError("The path to the default LAPACK directory must be "
534 "specified.")
535
536 if args["blas_subroutines"] is None:
537 args["blas_subroutines"] = "lapack_templates_data/blas_subroutines"
538 if args["lapack_subroutines"] is None:
539 args["lapack_subroutines"] = "lapack_templates_data/lapack_subroutines"
540 if args["fp_guarded_subroutines"] is None:
541 args["fp_guarded_subroutines"] = "lapack_templates_data/fp_subroutines"
542 if args["output_file"] is None:
543 args["output_file"] = "lapack_templates.h"
544
545 with open(args["lapack_subroutines"]) as lapack_handle:
546 for line in lapack_handle:
547 lapack_subroutines.append(line.strip())
548 with open(args["blas_subroutines"]) as blas_handle:
549 for line in blas_handle:
550 blas_subroutines.append(line.strip())
551 with open(args["fp_guarded_subroutines"]) as fp_handle:
552 for line in fp_handle:
553 fp_guarded_subroutines.append(line.strip())
554
555 #
556 # Parse subroutines:
557 #
558 routines = list()
559 all_general_routines = blas_subroutines + lapack_subroutines
560 for [general_routines, routine_directory] in [
561 [lapack_subroutines, args["lapack_root_directory"] + "/SRC/"],
562 # dlamch and slamch are in the INSTALL directory
563 [lapack_subroutines, args["lapack_root_directory"] + "/INSTALL/"],
564 [blas_subroutines, args["lapack_root_directory"] + "/BLAS/SRC/"]]:
565 for general_routine in general_routines:
566 globs = glob.glob(routine_directory + "*" + general_routine + ".f")
567 for file_name in globs:
568 try:
569 routine_name = osp.basename(file_name)[1:-2]
570 guard_fp = routine_name in fp_guarded_subroutines
571 routines.append(FortranRoutine(file_name, guard_fp))
572 except NotImplementedError:
573 # Not a lot we can do. If its in the allowed list we will fail
574 # again later anyway
575 continue
576 routines.sort(key=lambda u: u.general_name)
577
578 #
579 # Collect subroutines together that have the same general name
580 #
581 organized_routines = list()
582 organized_routines.append([routines[0]])
583 for routine in routines[1:]:
584 if routine.general_name == organized_routines[-1][0].general_name:
585 organized_routines[-1].append(routine)
586 else:
587 organized_routines.append([routine])
588 #
589 # sort by type (s, d, c z)
590 #
591 for routine_list in organized_routines:
592 routine_list.sort(key=lambda a: field_code_to_numeric_ranking(a.field_code))
593
594 #
595 # Generate output
596 #
597 with open(args["output_file"], 'w') as output:
598 print("// ------------------------------------------------------------------------",
599 file=output)
600 print("//",
601 file=output)
602 year = time.ctime().split(' ')[-1]
603 print("// SPDX-License-Identifier: LGPL-2.1-or-later",
604 file=output)
605 print("// Copyright (C) 2005 - {} by the deal.II authors".format(year),
606 file=output)
607 print("//",
608 file=output)
609 print("// This file is part of the deal.II library.",
610 file=output)
611 print("//",
612 file=output)
613 print("// Part of the source code is dual licensed under Apache-2.0 WITH",
614 file=output)
615 print("// LLVM-exception OR LGPL-2.1-or-later. Detailed license information",
616 file=output)
617 print("// governing the source code and code contributions can be found in",
618 file=output)
619 print("// LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.",
620 file=output)
621 print("//",
622 file=output)
623 print("// ------------------------------------------------------------------------------",
624 file=output)
625
626 print("", file=output)
627 print("", file=output)
628 print("#ifndef dealii_lapack_templates_h", file=output)
629 print("#define dealii_lapack_templates_h", file=output)
630 print("", file=output)
631 print("#include <deal.II/base/config.h>", file=output)
632 print("", file=output)
633 print("#include <deal.II/lac/lapack_support.h>", file=output)
634 print("", file=output)
635 print("#ifdef DEAL_II_HAVE_FP_EXCEPTIONS", file=output)
636 print("# include <cfenv>", file=output)
637 print("#endif", file=output)
638
639 print("", file=output)
640 print("extern \"C\"", file=output)
641 print("{", file=output)
642 for routine_list in organized_routines:
643 if routine_list[0].general_name in all_general_routines:
644 for routine in routine_list:
645 routine.print_prototype(file=output)
646 print("}", file=output)
647
648 print("", file=output)
649 print("DEAL_II_NAMESPACE_OPEN", file=output)
650 print("", file=output)
651 for routine_list in organized_routines:
652 if routine_list[0].general_name in all_general_routines:
653 routine_list[0].print_base_case_template(file=output)
654 for routine in routine_list:
655 routine.print_overload_definition(file=output)
656
657 print("DEAL_II_NAMESPACE_CLOSE", file=output)
658 print("", file=output)
659 print("#endif", file=output)
660
661
662 if __name__ == '__main__':
663 main()