Backport from GCC mainline.
[platform/upstream/linaro-gcc.git] / gcc / gengtype.c
1 /* Process source files and output type information.
2    Copyright (C) 2002-2016 Free Software Foundation, Inc.
3
4    This file is part of GCC.
5
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.
10
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.
15
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/>.  */
19
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"
34
35 /* Data types, macros, etc. used only in this file.  */
36
37
38 /* The list of output files.  */
39 outf_p output_files;
40
41 /* The output header file that is included into pretty much every
42    source file.  */
43 outf_p header_file;
44
45
46 /* The name of the file containing the list of input files.  */
47 static char *inputlist;
48
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;
53
54 /* The generated plugin output file and name.  */
55 static outf_p plugin_output;
56 static char *plugin_output_filename;
57
58 /* Our source directory and its length.  */
59 const char *srcdir;
60 size_t srcdir_len;
61
62 /* Variables used for reading and writing the state.  */
63 const char *read_state_filename;
64 const char *write_state_filename;
65
66 /* Variables to help debugging.  */
67 int do_dump;
68 int do_debug;
69
70 /* Level for verbose messages.  */
71 int verbosity_level;
72
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;
76
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.  */
81
82
83 static outf_p create_file (const char *, const char *);
84
85 static const char *get_file_basename (const input_file *);
86 static const char *get_file_realbasename (const input_file *);
87
88 static int get_prefix_langdir_index (const char *);
89 static const char *get_file_langdir (const input_file *);
90
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);
94 \f
95
96 /* Nonzero iff an error has occurred.  */
97 bool hit_error = false;
98
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);
103
104 /* Report an error at POS, printing MSG.  */
105
106 void
107 error_at_line (const struct fileloc *pos, const char *msg, ...)
108 {
109   va_list ap;
110
111   gcc_assert (pos != NULL && pos->file != NULL);
112   va_start (ap, msg);
113
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;
118
119   va_end (ap);
120 }
121 \f
122 /* Locate the ultimate base class of struct S.  */
123
124 static const_type_p
125 get_ultimate_base_class (const_type_p s)
126 {
127   while (s->u.s.base_class)
128     s = s->u.s.base_class;
129   return s;
130 }
131
132 static type_p
133 get_ultimate_base_class (type_p s)
134 {
135   while (s->u.s.base_class)
136     s = s->u.s.base_class;
137   return s;
138 }
139 \f
140 /* Input file handling. */
141
142 /* Table of all input files.  */
143 const input_file **gt_files;
144 size_t num_gt_files;
145
146 /* A number of places use the name of this "gengtype.c" file for a
147    location for things that we can't rely on the source to define.
148    Make sure we can still use pointer comparison on filenames.  */
149 input_file* this_file;
150 /* The "system.h" file is likewise specially useful.  */
151 input_file* system_h_file;
152
153 /* Vector of per-language directories.  */
154 const char **lang_dir_names;
155 size_t num_lang_dirs;
156
157 /* An array of output files suitable for definitions.  There is one
158    BASE_FILES entry for each language.  */
159 static outf_p *base_files;
160
161 /* Utility debugging function, printing the various type counts within
162    a list of types.  Called through the DBGPRINT_COUNT_TYPE macro.  */
163 void
164 dbgprint_count_type_at (const char *fil, int lin, const char *msg, type_p t)
165 {
166   int nb_types = 0, nb_scalar = 0, nb_string = 0;
167   int nb_struct = 0, nb_union = 0, nb_array = 0, nb_pointer = 0;
168   int nb_lang_struct = 0;
169   int nb_user_struct = 0, nb_undefined = 0;
170   type_p p = NULL;
171   for (p = t; p; p = p->next)
172     {
173       nb_types++;
174       switch (p->kind)
175         {
176         case TYPE_UNDEFINED:
177           nb_undefined++;
178         case TYPE_SCALAR:
179           nb_scalar++;
180           break;
181         case TYPE_STRING:
182           nb_string++;
183           break;
184         case TYPE_STRUCT:
185           nb_struct++;
186           break;
187         case TYPE_USER_STRUCT:
188           nb_user_struct++;
189           break;
190         case TYPE_UNION:
191           nb_union++;
192           break;
193         case TYPE_POINTER:
194           nb_pointer++;
195           break;
196         case TYPE_ARRAY:
197           nb_array++;
198           break;
199         case TYPE_LANG_STRUCT:
200           nb_lang_struct++;
201           break;
202         case TYPE_NONE:
203           gcc_unreachable ();
204         }
205     }
206   fprintf (stderr, "\n" "%s:%d: %s: @@%%@@ %d types ::\n",
207            lbasename (fil), lin, msg, nb_types);
208   if (nb_scalar > 0 || nb_string > 0)
209     fprintf (stderr, "@@%%@@ %d scalars, %d strings\n", nb_scalar, nb_string);
210   if (nb_struct > 0 || nb_union > 0)
211     fprintf (stderr, "@@%%@@ %d structs, %d unions\n", nb_struct, nb_union);
212   if (nb_pointer > 0 || nb_array > 0)
213     fprintf (stderr, "@@%%@@ %d pointers, %d arrays\n", nb_pointer, nb_array);
214   if (nb_lang_struct > 0)
215     fprintf (stderr, "@@%%@@ %d lang_structs\n", nb_lang_struct);
216   if (nb_user_struct > 0)
217     fprintf (stderr, "@@%%@@ %d user_structs\n", nb_user_struct);
218   if (nb_undefined > 0)
219     fprintf (stderr, "@@%%@@ %d undefined types\n", nb_undefined);
220   fprintf (stderr, "\n");
221 }
222
223 /* Scan the input file, LIST, and determine how much space we need to
224    store strings in.  Also, count the number of language directories
225    and files.  The numbers returned are overestimates as they does not
226    consider repeated files.  */
227 static size_t
228 measure_input_list (FILE *list)
229 {
230   size_t n = 0;
231   int c;
232   bool atbol = true;
233   num_lang_dirs = 0;
234   num_gt_files = plugin_files ? nb_plugin_files : 0;
235   while ((c = getc (list)) != EOF)
236     {
237       n++;
238       if (atbol)
239         {
240           if (c == '[')
241             num_lang_dirs++;
242           else
243             {
244               /* Add space for a lang_bitmap before the input file name.  */
245               n += sizeof (lang_bitmap);
246               num_gt_files++;
247             }
248           atbol = false;
249         }
250
251       if (c == '\n')
252         atbol = true;
253     }
254
255   rewind (list);
256   return n;
257 }
258
259 /* Read one input line from LIST to HEREP (which is updated).  A
260    pointer to the string is returned via LINEP.  If it was a language
261    subdirectory in square brackets, strip off the square brackets and
262    return true.  Otherwise, leave space before the string for a
263    lang_bitmap, and return false.  At EOF, returns false, does not
264    touch *HEREP, and sets *LINEP to NULL.  POS is used for
265    diagnostics.  */
266 static bool
267 read_input_line (FILE *list, char **herep, char **linep, struct fileloc *pos)
268 {
269   char *here = *herep;
270   char *line;
271   int c = getc (list);
272
273   /* Read over whitespace.  */
274   while (c == '\n' || c == ' ')
275     c = getc (list);
276
277   if (c == EOF)
278     {
279       *linep = 0;
280       return false;
281     }
282   else if (c == '[')
283     {
284       /* No space for a lang_bitmap is necessary.  Discard the '['. */
285       c = getc (list);
286       line = here;
287       while (c != ']' && c != '\n' && c != EOF)
288         {
289           *here++ = c;
290           c = getc (list);
291         }
292       *here++ = '\0';
293
294       if (c == ']')
295         {
296           c = getc (list);      /* eat what should be a newline */
297           if (c != '\n' && c != EOF)
298             error_at_line (pos, "junk on line after language tag [%s]", line);
299         }
300       else
301         error_at_line (pos, "missing close bracket for language tag [%s",
302                        line);
303
304       *herep = here;
305       *linep = line;
306       return true;
307     }
308   else
309     {
310       /* Leave space for a lang_bitmap.  */
311       memset (here, 0, sizeof (lang_bitmap));
312       here += sizeof (lang_bitmap);
313       line = here;
314       do
315         {
316           *here++ = c;
317           c = getc (list);
318         }
319       while (c != EOF && c != '\n');
320       *here++ = '\0';
321       *herep = here;
322       *linep = line;
323       return false;
324     }
325 }
326
327 /* Read the list of input files from LIST and compute all of the
328    relevant tables.  There is one file per line of the list.  At
329    first, all the files on the list are language-generic, but
330    eventually a line will appear which is the name of a language
331    subdirectory in square brackets, like this: [cp].  All subsequent
332    files are specific to that language, until another language
333    subdirectory tag appears.  Files can appear more than once, if
334    they apply to more than one language.  */
335 static void
336 read_input_list (const char *listname)
337 {
338   FILE *list = fopen (listname, "r");
339   if (!list)
340     fatal ("cannot open %s: %s", listname, xstrerror (errno));
341   else
342     {
343       struct fileloc epos;
344       size_t bufsz = measure_input_list (list);
345       char *buf = XNEWVEC (char, bufsz);
346       char *here = buf;
347       char *committed = buf;
348       char *limit = buf + bufsz;
349       char *line;
350       bool is_language;
351       size_t langno = 0;
352       size_t nfiles = 0;
353       lang_bitmap curlangs = (1 << num_lang_dirs) - 1;
354
355       epos.file = input_file_by_name (listname);
356       epos.line = 0;
357
358       lang_dir_names = XNEWVEC (const char *, num_lang_dirs);
359       gt_files = XNEWVEC (const input_file *, num_gt_files);
360
361       for (;;)
362         {
363         next_line:
364           epos.line++;
365           committed = here;
366           is_language = read_input_line (list, &here, &line, &epos);
367           gcc_assert (here <= limit);
368           if (line == 0)
369             break;
370           else if (is_language)
371             {
372               size_t i;
373               gcc_assert (langno <= num_lang_dirs);
374               for (i = 0; i < langno; i++)
375                 if (strcmp (lang_dir_names[i], line) == 0)
376                   {
377                     error_at_line (&epos, "duplicate language tag [%s]",
378                                    line);
379                     curlangs = 1 << i;
380                     here = committed;
381                     goto next_line;
382                   }
383
384               curlangs = 1 << langno;
385               lang_dir_names[langno++] = line;
386             }
387           else
388             {
389               size_t i;
390               input_file *inpf = input_file_by_name (line);
391               gcc_assert (nfiles <= num_gt_files);
392               for (i = 0; i < nfiles; i++)
393                 /* Since the input_file-s are uniquely hash-consed, we
394                    can just compare pointers! */
395                 if (gt_files[i] == inpf)
396                   {
397                     /* Throw away the string we just read, and add the
398                        current language to the existing string's bitmap.  */
399                     lang_bitmap bmap = get_lang_bitmap (inpf);
400                     if (bmap & curlangs)
401                       error_at_line (&epos,
402                                      "file %s specified more than once "
403                                      "for language %s", line,
404                                      langno ==
405                                      0 ? "(all)" : lang_dir_names[langno -
406                                                                   1]);
407
408                     bmap |= curlangs;
409                     set_lang_bitmap (inpf, bmap);
410                     here = committed;
411                     goto next_line;
412                   }
413
414               set_lang_bitmap (inpf, curlangs);
415               gt_files[nfiles++] = inpf;
416             }
417         }
418       /* Update the global counts now that we know accurately how many
419          things there are.  (We do not bother resizing the arrays down.)  */
420       num_lang_dirs = langno;
421       /* Add the plugin files if provided.  */
422       if (plugin_files)
423         {
424           size_t i;
425           for (i = 0; i < nb_plugin_files; i++)
426             gt_files[nfiles++] = plugin_files[i];
427         }
428       num_gt_files = nfiles;
429     }
430
431   /* Sanity check: any file that resides in a language subdirectory
432      (e.g. 'cp') ought to belong to the corresponding language.
433      ??? Still true if for instance ObjC++ is enabled and C++ isn't?
434      (Can you even do that?  Should you be allowed to?)  */
435   {
436     size_t f;
437     for (f = 0; f < num_gt_files; f++)
438       {
439         lang_bitmap bitmap = get_lang_bitmap (gt_files[f]);
440         const char *basename = get_file_basename (gt_files[f]);
441         const char *slashpos = strchr (basename, '/');
442 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
443         const char *slashpos2 = strchr (basename, '\\');
444
445         if (!slashpos || (slashpos2 && slashpos2 < slashpos))
446           slashpos = slashpos2;
447 #endif
448
449         if (slashpos)
450           {
451             size_t l;
452             for (l = 0; l < num_lang_dirs; l++)
453               if ((size_t) (slashpos - basename) == strlen (lang_dir_names[l])
454                   && memcmp (basename, lang_dir_names[l],
455                              strlen (lang_dir_names[l])) == 0)
456                 {
457                   if (!(bitmap & (1 << l)))
458                     error ("%s is in language directory '%s' but is not "
459                            "tagged for that language",
460                            basename, lang_dir_names[l]);
461                   break;
462                 }
463           }
464       }
465   }
466
467   if (ferror (list))
468     fatal ("error reading %s: %s", listname, xstrerror (errno));
469
470   fclose (list);
471 }
472 \f
473
474
475 /* The one and only TYPE_STRING.  */
476
477 struct type string_type = {
478   TYPE_STRING, 0, 0, 0, GC_USED, {0}
479 };
480
481 /* The two and only TYPE_SCALARs.  Their u.scalar_is_char flags are
482    set early in main.  */
483
484 struct type scalar_nonchar = {
485   TYPE_SCALAR, 0, 0, 0, GC_USED, {0}
486 };
487
488 struct type scalar_char = {
489   TYPE_SCALAR, 0, 0, 0, GC_USED, {0}
490 };
491
492 /* Lists of various things.  */
493
494 pair_p typedefs = NULL;
495 type_p structures = NULL;
496 pair_p variables = NULL;
497
498 static type_p adjust_field_tree_exp (type_p t, options_p opt);
499 static type_p adjust_field_rtx_def (type_p t, options_p opt);
500
501 /* Define S as a typedef to T at POS.  */
502
503 void
504 do_typedef (const char *s, type_p t, struct fileloc *pos)
505 {
506   pair_p p;
507
508   /* temporary kludge - gengtype doesn't handle conditionals or
509      macros.  Ignore any attempt to typedef CUMULATIVE_ARGS, unless it
510      is coming from this file (main() sets them up with safe dummy
511      definitions).  */
512   if (!strcmp (s, "CUMULATIVE_ARGS") && pos->file != this_file)
513     return;
514
515   for (p = typedefs; p != NULL; p = p->next)
516     if (strcmp (p->name, s) == 0)
517       {
518         if (p->type != t && strcmp (s, "result_type") != 0)
519           {
520             error_at_line (pos, "type `%s' previously defined", s);
521             error_at_line (&p->line, "previously defined here");
522           }
523         return;
524       }
525
526   p = XNEW (struct pair);
527   p->next = typedefs;
528   p->name = s;
529   p->type = t;
530   p->line = *pos;
531   p->opt = NULL;
532   typedefs = p;
533 }
534
535 /* Define S as a typename of a scalar.  Cannot be used to define
536    typedefs of 'char'.  Note: is also used for pointer-to-function
537    typedefs (which are therefore not treated as pointers).  */
538
539 void
540 do_scalar_typedef (const char *s, struct fileloc *pos)
541 {
542   do_typedef (s, &scalar_nonchar, pos);
543 }
544
545 /* Similar to strtok_r.  */
546
547 static char *
548 strtoken (char *str, const char *delim, char **next)
549 {
550   char *p;
551
552   if (str == NULL)
553     str = *next;
554
555   /* Skip the leading delimiters.  */
556   str += strspn (str, delim);
557   if (*str == '\0')
558     /* This is an empty token.  */
559     return NULL;
560
561   /* The current token.  */
562   p = str;
563
564   /* Find the next delimiter.  */
565   str += strcspn (str, delim);
566   if (*str == '\0')
567     /* This is the last token.  */
568     *next = str;
569   else
570     {
571       /* Terminate the current token.  */
572       *str = '\0';
573       /* Advance to the next token.  */
574       *next = str + 1;
575     }
576
577   return p;
578 }
579
580 /* Define TYPE_NAME to be a user defined type at location POS.  */
581
582 type_p
583 create_user_defined_type (const char *type_name, struct fileloc *pos)
584 {
585   type_p ty = find_structure (type_name, TYPE_USER_STRUCT);
586
587   /* We might have already seen an incomplete decl of the given type,
588      in which case we won't have yet seen a GTY((user)), and the type will
589      only have kind "TYPE_STRUCT".  Mark it as a user struct.  */
590   ty->kind = TYPE_USER_STRUCT;
591
592   ty->u.s.line = *pos;
593   ty->u.s.bitmap = get_lang_bitmap (pos->file);
594   do_typedef (type_name, ty, pos);
595
596   /* If TYPE_NAME specifies a template, create references to the types
597      in the template by pretending that each type is a field of TY.
598      This is needed to make sure that the types referenced by the
599      template are marked as used.  */
600   char *str = xstrdup (type_name);
601   char *open_bracket = strchr (str, '<');
602   if (open_bracket)
603     {
604       /* We only accept simple template declarations (see
605          require_template_declaration), so we only need to parse a
606          comma-separated list of strings, implicitly assumed to
607          be type names, potentially with "*" characters.  */
608       char *arg = open_bracket + 1;
609       /* Workaround -Wmaybe-uninitialized false positive during
610          profiledbootstrap by initializing it.  */
611       char *next = NULL;
612       char *type_id = strtoken (arg, ",>", &next);
613       pair_p fields = 0;
614       while (type_id)
615         {
616           /* Create a new field for every type found inside the template
617              parameter list.  */
618
619           /* Support a single trailing "*" character.  */
620           const char *star = strchr (type_id, '*');
621           int is_ptr = (star != NULL);
622           size_t offset_to_star = star - type_id;
623           if (is_ptr)
624             offset_to_star = star - type_id;
625
626           if (strstr (type_id, "char*"))
627             {
628           type_id = strtoken (0, ",>", &next);
629           continue;
630             }
631
632           char *field_name = xstrdup (type_id);
633
634           type_p arg_type;
635           if (is_ptr)
636             {
637               /* Strip off the first '*' character (and any subsequent text). */
638               *(field_name + offset_to_star) = '\0';
639
640               arg_type = find_structure (field_name, TYPE_STRUCT);
641               arg_type = create_pointer (arg_type);
642             }
643           else
644             arg_type = resolve_typedef (field_name, pos);
645
646           fields = create_field_at (fields, arg_type, field_name, 0, pos);
647           type_id = strtoken (0, ",>", &next);
648         }
649
650       /* Associate the field list to TY.  */
651       ty->u.s.fields = fields;
652     }
653   free (str);
654
655   return ty;
656 }
657
658
659 /* Given a typedef name S, return its associated type.  Return NULL if
660    S is not a registered type name.  */
661
662 static type_p
663 type_for_name (const char *s)
664 {
665   pair_p p;
666
667   /* Special-case support for types within a "gcc::" namespace.  Rather
668      than fully-supporting namespaces, simply strip off the "gcc::" prefix
669      where present.  This allows us to have GTY roots of this form:
670          extern GTY(()) gcc::some_type *some_ptr;
671      where the autogenerated functions will refer to simply "some_type",
672      where they can be resolved into their namespace.  */
673   if (0 == strncmp (s, "gcc::", 5))
674     s += 5;
675
676   for (p = typedefs; p != NULL; p = p->next)
677     if (strcmp (p->name, s) == 0)
678       return p->type;
679   return NULL;
680 }
681
682
683 /* Create an undefined type with name S and location POS.  Return the
684    newly created type.  */
685
686 static type_p
687 create_undefined_type (const char *s, struct fileloc *pos)
688 {
689   type_p ty = find_structure (s, TYPE_UNDEFINED);
690   ty->u.s.line = *pos;
691   ty->u.s.bitmap = get_lang_bitmap (pos->file);
692   do_typedef (s, ty, pos);
693   return ty;
694 }
695
696
697 /* Return the type previously defined for S.  Use POS to report errors.  */
698
699 type_p
700 resolve_typedef (const char *s, struct fileloc *pos)
701 {
702   bool is_template_instance = (strchr (s, '<') != NULL);
703   type_p p = type_for_name (s);
704
705   /* If we did not find a typedef registered, generate a TYPE_UNDEFINED
706      type for regular type identifiers.  If the type identifier S is a
707      template instantiation, however, we treat it as a user defined
708      type.
709
710      FIXME, this is actually a limitation in gengtype.  Supporting
711      template types and their instances would require keeping separate
712      track of the basic types definition and its instances.  This
713      essentially forces all template classes in GC to be marked
714      GTY((user)).  */
715   if (!p)
716     p = (is_template_instance)
717         ? create_user_defined_type (s, pos)
718         : create_undefined_type (s, pos);
719
720   return p;
721 }
722
723 /* Add SUBCLASS to head of linked list of BASE's subclasses.  */
724
725 void add_subclass (type_p base, type_p subclass)
726 {
727   gcc_assert (union_or_struct_p (base));
728   gcc_assert (union_or_struct_p (subclass));
729
730   subclass->u.s.next_sibling_class = base->u.s.first_subclass;
731   base->u.s.first_subclass = subclass;
732 }
733
734 /* Create and return a new structure with tag NAME at POS with fields
735    FIELDS and options O.  The KIND of structure must be one of
736    TYPE_STRUCT, TYPE_UNION or TYPE_USER_STRUCT.  */
737
738 type_p
739 new_structure (const char *name, enum typekind kind, struct fileloc *pos,
740                pair_p fields, options_p o, type_p base_class)
741 {
742   type_p si;
743   type_p s = NULL;
744   lang_bitmap bitmap = get_lang_bitmap (pos->file);
745   bool isunion = (kind == TYPE_UNION);
746
747   gcc_assert (union_or_struct_p (kind));
748
749   for (si = structures; si != NULL; si = si->next)
750     if (strcmp (name, si->u.s.tag) == 0 && UNION_P (si) == isunion)
751       {
752         type_p ls = NULL;
753         if (si->kind == TYPE_LANG_STRUCT)
754           {
755             ls = si;
756
757             for (si = ls->u.s.lang_struct; si != NULL; si = si->next)
758               if (si->u.s.bitmap == bitmap)
759                 s = si;
760           }
761         else if (si->u.s.line.file != NULL && si->u.s.bitmap != bitmap)
762           {
763             ls = si;
764             type_count++;
765             si = XCNEW (struct type);
766             memcpy (si, ls, sizeof (struct type));
767             ls->kind = TYPE_LANG_STRUCT;
768             ls->u.s.lang_struct = si;
769             ls->u.s.fields = NULL;
770             si->next = NULL;
771             si->state_number = -type_count;
772             si->pointer_to = NULL;
773             si->u.s.lang_struct = ls;
774           }
775         else
776           s = si;
777
778         if (ls != NULL && s == NULL)
779           {
780             type_count++;
781             s = XCNEW (struct type);
782             s->state_number = -type_count;
783             s->next = ls->u.s.lang_struct;
784             ls->u.s.lang_struct = s;
785             s->u.s.lang_struct = ls;
786           }
787         break;
788       }
789
790   if (s == NULL)
791     {
792       type_count++;
793       s = XCNEW (struct type);
794       s->state_number = -type_count;
795       s->next = structures;
796       structures = s;
797     }
798
799   if (s->u.s.lang_struct && (s->u.s.lang_struct->u.s.bitmap & bitmap))
800     {
801       error_at_line (pos, "duplicate definition of '%s %s'",
802                      isunion ? "union" : "struct", s->u.s.tag);
803       error_at_line (&s->u.s.line, "previous definition here");
804     }
805
806   s->kind = kind;
807   s->u.s.tag = name;
808   s->u.s.line = *pos;
809   s->u.s.fields = fields;
810   s->u.s.opt = o;
811   s->u.s.bitmap = bitmap;
812   if (s->u.s.lang_struct)
813     s->u.s.lang_struct->u.s.bitmap |= bitmap;
814   s->u.s.base_class = base_class;
815   if (base_class)
816     add_subclass (base_class, s);
817
818   return s;
819 }
820
821 /* Return the previously-defined structure or union with tag NAME,
822    or a new empty structure or union if none was defined previously.
823    The KIND of structure must be one of TYPE_STRUCT, TYPE_UNION or
824    TYPE_USER_STRUCT.  */
825
826 type_p
827 find_structure (const char *name, enum typekind kind)
828 {
829   type_p s;
830   bool isunion = (kind == TYPE_UNION);
831
832   gcc_assert (kind == TYPE_UNDEFINED || union_or_struct_p (kind));
833
834   for (s = structures; s != NULL; s = s->next)
835     if (strcmp (name, s->u.s.tag) == 0 && UNION_P (s) == isunion)
836       return s;
837
838   type_count++;
839   s = XCNEW (struct type);
840   s->next = structures;
841   s->state_number = -type_count;
842   structures = s;
843   s->kind = kind;
844   s->u.s.tag = name;
845   structures = s;
846   return s;
847 }
848
849 /* Return a scalar type with name NAME.  */
850
851 type_p
852 create_scalar_type (const char *name)
853 {
854   if (!strcmp (name, "char") || !strcmp (name, "unsigned char"))
855     return &scalar_char;
856   else
857     return &scalar_nonchar;
858 }
859
860
861 /* Return a pointer to T.  */
862
863 type_p
864 create_pointer (type_p t)
865 {
866   if (!t->pointer_to)
867     {
868       type_p r = XCNEW (struct type);
869       type_count++;
870       r->state_number = -type_count;
871       r->kind = TYPE_POINTER;
872       r->u.p = t;
873       t->pointer_to = r;
874     }
875   return t->pointer_to;
876 }
877
878 /* Return an array of length LEN.  */
879
880 type_p
881 create_array (type_p t, const char *len)
882 {
883   type_p v;
884
885   type_count++;
886   v = XCNEW (struct type);
887   v->kind = TYPE_ARRAY;
888   v->state_number = -type_count;
889   v->u.a.p = t;
890   v->u.a.len = len;
891   return v;
892 }
893
894 /* Return a string options structure with name NAME and info INFO.
895    NEXT is the next option in the chain.  */
896 options_p
897 create_string_option (options_p next, const char *name, const char *info)
898 {
899   options_p o = XNEW (struct options);
900   o->kind = OPTION_STRING;
901   o->next = next;
902   o->name = name;
903   o->info.string = info;
904   return o;
905 }
906
907 /* Create a type options structure with name NAME and info INFO.  NEXT
908    is the next option in the chain.  */
909 options_p
910 create_type_option (options_p next, const char* name, type_p info)
911 {
912   options_p o = XNEW (struct options);
913   o->next = next;
914   o->name = name;
915   o->kind = OPTION_TYPE;
916   o->info.type = info;
917   return o;
918 }
919
920 /* Create a nested pointer options structure with name NAME and info
921    INFO.  NEXT is the next option in the chain.  */
922 options_p
923 create_nested_option (options_p next, const char* name,
924                       struct nested_ptr_data* info)
925 {
926   options_p o;
927   o = XNEW (struct options);
928   o->next = next;
929   o->name = name;
930   o->kind = OPTION_NESTED;
931   o->info.nested = info;
932   return o;
933 }
934
935 /* Return an options structure for a "nested_ptr" option.  */
936 options_p
937 create_nested_ptr_option (options_p next, type_p t,
938                           const char *to, const char *from)
939 {
940   struct nested_ptr_data *d = XNEW (struct nested_ptr_data);
941
942   d->type = adjust_field_type (t, 0);
943   d->convert_to = to;
944   d->convert_from = from;
945   return create_nested_option (next, "nested_ptr", d);
946 }
947
948 /* Add a variable named S of type T with options O defined at POS,
949    to `variables'.  */
950 void
951 note_variable (const char *s, type_p t, options_p o, struct fileloc *pos)
952 {
953   pair_p n;
954   n = XNEW (struct pair);
955   n->name = s;
956   n->type = t;
957   n->line = *pos;
958   n->opt = o;
959   n->next = variables;
960   variables = n;
961 }
962
963 /* Most-general structure field creator.  */
964 static pair_p
965 create_field_all (pair_p next, type_p type, const char *name, options_p opt,
966                   const input_file *inpf, int line)
967 {
968   pair_p field;
969
970   field = XNEW (struct pair);
971   field->next = next;
972   field->type = type;
973   field->name = name;
974   field->opt = opt;
975   field->line.file = inpf;
976   field->line.line = line;
977   return field;
978 }
979
980 /* Create a field that came from the source code we are scanning,
981    i.e. we have a 'struct fileloc', and possibly options; also,
982    adjust_field_type should be called.  */
983 pair_p
984 create_field_at (pair_p next, type_p type, const char *name, options_p opt,
985                  struct fileloc *pos)
986 {
987   return create_field_all (next, adjust_field_type (type, opt),
988                            name, opt, pos->file, pos->line);
989 }
990
991 /* Create a fake field with the given type and name.  NEXT is the next
992    field in the chain.  */
993 #define create_field(next,type,name) \
994     create_field_all (next,type,name, 0, this_file, __LINE__)
995
996 /* Like create_field, but the field is only valid when condition COND
997    is true.  */
998
999 static pair_p
1000 create_optional_field_ (pair_p next, type_p type, const char *name,
1001                         const char *cond, int line)
1002 {
1003   static int id = 1;
1004   pair_p union_fields;
1005   type_p union_type;
1006
1007   /* Create a fake union type with a single nameless field of type TYPE.
1008      The field has a tag of "1".  This allows us to make the presence
1009      of a field of type TYPE depend on some boolean "desc" being true.  */
1010   union_fields = create_field (NULL, type, "");
1011   union_fields->opt = 
1012     create_string_option (union_fields->opt, "dot", "");
1013   union_fields->opt = 
1014     create_string_option (union_fields->opt, "tag", "1");
1015   union_type = 
1016     new_structure (xasprintf ("%s_%d", "fake_union", id++), TYPE_UNION,
1017                    &lexer_line, union_fields, NULL, NULL);
1018
1019   /* Create the field and give it the new fake union type.  Add a "desc"
1020      tag that specifies the condition under which the field is valid.  */
1021   return create_field_all (next, union_type, name,
1022                            create_string_option (0, "desc", cond), 
1023                            this_file, line);
1024 }
1025
1026 #define create_optional_field(next,type,name,cond)      \
1027        create_optional_field_(next,type,name,cond,__LINE__)
1028
1029 /* Reverse a linked list of 'struct pair's in place.  */
1030 pair_p
1031 nreverse_pairs (pair_p list)
1032 {
1033   pair_p prev = 0, p, next;
1034   for (p = list; p; p = next)
1035     {
1036       next = p->next;
1037       p->next = prev;
1038       prev = p;
1039     }
1040   return prev;
1041 }
1042 \f
1043
1044 /* We don't care how long a CONST_DOUBLE is.  */
1045 #define CONST_DOUBLE_FORMAT "ww"
1046 /* We don't want to see codes that are only for generator files.  */
1047 #undef GENERATOR_FILE
1048
1049 enum rtx_code
1050 {
1051 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) ENUM ,
1052 #include "rtl.def"
1053 #undef DEF_RTL_EXPR
1054   NUM_RTX_CODE
1055 };
1056
1057 static const char *const rtx_name[NUM_RTX_CODE] = {
1058 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS)   NAME ,
1059 #include "rtl.def"
1060 #undef DEF_RTL_EXPR
1061 };
1062
1063 static const char *const rtx_format[NUM_RTX_CODE] = {
1064 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS)   FORMAT ,
1065 #include "rtl.def"
1066 #undef DEF_RTL_EXPR
1067 };
1068
1069 static int rtx_next_new[NUM_RTX_CODE];
1070
1071 /* We also need codes and names for insn notes (not register notes).
1072    Note that we do *not* bias the note values here.  */
1073 enum insn_note
1074 {
1075 #define DEF_INSN_NOTE(NAME) NAME,
1076 #include "insn-notes.def"
1077 #undef DEF_INSN_NOTE
1078
1079   NOTE_INSN_MAX
1080 };
1081
1082 /* We must allocate one more entry here, as we use NOTE_INSN_MAX as the
1083    default field for line number notes.  */
1084 static const char *const note_insn_name[NOTE_INSN_MAX + 1] = {
1085 #define DEF_INSN_NOTE(NAME) #NAME,
1086 #include "insn-notes.def"
1087 #undef DEF_INSN_NOTE
1088 };
1089
1090 #undef CONST_DOUBLE_FORMAT
1091 #define GENERATOR_FILE
1092
1093 /* Generate the contents of the rtx_next array.  This really doesn't belong
1094    in gengtype at all, but it's needed for adjust_field_rtx_def.  */
1095
1096 static void
1097 gen_rtx_next (void)
1098 {
1099   int i;
1100   for (i = 0; i < NUM_RTX_CODE; i++)
1101     {
1102       int k;
1103
1104       rtx_next_new[i] = -1;
1105       if (strncmp (rtx_format[i], "uu", 2) == 0)
1106         rtx_next_new[i] = 1;
1107       else if (i == COND_EXEC || i == SET || i == EXPR_LIST || i == INSN_LIST)
1108         rtx_next_new[i] = 1;
1109       else
1110         for (k = strlen (rtx_format[i]) - 1; k >= 0; k--)
1111           if (rtx_format[i][k] == 'e' || rtx_format[i][k] == 'u')
1112             rtx_next_new[i] = k;
1113     }
1114 }
1115
1116 /* Write out the contents of the rtx_next array.  */
1117 static void
1118 write_rtx_next (void)
1119 {
1120   outf_p f = get_output_file_with_visibility (NULL);
1121   int i;
1122   if (!f)
1123     return;
1124
1125   oprintf (f, "\n/* Used to implement the RTX_NEXT macro.  */\n");
1126   oprintf (f, "EXPORTED_CONST unsigned char rtx_next[NUM_RTX_CODE] = {\n");
1127   for (i = 0; i < NUM_RTX_CODE; i++)
1128     if (rtx_next_new[i] == -1)
1129       oprintf (f, "  0,\n");
1130     else
1131       oprintf (f,
1132                "  RTX_HDR_SIZE + %d * sizeof (rtunion),\n", rtx_next_new[i]);
1133   oprintf (f, "};\n");
1134 }
1135
1136 /* Handle `special("rtx_def")'.  This is a special case for field
1137    `fld' of struct rtx_def, which is an array of unions whose values
1138    are based in a complex way on the type of RTL.  */
1139
1140 static type_p
1141 adjust_field_rtx_def (type_p t, options_p ARG_UNUSED (opt))
1142 {
1143   pair_p flds = NULL;
1144   options_p nodot;
1145   int i;
1146   type_p rtx_tp, rtvec_tp, tree_tp, mem_attrs_tp, note_union_tp, scalar_tp;
1147   type_p basic_block_tp, reg_attrs_tp, constant_tp, symbol_union_tp;
1148
1149   if (t->kind != TYPE_UNION)
1150     {
1151       error_at_line (&lexer_line,
1152                      "special `rtx_def' must be applied to a union");
1153       return &string_type;
1154     }
1155
1156   nodot = create_string_option (NULL, "dot", "");
1157
1158   rtx_tp = create_pointer (find_structure ("rtx_def", TYPE_STRUCT));
1159   rtvec_tp = create_pointer (find_structure ("rtvec_def", TYPE_STRUCT));
1160   tree_tp = create_pointer (find_structure ("tree_node", TYPE_UNION));
1161   mem_attrs_tp = create_pointer (find_structure ("mem_attrs", TYPE_STRUCT));
1162   reg_attrs_tp = 
1163     create_pointer (find_structure ("reg_attrs", TYPE_STRUCT));
1164   basic_block_tp = 
1165     create_pointer (find_structure ("basic_block_def", TYPE_STRUCT));
1166   constant_tp =
1167     create_pointer (find_structure ("constant_descriptor_rtx", TYPE_STRUCT));
1168   scalar_tp = &scalar_nonchar;  /* rtunion int */
1169
1170   {
1171     pair_p note_flds = NULL;
1172     int c;
1173
1174     for (c = 0; c <= NOTE_INSN_MAX; c++)
1175       {
1176         switch (c)
1177           {
1178           case NOTE_INSN_MAX:
1179           case NOTE_INSN_DELETED_LABEL:
1180           case NOTE_INSN_DELETED_DEBUG_LABEL:
1181             note_flds = create_field (note_flds, &string_type, "rt_str");
1182             break;
1183
1184           case NOTE_INSN_BLOCK_BEG:
1185           case NOTE_INSN_BLOCK_END:
1186             note_flds = create_field (note_flds, tree_tp, "rt_tree");
1187             break;
1188
1189           case NOTE_INSN_VAR_LOCATION:
1190           case NOTE_INSN_CALL_ARG_LOCATION:
1191             note_flds = create_field (note_flds, rtx_tp, "rt_rtx");
1192             break;
1193
1194           default:
1195             note_flds = create_field (note_flds, scalar_tp, "rt_int");
1196             break;
1197           }
1198         /* NOTE_INSN_MAX is used as the default field for line
1199            number notes.  */
1200         if (c == NOTE_INSN_MAX)
1201           note_flds->opt = 
1202             create_string_option (nodot, "default", "");
1203         else
1204           note_flds->opt = 
1205             create_string_option (nodot, "tag", note_insn_name[c]);
1206       }
1207     note_union_tp = new_structure ("rtx_def_note_subunion", TYPE_UNION,
1208                                    &lexer_line, note_flds, NULL, NULL);
1209   }
1210   /* Create a type to represent the various forms of SYMBOL_REF_DATA.  */
1211   {
1212     pair_p sym_flds;
1213     sym_flds = create_field (NULL, tree_tp, "rt_tree");
1214     sym_flds->opt = create_string_option (nodot, "default", "");
1215     sym_flds = create_field (sym_flds, constant_tp, "rt_constant");
1216     sym_flds->opt = create_string_option (nodot, "tag", "1");
1217     symbol_union_tp = new_structure ("rtx_def_symbol_subunion", TYPE_UNION,
1218                                      &lexer_line, sym_flds, NULL, NULL);
1219   }
1220   for (i = 0; i < NUM_RTX_CODE; i++)
1221     {
1222       pair_p subfields = NULL;
1223       size_t aindex, nmindex;
1224       const char *sname;
1225       type_p substruct;
1226       char *ftag;
1227
1228       for (aindex = 0; aindex < strlen (rtx_format[i]); aindex++)
1229         {
1230           type_p t;
1231           const char *subname;
1232
1233           switch (rtx_format[i][aindex])
1234             {
1235             case '*':
1236             case 'i':
1237             case 'n':
1238             case 'w':
1239             case 'r':
1240               t = scalar_tp;
1241               subname = "rt_int";
1242               break;
1243
1244             case '0':
1245               if (i == MEM && aindex == 1)
1246                 t = mem_attrs_tp, subname = "rt_mem";
1247               else if (i == JUMP_INSN && aindex == 7)
1248                 t = rtx_tp, subname = "rt_rtx";
1249               else if (i == CODE_LABEL && aindex == 4)
1250                 t = scalar_tp, subname = "rt_int";
1251               else if (i == CODE_LABEL && aindex == 3)
1252                 t = rtx_tp, subname = "rt_rtx";
1253               else if (i == LABEL_REF && (aindex == 1 || aindex == 2))
1254                 t = rtx_tp, subname = "rt_rtx";
1255               else if (i == NOTE && aindex == 3)
1256                 t = note_union_tp, subname = "";
1257               else if (i == NOTE && aindex == 4)
1258                 t = scalar_tp, subname = "rt_int";
1259               else if (i == NOTE && aindex >= 6)
1260                 t = scalar_tp, subname = "rt_int";
1261               else if (i == ADDR_DIFF_VEC && aindex == 4)
1262                 t = scalar_tp, subname = "rt_int";
1263               else if (i == VALUE && aindex == 0)
1264                 t = scalar_tp, subname = "rt_int";
1265               else if (i == DEBUG_EXPR && aindex == 0)
1266                 t = tree_tp, subname = "rt_tree";
1267               else if (i == SYMBOL_REF && aindex == 1)
1268                 t = symbol_union_tp, subname = "";
1269               else if (i == JUMP_TABLE_DATA && aindex >= 4)
1270                 t = scalar_tp, subname = "rt_int";
1271               else if (i == BARRIER && aindex >= 2)
1272                 t = scalar_tp, subname = "rt_int";
1273               else if (i == ENTRY_VALUE && aindex == 0)
1274                 t = rtx_tp, subname = "rt_rtx";
1275               else
1276                 {
1277                   error_at_line 
1278                     (&lexer_line,
1279                      "rtx type `%s' has `0' in position %lu, can't handle",
1280                      rtx_name[i], (unsigned long) aindex);
1281                   t = &string_type;
1282                   subname = "rt_int";
1283                 }
1284               break;
1285
1286             case 's':
1287             case 'S':
1288             case 'T':
1289               t = &string_type;
1290               subname = "rt_str";
1291               break;
1292
1293             case 'e':
1294             case 'u':
1295               t = rtx_tp;
1296               subname = "rt_rtx";
1297               break;
1298
1299             case 'E':
1300             case 'V':
1301               t = rtvec_tp;
1302               subname = "rt_rtvec";
1303               break;
1304
1305             case 't':
1306               t = tree_tp;
1307               subname = "rt_tree";
1308               break;
1309
1310             case 'B':
1311               t = basic_block_tp;
1312               subname = "rt_bb";
1313               break;
1314
1315             default:
1316               error_at_line
1317                 (&lexer_line,
1318                  "rtx type `%s' has `%c' in position %lu, can't handle",
1319                  rtx_name[i], rtx_format[i][aindex],
1320                  (unsigned long) aindex);
1321               t = &string_type;
1322               subname = "rt_int";
1323               break;
1324             }
1325
1326           subfields = create_field (subfields, t,
1327                                     xasprintf (".fld[%lu].%s",
1328                                                (unsigned long) aindex,
1329                                                subname));
1330           subfields->opt = nodot;
1331           if (t == note_union_tp)
1332             subfields->opt =
1333               create_string_option (subfields->opt, "desc",
1334                                     "NOTE_KIND (&%0)");
1335           if (t == symbol_union_tp)
1336             subfields->opt = 
1337               create_string_option (subfields->opt, "desc",
1338                                     "CONSTANT_POOL_ADDRESS_P (&%0)");
1339         }
1340
1341       if (i == REG)
1342         subfields = create_field (subfields, reg_attrs_tp, "reg.attrs");
1343
1344       if (i == SYMBOL_REF)
1345         {
1346           /* Add the "block_sym" field if SYMBOL_REF_HAS_BLOCK_INFO_P
1347              holds.  */
1348           type_p field_tp = find_structure ("block_symbol", TYPE_STRUCT);
1349           subfields
1350             = create_optional_field (subfields, field_tp, "block_sym",
1351                                      "SYMBOL_REF_HAS_BLOCK_INFO_P (&%0)");
1352         }
1353
1354       sname = xasprintf ("rtx_def_%s", rtx_name[i]);
1355       substruct = new_structure (sname, TYPE_STRUCT, &lexer_line, subfields,
1356                                  NULL, NULL);
1357
1358       ftag = xstrdup (rtx_name[i]);
1359       for (nmindex = 0; nmindex < strlen (ftag); nmindex++)
1360         ftag[nmindex] = TOUPPER (ftag[nmindex]);
1361       flds = create_field (flds, substruct, "");
1362       flds->opt = create_string_option (nodot, "tag", ftag);
1363     }
1364   return new_structure ("rtx_def_subunion", TYPE_UNION, &lexer_line, flds,
1365                         nodot, NULL);
1366 }
1367
1368 /* Handle `special("tree_exp")'.  This is a special case for
1369    field `operands' of struct tree_exp, which although it claims to contain
1370    pointers to trees, actually sometimes contains pointers to RTL too.
1371    Passed T, the old type of the field, and OPT its options.  Returns
1372    a new type for the field.  */
1373
1374 static type_p
1375 adjust_field_tree_exp (type_p t, options_p opt ATTRIBUTE_UNUSED)
1376 {
1377   pair_p flds;
1378   options_p nodot;
1379
1380   if (t->kind != TYPE_ARRAY)
1381     {
1382       error_at_line (&lexer_line,
1383                      "special `tree_exp' must be applied to an array");
1384       return &string_type;
1385     }
1386
1387   nodot = create_string_option (NULL, "dot", "");
1388
1389   flds = create_field (NULL, t, "");
1390   flds->opt = create_string_option (nodot, "length",
1391                                     "TREE_OPERAND_LENGTH ((tree) &%0)");
1392   flds->opt = create_string_option (flds->opt, "default", "");
1393
1394   return new_structure ("tree_exp_subunion", TYPE_UNION, &lexer_line, flds,
1395                         nodot, NULL);
1396 }
1397
1398 /* Perform any special processing on a type T, about to become the type
1399    of a field.  Return the appropriate type for the field.
1400    At present:
1401    - Converts pointer-to-char, with no length parameter, to TYPE_STRING;
1402    - Similarly for arrays of pointer-to-char;
1403    - Converts structures for which a parameter is provided to
1404      TYPE_PARAM_STRUCT;
1405    - Handles "special" options.
1406 */
1407
1408 type_p
1409 adjust_field_type (type_p t, options_p opt)
1410 {
1411   int length_p = 0;
1412   const int pointer_p = t->kind == TYPE_POINTER;
1413
1414   for (; opt; opt = opt->next)
1415     if (strcmp (opt->name, "length") == 0)
1416       {
1417         if (length_p)
1418           error_at_line (&lexer_line, "duplicate `%s' option", opt->name);
1419         if (t->u.p->kind == TYPE_SCALAR || t->u.p->kind == TYPE_STRING)
1420           {
1421             error_at_line (&lexer_line,
1422                            "option `%s' may not be applied to "
1423                            "arrays of atomic types", opt->name);
1424           }
1425         length_p = 1;
1426       }
1427     else if (strcmp (opt->name, "special") == 0
1428              && opt->kind == OPTION_STRING)
1429       {
1430         const char *special_name = opt->info.string;
1431         if (strcmp (special_name, "tree_exp") == 0)
1432           t = adjust_field_tree_exp (t, opt);
1433         else if (strcmp (special_name, "rtx_def") == 0)
1434           t = adjust_field_rtx_def (t, opt);
1435         else
1436           error_at_line (&lexer_line, "unknown special `%s'", special_name);
1437       }
1438
1439   if (!length_p
1440       && pointer_p && t->u.p->kind == TYPE_SCALAR && t->u.p->u.scalar_is_char)
1441     return &string_type;
1442   if (t->kind == TYPE_ARRAY && t->u.a.p->kind == TYPE_POINTER
1443       && t->u.a.p->u.p->kind == TYPE_SCALAR
1444       && t->u.a.p->u.p->u.scalar_is_char)
1445     return create_array (&string_type, t->u.a.len);
1446
1447   return t;
1448 }
1449 \f
1450
1451 static void set_gc_used_type (type_p, enum gc_used_enum, bool = false);
1452 static void set_gc_used (pair_p);
1453
1454 /* Handle OPT for set_gc_used_type.  */
1455
1456 static void
1457 process_gc_options (options_p opt, enum gc_used_enum level, int *maybe_undef,
1458                     int *length, int *skip, type_p *nested_ptr)
1459 {
1460   options_p o;
1461   for (o = opt; o; o = o->next)
1462     if (strcmp (o->name, "ptr_alias") == 0 && level == GC_POINTED_TO
1463         && o->kind == OPTION_TYPE)
1464       set_gc_used_type (o->info.type,
1465                         GC_POINTED_TO);
1466     else if (strcmp (o->name, "maybe_undef") == 0)
1467       *maybe_undef = 1;
1468     else if (strcmp (o->name, "length") == 0)
1469       *length = 1;
1470     else if (strcmp (o->name, "skip") == 0)
1471       *skip = 1;
1472     else if (strcmp (o->name, "nested_ptr") == 0
1473              && o->kind == OPTION_NESTED)
1474       *nested_ptr = ((const struct nested_ptr_data *) o->info.nested)->type;
1475 }
1476
1477
1478 /* Set the gc_used field of T to LEVEL, and handle the types it references.
1479
1480    If ALLOWED_UNDEFINED_TYPES is true, types of kind TYPE_UNDEFINED
1481    are set to GC_UNUSED.  Otherwise, an error is emitted for
1482    TYPE_UNDEFINED types.  This is used to support user-defined
1483    template types with non-type arguments.
1484
1485    For instance, when we parse a template type with enum arguments
1486    (e.g. MyType<AnotherType, EnumValue>), the parser created two
1487    artificial fields for 'MyType', one for 'AnotherType', the other
1488    one for 'EnumValue'.
1489
1490    At the time that we parse this type we don't know that 'EnumValue'
1491    is really an enum value, so the parser creates a TYPE_UNDEFINED
1492    type for it.  Since 'EnumValue' is never resolved to a known
1493    structure, it will stay with TYPE_UNDEFINED.
1494
1495    Since 'MyType' is a TYPE_USER_STRUCT, we can simply ignore
1496    'EnumValue'.  Generating marking code for it would cause
1497    compilation failures since the marking routines assumes that
1498    'EnumValue' is a type.  */
1499
1500 static void
1501 set_gc_used_type (type_p t, enum gc_used_enum level,
1502                   bool allow_undefined_types)
1503 {
1504   if (t->gc_used >= level)
1505     return;
1506
1507   t->gc_used = level;
1508
1509   switch (t->kind)
1510     {
1511     case TYPE_STRUCT:
1512     case TYPE_UNION:
1513     case TYPE_USER_STRUCT:
1514       {
1515         pair_p f;
1516         int dummy;
1517         type_p dummy2;
1518         bool allow_undefined_field_types = (t->kind == TYPE_USER_STRUCT);
1519
1520         process_gc_options (t->u.s.opt, level, &dummy, &dummy, &dummy,
1521                             &dummy2);
1522
1523         if (t->u.s.base_class)
1524           set_gc_used_type (t->u.s.base_class, level, allow_undefined_types);
1525         /* Anything pointing to a base class might actually be pointing
1526            to a subclass.  */
1527         for (type_p subclass = t->u.s.first_subclass; subclass;
1528              subclass = subclass->u.s.next_sibling_class)
1529           set_gc_used_type (subclass, level, allow_undefined_types);
1530
1531         FOR_ALL_INHERITED_FIELDS(t, f)
1532           {
1533             int maybe_undef = 0;
1534             int length = 0;
1535             int skip = 0;
1536             type_p nested_ptr = NULL;
1537             process_gc_options (f->opt, level, &maybe_undef, &length, &skip,
1538                                 &nested_ptr);
1539
1540             if (nested_ptr && f->type->kind == TYPE_POINTER)
1541               set_gc_used_type (nested_ptr, GC_POINTED_TO);
1542             else if (length && f->type->kind == TYPE_POINTER)
1543               set_gc_used_type (f->type->u.p, GC_USED);
1544             else if (maybe_undef && f->type->kind == TYPE_POINTER)
1545               set_gc_used_type (f->type->u.p, GC_MAYBE_POINTED_TO);
1546             else if (skip)
1547               ;                 /* target type is not used through this field */
1548             else
1549               set_gc_used_type (f->type, GC_USED, allow_undefined_field_types);
1550           }
1551         break;
1552       }
1553
1554     case TYPE_UNDEFINED:
1555       if (level > GC_UNUSED)
1556         {
1557           if (!allow_undefined_types)
1558             error_at_line (&t->u.s.line, "undefined type `%s'", t->u.s.tag);
1559           t->gc_used = GC_UNUSED;
1560         }
1561       break;
1562
1563     case TYPE_POINTER:
1564       set_gc_used_type (t->u.p, GC_POINTED_TO);
1565       break;
1566
1567     case TYPE_ARRAY:
1568       set_gc_used_type (t->u.a.p, GC_USED);
1569       break;
1570
1571     case TYPE_LANG_STRUCT:
1572       for (t = t->u.s.lang_struct; t; t = t->next)
1573         set_gc_used_type (t, level);
1574       break;
1575
1576     default:
1577       break;
1578     }
1579 }
1580
1581 /* Set the gc_used fields of all the types pointed to by VARIABLES.  */
1582
1583 static void
1584 set_gc_used (pair_p variables)
1585 {
1586   int nbvars = 0;
1587   pair_p p;
1588   for (p = variables; p; p = p->next)
1589     {
1590       set_gc_used_type (p->type, GC_USED);
1591       nbvars++;
1592     };
1593   if (verbosity_level >= 2)
1594     printf ("%s used %d GTY-ed variables\n", progname, nbvars);
1595 }
1596 \f
1597 /* File mapping routines.  For each input file, there is one output .c file
1598    (but some output files have many input files), and there is one .h file
1599    for the whole build.  */
1600
1601 /* Output file handling.  */
1602
1603 /* Create and return an outf_p for a new file for NAME, to be called
1604    ONAME.  */
1605
1606 static outf_p
1607 create_file (const char *name, const char *oname)
1608 {
1609   static const char *const hdr[] = {
1610     "   Copyright (C) 2004-2016 Free Software Foundation, Inc.\n",
1611     "\n",
1612     "This file is part of GCC.\n",
1613     "\n",
1614     "GCC is free software; you can redistribute it and/or modify it under\n",
1615     "the terms of the GNU General Public License as published by the Free\n",
1616     "Software Foundation; either version 3, or (at your option) any later\n",
1617     "version.\n",
1618     "\n",
1619     "GCC is distributed in the hope that it will be useful, but WITHOUT ANY\n",
1620     "WARRANTY; without even the implied warranty of MERCHANTABILITY or\n",
1621     "FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n",
1622     "for more details.\n",
1623     "\n",
1624     "You should have received a copy of the GNU General Public License\n",
1625     "along with GCC; see the file COPYING3.  If not see\n",
1626     "<http://www.gnu.org/licenses/>.  */\n",
1627     "\n",
1628     "/* This file is machine generated.  Do not edit.  */\n"
1629   };
1630   outf_p f;
1631   size_t i;
1632
1633   gcc_assert (name != NULL);
1634   gcc_assert (oname != NULL);
1635   f = XCNEW (struct outf);
1636   f->next = output_files;
1637   f->name = oname;
1638   output_files = f;
1639
1640   oprintf (f, "/* Type information for %s.\n", name);
1641   for (i = 0; i < ARRAY_SIZE (hdr); i++)
1642     oprintf (f, "%s", hdr[i]);
1643   return f;
1644 }
1645
1646 /* Print, like fprintf, to O.
1647    N.B. You might think this could be implemented more efficiently
1648    with vsnprintf().  Unfortunately, there are C libraries that
1649    provide that function but without the C99 semantics for its return
1650    value, making it impossible to know how much space is required.  */
1651 void
1652 oprintf (outf_p o, const char *format, ...)
1653 {
1654   char *s;
1655   size_t slength;
1656   va_list ap;
1657
1658   /* In plugin mode, the O could be a NULL pointer, so avoid crashing
1659      in that case.  */
1660   if (!o)
1661     return;
1662
1663   va_start (ap, format);
1664   slength = vasprintf (&s, format, ap);
1665   if (s == NULL || (int) slength < 0)
1666     fatal ("out of memory");
1667   va_end (ap);
1668
1669   if (o->bufused + slength > o->buflength)
1670     {
1671       size_t new_len = o->buflength;
1672       if (new_len == 0)
1673         new_len = 1024;
1674       do
1675         {
1676           new_len *= 2;
1677         }
1678       while (o->bufused + slength >= new_len);
1679       o->buf = XRESIZEVEC (char, o->buf, new_len);
1680       o->buflength = new_len;
1681     }
1682   memcpy (o->buf + o->bufused, s, slength);
1683   o->bufused += slength;
1684   free (s);
1685 }
1686
1687 /* Open the global header file and the language-specific header files.  */
1688
1689 static void
1690 open_base_files (void)
1691 {
1692   size_t i;
1693
1694   if (nb_plugin_files > 0 && plugin_files)
1695     return;
1696
1697   header_file = create_file ("GCC", "gtype-desc.h");
1698
1699   base_files = XNEWVEC (outf_p, num_lang_dirs);
1700
1701   for (i = 0; i < num_lang_dirs; i++)
1702     base_files[i] = create_file (lang_dir_names[i],
1703                                  xasprintf ("gtype-%s.h", lang_dir_names[i]));
1704
1705   /* gtype-desc.c is a little special, so we create it here.  */
1706   {
1707     /* The order of files here matters very much.  */
1708     static const char *const ifiles[] = {
1709       "config.h", "system.h", "coretypes.h", "backend.h", "predict.h", "tree.h",
1710       "rtl.h", "gimple.h", "fold-const.h", "insn-codes.h", "splay-tree.h",
1711       "alias.h", "insn-config.h", "flags.h", "expmed.h", "dojump.h",
1712       "explow.h", "calls.h", "emit-rtl.h", "varasm.h", "stmt.h",
1713       "expr.h", "alloc-pool.h", "cselib.h", "insn-addr.h", "optabs.h",
1714       "libfuncs.h", "debug.h", "internal-fn.h", "gimple-fold.h", "tree-eh.h",
1715       "gimple-iterator.h", "gimple-ssa.h", "tree-cfg.h",
1716       "tree-phinodes.h", "ssa-iterators.h", "stringpool.h", "tree-ssanames.h",
1717       "tree-ssa-loop.h", "tree-ssa-loop-ivopts.h", "tree-ssa-loop-manip.h",
1718       "tree-ssa-loop-niter.h", "tree-into-ssa.h", "tree-dfa.h", 
1719       "tree-ssa.h", "reload.h", "cpp-id-data.h", "tree-chrec.h",
1720       "except.h", "output.h",  "cfgloop.h", "target.h", "lto-streamer.h",
1721       "target-globals.h", "ipa-ref.h", "cgraph.h", "symbol-summary.h",
1722       "ipa-prop.h", "ipa-inline.h", "dwarf2out.h", "omp-low.h", NULL
1723     };
1724     const char *const *ifp;
1725     outf_p gtype_desc_c;
1726
1727     gtype_desc_c = create_file ("GCC", "gtype-desc.c");
1728     for (ifp = ifiles; *ifp; ifp++)
1729       oprintf (gtype_desc_c, "#include \"%s\"\n", *ifp);
1730
1731     /* Make sure we handle "cfun" specially.  */
1732     oprintf (gtype_desc_c, "\n/* See definition in function.h.  */\n");
1733     oprintf (gtype_desc_c, "#undef cfun\n");
1734
1735     oprintf (gtype_desc_c,
1736              "\n"
1737              "/* Types with a \"gcc::\" namespace have it stripped\n"
1738              "   during gengtype parsing.  Provide a \"using\" directive\n"
1739              "   to ensure that the fully-qualified types are found.  */\n"
1740              "using namespace gcc;\n");
1741   }
1742 }
1743
1744 /* For INPF an input file, return the real basename of INPF, with all
1745    the directory components skipped.  */
1746
1747 static const char *
1748 get_file_realbasename (const input_file *inpf)
1749 {
1750   return lbasename (get_input_file_name (inpf));
1751 }
1752
1753 /* For INPF a filename, return the relative path to INPF from
1754    $(srcdir) if the latter is a prefix in INPF, NULL otherwise.  */
1755
1756 const char *
1757 get_file_srcdir_relative_path (const input_file *inpf)
1758 {
1759   const char *f = get_input_file_name (inpf);
1760   if (strlen (f) > srcdir_len
1761       && IS_DIR_SEPARATOR (f[srcdir_len])
1762       && strncmp (f, srcdir, srcdir_len) == 0)
1763     return f + srcdir_len + 1;
1764   else
1765     return NULL;
1766 }
1767
1768 /*  For INPF an input_file, return the relative path to INPF from
1769     $(srcdir) if the latter is a prefix in INPF, or the real basename
1770     of INPF otherwise. */
1771
1772 static const char *
1773 get_file_basename (const input_file *inpf)
1774 {
1775   const char *srcdir_path = get_file_srcdir_relative_path (inpf);
1776
1777   return (srcdir_path != NULL) ? srcdir_path : get_file_realbasename (inpf);
1778 }
1779
1780 /* For F a filename, return the lang_dir_names relative index of the language
1781    directory that is a prefix in F, if any, -1 otherwise.  */
1782
1783 static int
1784 get_prefix_langdir_index (const char *f)
1785 {
1786   size_t f_len = strlen (f);
1787   size_t lang_index;
1788
1789   for (lang_index = 0; lang_index < num_lang_dirs; lang_index++)
1790     {
1791       const char *langdir = lang_dir_names[lang_index];
1792       size_t langdir_len = strlen (langdir);
1793
1794       if (f_len > langdir_len
1795           && IS_DIR_SEPARATOR (f[langdir_len])
1796           && memcmp (f, langdir, langdir_len) == 0)
1797         return lang_index;
1798     }
1799
1800   return -1;
1801 }
1802
1803 /* For INPF an input file, return the name of language directory where
1804    F is located, if any, NULL otherwise.  */
1805
1806 static const char *
1807 get_file_langdir (const input_file *inpf)
1808 {
1809   /* Get the relative path to INPF from $(srcdir) and find the
1810      language by comparing the prefix with language directory names.
1811      If INPF is not even srcdir relative, no point in looking
1812      further.  */
1813
1814   int lang_index;
1815   const char *srcdir_relative_path = get_file_srcdir_relative_path (inpf);
1816   const char *r;
1817
1818   if (!srcdir_relative_path)
1819     return NULL;
1820
1821   lang_index = get_prefix_langdir_index (srcdir_relative_path);
1822   if (lang_index < 0 && strncmp (srcdir_relative_path, "c-family", 8) == 0)
1823     r = "c-family";
1824   else if (lang_index >= 0)
1825     r = lang_dir_names[lang_index];
1826   else
1827     r = NULL;
1828
1829   return r;
1830 }
1831
1832 /* The gt- output file name for INPF.  */
1833
1834 static const char *
1835 get_file_gtfilename (const input_file *inpf)
1836 {
1837   /* Cook up an initial version of the gt- file name from the file real
1838      basename and the language name, if any.  */
1839
1840   const char *basename = get_file_realbasename (inpf);
1841   const char *langdir = get_file_langdir (inpf);
1842
1843   char *result =
1844     (langdir ? xasprintf ("gt-%s-%s", langdir, basename)
1845      : xasprintf ("gt-%s", basename));
1846
1847   /* Then replace all non alphanumerics characters by '-' and change the
1848      extension to ".h".  We expect the input filename extension was at least
1849      one character long.  */
1850
1851   char *s = result;
1852
1853   for (; *s != '.'; s++)
1854     if (!ISALNUM (*s) && *s != '-')
1855       *s = '-';
1856
1857   memcpy (s, ".h", sizeof (".h"));
1858
1859   return result;
1860 }
1861
1862 /* Each input_file has its associated output file outf_p.  The
1863    association is computed by the function
1864    get_output_file_with_visibility.  The associated file is cached
1865    inside input_file in its inpoutf field, so is really computed only
1866    once.  Associated output file paths (i.e. output_name-s) are
1867    computed by a rule based regexp machinery, using the files_rules
1868    array of struct file_rule_st.  A for_name is also computed, giving
1869    the source file name for which the output_file is generated; it is
1870    often the last component of the input_file path.  */
1871
1872
1873 /*
1874  Regexpr machinery to compute the output_name and for_name-s of each
1875  input_file.  We have a sequence of file rules which gives the POSIX
1876  extended regular expression to match an input file path, and two
1877  transformed strings for the corresponding output_name and the
1878  corresponding for_name.  The transformed string contain dollars: $0
1879  is replaced by the entire match, $1 is replaced by the substring
1880  matching the first parenthesis in the regexp, etc.  And $$ is replaced
1881  by a single verbatim dollar.  The rule order is important.  The
1882  general case is last, and the particular cases should come before.
1883  An action routine can, when needed, update the out_name & for_name
1884  and/or return the appropriate output file.  It is invoked only when a
1885  rule is triggered.  When a rule is triggered, the output_name and
1886  for_name are computed using their transform string in while $$, $0,
1887  $1, ... are suitably replaced.  If there is an action, it is called.
1888  In some few cases, the action can directly return the outf_p, but
1889  usually it just updates the output_name and for_name so should free
1890  them before replacing them.  The get_output_file_with_visibility
1891  function creates an outf_p only once per each output_name, so it
1892  scans the output_files list for previously seen output file names.
1893  */
1894
1895 /* Signature of actions in file rules.  */
1896 typedef outf_p (frul_actionrout_t) (input_file*, char**, char**);
1897
1898
1899 struct file_rule_st {
1900   const char* frul_srcexpr;     /* Source string for regexp.  */
1901   int frul_rflags;              /* Flags passed to regcomp, usually
1902                                  * REG_EXTENDED.  */
1903   regex_t* frul_re;             /* Compiled regular expression
1904                                    obtained by regcomp.  */
1905   const char* frul_tr_out;      /* Transformation string for making
1906                                  * the output_name, with $1 ... $9 for
1907                                  * subpatterns and $0 for the whole
1908                                  * matched filename.  */
1909   const char* frul_tr_for;      /* Tranformation string for making the
1910                                    for_name.  */
1911   frul_actionrout_t* frul_action; /* The action, if non null, is
1912                                    * called once the rule matches, on
1913                                    * the transformed out_name &
1914                                    * for_name.  It could change them
1915                                    * and/or give the output file.  */
1916 };
1917
1918 /* File rule action handling *.h files.  */
1919 static outf_p header_dot_h_frul (input_file*, char**, char**);
1920
1921 /* File rule action handling *.c files.  */
1922 static outf_p source_dot_c_frul (input_file*, char**, char**);
1923
1924 #define NULL_REGEX (regex_t*)0
1925
1926 /* The prefix in our regexp-s matching the directory.  */
1927 #define DIR_PREFIX_REGEX "^(([^/]*/)*)"
1928
1929 #define NULL_FRULACT (frul_actionrout_t*)0
1930
1931 /* The array of our rules governing file name generation.  Rules order
1932    matters, so change with extreme care!  */
1933
1934 struct file_rule_st files_rules[] = {
1935   /* The general rule assumes that files in subdirectories belong to a
1936      particular front-end, and files not in subdirectories are shared.
1937      The following rules deal with exceptions - files that are in
1938      subdirectories and yet are shared, and files that are top-level,
1939      but are not shared.  */
1940
1941   /* the c-family/ source directory is special.  */
1942   { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.c$",
1943     REG_EXTENDED, NULL_REGEX,
1944     "gt-c-family-$3.h", "c-family/$3.c", NULL_FRULACT},
1945
1946   { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.h$",
1947     REG_EXTENDED, NULL_REGEX,
1948     "gt-c-family-$3.h", "c-family/$3.h", NULL_FRULACT},
1949
1950   /* Both c-lang.h & c-tree.h gives gt-c-c-decl.h for c-decl.c !  */
1951   { DIR_PREFIX_REGEX "c/c-lang\\.h$",
1952     REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.c", NULL_FRULACT},
1953
1954   { DIR_PREFIX_REGEX "c/c-tree\\.h$",
1955     REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.c", NULL_FRULACT},
1956
1957   /* cp/cp-tree.h gives gt-cp-tree.h for cp/tree.c !  */
1958   { DIR_PREFIX_REGEX "cp/cp-tree\\.h$",
1959     REG_EXTENDED, NULL_REGEX,
1960     "gt-cp-tree.h", "cp/tree.c", NULL_FRULACT },
1961
1962   /* cp/decl.h & cp/decl.c gives gt-cp-decl.h for cp/decl.c !  */
1963   { DIR_PREFIX_REGEX "cp/decl\\.[ch]$",
1964     REG_EXTENDED, NULL_REGEX,
1965     "gt-cp-decl.h", "cp/decl.c", NULL_FRULACT },
1966
1967   /* cp/name-lookup.h gives gt-cp-name-lookup.h for cp/name-lookup.c !  */
1968   { DIR_PREFIX_REGEX "cp/name-lookup\\.h$",
1969     REG_EXTENDED, NULL_REGEX,
1970     "gt-cp-name-lookup.h", "cp/name-lookup.c", NULL_FRULACT },
1971
1972   /* cp/parser.h gives gt-cp-parser.h for cp/parser.c !  */
1973   { DIR_PREFIX_REGEX "cp/parser\\.h$",
1974     REG_EXTENDED, NULL_REGEX,
1975     "gt-cp-parser.h", "cp/parser.c", NULL_FRULACT },
1976
1977   /* objc/objc-act.h gives gt-objc-objc-act.h for objc/objc-act.c !  */
1978   { DIR_PREFIX_REGEX "objc/objc-act\\.h$",
1979     REG_EXTENDED, NULL_REGEX,
1980     "gt-objc-objc-act.h", "objc/objc-act.c", NULL_FRULACT },
1981
1982   /* objc/objc-map.h gives gt-objc-objc-map.h for objc/objc-map.c !  */
1983   { DIR_PREFIX_REGEX "objc/objc-map\\.h$",
1984     REG_EXTENDED, NULL_REGEX,
1985     "gt-objc-objc-map.h", "objc/objc-map.c", NULL_FRULACT },
1986
1987   /* General cases.  For header *.h and source *.c or *.cc files, we
1988    * need special actions to handle the language.  */
1989
1990   /* Source *.c files are using get_file_gtfilename to compute their
1991      output_name and get_file_basename to compute their for_name
1992      through the source_dot_c_frul action.  */
1993   { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.c$",
1994     REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.c", source_dot_c_frul},
1995
1996   /* Source *.cc files are using get_file_gtfilename to compute their
1997      output_name and get_file_basename to compute their for_name
1998      through the source_dot_c_frul action.  */
1999   { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.cc$",
2000     REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.cc", source_dot_c_frul},
2001
2002   /* Common header files get "gtype-desc.c" as their output_name,
2003    * while language specific header files are handled specially.  So
2004    * we need the header_dot_h_frul action.  */
2005   { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.h$",
2006     REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.h", header_dot_h_frul},
2007
2008   { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.in$",
2009     REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.in", NULL_FRULACT},
2010
2011   /* Mandatory null last entry signaling end of rules.  */
2012   {NULL, 0, NULL_REGEX, NULL, NULL, NULL_FRULACT}
2013 };
2014
2015 /* Special file rules action for handling *.h header files.  It gives
2016    "gtype-desc.c" for common headers and corresponding output
2017    files for language-specific header files.  */
2018 static outf_p
2019 header_dot_h_frul (input_file* inpf, char**poutname,
2020                    char**pforname ATTRIBUTE_UNUSED)
2021 {
2022   const char *basename = 0;
2023   int lang_index = 0;
2024   DBGPRINTF ("inpf %p inpname %s outname %s forname %s",
2025              (void*) inpf, get_input_file_name (inpf),
2026              *poutname, *pforname);
2027   basename = get_file_basename (inpf);
2028   lang_index = get_prefix_langdir_index (basename);
2029   DBGPRINTF ("basename %s lang_index %d", basename, lang_index);
2030
2031   if (lang_index >= 0)
2032     {
2033       /* The header is language specific.  Given output_name &
2034          for_name remains unchanged.  The base_files array gives the
2035          outf_p.  */
2036       DBGPRINTF ("header_dot_h found language specific @ %p '%s'",
2037                  (void*) base_files[lang_index],
2038                  (base_files[lang_index])->name);
2039       return base_files[lang_index];
2040     }
2041   else
2042     {
2043       /* The header is common to all front-end languages.  So
2044          output_name is "gtype-desc.c" file.  The calling function
2045          get_output_file_with_visibility will find its outf_p.  */
2046       free (*poutname);
2047       *poutname = xstrdup ("gtype-desc.c");
2048       DBGPRINTF ("special 'gtype-desc.c' for inpname %s",
2049                  get_input_file_name (inpf));
2050       return NULL;
2051     }
2052 }
2053
2054
2055 /* Special file rules action for handling *.c source files using
2056  * get_file_gtfilename to compute their output_name and
2057  * get_file_basename to compute their for_name.  The output_name is
2058  * gt-<LANG>-<BASE>.h for language specific source files, and
2059  * gt-<BASE>.h for common source files.  */
2060 static outf_p
2061 source_dot_c_frul (input_file* inpf, char**poutname, char**pforname)
2062 {
2063   char *newbasename = CONST_CAST (char*, get_file_basename (inpf));
2064   char *newoutname = CONST_CAST (char*, get_file_gtfilename (inpf));
2065   DBGPRINTF ("inpf %p inpname %s original outname %s forname %s",
2066              (void*) inpf, get_input_file_name (inpf),
2067              *poutname, *pforname);
2068   DBGPRINTF ("newoutname %s", newoutname);
2069   DBGPRINTF ("newbasename %s", newbasename);
2070   free (*poutname);
2071   free (*pforname);
2072   *poutname = newoutname;
2073   *pforname = newbasename;
2074   return NULL;
2075 }
2076
2077 /* Utility function for get_output_file_with_visibility which returns
2078  * a malloc-ed substituted string using TRS on matching of the FILNAM
2079  * file name, using the PMATCH array.  */
2080 static char*
2081 matching_file_name_substitute (const char *filnam, regmatch_t pmatch[10],
2082                                const char *trs)
2083 {
2084   struct obstack str_obstack;
2085   char *str = NULL;
2086   char *rawstr = NULL;
2087   const char *pt = NULL;
2088   DBGPRINTF ("filnam %s", filnam);
2089   obstack_init (&str_obstack);
2090   for (pt = trs; *pt; pt++) {
2091     char c = *pt;
2092     if (c == '$')
2093       {
2094         if (pt[1] == '$')
2095           {
2096             /* A double dollar $$ is substituted by a single verbatim
2097                dollar, but who really uses dollar signs in file
2098                paths? */
2099             obstack_1grow (&str_obstack, '$');
2100           }
2101         else if (ISDIGIT (pt[1]))
2102           {
2103             /* Handle $0 $1 ... $9 by appropriate substitution.  */
2104             int dolnum = pt[1] - '0';
2105             int so = pmatch[dolnum].rm_so;
2106             int eo = pmatch[dolnum].rm_eo;
2107             DBGPRINTF ("so=%d eo=%d dolnum=%d", so, eo, dolnum);
2108             if (so>=0 && eo>=so)
2109               obstack_grow (&str_obstack, filnam + so, eo - so);
2110           }
2111         else
2112           {
2113             /* This can happen only when files_rules is buggy! */
2114             gcc_unreachable ();
2115           }
2116         /* Always skip the character after the dollar.  */
2117         pt++;
2118       }
2119     else
2120       obstack_1grow (&str_obstack, c);
2121   }
2122   obstack_1grow (&str_obstack, '\0');
2123   rawstr = XOBFINISH (&str_obstack, char *);
2124   str = xstrdup (rawstr);
2125   obstack_free (&str_obstack, NULL);
2126   DBGPRINTF ("matched replacement %s", str);
2127   rawstr = NULL;
2128   return str;
2129 }
2130
2131
2132 /* An output file, suitable for definitions, that can see declarations
2133    made in INPF and is linked into every language that uses INPF.
2134    Since the result is cached inside INPF, that argument cannot be
2135    declared constant, but is "almost" constant. */
2136
2137 outf_p
2138 get_output_file_with_visibility (input_file *inpf)
2139 {
2140   outf_p r;
2141   char *for_name = NULL;
2142   char *output_name = NULL;
2143   const char* inpfname;
2144
2145   /* This can happen when we need a file with visibility on a
2146      structure that we've never seen.  We have to just hope that it's
2147      globally visible.  */
2148   if (inpf == NULL)
2149     inpf = system_h_file;
2150
2151   /* The result is cached in INPF, so return it if already known.  */
2152   if (inpf->inpoutf)
2153     return inpf->inpoutf;
2154
2155   /* In plugin mode, return NULL unless the input_file is one of the
2156      plugin_files.  */
2157   if (plugin_files)
2158     {
2159       size_t i;
2160       for (i = 0; i < nb_plugin_files; i++)
2161         if (inpf == plugin_files[i]) 
2162           {
2163             inpf->inpoutf = plugin_output;
2164             return plugin_output;
2165           }
2166
2167       return NULL;
2168     }
2169
2170   inpfname = get_input_file_name (inpf);
2171
2172   /* Try each rule in sequence in files_rules until one is triggered. */
2173   {
2174     int rulix = 0;
2175     DBGPRINTF ("passing input file @ %p named %s through the files_rules",
2176                (void*) inpf, inpfname);
2177
2178     for (; files_rules[rulix].frul_srcexpr != NULL; rulix++)
2179       {
2180         DBGPRINTF ("rulix#%d srcexpr %s",
2181                    rulix, files_rules[rulix].frul_srcexpr);
2182
2183         if (!files_rules[rulix].frul_re)
2184           {
2185             /* Compile the regexpr lazily.  */
2186             int err = 0;
2187             files_rules[rulix].frul_re = XCNEW (regex_t);
2188             err = regcomp (files_rules[rulix].frul_re,
2189                            files_rules[rulix].frul_srcexpr,
2190                            files_rules[rulix].frul_rflags);
2191             if (err)
2192               {
2193                 /* The regular expression compilation fails only when
2194                    file_rules is buggy.  */
2195                 gcc_unreachable ();
2196               }
2197           }
2198
2199         output_name = NULL;
2200         for_name = NULL;
2201
2202         /* Match the regexpr and trigger the rule if matched.  */
2203         {
2204           /* We have exactly ten pmatch-s, one for each $0, $1, $2,
2205              $3, ... $9.  */
2206           regmatch_t pmatch[10];
2207           memset (pmatch, 0, sizeof (pmatch));
2208           if (!regexec (files_rules[rulix].frul_re,
2209                         inpfname, 10, pmatch, 0))
2210             {
2211               DBGPRINTF ("input @ %p filename %s matched rulix#%d pattern %s",
2212                          (void*) inpf, inpfname, rulix,
2213                          files_rules[rulix].frul_srcexpr);
2214               for_name =
2215                 matching_file_name_substitute (inpfname, pmatch,
2216                                                files_rules[rulix].frul_tr_for);
2217               DBGPRINTF ("for_name %s", for_name);
2218               output_name =
2219                 matching_file_name_substitute (inpfname, pmatch,
2220                                                files_rules[rulix].frul_tr_out);
2221               DBGPRINTF ("output_name %s", output_name);
2222               if (files_rules[rulix].frul_action)
2223                 {
2224                   /* Invoke our action routine.  */
2225                   outf_p of = NULL;
2226                   DBGPRINTF ("before action rulix#%d output_name %s for_name %s",
2227                              rulix, output_name, for_name);
2228                   of =
2229                     (files_rules[rulix].frul_action) (inpf,
2230                                                       &output_name, &for_name);
2231                   DBGPRINTF ("after action rulix#%d of=%p output_name %s for_name %s",
2232                              rulix, (void*)of, output_name, for_name);
2233                   /* If the action routine returned something, give it back
2234                      immediately and cache it in inpf.  */
2235                   if (of)
2236                     {
2237                       inpf->inpoutf = of;
2238                       return of;
2239                     }
2240                 }
2241               /* The rule matched, and had no action, or that action did
2242                  not return any output file but could have changed the
2243                  output_name or for_name.  We break out of the loop on the
2244                  files_rules.  */
2245               break;
2246             }
2247           else
2248             {
2249               /* The regexpr did not match.  */
2250               DBGPRINTF ("rulix#%d did not match %s pattern %s",
2251                          rulix, inpfname, files_rules[rulix].frul_srcexpr);
2252               continue;
2253             }
2254         }
2255       }
2256   }
2257   if (!output_name || !for_name)
2258     {
2259       /* This should not be possible, and could only happen if the
2260          files_rules is incomplete or buggy.  */
2261       fatal ("failed to compute output name for %s", inpfname);
2262     }
2263
2264   /* Look through to see if we've ever seen this output filename
2265      before.  If found, cache the result in inpf.  */
2266   for (r = output_files; r; r = r->next)
2267     if (filename_cmp (r->name, output_name) == 0)
2268       {
2269         inpf->inpoutf = r;
2270         DBGPRINTF ("found r @ %p for output_name %s for_name %s", (void*)r,
2271                    output_name, for_name);
2272         return r;
2273       }
2274
2275   /* If not found, create it, and cache it in inpf.  */
2276   r = create_file (for_name, output_name);
2277
2278   gcc_assert (r && r->name);
2279   DBGPRINTF ("created r @ %p for output_name %s for_name %s", (void*) r,
2280              output_name, for_name);
2281   inpf->inpoutf = r;
2282   return r;
2283
2284
2285 }
2286
2287 /* The name of an output file, suitable for definitions, that can see
2288    declarations made in INPF and is linked into every language that
2289    uses INPF.  */
2290
2291 const char *
2292 get_output_file_name (input_file* inpf)
2293 {
2294   outf_p o = get_output_file_with_visibility (inpf);
2295   if (o)
2296     return o->name;
2297   return NULL;
2298 }
2299
2300 /* Check if existing file is equal to the in memory buffer. */
2301
2302 static bool
2303 is_file_equal (outf_p of)
2304 {
2305   FILE *newfile = fopen (of->name, "r");
2306   size_t i;
2307   bool equal;
2308   if (newfile == NULL)
2309     return false;
2310
2311   equal = true;
2312   for (i = 0; i < of->bufused; i++)
2313     {
2314       int ch;
2315       ch = fgetc (newfile);
2316       if (ch == EOF || ch != (unsigned char) of->buf[i])
2317         {
2318           equal = false;
2319           break;
2320         }
2321     }
2322   if (equal && EOF != fgetc (newfile))
2323     equal = false;
2324   fclose (newfile);
2325   return equal;
2326 }
2327
2328 /* Copy the output to its final destination,
2329    but don't unnecessarily change modification times.  */
2330
2331 static void
2332 close_output_files (void)
2333 {
2334   int nbwrittenfiles = 0;
2335   outf_p of;
2336
2337   for (of = output_files; of; of = of->next)
2338     {
2339       if (!is_file_equal (of))
2340         {
2341           FILE *newfile = NULL;
2342           char *backupname = NULL;
2343           /* Back up the old version of the output file gt-FOO.c as
2344              BACKUPDIR/gt-FOO.c~ if we have a backup directory.  */
2345           if (backup_dir)
2346             {
2347               backupname = concat (backup_dir, "/",
2348                                    lbasename (of->name), "~", NULL);
2349               if (!access (of->name, F_OK) && rename (of->name, backupname))
2350                 fatal ("failed to back up %s as %s: %s",
2351                        of->name, backupname, xstrerror (errno));
2352             }
2353
2354           newfile = fopen (of->name, "w");
2355           if (newfile == NULL)
2356             fatal ("opening output file %s: %s", of->name, xstrerror (errno));
2357           if (fwrite (of->buf, 1, of->bufused, newfile) != of->bufused)
2358             fatal ("writing output file %s: %s", of->name, xstrerror (errno));
2359           if (fclose (newfile) != 0)
2360             fatal ("closing output file %s: %s", of->name, xstrerror (errno));
2361           nbwrittenfiles++;
2362           if (verbosity_level >= 2 && backupname)
2363             printf ("%s wrote #%-3d %s backed-up in %s\n",
2364                     progname, nbwrittenfiles, of->name, backupname);
2365           else if (verbosity_level >= 1)
2366             printf ("%s write #%-3d %s\n", progname, nbwrittenfiles, of->name);
2367           free (backupname);
2368         }
2369       else 
2370         { 
2371           /* output file remains unchanged. */
2372           if (verbosity_level >= 2)
2373             printf ("%s keep %s\n", progname, of->name);
2374         }
2375       free (of->buf);
2376       of->buf = NULL;
2377       of->bufused = of->buflength = 0;
2378     }
2379   if (verbosity_level >= 1)
2380     printf ("%s wrote %d files.\n", progname, nbwrittenfiles);
2381 }
2382 \f
2383 struct flist
2384 {
2385   struct flist *next;
2386   int started_p;
2387   const input_file* file;
2388   outf_p f;
2389 };
2390
2391 struct walk_type_data;
2392
2393 /* For scalars and strings, given the item in 'val'.
2394    For structures, given a pointer to the item in 'val'.
2395    For misc. pointers, given the item in 'val'.
2396 */
2397 typedef void (*process_field_fn) (type_p f, const struct walk_type_data * p);
2398 typedef void (*func_name_fn) (type_p s, const struct walk_type_data * p);
2399
2400 /* Parameters for write_types.  */
2401
2402 struct write_types_data
2403 {
2404   const char *prefix;
2405   const char *param_prefix;
2406   const char *subfield_marker_routine;
2407   const char *marker_routine;
2408   const char *reorder_note_routine;
2409   const char *comment;
2410   enum write_types_kinds kind;
2411 };
2412
2413 static void output_escaped_param (struct walk_type_data *d,
2414                                   const char *, const char *);
2415 static void output_mangled_typename (outf_p, const_type_p);
2416 static void walk_type (type_p t, struct walk_type_data *d);
2417 static void write_func_for_structure (type_p orig_s, type_p s,
2418                                       const struct write_types_data *wtd);
2419 static void write_types_process_field
2420   (type_p f, const struct walk_type_data *d);
2421 static void write_types (outf_p output_header,
2422                          type_p structures,
2423                          const struct write_types_data *wtd);
2424 static void write_types_local_process_field
2425   (type_p f, const struct walk_type_data *d);
2426 static void write_local_func_for_structure (const_type_p orig_s, type_p s);
2427 static void write_local (outf_p output_header,
2428                          type_p structures);
2429 static int contains_scalar_p (type_p t);
2430 static void put_mangled_filename (outf_p, const input_file *);
2431 static void finish_root_table (struct flist *flp, const char *pfx,
2432                                const char *tname, const char *lastname,
2433                                const char *name);
2434 static void write_root (outf_p, pair_p, type_p, const char *, int,
2435                         struct fileloc *, bool);
2436 static void write_array (outf_p f, pair_p v,
2437                          const struct write_types_data *wtd);
2438 static void write_roots (pair_p, bool);
2439
2440 /* Parameters for walk_type.  */
2441
2442 struct walk_type_data
2443 {
2444   process_field_fn process_field;
2445   const void *cookie;
2446   outf_p of;
2447   options_p opt;
2448   const char *val;
2449   const char *prev_val[4];
2450   int indent;
2451   int counter;
2452   const struct fileloc *line;
2453   lang_bitmap bitmap;
2454   int used_length;
2455   type_p orig_s;
2456   const char *reorder_fn;
2457   bool needs_cast_p;
2458   bool fn_wants_lvalue;
2459   bool in_record_p;
2460   int loopcounter;
2461   bool in_ptr_field;
2462   bool have_this_obj;
2463 };
2464
2465
2466 /* Given a string TYPE_NAME, representing a C++ typename, return a valid
2467    pre-processor identifier to use in a #define directive.  This replaces
2468    special characters used in C++ identifiers like '>', '<' and ':' with
2469    '_'.
2470
2471    If no C++ special characters are found in TYPE_NAME, return
2472    TYPE_NAME.  Otherwise, return a copy of TYPE_NAME with the special
2473    characters replaced with '_'.  In this case, the caller is
2474    responsible for freeing the allocated string.  */
2475
2476 static const char *
2477 filter_type_name (const char *type_name)
2478 {
2479   if (strchr (type_name, '<') || strchr (type_name, ':'))
2480     {
2481       size_t i;
2482       char *s = xstrdup (type_name);
2483       for (i = 0; i < strlen (s); i++)
2484         if (s[i] == '<' || s[i] == '>' || s[i] == ':' || s[i] == ','
2485             || s[i] == '*')
2486           s[i] = '_';
2487       return s;
2488     }
2489   else
2490     return type_name;
2491 }
2492
2493
2494 /* Print a mangled name representing T to OF.  */
2495
2496 static void
2497 output_mangled_typename (outf_p of, const_type_p t)
2498 {
2499   if (t == NULL)
2500     oprintf (of, "Z");
2501   else
2502     switch (t->kind)
2503       {
2504       case TYPE_NONE:
2505       case TYPE_UNDEFINED:
2506         gcc_unreachable ();
2507         break;
2508       case TYPE_POINTER:
2509         oprintf (of, "P");
2510         output_mangled_typename (of, t->u.p);
2511         break;
2512       case TYPE_SCALAR:
2513         oprintf (of, "I");
2514         break;
2515       case TYPE_STRING:
2516         oprintf (of, "S");
2517         break;
2518       case TYPE_STRUCT:
2519       case TYPE_UNION:
2520       case TYPE_LANG_STRUCT:
2521       case TYPE_USER_STRUCT:
2522         {
2523           /* For references to classes within an inheritance hierarchy,
2524              only ever reference the ultimate base class, since only
2525              it will have gt_ functions.  */
2526           t = get_ultimate_base_class (t);
2527           const char *id_for_tag = filter_type_name (t->u.s.tag);
2528           oprintf (of, "%lu%s", (unsigned long) strlen (id_for_tag),
2529                    id_for_tag);
2530           if (id_for_tag != t->u.s.tag)
2531             free (CONST_CAST (char *, id_for_tag));
2532         }
2533         break;
2534       case TYPE_ARRAY:
2535         gcc_unreachable ();
2536       }
2537 }
2538
2539 /* Print PARAM to D->OF processing escapes.  D->VAL references the
2540    current object, D->PREV_VAL the object containing the current
2541    object, ONAME is the name of the option and D->LINE is used to
2542    print error messages.  */
2543
2544 static void
2545 output_escaped_param (struct walk_type_data *d, const char *param,
2546                       const char *oname)
2547 {
2548   const char *p;
2549
2550   for (p = param; *p; p++)
2551     if (*p != '%')
2552       oprintf (d->of, "%c", *p);
2553     else
2554       switch (*++p)
2555         {
2556         case 'h':
2557           oprintf (d->of, "(%s)", d->prev_val[2]);
2558           break;
2559         case '0':
2560           oprintf (d->of, "(%s)", d->prev_val[0]);
2561           break;
2562         case '1':
2563           oprintf (d->of, "(%s)", d->prev_val[1]);
2564           break;
2565         case 'a':
2566           {
2567             const char *pp = d->val + strlen (d->val);
2568             while (pp[-1] == ']')
2569               while (*pp != '[')
2570                 pp--;
2571             oprintf (d->of, "%s", pp);
2572           }
2573           break;
2574         default:
2575           error_at_line (d->line, "`%s' option contains bad escape %c%c",
2576                          oname, '%', *p);
2577         }
2578 }
2579
2580 const char *
2581 get_string_option (options_p opt, const char *key)
2582 {
2583   for (; opt; opt = opt->next)
2584     if (strcmp (opt->name, key) == 0)
2585       return opt->info.string;
2586   return NULL;
2587 }
2588
2589 /* Machinery for avoiding duplicate tags within switch statements.  */
2590 struct seen_tag
2591 {
2592   const char *tag;
2593   struct seen_tag *next;
2594 };
2595
2596 int
2597 already_seen_tag (struct seen_tag *seen_tags, const char *tag)
2598 {
2599   /* Linear search, so O(n^2), but n is currently small.  */
2600   while (seen_tags)
2601     {
2602       if (!strcmp (seen_tags->tag, tag))
2603         return 1;
2604       seen_tags = seen_tags->next;
2605     }
2606   /* Not yet seen this tag. */
2607   return 0;
2608 }
2609
2610 void
2611 mark_tag_as_seen (struct seen_tag **seen_tags, const char *tag)
2612 {
2613   /* Add to front of linked list. */
2614   struct seen_tag *new_node = XCNEW (struct seen_tag);
2615   new_node->tag = tag;
2616   new_node->next = *seen_tags;
2617   *seen_tags = new_node;
2618 }
2619
2620 static void
2621 walk_subclasses (type_p base, struct walk_type_data *d,
2622                  struct seen_tag **seen_tags)
2623 {
2624   for (type_p sub = base->u.s.first_subclass; sub != NULL;
2625        sub = sub->u.s.next_sibling_class)
2626     {
2627       const char *type_tag = get_string_option (sub->u.s.opt, "tag");
2628       if (type_tag && !already_seen_tag (*seen_tags, type_tag))
2629         {
2630           mark_tag_as_seen (seen_tags, type_tag);
2631           oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
2632           d->indent += 2;
2633           oprintf (d->of, "%*s{\n", d->indent, "");
2634           d->indent += 2;
2635           oprintf (d->of, "%*s%s *sub = static_cast <%s *> (x);\n",
2636                    d->indent, "", sub->u.s.tag, sub->u.s.tag);
2637           const char *old_val = d->val;
2638           d->val = "(*sub)";
2639           walk_type (sub, d);
2640           d->val = old_val;
2641           d->indent -= 2;
2642           oprintf (d->of, "%*s}\n", d->indent, "");
2643           oprintf (d->of, "%*sbreak;\n", d->indent, "");
2644           d->indent -= 2;
2645         }
2646       walk_subclasses (sub, d, seen_tags);
2647     }
2648 }
2649
2650 /* Call D->PROCESS_FIELD for every field (or subfield) of D->VAL,
2651    which is of type T.  Write code to D->OF to constrain execution (at
2652    the point that D->PROCESS_FIELD is called) to the appropriate
2653    cases.  Call D->PROCESS_FIELD on subobjects before calling it on
2654    pointers to those objects.  D->PREV_VAL lists the objects
2655    containing the current object, D->OPT is a list of options to
2656    apply, D->INDENT is the current indentation level, D->LINE is used
2657    to print error messages, D->BITMAP indicates which languages to
2658    print the structure for.  */
2659
2660 static void
2661 walk_type (type_p t, struct walk_type_data *d)
2662 {
2663   const char *length = NULL;
2664   const char *desc = NULL;
2665   const char *type_tag = NULL;
2666   int maybe_undef_p = 0;
2667   int atomic_p = 0;
2668   options_p oo;
2669   const struct nested_ptr_data *nested_ptr_d = NULL;
2670
2671   d->needs_cast_p = false;
2672   for (oo = d->opt; oo; oo = oo->next)
2673     if (strcmp (oo->name, "length") == 0 && oo->kind == OPTION_STRING)
2674       length = oo->info.string;
2675     else if (strcmp (oo->name, "maybe_undef") == 0)
2676       maybe_undef_p = 1;
2677     else if (strcmp (oo->name, "desc") == 0 && oo->kind == OPTION_STRING)
2678       desc = oo->info.string;
2679     else if (strcmp (oo->name, "nested_ptr") == 0 
2680              && oo->kind == OPTION_NESTED)
2681       nested_ptr_d = (const struct nested_ptr_data *) oo->info.nested;
2682     else if (strcmp (oo->name, "dot") == 0)
2683       ;
2684     else if (strcmp (oo->name, "tag") == 0)
2685       type_tag = oo->info.string;
2686     else if (strcmp (oo->name, "special") == 0)
2687       ;
2688     else if (strcmp (oo->name, "skip") == 0)
2689       ;
2690     else if (strcmp (oo->name, "atomic") == 0)
2691       atomic_p = 1;
2692     else if (strcmp (oo->name, "default") == 0)
2693       ;
2694     else if (strcmp (oo->name, "chain_next") == 0)
2695       ;
2696     else if (strcmp (oo->name, "chain_prev") == 0)
2697       ;
2698     else if (strcmp (oo->name, "chain_circular") == 0)
2699       ;
2700     else if (strcmp (oo->name, "reorder") == 0)
2701       ;
2702     else if (strcmp (oo->name, "variable_size") == 0)
2703       ;
2704     else if (strcmp (oo->name, "for_user") == 0)
2705       ;
2706     else
2707       error_at_line (d->line, "unknown option `%s'\n", oo->name);
2708
2709   if (d->used_length)
2710     length = NULL;
2711
2712   if (maybe_undef_p
2713       && (t->kind != TYPE_POINTER || !union_or_struct_p (t->u.p)))
2714     {
2715       error_at_line (d->line,
2716                      "field `%s' has invalid option `maybe_undef_p'\n",
2717                      d->val);
2718       return;
2719     }
2720
2721   if (atomic_p && (t->kind != TYPE_POINTER) && (t->kind != TYPE_STRING))
2722     {
2723       error_at_line (d->line, "field `%s' has invalid option `atomic'\n", d->val);
2724       return;
2725     }
2726
2727   switch (t->kind)
2728     {
2729     case TYPE_SCALAR:
2730     case TYPE_STRING:
2731       d->process_field (t, d);
2732       break;
2733
2734     case TYPE_POINTER:
2735       {
2736         d->in_ptr_field = true;
2737         if (maybe_undef_p && t->u.p->u.s.line.file == NULL)
2738           {
2739             oprintf (d->of, "%*sgcc_assert (!%s);\n", d->indent, "", d->val);
2740             break;
2741           }
2742
2743         /* If a pointer type is marked as "atomic", we process the
2744            field itself, but we don't walk the data that they point to.
2745
2746            There are two main cases where we walk types: to mark
2747            pointers that are reachable, and to relocate pointers when
2748            writing a PCH file.  In both cases, an atomic pointer is
2749            itself marked or relocated, but the memory that it points
2750            to is left untouched.  In the case of PCH, that memory will
2751            be read/written unchanged to the PCH file.  */
2752         if (atomic_p)
2753           {
2754             oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
2755             d->indent += 2;
2756             d->process_field (t, d);
2757             d->indent -= 2;
2758             oprintf (d->of, "%*s}\n", d->indent, "");
2759             break;
2760           }
2761
2762         if (!length)
2763           {
2764             if (!union_or_struct_p (t->u.p))
2765               {
2766                 error_at_line (d->line,
2767                                "field `%s' is pointer to unimplemented type",
2768                                d->val);
2769                 break;
2770               }
2771
2772             if (nested_ptr_d)
2773               {
2774                 const char *oldprevval2 = d->prev_val[2];
2775
2776                 if (!union_or_struct_p (nested_ptr_d->type))
2777                   {
2778                     error_at_line (d->line,
2779                                    "field `%s' has invalid "
2780                                    "option `nested_ptr'\n", d->val);
2781                     return;
2782                   }
2783
2784                 d->prev_val[2] = d->val;
2785                 oprintf (d->of, "%*s{\n", d->indent, "");
2786                 d->indent += 2;
2787                 d->val = xasprintf ("x%d", d->counter++);
2788                 oprintf (d->of, "%*s%s %s * %s%s =\n", d->indent, "",
2789                          (nested_ptr_d->type->kind == TYPE_UNION
2790                           ? "union" : "struct"),
2791                          nested_ptr_d->type->u.s.tag,
2792                          d->fn_wants_lvalue ? "" : "const ", d->val);
2793                 oprintf (d->of, "%*s", d->indent + 2, "");
2794                 output_escaped_param (d, nested_ptr_d->convert_from,
2795                                       "nested_ptr");
2796                 oprintf (d->of, ";\n");
2797
2798                 d->process_field (nested_ptr_d->type, d);
2799
2800                 if (d->fn_wants_lvalue)
2801                   {
2802                     oprintf (d->of, "%*s%s = ", d->indent, "",
2803                              d->prev_val[2]);
2804                     d->prev_val[2] = d->val;
2805                     output_escaped_param (d, nested_ptr_d->convert_to,
2806                                           "nested_ptr");
2807                     oprintf (d->of, ";\n");
2808                   }
2809
2810                 d->indent -= 2;
2811                 oprintf (d->of, "%*s}\n", d->indent, "");
2812                 d->val = d->prev_val[2];
2813                 d->prev_val[2] = oldprevval2;
2814               }
2815             else
2816               d->process_field (t->u.p, d);
2817           }
2818         else
2819           {
2820             int loopcounter = d->loopcounter;
2821             const char *oldval = d->val;
2822             const char *oldprevval3 = d->prev_val[3];
2823             char *newval;
2824
2825             oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
2826             d->indent += 2;
2827             oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2828             oprintf (d->of, "%*sfor (i%d = 0; i%d != (size_t)(", d->indent,
2829                      "", loopcounter, loopcounter);
2830             if (!d->in_record_p)
2831               output_escaped_param (d, length, "length");
2832             else
2833               oprintf (d->of, "l%d", loopcounter);
2834             if (d->have_this_obj)
2835               /* Try to unswitch loops (see PR53880).  */
2836               oprintf (d->of, ") && ((void *)%s == this_obj", oldval);
2837             oprintf (d->of, "); i%d++) {\n", loopcounter);
2838             d->indent += 2;
2839             d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2840             d->used_length = 1;
2841             d->prev_val[3] = oldval;
2842             walk_type (t->u.p, d);
2843             free (newval);
2844             d->val = oldval;
2845             d->prev_val[3] = oldprevval3;
2846             d->used_length = 0;
2847             d->indent -= 2;
2848             oprintf (d->of, "%*s}\n", d->indent, "");
2849             d->process_field (t, d);
2850             d->indent -= 2;
2851             oprintf (d->of, "%*s}\n", d->indent, "");
2852           }
2853         d->in_ptr_field = false;
2854       }
2855       break;
2856
2857     case TYPE_ARRAY:
2858       {
2859         int loopcounter;
2860         const char *oldval = d->val;
2861         char *newval;
2862
2863         /* If it's an array of scalars, we optimize by not generating
2864            any code.  */
2865         if (t->u.a.p->kind == TYPE_SCALAR)
2866           break;
2867
2868         if (length)
2869           loopcounter = d->loopcounter;
2870         else
2871           loopcounter = d->counter++;
2872
2873         /* When walking an array, compute the length and store it in a
2874            local variable before walking the array elements, instead of
2875            recomputing the length expression each time through the loop.
2876            This is necessary to handle tcc_vl_exp objects like CALL_EXPR,
2877            where the length is stored in the first array element,
2878            because otherwise that operand can get overwritten on the
2879            first iteration.  */
2880         oprintf (d->of, "%*s{\n", d->indent, "");
2881         d->indent += 2;
2882         oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2883         if (!d->in_record_p || !length)
2884           {
2885             oprintf (d->of, "%*ssize_t l%d = (size_t)(",
2886                      d->indent, "", loopcounter);
2887             if (length)
2888               output_escaped_param (d, length, "length");
2889             else
2890               oprintf (d->of, "%s", t->u.a.len);
2891             oprintf (d->of, ");\n");
2892           }
2893
2894         oprintf (d->of, "%*sfor (i%d = 0; i%d != l%d; i%d++) {\n",
2895                  d->indent, "",
2896                  loopcounter, loopcounter, loopcounter, loopcounter);
2897         d->indent += 2;
2898         d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2899         d->used_length = 1;
2900         walk_type (t->u.a.p, d);
2901         free (newval);
2902         d->used_length = 0;
2903         d->val = oldval;
2904         d->indent -= 2;
2905         oprintf (d->of, "%*s}\n", d->indent, "");
2906         d->indent -= 2;
2907         oprintf (d->of, "%*s}\n", d->indent, "");
2908       }
2909       break;
2910
2911     case TYPE_STRUCT:
2912     case TYPE_UNION:
2913       {
2914         pair_p f;
2915         const char *oldval = d->val;
2916         const char *oldprevval1 = d->prev_val[1];
2917         const char *oldprevval2 = d->prev_val[2];
2918         const int union_p = t->kind == TYPE_UNION;
2919         int seen_default_p = 0;
2920         options_p o;
2921         int lengths_seen = 0;
2922         int endcounter;
2923         bool any_length_seen = false;
2924
2925         if (!t->u.s.line.file)
2926           error_at_line (d->line, "incomplete structure `%s'", t->u.s.tag);
2927
2928         if ((d->bitmap & t->u.s.bitmap) != d->bitmap)
2929           {
2930             error_at_line (d->line,
2931                            "structure `%s' defined for mismatching languages",
2932                            t->u.s.tag);
2933             error_at_line (&t->u.s.line, "one structure defined here");
2934           }
2935
2936         /* Some things may also be defined in the structure's options.  */
2937         for (o = t->u.s.opt; o; o = o->next)
2938           if (!desc && strcmp (o->name, "desc") == 0
2939               && o->kind == OPTION_STRING)
2940             desc = o->info.string;
2941
2942         d->prev_val[2] = oldval;
2943         d->prev_val[1] = oldprevval2;
2944         if (union_p)
2945           {
2946             if (desc == NULL)
2947               {
2948                 error_at_line (d->line,
2949                                "missing `desc' option for union `%s'",
2950                                t->u.s.tag);
2951                 desc = "1";
2952               }
2953             oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
2954             output_escaped_param (d, desc, "desc");
2955             oprintf (d->of, "))\n");
2956             d->indent += 2;
2957             oprintf (d->of, "%*s{\n", d->indent, "");
2958           }
2959         else if (desc)
2960           {
2961             /* We have a "desc" option on a struct, signifying the
2962                base class within a GC-managed inheritance hierarchy.
2963                The current code specialcases the base class, then walks
2964                into subclasses, recursing into this routine to handle them.
2965                This organization requires the base class to have a case in
2966                the switch statement, and hence a tag value is mandatory
2967                for the base class.   This restriction could be removed, but
2968                it would require some restructing of this code.  */
2969             if (!type_tag)
2970               {
2971                 error_at_line (d->line,
2972                                "missing `tag' option for type `%s'",
2973                                t->u.s.tag);
2974               }
2975             oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
2976             output_escaped_param (d, desc, "desc");
2977             oprintf (d->of, "))\n");
2978             d->indent += 2;
2979             oprintf (d->of, "%*s{\n", d->indent, "");
2980             oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
2981             d->indent += 2;
2982           }
2983
2984         FOR_ALL_INHERITED_FIELDS (t, f)
2985           {
2986             options_p oo;
2987             int skip_p = 0;
2988             const char *fieldlength = NULL;
2989
2990             d->reorder_fn = NULL;
2991             for (oo = f->opt; oo; oo = oo->next)
2992               if (strcmp (oo->name, "skip") == 0)
2993                 skip_p = 1;
2994               else if (strcmp (oo->name, "length") == 0
2995                        && oo->kind == OPTION_STRING)
2996                 fieldlength = oo->info.string;
2997
2998             if (skip_p)
2999               continue;
3000             if (fieldlength)
3001               {
3002                 lengths_seen++;
3003                 d->counter++;
3004                 if (!union_p)
3005                   {
3006                     if (!any_length_seen)
3007                       {
3008                         oprintf (d->of, "%*s{\n", d->indent, "");
3009                         d->indent += 2;
3010                       }
3011                     any_length_seen = true;
3012
3013                     oprintf (d->of, "%*ssize_t l%d = (size_t)(",
3014                              d->indent, "", d->counter - 1);
3015                     output_escaped_param (d, fieldlength, "length");
3016                     oprintf (d->of, ");\n");
3017                   }
3018               }
3019           }
3020         endcounter = d->counter;
3021
3022         FOR_ALL_INHERITED_FIELDS (t, f)
3023           {
3024             options_p oo;
3025             const char *dot = ".";
3026             const char *tagid = NULL;
3027             int skip_p = 0;
3028             int default_p = 0;
3029             const char *fieldlength = NULL;
3030             char *newval;
3031
3032             d->reorder_fn = NULL;
3033             for (oo = f->opt; oo; oo = oo->next)
3034               if (strcmp (oo->name, "dot") == 0
3035                   && oo->kind == OPTION_STRING)
3036                 dot = oo->info.string;
3037               else if (strcmp (oo->name, "tag") == 0
3038                        && oo->kind == OPTION_STRING)
3039                 tagid = oo->info.string;
3040               else if (strcmp (oo->name, "skip") == 0)
3041                 skip_p = 1;
3042               else if (strcmp (oo->name, "default") == 0)
3043                 default_p = 1;
3044               else if (strcmp (oo->name, "reorder") == 0
3045                   && oo->kind == OPTION_STRING)
3046                 d->reorder_fn = oo->info.string;
3047               else if (strcmp (oo->name, "length") == 0
3048                        && oo->kind == OPTION_STRING)
3049                 fieldlength = oo->info.string;
3050
3051             if (skip_p)
3052               continue;
3053
3054             if (union_p && tagid)
3055               {
3056                 oprintf (d->of, "%*scase %s:\n", d->indent, "", tagid);
3057                 d->indent += 2;
3058               }
3059             else if (union_p && default_p)
3060               {
3061                 oprintf (d->of, "%*sdefault:\n", d->indent, "");
3062                 d->indent += 2;
3063                 seen_default_p = 1;
3064               }
3065             else if (!union_p && (default_p || tagid))
3066               error_at_line (d->line,
3067                              "can't use `%s' outside a union on field `%s'",
3068                              default_p ? "default" : "tag", f->name);
3069             else if (union_p && !(default_p || tagid)
3070                      && f->type->kind == TYPE_SCALAR)
3071               {
3072                 fprintf (stderr,
3073                          "%s:%d: warning: field `%s' is missing `tag' or `default' option\n",
3074                          get_input_file_name (d->line->file), d->line->line, 
3075                          f->name);
3076                 continue;
3077               }
3078             else if (union_p && !(default_p || tagid))
3079               error_at_line (d->line,
3080                              "field `%s' is missing `tag' or `default' option",
3081                              f->name);
3082
3083             if (fieldlength)
3084               {
3085                 d->loopcounter = endcounter - lengths_seen--;
3086               }
3087
3088             d->line = &f->line;
3089             d->val = newval = xasprintf ("%s%s%s", oldval, dot, f->name);
3090             d->opt = f->opt;
3091             d->used_length = false;
3092             d->in_record_p = !union_p;
3093
3094             walk_type (f->type, d);
3095
3096             d->in_record_p = false;
3097
3098             free (newval);
3099
3100             if (union_p)
3101               {
3102                 oprintf (d->of, "%*sbreak;\n", d->indent, "");
3103                 d->indent -= 2;
3104               }
3105           }
3106         d->reorder_fn = NULL;
3107
3108         d->val = oldval;
3109         d->prev_val[1] = oldprevval1;
3110         d->prev_val[2] = oldprevval2;
3111
3112         if (union_p && !seen_default_p)
3113           {
3114             oprintf (d->of, "%*sdefault:\n", d->indent, "");
3115             oprintf (d->of, "%*s  break;\n", d->indent, "");
3116           }
3117
3118         if (desc && !union_p)
3119           {
3120                 oprintf (d->of, "%*sbreak;\n", d->indent, "");
3121                 d->indent -= 2;
3122           }
3123         if (union_p)
3124           {
3125             oprintf (d->of, "%*s}\n", d->indent, "");
3126             d->indent -= 2;
3127           }
3128         else if (desc)
3129           {
3130             /* Add cases to handle subclasses.  */
3131             struct seen_tag *tags = NULL;
3132             walk_subclasses (t, d, &tags);
3133
3134             /* Ensure that if someone forgets a "tag" option that we don't
3135                silent fail to traverse that subclass's fields.  */
3136             if (!seen_default_p)
3137               {
3138                 oprintf (d->of, "%*s/* Unrecognized tag value.  */\n",
3139                          d->indent, "");
3140                 oprintf (d->of, "%*sdefault: gcc_unreachable (); \n",
3141                          d->indent, "");
3142               }
3143
3144             /* End of the switch statement */
3145             oprintf (d->of, "%*s}\n", d->indent, "");
3146             d->indent -= 2;
3147           }
3148         if (any_length_seen)
3149           {
3150             d->indent -= 2;
3151             oprintf (d->of, "%*s}\n", d->indent, "");
3152           }
3153       }
3154       break;
3155
3156     case TYPE_LANG_STRUCT:
3157       {
3158         type_p nt;
3159         for (nt = t->u.s.lang_struct; nt; nt = nt->next)
3160           if ((d->bitmap & nt->u.s.bitmap) == d->bitmap)
3161             break;
3162         if (nt == NULL)
3163           error_at_line (d->line, "structure `%s' differs between languages",
3164                          t->u.s.tag);
3165         else
3166           walk_type (nt, d);
3167       }
3168       break;
3169
3170     case TYPE_USER_STRUCT:
3171       d->process_field (t, d);
3172       break;
3173
3174     case TYPE_NONE:
3175     case TYPE_UNDEFINED:
3176       gcc_unreachable ();
3177     }
3178 }
3179
3180 /* process_field routine for marking routines.  */
3181
3182 static void
3183 write_types_process_field (type_p f, const struct walk_type_data *d)
3184 {
3185   const struct write_types_data *wtd;
3186   const char *cast = d->needs_cast_p ? "(void *)" : "";
3187   wtd = (const struct write_types_data *) d->cookie;
3188
3189   switch (f->kind)
3190     {
3191     case TYPE_NONE:
3192     case TYPE_UNDEFINED:
3193       gcc_unreachable ();
3194     case TYPE_POINTER:
3195       oprintf (d->of, "%*s%s (%s%s", d->indent, "",
3196                wtd->subfield_marker_routine, cast, d->val);
3197       if (wtd->param_prefix)
3198         {
3199           if (f->u.p->kind == TYPE_SCALAR)
3200             /* The current type is a pointer to a scalar (so not
3201                considered like a pointer to instances of user defined
3202                types) and we are seeing it; it means we must be even
3203                more careful about the second argument of the
3204                SUBFIELD_MARKER_ROUTINE call.  That argument must
3205                always be the instance of the type for which
3206                write_func_for_structure was called - this really is
3207                what the function SUBFIELD_MARKER_ROUTINE expects.
3208                That is, it must be an instance of the ORIG_S type
3209                parameter of write_func_for_structure.  The convention
3210                is that that argument must be "x" in that case (as set
3211                by write_func_for_structure).  The problem is, we can't
3212                count on d->prev_val[3] to be always set to "x" in that
3213                case.  Sometimes walk_type can set it to something else
3214                (to e.g cooperate with write_array when called from
3215                write_roots).  So let's set it to "x" here then.  */
3216             oprintf (d->of, ", x");
3217           else
3218             oprintf (d->of, ", %s", d->prev_val[3]);
3219           if (d->orig_s)
3220             {
3221               oprintf (d->of, ", gt_%s_", wtd->param_prefix);
3222               output_mangled_typename (d->of, d->orig_s);
3223             }
3224           else
3225             oprintf (d->of, ", gt_%sa_%s", wtd->param_prefix, d->prev_val[0]);
3226         }
3227       oprintf (d->of, ");\n");
3228       if (d->reorder_fn && wtd->reorder_note_routine)
3229         oprintf (d->of, "%*s%s (%s%s, %s, %s);\n", d->indent, "",
3230                  wtd->reorder_note_routine, cast, d->val,
3231                  d->prev_val[3], d->reorder_fn);
3232       break;
3233
3234     case TYPE_STRING:
3235     case TYPE_STRUCT:
3236     case TYPE_UNION:
3237     case TYPE_LANG_STRUCT:
3238     case TYPE_USER_STRUCT:
3239       if (f->kind == TYPE_USER_STRUCT && !d->in_ptr_field)
3240         {
3241           /* If F is a user-defined type and the field is not a
3242              pointer to the type, then we should not generate the
3243              standard pointer-marking code.  All we need to do is call
3244              the user-provided marking function to process the fields
3245              of F.  */
3246           oprintf (d->of, "%*sgt_%sx (&(%s));\n", d->indent, "", wtd->prefix,
3247                    d->val);
3248         }
3249       else
3250         {
3251           oprintf (d->of, "%*sgt_%s_", d->indent, "", wtd->prefix);
3252           output_mangled_typename (d->of, f);
3253           oprintf (d->of, " (%s%s);\n", cast, d->val);
3254           if (d->reorder_fn && wtd->reorder_note_routine)
3255             oprintf (d->of, "%*s%s (%s%s, %s%s, %s);\n", d->indent, "",
3256                      wtd->reorder_note_routine, cast, d->val, cast, d->val,
3257                      d->reorder_fn);
3258         }
3259       break;
3260
3261     case TYPE_SCALAR:
3262       break;
3263
3264     case TYPE_ARRAY:
3265       gcc_unreachable ();
3266     }
3267 }
3268
3269 /* Return an output file that is suitable for definitions which can
3270    reference struct S */
3271
3272 static outf_p
3273 get_output_file_for_structure (const_type_p s)
3274 {
3275   const input_file *fn;
3276
3277   gcc_assert (union_or_struct_p (s));
3278   fn = s->u.s.line.file;
3279
3280   /* The call to get_output_file_with_visibility may update fn by
3281      caching its result inside, so we need the CONST_CAST.  */
3282   return get_output_file_with_visibility (CONST_CAST (input_file*, fn));
3283 }
3284
3285
3286 /* Returns the specifier keyword for a string or union type S, empty string
3287    otherwise.  */
3288
3289 static const char *
3290 get_type_specifier (const type_p s)
3291 {
3292   if (s->kind == TYPE_STRUCT)
3293     return "struct ";
3294   else if (s->kind == TYPE_LANG_STRUCT)
3295     return get_type_specifier (s->u.s.lang_struct);
3296   else if (s->kind == TYPE_UNION)
3297     return "union ";
3298   return "";
3299 }
3300
3301
3302 /* Emits a declaration for type TY (assumed to be a union or a
3303    structure) on stream OUT.  */
3304
3305 static void
3306 write_type_decl (outf_p out, type_p ty)
3307 {
3308   if (union_or_struct_p (ty))
3309     oprintf (out, "%s%s", get_type_specifier (ty), ty->u.s.tag);
3310   else if (ty->kind == TYPE_SCALAR)
3311     {
3312       if (ty->u.scalar_is_char)
3313         oprintf (out, "const char");
3314       else
3315         oprintf (out, "void");
3316     }
3317   else if (ty->kind == TYPE_POINTER)
3318     {
3319       write_type_decl (out, ty->u.p);
3320       oprintf (out, " *");
3321     }
3322   else if (ty->kind == TYPE_ARRAY)
3323     {
3324       write_type_decl (out, ty->u.a.p);
3325       oprintf (out, " *");
3326     }
3327   else if (ty->kind == TYPE_STRING)
3328     {
3329       oprintf (out, "const char *");
3330     }
3331   else
3332     gcc_unreachable ();
3333 }
3334
3335
3336 /* Write on OF the name of the marker function for structure S. PREFIX
3337    is the prefix to use (to distinguish ggc from pch markers).  */
3338
3339 static void
3340 write_marker_function_name (outf_p of, type_p s, const char *prefix)
3341 {
3342   if (union_or_struct_p (s))
3343     {
3344       const char *id_for_tag = filter_type_name (s->u.s.tag);
3345       oprintf (of, "gt_%sx_%s", prefix, id_for_tag);
3346       if (id_for_tag != s->u.s.tag)
3347         free (CONST_CAST (char *, id_for_tag));
3348     }
3349   else
3350     gcc_unreachable ();
3351 }
3352
3353 /* Write on OF a user-callable routine to act as an entry point for
3354    the marking routine for S, generated by write_func_for_structure.
3355    WTD distinguishes between ggc and pch markers.  */
3356
3357 static void
3358 write_user_func_for_structure_ptr (outf_p of, type_p s, const write_types_data *wtd)
3359 {
3360   gcc_assert (union_or_struct_p (s));
3361
3362   type_p alias_of = NULL;
3363   for (options_p opt = s->u.s.opt; opt; opt = opt->next)
3364     if (strcmp (opt->name, "ptr_alias") == 0)
3365       {
3366         /* ALIAS_OF is set if ORIG_S is marked "ptr_alias". This means that
3367            we do not generate marking code for ORIG_S here. Instead, a
3368            forwarder #define in gtype-desc.h will cause every call to its
3369            marker to call the target of this alias.
3370
3371            However, we still want to create a user entry code for the
3372            aliased type. So, if ALIAS_OF is set, we only generate the
3373            user-callable marker function.  */
3374         alias_of = opt->info.type;
3375         break;
3376       }
3377
3378   DBGPRINTF ("write_user_func_for_structure_ptr: %s %s", s->u.s.tag,
3379              wtd->prefix);
3380
3381   /* Only write the function once. */
3382   if (s->u.s.wrote_user_func_for_ptr[wtd->kind])
3383     return;
3384   s->u.s.wrote_user_func_for_ptr[wtd->kind] = true;
3385
3386   oprintf (of, "\nvoid\n");
3387   oprintf (of, "gt_%sx (", wtd->prefix);
3388   write_type_decl (of, s);
3389   oprintf (of, " *& x)\n");
3390   oprintf (of, "{\n");
3391   oprintf (of, "  if (x)\n    ");
3392   write_marker_function_name (of,
3393                               alias_of ? alias_of : get_ultimate_base_class (s),
3394                               wtd->prefix);
3395   oprintf (of, " ((void *) x);\n");
3396   oprintf (of, "}\n");
3397 }
3398
3399
3400 /* Write a function to mark all the fields of type S on OF.  PREFIX
3401    and D are as in write_user_marking_functions.  */
3402
3403 static void
3404 write_user_func_for_structure_body (type_p s, const char *prefix,
3405                                     struct walk_type_data *d)
3406 {
3407   oprintf (d->of, "\nvoid\n");
3408   oprintf (d->of, "gt_%sx (", prefix);
3409   write_type_decl (d->of, s);
3410   oprintf (d->of, "& x_r ATTRIBUTE_UNUSED)\n");
3411   oprintf (d->of, "{\n");
3412   oprintf (d->of, "  ");
3413   write_type_decl (d->of, s);
3414   oprintf (d->of, " * ATTRIBUTE_UNUSED x = &x_r;\n");
3415   d->val = "(*x)";
3416   d->indent = 2;
3417   walk_type (s, d);
3418   oprintf (d->of, "}\n");
3419 }
3420
3421 /* Emit the user-callable functions needed to mark all the types used
3422    by the user structure S.  PREFIX is the prefix to use to
3423    distinguish ggc and pch markers.  D contains data needed to pass to
3424    walk_type when traversing the fields of a type.
3425
3426    For every type T referenced by S, two routines are generated: one
3427    that takes 'T *', marks the pointer and calls the second routine,
3428    which just marks the fields of T.  */
3429
3430 static void
3431 write_user_marking_functions (type_p s,
3432                               const write_types_data *w,
3433                               struct walk_type_data *d)
3434 {
3435   gcc_assert (s->kind == TYPE_USER_STRUCT);
3436
3437   for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
3438     {
3439       type_p fld_type = fld->type;
3440       if (fld_type->kind == TYPE_POINTER)
3441         {
3442           type_p pointed_to_type = fld_type->u.p;
3443           if (union_or_struct_p (pointed_to_type))
3444             write_user_func_for_structure_ptr (d->of, pointed_to_type, w);
3445         }
3446       else if (union_or_struct_p (fld_type))
3447         write_user_func_for_structure_body (fld_type, w->prefix, d);
3448     }
3449 }
3450
3451
3452 /* For S, a structure that's part of ORIG_S write out a routine that:
3453    - Takes a parameter, a void * but actually of type *S
3454    - If SEEN_ROUTINE returns nonzero, calls write_types_process_field on each
3455    field of S or its substructures and (in some cases) things
3456    that are pointed to by S.  */
3457
3458 static void
3459 write_func_for_structure (type_p orig_s, type_p s,
3460                           const struct write_types_data *wtd)
3461 {
3462   const char *chain_next = NULL;
3463   const char *chain_prev = NULL;
3464   const char *chain_circular = NULL;
3465   options_p opt;
3466   struct walk_type_data d;
3467
3468   if (s->u.s.base_class)
3469     {
3470       /* Verify that the base class has a "desc", since otherwise
3471          the traversal hooks there won't attempt to visit fields of
3472          subclasses such as this one.  */
3473       const_type_p ubc = get_ultimate_base_class (s);
3474       if ((!opts_have (ubc->u.s.opt, "user")
3475            && !opts_have (ubc->u.s.opt, "desc")))
3476         error_at_line (&s->u.s.line,
3477                        ("'%s' is a subclass of non-GTY(user) GTY class '%s'"
3478                         ", but '%s' lacks a discriminator 'desc' option"),
3479                        s->u.s.tag, ubc->u.s.tag, ubc->u.s.tag);
3480
3481       /* Don't write fns for subclasses, only for the ultimate base class
3482          within an inheritance hierarchy.  */
3483       return;
3484     }
3485
3486   memset (&d, 0, sizeof (d));
3487   d.of = get_output_file_for_structure (s);
3488
3489   bool for_user = false;
3490   for (opt = s->u.s.opt; opt; opt = opt->next)
3491     if (strcmp (opt->name, "chain_next") == 0
3492         && opt->kind == OPTION_STRING)
3493       chain_next = opt->info.string;
3494     else if (strcmp (opt->name, "chain_prev") == 0
3495              && opt->kind == OPTION_STRING)
3496       chain_prev = opt->info.string;
3497     else if (strcmp (opt->name, "chain_circular") == 0
3498              && opt->kind == OPTION_STRING)
3499       chain_circular = opt->info.string;
3500     else if (strcmp (opt->name, "for_user") == 0)
3501       for_user = true;
3502   if (chain_prev != NULL && chain_next == NULL)
3503     error_at_line (&s->u.s.line, "chain_prev without chain_next");
3504   if (chain_circular != NULL && chain_next != NULL)
3505     error_at_line (&s->u.s.line, "chain_circular with chain_next");
3506   if (chain_circular != NULL)
3507     chain_next = chain_circular;
3508
3509   d.process_field = write_types_process_field;
3510   d.cookie = wtd;
3511   d.orig_s = orig_s;
3512   d.opt = s->u.s.opt;
3513   d.line = &s->u.s.line;
3514   d.bitmap = s->u.s.bitmap;
3515   d.prev_val[0] = "*x";
3516   d.prev_val[1] = "not valid postage";  /* Guarantee an error.  */
3517   d.prev_val[3] = "x";
3518   d.val = "(*x)";
3519   d.have_this_obj = false;
3520
3521   oprintf (d.of, "\n");
3522   oprintf (d.of, "void\n");
3523   write_marker_function_name (d.of, orig_s, wtd->prefix);
3524   oprintf (d.of, " (void *x_p)\n");
3525   oprintf (d.of, "{\n  ");
3526   write_type_decl (d.of, s);
3527   oprintf (d.of, " * %sx = (", chain_next == NULL ? "const " : "");
3528   write_type_decl (d.of, s);
3529   oprintf (d.of, " *)x_p;\n");
3530   if (chain_next != NULL)
3531     {
3532       /* TYPE_USER_STRUCTs should not occur here.  These structures
3533          are completely handled by user code.  */
3534       gcc_assert (orig_s->kind != TYPE_USER_STRUCT);
3535
3536       oprintf (d.of, "  ");
3537       write_type_decl (d.of, s);
3538       oprintf (d.of, " * xlimit = x;\n");
3539     }
3540   if (chain_next == NULL)
3541     {
3542       oprintf (d.of, "  if (%s (x", wtd->marker_routine);
3543       if (wtd->param_prefix)
3544         {
3545           oprintf (d.of, ", x, gt_%s_", wtd->param_prefix);
3546           output_mangled_typename (d.of, orig_s);
3547         }
3548       oprintf (d.of, "))\n");
3549     }
3550   else
3551     {
3552       if (chain_circular != NULL)
3553         oprintf (d.of, "  if (!%s (xlimit", wtd->marker_routine);
3554       else
3555         oprintf (d.of, "  while (%s (xlimit", wtd->marker_routine);
3556       if (wtd->param_prefix)
3557         {
3558           oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
3559           output_mangled_typename (d.of, orig_s);
3560         }
3561       oprintf (d.of, "))\n");
3562       if (chain_circular != NULL)
3563         oprintf (d.of, "    return;\n  do\n");
3564
3565       oprintf (d.of, "   xlimit = (");
3566       d.prev_val[2] = "*xlimit";
3567       output_escaped_param (&d, chain_next, "chain_next");
3568       oprintf (d.of, ");\n");
3569       if (chain_prev != NULL)
3570         {
3571           oprintf (d.of, "  if (x != xlimit)\n");
3572           oprintf (d.of, "    for (;;)\n");
3573           oprintf (d.of, "      {\n");
3574           oprintf (d.of, "        %s %s * const xprev = (",
3575                    s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
3576
3577           d.prev_val[2] = "*x";
3578           output_escaped_param (&d, chain_prev, "chain_prev");
3579           oprintf (d.of, ");\n");
3580           oprintf (d.of, "        if (xprev == NULL) break;\n");
3581           oprintf (d.of, "        x = xprev;\n");
3582           oprintf (d.of, "        (void) %s (xprev", wtd->marker_routine);
3583           if (wtd->param_prefix)
3584             {
3585               oprintf (d.of, ", xprev, gt_%s_", wtd->param_prefix);
3586               output_mangled_typename (d.of, orig_s);
3587             }
3588           oprintf (d.of, ");\n");
3589           oprintf (d.of, "      }\n");
3590         }
3591       if (chain_circular != NULL)
3592         {
3593           oprintf (d.of, "  while (%s (xlimit", wtd->marker_routine);
3594           if (wtd->param_prefix)
3595             {
3596               oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
3597               output_mangled_typename (d.of, orig_s);
3598             }
3599           oprintf (d.of, "));\n");
3600           oprintf (d.of, "  do\n");
3601         }
3602       else
3603         oprintf (d.of, "  while (x != xlimit)\n");
3604     }
3605   oprintf (d.of, "    {\n");
3606
3607   d.prev_val[2] = "*x";
3608   d.indent = 6;
3609   if (orig_s->kind != TYPE_USER_STRUCT)
3610     walk_type (s, &d);
3611   else
3612     {
3613       /* User structures have no fields to walk. Simply generate a call
3614          to the user-provided structure marker.  */
3615       oprintf (d.of, "%*sgt_%sx (x);\n", d.indent, "", wtd->prefix);
3616     }
3617
3618   if (chain_next != NULL)
3619     {
3620       oprintf (d.of, "      x = (");
3621       output_escaped_param (&d, chain_next, "chain_next");
3622       oprintf (d.of, ");\n");
3623     }
3624
3625   oprintf (d.of, "    }\n");
3626   if (chain_circular != NULL)
3627     oprintf (d.of, "  while (x != xlimit);\n");
3628   oprintf (d.of, "}\n");
3629
3630   if (orig_s->kind == TYPE_USER_STRUCT)
3631     write_user_marking_functions (orig_s, wtd, &d);
3632
3633   if (for_user)
3634     {
3635       write_user_func_for_structure_body (orig_s, wtd->prefix, &d);
3636       write_user_func_for_structure_ptr (d.of, orig_s, wtd);
3637     }
3638 }
3639
3640
3641 /* Write out marker routines for STRUCTURES and PARAM_STRUCTS.  */
3642
3643 static void
3644 write_types (outf_p output_header, type_p structures,
3645              const struct write_types_data *wtd)
3646 {
3647   int nbfun = 0;                /* Count the emitted functions.  */
3648   type_p s;
3649
3650   oprintf (output_header, "\n/* %s*/\n", wtd->comment);
3651
3652   /* We first emit the macros and the declarations. Functions' code is
3653      emitted afterwards.  This is needed in plugin mode.  */
3654   oprintf (output_header, "/* Macros and declarations.  */\n");
3655   for (s = structures; s; s = s->next)
3656     /* Do not emit handlers for derived classes; we only ever deal with
3657        the ultimate base class within an inheritance hierarchy.  */
3658     if ((s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
3659         && !s->u.s.base_class)
3660       {
3661         options_p opt;
3662
3663         if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
3664           continue;
3665
3666         const char *s_id_for_tag = filter_type_name (s->u.s.tag);
3667
3668         oprintf (output_header, "#define gt_%s_", wtd->prefix);
3669         output_mangled_typename (output_header, s);
3670         oprintf (output_header, "(X) do { \\\n");
3671         oprintf (output_header,
3672                  "  if (X != NULL) gt_%sx_%s (X);\\\n", wtd->prefix,
3673                  s_id_for_tag);
3674         oprintf (output_header, "  } while (0)\n");
3675
3676         for (opt = s->u.s.opt; opt; opt = opt->next)
3677           if (strcmp (opt->name, "ptr_alias") == 0
3678               && opt->kind == OPTION_TYPE)
3679             {
3680               const_type_p const t = (const_type_p) opt->info.type;
3681               if (t->kind == TYPE_STRUCT
3682                   || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
3683                 {
3684                   const char *t_id_for_tag = filter_type_name (t->u.s.tag);
3685                   oprintf (output_header,
3686                            "#define gt_%sx_%s gt_%sx_%s\n",
3687                            wtd->prefix, s->u.s.tag, wtd->prefix, t_id_for_tag);
3688                   if (t_id_for_tag != t->u.s.tag)
3689                     free (CONST_CAST (char *, t_id_for_tag));
3690                 }
3691               else
3692                 error_at_line (&s->u.s.line,
3693                                "structure alias is not a structure");
3694               break;
3695             }
3696         if (opt)
3697           continue;
3698
3699         /* Declare the marker procedure only once.  */
3700         oprintf (output_header,
3701                  "extern void gt_%sx_%s (void *);\n",
3702                  wtd->prefix, s_id_for_tag);
3703
3704         if (s_id_for_tag != s->u.s.tag)
3705           free (CONST_CAST (char *, s_id_for_tag));
3706
3707         if (s->u.s.line.file == NULL)
3708           {
3709             fprintf (stderr, "warning: structure `%s' used but not defined\n",
3710                      s->u.s.tag);
3711             continue;
3712           }
3713       }
3714
3715   /* At last we emit the functions code.  */
3716   oprintf (output_header, "\n/* functions code */\n");
3717   for (s = structures; s; s = s->next)
3718     if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
3719       {
3720         options_p opt;
3721
3722         if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
3723           continue;
3724         for (opt = s->u.s.opt; opt; opt = opt->next)
3725           if (strcmp (opt->name, "ptr_alias") == 0)
3726             break;
3727         if (opt)
3728           continue;
3729
3730         if (s->kind == TYPE_LANG_STRUCT)
3731           {
3732             type_p ss;
3733             for (ss = s->u.s.lang_struct; ss; ss = ss->next)
3734               {
3735                 nbfun++;
3736                 DBGPRINTF ("writing func #%d lang_struct ss @ %p '%s'",
3737                            nbfun, (void*) ss, ss->u.s.tag);
3738                 write_func_for_structure (s, ss, wtd);
3739               }
3740           }
3741         else
3742           {
3743             nbfun++;
3744             DBGPRINTF ("writing func #%d struct s @ %p '%s'",
3745                        nbfun, (void*) s, s->u.s.tag);
3746             write_func_for_structure (s, s, wtd);
3747           }
3748       }
3749     else
3750       {
3751         /* Structure s is not possibly pointed to, so can be ignored.  */
3752         DBGPRINTF ("ignored s @ %p  '%s' gc_used#%d",
3753                    (void*)s,  s->u.s.tag,
3754                    (int) s->gc_used);
3755       }
3756
3757   if (verbosity_level >= 2)
3758     printf ("%s emitted %d routines for %s\n",
3759             progname, nbfun, wtd->comment);
3760 }
3761
3762 static const struct write_types_data ggc_wtd = {
3763   "ggc_m", NULL, "ggc_mark", "ggc_test_and_set_mark", NULL,
3764   "GC marker procedures.  ",
3765   WTK_GGC
3766 };
3767
3768 static const struct write_types_data pch_wtd = {
3769   "pch_n", "pch_p", "gt_pch_note_object", "gt_pch_note_object",
3770   "gt_pch_note_reorder",
3771   "PCH type-walking procedures.  ",
3772   WTK_PCH
3773 };
3774
3775 /* Write out the local pointer-walking routines.  */
3776
3777 /* process_field routine for local pointer-walking for user-callable
3778    routines.  The difference between this and
3779    write_types_local_process_field is that, in this case, we do not
3780    need to check whether the given pointer matches the address of the
3781    parent structure.  This check was already generated by the call
3782    to gt_pch_nx in the main gt_pch_p_*() function that is calling
3783    this code.  */
3784
3785 static void
3786 write_types_local_user_process_field (type_p f, const struct walk_type_data *d)
3787 {
3788   switch (f->kind)
3789     {
3790     case TYPE_POINTER:
3791     case TYPE_STRUCT:
3792     case TYPE_UNION:
3793     case TYPE_LANG_STRUCT:
3794     case TYPE_STRING:
3795       oprintf (d->of, "%*s  op (&(%s), cookie);\n", d->indent, "", d->val);
3796       break;
3797
3798     case TYPE_USER_STRUCT:
3799       if (d->in_ptr_field)
3800         oprintf (d->of, "%*s  op (&(%s), cookie);\n", d->indent, "", d->val);
3801       else
3802         oprintf (d->of, "%*s  gt_pch_nx (&(%s), op, cookie);\n",
3803                  d->indent, "", d->val);
3804       break;
3805
3806     case TYPE_SCALAR:
3807       break;
3808
3809     case TYPE_ARRAY:
3810     case TYPE_NONE:
3811     case TYPE_UNDEFINED:
3812       gcc_unreachable ();
3813     }
3814 }
3815
3816
3817 /* Write a function to PCH walk all the fields of type S on OF.
3818    D contains data needed by walk_type to recurse into the fields of S.  */
3819
3820 static void
3821 write_pch_user_walking_for_structure_body (type_p s, struct walk_type_data *d)
3822 {
3823   oprintf (d->of, "\nvoid\n");
3824   oprintf (d->of, "gt_pch_nx (");
3825   write_type_decl (d->of, s);
3826   oprintf (d->of, "* x ATTRIBUTE_UNUSED,\n"
3827            "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
3828            "\tATTRIBUTE_UNUSED void *cookie)\n");
3829   oprintf (d->of, "{\n");
3830   d->val = "(*x)";
3831   d->indent = 2;
3832   d->process_field = write_types_local_user_process_field;
3833   walk_type (s, d);
3834   oprintf (d->of, "}\n");
3835 }
3836
3837
3838 /* Emit the user-callable functions needed to mark all the types used
3839    by the user structure S.  PREFIX is the prefix to use to
3840    distinguish ggc and pch markers. CHAIN_NEXT is set if S has the
3841    chain_next option defined.  D contains data needed to pass to
3842    walk_type when traversing the fields of a type.
3843
3844    For every type T referenced by S, two routines are generated: one
3845    that takes 'T *', marks the pointer and calls the second routine,
3846    which just marks the fields of T.  */
3847
3848 static void
3849 write_pch_user_walking_functions (type_p s, struct walk_type_data *d)
3850 {
3851   gcc_assert (s->kind == TYPE_USER_STRUCT);
3852
3853   for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
3854     {
3855       type_p fld_type = fld->type;
3856       if (union_or_struct_p (fld_type))
3857         write_pch_user_walking_for_structure_body (fld_type, d);
3858     }
3859 }
3860
3861
3862 /* process_field routine for local pointer-walking.  */
3863
3864 static void
3865 write_types_local_process_field (type_p f, const struct walk_type_data *d)
3866 {
3867   gcc_assert (d->have_this_obj);
3868   switch (f->kind)
3869     {
3870     case TYPE_POINTER:
3871     case TYPE_STRUCT:
3872     case TYPE_UNION:
3873     case TYPE_LANG_STRUCT:
3874     case TYPE_STRING:
3875       oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3876                d->prev_val[3]);
3877       oprintf (d->of, "%*s  op (&(%s), cookie);\n", d->indent, "", d->val);
3878       break;
3879
3880     case TYPE_USER_STRUCT:
3881       oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
3882                d->prev_val[3]);
3883       if (d->in_ptr_field)
3884         oprintf (d->of, "%*s  op (&(%s), cookie);\n", d->indent, "", d->val);
3885       else
3886         oprintf (d->of, "%*s  gt_pch_nx (&(%s), op, cookie);\n",
3887                  d->indent, "", d->val);
3888       break;
3889
3890     case TYPE_SCALAR:
3891       break;
3892
3893     case TYPE_ARRAY:
3894     case TYPE_NONE:
3895     case TYPE_UNDEFINED:
3896       gcc_unreachable ();
3897     }
3898 }
3899
3900
3901 /* For S, a structure that's part of ORIG_S, and using parameters
3902    PARAM, write out a routine that:
3903    - Is of type gt_note_pointers
3904    - Calls PROCESS_FIELD on each field of S or its substructures.
3905 */
3906
3907 static void
3908 write_local_func_for_structure (const_type_p orig_s, type_p s)
3909 {
3910   struct walk_type_data d;
3911
3912   /* Don't write fns for subclasses, only for the ultimate base class
3913      within an inheritance hierarchy.  */
3914   if (s->u.s.base_class)
3915     return;
3916
3917   memset (&d, 0, sizeof (d));
3918   d.of = get_output_file_for_structure (s);
3919   d.process_field = write_types_local_process_field;
3920   d.opt = s->u.s.opt;
3921   d.line = &s->u.s.line;
3922   d.bitmap = s->u.s.bitmap;
3923   d.prev_val[0] = d.prev_val[2] = "*x";
3924   d.prev_val[1] = "not valid postage";  /* Guarantee an error.  */
3925   d.prev_val[3] = "x";
3926   d.val = "(*x)";
3927   d.fn_wants_lvalue = true;
3928
3929   oprintf (d.of, "\n");
3930   oprintf (d.of, "void\n");
3931   oprintf (d.of, "gt_pch_p_");
3932   output_mangled_typename (d.of, orig_s);
3933   oprintf (d.of, " (ATTRIBUTE_UNUSED void *this_obj,\n"
3934            "\tvoid *x_p,\n"
3935            "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
3936            "\tATTRIBUTE_UNUSED void *cookie)\n");
3937   oprintf (d.of, "{\n");
3938   oprintf (d.of, "  %s %s * x ATTRIBUTE_UNUSED = (%s %s *)x_p;\n",
3939            s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag,
3940            s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
3941   d.indent = 2;
3942   d.have_this_obj = true;
3943
3944   if (s->kind != TYPE_USER_STRUCT)
3945     walk_type (s, &d);
3946   else
3947     {
3948       /* User structures have no fields to walk. Simply generate a
3949          call to the user-provided PCH walker.  */
3950       oprintf (d.of, "%*sif ((void *)(%s) == this_obj)\n", d.indent, "",
3951                d.prev_val[3]);
3952       oprintf (d.of, "%*s  gt_pch_nx (&(%s), op, cookie);\n",
3953                d.indent, "", d.val);
3954     }
3955
3956   oprintf (d.of, "}\n");
3957
3958   /* Write user-callable entry points for the PCH walking routines.  */
3959   if (orig_s->kind == TYPE_USER_STRUCT)
3960     write_pch_user_walking_functions (s, &d);
3961
3962   for (options_p o = s->u.s.opt; o; o = o->next)
3963     if (strcmp (o->name, "for_user") == 0)
3964       {
3965         write_pch_user_walking_for_structure_body (s, &d);
3966         break;
3967       }
3968 }
3969
3970 /* Write out local marker routines for STRUCTURES and PARAM_STRUCTS.  */
3971
3972 static void
3973 write_local (outf_p output_header, type_p structures)
3974 {
3975   type_p s;
3976
3977   if (!output_header)
3978     return;
3979
3980   oprintf (output_header, "\n/* Local pointer-walking routines.  */\n");
3981   for (s = structures; s; s = s->next)
3982     if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
3983       {
3984         options_p opt;
3985
3986         if (s->u.s.line.file == NULL)
3987           continue;
3988         for (opt = s->u.s.opt; opt; opt = opt->next)
3989           if (strcmp (opt->name, "ptr_alias") == 0
3990               && opt->kind == OPTION_TYPE)
3991             {
3992               const_type_p const t = (const_type_p) opt->info.type;
3993               if (t->kind == TYPE_STRUCT
3994                   || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
3995                 {
3996                   oprintf (output_header, "#define gt_pch_p_");
3997                   output_mangled_typename (output_header, s);
3998                   oprintf (output_header, " gt_pch_p_");
3999                   output_mangled_typename (output_header, t);
4000                   oprintf (output_header, "\n");
4001                 }
4002               else
4003                 error_at_line (&s->u.s.line,
4004                                "structure alias is not a structure");
4005               break;
4006             }
4007         if (opt)
4008           continue;
4009
4010         /* Declare the marker procedure only once.  */
4011         oprintf (output_header, "extern void gt_pch_p_");
4012         output_mangled_typename (output_header, s);
4013         oprintf (output_header,
4014                  "\n    (void *, void *, gt_pointer_operator, void *);\n");
4015
4016         if (s->kind == TYPE_LANG_STRUCT)
4017           {
4018             type_p ss;
4019             for (ss = s->u.s.lang_struct; ss; ss = ss->next)
4020               write_local_func_for_structure (s, ss);
4021           }
4022         else
4023           write_local_func_for_structure (s, s);
4024       }
4025 }
4026
4027 /* Nonzero if S is a type for which typed GC allocators should be output.  */
4028
4029 #define USED_BY_TYPED_GC_P(s)                                           \
4030   ((s->kind == TYPE_POINTER                                             \
4031     && (s->u.p->gc_used == GC_POINTED_TO                                \
4032         || s->u.p->gc_used == GC_USED))                                 \
4033    || (union_or_struct_p (s)                                            \
4034        && ((s)->gc_used == GC_POINTED_TO                                \
4035            || ((s)->gc_used == GC_MAYBE_POINTED_TO                      \
4036                && s->u.s.line.file != NULL)                             \
4037            || ((s)->gc_used == GC_USED                                  \
4038                && strncmp (s->u.s.tag, "anonymous", strlen ("anonymous"))) \
4039            || (s->u.s.base_class && opts_have (s->u.s.opt, "tag")))))
4040
4041
4042
4043 /* Might T contain any non-pointer elements?  */
4044
4045 static int
4046 contains_scalar_p (type_p t)
4047 {
4048   switch (t->kind)
4049     {
4050     case TYPE_STRING:
4051     case TYPE_POINTER:
4052       return 0;
4053     case TYPE_ARRAY:
4054       return contains_scalar_p (t->u.a.p);
4055     case TYPE_USER_STRUCT:
4056       /* User-marked structures will typically contain pointers.  */
4057       return 0;
4058     default:
4059       /* Could also check for structures that have no non-pointer
4060          fields, but there aren't enough of those to worry about.  */
4061       return 1;
4062     }
4063 }
4064
4065 /* Mangle INPF and print it to F.  */
4066
4067 static void
4068 put_mangled_filename (outf_p f, const input_file *inpf)
4069 {
4070   /* The call to get_output_file_name may indirectly update fn since
4071      get_output_file_with_visibility caches its result inside, so we
4072      need the CONST_CAST.  */
4073   const char *name = get_output_file_name (CONST_CAST (input_file*, inpf));
4074   if (!f || !name)
4075     return;
4076   for (; *name != 0; name++)
4077     if (ISALNUM (*name))
4078       oprintf (f, "%c", *name);
4079     else
4080       oprintf (f, "%c", '_');
4081 }
4082
4083 /* Finish off the currently-created root tables in FLP.  PFX, TNAME,
4084    LASTNAME, and NAME are all strings to insert in various places in
4085    the resulting code.  */
4086
4087 static void
4088 finish_root_table (struct flist *flp, const char *pfx, const char *lastname,
4089                    const char *tname, const char *name)
4090 {
4091   struct flist *fli2;
4092
4093   for (fli2 = flp; fli2; fli2 = fli2->next)
4094     if (fli2->started_p)
4095       {
4096         oprintf (fli2->f, "  %s\n", lastname);
4097         oprintf (fli2->f, "};\n\n");
4098       }
4099
4100   for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
4101     if (fli2->started_p)
4102       {
4103         lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4104         int fnum;
4105
4106         for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
4107           if (bitmap & 1)
4108             {
4109               oprintf (base_files[fnum],
4110                        "extern const struct %s gt_%s_", tname, pfx);
4111               put_mangled_filename (base_files[fnum], fli2->file);
4112               oprintf (base_files[fnum], "[];\n");
4113             }
4114       }
4115
4116   {
4117     size_t fnum;
4118     for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4119       oprintf (base_files[fnum],
4120                "EXPORTED_CONST struct %s * const %s[] = {\n", tname, name);
4121   }
4122
4123
4124   for (fli2 = flp; fli2; fli2 = fli2->next)
4125     if (fli2->started_p)
4126       {
4127         lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4128         int fnum;
4129
4130         fli2->started_p = 0;
4131
4132         for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
4133           if (bitmap & 1)
4134             {
4135               oprintf (base_files[fnum], "  gt_%s_", pfx);
4136               put_mangled_filename (base_files[fnum], fli2->file);
4137               oprintf (base_files[fnum], ",\n");
4138             }
4139       }
4140
4141   {
4142     size_t fnum;
4143     for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4144       {
4145         oprintf (base_files[fnum], "  NULL\n");
4146         oprintf (base_files[fnum], "};\n");
4147       }
4148   }
4149 }
4150
4151 /* Finish off the created gt_clear_caches_file_c functions.  */
4152
4153 static void
4154 finish_cache_funcs (flist *flp)
4155 {
4156   struct flist *fli2;
4157
4158   for (fli2 = flp; fli2; fli2 = fli2->next)
4159     if (fli2->started_p)
4160       {
4161         oprintf (fli2->f, "}\n\n");
4162       }
4163
4164   for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
4165     if (fli2->started_p)
4166       {
4167         lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4168         int fnum;
4169
4170         for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
4171           if (bitmap & 1)
4172             {
4173               oprintf (base_files[fnum], "extern void gt_clear_caches_");
4174               put_mangled_filename (base_files[fnum], fli2->file);
4175               oprintf (base_files[fnum], " ();\n");
4176             }
4177       }
4178
4179   for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4180     oprintf (base_files[fnum], "void\ngt_clear_caches ()\n{\n");
4181
4182   for (fli2 = flp; fli2; fli2 = fli2->next)
4183     if (fli2->started_p)
4184       {
4185         lang_bitmap bitmap = get_lang_bitmap (fli2->file);
4186         int fnum;
4187
4188         fli2->started_p = 0;
4189
4190         for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
4191           if (bitmap & 1)
4192             {
4193               oprintf (base_files[fnum], "  gt_clear_caches_");
4194               put_mangled_filename (base_files[fnum], fli2->file);
4195               oprintf (base_files[fnum], " ();\n");
4196             }
4197       }
4198
4199   for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
4200     {
4201       oprintf (base_files[fnum], "}\n");
4202     }
4203 }
4204
4205 /* Write the first three fields (pointer, count and stride) for
4206    root NAME to F.  V and LINE are as for write_root.
4207
4208    Return true if the entry could be written; return false on error.  */
4209
4210 static bool
4211 start_root_entry (outf_p f, pair_p v, const char *name, struct fileloc *line)
4212 {
4213   type_p ap;
4214
4215   if (!v)
4216     {
4217       error_at_line (line, "`%s' is too complex to be a root", name);
4218       return false;
4219     }
4220
4221   oprintf (f, "  {\n");
4222   oprintf (f, "    &%s,\n", name);
4223   oprintf (f, "    1");
4224
4225   for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
4226     if (ap->u.a.len[0])
4227       oprintf (f, " * (%s)", ap->u.a.len);
4228     else if (ap == v->type)
4229       oprintf (f, " * ARRAY_SIZE (%s)", v->name);
4230   oprintf (f, ",\n");
4231   oprintf (f, "    sizeof (%s", v->name);
4232   for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
4233     oprintf (f, "[0]");
4234   oprintf (f, "),\n");
4235   return true;
4236 }
4237
4238 /* A subroutine of write_root for writing the roots for field FIELD_NAME,
4239    which has type FIELD_TYPE.  Parameters F to EMIT_PCH are the parameters
4240    of the caller.  */
4241
4242 static void
4243 write_field_root (outf_p f, pair_p v, type_p type, const char *name,
4244                   int has_length, struct fileloc *line,
4245                   bool emit_pch, type_p field_type, const char *field_name)
4246 {
4247   struct pair newv;
4248   /* If the field reference is relative to V, rather than to some
4249      subcomponent of V, we can mark any subarrays with a single stride.
4250      We're effectively treating the field as a global variable in its
4251      own right.  */
4252   if (v && type == v->type)
4253     {
4254       newv = *v;
4255       newv.type = field_type;
4256       newv.name = ACONCAT ((v->name, ".", field_name, NULL));
4257       v = &newv;
4258     }
4259   /* Otherwise, any arrays nested in the structure are too complex to
4260      handle.  */
4261   else if (field_type->kind == TYPE_ARRAY)
4262     v = NULL;
4263   write_root (f, v, field_type, ACONCAT ((name, ".", field_name, NULL)),
4264               has_length, line, emit_pch);
4265 }
4266
4267 /* Write out to F the table entry and any marker routines needed to
4268    mark NAME as TYPE.  V can be one of three values:
4269
4270      - null, if NAME is too complex to represent using a single
4271        count and stride.  In this case, it is an error for NAME to
4272        contain any gc-ed data.
4273
4274      - the outermost array that contains NAME, if NAME is part of an array.
4275
4276      - the C variable that contains NAME, if NAME is not part of an array.
4277
4278    LINE is the line of the C source that declares the root variable.
4279    HAS_LENGTH is nonzero iff V was a variable-length array.  */
4280
4281 static void
4282 write_root (outf_p f, pair_p v, type_p type, const char *name, int has_length,
4283             struct fileloc *line, bool emit_pch)
4284 {
4285   switch (type->kind)
4286     {
4287     case TYPE_STRUCT:
4288       {
4289         pair_p fld;
4290         for (fld = type->u.s.fields; fld; fld = fld->next)
4291           {
4292             int skip_p = 0;
4293             const char *desc = NULL;
4294             options_p o;
4295
4296             for (o = fld->opt; o; o = o->next)
4297               if (strcmp (o->name, "skip") == 0)
4298                 skip_p = 1;
4299               else if (strcmp (o->name, "desc") == 0
4300                        && o->kind == OPTION_STRING)
4301                 desc = o->info.string;
4302               else
4303                 error_at_line (line,
4304                                "field `%s' of global `%s' has unknown option `%s'",
4305                                fld->name, name, o->name);
4306
4307             if (skip_p)
4308               continue;
4309             else if (desc && fld->type->kind == TYPE_UNION)
4310               {
4311                 pair_p validf = NULL;
4312                 pair_p ufld;
4313
4314                 for (ufld = fld->type->u.s.fields; ufld; ufld = ufld->next)
4315                   {
4316                     const char *tag = NULL;
4317                     options_p oo;
4318                     for (oo = ufld->opt; oo; oo = oo->next)
4319                       if (strcmp (oo->name, "tag") == 0
4320                           && oo->kind == OPTION_STRING)
4321                         tag = oo->info.string;
4322                     if (tag == NULL || strcmp (tag, desc) != 0)
4323                       continue;
4324                     if (validf != NULL)
4325                       error_at_line (line,
4326                                      "both `%s.%s.%s' and `%s.%s.%s' have tag `%s'",
4327                                      name, fld->name, validf->name,
4328                                      name, fld->name, ufld->name, tag);
4329                     validf = ufld;
4330                   }
4331                 if (validf != NULL)
4332                   write_field_root (f, v, type, name, 0, line, emit_pch,
4333                                     validf->type,
4334                                     ACONCAT ((fld->name, ".",
4335                                               validf->name, NULL)));
4336               }
4337             else if (desc)
4338               error_at_line (line,
4339                              "global `%s.%s' has `desc' option but is not union",
4340                              name, fld->name);
4341             else
4342               write_field_root (f, v, type, name, 0, line, emit_pch, fld->type,
4343                                 fld->name);
4344           }
4345       }
4346       break;
4347
4348     case TYPE_ARRAY:
4349       {
4350         char *newname;
4351         newname = xasprintf ("%s[0]", name);
4352         write_root (f, v, type->u.a.p, newname, has_length, line, emit_pch);
4353         free (newname);
4354       }
4355       break;
4356
4357     case TYPE_USER_STRUCT:
4358       error_at_line (line, "`%s' must be a pointer type, because it is "
4359                      "a GC root and its type is marked with GTY((user))",
4360                      v->name);
4361       break;
4362
4363     case TYPE_POINTER:
4364       {
4365         const_type_p tp;
4366
4367         if (!start_root_entry (f, v, name, line))
4368           return;
4369
4370         tp = type->u.p;
4371
4372         if (!has_length && union_or_struct_p (tp))
4373           {
4374             tp = get_ultimate_base_class (tp);
4375             const char *id_for_tag = filter_type_name (tp->u.s.tag);
4376             oprintf (f, "    &gt_ggc_mx_%s,\n", id_for_tag);
4377             if (emit_pch)
4378               oprintf (f, "    &gt_pch_nx_%s", id_for_tag);
4379             else
4380               oprintf (f, "    NULL");
4381             if (id_for_tag != tp->u.s.tag)
4382               free (CONST_CAST (char *, id_for_tag));
4383           }
4384         else if (has_length
4385                  && (tp->kind == TYPE_POINTER || union_or_struct_p (tp)))
4386           {
4387             oprintf (f, "    &gt_ggc_ma_%s,\n", name);
4388             if (emit_pch)
4389               oprintf (f, "    &gt_pch_na_%s", name);
4390             else
4391               oprintf (f, "    NULL");
4392           }
4393         else
4394           {
4395             error_at_line (line,
4396                            "global `%s' is pointer to unimplemented type",
4397                            name);
4398           }
4399         oprintf (f, "\n  },\n");
4400       }
4401       break;
4402
4403     case TYPE_STRING:
4404       {
4405         if (!start_root_entry (f, v, name, line))
4406           return;
4407
4408         oprintf (f, "    (gt_pointer_walker) &gt_ggc_m_S,\n");
4409         oprintf (f, "    (gt_pointer_walker) &gt_pch_n_S\n");
4410         oprintf (f, "  },\n");
4411       }
4412       break;
4413
4414     case TYPE_SCALAR:
4415       break;
4416
4417     case TYPE_NONE:
4418     case TYPE_UNDEFINED:
4419     case TYPE_UNION:
4420     case TYPE_LANG_STRUCT:
4421       error_at_line (line, "global `%s' is unimplemented type", name);
4422     }
4423 }
4424
4425 /* This generates a routine to walk an array.  */
4426
4427 static void
4428 write_array (outf_p f, pair_p v, const struct write_types_data *wtd)
4429 {
4430   struct walk_type_data d;
4431   char *prevval3;
4432
4433   memset (&d, 0, sizeof (d));
4434   d.of = f;
4435   d.cookie = wtd;
4436   d.indent = 2;
4437   d.line = &v->line;
4438   d.opt = v->opt;
4439   d.bitmap = get_lang_bitmap (v->line.file);
4440
4441   d.prev_val[3] = prevval3 = xasprintf ("&%s", v->name);
4442
4443   if (wtd->param_prefix)
4444     {
4445       oprintf (f, "static void gt_%sa_%s\n", wtd->param_prefix, v->name);
4446       oprintf (f, "    (void *, void *, gt_pointer_operator, void *);\n");
4447       oprintf (f, "static void gt_%sa_%s (ATTRIBUTE_UNUSED void *this_obj,\n",
4448                wtd->param_prefix, v->name);
4449       oprintf (d.of,
4450                "      ATTRIBUTE_UNUSED void *x_p,\n"
4451                "      ATTRIBUTE_UNUSED gt_pointer_operator op,\n"
4452                "      ATTRIBUTE_UNUSED void * cookie)\n");
4453       oprintf (d.of, "{\n");
4454       d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
4455       d.process_field = write_types_local_process_field;
4456       d.have_this_obj = true;
4457       walk_type (v->type, &d);
4458       oprintf (f, "}\n\n");
4459     }
4460
4461   d.opt = v->opt;
4462   oprintf (f, "static void gt_%sa_%s (void *);\n", wtd->prefix, v->name);
4463   oprintf (f, "static void\ngt_%sa_%s (ATTRIBUTE_UNUSED void *x_p)\n",
4464            wtd->prefix, v->name);
4465   oprintf (f, "{\n");
4466   d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
4467   d.process_field = write_types_process_field;
4468   d.have_this_obj = false;
4469   walk_type (v->type, &d);
4470   free (prevval3);
4471   oprintf (f, "}\n\n");
4472 }
4473
4474 /* Output a table describing the locations and types of VARIABLES.  */
4475
4476 static void
4477 write_roots (pair_p variables, bool emit_pch)
4478 {
4479   pair_p v;
4480   struct flist *flp = NULL;
4481
4482   for (v = variables; v; v = v->next)
4483     {
4484       outf_p f = 
4485         get_output_file_with_visibility (CONST_CAST (input_file*,
4486                                                      v->line.file));
4487       struct flist *fli;
4488       const char *length = NULL;
4489       int deletable_p = 0;
4490       options_p o;
4491       for (o = v->opt; o; o = o->next)
4492         if (strcmp (o->name, "length") == 0
4493             && o->kind == OPTION_STRING)
4494           length = o->info.string;
4495         else if (strcmp (o->name, "deletable") == 0)
4496           deletable_p = 1;
4497         else if (strcmp (o->name, "cache") == 0)
4498           ;
4499         else
4500           error_at_line (&v->line,
4501                          "global `%s' has unknown option `%s'",
4502                          v->name, o->name);
4503
4504       for (fli = flp; fli; fli = fli->next)
4505         if (fli->f == f && f)
4506           break;
4507       if (fli == NULL)
4508         {
4509           fli = XNEW (struct flist);
4510           fli->f = f;
4511           fli->next = flp;
4512           fli->started_p = 0;
4513           fli->file = v->line.file;
4514           gcc_assert (fli->file);
4515           flp = fli;
4516
4517           oprintf (f, "\n/* GC roots.  */\n\n");
4518         }
4519
4520       if (!deletable_p
4521           && length
4522           && v->type->kind == TYPE_POINTER
4523           && (v->type->u.p->kind == TYPE_POINTER
4524               || v->type->u.p->kind == TYPE_STRUCT))
4525         {
4526           write_array (f, v, &ggc_wtd);
4527           write_array (f, v, &pch_wtd);
4528         }
4529     }
4530
4531   for (v = variables; v; v = v->next)
4532     {
4533       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4534                                                               v->line.file));
4535       struct flist *fli;
4536       int skip_p = 0;
4537       int length_p = 0;
4538       options_p o;
4539
4540       for (o = v->opt; o; o = o->next)
4541         if (strcmp (o->name, "length") == 0)
4542           length_p = 1;
4543         else if (strcmp (o->name, "deletable") == 0)
4544           skip_p = 1;
4545
4546       if (skip_p)
4547         continue;
4548
4549       for (fli = flp; fli; fli = fli->next)
4550         if (fli->f == f)
4551           break;
4552       if (!fli->started_p)
4553         {
4554           fli->started_p = 1;
4555
4556           oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_r_");
4557           put_mangled_filename (f, v->line.file);
4558           oprintf (f, "[] = {\n");
4559         }
4560
4561       write_root (f, v, v->type, v->name, length_p, &v->line, emit_pch);
4562     }
4563
4564   finish_root_table (flp, "ggc_r", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4565                      "gt_ggc_rtab");
4566
4567   for (v = variables; v; v = v->next)
4568     {
4569       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4570                                                               v->line.file));
4571       struct flist *fli;
4572       int skip_p = 1;
4573       options_p o;
4574
4575       for (o = v->opt; o; o = o->next)
4576         if (strcmp (o->name, "deletable") == 0)
4577           skip_p = 0;
4578
4579       if (skip_p)
4580         continue;
4581
4582       for (fli = flp; fli; fli = fli->next)
4583         if (fli->f == f)
4584           break;
4585       if (!fli->started_p)
4586         {
4587           fli->started_p = 1;
4588
4589           oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_rd_");
4590           put_mangled_filename (f, v->line.file);
4591           oprintf (f, "[] = {\n");
4592         }
4593
4594       oprintf (f, "  { &%s, 1, sizeof (%s), NULL, NULL },\n",
4595                v->name, v->name);
4596     }
4597
4598   finish_root_table (flp, "ggc_rd", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4599                      "gt_ggc_deletable_rtab");
4600
4601   for (v = variables; v; v = v->next)
4602     {
4603       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4604                                                               v->line.file));
4605       struct flist *fli;
4606       bool cache = false;
4607       options_p o;
4608
4609       for (o = v->opt; o; o = o->next)
4610         if (strcmp (o->name, "cache") == 0)
4611           cache = true;
4612        if (!cache)
4613         continue;
4614
4615       for (fli = flp; fli; fli = fli->next)
4616         if (fli->f == f)
4617           break;
4618       if (!fli->started_p)
4619         {
4620           fli->started_p = 1;
4621
4622           oprintf (f, "void\ngt_clear_caches_");
4623           put_mangled_filename (f, v->line.file);
4624           oprintf (f, " ()\n{\n");
4625         }
4626
4627       oprintf (f, "  gt_cleare_cache (%s);\n", v->name);
4628     }
4629
4630   finish_cache_funcs (flp);
4631
4632   if (!emit_pch)
4633     return;
4634
4635   for (v = variables; v; v = v->next)
4636     {
4637       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
4638                                                               v->line.file));
4639       struct flist *fli;
4640       int skip_p = 0;
4641       options_p o;
4642
4643       for (o = v->opt; o; o = o->next)
4644         if (strcmp (o->name, "deletable") == 0)
4645           {
4646             skip_p = 1;
4647             break;
4648           }
4649
4650       if (skip_p)
4651         continue;
4652
4653       if (!contains_scalar_p (v->type))
4654         continue;
4655
4656       for (fli = flp; fli; fli = fli->next)
4657         if (fli->f == f)
4658           break;
4659       if (!fli->started_p)
4660         {
4661           fli->started_p = 1;
4662
4663           oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_pch_rs_");
4664           put_mangled_filename (f, v->line.file);
4665           oprintf (f, "[] = {\n");
4666         }
4667
4668       oprintf (f, "  { &%s, 1, sizeof (%s), NULL, NULL },\n",
4669                v->name, v->name);
4670     }
4671
4672   finish_root_table (flp, "pch_rs", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
4673                      "gt_pch_scalar_rtab");
4674 }
4675
4676 /* Prints not-as-ugly version of a typename of T to OF.  Trades the uniquness
4677    guaranteee for somewhat increased readability.  If name conflicts do happen,
4678    this funcion will have to be adjusted to be more like
4679    output_mangled_typename.  */
4680
4681 #define INDENT 2
4682
4683 /* Dumps the value of typekind KIND.  */
4684
4685 static void
4686 dump_typekind (int indent, enum typekind kind)
4687 {
4688   printf ("%*ckind = ", indent, ' ');
4689   switch (kind)
4690     {
4691     case TYPE_SCALAR:
4692       printf ("TYPE_SCALAR");
4693       break;
4694     case TYPE_STRING:
4695       printf ("TYPE_STRING");
4696       break;
4697     case TYPE_STRUCT:
4698       printf ("TYPE_STRUCT");
4699       break;
4700     case TYPE_UNDEFINED:
4701       printf ("TYPE_UNDEFINED");
4702       break;
4703     case TYPE_USER_STRUCT:
4704       printf ("TYPE_USER_STRUCT");
4705       break;
4706     case TYPE_UNION:
4707       printf ("TYPE_UNION");
4708       break;
4709     case TYPE_POINTER:
4710       printf ("TYPE_POINTER");
4711       break;
4712     case TYPE_ARRAY:
4713       printf ("TYPE_ARRAY");
4714       break;
4715     case TYPE_LANG_STRUCT:
4716       printf ("TYPE_LANG_STRUCT");
4717       break;
4718     default:
4719       gcc_unreachable ();
4720     }
4721   printf ("\n");
4722 }
4723
4724 /* Dumps the value of GC_USED flag.  */
4725
4726 static void
4727 dump_gc_used (int indent, enum gc_used_enum gc_used)
4728 {
4729   printf ("%*cgc_used = ", indent, ' ');
4730   switch (gc_used)
4731     {
4732     case GC_UNUSED:
4733       printf ("GC_UNUSED");
4734       break;
4735     case GC_USED:
4736       printf ("GC_USED");
4737       break;
4738     case GC_MAYBE_POINTED_TO:
4739       printf ("GC_MAYBE_POINTED_TO");
4740       break;
4741     case GC_POINTED_TO:
4742       printf ("GC_POINTED_TO");
4743       break;
4744     default:
4745       gcc_unreachable ();
4746     }
4747   printf ("\n");
4748 }
4749
4750 /* Dumps the type options OPT.  */
4751
4752 static void
4753 dump_options (int indent, options_p opt)
4754 {
4755   options_p o;
4756   printf ("%*coptions = ", indent, ' ');
4757   o = opt;
4758   while (o)
4759     {
4760       switch (o->kind)
4761         {
4762         case OPTION_STRING:
4763           printf ("%s:string %s ", o->name, o->info.string);
4764           break;
4765         case OPTION_TYPE:
4766           printf ("%s:type ", o->name);
4767           dump_type (indent+1, o->info.type);
4768           break;
4769         case OPTION_NESTED:
4770           printf ("%s:nested ", o->name);
4771           break;
4772         case OPTION_NONE:
4773           gcc_unreachable ();
4774         }
4775       o = o->next;
4776     }
4777   printf ("\n");
4778 }
4779
4780 /* Dumps the source file location in LINE.  */
4781
4782 static void
4783 dump_fileloc (int indent, struct fileloc line)
4784 {
4785   printf ("%*cfileloc: file = %s, line = %d\n", indent, ' ', 
4786           get_input_file_name (line.file),
4787           line.line);
4788 }
4789
4790 /* Recursively dumps the struct, union, or a language-specific
4791    struct T.  */
4792
4793 static void
4794 dump_type_u_s (int indent, type_p t)
4795 {
4796   pair_p fields;
4797
4798   gcc_assert (union_or_struct_p (t));
4799   printf ("%*cu.s.tag = %s\n", indent, ' ', t->u.s.tag);
4800   dump_fileloc (indent, t->u.s.line);
4801   printf ("%*cu.s.fields =\n", indent, ' ');
4802   fields = t->u.s.fields;
4803   while (fields)
4804     {
4805       dump_pair (indent + INDENT, fields);
4806       fields = fields->next;
4807     }
4808   printf ("%*cend of fields of type %p\n", indent, ' ', (void *) t);
4809   dump_options (indent, t->u.s.opt);
4810   printf ("%*cu.s.bitmap = %X\n", indent, ' ', t->u.s.bitmap);
4811   if (t->kind == TYPE_LANG_STRUCT)
4812     {
4813       printf ("%*cu.s.lang_struct:\n", indent, ' ');
4814       dump_type_list (indent + INDENT, t->u.s.lang_struct);
4815     }
4816 }
4817
4818 /* Recursively dumps the array T.  */
4819
4820 static void
4821 dump_type_u_a (int indent, type_p t)
4822 {
4823   gcc_assert (t->kind == TYPE_ARRAY);
4824   printf ("%*clen = %s, u.a.p:\n", indent, ' ', t->u.a.len);
4825   dump_type_list (indent + INDENT, t->u.a.p);
4826 }
4827
4828 /* Recursively dumps the type list T.  */
4829
4830 static void
4831 dump_type_list (int indent, type_p t)
4832 {
4833   type_p p = t;
4834   while (p)
4835     {
4836       dump_type (indent, p);
4837       p = p->next;
4838     }
4839 }
4840
4841 static htab_t seen_types;
4842
4843 /* Recursively dumps the type T if it was not dumped previously.  */
4844
4845 static void
4846 dump_type (int indent, type_p t)
4847 {
4848   PTR *slot;
4849
4850   printf ("%*cType at %p: ", indent, ' ', (void *) t);
4851   if (t->kind == TYPE_UNDEFINED)
4852     {
4853       gcc_assert (t->gc_used == GC_UNUSED);
4854       printf ("undefined.\n");
4855       return;
4856     }
4857
4858   if (seen_types == NULL)
4859     seen_types = htab_create (100, htab_hash_pointer, htab_eq_pointer, NULL);
4860
4861   slot = htab_find_slot (seen_types, t, INSERT);
4862   if (*slot != NULL)
4863     {
4864       printf ("already seen.\n");
4865       return;
4866     }
4867   *slot = t;
4868   printf ("\n");
4869
4870   dump_typekind (indent, t->kind);
4871   printf ("%*cpointer_to = %p\n", indent + INDENT, ' ',
4872           (void *) t->pointer_to);
4873   dump_gc_used (indent + INDENT, t->gc_used);
4874   switch (t->kind)
4875     {
4876     case TYPE_SCALAR:
4877       printf ("%*cscalar_is_char = %s\n", indent + INDENT, ' ',
4878               t->u.scalar_is_char ? "true" : "false");
4879       break;
4880     case TYPE_STRING:
4881       break;
4882     case TYPE_STRUCT:
4883     case TYPE_UNION:
4884     case TYPE_LANG_STRUCT:
4885     case TYPE_USER_STRUCT:
4886       dump_type_u_s (indent + INDENT, t);
4887       break;
4888     case TYPE_POINTER:
4889       printf ("%*cp:\n", indent + INDENT, ' ');
4890       dump_type (indent + INDENT, t->u.p);
4891       break;
4892     case TYPE_ARRAY:
4893       dump_type_u_a (indent + INDENT, t);
4894       break;
4895     default:
4896       gcc_unreachable ();
4897     }
4898   printf ("%*cEnd of type at %p\n", indent, ' ', (void *) t);
4899 }
4900
4901 /* Dumps the pair P.  */
4902
4903 static void
4904 dump_pair (int indent, pair_p p)
4905 {
4906   printf ("%*cpair: name = %s\n", indent, ' ', p->name);
4907   dump_type (indent, p->type);
4908   dump_fileloc (indent, p->line);
4909   dump_options (indent, p->opt);
4910   printf ("%*cEnd of pair %s\n", indent, ' ', p->name);
4911 }
4912
4913 /* Dumps the list of pairs PP.  */
4914
4915 static void
4916 dump_pair_list (const char *name, pair_p pp)
4917 {
4918   pair_p p;
4919   printf ("%s:\n", name);
4920   for (p = pp; p != NULL; p = p->next)
4921     dump_pair (0, p);
4922   printf ("End of %s\n\n", name);
4923 }
4924
4925 /* Dumps the STRUCTURES.  */
4926
4927 static void
4928 dump_structures (const char *name, type_p structures)
4929 {
4930   printf ("%s:\n", name);
4931   dump_type_list (0, structures);
4932   printf ("End of %s\n\n", name);
4933 }
4934
4935 /* Dumps the internal structures of gengtype.  This is useful to debug
4936    gengtype itself, or to understand what it does, e.g. for plugin
4937    developers.  */
4938
4939 static void
4940 dump_everything (void)
4941 {
4942   dump_pair_list ("typedefs", typedefs);
4943   dump_structures ("structures", structures);
4944   dump_pair_list ("variables", variables);
4945
4946   /* Allocated with the first call to dump_type.  */
4947   htab_delete (seen_types);
4948 }
4949 \f
4950
4951
4952 /* Option specification for getopt_long.  */
4953 static const struct option gengtype_long_options[] = {
4954   {"help", no_argument, NULL, 'h'},
4955   {"version", no_argument, NULL, 'V'},
4956   {"verbose", no_argument, NULL, 'v'},
4957   {"dump", no_argument, NULL, 'd'},
4958   {"debug", no_argument, NULL, 'D'},
4959   {"plugin", required_argument, NULL, 'P'},
4960   {"srcdir", required_argument, NULL, 'S'},
4961   {"backupdir", required_argument, NULL, 'B'},
4962   {"inputs", required_argument, NULL, 'I'},
4963   {"read-state", required_argument, NULL, 'r'},
4964   {"write-state", required_argument, NULL, 'w'},
4965   /* Terminating NULL placeholder.  */
4966   {NULL, no_argument, NULL, 0},
4967 };
4968
4969
4970 static void
4971 print_usage (void)
4972 {
4973   printf ("Usage: %s\n", progname);
4974   printf ("\t -h | --help " " \t# Give this help.\n");
4975   printf ("\t -D | --debug "
4976           " \t# Give debug output to debug %s itself.\n", progname);
4977   printf ("\t -V | --version " " \t# Give version information.\n");
4978   printf ("\t -v | --verbose  \t# Increase verbosity.  Can be given several times.\n");
4979   printf ("\t -d | --dump " " \t# Dump state for debugging.\n");
4980   printf ("\t -P | --plugin <output-file> <plugin-src> ... "
4981           " \t# Generate for plugin.\n");
4982   printf ("\t -S | --srcdir <GCC-directory> "
4983           " \t# Specify the GCC source directory.\n");
4984   printf ("\t -B | --backupdir <directory> "
4985           " \t# Specify the backup directory for updated files.\n");
4986   printf ("\t -I | --inputs <input-list> "
4987           " \t# Specify the file with source files list.\n");
4988   printf ("\t -w | --write-state <state-file> " " \t# Write a state file.\n");
4989   printf ("\t -r | --read-state <state-file> " " \t# Read a state file.\n");
4990 }
4991
4992 static void
4993 print_version (void)
4994 {
4995   printf ("%s %s%s\n", progname, pkgversion_string, version_string);
4996   printf ("Report bugs: %s\n", bug_report_url);
4997 }
4998
4999 /* Parse the program options using getopt_long... */
5000 static void
5001 parse_program_options (int argc, char **argv)
5002 {
5003   int opt = -1;
5004   while ((opt = getopt_long (argc, argv, "hVvdP:S:B:I:w:r:D",
5005                              gengtype_long_options, NULL)) >= 0)
5006     {
5007       switch (opt)
5008         {
5009         case 'h':               /* --help */
5010           print_usage ();
5011           break;
5012         case 'V':               /* --version */
5013           print_version ();
5014           break;
5015         case 'd':               /* --dump */
5016           do_dump = 1;
5017           break;
5018         case 'D':               /* --debug */
5019           do_debug = 1;
5020           break;
5021         case 'v':               /* --verbose */
5022           verbosity_level++;
5023           break;
5024         case 'P':               /* --plugin */
5025           if (optarg)
5026             plugin_output_filename = optarg;
5027           else
5028             fatal ("missing plugin output file name");
5029           break;
5030         case 'S':               /* --srcdir */
5031           if (optarg)
5032             srcdir = optarg;
5033           else
5034             fatal ("missing source directory");
5035           srcdir_len = strlen (srcdir);
5036           break;
5037         case 'B':               /* --backupdir */
5038           if (optarg)
5039             backup_dir = optarg;
5040           else
5041             fatal ("missing backup directory");
5042           break;
5043         case 'I':               /* --inputs */
5044           if (optarg)
5045             inputlist = optarg;
5046           else
5047             fatal ("missing input list");
5048           break;
5049         case 'r':               /* --read-state */
5050           if (optarg)
5051             read_state_filename = optarg;
5052           else
5053             fatal ("missing read state file");
5054           DBGPRINTF ("read state %s\n", optarg);
5055           break;
5056         case 'w':               /* --write-state */
5057           DBGPRINTF ("write state %s\n", optarg);
5058           if (optarg)
5059             write_state_filename = optarg;
5060           else
5061             fatal ("missing write state file");
5062           break;
5063         default:
5064           fprintf (stderr, "%s: unknown flag '%c'\n", progname, opt);
5065           print_usage ();
5066           fatal ("unexpected flag");
5067         }
5068     };
5069   if (plugin_output_filename)
5070     {
5071       /* In plugin mode we require some input files.  */
5072       int i = 0;
5073       if (optind >= argc)
5074         fatal ("no source files given in plugin mode");
5075       nb_plugin_files = argc - optind;
5076       plugin_files = XNEWVEC (input_file*, nb_plugin_files);
5077       for (i = 0; i < (int) nb_plugin_files; i++)
5078         {
5079           char *name = argv[i + optind];
5080           plugin_files[i] = input_file_by_name (name);
5081         }
5082     }
5083 }
5084
5085
5086 \f
5087 /******* Manage input files.  ******/
5088
5089 /* Hash table of unique input file names.  */
5090 static htab_t input_file_htab;
5091
5092 /* Find or allocate a new input_file by hash-consing it.  */
5093 input_file*
5094 input_file_by_name (const char* name)
5095 {
5096   PTR* slot;
5097   input_file* f = NULL;
5098   int namlen = 0;
5099   if (!name)
5100     return NULL;
5101   namlen = strlen (name);
5102   f = XCNEWVAR (input_file, sizeof (input_file)+namlen+2);
5103   f->inpbitmap = 0;
5104   f->inpoutf = NULL;
5105   f->inpisplugin = false;
5106   strcpy (f->inpname, name);
5107   slot = htab_find_slot (input_file_htab, f, INSERT);
5108   gcc_assert (slot != NULL);
5109   if (*slot)
5110     {
5111       /* Already known input file.  */
5112       free (f);
5113       return (input_file*)(*slot);
5114     }
5115   /* New input file.  */
5116   *slot = f;
5117   return f;
5118     }
5119
5120 /* Hash table support routines for input_file-s.  */
5121 static hashval_t
5122 htab_hash_inputfile (const void *p)
5123 {
5124   const input_file *inpf = (const input_file *) p;
5125   gcc_assert (inpf);
5126   return htab_hash_string (get_input_file_name (inpf));
5127 }
5128
5129 static int
5130 htab_eq_inputfile (const void *x, const void *y)
5131 {
5132   const input_file *inpfx = (const input_file *) x;
5133   const input_file *inpfy = (const input_file *) y;
5134   gcc_assert (inpfx != NULL && inpfy != NULL);
5135   return !filename_cmp (get_input_file_name (inpfx), get_input_file_name (inpfy));
5136 }
5137
5138
5139 int
5140 main (int argc, char **argv)
5141 {
5142   size_t i;
5143   static struct fileloc pos = { NULL, 0 };
5144   outf_p output_header;
5145
5146   /* Mandatory common initializations.  */
5147   progname = "gengtype";        /* For fatal and messages.  */
5148   /* Create the hash-table used to hash-cons input files.  */
5149   input_file_htab =
5150     htab_create (800, htab_hash_inputfile, htab_eq_inputfile, NULL);
5151   /* Initialize our special input files.  */
5152   this_file = input_file_by_name (__FILE__);
5153   system_h_file = input_file_by_name ("system.h");
5154   /* Set the scalar_is_char union number for predefined scalar types.  */
5155   scalar_nonchar.u.scalar_is_char = FALSE;
5156   scalar_char.u.scalar_is_char = TRUE;
5157
5158   parse_program_options (argc, argv);
5159
5160   if (do_debug)
5161     {
5162       time_t now = (time_t) 0;
5163       time (&now);
5164       DBGPRINTF ("gengtype started pid %d at %s",
5165                  (int) getpid (), ctime (&now));
5166     }
5167
5168   /* Parse the input list and the input files.  */
5169   DBGPRINTF ("inputlist %s", inputlist);
5170   if (read_state_filename)
5171     {
5172       if (inputlist)
5173         fatal ("input list %s cannot be given with a read state file %s",
5174                inputlist, read_state_filename);
5175       read_state (read_state_filename);
5176       DBGPRINT_COUNT_TYPE ("structures after read_state", structures);
5177     }
5178   else if (inputlist)
5179     {
5180       /* These types are set up with #define or else outside of where
5181          we can see them.  We should initialize them before calling
5182          read_input_list.  */
5183 #define POS_HERE(Call) do { pos.file = this_file; pos.line = __LINE__; \
5184         Call;} while (0)
5185       POS_HERE (do_scalar_typedef ("CUMULATIVE_ARGS", &pos));
5186       POS_HERE (do_scalar_typedef ("REAL_VALUE_TYPE", &pos));
5187       POS_HERE (do_scalar_typedef ("FIXED_VALUE_TYPE", &pos));
5188       POS_HERE (do_scalar_typedef ("double_int", &pos));
5189       POS_HERE (do_scalar_typedef ("offset_int", &pos));
5190       POS_HERE (do_scalar_typedef ("widest_int", &pos));
5191       POS_HERE (do_scalar_typedef ("int64_t", &pos));
5192       POS_HERE (do_scalar_typedef ("uint64_t", &pos));
5193       POS_HERE (do_scalar_typedef ("uint8", &pos));
5194       POS_HERE (do_scalar_typedef ("uintptr_t", &pos));
5195       POS_HERE (do_scalar_typedef ("jword", &pos));
5196       POS_HERE (do_scalar_typedef ("JCF_u2", &pos));
5197       POS_HERE (do_scalar_typedef ("void", &pos));
5198       POS_HERE (do_scalar_typedef ("machine_mode", &pos));
5199       POS_HERE (do_typedef ("PTR", 
5200                             create_pointer (resolve_typedef ("void", &pos)),
5201                             &pos));
5202 #undef POS_HERE
5203       read_input_list (inputlist);
5204       for (i = 0; i < num_gt_files; i++)
5205         {
5206           parse_file (get_input_file_name (gt_files[i]));
5207           DBGPRINTF ("parsed file #%d %s", 
5208                      (int) i, get_input_file_name (gt_files[i]));
5209         }
5210       if (verbosity_level >= 1)
5211         printf ("%s parsed %d files with %d GTY types\n", 
5212                 progname, (int) num_gt_files, type_count);
5213
5214       DBGPRINT_COUNT_TYPE ("structures after parsing", structures);
5215     }
5216   else
5217     fatal ("either an input list or a read state file should be given");
5218   if (hit_error)
5219     return 1;
5220
5221
5222   if (plugin_output_filename)
5223     {
5224       size_t ix = 0;
5225       /* In plugin mode, we should have read a state file, and have
5226          given at least one plugin file.  */
5227       if (!read_state_filename)
5228         fatal ("No read state given in plugin mode for %s",
5229                plugin_output_filename);
5230
5231       if (nb_plugin_files == 0 || !plugin_files)
5232         fatal ("No plugin files given in plugin mode for %s",
5233                plugin_output_filename);
5234
5235       /* Parse our plugin files and augment the state.  */
5236       for (ix = 0; ix < nb_plugin_files; ix++)
5237         {
5238           input_file* pluginput = plugin_files [ix];
5239           pluginput->inpisplugin = true;
5240           parse_file (get_input_file_name (pluginput));
5241         }
5242       if (hit_error)
5243         return 1;
5244
5245       plugin_output = create_file ("GCC", plugin_output_filename);
5246       DBGPRINTF ("created plugin_output %p named %s",
5247                  (void *) plugin_output, plugin_output->name);
5248     }
5249   else
5250     {                           /* No plugin files, we are in normal mode.  */
5251       if (!srcdir)
5252         fatal ("gengtype needs a source directory in normal mode");
5253     }
5254   if (hit_error)
5255     return 1;
5256
5257   gen_rtx_next ();
5258
5259   set_gc_used (variables);
5260
5261   for (type_p t = structures; t; t = t->next)
5262     {
5263       bool for_user = false;
5264       for (options_p o = t->u.s.opt; o; o = o->next)
5265         if (strcmp (o->name, "for_user") == 0)
5266           {
5267             for_user = true;
5268             break;
5269           }
5270
5271       if (for_user)
5272         set_gc_used_type (t, GC_POINTED_TO);
5273     }
5274  /* The state at this point is read from the state input file or by
5275     parsing source files and optionally augmented by parsing plugin
5276     source files.  Write it now.  */
5277   if (write_state_filename)
5278     {
5279       DBGPRINT_COUNT_TYPE ("structures before write_state", structures);
5280
5281       if (hit_error)
5282         fatal ("didn't write state file %s after errors", 
5283                write_state_filename);
5284
5285       DBGPRINTF ("before write_state %s", write_state_filename);
5286       write_state (write_state_filename);
5287
5288       if (do_dump)
5289         dump_everything ();
5290
5291       /* After having written the state file we return immediately to
5292          avoid generating any output file.  */
5293       if (hit_error)
5294         return 1;
5295       else
5296         return 0;
5297     }
5298
5299
5300   open_base_files ();
5301
5302   output_header = plugin_output ? plugin_output : header_file;
5303   DBGPRINT_COUNT_TYPE ("structures before write_types outputheader",
5304                        structures);
5305
5306   write_types (output_header, structures, &ggc_wtd);
5307   if (plugin_files == NULL)
5308     {
5309       DBGPRINT_COUNT_TYPE ("structures before write_types headerfil",
5310                            structures);
5311       write_types (header_file, structures, &pch_wtd);
5312       write_local (header_file, structures);
5313     }
5314   write_roots (variables, plugin_files == NULL);
5315   write_rtx_next ();
5316   close_output_files ();
5317
5318   if (do_dump)
5319     dump_everything ();
5320
5321   /* Don't bother about free-ing any input or plugin file, etc.  */
5322
5323   if (hit_error)
5324     return 1;
5325   return 0;
5326 }