OSDN Git Service

PR c++/15745
[pf3gnuchains/gcc-fork.git] / gcc / cp / except.c
1 /* Handle exceptional things in C++.
2    Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2007  Free Software Foundation, Inc.
4    Contributed by Michael Tiemann <tiemann@cygnus.com>
5    Rewritten by Mike Stump <mrs@cygnus.com>, based upon an
6    initial re-implementation courtesy Tad Hunt.
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "tm.h"
29 #include "tree.h"
30 #include "rtl.h"
31 #include "expr.h"
32 #include "libfuncs.h"
33 #include "cp-tree.h"
34 #include "flags.h"
35 #include "output.h"
36 #include "except.h"
37 #include "toplev.h"
38 #include "tree-inline.h"
39 #include "tree-iterator.h"
40 #include "target.h"
41
42 static void push_eh_cleanup (tree);
43 static tree prepare_eh_type (tree);
44 static tree build_eh_type_type (tree);
45 static tree do_begin_catch (void);
46 static int dtor_nothrow (tree);
47 static tree do_end_catch (tree);
48 static bool decl_is_java_type (tree decl, int err);
49 static void initialize_handler_parm (tree, tree);
50 static tree do_allocate_exception (tree);
51 static tree wrap_cleanups_r (tree *, int *, void *);
52 static int complete_ptr_ref_or_void_ptr_p (tree, tree);
53 static bool is_admissible_throw_operand (tree);
54 static int can_convert_eh (tree, tree);
55 static tree cp_protect_cleanup_actions (void);
56
57 /* Sets up all the global eh stuff that needs to be initialized at the
58    start of compilation.  */
59
60 void
61 init_exception_processing (void)
62 {
63   tree tmp;
64
65   /* void std::terminate (); */
66   push_namespace (std_identifier);
67   tmp = build_function_type (void_type_node, void_list_node);
68   terminate_node = build_cp_library_fn_ptr ("terminate", tmp);
69   TREE_THIS_VOLATILE (terminate_node) = 1;
70   TREE_NOTHROW (terminate_node) = 1;
71   pop_namespace ();
72
73   /* void __cxa_call_unexpected(void *); */
74   tmp = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
75   tmp = build_function_type (void_type_node, tmp);
76   call_unexpected_node
77     = push_throw_library_fn (get_identifier ("__cxa_call_unexpected"), tmp);
78
79   eh_personality_libfunc = init_one_libfunc (USING_SJLJ_EXCEPTIONS
80                                              ? "__gxx_personality_sj0"
81                                              : "__gxx_personality_v0");
82   if (targetm.arm_eabi_unwinder)
83     unwind_resume_libfunc = init_one_libfunc ("__cxa_end_cleanup");
84   else
85     default_init_unwind_resume_libfunc ();
86
87   lang_eh_runtime_type = build_eh_type_type;
88   lang_protect_cleanup_actions = &cp_protect_cleanup_actions;
89 }
90
91 /* Returns an expression to be executed if an unhandled exception is
92    propagated out of a cleanup region.  */
93
94 static tree
95 cp_protect_cleanup_actions (void)
96 {
97   /* [except.terminate]
98
99      When the destruction of an object during stack unwinding exits
100      using an exception ... void terminate(); is called.  */
101   return build_call_n (terminate_node, 0);
102 }
103
104 static tree
105 prepare_eh_type (tree type)
106 {
107   if (type == NULL_TREE)
108     return type;
109   if (type == error_mark_node)
110     return error_mark_node;
111
112   /* peel back references, so they match.  */
113   type = non_reference (type);
114
115   /* Peel off cv qualifiers.  */
116   type = TYPE_MAIN_VARIANT (type);
117
118   /* Functions and arrays decay to pointers.  */
119   type = type_decays_to (type);
120
121   return type;
122 }
123
124 /* Return the type info for TYPE as used by EH machinery.  */
125 tree
126 eh_type_info (tree type)
127 {
128   tree exp;
129
130   if (type == NULL_TREE || type == error_mark_node)
131     return type;
132
133   if (decl_is_java_type (type, 0))
134     exp = build_java_class_ref (TREE_TYPE (type));
135   else
136     exp = get_tinfo_decl (type);
137
138   return exp;
139 }
140
141 /* Build the address of a typeinfo decl for use in the runtime
142    matching field of the exception model.  */
143
144 static tree
145 build_eh_type_type (tree type)
146 {
147   tree exp = eh_type_info (type);
148
149   if (!exp)
150     return NULL;
151
152   mark_used (exp);
153
154   return convert (ptr_type_node, build_address (exp));
155 }
156
157 tree
158 build_exc_ptr (void)
159 {
160   return build0 (EXC_PTR_EXPR, ptr_type_node);
161 }
162
163 /* Build up a call to __cxa_get_exception_ptr so that we can build a
164    copy constructor for the thrown object.  */
165
166 static tree
167 do_get_exception_ptr (void)
168 {
169   tree fn;
170
171   fn = get_identifier ("__cxa_get_exception_ptr");
172   if (!get_global_value_if_present (fn, &fn))
173     {
174       /* Declare void* __cxa_get_exception_ptr (void *).  */
175       tree tmp = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
176       fn = push_library_fn (fn, build_function_type (ptr_type_node, tmp));
177     }
178
179   return build_function_call (fn, tree_cons (NULL_TREE, build_exc_ptr (),
180                                              NULL_TREE));
181 }
182
183 /* Build up a call to __cxa_begin_catch, to tell the runtime that the
184    exception has been handled.  */
185
186 static tree
187 do_begin_catch (void)
188 {
189   tree fn;
190
191   fn = get_identifier ("__cxa_begin_catch");
192   if (!get_global_value_if_present (fn, &fn))
193     {
194       /* Declare void* __cxa_begin_catch (void *).  */
195       tree tmp = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
196       fn = push_library_fn (fn, build_function_type (ptr_type_node, tmp));
197     }
198
199   return build_function_call (fn, tree_cons (NULL_TREE, build_exc_ptr (),
200                                              NULL_TREE));
201 }
202
203 /* Returns nonzero if cleaning up an exception of type TYPE (which can be
204    NULL_TREE for a ... handler) will not throw an exception.  */
205
206 static int
207 dtor_nothrow (tree type)
208 {
209   if (type == NULL_TREE)
210     return 0;
211
212   if (!CLASS_TYPE_P (type))
213     return 1;
214
215   if (CLASSTYPE_LAZY_DESTRUCTOR (type))
216     lazily_declare_fn (sfk_destructor, type);
217
218   return TREE_NOTHROW (CLASSTYPE_DESTRUCTORS (type));
219 }
220
221 /* Build up a call to __cxa_end_catch, to destroy the exception object
222    for the current catch block if no others are currently using it.  */
223
224 static tree
225 do_end_catch (tree type)
226 {
227   tree fn, cleanup;
228
229   fn = get_identifier ("__cxa_end_catch");
230   if (!get_global_value_if_present (fn, &fn))
231     {
232       /* Declare void __cxa_end_catch ().  */
233       fn = push_void_library_fn (fn, void_list_node);
234       /* This can throw if the destructor for the exception throws.  */
235       TREE_NOTHROW (fn) = 0;
236     }
237
238   cleanup = build_function_call (fn, NULL_TREE);
239   TREE_NOTHROW (cleanup) = dtor_nothrow (type);
240
241   return cleanup;
242 }
243
244 /* This routine creates the cleanup for the current exception.  */
245
246 static void
247 push_eh_cleanup (tree type)
248 {
249   finish_decl_cleanup (NULL_TREE, do_end_catch (type));
250 }
251
252 /* Return nonzero value if DECL is a Java type suitable for catch or
253    throw.  */
254
255 static bool
256 decl_is_java_type (tree decl, int err)
257 {
258   bool r = (TREE_CODE (decl) == POINTER_TYPE
259             && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
260             && TYPE_FOR_JAVA (TREE_TYPE (decl)));
261
262   if (err)
263     {
264       if (TREE_CODE (decl) == REFERENCE_TYPE
265           && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
266           && TYPE_FOR_JAVA (TREE_TYPE (decl)))
267         {
268           /* Can't throw a reference.  */
269           error ("type %qT is disallowed in Java %<throw%> or %<catch%>",
270                  decl);
271         }
272
273       if (r)
274         {
275           tree jthrow_node
276             = IDENTIFIER_GLOBAL_VALUE (get_identifier ("jthrowable"));
277
278           if (jthrow_node == NULL_TREE)
279             fatal_error
280               ("call to Java %<catch%> or %<throw%> with %<jthrowable%> undefined");
281
282           jthrow_node = TREE_TYPE (TREE_TYPE (jthrow_node));
283
284           if (! DERIVED_FROM_P (jthrow_node, TREE_TYPE (decl)))
285             {
286               /* Thrown object must be a Throwable.  */
287               error ("type %qT is not derived from %<java::lang::Throwable%>",
288                      TREE_TYPE (decl));
289             }
290         }
291     }
292
293   return r;
294 }
295
296 /* Select the personality routine to be used for exception handling,
297    or issue an error if we need two different ones in the same
298    translation unit.
299    ??? At present eh_personality_libfunc is set to
300    __gxx_personality_(sj|v)0 in init_exception_processing - should it
301    be done here instead?  */
302 void
303 choose_personality_routine (enum languages lang)
304 {
305   static enum {
306     chose_none,
307     chose_cpp,
308     chose_java,
309     gave_error
310   } state;
311
312   switch (state)
313     {
314     case gave_error:
315       return;
316
317     case chose_cpp:
318       if (lang != lang_cplusplus)
319         goto give_error;
320       return;
321
322     case chose_java:
323       if (lang != lang_java)
324         goto give_error;
325       return;
326
327     case chose_none:
328       ; /* Proceed to language selection.  */
329     }
330
331   switch (lang)
332     {
333     case lang_cplusplus:
334       state = chose_cpp;
335       break;
336
337     case lang_java:
338       state = chose_java;
339       eh_personality_libfunc = init_one_libfunc (USING_SJLJ_EXCEPTIONS
340                                                  ? "__gcj_personality_sj0"
341                                                  : "__gcj_personality_v0");
342       break;
343
344     default:
345       gcc_unreachable ();
346     }
347   return;
348
349  give_error:
350   error ("mixing C++ and Java catches in a single translation unit");
351   state = gave_error;
352 }
353
354 /* Initialize the catch parameter DECL.  */
355
356 static void
357 initialize_handler_parm (tree decl, tree exp)
358 {
359   tree init;
360   tree init_type;
361
362   /* Make sure we mark the catch param as used, otherwise we'll get a
363      warning about an unused ((anonymous)).  */
364   TREE_USED (decl) = 1;
365
366   /* Figure out the type that the initializer is.  Pointers are returned
367      adjusted by value from __cxa_begin_catch.  Others are returned by
368      reference.  */
369   init_type = TREE_TYPE (decl);
370   if (!POINTER_TYPE_P (init_type))
371     init_type = build_reference_type (init_type);
372
373   choose_personality_routine (decl_is_java_type (init_type, 0)
374                               ? lang_java : lang_cplusplus);
375
376   /* Since pointers are passed by value, initialize a reference to
377      pointer catch parm with the address of the temporary.  */
378   if (TREE_CODE (init_type) == REFERENCE_TYPE
379       && TYPE_PTR_P (TREE_TYPE (init_type)))
380     exp = build_unary_op (ADDR_EXPR, exp, 1);
381
382   exp = ocp_convert (init_type, exp, CONV_IMPLICIT|CONV_FORCE_TEMP, 0);
383
384   init = convert_from_reference (exp);
385
386   /* If the constructor for the catch parm exits via an exception, we
387      must call terminate.  See eh23.C.  */
388   if (TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
389     {
390       /* Generate the copy constructor call directly so we can wrap it.
391          See also expand_default_init.  */
392       init = ocp_convert (TREE_TYPE (decl), init,
393                           CONV_IMPLICIT|CONV_FORCE_TEMP, 0);
394       /* Force cleanups now to avoid nesting problems with the
395          MUST_NOT_THROW_EXPR.  */
396       init = fold_build_cleanup_point_expr (TREE_TYPE (init), init);
397       init = build1 (MUST_NOT_THROW_EXPR, TREE_TYPE (init), init);
398     }
399
400   decl = pushdecl (decl);
401
402   start_decl_1 (decl, true);
403   cp_finish_decl (decl, init, /*init_const_expr_p=*/false, NULL_TREE,
404                   LOOKUP_ONLYCONVERTING|DIRECT_BIND);
405 }
406
407 /* Call this to start a catch block.  DECL is the catch parameter.  */
408
409 tree
410 expand_start_catch_block (tree decl)
411 {
412   tree exp;
413   tree type;
414
415   if (! doing_eh (1))
416     return NULL_TREE;
417
418   /* Make sure this declaration is reasonable.  */
419   if (decl && !complete_ptr_ref_or_void_ptr_p (TREE_TYPE (decl), NULL_TREE))
420     decl = error_mark_node;
421
422   if (decl)
423     type = prepare_eh_type (TREE_TYPE (decl));
424   else
425     type = NULL_TREE;
426
427   if (decl && decl_is_java_type (type, 1))
428     {
429       /* Java only passes object via pointer and doesn't require
430          adjusting.  The java object is immediately before the
431          generic exception header.  */
432       exp = build_exc_ptr ();
433       exp = build1 (NOP_EXPR, build_pointer_type (type), exp);
434       exp = build2 (POINTER_PLUS_EXPR, TREE_TYPE (exp), exp,
435                     fold_build1 (NEGATE_EXPR, sizetype,
436                                  TYPE_SIZE_UNIT (TREE_TYPE (exp))));
437       exp = build_indirect_ref (exp, NULL);
438       initialize_handler_parm (decl, exp);
439       return type;
440     }
441
442   /* Call __cxa_end_catch at the end of processing the exception.  */
443   push_eh_cleanup (type);
444
445   /* If there's no decl at all, then all we need to do is make sure
446      to tell the runtime that we've begun handling the exception.  */
447   if (decl == NULL || decl == error_mark_node)
448     finish_expr_stmt (do_begin_catch ());
449
450   /* If the C++ object needs constructing, we need to do that before
451      calling __cxa_begin_catch, so that std::uncaught_exception gets
452      the right value during the copy constructor.  */
453   else if (flag_use_cxa_get_exception_ptr
454            && TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
455     {
456       exp = do_get_exception_ptr ();
457       initialize_handler_parm (decl, exp);
458       finish_expr_stmt (do_begin_catch ());
459     }
460
461   /* Otherwise the type uses a bitwise copy, and we don't have to worry
462      about the value of std::uncaught_exception and therefore can do the
463      copy with the return value of __cxa_end_catch instead.  */
464   else
465     {
466       tree init = do_begin_catch ();
467       tree init_type = type;
468
469       /* Pointers are passed by values, everything else by reference.  */
470       if (!TYPE_PTR_P (type))
471         init_type = build_pointer_type (type);
472       if (init_type != TREE_TYPE (init))
473         init = build1 (NOP_EXPR, init_type, init);
474       exp = create_temporary_var (init_type);
475       DECL_REGISTER (exp) = 1;
476       cp_finish_decl (exp, init, /*init_const_expr=*/false,
477                       NULL_TREE, LOOKUP_ONLYCONVERTING);
478       initialize_handler_parm (decl, exp);
479     }
480
481   return type;
482 }
483
484
485 /* Call this to end a catch block.  Its responsible for emitting the
486    code to handle jumping back to the correct place, and for emitting
487    the label to jump to if this catch block didn't match.  */
488
489 void
490 expand_end_catch_block (void)
491 {
492   if (! doing_eh (1))
493     return;
494
495   /* The exception being handled is rethrown if control reaches the end of
496      a handler of the function-try-block of a constructor or destructor.  */
497   if (in_function_try_handler
498       && (DECL_CONSTRUCTOR_P (current_function_decl)
499           || DECL_DESTRUCTOR_P (current_function_decl)))
500     finish_expr_stmt (build_throw (NULL_TREE));
501 }
502
503 tree
504 begin_eh_spec_block (void)
505 {
506   tree r = build_stmt (EH_SPEC_BLOCK, NULL_TREE, NULL_TREE);
507   add_stmt (r);
508   EH_SPEC_STMTS (r) = push_stmt_list ();
509   return r;
510 }
511
512 void
513 finish_eh_spec_block (tree raw_raises, tree eh_spec_block)
514 {
515   tree raises;
516
517   EH_SPEC_STMTS (eh_spec_block) = pop_stmt_list (EH_SPEC_STMTS (eh_spec_block));
518
519   /* Strip cv quals, etc, from the specification types.  */
520   for (raises = NULL_TREE;
521        raw_raises && TREE_VALUE (raw_raises);
522        raw_raises = TREE_CHAIN (raw_raises))
523     {
524       tree type = prepare_eh_type (TREE_VALUE (raw_raises));
525       tree tinfo = eh_type_info (type);
526
527       mark_used (tinfo);
528       raises = tree_cons (NULL_TREE, type, raises);
529     }
530
531   EH_SPEC_RAISES (eh_spec_block) = raises;
532 }
533
534 /* Return a pointer to a buffer for an exception object of type TYPE.  */
535
536 static tree
537 do_allocate_exception (tree type)
538 {
539   tree fn;
540
541   fn = get_identifier ("__cxa_allocate_exception");
542   if (!get_global_value_if_present (fn, &fn))
543     {
544       /* Declare void *__cxa_allocate_exception(size_t).  */
545       tree tmp = tree_cons (NULL_TREE, size_type_node, void_list_node);
546       fn = push_library_fn (fn, build_function_type (ptr_type_node, tmp));
547     }
548
549   return build_function_call (fn, tree_cons (NULL_TREE, size_in_bytes (type),
550                                              NULL_TREE));
551 }
552
553 /* Call __cxa_free_exception from a cleanup.  This is never invoked
554    directly, but see the comment for stabilize_throw_expr.  */
555
556 static tree
557 do_free_exception (tree ptr)
558 {
559   tree fn;
560
561   fn = get_identifier ("__cxa_free_exception");
562   if (!get_global_value_if_present (fn, &fn))
563     {
564       /* Declare void __cxa_free_exception (void *).  */
565       fn = push_void_library_fn (fn, tree_cons (NULL_TREE, ptr_type_node,
566                                                 void_list_node));
567     }
568
569   return build_function_call (fn, tree_cons (NULL_TREE, ptr, NULL_TREE));
570 }
571
572 /* Wrap all cleanups for TARGET_EXPRs in MUST_NOT_THROW_EXPR.
573    Called from build_throw via walk_tree_without_duplicates.  */
574
575 static tree
576 wrap_cleanups_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
577                  void *data ATTRIBUTE_UNUSED)
578 {
579   tree exp = *tp;
580   tree cleanup;
581
582   /* Don't walk into types.  */
583   if (TYPE_P (exp))
584     {
585       *walk_subtrees = 0;
586       return NULL_TREE;
587     }
588   if (TREE_CODE (exp) != TARGET_EXPR)
589     return NULL_TREE;
590
591   cleanup = TARGET_EXPR_CLEANUP (exp);
592   if (cleanup)
593     {
594       cleanup = build1 (MUST_NOT_THROW_EXPR, void_type_node, cleanup);
595       TARGET_EXPR_CLEANUP (exp) = cleanup;
596     }
597
598   /* Keep iterating.  */
599   return NULL_TREE;
600 }
601
602 /* Build a throw expression.  */
603
604 tree
605 build_throw (tree exp)
606 {
607   tree fn;
608
609   if (exp == error_mark_node)
610     return exp;
611
612   if (processing_template_decl)
613     {
614       if (cfun)
615         current_function_returns_abnormally = 1;
616       return build_min (THROW_EXPR, void_type_node, exp);
617     }
618
619   if (exp == null_node)
620     warning (0, "throwing NULL, which has integral, not pointer type");
621
622   if (exp != NULL_TREE)
623     {
624       if (!is_admissible_throw_operand (exp))
625         return error_mark_node;
626     }
627
628   if (! doing_eh (1))
629     return error_mark_node;
630
631   if (exp && decl_is_java_type (TREE_TYPE (exp), 1))
632     {
633       tree fn = get_identifier ("_Jv_Throw");
634       if (!get_global_value_if_present (fn, &fn))
635         {
636           /* Declare void _Jv_Throw (void *).  */
637           tree tmp = tree_cons (NULL_TREE, ptr_type_node, void_list_node);
638           tmp = build_function_type (ptr_type_node, tmp);
639           fn = push_throw_library_fn (fn, tmp);
640         }
641       else if (really_overloaded_fn (fn))
642         {
643           error ("%qD should never be overloaded", fn);
644           return error_mark_node;
645         }
646       fn = OVL_CURRENT (fn);
647       exp = build_function_call (fn, tree_cons (NULL_TREE, exp, NULL_TREE));
648     }
649   else if (exp)
650     {
651       tree throw_type;
652       tree temp_type;
653       tree cleanup;
654       tree object, ptr;
655       tree tmp;
656       tree temp_expr, allocate_expr;
657       bool elided;
658
659       /* The CLEANUP_TYPE is the internal type of a destructor.  */
660       if (!cleanup_type)
661         {
662           tmp = void_list_node;
663           tmp = tree_cons (NULL_TREE, ptr_type_node, tmp);
664           tmp = build_function_type (void_type_node, tmp);
665           cleanup_type = build_pointer_type (tmp);
666         }
667
668       fn = get_identifier ("__cxa_throw");
669       if (!get_global_value_if_present (fn, &fn))
670         {
671           /* Declare void __cxa_throw (void*, void*, void (*)(void*)).  */
672           /* ??? Second argument is supposed to be "std::type_info*".  */
673           tmp = void_list_node;
674           tmp = tree_cons (NULL_TREE, cleanup_type, tmp);
675           tmp = tree_cons (NULL_TREE, ptr_type_node, tmp);
676           tmp = tree_cons (NULL_TREE, ptr_type_node, tmp);
677           tmp = build_function_type (void_type_node, tmp);
678           fn = push_throw_library_fn (fn, tmp);
679         }
680
681       /* [except.throw]
682
683          A throw-expression initializes a temporary object, the type
684          of which is determined by removing any top-level
685          cv-qualifiers from the static type of the operand of throw
686          and adjusting the type from "array of T" or "function return
687          T" to "pointer to T" or "pointer to function returning T"
688          respectively.  */
689       temp_type = is_bitfield_expr_with_lowered_type (exp);
690       if (!temp_type)
691         temp_type = type_decays_to (TREE_TYPE (exp));
692
693       /* OK, this is kind of wacky.  The standard says that we call
694          terminate when the exception handling mechanism, after
695          completing evaluation of the expression to be thrown but
696          before the exception is caught (_except.throw_), calls a
697          user function that exits via an uncaught exception.
698
699          So we have to protect the actual initialization of the
700          exception object with terminate(), but evaluate the
701          expression first.  Since there could be temps in the
702          expression, we need to handle that, too.  We also expand
703          the call to __cxa_allocate_exception first (which doesn't
704          matter, since it can't throw).  */
705
706       /* Allocate the space for the exception.  */
707       allocate_expr = do_allocate_exception (temp_type);
708       allocate_expr = get_target_expr (allocate_expr);
709       ptr = TARGET_EXPR_SLOT (allocate_expr);
710       object = build_nop (build_pointer_type (temp_type), ptr);
711       object = build_indirect_ref (object, NULL);
712
713       elided = (TREE_CODE (exp) == TARGET_EXPR);
714
715       /* And initialize the exception object.  */
716       if (CLASS_TYPE_P (temp_type))
717         {
718           int flags = LOOKUP_NORMAL | LOOKUP_ONLYCONVERTING;
719
720           /* Under C++0x [12.8/16 class.copy], a thrown lvalue is sometimes
721              treated as an rvalue for the purposes of overload resolution
722              to favor move constructors over copy constructors.  */
723           if (/* Must be a local, automatic variable.  */
724               TREE_CODE (exp) == VAR_DECL
725               && DECL_CONTEXT (exp) == current_function_decl
726               && ! TREE_STATIC (exp)
727               /* The variable must not have the `volatile' qualifier.  */
728               && !(cp_type_quals (TREE_TYPE (exp)) & TYPE_QUAL_VOLATILE))
729             flags = flags | LOOKUP_PREFER_RVALUE;
730
731           /* Call the copy constructor.  */
732           exp = (build_special_member_call
733                  (object, complete_ctor_identifier,
734                   build_tree_list (NULL_TREE, exp),
735                   TREE_TYPE (object),
736                   flags));
737           if (exp == error_mark_node)
738             {
739               error ("  in thrown expression");
740               return error_mark_node;
741             }
742         }
743       else
744         exp = build2 (INIT_EXPR, temp_type, object,
745                       decay_conversion (exp));
746
747       /* Pre-evaluate the thrown expression first, since if we allocated
748          the space first we would have to deal with cleaning it up if
749          evaluating this expression throws.
750
751          The case where EXP the initializer is a cast or a function
752          returning a class is a bit of a grey area in the standard; it's
753          unclear whether or not it should be allowed to throw.  We used to
754          say no, as that allowed us to optimize this case without worrying
755          about deallocating the exception object if it does.  But that
756          conflicted with expectations (PR 13944) and the EDG compiler; now
757          we wrap the initialization in a TRY_CATCH_EXPR to call
758          do_free_exception rather than in a MUST_NOT_THROW_EXPR, for this
759          case only.
760
761          BUT: Issue 475 may do away with this inconsistency by removing the
762          terminate() in this situation.
763
764          Note that we don't check the return value from stabilize_init
765          because it will only return false in cases where elided is true,
766          and therefore we don't need to work around the failure to
767          preevaluate.  */
768       temp_expr = NULL_TREE;
769       stabilize_init (exp, &temp_expr);
770
771       /* Wrap the initialization in a CLEANUP_POINT_EXPR so that cleanups
772          for temporaries within the initialization are run before the one
773          for the exception object, preserving LIFO order.  */
774       exp = build1 (CLEANUP_POINT_EXPR, void_type_node, exp);
775
776       if (elided)
777         exp = build2 (TRY_CATCH_EXPR, void_type_node, exp,
778                       do_free_exception (ptr));
779       else
780         exp = build1 (MUST_NOT_THROW_EXPR, void_type_node, exp);
781
782       /* Prepend the allocation.  */
783       exp = build2 (COMPOUND_EXPR, TREE_TYPE (exp), allocate_expr, exp);
784       if (temp_expr)
785         {
786           /* Prepend the calculation of the throw expression.  Also, force
787              any cleanups from the expression to be evaluated here so that
788              we don't have to do them during unwinding.  But first wrap
789              them in MUST_NOT_THROW_EXPR, since they are run after the
790              exception object is initialized.  */
791           cp_walk_tree_without_duplicates (&temp_expr, wrap_cleanups_r, 0);
792           exp = build2 (COMPOUND_EXPR, TREE_TYPE (exp), temp_expr, exp);
793           exp = build1 (CLEANUP_POINT_EXPR, TREE_TYPE (exp), exp);
794         }
795
796       throw_type = build_eh_type_type (prepare_eh_type (TREE_TYPE (object)));
797
798       if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (object)))
799         {
800           cleanup = lookup_fnfields (TYPE_BINFO (TREE_TYPE (object)),
801                                      complete_dtor_identifier, 0);
802           cleanup = BASELINK_FUNCTIONS (cleanup);
803           mark_used (cleanup);
804           cxx_mark_addressable (cleanup);
805           /* Pretend it's a normal function.  */
806           cleanup = build1 (ADDR_EXPR, cleanup_type, cleanup);
807         }
808       else
809         cleanup = build_int_cst (cleanup_type, 0);
810
811       tmp = tree_cons (NULL_TREE, cleanup, NULL_TREE);
812       tmp = tree_cons (NULL_TREE, throw_type, tmp);
813       tmp = tree_cons (NULL_TREE, ptr, tmp);
814       /* ??? Indicate that this function call throws throw_type.  */
815       tmp = build_function_call (fn, tmp);
816
817       /* Tack on the initialization stuff.  */
818       exp = build2 (COMPOUND_EXPR, TREE_TYPE (tmp), exp, tmp);
819     }
820   else
821     {
822       /* Rethrow current exception.  */
823
824       tree fn = get_identifier ("__cxa_rethrow");
825       if (!get_global_value_if_present (fn, &fn))
826         {
827           /* Declare void __cxa_rethrow (void).  */
828           fn = push_throw_library_fn
829             (fn, build_function_type (void_type_node, void_list_node));
830         }
831
832       /* ??? Indicate that this function call allows exceptions of the type
833          of the enclosing catch block (if known).  */
834       exp = build_function_call (fn, NULL_TREE);
835     }
836
837   exp = build1 (THROW_EXPR, void_type_node, exp);
838
839   return exp;
840 }
841
842 /* Make sure TYPE is complete, pointer to complete, reference to
843    complete, or pointer to cv void. Issue diagnostic on failure.
844    Return the zero on failure and nonzero on success. FROM can be
845    the expr or decl from whence TYPE came, if available.  */
846
847 static int
848 complete_ptr_ref_or_void_ptr_p (tree type, tree from)
849 {
850   int is_ptr;
851
852   /* Check complete.  */
853   type = complete_type_or_else (type, from);
854   if (!type)
855     return 0;
856
857   /* Or a pointer or ref to one, or cv void *.  */
858   is_ptr = TREE_CODE (type) == POINTER_TYPE;
859   if (is_ptr || TREE_CODE (type) == REFERENCE_TYPE)
860     {
861       tree core = TREE_TYPE (type);
862
863       if (is_ptr && VOID_TYPE_P (core))
864         /* OK */;
865       else if (!complete_type_or_else (core, from))
866         return 0;
867     }
868   return 1;
869 }
870
871 /* Return truth-value if EXPRESSION is admissible in throw-expression,
872    i.e. if it is not of incomplete type or a pointer/reference to such
873    a type or of an abstract class type.  */
874
875 static bool
876 is_admissible_throw_operand (tree expr)
877 {
878   tree type = TREE_TYPE (expr);
879
880   /* 15.1/4 [...] The type of the throw-expression shall not be an
881             incomplete type, or a pointer or a reference to an incomplete
882             type, other than void*, const void*, volatile void*, or
883             const volatile void*.  Except for these restriction and the
884             restrictions on type matching mentioned in 15.3, the operand
885             of throw is treated exactly as a function argument in a call
886             (5.2.2) or the operand of a return statement.  */
887   if (!complete_ptr_ref_or_void_ptr_p (type, expr))
888     return false;
889
890   /* 10.4/3 An abstract class shall not be used as a parameter type,
891             as a function return type or as type of an explicit
892             conversion.  */
893   else if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
894     {
895       error ("expression %qE of abstract class type %qT cannot "
896              "be used in throw-expression", expr, type);
897       return false;
898     }
899
900   return true;
901 }
902
903 /* Returns nonzero if FN is a declaration of a standard C library
904    function which is known not to throw.
905
906    [lib.res.on.exception.handling]: None of the functions from the
907    Standard C library shall report an error by throwing an
908    exception, unless it calls a program-supplied function that
909    throws an exception.  */
910
911 #include "cfns.h"
912
913 int
914 nothrow_libfn_p (const_tree fn)
915 {
916   tree id;
917
918   if (TREE_PUBLIC (fn)
919       && DECL_EXTERNAL (fn)
920       && DECL_NAMESPACE_SCOPE_P (fn)
921       && DECL_EXTERN_C_P (fn))
922     /* OK */;
923   else
924     /* Can't be a C library function.  */
925     return 0;
926
927   /* Being a C library function, DECL_ASSEMBLER_NAME == DECL_NAME
928      unless the system headers are playing rename tricks, and if
929      they are, we don't want to be confused by them.  */
930   id = DECL_NAME (fn);
931   return !!libc_name_p (IDENTIFIER_POINTER (id), IDENTIFIER_LENGTH (id));
932 }
933
934 /* Returns nonzero if an exception of type FROM will be caught by a
935    handler for type TO, as per [except.handle].  */
936
937 static int
938 can_convert_eh (tree to, tree from)
939 {
940   to = non_reference (to);
941   from = non_reference (from);
942
943   if (TREE_CODE (to) == POINTER_TYPE && TREE_CODE (from) == POINTER_TYPE)
944     {
945       to = TREE_TYPE (to);
946       from = TREE_TYPE (from);
947
948       if (! at_least_as_qualified_p (to, from))
949         return 0;
950
951       if (TREE_CODE (to) == VOID_TYPE)
952         return 1;
953
954       /* Else fall through.  */
955     }
956
957   if (CLASS_TYPE_P (to) && CLASS_TYPE_P (from)
958       && PUBLICLY_UNIQUELY_DERIVED_P (to, from))
959     return 1;
960
961   return 0;
962 }
963
964 /* Check whether any of the handlers in I are shadowed by another handler
965    accepting TYPE.  Note that the shadowing may not be complete; even if
966    an exception of type B would be caught by a handler for A, there could
967    be a derived class C for which A is an ambiguous base but B is not, so
968    the handler for B would catch an exception of type C.  */
969
970 static void
971 check_handlers_1 (tree master, tree_stmt_iterator i)
972 {
973   tree type = TREE_TYPE (master);
974
975   for (; !tsi_end_p (i); tsi_next (&i))
976     {
977       tree handler = tsi_stmt (i);
978       if (TREE_TYPE (handler) && can_convert_eh (type, TREE_TYPE (handler)))
979         {
980           warning (0, "%Hexception of type %qT will be caught",
981                    EXPR_LOCUS (handler), TREE_TYPE (handler));
982           warning (0, "%H   by earlier handler for %qT",
983                    EXPR_LOCUS (master), type);
984           break;
985         }
986     }
987 }
988
989 /* Given a STATEMENT_LIST of HANDLERs, make sure that they're OK.  */
990
991 void
992 check_handlers (tree handlers)
993 {
994   tree_stmt_iterator i;
995
996   /* If we don't have a STATEMENT_LIST, then we've just got one
997      handler, and thus nothing to warn about.  */
998   if (TREE_CODE (handlers) != STATEMENT_LIST)
999     return;
1000
1001   i = tsi_start (handlers);
1002   if (!tsi_end_p (i))
1003     while (1)
1004       {
1005         tree handler = tsi_stmt (i);
1006         tsi_next (&i);
1007
1008         /* No more handlers; nothing to shadow.  */
1009         if (tsi_end_p (i))
1010           break;
1011         if (TREE_TYPE (handler) == NULL_TREE)
1012           pedwarn ("%H%<...%> handler must be the last handler for"
1013                    " its try block", EXPR_LOCUS (handler));
1014         else
1015           check_handlers_1 (handler, i);
1016       }
1017 }