OSDN Git Service

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