d: Add testcase from PR108962
[official-gcc.git] / gcc / gengtype.cc
blob7763f40e9abc9b5ce72a2b0136405b2ec5c41789
1 /* Process source files and output type information.
2 Copyright (C) 2002-2023 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #ifdef HOST_GENERATOR_FILE
21 #include "config.h"
22 #define GENERATOR_FILE 1
23 #else
24 #include "bconfig.h"
25 #endif
26 #include "system.h"
27 #include "errors.h" /* for fatal */
28 #include "getopt.h"
29 #include "version.h" /* for version_string & pkgversion_string. */
30 #include "xregex.h"
31 #include "obstack.h"
32 #include "gengtype.h"
33 #include "filenames.h"
35 /* Data types, macros, etc. used only in this file. */
38 /* The list of output files. */
39 outf_p output_files;
41 /* The output header file that is included into pretty much every
42 source file. */
43 outf_p header_file;
46 /* The name of the file containing the list of input files. */
47 static char *inputlist;
49 /* The plugin input files and their number; in that case only
50 a single file is produced. */
51 static input_file **plugin_files;
52 static size_t nb_plugin_files;
54 /* The generated plugin output file and name. */
55 static outf_p plugin_output;
56 static char *plugin_output_filename;
58 /* Our source directory and its length. */
59 const char *srcdir;
60 size_t srcdir_len;
62 /* Variables used for reading and writing the state. */
63 const char *read_state_filename;
64 const char *write_state_filename;
66 /* Variables to help debugging. */
67 int do_dump;
68 int do_debug;
70 /* Level for verbose messages. */
71 int verbosity_level;
73 /* We have a type count and use it to set the state_number of newly
74 allocated types to some unique negative number. */
75 static int type_count;
77 /* The backup directory should be in the same file system as the
78 generated files, otherwise the rename(2) system call would fail.
79 If NULL, no backup is made when overwriting a generated file. */
80 static const char* backup_dir; /* (-B) program option. */
83 static outf_p create_file (const char *, const char *);
85 static const char *get_file_basename (const input_file *);
86 static const char *get_file_realbasename (const input_file *);
88 static int get_prefix_langdir_index (const char *);
89 static const char *get_file_langdir (const input_file *);
91 static void dump_pair (int indent, pair_p p);
92 static void dump_type (int indent, type_p p);
93 static void dump_type_list (int indent, type_p p);
96 /* Nonzero iff an error has occurred. */
97 bool hit_error = false;
99 static void gen_rtx_next (void);
100 static void write_rtx_next (void);
101 static void open_base_files (void);
102 static void close_output_files (void);
104 /* Report an error at POS, printing MSG. */
106 void
107 error_at_line (const struct fileloc *pos, const char *msg, ...)
109 va_list ap;
111 gcc_assert (pos != NULL && pos->file != NULL);
112 va_start (ap, msg);
114 fprintf (stderr, "%s:%d: ", get_input_file_name (pos->file), pos->line);
115 vfprintf (stderr, msg, ap);
116 fputc ('\n', stderr);
117 hit_error = true;
119 va_end (ap);
122 /* Locate the ultimate base class of struct S. */
124 static const_type_p
125 get_ultimate_base_class (const_type_p s)
127 while (s->u.s.base_class)
128 s = s->u.s.base_class;
129 return s;
132 static type_p
133 get_ultimate_base_class (type_p s)
135 while (s->u.s.base_class)
136 s = s->u.s.base_class;
137 return s;
140 /* Input file handling. */
142 /* Table of all input files. */
143 const input_file **gt_files;
144 size_t num_gt_files;
146 /* Table of headers to be included in gtype-desc.cc that are generated
147 during the build. These are identified as "./<filename>.h". */
148 const char **build_headers;
149 size_t num_build_headers;
151 /* A number of places use the name of this "gengtype.cc" file for a
152 location for things that we can't rely on the source to define.
153 Make sure we can still use pointer comparison on filenames. */
154 input_file* this_file;
155 /* The "system.h" file is likewise specially useful. */
156 input_file* system_h_file;
158 /* Vector of per-language directories. */
159 const char **lang_dir_names;
160 size_t num_lang_dirs;
162 /* An array of output files suitable for definitions. There is one
163 BASE_FILES entry for each language. */
164 static outf_p *base_files;
166 /* Utility debugging function, printing the various type counts within
167 a list of types. Called through the DBGPRINT_COUNT_TYPE macro. */
168 void
169 dbgprint_count_type_at (const char *fil, int lin, const char *msg, type_p t)
171 int nb_types = 0, nb_scalar = 0, nb_string = 0;
172 int nb_struct = 0, nb_union = 0, nb_array = 0, nb_pointer = 0;
173 int nb_lang_struct = 0;
174 int nb_user_struct = 0, nb_undefined = 0;
175 int nb_callback = 0;
176 type_p p = NULL;
177 for (p = t; p; p = p->next)
179 nb_types++;
180 switch (p->kind)
182 case TYPE_UNDEFINED:
183 nb_undefined++;
184 break;
185 case TYPE_SCALAR:
186 nb_scalar++;
187 break;
188 case TYPE_STRING:
189 nb_string++;
190 break;
191 case TYPE_STRUCT:
192 nb_struct++;
193 break;
194 case TYPE_USER_STRUCT:
195 nb_user_struct++;
196 break;
197 case TYPE_UNION:
198 nb_union++;
199 break;
200 case TYPE_POINTER:
201 nb_pointer++;
202 break;
203 case TYPE_ARRAY:
204 nb_array++;
205 break;
206 case TYPE_CALLBACK:
207 nb_callback++;
208 break;
209 case TYPE_LANG_STRUCT:
210 nb_lang_struct++;
211 break;
212 case TYPE_NONE:
213 gcc_unreachable ();
216 fprintf (stderr, "\n" "%s:%d: %s: @@%%@@ %d types ::\n",
217 lbasename (fil), lin, msg, nb_types);
218 if (nb_scalar > 0 || nb_string > 0)
219 fprintf (stderr, "@@%%@@ %d scalars, %d strings\n", nb_scalar, nb_string);
220 if (nb_struct > 0 || nb_union > 0)
221 fprintf (stderr, "@@%%@@ %d structs, %d unions\n", nb_struct, nb_union);
222 if (nb_pointer > 0 || nb_array > 0)
223 fprintf (stderr, "@@%%@@ %d pointers, %d arrays\n", nb_pointer, nb_array);
224 if (nb_callback > 0)
225 fprintf (stderr, "@@%%@@ %d callbacks\n", nb_callback);
226 if (nb_lang_struct > 0)
227 fprintf (stderr, "@@%%@@ %d lang_structs\n", nb_lang_struct);
228 if (nb_user_struct > 0)
229 fprintf (stderr, "@@%%@@ %d user_structs\n", nb_user_struct);
230 if (nb_undefined > 0)
231 fprintf (stderr, "@@%%@@ %d undefined types\n", nb_undefined);
232 fprintf (stderr, "\n");
235 /* Scan the input file, LIST, and determine how much space we need to
236 store strings in. Also, count the number of language directories
237 and files. The numbers returned are overestimates as they does not
238 consider repeated files. */
239 static size_t
240 measure_input_list (FILE *list)
242 size_t n = 0;
243 int c;
244 bool atbol = true;
245 num_lang_dirs = 0;
246 num_gt_files = plugin_files ? nb_plugin_files : 0;
247 while ((c = getc (list)) != EOF)
249 n++;
250 if (atbol)
252 if (c == '[')
253 num_lang_dirs++;
254 else
256 /* Add space for a lang_bitmap before the input file name. */
257 n += sizeof (lang_bitmap);
258 num_gt_files++;
260 atbol = false;
263 if (c == '\n')
264 atbol = true;
267 rewind (list);
268 return n;
271 /* Read one input line from LIST to HEREP (which is updated). A
272 pointer to the string is returned via LINEP. If it was a language
273 subdirectory in square brackets, strip off the square brackets and
274 return true. Otherwise, leave space before the string for a
275 lang_bitmap, and return false. At EOF, returns false, does not
276 touch *HEREP, and sets *LINEP to NULL. POS is used for
277 diagnostics. */
278 static bool
279 read_input_line (FILE *list, char **herep, char **linep, struct fileloc *pos)
281 char *here = *herep;
282 char *line;
283 int c = getc (list);
285 /* Read over whitespace. */
286 while (c == '\n' || c == ' ')
287 c = getc (list);
289 if (c == EOF)
291 *linep = 0;
292 return false;
294 else if (c == '[')
296 /* No space for a lang_bitmap is necessary. Discard the '['. */
297 c = getc (list);
298 line = here;
299 while (c != ']' && c != '\n' && c != EOF)
301 *here++ = c;
302 c = getc (list);
304 *here++ = '\0';
306 if (c == ']')
308 c = getc (list); /* eat what should be a newline */
309 if (c != '\n' && c != EOF)
310 error_at_line (pos, "junk on line after language tag [%s]", line);
312 else
313 error_at_line (pos, "missing close bracket for language tag [%s",
314 line);
316 *herep = here;
317 *linep = line;
318 return true;
320 else
322 /* Leave space for a lang_bitmap. */
323 memset (here, 0, sizeof (lang_bitmap));
324 here += sizeof (lang_bitmap);
325 line = here;
328 *here++ = c;
329 c = getc (list);
331 while (c != EOF && c != '\n');
332 *here++ = '\0';
333 *herep = here;
334 *linep = line;
335 return false;
339 /* Read the list of input files from LIST and compute all of the
340 relevant tables. There is one file per line of the list. At
341 first, all the files on the list are language-generic, but
342 eventually a line will appear which is the name of a language
343 subdirectory in square brackets, like this: [cp]. All subsequent
344 files are specific to that language, until another language
345 subdirectory tag appears. Files can appear more than once, if
346 they apply to more than one language. */
347 static void
348 read_input_list (const char *listname)
350 FILE *list = fopen (listname, "r");
351 if (!list)
352 fatal ("cannot open %s: %s", listname, xstrerror (errno));
353 else
355 struct fileloc epos;
356 size_t bufsz = measure_input_list (list);
357 char *buf = XNEWVEC (char, bufsz);
358 char *here = buf;
359 char *committed = buf;
360 char *limit = buf + bufsz;
361 char *line;
362 bool is_language;
363 size_t langno = 0;
364 size_t nfiles = 0;
365 lang_bitmap curlangs = (1 << num_lang_dirs) - 1;
367 epos.file = input_file_by_name (listname);
368 epos.line = 0;
370 lang_dir_names = XNEWVEC (const char *, num_lang_dirs);
371 gt_files = XNEWVEC (const input_file *, num_gt_files);
373 for (;;)
375 next_line:
376 epos.line++;
377 committed = here;
378 is_language = read_input_line (list, &here, &line, &epos);
379 gcc_assert (here <= limit);
380 if (line == 0)
381 break;
382 else if (is_language)
384 size_t i;
385 gcc_assert (langno <= num_lang_dirs);
386 for (i = 0; i < langno; i++)
387 if (strcmp (lang_dir_names[i], line) == 0)
389 error_at_line (&epos, "duplicate language tag [%s]",
390 line);
391 curlangs = 1 << i;
392 here = committed;
393 goto next_line;
396 curlangs = 1 << langno;
397 lang_dir_names[langno++] = line;
399 else
401 size_t i;
402 input_file *inpf = input_file_by_name (line);
403 gcc_assert (nfiles <= num_gt_files);
404 for (i = 0; i < nfiles; i++)
405 /* Since the input_file-s are uniquely hash-consed, we
406 can just compare pointers! */
407 if (gt_files[i] == inpf)
409 /* Throw away the string we just read, and add the
410 current language to the existing string's bitmap. */
411 lang_bitmap bmap = get_lang_bitmap (inpf);
412 if (bmap & curlangs)
413 error_at_line (&epos,
414 "file %s specified more than once "
415 "for language %s", line,
416 langno ==
417 0 ? "(all)" : lang_dir_names[langno -
418 1]);
420 bmap |= curlangs;
421 set_lang_bitmap (inpf, bmap);
422 here = committed;
423 goto next_line;
426 set_lang_bitmap (inpf, curlangs);
427 gt_files[nfiles++] = inpf;
430 /* Update the global counts now that we know accurately how many
431 things there are. (We do not bother resizing the arrays down.) */
432 num_lang_dirs = langno;
433 /* Add the plugin files if provided. */
434 if (plugin_files)
436 size_t i;
437 for (i = 0; i < nb_plugin_files; i++)
438 gt_files[nfiles++] = plugin_files[i];
440 num_gt_files = nfiles;
443 /* Sanity check: any file that resides in a language subdirectory
444 (e.g. 'cp') ought to belong to the corresponding language.
445 ??? Still true if for instance ObjC++ is enabled and C++ isn't?
446 (Can you even do that? Should you be allowed to?) */
448 size_t f;
449 for (f = 0; f < num_gt_files; f++)
451 lang_bitmap bitmap = get_lang_bitmap (gt_files[f]);
452 const char *basename = get_file_basename (gt_files[f]);
453 const char *slashpos = strchr (basename, '/');
454 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
455 const char *slashpos2 = strchr (basename, '\\');
457 if (!slashpos || (slashpos2 && slashpos2 < slashpos))
458 slashpos = slashpos2;
459 #endif
461 if (slashpos)
463 size_t l;
464 for (l = 0; l < num_lang_dirs; l++)
465 if ((size_t) (slashpos - basename) == strlen (lang_dir_names[l])
466 && memcmp (basename, lang_dir_names[l],
467 strlen (lang_dir_names[l])) == 0)
469 if (!(bitmap & (1 << l)))
470 error ("%s is in language directory '%s' but is not "
471 "tagged for that language",
472 basename, lang_dir_names[l]);
473 break;
479 if (ferror (list))
480 fatal ("error reading %s: %s", listname, xstrerror (errno));
482 fclose (list);
487 /* The one and only TYPE_STRING. */
489 struct type string_type = {
490 TYPE_STRING, 0, 0, 0, GC_USED, {0}
493 /* The two and only TYPE_SCALARs. Their u.scalar_is_char flags are
494 set early in main. */
496 struct type scalar_nonchar = {
497 TYPE_SCALAR, 0, 0, 0, GC_USED, {0}
500 struct type scalar_char = {
501 TYPE_SCALAR, 0, 0, 0, GC_USED, {0}
504 struct type callback_type = {
505 TYPE_CALLBACK, 0, 0, 0, GC_USED, {0}
508 /* Lists of various things. */
510 pair_p typedefs = NULL;
511 type_p structures = NULL;
512 pair_p variables = NULL;
514 static type_p adjust_field_rtx_def (type_p t, options_p opt);
516 /* Define S as a typedef to T at POS. */
518 void
519 do_typedef (const char *s, type_p t, struct fileloc *pos)
521 pair_p p;
523 /* temporary kludge - gengtype doesn't handle conditionals or
524 macros. Ignore any attempt to typedef CUMULATIVE_ARGS, unless it
525 is coming from this file (main() sets them up with safe dummy
526 definitions). */
527 if (!strcmp (s, "CUMULATIVE_ARGS") && pos->file != this_file)
528 return;
530 for (p = typedefs; p != NULL; p = p->next)
531 if (strcmp (p->name, s) == 0)
533 if (p->type != t && strcmp (s, "result_type") != 0)
535 error_at_line (pos, "type `%s' previously defined", s);
536 error_at_line (&p->line, "previously defined here");
538 return;
541 p = XNEW (struct pair);
542 p->next = typedefs;
543 p->name = s;
544 p->type = t;
545 p->line = *pos;
546 p->opt = NULL;
547 typedefs = p;
550 /* Define S as a typename of a scalar. Cannot be used to define
551 typedefs of 'char'. Note: is also used for pointer-to-function
552 typedefs (which are therefore not treated as pointers). */
554 void
555 do_scalar_typedef (const char *s, struct fileloc *pos)
557 do_typedef (s, &scalar_nonchar, pos);
560 /* Similar to strtok_r. */
562 static char *
563 strtoken (char *str, const char *delim, char **next)
565 char *p;
567 if (str == NULL)
568 str = *next;
570 /* Skip the leading delimiters. */
571 str += strspn (str, delim);
572 if (*str == '\0')
573 /* This is an empty token. */
574 return NULL;
576 /* The current token. */
577 p = str;
579 /* Find the next delimiter. */
580 str += strcspn (str, delim);
581 if (*str == '\0')
582 /* This is the last token. */
583 *next = str;
584 else
586 /* Terminate the current token. */
587 *str = '\0';
588 /* Advance to the next token. */
589 *next = str + 1;
592 return p;
595 /* Define TYPE_NAME to be a user defined type at location POS. */
597 type_p
598 create_user_defined_type (const char *type_name, struct fileloc *pos)
600 type_p ty = find_structure (type_name, TYPE_USER_STRUCT);
602 /* We might have already seen an incomplete decl of the given type,
603 in which case we won't have yet seen a GTY((user)), and the type will
604 only have kind "TYPE_STRUCT". Mark it as a user struct. */
605 ty->kind = TYPE_USER_STRUCT;
607 ty->u.s.line = *pos;
608 ty->u.s.bitmap = get_lang_bitmap (pos->file);
609 do_typedef (type_name, ty, pos);
611 /* If TYPE_NAME specifies a template, create references to the types
612 in the template by pretending that each type is a field of TY.
613 This is needed to make sure that the types referenced by the
614 template are marked as used. */
615 char *str = xstrdup (type_name);
616 char *open_bracket = strchr (str, '<');
617 if (open_bracket)
619 /* We only accept simple template declarations (see
620 require_template_declaration), so we only need to parse a
621 comma-separated list of strings, implicitly assumed to
622 be type names, potentially with "*" characters. */
623 char *arg = open_bracket + 1;
624 /* Workaround -Wmaybe-uninitialized false positive during
625 profiledbootstrap by initializing it. */
626 char *next = NULL;
627 char *type_id = strtoken (arg, ",>", &next);
628 pair_p fields = 0;
629 while (type_id)
631 /* Create a new field for every type found inside the template
632 parameter list. */
634 /* Support a single trailing "*" character. */
635 const char *star = strchr (type_id, '*');
636 int is_ptr = (star != NULL);
637 size_t offset_to_star = star - type_id;
638 if (is_ptr)
639 offset_to_star = star - type_id;
641 if (strstr (type_id, "char*"))
643 type_id = strtoken (0, ",>", &next);
644 continue;
647 char *field_name = xstrdup (type_id);
649 type_p arg_type;
650 if (is_ptr)
652 /* Strip off the first '*' character (and any subsequent text). */
653 *(field_name + offset_to_star) = '\0';
655 arg_type = find_structure (field_name, TYPE_STRUCT);
656 arg_type = create_pointer (arg_type);
658 else
659 arg_type = resolve_typedef (field_name, pos);
661 fields = create_field_at (fields, arg_type, field_name, 0, pos);
662 type_id = strtoken (0, ",>", &next);
665 /* Associate the field list to TY. */
666 ty->u.s.fields = fields;
668 free (str);
670 return ty;
674 /* Given a typedef name S, return its associated type. Return NULL if
675 S is not a registered type name. */
677 static type_p
678 type_for_name (const char *s)
680 pair_p p;
682 /* Special-case support for types within a "gcc::" namespace. Rather
683 than fully-supporting namespaces, simply strip off the "gcc::" prefix
684 where present. This allows us to have GTY roots of this form:
685 extern GTY(()) gcc::some_type *some_ptr;
686 where the autogenerated functions will refer to simply "some_type",
687 where they can be resolved into their namespace. */
688 if (startswith (s, "gcc::"))
689 s += 5;
691 for (p = typedefs; p != NULL; p = p->next)
692 if (strcmp (p->name, s) == 0)
693 return p->type;
694 return NULL;
698 /* Create an undefined type with name S and location POS. Return the
699 newly created type. */
701 static type_p
702 create_undefined_type (const char *s, struct fileloc *pos)
704 type_p ty = find_structure (s, TYPE_UNDEFINED);
705 ty->u.s.line = *pos;
706 ty->u.s.bitmap = get_lang_bitmap (pos->file);
707 do_typedef (s, ty, pos);
708 return ty;
712 /* Return the type previously defined for S. Use POS to report errors. */
714 type_p
715 resolve_typedef (const char *s, struct fileloc *pos)
717 bool is_template_instance = (strchr (s, '<') != NULL);
718 type_p p = type_for_name (s);
720 /* If we did not find a typedef registered, generate a TYPE_UNDEFINED
721 type for regular type identifiers. If the type identifier S is a
722 template instantiation, however, we treat it as a user defined
723 type.
725 FIXME, this is actually a limitation in gengtype. Supporting
726 template types and their instances would require keeping separate
727 track of the basic types definition and its instances. This
728 essentially forces all template classes in GC to be marked
729 GTY((user)). */
730 if (!p)
731 p = (is_template_instance)
732 ? create_user_defined_type (s, pos)
733 : create_undefined_type (s, pos);
735 return p;
738 /* Add SUBCLASS to head of linked list of BASE's subclasses. */
740 void add_subclass (type_p base, type_p subclass)
742 gcc_assert (union_or_struct_p (base));
743 gcc_assert (union_or_struct_p (subclass));
745 subclass->u.s.next_sibling_class = base->u.s.first_subclass;
746 base->u.s.first_subclass = subclass;
749 /* Create and return a new structure with tag NAME at POS with fields
750 FIELDS and options O. The KIND of structure must be one of
751 TYPE_STRUCT, TYPE_UNION or TYPE_USER_STRUCT. */
753 type_p
754 new_structure (const char *name, enum typekind kind, struct fileloc *pos,
755 pair_p fields, options_p o, type_p base_class)
757 type_p si;
758 type_p s = NULL;
759 lang_bitmap bitmap = get_lang_bitmap (pos->file);
760 bool isunion = (kind == TYPE_UNION);
761 type_p *p = &structures;
763 gcc_assert (union_or_struct_p (kind));
765 for (si = structures; si != NULL; p = &si->next, si = *p)
766 if (strcmp (name, si->u.s.tag) == 0 && UNION_P (si) == isunion)
768 type_p ls = NULL;
769 if (si->kind == TYPE_LANG_STRUCT)
771 ls = si;
773 for (si = ls->u.s.lang_struct; si != NULL; si = si->next)
774 if (si->u.s.bitmap == bitmap)
775 s = si;
777 else if (si->u.s.line.file != NULL && si->u.s.bitmap != bitmap)
779 ls = si;
780 type_count++;
781 si = XCNEW (struct type);
782 memcpy (si, ls, sizeof (struct type));
783 ls->kind = TYPE_LANG_STRUCT;
784 ls->u.s.lang_struct = si;
785 ls->u.s.fields = NULL;
786 si->next = NULL;
787 si->state_number = -type_count;
788 si->pointer_to = NULL;
789 si->u.s.lang_struct = ls;
791 else
792 s = si;
794 if (ls != NULL && s == NULL)
796 type_count++;
797 s = XCNEW (struct type);
798 s->state_number = -type_count;
799 s->next = ls->u.s.lang_struct;
800 ls->u.s.lang_struct = s;
801 s->u.s.lang_struct = ls;
803 break;
806 if (s == NULL)
808 type_count++;
809 s = XCNEW (struct type);
810 s->state_number = -type_count;
811 *p = s;
814 if (s->u.s.lang_struct && (s->u.s.lang_struct->u.s.bitmap & bitmap))
816 error_at_line (pos, "duplicate definition of '%s %s'",
817 isunion ? "union" : "struct", s->u.s.tag);
818 error_at_line (&s->u.s.line, "previous definition here");
821 s->kind = kind;
822 s->u.s.tag = name;
823 s->u.s.line = *pos;
824 s->u.s.fields = fields;
825 s->u.s.opt = o;
826 s->u.s.bitmap = bitmap;
827 if (s->u.s.lang_struct)
828 s->u.s.lang_struct->u.s.bitmap |= bitmap;
829 s->u.s.base_class = base_class;
830 if (base_class)
831 add_subclass (base_class, s);
833 return s;
836 /* Return the previously-defined structure or union with tag NAME,
837 or a new empty structure or union if none was defined previously.
838 The KIND of structure must be one of TYPE_STRUCT, TYPE_UNION or
839 TYPE_USER_STRUCT. */
841 type_p
842 find_structure (const char *name, enum typekind kind)
844 type_p s;
845 bool isunion = (kind == TYPE_UNION);
846 type_p *p = &structures;
848 gcc_assert (kind == TYPE_UNDEFINED || union_or_struct_p (kind));
850 for (s = structures; s != NULL; p = &s->next, s = *p)
851 if (strcmp (name, s->u.s.tag) == 0 && UNION_P (s) == isunion)
852 return s;
854 type_count++;
855 s = XCNEW (struct type);
856 s->state_number = -type_count;
857 s->kind = kind;
858 s->u.s.tag = name;
859 *p = s;
860 return s;
863 /* Return a scalar type with name NAME. */
865 type_p
866 create_scalar_type (const char *name)
868 if (!strcmp (name, "char") || !strcmp (name, "unsigned char"))
869 return &scalar_char;
870 else
871 return &scalar_nonchar;
875 /* Return a pointer to T. */
877 type_p
878 create_pointer (type_p t)
880 if (!t->pointer_to)
882 type_p r = XCNEW (struct type);
883 type_count++;
884 r->state_number = -type_count;
885 r->kind = TYPE_POINTER;
886 r->u.p = t;
887 t->pointer_to = r;
889 return t->pointer_to;
892 /* Return an array of length LEN. */
894 type_p
895 create_array (type_p t, const char *len)
897 type_p v;
899 type_count++;
900 v = XCNEW (struct type);
901 v->kind = TYPE_ARRAY;
902 v->state_number = -type_count;
903 v->u.a.p = t;
904 v->u.a.len = len;
905 return v;
908 /* Return a string options structure with name NAME and info INFO.
909 NEXT is the next option in the chain. */
910 options_p
911 create_string_option (options_p next, const char *name, const char *info)
913 options_p o = XNEW (struct options);
914 o->kind = OPTION_STRING;
915 o->next = next;
916 o->name = name;
917 o->info.string = info;
918 return o;
921 /* Create a type options structure with name NAME and info INFO. NEXT
922 is the next option in the chain. */
923 options_p
924 create_type_option (options_p next, const char* name, type_p info)
926 options_p o = XNEW (struct options);
927 o->next = next;
928 o->name = name;
929 o->kind = OPTION_TYPE;
930 o->info.type = info;
931 return o;
934 /* Create a nested pointer options structure with name NAME and info
935 INFO. NEXT is the next option in the chain. */
936 options_p
937 create_nested_option (options_p next, const char* name,
938 struct nested_ptr_data* info)
940 options_p o;
941 o = XNEW (struct options);
942 o->next = next;
943 o->name = name;
944 o->kind = OPTION_NESTED;
945 o->info.nested = info;
946 return o;
949 /* Return an options structure for a "nested_ptr" option. */
950 options_p
951 create_nested_ptr_option (options_p next, type_p t,
952 const char *to, const char *from)
954 struct nested_ptr_data *d = XNEW (struct nested_ptr_data);
956 d->type = adjust_field_type (t, 0);
957 d->convert_to = to;
958 d->convert_from = from;
959 return create_nested_option (next, "nested_ptr", d);
962 /* Add a variable named S of type T with options O defined at POS,
963 to `variables'. */
964 void
965 note_variable (const char *s, type_p t, options_p o, struct fileloc *pos)
967 pair_p n;
968 n = XNEW (struct pair);
969 n->name = s;
970 n->type = t;
971 n->line = *pos;
972 n->opt = o;
973 n->next = variables;
974 variables = n;
977 /* Most-general structure field creator. */
978 static pair_p
979 create_field_all (pair_p next, type_p type, const char *name, options_p opt,
980 const input_file *inpf, int line)
982 pair_p field;
984 field = XNEW (struct pair);
985 field->next = next;
986 field->type = type;
987 field->name = name;
988 field->opt = opt;
989 field->line.file = inpf;
990 field->line.line = line;
991 return field;
994 /* Create a field that came from the source code we are scanning,
995 i.e. we have a 'struct fileloc', and possibly options; also,
996 adjust_field_type should be called. */
997 pair_p
998 create_field_at (pair_p next, type_p type, const char *name, options_p opt,
999 struct fileloc *pos)
1001 return create_field_all (next, adjust_field_type (type, opt),
1002 name, opt, pos->file, pos->line);
1005 /* Create a fake field with the given type and name. NEXT is the next
1006 field in the chain. */
1007 #define create_field(next,type,name) \
1008 create_field_all (next,type,name, 0, this_file, __LINE__)
1010 /* Like create_field, but the field is only valid when condition COND
1011 is true. */
1013 static pair_p
1014 create_optional_field_ (pair_p next, type_p type, const char *name,
1015 const char *cond, int line)
1017 static int id = 1;
1018 pair_p union_fields;
1019 type_p union_type;
1021 /* Create a fake union type with a single nameless field of type TYPE.
1022 The field has a tag of "1". This allows us to make the presence
1023 of a field of type TYPE depend on some boolean "desc" being true. */
1024 union_fields = create_field (NULL, type, "");
1025 union_fields->opt =
1026 create_string_option (union_fields->opt, "dot", "");
1027 union_fields->opt =
1028 create_string_option (union_fields->opt, "tag", "1");
1029 union_type =
1030 new_structure (xasprintf ("%s_%d", "fake_union", id++), TYPE_UNION,
1031 &lexer_line, union_fields, NULL, NULL);
1033 /* Create the field and give it the new fake union type. Add a "desc"
1034 tag that specifies the condition under which the field is valid. */
1035 return create_field_all (next, union_type, name,
1036 create_string_option (0, "desc", cond),
1037 this_file, line);
1040 #define create_optional_field(next,type,name,cond) \
1041 create_optional_field_(next,type,name,cond,__LINE__)
1043 /* Reverse a linked list of 'struct pair's in place. */
1044 pair_p
1045 nreverse_pairs (pair_p list)
1047 pair_p prev = 0, p, next;
1048 for (p = list; p; p = next)
1050 next = p->next;
1051 p->next = prev;
1052 prev = p;
1054 return prev;
1058 /* We don't care how long a CONST_DOUBLE is. */
1059 #define CONST_DOUBLE_FORMAT "ww"
1060 /* We don't want to see codes that are only for generator files. */
1061 #undef GENERATOR_FILE
1063 enum rtx_code
1065 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) ENUM ,
1066 #include "rtl.def"
1067 #undef DEF_RTL_EXPR
1068 NUM_RTX_CODE
1071 static const char *const rtx_name[NUM_RTX_CODE] = {
1072 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) NAME ,
1073 #include "rtl.def"
1074 #undef DEF_RTL_EXPR
1077 static const char *const rtx_format[NUM_RTX_CODE] = {
1078 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) FORMAT ,
1079 #include "rtl.def"
1080 #undef DEF_RTL_EXPR
1083 static int rtx_next_new[NUM_RTX_CODE];
1085 /* We also need codes and names for insn notes (not register notes).
1086 Note that we do *not* bias the note values here. */
1087 enum insn_note
1089 #define DEF_INSN_NOTE(NAME) NAME,
1090 #include "insn-notes.def"
1091 #undef DEF_INSN_NOTE
1093 NOTE_INSN_MAX
1096 /* We must allocate one more entry here, as we use NOTE_INSN_MAX as the
1097 default field for line number notes. */
1098 static const char *const note_insn_name[NOTE_INSN_MAX + 1] = {
1099 #define DEF_INSN_NOTE(NAME) #NAME,
1100 #include "insn-notes.def"
1101 #undef DEF_INSN_NOTE
1104 #undef CONST_DOUBLE_FORMAT
1105 #define GENERATOR_FILE
1107 /* Generate the contents of the rtx_next array. This really doesn't belong
1108 in gengtype at all, but it's needed for adjust_field_rtx_def. */
1110 static void
1111 gen_rtx_next (void)
1113 int i;
1114 for (i = 0; i < NUM_RTX_CODE; i++)
1116 int k;
1118 rtx_next_new[i] = -1;
1119 if (startswith (rtx_format[i], "uu"))
1120 rtx_next_new[i] = 1;
1121 else if (i == COND_EXEC || i == SET || i == EXPR_LIST || i == INSN_LIST)
1122 rtx_next_new[i] = 1;
1123 else
1124 for (k = strlen (rtx_format[i]) - 1; k >= 0; k--)
1125 if (rtx_format[i][k] == 'e' || rtx_format[i][k] == 'u')
1126 rtx_next_new[i] = k;
1130 /* Write out the contents of the rtx_next array. */
1131 static void
1132 write_rtx_next (void)
1134 outf_p f = get_output_file_with_visibility (NULL);
1135 int i;
1136 if (!f)
1137 return;
1139 oprintf (f, "\n/* Used to implement the RTX_NEXT macro. */\n");
1140 oprintf (f, "EXPORTED_CONST unsigned char rtx_next[NUM_RTX_CODE] = {\n");
1141 for (i = 0; i < NUM_RTX_CODE; i++)
1142 if (rtx_next_new[i] == -1)
1143 oprintf (f, " 0,\n");
1144 else
1145 oprintf (f,
1146 " RTX_HDR_SIZE + %d * sizeof (rtunion),\n", rtx_next_new[i]);
1147 oprintf (f, "};\n");
1150 /* Handle `special("rtx_def")'. This is a special case for field
1151 `fld' of struct rtx_def, which is an array of unions whose values
1152 are based in a complex way on the type of RTL. */
1154 static type_p
1155 adjust_field_rtx_def (type_p t, options_p ARG_UNUSED (opt))
1157 pair_p flds = NULL;
1158 options_p nodot;
1159 int i;
1160 type_p rtx_tp, rtvec_tp, tree_tp, mem_attrs_tp, note_union_tp, scalar_tp;
1161 type_p basic_block_tp, reg_attrs_tp, constant_tp, symbol_union_tp;
1163 if (t->kind != TYPE_UNION)
1165 error_at_line (&lexer_line,
1166 "special `rtx_def' must be applied to a union");
1167 return &string_type;
1170 nodot = create_string_option (NULL, "dot", "");
1172 rtx_tp = create_pointer (find_structure ("rtx_def", TYPE_STRUCT));
1173 rtvec_tp = create_pointer (find_structure ("rtvec_def", TYPE_STRUCT));
1174 tree_tp = create_pointer (find_structure ("tree_node", TYPE_UNION));
1175 mem_attrs_tp = create_pointer (find_structure ("mem_attrs", TYPE_STRUCT));
1176 reg_attrs_tp =
1177 create_pointer (find_structure ("reg_attrs", TYPE_STRUCT));
1178 basic_block_tp =
1179 create_pointer (find_structure ("basic_block_def", TYPE_STRUCT));
1180 constant_tp =
1181 create_pointer (find_structure ("constant_descriptor_rtx", TYPE_STRUCT));
1182 scalar_tp = &scalar_nonchar; /* rtunion int */
1185 pair_p note_flds = NULL;
1186 int c;
1188 for (c = 0; c <= NOTE_INSN_MAX; c++)
1190 switch (c)
1192 case NOTE_INSN_MAX:
1193 case NOTE_INSN_DELETED_LABEL:
1194 case NOTE_INSN_DELETED_DEBUG_LABEL:
1195 note_flds = create_field (note_flds, &string_type, "rt_str");
1196 break;
1198 case NOTE_INSN_BLOCK_BEG:
1199 case NOTE_INSN_BLOCK_END:
1200 note_flds = create_field (note_flds, tree_tp, "rt_tree");
1201 break;
1203 case NOTE_INSN_VAR_LOCATION:
1204 note_flds = create_field (note_flds, rtx_tp, "rt_rtx");
1205 break;
1207 default:
1208 note_flds = create_field (note_flds, scalar_tp, "rt_int");
1209 break;
1211 /* NOTE_INSN_MAX is used as the default field for line
1212 number notes. */
1213 if (c == NOTE_INSN_MAX)
1214 note_flds->opt =
1215 create_string_option (nodot, "default", "");
1216 else
1217 note_flds->opt =
1218 create_string_option (nodot, "tag", note_insn_name[c]);
1220 note_union_tp = new_structure ("rtx_def_note_subunion", TYPE_UNION,
1221 &lexer_line, note_flds, NULL, NULL);
1223 /* Create a type to represent the various forms of SYMBOL_REF_DATA. */
1225 pair_p sym_flds;
1226 sym_flds = create_field (NULL, tree_tp, "rt_tree");
1227 sym_flds->opt = create_string_option (nodot, "default", "");
1228 sym_flds = create_field (sym_flds, constant_tp, "rt_constant");
1229 sym_flds->opt = create_string_option (nodot, "tag", "1");
1230 symbol_union_tp = new_structure ("rtx_def_symbol_subunion", TYPE_UNION,
1231 &lexer_line, sym_flds, NULL, NULL);
1233 for (i = 0; i < NUM_RTX_CODE; i++)
1235 pair_p subfields = NULL;
1236 size_t aindex, nmindex;
1237 const char *sname;
1238 type_p substruct;
1239 char *ftag;
1241 for (aindex = 0; aindex < strlen (rtx_format[i]); aindex++)
1243 type_p t;
1244 const char *subname;
1246 switch (rtx_format[i][aindex])
1248 case '*':
1249 case 'i':
1250 case 'n':
1251 case 'w':
1252 case 'r':
1253 t = scalar_tp;
1254 subname = "rt_int";
1255 break;
1257 case 'p':
1258 t = scalar_tp;
1259 subname = "rt_subreg";
1260 break;
1262 case '0':
1263 if (i == MEM && aindex == 1)
1264 t = mem_attrs_tp, subname = "rt_mem";
1265 else if (i == JUMP_INSN && aindex == 7)
1266 t = rtx_tp, subname = "rt_rtx";
1267 else if (i == CODE_LABEL && aindex == 4)
1268 t = scalar_tp, subname = "rt_int";
1269 else if (i == CODE_LABEL && aindex == 3)
1270 t = rtx_tp, subname = "rt_rtx";
1271 else if (i == LABEL_REF && (aindex == 1 || aindex == 2))
1272 t = rtx_tp, subname = "rt_rtx";
1273 else if (i == NOTE && aindex == 3)
1274 t = note_union_tp, subname = "";
1275 else if (i == NOTE && aindex == 4)
1276 t = scalar_tp, subname = "rt_int";
1277 else if (i == NOTE && aindex >= 6)
1278 t = scalar_tp, subname = "rt_int";
1279 else if (i == ADDR_DIFF_VEC && aindex == 4)
1280 t = scalar_tp, subname = "rt_int";
1281 else if (i == VALUE && aindex == 0)
1282 t = scalar_tp, subname = "rt_int";
1283 else if (i == DEBUG_EXPR && aindex == 0)
1284 t = tree_tp, subname = "rt_tree";
1285 else if (i == SYMBOL_REF && aindex == 1)
1286 t = symbol_union_tp, subname = "";
1287 else if (i == JUMP_TABLE_DATA && aindex >= 4)
1288 t = scalar_tp, subname = "rt_int";
1289 else if (i == BARRIER && aindex >= 2)
1290 t = scalar_tp, subname = "rt_int";
1291 else if (i == ENTRY_VALUE && aindex == 0)
1292 t = rtx_tp, subname = "rt_rtx";
1293 else
1295 error_at_line
1296 (&lexer_line,
1297 "rtx type `%s' has `0' in position %lu, can't handle",
1298 rtx_name[i], (unsigned long) aindex);
1299 t = &string_type;
1300 subname = "rt_int";
1302 break;
1304 case 's':
1305 case 'S':
1306 case 'T':
1307 t = &string_type;
1308 subname = "rt_str";
1309 break;
1311 case 'e':
1312 case 'u':
1313 t = rtx_tp;
1314 subname = "rt_rtx";
1315 break;
1317 case 'E':
1318 case 'V':
1319 t = rtvec_tp;
1320 subname = "rt_rtvec";
1321 break;
1323 case 't':
1324 t = tree_tp;
1325 subname = "rt_tree";
1326 break;
1328 case 'B':
1329 t = basic_block_tp;
1330 subname = "rt_bb";
1331 break;
1333 default:
1334 error_at_line
1335 (&lexer_line,
1336 "rtx type `%s' has `%c' in position %lu, can't handle",
1337 rtx_name[i], rtx_format[i][aindex],
1338 (unsigned long) aindex);
1339 t = &string_type;
1340 subname = "rt_int";
1341 break;
1344 subfields = create_field (subfields, t,
1345 xasprintf (".fld[%lu].%s",
1346 (unsigned long) aindex,
1347 subname));
1348 subfields->opt = nodot;
1349 if (t == note_union_tp)
1350 subfields->opt =
1351 create_string_option (subfields->opt, "desc",
1352 "NOTE_KIND (&%0)");
1353 if (t == symbol_union_tp)
1354 subfields->opt =
1355 create_string_option (subfields->opt, "desc",
1356 "CONSTANT_POOL_ADDRESS_P (&%0)");
1359 if (i == REG)
1360 subfields = create_field (subfields, reg_attrs_tp, "reg.attrs");
1362 if (i == SYMBOL_REF)
1364 /* Add the "block_sym" field if SYMBOL_REF_HAS_BLOCK_INFO_P
1365 holds. */
1366 type_p field_tp = find_structure ("block_symbol", TYPE_STRUCT);
1367 subfields
1368 = create_optional_field (subfields, field_tp, "block_sym",
1369 "SYMBOL_REF_HAS_BLOCK_INFO_P (&%0)");
1372 sname = xasprintf ("rtx_def_%s", rtx_name[i]);
1373 substruct = new_structure (sname, TYPE_STRUCT, &lexer_line, subfields,
1374 NULL, NULL);
1376 ftag = xstrdup (rtx_name[i]);
1377 for (nmindex = 0; nmindex < strlen (ftag); nmindex++)
1378 ftag[nmindex] = TOUPPER (ftag[nmindex]);
1379 flds = create_field (flds, substruct, "");
1380 flds->opt = create_string_option (nodot, "tag", ftag);
1382 return new_structure ("rtx_def_subunion", TYPE_UNION, &lexer_line, flds,
1383 nodot, NULL);
1386 /* Perform any special processing on a type T, about to become the type
1387 of a field. Return the appropriate type for the field.
1388 At present:
1389 - Converts pointer-to-char, with no length parameter, to TYPE_STRING;
1390 - Similarly for arrays of pointer-to-char;
1391 - Converts structures for which a parameter is provided to
1392 TYPE_PARAM_STRUCT;
1393 - Handles "special" options.
1396 type_p
1397 adjust_field_type (type_p t, options_p opt)
1399 int length_p = 0;
1400 const int pointer_p = t->kind == TYPE_POINTER;
1402 for (; opt; opt = opt->next)
1403 if (strcmp (opt->name, "length") == 0)
1405 if (length_p)
1406 error_at_line (&lexer_line, "duplicate `%s' option", opt->name);
1407 if (t->u.p->kind == TYPE_SCALAR || t->u.p->kind == TYPE_STRING)
1409 error_at_line (&lexer_line,
1410 "option `%s' may not be applied to "
1411 "arrays of atomic types", opt->name);
1413 length_p = 1;
1415 else if (strcmp (opt->name, "special") == 0
1416 && opt->kind == OPTION_STRING)
1418 const char *special_name = opt->info.string;
1419 if (strcmp (special_name, "rtx_def") == 0)
1420 t = adjust_field_rtx_def (t, opt);
1421 else
1422 error_at_line (&lexer_line, "unknown special `%s'", special_name);
1425 if (!length_p
1426 && pointer_p && t->u.p->kind == TYPE_SCALAR && t->u.p->u.scalar_is_char)
1427 return &string_type;
1428 if (t->kind == TYPE_ARRAY && t->u.a.p->kind == TYPE_POINTER
1429 && t->u.a.p->u.p->kind == TYPE_SCALAR
1430 && t->u.a.p->u.p->u.scalar_is_char)
1431 return create_array (&string_type, t->u.a.len);
1433 return t;
1437 static void set_gc_used_type (type_p, enum gc_used_enum, bool = false);
1438 static void set_gc_used (pair_p);
1440 /* Handle OPT for set_gc_used_type. */
1442 static void
1443 process_gc_options (options_p opt, enum gc_used_enum level, int *maybe_undef,
1444 int *length, int *skip, int *callback, type_p *nested_ptr)
1446 options_p o;
1447 for (o = opt; o; o = o->next)
1448 if (strcmp (o->name, "ptr_alias") == 0 && level == GC_POINTED_TO
1449 && o->kind == OPTION_TYPE)
1450 set_gc_used_type (o->info.type,
1451 GC_POINTED_TO);
1452 else if (strcmp (o->name, "maybe_undef") == 0)
1453 *maybe_undef = 1;
1454 else if (strcmp (o->name, "length") == 0)
1455 *length = 1;
1456 else if (strcmp (o->name, "skip") == 0)
1457 *skip = 1;
1458 else if (strcmp (o->name, "callback") == 0)
1459 *callback = 1;
1460 else if (strcmp (o->name, "nested_ptr") == 0
1461 && o->kind == OPTION_NESTED)
1462 *nested_ptr = ((const struct nested_ptr_data *) o->info.nested)->type;
1466 /* Set the gc_used field of T to LEVEL, and handle the types it references.
1468 If ALLOWED_UNDEFINED_TYPES is true, types of kind TYPE_UNDEFINED
1469 are set to GC_UNUSED. Otherwise, an error is emitted for
1470 TYPE_UNDEFINED types. This is used to support user-defined
1471 template types with non-type arguments.
1473 For instance, when we parse a template type with enum arguments
1474 (e.g. MyType<AnotherType, EnumValue>), the parser created two
1475 artificial fields for 'MyType', one for 'AnotherType', the other
1476 one for 'EnumValue'.
1478 At the time that we parse this type we don't know that 'EnumValue'
1479 is really an enum value, so the parser creates a TYPE_UNDEFINED
1480 type for it. Since 'EnumValue' is never resolved to a known
1481 structure, it will stay with TYPE_UNDEFINED.
1483 Since 'MyType' is a TYPE_USER_STRUCT, we can simply ignore
1484 'EnumValue'. Generating marking code for it would cause
1485 compilation failures since the marking routines assumes that
1486 'EnumValue' is a type. */
1488 static void
1489 set_gc_used_type (type_p t, enum gc_used_enum level,
1490 bool allow_undefined_types)
1492 if (t->gc_used >= level)
1493 return;
1495 t->gc_used = level;
1497 switch (t->kind)
1499 case TYPE_STRUCT:
1500 case TYPE_UNION:
1501 case TYPE_USER_STRUCT:
1503 pair_p f;
1504 int dummy;
1505 type_p dummy2;
1506 bool allow_undefined_field_types = (t->kind == TYPE_USER_STRUCT);
1508 process_gc_options (t->u.s.opt, level, &dummy, &dummy, &dummy, &dummy,
1509 &dummy2);
1511 if (t->u.s.base_class)
1512 set_gc_used_type (t->u.s.base_class, level, allow_undefined_types);
1513 /* Anything pointing to a base class might actually be pointing
1514 to a subclass. */
1515 for (type_p subclass = t->u.s.first_subclass; subclass;
1516 subclass = subclass->u.s.next_sibling_class)
1517 set_gc_used_type (subclass, level, allow_undefined_types);
1519 FOR_ALL_INHERITED_FIELDS(t, f)
1521 int maybe_undef = 0;
1522 int length = 0;
1523 int skip = 0;
1524 int callback = 0;
1525 type_p nested_ptr = NULL;
1526 process_gc_options (f->opt, level, &maybe_undef, &length, &skip,
1527 &callback, &nested_ptr);
1529 if (nested_ptr && f->type->kind == TYPE_POINTER)
1530 set_gc_used_type (nested_ptr, GC_POINTED_TO);
1531 else if (length && f->type->kind == TYPE_POINTER)
1532 set_gc_used_type (f->type->u.p, GC_USED);
1533 else if (maybe_undef && f->type->kind == TYPE_POINTER)
1534 set_gc_used_type (f->type->u.p, GC_MAYBE_POINTED_TO);
1535 else if (skip)
1536 ; /* target type is not used through this field */
1537 else if (callback)
1538 f->type = &callback_type;
1539 else
1540 set_gc_used_type (f->type, GC_USED, allow_undefined_field_types);
1542 break;
1545 case TYPE_UNDEFINED:
1546 if (level > GC_UNUSED)
1548 if (!allow_undefined_types)
1549 error_at_line (&t->u.s.line, "undefined type `%s'", t->u.s.tag);
1550 t->gc_used = GC_UNUSED;
1552 break;
1554 case TYPE_POINTER:
1555 set_gc_used_type (t->u.p, GC_POINTED_TO);
1556 break;
1558 case TYPE_ARRAY:
1559 set_gc_used_type (t->u.a.p, GC_USED);
1560 break;
1562 case TYPE_LANG_STRUCT:
1563 for (t = t->u.s.lang_struct; t; t = t->next)
1564 set_gc_used_type (t, level);
1565 break;
1567 default:
1568 break;
1572 /* Set the gc_used fields of all the types pointed to by VARIABLES. */
1574 static void
1575 set_gc_used (pair_p variables)
1577 int nbvars = 0;
1578 pair_p p;
1579 for (p = variables; p; p = p->next)
1581 set_gc_used_type (p->type, GC_USED);
1582 nbvars++;
1584 if (verbosity_level >= 2)
1585 printf ("%s used %d GTY-ed variables\n", progname, nbvars);
1588 /* File mapping routines. For each input file, there is one output .cc file
1589 (but some output files have many input files), and there is one .h file
1590 for the whole build. */
1592 /* Output file handling. */
1594 /* Create and return an outf_p for a new file for NAME, to be called
1595 ONAME. */
1597 static outf_p
1598 create_file (const char *name, const char *oname)
1600 static const char *const hdr[] = {
1601 " Copyright (C) 2004-2023 Free Software Foundation, Inc.\n",
1602 "\n",
1603 "This file is part of GCC.\n",
1604 "\n",
1605 "GCC is free software; you can redistribute it and/or modify it under\n",
1606 "the terms of the GNU General Public License as published by the Free\n",
1607 "Software Foundation; either version 3, or (at your option) any later\n",
1608 "version.\n",
1609 "\n",
1610 "GCC is distributed in the hope that it will be useful, but WITHOUT ANY\n",
1611 "WARRANTY; without even the implied warranty of MERCHANTABILITY or\n",
1612 "FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n",
1613 "for more details.\n",
1614 "\n",
1615 "You should have received a copy of the GNU General Public License\n",
1616 "along with GCC; see the file COPYING3. If not see\n",
1617 "<http://www.gnu.org/licenses/>. */\n",
1618 "\n",
1619 "/* This file is machine generated. Do not edit. */\n"
1621 outf_p f;
1622 size_t i;
1624 gcc_assert (name != NULL);
1625 gcc_assert (oname != NULL);
1626 f = XCNEW (struct outf);
1627 f->next = output_files;
1628 f->name = oname;
1629 output_files = f;
1631 oprintf (f, "/* Type information for %s.\n", name);
1632 for (i = 0; i < ARRAY_SIZE (hdr); i++)
1633 oprintf (f, "%s", hdr[i]);
1634 return f;
1637 /* Print, like fprintf, to O.
1638 N.B. You might think this could be implemented more efficiently
1639 with vsnprintf(). Unfortunately, there are C libraries that
1640 provide that function but without the C99 semantics for its return
1641 value, making it impossible to know how much space is required. */
1642 void
1643 oprintf (outf_p o, const char *format, ...)
1645 char *s;
1646 size_t slength;
1647 va_list ap;
1649 /* In plugin mode, the O could be a NULL pointer, so avoid crashing
1650 in that case. */
1651 if (!o)
1652 return;
1654 va_start (ap, format);
1655 slength = vasprintf (&s, format, ap);
1656 if (s == NULL || (int) slength < 0)
1657 fatal ("out of memory");
1658 va_end (ap);
1660 if (o->bufused + slength > o->buflength)
1662 size_t new_len = o->buflength;
1663 if (new_len == 0)
1664 new_len = 1024;
1667 new_len *= 2;
1669 while (o->bufused + slength >= new_len);
1670 o->buf = XRESIZEVEC (char, o->buf, new_len);
1671 o->buflength = new_len;
1673 memcpy (o->buf + o->bufused, s, slength);
1674 o->bufused += slength;
1675 free (s);
1678 /* Open the global header file and the language-specific header files. */
1680 static void
1681 open_base_files (void)
1683 size_t i;
1685 if (nb_plugin_files > 0 && plugin_files)
1686 return;
1688 header_file = create_file ("GCC", "gtype-desc.h");
1690 base_files = XNEWVEC (outf_p, num_lang_dirs);
1692 for (i = 0; i < num_lang_dirs; i++)
1693 base_files[i] = create_file (lang_dir_names[i],
1694 xasprintf ("gtype-%s.h", lang_dir_names[i]));
1696 /* gtype-desc.cc is a little special, so we create it here. */
1698 /* The order of files here matters very much. */
1699 static const char *const ifiles[] = {
1700 "config.h", "system.h", "coretypes.h",
1701 "backend.h", "predict.h", "tree.h",
1702 "rtl.h", "gimple.h", "fold-const.h", "insn-codes.h", "splay-tree.h",
1703 "alias.h", "insn-config.h", "flags.h", "expmed.h", "dojump.h",
1704 "explow.h", "calls.h", "memmodel.h", "emit-rtl.h", "varasm.h",
1705 "stmt.h", "expr.h", "alloc-pool.h", "cselib.h", "insn-addr.h",
1706 "optabs.h", "libfuncs.h", "debug.h", "internal-fn.h",
1707 "gimple-iterator.h", "gimple-fold.h", "value-range.h",
1708 "value-range-storage.h",
1709 "tree-eh.h", "gimple-ssa.h", "tree-cfg.h",
1710 "tree-vrp.h", "tree-phinodes.h", "ssa-iterators.h", "stringpool.h",
1711 "tree-ssanames.h", "tree-ssa-loop.h", "tree-ssa-loop-ivopts.h",
1712 "tree-ssa-loop-manip.h", "tree-ssa-loop-niter.h", "tree-into-ssa.h",
1713 "tree-dfa.h", "tree-ssa.h", "reload.h", "cpplib.h", "tree-chrec.h",
1714 "except.h", "output.h", "cfgloop.h", "target.h", "lto-streamer.h",
1715 "target-globals.h", "ipa-ref.h", "cgraph.h", "symbol-summary.h",
1716 "ipa-prop.h", "ipa-fnsummary.h", "dwarf2out.h", "omp-general.h",
1717 "omp-offload.h", "ipa-modref-tree.h", "ipa-modref.h", "symtab-thunks.h",
1718 "symtab-clones.h", "diagnostic-spec.h", "ctfc.h",
1719 NULL
1721 const char *const *ifp;
1722 outf_p gtype_desc_c;
1724 gtype_desc_c = create_file ("GCC", "gtype-desc.cc");
1725 for (ifp = ifiles; *ifp; ifp++)
1726 oprintf (gtype_desc_c, "#include \"%s\"\n", *ifp);
1727 for (int j = 0; j < (int) num_build_headers; j++)
1728 oprintf (gtype_desc_c, "#include \"%s\"\n", build_headers[j]);
1730 /* Make sure we handle "cfun" specially. */
1731 oprintf (gtype_desc_c, "\n/* See definition in function.h. */\n");
1732 oprintf (gtype_desc_c, "#undef cfun\n");
1734 oprintf (gtype_desc_c,
1735 "\n"
1736 "/* Types with a \"gcc::\" namespace have it stripped\n"
1737 " during gengtype parsing. Provide a \"using\" directive\n"
1738 " to ensure that the fully-qualified types are found. */\n"
1739 "using namespace gcc;\n");
1743 /* For INPF an input file, return the real basename of INPF, with all
1744 the directory components skipped. */
1746 static const char *
1747 get_file_realbasename (const input_file *inpf)
1749 return lbasename (get_input_file_name (inpf));
1752 /* For INPF a filename, return the relative path to INPF from
1753 $(srcdir) if the latter is a prefix in INPF, NULL otherwise. */
1755 const char *
1756 get_file_srcdir_relative_path (const input_file *inpf)
1758 const char *f = get_input_file_name (inpf);
1759 if (strlen (f) > srcdir_len
1760 && IS_DIR_SEPARATOR (f[srcdir_len])
1761 && strncmp (f, srcdir, srcdir_len) == 0)
1762 return f + srcdir_len + 1;
1763 else
1764 return NULL;
1767 /* For INPF an input_file, return the relative path to INPF from
1768 $(srcdir) if the latter is a prefix in INPF, or the real basename
1769 of INPF otherwise. */
1771 static const char *
1772 get_file_basename (const input_file *inpf)
1774 const char *srcdir_path = get_file_srcdir_relative_path (inpf);
1776 return (srcdir_path != NULL) ? srcdir_path : get_file_realbasename (inpf);
1779 /* For F a filename, return the lang_dir_names relative index of the language
1780 directory that is a prefix in F, if any, -1 otherwise. */
1782 static int
1783 get_prefix_langdir_index (const char *f)
1785 size_t f_len = strlen (f);
1786 size_t lang_index;
1788 for (lang_index = 0; lang_index < num_lang_dirs; lang_index++)
1790 const char *langdir = lang_dir_names[lang_index];
1791 size_t langdir_len = strlen (langdir);
1793 if (f_len > langdir_len
1794 && IS_DIR_SEPARATOR (f[langdir_len])
1795 && memcmp (f, langdir, langdir_len) == 0)
1796 return lang_index;
1799 return -1;
1802 /* For INPF an input file, return the name of language directory where
1803 F is located, if any, NULL otherwise. */
1805 static const char *
1806 get_file_langdir (const input_file *inpf)
1808 /* Get the relative path to INPF from $(srcdir) and find the
1809 language by comparing the prefix with language directory names.
1810 If INPF is not even srcdir relative, no point in looking
1811 further. */
1813 int lang_index;
1814 const char *srcdir_relative_path = get_file_srcdir_relative_path (inpf);
1815 const char *r;
1817 if (!srcdir_relative_path)
1818 return NULL;
1820 lang_index = get_prefix_langdir_index (srcdir_relative_path);
1821 if (lang_index < 0 && startswith (srcdir_relative_path, "c-family"))
1822 r = "c-family";
1823 else if (lang_index >= 0)
1824 r = lang_dir_names[lang_index];
1825 else
1826 r = NULL;
1828 return r;
1831 /* The gt- output file name for INPF. */
1833 static const char *
1834 get_file_gtfilename (const input_file *inpf)
1836 /* Cook up an initial version of the gt- file name from the file real
1837 basename and the language name, if any. */
1839 const char *basename = get_file_realbasename (inpf);
1840 const char *langdir = get_file_langdir (inpf);
1842 char *result =
1843 (langdir ? xasprintf ("gt-%s-%s", langdir, basename)
1844 : xasprintf ("gt-%s", basename));
1846 /* Then replace all non alphanumerics characters by '-' and change the
1847 extension to ".h". We expect the input filename extension was at least
1848 one character long. */
1850 char *s = result;
1852 for (; *s != '.'; s++)
1853 if (!ISALNUM (*s) && *s != '-')
1854 *s = '-';
1856 memcpy (s, ".h", sizeof (".h"));
1858 return result;
1861 /* Each input_file has its associated output file outf_p. The
1862 association is computed by the function
1863 get_output_file_with_visibility. The associated file is cached
1864 inside input_file in its inpoutf field, so is really computed only
1865 once. Associated output file paths (i.e. output_name-s) are
1866 computed by a rule based regexp machinery, using the files_rules
1867 array of struct file_rule_st. A for_name is also computed, giving
1868 the source file name for which the output_file is generated; it is
1869 often the last component of the input_file path. */
1873 Regexpr machinery to compute the output_name and for_name-s of each
1874 input_file. We have a sequence of file rules which gives the POSIX
1875 extended regular expression to match an input file path, and two
1876 transformed strings for the corresponding output_name and the
1877 corresponding for_name. The transformed string contain dollars: $0
1878 is replaced by the entire match, $1 is replaced by the substring
1879 matching the first parenthesis in the regexp, etc. And $$ is replaced
1880 by a single verbatim dollar. The rule order is important. The
1881 general case is last, and the particular cases should come before.
1882 An action routine can, when needed, update the out_name & for_name
1883 and/or return the appropriate output file. It is invoked only when a
1884 rule is triggered. When a rule is triggered, the output_name and
1885 for_name are computed using their transform string in while $$, $0,
1886 $1, ... are suitably replaced. If there is an action, it is called.
1887 In some few cases, the action can directly return the outf_p, but
1888 usually it just updates the output_name and for_name so should free
1889 them before replacing them. The get_output_file_with_visibility
1890 function creates an outf_p only once per each output_name, so it
1891 scans the output_files list for previously seen output file names.
1894 /* Signature of actions in file rules. */
1895 typedef outf_p (frul_actionrout_t) (input_file*, char**, char**);
1898 struct file_rule_st {
1899 const char* frul_srcexpr; /* Source string for regexp. */
1900 int frul_rflags; /* Flags passed to regcomp, usually
1901 * REG_EXTENDED. */
1902 regex_t* frul_re; /* Compiled regular expression
1903 obtained by regcomp. */
1904 const char* frul_tr_out; /* Transformation string for making
1905 * the output_name, with $1 ... $9 for
1906 * subpatterns and $0 for the whole
1907 * matched filename. */
1908 const char* frul_tr_for; /* Tranformation string for making the
1909 for_name. */
1910 frul_actionrout_t* frul_action; /* The action, if non null, is
1911 * called once the rule matches, on
1912 * the transformed out_name &
1913 * for_name. It could change them
1914 * and/or give the output file. */
1917 /* File rule action handling *.h files. */
1918 static outf_p header_dot_h_frul (input_file*, char**, char**);
1920 /* File rule action handling *.cc files. */
1921 static outf_p source_dot_cc_frul (input_file*, char**, char**);
1923 #define NULL_REGEX (regex_t*)0
1925 /* The prefix in our regexp-s matching the directory. */
1926 #define DIR_PREFIX_REGEX "^(([^/]*/)*)"
1928 #define NULL_FRULACT (frul_actionrout_t*)0
1930 /* The array of our rules governing file name generation. Rules order
1931 matters, so change with extreme care! */
1933 struct file_rule_st files_rules[] = {
1934 /* The general rule assumes that files in subdirectories belong to a
1935 particular front-end, and files not in subdirectories are shared.
1936 The following rules deal with exceptions - files that are in
1937 subdirectories and yet are shared, and files that are top-level,
1938 but are not shared. */
1940 /* the c-family/ source directory is special. */
1941 { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.cc$",
1942 REG_EXTENDED, NULL_REGEX,
1943 "gt-c-family-$3.h", "c-family/$3.cc", NULL_FRULACT},
1945 { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.h$",
1946 REG_EXTENDED, NULL_REGEX,
1947 "gt-c-family-$3.h", "c-family/$3.h", NULL_FRULACT},
1949 /* Both c-lang.h & c-tree.h gives gt-c-c-decl.h for c-decl.cc ! */
1950 { DIR_PREFIX_REGEX "c/c-lang\\.h$",
1951 REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.cc", NULL_FRULACT},
1953 { DIR_PREFIX_REGEX "c/c-tree\\.h$",
1954 REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.cc", NULL_FRULACT},
1956 /* cp/cp-tree.h gives gt-cp-tree.h for cp/tree.cc ! */
1957 { DIR_PREFIX_REGEX "cp/cp-tree\\.h$",
1958 REG_EXTENDED, NULL_REGEX,
1959 "gt-cp-tree.h", "cp/tree.cc", NULL_FRULACT },
1961 /* cp/decl.h & cp/decl.cc gives gt-cp-decl.h for cp/decl.cc ! */
1962 { DIR_PREFIX_REGEX "cp/decl\\.[ch]$",
1963 REG_EXTENDED, NULL_REGEX,
1964 "gt-cp-decl.h", "cp/decl.cc", NULL_FRULACT },
1966 /* cp/name-lookup.h gives gt-cp-name-lookup.h for cp/name-lookup.cc ! */
1967 { DIR_PREFIX_REGEX "cp/name-lookup\\.h$",
1968 REG_EXTENDED, NULL_REGEX,
1969 "gt-cp-name-lookup.h", "cp/name-lookup.cc", NULL_FRULACT },
1971 /* cp/parser.h gives gt-cp-parser.h for cp/parser.cc ! */
1972 { DIR_PREFIX_REGEX "cp/parser\\.h$",
1973 REG_EXTENDED, NULL_REGEX,
1974 "gt-cp-parser.h", "cp/parser.cc", NULL_FRULACT },
1976 /* objc/objc-act.h gives gt-objc-objc-act.h for objc/objc-act.cc ! */
1977 { DIR_PREFIX_REGEX "objc/objc-act\\.h$",
1978 REG_EXTENDED, NULL_REGEX,
1979 "gt-objc-objc-act.h", "objc/objc-act.cc", NULL_FRULACT },
1981 /* objc/objc-map.h gives gt-objc-objc-map.h for objc/objc-map.cc ! */
1982 { DIR_PREFIX_REGEX "objc/objc-map\\.h$",
1983 REG_EXTENDED, NULL_REGEX,
1984 "gt-objc-objc-map.h", "objc/objc-map.cc", NULL_FRULACT },
1986 /* General cases. For header *.h and *.cc files, we
1987 * need special actions to handle the language. */
1989 /* Source *.cc files are using get_file_gtfilename to compute their
1990 output_name and get_file_basename to compute their for_name
1991 through the source_dot_cc_frul action. */
1992 { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.cc$",
1993 REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.cc", source_dot_cc_frul},
1995 /* Common header files get "gtype-desc.cc" as their output_name,
1996 * while language specific header files are handled specially. So
1997 * we need the header_dot_h_frul action. */
1998 { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.h$",
1999 REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.h", header_dot_h_frul},
2001 { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.in$",
2002 REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.in", NULL_FRULACT},
2004 /* Mandatory null last entry signaling end of rules. */
2005 {NULL, 0, NULL_REGEX, NULL, NULL, NULL_FRULACT}
2008 /* Special file rules action for handling *.h header files. It gives
2009 "gtype-desc.cc" for common headers and corresponding output
2010 files for language-specific header files. */
2011 static outf_p
2012 header_dot_h_frul (input_file* inpf, char**poutname,
2013 char**pforname ATTRIBUTE_UNUSED)
2015 const char *basename = 0;
2016 int lang_index = 0;
2017 DBGPRINTF ("inpf %p inpname %s outname %s forname %s",
2018 (void*) inpf, get_input_file_name (inpf),
2019 *poutname, *pforname);
2020 basename = get_file_basename (inpf);
2021 lang_index = get_prefix_langdir_index (basename);
2022 DBGPRINTF ("basename %s lang_index %d", basename, lang_index);
2024 if (lang_index >= 0)
2026 /* The header is language specific. Given output_name &
2027 for_name remains unchanged. The base_files array gives the
2028 outf_p. */
2029 DBGPRINTF ("header_dot_h found language specific @ %p '%s'",
2030 (void*) base_files[lang_index],
2031 (base_files[lang_index])->name);
2032 return base_files[lang_index];
2034 else
2036 /* The header is common to all front-end languages. So
2037 output_name is "gtype-desc.cc" file. The calling function
2038 get_output_file_with_visibility will find its outf_p. */
2039 free (*poutname);
2040 *poutname = xstrdup ("gtype-desc.cc");
2041 DBGPRINTF ("special 'gtype-desc.cc' for inpname %s",
2042 get_input_file_name (inpf));
2043 return NULL;
2048 /* Special file rules action for handling *.cc source files using
2049 * get_file_gtfilename to compute their output_name and
2050 * get_file_basename to compute their for_name. The output_name is
2051 * gt-<LANG>-<BASE>.h for language specific source files, and
2052 * gt-<BASE>.h for common source files. */
2053 static outf_p
2054 source_dot_cc_frul (input_file* inpf, char**poutname, char**pforname)
2056 char *newbasename = CONST_CAST (char*, get_file_basename (inpf));
2057 char *newoutname = CONST_CAST (char*, get_file_gtfilename (inpf));
2058 DBGPRINTF ("inpf %p inpname %s original outname %s forname %s",
2059 (void*) inpf, get_input_file_name (inpf),
2060 *poutname, *pforname);
2061 DBGPRINTF ("newoutname %s", newoutname);
2062 DBGPRINTF ("newbasename %s", newbasename);
2063 free (*poutname);
2064 free (*pforname);
2065 *poutname = newoutname;
2066 *pforname = newbasename;
2067 return NULL;
2070 /* Utility function for get_output_file_with_visibility which returns
2071 * a malloc-ed substituted string using TRS on matching of the FILNAM
2072 * file name, using the PMATCH array. */
2073 static char*
2074 matching_file_name_substitute (const char *filnam, regmatch_t pmatch[10],
2075 const char *trs)
2077 struct obstack str_obstack;
2078 char *str = NULL;
2079 char *rawstr = NULL;
2080 const char *pt = NULL;
2081 DBGPRINTF ("filnam %s", filnam);
2082 obstack_init (&str_obstack);
2083 for (pt = trs; *pt; pt++) {
2084 char c = *pt;
2085 if (c == '$')
2087 if (pt[1] == '$')
2089 /* A double dollar $$ is substituted by a single verbatim
2090 dollar, but who really uses dollar signs in file
2091 paths? */
2092 obstack_1grow (&str_obstack, '$');
2094 else if (ISDIGIT (pt[1]))
2096 /* Handle $0 $1 ... $9 by appropriate substitution. */
2097 int dolnum = pt[1] - '0';
2098 int so = pmatch[dolnum].rm_so;
2099 int eo = pmatch[dolnum].rm_eo;
2100 DBGPRINTF ("so=%d eo=%d dolnum=%d", so, eo, dolnum);
2101 if (so>=0 && eo>=so)
2102 obstack_grow (&str_obstack, filnam + so, eo - so);
2104 else
2106 /* This can happen only when files_rules is buggy! */
2107 gcc_unreachable ();
2109 /* Always skip the character after the dollar. */
2110 pt++;
2112 else
2113 obstack_1grow (&str_obstack, c);
2115 obstack_1grow (&str_obstack, '\0');
2116 rawstr = XOBFINISH (&str_obstack, char *);
2117 str = xstrdup (rawstr);
2118 obstack_free (&str_obstack, NULL);
2119 DBGPRINTF ("matched replacement %s", str);
2120 rawstr = NULL;
2121 return str;
2125 /* An output file, suitable for definitions, that can see declarations
2126 made in INPF and is linked into every language that uses INPF.
2127 Since the result is cached inside INPF, that argument cannot be
2128 declared constant, but is "almost" constant. */
2130 outf_p
2131 get_output_file_with_visibility (input_file *inpf)
2133 outf_p r;
2134 char *for_name = NULL;
2135 char *output_name = NULL;
2136 const char* inpfname;
2138 /* This can happen when we need a file with visibility on a
2139 structure that we've never seen. We have to just hope that it's
2140 globally visible. */
2141 if (inpf == NULL)
2142 inpf = system_h_file;
2144 /* The result is cached in INPF, so return it if already known. */
2145 if (inpf->inpoutf)
2146 return inpf->inpoutf;
2148 /* In plugin mode, return NULL unless the input_file is one of the
2149 plugin_files. */
2150 if (plugin_files)
2152 size_t i;
2153 for (i = 0; i < nb_plugin_files; i++)
2154 if (inpf == plugin_files[i])
2156 inpf->inpoutf = plugin_output;
2157 return plugin_output;
2160 return NULL;
2163 inpfname = get_input_file_name (inpf);
2165 /* Try each rule in sequence in files_rules until one is triggered. */
2167 int rulix = 0;
2168 DBGPRINTF ("passing input file @ %p named %s through the files_rules",
2169 (void*) inpf, inpfname);
2171 for (; files_rules[rulix].frul_srcexpr != NULL; rulix++)
2173 DBGPRINTF ("rulix#%d srcexpr %s",
2174 rulix, files_rules[rulix].frul_srcexpr);
2176 if (!files_rules[rulix].frul_re)
2178 /* Compile the regexpr lazily. */
2179 int err = 0;
2180 files_rules[rulix].frul_re = XCNEW (regex_t);
2181 err = regcomp (files_rules[rulix].frul_re,
2182 files_rules[rulix].frul_srcexpr,
2183 files_rules[rulix].frul_rflags);
2184 if (err)
2186 /* The regular expression compilation fails only when
2187 file_rules is buggy. */
2188 gcc_unreachable ();
2192 output_name = NULL;
2193 for_name = NULL;
2195 /* Match the regexpr and trigger the rule if matched. */
2197 /* We have exactly ten pmatch-s, one for each $0, $1, $2,
2198 $3, ... $9. */
2199 regmatch_t pmatch[10];
2200 memset (pmatch, 0, sizeof (pmatch));
2201 if (!regexec (files_rules[rulix].frul_re,
2202 inpfname, 10, pmatch, 0))
2204 DBGPRINTF ("input @ %p filename %s matched rulix#%d pattern %s",
2205 (void*) inpf, inpfname, rulix,
2206 files_rules[rulix].frul_srcexpr);
2207 for_name =
2208 matching_file_name_substitute (inpfname, pmatch,
2209 files_rules[rulix].frul_tr_for);
2210 DBGPRINTF ("for_name %s", for_name);
2211 output_name =
2212 matching_file_name_substitute (inpfname, pmatch,
2213 files_rules[rulix].frul_tr_out);
2214 DBGPRINTF ("output_name %s", output_name);
2215 if (files_rules[rulix].frul_action)
2217 /* Invoke our action routine. */
2218 outf_p of = NULL;
2219 DBGPRINTF ("before action rulix#%d output_name %s for_name %s",
2220 rulix, output_name, for_name);
2221 of =
2222 (files_rules[rulix].frul_action) (inpf,
2223 &output_name, &for_name);
2224 DBGPRINTF ("after action rulix#%d of=%p output_name %s for_name %s",
2225 rulix, (void*)of, output_name, for_name);
2226 /* If the action routine returned something, give it back
2227 immediately and cache it in inpf. */
2228 if (of)
2230 inpf->inpoutf = of;
2231 return of;
2234 /* The rule matched, and had no action, or that action did
2235 not return any output file but could have changed the
2236 output_name or for_name. We break out of the loop on the
2237 files_rules. */
2238 break;
2240 else
2242 /* The regexpr did not match. */
2243 DBGPRINTF ("rulix#%d did not match %s pattern %s",
2244 rulix, inpfname, files_rules[rulix].frul_srcexpr);
2245 continue;
2250 if (!output_name || !for_name)
2252 /* This should not be possible, and could only happen if the
2253 files_rules is incomplete or buggy. */
2254 fatal ("failed to compute output name for %s", inpfname);
2257 /* Look through to see if we've ever seen this output filename
2258 before. If found, cache the result in inpf. */
2259 for (r = output_files; r; r = r->next)
2260 if (filename_cmp (r->name, output_name) == 0)
2262 inpf->inpoutf = r;
2263 DBGPRINTF ("found r @ %p for output_name %s for_name %s", (void*)r,
2264 output_name, for_name);
2265 return r;
2268 /* If not found, create it, and cache it in inpf. */
2269 r = create_file (for_name, output_name);
2271 gcc_assert (r && r->name);
2272 DBGPRINTF ("created r @ %p for output_name %s for_name %s", (void*) r,
2273 output_name, for_name);
2274 inpf->inpoutf = r;
2275 return r;
2280 /* The name of an output file, suitable for definitions, that can see
2281 declarations made in INPF and is linked into every language that
2282 uses INPF. */
2284 const char *
2285 get_output_file_name (input_file* inpf)
2287 outf_p o = get_output_file_with_visibility (inpf);
2288 if (o)
2289 return o->name;
2290 return NULL;
2293 /* Check if existing file is equal to the in memory buffer. */
2295 static bool
2296 is_file_equal (outf_p of)
2298 FILE *newfile = fopen (of->name, "r");
2299 size_t i;
2300 bool equal;
2301 if (newfile == NULL)
2302 return false;
2304 equal = true;
2305 for (i = 0; i < of->bufused; i++)
2307 int ch;
2308 ch = fgetc (newfile);
2309 if (ch == EOF || ch != (unsigned char) of->buf[i])
2311 equal = false;
2312 break;
2315 if (equal && EOF != fgetc (newfile))
2316 equal = false;
2317 fclose (newfile);
2318 return equal;
2321 /* Copy the output to its final destination,
2322 but don't unnecessarily change modification times. */
2324 static void
2325 close_output_files (void)
2327 int nbwrittenfiles = 0;
2328 outf_p of;
2330 for (of = output_files; of; of = of->next)
2332 if (!is_file_equal (of))
2334 FILE *newfile = NULL;
2335 char *backupname = NULL;
2336 /* Back up the old version of the output file gt-FOO.cc as
2337 BACKUPDIR/gt-FOO.cc~ if we have a backup directory. */
2338 if (backup_dir)
2340 backupname = concat (backup_dir, "/",
2341 lbasename (of->name), "~", NULL);
2342 if (!access (of->name, F_OK) && rename (of->name, backupname))
2343 fatal ("failed to back up %s as %s: %s",
2344 of->name, backupname, xstrerror (errno));
2347 newfile = fopen (of->name, "w");
2348 if (newfile == NULL)
2349 fatal ("opening output file %s: %s", of->name, xstrerror (errno));
2350 if (fwrite (of->buf, 1, of->bufused, newfile) != of->bufused)
2351 fatal ("writing output file %s: %s", of->name, xstrerror (errno));
2352 if (fclose (newfile) != 0)
2353 fatal ("closing output file %s: %s", of->name, xstrerror (errno));
2354 nbwrittenfiles++;
2355 if (verbosity_level >= 2 && backupname)
2356 printf ("%s wrote #%-3d %s backed-up in %s\n",
2357 progname, nbwrittenfiles, of->name, backupname);
2358 else if (verbosity_level >= 1)
2359 printf ("%s write #%-3d %s\n", progname, nbwrittenfiles, of->name);
2360 free (backupname);
2362 else
2364 /* output file remains unchanged. */
2365 if (verbosity_level >= 2)
2366 printf ("%s keep %s\n", progname, of->name);
2368 free (of->buf);
2369 of->buf = NULL;
2370 of->bufused = of->buflength = 0;
2372 if (verbosity_level >= 1)
2373 printf ("%s wrote %d files.\n", progname, nbwrittenfiles);
2376 struct flist
2378 struct flist *next;
2379 int started_p;
2380 const input_file* file;
2381 outf_p f;
2384 struct walk_type_data;
2386 /* For scalars and strings, given the item in 'val'.
2387 For structures, given a pointer to the item in 'val'.
2388 For misc. pointers, given the item in 'val'.
2390 typedef void (*process_field_fn) (type_p f, const struct walk_type_data * p);
2391 typedef void (*func_name_fn) (type_p s, const struct walk_type_data * p);
2393 /* Parameters for write_types. */
2395 struct write_types_data
2397 const char *prefix;
2398 const char *param_prefix;
2399 const char *subfield_marker_routine;
2400 const char *marker_routine;
2401 const char *reorder_note_routine;
2402 const char *comment;
2403 enum write_types_kinds kind;
2406 static void output_escaped_param (const struct walk_type_data *d,
2407 const char *, const char *);
2408 static void output_mangled_typename (outf_p, const_type_p);
2409 static void walk_type (type_p t, struct walk_type_data *d);
2410 static void write_func_for_structure (type_p orig_s, type_p s,
2411 const struct write_types_data *wtd);
2412 static void write_types_process_field
2413 (type_p f, const struct walk_type_data *d);
2414 static void write_types (outf_p output_header,
2415 type_p structures,
2416 const struct write_types_data *wtd);
2417 static void write_types_local_process_field
2418 (type_p f, const struct walk_type_data *d);
2419 static void write_local_func_for_structure (const_type_p orig_s, type_p s);
2420 static void write_local (outf_p output_header,
2421 type_p structures);
2422 static int contains_scalar_p (type_p t);
2423 static void put_mangled_filename (outf_p, const input_file *);
2424 static void finish_root_table (struct flist *flp, const char *pfx,
2425 const char *lastname,
2426 const char *tname, const char *name);
2427 static void write_root (outf_p, pair_p, type_p, const char *, int,
2428 struct fileloc *, bool);
2429 static void write_array (outf_p f, pair_p v,
2430 const struct write_types_data *wtd);
2431 static void write_roots (pair_p, bool);
2433 /* Parameters for walk_type. */
2435 struct walk_type_data
2437 process_field_fn process_field;
2438 const void *cookie;
2439 outf_p of;
2440 options_p opt;
2441 const char *val;
2442 const char *prev_val[4];
2443 int indent;
2444 int counter;
2445 const struct fileloc *line;
2446 lang_bitmap bitmap;
2447 int used_length;
2448 type_p orig_s;
2449 const char *reorder_fn;
2450 bool needs_cast_p;
2451 bool fn_wants_lvalue;
2452 bool in_record_p;
2453 int loopcounter;
2454 bool in_ptr_field;
2455 bool have_this_obj;
2456 bool in_nested_ptr;
2460 /* Given a string TYPE_NAME, representing a C++ typename, return a valid
2461 pre-processor identifier to use in a #define directive. This replaces
2462 special characters used in C++ identifiers like '>', '<' and ':' with
2463 '_'.
2465 If no C++ special characters are found in TYPE_NAME, return
2466 TYPE_NAME. Otherwise, return a copy of TYPE_NAME with the special
2467 characters replaced with '_'. In this case, the caller is
2468 responsible for freeing the allocated string. */
2470 static const char *
2471 filter_type_name (const char *type_name)
2473 if (strchr (type_name, '<') || strchr (type_name, ':'))
2475 size_t i;
2476 char *s = xstrdup (type_name);
2477 for (i = 0; i < strlen (s); i++)
2478 if (s[i] == '<' || s[i] == '>' || s[i] == ':' || s[i] == ','
2479 || s[i] == '*')
2480 s[i] = '_';
2481 return s;
2483 else
2484 return type_name;
2488 /* Print a mangled name representing T to OF. */
2490 static void
2491 output_mangled_typename (outf_p of, const_type_p t)
2493 if (t == NULL)
2494 oprintf (of, "Z");
2495 else
2496 switch (t->kind)
2498 case TYPE_NONE:
2499 case TYPE_UNDEFINED:
2500 case TYPE_CALLBACK:
2501 gcc_unreachable ();
2502 break;
2503 case TYPE_POINTER:
2504 oprintf (of, "P");
2505 output_mangled_typename (of, t->u.p);
2506 break;
2507 case TYPE_SCALAR:
2508 oprintf (of, "I");
2509 break;
2510 case TYPE_STRING:
2511 oprintf (of, "S");
2512 break;
2513 case TYPE_STRUCT:
2514 case TYPE_UNION:
2515 case TYPE_LANG_STRUCT:
2516 case TYPE_USER_STRUCT:
2518 /* For references to classes within an inheritance hierarchy,
2519 only ever reference the ultimate base class, since only
2520 it will have gt_ functions. */
2521 t = get_ultimate_base_class (t);
2522 const char *id_for_tag = filter_type_name (t->u.s.tag);
2523 oprintf (of, "%lu%s", (unsigned long) strlen (id_for_tag),
2524 id_for_tag);
2525 if (id_for_tag != t->u.s.tag)
2526 free (CONST_CAST (char *, id_for_tag));
2528 break;
2529 case TYPE_ARRAY:
2530 gcc_unreachable ();
2534 /* Print PARAM to D->OF processing escapes. D->VAL references the
2535 current object, D->PREV_VAL the object containing the current
2536 object, ONAME is the name of the option and D->LINE is used to
2537 print error messages. */
2539 static void
2540 output_escaped_param (const struct walk_type_data *d, const char *param,
2541 const char *oname)
2543 const char *p;
2545 for (p = param; *p; p++)
2546 if (*p != '%')
2547 oprintf (d->of, "%c", *p);
2548 else
2549 switch (*++p)
2551 case 'h':
2552 oprintf (d->of, "(%s)", d->prev_val[2]);
2553 break;
2554 case '0':
2555 oprintf (d->of, "(%s)", d->prev_val[0]);
2556 break;
2557 case '1':
2558 oprintf (d->of, "(%s)", d->prev_val[1]);
2559 break;
2560 case 'a':
2562 const char *pp = d->val + strlen (d->val);
2563 while (pp[-1] == ']')
2564 while (*pp != '[')
2565 pp--;
2566 oprintf (d->of, "%s", pp);
2568 break;
2569 default:
2570 error_at_line (d->line, "`%s' option contains bad escape %c%c",
2571 oname, '%', *p);
2575 const char *
2576 get_string_option (options_p opt, const char *key)
2578 for (; opt; opt = opt->next)
2579 if (opt->kind == OPTION_STRING && strcmp (opt->name, key) == 0)
2580 return opt->info.string;
2581 return NULL;
2584 /* Machinery for avoiding duplicate tags within switch statements. */
2585 struct seen_tag
2587 const char *tag;
2588 struct seen_tag *next;
2592 already_seen_tag (struct seen_tag *seen_tags, const char *tag)
2594 /* Linear search, so O(n^2), but n is currently small. */
2595 while (seen_tags)
2597 if (!strcmp (seen_tags->tag, tag))
2598 return 1;
2599 seen_tags = seen_tags->next;
2601 /* Not yet seen this tag. */
2602 return 0;
2605 void
2606 mark_tag_as_seen (struct seen_tag **seen_tags, const char *tag)
2608 /* Add to front of linked list. */
2609 struct seen_tag *new_node = XCNEW (struct seen_tag);
2610 new_node->tag = tag;
2611 new_node->next = *seen_tags;
2612 *seen_tags = new_node;
2615 static void
2616 walk_subclasses (type_p base, struct walk_type_data *d,
2617 struct seen_tag **seen_tags)
2619 for (type_p sub = base->u.s.first_subclass; sub != NULL;
2620 sub = sub->u.s.next_sibling_class)
2622 const char *type_tag = get_string_option (sub->u.s.opt, "tag");
2623 if (type_tag && !already_seen_tag (*seen_tags, type_tag))
2625 mark_tag_as_seen (seen_tags, type_tag);
2626 oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
2627 d->indent += 2;
2628 oprintf (d->of, "%*s{\n", d->indent, "");
2629 d->indent += 2;
2630 oprintf (d->of, "%*s%s *sub = static_cast <%s *> (x);\n",
2631 d->indent, "", sub->u.s.tag, sub->u.s.tag);
2632 const char *old_val = d->val;
2633 d->val = "(*sub)";
2634 walk_type (sub, d);
2635 d->val = old_val;
2636 d->indent -= 2;
2637 oprintf (d->of, "%*s}\n", d->indent, "");
2638 oprintf (d->of, "%*sbreak;\n", d->indent, "");
2639 d->indent -= 2;
2641 walk_subclasses (sub, d, seen_tags);
2645 /* Call D->PROCESS_FIELD for every field (or subfield) of D->VAL,
2646 which is of type T. Write code to D->OF to constrain execution (at
2647 the point that D->PROCESS_FIELD is called) to the appropriate
2648 cases. Call D->PROCESS_FIELD on subobjects before calling it on
2649 pointers to those objects. D->PREV_VAL lists the objects
2650 containing the current object, D->OPT is a list of options to
2651 apply, D->INDENT is the current indentation level, D->LINE is used
2652 to print error messages, D->BITMAP indicates which languages to
2653 print the structure for. */
2655 static void
2656 walk_type (type_p t, struct walk_type_data *d)
2658 const char *length = NULL;
2659 const char *desc = NULL;
2660 const char *type_tag = NULL;
2661 int maybe_undef_p = 0;
2662 int atomic_p = 0;
2663 options_p oo;
2664 const struct nested_ptr_data *nested_ptr_d = NULL;
2666 d->needs_cast_p = false;
2667 for (oo = d->opt; oo; oo = oo->next)
2668 if (strcmp (oo->name, "length") == 0 && oo->kind == OPTION_STRING)
2669 length = oo->info.string;
2670 else if (strcmp (oo->name, "maybe_undef") == 0)
2671 maybe_undef_p = 1;
2672 else if (strcmp (oo->name, "desc") == 0 && oo->kind == OPTION_STRING)
2673 desc = oo->info.string;
2674 else if (strcmp (oo->name, "nested_ptr") == 0
2675 && oo->kind == OPTION_NESTED)
2676 nested_ptr_d = (const struct nested_ptr_data *) oo->info.nested;
2677 else if (strcmp (oo->name, "dot") == 0)
2679 else if (strcmp (oo->name, "tag") == 0)
2680 type_tag = oo->info.string;
2681 else if (strcmp (oo->name, "special") == 0)
2683 else if (strcmp (oo->name, "skip") == 0)
2685 else if (strcmp (oo->name, "atomic") == 0)
2686 atomic_p = 1;
2687 else if (strcmp (oo->name, "default") == 0)
2689 else if (strcmp (oo->name, "chain_next") == 0)
2691 else if (strcmp (oo->name, "chain_prev") == 0)
2693 else if (strcmp (oo->name, "chain_circular") == 0)
2695 else if (strcmp (oo->name, "reorder") == 0)
2697 else if (strcmp (oo->name, "variable_size") == 0)
2699 else if (strcmp (oo->name, "for_user") == 0)
2701 else if (strcmp (oo->name, "callback") == 0)
2703 else if (strcmp (oo->name, "string_length") == 0)
2705 else
2706 error_at_line (d->line, "unknown option `%s'\n", oo->name);
2708 if (d->used_length)
2709 length = NULL;
2711 if (maybe_undef_p
2712 && (t->kind != TYPE_POINTER || !union_or_struct_p (t->u.p)))
2714 error_at_line (d->line,
2715 "field `%s' has invalid option `maybe_undef_p'\n",
2716 d->val);
2717 return;
2720 if (atomic_p && (t->kind != TYPE_POINTER) && (t->kind != TYPE_STRING))
2722 error_at_line (d->line, "field `%s' has invalid option `atomic'\n", d->val);
2723 return;
2726 switch (t->kind)
2728 case TYPE_SCALAR:
2729 case TYPE_STRING:
2730 case TYPE_CALLBACK:
2731 d->process_field (t, d);
2732 break;
2734 case TYPE_POINTER:
2736 d->in_ptr_field = true;
2737 if (maybe_undef_p && t->u.p->u.s.line.file == NULL)
2739 oprintf (d->of, "%*sgcc_assert (!%s);\n", d->indent, "", d->val);
2740 break;
2743 /* If a pointer type is marked as "atomic", we process the
2744 field itself, but we don't walk the data that they point to.
2746 There are two main cases where we walk types: to mark
2747 pointers that are reachable, and to relocate pointers when
2748 writing a PCH file. In both cases, an atomic pointer is
2749 itself marked or relocated, but the memory that it points
2750 to is left untouched. In the case of PCH, that memory will
2751 be read/written unchanged to the PCH file. */
2752 if (atomic_p)
2754 oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
2755 d->indent += 2;
2756 d->process_field (t, d);
2757 d->indent -= 2;
2758 oprintf (d->of, "%*s}\n", d->indent, "");
2759 break;
2762 if (!length)
2764 if (!union_or_struct_p (t->u.p))
2766 error_at_line (d->line,
2767 "field `%s' is pointer to unimplemented type",
2768 d->val);
2769 break;
2772 if (nested_ptr_d)
2774 const char *oldprevval2 = d->prev_val[2];
2775 bool old_in_nested_ptr = d->in_nested_ptr;
2777 if (!union_or_struct_p (nested_ptr_d->type))
2779 error_at_line (d->line,
2780 "field `%s' has invalid "
2781 "option `nested_ptr'\n", d->val);
2782 return;
2785 d->prev_val[2] = d->val;
2786 d->in_nested_ptr = true;
2787 oprintf (d->of, "%*s{\n", d->indent, "");
2788 d->indent += 2;
2789 d->val = xasprintf ("x%d", d->counter++);
2790 oprintf (d->of, "%*s%s %s * %s%s =\n", d->indent, "",
2791 (nested_ptr_d->type->kind == TYPE_UNION
2792 ? "union" : "struct"),
2793 nested_ptr_d->type->u.s.tag,
2794 d->fn_wants_lvalue ? "" : "const ", d->val);
2795 oprintf (d->of, "%*s", d->indent + 2, "");
2796 output_escaped_param (d, nested_ptr_d->convert_from,
2797 "nested_ptr");
2798 oprintf (d->of, ";\n");
2800 d->process_field (nested_ptr_d->type, d);
2802 if (d->fn_wants_lvalue)
2804 oprintf (d->of, "%*s%s = ", d->indent, "",
2805 d->prev_val[2]);
2806 d->prev_val[2] = d->val;
2807 output_escaped_param (d, nested_ptr_d->convert_to,
2808 "nested_ptr");
2809 oprintf (d->of, ";\n");
2812 d->indent -= 2;
2813 oprintf (d->of, "%*s}\n", d->indent, "");
2814 d->val = d->prev_val[2];
2815 d->prev_val[2] = oldprevval2;
2816 d->in_nested_ptr = old_in_nested_ptr;
2818 else
2819 d->process_field (t->u.p, d);
2821 else
2823 int loopcounter = d->loopcounter;
2824 const char *oldval = d->val;
2825 const char *oldprevval3 = d->prev_val[3];
2826 char *newval;
2828 oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
2829 d->indent += 2;
2830 oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2831 oprintf (d->of, "%*sfor (i%d = 0; i%d != (size_t)(", d->indent,
2832 "", loopcounter, loopcounter);
2833 if (!d->in_record_p)
2834 output_escaped_param (d, length, "length");
2835 else
2836 oprintf (d->of, "l%d", loopcounter);
2837 if (d->have_this_obj)
2838 /* Try to unswitch loops (see PR53880). */
2839 oprintf (d->of, ") && ((void *)%s == this_obj", oldval);
2840 oprintf (d->of, "); i%d++) {\n", loopcounter);
2841 d->indent += 2;
2842 d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2843 d->used_length = 1;
2844 d->prev_val[3] = oldval;
2845 walk_type (t->u.p, d);
2846 free (newval);
2847 d->val = oldval;
2848 d->prev_val[3] = oldprevval3;
2849 d->used_length = 0;
2850 d->indent -= 2;
2851 oprintf (d->of, "%*s}\n", d->indent, "");
2852 d->process_field (t, d);
2853 d->indent -= 2;
2854 oprintf (d->of, "%*s}\n", d->indent, "");
2856 d->in_ptr_field = false;
2858 break;
2860 case TYPE_ARRAY:
2862 int loopcounter;
2863 const char *oldval = d->val;
2864 char *newval;
2866 /* If it's an array of scalars, we optimize by not generating
2867 any code. */
2868 if (t->u.a.p->kind == TYPE_SCALAR)
2869 break;
2871 if (length)
2872 loopcounter = d->loopcounter;
2873 else
2874 loopcounter = d->counter++;
2876 /* When walking an array, compute the length and store it in a
2877 local variable before walking the array elements, instead of
2878 recomputing the length expression each time through the loop.
2879 This is necessary to handle tcc_vl_exp objects like CALL_EXPR,
2880 where the length is stored in the first array element,
2881 because otherwise that operand can get overwritten on the
2882 first iteration. */
2883 oprintf (d->of, "%*s{\n", d->indent, "");
2884 d->indent += 2;
2885 oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2886 if (!d->in_record_p || !length)
2888 oprintf (d->of, "%*ssize_t l%d = (size_t)(",
2889 d->indent, "", loopcounter);
2890 if (length)
2891 output_escaped_param (d, length, "length");
2892 else
2893 oprintf (d->of, "%s", t->u.a.len);
2894 oprintf (d->of, ");\n");
2897 oprintf (d->of, "%*sfor (i%d = 0; i%d != l%d; i%d++) {\n",
2898 d->indent, "",
2899 loopcounter, loopcounter, loopcounter, loopcounter);
2900 d->indent += 2;
2901 d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2902 d->used_length = 1;
2903 walk_type (t->u.a.p, d);
2904 free (newval);
2905 d->used_length = 0;
2906 d->val = oldval;
2907 d->indent -= 2;
2908 oprintf (d->of, "%*s}\n", d->indent, "");
2909 d->indent -= 2;
2910 oprintf (d->of, "%*s}\n", d->indent, "");
2912 break;
2914 case TYPE_STRUCT:
2915 case TYPE_UNION:
2917 pair_p f;
2918 const char *oldval = d->val;
2919 const char *oldprevval1 = d->prev_val[1];
2920 const char *oldprevval2 = d->prev_val[2];
2921 const int union_p = t->kind == TYPE_UNION;
2922 int seen_default_p = 0;
2923 options_p o;
2924 int lengths_seen = 0;
2925 int endcounter;
2926 bool any_length_seen = false;
2928 if (!t->u.s.line.file)
2929 error_at_line (d->line, "incomplete structure `%s'", t->u.s.tag);
2931 if ((d->bitmap & t->u.s.bitmap) != d->bitmap)
2933 error_at_line (d->line,
2934 "structure `%s' defined for mismatching languages",
2935 t->u.s.tag);
2936 error_at_line (&t->u.s.line, "one structure defined here");
2939 /* Some things may also be defined in the structure's options. */
2940 for (o = t->u.s.opt; o; o = o->next)
2941 if (!desc && strcmp (o->name, "desc") == 0
2942 && o->kind == OPTION_STRING)
2943 desc = o->info.string;
2945 d->prev_val[2] = oldval;
2946 d->prev_val[1] = oldprevval2;
2947 if (union_p)
2949 if (desc == NULL)
2951 error_at_line (d->line,
2952 "missing `desc' option for union `%s'",
2953 t->u.s.tag);
2954 desc = "1";
2956 oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
2957 output_escaped_param (d, desc, "desc");
2958 oprintf (d->of, "))\n");
2959 d->indent += 2;
2960 oprintf (d->of, "%*s{\n", d->indent, "");
2962 else if (desc)
2964 /* We have a "desc" option on a struct, signifying the
2965 base class within a GC-managed inheritance hierarchy.
2966 The current code specialcases the base class, then walks
2967 into subclasses, recursing into this routine to handle them.
2968 This organization requires the base class to have a case in
2969 the switch statement, and hence a tag value is mandatory
2970 for the base class. This restriction could be removed, but
2971 it would require some restructing of this code. */
2972 if (!type_tag)
2974 error_at_line (d->line,
2975 "missing `tag' option for type `%s'",
2976 t->u.s.tag);
2978 oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
2979 output_escaped_param (d, desc, "desc");
2980 oprintf (d->of, "))\n");
2981 d->indent += 2;
2982 oprintf (d->of, "%*s{\n", d->indent, "");
2983 oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
2984 d->indent += 2;
2987 FOR_ALL_INHERITED_FIELDS (t, f)
2989 options_p oo;
2990 int skip_p = 0;
2991 const char *fieldlength = NULL;
2993 d->reorder_fn = NULL;
2994 for (oo = f->opt; oo; oo = oo->next)
2995 if (strcmp (oo->name, "skip") == 0)
2996 skip_p = 1;
2997 else if (strcmp (oo->name, "length") == 0
2998 && oo->kind == OPTION_STRING)
2999 fieldlength = oo->info.string;
3001 if (skip_p)
3002 continue;
3003 if (fieldlength)
3005 lengths_seen++;
3006 d->counter++;
3007 if (!union_p)
3009 if (!any_length_seen)
3011 oprintf (d->of, "%*s{\n", d->indent, "");
3012 d->indent += 2;
3014 any_length_seen = true;
3016 oprintf (d->of, "%*ssize_t l%d = (size_t)(",
3017 d->indent, "", d->counter - 1);
3018 output_escaped_param (d, fieldlength, "length");
3019 oprintf (d->of, ");\n");
3023 endcounter = d->counter;
3025 FOR_ALL_INHERITED_FIELDS (t, f)
3027 options_p oo;
3028 const char *dot = ".";
3029 const char *tagid = NULL;
3030 int skip_p = 0;
3031 int default_p = 0;
3032 const char *fieldlength = NULL;
3033 char *newval;
3035 d->reorder_fn = NULL;
3036 for (oo = f->opt; oo; oo = oo->next)
3037 if (strcmp (oo->name, "dot") == 0
3038 && oo->kind == OPTION_STRING)
3039 dot = oo->info.string;
3040 else if (strcmp (oo->name, "tag") == 0
3041 && oo->kind == OPTION_STRING)
3042 tagid = oo->info.string;
3043 else if (strcmp (oo->name, "skip") == 0)
3044 skip_p = 1;
3045 else if (strcmp (oo->name, "default") == 0)
3046 default_p = 1;
3047 else if (strcmp (oo->name, "reorder") == 0
3048 && oo->kind == OPTION_STRING)
3049 d->reorder_fn = oo->info.string;
3050 else if (strcmp (oo->name, "length") == 0
3051 && oo->kind == OPTION_STRING)
3052 fieldlength = oo->info.string;
3054 if (skip_p)
3055 continue;
3057 if (union_p && tagid)
3059 oprintf (d->of, "%*scase %s:\n", d->indent, "", tagid);
3060 d->indent += 2;
3062 else if (union_p && default_p)
3064 oprintf (d->of, "%*sdefault:\n", d->indent, "");
3065 d->indent += 2;
3066 seen_default_p = 1;
3068 else if (!union_p && (default_p || tagid))
3069 error_at_line (d->line,
3070 "can't use `%s' outside a union on field `%s'",
3071 default_p ? "default" : "tag", f->name);
3072 else if (union_p && !(default_p || tagid)
3073 && f->type->kind == TYPE_SCALAR)
3075 fprintf (stderr,
3076 "%s:%d: warning: field `%s' is missing `tag' or `default' option\n",
3077 get_input_file_name (d->line->file), d->line->line,
3078 f->name);
3079 continue;
3081 else if (union_p && !(default_p || tagid))
3082 error_at_line (d->line,
3083 "field `%s' is missing `tag' or `default' option",
3084 f->name);
3086 if (fieldlength)
3088 d->loopcounter = endcounter - lengths_seen--;
3091 d->line = &f->line;
3092 d->val = newval = xasprintf ("%s%s%s", oldval, dot, f->name);
3093 d->opt = f->opt;
3094 d->used_length = false;
3095 d->in_record_p = !union_p;
3097 walk_type (f->type, d);
3099 d->in_record_p = false;
3101 free (newval);
3103 if (union_p)
3105 oprintf (d->of, "%*sbreak;\n", d->indent, "");
3106 d->indent -= 2;
3109 d->reorder_fn = NULL;
3111 d->val = oldval;
3112 d->prev_val[1] = oldprevval1;
3113 d->prev_val[2] = oldprevval2;
3115 if (union_p && !seen_default_p)
3117 oprintf (d->of, "%*sdefault:\n", d->indent, "");
3118 oprintf (d->of, "%*s break;\n", d->indent, "");
3121 if (desc && !union_p)
3123 oprintf (d->of, "%*sbreak;\n", d->indent, "");
3124 d->indent -= 2;
3126 if (union_p)
3128 oprintf (d->of, "%*s}\n", d->indent, "");
3129 d->indent -= 2;
3131 else if (desc)
3133 /* Add cases to handle subclasses. */
3134 struct seen_tag *tags = NULL;
3135 walk_subclasses (t, d, &tags);
3137 /* Ensure that if someone forgets a "tag" option that we don't
3138 silent fail to traverse that subclass's fields. */
3139 if (!seen_default_p)
3141 oprintf (d->of, "%*s/* Unrecognized tag value. */\n",
3142 d->indent, "");
3143 oprintf (d->of, "%*sdefault: gcc_unreachable (); \n",
3144 d->indent, "");
3147 /* End of the switch statement */
3148 oprintf (d->of, "%*s}\n", d->indent, "");
3149 d->indent -= 2;
3151 if (any_length_seen)
3153 d->indent -= 2;
3154 oprintf (d->of, "%*s}\n", d->indent, "");
3157 break;
3159 case TYPE_LANG_STRUCT:
3161 type_p nt;
3162 for (nt = t->u.s.lang_struct; nt; nt = nt->next)
3163 if ((d->bitmap & nt->u.s.bitmap) == d->bitmap)
3164 break;
3165 if (nt == NULL)
3166 error_at_line (d->line, "structure `%s' differs between languages",
3167 t->u.s.tag);
3168 else
3169 walk_type (nt, d);
3171 break;
3173 case TYPE_USER_STRUCT:
3174 d->process_field (t, d);
3175 break;
3177 case TYPE_NONE:
3178 case TYPE_UNDEFINED:
3179 gcc_unreachable ();
3183 /* process_field routine for marking routines. */
3185 static void
3186 write_types_process_field (type_p f, const struct walk_type_data *d)
3188 const struct write_types_data *wtd;
3189 const char *cast = d->needs_cast_p ? "(void *)" : "";
3190 wtd = (const struct write_types_data *) d->cookie;
3192 switch (f->kind)
3194 case TYPE_NONE:
3195 case TYPE_UNDEFINED:
3196 gcc_unreachable ();
3197 case TYPE_POINTER:
3198 oprintf (d->of, "%*s%s (%s%s", d->indent, "",
3199 wtd->subfield_marker_routine, cast, d->val);
3200 if (wtd->param_prefix)
3202 if (f->u.p->kind == TYPE_SCALAR)
3203 /* The current type is a pointer to a scalar (so not
3204 considered like a pointer to instances of user defined
3205 types) and we are seeing it; it means we must be even
3206 more careful about the second argument of the
3207 SUBFIELD_MARKER_ROUTINE call. That argument must
3208 always be the instance of the type for which
3209 write_func_for_structure was called - this really is
3210 what the function SUBFIELD_MARKER_ROUTINE expects.
3211 That is, it must be an instance of the ORIG_S type
3212 parameter of write_func_for_structure. The convention
3213 is that that argument must be "x" in that case (as set
3214 by write_func_for_structure). The problem is, we can't
3215 count on d->prev_val[3] to be always set to "x" in that
3216 case. Sometimes walk_type can set it to something else
3217 (to e.g cooperate with write_array when called from
3218 write_roots). So let's set it to "x" here then. */
3219 oprintf (d->of, ", x");
3220 else
3221 oprintf (d->of, ", %s", d->prev_val[3]);
3222 if (d->orig_s)
3224 oprintf (d->of, ", gt_%s_", wtd->param_prefix);
3225 output_mangled_typename (d->of, d->orig_s);
3227 else
3228 oprintf (d->of, ", gt_%sa_%s", wtd->param_prefix, d->prev_val[0]);
3230 oprintf (d->of, ");\n");
3231 if (d->reorder_fn && wtd->reorder_note_routine)
3232 oprintf (d->of, "%*s%s (%s%s, %s, %s);\n", d->indent, "",
3233 wtd->reorder_note_routine, cast, d->val,
3234 d->prev_val[3], d->reorder_fn);
3235 break;
3237 case TYPE_STRING:
3238 case TYPE_STRUCT:
3239 case TYPE_UNION:
3240 case TYPE_LANG_STRUCT:
3241 case TYPE_USER_STRUCT:
3242 if (f->kind == TYPE_USER_STRUCT && !d->in_ptr_field)
3244 /* If F is a user-defined type and the field is not a
3245 pointer to the type, then we should not generate the
3246 standard pointer-marking code. All we need to do is call
3247 the user-provided marking function to process the fields
3248 of F. */
3249 oprintf (d->of, "%*sgt_%sx (&(%s));\n", d->indent, "", wtd->prefix,
3250 d->val);
3252 else
3254 oprintf (d->of, "%*sgt_%s_", d->indent, "", wtd->prefix);
3255 output_mangled_typename (d->of, f);
3257 /* Check if we need to call the special pch note version
3258 for strings that takes an explicit length. */
3259 const auto length_override
3260 = (f->kind == TYPE_STRING && !strcmp (wtd->prefix, "pch_n")
3261 ? get_string_option (d->opt, "string_length")
3262 : nullptr);
3263 if (length_override)
3265 oprintf (d->of, "2 (%s%s, ", cast, d->val);
3266 output_escaped_param (d, length_override, "string_length");
3268 else
3269 oprintf (d->of, " (%s%s", cast, d->val);
3271 oprintf (d->of, ");\n");
3272 if (d->reorder_fn && wtd->reorder_note_routine)
3273 oprintf (d->of, "%*s%s (%s%s, %s%s, %s);\n", d->indent, "",
3274 wtd->reorder_note_routine, cast, d->val, cast, d->val,
3275 d->reorder_fn);
3277 break;
3279 case TYPE_SCALAR:
3280 case TYPE_CALLBACK:
3281 break;
3283 case TYPE_ARRAY:
3284 gcc_unreachable ();
3288 /* Return an output file that is suitable for definitions which can
3289 reference struct S */
3291 static outf_p
3292 get_output_file_for_structure (const_type_p s)
3294 const input_file *fn;
3296 gcc_assert (union_or_struct_p (s));
3297 fn = s->u.s.line.file;
3299 /* The call to get_output_file_with_visibility may update fn by
3300 caching its result inside, so we need the CONST_CAST. */
3301 return get_output_file_with_visibility (CONST_CAST (input_file*, fn));
3305 /* Returns the specifier keyword for a string or union type S, empty string
3306 otherwise. */
3308 static const char *
3309 get_type_specifier (const type_p s)
3311 if (s->kind == TYPE_STRUCT)
3312 return "struct ";
3313 else if (s->kind == TYPE_LANG_STRUCT)
3314 return get_type_specifier (s->u.s.lang_struct);
3315 else if (s->kind == TYPE_UNION)
3316 return "union ";
3317 return "";
3321 /* Emits a declaration for type TY (assumed to be a union or a
3322 structure) on stream OUT. */
3324 static void
3325 write_type_decl (outf_p out, type_p ty)
3327 if (union_or_struct_p (ty))
3328 oprintf (out, "%s%s", get_type_specifier (ty), ty->u.s.tag);
3329 else if (ty->kind == TYPE_SCALAR)
3331 if (ty->u.scalar_is_char)
3332 oprintf (out, "const char");
3333 else
3334 oprintf (out, "void");
3336 else if (ty->kind == TYPE_POINTER)
3338 write_type_decl (out, ty->u.p);
3339 oprintf (out, " *");
3341 else if (ty->kind == TYPE_ARRAY)
3343 write_type_decl (out, ty->u.a.p);
3344 oprintf (out, " *");
3346 else if (ty->kind == TYPE_STRING)
3348 oprintf (out, "const char *");
3350 else
3351 gcc_unreachable ();
3355 /* Write on OF the name of the marker function for structure S. PREFIX
3356 is the prefix to use (to distinguish ggc from pch markers). */
3358 static void
3359 write_marker_function_name (outf_p of, type_p s, const char *prefix)
3361 if (union_or_struct_p (s))
3363 const char *id_for_tag = filter_type_name (s->u.s.tag);
3364 oprintf (of, "gt_%sx_%s", prefix, id_for_tag);
3365 if (id_for_tag != s->u.s.tag)
3366 free (CONST_CAST (char *, id_for_tag));
3368 else
3369 gcc_unreachable ();
3372 /* Write on OF a user-callable routine to act as an entry point for
3373 the marking routine for S, generated by write_func_for_structure.
3374 WTD distinguishes between ggc and pch markers. */
3376 static void
3377 write_user_func_for_structure_ptr (outf_p of, type_p s, const write_types_data *wtd)
3379 gcc_assert (union_or_struct_p (s));
3381 type_p alias_of = NULL;
3382 for (options_p opt = s->u.s.opt; opt; opt = opt->next)
3383 if (strcmp (opt->name, "ptr_alias") == 0)
3385 /* ALIAS_OF is set if ORIG_S is marked "ptr_alias". This means that
3386 we do not generate marking code for ORIG_S here. Instead, a
3387 forwarder #define in gtype-desc.h will cause every call to its
3388 marker to call the target of this alias.
3390 However, we still want to create a user entry code for the
3391 aliased type. So, if ALIAS_OF is set, we only generate the
3392 user-callable marker function. */
3393 alias_of = opt->info.type;
3394 break;
3397 DBGPRINTF ("write_user_func_for_structure_ptr: %s %s", s->u.s.tag,
3398 wtd->prefix);
3400 /* Only write the function once. */
3401 if (s->u.s.wrote_user_func_for_ptr[wtd->kind])
3402 return;
3403 s->u.s.wrote_user_func_for_ptr[wtd->kind] = true;
3405 oprintf (of, "\nvoid\n");
3406 oprintf (of, "gt_%sx (", wtd->prefix);
3407 write_type_decl (of, s);
3408 oprintf (of, " *& x)\n");
3409 oprintf (of, "{\n");
3410 oprintf (of, " if (x)\n ");
3411 write_marker_function_name (of,
3412 alias_of ? alias_of : get_ultimate_base_class (s),
3413 wtd->prefix);
3414 oprintf (of, " ((void *) x);\n");
3415 oprintf (of, "}\n");
3419 /* Write a function to mark all the fields of type S on OF. PREFIX
3420 and D are as in write_user_marking_functions. */
3422 static void
3423 write_user_func_for_structure_body (type_p s, const char *prefix,
3424 struct walk_type_data *d)
3426 oprintf (d->of, "\nvoid\n");
3427 oprintf (d->of, "gt_%sx (", prefix);
3428 write_type_decl (d->of, s);
3429 oprintf (d->of, "& x_r ATTRIBUTE_UNUSED)\n");
3430 oprintf (d->of, "{\n");
3431 oprintf (d->of, " ");
3432 write_type_decl (d->of, s);
3433 oprintf (d->of, " * ATTRIBUTE_UNUSED x = &x_r;\n");
3434 d->val = "(*x)";
3435 d->indent = 2;
3436 walk_type (s, d);
3437 oprintf (d->of, "}\n");
3440 /* Emit the user-callable functions needed to mark all the types used
3441 by the user structure S. PREFIX is the prefix to use to
3442 distinguish ggc and pch markers. D contains data needed to pass to
3443 walk_type when traversing the fields of a type.
3445 For every type T referenced by S, two routines are generated: one
3446 that takes 'T *', marks the pointer and calls the second routine,
3447 which just marks the fields of T. */
3449 static void
3450 write_user_marking_functions (type_p s,
3451 const write_types_data *w,
3452 struct walk_type_data *d)
3454 gcc_assert (s->kind == TYPE_USER_STRUCT);
3456 for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
3458 type_p fld_type = fld->type;
3459 if (fld_type->kind == TYPE_POINTER)
3461 type_p pointed_to_type = fld_type->u.p;
3462 if (union_or_struct_p (pointed_to_type))
3463 write_user_func_for_structure_ptr (d->of, pointed_to_type, w);
3465 else if (union_or_struct_p (fld_type))
3466 write_user_func_for_structure_body (fld_type, w->prefix, d);
3471 /* For S, a structure that's part of ORIG_S write out a routine that:
3472 - Takes a parameter, a void * but actually of type *S
3473 - If SEEN_ROUTINE returns nonzero, calls write_types_process_field on each
3474 field of S or its substructures and (in some cases) things
3475 that are pointed to by S. */
3477 static void
3478 write_func_for_structure (type_p orig_s, type_p s,
3479 const struct write_types_data *wtd)
3481 const char *chain_next = NULL;
3482 const char *chain_prev = NULL;
3483 const char *chain_circular = NULL;
3484 options_p opt;
3485 struct walk_type_data d;
3487 if (s->u.s.base_class)
3489 /* Verify that the base class has a "desc", since otherwise
3490 the traversal hooks there won't attempt to visit fields of
3491 subclasses such as this one. */
3492 const_type_p ubc = get_ultimate_base_class (s);
3493 if ((!opts_have (ubc->u.s.opt, "user")
3494 && !opts_have (ubc->u.s.opt, "desc")))
3495 error_at_line (&s->u.s.line,
3496 ("'%s' is a subclass of non-GTY(user) GTY class '%s'"
3497 ", but '%s' lacks a discriminator 'desc' option"),
3498 s->u.s.tag, ubc->u.s.tag, ubc->u.s.tag);
3500 /* Don't write fns for subclasses, only for the ultimate base class
3501 within an inheritance hierarchy. */
3502 return;
3505 memset (&d, 0, sizeof (d));
3506 d.of = get_output_file_for_structure (s);
3508 bool for_user = false;
3509 for (opt = s->u.s.opt; opt; opt = opt->next)
3510 if (strcmp (opt->name, "chain_next") == 0
3511 && opt->kind == OPTION_STRING)
3512 chain_next = opt->info.string;
3513 else if (strcmp (opt->name, "chain_prev") == 0
3514 && opt->kind == OPTION_STRING)
3515 chain_prev = opt->info.string;
3516 else if (strcmp (opt->name, "chain_circular") == 0
3517 && opt->kind == OPTION_STRING)
3518 chain_circular = opt->info.string;
3519 else if (strcmp (opt->name, "for_user") == 0)
3520 for_user = true;
3521 if (chain_prev != NULL && chain_next == NULL)
3522 error_at_line (&s->u.s.line, "chain_prev without chain_next");
3523 if (chain_circular != NULL && chain_next != NULL)
3524 error_at_line (&s->u.s.line, "chain_circular with chain_next");
3525 if (chain_circular != NULL)
3526 chain_next = chain_circular;
3528 d.process_field = write_types_process_field;
3529 d.cookie = wtd;
3530 d.orig_s = orig_s;
3531 d.opt = s->u.s.opt;
3532 d.line = &s->u.s.line;
3533 d.bitmap = s->u.s.bitmap;
3534 d.prev_val[0] = "*x";
3535 d.prev_val[1] = "not valid postage"; /* Guarantee an error. */
3536 d.prev_val[3] = "x";
3537 d.val = "(*x)";
3538 d.have_this_obj = false;
3540 oprintf (d.of, "\n");
3541 oprintf (d.of, "void\n");
3542 write_marker_function_name (d.of, orig_s, wtd->prefix);
3543 oprintf (d.of, " (void *x_p)\n");
3544 oprintf (d.of, "{\n ");
3545 write_type_decl (d.of, s);
3546 oprintf (d.of, " * %sx = (", chain_next == NULL ? "const " : "");
3547 write_type_decl (d.of, s);
3548 oprintf (d.of, " *)x_p;\n");
3549 if (chain_next != NULL)
3551 /* TYPE_USER_STRUCTs should not occur here. These structures
3552 are completely handled by user code. */
3553 gcc_assert (orig_s->kind != TYPE_USER_STRUCT);
3555 oprintf (d.of, " ");
3556 write_type_decl (d.of, s);
3557 oprintf (d.of, " * xlimit = x;\n");
3559 if (chain_next == NULL)
3561 oprintf (d.of, " if (%s (x", wtd->marker_routine);
3562 if (wtd->param_prefix)
3564 oprintf (d.of, ", x, gt_%s_", wtd->param_prefix);
3565 output_mangled_typename (d.of, orig_s);
3567 oprintf (d.of, "))\n");
3569 else
3571 if (chain_circular != NULL)
3572 oprintf (d.of, " if (!%s (xlimit", wtd->marker_routine);
3573 else
3574 oprintf (d.of, " while (%s (xlimit", wtd->marker_routine);
3575 if (wtd->param_prefix)
3577 oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
3578 output_mangled_typename (d.of, orig_s);
3580 oprintf (d.of, "))\n");
3581 if (chain_circular != NULL)
3582 oprintf (d.of, " return;\n do\n");
3584 oprintf (d.of, " xlimit = (");
3585 d.prev_val[2] = "*xlimit";
3586 output_escaped_param (&d, chain_next, "chain_next");
3587 oprintf (d.of, ");\n");
3588 if (chain_prev != NULL)
3590 oprintf (d.of, " if (x != xlimit)\n");
3591 oprintf (d.of, " for (;;)\n");
3592 oprintf (d.of, " {\n");
3593 oprintf (d.of, " %s %s * const xprev = (",
3594 s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
3596 d.prev_val[2] = "*x";
3597 output_escaped_param (&d, chain_prev, "chain_prev");
3598 oprintf (d.of, ");\n");
3599 oprintf (d.of, " if (xprev == NULL) break;\n");
3600 oprintf (d.of, " x = xprev;\n");
3601 oprintf (d.of, " (void) %s (xprev", wtd->marker_routine);
3602 if (wtd->param_prefix)
3604 oprintf (d.of, ", xprev, gt_%s_", wtd->param_prefix);
3605 output_mangled_typename (d.of, orig_s);
3607 oprintf (d.of, ");\n");
3608 oprintf (d.of, " }\n");
3610 if (chain_circular != NULL)
3612 oprintf (d.of, " while (%s (xlimit", wtd->marker_routine);
3613 if (wtd->param_prefix)
3615 oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
3616 output_mangled_typename (d.of, orig_s);
3618 oprintf (d.of, "));\n");
3619 oprintf (d.of, " do\n");
3621 else
3622 oprintf (d.of, " while (x != xlimit)\n");
3624 oprintf (d.of, " {\n");
3626 d.prev_val[2] = "*x";
3627 d.indent = 6;
3628 if (orig_s->kind != TYPE_USER_STRUCT)
3629 walk_type (s, &d);
3630 else
3632 /* User structures have no fields to walk. Simply generate a call
3633 to the user-provided structure marker. */
3634 oprintf (d.of, "%*sgt_%sx (x);\n", d.indent, "", wtd->prefix);
3637 if (chain_next != NULL)
3639 oprintf (d.of, " x = (");
3640 output_escaped_param (&d, chain_next, "chain_next");
3641 oprintf (d.of, ");\n");
3644 oprintf (d.of, " }\n");
3645 if (chain_circular != NULL)
3646 oprintf (d.of, " while (x != xlimit);\n");
3647 oprintf (d.of, "}\n");
3649 if (orig_s->kind == TYPE_USER_STRUCT)
3650 write_user_marking_functions (orig_s, wtd, &d);
3652 if (for_user)
3654 write_user_func_for_structure_body (orig_s, wtd->prefix, &d);
3655 write_user_func_for_structure_ptr (d.of, orig_s, wtd);
3660 /* Write out marker routines for STRUCTURES and PARAM_STRUCTS. */
3662 static void
3663 write_types (outf_p output_header, type_p structures,
3664 const struct write_types_data *wtd)
3666 int nbfun = 0; /* Count the emitted functions. */
3667 type_p s;
3669 oprintf (output_header, "\n/* %s*/\n", wtd->comment);
3671 /* We first emit the macros and the declarations. Functions' code is
3672 emitted afterwards. This is needed in plugin mode. */
3673 oprintf (output_header, "/* Macros and declarations. */\n");
3674 for (s = structures; s; s = s->next)
3675 /* Do not emit handlers for derived classes; we only ever deal with
3676 the ultimate base class within an inheritance hierarchy. */
3677 if ((s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
3678 && !s->u.s.base_class)
3680 options_p opt;
3682 if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
3683 continue;
3685 const char *s_id_for_tag = filter_type_name (s->u.s.tag);
3687 oprintf (output_header, "#define gt_%s_", wtd->prefix);
3688 output_mangled_typename (output_header, s);
3689 oprintf (output_header, "(X) do { \\\n");
3690 oprintf (output_header,
3691 " if ((intptr_t)(X) != 0) gt_%sx_%s (X);\\\n",
3692 wtd->prefix, s_id_for_tag);
3693 oprintf (output_header, " } while (0)\n");
3695 for (opt = s->u.s.opt; opt; opt = opt->next)
3696 if (strcmp (opt->name, "ptr_alias") == 0
3697 && opt->kind == OPTION_TYPE)
3699 const_type_p const t = (const_type_p) opt->info.type;
3700 if (t->kind == TYPE_STRUCT
3701 || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
3703 const char *t_id_for_tag = filter_type_name (t->u.s.tag);
3704 oprintf (output_header,
3705 "#define gt_%sx_%s gt_%sx_%s\n",
3706 wtd->prefix, s->u.s.tag, wtd->prefix, t_id_for_tag);
3707 if (t_id_for_tag != t->u.s.tag)
3708 free (CONST_CAST (char *, t_id_for_tag));
3710 else
3711 error_at_line (&s->u.s.line,
3712 "structure alias is not a structure");
3713 break;
3715 if (opt)
3716 continue;
3718 /* Declare the marker procedure only once. */
3719 oprintf (output_header,
3720 "extern void gt_%sx_%s (void *);\n",
3721 wtd->prefix, s_id_for_tag);
3723 if (s_id_for_tag != s->u.s.tag)
3724 free (CONST_CAST (char *, s_id_for_tag));
3726 if (s->u.s.line.file == NULL)
3728 fprintf (stderr, "warning: structure `%s' used but not defined\n",
3729 s->u.s.tag);
3730 continue;
3734 /* At last we emit the functions code. */
3735 oprintf (output_header, "\n/* functions code */\n");
3736 for (s = structures; s; s = s->next)
3737 if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
3739 options_p opt;
3741 if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
3742 continue;
3743 for (opt = s->u.s.opt; opt; opt = opt->next)
3744 if (strcmp (opt->name, "ptr_alias") == 0)
3745 break;
3746 if (opt)
3747 continue;
3749 if (s->kind == TYPE_LANG_STRUCT)
3751 type_p ss;
3752 for (ss = s->u.s.lang_struct; ss; ss = ss->next)
3754 nbfun++;
3755 DBGPRINTF ("writing func #%d lang_struct ss @ %p '%s'",
3756 nbfun, (void*) ss, ss->u.s.tag);
3757 write_func_for_structure (s, ss, wtd);
3760 else
3762 nbfun++;
3763 DBGPRINTF ("writing func #%d struct s @ %p '%s'",
3764 nbfun, (void*) s, s->u.s.tag);
3765 write_func_for_structure (s, s, wtd);
3768 else
3770 /* Structure s is not possibly pointed to, so can be ignored. */
3771 DBGPRINTF ("ignored s @ %p '%s' gc_used#%d",
3772 (void*)s, s->u.s.tag,
3773 (int) s->gc_used);
3776 if (verbosity_level >= 2)
3777 printf ("%s emitted %d routines for %s\n",
3778 progname, nbfun, wtd->comment);
3781 static const struct write_types_data ggc_wtd = {
3782 "ggc_m", NULL, "ggc_mark", "ggc_test_and_set_mark", NULL,
3783 "GC marker procedures. ",
3784 WTK_GGC
3787 static const struct write_types_data pch_wtd = {
3788 "pch_n", "pch_p", "gt_pch_note_object", "gt_pch_note_object",
3789 "gt_pch_note_reorder",
3790 "PCH type-walking procedures. ",
3791 WTK_PCH
3794 /* Write out the local pointer-walking routines. */
3796 /* process_field routine for local pointer-walking for user-callable
3797 routines. The difference between this and
3798 write_types_local_process_field is that, in this case, we do not
3799 need to check whether the given pointer matches the address of the
3800 parent structure. This check was already generated by the call
3801 to gt_pch_nx in the main gt_pch_p_*() function that is calling
3802 this code. */
3804 static void
3805 write_types_local_user_process_field (type_p f, const struct walk_type_data *d)
3807 switch (f->kind)
3809 case TYPE_POINTER:
3810 case TYPE_STRUCT:
3811 case TYPE_UNION:
3812 case TYPE_LANG_STRUCT:
3813 case TYPE_STRING:
3814 if (d->in_nested_ptr)
3815 oprintf (d->of, "%*s op (&(%s), &(%s), cookie);\n",
3816 d->indent, "", d->val, d->prev_val[2]);
3817 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3818 d->indent, "", d->val);
3819 break;
3821 case TYPE_USER_STRUCT:
3822 if (d->in_ptr_field)
3823 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3824 d->indent, "", d->val);
3825 else
3826 oprintf (d->of, "%*s gt_pch_nx (&(%s), op, cookie);\n",
3827 d->indent, "", d->val);
3828 break;
3830 case TYPE_SCALAR:
3831 case TYPE_CALLBACK:
3832 break;
3834 case TYPE_ARRAY:
3835 case TYPE_NONE:
3836 case TYPE_UNDEFINED:
3837 gcc_unreachable ();
3842 /* Write a function to PCH walk all the fields of type S on OF.
3843 D contains data needed by walk_type to recurse into the fields of S. */
3845 static void
3846 write_pch_user_walking_for_structure_body (type_p s, struct walk_type_data *d)
3848 oprintf (d->of, "\nvoid\n");
3849 oprintf (d->of, "gt_pch_nx (");
3850 write_type_decl (d->of, s);
3851 oprintf (d->of, "* x ATTRIBUTE_UNUSED,\n"
3852 "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
3853 "\tATTRIBUTE_UNUSED void *cookie)\n");
3854 oprintf (d->of, "{\n");
3855 d->val = "(*x)";
3856 d->indent = 2;
3857 d->process_field = write_types_local_user_process_field;
3858 walk_type (s, d);
3859 oprintf (d->of, "}\n");
3863 /* Emit the user-callable functions needed to mark all the types used
3864 by the user structure S. PREFIX is the prefix to use to
3865 distinguish ggc and pch markers. CHAIN_NEXT is set if S has the
3866 chain_next option defined. D contains data needed to pass to
3867 walk_type when traversing the fields of a type.
3869 For every type T referenced by S, two routines are generated: one
3870 that takes 'T *', marks the pointer and calls the second routine,
3871 which just marks the fields of T. */
3873 static void
3874 write_pch_user_walking_functions (type_p s, struct walk_type_data *d)
3876 gcc_assert (s->kind == TYPE_USER_STRUCT);
3878 for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
3880 type_p fld_type = fld->type;
3881 if (union_or_struct_p (fld_type))
3882 write_pch_user_walking_for_structure_body (fld_type, d);
3887 /* process_field routine for local pointer-walking. */
3889 static void
3890 write_types_local_process_field (type_p f, const struct walk_type_data *d)
3892 gcc_assert (d->have_this_obj);
3893 switch (f->kind)
3895 case TYPE_POINTER:
3896 case TYPE_STRUCT:
3897 case TYPE_UNION:
3898 case TYPE_LANG_STRUCT:
3899 case TYPE_STRING:
3900 oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3901 d->prev_val[3]);
3902 if (d->in_nested_ptr)
3903 oprintf (d->of, "%*s op (&(%s), &(%s), cookie);\n",
3904 d->indent, "", d->val, d->prev_val[2]);
3905 else
3906 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3907 d->indent, "", d->val);
3908 break;
3910 case TYPE_USER_STRUCT:
3911 oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3912 d->prev_val[3]);
3913 if (d->in_ptr_field)
3914 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3915 d->indent, "", d->val);
3916 else
3917 oprintf (d->of, "%*s gt_pch_nx (&(%s), op, cookie);\n",
3918 d->indent, "", d->val);
3919 break;
3921 case TYPE_SCALAR:
3922 break;
3924 case TYPE_CALLBACK:
3925 oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3926 d->prev_val[3]);
3927 oprintf (d->of, "%*s gt_pch_note_callback (&(%s), this_obj);\n",
3928 d->indent, "", d->val);
3929 break;
3931 case TYPE_ARRAY:
3932 case TYPE_NONE:
3933 case TYPE_UNDEFINED:
3934 gcc_unreachable ();
3939 /* For S, a structure that's part of ORIG_S, and using parameters
3940 PARAM, write out a routine that:
3941 - Is of type gt_note_pointers
3942 - Calls PROCESS_FIELD on each field of S or its substructures.
3945 static void
3946 write_local_func_for_structure (const_type_p orig_s, type_p s)
3948 struct walk_type_data d;
3950 /* Don't write fns for subclasses, only for the ultimate base class
3951 within an inheritance hierarchy. */
3952 if (s->u.s.base_class)
3953 return;
3955 memset (&d, 0, sizeof (d));
3956 d.of = get_output_file_for_structure (s);
3957 d.process_field = write_types_local_process_field;
3958 d.opt = s->u.s.opt;
3959 d.line = &s->u.s.line;
3960 d.bitmap = s->u.s.bitmap;
3961 d.prev_val[0] = d.prev_val[2] = "*x";
3962 d.prev_val[1] = "not valid postage"; /* Guarantee an error. */
3963 d.prev_val[3] = "x";
3964 d.val = "(*x)";
3965 d.fn_wants_lvalue = true;
3967 oprintf (d.of, "\n");
3968 oprintf (d.of, "void\n");
3969 oprintf (d.of, "gt_pch_p_");
3970 output_mangled_typename (d.of, orig_s);
3971 oprintf (d.of, " (ATTRIBUTE_UNUSED void *this_obj,\n"
3972 "\tvoid *x_p,\n"
3973 "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
3974 "\tATTRIBUTE_UNUSED void *cookie)\n");
3975 oprintf (d.of, "{\n");
3976 oprintf (d.of, " %s %s * x ATTRIBUTE_UNUSED = (%s %s *)x_p;\n",
3977 s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag,
3978 s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
3979 d.indent = 2;
3980 d.have_this_obj = true;
3982 if (s->kind != TYPE_USER_STRUCT)
3983 walk_type (s, &d);
3984 else
3986 /* User structures have no fields to walk. Simply generate a
3987 call to the user-provided PCH walker. */
3988 oprintf (d.of, "%*sif ((void *)(%s) == this_obj)\n", d.indent, "",
3989 d.prev_val[3]);
3990 oprintf (d.of, "%*s gt_pch_nx (&(%s), op, cookie);\n",
3991 d.indent, "", d.val);
3994 oprintf (d.of, "}\n");
3996 /* Write user-callable entry points for the PCH walking routines. */
3997 if (orig_s->kind == TYPE_USER_STRUCT)
3998 write_pch_user_walking_functions (s, &d);
4000 for (options_p o = s->u.s.opt; o; o = o->next)
4001 if (strcmp (o->name, "for_user") == 0)
4003 write_pch_user_walking_for_structure_body (s, &d);
4004 break;
4008 /* Write out local marker routines for STRUCTURES and PARAM_STRUCTS. */
4010 static void
4011 write_local (outf_p output_header, type_p structures)
4013 type_p s;
4015 if (!output_header)
4016 return;
4018 oprintf (output_header, "\n/* Local pointer-walking routines. */\n");
4019 for (s = structures; s; s = s->next)
4020 if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
4022 options_p opt;
4024 if (s->u.s.line.file == NULL)
4025 continue;
4026 for (opt = s->u.s.opt; opt; opt = opt->next)
4027 if (strcmp (opt->name, "ptr_alias") == 0
4028 && opt->kind == OPTION_TYPE)
4030 const_type_p const t = (const_type_p) opt->info.type;
4031 if (t->kind == TYPE_STRUCT
4032 || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
4034 oprintf (output_header, "#define gt_pch_p_");
4035 output_mangled_typename (output_header, s);
4036 oprintf (output_header, " gt_pch_p_");
4037 output_mangled_typename (output_header, t);
4038 oprintf (output_header, "\n");
4040 else
4041 error_at_line (&s->u.s.line,
4042 "structure alias is not a structure");
4043 break;
4045 if (opt)
4046 continue;
4048 /* Declare the marker procedure only once. */
4049 oprintf (output_header, "extern void gt_pch_p_");
4050 output_mangled_typename (output_header, s);
4051 oprintf (output_header,
4052 "\n (void *, void *, gt_pointer_operator, void *);\n");
4054 if (s->kind == TYPE_LANG_STRUCT)
4056 type_p ss;
4057 for (ss = s->u.s.lang_struct; ss; ss = ss->next)
4058 write_local_func_for_structure (s, ss);
4060 else
4061 write_local_func_for_structure (s, s);
4065 /* Nonzero if S is a type for which typed GC allocators should be output. */
4067 #define USED_BY_TYPED_GC_P(s) \
4068 ((s->kind == TYPE_POINTER \
4069 && (s->u.p->gc_used == GC_POINTED_TO \
4070 || s->u.p->gc_used == GC_USED)) \
4071 || (union_or_struct_p (s) \
4072 && ((s)->gc_used == GC_POINTED_TO \
4073 || ((s)->gc_used == GC_MAYBE_POINTED_TO \
4074 && s->u.s.line.file != NULL) \
4075 || ((s)->gc_used == GC_USED \
4076 && !startswith (s->u.s.tag, "anonymous")) \
4077 || (s->u.s.base_class && opts_have (s->u.s.opt, "tag")))))
4081 /* Might T contain any non-pointer elements? */
4083 static int
4084 contains_scalar_p (type_p t)
4086 switch (t->kind)
4088 case TYPE_STRING:
4089 case TYPE_POINTER:
4090 return 0;
4091 case TYPE_ARRAY:
4092 return contains_scalar_p (t->u.a.p);
4093 case TYPE_USER_STRUCT:
4094 /* User-marked structures will typically contain pointers. */
4095 return 0;
4096 default:
4097 /* Could also check for structures that have no non-pointer
4098 fields, but there aren't enough of those to worry about. */
4099 return 1;
4103 /* Mangle INPF and print it to F. */
4105 static void
4106 put_mangled_filename (outf_p f, const input_file *inpf)
4108 /* The call to get_output_file_name may indirectly update fn since
4109 get_output_file_with_visibility caches its result inside, so we
4110 need the CONST_CAST. */
4111 const char *name = get_output_file_name (CONST_CAST (input_file*, inpf));
4112 if (!f || !name)
4113 return;
4114 for (; *name != 0; name++)
4115 if (ISALNUM (*name))
4116 oprintf (f, "%c", *name);
4117 else
4118 oprintf (f, "%c", '_');
4121 /* Finish off the currently-created root tables in FLP. PFX, TNAME,
4122 LASTNAME, and NAME are all strings to insert in various places in
4123 the resulting code. */
4125 static void
4126 finish_root_table (struct flist *flp, const char *pfx, const char *lastname,
4127 const char *tname, const char *name)
4129 struct flist *fli2;
4131 for (fli2 = flp; fli2; fli2 = fli2->next)
4132 if (fli2->started_p)
4134 oprintf (fli2->f, " %s\n", lastname);
4135 oprintf (fli2->f, "};\n\n");
4138 for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
4139 if (fli2->started_p)
4141 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4142 int fnum;
4144 for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
4145 if (bitmap & 1)
4147 oprintf (base_files[fnum],
4148 "extern const struct %s gt_%s_", tname, pfx);
4149 put_mangled_filename (base_files[fnum], fli2->file);
4150 oprintf (base_files[fnum], "[];\n");
4155 size_t fnum;
4156 for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4157 oprintf (base_files[fnum],
4158 "EXPORTED_CONST struct %s * const %s[] = {\n", tname, name);
4162 for (fli2 = flp; fli2; fli2 = fli2->next)
4163 if (fli2->started_p)
4165 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4166 int fnum;
4168 fli2->started_p = 0;
4170 for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
4171 if (bitmap & 1)
4173 oprintf (base_files[fnum], " gt_%s_", pfx);
4174 put_mangled_filename (base_files[fnum], fli2->file);
4175 oprintf (base_files[fnum], ",\n");
4180 size_t fnum;
4181 for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4183 oprintf (base_files[fnum], " NULL\n");
4184 oprintf (base_files[fnum], "};\n");
4189 /* Finish off the created gt_clear_caches_file_c functions. */
4191 static void
4192 finish_cache_funcs (flist *flp)
4194 struct flist *fli2;
4196 for (fli2 = flp; fli2; fli2 = fli2->next)
4197 if (fli2->started_p)
4199 oprintf (fli2->f, "}\n\n");
4202 for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
4203 if (fli2->started_p)
4205 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4206 int fnum;
4208 for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
4209 if (bitmap & 1)
4211 oprintf (base_files[fnum], "extern void gt_clear_caches_");
4212 put_mangled_filename (base_files[fnum], fli2->file);
4213 oprintf (base_files[fnum], " ();\n");
4217 for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4218 oprintf (base_files[fnum], "void\ngt_clear_caches ()\n{\n");
4220 for (fli2 = flp; fli2; fli2 = fli2->next)
4221 if (fli2->started_p)
4223 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4224 int fnum;
4226 fli2->started_p = 0;
4228 for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
4229 if (bitmap & 1)
4231 oprintf (base_files[fnum], " gt_clear_caches_");
4232 put_mangled_filename (base_files[fnum], fli2->file);
4233 oprintf (base_files[fnum], " ();\n");
4237 for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4239 oprintf (base_files[fnum], "}\n");
4243 /* Write the first three fields (pointer, count and stride) for
4244 root NAME to F. V and LINE are as for write_root.
4246 Return true if the entry could be written; return false on error. */
4248 static bool
4249 start_root_entry (outf_p f, pair_p v, const char *name, struct fileloc *line)
4251 type_p ap;
4253 if (!v)
4255 error_at_line (line, "`%s' is too complex to be a root", name);
4256 return false;
4259 oprintf (f, " {\n");
4260 oprintf (f, " &%s,\n", name);
4261 oprintf (f, " 1");
4263 for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
4264 if (ap->u.a.len[0])
4265 oprintf (f, " * (%s)", ap->u.a.len);
4266 else if (ap == v->type)
4267 oprintf (f, " * ARRAY_SIZE (%s)", v->name);
4268 oprintf (f, ",\n");
4269 oprintf (f, " sizeof (%s", v->name);
4270 for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
4271 oprintf (f, "[0]");
4272 oprintf (f, "),\n");
4273 return true;
4276 /* A subroutine of write_root for writing the roots for field FIELD_NAME,
4277 which has type FIELD_TYPE. Parameters F to EMIT_PCH are the parameters
4278 of the caller. */
4280 static void
4281 write_field_root (outf_p f, pair_p v, type_p type, const char *name,
4282 int has_length, struct fileloc *line,
4283 bool emit_pch, type_p field_type, const char *field_name)
4285 struct pair newv;
4286 /* If the field reference is relative to V, rather than to some
4287 subcomponent of V, we can mark any subarrays with a single stride.
4288 We're effectively treating the field as a global variable in its
4289 own right. */
4290 if (v && type == v->type)
4292 newv = *v;
4293 newv.type = field_type;
4294 newv.name = ACONCAT ((v->name, ".", field_name, NULL));
4295 v = &newv;
4297 /* Otherwise, any arrays nested in the structure are too complex to
4298 handle. */
4299 else if (field_type->kind == TYPE_ARRAY)
4300 v = NULL;
4301 write_root (f, v, field_type, ACONCAT ((name, ".", field_name, NULL)),
4302 has_length, line, emit_pch);
4305 /* Write out to F the table entry and any marker routines needed to
4306 mark NAME as TYPE. V can be one of three values:
4308 - null, if NAME is too complex to represent using a single
4309 count and stride. In this case, it is an error for NAME to
4310 contain any gc-ed data.
4312 - the outermost array that contains NAME, if NAME is part of an array.
4314 - the C variable that contains NAME, if NAME is not part of an array.
4316 LINE is the line of the C source that declares the root variable.
4317 HAS_LENGTH is nonzero iff V was a variable-length array. */
4319 static void
4320 write_root (outf_p f, pair_p v, type_p type, const char *name, int has_length,
4321 struct fileloc *line, bool emit_pch)
4323 switch (type->kind)
4325 case TYPE_STRUCT:
4327 pair_p fld;
4328 for (fld = type->u.s.fields; fld; fld = fld->next)
4330 int skip_p = 0;
4331 const char *desc = NULL;
4332 options_p o;
4334 for (o = fld->opt; o; o = o->next)
4335 if (strcmp (o->name, "skip") == 0)
4336 skip_p = 1;
4337 else if (strcmp (o->name, "desc") == 0
4338 && o->kind == OPTION_STRING)
4339 desc = o->info.string;
4340 else
4341 error_at_line (line,
4342 "field `%s' of global `%s' has unknown option `%s'",
4343 fld->name, name, o->name);
4345 if (skip_p)
4346 continue;
4347 else if (desc && fld->type->kind == TYPE_UNION)
4349 pair_p validf = NULL;
4350 pair_p ufld;
4352 for (ufld = fld->type->u.s.fields; ufld; ufld = ufld->next)
4354 const char *tag = NULL;
4355 options_p oo;
4356 for (oo = ufld->opt; oo; oo = oo->next)
4357 if (strcmp (oo->name, "tag") == 0
4358 && oo->kind == OPTION_STRING)
4359 tag = oo->info.string;
4360 if (tag == NULL || strcmp (tag, desc) != 0)
4361 continue;
4362 if (validf != NULL)
4363 error_at_line (line,
4364 "both `%s.%s.%s' and `%s.%s.%s' have tag `%s'",
4365 name, fld->name, validf->name,
4366 name, fld->name, ufld->name, tag);
4367 validf = ufld;
4369 if (validf != NULL)
4370 write_field_root (f, v, type, name, 0, line, emit_pch,
4371 validf->type,
4372 ACONCAT ((fld->name, ".",
4373 validf->name, NULL)));
4375 else if (desc)
4376 error_at_line (line,
4377 "global `%s.%s' has `desc' option but is not union",
4378 name, fld->name);
4379 else
4380 write_field_root (f, v, type, name, 0, line, emit_pch, fld->type,
4381 fld->name);
4384 break;
4386 case TYPE_ARRAY:
4388 char *newname;
4389 newname = xasprintf ("%s[0]", name);
4390 write_root (f, v, type->u.a.p, newname, has_length, line, emit_pch);
4391 free (newname);
4393 break;
4395 case TYPE_USER_STRUCT:
4396 error_at_line (line, "`%s' must be a pointer type, because it is "
4397 "a GC root and its type is marked with GTY((user))",
4398 v->name);
4399 break;
4401 case TYPE_POINTER:
4403 const_type_p tp;
4405 if (!start_root_entry (f, v, name, line))
4406 return;
4408 tp = type->u.p;
4410 if (!has_length && union_or_struct_p (tp))
4412 tp = get_ultimate_base_class (tp);
4413 const char *id_for_tag = filter_type_name (tp->u.s.tag);
4414 oprintf (f, " &gt_ggc_mx_%s,\n", id_for_tag);
4415 if (emit_pch)
4416 oprintf (f, " &gt_pch_nx_%s", id_for_tag);
4417 else
4418 oprintf (f, " NULL");
4419 if (id_for_tag != tp->u.s.tag)
4420 free (CONST_CAST (char *, id_for_tag));
4422 else if (has_length
4423 && (tp->kind == TYPE_POINTER || union_or_struct_p (tp)))
4425 oprintf (f, " &gt_ggc_ma_%s,\n", name);
4426 if (emit_pch)
4427 oprintf (f, " &gt_pch_na_%s", name);
4428 else
4429 oprintf (f, " NULL");
4431 else
4433 error_at_line (line,
4434 "global `%s' is pointer to unimplemented type",
4435 name);
4437 oprintf (f, "\n },\n");
4439 break;
4441 case TYPE_STRING:
4443 if (!start_root_entry (f, v, name, line))
4444 return;
4446 oprintf (f, " (gt_pointer_walker) &gt_ggc_m_S,\n");
4447 oprintf (f, " (gt_pointer_walker) &gt_pch_n_S\n");
4448 oprintf (f, " },\n");
4450 break;
4452 case TYPE_SCALAR:
4453 break;
4455 case TYPE_NONE:
4456 case TYPE_UNDEFINED:
4457 case TYPE_UNION:
4458 case TYPE_LANG_STRUCT:
4459 case TYPE_CALLBACK:
4460 error_at_line (line, "global `%s' is unimplemented type", name);
4464 /* This generates a routine to walk an array. */
4466 static void
4467 write_array (outf_p f, pair_p v, const struct write_types_data *wtd)
4469 struct walk_type_data d;
4470 char *prevval3;
4472 memset (&d, 0, sizeof (d));
4473 d.of = f;
4474 d.cookie = wtd;
4475 d.indent = 2;
4476 d.line = &v->line;
4477 d.opt = v->opt;
4478 d.bitmap = get_lang_bitmap (v->line.file);
4480 d.prev_val[3] = prevval3 = xasprintf ("&%s", v->name);
4482 if (wtd->param_prefix)
4484 oprintf (f, "static void gt_%sa_%s\n", wtd->param_prefix, v->name);
4485 oprintf (f, " (void *, void *, gt_pointer_operator, void *);\n");
4486 oprintf (f, "static void gt_%sa_%s (ATTRIBUTE_UNUSED void *this_obj,\n",
4487 wtd->param_prefix, v->name);
4488 oprintf (d.of,
4489 " ATTRIBUTE_UNUSED void *x_p,\n"
4490 " ATTRIBUTE_UNUSED gt_pointer_operator op,\n"
4491 " ATTRIBUTE_UNUSED void * cookie)\n");
4492 oprintf (d.of, "{\n");
4493 d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
4494 d.process_field = write_types_local_process_field;
4495 d.have_this_obj = true;
4496 walk_type (v->type, &d);
4497 oprintf (f, "}\n\n");
4500 d.opt = v->opt;
4501 oprintf (f, "static void gt_%sa_%s (void *);\n", wtd->prefix, v->name);
4502 oprintf (f, "static void\ngt_%sa_%s (ATTRIBUTE_UNUSED void *x_p)\n",
4503 wtd->prefix, v->name);
4504 oprintf (f, "{\n");
4505 d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
4506 d.process_field = write_types_process_field;
4507 d.have_this_obj = false;
4508 walk_type (v->type, &d);
4509 free (prevval3);
4510 oprintf (f, "}\n\n");
4513 /* Output a table describing the locations and types of VARIABLES. */
4515 static void
4516 write_roots (pair_p variables, bool emit_pch)
4518 pair_p v;
4519 struct flist *flp = NULL;
4521 for (v = variables; v; v = v->next)
4523 outf_p f =
4524 get_output_file_with_visibility (CONST_CAST (input_file*,
4525 v->line.file));
4526 struct flist *fli;
4527 const char *length = NULL;
4528 int deletable_p = 0;
4529 options_p o;
4530 for (o = v->opt; o; o = o->next)
4531 if (strcmp (o->name, "length") == 0
4532 && o->kind == OPTION_STRING)
4533 length = o->info.string;
4534 else if (strcmp (o->name, "deletable") == 0)
4535 deletable_p = 1;
4536 else if (strcmp (o->name, "cache") == 0)
4538 else
4539 error_at_line (&v->line,
4540 "global `%s' has unknown option `%s'",
4541 v->name, o->name);
4543 for (fli = flp; fli; fli = fli->next)
4544 if (fli->f == f && f)
4545 break;
4546 if (fli == NULL)
4548 fli = XNEW (struct flist);
4549 fli->f = f;
4550 fli->next = flp;
4551 fli->started_p = 0;
4552 fli->file = v->line.file;
4553 gcc_assert (fli->file);
4554 flp = fli;
4556 oprintf (f, "\n/* GC roots. */\n\n");
4559 if (!deletable_p
4560 && length
4561 && v->type->kind == TYPE_POINTER
4562 && (v->type->u.p->kind == TYPE_POINTER
4563 || v->type->u.p->kind == TYPE_STRUCT))
4565 write_array (f, v, &ggc_wtd);
4566 write_array (f, v, &pch_wtd);
4570 for (v = variables; v; v = v->next)
4572 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4573 v->line.file));
4574 struct flist *fli;
4575 int skip_p = 0;
4576 int length_p = 0;
4577 options_p o;
4579 for (o = v->opt; o; o = o->next)
4580 if (strcmp (o->name, "length") == 0)
4581 length_p = 1;
4582 else if (strcmp (o->name, "deletable") == 0)
4583 skip_p = 1;
4585 if (skip_p)
4586 continue;
4588 for (fli = flp; fli; fli = fli->next)
4589 if (fli->f == f)
4590 break;
4591 if (!fli->started_p)
4593 fli->started_p = 1;
4595 oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_r_");
4596 put_mangled_filename (f, v->line.file);
4597 oprintf (f, "[] = {\n");
4600 write_root (f, v, v->type, v->name, length_p, &v->line, emit_pch);
4603 finish_root_table (flp, "ggc_r", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4604 "gt_ggc_rtab");
4606 for (v = variables; v; v = v->next)
4608 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4609 v->line.file));
4610 struct flist *fli;
4611 int skip_p = 1;
4612 options_p o;
4614 for (o = v->opt; o; o = o->next)
4615 if (strcmp (o->name, "deletable") == 0)
4616 skip_p = 0;
4618 if (skip_p)
4619 continue;
4621 for (fli = flp; fli; fli = fli->next)
4622 if (fli->f == f)
4623 break;
4624 if (!fli->started_p)
4626 fli->started_p = 1;
4628 oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_rd_");
4629 put_mangled_filename (f, v->line.file);
4630 oprintf (f, "[] = {\n");
4633 oprintf (f, " { &%s, 1, sizeof (%s), NULL, NULL },\n",
4634 v->name, v->name);
4637 finish_root_table (flp, "ggc_rd", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4638 "gt_ggc_deletable_rtab");
4640 for (v = variables; v; v = v->next)
4642 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4643 v->line.file));
4644 struct flist *fli;
4645 bool cache = false;
4646 options_p o;
4648 for (o = v->opt; o; o = o->next)
4649 if (strcmp (o->name, "cache") == 0)
4650 cache = true;
4651 if (!cache)
4652 continue;
4654 for (fli = flp; fli; fli = fli->next)
4655 if (fli->f == f)
4656 break;
4657 if (!fli->started_p)
4659 fli->started_p = 1;
4661 oprintf (f, "void\ngt_clear_caches_");
4662 put_mangled_filename (f, v->line.file);
4663 oprintf (f, " ()\n{\n");
4666 oprintf (f, " gt_cleare_cache (%s);\n", v->name);
4669 finish_cache_funcs (flp);
4671 if (!emit_pch)
4672 return;
4674 for (v = variables; v; v = v->next)
4676 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4677 v->line.file));
4678 struct flist *fli;
4679 int skip_p = 0;
4680 options_p o;
4682 for (o = v->opt; o; o = o->next)
4683 if (strcmp (o->name, "deletable") == 0)
4685 skip_p = 1;
4686 break;
4689 if (skip_p)
4690 continue;
4692 if (!contains_scalar_p (v->type))
4693 continue;
4695 for (fli = flp; fli; fli = fli->next)
4696 if (fli->f == f)
4697 break;
4698 if (!fli->started_p)
4700 fli->started_p = 1;
4702 oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_pch_rs_");
4703 put_mangled_filename (f, v->line.file);
4704 oprintf (f, "[] = {\n");
4707 oprintf (f, " { &%s, 1, sizeof (%s), NULL, NULL },\n",
4708 v->name, v->name);
4711 finish_root_table (flp, "pch_rs", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4712 "gt_pch_scalar_rtab");
4715 /* Prints not-as-ugly version of a typename of T to OF. Trades the uniquness
4716 guaranteee for somewhat increased readability. If name conflicts do happen,
4717 this funcion will have to be adjusted to be more like
4718 output_mangled_typename. */
4720 #define INDENT 2
4722 /* Dumps the value of typekind KIND. */
4724 static void
4725 dump_typekind (int indent, enum typekind kind)
4727 printf ("%*ckind = ", indent, ' ');
4728 switch (kind)
4730 case TYPE_SCALAR:
4731 printf ("TYPE_SCALAR");
4732 break;
4733 case TYPE_STRING:
4734 printf ("TYPE_STRING");
4735 break;
4736 case TYPE_STRUCT:
4737 printf ("TYPE_STRUCT");
4738 break;
4739 case TYPE_UNDEFINED:
4740 printf ("TYPE_UNDEFINED");
4741 break;
4742 case TYPE_USER_STRUCT:
4743 printf ("TYPE_USER_STRUCT");
4744 break;
4745 case TYPE_UNION:
4746 printf ("TYPE_UNION");
4747 break;
4748 case TYPE_POINTER:
4749 printf ("TYPE_POINTER");
4750 break;
4751 case TYPE_ARRAY:
4752 printf ("TYPE_ARRAY");
4753 break;
4754 case TYPE_CALLBACK:
4755 printf ("TYPE_CALLBACK");
4756 break;
4757 case TYPE_LANG_STRUCT:
4758 printf ("TYPE_LANG_STRUCT");
4759 break;
4760 default:
4761 gcc_unreachable ();
4763 printf ("\n");
4766 /* Dumps the value of GC_USED flag. */
4768 static void
4769 dump_gc_used (int indent, enum gc_used_enum gc_used)
4771 printf ("%*cgc_used = ", indent, ' ');
4772 switch (gc_used)
4774 case GC_UNUSED:
4775 printf ("GC_UNUSED");
4776 break;
4777 case GC_USED:
4778 printf ("GC_USED");
4779 break;
4780 case GC_MAYBE_POINTED_TO:
4781 printf ("GC_MAYBE_POINTED_TO");
4782 break;
4783 case GC_POINTED_TO:
4784 printf ("GC_POINTED_TO");
4785 break;
4786 default:
4787 gcc_unreachable ();
4789 printf ("\n");
4792 /* Dumps the type options OPT. */
4794 static void
4795 dump_options (int indent, options_p opt)
4797 options_p o;
4798 printf ("%*coptions = ", indent, ' ');
4799 o = opt;
4800 while (o)
4802 switch (o->kind)
4804 case OPTION_STRING:
4805 printf ("%s:string %s ", o->name, o->info.string);
4806 break;
4807 case OPTION_TYPE:
4808 printf ("%s:type ", o->name);
4809 dump_type (indent+1, o->info.type);
4810 break;
4811 case OPTION_NESTED:
4812 printf ("%s:nested ", o->name);
4813 break;
4814 case OPTION_NONE:
4815 gcc_unreachable ();
4817 o = o->next;
4819 printf ("\n");
4822 /* Dumps the source file location in LINE. */
4824 static void
4825 dump_fileloc (int indent, struct fileloc line)
4827 printf ("%*cfileloc: file = %s, line = %d\n", indent, ' ',
4828 get_input_file_name (line.file),
4829 line.line);
4832 /* Recursively dumps the struct, union, or a language-specific
4833 struct T. */
4835 static void
4836 dump_type_u_s (int indent, type_p t)
4838 pair_p fields;
4840 gcc_assert (union_or_struct_p (t));
4841 printf ("%*cu.s.tag = %s\n", indent, ' ', t->u.s.tag);
4842 dump_fileloc (indent, t->u.s.line);
4843 printf ("%*cu.s.fields =\n", indent, ' ');
4844 fields = t->u.s.fields;
4845 while (fields)
4847 dump_pair (indent + INDENT, fields);
4848 fields = fields->next;
4850 printf ("%*cend of fields of type %p\n", indent, ' ', (void *) t);
4851 dump_options (indent, t->u.s.opt);
4852 printf ("%*cu.s.bitmap = %X\n", indent, ' ', t->u.s.bitmap);
4853 if (t->kind == TYPE_LANG_STRUCT)
4855 printf ("%*cu.s.lang_struct:\n", indent, ' ');
4856 dump_type_list (indent + INDENT, t->u.s.lang_struct);
4860 /* Recursively dumps the array T. */
4862 static void
4863 dump_type_u_a (int indent, type_p t)
4865 gcc_assert (t->kind == TYPE_ARRAY);
4866 printf ("%*clen = %s, u.a.p:\n", indent, ' ', t->u.a.len);
4867 dump_type_list (indent + INDENT, t->u.a.p);
4870 /* Recursively dumps the type list T. */
4872 static void
4873 dump_type_list (int indent, type_p t)
4875 type_p p = t;
4876 while (p)
4878 dump_type (indent, p);
4879 p = p->next;
4883 static htab_t seen_types;
4885 /* Recursively dumps the type T if it was not dumped previously. */
4887 static void
4888 dump_type (int indent, type_p t)
4890 void **slot;
4892 printf ("%*cType at %p: ", indent, ' ', (void *) t);
4893 if (t->kind == TYPE_UNDEFINED)
4895 gcc_assert (t->gc_used == GC_UNUSED);
4896 printf ("undefined.\n");
4897 return;
4900 if (seen_types == NULL)
4901 seen_types = htab_create (100, htab_hash_pointer, htab_eq_pointer, NULL);
4903 slot = htab_find_slot (seen_types, t, INSERT);
4904 if (*slot != NULL)
4906 printf ("already seen.\n");
4907 return;
4909 *slot = t;
4910 printf ("\n");
4912 dump_typekind (indent, t->kind);
4913 printf ("%*cpointer_to = %p\n", indent + INDENT, ' ',
4914 (void *) t->pointer_to);
4915 dump_gc_used (indent + INDENT, t->gc_used);
4916 switch (t->kind)
4918 case TYPE_SCALAR:
4919 printf ("%*cscalar_is_char = %s\n", indent + INDENT, ' ',
4920 t->u.scalar_is_char ? "true" : "false");
4921 break;
4922 case TYPE_STRING:
4923 case TYPE_CALLBACK:
4924 break;
4925 case TYPE_STRUCT:
4926 case TYPE_UNION:
4927 case TYPE_LANG_STRUCT:
4928 case TYPE_USER_STRUCT:
4929 dump_type_u_s (indent + INDENT, t);
4930 break;
4931 case TYPE_POINTER:
4932 printf ("%*cp:\n", indent + INDENT, ' ');
4933 dump_type (indent + INDENT, t->u.p);
4934 break;
4935 case TYPE_ARRAY:
4936 dump_type_u_a (indent + INDENT, t);
4937 break;
4938 default:
4939 gcc_unreachable ();
4941 printf ("%*cEnd of type at %p\n", indent, ' ', (void *) t);
4944 /* Dumps the pair P. */
4946 static void
4947 dump_pair (int indent, pair_p p)
4949 printf ("%*cpair: name = %s\n", indent, ' ', p->name);
4950 dump_type (indent, p->type);
4951 dump_fileloc (indent, p->line);
4952 dump_options (indent, p->opt);
4953 printf ("%*cEnd of pair %s\n", indent, ' ', p->name);
4956 /* Dumps the list of pairs PP. */
4958 static void
4959 dump_pair_list (const char *name, pair_p pp)
4961 pair_p p;
4962 printf ("%s:\n", name);
4963 for (p = pp; p != NULL; p = p->next)
4964 dump_pair (0, p);
4965 printf ("End of %s\n\n", name);
4968 /* Dumps the STRUCTURES. */
4970 static void
4971 dump_structures (const char *name, type_p structures)
4973 printf ("%s:\n", name);
4974 dump_type_list (0, structures);
4975 printf ("End of %s\n\n", name);
4978 /* Dumps the internal structures of gengtype. This is useful to debug
4979 gengtype itself, or to understand what it does, e.g. for plugin
4980 developers. */
4982 static void
4983 dump_everything (void)
4985 dump_pair_list ("typedefs", typedefs);
4986 dump_structures ("structures", structures);
4987 dump_pair_list ("variables", variables);
4989 /* Allocated with the first call to dump_type. */
4990 htab_delete (seen_types);
4995 /* Option specification for getopt_long. */
4996 static const struct option gengtype_long_options[] = {
4997 {"help", no_argument, NULL, 'h'},
4998 {"version", no_argument, NULL, 'V'},
4999 {"verbose", no_argument, NULL, 'v'},
5000 {"dump", no_argument, NULL, 'd'},
5001 {"debug", no_argument, NULL, 'D'},
5002 {"plugin", required_argument, NULL, 'P'},
5003 {"srcdir", required_argument, NULL, 'S'},
5004 {"backupdir", required_argument, NULL, 'B'},
5005 {"inputs", required_argument, NULL, 'I'},
5006 {"read-state", required_argument, NULL, 'r'},
5007 {"write-state", required_argument, NULL, 'w'},
5008 /* Terminating NULL placeholder. */
5009 {NULL, no_argument, NULL, 0},
5013 static void
5014 print_usage (void)
5016 printf ("Usage: %s\n", progname);
5017 printf ("\t -h | --help " " \t# Give this help.\n");
5018 printf ("\t -D | --debug "
5019 " \t# Give debug output to debug %s itself.\n", progname);
5020 printf ("\t -V | --version " " \t# Give version information.\n");
5021 printf ("\t -v | --verbose \t# Increase verbosity. Can be given several times.\n");
5022 printf ("\t -d | --dump " " \t# Dump state for debugging.\n");
5023 printf ("\t -P | --plugin <output-file> <plugin-src> ... "
5024 " \t# Generate for plugin.\n");
5025 printf ("\t -S | --srcdir <GCC-directory> "
5026 " \t# Specify the GCC source directory.\n");
5027 printf ("\t -B | --backupdir <directory> "
5028 " \t# Specify the backup directory for updated files.\n");
5029 printf ("\t -I | --inputs <input-list> "
5030 " \t# Specify the file with source files list.\n");
5031 printf ("\t -w | --write-state <state-file> " " \t# Write a state file.\n");
5032 printf ("\t -r | --read-state <state-file> " " \t# Read a state file.\n");
5035 static void
5036 print_version (void)
5038 printf ("%s %s%s\n", progname, pkgversion_string, version_string);
5039 printf ("Report bugs: %s\n", bug_report_url);
5042 /* Parse the program options using getopt_long... */
5043 static void
5044 parse_program_options (int argc, char **argv)
5046 int opt = -1;
5047 while ((opt = getopt_long (argc, argv, "hVvdP:S:B:I:w:r:D",
5048 gengtype_long_options, NULL)) >= 0)
5050 switch (opt)
5052 case 'h': /* --help */
5053 print_usage ();
5054 break;
5055 case 'V': /* --version */
5056 print_version ();
5057 break;
5058 case 'd': /* --dump */
5059 do_dump = 1;
5060 break;
5061 case 'D': /* --debug */
5062 do_debug = 1;
5063 break;
5064 case 'v': /* --verbose */
5065 verbosity_level++;
5066 break;
5067 case 'P': /* --plugin */
5068 if (optarg)
5069 plugin_output_filename = optarg;
5070 else
5071 fatal ("missing plugin output file name");
5072 break;
5073 case 'S': /* --srcdir */
5074 if (optarg)
5075 srcdir = optarg;
5076 else
5077 fatal ("missing source directory");
5078 srcdir_len = strlen (srcdir);
5079 break;
5080 case 'B': /* --backupdir */
5081 if (optarg)
5082 backup_dir = optarg;
5083 else
5084 fatal ("missing backup directory");
5085 break;
5086 case 'I': /* --inputs */
5087 if (optarg)
5088 inputlist = optarg;
5089 else
5090 fatal ("missing input list");
5091 break;
5092 case 'r': /* --read-state */
5093 if (optarg)
5094 read_state_filename = optarg;
5095 else
5096 fatal ("missing read state file");
5097 DBGPRINTF ("read state %s\n", optarg);
5098 break;
5099 case 'w': /* --write-state */
5100 DBGPRINTF ("write state %s\n", optarg);
5101 if (optarg)
5102 write_state_filename = optarg;
5103 else
5104 fatal ("missing write state file");
5105 break;
5106 default:
5107 fprintf (stderr, "%s: unknown flag '%c'\n", progname, opt);
5108 print_usage ();
5109 fatal ("unexpected flag");
5112 if (plugin_output_filename)
5114 /* In plugin mode we require some input files. */
5115 int i = 0;
5116 if (optind >= argc)
5117 fatal ("no source files given in plugin mode");
5118 nb_plugin_files = argc - optind;
5119 plugin_files = XNEWVEC (input_file*, nb_plugin_files);
5120 for (i = 0; i < (int) nb_plugin_files; i++)
5122 char *name = argv[i + optind];
5123 plugin_files[i] = input_file_by_name (name);
5130 /******* Manage input files. ******/
5132 /* Hash table of unique input file names. */
5133 static htab_t input_file_htab;
5135 /* Find or allocate a new input_file by hash-consing it. */
5136 input_file*
5137 input_file_by_name (const char* name)
5139 void ** slot;
5140 input_file* f = NULL;
5141 int namlen = 0;
5142 if (!name)
5143 return NULL;
5144 namlen = strlen (name);
5145 f = XCNEWVAR (input_file, sizeof (input_file)+namlen+2);
5146 f->inpbitmap = 0;
5147 f->inpoutf = NULL;
5148 f->inpisplugin = false;
5149 strcpy (f->inpname, name);
5150 slot = htab_find_slot (input_file_htab, f, INSERT);
5151 gcc_assert (slot != NULL);
5152 if (*slot)
5154 /* Already known input file. */
5155 free (f);
5156 return (input_file*)(*slot);
5158 /* New input file. */
5159 *slot = f;
5160 return f;
5163 /* Hash table support routines for input_file-s. */
5164 static hashval_t
5165 htab_hash_inputfile (const void *p)
5167 const input_file *inpf = (const input_file *) p;
5168 gcc_assert (inpf);
5169 return htab_hash_string (get_input_file_name (inpf));
5172 static int
5173 htab_eq_inputfile (const void *x, const void *y)
5175 const input_file *inpfx = (const input_file *) x;
5176 const input_file *inpfy = (const input_file *) y;
5177 gcc_assert (inpfx != NULL && inpfy != NULL);
5178 return !filename_cmp (get_input_file_name (inpfx), get_input_file_name (inpfy));
5183 main (int argc, char **argv)
5185 size_t i;
5186 static struct fileloc pos = { NULL, 0 };
5187 outf_p output_header;
5189 /* Mandatory common initializations. */
5190 progname = "gengtype"; /* For fatal and messages. */
5191 /* Create the hash-table used to hash-cons input files. */
5192 input_file_htab =
5193 htab_create (800, htab_hash_inputfile, htab_eq_inputfile, NULL);
5194 /* Initialize our special input files. */
5195 this_file = input_file_by_name (__FILE__);
5196 system_h_file = input_file_by_name ("system.h");
5197 /* Set the scalar_is_char union number for predefined scalar types. */
5198 scalar_nonchar.u.scalar_is_char = FALSE;
5199 scalar_char.u.scalar_is_char = TRUE;
5201 parse_program_options (argc, argv);
5203 if (do_debug)
5205 time_t now = (time_t) 0;
5206 time (&now);
5207 DBGPRINTF ("gengtype started pid %d at %s",
5208 (int) getpid (), ctime (&now));
5211 /* Parse the input list and the input files. */
5212 DBGPRINTF ("inputlist %s", inputlist);
5213 if (read_state_filename)
5215 if (inputlist)
5216 fatal ("input list %s cannot be given with a read state file %s",
5217 inputlist, read_state_filename);
5218 read_state (read_state_filename);
5219 DBGPRINT_COUNT_TYPE ("structures after read_state", structures);
5221 else if (inputlist)
5223 /* These types are set up with #define or else outside of where
5224 we can see them. We should initialize them before calling
5225 read_input_list. */
5226 #define POS_HERE(Call) do { pos.file = this_file; pos.line = __LINE__; \
5227 Call;} while (0)
5228 POS_HERE (do_scalar_typedef ("CUMULATIVE_ARGS", &pos));
5229 POS_HERE (do_scalar_typedef ("REAL_VALUE_TYPE", &pos));
5230 POS_HERE (do_scalar_typedef ("FIXED_VALUE_TYPE", &pos));
5231 POS_HERE (do_scalar_typedef ("double_int", &pos));
5232 POS_HERE (do_scalar_typedef ("poly_int64_pod", &pos));
5233 POS_HERE (do_scalar_typedef ("offset_int", &pos));
5234 POS_HERE (do_scalar_typedef ("widest_int", &pos));
5235 POS_HERE (do_scalar_typedef ("int64_t", &pos));
5236 POS_HERE (do_scalar_typedef ("poly_int64", &pos));
5237 POS_HERE (do_scalar_typedef ("poly_uint64", &pos));
5238 POS_HERE (do_scalar_typedef ("uint64_t", &pos));
5239 POS_HERE (do_scalar_typedef ("uint32_t", &pos));
5240 POS_HERE (do_scalar_typedef ("uint8", &pos));
5241 POS_HERE (do_scalar_typedef ("uintptr_t", &pos));
5242 POS_HERE (do_scalar_typedef ("jword", &pos));
5243 POS_HERE (do_scalar_typedef ("JCF_u2", &pos));
5244 POS_HERE (do_scalar_typedef ("void", &pos));
5245 POS_HERE (do_scalar_typedef ("machine_mode", &pos));
5246 POS_HERE (do_scalar_typedef ("fixed_size_mode", &pos));
5247 POS_HERE (do_scalar_typedef ("CONSTEXPR", &pos));
5248 POS_HERE (do_typedef ("void *",
5249 create_pointer (resolve_typedef ("void", &pos)),
5250 &pos));
5251 #undef POS_HERE
5252 read_input_list (inputlist);
5253 num_build_headers = 0;
5254 for (i = 0; i < num_gt_files; i++)
5256 const char *fname = get_input_file_name (gt_files[i]);
5257 parse_file (fname);
5258 DBGPRINTF ("parsed file #%d %s", (int) i, fname);
5259 /* Check if this is a header file generated during the build. */
5260 int len = strlen (fname);
5261 if (len >= 5
5262 && fname[0] == '.'
5263 && IS_DIR_SEPARATOR (fname[1])
5264 && fname[len-2] == '.'
5265 && fname[len-1] == 'h')
5266 num_build_headers++;
5268 if (verbosity_level >= 1)
5269 printf ("%s parsed %d files with %d GTY types\n",
5270 progname, (int) num_gt_files, type_count);
5272 DBGPRINT_COUNT_TYPE ("structures after parsing", structures);
5274 else
5275 fatal ("either an input list or a read state file should be given");
5276 if (hit_error)
5277 return 1;
5280 if (plugin_output_filename)
5282 size_t ix = 0;
5283 /* In plugin mode, we should have read a state file, and have
5284 given at least one plugin file. */
5285 if (!read_state_filename)
5286 fatal ("No read state given in plugin mode for %s",
5287 plugin_output_filename);
5289 if (nb_plugin_files == 0 || !plugin_files)
5290 fatal ("No plugin files given in plugin mode for %s",
5291 plugin_output_filename);
5293 /* Parse our plugin files and augment the state. */
5294 for (ix = 0; ix < nb_plugin_files; ix++)
5296 input_file* pluginput = plugin_files [ix];
5297 pluginput->inpisplugin = true;
5298 parse_file (get_input_file_name (pluginput));
5300 if (hit_error)
5301 return 1;
5303 plugin_output = create_file ("GCC", plugin_output_filename);
5304 DBGPRINTF ("created plugin_output %p named %s",
5305 (void *) plugin_output, plugin_output->name);
5307 else
5308 { /* No plugin files, we are in normal mode. */
5309 if (!srcdir)
5310 fatal ("gengtype needs a source directory in normal mode");
5312 if (hit_error)
5313 return 1;
5315 gen_rtx_next ();
5317 set_gc_used (variables);
5319 for (type_p t = structures; t; t = t->next)
5321 bool for_user = false;
5322 for (options_p o = t->u.s.opt; o; o = o->next)
5323 if (strcmp (o->name, "for_user") == 0)
5325 for_user = true;
5326 break;
5329 if (for_user)
5330 set_gc_used_type (t, GC_POINTED_TO);
5332 /* The state at this point is read from the state input file or by
5333 parsing source files and optionally augmented by parsing plugin
5334 source files. Write it now. */
5335 if (write_state_filename)
5337 DBGPRINT_COUNT_TYPE ("structures before write_state", structures);
5339 if (hit_error)
5340 fatal ("didn't write state file %s after errors",
5341 write_state_filename);
5343 DBGPRINTF ("before write_state %s", write_state_filename);
5344 write_state (write_state_filename);
5346 if (do_dump)
5347 dump_everything ();
5349 /* After having written the state file we return immediately to
5350 avoid generating any output file. */
5351 if (hit_error)
5352 return 1;
5353 else
5354 return 0;
5358 open_base_files ();
5360 output_header = plugin_output ? plugin_output : header_file;
5361 DBGPRINT_COUNT_TYPE ("structures before write_types outputheader",
5362 structures);
5364 write_types (output_header, structures, &ggc_wtd);
5365 if (plugin_files == NULL)
5367 DBGPRINT_COUNT_TYPE ("structures before write_types headerfil",
5368 structures);
5369 write_types (header_file, structures, &pch_wtd);
5370 write_local (header_file, structures);
5372 write_roots (variables, plugin_files == NULL);
5373 write_rtx_next ();
5374 close_output_files ();
5376 if (do_dump)
5377 dump_everything ();
5379 /* Don't bother about free-ing any input or plugin file, etc. */
5381 if (hit_error)
5382 return 1;
5383 return 0;