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