xref: /dragonfly/contrib/gcc-8.0/gcc/cp/rtti.c (revision 2b3f93ea)
1 /* RunTime Type Identification
2    Copyright (C) 1995-2018 Free Software Foundation, Inc.
3    Mostly written by Jason Merrill (jason@cygnus.com).
4 
5 This file is part of GCC.
6 
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11 
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20 
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "target.h"
25 #include "cp-tree.h"
26 #include "memmodel.h"
27 #include "tm_p.h"
28 #include "stringpool.h"
29 #include "intl.h"
30 #include "stor-layout.h"
31 #include "c-family/c-pragma.h"
32 #include "gcc-rich-location.h"
33 
34 /* C++ returns type information to the user in struct type_info
35    objects. We also use type information to implement dynamic_cast and
36    exception handlers. Type information for a particular type is
37    indicated with an ABI defined structure derived from type_info.
38    This would all be very straight forward, but for the fact that the
39    runtime library provides the definitions of the type_info structure
40    and the ABI defined derived classes. We cannot build declarations
41    of them directly in the compiler, but we need to layout objects of
42    their type.  Somewhere we have to lie.
43 
44    We define layout compatible POD-structs with compiler-defined names
45    and generate the appropriate initializations for them (complete
46    with explicit mention of their vtable). When we have to provide a
47    type_info to the user we reinterpret_cast the internal compiler
48    type to type_info.  A well formed program can only explicitly refer
49    to the type_infos of complete types (& cv void).  However, we chain
50    pointer type_infos to the pointed-to-type, and that can be
51    incomplete.  We only need the addresses of such incomplete
52    type_info objects for static initialization.
53 
54    The type information VAR_DECL of a type is held on the
55    get_global_binding of the type's mangled name. That VAR_DECL
56    will be the internal type.  It will usually have the correct
57    internal type reflecting the kind of type it represents (pointer,
58    array, function, class, inherited class, etc).  When the type it
59    represents is incomplete, it will have the internal type
60    corresponding to type_info.  That will only happen at the end of
61    translation, when we are emitting the type info objects.  */
62 
63 /* Auxiliary data we hold for each type_info derived object we need.  */
64 struct GTY (()) tinfo_s {
65   tree type;  /* The RECORD_TYPE for this type_info object */
66 
67   tree vtable; /* The VAR_DECL of the vtable.  Only filled at end of
68 		  translation.  */
69 
70   tree name;  /* IDENTIFIER_NODE for the ABI specified name of
71 		 the type_info derived type.  */
72 };
73 
74 
75 enum tinfo_kind
76 {
77   TK_TYPE_INFO_TYPE,    /* abi::__type_info_pseudo */
78   TK_BASE_TYPE,		/* abi::__base_class_type_info */
79   TK_DERIVED_TYPES,	/* Start of types derived from abi::__type_info  */
80   TK_BUILTIN_TYPE = TK_DERIVED_TYPES,	/* abi::__fundamental_type_info */
81   TK_ARRAY_TYPE,	/* abi::__array_type_info */
82   TK_FUNCTION_TYPE,	/* abi::__function_type_info */
83   TK_ENUMERAL_TYPE,	/* abi::__enum_type_info */
84   TK_POINTER_TYPE,	/* abi::__pointer_type_info */
85   TK_POINTER_MEMBER_TYPE, /* abi::__pointer_to_member_type_info */
86   TK_CLASS_TYPE,	/* abi::__class_type_info */
87   TK_SI_CLASS_TYPE,	/* abi::__si_class_type_info */
88   TK_VMI_CLASS_TYPES,	/* abi::__vmi_class_type_info<int> */
89   TK_MAX
90 };
91 
92 /* Names of the tinfo types.  Must be same order as TK enumeration
93    above.  */
94 
95 static const char *const tinfo_names[TK_MAX] =
96 {
97   "__type_info",
98   "__base_class_type_info",
99   "__fundamental_type_info",
100   "__array_type_info",
101   "__function_type_info",
102   "__enum_type_info",
103   "__pointer_type_info",
104   "__pointer_to_member_type_info",
105   "__class_type_info",
106   "__si_class_type_info",
107   "__vmi_class_type_info"
108 };
109 
110 /* Helper macro to get maximum scalar-width of pointer or of the 'long'-type.
111    This of interest for llp64 targets.  */
112 #define LONGPTR_T \
113   integer_types[(POINTER_SIZE <= TYPE_PRECISION (integer_types[itk_long]) \
114 		 ? itk_long : itk_long_long)]
115 
116 /* A vector of all tinfo decls that haven't yet been emitted.  */
117 vec<tree, va_gc> *unemitted_tinfo_decls;
118 
119 /* A vector of all type_info derived types we need.  The first few are
120    fixed and created early. The remainder are for multiple inheritance
121    and are generated as needed. */
122 static GTY (()) vec<tinfo_s, va_gc> *tinfo_descs;
123 
124 static tree ifnonnull (tree, tree, tsubst_flags_t);
125 static tree tinfo_name (tree, bool);
126 static tree build_dynamic_cast_1 (tree, tree, tsubst_flags_t);
127 static tree throw_bad_cast (void);
128 static tree throw_bad_typeid (void);
129 static tree get_tinfo_ptr (tree);
130 static bool typeid_ok_p (void);
131 static int qualifier_flags (tree);
132 static bool target_incomplete_p (tree);
133 static tree tinfo_base_init (tinfo_s *, tree);
134 static tree generic_initializer (tinfo_s *, tree);
135 static tree ptr_initializer (tinfo_s *, tree);
136 static tree ptm_initializer (tinfo_s *, tree);
137 static tree class_initializer (tinfo_s *, tree, unsigned, ...);
138 static tree get_pseudo_ti_init (tree, unsigned);
139 static unsigned get_pseudo_ti_index (tree);
140 static tinfo_s *get_tinfo_desc (unsigned);
141 static void create_tinfo_types (void);
142 static bool typeinfo_in_lib_p (tree);
143 
144 static int doing_runtime = 0;
145 
146 static void
147 push_abi_namespace (void)
148 {
149   push_nested_namespace (abi_node);
150   push_visibility ("default", 2);
151 }
152 
153 static void
154 pop_abi_namespace (void)
155 {
156   pop_visibility (2);
157   pop_nested_namespace (abi_node);
158 }
159 
160 /* Declare language defined type_info type and a pointer to const
161    type_info.  This is incomplete here, and will be completed when
162    the user #includes <typeinfo>.  There are language defined
163    restrictions on what can be done until that is included.  Create
164    the internal versions of the ABI types.  */
165 
166 void
167 init_rtti_processing (void)
168 {
169   tree type_info_type;
170 
171   push_namespace (std_identifier);
172   type_info_type = xref_tag (class_type, get_identifier ("type_info"),
173 			     /*tag_scope=*/ts_current, false);
174   pop_namespace ();
175   const_type_info_type_node
176     = cp_build_qualified_type (type_info_type, TYPE_QUAL_CONST);
177   type_info_ptr_type = build_pointer_type (const_type_info_type_node);
178 
179   vec_alloc (unemitted_tinfo_decls, 124);
180 
181   create_tinfo_types ();
182 }
183 
184 /* Given the expression EXP of type `class *', return the head of the
185    object pointed to by EXP with type cv void*, if the class has any
186    virtual functions (TYPE_POLYMORPHIC_P), else just return the
187    expression.  */
188 
189 tree
190 build_headof (tree exp)
191 {
192   tree type = TREE_TYPE (exp);
193   tree offset;
194   tree index;
195 
196   gcc_assert (TYPE_PTR_P (type));
197   type = TREE_TYPE (type);
198 
199   if (!TYPE_POLYMORPHIC_P (type))
200     return exp;
201 
202   /* We use this a couple of times below, protect it.  */
203   exp = save_expr (exp);
204 
205   /* The offset-to-top field is at index -2 from the vptr.  */
206   index = build_int_cst (NULL_TREE,
207 			 -2 * TARGET_VTABLE_DATA_ENTRY_DISTANCE);
208 
209   offset = build_vtbl_ref (cp_build_fold_indirect_ref (exp),
210                            index);
211 
212   type = cp_build_qualified_type (ptr_type_node,
213 				  cp_type_quals (TREE_TYPE (exp)));
214   return fold_build_pointer_plus (exp, offset);
215 }
216 
217 /* Get a bad_cast node for the program to throw...
218 
219    See libstdc++/exception.cc for __throw_bad_cast */
220 
221 static tree
222 throw_bad_cast (void)
223 {
224   static tree fn;
225   if (!fn)
226     {
227       tree name = get_identifier ("__cxa_bad_cast");
228       fn = get_global_binding (name);
229       if (!fn)
230 	fn = push_throw_library_fn
231 	  (name, build_function_type_list (ptr_type_node, NULL_TREE));
232     }
233 
234   return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
235 }
236 
237 /* Return an expression for "__cxa_bad_typeid()".  The expression
238    returned is an lvalue of type "const std::type_info".  */
239 
240 static tree
241 throw_bad_typeid (void)
242 {
243   static tree fn;
244   if (!fn)
245     {
246       tree name = get_identifier ("__cxa_bad_typeid");
247       fn = get_global_binding (name);
248       if (!fn)
249 	{
250 	  tree t = build_reference_type (const_type_info_type_node);
251 	  t = build_function_type_list (t, NULL_TREE);
252 	  fn = push_throw_library_fn (name, t);
253 	}
254     }
255 
256   return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
257 }
258 
259 /* Return an lvalue expression whose type is "const std::type_info"
260    and whose value indicates the type of the expression EXP.  If EXP
261    is a reference to a polymorphic class, return the dynamic type;
262    otherwise return the static type of the expression.  */
263 
264 static tree
265 get_tinfo_decl_dynamic (tree exp, tsubst_flags_t complain)
266 {
267   tree type;
268   tree t;
269 
270   if (error_operand_p (exp))
271     return error_mark_node;
272 
273   exp = resolve_nondeduced_context (exp, complain);
274 
275   /* peel back references, so they match.  */
276   type = non_reference (TREE_TYPE (exp));
277 
278   /* Peel off cv qualifiers.  */
279   type = TYPE_MAIN_VARIANT (type);
280 
281   /* For UNKNOWN_TYPEs call complete_type_or_else to get diagnostics.  */
282   if (CLASS_TYPE_P (type) || type == unknown_type_node
283       || type == init_list_type_node)
284     type = complete_type_or_maybe_complain (type, exp, complain);
285 
286   if (!type)
287     return error_mark_node;
288 
289   /* If exp is a reference to polymorphic type, get the real type_info.  */
290   if (TYPE_POLYMORPHIC_P (type) && ! resolves_to_fixed_type_p (exp, 0))
291     {
292       /* build reference to type_info from vtable.  */
293       tree index;
294 
295       /* The RTTI information is at index -1.  */
296       index = build_int_cst (NULL_TREE,
297 			     -1 * TARGET_VTABLE_DATA_ENTRY_DISTANCE);
298       t = build_vtbl_ref (exp, index);
299       t = convert (type_info_ptr_type, t);
300     }
301   else
302     /* Otherwise return the type_info for the static type of the expr.  */
303     t = get_tinfo_ptr (TYPE_MAIN_VARIANT (type));
304 
305   return cp_build_fold_indirect_ref (t);
306 }
307 
308 static bool
309 typeid_ok_p (void)
310 {
311   if (! flag_rtti)
312     {
313       error ("cannot use %<typeid%> with -fno-rtti");
314       return false;
315     }
316 
317   if (!COMPLETE_TYPE_P (const_type_info_type_node))
318     {
319       gcc_rich_location richloc (input_location);
320       maybe_add_include_fixit (&richloc, "<typeinfo>");
321       error_at (&richloc,
322 		"must %<#include <typeinfo>%> before using"
323 		" %<typeid%>");
324 
325       return false;
326     }
327 
328   tree pseudo = TYPE_MAIN_VARIANT (get_tinfo_desc (TK_TYPE_INFO_TYPE)->type);
329   tree real = TYPE_MAIN_VARIANT (const_type_info_type_node);
330 
331   /* Make sure abi::__type_info_pseudo has the same alias set
332      as std::type_info.  */
333   if (! TYPE_ALIAS_SET_KNOWN_P (pseudo))
334     TYPE_ALIAS_SET (pseudo) = get_alias_set (real);
335   else
336     gcc_assert (TYPE_ALIAS_SET (pseudo) == get_alias_set (real));
337 
338   return true;
339 }
340 
341 /* Return an expression for "typeid(EXP)".  The expression returned is
342    an lvalue of type "const std::type_info".  */
343 
344 tree
345 build_typeid (tree exp, tsubst_flags_t complain)
346 {
347   tree cond = NULL_TREE, initial_expr = exp;
348   int nonnull = 0;
349 
350   if (exp == error_mark_node || !typeid_ok_p ())
351     return error_mark_node;
352 
353   if (processing_template_decl)
354     return build_min (TYPEID_EXPR, const_type_info_type_node, exp);
355 
356   /* FIXME when integrating with c_fully_fold, mark
357      resolves_to_fixed_type_p case as a non-constant expression.  */
358   if (TYPE_POLYMORPHIC_P (TREE_TYPE (exp))
359       && ! resolves_to_fixed_type_p (exp, &nonnull)
360       && ! nonnull)
361     {
362       /* So we need to look into the vtable of the type of exp.
363          Make sure it isn't a null lvalue.  */
364       exp = cp_build_addr_expr (exp, complain);
365       exp = save_expr (exp);
366       cond = cp_convert (boolean_type_node, exp, complain);
367       exp = cp_build_fold_indirect_ref (exp);
368     }
369 
370   exp = get_tinfo_decl_dynamic (exp, complain);
371 
372   if (exp == error_mark_node)
373     return error_mark_node;
374 
375   if (cond)
376     {
377       tree bad = throw_bad_typeid ();
378 
379       exp = build3 (COND_EXPR, TREE_TYPE (exp), cond, exp, bad);
380     }
381   else
382     mark_type_use (initial_expr);
383 
384   return exp;
385 }
386 
387 /* Generate the NTBS name of a type.  If MARK_PRIVATE, put a '*' in front so that
388    comparisons will be done by pointer rather than string comparison.  */
389 static tree
390 tinfo_name (tree type, bool mark_private)
391 {
392   const char *name;
393   int length;
394   tree name_string;
395 
396   name = mangle_type_string (type);
397   length = strlen (name);
398 
399   if (mark_private)
400     {
401       /* Inject '*' at beginning of name to force pointer comparison.  */
402       char* buf = (char*) XALLOCAVEC (char, length + 2);
403       buf[0] = '*';
404       memcpy (buf + 1, name, length + 1);
405       name_string = build_string (length + 2, buf);
406     }
407   else
408     name_string = build_string (length + 1, name);
409 
410   return fix_string_type (name_string);
411 }
412 
413 /* Return a VAR_DECL for the internal ABI defined type_info object for
414    TYPE. You must arrange that the decl is mark_used, if actually use
415    it --- decls in vtables are only used if the vtable is output.  */
416 
417 tree
418 get_tinfo_decl (tree type)
419 {
420   tree name;
421   tree d;
422 
423   if (variably_modified_type_p (type, /*fn=*/NULL_TREE))
424     {
425       error ("cannot create type information for type %qT because "
426 	     "it involves types of variable size",
427 	     type);
428       return error_mark_node;
429     }
430 
431   if (TREE_CODE (type) == METHOD_TYPE)
432     type = build_function_type (TREE_TYPE (type),
433 				TREE_CHAIN (TYPE_ARG_TYPES (type)));
434 
435   type = complete_type (type);
436 
437   /* For a class type, the variable is cached in the type node
438      itself.  */
439   if (CLASS_TYPE_P (type))
440     {
441       d = CLASSTYPE_TYPEINFO_VAR (TYPE_MAIN_VARIANT (type));
442       if (d)
443 	return d;
444     }
445 
446   name = mangle_typeinfo_for_type (type);
447 
448   d = get_global_binding (name);
449   if (!d)
450     {
451       int ix = get_pseudo_ti_index (type);
452       const tinfo_s *ti = get_tinfo_desc (ix);
453 
454       d = build_lang_decl (VAR_DECL, name, ti->type);
455       SET_DECL_ASSEMBLER_NAME (d, name);
456       /* Remember the type it is for.  */
457       TREE_TYPE (name) = type;
458       DECL_TINFO_P (d) = 1;
459       DECL_ARTIFICIAL (d) = 1;
460       DECL_IGNORED_P (d) = 1;
461       TREE_READONLY (d) = 1;
462       TREE_STATIC (d) = 1;
463       /* Mark the variable as undefined -- but remember that we can
464 	 define it later if we need to do so.  */
465       DECL_EXTERNAL (d) = 1;
466       DECL_NOT_REALLY_EXTERN (d) = 1;
467       set_linkage_according_to_type (type, d);
468 
469       d = pushdecl_top_level_and_finish (d, NULL_TREE);
470       if (CLASS_TYPE_P (type))
471 	CLASSTYPE_TYPEINFO_VAR (TYPE_MAIN_VARIANT (type)) = d;
472 
473       /* Add decl to the global array of tinfo decls.  */
474       vec_safe_push (unemitted_tinfo_decls, d);
475     }
476 
477   return d;
478 }
479 
480 /* Return a pointer to a type_info object describing TYPE, suitably
481    cast to the language defined type.  */
482 
483 static tree
484 get_tinfo_ptr (tree type)
485 {
486   tree decl = get_tinfo_decl (type);
487 
488   mark_used (decl);
489   return build_nop (type_info_ptr_type,
490 		    build_address (decl));
491 }
492 
493 /* Return the type_info object for TYPE.  */
494 
495 tree
496 get_typeid (tree type, tsubst_flags_t complain)
497 {
498   if (type == error_mark_node || !typeid_ok_p ())
499     return error_mark_node;
500 
501   if (processing_template_decl)
502     return build_min (TYPEID_EXPR, const_type_info_type_node, type);
503 
504   /* If the type of the type-id is a reference type, the result of the
505      typeid expression refers to a type_info object representing the
506      referenced type.  */
507   type = non_reference (type);
508 
509   /* This is not one of the uses of a qualified function type in 8.3.5.  */
510   if (TREE_CODE (type) == FUNCTION_TYPE
511       && (type_memfn_quals (type) != TYPE_UNQUALIFIED
512 	  || type_memfn_rqual (type) != REF_QUAL_NONE))
513     {
514       if (complain & tf_error)
515 	error ("typeid of qualified function type %qT", type);
516       return error_mark_node;
517     }
518 
519   /* The top-level cv-qualifiers of the lvalue expression or the type-id
520      that is the operand of typeid are always ignored.  */
521   type = TYPE_MAIN_VARIANT (type);
522 
523   /* For UNKNOWN_TYPEs call complete_type_or_else to get diagnostics.  */
524   if (CLASS_TYPE_P (type) || type == unknown_type_node
525       || type == init_list_type_node)
526     type = complete_type_or_maybe_complain (type, NULL_TREE, complain);
527 
528   if (!type)
529     return error_mark_node;
530 
531   return cp_build_fold_indirect_ref (get_tinfo_ptr (type));
532 }
533 
534 /* Check whether TEST is null before returning RESULT.  If TEST is used in
535    RESULT, it must have previously had a save_expr applied to it.  */
536 
537 static tree
538 ifnonnull (tree test, tree result, tsubst_flags_t complain)
539 {
540   tree cond = build2 (NE_EXPR, boolean_type_node, test,
541 		      cp_convert (TREE_TYPE (test), nullptr_node, complain));
542   /* This is a compiler generated comparison, don't emit
543      e.g. -Wnonnull-compare warning for it.  */
544   TREE_NO_WARNING (cond) = 1;
545   return build3 (COND_EXPR, TREE_TYPE (result), cond, result,
546 		 cp_convert (TREE_TYPE (result), nullptr_node, complain));
547 }
548 
549 /* Execute a dynamic cast, as described in section 5.2.6 of the 9/93 working
550    paper.  */
551 
552 static tree
553 build_dynamic_cast_1 (tree type, tree expr, tsubst_flags_t complain)
554 {
555   enum tree_code tc = TREE_CODE (type);
556   tree exprtype;
557   tree dcast_fn;
558   tree old_expr = expr;
559   const char *errstr = NULL;
560 
561   /* Save casted types in the function's used types hash table.  */
562   used_types_insert (type);
563 
564   /* T shall be a pointer or reference to a complete class type, or
565      `pointer to cv void''.  */
566   switch (tc)
567     {
568     case POINTER_TYPE:
569       if (VOID_TYPE_P (TREE_TYPE (type)))
570 	break;
571       /* Fall through.  */
572     case REFERENCE_TYPE:
573       if (! MAYBE_CLASS_TYPE_P (TREE_TYPE (type)))
574 	{
575 	  errstr = _("target is not pointer or reference to class");
576 	  goto fail;
577 	}
578       if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
579 	{
580 	  errstr = _("target is not pointer or reference to complete type");
581 	  goto fail;
582 	}
583       break;
584 
585     default:
586       errstr = _("target is not pointer or reference");
587       goto fail;
588     }
589 
590   if (tc == POINTER_TYPE)
591     {
592       expr = decay_conversion (expr, complain);
593       exprtype = TREE_TYPE (expr);
594 
595       /* If T is a pointer type, v shall be an rvalue of a pointer to
596 	 complete class type, and the result is an rvalue of type T.  */
597 
598       expr = mark_rvalue_use (expr);
599 
600       if (!TYPE_PTR_P (exprtype))
601 	{
602 	  errstr = _("source is not a pointer");
603 	  goto fail;
604 	}
605       if (! MAYBE_CLASS_TYPE_P (TREE_TYPE (exprtype)))
606 	{
607 	  errstr = _("source is not a pointer to class");
608 	  goto fail;
609 	}
610       if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (exprtype))))
611 	{
612 	  errstr = _("source is a pointer to incomplete type");
613 	  goto fail;
614 	}
615     }
616   else
617     {
618       expr = mark_lvalue_use (expr);
619 
620       exprtype = build_reference_type (TREE_TYPE (expr));
621 
622       /* T is a reference type, v shall be an lvalue of a complete class
623 	 type, and the result is an lvalue of the type referred to by T.  */
624 
625       if (! MAYBE_CLASS_TYPE_P (TREE_TYPE (exprtype)))
626 	{
627 	  errstr = _("source is not of class type");
628 	  goto fail;
629 	}
630       if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (exprtype))))
631 	{
632 	  errstr = _("source is of incomplete class type");
633 	  goto fail;
634 	}
635     }
636 
637   /* The dynamic_cast operator shall not cast away constness.  */
638   if (!at_least_as_qualified_p (TREE_TYPE (type),
639 				TREE_TYPE (exprtype)))
640     {
641       errstr = _("conversion casts away constness");
642       goto fail;
643     }
644 
645   /* If *type is an unambiguous accessible base class of *exprtype,
646      convert statically.  */
647   {
648     tree binfo = lookup_base (TREE_TYPE (exprtype), TREE_TYPE (type),
649 			      ba_check, NULL, complain);
650     if (binfo)
651       return build_static_cast (type, expr, complain);
652   }
653 
654   /* Apply trivial conversion T -> T& for dereferenced ptrs.  */
655   if (tc == REFERENCE_TYPE)
656     expr = convert_to_reference (exprtype, expr, CONV_IMPLICIT,
657 				 LOOKUP_NORMAL, NULL_TREE, complain);
658 
659   /* Otherwise *exprtype must be a polymorphic class (have a vtbl).  */
660   if (TYPE_POLYMORPHIC_P (TREE_TYPE (exprtype)))
661     {
662       tree expr1;
663       /* if TYPE is `void *', return pointer to complete object.  */
664       if (tc == POINTER_TYPE && VOID_TYPE_P (TREE_TYPE (type)))
665 	{
666 	  /* if b is an object, dynamic_cast<void *>(&b) == (void *)&b.  */
667 	  if (TREE_CODE (expr) == ADDR_EXPR
668 	      && VAR_P (TREE_OPERAND (expr, 0))
669 	      && TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == RECORD_TYPE)
670 	    return build1 (NOP_EXPR, type, expr);
671 
672 	  /* Since expr is used twice below, save it.  */
673 	  expr = save_expr (expr);
674 
675 	  expr1 = build_headof (expr);
676 	  if (TREE_TYPE (expr1) != type)
677 	    expr1 = build1 (NOP_EXPR, type, expr1);
678 	  return ifnonnull (expr, expr1, complain);
679 	}
680       else
681 	{
682 	  tree retval;
683 	  tree result, td2, td3;
684 	  tree elems[4];
685 	  tree static_type, target_type, boff;
686 
687 	  /* If we got here, we can't convert statically.  Therefore,
688 	     dynamic_cast<D&>(b) (b an object) cannot succeed.  */
689 	  if (tc == REFERENCE_TYPE)
690 	    {
691 	      if (VAR_P (old_expr)
692 		  && TREE_CODE (TREE_TYPE (old_expr)) == RECORD_TYPE)
693 		{
694 		  tree expr = throw_bad_cast ();
695                   if (complain & tf_warning)
696                     warning (0, "dynamic_cast of %q#D to %q#T can never succeed",
697                              old_expr, type);
698 		  /* Bash it to the expected type.  */
699 		  TREE_TYPE (expr) = type;
700 		  return expr;
701 		}
702 	    }
703 	  /* Ditto for dynamic_cast<D*>(&b).  */
704 	  else if (TREE_CODE (expr) == ADDR_EXPR)
705 	    {
706 	      tree op = TREE_OPERAND (expr, 0);
707 	      if (VAR_P (op)
708 		  && TREE_CODE (TREE_TYPE (op)) == RECORD_TYPE)
709 		{
710                   if (complain & tf_warning)
711                     warning (0, "dynamic_cast of %q#D to %q#T can never succeed",
712                              op, type);
713 		  retval = build_int_cst (type, 0);
714 		  return retval;
715 		}
716 	    }
717 
718 	  /* Use of dynamic_cast when -fno-rtti is prohibited.  */
719 	  if (!flag_rtti)
720 	    {
721               if (complain & tf_error)
722                 error ("%<dynamic_cast%> not permitted with -fno-rtti");
723 	      return error_mark_node;
724 	    }
725 
726 	  target_type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
727 	  static_type = TYPE_MAIN_VARIANT (TREE_TYPE (exprtype));
728 	  td2 = get_tinfo_decl (target_type);
729 	  if (!mark_used (td2, complain) && !(complain & tf_error))
730 	    return error_mark_node;
731 	  td2 = cp_build_addr_expr (td2, complain);
732 	  td3 = get_tinfo_decl (static_type);
733 	  if (!mark_used (td3, complain) && !(complain & tf_error))
734 	    return error_mark_node;
735 	  td3 = cp_build_addr_expr (td3, complain);
736 
737 	  /* Determine how T and V are related.  */
738 	  boff = dcast_base_hint (static_type, target_type);
739 
740 	  /* Since expr is used twice below, save it.  */
741 	  expr = save_expr (expr);
742 
743 	  expr1 = expr;
744 	  if (tc == REFERENCE_TYPE)
745 	    expr1 = cp_build_addr_expr (expr1, complain);
746 
747 	  elems[0] = expr1;
748 	  elems[1] = td3;
749 	  elems[2] = td2;
750 	  elems[3] = boff;
751 
752 	  dcast_fn = dynamic_cast_node;
753 	  if (!dcast_fn)
754 	    {
755 	      tree tmp;
756 	      tree tinfo_ptr;
757 	      const char *name;
758 
759 	      push_abi_namespace ();
760 	      tinfo_ptr = xref_tag (class_type,
761 				    get_identifier ("__class_type_info"),
762 				    /*tag_scope=*/ts_current, false);
763 
764 	      tinfo_ptr = build_pointer_type
765 		(cp_build_qualified_type
766 		 (tinfo_ptr, TYPE_QUAL_CONST));
767 	      name = "__dynamic_cast";
768 	      tmp = build_function_type_list (ptr_type_node,
769 					      const_ptr_type_node,
770 					      tinfo_ptr, tinfo_ptr,
771 					      ptrdiff_type_node, NULL_TREE);
772 	      dcast_fn = build_library_fn_ptr (name, tmp,
773 					       ECF_LEAF | ECF_PURE | ECF_NOTHROW);
774 	      pop_abi_namespace ();
775 	      dynamic_cast_node = dcast_fn;
776 	    }
777 	  result = build_cxx_call (dcast_fn, 4, elems, complain);
778 
779 	  if (tc == REFERENCE_TYPE)
780 	    {
781 	      tree bad = throw_bad_cast ();
782 	      tree neq;
783 
784 	      result = save_expr (result);
785 	      neq = cp_truthvalue_conversion (result);
786 	      return cp_convert (type,
787 				 build3 (COND_EXPR, TREE_TYPE (result),
788 					 neq, result, bad), complain);
789 	    }
790 
791 	  /* Now back to the type we want from a void*.  */
792 	  result = cp_convert (type, result, complain);
793 	  return ifnonnull (expr, result, complain);
794 	}
795     }
796   else
797     errstr = _("source type is not polymorphic");
798 
799  fail:
800   if (complain & tf_error)
801     error ("cannot dynamic_cast %qE (of type %q#T) to type %q#T (%s)",
802            old_expr, TREE_TYPE (old_expr), type, errstr);
803   return error_mark_node;
804 }
805 
806 tree
807 build_dynamic_cast (tree type, tree expr, tsubst_flags_t complain)
808 {
809   tree r;
810 
811   if (type == error_mark_node || expr == error_mark_node)
812     return error_mark_node;
813 
814   if (processing_template_decl)
815     {
816       expr = build_min (DYNAMIC_CAST_EXPR, type, expr);
817       TREE_SIDE_EFFECTS (expr) = 1;
818       return convert_from_reference (expr);
819     }
820 
821   r = convert_from_reference (build_dynamic_cast_1 (type, expr, complain));
822   if (r != error_mark_node)
823     maybe_warn_about_useless_cast (type, expr, complain);
824   return r;
825 }
826 
827 /* Return the runtime bit mask encoding the qualifiers of TYPE.  */
828 
829 static int
830 qualifier_flags (tree type)
831 {
832   int flags = 0;
833   int quals = cp_type_quals (type);
834 
835   if (quals & TYPE_QUAL_CONST)
836     flags |= 1;
837   if (quals & TYPE_QUAL_VOLATILE)
838     flags |= 2;
839   if (quals & TYPE_QUAL_RESTRICT)
840     flags |= 4;
841   return flags;
842 }
843 
844 /* Return true, if the pointer chain TYPE ends at an incomplete type, or
845    contains a pointer to member of an incomplete class.  */
846 
847 static bool
848 target_incomplete_p (tree type)
849 {
850   while (true)
851     if (TYPE_PTRDATAMEM_P (type))
852       {
853 	if (!COMPLETE_TYPE_P (TYPE_PTRMEM_CLASS_TYPE (type)))
854 	  return true;
855 	type = TYPE_PTRMEM_POINTED_TO_TYPE (type);
856       }
857     else if (TYPE_PTR_P (type))
858       type = TREE_TYPE (type);
859     else
860       return !COMPLETE_OR_VOID_TYPE_P (type);
861 }
862 
863 /* Returns true if TYPE involves an incomplete class type; in that
864    case, typeinfo variables for TYPE should be emitted with internal
865    linkage.  */
866 
867 static bool
868 involves_incomplete_p (tree type)
869 {
870   switch (TREE_CODE (type))
871     {
872     case POINTER_TYPE:
873       return target_incomplete_p (TREE_TYPE (type));
874 
875     case OFFSET_TYPE:
876     ptrmem:
877       return
878 	(target_incomplete_p (TYPE_PTRMEM_POINTED_TO_TYPE (type))
879 	 || !COMPLETE_TYPE_P (TYPE_PTRMEM_CLASS_TYPE (type)));
880 
881     case RECORD_TYPE:
882       if (TYPE_PTRMEMFUNC_P (type))
883 	goto ptrmem;
884       /* Fall through.  */
885     case UNION_TYPE:
886       if (!COMPLETE_TYPE_P (type))
887 	return true;
888       /* Fall through.  */
889     default:
890       /* All other types do not involve incomplete class types.  */
891       return false;
892     }
893 }
894 
895 /* Return a CONSTRUCTOR for the common part of the type_info objects. This
896    is the vtable pointer and NTBS name.  The NTBS name is emitted as a
897    comdat const char array, so it becomes a unique key for the type. Generate
898    and emit that VAR_DECL here.  (We can't always emit the type_info itself
899    as comdat, because of pointers to incomplete.) */
900 
901 static tree
902 tinfo_base_init (tinfo_s *ti, tree target)
903 {
904   tree init;
905   tree name_decl;
906   tree vtable_ptr;
907   vec<constructor_elt, va_gc> *v;
908 
909   {
910     tree name_name, name_string;
911 
912     /* Generate the NTBS array variable.  */
913     tree name_type = build_cplus_array_type
914 		     (cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST),
915 		     NULL_TREE);
916 
917     /* Determine the name of the variable -- and remember with which
918        type it is associated.  */
919     name_name = mangle_typeinfo_string_for_type (target);
920     TREE_TYPE (name_name) = target;
921 
922     name_decl = build_lang_decl (VAR_DECL, name_name, name_type);
923     SET_DECL_ASSEMBLER_NAME (name_decl, name_name);
924     DECL_ARTIFICIAL (name_decl) = 1;
925     DECL_IGNORED_P (name_decl) = 1;
926     TREE_READONLY (name_decl) = 1;
927     TREE_STATIC (name_decl) = 1;
928     DECL_EXTERNAL (name_decl) = 0;
929     DECL_TINFO_P (name_decl) = 1;
930     set_linkage_according_to_type (target, name_decl);
931     import_export_decl (name_decl);
932     name_string = tinfo_name (target, !TREE_PUBLIC (name_decl));
933     DECL_INITIAL (name_decl) = name_string;
934     mark_used (name_decl);
935     pushdecl_top_level_and_finish (name_decl, name_string);
936   }
937 
938   vtable_ptr = ti->vtable;
939   if (!vtable_ptr)
940     {
941       tree real_type;
942       push_abi_namespace ();
943       real_type = xref_tag (class_type, ti->name,
944 			    /*tag_scope=*/ts_current, false);
945       pop_abi_namespace ();
946 
947       if (!COMPLETE_TYPE_P (real_type))
948 	{
949 	  /* We never saw a definition of this type, so we need to
950 	     tell the compiler that this is an exported class, as
951 	     indeed all of the __*_type_info classes are.  */
952 	  SET_CLASSTYPE_INTERFACE_KNOWN (real_type);
953 	  CLASSTYPE_INTERFACE_ONLY (real_type) = 1;
954 	}
955 
956       vtable_ptr = get_vtable_decl (real_type, /*complete=*/1);
957       vtable_ptr = cp_build_addr_expr (vtable_ptr, tf_warning_or_error);
958 
959       /* We need to point into the middle of the vtable.  */
960       vtable_ptr = fold_build_pointer_plus
961 	(vtable_ptr,
962 	 size_binop (MULT_EXPR,
963 		     size_int (2 * TARGET_VTABLE_DATA_ENTRY_DISTANCE),
964 		     TYPE_SIZE_UNIT (vtable_entry_type)));
965 
966       ti->vtable = vtable_ptr;
967     }
968 
969   vec_alloc (v, 2);
970   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, vtable_ptr);
971   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
972 			  decay_conversion (name_decl, tf_warning_or_error));
973 
974   init = build_constructor (init_list_type_node, v);
975   TREE_CONSTANT (init) = 1;
976   TREE_STATIC (init) = 1;
977 
978   return init;
979 }
980 
981 /* Return the CONSTRUCTOR expr for a type_info of TYPE. TI provides the
982    information about the particular type_info derivation, which adds no
983    additional fields to the type_info base.  */
984 
985 static tree
986 generic_initializer (tinfo_s *ti, tree target)
987 {
988   tree init = tinfo_base_init (ti, target);
989 
990   init = build_constructor_single (init_list_type_node, NULL_TREE, init);
991   TREE_CONSTANT (init) = 1;
992   TREE_STATIC (init) = 1;
993   return init;
994 }
995 
996 /* Return the CONSTRUCTOR expr for a type_info of pointer TYPE.
997    TI provides information about the particular type_info derivation,
998    which adds target type and qualifier flags members to the type_info base.  */
999 
1000 static tree
1001 ptr_initializer (tinfo_s *ti, tree target)
1002 {
1003   tree init = tinfo_base_init (ti, target);
1004   tree to = TREE_TYPE (target);
1005   int flags = qualifier_flags (to);
1006   bool incomplete = target_incomplete_p (to);
1007   vec<constructor_elt, va_gc> *v;
1008   vec_alloc (v, 3);
1009 
1010   if (incomplete)
1011     flags |= 8;
1012   if (tx_safe_fn_type_p (to))
1013     {
1014       flags |= 0x20;
1015       to = tx_unsafe_fn_variant (to);
1016     }
1017   if (flag_noexcept_type
1018       && (TREE_CODE (to) == FUNCTION_TYPE
1019 	  || TREE_CODE (to) == METHOD_TYPE)
1020       && TYPE_NOTHROW_P (to))
1021     {
1022       flags |= 0x40;
1023       to = build_exception_variant (to, NULL_TREE);
1024     }
1025   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
1026   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, build_int_cst (NULL_TREE, flags));
1027   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
1028                           get_tinfo_ptr (TYPE_MAIN_VARIANT (to)));
1029 
1030   init = build_constructor (init_list_type_node, v);
1031   TREE_CONSTANT (init) = 1;
1032   TREE_STATIC (init) = 1;
1033   return init;
1034 }
1035 
1036 /* Return the CONSTRUCTOR expr for a type_info of pointer to member data TYPE.
1037    TI provides information about the particular type_info derivation,
1038    which adds class, target type and qualifier flags members to the type_info
1039    base.  */
1040 
1041 static tree
1042 ptm_initializer (tinfo_s *ti, tree target)
1043 {
1044   tree init = tinfo_base_init (ti, target);
1045   tree to = TYPE_PTRMEM_POINTED_TO_TYPE (target);
1046   tree klass = TYPE_PTRMEM_CLASS_TYPE (target);
1047   int flags = qualifier_flags (to);
1048   bool incomplete = target_incomplete_p (to);
1049   vec<constructor_elt, va_gc> *v;
1050   vec_alloc (v, 4);
1051 
1052   if (incomplete)
1053     flags |= 0x8;
1054   if (!COMPLETE_TYPE_P (klass))
1055     flags |= 0x10;
1056   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
1057   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, build_int_cst (NULL_TREE, flags));
1058   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
1059                           get_tinfo_ptr (TYPE_MAIN_VARIANT (to)));
1060   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, get_tinfo_ptr (klass));
1061 
1062   init = build_constructor (init_list_type_node, v);
1063   TREE_CONSTANT (init) = 1;
1064   TREE_STATIC (init) = 1;
1065   return init;
1066 }
1067 
1068 /* Return the CONSTRUCTOR expr for a type_info of class TYPE.
1069    TI provides information about the particular __class_type_info derivation,
1070    which adds hint flags and N extra initializers to the type_info base.  */
1071 
1072 static tree
1073 class_initializer (tinfo_s *ti, tree target, unsigned n, ...)
1074 {
1075   tree init = tinfo_base_init (ti, target);
1076   va_list extra_inits;
1077   unsigned i;
1078   vec<constructor_elt, va_gc> *v;
1079   vec_alloc (v, n+1);
1080 
1081   CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
1082   va_start (extra_inits, n);
1083   for (i = 0; i < n; i++)
1084     CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, va_arg (extra_inits, tree));
1085   va_end (extra_inits);
1086 
1087   init = build_constructor (init_list_type_node, v);
1088   TREE_CONSTANT (init) = 1;
1089   TREE_STATIC (init) = 1;
1090   return init;
1091 }
1092 
1093 /* Returns true if the typeinfo for type should be placed in
1094    the runtime library.  */
1095 
1096 static bool
1097 typeinfo_in_lib_p (tree type)
1098 {
1099   /* The typeinfo objects for `T*' and `const T*' are in the runtime
1100      library for simple types T.  */
1101   if (TYPE_PTR_P (type)
1102       && (cp_type_quals (TREE_TYPE (type)) == TYPE_QUAL_CONST
1103 	  || cp_type_quals (TREE_TYPE (type)) == TYPE_UNQUALIFIED))
1104     type = TREE_TYPE (type);
1105 
1106   switch (TREE_CODE (type))
1107     {
1108     case INTEGER_TYPE:
1109     case BOOLEAN_TYPE:
1110     case REAL_TYPE:
1111     case VOID_TYPE:
1112     case NULLPTR_TYPE:
1113       return true;
1114 
1115     case LANG_TYPE:
1116       /* fall through.  */
1117 
1118     default:
1119       return false;
1120     }
1121 }
1122 
1123 /* Generate the initializer for the type info describing TYPE.  TK_INDEX is
1124    the index of the descriptor in the tinfo_desc vector. */
1125 
1126 static tree
1127 get_pseudo_ti_init (tree type, unsigned tk_index)
1128 {
1129   tinfo_s *ti = get_tinfo_desc (tk_index);
1130 
1131   gcc_assert (at_eof);
1132   switch (tk_index)
1133     {
1134     case TK_POINTER_MEMBER_TYPE:
1135       return ptm_initializer (ti, type);
1136 
1137     case TK_POINTER_TYPE:
1138       return ptr_initializer (ti, type);
1139 
1140     case TK_BUILTIN_TYPE:
1141     case TK_ENUMERAL_TYPE:
1142     case TK_FUNCTION_TYPE:
1143     case TK_ARRAY_TYPE:
1144       return generic_initializer (ti, type);
1145 
1146     case TK_CLASS_TYPE:
1147       return class_initializer (ti, type, 0);
1148 
1149     case TK_SI_CLASS_TYPE:
1150       {
1151 	tree base_binfo = BINFO_BASE_BINFO (TYPE_BINFO (type), 0);
1152 	tree tinfo = get_tinfo_ptr (BINFO_TYPE (base_binfo));
1153 
1154 	/* get_tinfo_ptr might have reallocated the tinfo_descs vector.  */
1155 	ti = &(*tinfo_descs)[tk_index];
1156 	return class_initializer (ti, type, 1, tinfo);
1157       }
1158 
1159     default:
1160       {
1161 	int hint = ((CLASSTYPE_REPEATED_BASE_P (type) << 0)
1162 		    | (CLASSTYPE_DIAMOND_SHAPED_P (type) << 1));
1163 	tree binfo = TYPE_BINFO (type);
1164 	unsigned nbases = BINFO_N_BASE_BINFOS (binfo);
1165 	vec<tree, va_gc> *base_accesses = BINFO_BASE_ACCESSES (binfo);
1166 	tree offset_type = LONGPTR_T;
1167 	vec<constructor_elt, va_gc> *init_vec = NULL;
1168 
1169 	gcc_assert (tk_index - TK_VMI_CLASS_TYPES + 1 == nbases);
1170 
1171 	vec_safe_grow (init_vec, nbases);
1172 	/* Generate the base information initializer.  */
1173 	for (unsigned ix = nbases; ix--;)
1174 	  {
1175 	    tree base_binfo = BINFO_BASE_BINFO (binfo, ix);
1176 	    int flags = 0;
1177 	    tree tinfo;
1178 	    tree offset;
1179 	    vec<constructor_elt, va_gc> *v;
1180 
1181 	    if ((*base_accesses)[ix] == access_public_node)
1182 	      flags |= 2;
1183 	    tinfo = get_tinfo_ptr (BINFO_TYPE (base_binfo));
1184 	    if (BINFO_VIRTUAL_P (base_binfo))
1185 	      {
1186 		/* We store the vtable offset at which the virtual
1187 		   base offset can be found.  */
1188 		offset = BINFO_VPTR_FIELD (base_binfo);
1189 		flags |= 1;
1190 	      }
1191 	    else
1192 	      offset = BINFO_OFFSET (base_binfo);
1193 
1194 	    /* Combine offset and flags into one field.  */
1195 	    offset = fold_convert (offset_type, offset);
1196 	    offset = fold_build2_loc (input_location,
1197 				  LSHIFT_EXPR, offset_type, offset,
1198 				  build_int_cst (offset_type, 8));
1199 	    offset = fold_build2_loc (input_location,
1200 				  BIT_IOR_EXPR, offset_type, offset,
1201 				  build_int_cst (offset_type, flags));
1202 	    vec_alloc (v, 2);
1203 	    CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, tinfo);
1204 	    CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, offset);
1205 	    tree base_init = build_constructor (init_list_type_node, v);
1206 	    constructor_elt *e = &(*init_vec)[ix];
1207 	    e->index = NULL_TREE;
1208 	    e->value = base_init;
1209 	  }
1210 	tree base_inits = build_constructor (init_list_type_node, init_vec);
1211 
1212 	/* get_tinfo_ptr might have reallocated the tinfo_descs vector.  */
1213 	ti = &(*tinfo_descs)[tk_index];
1214 	return class_initializer (ti, type, 3,
1215 				  build_int_cst (NULL_TREE, hint),
1216 				  build_int_cst (NULL_TREE, nbases),
1217 				  base_inits);
1218       }
1219     }
1220 }
1221 
1222 /* Return the index of a pseudo type info type node used to describe
1223    TYPE.  TYPE must be a complete type (or cv void), except at the end
1224    of the translation unit.  */
1225 
1226 static unsigned
1227 get_pseudo_ti_index (tree type)
1228 {
1229   unsigned ix;
1230 
1231   switch (TREE_CODE (type))
1232     {
1233     case OFFSET_TYPE:
1234       ix = TK_POINTER_MEMBER_TYPE;
1235       break;
1236 
1237     case POINTER_TYPE:
1238       ix = TK_POINTER_TYPE;
1239       break;
1240 
1241     case ENUMERAL_TYPE:
1242       ix = TK_ENUMERAL_TYPE;
1243       break;
1244 
1245     case FUNCTION_TYPE:
1246       ix = TK_FUNCTION_TYPE;
1247       break;
1248 
1249     case ARRAY_TYPE:
1250       ix = TK_ARRAY_TYPE;
1251       break;
1252 
1253     case UNION_TYPE:
1254     case RECORD_TYPE:
1255       if (TYPE_PTRMEMFUNC_P (type))
1256 	ix = TK_POINTER_MEMBER_TYPE;
1257       else if (!COMPLETE_TYPE_P (type))
1258 	{
1259 	  if (!at_eof)
1260 	    cxx_incomplete_type_error (NULL_TREE, type);
1261 	  ix = TK_CLASS_TYPE;
1262 	}
1263       else if (!TYPE_BINFO (type)
1264 	       || !BINFO_N_BASE_BINFOS (TYPE_BINFO (type)))
1265 	ix = TK_CLASS_TYPE;
1266       else
1267 	{
1268 	  tree binfo = TYPE_BINFO (type);
1269 	  vec<tree, va_gc> *base_accesses = BINFO_BASE_ACCESSES (binfo);
1270 	  tree base_binfo = BINFO_BASE_BINFO (binfo, 0);
1271 	  int num_bases = BINFO_N_BASE_BINFOS (binfo);
1272 
1273 	  if (num_bases == 1
1274 	      && (*base_accesses)[0] == access_public_node
1275 	      && !BINFO_VIRTUAL_P (base_binfo)
1276 	      && integer_zerop (BINFO_OFFSET (base_binfo)))
1277 	    /* single non-virtual public.  */
1278 	    ix = TK_SI_CLASS_TYPE;
1279 	  else
1280 	    ix = TK_VMI_CLASS_TYPES + num_bases - 1;
1281 	}
1282       break;
1283 
1284     default:
1285       ix = TK_BUILTIN_TYPE;
1286       break;
1287     }
1288   return ix;
1289 }
1290 
1291 /* Return pointer to tinfo descriptor.  Possibly creating the tinfo
1292    descriptor in the first place.  */
1293 
1294 static tinfo_s *
1295 get_tinfo_desc (unsigned ix)
1296 {
1297   unsigned len = tinfo_descs->length ();
1298 
1299   if (len <= ix)
1300     {
1301       /* too short, extend.  */
1302       len = ix + 1 - len;
1303       vec_safe_reserve (tinfo_descs, len);
1304       tinfo_s elt;
1305       elt.type = elt.vtable = elt.name = NULL_TREE;
1306       while (len--)
1307 	tinfo_descs->quick_push (elt);
1308     }
1309 
1310   tinfo_s *res = &(*tinfo_descs)[ix];
1311 
1312   if (res->type)
1313     return res;
1314 
1315   /* Ok, we have to create it.  This layout must be consistent with
1316      that defined in the runtime support.  We explicitly manage the
1317      vtable member, and name it for real type as used in the runtime.
1318      The RECORD type has a different name, to avoid collisions.  We
1319      have to delay generating the VAR_DECL of the vtable until the end
1320      of the translation, when we'll have seen the library definition,
1321      if there was one.  */
1322 
1323   /* Fields to add, chained in reverse order.  */
1324   tree fields = NULL_TREE;
1325 
1326   if (ix >= TK_DERIVED_TYPES)
1327     {
1328       /* First field is the pseudo type_info base class.  */
1329       tree fld_base = build_decl (BUILTINS_LOCATION, FIELD_DECL, NULL_TREE,
1330 				  get_tinfo_desc (TK_TYPE_INFO_TYPE)->type);
1331 
1332       DECL_CHAIN (fld_base) = fields;
1333       fields = fld_base;
1334     }
1335 
1336   switch (ix)
1337     {
1338     case TK_TYPE_INFO_TYPE:
1339       {
1340 	tree fld_ptr = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1341 				   NULL_TREE, const_ptr_type_node);
1342 	fields = fld_ptr;
1343 
1344 	tree fld_str = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1345 				   NULL_TREE, const_string_type_node);
1346 	DECL_CHAIN (fld_str) = fields;
1347 	fields = fld_str;
1348 	break;
1349       }
1350 
1351     case TK_BASE_TYPE:
1352       {
1353 	/* Base class internal helper. Pointer to base type, offset to
1354 	   base, flags.  */
1355 	tree fld_ptr = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1356 				   NULL_TREE, type_info_ptr_type);
1357 	DECL_CHAIN (fld_ptr) = fields;
1358 	fields = fld_ptr;
1359 
1360 	tree fld_flag = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1361 				    NULL_TREE, LONGPTR_T);
1362 	DECL_CHAIN (fld_flag) = fields;
1363 	fields = fld_flag;
1364 	break;
1365       }
1366 
1367     case TK_BUILTIN_TYPE:
1368       /* Fundamental type_info */
1369       break;
1370 
1371     case TK_ARRAY_TYPE:
1372       break;
1373 
1374     case TK_FUNCTION_TYPE:
1375       break;
1376 
1377     case TK_ENUMERAL_TYPE:
1378       break;
1379 
1380     case TK_POINTER_TYPE:
1381     case TK_POINTER_MEMBER_TYPE:
1382       {
1383 	/* Pointer type_info. Adds two fields, qualification mask and
1384 	   pointer to the pointed to type.  This is really a
1385 	   descendant of __pbase_type_info.  */
1386 	tree fld_mask = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1387 				    NULL_TREE, integer_type_node);
1388 	DECL_CHAIN (fld_mask) = fields;
1389 	fields = fld_mask;
1390 
1391 	tree fld_ptr = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1392 				   NULL_TREE, type_info_ptr_type);
1393 	DECL_CHAIN (fld_ptr) = fields;
1394 	fields = fld_ptr;
1395 
1396 	if (ix == TK_POINTER_MEMBER_TYPE)
1397 	  {
1398 	    /* Add a pointer to the class too.  */
1399 	    tree fld_cls = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1400 				   NULL_TREE, type_info_ptr_type);
1401 	    DECL_CHAIN (fld_cls) = fields;
1402 	    fields = fld_cls;
1403 	  }
1404 	break;
1405       }
1406 
1407     case TK_CLASS_TYPE:
1408       /* Class type_info.  No additional fields.  */
1409       break;
1410 
1411     case TK_SI_CLASS_TYPE:
1412       {
1413 	/* Single public non-virtual base class. Add pointer to base
1414 	   class.  This is really a descendant of
1415 	   __class_type_info.  */
1416 	tree fld_ptr = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1417 				   NULL_TREE, type_info_ptr_type);
1418 	DECL_CHAIN (fld_ptr) = fields;
1419 	fields = fld_ptr;
1420 	break;
1421       }
1422 
1423     default: /* Multiple inheritance.  */
1424       {
1425 	unsigned num_bases = ix - TK_VMI_CLASS_TYPES + 1;
1426 
1427 	tree fld_flg = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1428 				   NULL_TREE, integer_type_node);
1429 	DECL_CHAIN (fld_flg) = fields;
1430 	fields = fld_flg;
1431 
1432 	tree fld_cnt = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1433 				   NULL_TREE, integer_type_node);
1434 	DECL_CHAIN (fld_cnt) = fields;
1435 	fields = fld_cnt;
1436 
1437 	/* Create the array of __base_class_type_info entries.  */
1438 	tree domain = build_index_type (size_int (num_bases - 1));
1439 	tree array = build_array_type (get_tinfo_desc (TK_BASE_TYPE)->type,
1440 				       domain);
1441 	tree fld_ary = build_decl (BUILTINS_LOCATION, FIELD_DECL,
1442 				   NULL_TREE, array);
1443 	DECL_CHAIN (fld_ary) = fields;
1444 	fields = fld_ary;
1445 	break;
1446       }
1447     }
1448 
1449   push_abi_namespace ();
1450 
1451   /* Generate the pseudo type name.  */
1452   const char *real_name = tinfo_names[ix < TK_VMI_CLASS_TYPES
1453 				      ? ix : unsigned (TK_VMI_CLASS_TYPES)];
1454   size_t name_len = strlen (real_name);
1455   char *pseudo_name = (char *) alloca (name_len + 30);
1456   memcpy (pseudo_name, real_name, name_len);
1457   /* Those >= TK_VMI_CLASS_TYPES need a discriminator, may as well
1458      apply it to all.  See get_peudo_tinfo_index where we make use of
1459      this.  */
1460   sprintf (pseudo_name + name_len, "_pseudo_%d", ix);
1461 
1462   /* Create the pseudo type.  */
1463   tree pseudo_type = make_class_type (RECORD_TYPE);
1464   /* Pass the fields chained in reverse.  */
1465   finish_builtin_struct (pseudo_type, pseudo_name, fields, NULL_TREE);
1466   CLASSTYPE_AS_BASE (pseudo_type) = pseudo_type;
1467 
1468   res->type = cp_build_qualified_type (pseudo_type, TYPE_QUAL_CONST);
1469   res->name = get_identifier (real_name);
1470 
1471   /* Pretend this is public so determine_visibility doesn't give vtables
1472      internal linkage.  */
1473   TREE_PUBLIC (TYPE_MAIN_DECL (res->type)) = 1;
1474 
1475   pop_abi_namespace ();
1476   return res;
1477 }
1478 
1479 /* We lazily create the type info types.  */
1480 
1481 static void
1482 create_tinfo_types (void)
1483 {
1484   gcc_assert (!tinfo_descs);
1485 
1486   vec_alloc (tinfo_descs, TK_MAX + 20);
1487 }
1488 
1489 /* Helper for emit_support_tinfos. Emits the type_info descriptor of
1490    a single type.  */
1491 
1492 void
1493 emit_support_tinfo_1 (tree bltn)
1494 {
1495   tree types[3];
1496 
1497   if (bltn == NULL_TREE)
1498     return;
1499   types[0] = bltn;
1500   types[1] = build_pointer_type (bltn);
1501   types[2] = build_pointer_type (cp_build_qualified_type (bltn,
1502 							  TYPE_QUAL_CONST));
1503 
1504   for (int i = 0; i < 3; ++i)
1505     {
1506       tree tinfo = get_tinfo_decl (types[i]);
1507       TREE_USED (tinfo) = 1;
1508       mark_needed (tinfo);
1509       /* The C++ ABI requires that these objects be COMDAT.  But,
1510 	 On systems without weak symbols, initialized COMDAT
1511 	 objects are emitted with internal linkage.  (See
1512 	 comdat_linkage for details.)  Since we want these objects
1513 	 to have external linkage so that copies do not have to be
1514 	 emitted in code outside the runtime library, we make them
1515 	 non-COMDAT here.
1516 
1517 	 It might also not be necessary to follow this detail of the
1518 	 ABI.  */
1519       if (!flag_weak || ! targetm.cxx.library_rtti_comdat ())
1520 	{
1521 	  gcc_assert (TREE_PUBLIC (tinfo) && !DECL_COMDAT (tinfo));
1522 	  DECL_INTERFACE_KNOWN (tinfo) = 1;
1523 	}
1524     }
1525 }
1526 
1527 /* Emit the type_info descriptors which are guaranteed to be in the runtime
1528    support.  Generating them here guarantees consistency with the other
1529    structures.  We use the following heuristic to determine when the runtime
1530    is being generated.  If std::__fundamental_type_info is defined, and its
1531    destructor is defined, then the runtime is being built.  */
1532 
1533 void
1534 emit_support_tinfos (void)
1535 {
1536   /* Dummy static variable so we can put nullptr in the array; it will be
1537      set before we actually start to walk the array.  */
1538   static tree *const fundamentals[] =
1539   {
1540     &void_type_node,
1541     &boolean_type_node,
1542     &wchar_type_node, &char16_type_node, &char32_type_node,
1543     &char_type_node, &signed_char_type_node, &unsigned_char_type_node,
1544     &short_integer_type_node, &short_unsigned_type_node,
1545     &integer_type_node, &unsigned_type_node,
1546     &long_integer_type_node, &long_unsigned_type_node,
1547     &long_long_integer_type_node, &long_long_unsigned_type_node,
1548     &float_type_node, &double_type_node, &long_double_type_node,
1549     &dfloat32_type_node, &dfloat64_type_node, &dfloat128_type_node,
1550     &nullptr_type_node,
1551     0
1552   };
1553   int ix;
1554 
1555   /* Look for a defined class.  */
1556   tree bltn_type = lookup_qualified_name
1557     (abi_node, get_identifier ("__fundamental_type_info"), true, false, false);
1558   if (TREE_CODE (bltn_type) != TYPE_DECL)
1559     return;
1560 
1561   bltn_type = TREE_TYPE (bltn_type);
1562   if (!COMPLETE_TYPE_P (bltn_type))
1563     return;
1564   tree dtor = CLASSTYPE_DESTRUCTOR (bltn_type);
1565   if (!dtor || DECL_EXTERNAL (dtor))
1566     return;
1567 
1568   /* All these are really builtins.  So set the location.  */
1569   location_t saved_loc = input_location;
1570   input_location = BUILTINS_LOCATION;
1571   doing_runtime = 1;
1572   for (ix = 0; fundamentals[ix]; ix++)
1573     emit_support_tinfo_1 (*fundamentals[ix]);
1574   for (ix = 0; ix < NUM_INT_N_ENTS; ix ++)
1575     if (int_n_enabled_p[ix])
1576       {
1577 	emit_support_tinfo_1 (int_n_trees[ix].signed_type);
1578 	emit_support_tinfo_1 (int_n_trees[ix].unsigned_type);
1579       }
1580   for (tree t = registered_builtin_types; t; t = TREE_CHAIN (t))
1581     emit_support_tinfo_1 (TREE_VALUE (t));
1582   input_location = saved_loc;
1583 }
1584 
1585 /* Finish a type info decl. DECL_PTR is a pointer to an unemitted
1586    tinfo decl.  Determine whether it needs emitting, and if so
1587    generate the initializer.  */
1588 
1589 bool
1590 emit_tinfo_decl (tree decl)
1591 {
1592   tree type = TREE_TYPE (DECL_NAME (decl));
1593   int in_library = typeinfo_in_lib_p (type);
1594 
1595   gcc_assert (DECL_TINFO_P (decl));
1596 
1597   if (in_library)
1598     {
1599       if (doing_runtime)
1600 	DECL_EXTERNAL (decl) = 0;
1601       else
1602 	{
1603 	  /* If we're not in the runtime, then DECL (which is already
1604 	     DECL_EXTERNAL) will not be defined here.  */
1605 	  DECL_INTERFACE_KNOWN (decl) = 1;
1606 	  return false;
1607 	}
1608     }
1609   else if (involves_incomplete_p (type))
1610     {
1611       if (!decl_needed_p (decl))
1612 	return false;
1613       /* If TYPE involves an incomplete class type, then the typeinfo
1614 	 object will be emitted with internal linkage.  There is no
1615 	 way to know whether or not types are incomplete until the end
1616 	 of the compilation, so this determination must be deferred
1617 	 until this point.  */
1618       TREE_PUBLIC (decl) = 0;
1619       DECL_EXTERNAL (decl) = 0;
1620       DECL_INTERFACE_KNOWN (decl) = 1;
1621     }
1622 
1623   import_export_decl (decl);
1624   if (DECL_NOT_REALLY_EXTERN (decl) && decl_needed_p (decl))
1625     {
1626       tree init;
1627 
1628       DECL_EXTERNAL (decl) = 0;
1629       init = get_pseudo_ti_init (type, get_pseudo_ti_index (type));
1630       DECL_INITIAL (decl) = init;
1631       mark_used (decl);
1632       cp_finish_decl (decl, init, false, NULL_TREE, 0);
1633       /* Avoid targets optionally bumping up the alignment to improve
1634 	 vector instruction accesses, tinfo are never accessed this way.  */
1635 #ifdef DATA_ABI_ALIGNMENT
1636       SET_DECL_ALIGN (decl, DATA_ABI_ALIGNMENT (decl, TYPE_ALIGN (TREE_TYPE (decl))));
1637       DECL_USER_ALIGN (decl) = true;
1638 #endif
1639       return true;
1640     }
1641   else
1642     return false;
1643 }
1644 
1645 #include "gt-cp-rtti.h"
1646