OSDN Git Service

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