Daily bump.
[official-gcc.git] / gcc / gengtype.c
blobdb218a7bce764093bc6bdeab487a10f7ca2ed3d7
1 /* Process source files and output type information.
2 Copyright (C) 2002-2021 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.c 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.c" 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_tree_exp (type_p t, options_p opt);
515 static type_p adjust_field_rtx_def (type_p t, options_p opt);
517 /* Define S as a typedef to T at POS. */
519 void
520 do_typedef (const char *s, type_p t, struct fileloc *pos)
522 pair_p p;
524 /* temporary kludge - gengtype doesn't handle conditionals or
525 macros. Ignore any attempt to typedef CUMULATIVE_ARGS, unless it
526 is coming from this file (main() sets them up with safe dummy
527 definitions). */
528 if (!strcmp (s, "CUMULATIVE_ARGS") && pos->file != this_file)
529 return;
531 for (p = typedefs; p != NULL; p = p->next)
532 if (strcmp (p->name, s) == 0)
534 if (p->type != t && strcmp (s, "result_type") != 0)
536 error_at_line (pos, "type `%s' previously defined", s);
537 error_at_line (&p->line, "previously defined here");
539 return;
542 p = XNEW (struct pair);
543 p->next = typedefs;
544 p->name = s;
545 p->type = t;
546 p->line = *pos;
547 p->opt = NULL;
548 typedefs = p;
551 /* Define S as a typename of a scalar. Cannot be used to define
552 typedefs of 'char'. Note: is also used for pointer-to-function
553 typedefs (which are therefore not treated as pointers). */
555 void
556 do_scalar_typedef (const char *s, struct fileloc *pos)
558 do_typedef (s, &scalar_nonchar, pos);
561 /* Similar to strtok_r. */
563 static char *
564 strtoken (char *str, const char *delim, char **next)
566 char *p;
568 if (str == NULL)
569 str = *next;
571 /* Skip the leading delimiters. */
572 str += strspn (str, delim);
573 if (*str == '\0')
574 /* This is an empty token. */
575 return NULL;
577 /* The current token. */
578 p = str;
580 /* Find the next delimiter. */
581 str += strcspn (str, delim);
582 if (*str == '\0')
583 /* This is the last token. */
584 *next = str;
585 else
587 /* Terminate the current token. */
588 *str = '\0';
589 /* Advance to the next token. */
590 *next = str + 1;
593 return p;
596 /* Define TYPE_NAME to be a user defined type at location POS. */
598 type_p
599 create_user_defined_type (const char *type_name, struct fileloc *pos)
601 type_p ty = find_structure (type_name, TYPE_USER_STRUCT);
603 /* We might have already seen an incomplete decl of the given type,
604 in which case we won't have yet seen a GTY((user)), and the type will
605 only have kind "TYPE_STRUCT". Mark it as a user struct. */
606 ty->kind = TYPE_USER_STRUCT;
608 ty->u.s.line = *pos;
609 ty->u.s.bitmap = get_lang_bitmap (pos->file);
610 do_typedef (type_name, ty, pos);
612 /* If TYPE_NAME specifies a template, create references to the types
613 in the template by pretending that each type is a field of TY.
614 This is needed to make sure that the types referenced by the
615 template are marked as used. */
616 char *str = xstrdup (type_name);
617 char *open_bracket = strchr (str, '<');
618 if (open_bracket)
620 /* We only accept simple template declarations (see
621 require_template_declaration), so we only need to parse a
622 comma-separated list of strings, implicitly assumed to
623 be type names, potentially with "*" characters. */
624 char *arg = open_bracket + 1;
625 /* Workaround -Wmaybe-uninitialized false positive during
626 profiledbootstrap by initializing it. */
627 char *next = NULL;
628 char *type_id = strtoken (arg, ",>", &next);
629 pair_p fields = 0;
630 while (type_id)
632 /* Create a new field for every type found inside the template
633 parameter list. */
635 /* Support a single trailing "*" character. */
636 const char *star = strchr (type_id, '*');
637 int is_ptr = (star != NULL);
638 size_t offset_to_star = star - type_id;
639 if (is_ptr)
640 offset_to_star = star - type_id;
642 if (strstr (type_id, "char*"))
644 type_id = strtoken (0, ",>", &next);
645 continue;
648 char *field_name = xstrdup (type_id);
650 type_p arg_type;
651 if (is_ptr)
653 /* Strip off the first '*' character (and any subsequent text). */
654 *(field_name + offset_to_star) = '\0';
656 arg_type = find_structure (field_name, TYPE_STRUCT);
657 arg_type = create_pointer (arg_type);
659 else
660 arg_type = resolve_typedef (field_name, pos);
662 fields = create_field_at (fields, arg_type, field_name, 0, pos);
663 type_id = strtoken (0, ",>", &next);
666 /* Associate the field list to TY. */
667 ty->u.s.fields = fields;
669 free (str);
671 return ty;
675 /* Given a typedef name S, return its associated type. Return NULL if
676 S is not a registered type name. */
678 static type_p
679 type_for_name (const char *s)
681 pair_p p;
683 /* Special-case support for types within a "gcc::" namespace. Rather
684 than fully-supporting namespaces, simply strip off the "gcc::" prefix
685 where present. This allows us to have GTY roots of this form:
686 extern GTY(()) gcc::some_type *some_ptr;
687 where the autogenerated functions will refer to simply "some_type",
688 where they can be resolved into their namespace. */
689 if (startswith (s, "gcc::"))
690 s += 5;
692 for (p = typedefs; p != NULL; p = p->next)
693 if (strcmp (p->name, s) == 0)
694 return p->type;
695 return NULL;
699 /* Create an undefined type with name S and location POS. Return the
700 newly created type. */
702 static type_p
703 create_undefined_type (const char *s, struct fileloc *pos)
705 type_p ty = find_structure (s, TYPE_UNDEFINED);
706 ty->u.s.line = *pos;
707 ty->u.s.bitmap = get_lang_bitmap (pos->file);
708 do_typedef (s, ty, pos);
709 return ty;
713 /* Return the type previously defined for S. Use POS to report errors. */
715 type_p
716 resolve_typedef (const char *s, struct fileloc *pos)
718 bool is_template_instance = (strchr (s, '<') != NULL);
719 type_p p = type_for_name (s);
721 /* If we did not find a typedef registered, generate a TYPE_UNDEFINED
722 type for regular type identifiers. If the type identifier S is a
723 template instantiation, however, we treat it as a user defined
724 type.
726 FIXME, this is actually a limitation in gengtype. Supporting
727 template types and their instances would require keeping separate
728 track of the basic types definition and its instances. This
729 essentially forces all template classes in GC to be marked
730 GTY((user)). */
731 if (!p)
732 p = (is_template_instance)
733 ? create_user_defined_type (s, pos)
734 : create_undefined_type (s, pos);
736 return p;
739 /* Add SUBCLASS to head of linked list of BASE's subclasses. */
741 void add_subclass (type_p base, type_p subclass)
743 gcc_assert (union_or_struct_p (base));
744 gcc_assert (union_or_struct_p (subclass));
746 subclass->u.s.next_sibling_class = base->u.s.first_subclass;
747 base->u.s.first_subclass = subclass;
750 /* Create and return a new structure with tag NAME at POS with fields
751 FIELDS and options O. The KIND of structure must be one of
752 TYPE_STRUCT, TYPE_UNION or TYPE_USER_STRUCT. */
754 type_p
755 new_structure (const char *name, enum typekind kind, struct fileloc *pos,
756 pair_p fields, options_p o, type_p base_class)
758 type_p si;
759 type_p s = NULL;
760 lang_bitmap bitmap = get_lang_bitmap (pos->file);
761 bool isunion = (kind == TYPE_UNION);
762 type_p *p = &structures;
764 gcc_assert (union_or_struct_p (kind));
766 for (si = structures; si != NULL; p = &si->next, si = *p)
767 if (strcmp (name, si->u.s.tag) == 0 && UNION_P (si) == isunion)
769 type_p ls = NULL;
770 if (si->kind == TYPE_LANG_STRUCT)
772 ls = si;
774 for (si = ls->u.s.lang_struct; si != NULL; si = si->next)
775 if (si->u.s.bitmap == bitmap)
776 s = si;
778 else if (si->u.s.line.file != NULL && si->u.s.bitmap != bitmap)
780 ls = si;
781 type_count++;
782 si = XCNEW (struct type);
783 memcpy (si, ls, sizeof (struct type));
784 ls->kind = TYPE_LANG_STRUCT;
785 ls->u.s.lang_struct = si;
786 ls->u.s.fields = NULL;
787 si->next = NULL;
788 si->state_number = -type_count;
789 si->pointer_to = NULL;
790 si->u.s.lang_struct = ls;
792 else
793 s = si;
795 if (ls != NULL && s == NULL)
797 type_count++;
798 s = XCNEW (struct type);
799 s->state_number = -type_count;
800 s->next = ls->u.s.lang_struct;
801 ls->u.s.lang_struct = s;
802 s->u.s.lang_struct = ls;
804 break;
807 if (s == NULL)
809 type_count++;
810 s = XCNEW (struct type);
811 s->state_number = -type_count;
812 *p = s;
815 if (s->u.s.lang_struct && (s->u.s.lang_struct->u.s.bitmap & bitmap))
817 error_at_line (pos, "duplicate definition of '%s %s'",
818 isunion ? "union" : "struct", s->u.s.tag);
819 error_at_line (&s->u.s.line, "previous definition here");
822 s->kind = kind;
823 s->u.s.tag = name;
824 s->u.s.line = *pos;
825 s->u.s.fields = fields;
826 s->u.s.opt = o;
827 s->u.s.bitmap = bitmap;
828 if (s->u.s.lang_struct)
829 s->u.s.lang_struct->u.s.bitmap |= bitmap;
830 s->u.s.base_class = base_class;
831 if (base_class)
832 add_subclass (base_class, s);
834 return s;
837 /* Return the previously-defined structure or union with tag NAME,
838 or a new empty structure or union if none was defined previously.
839 The KIND of structure must be one of TYPE_STRUCT, TYPE_UNION or
840 TYPE_USER_STRUCT. */
842 type_p
843 find_structure (const char *name, enum typekind kind)
845 type_p s;
846 bool isunion = (kind == TYPE_UNION);
847 type_p *p = &structures;
849 gcc_assert (kind == TYPE_UNDEFINED || union_or_struct_p (kind));
851 for (s = structures; s != NULL; p = &s->next, s = *p)
852 if (strcmp (name, s->u.s.tag) == 0 && UNION_P (s) == isunion)
853 return s;
855 type_count++;
856 s = XCNEW (struct type);
857 s->state_number = -type_count;
858 s->kind = kind;
859 s->u.s.tag = name;
860 *p = s;
861 return s;
864 /* Return a scalar type with name NAME. */
866 type_p
867 create_scalar_type (const char *name)
869 if (!strcmp (name, "char") || !strcmp (name, "unsigned char"))
870 return &scalar_char;
871 else
872 return &scalar_nonchar;
876 /* Return a pointer to T. */
878 type_p
879 create_pointer (type_p t)
881 if (!t->pointer_to)
883 type_p r = XCNEW (struct type);
884 type_count++;
885 r->state_number = -type_count;
886 r->kind = TYPE_POINTER;
887 r->u.p = t;
888 t->pointer_to = r;
890 return t->pointer_to;
893 /* Return an array of length LEN. */
895 type_p
896 create_array (type_p t, const char *len)
898 type_p v;
900 type_count++;
901 v = XCNEW (struct type);
902 v->kind = TYPE_ARRAY;
903 v->state_number = -type_count;
904 v->u.a.p = t;
905 v->u.a.len = len;
906 return v;
909 /* Return a string options structure with name NAME and info INFO.
910 NEXT is the next option in the chain. */
911 options_p
912 create_string_option (options_p next, const char *name, const char *info)
914 options_p o = XNEW (struct options);
915 o->kind = OPTION_STRING;
916 o->next = next;
917 o->name = name;
918 o->info.string = info;
919 return o;
922 /* Create a type options structure with name NAME and info INFO. NEXT
923 is the next option in the chain. */
924 options_p
925 create_type_option (options_p next, const char* name, type_p info)
927 options_p o = XNEW (struct options);
928 o->next = next;
929 o->name = name;
930 o->kind = OPTION_TYPE;
931 o->info.type = info;
932 return o;
935 /* Create a nested pointer options structure with name NAME and info
936 INFO. NEXT is the next option in the chain. */
937 options_p
938 create_nested_option (options_p next, const char* name,
939 struct nested_ptr_data* info)
941 options_p o;
942 o = XNEW (struct options);
943 o->next = next;
944 o->name = name;
945 o->kind = OPTION_NESTED;
946 o->info.nested = info;
947 return o;
950 /* Return an options structure for a "nested_ptr" option. */
951 options_p
952 create_nested_ptr_option (options_p next, type_p t,
953 const char *to, const char *from)
955 struct nested_ptr_data *d = XNEW (struct nested_ptr_data);
957 d->type = adjust_field_type (t, 0);
958 d->convert_to = to;
959 d->convert_from = from;
960 return create_nested_option (next, "nested_ptr", d);
963 /* Add a variable named S of type T with options O defined at POS,
964 to `variables'. */
965 void
966 note_variable (const char *s, type_p t, options_p o, struct fileloc *pos)
968 pair_p n;
969 n = XNEW (struct pair);
970 n->name = s;
971 n->type = t;
972 n->line = *pos;
973 n->opt = o;
974 n->next = variables;
975 variables = n;
978 /* Most-general structure field creator. */
979 static pair_p
980 create_field_all (pair_p next, type_p type, const char *name, options_p opt,
981 const input_file *inpf, int line)
983 pair_p field;
985 field = XNEW (struct pair);
986 field->next = next;
987 field->type = type;
988 field->name = name;
989 field->opt = opt;
990 field->line.file = inpf;
991 field->line.line = line;
992 return field;
995 /* Create a field that came from the source code we are scanning,
996 i.e. we have a 'struct fileloc', and possibly options; also,
997 adjust_field_type should be called. */
998 pair_p
999 create_field_at (pair_p next, type_p type, const char *name, options_p opt,
1000 struct fileloc *pos)
1002 return create_field_all (next, adjust_field_type (type, opt),
1003 name, opt, pos->file, pos->line);
1006 /* Create a fake field with the given type and name. NEXT is the next
1007 field in the chain. */
1008 #define create_field(next,type,name) \
1009 create_field_all (next,type,name, 0, this_file, __LINE__)
1011 /* Like create_field, but the field is only valid when condition COND
1012 is true. */
1014 static pair_p
1015 create_optional_field_ (pair_p next, type_p type, const char *name,
1016 const char *cond, int line)
1018 static int id = 1;
1019 pair_p union_fields;
1020 type_p union_type;
1022 /* Create a fake union type with a single nameless field of type TYPE.
1023 The field has a tag of "1". This allows us to make the presence
1024 of a field of type TYPE depend on some boolean "desc" being true. */
1025 union_fields = create_field (NULL, type, "");
1026 union_fields->opt =
1027 create_string_option (union_fields->opt, "dot", "");
1028 union_fields->opt =
1029 create_string_option (union_fields->opt, "tag", "1");
1030 union_type =
1031 new_structure (xasprintf ("%s_%d", "fake_union", id++), TYPE_UNION,
1032 &lexer_line, union_fields, NULL, NULL);
1034 /* Create the field and give it the new fake union type. Add a "desc"
1035 tag that specifies the condition under which the field is valid. */
1036 return create_field_all (next, union_type, name,
1037 create_string_option (0, "desc", cond),
1038 this_file, line);
1041 #define create_optional_field(next,type,name,cond) \
1042 create_optional_field_(next,type,name,cond,__LINE__)
1044 /* Reverse a linked list of 'struct pair's in place. */
1045 pair_p
1046 nreverse_pairs (pair_p list)
1048 pair_p prev = 0, p, next;
1049 for (p = list; p; p = next)
1051 next = p->next;
1052 p->next = prev;
1053 prev = p;
1055 return prev;
1059 /* We don't care how long a CONST_DOUBLE is. */
1060 #define CONST_DOUBLE_FORMAT "ww"
1061 /* We don't want to see codes that are only for generator files. */
1062 #undef GENERATOR_FILE
1064 enum rtx_code
1066 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) ENUM ,
1067 #include "rtl.def"
1068 #undef DEF_RTL_EXPR
1069 NUM_RTX_CODE
1072 static const char *const rtx_name[NUM_RTX_CODE] = {
1073 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) NAME ,
1074 #include "rtl.def"
1075 #undef DEF_RTL_EXPR
1078 static const char *const rtx_format[NUM_RTX_CODE] = {
1079 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) FORMAT ,
1080 #include "rtl.def"
1081 #undef DEF_RTL_EXPR
1084 static int rtx_next_new[NUM_RTX_CODE];
1086 /* We also need codes and names for insn notes (not register notes).
1087 Note that we do *not* bias the note values here. */
1088 enum insn_note
1090 #define DEF_INSN_NOTE(NAME) NAME,
1091 #include "insn-notes.def"
1092 #undef DEF_INSN_NOTE
1094 NOTE_INSN_MAX
1097 /* We must allocate one more entry here, as we use NOTE_INSN_MAX as the
1098 default field for line number notes. */
1099 static const char *const note_insn_name[NOTE_INSN_MAX + 1] = {
1100 #define DEF_INSN_NOTE(NAME) #NAME,
1101 #include "insn-notes.def"
1102 #undef DEF_INSN_NOTE
1105 #undef CONST_DOUBLE_FORMAT
1106 #define GENERATOR_FILE
1108 /* Generate the contents of the rtx_next array. This really doesn't belong
1109 in gengtype at all, but it's needed for adjust_field_rtx_def. */
1111 static void
1112 gen_rtx_next (void)
1114 int i;
1115 for (i = 0; i < NUM_RTX_CODE; i++)
1117 int k;
1119 rtx_next_new[i] = -1;
1120 if (startswith (rtx_format[i], "uu"))
1121 rtx_next_new[i] = 1;
1122 else if (i == COND_EXEC || i == SET || i == EXPR_LIST || i == INSN_LIST)
1123 rtx_next_new[i] = 1;
1124 else
1125 for (k = strlen (rtx_format[i]) - 1; k >= 0; k--)
1126 if (rtx_format[i][k] == 'e' || rtx_format[i][k] == 'u')
1127 rtx_next_new[i] = k;
1131 /* Write out the contents of the rtx_next array. */
1132 static void
1133 write_rtx_next (void)
1135 outf_p f = get_output_file_with_visibility (NULL);
1136 int i;
1137 if (!f)
1138 return;
1140 oprintf (f, "\n/* Used to implement the RTX_NEXT macro. */\n");
1141 oprintf (f, "EXPORTED_CONST unsigned char rtx_next[NUM_RTX_CODE] = {\n");
1142 for (i = 0; i < NUM_RTX_CODE; i++)
1143 if (rtx_next_new[i] == -1)
1144 oprintf (f, " 0,\n");
1145 else
1146 oprintf (f,
1147 " RTX_HDR_SIZE + %d * sizeof (rtunion),\n", rtx_next_new[i]);
1148 oprintf (f, "};\n");
1151 /* Handle `special("rtx_def")'. This is a special case for field
1152 `fld' of struct rtx_def, which is an array of unions whose values
1153 are based in a complex way on the type of RTL. */
1155 static type_p
1156 adjust_field_rtx_def (type_p t, options_p ARG_UNUSED (opt))
1158 pair_p flds = NULL;
1159 options_p nodot;
1160 int i;
1161 type_p rtx_tp, rtvec_tp, tree_tp, mem_attrs_tp, note_union_tp, scalar_tp;
1162 type_p basic_block_tp, reg_attrs_tp, constant_tp, symbol_union_tp;
1164 if (t->kind != TYPE_UNION)
1166 error_at_line (&lexer_line,
1167 "special `rtx_def' must be applied to a union");
1168 return &string_type;
1171 nodot = create_string_option (NULL, "dot", "");
1173 rtx_tp = create_pointer (find_structure ("rtx_def", TYPE_STRUCT));
1174 rtvec_tp = create_pointer (find_structure ("rtvec_def", TYPE_STRUCT));
1175 tree_tp = create_pointer (find_structure ("tree_node", TYPE_UNION));
1176 mem_attrs_tp = create_pointer (find_structure ("mem_attrs", TYPE_STRUCT));
1177 reg_attrs_tp =
1178 create_pointer (find_structure ("reg_attrs", TYPE_STRUCT));
1179 basic_block_tp =
1180 create_pointer (find_structure ("basic_block_def", TYPE_STRUCT));
1181 constant_tp =
1182 create_pointer (find_structure ("constant_descriptor_rtx", TYPE_STRUCT));
1183 scalar_tp = &scalar_nonchar; /* rtunion int */
1186 pair_p note_flds = NULL;
1187 int c;
1189 for (c = 0; c <= NOTE_INSN_MAX; c++)
1191 switch (c)
1193 case NOTE_INSN_MAX:
1194 case NOTE_INSN_DELETED_LABEL:
1195 case NOTE_INSN_DELETED_DEBUG_LABEL:
1196 note_flds = create_field (note_flds, &string_type, "rt_str");
1197 break;
1199 case NOTE_INSN_BLOCK_BEG:
1200 case NOTE_INSN_BLOCK_END:
1201 note_flds = create_field (note_flds, tree_tp, "rt_tree");
1202 break;
1204 case NOTE_INSN_VAR_LOCATION:
1205 note_flds = create_field (note_flds, rtx_tp, "rt_rtx");
1206 break;
1208 default:
1209 note_flds = create_field (note_flds, scalar_tp, "rt_int");
1210 break;
1212 /* NOTE_INSN_MAX is used as the default field for line
1213 number notes. */
1214 if (c == NOTE_INSN_MAX)
1215 note_flds->opt =
1216 create_string_option (nodot, "default", "");
1217 else
1218 note_flds->opt =
1219 create_string_option (nodot, "tag", note_insn_name[c]);
1221 note_union_tp = new_structure ("rtx_def_note_subunion", TYPE_UNION,
1222 &lexer_line, note_flds, NULL, NULL);
1224 /* Create a type to represent the various forms of SYMBOL_REF_DATA. */
1226 pair_p sym_flds;
1227 sym_flds = create_field (NULL, tree_tp, "rt_tree");
1228 sym_flds->opt = create_string_option (nodot, "default", "");
1229 sym_flds = create_field (sym_flds, constant_tp, "rt_constant");
1230 sym_flds->opt = create_string_option (nodot, "tag", "1");
1231 symbol_union_tp = new_structure ("rtx_def_symbol_subunion", TYPE_UNION,
1232 &lexer_line, sym_flds, NULL, NULL);
1234 for (i = 0; i < NUM_RTX_CODE; i++)
1236 pair_p subfields = NULL;
1237 size_t aindex, nmindex;
1238 const char *sname;
1239 type_p substruct;
1240 char *ftag;
1242 for (aindex = 0; aindex < strlen (rtx_format[i]); aindex++)
1244 type_p t;
1245 const char *subname;
1247 switch (rtx_format[i][aindex])
1249 case '*':
1250 case 'i':
1251 case 'n':
1252 case 'w':
1253 case 'r':
1254 t = scalar_tp;
1255 subname = "rt_int";
1256 break;
1258 case 'p':
1259 t = scalar_tp;
1260 subname = "rt_subreg";
1261 break;
1263 case '0':
1264 if (i == MEM && aindex == 1)
1265 t = mem_attrs_tp, subname = "rt_mem";
1266 else if (i == JUMP_INSN && aindex == 7)
1267 t = rtx_tp, subname = "rt_rtx";
1268 else if (i == CODE_LABEL && aindex == 4)
1269 t = scalar_tp, subname = "rt_int";
1270 else if (i == CODE_LABEL && aindex == 3)
1271 t = rtx_tp, subname = "rt_rtx";
1272 else if (i == LABEL_REF && (aindex == 1 || aindex == 2))
1273 t = rtx_tp, subname = "rt_rtx";
1274 else if (i == NOTE && aindex == 3)
1275 t = note_union_tp, subname = "";
1276 else if (i == NOTE && aindex == 4)
1277 t = scalar_tp, subname = "rt_int";
1278 else if (i == NOTE && aindex >= 6)
1279 t = scalar_tp, subname = "rt_int";
1280 else if (i == ADDR_DIFF_VEC && aindex == 4)
1281 t = scalar_tp, subname = "rt_int";
1282 else if (i == VALUE && aindex == 0)
1283 t = scalar_tp, subname = "rt_int";
1284 else if (i == DEBUG_EXPR && aindex == 0)
1285 t = tree_tp, subname = "rt_tree";
1286 else if (i == SYMBOL_REF && aindex == 1)
1287 t = symbol_union_tp, subname = "";
1288 else if (i == JUMP_TABLE_DATA && aindex >= 4)
1289 t = scalar_tp, subname = "rt_int";
1290 else if (i == BARRIER && aindex >= 2)
1291 t = scalar_tp, subname = "rt_int";
1292 else if (i == ENTRY_VALUE && aindex == 0)
1293 t = rtx_tp, subname = "rt_rtx";
1294 else
1296 error_at_line
1297 (&lexer_line,
1298 "rtx type `%s' has `0' in position %lu, can't handle",
1299 rtx_name[i], (unsigned long) aindex);
1300 t = &string_type;
1301 subname = "rt_int";
1303 break;
1305 case 's':
1306 case 'S':
1307 case 'T':
1308 t = &string_type;
1309 subname = "rt_str";
1310 break;
1312 case 'e':
1313 case 'u':
1314 t = rtx_tp;
1315 subname = "rt_rtx";
1316 break;
1318 case 'E':
1319 case 'V':
1320 t = rtvec_tp;
1321 subname = "rt_rtvec";
1322 break;
1324 case 't':
1325 t = tree_tp;
1326 subname = "rt_tree";
1327 break;
1329 case 'B':
1330 t = basic_block_tp;
1331 subname = "rt_bb";
1332 break;
1334 default:
1335 error_at_line
1336 (&lexer_line,
1337 "rtx type `%s' has `%c' in position %lu, can't handle",
1338 rtx_name[i], rtx_format[i][aindex],
1339 (unsigned long) aindex);
1340 t = &string_type;
1341 subname = "rt_int";
1342 break;
1345 subfields = create_field (subfields, t,
1346 xasprintf (".fld[%lu].%s",
1347 (unsigned long) aindex,
1348 subname));
1349 subfields->opt = nodot;
1350 if (t == note_union_tp)
1351 subfields->opt =
1352 create_string_option (subfields->opt, "desc",
1353 "NOTE_KIND (&%0)");
1354 if (t == symbol_union_tp)
1355 subfields->opt =
1356 create_string_option (subfields->opt, "desc",
1357 "CONSTANT_POOL_ADDRESS_P (&%0)");
1360 if (i == REG)
1361 subfields = create_field (subfields, reg_attrs_tp, "reg.attrs");
1363 if (i == SYMBOL_REF)
1365 /* Add the "block_sym" field if SYMBOL_REF_HAS_BLOCK_INFO_P
1366 holds. */
1367 type_p field_tp = find_structure ("block_symbol", TYPE_STRUCT);
1368 subfields
1369 = create_optional_field (subfields, field_tp, "block_sym",
1370 "SYMBOL_REF_HAS_BLOCK_INFO_P (&%0)");
1373 sname = xasprintf ("rtx_def_%s", rtx_name[i]);
1374 substruct = new_structure (sname, TYPE_STRUCT, &lexer_line, subfields,
1375 NULL, NULL);
1377 ftag = xstrdup (rtx_name[i]);
1378 for (nmindex = 0; nmindex < strlen (ftag); nmindex++)
1379 ftag[nmindex] = TOUPPER (ftag[nmindex]);
1380 flds = create_field (flds, substruct, "");
1381 flds->opt = create_string_option (nodot, "tag", ftag);
1383 return new_structure ("rtx_def_subunion", TYPE_UNION, &lexer_line, flds,
1384 nodot, NULL);
1387 /* Handle `special("tree_exp")'. This is a special case for
1388 field `operands' of struct tree_exp, which although it claims to contain
1389 pointers to trees, actually sometimes contains pointers to RTL too.
1390 Passed T, the old type of the field, and OPT its options. Returns
1391 a new type for the field. */
1393 static type_p
1394 adjust_field_tree_exp (type_p t, options_p opt ATTRIBUTE_UNUSED)
1396 pair_p flds;
1397 options_p nodot;
1399 if (t->kind != TYPE_ARRAY)
1401 error_at_line (&lexer_line,
1402 "special `tree_exp' must be applied to an array");
1403 return &string_type;
1406 nodot = create_string_option (NULL, "dot", "");
1408 flds = create_field (NULL, t, "");
1409 flds->opt = create_string_option (nodot, "length",
1410 "TREE_OPERAND_LENGTH ((tree) &%0)");
1411 flds->opt = create_string_option (flds->opt, "default", "");
1413 return new_structure ("tree_exp_subunion", TYPE_UNION, &lexer_line, flds,
1414 nodot, NULL);
1417 /* Perform any special processing on a type T, about to become the type
1418 of a field. Return the appropriate type for the field.
1419 At present:
1420 - Converts pointer-to-char, with no length parameter, to TYPE_STRING;
1421 - Similarly for arrays of pointer-to-char;
1422 - Converts structures for which a parameter is provided to
1423 TYPE_PARAM_STRUCT;
1424 - Handles "special" options.
1427 type_p
1428 adjust_field_type (type_p t, options_p opt)
1430 int length_p = 0;
1431 const int pointer_p = t->kind == TYPE_POINTER;
1433 for (; opt; opt = opt->next)
1434 if (strcmp (opt->name, "length") == 0)
1436 if (length_p)
1437 error_at_line (&lexer_line, "duplicate `%s' option", opt->name);
1438 if (t->u.p->kind == TYPE_SCALAR || t->u.p->kind == TYPE_STRING)
1440 error_at_line (&lexer_line,
1441 "option `%s' may not be applied to "
1442 "arrays of atomic types", opt->name);
1444 length_p = 1;
1446 else if (strcmp (opt->name, "special") == 0
1447 && opt->kind == OPTION_STRING)
1449 const char *special_name = opt->info.string;
1450 if (strcmp (special_name, "tree_exp") == 0)
1451 t = adjust_field_tree_exp (t, opt);
1452 else if (strcmp (special_name, "rtx_def") == 0)
1453 t = adjust_field_rtx_def (t, opt);
1454 else
1455 error_at_line (&lexer_line, "unknown special `%s'", special_name);
1458 if (!length_p
1459 && pointer_p && t->u.p->kind == TYPE_SCALAR && t->u.p->u.scalar_is_char)
1460 return &string_type;
1461 if (t->kind == TYPE_ARRAY && t->u.a.p->kind == TYPE_POINTER
1462 && t->u.a.p->u.p->kind == TYPE_SCALAR
1463 && t->u.a.p->u.p->u.scalar_is_char)
1464 return create_array (&string_type, t->u.a.len);
1466 return t;
1470 static void set_gc_used_type (type_p, enum gc_used_enum, bool = false);
1471 static void set_gc_used (pair_p);
1473 /* Handle OPT for set_gc_used_type. */
1475 static void
1476 process_gc_options (options_p opt, enum gc_used_enum level, int *maybe_undef,
1477 int *length, int *skip, int *callback, type_p *nested_ptr)
1479 options_p o;
1480 for (o = opt; o; o = o->next)
1481 if (strcmp (o->name, "ptr_alias") == 0 && level == GC_POINTED_TO
1482 && o->kind == OPTION_TYPE)
1483 set_gc_used_type (o->info.type,
1484 GC_POINTED_TO);
1485 else if (strcmp (o->name, "maybe_undef") == 0)
1486 *maybe_undef = 1;
1487 else if (strcmp (o->name, "length") == 0)
1488 *length = 1;
1489 else if (strcmp (o->name, "skip") == 0)
1490 *skip = 1;
1491 else if (strcmp (o->name, "callback") == 0)
1492 *callback = 1;
1493 else if (strcmp (o->name, "nested_ptr") == 0
1494 && o->kind == OPTION_NESTED)
1495 *nested_ptr = ((const struct nested_ptr_data *) o->info.nested)->type;
1499 /* Set the gc_used field of T to LEVEL, and handle the types it references.
1501 If ALLOWED_UNDEFINED_TYPES is true, types of kind TYPE_UNDEFINED
1502 are set to GC_UNUSED. Otherwise, an error is emitted for
1503 TYPE_UNDEFINED types. This is used to support user-defined
1504 template types with non-type arguments.
1506 For instance, when we parse a template type with enum arguments
1507 (e.g. MyType<AnotherType, EnumValue>), the parser created two
1508 artificial fields for 'MyType', one for 'AnotherType', the other
1509 one for 'EnumValue'.
1511 At the time that we parse this type we don't know that 'EnumValue'
1512 is really an enum value, so the parser creates a TYPE_UNDEFINED
1513 type for it. Since 'EnumValue' is never resolved to a known
1514 structure, it will stay with TYPE_UNDEFINED.
1516 Since 'MyType' is a TYPE_USER_STRUCT, we can simply ignore
1517 'EnumValue'. Generating marking code for it would cause
1518 compilation failures since the marking routines assumes that
1519 'EnumValue' is a type. */
1521 static void
1522 set_gc_used_type (type_p t, enum gc_used_enum level,
1523 bool allow_undefined_types)
1525 if (t->gc_used >= level)
1526 return;
1528 t->gc_used = level;
1530 switch (t->kind)
1532 case TYPE_STRUCT:
1533 case TYPE_UNION:
1534 case TYPE_USER_STRUCT:
1536 pair_p f;
1537 int dummy;
1538 type_p dummy2;
1539 bool allow_undefined_field_types = (t->kind == TYPE_USER_STRUCT);
1541 process_gc_options (t->u.s.opt, level, &dummy, &dummy, &dummy, &dummy,
1542 &dummy2);
1544 if (t->u.s.base_class)
1545 set_gc_used_type (t->u.s.base_class, level, allow_undefined_types);
1546 /* Anything pointing to a base class might actually be pointing
1547 to a subclass. */
1548 for (type_p subclass = t->u.s.first_subclass; subclass;
1549 subclass = subclass->u.s.next_sibling_class)
1550 set_gc_used_type (subclass, level, allow_undefined_types);
1552 FOR_ALL_INHERITED_FIELDS(t, f)
1554 int maybe_undef = 0;
1555 int length = 0;
1556 int skip = 0;
1557 int callback = 0;
1558 type_p nested_ptr = NULL;
1559 process_gc_options (f->opt, level, &maybe_undef, &length, &skip,
1560 &callback, &nested_ptr);
1562 if (nested_ptr && f->type->kind == TYPE_POINTER)
1563 set_gc_used_type (nested_ptr, GC_POINTED_TO);
1564 else if (length && f->type->kind == TYPE_POINTER)
1565 set_gc_used_type (f->type->u.p, GC_USED);
1566 else if (maybe_undef && f->type->kind == TYPE_POINTER)
1567 set_gc_used_type (f->type->u.p, GC_MAYBE_POINTED_TO);
1568 else if (skip)
1569 ; /* target type is not used through this field */
1570 else if (callback)
1571 f->type = &callback_type;
1572 else
1573 set_gc_used_type (f->type, GC_USED, allow_undefined_field_types);
1575 break;
1578 case TYPE_UNDEFINED:
1579 if (level > GC_UNUSED)
1581 if (!allow_undefined_types)
1582 error_at_line (&t->u.s.line, "undefined type `%s'", t->u.s.tag);
1583 t->gc_used = GC_UNUSED;
1585 break;
1587 case TYPE_POINTER:
1588 set_gc_used_type (t->u.p, GC_POINTED_TO);
1589 break;
1591 case TYPE_ARRAY:
1592 set_gc_used_type (t->u.a.p, GC_USED);
1593 break;
1595 case TYPE_LANG_STRUCT:
1596 for (t = t->u.s.lang_struct; t; t = t->next)
1597 set_gc_used_type (t, level);
1598 break;
1600 default:
1601 break;
1605 /* Set the gc_used fields of all the types pointed to by VARIABLES. */
1607 static void
1608 set_gc_used (pair_p variables)
1610 int nbvars = 0;
1611 pair_p p;
1612 for (p = variables; p; p = p->next)
1614 set_gc_used_type (p->type, GC_USED);
1615 nbvars++;
1617 if (verbosity_level >= 2)
1618 printf ("%s used %d GTY-ed variables\n", progname, nbvars);
1621 /* File mapping routines. For each input file, there is one output .c file
1622 (but some output files have many input files), and there is one .h file
1623 for the whole build. */
1625 /* Output file handling. */
1627 /* Create and return an outf_p for a new file for NAME, to be called
1628 ONAME. */
1630 static outf_p
1631 create_file (const char *name, const char *oname)
1633 static const char *const hdr[] = {
1634 " Copyright (C) 2004-2021 Free Software Foundation, Inc.\n",
1635 "\n",
1636 "This file is part of GCC.\n",
1637 "\n",
1638 "GCC is free software; you can redistribute it and/or modify it under\n",
1639 "the terms of the GNU General Public License as published by the Free\n",
1640 "Software Foundation; either version 3, or (at your option) any later\n",
1641 "version.\n",
1642 "\n",
1643 "GCC is distributed in the hope that it will be useful, but WITHOUT ANY\n",
1644 "WARRANTY; without even the implied warranty of MERCHANTABILITY or\n",
1645 "FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n",
1646 "for more details.\n",
1647 "\n",
1648 "You should have received a copy of the GNU General Public License\n",
1649 "along with GCC; see the file COPYING3. If not see\n",
1650 "<http://www.gnu.org/licenses/>. */\n",
1651 "\n",
1652 "/* This file is machine generated. Do not edit. */\n"
1654 outf_p f;
1655 size_t i;
1657 gcc_assert (name != NULL);
1658 gcc_assert (oname != NULL);
1659 f = XCNEW (struct outf);
1660 f->next = output_files;
1661 f->name = oname;
1662 output_files = f;
1664 oprintf (f, "/* Type information for %s.\n", name);
1665 for (i = 0; i < ARRAY_SIZE (hdr); i++)
1666 oprintf (f, "%s", hdr[i]);
1667 return f;
1670 /* Print, like fprintf, to O.
1671 N.B. You might think this could be implemented more efficiently
1672 with vsnprintf(). Unfortunately, there are C libraries that
1673 provide that function but without the C99 semantics for its return
1674 value, making it impossible to know how much space is required. */
1675 void
1676 oprintf (outf_p o, const char *format, ...)
1678 char *s;
1679 size_t slength;
1680 va_list ap;
1682 /* In plugin mode, the O could be a NULL pointer, so avoid crashing
1683 in that case. */
1684 if (!o)
1685 return;
1687 va_start (ap, format);
1688 slength = vasprintf (&s, format, ap);
1689 if (s == NULL || (int) slength < 0)
1690 fatal ("out of memory");
1691 va_end (ap);
1693 if (o->bufused + slength > o->buflength)
1695 size_t new_len = o->buflength;
1696 if (new_len == 0)
1697 new_len = 1024;
1700 new_len *= 2;
1702 while (o->bufused + slength >= new_len);
1703 o->buf = XRESIZEVEC (char, o->buf, new_len);
1704 o->buflength = new_len;
1706 memcpy (o->buf + o->bufused, s, slength);
1707 o->bufused += slength;
1708 free (s);
1711 /* Open the global header file and the language-specific header files. */
1713 static void
1714 open_base_files (void)
1716 size_t i;
1718 if (nb_plugin_files > 0 && plugin_files)
1719 return;
1721 header_file = create_file ("GCC", "gtype-desc.h");
1723 base_files = XNEWVEC (outf_p, num_lang_dirs);
1725 for (i = 0; i < num_lang_dirs; i++)
1726 base_files[i] = create_file (lang_dir_names[i],
1727 xasprintf ("gtype-%s.h", lang_dir_names[i]));
1729 /* gtype-desc.c is a little special, so we create it here. */
1731 /* The order of files here matters very much. */
1732 static const char *const ifiles[] = {
1733 "config.h", "system.h", "coretypes.h",
1734 "backend.h", "predict.h", "tree.h",
1735 "rtl.h", "gimple.h", "fold-const.h", "insn-codes.h", "splay-tree.h",
1736 "alias.h", "insn-config.h", "flags.h", "expmed.h", "dojump.h",
1737 "explow.h", "calls.h", "memmodel.h", "emit-rtl.h", "varasm.h",
1738 "stmt.h", "expr.h", "alloc-pool.h", "cselib.h", "insn-addr.h",
1739 "optabs.h", "libfuncs.h", "debug.h", "internal-fn.h", "gimple-fold.h",
1740 "value-range.h",
1741 "tree-eh.h", "gimple-iterator.h", "gimple-ssa.h", "tree-cfg.h",
1742 "tree-vrp.h", "tree-phinodes.h", "ssa-iterators.h", "stringpool.h",
1743 "tree-ssanames.h", "tree-ssa-loop.h", "tree-ssa-loop-ivopts.h",
1744 "tree-ssa-loop-manip.h", "tree-ssa-loop-niter.h", "tree-into-ssa.h",
1745 "tree-dfa.h", "tree-ssa.h", "reload.h", "cpplib.h", "tree-chrec.h",
1746 "except.h", "output.h", "cfgloop.h", "target.h", "lto-streamer.h",
1747 "target-globals.h", "ipa-ref.h", "cgraph.h", "symbol-summary.h",
1748 "ipa-prop.h", "ipa-fnsummary.h", "dwarf2out.h", "omp-general.h",
1749 "omp-offload.h", "ipa-modref-tree.h", "ipa-modref.h", "symtab-thunks.h",
1750 "symtab-clones.h", "diagnostic-spec.h", "ctfc.h",
1751 NULL
1753 const char *const *ifp;
1754 outf_p gtype_desc_c;
1756 gtype_desc_c = create_file ("GCC", "gtype-desc.c");
1757 for (ifp = ifiles; *ifp; ifp++)
1758 oprintf (gtype_desc_c, "#include \"%s\"\n", *ifp);
1759 for (int j = 0; j < (int) num_build_headers; j++)
1760 oprintf (gtype_desc_c, "#include \"%s\"\n", build_headers[j]);
1762 /* Make sure we handle "cfun" specially. */
1763 oprintf (gtype_desc_c, "\n/* See definition in function.h. */\n");
1764 oprintf (gtype_desc_c, "#undef cfun\n");
1766 oprintf (gtype_desc_c,
1767 "\n"
1768 "/* Types with a \"gcc::\" namespace have it stripped\n"
1769 " during gengtype parsing. Provide a \"using\" directive\n"
1770 " to ensure that the fully-qualified types are found. */\n"
1771 "using namespace gcc;\n");
1775 /* For INPF an input file, return the real basename of INPF, with all
1776 the directory components skipped. */
1778 static const char *
1779 get_file_realbasename (const input_file *inpf)
1781 return lbasename (get_input_file_name (inpf));
1784 /* For INPF a filename, return the relative path to INPF from
1785 $(srcdir) if the latter is a prefix in INPF, NULL otherwise. */
1787 const char *
1788 get_file_srcdir_relative_path (const input_file *inpf)
1790 const char *f = get_input_file_name (inpf);
1791 if (strlen (f) > srcdir_len
1792 && IS_DIR_SEPARATOR (f[srcdir_len])
1793 && strncmp (f, srcdir, srcdir_len) == 0)
1794 return f + srcdir_len + 1;
1795 else
1796 return NULL;
1799 /* For INPF an input_file, return the relative path to INPF from
1800 $(srcdir) if the latter is a prefix in INPF, or the real basename
1801 of INPF otherwise. */
1803 static const char *
1804 get_file_basename (const input_file *inpf)
1806 const char *srcdir_path = get_file_srcdir_relative_path (inpf);
1808 return (srcdir_path != NULL) ? srcdir_path : get_file_realbasename (inpf);
1811 /* For F a filename, return the lang_dir_names relative index of the language
1812 directory that is a prefix in F, if any, -1 otherwise. */
1814 static int
1815 get_prefix_langdir_index (const char *f)
1817 size_t f_len = strlen (f);
1818 size_t lang_index;
1820 for (lang_index = 0; lang_index < num_lang_dirs; lang_index++)
1822 const char *langdir = lang_dir_names[lang_index];
1823 size_t langdir_len = strlen (langdir);
1825 if (f_len > langdir_len
1826 && IS_DIR_SEPARATOR (f[langdir_len])
1827 && memcmp (f, langdir, langdir_len) == 0)
1828 return lang_index;
1831 return -1;
1834 /* For INPF an input file, return the name of language directory where
1835 F is located, if any, NULL otherwise. */
1837 static const char *
1838 get_file_langdir (const input_file *inpf)
1840 /* Get the relative path to INPF from $(srcdir) and find the
1841 language by comparing the prefix with language directory names.
1842 If INPF is not even srcdir relative, no point in looking
1843 further. */
1845 int lang_index;
1846 const char *srcdir_relative_path = get_file_srcdir_relative_path (inpf);
1847 const char *r;
1849 if (!srcdir_relative_path)
1850 return NULL;
1852 lang_index = get_prefix_langdir_index (srcdir_relative_path);
1853 if (lang_index < 0 && startswith (srcdir_relative_path, "c-family"))
1854 r = "c-family";
1855 else if (lang_index >= 0)
1856 r = lang_dir_names[lang_index];
1857 else
1858 r = NULL;
1860 return r;
1863 /* The gt- output file name for INPF. */
1865 static const char *
1866 get_file_gtfilename (const input_file *inpf)
1868 /* Cook up an initial version of the gt- file name from the file real
1869 basename and the language name, if any. */
1871 const char *basename = get_file_realbasename (inpf);
1872 const char *langdir = get_file_langdir (inpf);
1874 char *result =
1875 (langdir ? xasprintf ("gt-%s-%s", langdir, basename)
1876 : xasprintf ("gt-%s", basename));
1878 /* Then replace all non alphanumerics characters by '-' and change the
1879 extension to ".h". We expect the input filename extension was at least
1880 one character long. */
1882 char *s = result;
1884 for (; *s != '.'; s++)
1885 if (!ISALNUM (*s) && *s != '-')
1886 *s = '-';
1888 memcpy (s, ".h", sizeof (".h"));
1890 return result;
1893 /* Each input_file has its associated output file outf_p. The
1894 association is computed by the function
1895 get_output_file_with_visibility. The associated file is cached
1896 inside input_file in its inpoutf field, so is really computed only
1897 once. Associated output file paths (i.e. output_name-s) are
1898 computed by a rule based regexp machinery, using the files_rules
1899 array of struct file_rule_st. A for_name is also computed, giving
1900 the source file name for which the output_file is generated; it is
1901 often the last component of the input_file path. */
1905 Regexpr machinery to compute the output_name and for_name-s of each
1906 input_file. We have a sequence of file rules which gives the POSIX
1907 extended regular expression to match an input file path, and two
1908 transformed strings for the corresponding output_name and the
1909 corresponding for_name. The transformed string contain dollars: $0
1910 is replaced by the entire match, $1 is replaced by the substring
1911 matching the first parenthesis in the regexp, etc. And $$ is replaced
1912 by a single verbatim dollar. The rule order is important. The
1913 general case is last, and the particular cases should come before.
1914 An action routine can, when needed, update the out_name & for_name
1915 and/or return the appropriate output file. It is invoked only when a
1916 rule is triggered. When a rule is triggered, the output_name and
1917 for_name are computed using their transform string in while $$, $0,
1918 $1, ... are suitably replaced. If there is an action, it is called.
1919 In some few cases, the action can directly return the outf_p, but
1920 usually it just updates the output_name and for_name so should free
1921 them before replacing them. The get_output_file_with_visibility
1922 function creates an outf_p only once per each output_name, so it
1923 scans the output_files list for previously seen output file names.
1926 /* Signature of actions in file rules. */
1927 typedef outf_p (frul_actionrout_t) (input_file*, char**, char**);
1930 struct file_rule_st {
1931 const char* frul_srcexpr; /* Source string for regexp. */
1932 int frul_rflags; /* Flags passed to regcomp, usually
1933 * REG_EXTENDED. */
1934 regex_t* frul_re; /* Compiled regular expression
1935 obtained by regcomp. */
1936 const char* frul_tr_out; /* Transformation string for making
1937 * the output_name, with $1 ... $9 for
1938 * subpatterns and $0 for the whole
1939 * matched filename. */
1940 const char* frul_tr_for; /* Tranformation string for making the
1941 for_name. */
1942 frul_actionrout_t* frul_action; /* The action, if non null, is
1943 * called once the rule matches, on
1944 * the transformed out_name &
1945 * for_name. It could change them
1946 * and/or give the output file. */
1949 /* File rule action handling *.h files. */
1950 static outf_p header_dot_h_frul (input_file*, char**, char**);
1952 /* File rule action handling *.c files. */
1953 static outf_p source_dot_c_frul (input_file*, char**, char**);
1955 #define NULL_REGEX (regex_t*)0
1957 /* The prefix in our regexp-s matching the directory. */
1958 #define DIR_PREFIX_REGEX "^(([^/]*/)*)"
1960 #define NULL_FRULACT (frul_actionrout_t*)0
1962 /* The array of our rules governing file name generation. Rules order
1963 matters, so change with extreme care! */
1965 struct file_rule_st files_rules[] = {
1966 /* The general rule assumes that files in subdirectories belong to a
1967 particular front-end, and files not in subdirectories are shared.
1968 The following rules deal with exceptions - files that are in
1969 subdirectories and yet are shared, and files that are top-level,
1970 but are not shared. */
1972 /* the c-family/ source directory is special. */
1973 { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.c$",
1974 REG_EXTENDED, NULL_REGEX,
1975 "gt-c-family-$3.h", "c-family/$3.c", NULL_FRULACT},
1977 { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.h$",
1978 REG_EXTENDED, NULL_REGEX,
1979 "gt-c-family-$3.h", "c-family/$3.h", NULL_FRULACT},
1981 /* Both c-lang.h & c-tree.h gives gt-c-c-decl.h for c-decl.c ! */
1982 { DIR_PREFIX_REGEX "c/c-lang\\.h$",
1983 REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.c", NULL_FRULACT},
1985 { DIR_PREFIX_REGEX "c/c-tree\\.h$",
1986 REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.c", NULL_FRULACT},
1988 /* cp/cp-tree.h gives gt-cp-tree.h for cp/tree.c ! */
1989 { DIR_PREFIX_REGEX "cp/cp-tree\\.h$",
1990 REG_EXTENDED, NULL_REGEX,
1991 "gt-cp-tree.h", "cp/tree.c", NULL_FRULACT },
1993 /* cp/decl.h & cp/decl.c gives gt-cp-decl.h for cp/decl.c ! */
1994 { DIR_PREFIX_REGEX "cp/decl\\.[ch]$",
1995 REG_EXTENDED, NULL_REGEX,
1996 "gt-cp-decl.h", "cp/decl.c", NULL_FRULACT },
1998 /* cp/name-lookup.h gives gt-cp-name-lookup.h for cp/name-lookup.c ! */
1999 { DIR_PREFIX_REGEX "cp/name-lookup\\.h$",
2000 REG_EXTENDED, NULL_REGEX,
2001 "gt-cp-name-lookup.h", "cp/name-lookup.c", NULL_FRULACT },
2003 /* cp/parser.h gives gt-cp-parser.h for cp/parser.c ! */
2004 { DIR_PREFIX_REGEX "cp/parser\\.h$",
2005 REG_EXTENDED, NULL_REGEX,
2006 "gt-cp-parser.h", "cp/parser.c", NULL_FRULACT },
2008 /* objc/objc-act.h gives gt-objc-objc-act.h for objc/objc-act.c ! */
2009 { DIR_PREFIX_REGEX "objc/objc-act\\.h$",
2010 REG_EXTENDED, NULL_REGEX,
2011 "gt-objc-objc-act.h", "objc/objc-act.c", NULL_FRULACT },
2013 /* objc/objc-map.h gives gt-objc-objc-map.h for objc/objc-map.c ! */
2014 { DIR_PREFIX_REGEX "objc/objc-map\\.h$",
2015 REG_EXTENDED, NULL_REGEX,
2016 "gt-objc-objc-map.h", "objc/objc-map.c", NULL_FRULACT },
2018 /* General cases. For header *.h and source *.c or *.cc files, we
2019 * need special actions to handle the language. */
2021 /* Source *.c files are using get_file_gtfilename to compute their
2022 output_name and get_file_basename to compute their for_name
2023 through the source_dot_c_frul action. */
2024 { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.c$",
2025 REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.c", source_dot_c_frul},
2027 /* Source *.cc files are using get_file_gtfilename to compute their
2028 output_name and get_file_basename to compute their for_name
2029 through the source_dot_c_frul action. */
2030 { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.cc$",
2031 REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.cc", source_dot_c_frul},
2033 /* Common header files get "gtype-desc.c" as their output_name,
2034 * while language specific header files are handled specially. So
2035 * we need the header_dot_h_frul action. */
2036 { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.h$",
2037 REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.h", header_dot_h_frul},
2039 { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.in$",
2040 REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.in", NULL_FRULACT},
2042 /* Mandatory null last entry signaling end of rules. */
2043 {NULL, 0, NULL_REGEX, NULL, NULL, NULL_FRULACT}
2046 /* Special file rules action for handling *.h header files. It gives
2047 "gtype-desc.c" for common headers and corresponding output
2048 files for language-specific header files. */
2049 static outf_p
2050 header_dot_h_frul (input_file* inpf, char**poutname,
2051 char**pforname ATTRIBUTE_UNUSED)
2053 const char *basename = 0;
2054 int lang_index = 0;
2055 DBGPRINTF ("inpf %p inpname %s outname %s forname %s",
2056 (void*) inpf, get_input_file_name (inpf),
2057 *poutname, *pforname);
2058 basename = get_file_basename (inpf);
2059 lang_index = get_prefix_langdir_index (basename);
2060 DBGPRINTF ("basename %s lang_index %d", basename, lang_index);
2062 if (lang_index >= 0)
2064 /* The header is language specific. Given output_name &
2065 for_name remains unchanged. The base_files array gives the
2066 outf_p. */
2067 DBGPRINTF ("header_dot_h found language specific @ %p '%s'",
2068 (void*) base_files[lang_index],
2069 (base_files[lang_index])->name);
2070 return base_files[lang_index];
2072 else
2074 /* The header is common to all front-end languages. So
2075 output_name is "gtype-desc.c" file. The calling function
2076 get_output_file_with_visibility will find its outf_p. */
2077 free (*poutname);
2078 *poutname = xstrdup ("gtype-desc.c");
2079 DBGPRINTF ("special 'gtype-desc.c' for inpname %s",
2080 get_input_file_name (inpf));
2081 return NULL;
2086 /* Special file rules action for handling *.c source files using
2087 * get_file_gtfilename to compute their output_name and
2088 * get_file_basename to compute their for_name. The output_name is
2089 * gt-<LANG>-<BASE>.h for language specific source files, and
2090 * gt-<BASE>.h for common source files. */
2091 static outf_p
2092 source_dot_c_frul (input_file* inpf, char**poutname, char**pforname)
2094 char *newbasename = CONST_CAST (char*, get_file_basename (inpf));
2095 char *newoutname = CONST_CAST (char*, get_file_gtfilename (inpf));
2096 DBGPRINTF ("inpf %p inpname %s original outname %s forname %s",
2097 (void*) inpf, get_input_file_name (inpf),
2098 *poutname, *pforname);
2099 DBGPRINTF ("newoutname %s", newoutname);
2100 DBGPRINTF ("newbasename %s", newbasename);
2101 free (*poutname);
2102 free (*pforname);
2103 *poutname = newoutname;
2104 *pforname = newbasename;
2105 return NULL;
2108 /* Utility function for get_output_file_with_visibility which returns
2109 * a malloc-ed substituted string using TRS on matching of the FILNAM
2110 * file name, using the PMATCH array. */
2111 static char*
2112 matching_file_name_substitute (const char *filnam, regmatch_t pmatch[10],
2113 const char *trs)
2115 struct obstack str_obstack;
2116 char *str = NULL;
2117 char *rawstr = NULL;
2118 const char *pt = NULL;
2119 DBGPRINTF ("filnam %s", filnam);
2120 obstack_init (&str_obstack);
2121 for (pt = trs; *pt; pt++) {
2122 char c = *pt;
2123 if (c == '$')
2125 if (pt[1] == '$')
2127 /* A double dollar $$ is substituted by a single verbatim
2128 dollar, but who really uses dollar signs in file
2129 paths? */
2130 obstack_1grow (&str_obstack, '$');
2132 else if (ISDIGIT (pt[1]))
2134 /* Handle $0 $1 ... $9 by appropriate substitution. */
2135 int dolnum = pt[1] - '0';
2136 int so = pmatch[dolnum].rm_so;
2137 int eo = pmatch[dolnum].rm_eo;
2138 DBGPRINTF ("so=%d eo=%d dolnum=%d", so, eo, dolnum);
2139 if (so>=0 && eo>=so)
2140 obstack_grow (&str_obstack, filnam + so, eo - so);
2142 else
2144 /* This can happen only when files_rules is buggy! */
2145 gcc_unreachable ();
2147 /* Always skip the character after the dollar. */
2148 pt++;
2150 else
2151 obstack_1grow (&str_obstack, c);
2153 obstack_1grow (&str_obstack, '\0');
2154 rawstr = XOBFINISH (&str_obstack, char *);
2155 str = xstrdup (rawstr);
2156 obstack_free (&str_obstack, NULL);
2157 DBGPRINTF ("matched replacement %s", str);
2158 rawstr = NULL;
2159 return str;
2163 /* An output file, suitable for definitions, that can see declarations
2164 made in INPF and is linked into every language that uses INPF.
2165 Since the result is cached inside INPF, that argument cannot be
2166 declared constant, but is "almost" constant. */
2168 outf_p
2169 get_output_file_with_visibility (input_file *inpf)
2171 outf_p r;
2172 char *for_name = NULL;
2173 char *output_name = NULL;
2174 const char* inpfname;
2176 /* This can happen when we need a file with visibility on a
2177 structure that we've never seen. We have to just hope that it's
2178 globally visible. */
2179 if (inpf == NULL)
2180 inpf = system_h_file;
2182 /* The result is cached in INPF, so return it if already known. */
2183 if (inpf->inpoutf)
2184 return inpf->inpoutf;
2186 /* In plugin mode, return NULL unless the input_file is one of the
2187 plugin_files. */
2188 if (plugin_files)
2190 size_t i;
2191 for (i = 0; i < nb_plugin_files; i++)
2192 if (inpf == plugin_files[i])
2194 inpf->inpoutf = plugin_output;
2195 return plugin_output;
2198 return NULL;
2201 inpfname = get_input_file_name (inpf);
2203 /* Try each rule in sequence in files_rules until one is triggered. */
2205 int rulix = 0;
2206 DBGPRINTF ("passing input file @ %p named %s through the files_rules",
2207 (void*) inpf, inpfname);
2209 for (; files_rules[rulix].frul_srcexpr != NULL; rulix++)
2211 DBGPRINTF ("rulix#%d srcexpr %s",
2212 rulix, files_rules[rulix].frul_srcexpr);
2214 if (!files_rules[rulix].frul_re)
2216 /* Compile the regexpr lazily. */
2217 int err = 0;
2218 files_rules[rulix].frul_re = XCNEW (regex_t);
2219 err = regcomp (files_rules[rulix].frul_re,
2220 files_rules[rulix].frul_srcexpr,
2221 files_rules[rulix].frul_rflags);
2222 if (err)
2224 /* The regular expression compilation fails only when
2225 file_rules is buggy. */
2226 gcc_unreachable ();
2230 output_name = NULL;
2231 for_name = NULL;
2233 /* Match the regexpr and trigger the rule if matched. */
2235 /* We have exactly ten pmatch-s, one for each $0, $1, $2,
2236 $3, ... $9. */
2237 regmatch_t pmatch[10];
2238 memset (pmatch, 0, sizeof (pmatch));
2239 if (!regexec (files_rules[rulix].frul_re,
2240 inpfname, 10, pmatch, 0))
2242 DBGPRINTF ("input @ %p filename %s matched rulix#%d pattern %s",
2243 (void*) inpf, inpfname, rulix,
2244 files_rules[rulix].frul_srcexpr);
2245 for_name =
2246 matching_file_name_substitute (inpfname, pmatch,
2247 files_rules[rulix].frul_tr_for);
2248 DBGPRINTF ("for_name %s", for_name);
2249 output_name =
2250 matching_file_name_substitute (inpfname, pmatch,
2251 files_rules[rulix].frul_tr_out);
2252 DBGPRINTF ("output_name %s", output_name);
2253 if (files_rules[rulix].frul_action)
2255 /* Invoke our action routine. */
2256 outf_p of = NULL;
2257 DBGPRINTF ("before action rulix#%d output_name %s for_name %s",
2258 rulix, output_name, for_name);
2259 of =
2260 (files_rules[rulix].frul_action) (inpf,
2261 &output_name, &for_name);
2262 DBGPRINTF ("after action rulix#%d of=%p output_name %s for_name %s",
2263 rulix, (void*)of, output_name, for_name);
2264 /* If the action routine returned something, give it back
2265 immediately and cache it in inpf. */
2266 if (of)
2268 inpf->inpoutf = of;
2269 return of;
2272 /* The rule matched, and had no action, or that action did
2273 not return any output file but could have changed the
2274 output_name or for_name. We break out of the loop on the
2275 files_rules. */
2276 break;
2278 else
2280 /* The regexpr did not match. */
2281 DBGPRINTF ("rulix#%d did not match %s pattern %s",
2282 rulix, inpfname, files_rules[rulix].frul_srcexpr);
2283 continue;
2288 if (!output_name || !for_name)
2290 /* This should not be possible, and could only happen if the
2291 files_rules is incomplete or buggy. */
2292 fatal ("failed to compute output name for %s", inpfname);
2295 /* Look through to see if we've ever seen this output filename
2296 before. If found, cache the result in inpf. */
2297 for (r = output_files; r; r = r->next)
2298 if (filename_cmp (r->name, output_name) == 0)
2300 inpf->inpoutf = r;
2301 DBGPRINTF ("found r @ %p for output_name %s for_name %s", (void*)r,
2302 output_name, for_name);
2303 return r;
2306 /* If not found, create it, and cache it in inpf. */
2307 r = create_file (for_name, output_name);
2309 gcc_assert (r && r->name);
2310 DBGPRINTF ("created r @ %p for output_name %s for_name %s", (void*) r,
2311 output_name, for_name);
2312 inpf->inpoutf = r;
2313 return r;
2318 /* The name of an output file, suitable for definitions, that can see
2319 declarations made in INPF and is linked into every language that
2320 uses INPF. */
2322 const char *
2323 get_output_file_name (input_file* inpf)
2325 outf_p o = get_output_file_with_visibility (inpf);
2326 if (o)
2327 return o->name;
2328 return NULL;
2331 /* Check if existing file is equal to the in memory buffer. */
2333 static bool
2334 is_file_equal (outf_p of)
2336 FILE *newfile = fopen (of->name, "r");
2337 size_t i;
2338 bool equal;
2339 if (newfile == NULL)
2340 return false;
2342 equal = true;
2343 for (i = 0; i < of->bufused; i++)
2345 int ch;
2346 ch = fgetc (newfile);
2347 if (ch == EOF || ch != (unsigned char) of->buf[i])
2349 equal = false;
2350 break;
2353 if (equal && EOF != fgetc (newfile))
2354 equal = false;
2355 fclose (newfile);
2356 return equal;
2359 /* Copy the output to its final destination,
2360 but don't unnecessarily change modification times. */
2362 static void
2363 close_output_files (void)
2365 int nbwrittenfiles = 0;
2366 outf_p of;
2368 for (of = output_files; of; of = of->next)
2370 if (!is_file_equal (of))
2372 FILE *newfile = NULL;
2373 char *backupname = NULL;
2374 /* Back up the old version of the output file gt-FOO.c as
2375 BACKUPDIR/gt-FOO.c~ if we have a backup directory. */
2376 if (backup_dir)
2378 backupname = concat (backup_dir, "/",
2379 lbasename (of->name), "~", NULL);
2380 if (!access (of->name, F_OK) && rename (of->name, backupname))
2381 fatal ("failed to back up %s as %s: %s",
2382 of->name, backupname, xstrerror (errno));
2385 newfile = fopen (of->name, "w");
2386 if (newfile == NULL)
2387 fatal ("opening output file %s: %s", of->name, xstrerror (errno));
2388 if (fwrite (of->buf, 1, of->bufused, newfile) != of->bufused)
2389 fatal ("writing output file %s: %s", of->name, xstrerror (errno));
2390 if (fclose (newfile) != 0)
2391 fatal ("closing output file %s: %s", of->name, xstrerror (errno));
2392 nbwrittenfiles++;
2393 if (verbosity_level >= 2 && backupname)
2394 printf ("%s wrote #%-3d %s backed-up in %s\n",
2395 progname, nbwrittenfiles, of->name, backupname);
2396 else if (verbosity_level >= 1)
2397 printf ("%s write #%-3d %s\n", progname, nbwrittenfiles, of->name);
2398 free (backupname);
2400 else
2402 /* output file remains unchanged. */
2403 if (verbosity_level >= 2)
2404 printf ("%s keep %s\n", progname, of->name);
2406 free (of->buf);
2407 of->buf = NULL;
2408 of->bufused = of->buflength = 0;
2410 if (verbosity_level >= 1)
2411 printf ("%s wrote %d files.\n", progname, nbwrittenfiles);
2414 struct flist
2416 struct flist *next;
2417 int started_p;
2418 const input_file* file;
2419 outf_p f;
2422 struct walk_type_data;
2424 /* For scalars and strings, given the item in 'val'.
2425 For structures, given a pointer to the item in 'val'.
2426 For misc. pointers, given the item in 'val'.
2428 typedef void (*process_field_fn) (type_p f, const struct walk_type_data * p);
2429 typedef void (*func_name_fn) (type_p s, const struct walk_type_data * p);
2431 /* Parameters for write_types. */
2433 struct write_types_data
2435 const char *prefix;
2436 const char *param_prefix;
2437 const char *subfield_marker_routine;
2438 const char *marker_routine;
2439 const char *reorder_note_routine;
2440 const char *comment;
2441 enum write_types_kinds kind;
2444 static void output_escaped_param (struct walk_type_data *d,
2445 const char *, const char *);
2446 static void output_mangled_typename (outf_p, const_type_p);
2447 static void walk_type (type_p t, struct walk_type_data *d);
2448 static void write_func_for_structure (type_p orig_s, type_p s,
2449 const struct write_types_data *wtd);
2450 static void write_types_process_field
2451 (type_p f, const struct walk_type_data *d);
2452 static void write_types (outf_p output_header,
2453 type_p structures,
2454 const struct write_types_data *wtd);
2455 static void write_types_local_process_field
2456 (type_p f, const struct walk_type_data *d);
2457 static void write_local_func_for_structure (const_type_p orig_s, type_p s);
2458 static void write_local (outf_p output_header,
2459 type_p structures);
2460 static int contains_scalar_p (type_p t);
2461 static void put_mangled_filename (outf_p, const input_file *);
2462 static void finish_root_table (struct flist *flp, const char *pfx,
2463 const char *lastname,
2464 const char *tname, const char *name);
2465 static void write_root (outf_p, pair_p, type_p, const char *, int,
2466 struct fileloc *, bool);
2467 static void write_array (outf_p f, pair_p v,
2468 const struct write_types_data *wtd);
2469 static void write_roots (pair_p, bool);
2471 /* Parameters for walk_type. */
2473 struct walk_type_data
2475 process_field_fn process_field;
2476 const void *cookie;
2477 outf_p of;
2478 options_p opt;
2479 const char *val;
2480 const char *prev_val[4];
2481 int indent;
2482 int counter;
2483 const struct fileloc *line;
2484 lang_bitmap bitmap;
2485 int used_length;
2486 type_p orig_s;
2487 const char *reorder_fn;
2488 bool needs_cast_p;
2489 bool fn_wants_lvalue;
2490 bool in_record_p;
2491 int loopcounter;
2492 bool in_ptr_field;
2493 bool have_this_obj;
2494 bool in_nested_ptr;
2498 /* Given a string TYPE_NAME, representing a C++ typename, return a valid
2499 pre-processor identifier to use in a #define directive. This replaces
2500 special characters used in C++ identifiers like '>', '<' and ':' with
2501 '_'.
2503 If no C++ special characters are found in TYPE_NAME, return
2504 TYPE_NAME. Otherwise, return a copy of TYPE_NAME with the special
2505 characters replaced with '_'. In this case, the caller is
2506 responsible for freeing the allocated string. */
2508 static const char *
2509 filter_type_name (const char *type_name)
2511 if (strchr (type_name, '<') || strchr (type_name, ':'))
2513 size_t i;
2514 char *s = xstrdup (type_name);
2515 for (i = 0; i < strlen (s); i++)
2516 if (s[i] == '<' || s[i] == '>' || s[i] == ':' || s[i] == ','
2517 || s[i] == '*')
2518 s[i] = '_';
2519 return s;
2521 else
2522 return type_name;
2526 /* Print a mangled name representing T to OF. */
2528 static void
2529 output_mangled_typename (outf_p of, const_type_p t)
2531 if (t == NULL)
2532 oprintf (of, "Z");
2533 else
2534 switch (t->kind)
2536 case TYPE_NONE:
2537 case TYPE_UNDEFINED:
2538 case TYPE_CALLBACK:
2539 gcc_unreachable ();
2540 break;
2541 case TYPE_POINTER:
2542 oprintf (of, "P");
2543 output_mangled_typename (of, t->u.p);
2544 break;
2545 case TYPE_SCALAR:
2546 oprintf (of, "I");
2547 break;
2548 case TYPE_STRING:
2549 oprintf (of, "S");
2550 break;
2551 case TYPE_STRUCT:
2552 case TYPE_UNION:
2553 case TYPE_LANG_STRUCT:
2554 case TYPE_USER_STRUCT:
2556 /* For references to classes within an inheritance hierarchy,
2557 only ever reference the ultimate base class, since only
2558 it will have gt_ functions. */
2559 t = get_ultimate_base_class (t);
2560 const char *id_for_tag = filter_type_name (t->u.s.tag);
2561 oprintf (of, "%lu%s", (unsigned long) strlen (id_for_tag),
2562 id_for_tag);
2563 if (id_for_tag != t->u.s.tag)
2564 free (CONST_CAST (char *, id_for_tag));
2566 break;
2567 case TYPE_ARRAY:
2568 gcc_unreachable ();
2572 /* Print PARAM to D->OF processing escapes. D->VAL references the
2573 current object, D->PREV_VAL the object containing the current
2574 object, ONAME is the name of the option and D->LINE is used to
2575 print error messages. */
2577 static void
2578 output_escaped_param (struct walk_type_data *d, const char *param,
2579 const char *oname)
2581 const char *p;
2583 for (p = param; *p; p++)
2584 if (*p != '%')
2585 oprintf (d->of, "%c", *p);
2586 else
2587 switch (*++p)
2589 case 'h':
2590 oprintf (d->of, "(%s)", d->prev_val[2]);
2591 break;
2592 case '0':
2593 oprintf (d->of, "(%s)", d->prev_val[0]);
2594 break;
2595 case '1':
2596 oprintf (d->of, "(%s)", d->prev_val[1]);
2597 break;
2598 case 'a':
2600 const char *pp = d->val + strlen (d->val);
2601 while (pp[-1] == ']')
2602 while (*pp != '[')
2603 pp--;
2604 oprintf (d->of, "%s", pp);
2606 break;
2607 default:
2608 error_at_line (d->line, "`%s' option contains bad escape %c%c",
2609 oname, '%', *p);
2613 const char *
2614 get_string_option (options_p opt, const char *key)
2616 for (; opt; opt = opt->next)
2617 if (strcmp (opt->name, key) == 0)
2618 return opt->info.string;
2619 return NULL;
2622 /* Machinery for avoiding duplicate tags within switch statements. */
2623 struct seen_tag
2625 const char *tag;
2626 struct seen_tag *next;
2630 already_seen_tag (struct seen_tag *seen_tags, const char *tag)
2632 /* Linear search, so O(n^2), but n is currently small. */
2633 while (seen_tags)
2635 if (!strcmp (seen_tags->tag, tag))
2636 return 1;
2637 seen_tags = seen_tags->next;
2639 /* Not yet seen this tag. */
2640 return 0;
2643 void
2644 mark_tag_as_seen (struct seen_tag **seen_tags, const char *tag)
2646 /* Add to front of linked list. */
2647 struct seen_tag *new_node = XCNEW (struct seen_tag);
2648 new_node->tag = tag;
2649 new_node->next = *seen_tags;
2650 *seen_tags = new_node;
2653 static void
2654 walk_subclasses (type_p base, struct walk_type_data *d,
2655 struct seen_tag **seen_tags)
2657 for (type_p sub = base->u.s.first_subclass; sub != NULL;
2658 sub = sub->u.s.next_sibling_class)
2660 const char *type_tag = get_string_option (sub->u.s.opt, "tag");
2661 if (type_tag && !already_seen_tag (*seen_tags, type_tag))
2663 mark_tag_as_seen (seen_tags, type_tag);
2664 oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
2665 d->indent += 2;
2666 oprintf (d->of, "%*s{\n", d->indent, "");
2667 d->indent += 2;
2668 oprintf (d->of, "%*s%s *sub = static_cast <%s *> (x);\n",
2669 d->indent, "", sub->u.s.tag, sub->u.s.tag);
2670 const char *old_val = d->val;
2671 d->val = "(*sub)";
2672 walk_type (sub, d);
2673 d->val = old_val;
2674 d->indent -= 2;
2675 oprintf (d->of, "%*s}\n", d->indent, "");
2676 oprintf (d->of, "%*sbreak;\n", d->indent, "");
2677 d->indent -= 2;
2679 walk_subclasses (sub, d, seen_tags);
2683 /* Call D->PROCESS_FIELD for every field (or subfield) of D->VAL,
2684 which is of type T. Write code to D->OF to constrain execution (at
2685 the point that D->PROCESS_FIELD is called) to the appropriate
2686 cases. Call D->PROCESS_FIELD on subobjects before calling it on
2687 pointers to those objects. D->PREV_VAL lists the objects
2688 containing the current object, D->OPT is a list of options to
2689 apply, D->INDENT is the current indentation level, D->LINE is used
2690 to print error messages, D->BITMAP indicates which languages to
2691 print the structure for. */
2693 static void
2694 walk_type (type_p t, struct walk_type_data *d)
2696 const char *length = NULL;
2697 const char *desc = NULL;
2698 const char *type_tag = NULL;
2699 int maybe_undef_p = 0;
2700 int atomic_p = 0;
2701 options_p oo;
2702 const struct nested_ptr_data *nested_ptr_d = NULL;
2704 d->needs_cast_p = false;
2705 for (oo = d->opt; oo; oo = oo->next)
2706 if (strcmp (oo->name, "length") == 0 && oo->kind == OPTION_STRING)
2707 length = oo->info.string;
2708 else if (strcmp (oo->name, "maybe_undef") == 0)
2709 maybe_undef_p = 1;
2710 else if (strcmp (oo->name, "desc") == 0 && oo->kind == OPTION_STRING)
2711 desc = oo->info.string;
2712 else if (strcmp (oo->name, "nested_ptr") == 0
2713 && oo->kind == OPTION_NESTED)
2714 nested_ptr_d = (const struct nested_ptr_data *) oo->info.nested;
2715 else if (strcmp (oo->name, "dot") == 0)
2717 else if (strcmp (oo->name, "tag") == 0)
2718 type_tag = oo->info.string;
2719 else if (strcmp (oo->name, "special") == 0)
2721 else if (strcmp (oo->name, "skip") == 0)
2723 else if (strcmp (oo->name, "atomic") == 0)
2724 atomic_p = 1;
2725 else if (strcmp (oo->name, "default") == 0)
2727 else if (strcmp (oo->name, "chain_next") == 0)
2729 else if (strcmp (oo->name, "chain_prev") == 0)
2731 else if (strcmp (oo->name, "chain_circular") == 0)
2733 else if (strcmp (oo->name, "reorder") == 0)
2735 else if (strcmp (oo->name, "variable_size") == 0)
2737 else if (strcmp (oo->name, "for_user") == 0)
2739 else if (strcmp (oo->name, "callback") == 0)
2741 else
2742 error_at_line (d->line, "unknown option `%s'\n", oo->name);
2744 if (d->used_length)
2745 length = NULL;
2747 if (maybe_undef_p
2748 && (t->kind != TYPE_POINTER || !union_or_struct_p (t->u.p)))
2750 error_at_line (d->line,
2751 "field `%s' has invalid option `maybe_undef_p'\n",
2752 d->val);
2753 return;
2756 if (atomic_p && (t->kind != TYPE_POINTER) && (t->kind != TYPE_STRING))
2758 error_at_line (d->line, "field `%s' has invalid option `atomic'\n", d->val);
2759 return;
2762 switch (t->kind)
2764 case TYPE_SCALAR:
2765 case TYPE_STRING:
2766 case TYPE_CALLBACK:
2767 d->process_field (t, d);
2768 break;
2770 case TYPE_POINTER:
2772 d->in_ptr_field = true;
2773 if (maybe_undef_p && t->u.p->u.s.line.file == NULL)
2775 oprintf (d->of, "%*sgcc_assert (!%s);\n", d->indent, "", d->val);
2776 break;
2779 /* If a pointer type is marked as "atomic", we process the
2780 field itself, but we don't walk the data that they point to.
2782 There are two main cases where we walk types: to mark
2783 pointers that are reachable, and to relocate pointers when
2784 writing a PCH file. In both cases, an atomic pointer is
2785 itself marked or relocated, but the memory that it points
2786 to is left untouched. In the case of PCH, that memory will
2787 be read/written unchanged to the PCH file. */
2788 if (atomic_p)
2790 oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
2791 d->indent += 2;
2792 d->process_field (t, d);
2793 d->indent -= 2;
2794 oprintf (d->of, "%*s}\n", d->indent, "");
2795 break;
2798 if (!length)
2800 if (!union_or_struct_p (t->u.p))
2802 error_at_line (d->line,
2803 "field `%s' is pointer to unimplemented type",
2804 d->val);
2805 break;
2808 if (nested_ptr_d)
2810 const char *oldprevval2 = d->prev_val[2];
2811 bool old_in_nested_ptr = d->in_nested_ptr;
2813 if (!union_or_struct_p (nested_ptr_d->type))
2815 error_at_line (d->line,
2816 "field `%s' has invalid "
2817 "option `nested_ptr'\n", d->val);
2818 return;
2821 d->prev_val[2] = d->val;
2822 d->in_nested_ptr = true;
2823 oprintf (d->of, "%*s{\n", d->indent, "");
2824 d->indent += 2;
2825 d->val = xasprintf ("x%d", d->counter++);
2826 oprintf (d->of, "%*s%s %s * %s%s =\n", d->indent, "",
2827 (nested_ptr_d->type->kind == TYPE_UNION
2828 ? "union" : "struct"),
2829 nested_ptr_d->type->u.s.tag,
2830 d->fn_wants_lvalue ? "" : "const ", d->val);
2831 oprintf (d->of, "%*s", d->indent + 2, "");
2832 output_escaped_param (d, nested_ptr_d->convert_from,
2833 "nested_ptr");
2834 oprintf (d->of, ";\n");
2836 d->process_field (nested_ptr_d->type, d);
2838 if (d->fn_wants_lvalue)
2840 oprintf (d->of, "%*s%s = ", d->indent, "",
2841 d->prev_val[2]);
2842 d->prev_val[2] = d->val;
2843 output_escaped_param (d, nested_ptr_d->convert_to,
2844 "nested_ptr");
2845 oprintf (d->of, ";\n");
2848 d->indent -= 2;
2849 oprintf (d->of, "%*s}\n", d->indent, "");
2850 d->val = d->prev_val[2];
2851 d->prev_val[2] = oldprevval2;
2852 d->in_nested_ptr = old_in_nested_ptr;
2854 else
2855 d->process_field (t->u.p, d);
2857 else
2859 int loopcounter = d->loopcounter;
2860 const char *oldval = d->val;
2861 const char *oldprevval3 = d->prev_val[3];
2862 char *newval;
2864 oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
2865 d->indent += 2;
2866 oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2867 oprintf (d->of, "%*sfor (i%d = 0; i%d != (size_t)(", d->indent,
2868 "", loopcounter, loopcounter);
2869 if (!d->in_record_p)
2870 output_escaped_param (d, length, "length");
2871 else
2872 oprintf (d->of, "l%d", loopcounter);
2873 if (d->have_this_obj)
2874 /* Try to unswitch loops (see PR53880). */
2875 oprintf (d->of, ") && ((void *)%s == this_obj", oldval);
2876 oprintf (d->of, "); i%d++) {\n", loopcounter);
2877 d->indent += 2;
2878 d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2879 d->used_length = 1;
2880 d->prev_val[3] = oldval;
2881 walk_type (t->u.p, d);
2882 free (newval);
2883 d->val = oldval;
2884 d->prev_val[3] = oldprevval3;
2885 d->used_length = 0;
2886 d->indent -= 2;
2887 oprintf (d->of, "%*s}\n", d->indent, "");
2888 d->process_field (t, d);
2889 d->indent -= 2;
2890 oprintf (d->of, "%*s}\n", d->indent, "");
2892 d->in_ptr_field = false;
2894 break;
2896 case TYPE_ARRAY:
2898 int loopcounter;
2899 const char *oldval = d->val;
2900 char *newval;
2902 /* If it's an array of scalars, we optimize by not generating
2903 any code. */
2904 if (t->u.a.p->kind == TYPE_SCALAR)
2905 break;
2907 if (length)
2908 loopcounter = d->loopcounter;
2909 else
2910 loopcounter = d->counter++;
2912 /* When walking an array, compute the length and store it in a
2913 local variable before walking the array elements, instead of
2914 recomputing the length expression each time through the loop.
2915 This is necessary to handle tcc_vl_exp objects like CALL_EXPR,
2916 where the length is stored in the first array element,
2917 because otherwise that operand can get overwritten on the
2918 first iteration. */
2919 oprintf (d->of, "%*s{\n", d->indent, "");
2920 d->indent += 2;
2921 oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2922 if (!d->in_record_p || !length)
2924 oprintf (d->of, "%*ssize_t l%d = (size_t)(",
2925 d->indent, "", loopcounter);
2926 if (length)
2927 output_escaped_param (d, length, "length");
2928 else
2929 oprintf (d->of, "%s", t->u.a.len);
2930 oprintf (d->of, ");\n");
2933 oprintf (d->of, "%*sfor (i%d = 0; i%d != l%d; i%d++) {\n",
2934 d->indent, "",
2935 loopcounter, loopcounter, loopcounter, loopcounter);
2936 d->indent += 2;
2937 d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2938 d->used_length = 1;
2939 walk_type (t->u.a.p, d);
2940 free (newval);
2941 d->used_length = 0;
2942 d->val = oldval;
2943 d->indent -= 2;
2944 oprintf (d->of, "%*s}\n", d->indent, "");
2945 d->indent -= 2;
2946 oprintf (d->of, "%*s}\n", d->indent, "");
2948 break;
2950 case TYPE_STRUCT:
2951 case TYPE_UNION:
2953 pair_p f;
2954 const char *oldval = d->val;
2955 const char *oldprevval1 = d->prev_val[1];
2956 const char *oldprevval2 = d->prev_val[2];
2957 const int union_p = t->kind == TYPE_UNION;
2958 int seen_default_p = 0;
2959 options_p o;
2960 int lengths_seen = 0;
2961 int endcounter;
2962 bool any_length_seen = false;
2964 if (!t->u.s.line.file)
2965 error_at_line (d->line, "incomplete structure `%s'", t->u.s.tag);
2967 if ((d->bitmap & t->u.s.bitmap) != d->bitmap)
2969 error_at_line (d->line,
2970 "structure `%s' defined for mismatching languages",
2971 t->u.s.tag);
2972 error_at_line (&t->u.s.line, "one structure defined here");
2975 /* Some things may also be defined in the structure's options. */
2976 for (o = t->u.s.opt; o; o = o->next)
2977 if (!desc && strcmp (o->name, "desc") == 0
2978 && o->kind == OPTION_STRING)
2979 desc = o->info.string;
2981 d->prev_val[2] = oldval;
2982 d->prev_val[1] = oldprevval2;
2983 if (union_p)
2985 if (desc == NULL)
2987 error_at_line (d->line,
2988 "missing `desc' option for union `%s'",
2989 t->u.s.tag);
2990 desc = "1";
2992 oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
2993 output_escaped_param (d, desc, "desc");
2994 oprintf (d->of, "))\n");
2995 d->indent += 2;
2996 oprintf (d->of, "%*s{\n", d->indent, "");
2998 else if (desc)
3000 /* We have a "desc" option on a struct, signifying the
3001 base class within a GC-managed inheritance hierarchy.
3002 The current code specialcases the base class, then walks
3003 into subclasses, recursing into this routine to handle them.
3004 This organization requires the base class to have a case in
3005 the switch statement, and hence a tag value is mandatory
3006 for the base class. This restriction could be removed, but
3007 it would require some restructing of this code. */
3008 if (!type_tag)
3010 error_at_line (d->line,
3011 "missing `tag' option for type `%s'",
3012 t->u.s.tag);
3014 oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
3015 output_escaped_param (d, desc, "desc");
3016 oprintf (d->of, "))\n");
3017 d->indent += 2;
3018 oprintf (d->of, "%*s{\n", d->indent, "");
3019 oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
3020 d->indent += 2;
3023 FOR_ALL_INHERITED_FIELDS (t, f)
3025 options_p oo;
3026 int skip_p = 0;
3027 const char *fieldlength = NULL;
3029 d->reorder_fn = NULL;
3030 for (oo = f->opt; oo; oo = oo->next)
3031 if (strcmp (oo->name, "skip") == 0)
3032 skip_p = 1;
3033 else if (strcmp (oo->name, "length") == 0
3034 && oo->kind == OPTION_STRING)
3035 fieldlength = oo->info.string;
3037 if (skip_p)
3038 continue;
3039 if (fieldlength)
3041 lengths_seen++;
3042 d->counter++;
3043 if (!union_p)
3045 if (!any_length_seen)
3047 oprintf (d->of, "%*s{\n", d->indent, "");
3048 d->indent += 2;
3050 any_length_seen = true;
3052 oprintf (d->of, "%*ssize_t l%d = (size_t)(",
3053 d->indent, "", d->counter - 1);
3054 output_escaped_param (d, fieldlength, "length");
3055 oprintf (d->of, ");\n");
3059 endcounter = d->counter;
3061 FOR_ALL_INHERITED_FIELDS (t, f)
3063 options_p oo;
3064 const char *dot = ".";
3065 const char *tagid = NULL;
3066 int skip_p = 0;
3067 int default_p = 0;
3068 const char *fieldlength = NULL;
3069 char *newval;
3071 d->reorder_fn = NULL;
3072 for (oo = f->opt; oo; oo = oo->next)
3073 if (strcmp (oo->name, "dot") == 0
3074 && oo->kind == OPTION_STRING)
3075 dot = oo->info.string;
3076 else if (strcmp (oo->name, "tag") == 0
3077 && oo->kind == OPTION_STRING)
3078 tagid = oo->info.string;
3079 else if (strcmp (oo->name, "skip") == 0)
3080 skip_p = 1;
3081 else if (strcmp (oo->name, "default") == 0)
3082 default_p = 1;
3083 else if (strcmp (oo->name, "reorder") == 0
3084 && oo->kind == OPTION_STRING)
3085 d->reorder_fn = oo->info.string;
3086 else if (strcmp (oo->name, "length") == 0
3087 && oo->kind == OPTION_STRING)
3088 fieldlength = oo->info.string;
3090 if (skip_p)
3091 continue;
3093 if (union_p && tagid)
3095 oprintf (d->of, "%*scase %s:\n", d->indent, "", tagid);
3096 d->indent += 2;
3098 else if (union_p && default_p)
3100 oprintf (d->of, "%*sdefault:\n", d->indent, "");
3101 d->indent += 2;
3102 seen_default_p = 1;
3104 else if (!union_p && (default_p || tagid))
3105 error_at_line (d->line,
3106 "can't use `%s' outside a union on field `%s'",
3107 default_p ? "default" : "tag", f->name);
3108 else if (union_p && !(default_p || tagid)
3109 && f->type->kind == TYPE_SCALAR)
3111 fprintf (stderr,
3112 "%s:%d: warning: field `%s' is missing `tag' or `default' option\n",
3113 get_input_file_name (d->line->file), d->line->line,
3114 f->name);
3115 continue;
3117 else if (union_p && !(default_p || tagid))
3118 error_at_line (d->line,
3119 "field `%s' is missing `tag' or `default' option",
3120 f->name);
3122 if (fieldlength)
3124 d->loopcounter = endcounter - lengths_seen--;
3127 d->line = &f->line;
3128 d->val = newval = xasprintf ("%s%s%s", oldval, dot, f->name);
3129 d->opt = f->opt;
3130 d->used_length = false;
3131 d->in_record_p = !union_p;
3133 walk_type (f->type, d);
3135 d->in_record_p = false;
3137 free (newval);
3139 if (union_p)
3141 oprintf (d->of, "%*sbreak;\n", d->indent, "");
3142 d->indent -= 2;
3145 d->reorder_fn = NULL;
3147 d->val = oldval;
3148 d->prev_val[1] = oldprevval1;
3149 d->prev_val[2] = oldprevval2;
3151 if (union_p && !seen_default_p)
3153 oprintf (d->of, "%*sdefault:\n", d->indent, "");
3154 oprintf (d->of, "%*s break;\n", d->indent, "");
3157 if (desc && !union_p)
3159 oprintf (d->of, "%*sbreak;\n", d->indent, "");
3160 d->indent -= 2;
3162 if (union_p)
3164 oprintf (d->of, "%*s}\n", d->indent, "");
3165 d->indent -= 2;
3167 else if (desc)
3169 /* Add cases to handle subclasses. */
3170 struct seen_tag *tags = NULL;
3171 walk_subclasses (t, d, &tags);
3173 /* Ensure that if someone forgets a "tag" option that we don't
3174 silent fail to traverse that subclass's fields. */
3175 if (!seen_default_p)
3177 oprintf (d->of, "%*s/* Unrecognized tag value. */\n",
3178 d->indent, "");
3179 oprintf (d->of, "%*sdefault: gcc_unreachable (); \n",
3180 d->indent, "");
3183 /* End of the switch statement */
3184 oprintf (d->of, "%*s}\n", d->indent, "");
3185 d->indent -= 2;
3187 if (any_length_seen)
3189 d->indent -= 2;
3190 oprintf (d->of, "%*s}\n", d->indent, "");
3193 break;
3195 case TYPE_LANG_STRUCT:
3197 type_p nt;
3198 for (nt = t->u.s.lang_struct; nt; nt = nt->next)
3199 if ((d->bitmap & nt->u.s.bitmap) == d->bitmap)
3200 break;
3201 if (nt == NULL)
3202 error_at_line (d->line, "structure `%s' differs between languages",
3203 t->u.s.tag);
3204 else
3205 walk_type (nt, d);
3207 break;
3209 case TYPE_USER_STRUCT:
3210 d->process_field (t, d);
3211 break;
3213 case TYPE_NONE:
3214 case TYPE_UNDEFINED:
3215 gcc_unreachable ();
3219 /* process_field routine for marking routines. */
3221 static void
3222 write_types_process_field (type_p f, const struct walk_type_data *d)
3224 const struct write_types_data *wtd;
3225 const char *cast = d->needs_cast_p ? "(void *)" : "";
3226 wtd = (const struct write_types_data *) d->cookie;
3228 switch (f->kind)
3230 case TYPE_NONE:
3231 case TYPE_UNDEFINED:
3232 gcc_unreachable ();
3233 case TYPE_POINTER:
3234 oprintf (d->of, "%*s%s (%s%s", d->indent, "",
3235 wtd->subfield_marker_routine, cast, d->val);
3236 if (wtd->param_prefix)
3238 if (f->u.p->kind == TYPE_SCALAR)
3239 /* The current type is a pointer to a scalar (so not
3240 considered like a pointer to instances of user defined
3241 types) and we are seeing it; it means we must be even
3242 more careful about the second argument of the
3243 SUBFIELD_MARKER_ROUTINE call. That argument must
3244 always be the instance of the type for which
3245 write_func_for_structure was called - this really is
3246 what the function SUBFIELD_MARKER_ROUTINE expects.
3247 That is, it must be an instance of the ORIG_S type
3248 parameter of write_func_for_structure. The convention
3249 is that that argument must be "x" in that case (as set
3250 by write_func_for_structure). The problem is, we can't
3251 count on d->prev_val[3] to be always set to "x" in that
3252 case. Sometimes walk_type can set it to something else
3253 (to e.g cooperate with write_array when called from
3254 write_roots). So let's set it to "x" here then. */
3255 oprintf (d->of, ", x");
3256 else
3257 oprintf (d->of, ", %s", d->prev_val[3]);
3258 if (d->orig_s)
3260 oprintf (d->of, ", gt_%s_", wtd->param_prefix);
3261 output_mangled_typename (d->of, d->orig_s);
3263 else
3264 oprintf (d->of, ", gt_%sa_%s", wtd->param_prefix, d->prev_val[0]);
3266 oprintf (d->of, ");\n");
3267 if (d->reorder_fn && wtd->reorder_note_routine)
3268 oprintf (d->of, "%*s%s (%s%s, %s, %s);\n", d->indent, "",
3269 wtd->reorder_note_routine, cast, d->val,
3270 d->prev_val[3], d->reorder_fn);
3271 break;
3273 case TYPE_STRING:
3274 case TYPE_STRUCT:
3275 case TYPE_UNION:
3276 case TYPE_LANG_STRUCT:
3277 case TYPE_USER_STRUCT:
3278 if (f->kind == TYPE_USER_STRUCT && !d->in_ptr_field)
3280 /* If F is a user-defined type and the field is not a
3281 pointer to the type, then we should not generate the
3282 standard pointer-marking code. All we need to do is call
3283 the user-provided marking function to process the fields
3284 of F. */
3285 oprintf (d->of, "%*sgt_%sx (&(%s));\n", d->indent, "", wtd->prefix,
3286 d->val);
3288 else
3290 oprintf (d->of, "%*sgt_%s_", d->indent, "", wtd->prefix);
3291 output_mangled_typename (d->of, f);
3292 oprintf (d->of, " (%s%s);\n", cast, d->val);
3293 if (d->reorder_fn && wtd->reorder_note_routine)
3294 oprintf (d->of, "%*s%s (%s%s, %s%s, %s);\n", d->indent, "",
3295 wtd->reorder_note_routine, cast, d->val, cast, d->val,
3296 d->reorder_fn);
3298 break;
3300 case TYPE_SCALAR:
3301 case TYPE_CALLBACK:
3302 break;
3304 case TYPE_ARRAY:
3305 gcc_unreachable ();
3309 /* Return an output file that is suitable for definitions which can
3310 reference struct S */
3312 static outf_p
3313 get_output_file_for_structure (const_type_p s)
3315 const input_file *fn;
3317 gcc_assert (union_or_struct_p (s));
3318 fn = s->u.s.line.file;
3320 /* The call to get_output_file_with_visibility may update fn by
3321 caching its result inside, so we need the CONST_CAST. */
3322 return get_output_file_with_visibility (CONST_CAST (input_file*, fn));
3326 /* Returns the specifier keyword for a string or union type S, empty string
3327 otherwise. */
3329 static const char *
3330 get_type_specifier (const type_p s)
3332 if (s->kind == TYPE_STRUCT)
3333 return "struct ";
3334 else if (s->kind == TYPE_LANG_STRUCT)
3335 return get_type_specifier (s->u.s.lang_struct);
3336 else if (s->kind == TYPE_UNION)
3337 return "union ";
3338 return "";
3342 /* Emits a declaration for type TY (assumed to be a union or a
3343 structure) on stream OUT. */
3345 static void
3346 write_type_decl (outf_p out, type_p ty)
3348 if (union_or_struct_p (ty))
3349 oprintf (out, "%s%s", get_type_specifier (ty), ty->u.s.tag);
3350 else if (ty->kind == TYPE_SCALAR)
3352 if (ty->u.scalar_is_char)
3353 oprintf (out, "const char");
3354 else
3355 oprintf (out, "void");
3357 else if (ty->kind == TYPE_POINTER)
3359 write_type_decl (out, ty->u.p);
3360 oprintf (out, " *");
3362 else if (ty->kind == TYPE_ARRAY)
3364 write_type_decl (out, ty->u.a.p);
3365 oprintf (out, " *");
3367 else if (ty->kind == TYPE_STRING)
3369 oprintf (out, "const char *");
3371 else
3372 gcc_unreachable ();
3376 /* Write on OF the name of the marker function for structure S. PREFIX
3377 is the prefix to use (to distinguish ggc from pch markers). */
3379 static void
3380 write_marker_function_name (outf_p of, type_p s, const char *prefix)
3382 if (union_or_struct_p (s))
3384 const char *id_for_tag = filter_type_name (s->u.s.tag);
3385 oprintf (of, "gt_%sx_%s", prefix, id_for_tag);
3386 if (id_for_tag != s->u.s.tag)
3387 free (CONST_CAST (char *, id_for_tag));
3389 else
3390 gcc_unreachable ();
3393 /* Write on OF a user-callable routine to act as an entry point for
3394 the marking routine for S, generated by write_func_for_structure.
3395 WTD distinguishes between ggc and pch markers. */
3397 static void
3398 write_user_func_for_structure_ptr (outf_p of, type_p s, const write_types_data *wtd)
3400 gcc_assert (union_or_struct_p (s));
3402 type_p alias_of = NULL;
3403 for (options_p opt = s->u.s.opt; opt; opt = opt->next)
3404 if (strcmp (opt->name, "ptr_alias") == 0)
3406 /* ALIAS_OF is set if ORIG_S is marked "ptr_alias". This means that
3407 we do not generate marking code for ORIG_S here. Instead, a
3408 forwarder #define in gtype-desc.h will cause every call to its
3409 marker to call the target of this alias.
3411 However, we still want to create a user entry code for the
3412 aliased type. So, if ALIAS_OF is set, we only generate the
3413 user-callable marker function. */
3414 alias_of = opt->info.type;
3415 break;
3418 DBGPRINTF ("write_user_func_for_structure_ptr: %s %s", s->u.s.tag,
3419 wtd->prefix);
3421 /* Only write the function once. */
3422 if (s->u.s.wrote_user_func_for_ptr[wtd->kind])
3423 return;
3424 s->u.s.wrote_user_func_for_ptr[wtd->kind] = true;
3426 oprintf (of, "\nvoid\n");
3427 oprintf (of, "gt_%sx (", wtd->prefix);
3428 write_type_decl (of, s);
3429 oprintf (of, " *& x)\n");
3430 oprintf (of, "{\n");
3431 oprintf (of, " if (x)\n ");
3432 write_marker_function_name (of,
3433 alias_of ? alias_of : get_ultimate_base_class (s),
3434 wtd->prefix);
3435 oprintf (of, " ((void *) x);\n");
3436 oprintf (of, "}\n");
3440 /* Write a function to mark all the fields of type S on OF. PREFIX
3441 and D are as in write_user_marking_functions. */
3443 static void
3444 write_user_func_for_structure_body (type_p s, const char *prefix,
3445 struct walk_type_data *d)
3447 oprintf (d->of, "\nvoid\n");
3448 oprintf (d->of, "gt_%sx (", prefix);
3449 write_type_decl (d->of, s);
3450 oprintf (d->of, "& x_r ATTRIBUTE_UNUSED)\n");
3451 oprintf (d->of, "{\n");
3452 oprintf (d->of, " ");
3453 write_type_decl (d->of, s);
3454 oprintf (d->of, " * ATTRIBUTE_UNUSED x = &x_r;\n");
3455 d->val = "(*x)";
3456 d->indent = 2;
3457 walk_type (s, d);
3458 oprintf (d->of, "}\n");
3461 /* Emit the user-callable functions needed to mark all the types used
3462 by the user structure S. PREFIX is the prefix to use to
3463 distinguish ggc and pch markers. D contains data needed to pass to
3464 walk_type when traversing the fields of a type.
3466 For every type T referenced by S, two routines are generated: one
3467 that takes 'T *', marks the pointer and calls the second routine,
3468 which just marks the fields of T. */
3470 static void
3471 write_user_marking_functions (type_p s,
3472 const write_types_data *w,
3473 struct walk_type_data *d)
3475 gcc_assert (s->kind == TYPE_USER_STRUCT);
3477 for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
3479 type_p fld_type = fld->type;
3480 if (fld_type->kind == TYPE_POINTER)
3482 type_p pointed_to_type = fld_type->u.p;
3483 if (union_or_struct_p (pointed_to_type))
3484 write_user_func_for_structure_ptr (d->of, pointed_to_type, w);
3486 else if (union_or_struct_p (fld_type))
3487 write_user_func_for_structure_body (fld_type, w->prefix, d);
3492 /* For S, a structure that's part of ORIG_S write out a routine that:
3493 - Takes a parameter, a void * but actually of type *S
3494 - If SEEN_ROUTINE returns nonzero, calls write_types_process_field on each
3495 field of S or its substructures and (in some cases) things
3496 that are pointed to by S. */
3498 static void
3499 write_func_for_structure (type_p orig_s, type_p s,
3500 const struct write_types_data *wtd)
3502 const char *chain_next = NULL;
3503 const char *chain_prev = NULL;
3504 const char *chain_circular = NULL;
3505 options_p opt;
3506 struct walk_type_data d;
3508 if (s->u.s.base_class)
3510 /* Verify that the base class has a "desc", since otherwise
3511 the traversal hooks there won't attempt to visit fields of
3512 subclasses such as this one. */
3513 const_type_p ubc = get_ultimate_base_class (s);
3514 if ((!opts_have (ubc->u.s.opt, "user")
3515 && !opts_have (ubc->u.s.opt, "desc")))
3516 error_at_line (&s->u.s.line,
3517 ("'%s' is a subclass of non-GTY(user) GTY class '%s'"
3518 ", but '%s' lacks a discriminator 'desc' option"),
3519 s->u.s.tag, ubc->u.s.tag, ubc->u.s.tag);
3521 /* Don't write fns for subclasses, only for the ultimate base class
3522 within an inheritance hierarchy. */
3523 return;
3526 memset (&d, 0, sizeof (d));
3527 d.of = get_output_file_for_structure (s);
3529 bool for_user = false;
3530 for (opt = s->u.s.opt; opt; opt = opt->next)
3531 if (strcmp (opt->name, "chain_next") == 0
3532 && opt->kind == OPTION_STRING)
3533 chain_next = opt->info.string;
3534 else if (strcmp (opt->name, "chain_prev") == 0
3535 && opt->kind == OPTION_STRING)
3536 chain_prev = opt->info.string;
3537 else if (strcmp (opt->name, "chain_circular") == 0
3538 && opt->kind == OPTION_STRING)
3539 chain_circular = opt->info.string;
3540 else if (strcmp (opt->name, "for_user") == 0)
3541 for_user = true;
3542 if (chain_prev != NULL && chain_next == NULL)
3543 error_at_line (&s->u.s.line, "chain_prev without chain_next");
3544 if (chain_circular != NULL && chain_next != NULL)
3545 error_at_line (&s->u.s.line, "chain_circular with chain_next");
3546 if (chain_circular != NULL)
3547 chain_next = chain_circular;
3549 d.process_field = write_types_process_field;
3550 d.cookie = wtd;
3551 d.orig_s = orig_s;
3552 d.opt = s->u.s.opt;
3553 d.line = &s->u.s.line;
3554 d.bitmap = s->u.s.bitmap;
3555 d.prev_val[0] = "*x";
3556 d.prev_val[1] = "not valid postage"; /* Guarantee an error. */
3557 d.prev_val[3] = "x";
3558 d.val = "(*x)";
3559 d.have_this_obj = false;
3561 oprintf (d.of, "\n");
3562 oprintf (d.of, "void\n");
3563 write_marker_function_name (d.of, orig_s, wtd->prefix);
3564 oprintf (d.of, " (void *x_p)\n");
3565 oprintf (d.of, "{\n ");
3566 write_type_decl (d.of, s);
3567 oprintf (d.of, " * %sx = (", chain_next == NULL ? "const " : "");
3568 write_type_decl (d.of, s);
3569 oprintf (d.of, " *)x_p;\n");
3570 if (chain_next != NULL)
3572 /* TYPE_USER_STRUCTs should not occur here. These structures
3573 are completely handled by user code. */
3574 gcc_assert (orig_s->kind != TYPE_USER_STRUCT);
3576 oprintf (d.of, " ");
3577 write_type_decl (d.of, s);
3578 oprintf (d.of, " * xlimit = x;\n");
3580 if (chain_next == NULL)
3582 oprintf (d.of, " if (%s (x", wtd->marker_routine);
3583 if (wtd->param_prefix)
3585 oprintf (d.of, ", x, gt_%s_", wtd->param_prefix);
3586 output_mangled_typename (d.of, orig_s);
3588 oprintf (d.of, "))\n");
3590 else
3592 if (chain_circular != NULL)
3593 oprintf (d.of, " if (!%s (xlimit", wtd->marker_routine);
3594 else
3595 oprintf (d.of, " while (%s (xlimit", wtd->marker_routine);
3596 if (wtd->param_prefix)
3598 oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
3599 output_mangled_typename (d.of, orig_s);
3601 oprintf (d.of, "))\n");
3602 if (chain_circular != NULL)
3603 oprintf (d.of, " return;\n do\n");
3605 oprintf (d.of, " xlimit = (");
3606 d.prev_val[2] = "*xlimit";
3607 output_escaped_param (&d, chain_next, "chain_next");
3608 oprintf (d.of, ");\n");
3609 if (chain_prev != NULL)
3611 oprintf (d.of, " if (x != xlimit)\n");
3612 oprintf (d.of, " for (;;)\n");
3613 oprintf (d.of, " {\n");
3614 oprintf (d.of, " %s %s * const xprev = (",
3615 s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
3617 d.prev_val[2] = "*x";
3618 output_escaped_param (&d, chain_prev, "chain_prev");
3619 oprintf (d.of, ");\n");
3620 oprintf (d.of, " if (xprev == NULL) break;\n");
3621 oprintf (d.of, " x = xprev;\n");
3622 oprintf (d.of, " (void) %s (xprev", wtd->marker_routine);
3623 if (wtd->param_prefix)
3625 oprintf (d.of, ", xprev, gt_%s_", wtd->param_prefix);
3626 output_mangled_typename (d.of, orig_s);
3628 oprintf (d.of, ");\n");
3629 oprintf (d.of, " }\n");
3631 if (chain_circular != NULL)
3633 oprintf (d.of, " while (%s (xlimit", wtd->marker_routine);
3634 if (wtd->param_prefix)
3636 oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
3637 output_mangled_typename (d.of, orig_s);
3639 oprintf (d.of, "));\n");
3640 oprintf (d.of, " do\n");
3642 else
3643 oprintf (d.of, " while (x != xlimit)\n");
3645 oprintf (d.of, " {\n");
3647 d.prev_val[2] = "*x";
3648 d.indent = 6;
3649 if (orig_s->kind != TYPE_USER_STRUCT)
3650 walk_type (s, &d);
3651 else
3653 /* User structures have no fields to walk. Simply generate a call
3654 to the user-provided structure marker. */
3655 oprintf (d.of, "%*sgt_%sx (x);\n", d.indent, "", wtd->prefix);
3658 if (chain_next != NULL)
3660 oprintf (d.of, " x = (");
3661 output_escaped_param (&d, chain_next, "chain_next");
3662 oprintf (d.of, ");\n");
3665 oprintf (d.of, " }\n");
3666 if (chain_circular != NULL)
3667 oprintf (d.of, " while (x != xlimit);\n");
3668 oprintf (d.of, "}\n");
3670 if (orig_s->kind == TYPE_USER_STRUCT)
3671 write_user_marking_functions (orig_s, wtd, &d);
3673 if (for_user)
3675 write_user_func_for_structure_body (orig_s, wtd->prefix, &d);
3676 write_user_func_for_structure_ptr (d.of, orig_s, wtd);
3681 /* Write out marker routines for STRUCTURES and PARAM_STRUCTS. */
3683 static void
3684 write_types (outf_p output_header, type_p structures,
3685 const struct write_types_data *wtd)
3687 int nbfun = 0; /* Count the emitted functions. */
3688 type_p s;
3690 oprintf (output_header, "\n/* %s*/\n", wtd->comment);
3692 /* We first emit the macros and the declarations. Functions' code is
3693 emitted afterwards. This is needed in plugin mode. */
3694 oprintf (output_header, "/* Macros and declarations. */\n");
3695 for (s = structures; s; s = s->next)
3696 /* Do not emit handlers for derived classes; we only ever deal with
3697 the ultimate base class within an inheritance hierarchy. */
3698 if ((s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
3699 && !s->u.s.base_class)
3701 options_p opt;
3703 if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
3704 continue;
3706 const char *s_id_for_tag = filter_type_name (s->u.s.tag);
3708 oprintf (output_header, "#define gt_%s_", wtd->prefix);
3709 output_mangled_typename (output_header, s);
3710 oprintf (output_header, "(X) do { \\\n");
3711 oprintf (output_header,
3712 " if ((intptr_t)(X) != 0) gt_%sx_%s (X);\\\n",
3713 wtd->prefix, s_id_for_tag);
3714 oprintf (output_header, " } while (0)\n");
3716 for (opt = s->u.s.opt; opt; opt = opt->next)
3717 if (strcmp (opt->name, "ptr_alias") == 0
3718 && opt->kind == OPTION_TYPE)
3720 const_type_p const t = (const_type_p) opt->info.type;
3721 if (t->kind == TYPE_STRUCT
3722 || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
3724 const char *t_id_for_tag = filter_type_name (t->u.s.tag);
3725 oprintf (output_header,
3726 "#define gt_%sx_%s gt_%sx_%s\n",
3727 wtd->prefix, s->u.s.tag, wtd->prefix, t_id_for_tag);
3728 if (t_id_for_tag != t->u.s.tag)
3729 free (CONST_CAST (char *, t_id_for_tag));
3731 else
3732 error_at_line (&s->u.s.line,
3733 "structure alias is not a structure");
3734 break;
3736 if (opt)
3737 continue;
3739 /* Declare the marker procedure only once. */
3740 oprintf (output_header,
3741 "extern void gt_%sx_%s (void *);\n",
3742 wtd->prefix, s_id_for_tag);
3744 if (s_id_for_tag != s->u.s.tag)
3745 free (CONST_CAST (char *, s_id_for_tag));
3747 if (s->u.s.line.file == NULL)
3749 fprintf (stderr, "warning: structure `%s' used but not defined\n",
3750 s->u.s.tag);
3751 continue;
3755 /* At last we emit the functions code. */
3756 oprintf (output_header, "\n/* functions code */\n");
3757 for (s = structures; s; s = s->next)
3758 if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
3760 options_p opt;
3762 if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
3763 continue;
3764 for (opt = s->u.s.opt; opt; opt = opt->next)
3765 if (strcmp (opt->name, "ptr_alias") == 0)
3766 break;
3767 if (opt)
3768 continue;
3770 if (s->kind == TYPE_LANG_STRUCT)
3772 type_p ss;
3773 for (ss = s->u.s.lang_struct; ss; ss = ss->next)
3775 nbfun++;
3776 DBGPRINTF ("writing func #%d lang_struct ss @ %p '%s'",
3777 nbfun, (void*) ss, ss->u.s.tag);
3778 write_func_for_structure (s, ss, wtd);
3781 else
3783 nbfun++;
3784 DBGPRINTF ("writing func #%d struct s @ %p '%s'",
3785 nbfun, (void*) s, s->u.s.tag);
3786 write_func_for_structure (s, s, wtd);
3789 else
3791 /* Structure s is not possibly pointed to, so can be ignored. */
3792 DBGPRINTF ("ignored s @ %p '%s' gc_used#%d",
3793 (void*)s, s->u.s.tag,
3794 (int) s->gc_used);
3797 if (verbosity_level >= 2)
3798 printf ("%s emitted %d routines for %s\n",
3799 progname, nbfun, wtd->comment);
3802 static const struct write_types_data ggc_wtd = {
3803 "ggc_m", NULL, "ggc_mark", "ggc_test_and_set_mark", NULL,
3804 "GC marker procedures. ",
3805 WTK_GGC
3808 static const struct write_types_data pch_wtd = {
3809 "pch_n", "pch_p", "gt_pch_note_object", "gt_pch_note_object",
3810 "gt_pch_note_reorder",
3811 "PCH type-walking procedures. ",
3812 WTK_PCH
3815 /* Write out the local pointer-walking routines. */
3817 /* process_field routine for local pointer-walking for user-callable
3818 routines. The difference between this and
3819 write_types_local_process_field is that, in this case, we do not
3820 need to check whether the given pointer matches the address of the
3821 parent structure. This check was already generated by the call
3822 to gt_pch_nx in the main gt_pch_p_*() function that is calling
3823 this code. */
3825 static void
3826 write_types_local_user_process_field (type_p f, const struct walk_type_data *d)
3828 switch (f->kind)
3830 case TYPE_POINTER:
3831 case TYPE_STRUCT:
3832 case TYPE_UNION:
3833 case TYPE_LANG_STRUCT:
3834 case TYPE_STRING:
3835 if (d->in_nested_ptr)
3836 oprintf (d->of, "%*s op (&(%s), &(%s), cookie);\n",
3837 d->indent, "", d->val, d->prev_val[2]);
3838 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3839 d->indent, "", d->val);
3840 break;
3842 case TYPE_USER_STRUCT:
3843 if (d->in_ptr_field)
3844 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3845 d->indent, "", d->val);
3846 else
3847 oprintf (d->of, "%*s gt_pch_nx (&(%s), op, cookie);\n",
3848 d->indent, "", d->val);
3849 break;
3851 case TYPE_SCALAR:
3852 case TYPE_CALLBACK:
3853 break;
3855 case TYPE_ARRAY:
3856 case TYPE_NONE:
3857 case TYPE_UNDEFINED:
3858 gcc_unreachable ();
3863 /* Write a function to PCH walk all the fields of type S on OF.
3864 D contains data needed by walk_type to recurse into the fields of S. */
3866 static void
3867 write_pch_user_walking_for_structure_body (type_p s, struct walk_type_data *d)
3869 oprintf (d->of, "\nvoid\n");
3870 oprintf (d->of, "gt_pch_nx (");
3871 write_type_decl (d->of, s);
3872 oprintf (d->of, "* x ATTRIBUTE_UNUSED,\n"
3873 "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
3874 "\tATTRIBUTE_UNUSED void *cookie)\n");
3875 oprintf (d->of, "{\n");
3876 d->val = "(*x)";
3877 d->indent = 2;
3878 d->process_field = write_types_local_user_process_field;
3879 walk_type (s, d);
3880 oprintf (d->of, "}\n");
3884 /* Emit the user-callable functions needed to mark all the types used
3885 by the user structure S. PREFIX is the prefix to use to
3886 distinguish ggc and pch markers. CHAIN_NEXT is set if S has the
3887 chain_next option defined. D contains data needed to pass to
3888 walk_type when traversing the fields of a type.
3890 For every type T referenced by S, two routines are generated: one
3891 that takes 'T *', marks the pointer and calls the second routine,
3892 which just marks the fields of T. */
3894 static void
3895 write_pch_user_walking_functions (type_p s, struct walk_type_data *d)
3897 gcc_assert (s->kind == TYPE_USER_STRUCT);
3899 for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
3901 type_p fld_type = fld->type;
3902 if (union_or_struct_p (fld_type))
3903 write_pch_user_walking_for_structure_body (fld_type, d);
3908 /* process_field routine for local pointer-walking. */
3910 static void
3911 write_types_local_process_field (type_p f, const struct walk_type_data *d)
3913 gcc_assert (d->have_this_obj);
3914 switch (f->kind)
3916 case TYPE_POINTER:
3917 case TYPE_STRUCT:
3918 case TYPE_UNION:
3919 case TYPE_LANG_STRUCT:
3920 case TYPE_STRING:
3921 oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3922 d->prev_val[3]);
3923 if (d->in_nested_ptr)
3924 oprintf (d->of, "%*s op (&(%s), &(%s), cookie);\n",
3925 d->indent, "", d->val, d->prev_val[2]);
3926 else
3927 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3928 d->indent, "", d->val);
3929 break;
3931 case TYPE_USER_STRUCT:
3932 oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3933 d->prev_val[3]);
3934 if (d->in_ptr_field)
3935 oprintf (d->of, "%*s op (&(%s), NULL, cookie);\n",
3936 d->indent, "", d->val);
3937 else
3938 oprintf (d->of, "%*s gt_pch_nx (&(%s), op, cookie);\n",
3939 d->indent, "", d->val);
3940 break;
3942 case TYPE_SCALAR:
3943 break;
3945 case TYPE_CALLBACK:
3946 oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3947 d->prev_val[3]);
3948 oprintf (d->of, "%*s gt_pch_note_callback (&(%s), this_obj);\n",
3949 d->indent, "", d->val);
3950 break;
3952 case TYPE_ARRAY:
3953 case TYPE_NONE:
3954 case TYPE_UNDEFINED:
3955 gcc_unreachable ();
3960 /* For S, a structure that's part of ORIG_S, and using parameters
3961 PARAM, write out a routine that:
3962 - Is of type gt_note_pointers
3963 - Calls PROCESS_FIELD on each field of S or its substructures.
3966 static void
3967 write_local_func_for_structure (const_type_p orig_s, type_p s)
3969 struct walk_type_data d;
3971 /* Don't write fns for subclasses, only for the ultimate base class
3972 within an inheritance hierarchy. */
3973 if (s->u.s.base_class)
3974 return;
3976 memset (&d, 0, sizeof (d));
3977 d.of = get_output_file_for_structure (s);
3978 d.process_field = write_types_local_process_field;
3979 d.opt = s->u.s.opt;
3980 d.line = &s->u.s.line;
3981 d.bitmap = s->u.s.bitmap;
3982 d.prev_val[0] = d.prev_val[2] = "*x";
3983 d.prev_val[1] = "not valid postage"; /* Guarantee an error. */
3984 d.prev_val[3] = "x";
3985 d.val = "(*x)";
3986 d.fn_wants_lvalue = true;
3988 oprintf (d.of, "\n");
3989 oprintf (d.of, "void\n");
3990 oprintf (d.of, "gt_pch_p_");
3991 output_mangled_typename (d.of, orig_s);
3992 oprintf (d.of, " (ATTRIBUTE_UNUSED void *this_obj,\n"
3993 "\tvoid *x_p,\n"
3994 "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
3995 "\tATTRIBUTE_UNUSED void *cookie)\n");
3996 oprintf (d.of, "{\n");
3997 oprintf (d.of, " %s %s * x ATTRIBUTE_UNUSED = (%s %s *)x_p;\n",
3998 s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag,
3999 s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
4000 d.indent = 2;
4001 d.have_this_obj = true;
4003 if (s->kind != TYPE_USER_STRUCT)
4004 walk_type (s, &d);
4005 else
4007 /* User structures have no fields to walk. Simply generate a
4008 call to the user-provided PCH walker. */
4009 oprintf (d.of, "%*sif ((void *)(%s) == this_obj)\n", d.indent, "",
4010 d.prev_val[3]);
4011 oprintf (d.of, "%*s gt_pch_nx (&(%s), op, cookie);\n",
4012 d.indent, "", d.val);
4015 oprintf (d.of, "}\n");
4017 /* Write user-callable entry points for the PCH walking routines. */
4018 if (orig_s->kind == TYPE_USER_STRUCT)
4019 write_pch_user_walking_functions (s, &d);
4021 for (options_p o = s->u.s.opt; o; o = o->next)
4022 if (strcmp (o->name, "for_user") == 0)
4024 write_pch_user_walking_for_structure_body (s, &d);
4025 break;
4029 /* Write out local marker routines for STRUCTURES and PARAM_STRUCTS. */
4031 static void
4032 write_local (outf_p output_header, type_p structures)
4034 type_p s;
4036 if (!output_header)
4037 return;
4039 oprintf (output_header, "\n/* Local pointer-walking routines. */\n");
4040 for (s = structures; s; s = s->next)
4041 if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
4043 options_p opt;
4045 if (s->u.s.line.file == NULL)
4046 continue;
4047 for (opt = s->u.s.opt; opt; opt = opt->next)
4048 if (strcmp (opt->name, "ptr_alias") == 0
4049 && opt->kind == OPTION_TYPE)
4051 const_type_p const t = (const_type_p) opt->info.type;
4052 if (t->kind == TYPE_STRUCT
4053 || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
4055 oprintf (output_header, "#define gt_pch_p_");
4056 output_mangled_typename (output_header, s);
4057 oprintf (output_header, " gt_pch_p_");
4058 output_mangled_typename (output_header, t);
4059 oprintf (output_header, "\n");
4061 else
4062 error_at_line (&s->u.s.line,
4063 "structure alias is not a structure");
4064 break;
4066 if (opt)
4067 continue;
4069 /* Declare the marker procedure only once. */
4070 oprintf (output_header, "extern void gt_pch_p_");
4071 output_mangled_typename (output_header, s);
4072 oprintf (output_header,
4073 "\n (void *, void *, gt_pointer_operator, void *);\n");
4075 if (s->kind == TYPE_LANG_STRUCT)
4077 type_p ss;
4078 for (ss = s->u.s.lang_struct; ss; ss = ss->next)
4079 write_local_func_for_structure (s, ss);
4081 else
4082 write_local_func_for_structure (s, s);
4086 /* Nonzero if S is a type for which typed GC allocators should be output. */
4088 #define USED_BY_TYPED_GC_P(s) \
4089 ((s->kind == TYPE_POINTER \
4090 && (s->u.p->gc_used == GC_POINTED_TO \
4091 || s->u.p->gc_used == GC_USED)) \
4092 || (union_or_struct_p (s) \
4093 && ((s)->gc_used == GC_POINTED_TO \
4094 || ((s)->gc_used == GC_MAYBE_POINTED_TO \
4095 && s->u.s.line.file != NULL) \
4096 || ((s)->gc_used == GC_USED \
4097 && !startswith (s->u.s.tag, "anonymous")) \
4098 || (s->u.s.base_class && opts_have (s->u.s.opt, "tag")))))
4102 /* Might T contain any non-pointer elements? */
4104 static int
4105 contains_scalar_p (type_p t)
4107 switch (t->kind)
4109 case TYPE_STRING:
4110 case TYPE_POINTER:
4111 return 0;
4112 case TYPE_ARRAY:
4113 return contains_scalar_p (t->u.a.p);
4114 case TYPE_USER_STRUCT:
4115 /* User-marked structures will typically contain pointers. */
4116 return 0;
4117 default:
4118 /* Could also check for structures that have no non-pointer
4119 fields, but there aren't enough of those to worry about. */
4120 return 1;
4124 /* Mangle INPF and print it to F. */
4126 static void
4127 put_mangled_filename (outf_p f, const input_file *inpf)
4129 /* The call to get_output_file_name may indirectly update fn since
4130 get_output_file_with_visibility caches its result inside, so we
4131 need the CONST_CAST. */
4132 const char *name = get_output_file_name (CONST_CAST (input_file*, inpf));
4133 if (!f || !name)
4134 return;
4135 for (; *name != 0; name++)
4136 if (ISALNUM (*name))
4137 oprintf (f, "%c", *name);
4138 else
4139 oprintf (f, "%c", '_');
4142 /* Finish off the currently-created root tables in FLP. PFX, TNAME,
4143 LASTNAME, and NAME are all strings to insert in various places in
4144 the resulting code. */
4146 static void
4147 finish_root_table (struct flist *flp, const char *pfx, const char *lastname,
4148 const char *tname, const char *name)
4150 struct flist *fli2;
4152 for (fli2 = flp; fli2; fli2 = fli2->next)
4153 if (fli2->started_p)
4155 oprintf (fli2->f, " %s\n", lastname);
4156 oprintf (fli2->f, "};\n\n");
4159 for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
4160 if (fli2->started_p)
4162 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4163 int fnum;
4165 for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
4166 if (bitmap & 1)
4168 oprintf (base_files[fnum],
4169 "extern const struct %s gt_%s_", tname, pfx);
4170 put_mangled_filename (base_files[fnum], fli2->file);
4171 oprintf (base_files[fnum], "[];\n");
4176 size_t fnum;
4177 for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4178 oprintf (base_files[fnum],
4179 "EXPORTED_CONST struct %s * const %s[] = {\n", tname, name);
4183 for (fli2 = flp; fli2; fli2 = fli2->next)
4184 if (fli2->started_p)
4186 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4187 int fnum;
4189 fli2->started_p = 0;
4191 for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
4192 if (bitmap & 1)
4194 oprintf (base_files[fnum], " gt_%s_", pfx);
4195 put_mangled_filename (base_files[fnum], fli2->file);
4196 oprintf (base_files[fnum], ",\n");
4201 size_t fnum;
4202 for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4204 oprintf (base_files[fnum], " NULL\n");
4205 oprintf (base_files[fnum], "};\n");
4210 /* Finish off the created gt_clear_caches_file_c functions. */
4212 static void
4213 finish_cache_funcs (flist *flp)
4215 struct flist *fli2;
4217 for (fli2 = flp; fli2; fli2 = fli2->next)
4218 if (fli2->started_p)
4220 oprintf (fli2->f, "}\n\n");
4223 for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
4224 if (fli2->started_p)
4226 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4227 int fnum;
4229 for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
4230 if (bitmap & 1)
4232 oprintf (base_files[fnum], "extern void gt_clear_caches_");
4233 put_mangled_filename (base_files[fnum], fli2->file);
4234 oprintf (base_files[fnum], " ();\n");
4238 for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4239 oprintf (base_files[fnum], "void\ngt_clear_caches ()\n{\n");
4241 for (fli2 = flp; fli2; fli2 = fli2->next)
4242 if (fli2->started_p)
4244 lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4245 int fnum;
4247 fli2->started_p = 0;
4249 for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
4250 if (bitmap & 1)
4252 oprintf (base_files[fnum], " gt_clear_caches_");
4253 put_mangled_filename (base_files[fnum], fli2->file);
4254 oprintf (base_files[fnum], " ();\n");
4258 for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4260 oprintf (base_files[fnum], "}\n");
4264 /* Write the first three fields (pointer, count and stride) for
4265 root NAME to F. V and LINE are as for write_root.
4267 Return true if the entry could be written; return false on error. */
4269 static bool
4270 start_root_entry (outf_p f, pair_p v, const char *name, struct fileloc *line)
4272 type_p ap;
4274 if (!v)
4276 error_at_line (line, "`%s' is too complex to be a root", name);
4277 return false;
4280 oprintf (f, " {\n");
4281 oprintf (f, " &%s,\n", name);
4282 oprintf (f, " 1");
4284 for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
4285 if (ap->u.a.len[0])
4286 oprintf (f, " * (%s)", ap->u.a.len);
4287 else if (ap == v->type)
4288 oprintf (f, " * ARRAY_SIZE (%s)", v->name);
4289 oprintf (f, ",\n");
4290 oprintf (f, " sizeof (%s", v->name);
4291 for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
4292 oprintf (f, "[0]");
4293 oprintf (f, "),\n");
4294 return true;
4297 /* A subroutine of write_root for writing the roots for field FIELD_NAME,
4298 which has type FIELD_TYPE. Parameters F to EMIT_PCH are the parameters
4299 of the caller. */
4301 static void
4302 write_field_root (outf_p f, pair_p v, type_p type, const char *name,
4303 int has_length, struct fileloc *line,
4304 bool emit_pch, type_p field_type, const char *field_name)
4306 struct pair newv;
4307 /* If the field reference is relative to V, rather than to some
4308 subcomponent of V, we can mark any subarrays with a single stride.
4309 We're effectively treating the field as a global variable in its
4310 own right. */
4311 if (v && type == v->type)
4313 newv = *v;
4314 newv.type = field_type;
4315 newv.name = ACONCAT ((v->name, ".", field_name, NULL));
4316 v = &newv;
4318 /* Otherwise, any arrays nested in the structure are too complex to
4319 handle. */
4320 else if (field_type->kind == TYPE_ARRAY)
4321 v = NULL;
4322 write_root (f, v, field_type, ACONCAT ((name, ".", field_name, NULL)),
4323 has_length, line, emit_pch);
4326 /* Write out to F the table entry and any marker routines needed to
4327 mark NAME as TYPE. V can be one of three values:
4329 - null, if NAME is too complex to represent using a single
4330 count and stride. In this case, it is an error for NAME to
4331 contain any gc-ed data.
4333 - the outermost array that contains NAME, if NAME is part of an array.
4335 - the C variable that contains NAME, if NAME is not part of an array.
4337 LINE is the line of the C source that declares the root variable.
4338 HAS_LENGTH is nonzero iff V was a variable-length array. */
4340 static void
4341 write_root (outf_p f, pair_p v, type_p type, const char *name, int has_length,
4342 struct fileloc *line, bool emit_pch)
4344 switch (type->kind)
4346 case TYPE_STRUCT:
4348 pair_p fld;
4349 for (fld = type->u.s.fields; fld; fld = fld->next)
4351 int skip_p = 0;
4352 const char *desc = NULL;
4353 options_p o;
4355 for (o = fld->opt; o; o = o->next)
4356 if (strcmp (o->name, "skip") == 0)
4357 skip_p = 1;
4358 else if (strcmp (o->name, "desc") == 0
4359 && o->kind == OPTION_STRING)
4360 desc = o->info.string;
4361 else
4362 error_at_line (line,
4363 "field `%s' of global `%s' has unknown option `%s'",
4364 fld->name, name, o->name);
4366 if (skip_p)
4367 continue;
4368 else if (desc && fld->type->kind == TYPE_UNION)
4370 pair_p validf = NULL;
4371 pair_p ufld;
4373 for (ufld = fld->type->u.s.fields; ufld; ufld = ufld->next)
4375 const char *tag = NULL;
4376 options_p oo;
4377 for (oo = ufld->opt; oo; oo = oo->next)
4378 if (strcmp (oo->name, "tag") == 0
4379 && oo->kind == OPTION_STRING)
4380 tag = oo->info.string;
4381 if (tag == NULL || strcmp (tag, desc) != 0)
4382 continue;
4383 if (validf != NULL)
4384 error_at_line (line,
4385 "both `%s.%s.%s' and `%s.%s.%s' have tag `%s'",
4386 name, fld->name, validf->name,
4387 name, fld->name, ufld->name, tag);
4388 validf = ufld;
4390 if (validf != NULL)
4391 write_field_root (f, v, type, name, 0, line, emit_pch,
4392 validf->type,
4393 ACONCAT ((fld->name, ".",
4394 validf->name, NULL)));
4396 else if (desc)
4397 error_at_line (line,
4398 "global `%s.%s' has `desc' option but is not union",
4399 name, fld->name);
4400 else
4401 write_field_root (f, v, type, name, 0, line, emit_pch, fld->type,
4402 fld->name);
4405 break;
4407 case TYPE_ARRAY:
4409 char *newname;
4410 newname = xasprintf ("%s[0]", name);
4411 write_root (f, v, type->u.a.p, newname, has_length, line, emit_pch);
4412 free (newname);
4414 break;
4416 case TYPE_USER_STRUCT:
4417 error_at_line (line, "`%s' must be a pointer type, because it is "
4418 "a GC root and its type is marked with GTY((user))",
4419 v->name);
4420 break;
4422 case TYPE_POINTER:
4424 const_type_p tp;
4426 if (!start_root_entry (f, v, name, line))
4427 return;
4429 tp = type->u.p;
4431 if (!has_length && union_or_struct_p (tp))
4433 tp = get_ultimate_base_class (tp);
4434 const char *id_for_tag = filter_type_name (tp->u.s.tag);
4435 oprintf (f, " &gt_ggc_mx_%s,\n", id_for_tag);
4436 if (emit_pch)
4437 oprintf (f, " &gt_pch_nx_%s", id_for_tag);
4438 else
4439 oprintf (f, " NULL");
4440 if (id_for_tag != tp->u.s.tag)
4441 free (CONST_CAST (char *, id_for_tag));
4443 else if (has_length
4444 && (tp->kind == TYPE_POINTER || union_or_struct_p (tp)))
4446 oprintf (f, " &gt_ggc_ma_%s,\n", name);
4447 if (emit_pch)
4448 oprintf (f, " &gt_pch_na_%s", name);
4449 else
4450 oprintf (f, " NULL");
4452 else
4454 error_at_line (line,
4455 "global `%s' is pointer to unimplemented type",
4456 name);
4458 oprintf (f, "\n },\n");
4460 break;
4462 case TYPE_STRING:
4464 if (!start_root_entry (f, v, name, line))
4465 return;
4467 oprintf (f, " (gt_pointer_walker) &gt_ggc_m_S,\n");
4468 oprintf (f, " (gt_pointer_walker) &gt_pch_n_S\n");
4469 oprintf (f, " },\n");
4471 break;
4473 case TYPE_SCALAR:
4474 break;
4476 case TYPE_NONE:
4477 case TYPE_UNDEFINED:
4478 case TYPE_UNION:
4479 case TYPE_LANG_STRUCT:
4480 case TYPE_CALLBACK:
4481 error_at_line (line, "global `%s' is unimplemented type", name);
4485 /* This generates a routine to walk an array. */
4487 static void
4488 write_array (outf_p f, pair_p v, const struct write_types_data *wtd)
4490 struct walk_type_data d;
4491 char *prevval3;
4493 memset (&d, 0, sizeof (d));
4494 d.of = f;
4495 d.cookie = wtd;
4496 d.indent = 2;
4497 d.line = &v->line;
4498 d.opt = v->opt;
4499 d.bitmap = get_lang_bitmap (v->line.file);
4501 d.prev_val[3] = prevval3 = xasprintf ("&%s", v->name);
4503 if (wtd->param_prefix)
4505 oprintf (f, "static void gt_%sa_%s\n", wtd->param_prefix, v->name);
4506 oprintf (f, " (void *, void *, gt_pointer_operator, void *);\n");
4507 oprintf (f, "static void gt_%sa_%s (ATTRIBUTE_UNUSED void *this_obj,\n",
4508 wtd->param_prefix, v->name);
4509 oprintf (d.of,
4510 " ATTRIBUTE_UNUSED void *x_p,\n"
4511 " ATTRIBUTE_UNUSED gt_pointer_operator op,\n"
4512 " ATTRIBUTE_UNUSED void * cookie)\n");
4513 oprintf (d.of, "{\n");
4514 d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
4515 d.process_field = write_types_local_process_field;
4516 d.have_this_obj = true;
4517 walk_type (v->type, &d);
4518 oprintf (f, "}\n\n");
4521 d.opt = v->opt;
4522 oprintf (f, "static void gt_%sa_%s (void *);\n", wtd->prefix, v->name);
4523 oprintf (f, "static void\ngt_%sa_%s (ATTRIBUTE_UNUSED void *x_p)\n",
4524 wtd->prefix, v->name);
4525 oprintf (f, "{\n");
4526 d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
4527 d.process_field = write_types_process_field;
4528 d.have_this_obj = false;
4529 walk_type (v->type, &d);
4530 free (prevval3);
4531 oprintf (f, "}\n\n");
4534 /* Output a table describing the locations and types of VARIABLES. */
4536 static void
4537 write_roots (pair_p variables, bool emit_pch)
4539 pair_p v;
4540 struct flist *flp = NULL;
4542 for (v = variables; v; v = v->next)
4544 outf_p f =
4545 get_output_file_with_visibility (CONST_CAST (input_file*,
4546 v->line.file));
4547 struct flist *fli;
4548 const char *length = NULL;
4549 int deletable_p = 0;
4550 options_p o;
4551 for (o = v->opt; o; o = o->next)
4552 if (strcmp (o->name, "length") == 0
4553 && o->kind == OPTION_STRING)
4554 length = o->info.string;
4555 else if (strcmp (o->name, "deletable") == 0)
4556 deletable_p = 1;
4557 else if (strcmp (o->name, "cache") == 0)
4559 else
4560 error_at_line (&v->line,
4561 "global `%s' has unknown option `%s'",
4562 v->name, o->name);
4564 for (fli = flp; fli; fli = fli->next)
4565 if (fli->f == f && f)
4566 break;
4567 if (fli == NULL)
4569 fli = XNEW (struct flist);
4570 fli->f = f;
4571 fli->next = flp;
4572 fli->started_p = 0;
4573 fli->file = v->line.file;
4574 gcc_assert (fli->file);
4575 flp = fli;
4577 oprintf (f, "\n/* GC roots. */\n\n");
4580 if (!deletable_p
4581 && length
4582 && v->type->kind == TYPE_POINTER
4583 && (v->type->u.p->kind == TYPE_POINTER
4584 || v->type->u.p->kind == TYPE_STRUCT))
4586 write_array (f, v, &ggc_wtd);
4587 write_array (f, v, &pch_wtd);
4591 for (v = variables; v; v = v->next)
4593 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4594 v->line.file));
4595 struct flist *fli;
4596 int skip_p = 0;
4597 int length_p = 0;
4598 options_p o;
4600 for (o = v->opt; o; o = o->next)
4601 if (strcmp (o->name, "length") == 0)
4602 length_p = 1;
4603 else if (strcmp (o->name, "deletable") == 0)
4604 skip_p = 1;
4606 if (skip_p)
4607 continue;
4609 for (fli = flp; fli; fli = fli->next)
4610 if (fli->f == f)
4611 break;
4612 if (!fli->started_p)
4614 fli->started_p = 1;
4616 oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_r_");
4617 put_mangled_filename (f, v->line.file);
4618 oprintf (f, "[] = {\n");
4621 write_root (f, v, v->type, v->name, length_p, &v->line, emit_pch);
4624 finish_root_table (flp, "ggc_r", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4625 "gt_ggc_rtab");
4627 for (v = variables; v; v = v->next)
4629 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4630 v->line.file));
4631 struct flist *fli;
4632 int skip_p = 1;
4633 options_p o;
4635 for (o = v->opt; o; o = o->next)
4636 if (strcmp (o->name, "deletable") == 0)
4637 skip_p = 0;
4639 if (skip_p)
4640 continue;
4642 for (fli = flp; fli; fli = fli->next)
4643 if (fli->f == f)
4644 break;
4645 if (!fli->started_p)
4647 fli->started_p = 1;
4649 oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_rd_");
4650 put_mangled_filename (f, v->line.file);
4651 oprintf (f, "[] = {\n");
4654 oprintf (f, " { &%s, 1, sizeof (%s), NULL, NULL },\n",
4655 v->name, v->name);
4658 finish_root_table (flp, "ggc_rd", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4659 "gt_ggc_deletable_rtab");
4661 for (v = variables; v; v = v->next)
4663 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4664 v->line.file));
4665 struct flist *fli;
4666 bool cache = false;
4667 options_p o;
4669 for (o = v->opt; o; o = o->next)
4670 if (strcmp (o->name, "cache") == 0)
4671 cache = true;
4672 if (!cache)
4673 continue;
4675 for (fli = flp; fli; fli = fli->next)
4676 if (fli->f == f)
4677 break;
4678 if (!fli->started_p)
4680 fli->started_p = 1;
4682 oprintf (f, "void\ngt_clear_caches_");
4683 put_mangled_filename (f, v->line.file);
4684 oprintf (f, " ()\n{\n");
4687 oprintf (f, " gt_cleare_cache (%s);\n", v->name);
4690 finish_cache_funcs (flp);
4692 if (!emit_pch)
4693 return;
4695 for (v = variables; v; v = v->next)
4697 outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4698 v->line.file));
4699 struct flist *fli;
4700 int skip_p = 0;
4701 options_p o;
4703 for (o = v->opt; o; o = o->next)
4704 if (strcmp (o->name, "deletable") == 0)
4706 skip_p = 1;
4707 break;
4710 if (skip_p)
4711 continue;
4713 if (!contains_scalar_p (v->type))
4714 continue;
4716 for (fli = flp; fli; fli = fli->next)
4717 if (fli->f == f)
4718 break;
4719 if (!fli->started_p)
4721 fli->started_p = 1;
4723 oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_pch_rs_");
4724 put_mangled_filename (f, v->line.file);
4725 oprintf (f, "[] = {\n");
4728 oprintf (f, " { &%s, 1, sizeof (%s), NULL, NULL },\n",
4729 v->name, v->name);
4732 finish_root_table (flp, "pch_rs", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4733 "gt_pch_scalar_rtab");
4736 /* Prints not-as-ugly version of a typename of T to OF. Trades the uniquness
4737 guaranteee for somewhat increased readability. If name conflicts do happen,
4738 this funcion will have to be adjusted to be more like
4739 output_mangled_typename. */
4741 #define INDENT 2
4743 /* Dumps the value of typekind KIND. */
4745 static void
4746 dump_typekind (int indent, enum typekind kind)
4748 printf ("%*ckind = ", indent, ' ');
4749 switch (kind)
4751 case TYPE_SCALAR:
4752 printf ("TYPE_SCALAR");
4753 break;
4754 case TYPE_STRING:
4755 printf ("TYPE_STRING");
4756 break;
4757 case TYPE_STRUCT:
4758 printf ("TYPE_STRUCT");
4759 break;
4760 case TYPE_UNDEFINED:
4761 printf ("TYPE_UNDEFINED");
4762 break;
4763 case TYPE_USER_STRUCT:
4764 printf ("TYPE_USER_STRUCT");
4765 break;
4766 case TYPE_UNION:
4767 printf ("TYPE_UNION");
4768 break;
4769 case TYPE_POINTER:
4770 printf ("TYPE_POINTER");
4771 break;
4772 case TYPE_ARRAY:
4773 printf ("TYPE_ARRAY");
4774 break;
4775 case TYPE_CALLBACK:
4776 printf ("TYPE_CALLBACK");
4777 break;
4778 case TYPE_LANG_STRUCT:
4779 printf ("TYPE_LANG_STRUCT");
4780 break;
4781 default:
4782 gcc_unreachable ();
4784 printf ("\n");
4787 /* Dumps the value of GC_USED flag. */
4789 static void
4790 dump_gc_used (int indent, enum gc_used_enum gc_used)
4792 printf ("%*cgc_used = ", indent, ' ');
4793 switch (gc_used)
4795 case GC_UNUSED:
4796 printf ("GC_UNUSED");
4797 break;
4798 case GC_USED:
4799 printf ("GC_USED");
4800 break;
4801 case GC_MAYBE_POINTED_TO:
4802 printf ("GC_MAYBE_POINTED_TO");
4803 break;
4804 case GC_POINTED_TO:
4805 printf ("GC_POINTED_TO");
4806 break;
4807 default:
4808 gcc_unreachable ();
4810 printf ("\n");
4813 /* Dumps the type options OPT. */
4815 static void
4816 dump_options (int indent, options_p opt)
4818 options_p o;
4819 printf ("%*coptions = ", indent, ' ');
4820 o = opt;
4821 while (o)
4823 switch (o->kind)
4825 case OPTION_STRING:
4826 printf ("%s:string %s ", o->name, o->info.string);
4827 break;
4828 case OPTION_TYPE:
4829 printf ("%s:type ", o->name);
4830 dump_type (indent+1, o->info.type);
4831 break;
4832 case OPTION_NESTED:
4833 printf ("%s:nested ", o->name);
4834 break;
4835 case OPTION_NONE:
4836 gcc_unreachable ();
4838 o = o->next;
4840 printf ("\n");
4843 /* Dumps the source file location in LINE. */
4845 static void
4846 dump_fileloc (int indent, struct fileloc line)
4848 printf ("%*cfileloc: file = %s, line = %d\n", indent, ' ',
4849 get_input_file_name (line.file),
4850 line.line);
4853 /* Recursively dumps the struct, union, or a language-specific
4854 struct T. */
4856 static void
4857 dump_type_u_s (int indent, type_p t)
4859 pair_p fields;
4861 gcc_assert (union_or_struct_p (t));
4862 printf ("%*cu.s.tag = %s\n", indent, ' ', t->u.s.tag);
4863 dump_fileloc (indent, t->u.s.line);
4864 printf ("%*cu.s.fields =\n", indent, ' ');
4865 fields = t->u.s.fields;
4866 while (fields)
4868 dump_pair (indent + INDENT, fields);
4869 fields = fields->next;
4871 printf ("%*cend of fields of type %p\n", indent, ' ', (void *) t);
4872 dump_options (indent, t->u.s.opt);
4873 printf ("%*cu.s.bitmap = %X\n", indent, ' ', t->u.s.bitmap);
4874 if (t->kind == TYPE_LANG_STRUCT)
4876 printf ("%*cu.s.lang_struct:\n", indent, ' ');
4877 dump_type_list (indent + INDENT, t->u.s.lang_struct);
4881 /* Recursively dumps the array T. */
4883 static void
4884 dump_type_u_a (int indent, type_p t)
4886 gcc_assert (t->kind == TYPE_ARRAY);
4887 printf ("%*clen = %s, u.a.p:\n", indent, ' ', t->u.a.len);
4888 dump_type_list (indent + INDENT, t->u.a.p);
4891 /* Recursively dumps the type list T. */
4893 static void
4894 dump_type_list (int indent, type_p t)
4896 type_p p = t;
4897 while (p)
4899 dump_type (indent, p);
4900 p = p->next;
4904 static htab_t seen_types;
4906 /* Recursively dumps the type T if it was not dumped previously. */
4908 static void
4909 dump_type (int indent, type_p t)
4911 PTR *slot;
4913 printf ("%*cType at %p: ", indent, ' ', (void *) t);
4914 if (t->kind == TYPE_UNDEFINED)
4916 gcc_assert (t->gc_used == GC_UNUSED);
4917 printf ("undefined.\n");
4918 return;
4921 if (seen_types == NULL)
4922 seen_types = htab_create (100, htab_hash_pointer, htab_eq_pointer, NULL);
4924 slot = htab_find_slot (seen_types, t, INSERT);
4925 if (*slot != NULL)
4927 printf ("already seen.\n");
4928 return;
4930 *slot = t;
4931 printf ("\n");
4933 dump_typekind (indent, t->kind);
4934 printf ("%*cpointer_to = %p\n", indent + INDENT, ' ',
4935 (void *) t->pointer_to);
4936 dump_gc_used (indent + INDENT, t->gc_used);
4937 switch (t->kind)
4939 case TYPE_SCALAR:
4940 printf ("%*cscalar_is_char = %s\n", indent + INDENT, ' ',
4941 t->u.scalar_is_char ? "true" : "false");
4942 break;
4943 case TYPE_STRING:
4944 case TYPE_CALLBACK:
4945 break;
4946 case TYPE_STRUCT:
4947 case TYPE_UNION:
4948 case TYPE_LANG_STRUCT:
4949 case TYPE_USER_STRUCT:
4950 dump_type_u_s (indent + INDENT, t);
4951 break;
4952 case TYPE_POINTER:
4953 printf ("%*cp:\n", indent + INDENT, ' ');
4954 dump_type (indent + INDENT, t->u.p);
4955 break;
4956 case TYPE_ARRAY:
4957 dump_type_u_a (indent + INDENT, t);
4958 break;
4959 default:
4960 gcc_unreachable ();
4962 printf ("%*cEnd of type at %p\n", indent, ' ', (void *) t);
4965 /* Dumps the pair P. */
4967 static void
4968 dump_pair (int indent, pair_p p)
4970 printf ("%*cpair: name = %s\n", indent, ' ', p->name);
4971 dump_type (indent, p->type);
4972 dump_fileloc (indent, p->line);
4973 dump_options (indent, p->opt);
4974 printf ("%*cEnd of pair %s\n", indent, ' ', p->name);
4977 /* Dumps the list of pairs PP. */
4979 static void
4980 dump_pair_list (const char *name, pair_p pp)
4982 pair_p p;
4983 printf ("%s:\n", name);
4984 for (p = pp; p != NULL; p = p->next)
4985 dump_pair (0, p);
4986 printf ("End of %s\n\n", name);
4989 /* Dumps the STRUCTURES. */
4991 static void
4992 dump_structures (const char *name, type_p structures)
4994 printf ("%s:\n", name);
4995 dump_type_list (0, structures);
4996 printf ("End of %s\n\n", name);
4999 /* Dumps the internal structures of gengtype. This is useful to debug
5000 gengtype itself, or to understand what it does, e.g. for plugin
5001 developers. */
5003 static void
5004 dump_everything (void)
5006 dump_pair_list ("typedefs", typedefs);
5007 dump_structures ("structures", structures);
5008 dump_pair_list ("variables", variables);
5010 /* Allocated with the first call to dump_type. */
5011 htab_delete (seen_types);
5016 /* Option specification for getopt_long. */
5017 static const struct option gengtype_long_options[] = {
5018 {"help", no_argument, NULL, 'h'},
5019 {"version", no_argument, NULL, 'V'},
5020 {"verbose", no_argument, NULL, 'v'},
5021 {"dump", no_argument, NULL, 'd'},
5022 {"debug", no_argument, NULL, 'D'},
5023 {"plugin", required_argument, NULL, 'P'},
5024 {"srcdir", required_argument, NULL, 'S'},
5025 {"backupdir", required_argument, NULL, 'B'},
5026 {"inputs", required_argument, NULL, 'I'},
5027 {"read-state", required_argument, NULL, 'r'},
5028 {"write-state", required_argument, NULL, 'w'},
5029 /* Terminating NULL placeholder. */
5030 {NULL, no_argument, NULL, 0},
5034 static void
5035 print_usage (void)
5037 printf ("Usage: %s\n", progname);
5038 printf ("\t -h | --help " " \t# Give this help.\n");
5039 printf ("\t -D | --debug "
5040 " \t# Give debug output to debug %s itself.\n", progname);
5041 printf ("\t -V | --version " " \t# Give version information.\n");
5042 printf ("\t -v | --verbose \t# Increase verbosity. Can be given several times.\n");
5043 printf ("\t -d | --dump " " \t# Dump state for debugging.\n");
5044 printf ("\t -P | --plugin <output-file> <plugin-src> ... "
5045 " \t# Generate for plugin.\n");
5046 printf ("\t -S | --srcdir <GCC-directory> "
5047 " \t# Specify the GCC source directory.\n");
5048 printf ("\t -B | --backupdir <directory> "
5049 " \t# Specify the backup directory for updated files.\n");
5050 printf ("\t -I | --inputs <input-list> "
5051 " \t# Specify the file with source files list.\n");
5052 printf ("\t -w | --write-state <state-file> " " \t# Write a state file.\n");
5053 printf ("\t -r | --read-state <state-file> " " \t# Read a state file.\n");
5056 static void
5057 print_version (void)
5059 printf ("%s %s%s\n", progname, pkgversion_string, version_string);
5060 printf ("Report bugs: %s\n", bug_report_url);
5063 /* Parse the program options using getopt_long... */
5064 static void
5065 parse_program_options (int argc, char **argv)
5067 int opt = -1;
5068 while ((opt = getopt_long (argc, argv, "hVvdP:S:B:I:w:r:D",
5069 gengtype_long_options, NULL)) >= 0)
5071 switch (opt)
5073 case 'h': /* --help */
5074 print_usage ();
5075 break;
5076 case 'V': /* --version */
5077 print_version ();
5078 break;
5079 case 'd': /* --dump */
5080 do_dump = 1;
5081 break;
5082 case 'D': /* --debug */
5083 do_debug = 1;
5084 break;
5085 case 'v': /* --verbose */
5086 verbosity_level++;
5087 break;
5088 case 'P': /* --plugin */
5089 if (optarg)
5090 plugin_output_filename = optarg;
5091 else
5092 fatal ("missing plugin output file name");
5093 break;
5094 case 'S': /* --srcdir */
5095 if (optarg)
5096 srcdir = optarg;
5097 else
5098 fatal ("missing source directory");
5099 srcdir_len = strlen (srcdir);
5100 break;
5101 case 'B': /* --backupdir */
5102 if (optarg)
5103 backup_dir = optarg;
5104 else
5105 fatal ("missing backup directory");
5106 break;
5107 case 'I': /* --inputs */
5108 if (optarg)
5109 inputlist = optarg;
5110 else
5111 fatal ("missing input list");
5112 break;
5113 case 'r': /* --read-state */
5114 if (optarg)
5115 read_state_filename = optarg;
5116 else
5117 fatal ("missing read state file");
5118 DBGPRINTF ("read state %s\n", optarg);
5119 break;
5120 case 'w': /* --write-state */
5121 DBGPRINTF ("write state %s\n", optarg);
5122 if (optarg)
5123 write_state_filename = optarg;
5124 else
5125 fatal ("missing write state file");
5126 break;
5127 default:
5128 fprintf (stderr, "%s: unknown flag '%c'\n", progname, opt);
5129 print_usage ();
5130 fatal ("unexpected flag");
5133 if (plugin_output_filename)
5135 /* In plugin mode we require some input files. */
5136 int i = 0;
5137 if (optind >= argc)
5138 fatal ("no source files given in plugin mode");
5139 nb_plugin_files = argc - optind;
5140 plugin_files = XNEWVEC (input_file*, nb_plugin_files);
5141 for (i = 0; i < (int) nb_plugin_files; i++)
5143 char *name = argv[i + optind];
5144 plugin_files[i] = input_file_by_name (name);
5151 /******* Manage input files. ******/
5153 /* Hash table of unique input file names. */
5154 static htab_t input_file_htab;
5156 /* Find or allocate a new input_file by hash-consing it. */
5157 input_file*
5158 input_file_by_name (const char* name)
5160 PTR* slot;
5161 input_file* f = NULL;
5162 int namlen = 0;
5163 if (!name)
5164 return NULL;
5165 namlen = strlen (name);
5166 f = XCNEWVAR (input_file, sizeof (input_file)+namlen+2);
5167 f->inpbitmap = 0;
5168 f->inpoutf = NULL;
5169 f->inpisplugin = false;
5170 strcpy (f->inpname, name);
5171 slot = htab_find_slot (input_file_htab, f, INSERT);
5172 gcc_assert (slot != NULL);
5173 if (*slot)
5175 /* Already known input file. */
5176 free (f);
5177 return (input_file*)(*slot);
5179 /* New input file. */
5180 *slot = f;
5181 return f;
5184 /* Hash table support routines for input_file-s. */
5185 static hashval_t
5186 htab_hash_inputfile (const void *p)
5188 const input_file *inpf = (const input_file *) p;
5189 gcc_assert (inpf);
5190 return htab_hash_string (get_input_file_name (inpf));
5193 static int
5194 htab_eq_inputfile (const void *x, const void *y)
5196 const input_file *inpfx = (const input_file *) x;
5197 const input_file *inpfy = (const input_file *) y;
5198 gcc_assert (inpfx != NULL && inpfy != NULL);
5199 return !filename_cmp (get_input_file_name (inpfx), get_input_file_name (inpfy));
5204 main (int argc, char **argv)
5206 size_t i;
5207 static struct fileloc pos = { NULL, 0 };
5208 outf_p output_header;
5210 /* Mandatory common initializations. */
5211 progname = "gengtype"; /* For fatal and messages. */
5212 /* Create the hash-table used to hash-cons input files. */
5213 input_file_htab =
5214 htab_create (800, htab_hash_inputfile, htab_eq_inputfile, NULL);
5215 /* Initialize our special input files. */
5216 this_file = input_file_by_name (__FILE__);
5217 system_h_file = input_file_by_name ("system.h");
5218 /* Set the scalar_is_char union number for predefined scalar types. */
5219 scalar_nonchar.u.scalar_is_char = FALSE;
5220 scalar_char.u.scalar_is_char = TRUE;
5222 parse_program_options (argc, argv);
5224 if (do_debug)
5226 time_t now = (time_t) 0;
5227 time (&now);
5228 DBGPRINTF ("gengtype started pid %d at %s",
5229 (int) getpid (), ctime (&now));
5232 /* Parse the input list and the input files. */
5233 DBGPRINTF ("inputlist %s", inputlist);
5234 if (read_state_filename)
5236 if (inputlist)
5237 fatal ("input list %s cannot be given with a read state file %s",
5238 inputlist, read_state_filename);
5239 read_state (read_state_filename);
5240 DBGPRINT_COUNT_TYPE ("structures after read_state", structures);
5242 else if (inputlist)
5244 /* These types are set up with #define or else outside of where
5245 we can see them. We should initialize them before calling
5246 read_input_list. */
5247 #define POS_HERE(Call) do { pos.file = this_file; pos.line = __LINE__; \
5248 Call;} while (0)
5249 POS_HERE (do_scalar_typedef ("CUMULATIVE_ARGS", &pos));
5250 POS_HERE (do_scalar_typedef ("REAL_VALUE_TYPE", &pos));
5251 POS_HERE (do_scalar_typedef ("FIXED_VALUE_TYPE", &pos));
5252 POS_HERE (do_scalar_typedef ("double_int", &pos));
5253 POS_HERE (do_scalar_typedef ("poly_int64_pod", &pos));
5254 POS_HERE (do_scalar_typedef ("offset_int", &pos));
5255 POS_HERE (do_scalar_typedef ("widest_int", &pos));
5256 POS_HERE (do_scalar_typedef ("int64_t", &pos));
5257 POS_HERE (do_scalar_typedef ("poly_int64", &pos));
5258 POS_HERE (do_scalar_typedef ("poly_uint64", &pos));
5259 POS_HERE (do_scalar_typedef ("uint64_t", &pos));
5260 POS_HERE (do_scalar_typedef ("uint32_t", &pos));
5261 POS_HERE (do_scalar_typedef ("uint8", &pos));
5262 POS_HERE (do_scalar_typedef ("uintptr_t", &pos));
5263 POS_HERE (do_scalar_typedef ("jword", &pos));
5264 POS_HERE (do_scalar_typedef ("JCF_u2", &pos));
5265 POS_HERE (do_scalar_typedef ("void", &pos));
5266 POS_HERE (do_scalar_typedef ("machine_mode", &pos));
5267 POS_HERE (do_scalar_typedef ("fixed_size_mode", &pos));
5268 POS_HERE (do_scalar_typedef ("CONSTEXPR", &pos));
5269 POS_HERE (do_typedef ("PTR",
5270 create_pointer (resolve_typedef ("void", &pos)),
5271 &pos));
5272 #undef POS_HERE
5273 read_input_list (inputlist);
5274 num_build_headers = 0;
5275 for (i = 0; i < num_gt_files; i++)
5277 const char *fname = get_input_file_name (gt_files[i]);
5278 parse_file (fname);
5279 DBGPRINTF ("parsed file #%d %s", (int) i, fname);
5280 /* Check if this is a header file generated during the build. */
5281 int len = strlen (fname);
5282 if (len >= 5
5283 && fname[0] == '.'
5284 && IS_DIR_SEPARATOR (fname[1])
5285 && fname[len-2] == '.'
5286 && fname[len-1] == 'h')
5287 num_build_headers++;
5289 if (verbosity_level >= 1)
5290 printf ("%s parsed %d files with %d GTY types\n",
5291 progname, (int) num_gt_files, type_count);
5293 DBGPRINT_COUNT_TYPE ("structures after parsing", structures);
5295 else
5296 fatal ("either an input list or a read state file should be given");
5297 if (hit_error)
5298 return 1;
5301 if (plugin_output_filename)
5303 size_t ix = 0;
5304 /* In plugin mode, we should have read a state file, and have
5305 given at least one plugin file. */
5306 if (!read_state_filename)
5307 fatal ("No read state given in plugin mode for %s",
5308 plugin_output_filename);
5310 if (nb_plugin_files == 0 || !plugin_files)
5311 fatal ("No plugin files given in plugin mode for %s",
5312 plugin_output_filename);
5314 /* Parse our plugin files and augment the state. */
5315 for (ix = 0; ix < nb_plugin_files; ix++)
5317 input_file* pluginput = plugin_files [ix];
5318 pluginput->inpisplugin = true;
5319 parse_file (get_input_file_name (pluginput));
5321 if (hit_error)
5322 return 1;
5324 plugin_output = create_file ("GCC", plugin_output_filename);
5325 DBGPRINTF ("created plugin_output %p named %s",
5326 (void *) plugin_output, plugin_output->name);
5328 else
5329 { /* No plugin files, we are in normal mode. */
5330 if (!srcdir)
5331 fatal ("gengtype needs a source directory in normal mode");
5333 if (hit_error)
5334 return 1;
5336 gen_rtx_next ();
5338 set_gc_used (variables);
5340 for (type_p t = structures; t; t = t->next)
5342 bool for_user = false;
5343 for (options_p o = t->u.s.opt; o; o = o->next)
5344 if (strcmp (o->name, "for_user") == 0)
5346 for_user = true;
5347 break;
5350 if (for_user)
5351 set_gc_used_type (t, GC_POINTED_TO);
5353 /* The state at this point is read from the state input file or by
5354 parsing source files and optionally augmented by parsing plugin
5355 source files. Write it now. */
5356 if (write_state_filename)
5358 DBGPRINT_COUNT_TYPE ("structures before write_state", structures);
5360 if (hit_error)
5361 fatal ("didn't write state file %s after errors",
5362 write_state_filename);
5364 DBGPRINTF ("before write_state %s", write_state_filename);
5365 write_state (write_state_filename);
5367 if (do_dump)
5368 dump_everything ();
5370 /* After having written the state file we return immediately to
5371 avoid generating any output file. */
5372 if (hit_error)
5373 return 1;
5374 else
5375 return 0;
5379 open_base_files ();
5381 output_header = plugin_output ? plugin_output : header_file;
5382 DBGPRINT_COUNT_TYPE ("structures before write_types outputheader",
5383 structures);
5385 write_types (output_header, structures, &ggc_wtd);
5386 if (plugin_files == NULL)
5388 DBGPRINT_COUNT_TYPE ("structures before write_types headerfil",
5389 structures);
5390 write_types (header_file, structures, &pch_wtd);
5391 write_local (header_file, structures);
5393 write_roots (variables, plugin_files == NULL);
5394 write_rtx_next ();
5395 close_output_files ();
5397 if (do_dump)
5398 dump_everything ();
5400 /* Don't bother about free-ing any input or plugin file, etc. */
5402 if (hit_error)
5403 return 1;
5404 return 0;