OSDN Git Service

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