OSDN Git Service

90th Cygnus<->FSF quick merge
[pf3gnuchains/gcc-fork.git] / gcc / cp / gxxint.texi
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header 
3 @setfilename g++int.info
4 @settitle G++ internals
5 @setchapternewpage odd
6 @c %**end of header
7      
8 @node Top, Limitations of g++, (dir), (dir)
9 @chapter Internal Architecture of the Compiler
10
11 This is meant to describe the C++ front-end for gcc in detail.
12 Questions and comments to Mike Stump @code{<mrs@@cygnus.com>}.
13
14 @menu
15 * Limitations of g++::          
16 * Routines::                    
17 * Implementation Specifics::    
18 * Glossary::                    
19 * Macros::                      
20 * Typical Behavior::            
21 * Coding Conventions::          
22 * Templates::                   
23 * Access Control::              
24 * Error Reporting::             
25 * Parser::                      
26 * Copying Objects::             
27 * Exception Handling::          
28 * Free Store::                  
29 * Concept Index::               
30 @end menu
31
32 @node Limitations of g++, Routines, Top, Top
33 @section Limitations of g++
34
35 @itemize @bullet
36 @item
37 Limitations on input source code: 240 nesting levels with the parser
38 stacksize (YYSTACKSIZE) set to 500 (the default), and requires around
39 16.4k swap space per nesting level.  The parser needs about 2.09 *
40 number of nesting levels worth of stackspace.
41
42 @cindex pushdecl_class_level
43 @item
44 I suspect there are other uses of pushdecl_class_level that do not call
45 set_identifier_type_value in tandem with the call to
46 pushdecl_class_level.  It would seem to be an omission.
47
48 @cindex access checking
49 @item
50 Access checking is unimplemented for nested types.
51
52 @cindex @code{volatile}
53 @item
54 @code{volatile} is not implemented in general.
55
56 @end itemize
57
58 @node Routines, Implementation Specifics, Limitations of g++, Top
59 @section Routines
60
61 This section describes some of the routines used in the C++ front-end.
62
63 @code{build_vtable} and @code{prepare_fresh_vtable} is used only within
64 the @file{cp-class.c} file, and only in @code{finish_struct} and
65 @code{modify_vtable_entries}.
66
67 @code{build_vtable}, @code{prepare_fresh_vtable}, and
68 @code{finish_struct} are the only routines that set @code{DECL_VPARENT}.
69
70 @code{finish_struct} can steal the virtual function table from parents,
71 this prohibits related_vslot from working.  When finish_struct steals,
72 we know that
73
74 @example
75 get_binfo (DECL_FIELD_CONTEXT (CLASSTYPE_VFIELD (t)), t, 0)
76 @end example
77
78 @noindent
79 will get the related binfo.
80
81 @code{layout_basetypes} does something with the VIRTUALS.
82
83 Supposedly (according to Tiemann) most of the breadth first searching
84 done, like in @code{get_base_distance} and in @code{get_binfo} was not
85 because of any design decision.  I have since found out the at least one
86 part of the compiler needs the notion of depth first binfo searching, I
87 am going to try and convert the whole thing, it should just work.  The
88 term left-most refers to the depth first left-most node.  It uses
89 @code{MAIN_VARIANT == type} as the condition to get left-most, because
90 the things that have @code{BINFO_OFFSET}s of zero are shared and will
91 have themselves as their own @code{MAIN_VARIANT}s.  The non-shared right
92 ones, are copies of the left-most one, hence if it is its own
93 @code{MAIN_VARIANT}, we know it IS a left-most one, if it is not, it is
94 a non-left-most one.
95
96 @code{get_base_distance}'s path and distance matters in its use in:
97
98 @itemize @bullet
99 @item
100 @code{prepare_fresh_vtable} (the code is probably wrong)
101 @item
102 @code{init_vfields} Depends upon distance probably in a safe way,
103 build_offset_ref might use partial paths to do further lookups,
104 hack_identifier is probably not properly checking access.
105
106 @item
107 @code{get_first_matching_virtual} probably should check for
108 @code{get_base_distance} returning -2.
109
110 @item
111 @code{resolve_offset_ref} should be called in a more deterministic
112 manner.  Right now, it is called in some random contexts, like for
113 arguments at @code{build_method_call} time, @code{default_conversion}
114 time, @code{convert_arguments} time, @code{build_unary_op} time,
115 @code{build_c_cast} time, @code{build_modify_expr} time,
116 @code{convert_for_assignment} time, and
117 @code{convert_for_initialization} time.
118
119 But, there are still more contexts it needs to be called in, one was the
120 ever simple:
121
122 @example
123 if (obj.*pmi != 7)
124    @dots{}
125 @end example
126
127 Seems that the problems were due to the fact that @code{TREE_TYPE} of
128 the @code{OFFSET_REF} was not a @code{OFFSET_TYPE}, but rather the type
129 of the referent (like @code{INTEGER_TYPE}).  This problem was fixed by
130 changing @code{default_conversion} to check @code{TREE_CODE (x)},
131 instead of only checking @code{TREE_CODE (TREE_TYPE (x))} to see if it
132 was @code{OFFSET_TYPE}.
133
134 @end itemize
135
136 @node Implementation Specifics, Glossary, Routines, Top
137 @section Implementation Specifics
138
139 @itemize @bullet
140 @item Explicit Initialization
141
142 The global list @code{current_member_init_list} contains the list of
143 mem-initializers specified in a constructor declaration.  For example:
144
145 @example
146 foo::foo() : a(1), b(2) @{@}
147 @end example
148
149 @noindent
150 will initialize @samp{a} with 1 and @samp{b} with 2.
151 @code{expand_member_init} places each initialization (a with 1) on the
152 global list.  Then, when the fndecl is being processed,
153 @code{emit_base_init} runs down the list, initializing them.  It used to
154 be the case that g++ first ran down @code{current_member_init_list},
155 then ran down the list of members initializing the ones that weren't
156 explicitly initialized.  Things were rewritten to perform the
157 initializations in order of declaration in the class.  So, for the above
158 example, @samp{a} and @samp{b} will be initialized in the order that
159 they were declared:
160
161 @example
162 class foo @{ public: int b; int a; foo (); @};
163 @end example
164
165 @noindent
166 Thus, @samp{b} will be initialized with 2 first, then @samp{a} will be
167 initialized with 1, regardless of how they're listed in the mem-initializer.
168
169 @item Argument Matching
170
171 In early 1993, the argument matching scheme in @sc{gnu} C++ changed
172 significantly.  The original code was completely replaced with a new
173 method that will, hopefully, be easier to understand and make fixing
174 specific cases much easier.
175
176 The @samp{-fansi-overloading} option is used to enable the new code; at
177 some point in the future, it will become the default behavior of the
178 compiler.
179
180 The file @file{cp-call.c} contains all of the new work, in the functions
181 @code{rank_for_overload}, @code{compute_harshness},
182 @code{compute_conversion_costs}, and @code{ideal_candidate}.
183
184 Instead of using obscure numerical values, the quality of an argument
185 match is now represented by clear, individual codes.  The new data
186 structure @code{struct harshness} (it used to be an @code{unsigned}
187 number) contains:
188
189 @enumerate a
190 @item the @samp{code} field, to signify what was involved in matching two
191 arguments;
192 @item the @samp{distance} field, used in situations where inheritance
193 decides which function should be called (one is ``closer'' than
194 another);
195 @item and the @samp{int_penalty} field, used by some codes as a tie-breaker.
196 @end enumerate
197
198 The @samp{code} field is a number with a given bit set for each type of
199 code, OR'd together.  The new codes are:
200
201 @itemize @bullet
202 @item @code{EVIL_CODE}
203 The argument was not a permissible match.
204
205 @item @code{CONST_CODE}
206 Currently, this is only used by @code{compute_conversion_costs}, to
207 distinguish when a non-@code{const} member function is called from a
208 @code{const} member function.
209
210 @item @code{ELLIPSIS_CODE}
211 A match against an ellipsis @samp{...} is considered worse than all others.
212
213 @item @code{USER_CODE}
214 Used for a match involving a user-defined conversion.
215
216 @item @code{STD_CODE}
217 A match involving a standard conversion.
218
219 @item @code{PROMO_CODE}
220 A match involving an integral promotion.  For these, the
221 @code{int_penalty} field is used to handle the ARM's rule (XXX cite)
222 that a smaller @code{unsigned} type should promote to a @code{int}, not
223 to an @code{unsigned int}.
224
225 @item @code{QUAL_CODE}
226 Used to mark use of qualifiers like @code{const} and @code{volatile}.
227
228 @item @code{TRIVIAL_CODE}
229 Used for trivial conversions.  The @samp{int_penalty} field is used by
230 @code{convert_harshness} to communicate further penalty information back
231 to @code{build_overload_call_real} when deciding which function should
232 be call.
233 @end itemize
234
235 The functions @code{convert_to_aggr} and @code{build_method_call} use
236 @code{compute_conversion_costs} to rate each argument's suitability for
237 a given candidate function (that's how we get the list of candidates for
238 @code{ideal_candidate}).
239
240 @end itemize
241
242 @node Glossary, Macros, Implementation Specifics, Top
243 @section Glossary
244
245 @table @r
246 @item binfo
247 The main data structure in the compiler used to represent the
248 inheritance relationships between classes.  The data in the binfo can be
249 accessed by the BINFO_ accessor macros.
250
251 @item vtable
252 @itemx virtual function table
253
254 The virtual function table holds information used in virtual function
255 dispatching.  In the compiler, they are usually referred to as vtables,
256 or vtbls.  The first index is not used in the normal way, I believe it
257 is probably used for the virtual destructor.
258
259 @item vfield
260
261 vfields can be thought of as the base information needed to build
262 vtables.  For every vtable that exists for a class, there is a vfield.
263 See also vtable and virtual function table pointer.  When a type is used
264 as a base class to another type, the virtual function table for the
265 derived class can be based upon the vtable for the base class, just
266 extended to include the additional virtual methods declared in the
267 derived class.  The virtual function table from a virtual base class is
268 never reused in a derived class.  @code{is_normal} depends upon this.
269
270 @item virtual function table pointer
271
272 These are @code{FIELD_DECL}s that are pointer types that point to
273 vtables.  See also vtable and vfield.
274 @end table
275
276 @node Macros, Typical Behavior, Glossary, Top
277 @section Macros
278
279 This section describes some of the macros used on trees.  The list
280 should be alphabetical.  Eventually all macros should be documented
281 here.
282
283 @table @code
284 @item BINFO_BASETYPES
285 A vector of additional binfos for the types inherited by this basetype.
286 The binfos are fully unshared (except for virtual bases, in which
287 case the binfo structure is shared).
288
289    If this basetype describes type D as inherited in C,
290    and if the basetypes of D are E anf F,
291    then this vector contains binfos for inheritance of E and F by C.
292
293 Has values of:
294
295         TREE_VECs
296
297
298 @item BINFO_INHERITANCE_CHAIN
299 Temporarily used to represent specific inheritances.  It usually points
300 to the binfo associated with the lesser derived type, but it can be
301 reversed by reverse_path.  For example:
302
303 @example
304         Z ZbY   least derived
305         |
306         Y YbX
307         |
308         X Xb    most derived
309
310 TYPE_BINFO (X) == Xb
311 BINFO_INHERITANCE_CHAIN (Xb) == YbX
312 BINFO_INHERITANCE_CHAIN (Yb) == ZbY
313 BINFO_INHERITANCE_CHAIN (Zb) == 0
314 @end example
315
316 Not sure is the above is really true, get_base_distance has is point
317 towards the most derived type, opposite from above.
318
319 Set by build_vbase_path, recursive_bounded_basetype_p,
320 get_base_distance, lookup_field, lookup_fnfields, and reverse_path.
321
322 What things can this be used on:
323
324         TREE_VECs that are binfos
325
326
327 @item BINFO_OFFSET
328 The offset where this basetype appears in its containing type.
329 BINFO_OFFSET slot holds the offset (in bytes) from the base of the
330 complete object to the base of the part of the object that is allocated
331 on behalf of this `type'.  This is always 0 except when there is
332 multiple inheritance.
333
334 Used on TREE_VEC_ELTs of the binfos BINFO_BASETYPES (...) for example.
335
336
337 @item BINFO_VIRTUALS
338 A unique list of functions for the virtual function table.  See also
339 TYPE_BINFO_VIRTUALS.
340
341 What things can this be used on:
342
343         TREE_VECs that are binfos
344
345
346 @item BINFO_VTABLE
347 Used to find the VAR_DECL that is the virtual function table associated
348 with this binfo.  See also TYPE_BINFO_VTABLE.  To get the virtual
349 function table pointer, see CLASSTYPE_VFIELD.
350
351 What things can this be used on:
352
353         TREE_VECs that are binfos
354
355 Has values of:
356
357         VAR_DECLs that are virtual function tables
358
359
360 @item BLOCK_SUPERCONTEXT
361 In the outermost scope of each function, it points to the FUNCTION_DECL
362 node.  It aids in better DWARF support of inline functions.
363
364
365 @item CLASSTYPE_TAGS
366 CLASSTYPE_TAGS is a linked (via TREE_CHAIN) list of member classes of a
367 class. TREE_PURPOSE is the name, TREE_VALUE is the type (pushclass scans
368 these and calls pushtag on them.)
369
370 finish_struct scans these to produce TYPE_DECLs to add to the
371 TYPE_FIELDS of the type.
372
373 It is expected that name found in the TREE_PURPOSE slot is unique,
374 resolve_scope_to_name is one such place that depends upon this
375 uniqueness.
376
377
378 @item CLASSTYPE_METHOD_VEC
379 The following is true after finish_struct has been called (on the
380 class?) but not before.  Before finish_struct is called, things are
381 different to some extent.  Contains a TREE_VEC of methods of the class.
382 The TREE_VEC_LENGTH is the number of differently named methods plus one
383 for the 0th entry.  The 0th entry is always allocated, and reserved for
384 ctors and dtors.  If there are none, TREE_VEC_ELT(N,0) == NULL_TREE.
385 Each entry of the TREE_VEC is a FUNCTION_DECL.  For each FUNCTION_DECL,
386 there is a DECL_CHAIN slot.  If the FUNCTION_DECL is the last one with a
387 given name, the DECL_CHAIN slot is NULL_TREE.  Otherwise it is the next
388 method that has the same name (but a different signature).  It would
389 seem that it is not true that because the DECL_CHAIN slot is used in
390 this way, we cannot call pushdecl to put the method in the global scope
391 (cause that would overwrite the TREE_CHAIN slot), because they use
392 different _CHAINs.  finish_struct_methods setups up one version of the
393 TREE_CHAIN slots on the FUNCTION_DECLs.
394
395 friends are kept in TREE_LISTs, so that there's no need to use their
396 TREE_CHAIN slot for anything.
397
398 Has values of:
399
400         TREE_VECs
401         
402
403 @item CLASSTYPE_VFIELD
404 Seems to be in the process of being renamed TYPE_VFIELD.  Use on types
405 to get the main virtual function table pointer.  To get the virtual
406 function table use BINFO_VTABLE (TYPE_BINFO ()).
407
408 Has values of:
409
410         FIELD_DECLs that are virtual function table pointers
411
412 What things can this be used on:
413
414         RECORD_TYPEs
415
416
417 @item DECL_CLASS_CONTEXT
418 Identifies the context that the _DECL was found in.  For virtual function
419 tables, it points to the type associated with the virtual function
420 table.  See also DECL_CONTEXT, DECL_FIELD_CONTEXT and DECL_FCONTEXT.
421
422 The difference between this and DECL_CONTEXT, is that for virtuals
423 functions like:
424
425 @example
426 struct A
427 @{
428   virtual int f ();
429 @};
430
431 struct B : A
432 @{
433   int f ();
434 @};
435
436 DECL_CONTEXT (A::f) == A
437 DECL_CLASS_CONTEXT (A::f) == A
438
439 DECL_CONTEXT (B::f) == A
440 DECL_CLASS_CONTEXT (B::f) == B
441 @end example
442
443 Has values of:
444
445         RECORD_TYPEs, or UNION_TYPEs
446
447 What things can this be used on:
448
449         TYPE_DECLs, _DECLs
450
451
452 @item DECL_CONTEXT
453 Identifies the context that the _DECL was found in.  Can be used on
454 virtual function tables to find the type associated with the virtual
455 function table, but since they are FIELD_DECLs, DECL_FIELD_CONTEXT is a
456 better access method.  Internally the same as DECL_FIELD_CONTEXT, so
457 don't us both.  See also DECL_FIELD_CONTEXT, DECL_FCONTEXT and
458 DECL_CLASS_CONTEXT.
459
460 Has values of:
461
462         RECORD_TYPEs
463
464
465 What things can this be used on:
466
467 @display
468 VAR_DECLs that are virtual function tables
469 _DECLs
470 @end display
471
472
473 @item DECL_FIELD_CONTEXT
474 Identifies the context that the FIELD_DECL was found in.  Internally the
475 same as DECL_CONTEXT, so don't us both.  See also DECL_CONTEXT,
476 DECL_FCONTEXT and DECL_CLASS_CONTEXT.
477
478 Has values of:
479
480         RECORD_TYPEs
481
482 What things can this be used on:
483
484 @display
485 FIELD_DECLs that are virtual function pointers
486 FIELD_DECLs
487 @end display
488
489
490 @item DECL_NESTED_TYPENAME
491 Holds the fully qualified type name.  Example, Base::Derived.
492
493 Has values of:
494
495         IDENTIFIER_NODEs
496
497 What things can this be used on:
498
499         TYPE_DECLs
500
501
502 @item DECL_NAME
503
504 Has values of:
505
506 @display
507 0 for things that don't have names
508 IDENTIFIER_NODEs for TYPE_DECLs
509 @end display
510
511 @item DECL_IGNORED_P
512 A bit that can be set to inform the debug information output routines in
513 the back-end that a certain _DECL node should be totally ignored.
514
515 Used in cases where it is known that the debugging information will be
516 output in another file, or where a sub-type is known not to be needed
517 because the enclosing type is not needed.
518
519 A compiler constructed virtual destructor in derived classes that do not
520 define an explicit destructor that was defined explicit in a base class
521 has this bit set as well.  Also used on __FUNCTION__ and
522 __PRETTY_FUNCTION__ to mark they are ``compiler generated.''  c-decl and
523 c-lex.c both want DECL_IGNORED_P set for ``internally generated vars,''
524 and ``user-invisible variable.''
525
526 Functions built by the C++ front-end such as default destructors,
527 virtual destructors and default constructors want to be marked that
528 they are compiler generated, but unsure why.
529
530 Currently, it is used in an absolute way in the C++ front-end, as an
531 optimization, to tell the debug information output routines to not
532 generate debugging information that will be output by another separately
533 compiled file.
534
535
536 @item DECL_VIRTUAL_P
537 A flag used on FIELD_DECLs and VAR_DECLs.  (Documentation in tree.h is
538 wrong.)  Used in VAR_DECLs to indicate that the variable is a vtable.
539 It is also used in FIELD_DECLs for vtable pointers.
540
541 What things can this be used on:
542
543         FIELD_DECLs and VAR_DECLs
544
545
546 @item DECL_VPARENT
547 Used to point to the parent type of the vtable if there is one, else it
548 is just the type associated with the vtable.  Because of the sharing of
549 virtual function tables that goes on, this slot is not very useful, and
550 is in fact, not used in the compiler at all.  It can be removed.
551
552 What things can this be used on:
553
554         VAR_DECLs that are virtual function tables
555
556 Has values of:
557
558         RECORD_TYPEs maybe UNION_TYPEs
559
560
561 @item DECL_FCONTEXT
562 Used to find the first baseclass in which this FIELD_DECL is defined.
563 See also DECL_CONTEXT, DECL_FIELD_CONTEXT and DECL_CLASS_CONTEXT.
564
565 How it is used:
566
567         Used when writing out debugging information about vfield and
568         vbase decls.
569
570 What things can this be used on:
571
572         FIELD_DECLs that are virtual function pointers
573         FIELD_DECLs
574
575
576 @item DECL_REFERENCE_SLOT
577 Used to hold the initialize for the reference.
578
579 What things can this be used on:
580
581         PARM_DECLs and VAR_DECLs that have a reference type
582
583
584 @item DECL_VINDEX
585 Used for FUNCTION_DECLs in two different ways.  Before the structure
586 containing the FUNCTION_DECL is laid out, DECL_VINDEX may point to a
587 FUNCTION_DECL in a base class which is the FUNCTION_DECL which this
588 FUNCTION_DECL will replace as a virtual function.  When the class is
589 laid out, this pointer is changed to an INTEGER_CST node which is
590 suitable to find an index into the virtual function table.  See
591 get_vtable_entry as to how one can find the right index into the virtual
592 function table.  The first index 0, of a virtual function table it not
593 used in the normal way, so the first real index is 1.
594
595 DECL_VINDEX may be a TREE_LIST, that would seem to be a list of
596 overridden FUNCTION_DECLs.  add_virtual_function has code to deal with
597 this when it uses the variable base_fndecl_list, but it would seem that
598 somehow, it is possible for the TREE_LIST to pursist until method_call,
599 and it should not.
600
601
602 What things can this be used on:
603
604         FUNCTION_DECLs
605
606
607 @item DECL_SOURCE_FILE
608 Identifies what source file a particular declaration was found in.
609
610 Has values of:
611
612         "<built-in>" on TYPE_DECLs to mean the typedef is built in
613
614
615 @item DECL_SOURCE_LINE
616 Identifies what source line number in the source file the declaration
617 was found at.
618
619 Has values of:
620
621 @display
622 0 for an undefined label
623
624 0 for TYPE_DECLs that are internally generated
625
626 0 for FUNCTION_DECLs for functions generated by the compiler
627         (not yet, but should be)
628
629 0 for ``magic'' arguments to functions, that the user has no
630         control over
631 @end display
632
633
634 @item TREE_USED
635
636 Has values of:
637
638         0 for unused labels
639
640
641 @item TREE_ADDRESSABLE
642 A flag that is set for any type that has a constructor.
643
644
645 @item TREE_COMPLEXITY
646 They seem a kludge way to track recursion, poping, and pushing.  They only
647 appear in cp-decl.c and cp-decl2.c, so the are a good candidate for
648 proper fixing, and removal.
649
650
651 @item TREE_HAS_CONSTRUCTOR
652 A flag to indicate when a CALL_EXPR represents a call to a constructor.
653 If set, we know that the type of the object, is the complete type of the
654 object, and that the value returned is nonnull.  When used in this
655 fashion, it is an optimization.  Can also be used on SAVE_EXPRs to
656 indicate when they are of fixed type and nonnull.  Can also be used on
657 INDIRECT_EXPRs on CALL_EXPRs that represent a call to a constructor.
658
659
660 @item TREE_PRIVATE
661 Set for FIELD_DECLs by finish_struct.  But not uniformly set.
662
663 The following routines do something with PRIVATE access:
664 build_method_call, alter_access, finish_struct_methods,
665 finish_struct, convert_to_aggr, CWriteLanguageDecl, CWriteLanguageType,
666 CWriteUseObject, compute_access, lookup_field, dfs_pushdecl,
667 GNU_xref_member, dbxout_type_fields, dbxout_type_method_1
668
669
670 @item TREE_PROTECTED
671 The following routines do something with PROTECTED access:
672 build_method_call, alter_access, finish_struct, convert_to_aggr,
673 CWriteLanguageDecl, CWriteLanguageType, CWriteUseObject,
674 compute_access, lookup_field, GNU_xref_member, dbxout_type_fields,
675 dbxout_type_method_1
676
677
678 @item TYPE_BINFO
679 Used to get the binfo for the type.
680
681 Has values of:
682
683         TREE_VECs that are binfos
684
685 What things can this be used on:
686
687         RECORD_TYPEs
688
689
690 @item TYPE_BINFO_BASETYPES
691 See also BINFO_BASETYPES.
692
693 @item TYPE_BINFO_VIRTUALS
694 A unique list of functions for the virtual function table.  See also
695 BINFO_VIRTUALS.
696
697 What things can this be used on:
698
699         RECORD_TYPEs
700
701
702 @item TYPE_BINFO_VTABLE
703 Points to the virtual function table associated with the given type.
704 See also BINFO_VTABLE.
705
706 What things can this be used on:
707
708         RECORD_TYPEs
709
710 Has values of:
711
712         VAR_DECLs that are virtual function tables
713
714
715 @item TYPE_NAME
716 Names the type.
717
718 Has values of:
719
720 @display
721 0 for things that don't have names.
722 should be IDENTIFIER_NODE for RECORD_TYPEs UNION_TYPEs and 
723         ENUM_TYPEs.
724 TYPE_DECL for RECORD_TYPEs, UNION_TYPEs and ENUM_TYPEs, but 
725         shouldn't be.
726 TYPE_DECL for typedefs, unsure why.
727 @end display
728
729 What things can one use this on:
730
731 @display
732 TYPE_DECLs
733 RECORD_TYPEs
734 UNION_TYPEs
735 ENUM_TYPEs
736 @end display
737
738 History:
739
740         It currently points to the TYPE_DECL for RECORD_TYPEs,
741         UNION_TYPEs and ENUM_TYPEs, but it should be history soon.
742
743
744 @item TYPE_METHODS
745 Synonym for @code{CLASSTYPE_METHOD_VEC}.  Chained together with
746 @code{TREE_CHAIN}.  @file{dbxout.c} uses this to get at the methods of a
747 class.
748
749
750 @item TYPE_DECL
751 Used to represent typedefs, and used to represent bindings layers.
752
753 Components:
754
755         DECL_NAME is the name of the typedef.  For example, foo would
756         be found in the DECL_NAME slot when @code{typedef int foo;} is
757         seen.
758
759         DECL_SOURCE_LINE identifies what source line number in the
760         source file the declaration was found at.  A value of 0
761         indicates that this TYPE_DECL is just an internal binding layer
762         marker, and does not correspond to a user supplied typedef.
763
764         DECL_SOURCE_FILE
765
766 @item TYPE_FIELDS
767 A linked list (via @code{TREE_CHAIN}) of member types of a class.  The
768 list can contain @code{TYPE_DECL}s, but there can also be other things
769 in the list apparently.  See also @code{CLASSTYPE_TAGS}.
770
771
772 @item TYPE_VIRTUAL_P
773 A flag used on a @code{FIELD_DECL} or a @code{VAR_DECL}, indicates it is
774 a virtual function table or a pointer to one.  When used on a
775 @code{FUNCTION_DECL}, indicates that it is a virtual function.  When
776 used on an @code{IDENTIFIER_NODE}, indicates that a function with this
777 same name exists and has been declared virtual.
778
779 When used on types, it indicates that the type has virtual functions, or
780 is derived from one that does.
781
782 Not sure if the above about virtual function tables is still true.  See
783 also info on @code{DECL_VIRTUAL_P}.
784
785 What things can this be used on:
786
787         FIELD_DECLs, VAR_DECLs, FUNCTION_DECLs, IDENTIFIER_NODEs
788
789
790 @item VF_BASETYPE_VALUE
791 Get the associated type from the binfo that caused the given vfield to
792 exist.  This is the least derived class (the most parent class) that
793 needed a virtual function table.  It is probably the case that all uses
794 of this field are misguided, but they need to be examined on a
795 case-by-case basis.  See history for more information on why the
796 previous statement was made.
797
798 Set at @code{finish_base_struct} time.
799
800 What things can this be used on:
801
802         TREE_LISTs that are vfields
803
804 History:
805
806         This field was used to determine if a virtual function table's
807         slot should be filled in with a certain virtual function, by
808         checking to see if the type returned by VF_BASETYPE_VALUE was a
809         parent of the context in which the old virtual function existed.
810         This incorrectly assumes that a given type _could_ not appear as
811         a parent twice in a given inheritance lattice.  For single
812         inheritance, this would in fact work, because a type could not
813         possibly appear more than once in an inheritance lattice, but
814         with multiple inheritance, a type can appear more than once.
815
816
817 @item VF_BINFO_VALUE
818 Identifies the binfo that caused this vfield to exist.  If this vfield
819 is from the first direct base class that has a virtual function table,
820 then VF_BINFO_VALUE is NULL_TREE, otherwise it will be the binfo of the
821 direct base where the vfield came from.  Can use @code{TREE_VIA_VIRTUAL}
822 on result to find out if it is a virtual base class.  Related to the
823 binfo found by
824
825 @example
826 get_binfo (VF_BASETYPE_VALUE (vfield), t, 0)
827 @end example
828
829 @noindent
830 where @samp{t} is the type that has the given vfield.
831
832 @example
833 get_binfo (VF_BASETYPE_VALUE (vfield), t, 0)
834 @end example
835
836 @noindent
837 will return the binfo for the the given vfield.
838
839 May or may not be set at @code{modify_vtable_entries} time.  Set at
840 @code{finish_base_struct} time.
841
842 What things can this be used on:
843
844         TREE_LISTs that are vfields
845
846
847 @item VF_DERIVED_VALUE
848 Identifies the type of the most derived class of the vfield, excluding
849 the the class this vfield is for.
850
851 Set at @code{finish_base_struct} time.
852
853 What things can this be used on:
854
855         TREE_LISTs that are vfields
856
857
858 @item VF_NORMAL_VALUE
859 Identifies the type of the most derived class of the vfield, including
860 the class this vfield is for.
861
862 Set at @code{finish_base_struct} time.
863
864 What things can this be used on:
865
866         TREE_LISTs that are vfields
867
868
869 @item WRITABLE_VTABLES
870 This is a option that can be defined when building the compiler, that
871 will cause the compiler to output vtables into the data segment so that
872 the vtables maybe written.  This is undefined by default, because
873 normally the vtables should be unwritable.  People that implement object
874 I/O facilities may, or people that want to change the dynamic type of
875 objects may want to have the vtables writable.  Another way of achieving
876 this would be to make a copy of the vtable into writable memory, but the
877 drawback there is that that method only changes the type for one object.
878
879 @end table
880
881 @node Typical Behavior, Coding Conventions, Macros, Top
882 @section Typical Behavior
883
884 @cindex parse errors
885
886 Whenever seemingly normal code fails with errors like
887 @code{syntax error at `\@{'}, it's highly likely that grokdeclarator is
888 returning a NULL_TREE for whatever reason.
889
890 @node Coding Conventions, Templates, Typical Behavior, Top
891 @section Coding Conventions
892
893 It should never be that case that trees are modified in-place by the
894 back-end, @emph{unless} it is guaranteed that the semantics are the same
895 no matter how shared the tree structure is.  @file{fold-const.c} still
896 has some cases where this is not true, but rms hypothesizes that this
897 will never be a problem.
898
899 @node Templates, Access Control, Coding Conventions, Top
900 @section Templates
901
902 A template is represented by a @code{TEMPLATE_DECL}.  The specific
903 fields used are:
904
905 @table @code
906 @item DECL_TEMPLATE_RESULT
907 The generic decl on which instantiations are based.  This looks just
908 like any other decl.
909
910 @item DECL_TEMPLATE_PARMS
911 The parameters to this template.
912 @end table
913
914 The generic decl is parsed as much like any other decl as possible,
915 given the parameterization.  The template decl is not built up until the
916 generic decl has been completed.  For template classes, a template decl
917 is generated for each member function and static data member, as well.
918
919 Template members of template classes are represented by a TEMPLATE_DECL
920 for the class' parameters around another TEMPLATE_DECL for the member's
921 parameters.
922
923 All declarations that are instantiations or specializations of templates
924 refer to their template and parameters through DECL_TEMPLATE_INFO.
925
926 How should I handle parsing member functions with the proper param
927 decls?  Set them up again or try to use the same ones?  Currently we do
928 the former.  We can probably do this without any extra machinery in
929 store_pending_inline, by deducing the parameters from the decl in
930 do_pending_inlines.  PRE_PARSED_TEMPLATE_DECL?
931
932 If a base is a parm, we can't check anything about it.  If a base is not
933 a parm, we need to check it for name binding.  Do finish_base_struct if
934 no bases are parameterized (only if none, including indirect, are
935 parms).  Nah, don't bother trying to do any of this until instantiation
936 -- we only need to do name binding in advance.
937
938 Always set up method vec and fields, inc. synthesized methods.  Really?
939 We can't know the types of the copy folks, or whether we need a
940 destructor, or can have a default ctor, until we know our bases and
941 fields.  Otherwise, we can assume and fix ourselves later.  Hopefully.
942
943 @node Access Control, Error Reporting, Templates, Top
944 @section Access Control
945 The function compute_access returns one of three values:
946
947 @table @code
948 @item access_public
949 means that the field can be accessed by the current lexical scope.
950
951 @item access_protected
952 means that the field cannot be accessed by the current lexical scope
953 because it is protected.
954
955 @item access_private
956 means that the field cannot be accessed by the current lexical scope
957 because it is private.
958 @end table
959
960 DECL_ACCESS is used for access declarations; alter_access creates a list
961 of types and accesses for a given decl.
962
963 Formerly, DECL_@{PUBLIC,PROTECTED,PRIVATE@} corresponded to the return
964 codes of compute_access and were used as a cache for compute_access.
965 Now they are not used at all.
966
967 TREE_PROTECTED and TREE_PRIVATE are used to record the access levels
968 granted by the containing class.  BEWARE: TREE_PUBLIC means something
969 completely unrelated to access control!
970
971 @node Error Reporting, Parser, Access Control, Top
972 @section Error Reporting
973
974 The C++ front-end uses a call-back mechanism to allow functions to print
975 out reasonable strings for types and functions without putting extra
976 logic in the functions where errors are found.  The interface is through
977 the @code{cp_error} function (or @code{cp_warning}, etc.).  The
978 syntax is exactly like that of @code{error}, except that a few more
979 conversions are supported:
980
981 @itemize @bullet
982 @item
983 %C indicates a value of `enum tree_code'.
984 @item
985 %D indicates a *_DECL node.
986 @item
987 %E indicates a *_EXPR node.
988 @item
989 %L indicates a value of `enum languages'.
990 @item
991 %P indicates the name of a parameter (i.e. "this", "1", "2", ...)
992 @item
993 %T indicates a *_TYPE node.
994 @item
995 %O indicates the name of an operator (MODIFY_EXPR -> "operator =").
996
997 @end itemize
998
999 There is some overlap between these; for instance, any of the node
1000 options can be used for printing an identifier (though only @code{%D}
1001 tries to decipher function names).
1002
1003 For a more verbose message (@code{class foo} as opposed to just @code{foo},
1004 including the return type for functions), use @code{%#c}.
1005 To have the line number on the error message indicate the line of the
1006 DECL, use @code{cp_error_at} and its ilk; to indicate which argument you want,
1007 use @code{%+D}, or it will default to the first.
1008
1009 @node Parser, Copying Objects, Error Reporting, Top
1010 @section Parser
1011
1012 Some comments on the parser:
1013
1014 The @code{after_type_declarator} / @code{notype_declarator} hack is
1015 necessary in order to allow redeclarations of @code{TYPENAME}s, for
1016 instance
1017
1018 @example
1019 typedef int foo;
1020 class A @{
1021   char *foo;
1022 @};
1023 @end example
1024
1025 In the above, the first @code{foo} is parsed as a @code{notype_declarator},
1026 and the second as a @code{after_type_declarator}.
1027
1028 Ambiguities:
1029
1030 There are currently four reduce/reduce ambiguities in the parser.  They are:
1031
1032 1) Between @code{template_parm} and
1033 @code{named_class_head_sans_basetype}, for the tokens @code{aggr
1034 identifier}.  This situation occurs in code looking like
1035
1036 @example
1037 template <class T> class A @{ @};
1038 @end example
1039
1040 It is ambiguous whether @code{class T} should be parsed as the
1041 declaration of a template type parameter named @code{T} or an unnamed
1042 constant parameter of type @code{class T}.  Section 14.6, paragraph 3 of
1043 the January '94 working paper states that the first interpretation is
1044 the correct one.  This ambiguity results in two reduce/reduce conflicts.
1045
1046 2) Between @code{primary} and @code{type_id} for code like @samp{int()}
1047 in places where both can be accepted, such as the argument to
1048 @code{sizeof}.  Section 8.1 of the pre-San Diego working paper specifies
1049 that these ambiguous constructs will be interpreted as @code{typename}s.
1050 This ambiguity results in six reduce/reduce conflicts between
1051 @samp{absdcl} and @samp{functional_cast}.
1052
1053 3) Between @code{functional_cast} and
1054 @code{complex_direct_notype_declarator}, for various token strings.
1055 This situation occurs in code looking like
1056
1057 @example
1058 int (*a);
1059 @end example
1060
1061 This code is ambiguous; it could be a declaration of the variable
1062 @samp{a} as a pointer to @samp{int}, or it could be a functional cast of
1063 @samp{*a} to @samp{int}.  Section 6.8 specifies that the former
1064 interpretation is correct.  This ambiguity results in 7 reduce/reduce
1065 conflicts.  Another aspect of this ambiguity is code like 'int (x[2]);',
1066 which is resolved at the '[' and accounts for 6 reduce/reduce conflicts
1067 between @samp{direct_notype_declarator} and
1068 @samp{primary}/@samp{overqualified_id}.  Finally, there are 4 r/r
1069 conflicts between @samp{expr_or_declarator} and @samp{primary} over code
1070 like 'int (a);', which could probably be resolved but would also
1071 probably be more trouble than it's worth.  In all, this situation
1072 accounts for 17 conflicts.  Ack!
1073
1074 The second case above is responsible for the failure to parse 'LinppFile
1075 ppfile (String (argv[1]), &outs, argc, argv);' (from Rogue Wave
1076 Math.h++) as an object declaration, and must be fixed so that it does
1077 not resolve until later.
1078
1079 4) Indirectly between @code{after_type_declarator} and @code{parm}, for
1080 type names.  This occurs in (as one example) code like
1081
1082 @example
1083 typedef int foo, bar;
1084 class A @{
1085   foo (bar);
1086 @};
1087 @end example
1088
1089 What is @code{bar} inside the class definition?  We currently interpret
1090 it as a @code{parm}, as does Cfront, but IBM xlC interprets it as an
1091 @code{after_type_declarator}.  I believe that xlC is correct, in light
1092 of 7.1p2, which says "The longest sequence of @i{decl-specifiers} that
1093 could possibly be a type name is taken as the @i{decl-specifier-seq} of
1094 a @i{declaration}."  However, it seems clear that this rule must be
1095 violated in the case of constructors.  This ambiguity accounts for 8
1096 conflicts.
1097
1098 Unlike the others, this ambiguity is not recognized by the Working Paper.
1099
1100 @node  Copying Objects, Exception Handling, Parser, Top
1101 @section Copying Objects
1102
1103 The generated copy assignment operator in g++ does not currently do the
1104 right thing for multiple inheritance involving virtual bases; it just
1105 calls the copy assignment operators for its direct bases.  What it
1106 should probably do is:
1107
1108 1) Split up the copy assignment operator for all classes that have
1109 vbases into "copy my vbases" and "copy everything else" parts.  Or do
1110 the trickiness that the constructors do to ensure that vbases don't get
1111 initialized by intermediate bases.
1112
1113 2) Wander through the class lattice, find all vbases for which no
1114 intermediate base has a user-defined copy assignment operator, and call
1115 their "copy everything else" routines.  If not all of my vbases satisfy
1116 this criterion, warn, because this may be surprising behavior.
1117
1118 3) Call the "copy everything else" routine for my direct bases.
1119
1120 If we only have one direct base, we can just foist everything off onto
1121 them.
1122
1123 This issue is currently under discussion in the core reflector
1124 (2/28/94).
1125
1126 @node  Exception Handling, Free Store, Copying Objects, Top
1127 @section Exception Handling
1128
1129 Note, exception handling in g++ is still under development.  
1130
1131 This section describes the mapping of C++ exceptions in the C++
1132 front-end, into the back-end exception handling framework.
1133
1134 The basic mechanism of exception handling in the back-end is
1135 unwind-protect a la elisp.  This is a general, robust, and language
1136 independent representation for exceptions.
1137
1138 The C++ front-end exceptions are mapping into the unwind-protect
1139 semantics by the C++ front-end.  The mapping is describe below.
1140
1141 When -frtti is used, rtti is used to do exception object type checking,
1142 when it isn't used, the encoded name for the type of the object being
1143 thrown is used instead.  All code that originates exceptions, even code
1144 that throws exceptions as a side effect, like dynamic casting, and all
1145 code that catches exceptions must be compiled with either -frtti, or
1146 -fno-rtti.  It is not possible to mix rtti base exception handling
1147 objects with code that doesn't use rtti.  The exceptions to this, are
1148 code that doesn't catch or throw exceptions, catch (...), and code that
1149 just rethrows an exception.
1150
1151 Currently we use the normal mangling used in building functions names
1152 (int's are "i", const char * is PCc) to build the non-rtti base type
1153 descriptors for exception handling.  These descriptors are just plain
1154 NULL terminated strings, and internally they are passed around as char
1155 *.
1156
1157 In C++, all cleanups should be protected by exception regions.  The
1158 region starts just after the reason why the cleanup is created has
1159 ended.  For example, with an automatic variable, that has a constructor,
1160 it would be right after the constructor is run.  The region ends just
1161 before the finalization is expanded.  Since the backend may expand the
1162 cleanup multiple times along different paths, once for normal end of the
1163 region, once for non-local gotos, once for returns, etc, the backend
1164 must take special care to protect the finalization expansion, if the
1165 expansion is for any other reason than normal region end, and it is
1166 `inline' (it is inside the exception region).  The backend can either
1167 choose to move them out of line, or it can created an exception region
1168 over the finalization to protect it, and in the handler associated with
1169 it, it would not run the finalization as it otherwise would have, but
1170 rather just rethrow to the outer handler, careful to skip the normal
1171 handler for the original region.
1172
1173 In Ada, they will use the more runtime intensive approach of having
1174 fewer regions, but at the cost of additional work at run time, to keep a
1175 list of things that need cleanups.  When a variable has finished
1176 construction, they add the cleanup to the list, when the come to the end
1177 of the lifetime of the variable, the run the list down.  If the take a
1178 hit before the section finishes normally, they examine the list for
1179 actions to perform.  I hope they add this logic into the back-end, as it
1180 would be nice to get that alternative approach in C++.
1181
1182 On an rs6000, xlC stores exception objects on that stack, under the try
1183 block.  When is unwinds down into a handler, the frame pointer is
1184 adjusted back to the normal value for the frame in which the handler
1185 resides, and the stack pointer is left unchanged from the time at which
1186 the object was thrown.  This is so that there is always someplace for
1187 the exception object, and nothing can overwrite it, once we start
1188 throwing.  The only bad part, is that the stack remains large.
1189
1190 The below points out some things that work in g++'s exception handling.
1191
1192 All completely constructed temps and local variables are cleaned up in
1193 all unwinded scopes.  Completely constructed parts of partially
1194 constructed objects are cleaned up.  This includes partially built
1195 arrays.  Exception specifications are now handled.  Thrown objects are
1196 now cleaned up all the time.  We can now tell if we have an active
1197 exception being thrown or not (__eh_type != 0).  We use this to call
1198 terminate if someone does a throw; without there being an active
1199 exception object.  uncaught_exception () works.
1200
1201 The below points out some flaws in g++'s exception handling, as it now
1202 stands.
1203
1204 Only exact type matching or reference matching of throw types works when
1205 -fno-rtti is used.  Only works on a SPARC (like Suns), SPARClite, i386,
1206 arm, rs6000, PowerPC, Alpha, mips, VAX, m68k and z8k machines.  Partial
1207 support is in for all other machines, but a stack unwinder called
1208 __unwind_function has to be written, and added to libgcc2 for them.  The
1209 new EH code doesn't rely upon the __unwind_function for C++ code,
1210 instead it creates per function unwinders right inside the function,
1211 unfortunately, on many platforms the definition of RETURN_ADDR_RTX in
1212 the tm.h file for the machine port is wrong.  The HPPA has a brain dead
1213 abi that prevents exception handling from just working.  See below for
1214 details on __unwind_function.  Don't expect exception handling to work
1215 right if you optimize, in fact the compiler will probably core dump.
1216 RTL_EXPRs for EH cond variables for && and || exprs should probably be
1217 wrapped in UNSAVE_EXPRs, and RTL_EXPRs tweaked so that they can be
1218 unsaved, and the UNSAVE_EXPR code should be in the backend, or
1219 alternatively, UNSAVE_EXPR should be ripped out and exactly one
1220 finalization allowed to be expanded by the backend.  I talked with
1221 kenner about this, and we have to allow multiple expansions.
1222
1223 We only do pointer conversions on exception matching a la 15.3 p2 case
1224 3: `A handler with type T, const T, T&, or const T& is a match for a
1225 throw-expression with an object of type E if [3]T is a pointer type and
1226 E is a pointer type that can be converted to T by a standard pointer
1227 conversion (_conv.ptr_) not involving conversions to pointers to private
1228 or protected base classes.' when -frtti is given.
1229
1230 We don't call delete on new expressions that die because the ctor threw
1231 an exception.  See except/18 for a test case.
1232
1233 15.2 para 13: The exception being handled should be rethrown if control
1234 reaches the end of a handler of the function-try-block of a constructor
1235 or destructor, right now, it is not.
1236
1237 15.2 para 12: If a return statement appears in a handler of
1238 function-try-block of a constructor, the program is ill-formed, but this
1239 isn't diagnosed.
1240
1241 15.2 para 11: If the handlers of a function-try-block contain a jump
1242 into the body of a constructor or destructor, the program is ill-formed,
1243 but this isn't diagnosed.
1244
1245 15.2 para 9: Check that the fully constructed base classes and members
1246 of an object are destroyed before entering the handler of a
1247 function-try-block of a constructor or destructor for that object.
1248
1249 build_exception_variant should sort the incoming list, so that it
1250 implements set compares, not exact list equality.  Type smashing should
1251 smash exception specifications using set union.
1252
1253 Thrown objects are usually allocated on the heap, in the usual way.  If
1254 one runs out of heap space, throwing an object will probably never work.
1255 This could be relaxed some by passing an __in_chrg parameter to track
1256 who has control over the exception object.  Thrown objects are not
1257 allocated on the heap when they are pointer to object types.  We should
1258 extend it so that all small (<4*sizeof(void*)) objects are stored
1259 directly, instead of allocated on the heap.
1260
1261 When the backend returns a value, it can create new exception regions
1262 that need protecting.  The new region should rethrow the object in
1263 context of the last associated cleanup that ran to completion.
1264
1265 The structure of the code that is generated for C++ exception handling
1266 code is shown below:
1267
1268 @example
1269 Ln:                                     throw value;
1270         copy value onto heap
1271         jump throw (Ln, id, address of copy of value on heap)
1272
1273                                         try @{
1274 +Lstart:        the start of the main EH region
1275 |...                                            ...
1276 +Lend:          the end of the main EH region
1277                                         @} catch (T o) @{
1278                                                 ...1
1279                                         @}
1280 Lresume:
1281         nop     used to make sure there is something before
1282                 the next region ends, if there is one
1283 ...                                     ...
1284
1285         jump Ldone
1286 [
1287 Lmainhandler:    handler for the region Lstart-Lend
1288         cleanup
1289 ] zero or more, depending upon automatic vars with dtors
1290 +Lpartial:
1291 |        jump Lover
1292 +Lhere:
1293         rethrow (Lhere, same id, same obj);
1294 Lterm:          handler for the region Lpartial-Lhere
1295         call terminate
1296 Lover:
1297 [
1298  [
1299         call throw_type_match
1300         if (eq) @{
1301  ] these lines disappear when there is no catch condition
1302 +Lsregion2:
1303 |       ...1
1304 |       jump Lresume
1305 |Lhandler:      handler for the region Lsregion2-Leregion2
1306 |       rethrow (Lresume, same id, same obj);
1307 +Leregion2
1308         @}
1309 ] there are zero or more of these sections, depending upon how many
1310   catch clauses there are
1311 ----------------------------- expand_end_all_catch --------------------------
1312                 here we have fallen off the end of all catch
1313                 clauses, so we rethrow to outer
1314         rethrow (Lresume, same id, same obj);
1315 ----------------------------- expand_end_all_catch --------------------------
1316 [
1317 L1:     maybe throw routine
1318 ] depending upon if we have expanded it or not
1319 Ldone:
1320         ret
1321
1322 start_all_catch emits labels: Lresume, 
1323
1324 @end example
1325
1326 The __unwind_function takes a pointer to the throw handler, and is
1327 expected to pop the stack frame that was built to call it, as well as
1328 the frame underneath and then jump to the throw handler.  It must
1329 restore all registers to their proper values as well as all other
1330 machine state as determined by the context in which we are unwinding
1331 into.  The way I normally start is to compile:
1332
1333         void *g;
1334         foo(void* a) @{ g = a; @}
1335
1336 with -S, and change the thing that alters the PC (return, or ret
1337 usually) to not alter the PC, making sure to leave all other semantics
1338 (like adjusting the stack pointer, or frame pointers) in.  After that,
1339 replicate the prologue once more at the end, again, changing the PC
1340 altering instructions, and finally, at the very end, jump to `g'.
1341
1342 It takes about a week to write this routine, if someone wants to
1343 volunteer to write this routine for any architecture, exception support
1344 for that architecture will be added to g++.  Please send in those code
1345 donations.  One other thing that needs to be done, is to double check
1346 that __builtin_return_address (0) works.
1347
1348 @subsection Specific Targets
1349
1350 For the alpha, the __unwind_function will be something resembling:
1351
1352 @example
1353 void
1354 __unwind_function(void *ptr)
1355 @{
1356   /* First frame */
1357   asm ("ldq $15, 8($30)"); /* get the saved frame ptr; 15 is fp, 30 is sp */
1358   asm ("bis $15, $15, $30"); /* reload sp with the fp we found */
1359
1360   /* Second frame */
1361   asm ("ldq $15, 8($30)"); /* fp */
1362   asm ("bis $15, $15, $30"); /* reload sp with the fp we found */
1363
1364   /* Return */
1365   asm ("ret $31, ($16), 1"); /* return to PTR, stored in a0 */
1366 @}
1367 @end example
1368
1369 @noindent
1370 However, there are a few problems preventing it from working.  First of
1371 all, the gcc-internal function @code{__builtin_return_address} needs to
1372 work given an argument of 0 for the alpha.  As it stands as of August
1373 30th, 1995, the code for @code{BUILT_IN_RETURN_ADDRESS} in @file{expr.c}
1374 will definitely not work on the alpha.  Instead, we need to define
1375 the macros @code{DYNAMIC_CHAIN_ADDRESS} (maybe),
1376 @code{RETURN_ADDR_IN_PREVIOUS_FRAME}, and definitely need a new
1377 definition for @code{RETURN_ADDR_RTX}.
1378
1379 In addition (and more importantly), we need a way to reliably find the
1380 frame pointer on the alpha.  The use of the value 8 above to restore the
1381 frame pointer (register 15) is incorrect.  On many systems, the frame
1382 pointer is consistently offset to a specific point on the stack.  On the
1383 alpha, however, the frame pointer is pushed last.  First the return
1384 address is stored, then any other registers are saved (e.g., @code{s0}),
1385 and finally the frame pointer is put in place.  So @code{fp} could have
1386 an offset of 8, but if the calling function saved any registers at all,
1387 they add to the offset.
1388
1389 The only places the frame size is noted are with the @samp{.frame}
1390 directive, for use by the debugger and the OSF exception handling model
1391 (useless to us), and in the initial computation of the new value for
1392 @code{sp}, the stack pointer.  For example, the function may start with:
1393
1394 @example
1395 lda $30,-32($30)
1396 .frame $15,32,$26,0
1397 @end example 
1398
1399 @noindent
1400 The 32 above is exactly the value we need.  With this, we can be sure
1401 that the frame pointer is stored 8 bytes less---in this case, at 24(sp)).
1402 The drawback is that there is no way that I (Brendan) have found to let
1403 us discover the size of a previous frame @emph{inside} the definition
1404 of @code{__unwind_function}.
1405
1406 So to accomplish exception handling support on the alpha, we need two
1407 things: first, a way to figure out where the frame pointer was stored,
1408 and second, a functional @code{__builtin_return_address} implementation
1409 for except.c to be able to use it.
1410
1411 @subsection Backend Exception Support
1412
1413 The backend must be extended to fully support exceptions.  Right now
1414 there are a few hooks into the alpha exception handling backend that
1415 resides in the C++ frontend from that backend that allows exception
1416 handling to work in g++.  An exception region is a segment of generated
1417 code that has a handler associated with it.  The exception regions are
1418 denoted in the generated code as address ranges denoted by a starting PC
1419 value and an ending PC value of the region.  Some of the limitations
1420 with this scheme are:
1421
1422 @itemize @bullet
1423 @item
1424 The backend replicates insns for such things as loop unrolling and
1425 function inlining.  Right now, there are no hooks into the frontend's
1426 exception handling backend to handle the replication of insns.  When
1427 replication happens, a new exception region descriptor needs to be
1428 generated for the new region.
1429
1430 @item
1431 The backend expects to be able to rearrange code, for things like jump
1432 optimization.  Any rearranging of the code needs have exception region
1433 descriptors updated appropriately.
1434
1435 @item
1436 The backend can eliminate dead code.  Any associated exception region
1437 descriptor that refers to fully contained code that has been eliminated
1438 should also be removed, although not doing this is harmless in terms of
1439 semantics.
1440
1441 @end itemize
1442
1443 The above is not meant to be exhaustive, but does include all things I
1444 have thought of so far.  I am sure other limitations exist.
1445
1446 Below are some notes on the migration of the exception handling code
1447 backend from the C++ frontend to the backend.
1448
1449 NOTEs are to be used to denote the start of an exception region, and the
1450 end of the region.  I presume that the interface used to generate these
1451 notes in the backend would be two functions, start_exception_region and
1452 end_exception_region (or something like that).  The frontends are
1453 required to call them in pairs.  When marking the end of a region, an
1454 argument can be passed to indicate the handler for the marked region.
1455 This can be passed in many ways, currently a tree is used.  Another
1456 possibility would be insns for the handler, or a label that denotes a
1457 handler.  I have a feeling insns might be the the best way to pass it.
1458 Semantics are, if an exception is thrown inside the region, control is
1459 transfered unconditionally to the handler.  If control passes through
1460 the handler, then the backend is to rethrow the exception, in the
1461 context of the end of the original region.  The handler is protected by
1462 the conventional mechanisms; it is the frontend's responsibility to
1463 protect the handler, if special semantics are required.
1464
1465 This is a very low level view, and it would be nice is the backend
1466 supported a somewhat higher level view in addition to this view.  This
1467 higher level could include source line number, name of the source file,
1468 name of the language that threw the exception and possibly the name of
1469 the exception.  Kenner may want to rope you into doing more than just
1470 the basics required by C++.  You will have to resolve this.  He may want
1471 you to do support for non-local gotos, first scan for exception handler,
1472 if none is found, allow the debugger to be entered, without any cleanups
1473 being done.  To do this, the backend would have to know the difference
1474 between a cleanup-rethrower, and a real handler, if would also have to
1475 have a way to know if a handler `matches' a thrown exception, and this
1476 is frontend specific.
1477
1478 The stack unwinder is one of the hardest parts to do.  It is highly
1479 machine dependent.  The form that kenner seems to like was a couple of
1480 macros, that would do the machine dependent grunt work.  One preexisting
1481 function that might be of some use is __builtin_return_address ().  One
1482 macro he seemed to want was __builtin_return_address, and the other
1483 would do the hard work of fixing up the registers, adjusting the stack
1484 pointer, frame pointer, arg pointer and so on.
1485
1486
1487 @node Free Store, Concept Index, Exception Handling, Top
1488 @section Free Store
1489
1490 @code{operator new []} adds a magic cookie to the beginning of arrays
1491 for which the number of elements will be needed by @code{operator delete
1492 []}.  These are arrays of objects with destructors and arrays of objects
1493 that define @code{operator delete []} with the optional size_t argument.
1494 This cookie can be examined from a program as follows:
1495
1496 @example
1497 typedef unsigned long size_t;
1498 extern "C" int printf (const char *, ...);
1499
1500 size_t nelts (void *p)
1501 @{
1502   struct cookie @{
1503     size_t nelts __attribute__ ((aligned (sizeof (double))));
1504   @};
1505
1506   cookie *cp = (cookie *)p;
1507   --cp;
1508
1509   return cp->nelts;
1510 @}
1511
1512 struct A @{
1513   ~A() @{ @}
1514 @};
1515
1516 main()
1517 @{
1518   A *ap = new A[3];
1519   printf ("%ld\n", nelts (ap));
1520 @}
1521 @end example
1522
1523 @section Linkage
1524 The linkage code in g++ is horribly twisted in order to meet two design goals:
1525
1526 1) Avoid unnecessary emission of inlines and vtables.
1527
1528 2) Support pedantic assemblers like the one in AIX.
1529
1530 To meet the first goal, we defer emission of inlines and vtables until
1531 the end of the translation unit, where we can decide whether or not they
1532 are needed, and how to emit them if they are.
1533
1534 @node Concept Index,  , Free Store, Top
1535 @section Concept Index
1536
1537 @printindex cp
1538
1539 @bye