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