OSDN Git Service

7e8b785b3eb7b3d903bb107a8256d9115ea1a6c0
[pf3gnuchains/gcc-fork.git] / gcc / cp / typeck.c
1 /* Build expressions with type checking for C++ compiler.
2    Copyright (C) 1987, 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4    Hacked by Michael Tiemann (tiemann@cygnus.com)
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.  */
22
23
24 /* This file is part of the C++ front end.
25    It contains routines to build C++ expressions given their operands,
26    including computing the types of the result, C and C++ specific error
27    checks, and some optimization.  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "rtl.h"
35 #include "expr.h"
36 #include "cp-tree.h"
37 #include "tm_p.h"
38 #include "flags.h"
39 #include "output.h"
40 #include "toplev.h"
41 #include "diagnostic.h"
42 #include "intl.h"
43 #include "target.h"
44 #include "convert.h"
45 #include "c-common.h"
46 #include "params.h"
47
48 static tree pfn_from_ptrmemfunc (tree);
49 static tree convert_for_assignment (tree, tree, const char *, tree, int);
50 static tree cp_pointer_int_sum (enum tree_code, tree, tree);
51 static tree rationalize_conditional_expr (enum tree_code, tree);
52 static int comp_ptr_ttypes_real (tree, tree, int);
53 static bool comp_except_types (tree, tree, bool);
54 static bool comp_array_types (tree, tree, bool);
55 static tree common_base_type (tree, tree);
56 static tree pointer_diff (tree, tree, tree);
57 static tree get_delta_difference (tree, tree, bool, bool);
58 static void casts_away_constness_r (tree *, tree *);
59 static bool casts_away_constness (tree, tree);
60 static void maybe_warn_about_returning_address_of_local (tree);
61 static tree lookup_destructor (tree, tree, tree);
62 static tree convert_arguments (tree, tree, tree, int);
63
64 /* Do `exp = require_complete_type (exp);' to make sure exp
65    does not have an incomplete type.  (That includes void types.)
66    Returns the error_mark_node if the VALUE does not have
67    complete type when this function returns.  */
68
69 tree
70 require_complete_type (tree value)
71 {
72   tree type;
73
74   if (processing_template_decl || value == error_mark_node)
75     return value;
76
77   if (TREE_CODE (value) == OVERLOAD)
78     type = unknown_type_node;
79   else
80     type = TREE_TYPE (value);
81
82   if (type == error_mark_node)
83     return error_mark_node;
84
85   /* First, detect a valid value with a complete type.  */
86   if (COMPLETE_TYPE_P (type))
87     return value;
88
89   if (complete_type_or_else (type, value))
90     return value;
91   else
92     return error_mark_node;
93 }
94
95 /* Try to complete TYPE, if it is incomplete.  For example, if TYPE is
96    a template instantiation, do the instantiation.  Returns TYPE,
97    whether or not it could be completed, unless something goes
98    horribly wrong, in which case the error_mark_node is returned.  */
99
100 tree
101 complete_type (tree type)
102 {
103   if (type == NULL_TREE)
104     /* Rather than crash, we return something sure to cause an error
105        at some point.  */
106     return error_mark_node;
107
108   if (type == error_mark_node || COMPLETE_TYPE_P (type))
109     ;
110   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
111     {
112       tree t = complete_type (TREE_TYPE (type));
113       unsigned int needs_constructing, has_nontrivial_dtor;
114       if (COMPLETE_TYPE_P (t) && !dependent_type_p (type))
115         layout_type (type);
116       needs_constructing
117         = TYPE_NEEDS_CONSTRUCTING (TYPE_MAIN_VARIANT (t));
118       has_nontrivial_dtor
119         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TYPE_MAIN_VARIANT (t));
120       for (t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
121         {
122           TYPE_NEEDS_CONSTRUCTING (t) = needs_constructing;
123           TYPE_HAS_NONTRIVIAL_DESTRUCTOR (t) = has_nontrivial_dtor;
124         }
125     }
126   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INSTANTIATION (type))
127     instantiate_class_template (TYPE_MAIN_VARIANT (type));
128
129   return type;
130 }
131
132 /* Like complete_type, but issue an error if the TYPE cannot be completed.
133    VALUE is used for informative diagnostics.
134    Returns NULL_TREE if the type cannot be made complete.  */
135
136 tree
137 complete_type_or_else (tree type, tree value)
138 {
139   type = complete_type (type);
140   if (type == error_mark_node)
141     /* We already issued an error.  */
142     return NULL_TREE;
143   else if (!COMPLETE_TYPE_P (type))
144     {
145       cxx_incomplete_type_diagnostic (value, type, 0);
146       return NULL_TREE;
147     }
148   else
149     return type;
150 }
151
152 /* Return truthvalue of whether type of EXP is instantiated.  */
153
154 int
155 type_unknown_p (tree exp)
156 {
157   return (TREE_CODE (exp) == TREE_LIST
158           || TREE_TYPE (exp) == unknown_type_node);
159 }
160
161 \f
162 /* Return the common type of two parameter lists.
163    We assume that comptypes has already been done and returned 1;
164    if that isn't so, this may crash.
165
166    As an optimization, free the space we allocate if the parameter
167    lists are already common.  */
168
169 static tree
170 commonparms (tree p1, tree p2)
171 {
172   tree oldargs = p1, newargs, n;
173   int i, len;
174   int any_change = 0;
175
176   len = list_length (p1);
177   newargs = tree_last (p1);
178
179   if (newargs == void_list_node)
180     i = 1;
181   else
182     {
183       i = 0;
184       newargs = 0;
185     }
186
187   for (; i < len; i++)
188     newargs = tree_cons (NULL_TREE, NULL_TREE, newargs);
189
190   n = newargs;
191
192   for (i = 0; p1;
193        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2), n = TREE_CHAIN (n), i++)
194     {
195       if (TREE_PURPOSE (p1) && !TREE_PURPOSE (p2))
196         {
197           TREE_PURPOSE (n) = TREE_PURPOSE (p1);
198           any_change = 1;
199         }
200       else if (! TREE_PURPOSE (p1))
201         {
202           if (TREE_PURPOSE (p2))
203             {
204               TREE_PURPOSE (n) = TREE_PURPOSE (p2);
205               any_change = 1;
206             }
207         }
208       else
209         {
210           if (1 != simple_cst_equal (TREE_PURPOSE (p1), TREE_PURPOSE (p2)))
211             any_change = 1;
212           TREE_PURPOSE (n) = TREE_PURPOSE (p2);
213         }
214       if (TREE_VALUE (p1) != TREE_VALUE (p2))
215         {
216           any_change = 1;
217           TREE_VALUE (n) = merge_types (TREE_VALUE (p1), TREE_VALUE (p2));
218         }
219       else
220         TREE_VALUE (n) = TREE_VALUE (p1);
221     }
222   if (! any_change)
223     return oldargs;
224
225   return newargs;
226 }
227
228 /* Given a type, perhaps copied for a typedef,
229    find the "original" version of it.  */
230 static tree
231 original_type (tree t)
232 {
233   int quals = cp_type_quals (t);
234   while (t != error_mark_node
235          && TYPE_NAME (t) != NULL_TREE)
236     {
237       tree x = TYPE_NAME (t);
238       if (TREE_CODE (x) != TYPE_DECL)
239         break;
240       x = DECL_ORIGINAL_TYPE (x);
241       if (x == NULL_TREE)
242         break;
243       t = x;
244     }
245   return cp_build_qualified_type (t, quals);
246 }
247
248 /* T1 and T2 are arithmetic or enumeration types.  Return the type
249    that will result from the "usual arithmetic conversions" on T1 and
250    T2 as described in [expr].  */
251
252 tree
253 type_after_usual_arithmetic_conversions (tree t1, tree t2)
254 {
255   enum tree_code code1 = TREE_CODE (t1);
256   enum tree_code code2 = TREE_CODE (t2);
257   tree attributes;
258
259   /* FIXME: Attributes.  */
260   gcc_assert (ARITHMETIC_TYPE_P (t1)
261               || TREE_CODE (t1) == COMPLEX_TYPE
262               || TREE_CODE (t1) == VECTOR_TYPE
263               || TREE_CODE (t1) == ENUMERAL_TYPE);
264   gcc_assert (ARITHMETIC_TYPE_P (t2)
265               || TREE_CODE (t2) == COMPLEX_TYPE
266               || TREE_CODE (t2) == VECTOR_TYPE
267               || TREE_CODE (t2) == ENUMERAL_TYPE);
268
269   /* In what follows, we slightly generalize the rules given in [expr] so
270      as to deal with `long long' and `complex'.  First, merge the
271      attributes.  */
272   attributes = (*targetm.merge_type_attributes) (t1, t2);
273
274   /* If one type is complex, form the common type of the non-complex
275      components, then make that complex.  Use T1 or T2 if it is the
276      required type.  */
277   if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE)
278     {
279       tree subtype1 = code1 == COMPLEX_TYPE ? TREE_TYPE (t1) : t1;
280       tree subtype2 = code2 == COMPLEX_TYPE ? TREE_TYPE (t2) : t2;
281       tree subtype
282         = type_after_usual_arithmetic_conversions (subtype1, subtype2);
283
284       if (code1 == COMPLEX_TYPE && TREE_TYPE (t1) == subtype)
285         return build_type_attribute_variant (t1, attributes);
286       else if (code2 == COMPLEX_TYPE && TREE_TYPE (t2) == subtype)
287         return build_type_attribute_variant (t2, attributes);
288       else
289         return build_type_attribute_variant (build_complex_type (subtype),
290                                              attributes);
291     }
292
293   if (code1 == VECTOR_TYPE)
294     {
295       /* When we get here we should have two vectors of the same size.
296          Just prefer the unsigned one if present.  */
297       if (TYPE_UNSIGNED (t1))
298         return build_type_attribute_variant (t1, attributes);
299       else
300         return build_type_attribute_variant (t2, attributes);
301     }
302
303   /* If only one is real, use it as the result.  */
304   if (code1 == REAL_TYPE && code2 != REAL_TYPE)
305     return build_type_attribute_variant (t1, attributes);
306   if (code2 == REAL_TYPE && code1 != REAL_TYPE)
307     return build_type_attribute_variant (t2, attributes);
308
309   /* Perform the integral promotions.  */
310   if (code1 != REAL_TYPE)
311     {
312       t1 = type_promotes_to (t1);
313       t2 = type_promotes_to (t2);
314     }
315
316   /* Both real or both integers; use the one with greater precision.  */
317   if (TYPE_PRECISION (t1) > TYPE_PRECISION (t2))
318     return build_type_attribute_variant (t1, attributes);
319   else if (TYPE_PRECISION (t2) > TYPE_PRECISION (t1))
320     return build_type_attribute_variant (t2, attributes);
321
322   /* The types are the same; no need to do anything fancy.  */
323   if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
324     return build_type_attribute_variant (t1, attributes);
325
326   if (code1 != REAL_TYPE)
327     {
328       /* If one is unsigned long long, then convert the other to unsigned
329          long long.  */
330       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_unsigned_type_node)
331           || same_type_p (TYPE_MAIN_VARIANT (t2), long_long_unsigned_type_node))
332         return build_type_attribute_variant (long_long_unsigned_type_node,
333                                              attributes);
334       /* If one is a long long, and the other is an unsigned long, and
335          long long can represent all the values of an unsigned long, then
336          convert to a long long.  Otherwise, convert to an unsigned long
337          long.  Otherwise, if either operand is long long, convert the
338          other to long long.
339
340          Since we're here, we know the TYPE_PRECISION is the same;
341          therefore converting to long long cannot represent all the values
342          of an unsigned long, so we choose unsigned long long in that
343          case.  */
344       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_long_integer_type_node)
345           || same_type_p (TYPE_MAIN_VARIANT (t2), long_long_integer_type_node))
346         {
347           tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
348                     ? long_long_unsigned_type_node
349                     : long_long_integer_type_node);
350           return build_type_attribute_variant (t, attributes);
351         }
352
353       /* Go through the same procedure, but for longs.  */
354       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_unsigned_type_node)
355           || same_type_p (TYPE_MAIN_VARIANT (t2), long_unsigned_type_node))
356         return build_type_attribute_variant (long_unsigned_type_node,
357                                              attributes);
358       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_integer_type_node)
359           || same_type_p (TYPE_MAIN_VARIANT (t2), long_integer_type_node))
360         {
361           tree t = ((TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2))
362                     ? long_unsigned_type_node : long_integer_type_node);
363           return build_type_attribute_variant (t, attributes);
364         }
365       /* Otherwise prefer the unsigned one.  */
366       if (TYPE_UNSIGNED (t1))
367         return build_type_attribute_variant (t1, attributes);
368       else
369         return build_type_attribute_variant (t2, attributes);
370     }
371   else
372     {
373       if (same_type_p (TYPE_MAIN_VARIANT (t1), long_double_type_node)
374           || same_type_p (TYPE_MAIN_VARIANT (t2), long_double_type_node))
375         return build_type_attribute_variant (long_double_type_node,
376                                              attributes);
377       if (same_type_p (TYPE_MAIN_VARIANT (t1), double_type_node)
378           || same_type_p (TYPE_MAIN_VARIANT (t2), double_type_node))
379         return build_type_attribute_variant (double_type_node,
380                                              attributes);
381       if (same_type_p (TYPE_MAIN_VARIANT (t1), float_type_node)
382           || same_type_p (TYPE_MAIN_VARIANT (t2), float_type_node))
383         return build_type_attribute_variant (float_type_node,
384                                              attributes);
385
386       /* Two floating-point types whose TYPE_MAIN_VARIANTs are none of
387          the standard C++ floating-point types.  Logic earlier in this
388          function has already eliminated the possibility that
389          TYPE_PRECISION (t2) != TYPE_PRECISION (t1), so there's no
390          compelling reason to choose one or the other.  */
391       return build_type_attribute_variant (t1, attributes);
392     }
393 }
394
395 /* Subroutine of composite_pointer_type to implement the recursive
396    case.  See that function for documentation fo the parameters.  */
397
398 static tree
399 composite_pointer_type_r (tree t1, tree t2, const char* location)
400 {
401   tree pointee1;
402   tree pointee2;
403   tree result_type;
404   tree attributes;
405
406   /* Determine the types pointed to by T1 and T2.  */
407   if (TREE_CODE (t1) == POINTER_TYPE)
408     {
409       pointee1 = TREE_TYPE (t1);
410       pointee2 = TREE_TYPE (t2);
411     }
412   else
413     {
414       pointee1 = TYPE_PTRMEM_POINTED_TO_TYPE (t1);
415       pointee2 = TYPE_PTRMEM_POINTED_TO_TYPE (t2);
416     }
417
418   /* [expr.rel]
419
420      Otherwise, the composite pointer type is a pointer type
421      similar (_conv.qual_) to the type of one of the operands,
422      with a cv-qualification signature (_conv.qual_) that is the
423      union of the cv-qualification signatures of the operand
424      types.  */
425   if (same_type_ignoring_top_level_qualifiers_p (pointee1, pointee2))
426     result_type = pointee1;
427   else if ((TREE_CODE (pointee1) == POINTER_TYPE
428             && TREE_CODE (pointee2) == POINTER_TYPE)
429            || (TYPE_PTR_TO_MEMBER_P (pointee1)
430                && TYPE_PTR_TO_MEMBER_P (pointee2)))
431     result_type = composite_pointer_type_r (pointee1, pointee2, location);
432   else
433     {
434       pedwarn ("%s between distinct pointer types %qT and %qT "
435                "lacks a cast",
436                location, t1, t2);
437       result_type = void_type_node;
438     }
439   result_type = cp_build_qualified_type (result_type,
440                                          (cp_type_quals (pointee1)
441                                           | cp_type_quals (pointee2)));
442   /* If the original types were pointers to members, so is the
443      result.  */
444   if (TYPE_PTR_TO_MEMBER_P (t1))
445     {
446       if (!same_type_p (TYPE_PTRMEM_CLASS_TYPE (t1),
447                         TYPE_PTRMEM_CLASS_TYPE (t2)))
448         pedwarn ("%s between distinct pointer types %qT and %qT "
449                  "lacks a cast",
450                  location, t1, t2);
451       result_type = build_ptrmem_type (TYPE_PTRMEM_CLASS_TYPE (t1),
452                                        result_type);
453     }
454   else
455     result_type = build_pointer_type (result_type);
456
457   /* Merge the attributes.  */
458   attributes = (*targetm.merge_type_attributes) (t1, t2);
459   return build_type_attribute_variant (result_type, attributes);
460 }
461
462 /* Return the composite pointer type (see [expr.rel]) for T1 and T2.
463    ARG1 and ARG2 are the values with those types.  The LOCATION is a
464    string describing the current location, in case an error occurs.
465
466    This routine also implements the computation of a common type for
467    pointers-to-members as per [expr.eq].  */
468
469 tree
470 composite_pointer_type (tree t1, tree t2, tree arg1, tree arg2,
471                         const char* location)
472 {
473   tree class1;
474   tree class2;
475
476   /* [expr.rel]
477
478      If one operand is a null pointer constant, the composite pointer
479      type is the type of the other operand.  */
480   if (null_ptr_cst_p (arg1))
481     return t2;
482   if (null_ptr_cst_p (arg2))
483     return t1;
484
485   /* We have:
486
487        [expr.rel]
488
489        If one of the operands has type "pointer to cv1 void*", then
490        the other has type "pointer to cv2T", and the composite pointer
491        type is "pointer to cv12 void", where cv12 is the union of cv1
492        and cv2.
493
494     If either type is a pointer to void, make sure it is T1.  */
495   if (TREE_CODE (t2) == POINTER_TYPE && VOID_TYPE_P (TREE_TYPE (t2)))
496     {
497       tree t;
498       t = t1;
499       t1 = t2;
500       t2 = t;
501     }
502
503   /* Now, if T1 is a pointer to void, merge the qualifiers.  */
504   if (TREE_CODE (t1) == POINTER_TYPE && VOID_TYPE_P (TREE_TYPE (t1)))
505     {
506       tree attributes;
507       tree result_type;
508
509       if (pedantic && TYPE_PTRFN_P (t2))
510         pedwarn ("ISO C++ forbids %s between pointer of type %<void *%> "
511                  "and pointer-to-function", location);
512       result_type
513         = cp_build_qualified_type (void_type_node,
514                                    (cp_type_quals (TREE_TYPE (t1))
515                                     | cp_type_quals (TREE_TYPE (t2))));
516       result_type = build_pointer_type (result_type);
517       /* Merge the attributes.  */
518       attributes = (*targetm.merge_type_attributes) (t1, t2);
519       return build_type_attribute_variant (result_type, attributes);
520     }
521
522   if (c_dialect_objc () && TREE_CODE (t1) == POINTER_TYPE
523       && TREE_CODE (t2) == POINTER_TYPE)
524     {
525       if (objc_compare_types (t1, t2, -3, NULL_TREE))
526         return t1;
527     }
528
529   /* [expr.eq] permits the application of a pointer conversion to
530      bring the pointers to a common type.  */
531   if (TREE_CODE (t1) == POINTER_TYPE && TREE_CODE (t2) == POINTER_TYPE
532       && CLASS_TYPE_P (TREE_TYPE (t1))
533       && CLASS_TYPE_P (TREE_TYPE (t2))
534       && !same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (t1),
535                                                      TREE_TYPE (t2)))
536     {
537       class1 = TREE_TYPE (t1);
538       class2 = TREE_TYPE (t2);
539
540       if (DERIVED_FROM_P (class1, class2))
541         t2 = (build_pointer_type
542               (cp_build_qualified_type (class1, TYPE_QUALS (class2))));
543       else if (DERIVED_FROM_P (class2, class1))
544         t1 = (build_pointer_type
545               (cp_build_qualified_type (class2, TYPE_QUALS (class1))));
546       else
547         {
548           error ("%s between distinct pointer types %qT and %qT "
549                  "lacks a cast", location, t1, t2);
550           return error_mark_node;
551         }
552     }
553   /* [expr.eq] permits the application of a pointer-to-member
554      conversion to change the class type of one of the types.  */
555   else if (TYPE_PTR_TO_MEMBER_P (t1)
556            && !same_type_p (TYPE_PTRMEM_CLASS_TYPE (t1),
557                             TYPE_PTRMEM_CLASS_TYPE (t2)))
558     {
559       class1 = TYPE_PTRMEM_CLASS_TYPE (t1);
560       class2 = TYPE_PTRMEM_CLASS_TYPE (t2);
561
562       if (DERIVED_FROM_P (class1, class2))
563         t1 = build_ptrmem_type (class2, TYPE_PTRMEM_POINTED_TO_TYPE (t1));
564       else if (DERIVED_FROM_P (class2, class1))
565         t2 = build_ptrmem_type (class1, TYPE_PTRMEM_POINTED_TO_TYPE (t2));
566       else
567         {
568           error ("%s between distinct pointer-to-member types %qT and %qT "
569                  "lacks a cast", location, t1, t2);
570           return error_mark_node;
571         }
572     }
573
574   return composite_pointer_type_r (t1, t2, location);
575 }
576
577 /* Return the merged type of two types.
578    We assume that comptypes has already been done and returned 1;
579    if that isn't so, this may crash.
580
581    This just combines attributes and default arguments; any other
582    differences would cause the two types to compare unalike.  */
583
584 tree
585 merge_types (tree t1, tree t2)
586 {
587   enum tree_code code1;
588   enum tree_code code2;
589   tree attributes;
590
591   /* Save time if the two types are the same.  */
592   if (t1 == t2)
593     return t1;
594   if (original_type (t1) == original_type (t2))
595     return t1;
596
597   /* If one type is nonsense, use the other.  */
598   if (t1 == error_mark_node)
599     return t2;
600   if (t2 == error_mark_node)
601     return t1;
602
603   /* Merge the attributes.  */
604   attributes = (*targetm.merge_type_attributes) (t1, t2);
605
606   if (TYPE_PTRMEMFUNC_P (t1))
607     t1 = TYPE_PTRMEMFUNC_FN_TYPE (t1);
608   if (TYPE_PTRMEMFUNC_P (t2))
609     t2 = TYPE_PTRMEMFUNC_FN_TYPE (t2);
610
611   code1 = TREE_CODE (t1);
612   code2 = TREE_CODE (t2);
613
614   switch (code1)
615     {
616     case POINTER_TYPE:
617     case REFERENCE_TYPE:
618       /* For two pointers, do this recursively on the target type.  */
619       {
620         tree target = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
621         int quals = cp_type_quals (t1);
622
623         if (code1 == POINTER_TYPE)
624           t1 = build_pointer_type (target);
625         else
626           t1 = build_reference_type (target);
627         t1 = build_type_attribute_variant (t1, attributes);
628         t1 = cp_build_qualified_type (t1, quals);
629
630         if (TREE_CODE (target) == METHOD_TYPE)
631           t1 = build_ptrmemfunc_type (t1);
632
633         return t1;
634       }
635
636     case OFFSET_TYPE:
637       {
638         int quals;
639         tree pointee;
640         quals = cp_type_quals (t1);
641         pointee = merge_types (TYPE_PTRMEM_POINTED_TO_TYPE (t1),
642                                TYPE_PTRMEM_POINTED_TO_TYPE (t2));
643         t1 = build_ptrmem_type (TYPE_PTRMEM_CLASS_TYPE (t1),
644                                 pointee);
645         t1 = cp_build_qualified_type (t1, quals);
646         break;
647       }
648
649     case ARRAY_TYPE:
650       {
651         tree elt = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
652         /* Save space: see if the result is identical to one of the args.  */
653         if (elt == TREE_TYPE (t1) && TYPE_DOMAIN (t1))
654           return build_type_attribute_variant (t1, attributes);
655         if (elt == TREE_TYPE (t2) && TYPE_DOMAIN (t2))
656           return build_type_attribute_variant (t2, attributes);
657         /* Merge the element types, and have a size if either arg has one.  */
658         t1 = build_cplus_array_type
659           (elt, TYPE_DOMAIN (TYPE_DOMAIN (t1) ? t1 : t2));
660         break;
661       }
662
663     case FUNCTION_TYPE:
664       /* Function types: prefer the one that specified arg types.
665          If both do, merge the arg types.  Also merge the return types.  */
666       {
667         tree valtype = merge_types (TREE_TYPE (t1), TREE_TYPE (t2));
668         tree p1 = TYPE_ARG_TYPES (t1);
669         tree p2 = TYPE_ARG_TYPES (t2);
670         tree rval, raises;
671
672         /* Save space: see if the result is identical to one of the args.  */
673         if (valtype == TREE_TYPE (t1) && ! p2)
674           return cp_build_type_attribute_variant (t1, attributes);
675         if (valtype == TREE_TYPE (t2) && ! p1)
676           return cp_build_type_attribute_variant (t2, attributes);
677
678         /* Simple way if one arg fails to specify argument types.  */
679         if (p1 == NULL_TREE || TREE_VALUE (p1) == void_type_node)
680           {
681             rval = build_function_type (valtype, p2);
682             if ((raises = TYPE_RAISES_EXCEPTIONS (t2)))
683               rval = build_exception_variant (rval, raises);
684             return cp_build_type_attribute_variant (rval, attributes);
685           }
686         raises = TYPE_RAISES_EXCEPTIONS (t1);
687         if (p2 == NULL_TREE || TREE_VALUE (p2) == void_type_node)
688           {
689             rval = build_function_type (valtype, p1);
690             if (raises)
691               rval = build_exception_variant (rval, raises);
692             return cp_build_type_attribute_variant (rval, attributes);
693           }
694
695         rval = build_function_type (valtype, commonparms (p1, p2));
696         t1 = build_exception_variant (rval, raises);
697         break;
698       }
699
700     case METHOD_TYPE:
701       {
702         /* Get this value the long way, since TYPE_METHOD_BASETYPE
703            is just the main variant of this.  */
704         tree basetype = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (t2)));
705         tree raises = TYPE_RAISES_EXCEPTIONS (t1);
706         tree t3;
707
708         /* If this was a member function type, get back to the
709            original type of type member function (i.e., without
710            the class instance variable up front.  */
711         t1 = build_function_type (TREE_TYPE (t1),
712                                   TREE_CHAIN (TYPE_ARG_TYPES (t1)));
713         t2 = build_function_type (TREE_TYPE (t2),
714                                   TREE_CHAIN (TYPE_ARG_TYPES (t2)));
715         t3 = merge_types (t1, t2);
716         t3 = build_method_type_directly (basetype, TREE_TYPE (t3),
717                                          TYPE_ARG_TYPES (t3));
718         t1 = build_exception_variant (t3, raises);
719         break;
720       }
721
722     case TYPENAME_TYPE:
723       /* There is no need to merge attributes into a TYPENAME_TYPE.
724          When the type is instantiated it will have whatever
725          attributes result from the instantiation.  */
726       return t1;
727
728     default:;
729     }
730
731   if (attribute_list_equal (TYPE_ATTRIBUTES (t1), attributes))
732     return t1;
733   else if (attribute_list_equal (TYPE_ATTRIBUTES (t2), attributes))
734     return t2;
735   else
736     return cp_build_type_attribute_variant (t1, attributes);
737 }
738
739 /* Return the common type of two types.
740    We assume that comptypes has already been done and returned 1;
741    if that isn't so, this may crash.
742
743    This is the type for the result of most arithmetic operations
744    if the operands have the given two types.  */
745
746 tree
747 common_type (tree t1, tree t2)
748 {
749   enum tree_code code1;
750   enum tree_code code2;
751
752   /* If one type is nonsense, bail.  */
753   if (t1 == error_mark_node || t2 == error_mark_node)
754     return error_mark_node;
755
756   code1 = TREE_CODE (t1);
757   code2 = TREE_CODE (t2);
758
759   if ((ARITHMETIC_TYPE_P (t1) || code1 == ENUMERAL_TYPE
760        || code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE)
761       && (ARITHMETIC_TYPE_P (t2) || code2 == ENUMERAL_TYPE
762           || code2 == COMPLEX_TYPE || code2 == VECTOR_TYPE))
763     return type_after_usual_arithmetic_conversions (t1, t2);
764
765   else if ((TYPE_PTR_P (t1) && TYPE_PTR_P (t2))
766            || (TYPE_PTRMEM_P (t1) && TYPE_PTRMEM_P (t2))
767            || (TYPE_PTRMEMFUNC_P (t1) && TYPE_PTRMEMFUNC_P (t2)))
768     return composite_pointer_type (t1, t2, error_mark_node, error_mark_node,
769                                    "conversion");
770   else
771     gcc_unreachable ();
772 }
773 \f
774 /* Compare two exception specifier types for exactness or subsetness, if
775    allowed. Returns false for mismatch, true for match (same, or
776    derived and !exact).
777
778    [except.spec] "If a class X ... objects of class X or any class publicly
779    and unambiguously derived from X. Similarly, if a pointer type Y * ...
780    exceptions of type Y * or that are pointers to any type publicly and
781    unambiguously derived from Y. Otherwise a function only allows exceptions
782    that have the same type ..."
783    This does not mention cv qualifiers and is different to what throw
784    [except.throw] and catch [except.catch] will do. They will ignore the
785    top level cv qualifiers, and allow qualifiers in the pointer to class
786    example.
787
788    We implement the letter of the standard.  */
789
790 static bool
791 comp_except_types (tree a, tree b, bool exact)
792 {
793   if (same_type_p (a, b))
794     return true;
795   else if (!exact)
796     {
797       if (cp_type_quals (a) || cp_type_quals (b))
798         return false;
799
800       if (TREE_CODE (a) == POINTER_TYPE
801           && TREE_CODE (b) == POINTER_TYPE)
802         {
803           a = TREE_TYPE (a);
804           b = TREE_TYPE (b);
805           if (cp_type_quals (a) || cp_type_quals (b))
806             return false;
807         }
808
809       if (TREE_CODE (a) != RECORD_TYPE
810           || TREE_CODE (b) != RECORD_TYPE)
811         return false;
812
813       if (PUBLICLY_UNIQUELY_DERIVED_P (a, b))
814         return true;
815     }
816   return false;
817 }
818
819 /* Return true if TYPE1 and TYPE2 are equivalent exception specifiers.
820    If EXACT is false, T2 can be stricter than T1 (according to 15.4/7),
821    otherwise it must be exact. Exception lists are unordered, but
822    we've already filtered out duplicates. Most lists will be in order,
823    we should try to make use of that.  */
824
825 bool
826 comp_except_specs (tree t1, tree t2, bool exact)
827 {
828   tree probe;
829   tree base;
830   int  length = 0;
831
832   if (t1 == t2)
833     return true;
834
835   if (t1 == NULL_TREE)                     /* T1 is ...  */
836     return t2 == NULL_TREE || !exact;
837   if (!TREE_VALUE (t1))                    /* t1 is EMPTY */
838     return t2 != NULL_TREE && !TREE_VALUE (t2);
839   if (t2 == NULL_TREE)                     /* T2 is ...  */
840     return false;
841   if (TREE_VALUE (t1) && !TREE_VALUE (t2)) /* T2 is EMPTY, T1 is not */
842     return !exact;
843
844   /* Neither set is ... or EMPTY, make sure each part of T2 is in T1.
845      Count how many we find, to determine exactness. For exact matching and
846      ordered T1, T2, this is an O(n) operation, otherwise its worst case is
847      O(nm).  */
848   for (base = t1; t2 != NULL_TREE; t2 = TREE_CHAIN (t2))
849     {
850       for (probe = base; probe != NULL_TREE; probe = TREE_CHAIN (probe))
851         {
852           tree a = TREE_VALUE (probe);
853           tree b = TREE_VALUE (t2);
854
855           if (comp_except_types (a, b, exact))
856             {
857               if (probe == base && exact)
858                 base = TREE_CHAIN (probe);
859               length++;
860               break;
861             }
862         }
863       if (probe == NULL_TREE)
864         return false;
865     }
866   return !exact || base == NULL_TREE || length == list_length (t1);
867 }
868
869 /* Compare the array types T1 and T2.  ALLOW_REDECLARATION is true if
870    [] can match [size].  */
871
872 static bool
873 comp_array_types (tree t1, tree t2, bool allow_redeclaration)
874 {
875   tree d1;
876   tree d2;
877   tree max1, max2;
878
879   if (t1 == t2)
880     return true;
881
882   /* The type of the array elements must be the same.  */
883   if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
884     return false;
885
886   d1 = TYPE_DOMAIN (t1);
887   d2 = TYPE_DOMAIN (t2);
888
889   if (d1 == d2)
890     return true;
891
892   /* If one of the arrays is dimensionless, and the other has a
893      dimension, they are of different types.  However, it is valid to
894      write:
895
896        extern int a[];
897        int a[3];
898
899      by [basic.link]:
900
901        declarations for an array object can specify
902        array types that differ by the presence or absence of a major
903        array bound (_dcl.array_).  */
904   if (!d1 || !d2)
905     return allow_redeclaration;
906
907   /* Check that the dimensions are the same.  */
908
909   if (!cp_tree_equal (TYPE_MIN_VALUE (d1), TYPE_MIN_VALUE (d2)))
910     return false;
911   max1 = TYPE_MAX_VALUE (d1);
912   max2 = TYPE_MAX_VALUE (d2);
913   if (processing_template_decl && !abi_version_at_least (2)
914       && !value_dependent_expression_p (max1)
915       && !value_dependent_expression_p (max2))
916     {
917       /* With abi-1 we do not fold non-dependent array bounds, (and
918          consequently mangle them incorrectly).  We must therefore
919          fold them here, to verify the domains have the same
920          value.  */
921       max1 = fold (max1);
922       max2 = fold (max2);
923     }
924
925   if (!cp_tree_equal (max1, max2))
926     return false;
927
928   return true;
929 }
930
931 /* Subroutine in comptypes.  */
932
933 static bool
934 structural_comptypes (tree t1, tree t2, int strict)
935 {
936   if (t1 == t2)
937     return true;
938
939   /* Suppress errors caused by previously reported errors.  */
940   if (t1 == error_mark_node || t2 == error_mark_node)
941     return false;
942
943   gcc_assert (TYPE_P (t1) && TYPE_P (t2));
944
945   /* TYPENAME_TYPEs should be resolved if the qualifying scope is the
946      current instantiation.  */
947   if (TREE_CODE (t1) == TYPENAME_TYPE)
948     {
949       tree resolved = resolve_typename_type (t1, /*only_current_p=*/true);
950
951       if (resolved != error_mark_node)
952         t1 = resolved;
953     }
954
955   if (TREE_CODE (t2) == TYPENAME_TYPE)
956     {
957       tree resolved = resolve_typename_type (t2, /*only_current_p=*/true);
958
959       if (resolved != error_mark_node)
960         t2 = resolved;
961     }
962
963   if (TYPE_PTRMEMFUNC_P (t1))
964     t1 = TYPE_PTRMEMFUNC_FN_TYPE (t1);
965   if (TYPE_PTRMEMFUNC_P (t2))
966     t2 = TYPE_PTRMEMFUNC_FN_TYPE (t2);
967
968   /* Different classes of types can't be compatible.  */
969   if (TREE_CODE (t1) != TREE_CODE (t2))
970     return false;
971
972   /* Qualifiers must match.  For array types, we will check when we
973      recur on the array element types.  */
974   if (TREE_CODE (t1) != ARRAY_TYPE
975       && TYPE_QUALS (t1) != TYPE_QUALS (t2))
976     return false;
977   if (TYPE_FOR_JAVA (t1) != TYPE_FOR_JAVA (t2))
978     return false;
979
980   /* Allow for two different type nodes which have essentially the same
981      definition.  Note that we already checked for equality of the type
982      qualifiers (just above).  */
983
984   if (TREE_CODE (t1) != ARRAY_TYPE
985       && TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
986     return true;
987
988   /* Compare the types.  Break out if they could be the same.  */
989   switch (TREE_CODE (t1))
990     {
991     case TEMPLATE_TEMPLATE_PARM:
992     case BOUND_TEMPLATE_TEMPLATE_PARM:
993       if (TEMPLATE_TYPE_IDX (t1) != TEMPLATE_TYPE_IDX (t2)
994           || TEMPLATE_TYPE_LEVEL (t1) != TEMPLATE_TYPE_LEVEL (t2))
995         return false;
996       if (!comp_template_parms
997           (DECL_TEMPLATE_PARMS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t1)),
998            DECL_TEMPLATE_PARMS (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t2))))
999         return false;
1000       if (TREE_CODE (t1) == TEMPLATE_TEMPLATE_PARM)
1001         break;
1002       /* Don't check inheritance.  */
1003       strict = COMPARE_STRICT;
1004       /* Fall through.  */
1005
1006     case RECORD_TYPE:
1007     case UNION_TYPE:
1008       if (TYPE_TEMPLATE_INFO (t1) && TYPE_TEMPLATE_INFO (t2)
1009           && (TYPE_TI_TEMPLATE (t1) == TYPE_TI_TEMPLATE (t2)
1010               || TREE_CODE (t1) == BOUND_TEMPLATE_TEMPLATE_PARM)
1011           && comp_template_args (TYPE_TI_ARGS (t1), TYPE_TI_ARGS (t2)))
1012         break;
1013
1014       if ((strict & COMPARE_BASE) && DERIVED_FROM_P (t1, t2))
1015         break;
1016       else if ((strict & COMPARE_DERIVED) && DERIVED_FROM_P (t2, t1))
1017         break;
1018
1019       return false;
1020
1021     case OFFSET_TYPE:
1022       if (!comptypes (TYPE_OFFSET_BASETYPE (t1), TYPE_OFFSET_BASETYPE (t2),
1023                       strict & ~COMPARE_REDECLARATION))
1024         return false;
1025       if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1026         return false;
1027       break;
1028
1029     case POINTER_TYPE:
1030     case REFERENCE_TYPE:
1031       if (TYPE_MODE (t1) != TYPE_MODE (t2)
1032           || TYPE_REF_CAN_ALIAS_ALL (t1) != TYPE_REF_CAN_ALIAS_ALL (t2)
1033           || !same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1034         return false;
1035       break;
1036
1037     case METHOD_TYPE:
1038     case FUNCTION_TYPE:
1039       if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1040         return false;
1041       if (!compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2)))
1042         return false;
1043       break;
1044
1045     case ARRAY_TYPE:
1046       /* Target types must match incl. qualifiers.  */
1047       if (!comp_array_types (t1, t2, !!(strict & COMPARE_REDECLARATION)))
1048         return false;
1049       break;
1050
1051     case TEMPLATE_TYPE_PARM:
1052       if (TEMPLATE_TYPE_IDX (t1) != TEMPLATE_TYPE_IDX (t2)
1053           || TEMPLATE_TYPE_LEVEL (t1) != TEMPLATE_TYPE_LEVEL (t2))
1054         return false;
1055       break;
1056
1057     case TYPENAME_TYPE:
1058       if (!cp_tree_equal (TYPENAME_TYPE_FULLNAME (t1),
1059                           TYPENAME_TYPE_FULLNAME (t2)))
1060         return false;
1061       if (!same_type_p (TYPE_CONTEXT (t1), TYPE_CONTEXT (t2)))
1062         return false;
1063       break;
1064
1065     case UNBOUND_CLASS_TEMPLATE:
1066       if (!cp_tree_equal (TYPE_IDENTIFIER (t1), TYPE_IDENTIFIER (t2)))
1067         return false;
1068       if (!same_type_p (TYPE_CONTEXT (t1), TYPE_CONTEXT (t2)))
1069         return false;
1070       break;
1071
1072     case COMPLEX_TYPE:
1073       if (!same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1074         return false;
1075       break;
1076
1077     case VECTOR_TYPE:
1078       if (TYPE_VECTOR_SUBPARTS (t1) != TYPE_VECTOR_SUBPARTS (t2)
1079           || !same_type_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1080         return false;
1081       break;
1082
1083     default:
1084       return false;
1085     }
1086
1087   /* If we get here, we know that from a target independent POV the
1088      types are the same.  Make sure the target attributes are also
1089      the same.  */
1090   return targetm.comp_type_attributes (t1, t2);
1091 }
1092
1093 /* Return true if T1 and T2 are related as allowed by STRICT.  STRICT
1094    is a bitwise-or of the COMPARE_* flags.  */
1095
1096 bool
1097 comptypes (tree t1, tree t2, int strict)
1098 {
1099   if (strict == COMPARE_STRICT)
1100     {
1101       bool result;
1102
1103       if (t1 == t2)
1104         return true;
1105
1106       if (t1 == error_mark_node || t2 == error_mark_node)
1107         return false;
1108
1109       if (TYPE_STRUCTURAL_EQUALITY_P (t1) || TYPE_STRUCTURAL_EQUALITY_P (t2))
1110         /* At least one of the types requires structural equality, so
1111            perform a deep check. */
1112         return structural_comptypes (t1, t2, strict);
1113
1114       if (VERIFY_CANONICAL_TYPES)
1115         {
1116           result = structural_comptypes (t1, t2, strict);
1117
1118           if (result && TYPE_CANONICAL (t1) != TYPE_CANONICAL (t2))
1119             {
1120               /* The two types are structurally equivalent, but their
1121                  canonical types were different. This is a failure of the
1122                  canonical type propagation code.*/
1123               warning(0,
1124                       "canonical types differ for identical types %T and %T", 
1125                       t1, t2);
1126               debug_tree (t1);
1127               debug_tree (t2);
1128             }
1129           else if (!result && TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2))
1130             {
1131               /* Two types are structurally different, but the canonical
1132                  types are the same. This means we were over-eager in
1133                  assigning canonical types. */
1134               warning (0, 
1135                        "same canonical type node for different types %T and %T",
1136                        t1, t2);
1137               debug_tree (t1);
1138               debug_tree (t2);
1139             }
1140           
1141           return result;
1142         }
1143       else
1144         return TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2);
1145     }
1146   else if (strict == COMPARE_STRUCTURAL)
1147     return structural_comptypes (t1, t2, COMPARE_STRICT);
1148   else
1149     return structural_comptypes (t1, t2, strict);
1150 }
1151
1152 /* Returns 1 if TYPE1 is at least as qualified as TYPE2.  */
1153
1154 bool
1155 at_least_as_qualified_p (tree type1, tree type2)
1156 {
1157   int q1 = cp_type_quals (type1);
1158   int q2 = cp_type_quals (type2);
1159
1160   /* All qualifiers for TYPE2 must also appear in TYPE1.  */
1161   return (q1 & q2) == q2;
1162 }
1163
1164 /* Returns 1 if TYPE1 is more cv-qualified than TYPE2, -1 if TYPE2 is
1165    more cv-qualified that TYPE1, and 0 otherwise.  */
1166
1167 int
1168 comp_cv_qualification (tree type1, tree type2)
1169 {
1170   int q1 = cp_type_quals (type1);
1171   int q2 = cp_type_quals (type2);
1172
1173   if (q1 == q2)
1174     return 0;
1175
1176   if ((q1 & q2) == q2)
1177     return 1;
1178   else if ((q1 & q2) == q1)
1179     return -1;
1180
1181   return 0;
1182 }
1183
1184 /* Returns 1 if the cv-qualification signature of TYPE1 is a proper
1185    subset of the cv-qualification signature of TYPE2, and the types
1186    are similar.  Returns -1 if the other way 'round, and 0 otherwise.  */
1187
1188 int
1189 comp_cv_qual_signature (tree type1, tree type2)
1190 {
1191   if (comp_ptr_ttypes_real (type2, type1, -1))
1192     return 1;
1193   else if (comp_ptr_ttypes_real (type1, type2, -1))
1194     return -1;
1195   else
1196     return 0;
1197 }
1198
1199 /* If two types share a common base type, return that basetype.
1200    If there is not a unique most-derived base type, this function
1201    returns ERROR_MARK_NODE.  */
1202
1203 static tree
1204 common_base_type (tree tt1, tree tt2)
1205 {
1206   tree best = NULL_TREE;
1207   int i;
1208
1209   /* If one is a baseclass of another, that's good enough.  */
1210   if (UNIQUELY_DERIVED_FROM_P (tt1, tt2))
1211     return tt1;
1212   if (UNIQUELY_DERIVED_FROM_P (tt2, tt1))
1213     return tt2;
1214
1215   /* Otherwise, try to find a unique baseclass of TT1
1216      that is shared by TT2, and follow that down.  */
1217   for (i = BINFO_N_BASE_BINFOS (TYPE_BINFO (tt1))-1; i >= 0; i--)
1218     {
1219       tree basetype = BINFO_TYPE (BINFO_BASE_BINFO (TYPE_BINFO (tt1), i));
1220       tree trial = common_base_type (basetype, tt2);
1221
1222       if (trial)
1223         {
1224           if (trial == error_mark_node)
1225             return trial;
1226           if (best == NULL_TREE)
1227             best = trial;
1228           else if (best != trial)
1229             return error_mark_node;
1230         }
1231     }
1232
1233   /* Same for TT2.  */
1234   for (i = BINFO_N_BASE_BINFOS (TYPE_BINFO (tt2))-1; i >= 0; i--)
1235     {
1236       tree basetype = BINFO_TYPE (BINFO_BASE_BINFO (TYPE_BINFO (tt2), i));
1237       tree trial = common_base_type (tt1, basetype);
1238
1239       if (trial)
1240         {
1241           if (trial == error_mark_node)
1242             return trial;
1243           if (best == NULL_TREE)
1244             best = trial;
1245           else if (best != trial)
1246             return error_mark_node;
1247         }
1248     }
1249   return best;
1250 }
1251 \f
1252 /* Subroutines of `comptypes'.  */
1253
1254 /* Return true if two parameter type lists PARMS1 and PARMS2 are
1255    equivalent in the sense that functions with those parameter types
1256    can have equivalent types.  The two lists must be equivalent,
1257    element by element.  */
1258
1259 bool
1260 compparms (tree parms1, tree parms2)
1261 {
1262   tree t1, t2;
1263
1264   /* An unspecified parmlist matches any specified parmlist
1265      whose argument types don't need default promotions.  */
1266
1267   for (t1 = parms1, t2 = parms2;
1268        t1 || t2;
1269        t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1270     {
1271       /* If one parmlist is shorter than the other,
1272          they fail to match.  */
1273       if (!t1 || !t2)
1274         return false;
1275       if (!same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1276         return false;
1277     }
1278   return true;
1279 }
1280
1281 \f
1282 /* Process a sizeof or alignof expression where the operand is a
1283    type.  */
1284
1285 tree
1286 cxx_sizeof_or_alignof_type (tree type, enum tree_code op, bool complain)
1287 {
1288   tree value;
1289   bool dependent_p;
1290
1291   gcc_assert (op == SIZEOF_EXPR || op == ALIGNOF_EXPR);
1292   if (type == error_mark_node)
1293     return error_mark_node;
1294
1295   type = non_reference (type);
1296   if (TREE_CODE (type) == METHOD_TYPE)
1297     {
1298       if (complain && (pedantic || warn_pointer_arith))
1299         pedwarn ("invalid application of %qs to a member function", 
1300                  operator_name_info[(int) op].name);
1301       value = size_one_node;
1302     }
1303
1304   dependent_p = dependent_type_p (type);
1305   if (!dependent_p)
1306     complete_type (type);
1307   if (dependent_p
1308       /* VLA types will have a non-constant size.  In the body of an
1309          uninstantiated template, we don't need to try to compute the
1310          value, because the sizeof expression is not an integral
1311          constant expression in that case.  And, if we do try to
1312          compute the value, we'll likely end up with SAVE_EXPRs, which
1313          the template substitution machinery does not expect to see.  */
1314       || (processing_template_decl 
1315           && COMPLETE_TYPE_P (type)
1316           && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
1317     {
1318       value = build_min (op, size_type_node, type);
1319       TREE_READONLY (value) = 1;
1320       return value;
1321     }
1322
1323   return c_sizeof_or_alignof_type (complete_type (type),
1324                                    op == SIZEOF_EXPR,
1325                                    complain);
1326 }
1327
1328 /* Process a sizeof expression where the operand is an expression.  */
1329
1330 static tree
1331 cxx_sizeof_expr (tree e)
1332 {
1333   if (e == error_mark_node)
1334     return error_mark_node;
1335
1336   if (processing_template_decl)
1337     {
1338       e = build_min (SIZEOF_EXPR, size_type_node, e);
1339       TREE_SIDE_EFFECTS (e) = 0;
1340       TREE_READONLY (e) = 1;
1341
1342       return e;
1343     }
1344
1345   if (TREE_CODE (e) == COMPONENT_REF
1346       && TREE_CODE (TREE_OPERAND (e, 1)) == FIELD_DECL
1347       && DECL_C_BIT_FIELD (TREE_OPERAND (e, 1)))
1348     {
1349       error ("invalid application of %<sizeof%> to a bit-field");
1350       e = char_type_node;
1351     }
1352   else if (is_overloaded_fn (e))
1353     {
1354       pedwarn ("ISO C++ forbids applying %<sizeof%> to an expression of "
1355                "function type");
1356       e = char_type_node;
1357     }
1358   else if (type_unknown_p (e))
1359     {
1360       cxx_incomplete_type_error (e, TREE_TYPE (e));
1361       e = char_type_node;
1362     }
1363   else
1364     e = TREE_TYPE (e);
1365
1366   return cxx_sizeof_or_alignof_type (e, SIZEOF_EXPR, true);
1367 }
1368
1369 /* Implement the __alignof keyword: Return the minimum required
1370    alignment of E, measured in bytes.  For VAR_DECL's and
1371    FIELD_DECL's return DECL_ALIGN (which can be set from an
1372    "aligned" __attribute__ specification).  */
1373
1374 static tree
1375 cxx_alignof_expr (tree e)
1376 {
1377   tree t;
1378
1379   if (e == error_mark_node)
1380     return error_mark_node;
1381
1382   if (processing_template_decl)
1383     {
1384       e = build_min (ALIGNOF_EXPR, size_type_node, e);
1385       TREE_SIDE_EFFECTS (e) = 0;
1386       TREE_READONLY (e) = 1;
1387
1388       return e;
1389     }
1390
1391   if (TREE_CODE (e) == VAR_DECL)
1392     t = size_int (DECL_ALIGN_UNIT (e));
1393   else if (TREE_CODE (e) == COMPONENT_REF
1394            && TREE_CODE (TREE_OPERAND (e, 1)) == FIELD_DECL
1395            && DECL_C_BIT_FIELD (TREE_OPERAND (e, 1)))
1396     {
1397       error ("invalid application of %<__alignof%> to a bit-field");
1398       t = size_one_node;
1399     }
1400   else if (TREE_CODE (e) == COMPONENT_REF
1401            && TREE_CODE (TREE_OPERAND (e, 1)) == FIELD_DECL)
1402     t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (e, 1)));
1403   else if (is_overloaded_fn (e))
1404     {
1405       pedwarn ("ISO C++ forbids applying %<__alignof%> to an expression of "
1406                "function type");
1407       t = size_one_node;
1408     }
1409   else if (type_unknown_p (e))
1410     {
1411       cxx_incomplete_type_error (e, TREE_TYPE (e));
1412       t = size_one_node;
1413     }
1414   else
1415     return cxx_sizeof_or_alignof_type (TREE_TYPE (e), ALIGNOF_EXPR, true);
1416
1417   return fold_convert (size_type_node, t);
1418 }
1419
1420 /* Process a sizeof or alignof expression E with code OP where the operand
1421    is an expression.  */
1422
1423 tree
1424 cxx_sizeof_or_alignof_expr (tree e, enum tree_code op)
1425 {
1426   if (op == SIZEOF_EXPR)
1427     return cxx_sizeof_expr (e);
1428   else
1429     return cxx_alignof_expr (e);
1430 }
1431 \f
1432 /* EXPR is being used in a context that is not a function call.
1433    Enforce:
1434
1435      [expr.ref]
1436
1437      The expression can be used only as the left-hand operand of a
1438      member function call.
1439
1440      [expr.mptr.operator]
1441
1442      If the result of .* or ->* is a function, then that result can be
1443      used only as the operand for the function call operator ().
1444
1445    by issuing an error message if appropriate.  Returns true iff EXPR
1446    violates these rules.  */
1447
1448 bool
1449 invalid_nonstatic_memfn_p (tree expr)
1450 {
1451   if (TREE_CODE (TREE_TYPE (expr)) == METHOD_TYPE)
1452     {
1453       error ("invalid use of non-static member function");
1454       return true;
1455     }
1456   return false;
1457 }
1458
1459 /* If EXP is a reference to a bitfield, and the type of EXP does not
1460    match the declared type of the bitfield, return the declared type
1461    of the bitfield.  Otherwise, return NULL_TREE.  */
1462
1463 tree
1464 is_bitfield_expr_with_lowered_type (tree exp)
1465 {
1466   tree field;
1467
1468   if (TREE_CODE (exp) == COND_EXPR)
1469     {
1470       if (!is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 1)))
1471         return NULL_TREE;
1472       return is_bitfield_expr_with_lowered_type (TREE_OPERAND (exp, 2));
1473     }
1474   if (TREE_CODE (exp) != COMPONENT_REF)
1475     return NULL_TREE;
1476   field = TREE_OPERAND (exp, 1);
1477   if (TREE_CODE (field) != FIELD_DECL || !DECL_C_BIT_FIELD (field))
1478     return NULL_TREE;
1479   if (same_type_ignoring_top_level_qualifiers_p
1480       (TREE_TYPE (exp), DECL_BIT_FIELD_TYPE (field)))
1481     return NULL_TREE;
1482   return DECL_BIT_FIELD_TYPE (field);
1483 }
1484
1485 /* Perform the conversions in [expr] that apply when an lvalue appears
1486    in an rvalue context: the lvalue-to-rvalue, array-to-pointer, and
1487    function-to-pointer conversions.  In addition, manifest constants
1488    are replaced by their values, and bitfield references are converted
1489    to their declared types.
1490
1491    Although the returned value is being used as an rvalue, this
1492    function does not wrap the returned expression in a
1493    NON_LVALUE_EXPR; the caller is expected to be mindful of the fact
1494    that the return value is no longer an lvalue.  */
1495
1496 tree
1497 decay_conversion (tree exp)
1498 {
1499   tree type;
1500   enum tree_code code;
1501
1502   type = TREE_TYPE (exp);
1503   if (type == error_mark_node)
1504     return error_mark_node;
1505
1506   if (type_unknown_p (exp))
1507     {
1508       cxx_incomplete_type_error (exp, TREE_TYPE (exp));
1509       return error_mark_node;
1510     }
1511
1512   exp = decl_constant_value (exp);
1513   if (error_operand_p (exp))
1514     return error_mark_node;
1515
1516   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
1517      Leave such NOP_EXPRs, since RHS is being used in non-lvalue context.  */
1518   code = TREE_CODE (type);
1519   if (code == VOID_TYPE)
1520     {
1521       error ("void value not ignored as it ought to be");
1522       return error_mark_node;
1523     }
1524   if (invalid_nonstatic_memfn_p (exp))
1525     return error_mark_node;
1526   if (code == FUNCTION_TYPE || is_overloaded_fn (exp))
1527     return build_unary_op (ADDR_EXPR, exp, 0);
1528   if (code == ARRAY_TYPE)
1529     {
1530       tree adr;
1531       tree ptrtype;
1532
1533       if (TREE_CODE (exp) == INDIRECT_REF)
1534         return build_nop (build_pointer_type (TREE_TYPE (type)),
1535                           TREE_OPERAND (exp, 0));
1536
1537       if (TREE_CODE (exp) == COMPOUND_EXPR)
1538         {
1539           tree op1 = decay_conversion (TREE_OPERAND (exp, 1));
1540           return build2 (COMPOUND_EXPR, TREE_TYPE (op1),
1541                          TREE_OPERAND (exp, 0), op1);
1542         }
1543
1544       if (!lvalue_p (exp)
1545           && ! (TREE_CODE (exp) == CONSTRUCTOR && TREE_STATIC (exp)))
1546         {
1547           error ("invalid use of non-lvalue array");
1548           return error_mark_node;
1549         }
1550
1551       ptrtype = build_pointer_type (TREE_TYPE (type));
1552
1553       if (TREE_CODE (exp) == VAR_DECL)
1554         {
1555           if (!cxx_mark_addressable (exp))
1556             return error_mark_node;
1557           adr = build_nop (ptrtype, build_address (exp));
1558           return adr;
1559         }
1560       /* This way is better for a COMPONENT_REF since it can
1561          simplify the offset for a component.  */
1562       adr = build_unary_op (ADDR_EXPR, exp, 1);
1563       return cp_convert (ptrtype, adr);
1564     }
1565
1566   /* If a bitfield is used in a context where integral promotion
1567      applies, then the caller is expected to have used
1568      default_conversion.  That function promotes bitfields correctly
1569      before calling this function.  At this point, if we have a
1570      bitfield referenced, we may assume that is not subject to
1571      promotion, and that, therefore, the type of the resulting rvalue
1572      is the declared type of the bitfield.  */
1573   exp = convert_bitfield_to_declared_type (exp);
1574
1575   /* We do not call rvalue() here because we do not want to wrap EXP
1576      in a NON_LVALUE_EXPR.  */
1577
1578   /* [basic.lval]
1579
1580      Non-class rvalues always have cv-unqualified types.  */
1581   type = TREE_TYPE (exp);
1582   if (!CLASS_TYPE_P (type) && cp_type_quals (type))
1583     exp = build_nop (TYPE_MAIN_VARIANT (type), exp);
1584
1585   return exp;
1586 }
1587
1588 /* Perform prepatory conversions, as part of the "usual arithmetic
1589    conversions".  In particular, as per [expr]:
1590
1591      Whenever an lvalue expression appears as an operand of an
1592      operator that expects the rvalue for that operand, the
1593      lvalue-to-rvalue, array-to-pointer, or function-to-pointer
1594      standard conversions are applied to convert the expression to an
1595      rvalue.
1596
1597    In addition, we perform integral promotions here, as those are
1598    applied to both operands to a binary operator before determining
1599    what additional conversions should apply.  */
1600
1601 tree
1602 default_conversion (tree exp)
1603 {
1604   /* Perform the integral promotions first so that bitfield
1605      expressions (which may promote to "int", even if the bitfield is
1606      declared "unsigned") are promoted correctly.  */
1607   if (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (exp)))
1608     exp = perform_integral_promotions (exp);
1609   /* Perform the other conversions.  */
1610   exp = decay_conversion (exp);
1611
1612   return exp;
1613 }
1614
1615 /* EXPR is an expression with an integral or enumeration type.
1616    Perform the integral promotions in [conv.prom], and return the
1617    converted value.  */
1618
1619 tree
1620 perform_integral_promotions (tree expr)
1621 {
1622   tree type;
1623   tree promoted_type;
1624
1625   /* [conv.prom]
1626
1627      If the bitfield has an enumerated type, it is treated as any
1628      other value of that type for promotion purposes.  */
1629   type = is_bitfield_expr_with_lowered_type (expr);
1630   if (!type || TREE_CODE (type) != ENUMERAL_TYPE)
1631     type = TREE_TYPE (expr);
1632   gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
1633   promoted_type = type_promotes_to (type);
1634   if (type != promoted_type)
1635     expr = cp_convert (promoted_type, expr);
1636   return expr;
1637 }
1638
1639 /* Take the address of an inline function without setting TREE_ADDRESSABLE
1640    or TREE_USED.  */
1641
1642 tree
1643 inline_conversion (tree exp)
1644 {
1645   if (TREE_CODE (exp) == FUNCTION_DECL)
1646     exp = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (exp)), exp);
1647
1648   return exp;
1649 }
1650
1651 /* Returns nonzero iff exp is a STRING_CST or the result of applying
1652    decay_conversion to one.  */
1653
1654 int
1655 string_conv_p (tree totype, tree exp, int warn)
1656 {
1657   tree t;
1658
1659   if (TREE_CODE (totype) != POINTER_TYPE)
1660     return 0;
1661
1662   t = TREE_TYPE (totype);
1663   if (!same_type_p (t, char_type_node)
1664       && !same_type_p (t, wchar_type_node))
1665     return 0;
1666
1667   if (TREE_CODE (exp) == STRING_CST)
1668     {
1669       /* Make sure that we don't try to convert between char and wchar_t.  */
1670       if (!same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (exp))), t))
1671         return 0;
1672     }
1673   else
1674     {
1675       /* Is this a string constant which has decayed to 'const char *'?  */
1676       t = build_pointer_type (build_qualified_type (t, TYPE_QUAL_CONST));
1677       if (!same_type_p (TREE_TYPE (exp), t))
1678         return 0;
1679       STRIP_NOPS (exp);
1680       if (TREE_CODE (exp) != ADDR_EXPR
1681           || TREE_CODE (TREE_OPERAND (exp, 0)) != STRING_CST)
1682         return 0;
1683     }
1684
1685   /* This warning is not very useful, as it complains about printf.  */
1686   if (warn)
1687     warning (OPT_Wwrite_strings,
1688              "deprecated conversion from string constant to %qT",
1689              totype);
1690
1691   return 1;
1692 }
1693
1694 /* Given a COND_EXPR, MIN_EXPR, or MAX_EXPR in T, return it in a form that we
1695    can, for example, use as an lvalue.  This code used to be in
1696    unary_complex_lvalue, but we needed it to deal with `a = (d == c) ? b : c'
1697    expressions, where we're dealing with aggregates.  But now it's again only
1698    called from unary_complex_lvalue.  The case (in particular) that led to
1699    this was with CODE == ADDR_EXPR, since it's not an lvalue when we'd
1700    get it there.  */
1701
1702 static tree
1703 rationalize_conditional_expr (enum tree_code code, tree t)
1704 {
1705   /* For MIN_EXPR or MAX_EXPR, fold-const.c has arranged things so that
1706      the first operand is always the one to be used if both operands
1707      are equal, so we know what conditional expression this used to be.  */
1708   if (TREE_CODE (t) == MIN_EXPR || TREE_CODE (t) == MAX_EXPR)
1709     {
1710       tree op0 = TREE_OPERAND (t, 0);
1711       tree op1 = TREE_OPERAND (t, 1);
1712
1713       /* The following code is incorrect if either operand side-effects.  */
1714       gcc_assert (!TREE_SIDE_EFFECTS (op0)
1715                   && !TREE_SIDE_EFFECTS (op1));
1716       return
1717         build_conditional_expr (build_x_binary_op ((TREE_CODE (t) == MIN_EXPR
1718                                                     ? LE_EXPR : GE_EXPR),
1719                                                    op0, TREE_CODE (op0),
1720                                                    op1, TREE_CODE (op1),
1721                                                    /*overloaded_p=*/NULL),
1722                             build_unary_op (code, op0, 0),
1723                             build_unary_op (code, op1, 0));
1724     }
1725
1726   return
1727     build_conditional_expr (TREE_OPERAND (t, 0),
1728                             build_unary_op (code, TREE_OPERAND (t, 1), 0),
1729                             build_unary_op (code, TREE_OPERAND (t, 2), 0));
1730 }
1731
1732 /* Given the TYPE of an anonymous union field inside T, return the
1733    FIELD_DECL for the field.  If not found return NULL_TREE.  Because
1734    anonymous unions can nest, we must also search all anonymous unions
1735    that are directly reachable.  */
1736
1737 tree
1738 lookup_anon_field (tree t, tree type)
1739 {
1740   tree field;
1741
1742   for (field = TYPE_FIELDS (t); field; field = TREE_CHAIN (field))
1743     {
1744       if (TREE_STATIC (field))
1745         continue;
1746       if (TREE_CODE (field) != FIELD_DECL || DECL_ARTIFICIAL (field))
1747         continue;
1748
1749       /* If we find it directly, return the field.  */
1750       if (DECL_NAME (field) == NULL_TREE
1751           && type == TYPE_MAIN_VARIANT (TREE_TYPE (field)))
1752         {
1753           return field;
1754         }
1755
1756       /* Otherwise, it could be nested, search harder.  */
1757       if (DECL_NAME (field) == NULL_TREE
1758           && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1759         {
1760           tree subfield = lookup_anon_field (TREE_TYPE (field), type);
1761           if (subfield)
1762             return subfield;
1763         }
1764     }
1765   return NULL_TREE;
1766 }
1767
1768 /* Build an expression representing OBJECT.MEMBER.  OBJECT is an
1769    expression; MEMBER is a DECL or baselink.  If ACCESS_PATH is
1770    non-NULL, it indicates the path to the base used to name MEMBER.
1771    If PRESERVE_REFERENCE is true, the expression returned will have
1772    REFERENCE_TYPE if the MEMBER does.  Otherwise, the expression
1773    returned will have the type referred to by the reference.
1774
1775    This function does not perform access control; that is either done
1776    earlier by the parser when the name of MEMBER is resolved to MEMBER
1777    itself, or later when overload resolution selects one of the
1778    functions indicated by MEMBER.  */
1779
1780 tree
1781 build_class_member_access_expr (tree object, tree member,
1782                                 tree access_path, bool preserve_reference)
1783 {
1784   tree object_type;
1785   tree member_scope;
1786   tree result = NULL_TREE;
1787
1788   if (error_operand_p (object) || error_operand_p (member))
1789     return error_mark_node;
1790
1791   gcc_assert (DECL_P (member) || BASELINK_P (member));
1792
1793   /* [expr.ref]
1794
1795      The type of the first expression shall be "class object" (of a
1796      complete type).  */
1797   object_type = TREE_TYPE (object);
1798   if (!currently_open_class (object_type)
1799       && !complete_type_or_else (object_type, object))
1800     return error_mark_node;
1801   if (!CLASS_TYPE_P (object_type))
1802     {
1803       error ("request for member %qD in %qE, which is of non-class type %qT",
1804              member, object, object_type);
1805       return error_mark_node;
1806     }
1807
1808   /* The standard does not seem to actually say that MEMBER must be a
1809      member of OBJECT_TYPE.  However, that is clearly what is
1810      intended.  */
1811   if (DECL_P (member))
1812     {
1813       member_scope = DECL_CLASS_CONTEXT (member);
1814       mark_used (member);
1815       if (TREE_DEPRECATED (member))
1816         warn_deprecated_use (member);
1817     }
1818   else
1819     member_scope = BINFO_TYPE (BASELINK_BINFO (member));
1820   /* If MEMBER is from an anonymous aggregate, MEMBER_SCOPE will
1821      presently be the anonymous union.  Go outwards until we find a
1822      type related to OBJECT_TYPE.  */
1823   while (ANON_AGGR_TYPE_P (member_scope)
1824          && !same_type_ignoring_top_level_qualifiers_p (member_scope,
1825                                                         object_type))
1826     member_scope = TYPE_CONTEXT (member_scope);
1827   if (!member_scope || !DERIVED_FROM_P (member_scope, object_type))
1828     {
1829       if (TREE_CODE (member) == FIELD_DECL)
1830         error ("invalid use of nonstatic data member %qE", member);
1831       else
1832         error ("%qD is not a member of %qT", member, object_type);
1833       return error_mark_node;
1834     }
1835
1836   /* Transform `(a, b).x' into `(*(a, &b)).x', `(a ? b : c).x' into
1837      `(*(a ?  &b : &c)).x', and so on.  A COND_EXPR is only an lvalue
1838      in the frontend; only _DECLs and _REFs are lvalues in the backend.  */
1839   {
1840     tree temp = unary_complex_lvalue (ADDR_EXPR, object);
1841     if (temp)
1842       object = build_indirect_ref (temp, NULL);
1843   }
1844
1845   /* In [expr.ref], there is an explicit list of the valid choices for
1846      MEMBER.  We check for each of those cases here.  */
1847   if (TREE_CODE (member) == VAR_DECL)
1848     {
1849       /* A static data member.  */
1850       result = member;
1851       /* If OBJECT has side-effects, they are supposed to occur.  */
1852       if (TREE_SIDE_EFFECTS (object))
1853         result = build2 (COMPOUND_EXPR, TREE_TYPE (result), object, result);
1854     }
1855   else if (TREE_CODE (member) == FIELD_DECL)
1856     {
1857       /* A non-static data member.  */
1858       bool null_object_p;
1859       int type_quals;
1860       tree member_type;
1861
1862       null_object_p = (TREE_CODE (object) == INDIRECT_REF
1863                        && integer_zerop (TREE_OPERAND (object, 0)));
1864
1865       /* Convert OBJECT to the type of MEMBER.  */
1866       if (!same_type_p (TYPE_MAIN_VARIANT (object_type),
1867                         TYPE_MAIN_VARIANT (member_scope)))
1868         {
1869           tree binfo;
1870           base_kind kind;
1871
1872           binfo = lookup_base (access_path ? access_path : object_type,
1873                                member_scope, ba_unique,  &kind);
1874           if (binfo == error_mark_node)
1875             return error_mark_node;
1876
1877           /* It is invalid to try to get to a virtual base of a
1878              NULL object.  The most common cause is invalid use of
1879              offsetof macro.  */
1880           if (null_object_p && kind == bk_via_virtual)
1881             {
1882               error ("invalid access to non-static data member %qD of "
1883                      "NULL object",
1884                      member);
1885               error ("(perhaps the %<offsetof%> macro was used incorrectly)");
1886               return error_mark_node;
1887             }
1888
1889           /* Convert to the base.  */
1890           object = build_base_path (PLUS_EXPR, object, binfo,
1891                                     /*nonnull=*/1);
1892           /* If we found the base successfully then we should be able
1893              to convert to it successfully.  */
1894           gcc_assert (object != error_mark_node);
1895         }
1896
1897       /* Complain about other invalid uses of offsetof, even though they will
1898          give the right answer.  Note that we complain whether or not they
1899          actually used the offsetof macro, since there's no way to know at this
1900          point.  So we just give a warning, instead of a pedwarn.  */
1901       /* Do not produce this warning for base class field references, because
1902          we know for a fact that didn't come from offsetof.  This does occur
1903          in various testsuite cases where a null object is passed where a
1904          vtable access is required.  */
1905       if (null_object_p && warn_invalid_offsetof
1906           && CLASSTYPE_NON_POD_P (object_type)
1907           && !DECL_FIELD_IS_BASE (member)
1908           && !skip_evaluation)
1909         {
1910           warning (0, "invalid access to non-static data member %qD of NULL object",
1911                    member);
1912           warning (0, "(perhaps the %<offsetof%> macro was used incorrectly)");
1913         }
1914
1915       /* If MEMBER is from an anonymous aggregate, we have converted
1916          OBJECT so that it refers to the class containing the
1917          anonymous union.  Generate a reference to the anonymous union
1918          itself, and recur to find MEMBER.  */
1919       if (ANON_AGGR_TYPE_P (DECL_CONTEXT (member))
1920           /* When this code is called from build_field_call, the
1921              object already has the type of the anonymous union.
1922              That is because the COMPONENT_REF was already
1923              constructed, and was then disassembled before calling
1924              build_field_call.  After the function-call code is
1925              cleaned up, this waste can be eliminated.  */
1926           && (!same_type_ignoring_top_level_qualifiers_p
1927               (TREE_TYPE (object), DECL_CONTEXT (member))))
1928         {
1929           tree anonymous_union;
1930
1931           anonymous_union = lookup_anon_field (TREE_TYPE (object),
1932                                                DECL_CONTEXT (member));
1933           object = build_class_member_access_expr (object,
1934                                                    anonymous_union,
1935                                                    /*access_path=*/NULL_TREE,
1936                                                    preserve_reference);
1937         }
1938
1939       /* Compute the type of the field, as described in [expr.ref].  */
1940       type_quals = TYPE_UNQUALIFIED;
1941       member_type = TREE_TYPE (member);
1942       if (TREE_CODE (member_type) != REFERENCE_TYPE)
1943         {
1944           type_quals = (cp_type_quals (member_type)
1945                         | cp_type_quals (object_type));
1946
1947           /* A field is const (volatile) if the enclosing object, or the
1948              field itself, is const (volatile).  But, a mutable field is
1949              not const, even within a const object.  */
1950           if (DECL_MUTABLE_P (member))
1951             type_quals &= ~TYPE_QUAL_CONST;
1952           member_type = cp_build_qualified_type (member_type, type_quals);
1953         }
1954
1955       result = build3 (COMPONENT_REF, member_type, object, member,
1956                        NULL_TREE);
1957       result = fold_if_not_in_template (result);
1958
1959       /* Mark the expression const or volatile, as appropriate.  Even
1960          though we've dealt with the type above, we still have to mark the
1961          expression itself.  */
1962       if (type_quals & TYPE_QUAL_CONST)
1963         TREE_READONLY (result) = 1;
1964       if (type_quals & TYPE_QUAL_VOLATILE)
1965         TREE_THIS_VOLATILE (result) = 1;
1966     }
1967   else if (BASELINK_P (member))
1968     {
1969       /* The member is a (possibly overloaded) member function.  */
1970       tree functions;
1971       tree type;
1972
1973       /* If the MEMBER is exactly one static member function, then we
1974          know the type of the expression.  Otherwise, we must wait
1975          until overload resolution has been performed.  */
1976       functions = BASELINK_FUNCTIONS (member);
1977       if (TREE_CODE (functions) == FUNCTION_DECL
1978           && DECL_STATIC_FUNCTION_P (functions))
1979         type = TREE_TYPE (functions);
1980       else
1981         type = unknown_type_node;
1982       /* Note that we do not convert OBJECT to the BASELINK_BINFO
1983          base.  That will happen when the function is called.  */
1984       result = build3 (COMPONENT_REF, type, object, member, NULL_TREE);
1985     }
1986   else if (TREE_CODE (member) == CONST_DECL)
1987     {
1988       /* The member is an enumerator.  */
1989       result = member;
1990       /* If OBJECT has side-effects, they are supposed to occur.  */
1991       if (TREE_SIDE_EFFECTS (object))
1992         result = build2 (COMPOUND_EXPR, TREE_TYPE (result),
1993                          object, result);
1994     }
1995   else
1996     {
1997       error ("invalid use of %qD", member);
1998       return error_mark_node;
1999     }
2000
2001   if (!preserve_reference)
2002     /* [expr.ref]
2003
2004        If E2 is declared to have type "reference to T", then ... the
2005        type of E1.E2 is T.  */
2006     result = convert_from_reference (result);
2007
2008   return result;
2009 }
2010
2011 /* Return the destructor denoted by OBJECT.SCOPE::~DTOR_NAME, or, if
2012    SCOPE is NULL, by OBJECT.~DTOR_NAME.  */
2013
2014 static tree
2015 lookup_destructor (tree object, tree scope, tree dtor_name)
2016 {
2017   tree object_type = TREE_TYPE (object);
2018   tree dtor_type = TREE_OPERAND (dtor_name, 0);
2019   tree expr;
2020
2021   if (scope && !check_dtor_name (scope, dtor_type))
2022     {
2023       error ("qualified type %qT does not match destructor name ~%qT",
2024              scope, dtor_type);
2025       return error_mark_node;
2026     }
2027   if (!DERIVED_FROM_P (dtor_type, TYPE_MAIN_VARIANT (object_type)))
2028     {
2029       error ("the type being destroyed is %qT, but the destructor refers to %qT",
2030              TYPE_MAIN_VARIANT (object_type), dtor_type);
2031       return error_mark_node;
2032     }
2033   expr = lookup_member (dtor_type, complete_dtor_identifier,
2034                         /*protect=*/1, /*want_type=*/false);
2035   expr = (adjust_result_of_qualified_name_lookup
2036           (expr, dtor_type, object_type));
2037   return expr;
2038 }
2039
2040 /* An expression of the form "A::template B" has been resolved to
2041    DECL.  Issue a diagnostic if B is not a template or template
2042    specialization.  */
2043
2044 void
2045 check_template_keyword (tree decl)
2046 {
2047   /* The standard says:
2048
2049       [temp.names]
2050
2051       If a name prefixed by the keyword template is not a member
2052       template, the program is ill-formed.
2053
2054      DR 228 removed the restriction that the template be a member
2055      template.
2056
2057      DR 96, if accepted would add the further restriction that explicit
2058      template arguments must be provided if the template keyword is
2059      used, but, as of 2005-10-16, that DR is still in "drafting".  If
2060      this DR is accepted, then the semantic checks here can be
2061      simplified, as the entity named must in fact be a template
2062      specialization, rather than, as at present, a set of overloaded
2063      functions containing at least one template function.  */
2064   if (TREE_CODE (decl) != TEMPLATE_DECL
2065       && TREE_CODE (decl) != TEMPLATE_ID_EXPR)
2066     {
2067       if (!is_overloaded_fn (decl))
2068         pedwarn ("%qD is not a template", decl);
2069       else
2070         {
2071           tree fns;
2072           fns = decl;
2073           if (BASELINK_P (fns))
2074             fns = BASELINK_FUNCTIONS (fns);
2075           while (fns)
2076             {
2077               tree fn = OVL_CURRENT (fns);
2078               if (TREE_CODE (fn) == TEMPLATE_DECL
2079                   || TREE_CODE (fn) == TEMPLATE_ID_EXPR)
2080                 break;
2081               if (TREE_CODE (fn) == FUNCTION_DECL
2082                   && DECL_USE_TEMPLATE (fn)
2083                   && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (fn)))
2084                 break;
2085               fns = OVL_NEXT (fns);
2086             }
2087           if (!fns)
2088             pedwarn ("%qD is not a template", decl);
2089         }
2090     }
2091 }
2092
2093 /* This function is called by the parser to process a class member
2094    access expression of the form OBJECT.NAME.  NAME is a node used by
2095    the parser to represent a name; it is not yet a DECL.  It may,
2096    however, be a BASELINK where the BASELINK_FUNCTIONS is a
2097    TEMPLATE_ID_EXPR.  Templates must be looked up by the parser, and
2098    there is no reason to do the lookup twice, so the parser keeps the
2099    BASELINK.  TEMPLATE_P is true iff NAME was explicitly declared to
2100    be a template via the use of the "A::template B" syntax.  */
2101
2102 tree
2103 finish_class_member_access_expr (tree object, tree name, bool template_p)
2104 {
2105   tree expr;
2106   tree object_type;
2107   tree member;
2108   tree access_path = NULL_TREE;
2109   tree orig_object = object;
2110   tree orig_name = name;
2111
2112   if (object == error_mark_node || name == error_mark_node)
2113     return error_mark_node;
2114
2115   /* If OBJECT is an ObjC class instance, we must obey ObjC access rules.  */
2116   if (!objc_is_public (object, name))
2117     return error_mark_node;
2118
2119   object_type = TREE_TYPE (object);
2120
2121   if (processing_template_decl)
2122     {
2123       if (/* If OBJECT_TYPE is dependent, so is OBJECT.NAME.  */
2124           dependent_type_p (object_type)
2125           /* If NAME is just an IDENTIFIER_NODE, then the expression
2126              is dependent.  */
2127           || TREE_CODE (object) == IDENTIFIER_NODE
2128           /* If NAME is "f<args>", where either 'f' or 'args' is
2129              dependent, then the expression is dependent.  */
2130           || (TREE_CODE (name) == TEMPLATE_ID_EXPR
2131               && dependent_template_id_p (TREE_OPERAND (name, 0),
2132                                           TREE_OPERAND (name, 1)))
2133           /* If NAME is "T::X" where "T" is dependent, then the
2134              expression is dependent.  */
2135           || (TREE_CODE (name) == SCOPE_REF
2136               && TYPE_P (TREE_OPERAND (name, 0))
2137               && dependent_type_p (TREE_OPERAND (name, 0))))
2138         return build_min_nt (COMPONENT_REF, object, name, NULL_TREE);
2139       object = build_non_dependent_expr (object);
2140     }
2141
2142   /* [expr.ref]
2143
2144      The type of the first expression shall be "class object" (of a
2145      complete type).  */
2146   if (!currently_open_class (object_type)
2147       && !complete_type_or_else (object_type, object))
2148     return error_mark_node;
2149   if (!CLASS_TYPE_P (object_type))
2150     {
2151       error ("request for member %qD in %qE, which is of non-class type %qT",
2152              name, object, object_type);
2153       return error_mark_node;
2154     }
2155
2156   if (BASELINK_P (name))
2157     /* A member function that has already been looked up.  */
2158     member = name;
2159   else
2160     {
2161       bool is_template_id = false;
2162       tree template_args = NULL_TREE;
2163       tree scope;
2164
2165       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
2166         {
2167           is_template_id = true;
2168           template_args = TREE_OPERAND (name, 1);
2169           name = TREE_OPERAND (name, 0);
2170
2171           if (TREE_CODE (name) == OVERLOAD)
2172             name = DECL_NAME (get_first_fn (name));
2173           else if (DECL_P (name))
2174             name = DECL_NAME (name);
2175         }
2176
2177       if (TREE_CODE (name) == SCOPE_REF)
2178         {
2179           /* A qualified name.  The qualifying class or namespace `S'
2180              has already been looked up; it is either a TYPE or a
2181              NAMESPACE_DECL.  */
2182           scope = TREE_OPERAND (name, 0);
2183           name = TREE_OPERAND (name, 1);
2184
2185           /* If SCOPE is a namespace, then the qualified name does not
2186              name a member of OBJECT_TYPE.  */
2187           if (TREE_CODE (scope) == NAMESPACE_DECL)
2188             {
2189               error ("%<%D::%D%> is not a member of %qT",
2190                      scope, name, object_type);
2191               return error_mark_node;
2192             }
2193
2194           gcc_assert (CLASS_TYPE_P (scope));
2195           gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE
2196                       || TREE_CODE (name) == BIT_NOT_EXPR);
2197
2198           /* Find the base of OBJECT_TYPE corresponding to SCOPE.  */
2199           access_path = lookup_base (object_type, scope, ba_check, NULL);
2200           if (access_path == error_mark_node)
2201             return error_mark_node;
2202           if (!access_path)
2203             {
2204               error ("%qT is not a base of %qT", scope, object_type);
2205               return error_mark_node;
2206             }
2207         }
2208       else
2209         {
2210           scope = NULL_TREE;
2211           access_path = object_type;
2212         }
2213
2214       if (TREE_CODE (name) == BIT_NOT_EXPR)
2215         member = lookup_destructor (object, scope, name);
2216       else
2217         {
2218           /* Look up the member.  */
2219           member = lookup_member (access_path, name, /*protect=*/1,
2220                                   /*want_type=*/false);
2221           if (member == NULL_TREE)
2222             {
2223               error ("%qD has no member named %qE", object_type, name);
2224               return error_mark_node;
2225             }
2226           if (member == error_mark_node)
2227             return error_mark_node;
2228         }
2229
2230       if (is_template_id)
2231         {
2232           tree template = member;
2233
2234           if (BASELINK_P (template))
2235             template = lookup_template_function (template, template_args);
2236           else
2237             {
2238               error ("%qD is not a member template function", name);
2239               return error_mark_node;
2240             }
2241         }
2242     }
2243
2244   if (TREE_DEPRECATED (member))
2245     warn_deprecated_use (member);
2246
2247   if (template_p)
2248     check_template_keyword (member);
2249
2250   expr = build_class_member_access_expr (object, member, access_path,
2251                                          /*preserve_reference=*/false);
2252   if (processing_template_decl && expr != error_mark_node)
2253     {
2254       if (BASELINK_P (member))
2255         {
2256           if (TREE_CODE (orig_name) == SCOPE_REF)
2257             BASELINK_QUALIFIED_P (member) = 1;
2258           orig_name = member;
2259         }
2260       return build_min_non_dep (COMPONENT_REF, expr,
2261                                 orig_object, orig_name,
2262                                 NULL_TREE);
2263     }
2264
2265   return expr;
2266 }
2267
2268 /* Return an expression for the MEMBER_NAME field in the internal
2269    representation of PTRMEM, a pointer-to-member function.  (Each
2270    pointer-to-member function type gets its own RECORD_TYPE so it is
2271    more convenient to access the fields by name than by FIELD_DECL.)
2272    This routine converts the NAME to a FIELD_DECL and then creates the
2273    node for the complete expression.  */
2274
2275 tree
2276 build_ptrmemfunc_access_expr (tree ptrmem, tree member_name)
2277 {
2278   tree ptrmem_type;
2279   tree member;
2280   tree member_type;
2281
2282   /* This code is a stripped down version of
2283      build_class_member_access_expr.  It does not work to use that
2284      routine directly because it expects the object to be of class
2285      type.  */
2286   ptrmem_type = TREE_TYPE (ptrmem);
2287   gcc_assert (TYPE_PTRMEMFUNC_P (ptrmem_type));
2288   member = lookup_member (ptrmem_type, member_name, /*protect=*/0,
2289                           /*want_type=*/false);
2290   member_type = cp_build_qualified_type (TREE_TYPE (member),
2291                                          cp_type_quals (ptrmem_type));
2292   return fold_build3 (COMPONENT_REF, member_type,
2293                       ptrmem, member, NULL_TREE);
2294 }
2295
2296 /* Given an expression PTR for a pointer, return an expression
2297    for the value pointed to.
2298    ERRORSTRING is the name of the operator to appear in error messages.
2299
2300    This function may need to overload OPERATOR_FNNAME.
2301    Must also handle REFERENCE_TYPEs for C++.  */
2302
2303 tree
2304 build_x_indirect_ref (tree expr, const char *errorstring)
2305 {
2306   tree orig_expr = expr;
2307   tree rval;
2308
2309   if (processing_template_decl)
2310     {
2311       if (type_dependent_expression_p (expr))
2312         return build_min_nt (INDIRECT_REF, expr);
2313       expr = build_non_dependent_expr (expr);
2314     }
2315
2316   rval = build_new_op (INDIRECT_REF, LOOKUP_NORMAL, expr, NULL_TREE,
2317                        NULL_TREE, /*overloaded_p=*/NULL);
2318   if (!rval)
2319     rval = build_indirect_ref (expr, errorstring);
2320
2321   if (processing_template_decl && rval != error_mark_node)
2322     return build_min_non_dep (INDIRECT_REF, rval, orig_expr);
2323   else
2324     return rval;
2325 }
2326
2327 tree
2328 build_indirect_ref (tree ptr, const char *errorstring)
2329 {
2330   tree pointer, type;
2331
2332   if (ptr == error_mark_node)
2333     return error_mark_node;
2334
2335   if (ptr == current_class_ptr)
2336     return current_class_ref;
2337
2338   pointer = (TREE_CODE (TREE_TYPE (ptr)) == REFERENCE_TYPE
2339              ? ptr : decay_conversion (ptr));
2340   type = TREE_TYPE (pointer);
2341
2342   if (POINTER_TYPE_P (type))
2343     {
2344       /* [expr.unary.op]
2345
2346          If the type of the expression is "pointer to T," the type
2347          of  the  result  is  "T."
2348
2349          We must use the canonical variant because certain parts of
2350          the back end, like fold, do pointer comparisons between
2351          types.  */
2352       tree t = canonical_type_variant (TREE_TYPE (type));
2353
2354       if (VOID_TYPE_P (t))
2355         {
2356           /* A pointer to incomplete type (other than cv void) can be
2357              dereferenced [expr.unary.op]/1  */
2358           error ("%qT is not a pointer-to-object type", type);
2359           return error_mark_node;
2360         }
2361       else if (TREE_CODE (pointer) == ADDR_EXPR
2362                && same_type_p (t, TREE_TYPE (TREE_OPERAND (pointer, 0))))
2363         /* The POINTER was something like `&x'.  We simplify `*&x' to
2364            `x'.  */
2365         return TREE_OPERAND (pointer, 0);
2366       else
2367         {
2368           tree ref = build1 (INDIRECT_REF, t, pointer);
2369
2370           /* We *must* set TREE_READONLY when dereferencing a pointer to const,
2371              so that we get the proper error message if the result is used
2372              to assign to.  Also, &* is supposed to be a no-op.  */
2373           TREE_READONLY (ref) = CP_TYPE_CONST_P (t);
2374           TREE_THIS_VOLATILE (ref) = CP_TYPE_VOLATILE_P (t);
2375           TREE_SIDE_EFFECTS (ref)
2376             = (TREE_THIS_VOLATILE (ref) || TREE_SIDE_EFFECTS (pointer));
2377           return ref;
2378         }
2379     }
2380   /* `pointer' won't be an error_mark_node if we were given a
2381      pointer to member, so it's cool to check for this here.  */
2382   else if (TYPE_PTR_TO_MEMBER_P (type))
2383     error ("invalid use of %qs on pointer to member", errorstring);
2384   else if (pointer != error_mark_node)
2385     {
2386       if (errorstring)
2387         error ("invalid type argument of %qs", errorstring);
2388       else
2389         error ("invalid type argument");
2390     }
2391   return error_mark_node;
2392 }
2393
2394 /* This handles expressions of the form "a[i]", which denotes
2395    an array reference.
2396
2397    This is logically equivalent in C to *(a+i), but we may do it differently.
2398    If A is a variable or a member, we generate a primitive ARRAY_REF.
2399    This avoids forcing the array out of registers, and can work on
2400    arrays that are not lvalues (for example, members of structures returned
2401    by functions).
2402
2403    If INDEX is of some user-defined type, it must be converted to
2404    integer type.  Otherwise, to make a compatible PLUS_EXPR, it
2405    will inherit the type of the array, which will be some pointer type.  */
2406
2407 tree
2408 build_array_ref (tree array, tree idx)
2409 {
2410   if (idx == 0)
2411     {
2412       error ("subscript missing in array reference");
2413       return error_mark_node;
2414     }
2415
2416   if (TREE_TYPE (array) == error_mark_node
2417       || TREE_TYPE (idx) == error_mark_node)
2418     return error_mark_node;
2419
2420   /* If ARRAY is a COMPOUND_EXPR or COND_EXPR, move our reference
2421      inside it.  */
2422   switch (TREE_CODE (array))
2423     {
2424     case COMPOUND_EXPR:
2425       {
2426         tree value = build_array_ref (TREE_OPERAND (array, 1), idx);
2427         return build2 (COMPOUND_EXPR, TREE_TYPE (value),
2428                        TREE_OPERAND (array, 0), value);
2429       }
2430
2431     case COND_EXPR:
2432       return build_conditional_expr
2433         (TREE_OPERAND (array, 0),
2434          build_array_ref (TREE_OPERAND (array, 1), idx),
2435          build_array_ref (TREE_OPERAND (array, 2), idx));
2436
2437     default:
2438       break;
2439     }
2440
2441   if (TREE_CODE (TREE_TYPE (array)) == ARRAY_TYPE)
2442     {
2443       tree rval, type;
2444
2445       warn_array_subscript_with_type_char (idx);
2446
2447       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (idx)))
2448         {
2449           error ("array subscript is not an integer");
2450           return error_mark_node;
2451         }
2452
2453       /* Apply integral promotions *after* noticing character types.
2454          (It is unclear why we do these promotions -- the standard
2455          does not say that we should.  In fact, the natural thing would
2456          seem to be to convert IDX to ptrdiff_t; we're performing
2457          pointer arithmetic.)  */
2458       idx = perform_integral_promotions (idx);
2459
2460       /* An array that is indexed by a non-constant
2461          cannot be stored in a register; we must be able to do
2462          address arithmetic on its address.
2463          Likewise an array of elements of variable size.  */
2464       if (TREE_CODE (idx) != INTEGER_CST
2465           || (COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (array)))
2466               && (TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (array))))
2467                   != INTEGER_CST)))
2468         {
2469           if (!cxx_mark_addressable (array))
2470             return error_mark_node;
2471         }
2472
2473       /* An array that is indexed by a constant value which is not within
2474          the array bounds cannot be stored in a register either; because we
2475          would get a crash in store_bit_field/extract_bit_field when trying
2476          to access a non-existent part of the register.  */
2477       if (TREE_CODE (idx) == INTEGER_CST
2478           && TYPE_DOMAIN (TREE_TYPE (array))
2479           && ! int_fits_type_p (idx, TYPE_DOMAIN (TREE_TYPE (array))))
2480         {
2481           if (!cxx_mark_addressable (array))
2482             return error_mark_node;
2483         }
2484
2485       if (pedantic && !lvalue_p (array))
2486         pedwarn ("ISO C++ forbids subscripting non-lvalue array");
2487
2488       /* Note in C++ it is valid to subscript a `register' array, since
2489          it is valid to take the address of something with that
2490          storage specification.  */
2491       if (extra_warnings)
2492         {
2493           tree foo = array;
2494           while (TREE_CODE (foo) == COMPONENT_REF)
2495             foo = TREE_OPERAND (foo, 0);
2496           if (TREE_CODE (foo) == VAR_DECL && DECL_REGISTER (foo))
2497             warning (OPT_Wextra, "subscripting array declared %<register%>");
2498         }
2499
2500       type = TREE_TYPE (TREE_TYPE (array));
2501       rval = build4 (ARRAY_REF, type, array, idx, NULL_TREE, NULL_TREE);
2502       /* Array ref is const/volatile if the array elements are
2503          or if the array is..  */
2504       TREE_READONLY (rval)
2505         |= (CP_TYPE_CONST_P (type) | TREE_READONLY (array));
2506       TREE_SIDE_EFFECTS (rval)
2507         |= (CP_TYPE_VOLATILE_P (type) | TREE_SIDE_EFFECTS (array));
2508       TREE_THIS_VOLATILE (rval)
2509         |= (CP_TYPE_VOLATILE_P (type) | TREE_THIS_VOLATILE (array));
2510       return require_complete_type (fold_if_not_in_template (rval));
2511     }
2512
2513   {
2514     tree ar = default_conversion (array);
2515     tree ind = default_conversion (idx);
2516
2517     /* Put the integer in IND to simplify error checking.  */
2518     if (TREE_CODE (TREE_TYPE (ar)) == INTEGER_TYPE)
2519       {
2520         tree temp = ar;
2521         ar = ind;
2522         ind = temp;
2523       }
2524
2525     if (ar == error_mark_node)
2526       return ar;
2527
2528     if (TREE_CODE (TREE_TYPE (ar)) != POINTER_TYPE)
2529       {
2530         error ("subscripted value is neither array nor pointer");
2531         return error_mark_node;
2532       }
2533     if (TREE_CODE (TREE_TYPE (ind)) != INTEGER_TYPE)
2534       {
2535         error ("array subscript is not an integer");
2536         return error_mark_node;
2537       }
2538
2539     warn_array_subscript_with_type_char (idx);
2540
2541     return build_indirect_ref (cp_build_binary_op (PLUS_EXPR, ar, ind),
2542                                "array indexing");
2543   }
2544 }
2545 \f
2546 /* Resolve a pointer to member function.  INSTANCE is the object
2547    instance to use, if the member points to a virtual member.
2548
2549    This used to avoid checking for virtual functions if basetype
2550    has no virtual functions, according to an earlier ANSI draft.
2551    With the final ISO C++ rules, such an optimization is
2552    incorrect: A pointer to a derived member can be static_cast
2553    to pointer-to-base-member, as long as the dynamic object
2554    later has the right member.  */
2555
2556 tree
2557 get_member_function_from_ptrfunc (tree *instance_ptrptr, tree function)
2558 {
2559   if (TREE_CODE (function) == OFFSET_REF)
2560     function = TREE_OPERAND (function, 1);
2561
2562   if (TYPE_PTRMEMFUNC_P (TREE_TYPE (function)))
2563     {
2564       tree idx, delta, e1, e2, e3, vtbl, basetype;
2565       tree fntype = TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (function));
2566
2567       tree instance_ptr = *instance_ptrptr;
2568       tree instance_save_expr = 0;
2569       if (instance_ptr == error_mark_node)
2570         {
2571           if (TREE_CODE (function) == PTRMEM_CST)
2572             {
2573               /* Extracting the function address from a pmf is only
2574                  allowed with -Wno-pmf-conversions. It only works for
2575                  pmf constants.  */
2576               e1 = build_addr_func (PTRMEM_CST_MEMBER (function));
2577               e1 = convert (fntype, e1);
2578               return e1;
2579             }
2580           else
2581             {
2582               error ("object missing in use of %qE", function);
2583               return error_mark_node;
2584             }
2585         }
2586
2587       if (TREE_SIDE_EFFECTS (instance_ptr))
2588         instance_ptr = instance_save_expr = save_expr (instance_ptr);
2589
2590       if (TREE_SIDE_EFFECTS (function))
2591         function = save_expr (function);
2592
2593       /* Start by extracting all the information from the PMF itself.  */
2594       e3 = pfn_from_ptrmemfunc (function);
2595       delta = build_ptrmemfunc_access_expr (function, delta_identifier);
2596       idx = build1 (NOP_EXPR, vtable_index_type, e3);
2597       switch (TARGET_PTRMEMFUNC_VBIT_LOCATION)
2598         {
2599         case ptrmemfunc_vbit_in_pfn:
2600           e1 = cp_build_binary_op (BIT_AND_EXPR, idx, integer_one_node);
2601           idx = cp_build_binary_op (MINUS_EXPR, idx, integer_one_node);
2602           break;
2603
2604         case ptrmemfunc_vbit_in_delta:
2605           e1 = cp_build_binary_op (BIT_AND_EXPR, delta, integer_one_node);
2606           delta = cp_build_binary_op (RSHIFT_EXPR, delta, integer_one_node);
2607           break;
2608
2609         default:
2610           gcc_unreachable ();
2611         }
2612
2613       /* Convert down to the right base before using the instance.  A
2614          special case is that in a pointer to member of class C, C may
2615          be incomplete.  In that case, the function will of course be
2616          a member of C, and no conversion is required.  In fact,
2617          lookup_base will fail in that case, because incomplete
2618          classes do not have BINFOs.  */
2619       basetype = TYPE_METHOD_BASETYPE (TREE_TYPE (fntype));
2620       if (!same_type_ignoring_top_level_qualifiers_p
2621           (basetype, TREE_TYPE (TREE_TYPE (instance_ptr))))
2622         {
2623           basetype = lookup_base (TREE_TYPE (TREE_TYPE (instance_ptr)),
2624                                   basetype, ba_check, NULL);
2625           instance_ptr = build_base_path (PLUS_EXPR, instance_ptr, basetype,
2626                                           1);
2627           if (instance_ptr == error_mark_node)
2628             return error_mark_node;
2629         }
2630       /* ...and then the delta in the PMF.  */
2631       instance_ptr = build2 (PLUS_EXPR, TREE_TYPE (instance_ptr),
2632                              instance_ptr, delta);
2633
2634       /* Hand back the adjusted 'this' argument to our caller.  */
2635       *instance_ptrptr = instance_ptr;
2636
2637       /* Next extract the vtable pointer from the object.  */
2638       vtbl = build1 (NOP_EXPR, build_pointer_type (vtbl_ptr_type_node),
2639                      instance_ptr);
2640       vtbl = build_indirect_ref (vtbl, NULL);
2641
2642       /* Finally, extract the function pointer from the vtable.  */
2643       e2 = fold_build2 (PLUS_EXPR, TREE_TYPE (vtbl), vtbl, idx);
2644       e2 = build_indirect_ref (e2, NULL);
2645       TREE_CONSTANT (e2) = 1;
2646       TREE_INVARIANT (e2) = 1;
2647
2648       /* When using function descriptors, the address of the
2649          vtable entry is treated as a function pointer.  */
2650       if (TARGET_VTABLE_USES_DESCRIPTORS)
2651         e2 = build1 (NOP_EXPR, TREE_TYPE (e2),
2652                      build_unary_op (ADDR_EXPR, e2, /*noconvert=*/1));
2653
2654       TREE_TYPE (e2) = TREE_TYPE (e3);
2655       e1 = build_conditional_expr (e1, e2, e3);
2656
2657       /* Make sure this doesn't get evaluated first inside one of the
2658          branches of the COND_EXPR.  */
2659       if (instance_save_expr)
2660         e1 = build2 (COMPOUND_EXPR, TREE_TYPE (e1),
2661                      instance_save_expr, e1);
2662
2663       function = e1;
2664     }
2665   return function;
2666 }
2667
2668 tree
2669 build_function_call (tree function, tree params)
2670 {
2671   tree fntype, fndecl;
2672   tree coerced_params;
2673   tree name = NULL_TREE;
2674   int is_method;
2675   tree original = function;
2676
2677   /* For Objective-C, convert any calls via a cast to OBJC_TYPE_REF
2678      expressions, like those used for ObjC messenger dispatches.  */
2679   function = objc_rewrite_function_call (function, params);
2680
2681   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
2682      Strip such NOP_EXPRs, since FUNCTION is used in non-lvalue context.  */
2683   if (TREE_CODE (function) == NOP_EXPR
2684       && TREE_TYPE (function) == TREE_TYPE (TREE_OPERAND (function, 0)))
2685     function = TREE_OPERAND (function, 0);
2686
2687   if (TREE_CODE (function) == FUNCTION_DECL)
2688     {
2689       name = DECL_NAME (function);
2690
2691       mark_used (function);
2692       fndecl = function;
2693
2694       /* Convert anything with function type to a pointer-to-function.  */
2695       if (pedantic && DECL_MAIN_P (function))
2696         pedwarn ("ISO C++ forbids calling %<::main%> from within program");
2697
2698       /* Differs from default_conversion by not setting TREE_ADDRESSABLE
2699          (because calling an inline function does not mean the function
2700          needs to be separately compiled).  */
2701
2702       if (DECL_INLINE (function))
2703         function = inline_conversion (function);
2704       else
2705         function = build_addr_func (function);
2706     }
2707   else
2708     {
2709       fndecl = NULL_TREE;
2710
2711       function = build_addr_func (function);
2712     }
2713
2714   if (function == error_mark_node)
2715     return error_mark_node;
2716
2717   fntype = TREE_TYPE (function);
2718
2719   if (TYPE_PTRMEMFUNC_P (fntype))
2720     {
2721       error ("must use %<.*%> or %<->*%> to call pointer-to-member "
2722              "function in %<%E (...)%>",
2723              original);
2724       return error_mark_node;
2725     }
2726
2727   is_method = (TREE_CODE (fntype) == POINTER_TYPE
2728                && TREE_CODE (TREE_TYPE (fntype)) == METHOD_TYPE);
2729
2730   if (!((TREE_CODE (fntype) == POINTER_TYPE
2731          && TREE_CODE (TREE_TYPE (fntype)) == FUNCTION_TYPE)
2732         || is_method
2733         || TREE_CODE (function) == TEMPLATE_ID_EXPR))
2734     {
2735       error ("%qE cannot be used as a function", original);
2736       return error_mark_node;
2737     }
2738
2739   /* fntype now gets the type of function pointed to.  */
2740   fntype = TREE_TYPE (fntype);
2741
2742   /* Convert the parameters to the types declared in the
2743      function prototype, or apply default promotions.  */
2744
2745   coerced_params = convert_arguments (TYPE_ARG_TYPES (fntype),
2746                                       params, fndecl, LOOKUP_NORMAL);
2747   if (coerced_params == error_mark_node)
2748     return error_mark_node;
2749
2750   /* Check for errors in format strings and inappropriately
2751      null parameters.  */
2752
2753   check_function_arguments (TYPE_ATTRIBUTES (fntype), coerced_params,
2754                             TYPE_ARG_TYPES (fntype));
2755
2756   return build_cxx_call (function, coerced_params);
2757 }
2758 \f
2759 /* Convert the actual parameter expressions in the list VALUES
2760    to the types in the list TYPELIST.
2761    If parmdecls is exhausted, or when an element has NULL as its type,
2762    perform the default conversions.
2763
2764    NAME is an IDENTIFIER_NODE or 0.  It is used only for error messages.
2765
2766    This is also where warnings about wrong number of args are generated.
2767
2768    Return a list of expressions for the parameters as converted.
2769
2770    Both VALUES and the returned value are chains of TREE_LIST nodes
2771    with the elements of the list in the TREE_VALUE slots of those nodes.
2772
2773    In C++, unspecified trailing parameters can be filled in with their
2774    default arguments, if such were specified.  Do so here.  */
2775
2776 static tree
2777 convert_arguments (tree typelist, tree values, tree fndecl, int flags)
2778 {
2779   tree typetail, valtail;
2780   tree result = NULL_TREE;
2781   const char *called_thing = 0;
2782   int i = 0;
2783
2784   /* Argument passing is always copy-initialization.  */
2785   flags |= LOOKUP_ONLYCONVERTING;
2786
2787   if (fndecl)
2788     {
2789       if (TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE)
2790         {
2791           if (DECL_NAME (fndecl) == NULL_TREE
2792               || IDENTIFIER_HAS_TYPE_VALUE (DECL_NAME (fndecl)))
2793             called_thing = "constructor";
2794           else
2795             called_thing = "member function";
2796         }
2797       else
2798         called_thing = "function";
2799     }
2800
2801   for (valtail = values, typetail = typelist;
2802        valtail;
2803        valtail = TREE_CHAIN (valtail), i++)
2804     {
2805       tree type = typetail ? TREE_VALUE (typetail) : 0;
2806       tree val = TREE_VALUE (valtail);
2807
2808       if (val == error_mark_node || type == error_mark_node)
2809         return error_mark_node;
2810
2811       if (type == void_type_node)
2812         {
2813           if (fndecl)
2814             {
2815               error ("too many arguments to %s %q+#D", called_thing, fndecl);
2816               error ("at this point in file");
2817             }
2818           else
2819             error ("too many arguments to function");
2820           /* In case anybody wants to know if this argument
2821              list is valid.  */
2822           if (result)
2823             TREE_TYPE (tree_last (result)) = error_mark_node;
2824           break;
2825         }
2826
2827       /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
2828          Strip such NOP_EXPRs, since VAL is used in non-lvalue context.  */
2829       if (TREE_CODE (val) == NOP_EXPR
2830           && TREE_TYPE (val) == TREE_TYPE (TREE_OPERAND (val, 0))
2831           && (type == 0 || TREE_CODE (type) != REFERENCE_TYPE))
2832         val = TREE_OPERAND (val, 0);
2833
2834       if (type == 0 || TREE_CODE (type) != REFERENCE_TYPE)
2835         {
2836           if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE
2837               || TREE_CODE (TREE_TYPE (val)) == FUNCTION_TYPE
2838               || TREE_CODE (TREE_TYPE (val)) == METHOD_TYPE)
2839             val = decay_conversion (val);
2840         }
2841
2842       if (val == error_mark_node)
2843         return error_mark_node;
2844
2845       if (type != 0)
2846         {
2847           /* Formal parm type is specified by a function prototype.  */
2848           tree parmval;
2849
2850           if (!COMPLETE_TYPE_P (complete_type (type)))
2851             {
2852               if (fndecl)
2853                 error ("parameter %P of %qD has incomplete type %qT",
2854                        i, fndecl, type);
2855               else
2856                 error ("parameter %P has incomplete type %qT", i, type);
2857               parmval = error_mark_node;
2858             }
2859           else
2860             {
2861               parmval = convert_for_initialization
2862                 (NULL_TREE, type, val, flags,
2863                  "argument passing", fndecl, i);
2864               parmval = convert_for_arg_passing (type, parmval);
2865             }
2866
2867           if (parmval == error_mark_node)
2868             return error_mark_node;
2869
2870           result = tree_cons (NULL_TREE, parmval, result);
2871         }
2872       else
2873         {
2874           if (fndecl && DECL_BUILT_IN (fndecl)
2875               && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CONSTANT_P)
2876             /* Don't do ellipsis conversion for __built_in_constant_p
2877                as this will result in spurious warnings for non-POD
2878                types.  */
2879             val = require_complete_type (val);
2880           else
2881             val = convert_arg_to_ellipsis (val);
2882
2883           result = tree_cons (NULL_TREE, val, result);
2884         }
2885
2886       if (typetail)
2887         typetail = TREE_CHAIN (typetail);
2888     }
2889
2890   if (typetail != 0 && typetail != void_list_node)
2891     {
2892       /* See if there are default arguments that can be used.  */
2893       if (TREE_PURPOSE (typetail)
2894           && TREE_CODE (TREE_PURPOSE (typetail)) != DEFAULT_ARG)
2895         {
2896           for (; typetail != void_list_node; ++i)
2897             {
2898               tree parmval
2899                 = convert_default_arg (TREE_VALUE (typetail),
2900                                        TREE_PURPOSE (typetail),
2901                                        fndecl, i);
2902
2903               if (parmval == error_mark_node)
2904                 return error_mark_node;
2905
2906               result = tree_cons (0, parmval, result);
2907               typetail = TREE_CHAIN (typetail);
2908               /* ends with `...'.  */
2909               if (typetail == NULL_TREE)
2910                 break;
2911             }
2912         }
2913       else
2914         {
2915           if (fndecl)
2916             {
2917               error ("too few arguments to %s %q+#D", called_thing, fndecl);
2918               error ("at this point in file");
2919             }
2920           else
2921             error ("too few arguments to function");
2922           return error_mark_node;
2923         }
2924     }
2925
2926   return nreverse (result);
2927 }
2928 \f
2929 /* Build a binary-operation expression, after performing default
2930    conversions on the operands.  CODE is the kind of expression to
2931    build.  ARG1 and ARG2 are the arguments.  ARG1_CODE and ARG2_CODE
2932    are the tree codes which correspond to ARG1 and ARG2 when issuing
2933    warnings about possibly misplaced parentheses.  They may differ
2934    from the TREE_CODE of ARG1 and ARG2 if the parser has done constant
2935    folding (e.g., if the parser sees "a | 1 + 1", it may call this
2936    routine with ARG2 being an INTEGER_CST and ARG2_CODE == PLUS_EXPR).
2937    To avoid issuing any parentheses warnings, pass ARG1_CODE and/or
2938    ARG2_CODE as ERROR_MARK.  */
2939
2940 tree
2941 build_x_binary_op (enum tree_code code, tree arg1, enum tree_code arg1_code,
2942                    tree arg2, enum tree_code arg2_code, bool *overloaded_p)
2943 {
2944   tree orig_arg1;
2945   tree orig_arg2;
2946   tree expr;
2947
2948   orig_arg1 = arg1;
2949   orig_arg2 = arg2;
2950
2951   if (processing_template_decl)
2952     {
2953       if (type_dependent_expression_p (arg1)
2954           || type_dependent_expression_p (arg2))
2955         return build_min_nt (code, arg1, arg2);
2956       arg1 = build_non_dependent_expr (arg1);
2957       arg2 = build_non_dependent_expr (arg2);
2958     }
2959
2960   if (code == DOTSTAR_EXPR)
2961     expr = build_m_component_ref (arg1, arg2);
2962   else
2963     expr = build_new_op (code, LOOKUP_NORMAL, arg1, arg2, NULL_TREE,
2964                          overloaded_p);
2965
2966   /* Check for cases such as x+y<<z which users are likely to
2967      misinterpret.  But don't warn about obj << x + y, since that is a
2968      common idiom for I/O.  */
2969   if (warn_parentheses
2970       && !processing_template_decl
2971       && !error_operand_p (arg1)
2972       && !error_operand_p (arg2)
2973       && (code != LSHIFT_EXPR
2974           || !CLASS_TYPE_P (TREE_TYPE (arg1))))
2975     warn_about_parentheses (code, arg1_code, arg2_code);
2976
2977   if (processing_template_decl && expr != error_mark_node)
2978     return build_min_non_dep (code, expr, orig_arg1, orig_arg2);
2979
2980   return expr;
2981 }
2982
2983 /* Build a binary-operation expression without default conversions.
2984    CODE is the kind of expression to build.
2985    This function differs from `build' in several ways:
2986    the data type of the result is computed and recorded in it,
2987    warnings are generated if arg data types are invalid,
2988    special handling for addition and subtraction of pointers is known,
2989    and some optimization is done (operations on narrow ints
2990    are done in the narrower type when that gives the same result).
2991    Constant folding is also done before the result is returned.
2992
2993    Note that the operands will never have enumeral types
2994    because either they have just had the default conversions performed
2995    or they have both just been converted to some other type in which
2996    the arithmetic is to be done.
2997
2998    C++: must do special pointer arithmetic when implementing
2999    multiple inheritance, and deal with pointer to member functions.  */
3000
3001 tree
3002 build_binary_op (enum tree_code code, tree orig_op0, tree orig_op1,
3003                  int convert_p ATTRIBUTE_UNUSED)
3004 {
3005   tree op0, op1;
3006   enum tree_code code0, code1;
3007   tree type0, type1;
3008   const char *invalid_op_diag;
3009
3010   /* Expression code to give to the expression when it is built.
3011      Normally this is CODE, which is what the caller asked for,
3012      but in some special cases we change it.  */
3013   enum tree_code resultcode = code;
3014
3015   /* Data type in which the computation is to be performed.
3016      In the simplest cases this is the common type of the arguments.  */
3017   tree result_type = NULL;
3018
3019   /* Nonzero means operands have already been type-converted
3020      in whatever way is necessary.
3021      Zero means they need to be converted to RESULT_TYPE.  */
3022   int converted = 0;
3023
3024   /* Nonzero means create the expression with this type, rather than
3025      RESULT_TYPE.  */
3026   tree build_type = 0;
3027
3028   /* Nonzero means after finally constructing the expression
3029      convert it to this type.  */
3030   tree final_type = 0;
3031
3032   tree result;
3033
3034   /* Nonzero if this is an operation like MIN or MAX which can
3035      safely be computed in short if both args are promoted shorts.
3036      Also implies COMMON.
3037      -1 indicates a bitwise operation; this makes a difference
3038      in the exact conditions for when it is safe to do the operation
3039      in a narrower mode.  */
3040   int shorten = 0;
3041
3042   /* Nonzero if this is a comparison operation;
3043      if both args are promoted shorts, compare the original shorts.
3044      Also implies COMMON.  */
3045   int short_compare = 0;
3046
3047   /* Nonzero if this is a right-shift operation, which can be computed on the
3048      original short and then promoted if the operand is a promoted short.  */
3049   int short_shift = 0;
3050
3051   /* Nonzero means set RESULT_TYPE to the common type of the args.  */
3052   int common = 0;
3053
3054   /* True if both operands have arithmetic type.  */
3055   bool arithmetic_types_p;
3056
3057   /* Apply default conversions.  */
3058   op0 = orig_op0;
3059   op1 = orig_op1;
3060
3061   if (code == TRUTH_AND_EXPR || code == TRUTH_ANDIF_EXPR
3062       || code == TRUTH_OR_EXPR || code == TRUTH_ORIF_EXPR
3063       || code == TRUTH_XOR_EXPR)
3064     {
3065       if (!really_overloaded_fn (op0))
3066         op0 = decay_conversion (op0);
3067       if (!really_overloaded_fn (op1))
3068         op1 = decay_conversion (op1);
3069     }
3070   else
3071     {
3072       if (!really_overloaded_fn (op0))
3073         op0 = default_conversion (op0);
3074       if (!really_overloaded_fn (op1))
3075         op1 = default_conversion (op1);
3076     }
3077
3078   /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue.  */
3079   STRIP_TYPE_NOPS (op0);
3080   STRIP_TYPE_NOPS (op1);
3081
3082   /* DTRT if one side is an overloaded function, but complain about it.  */
3083   if (type_unknown_p (op0))
3084     {
3085       tree t = instantiate_type (TREE_TYPE (op1), op0, tf_none);
3086       if (t != error_mark_node)
3087         {
3088           pedwarn ("assuming cast to type %qT from overloaded function",
3089                    TREE_TYPE (t));
3090           op0 = t;
3091         }
3092     }
3093   if (type_unknown_p (op1))
3094     {
3095       tree t = instantiate_type (TREE_TYPE (op0), op1, tf_none);
3096       if (t != error_mark_node)
3097         {
3098           pedwarn ("assuming cast to type %qT from overloaded function",
3099                    TREE_TYPE (t));
3100           op1 = t;
3101         }
3102     }
3103
3104   type0 = TREE_TYPE (op0);
3105   type1 = TREE_TYPE (op1);
3106
3107   /* The expression codes of the data types of the arguments tell us
3108      whether the arguments are integers, floating, pointers, etc.  */
3109   code0 = TREE_CODE (type0);
3110   code1 = TREE_CODE (type1);
3111
3112   /* If an error was already reported for one of the arguments,
3113      avoid reporting another error.  */
3114
3115   if (code0 == ERROR_MARK || code1 == ERROR_MARK)
3116     return error_mark_node;
3117
3118   if ((invalid_op_diag
3119        = targetm.invalid_binary_op (code, type0, type1)))
3120     {
3121       error (invalid_op_diag);
3122       return error_mark_node;
3123     }
3124
3125   switch (code)
3126     {
3127     case MINUS_EXPR:
3128       /* Subtraction of two similar pointers.
3129          We must subtract them as integers, then divide by object size.  */
3130       if (code0 == POINTER_TYPE && code1 == POINTER_TYPE
3131           && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type0),
3132                                                         TREE_TYPE (type1)))
3133         return pointer_diff (op0, op1, common_type (type0, type1));
3134       /* In all other cases except pointer - int, the usual arithmetic
3135          rules aply.  */
3136       else if (!(code0 == POINTER_TYPE && code1 == INTEGER_TYPE))
3137         {
3138           common = 1;
3139           break;
3140         }
3141       /* The pointer - int case is just like pointer + int; fall
3142          through.  */
3143     case PLUS_EXPR:
3144       if ((code0 == POINTER_TYPE || code1 == POINTER_TYPE)
3145           && (code0 == INTEGER_TYPE || code1 == INTEGER_TYPE))
3146         {
3147           tree ptr_operand;
3148           tree int_operand;
3149           ptr_operand = ((code0 == POINTER_TYPE) ? op0 : op1);
3150           int_operand = ((code0 == INTEGER_TYPE) ? op0 : op1);
3151           if (processing_template_decl)
3152             {
3153               result_type = TREE_TYPE (ptr_operand);
3154               break;
3155             }
3156           return cp_pointer_int_sum (code,
3157                                      ptr_operand, 
3158                                      int_operand);
3159         }
3160       common = 1;
3161       break;
3162
3163     case MULT_EXPR:
3164       common = 1;
3165       break;
3166
3167     case TRUNC_DIV_EXPR:
3168     case CEIL_DIV_EXPR:
3169     case FLOOR_DIV_EXPR:
3170     case ROUND_DIV_EXPR:
3171     case EXACT_DIV_EXPR:
3172       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
3173            || code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE)
3174           && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
3175               || code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE))
3176         {
3177           enum tree_code tcode0 = code0, tcode1 = code1;
3178
3179           if (TREE_CODE (op1) == INTEGER_CST && integer_zerop (op1))
3180             warning (OPT_Wdiv_by_zero, "division by zero in %<%E / 0%>", op0);
3181           else if (TREE_CODE (op1) == REAL_CST && real_zerop (op1))
3182             warning (OPT_Wdiv_by_zero, "division by zero in %<%E / 0.%>", op0);
3183
3184           if (tcode0 == COMPLEX_TYPE || tcode0 == VECTOR_TYPE)
3185             tcode0 = TREE_CODE (TREE_TYPE (TREE_TYPE (op0)));
3186           if (tcode1 == COMPLEX_TYPE || tcode1 == VECTOR_TYPE)
3187             tcode1 = TREE_CODE (TREE_TYPE (TREE_TYPE (op1)));
3188
3189           if (!(tcode0 == INTEGER_TYPE && tcode1 == INTEGER_TYPE))
3190             resultcode = RDIV_EXPR;
3191           else
3192             /* When dividing two signed integers, we have to promote to int.
3193                unless we divide by a constant != -1.  Note that default
3194                conversion will have been performed on the operands at this
3195                point, so we have to dig out the original type to find out if
3196                it was unsigned.  */
3197             shorten = ((TREE_CODE (op0) == NOP_EXPR
3198                         && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op0, 0))))
3199                        || (TREE_CODE (op1) == INTEGER_CST
3200                            && ! integer_all_onesp (op1)));
3201
3202           common = 1;
3203         }
3204       break;
3205
3206     case BIT_AND_EXPR:
3207     case BIT_IOR_EXPR:
3208     case BIT_XOR_EXPR:
3209       if ((code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
3210           || (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE))
3211         shorten = -1;
3212       break;
3213
3214     case TRUNC_MOD_EXPR:
3215     case FLOOR_MOD_EXPR:
3216       if (code1 == INTEGER_TYPE && integer_zerop (op1))
3217         warning (OPT_Wdiv_by_zero, "division by zero in %<%E %% 0%>", op0);
3218       else if (code1 == REAL_TYPE && real_zerop (op1))
3219         warning (OPT_Wdiv_by_zero, "division by zero in %<%E %% 0.%>", op0);
3220
3221       if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
3222         {
3223           /* Although it would be tempting to shorten always here, that loses
3224              on some targets, since the modulo instruction is undefined if the
3225              quotient can't be represented in the computation mode.  We shorten
3226              only if unsigned or if dividing by something we know != -1.  */
3227           shorten = ((TREE_CODE (op0) == NOP_EXPR
3228                       && TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (op0, 0))))
3229                      || (TREE_CODE (op1) == INTEGER_CST
3230                          && ! integer_all_onesp (op1)));
3231           common = 1;
3232         }
3233       break;
3234
3235     case TRUTH_ANDIF_EXPR:
3236     case TRUTH_ORIF_EXPR:
3237     case TRUTH_AND_EXPR:
3238     case TRUTH_OR_EXPR:
3239       result_type = boolean_type_node;
3240       break;
3241
3242       /* Shift operations: result has same type as first operand;
3243          always convert second operand to int.
3244          Also set SHORT_SHIFT if shifting rightward.  */
3245
3246     case RSHIFT_EXPR:
3247       if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
3248         {
3249           result_type = type0;
3250           if (TREE_CODE (op1) == INTEGER_CST)
3251             {
3252               if (tree_int_cst_lt (op1, integer_zero_node))
3253                 warning (0, "right shift count is negative");
3254               else
3255                 {
3256                   if (! integer_zerop (op1))
3257                     short_shift = 1;
3258                   if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0)
3259                     warning (0, "right shift count >= width of type");
3260                 }
3261             }
3262           /* Convert the shift-count to an integer, regardless of
3263              size of value being shifted.  */
3264           if (TYPE_MAIN_VARIANT (TREE_TYPE (op1)) != integer_type_node)
3265             op1 = cp_convert (integer_type_node, op1);
3266           /* Avoid converting op1 to result_type later.  */
3267           converted = 1;
3268         }
3269       break;
3270
3271     case LSHIFT_EXPR:
3272       if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
3273         {
3274           result_type = type0;
3275           if (TREE_CODE (op1) == INTEGER_CST)
3276             {
3277               if (tree_int_cst_lt (op1, integer_zero_node))
3278                 warning (0, "left shift count is negative");
3279               else if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0)
3280                 warning (0, "left shift count >= width of type");
3281             }
3282           /* Convert the shift-count to an integer, regardless of
3283              size of value being shifted.  */
3284           if (TYPE_MAIN_VARIANT (TREE_TYPE (op1)) != integer_type_node)
3285             op1 = cp_convert (integer_type_node, op1);
3286           /* Avoid converting op1 to result_type later.  */
3287           converted = 1;
3288         }
3289       break;
3290
3291     case RROTATE_EXPR:
3292     case LROTATE_EXPR:
3293       if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE)
3294         {
3295           result_type = type0;
3296           if (TREE_CODE (op1) == INTEGER_CST)
3297             {
3298               if (tree_int_cst_lt (op1, integer_zero_node))
3299                 warning (0, (code == LROTATE_EXPR)
3300                             ? G_("left rotate count is negative")
3301                             : G_("right rotate count is negative"));
3302               else if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0)
3303                 warning (0, (code == LROTATE_EXPR) 
3304                             ? G_("left rotate count >= width of type")
3305                             : G_("right rotate count >= width of type"));
3306             }
3307           /* Convert the shift-count to an integer, regardless of
3308              size of value being shifted.  */
3309           if (TYPE_MAIN_VARIANT (TREE_TYPE (op1)) != integer_type_node)
3310             op1 = cp_convert (integer_type_node, op1);
3311         }
3312       break;
3313
3314     case EQ_EXPR:
3315     case NE_EXPR:
3316       if (code0 == REAL_TYPE || code1 == REAL_TYPE)
3317         warning (OPT_Wfloat_equal,
3318                  "comparing floating point with == or != is unsafe");
3319       if ((TREE_CODE (orig_op0) == STRING_CST && !integer_zerop (op1))
3320           || (TREE_CODE (orig_op1) == STRING_CST && !integer_zerop (op0)))
3321         warning (OPT_Wstring_literal_comparison,
3322                  "comparison with string literal");
3323
3324       build_type = boolean_type_node;
3325       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE
3326            || code0 == COMPLEX_TYPE)
3327           && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
3328               || code1 == COMPLEX_TYPE))
3329         short_compare = 1;
3330       else if ((code0 == POINTER_TYPE && code1 == POINTER_TYPE)
3331                || (TYPE_PTRMEM_P (type0) && TYPE_PTRMEM_P (type1)))
3332         result_type = composite_pointer_type (type0, type1, op0, op1,
3333                                               "comparison");
3334       else if ((code0 == POINTER_TYPE || TYPE_PTRMEM_P (type0))
3335                && null_ptr_cst_p (op1))
3336         result_type = type0;
3337       else if ((code1 == POINTER_TYPE || TYPE_PTRMEM_P (type1))
3338                && null_ptr_cst_p (op0))
3339         result_type = type1;
3340       else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
3341         {
3342           result_type = type0;
3343           error ("ISO C++ forbids comparison between pointer and integer");
3344         }
3345       else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
3346         {
3347           result_type = type1;
3348           error ("ISO C++ forbids comparison between pointer and integer");
3349         }
3350       else if (TYPE_PTRMEMFUNC_P (type0) && null_ptr_cst_p (op1))
3351         {
3352           if (TARGET_PTRMEMFUNC_VBIT_LOCATION
3353               == ptrmemfunc_vbit_in_delta)
3354             {
3355               tree pfn0 = pfn_from_ptrmemfunc (op0);
3356               tree delta0 = build_ptrmemfunc_access_expr (op0,
3357                                                           delta_identifier);
3358               tree e1 = cp_build_binary_op (EQ_EXPR,
3359                                             pfn0,       
3360                                             fold_convert (TREE_TYPE (pfn0),
3361                                                           integer_zero_node));
3362               tree e2 = cp_build_binary_op (BIT_AND_EXPR, 
3363                                             delta0,
3364                                             integer_one_node);
3365               e2 = cp_build_binary_op (EQ_EXPR, e2, integer_zero_node);
3366               op0 = cp_build_binary_op (TRUTH_ANDIF_EXPR, e1, e2);
3367               op1 = cp_convert (TREE_TYPE (op0), integer_one_node); 
3368             }
3369           else 
3370             {
3371               op0 = build_ptrmemfunc_access_expr (op0, pfn_identifier);
3372               op1 = cp_convert (TREE_TYPE (op0), integer_zero_node); 
3373             }
3374           result_type = TREE_TYPE (op0);
3375         }
3376       else if (TYPE_PTRMEMFUNC_P (type1) && null_ptr_cst_p (op0))
3377         return cp_build_binary_op (code, op1, op0);
3378       else if (TYPE_PTRMEMFUNC_P (type0) && TYPE_PTRMEMFUNC_P (type1)
3379                && same_type_p (type0, type1))
3380         {
3381           /* E will be the final comparison.  */
3382           tree e;
3383           /* E1 and E2 are for scratch.  */
3384           tree e1;
3385           tree e2;
3386           tree pfn0;
3387           tree pfn1;
3388           tree delta0;
3389           tree delta1;
3390
3391           if (TREE_SIDE_EFFECTS (op0))
3392             op0 = save_expr (op0);
3393           if (TREE_SIDE_EFFECTS (op1))
3394             op1 = save_expr (op1);
3395
3396           pfn0 = pfn_from_ptrmemfunc (op0);
3397           pfn1 = pfn_from_ptrmemfunc (op1);
3398           delta0 = build_ptrmemfunc_access_expr (op0,
3399                                                  delta_identifier);
3400           delta1 = build_ptrmemfunc_access_expr (op1,
3401                                                  delta_identifier);
3402           if (TARGET_PTRMEMFUNC_VBIT_LOCATION
3403               == ptrmemfunc_vbit_in_delta)
3404             {
3405               /* We generate:
3406
3407                  (op0.pfn == op1.pfn
3408                   && ((op0.delta == op1.delta)
3409                        || (!op0.pfn && op0.delta & 1 == 0 
3410                            && op1.delta & 1 == 0))
3411
3412                  The reason for the `!op0.pfn' bit is that a NULL
3413                  pointer-to-member is any member with a zero PFN and
3414                  LSB of the DELTA field is 0.  */
3415
3416               e1 = cp_build_binary_op (BIT_AND_EXPR,
3417                                        delta0, 
3418                                        integer_one_node);
3419               e1 = cp_build_binary_op (EQ_EXPR, e1, integer_zero_node);
3420               e2 = cp_build_binary_op (BIT_AND_EXPR,
3421                                        delta1,
3422                                        integer_one_node);
3423               e2 = cp_build_binary_op (EQ_EXPR, e2, integer_zero_node);
3424               e1 = cp_build_binary_op (TRUTH_ANDIF_EXPR, e2, e1);
3425               e2 = cp_build_binary_op (EQ_EXPR,
3426                                        pfn0,
3427                                        fold_convert (TREE_TYPE (pfn0),
3428                                                      integer_zero_node));
3429               e2 = cp_build_binary_op (TRUTH_ANDIF_EXPR, e2, e1);
3430               e1 = cp_build_binary_op (EQ_EXPR, delta0, delta1);
3431               e1 = cp_build_binary_op (TRUTH_ORIF_EXPR, e1, e2);
3432             }
3433           else
3434             {
3435               /* We generate:
3436
3437                  (op0.pfn == op1.pfn
3438                  && (!op0.pfn || op0.delta == op1.delta))
3439
3440                  The reason for the `!op0.pfn' bit is that a NULL
3441                  pointer-to-member is any member with a zero PFN; the
3442                  DELTA field is unspecified.  */
3443  
3444               e1 = cp_build_binary_op (EQ_EXPR, delta0, delta1);
3445               e2 = cp_build_binary_op (EQ_EXPR,
3446                                        pfn0,
3447                                        fold_convert (TREE_TYPE (pfn0),
3448                                                    integer_zero_node));
3449               e1 = cp_build_binary_op (TRUTH_ORIF_EXPR, e1, e2);
3450             }
3451           e2 = build2 (EQ_EXPR, boolean_type_node, pfn0, pfn1);
3452           e = cp_build_binary_op (TRUTH_ANDIF_EXPR, e2, e1);
3453           if (code == EQ_EXPR)
3454             return e;
3455           return cp_build_binary_op (EQ_EXPR, e, integer_zero_node);
3456         }
3457       else
3458         {
3459           gcc_assert (!TYPE_PTRMEMFUNC_P (type0)
3460                       || !same_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type0),
3461                                        type1));
3462           gcc_assert (!TYPE_PTRMEMFUNC_P (type1)
3463                       || !same_type_p (TYPE_PTRMEMFUNC_FN_TYPE (type1),
3464                                        type0));
3465         }
3466
3467       break;
3468
3469     case MAX_EXPR:
3470     case MIN_EXPR:
3471       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE)
3472            && (code1 == INTEGER_TYPE || code1 == REAL_TYPE))
3473         shorten = 1;
3474       else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
3475         result_type = composite_pointer_type (type0, type1, op0, op1,
3476                                               "comparison");
3477       break;
3478
3479     case LE_EXPR:
3480     case GE_EXPR:
3481     case LT_EXPR:
3482     case GT_EXPR:
3483       if (TREE_CODE (orig_op0) == STRING_CST
3484           || TREE_CODE (orig_op1) == STRING_CST)
3485         warning (OPT_Wstring_literal_comparison,
3486                  "comparison with string literal");
3487
3488       build_type = boolean_type_node;
3489       if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE)
3490            && (code1 == INTEGER_TYPE || code1 == REAL_TYPE))
3491         short_compare = 1;
3492       else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE)
3493         result_type = composite_pointer_type (type0, type1, op0, op1,
3494                                               "comparison");
3495       else if (code0 == POINTER_TYPE && TREE_CODE (op1) == INTEGER_CST
3496                && integer_zerop (op1))
3497         result_type = type0;
3498       else if (code1 == POINTER_TYPE && TREE_CODE (op0) == INTEGER_CST
3499                && integer_zerop (op0))
3500         result_type = type1;
3501       else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE)
3502         {
3503           result_type = type0;
3504           pedwarn ("ISO C++ forbids comparison between pointer and integer");
3505         }
3506       else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE)
3507         {
3508           result_type = type1;
3509           pedwarn ("ISO C++ forbids comparison between pointer and integer");
3510         }
3511       break;
3512
3513     case UNORDERED_EXPR:
3514     case ORDERED_EXPR:
3515     case UNLT_EXPR:
3516     case UNLE_EXPR:
3517     case UNGT_EXPR:
3518     case UNGE_EXPR:
3519     case UNEQ_EXPR:
3520       build_type = integer_type_node;
3521       if (code0 != REAL_TYPE || code1 != REAL_TYPE)
3522         {
3523           error ("unordered comparison on non-floating point argument");
3524           return error_mark_node;
3525         }
3526       common = 1;
3527       break;
3528
3529     default:
3530       break;
3531     }
3532
3533   if (((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE)
3534        && (code1 == INTEGER_TYPE || code1 == REAL_TYPE
3535            || code1 == COMPLEX_TYPE)))
3536     arithmetic_types_p = 1;
3537   else
3538     {
3539       arithmetic_types_p = 0;
3540       /* Vector arithmetic is only allowed when both sides are vectors.  */
3541       if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE)
3542         {
3543           if (!tree_int_cst_equal (TYPE_SIZE (type0), TYPE_SIZE (type1))
3544               || !same_scalar_type_ignoring_signedness (TREE_TYPE (type0),
3545                                                         TREE_TYPE (type1)))
3546             {
3547               binary_op_error (code);
3548               return error_mark_node;
3549             }
3550           arithmetic_types_p = 1;
3551         }
3552     }
3553   /* Determine the RESULT_TYPE, if it is not already known.  */
3554   if (!result_type
3555       && arithmetic_types_p
3556       && (shorten || common || short_compare))
3557     result_type = common_type (type0, type1);
3558
3559   if (!result_type)
3560     {
3561       error ("invalid operands of types %qT and %qT to binary %qO",
3562              TREE_TYPE (orig_op0), TREE_TYPE (orig_op1), code);
3563       return error_mark_node;
3564     }
3565
3566   /* If we're in a template, the only thing we need to know is the
3567      RESULT_TYPE.  */
3568   if (processing_template_decl)
3569     return build2 (resultcode,
3570                    build_type ? build_type : result_type,
3571                    op0, op1);
3572
3573   if (arithmetic_types_p)
3574     {
3575       int none_complex = (code0 != COMPLEX_TYPE && code1 != COMPLEX_TYPE);
3576
3577       /* For certain operations (which identify themselves by shorten != 0)
3578          if both args were extended from the same smaller type,
3579          do the arithmetic in that type and then extend.
3580
3581          shorten !=0 and !=1 indicates a bitwise operation.
3582          For them, this optimization is safe only if
3583          both args are zero-extended or both are sign-extended.
3584          Otherwise, we might change the result.
3585          Eg, (short)-1 | (unsigned short)-1 is (int)-1
3586          but calculated in (unsigned short) it would be (unsigned short)-1.  */
3587
3588       if (shorten && none_complex)
3589         {
3590           int unsigned0, unsigned1;
3591           tree arg0 = get_narrower (op0, &unsigned0);
3592           tree arg1 = get_narrower (op1, &unsigned1);
3593           /* UNS is 1 if the operation to be done is an unsigned one.  */
3594           int uns = TYPE_UNSIGNED (result_type);
3595           tree type;
3596
3597           final_type = result_type;
3598
3599           /* Handle the case that OP0 does not *contain* a conversion
3600              but it *requires* conversion to FINAL_TYPE.  */
3601
3602           if (op0 == arg0 && TREE_TYPE (op0) != final_type)
3603             unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
3604           if (op1 == arg1 && TREE_TYPE (op1) != final_type)
3605             unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
3606
3607           /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE.  */
3608
3609           /* For bitwise operations, signedness of nominal type
3610              does not matter.  Consider only how operands were extended.  */
3611           if (shorten == -1)
3612             uns = unsigned0;
3613
3614           /* Note that in all three cases below we refrain from optimizing
3615              an unsigned operation on sign-extended args.
3616              That would not be valid.  */
3617
3618           /* Both args variable: if both extended in same way
3619              from same width, do it in that width.
3620              Do it unsigned if args were zero-extended.  */
3621           if ((TYPE_PRECISION (TREE_TYPE (arg0))
3622                < TYPE_PRECISION (result_type))
3623               && (TYPE_PRECISION (TREE_TYPE (arg1))
3624                   == TYPE_PRECISION (TREE_TYPE (arg0)))
3625               && unsigned0 == unsigned1
3626               && (unsigned0 || !uns))
3627             result_type = c_common_signed_or_unsigned_type
3628               (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
3629           else if (TREE_CODE (arg0) == INTEGER_CST
3630                    && (unsigned1 || !uns)
3631                    && (TYPE_PRECISION (TREE_TYPE (arg1))
3632                        < TYPE_PRECISION (result_type))
3633                    && (type = c_common_signed_or_unsigned_type
3634                        (unsigned1, TREE_TYPE (arg1)),
3635                        int_fits_type_p (arg0, type)))
3636             result_type = type;
3637           else if (TREE_CODE (arg1) == INTEGER_CST
3638                    && (unsigned0 || !uns)
3639                    && (TYPE_PRECISION (TREE_TYPE (arg0))
3640                        < TYPE_PRECISION (result_type))
3641                    && (type = c_common_signed_or_unsigned_type
3642                        (unsigned0, TREE_TYPE (arg0)),
3643                        int_fits_type_p (arg1, type)))
3644             result_type = type;
3645         }
3646
3647       /* Shifts can be shortened if shifting right.  */
3648
3649       if (short_shift)
3650         {
3651           int unsigned_arg;
3652           tree arg0 = get_narrower (op0, &unsigned_arg);
3653
3654           final_type = result_type;
3655
3656           if (arg0 == op0 && final_type == TREE_TYPE (op0))
3657             unsigned_arg = TYPE_UNSIGNED (TREE_TYPE (op0));
3658
3659           if (TYPE_PRECISION (TREE_TYPE (arg0)) < TYPE_PRECISION (result_type)
3660               /* We can shorten only if the shift count is less than the
3661                  number of bits in the smaller type size.  */
3662               && compare_tree_int (op1, TYPE_PRECISION (TREE_TYPE (arg0))) < 0
3663               /* If arg is sign-extended and then unsigned-shifted,
3664                  we can simulate this with a signed shift in arg's type
3665                  only if the extended result is at least twice as wide
3666                  as the arg.  Otherwise, the shift could use up all the
3667                  ones made by sign-extension and bring in zeros.
3668                  We can't optimize that case at all, but in most machines
3669                  it never happens because available widths are 2**N.  */
3670               && (!TYPE_UNSIGNED (final_type)
3671                   || unsigned_arg
3672                   || (((unsigned) 2 * TYPE_PRECISION (TREE_TYPE (arg0)))
3673                       <= TYPE_PRECISION (result_type))))
3674             {
3675               /* Do an unsigned shift if the operand was zero-extended.  */
3676               result_type
3677                 = c_common_signed_or_unsigned_type (unsigned_arg,
3678                                                     TREE_TYPE (arg0));
3679               /* Convert value-to-be-shifted to that type.  */
3680               if (TREE_TYPE (op0) != result_type)
3681                 op0 = cp_convert (result_type, op0);
3682               converted = 1;
3683             }
3684         }
3685
3686       /* Comparison operations are shortened too but differently.
3687          They identify themselves by setting short_compare = 1.  */
3688
3689       if (short_compare)
3690         {
3691           /* Don't write &op0, etc., because that would prevent op0
3692              from being kept in a register.
3693              Instead, make copies of the our local variables and
3694              pass the copies by reference, then copy them back afterward.  */
3695           tree xop0 = op0, xop1 = op1, xresult_type = result_type;
3696           enum tree_code xresultcode = resultcode;
3697           tree val
3698             = shorten_compare (&xop0, &xop1, &xresult_type, &xresultcode);
3699           if (val != 0)
3700             return cp_convert (boolean_type_node, val);
3701           op0 = xop0, op1 = xop1;
3702           converted = 1;
3703           resultcode = xresultcode;
3704         }
3705
3706       if ((short_compare || code == MIN_EXPR || code == MAX_EXPR)
3707           && warn_sign_compare
3708           /* Do not warn until the template is instantiated; we cannot
3709              bound the ranges of the arguments until that point.  */
3710           && !processing_template_decl)
3711         {
3712           int op0_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op0));
3713           int op1_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op1));
3714
3715           int unsignedp0, unsignedp1;
3716           tree primop0 = get_narrower (op0, &unsignedp0);
3717           tree primop1 = get_narrower (op1, &unsignedp1);
3718
3719           /* Check for comparison of different enum types.  */
3720           if (TREE_CODE (TREE_TYPE (orig_op0)) == ENUMERAL_TYPE
3721               && TREE_CODE (TREE_TYPE (orig_op1)) == ENUMERAL_TYPE
3722               && TYPE_MAIN_VARIANT (TREE_TYPE (orig_op0))
3723                  != TYPE_MAIN_VARIANT (TREE_TYPE (orig_op1)))
3724             {
3725               warning (0, "comparison between types %q#T and %q#T",
3726                        TREE_TYPE (orig_op0), TREE_TYPE (orig_op1));
3727             }
3728
3729           /* Give warnings for comparisons between signed and unsigned
3730              quantities that may fail.  */
3731           /* Do the checking based on the original operand trees, so that
3732              casts will be considered, but default promotions won't be.  */
3733
3734           /* Do not warn if the comparison is being done in a signed type,
3735              since the signed type will only be chosen if it can represent
3736              all the values of the unsigned type.  */
3737           if (!TYPE_UNSIGNED (result_type))
3738             /* OK */;
3739           /* Do not warn if both operands are unsigned.  */
3740           else if (op0_signed == op1_signed)
3741             /* OK */;
3742           /* Do not warn if the signed quantity is an unsuffixed
3743              integer literal (or some static constant expression
3744              involving such literals or a conditional expression
3745              involving such literals) and it is non-negative.  */
3746           else if ((op0_signed && tree_expr_nonnegative_p (orig_op0))
3747                    || (op1_signed && tree_expr_nonnegative_p (orig_op1)))
3748             /* OK */;
3749           /* Do not warn if the comparison is an equality operation,
3750              the unsigned quantity is an integral constant and it does
3751              not use the most significant bit of result_type.  */
3752           else if ((resultcode == EQ_EXPR || resultcode == NE_EXPR)
3753                    && ((op0_signed && TREE_CODE (orig_op1) == INTEGER_CST
3754                         && int_fits_type_p (orig_op1, c_common_signed_type
3755                                             (result_type)))
3756                         || (op1_signed && TREE_CODE (orig_op0) == INTEGER_CST
3757                             && int_fits_type_p (orig_op0, c_common_signed_type
3758                                                 (result_type)))))
3759             /* OK */;
3760           else
3761             warning (0, "comparison between signed and unsigned integer expressions");
3762
3763           /* Warn if two unsigned values are being compared in a size
3764              larger than their original size, and one (and only one) is the
3765              result of a `~' operator.  This comparison will always fail.
3766
3767              Also warn if one operand is a constant, and the constant does not
3768              have all bits set that are set in the ~ operand when it is
3769              extended.  */
3770
3771           if ((TREE_CODE (primop0) == BIT_NOT_EXPR)
3772               ^ (TREE_CODE (primop1) == BIT_NOT_EXPR))
3773             {
3774               if (TREE_CODE (primop0) == BIT_NOT_EXPR)
3775                 primop0 = get_narrower (TREE_OPERAND (op0, 0), &unsignedp0);
3776               if (TREE_CODE (primop1) == BIT_NOT_EXPR)
3777                 primop1 = get_narrower (TREE_OPERAND (op1, 0), &unsignedp1);
3778
3779               if (host_integerp (primop0, 0) || host_integerp (primop1, 0))
3780                 {
3781                   tree primop;
3782                   HOST_WIDE_INT constant, mask;
3783                   int unsignedp;
3784                   unsigned int bits;
3785
3786                   if (host_integerp (primop0, 0))
3787                     {
3788                       primop = primop1;
3789                       unsignedp = unsignedp1;
3790                       constant = tree_low_cst (primop0, 0);
3791                     }
3792                   else
3793                     {
3794                       primop = primop0;
3795                       unsignedp = unsignedp0;
3796                       constant = tree_low_cst (primop1, 0);
3797                     }
3798
3799                   bits = TYPE_PRECISION (TREE_TYPE (primop));
3800                   if (bits < TYPE_PRECISION (result_type)
3801                       && bits < HOST_BITS_PER_LONG && unsignedp)
3802                     {
3803                       mask = (~ (HOST_WIDE_INT) 0) << bits;
3804                       if ((mask & constant) != mask)
3805                         warning (0, "comparison of promoted ~unsigned with constant");
3806                     }
3807                 }
3808               else if (unsignedp0 && unsignedp1
3809                        && (TYPE_PRECISION (TREE_TYPE (primop0))
3810                            < TYPE_PRECISION (result_type))
3811                        && (TYPE_PRECISION (TREE_TYPE (primop1))
3812                            < TYPE_PRECISION (result_type)))
3813                 warning (0, "comparison of promoted ~unsigned with unsigned");
3814             }
3815         }
3816     }
3817
3818   /* If CONVERTED is zero, both args will be converted to type RESULT_TYPE.
3819      Then the expression will be built.
3820      It will be given type FINAL_TYPE if that is nonzero;
3821      otherwise, it will be given type RESULT_TYPE.  */
3822
3823   /* Issue warnings about peculiar, but valid, uses of NULL.  */
3824   if (/* It's reasonable to use pointer values as operands of &&
3825          and ||, so NULL is no exception.  */
3826       !(code == TRUTH_ANDIF_EXPR || code == TRUTH_ORIF_EXPR)
3827       && (/* If OP0 is NULL and OP1 is not a pointer, or vice versa.  */
3828           (orig_op0 == null_node
3829            && TREE_CODE (TREE_TYPE (op1)) != POINTER_TYPE)
3830           /* Or vice versa.  */
3831           || (orig_op1 == null_node
3832               && TREE_CODE (TREE_TYPE (op0)) != POINTER_TYPE)
3833           /* Or, both are NULL and the operation was not a comparison.  */
3834           || (orig_op0 == null_node && orig_op1 == null_node
3835               && code != EQ_EXPR && code != NE_EXPR)))
3836     /* Some sort of arithmetic operation involving NULL was
3837        performed.  Note that pointer-difference and pointer-addition
3838        have already been handled above, and so we don't end up here in
3839        that case.  */
3840     warning (0, "NULL used in arithmetic");
3841
3842   if (! converted)
3843     {
3844       if (TREE_TYPE (op0) != result_type)
3845         op0 = cp_convert (result_type, op0);
3846       if (TREE_TYPE (op1) != result_type)
3847         op1 = cp_convert (result_type, op1);
3848
3849       if (op0 == error_mark_node || op1 == error_mark_node)
3850         return error_mark_node;
3851     }
3852
3853   if (build_type == NULL_TREE)
3854     build_type = result_type;
3855
3856   result = build2 (resultcode, build_type, op0, op1);
3857   result = fold_if_not_in_template (result);
3858   if (final_type != 0)
3859     result = cp_convert (final_type, result);
3860   return result;
3861 }
3862 \f
3863 /* Return a tree for the sum or difference (RESULTCODE says which)
3864    of pointer PTROP and integer INTOP.  */
3865
3866 static tree
3867 cp_pointer_int_sum (enum tree_code resultcode, tree ptrop, tree intop)
3868 {
3869   tree res_type = TREE_TYPE (ptrop);
3870
3871   /* pointer_int_sum() uses size_in_bytes() on the TREE_TYPE(res_type)
3872      in certain circumstance (when it's valid to do so).  So we need
3873      to make sure it's complete.  We don't need to check here, if we
3874      can actually complete it at all, as those checks will be done in
3875      pointer_int_sum() anyway.  */
3876   complete_type (TREE_TYPE (res_type));
3877
3878   return pointer_int_sum (resultcode, ptrop,
3879                           fold_if_not_in_template (intop));
3880 }
3881
3882 /* Return a tree for the difference of pointers OP0 and OP1.
3883    The resulting tree has type int.  */
3884
3885 static tree
3886 pointer_diff (tree op0, tree op1, tree ptrtype)
3887 {
3888   tree result;
3889   tree restype = ptrdiff_type_node;
3890   tree target_type = TREE_TYPE (ptrtype);
3891
3892   if (!complete_type_or_else (target_type, NULL_TREE))
3893     return error_mark_node;
3894
3895   if (pedantic || warn_pointer_arith)
3896     {
3897       if (TREE_CODE (target_type) == VOID_TYPE)
3898         pedwarn ("ISO C++ forbids using pointer of type %<void *%> in subtraction");
3899       if (TREE_CODE (target_type) == FUNCTION_TYPE)
3900         pedwarn ("ISO C++ forbids using pointer to a function in subtraction");
3901       if (TREE_CODE (target_type) == METHOD_TYPE)
3902         pedwarn ("ISO C++ forbids using pointer to a method in subtraction");
3903     }
3904
3905   /* First do the subtraction as integers;
3906      then drop through to build the divide operator.  */
3907
3908   op0 = cp_build_binary_op (MINUS_EXPR,
3909                             cp_convert (restype, op0),
3910                             cp_convert (restype, op1));
3911
3912   /* This generates an error if op1 is a pointer to an incomplete type.  */
3913   if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (op1))))
3914     error ("invalid use of a pointer to an incomplete type in pointer arithmetic");
3915
3916   op1 = (TYPE_PTROB_P (ptrtype)
3917          ? size_in_bytes (target_type)
3918          : integer_one_node);
3919
3920   /* Do the division.  */
3921
3922   result = build2 (EXACT_DIV_EXPR, restype, op0, cp_convert (restype, op1));
3923   return fold_if_not_in_template (result);
3924 }
3925 \f
3926 /* Construct and perhaps optimize a tree representation
3927    for a unary operation.  CODE, a tree_code, specifies the operation
3928    and XARG is the operand.  */
3929
3930 tree
3931 build_x_unary_op (enum tree_code code, tree xarg)
3932 {
3933   tree orig_expr = xarg;
3934   tree exp;
3935   int ptrmem = 0;
3936
3937   if (processing_template_decl)
3938     {
3939       if (type_dependent_expression_p (xarg))
3940         return build_min_nt (code, xarg, NULL_TREE);
3941
3942       xarg = build_non_dependent_expr (xarg);
3943     }
3944
3945   exp = NULL_TREE;
3946
3947   /* [expr.unary.op] says:
3948
3949        The address of an object of incomplete type can be taken.
3950
3951      (And is just the ordinary address operator, not an overloaded
3952      "operator &".)  However, if the type is a template
3953      specialization, we must complete the type at this point so that
3954      an overloaded "operator &" will be available if required.  */
3955   if (code == ADDR_EXPR
3956       && TREE_CODE (xarg) != TEMPLATE_ID_EXPR
3957       && ((CLASS_TYPE_P (TREE_TYPE (xarg))
3958            && !COMPLETE_TYPE_P (complete_type (TREE_TYPE (xarg))))
3959           || (TREE_CODE (xarg) == OFFSET_REF)))
3960     /* Don't look for a function.  */;
3961   else
3962     exp = build_new_op (code, LOOKUP_NORMAL, xarg, NULL_TREE, NULL_TREE,
3963                         /*overloaded_p=*/NULL);
3964   if (!exp && code == ADDR_EXPR)
3965     {
3966       /*  A pointer to member-function can be formed only by saying
3967           &X::mf.  */
3968       if (!flag_ms_extensions && TREE_CODE (TREE_TYPE (xarg)) == METHOD_TYPE
3969           && (TREE_CODE (xarg) != OFFSET_REF || !PTRMEM_OK_P (xarg)))
3970         {
3971           if (TREE_CODE (xarg) != OFFSET_REF
3972               || !TYPE_P (TREE_OPERAND (xarg, 0)))
3973             {
3974               error ("invalid use of %qE to form a pointer-to-member-function",
3975                      xarg);
3976               if (TREE_CODE (xarg) != OFFSET_REF)
3977                 inform ("  a qualified-id is required");
3978               return error_mark_node;
3979             }
3980           else
3981             {
3982               error ("parentheses around %qE cannot be used to form a"
3983                      " pointer-to-member-function",
3984                      xarg);
3985               PTRMEM_OK_P (xarg) = 1;
3986             }
3987         }
3988
3989       if (TREE_CODE (xarg) == OFFSET_REF)
3990         {
3991           ptrmem = PTRMEM_OK_P (xarg);
3992
3993           if (!ptrmem && !flag_ms_extensions
3994               && TREE_CODE (TREE_TYPE (TREE_OPERAND (xarg, 1))) == METHOD_TYPE)
3995             {
3996               /* A single non-static member, make sure we don't allow a
3997                  pointer-to-member.  */
3998               xarg = build2 (OFFSET_REF, TREE_TYPE (xarg),
3999                              TREE_OPERAND (xarg, 0),
4000                              ovl_cons (TREE_OPERAND (xarg, 1), NULL_TREE));
4001               PTRMEM_OK_P (xarg) = ptrmem;
4002             }
4003         }
4004       else if (TREE_CODE (xarg) == TARGET_EXPR)
4005         warning (0, "taking address of temporary");
4006       exp = build_unary_op (ADDR_EXPR, xarg, 0);
4007     }
4008
4009   if (processing_template_decl && exp != error_mark_node)
4010     exp = build_min_non_dep (code, exp, orig_expr,
4011                              /*For {PRE,POST}{INC,DEC}REMENT_EXPR*/NULL_TREE);
4012   if (TREE_CODE (exp) == ADDR_EXPR)
4013     PTRMEM_OK_P (exp) = ptrmem;
4014   return exp;
4015 }
4016
4017 /* Like c_common_truthvalue_conversion, but handle pointer-to-member
4018    constants, where a null value is represented by an INTEGER_CST of
4019    -1.  */
4020
4021 tree
4022 cp_truthvalue_conversion (tree expr)
4023 {
4024   tree type = TREE_TYPE (expr);
4025   if (TYPE_PTRMEM_P (type))
4026     return build_binary_op (NE_EXPR, expr, integer_zero_node, 1);
4027   else
4028     return c_common_truthvalue_conversion (expr);
4029 }
4030
4031 /* Just like cp_truthvalue_conversion, but we want a CLEANUP_POINT_EXPR.  */
4032
4033 tree
4034 condition_conversion (tree expr)
4035 {
4036   tree t;
4037   if (processing_template_decl)
4038     return expr;
4039   t = perform_implicit_conversion (boolean_type_node, expr);
4040   t = fold_build_cleanup_point_expr (boolean_type_node, t);
4041   return t;
4042 }
4043
4044 /* Return an ADDR_EXPR giving the address of T.  This function
4045    attempts no optimizations or simplifications; it is a low-level
4046    primitive.  */
4047
4048 tree
4049 build_address (tree t)
4050 {
4051   tree addr;
4052
4053   if (error_operand_p (t) || !cxx_mark_addressable (t))
4054     return error_mark_node;
4055
4056   addr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (t)), t);
4057
4058   return addr;
4059 }
4060
4061 /* Return a NOP_EXPR converting EXPR to TYPE.  */
4062
4063 tree
4064 build_nop (tree type, tree expr)
4065 {
4066   if (type == error_mark_node || error_operand_p (expr))
4067     return expr;
4068   return build1 (NOP_EXPR, type, expr);
4069 }
4070
4071 /* C++: Must handle pointers to members.
4072
4073    Perhaps type instantiation should be extended to handle conversion
4074    from aggregates to types we don't yet know we want?  (Or are those
4075    cases typically errors which should be reported?)
4076
4077    NOCONVERT nonzero suppresses the default promotions
4078    (such as from short to int).  */
4079
4080 tree
4081 build_unary_op (enum tree_code code, tree xarg, int noconvert)
4082 {
4083   /* No default_conversion here.  It causes trouble for ADDR_EXPR.  */
4084   tree arg = xarg;
4085   tree argtype = 0;
4086   const char *errstring = NULL;
4087   tree val;
4088   const char *invalid_op_diag;
4089
4090   if (arg == error_mark_node)
4091     return error_mark_node;
4092
4093   if ((invalid_op_diag
4094        = targetm.invalid_unary_op ((code == UNARY_PLUS_EXPR
4095                                     ? CONVERT_EXPR
4096                                     : code),
4097                                    TREE_TYPE (xarg))))
4098     {
4099       error (invalid_op_diag);
4100       return error_mark_node;
4101     }
4102
4103   switch (code)
4104     {
4105     case UNARY_PLUS_EXPR:
4106     case NEGATE_EXPR:
4107       {
4108         int flags = WANT_ARITH | WANT_ENUM;
4109         /* Unary plus (but not unary minus) is allowed on pointers.  */
4110         if (code == UNARY_PLUS_EXPR)
4111           flags |= WANT_POINTER;
4112         arg = build_expr_type_conversion (flags, arg, true);
4113         if (!arg)
4114           errstring = (code == NEGATE_EXPR
4115                        ? "wrong type argument to unary minus"
4116                        : "wrong type argument to unary plus");
4117         else
4118           {
4119             if (!noconvert && CP_INTEGRAL_TYPE_P (TREE_TYPE (arg)))
4120               arg = perform_integral_promotions (arg);
4121
4122             /* Make sure the result is not an lvalue: a unary plus or minus
4123                expression is always a rvalue.  */
4124             arg = rvalue (arg);
4125           }
4126       }
4127       break;
4128
4129     case BIT_NOT_EXPR:
4130       if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
4131         {
4132           code = CONJ_EXPR;
4133           if (!noconvert)
4134             arg = default_conversion (arg);
4135         }
4136       else if (!(arg = build_expr_type_conversion (WANT_INT | WANT_ENUM
4137                                                    | WANT_VECTOR,
4138                                                    arg, true)))
4139         errstring = "wrong type argument to bit-complement";
4140       else if (!noconvert && CP_INTEGRAL_TYPE_P (TREE_TYPE (arg)))
4141         arg = perform_integral_promotions (arg);
4142       break;
4143
4144     case ABS_EXPR:
4145       if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_ENUM, arg, true)))
4146         errstring = "wrong type argument to abs";
4147       else if (!noconvert)
4148         arg = default_conversion (arg);
4149       break;
4150
4151     case CONJ_EXPR:
4152       /* Conjugating a real value is a no-op, but allow it anyway.  */
4153       if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_ENUM, arg, true)))
4154         errstring = "wrong type argument to conjugation";
4155       else if (!noconvert)
4156         arg = default_conversion (arg);
4157       break;
4158
4159     case TRUTH_NOT_EXPR:
4160       arg = perform_implicit_conversion (boolean_type_node, arg);
4161       val = invert_truthvalue (arg);
4162       if (arg != error_mark_node)
4163         return val;
4164       errstring = "in argument to unary !";
4165       break;
4166
4167     case NOP_EXPR:
4168       break;
4169
4170     case REALPART_EXPR:
4171       if (TREE_CODE (arg) == COMPLEX_CST)
4172         return TREE_REALPART (arg);
4173       else if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
4174         {
4175           arg = build1 (REALPART_EXPR, TREE_TYPE (TREE_TYPE (arg)), arg);
4176           return fold_if_not_in_template (arg);
4177         }
4178       else
4179         return arg;
4180
4181     case IMAGPART_EXPR:
4182       if (TREE_CODE (arg) == COMPLEX_CST)
4183         return TREE_IMAGPART (arg);
4184       else if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
4185         {
4186           arg = build1 (IMAGPART_EXPR, TREE_TYPE (TREE_TYPE (arg)), arg);
4187           return fold_if_not_in_template (arg);
4188         }
4189       else
4190         return cp_convert (TREE_TYPE (arg), integer_zero_node);
4191
4192     case PREINCREMENT_EXPR:
4193     case POSTINCREMENT_EXPR:
4194     case PREDECREMENT_EXPR:
4195     case POSTDECREMENT_EXPR:
4196       /* Handle complex lvalues (when permitted)
4197          by reduction to simpler cases.  */
4198
4199       val = unary_complex_lvalue (code, arg);
4200       if (val != 0)
4201         return val;
4202
4203       /* Increment or decrement the real part of the value,
4204          and don't change the imaginary part.  */
4205       if (TREE_CODE (TREE_TYPE (arg)) == COMPLEX_TYPE)
4206         {
4207           tree real, imag;
4208
4209           arg = stabilize_reference (arg);
4210           real = build_unary_op (REALPART_EXPR, arg, 1);
4211           imag = build_unary_op (IMAGPART_EXPR, arg, 1);
4212           return build2 (COMPLEX_EXPR, TREE_TYPE (arg),
4213                          build_unary_op (code, real, 1), imag);
4214         }
4215
4216       /* Report invalid types.  */
4217
4218       if (!(arg = build_expr_type_conversion (WANT_ARITH | WANT_POINTER,
4219                                               arg, true)))
4220         {
4221           if (code == PREINCREMENT_EXPR)
4222             errstring ="no pre-increment operator for type";
4223           else if (code == POSTINCREMENT_EXPR)
4224             errstring ="no post-increment operator for type";
4225           else if (code == PREDECREMENT_EXPR)
4226             errstring ="no pre-decrement operator for type";
4227           else
4228             errstring ="no post-decrement operator for type";
4229           break;
4230         }
4231
4232       /* Report something read-only.  */
4233
4234       if (CP_TYPE_CONST_P (TREE_TYPE (arg))
4235           || TREE_READONLY (arg))
4236         readonly_error (arg, ((code == PREINCREMENT_EXPR
4237                                || code == POSTINCREMENT_EXPR)
4238                               ? "increment" : "decrement"),
4239                         0);
4240
4241       {
4242         tree inc;
4243         tree result_type = TREE_TYPE (arg);
4244
4245         arg = get_unwidened (arg, 0);
4246         argtype = TREE_TYPE (arg);
4247
4248         /* ARM $5.2.5 last annotation says this should be forbidden.  */
4249         if (TREE_CODE (argtype) == ENUMERAL_TYPE)
4250           pedwarn ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR)
4251                    ? G_("ISO C++ forbids incrementing an enum")
4252                    : G_("ISO C++ forbids decrementing an enum"));
4253
4254         /* Compute the increment.  */
4255
4256         if (TREE_CODE (argtype) == POINTER_TYPE)
4257           {
4258             tree type = complete_type (TREE_TYPE (argtype));
4259
4260             if (!COMPLETE_OR_VOID_TYPE_P (type))
4261               error (((code == PREINCREMENT_EXPR
4262                        || code == POSTINCREMENT_EXPR))
4263                      ? G_("cannot increment a pointer to incomplete type %qT")
4264                      : G_("cannot decrement a pointer to incomplete type %qT"),
4265                       TREE_TYPE (argtype));
4266             else if ((pedantic || warn_pointer_arith)
4267                      && !TYPE_PTROB_P (argtype))
4268               pedwarn ((code == PREINCREMENT_EXPR
4269                          || code == POSTINCREMENT_EXPR)
4270                        ? G_("ISO C++ forbids incrementing a pointer of type %qT")
4271                        : G_("ISO C++ forbids decrementing a pointer of type %qT"),
4272                         argtype);
4273             inc = cxx_sizeof_nowarn (TREE_TYPE (argtype));
4274           }
4275         else
4276           inc = integer_one_node;
4277
4278         inc = cp_convert (argtype, inc);
4279
4280         /* Handle incrementing a cast-expression.  */
4281
4282         switch (TREE_CODE (arg))
4283           {
4284           case NOP_EXPR:
4285           case CONVERT_EXPR:
4286           case FLOAT_EXPR:
4287           case FIX_TRUNC_EXPR:
4288             {
4289               tree incremented, modify, value, compound;
4290               if (! lvalue_p (arg) && pedantic)
4291                 pedwarn ("cast to non-reference type used as lvalue");
4292               arg = stabilize_reference (arg);
4293               if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
4294                 value = arg;
4295               else
4296                 value = save_expr (arg);
4297               incremented = build2 (((code == PREINCREMENT_EXPR
4298                                       || code == POSTINCREMENT_EXPR)
4299                                      ? PLUS_EXPR : MINUS_EXPR),
4300                                     argtype, value, inc);
4301
4302               modify = build_modify_expr (arg, NOP_EXPR, incremented);
4303               compound = build2 (COMPOUND_EXPR, TREE_TYPE (arg),
4304                                  modify, value);
4305
4306               /* Eliminate warning about unused result of + or -.  */
4307               TREE_NO_WARNING (compound) = 1;
4308               return compound;
4309             }
4310
4311           default:
4312             break;
4313           }
4314
4315         /* Complain about anything else that is not a true lvalue.  */
4316         if (!lvalue_or_else (arg, ((code == PREINCREMENT_EXPR
4317                                     || code == POSTINCREMENT_EXPR)
4318                                    ? lv_increment : lv_decrement)))
4319           return error_mark_node;
4320
4321         /* Forbid using -- on `bool'.  */
4322         if (same_type_p (TREE_TYPE (arg), boolean_type_node))
4323           {
4324             if (code == POSTDECREMENT_EXPR || code == PREDECREMENT_EXPR)
4325               {
4326                 error ("invalid use of %<--%> on bool variable %qD", arg);
4327                 return error_mark_node;
4328               }
4329             val = boolean_increment (code, arg);
4330           }
4331         else
4332           val = build2 (code, TREE_TYPE (arg), arg, inc);
4333
4334         TREE_SIDE_EFFECTS (val) = 1;
4335         return cp_convert (result_type, val);
4336       }
4337
4338     case ADDR_EXPR:
4339       /* Note that this operation never does default_conversion
4340          regardless of NOCONVERT.  */
4341
4342       argtype = lvalue_type (arg);
4343
4344       if (TREE_CODE (arg) == OFFSET_REF)
4345         goto offset_ref;
4346
4347       if (TREE_CODE (argtype) == REFERENCE_TYPE)
4348         {
4349           tree type = build_pointer_type (TREE_TYPE (argtype));
4350           arg = build1 (CONVERT_EXPR, type, arg);
4351           return arg;
4352         }
4353       else if (pedantic && DECL_MAIN_P (arg))
4354         /* ARM $3.4 */
4355         pedwarn ("ISO C++ forbids taking address of function %<::main%>");
4356
4357       /* Let &* cancel out to simplify resulting code.  */
4358       if (TREE_CODE (arg) == INDIRECT_REF)
4359         {
4360           /* We don't need to have `current_class_ptr' wrapped in a
4361              NON_LVALUE_EXPR node.  */
4362           if (arg == current_class_ref)
4363             return current_class_ptr;
4364
4365           arg = TREE_OPERAND (arg, 0);
4366           if (TREE_CODE (TREE_TYPE (arg)) == REFERENCE_TYPE)
4367             {
4368               tree type = build_pointer_type (TREE_TYPE (TREE_TYPE (arg)));
4369               arg = build1 (CONVERT_EXPR, type, arg);
4370             }
4371           else
4372             /* Don't let this be an lvalue.  */
4373             arg = rvalue (arg);
4374           return arg;
4375         }
4376
4377       /* Uninstantiated types are all functions.  Taking the
4378          address of a function is a no-op, so just return the
4379          argument.  */
4380
4381       gcc_assert (TREE_CODE (arg) != IDENTIFIER_NODE
4382                   || !IDENTIFIER_OPNAME_P (arg));
4383
4384       if (TREE_CODE (arg) == COMPONENT_REF && type_unknown_p (arg)
4385           && !really_overloaded_fn (TREE_OPERAND (arg, 1)))
4386         {
4387           /* They're trying to take the address of a unique non-static
4388              member function.  This is ill-formed (except in MS-land),
4389              but let's try to DTRT.
4390              Note: We only handle unique functions here because we don't
4391              want to complain if there's a static overload; non-unique
4392              cases will be handled by instantiate_type.  But we need to
4393              handle this case here to allow casts on the resulting PMF.
4394              We could defer this in non-MS mode, but it's easier to give
4395              a useful error here.  */
4396
4397           /* Inside constant member functions, the `this' pointer
4398              contains an extra const qualifier.  TYPE_MAIN_VARIANT
4399              is used here to remove this const from the diagnostics
4400              and the created OFFSET_REF.  */
4401           tree base = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (arg, 0)));
4402           tree fn = get_first_fn (TREE_OPERAND (arg, 1));
4403           mark_used (fn);
4404
4405           if (! flag_ms_extensions)
4406             {
4407               tree name = DECL_NAME (fn);
4408               if (current_class_type
4409                   && TREE_OPERAND (arg, 0) == current_class_ref)
4410                 /* An expression like &memfn.  */
4411                 pedwarn ("ISO C++ forbids taking the address of an unqualified"
4412                          " or parenthesized non-static member function to form"
4413                          " a pointer to member function.  Say %<&%T::%D%>",
4414                          base, name);
4415               else
4416                 pedwarn ("ISO C++ forbids taking the address of a bound member"
4417                          " function to form a pointer to member function."
4418                          "  Say %<&%T::%D%>",
4419                          base, name);
4420             }
4421           arg = build_offset_ref (base, fn, /*address_p=*/true);
4422         }
4423
4424     offset_ref:
4425       if (type_unknown_p (arg))
4426         return build1 (ADDR_EXPR, unknown_type_node, arg);
4427
4428       /* Handle complex lvalues (when permitted)
4429          by reduction to simpler cases.  */
4430       val = unary_complex_lvalue (code, arg);
4431       if (val != 0)
4432         return val;
4433
4434       switch (TREE_CODE (arg))
4435         {
4436         case NOP_EXPR:
4437         case CONVERT_EXPR:
4438         case FLOAT_EXPR:
4439         case FIX_TRUNC_EXPR:
4440           if (! lvalue_p (arg) && pedantic)
4441             pedwarn ("ISO C++ forbids taking the address of a cast to a non-lvalue expression");
4442           break;
4443
4444         case BASELINK:
4445           arg = BASELINK_FUNCTIONS (arg);
4446           /* Fall through.  */
4447
4448         case OVERLOAD:
4449           arg = OVL_CURRENT (arg);
4450           break;
4451
4452         case OFFSET_REF:
4453           /* Turn a reference to a non-static data member into a
4454              pointer-to-member.  */
4455           {
4456             tree type;
4457             tree t;
4458
4459             if (!PTRMEM_OK_P (arg))
4460               return build_unary_op (code, arg, 0);
4461
4462             t = TREE_OPERAND (arg, 1);
4463             if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
4464               {
4465                 error ("cannot create pointer to reference member %qD", t);
4466                 return error_mark_node;
4467               }
4468
4469             type = build_ptrmem_type (context_for_name_lookup (t),
4470                                       TREE_TYPE (t));
4471             t = make_ptrmem_cst (type, TREE_OPERAND (arg, 1));
4472             return t;
4473           }
4474
4475         default:
4476           break;
4477         }
4478
4479       /* Anything not already handled and not a true memory reference
4480          is an error.  */
4481       if (TREE_CODE (argtype) != FUNCTION_TYPE
4482           && TREE_CODE (argtype) != METHOD_TYPE
4483           && TREE_CODE (arg) != OFFSET_REF
4484           && !lvalue_or_else (arg, lv_addressof))
4485         return error_mark_node;
4486
4487       if (argtype != error_mark_node)
4488         argtype = build_pointer_type (argtype);
4489
4490       /* In a template, we are processing a non-dependent expression
4491          so we can just form an ADDR_EXPR with the correct type.  */
4492       if (processing_template_decl)
4493         {
4494           val = build_address (arg);
4495           if (TREE_CODE (arg) == OFFSET_REF)
4496             PTRMEM_OK_P (val) = PTRMEM_OK_P (arg);
4497           return val;
4498         }
4499
4500       if (TREE_CODE (arg) != COMPONENT_REF)
4501         {
4502           val = build_address (arg);
4503           if (TREE_CODE (arg) == OFFSET_REF)
4504             PTRMEM_OK_P (val) = PTRMEM_OK_P (arg);
4505         }
4506       else if (TREE_CODE (TREE_OPERAND (arg, 1)) == BASELINK)
4507         {
4508           tree fn = BASELINK_FUNCTIONS (TREE_OPERAND (arg, 1));
4509
4510           /* We can only get here with a single static member
4511              function.  */
4512           gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
4513                       && DECL_STATIC_FUNCTION_P (fn));
4514           mark_used (fn);
4515           val = build_address (fn);
4516           if (TREE_SIDE_EFFECTS (TREE_OPERAND (arg, 0)))
4517             /* Do not lose object's side effects.  */
4518             val = build2 (COMPOUND_EXPR, TREE_TYPE (val),
4519                           TREE_OPERAND (arg, 0), val);
4520         }
4521       else if (DECL_C_BIT_FIELD (TREE_OPERAND (arg, 1)))
4522         {
4523           error ("attempt to take address of bit-field structure member %qD",
4524                  TREE_OPERAND (arg, 1));
4525           return error_mark_node;
4526         }
4527       else
4528         {
4529           tree object = TREE_OPERAND (arg, 0);
4530           tree field = TREE_OPERAND (arg, 1);
4531           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4532                       (TREE_TYPE (object), decl_type_context (field)));
4533           val = build_address (arg);
4534         }
4535
4536       if (TREE_CODE (argtype) == POINTER_TYPE
4537           && TREE_CODE (TREE_TYPE (argtype)) == METHOD_TYPE)
4538         {
4539           build_ptrmemfunc_type (argtype);
4540           val = build_ptrmemfunc (argtype, val, 0,
4541                                   /*c_cast_p=*/false);
4542         }
4543
4544       return val;
4545
4546     default:
4547       break;
4548     }
4549
4550   if (!errstring)
4551     {
4552       if (argtype == 0)
4553         argtype = TREE_TYPE (arg);
4554       return fold_if_not_in_template (build1 (code, argtype, arg));
4555     }
4556
4557   error ("%s", errstring);
4558   return error_mark_node;
4559 }
4560
4561 /* Apply unary lvalue-demanding operator CODE to the expression ARG
4562    for certain kinds of expressions which are not really lvalues
4563    but which we can accept as lvalues.
4564
4565    If ARG is not a kind of expression we can handle, return
4566    NULL_TREE.  */
4567
4568 tree
4569 unary_complex_lvalue (enum tree_code code, tree arg)
4570 {
4571   /* Inside a template, making these kinds of adjustments is
4572      pointless; we are only concerned with the type of the
4573      expression.  */
4574   if (processing_template_decl)
4575     return NULL_TREE;
4576
4577   /* Handle (a, b) used as an "lvalue".  */
4578   if (TREE_CODE (arg) == COMPOUND_EXPR)
4579     {
4580       tree real_result = build_unary_op (code, TREE_OPERAND (arg, 1), 0);
4581       return build2 (COMPOUND_EXPR, TREE_TYPE (real_result),
4582                      TREE_OPERAND (arg, 0), real_result);
4583     }
4584
4585   /* Handle (a ? b : c) used as an "lvalue".  */
4586   if (TREE_CODE (arg) == COND_EXPR
4587       || TREE_CODE (arg) == MIN_EXPR || TREE_CODE (arg) == MAX_EXPR)
4588     return rationalize_conditional_expr (code, arg);
4589
4590   /* Handle (a = b), (++a), and (--a) used as an "lvalue".  */
4591   if (TREE_CODE (arg) == MODIFY_EXPR
4592       || TREE_CODE (arg) == PREINCREMENT_EXPR
4593       || TREE_CODE (arg) == PREDECREMENT_EXPR)
4594     {
4595       tree lvalue = TREE_OPERAND (arg, 0);
4596       if (TREE_SIDE_EFFECTS (lvalue))
4597         {
4598           lvalue = stabilize_reference (lvalue);
4599           arg = build2 (TREE_CODE (arg), TREE_TYPE (arg),
4600                         lvalue, TREE_OPERAND (arg, 1));
4601         }
4602       return unary_complex_lvalue
4603         (code, build2 (COMPOUND_EXPR, TREE_TYPE (lvalue), arg, lvalue));
4604     }
4605
4606   if (code != ADDR_EXPR)
4607     return NULL_TREE;
4608
4609   /* Handle (a = b) used as an "lvalue" for `&'.  */
4610   if (TREE_CODE (arg) == MODIFY_EXPR
4611       || TREE_CODE (arg) == INIT_EXPR)
4612     {
4613       tree real_result = build_unary_op (code, TREE_OPERAND (arg, 0), 0);
4614       arg = build2 (COMPOUND_EXPR, TREE_TYPE (real_result),
4615                     arg, real_result);
4616       TREE_NO_WARNING (arg) = 1;
4617       return arg;
4618     }
4619
4620   if (TREE_CODE (TREE_TYPE (arg)) == FUNCTION_TYPE
4621       || TREE_CODE (TREE_TYPE (arg)) == METHOD_TYPE
4622       || TREE_CODE (arg) == OFFSET_REF)
4623     return NULL_TREE;
4624
4625   /* We permit compiler to make function calls returning
4626      objects of aggregate type look like lvalues.  */
4627   {
4628     tree targ = arg;
4629
4630     if (TREE_CODE (targ) == SAVE_EXPR)
4631       targ = TREE_OPERAND (targ, 0);
4632
4633     if (TREE_CODE (targ) == CALL_EXPR && IS_AGGR_TYPE (TREE_TYPE (targ)))
4634       {
4635         if (TREE_CODE (arg) == SAVE_EXPR)
4636           targ = arg;
4637         else
4638           targ = build_cplus_new (TREE_TYPE (arg), arg);
4639         return build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (arg)), targ);
4640       }
4641
4642     if (TREE_CODE (arg) == SAVE_EXPR && TREE_CODE (targ) == INDIRECT_REF)
4643       return build3 (SAVE_EXPR, build_pointer_type (TREE_TYPE (arg)),
4644                      TREE_OPERAND (targ, 0), current_function_decl, NULL);
4645   }
4646
4647   /* Don't let anything else be handled specially.  */
4648   return NULL_TREE;
4649 }
4650 \f
4651 /* Mark EXP saying that we need to be able to take the
4652    address of it; it should not be allocated in a register.
4653    Value is true if successful.
4654
4655    C++: we do not allow `current_class_ptr' to be addressable.  */
4656
4657 bool
4658 cxx_mark_addressable (tree exp)
4659 {
4660   tree x = exp;
4661
4662   while (1)
4663     switch (TREE_CODE (x))
4664       {
4665       case ADDR_EXPR:
4666       case COMPONENT_REF:
4667       case ARRAY_REF:
4668       case REALPART_EXPR:
4669       case IMAGPART_EXPR:
4670         x = TREE_OPERAND (x, 0);
4671         break;
4672
4673       case PARM_DECL:
4674         if (x == current_class_ptr)
4675           {
4676             error ("cannot take the address of %<this%>, which is an rvalue expression");
4677             TREE_ADDRESSABLE (x) = 1; /* so compiler doesn't die later.  */
4678             return true;
4679           }
4680         /* Fall through.  */
4681
4682       case VAR_DECL:
4683         /* Caller should not be trying to mark initialized
4684            constant fields addressable.  */
4685         gcc_assert (DECL_LANG_SPECIFIC (x) == 0
4686                     || DECL_IN_AGGR_P (x) == 0
4687                     || TREE_STATIC (x)
4688                     || DECL_EXTERNAL (x));
4689         /* Fall through.  */
4690
4691       case CONST_DECL:
4692       case RESULT_DECL:
4693         if (DECL_REGISTER (x) && !TREE_ADDRESSABLE (x)
4694             && !DECL_ARTIFICIAL (x))
4695           {
4696             if (TREE_CODE (x) == VAR_DECL && DECL_HARD_REGISTER (x))
4697               {
4698                 error
4699                   ("address of explicit register variable %qD requested", x);
4700                 return false;
4701               }
4702             else if (extra_warnings)
4703               warning
4704                 (OPT_Wextra, "address requested for %qD, which is declared %<register%>", x);
4705           }
4706         TREE_ADDRESSABLE (x) = 1;
4707         return true;
4708
4709       case FUNCTION_DECL:
4710         TREE_ADDRESSABLE (x) = 1;
4711         return true;
4712
4713       case CONSTRUCTOR:
4714         TREE_ADDRESSABLE (x) = 1;
4715         return true;
4716
4717       case TARGET_EXPR:
4718         TREE_ADDRESSABLE (x) = 1;
4719         cxx_mark_addressable (TREE_OPERAND (x, 0));
4720         return true;
4721
4722       default:
4723         return true;
4724     }
4725 }
4726 \f
4727 /* Build and return a conditional expression IFEXP ? OP1 : OP2.  */
4728
4729 tree
4730 build_x_conditional_expr (tree ifexp, tree op1, tree op2)
4731 {
4732   tree orig_ifexp = ifexp;
4733   tree orig_op1 = op1;
4734   tree orig_op2 = op2;
4735   tree expr;
4736
4737   if (processing_template_decl)
4738     {
4739       /* The standard says that the expression is type-dependent if
4740          IFEXP is type-dependent, even though the eventual type of the
4741          expression doesn't dependent on IFEXP.  */
4742       if (type_dependent_expression_p (ifexp)
4743           /* As a GNU extension, the middle operand may be omitted.  */
4744           || (op1 && type_dependent_expression_p (op1))
4745           || type_dependent_expression_p (op2))
4746         return build_min_nt (COND_EXPR, ifexp, op1, op2);
4747       ifexp = build_non_dependent_expr (ifexp);
4748       if (op1)
4749         op1 = build_non_dependent_expr (op1);
4750       op2 = build_non_dependent_expr (op2);
4751     }
4752
4753   expr = build_conditional_expr (ifexp, op1, op2);
4754   if (processing_template_decl && expr != error_mark_node)
4755     return build_min_non_dep (COND_EXPR, expr,
4756                               orig_ifexp, orig_op1, orig_op2);
4757   return expr;
4758 }
4759 \f
4760 /* Given a list of expressions, return a compound expression
4761    that performs them all and returns the value of the last of them.  */
4762
4763 tree build_x_compound_expr_from_list (tree list, const char *msg)
4764 {
4765   tree expr = TREE_VALUE (list);
4766
4767   if (TREE_CHAIN (list))
4768     {
4769       if (msg)
4770         pedwarn ("%s expression list treated as compound expression", msg);
4771
4772       for (list = TREE_CHAIN (list); list; list = TREE_CHAIN (list))
4773         expr = build_x_compound_expr (expr, TREE_VALUE (list));
4774     }
4775
4776   return expr;
4777 }
4778
4779 /* Handle overloading of the ',' operator when needed.  */
4780
4781 tree
4782 build_x_compound_expr (tree op1, tree op2)
4783 {
4784   tree result;
4785   tree orig_op1 = op1;
4786   tree orig_op2 = op2;
4787
4788   if (processing_template_decl)
4789     {
4790       if (type_dependent_expression_p (op1)
4791           || type_dependent_expression_p (op2))
4792         return build_min_nt (COMPOUND_EXPR, op1, op2);
4793       op1 = build_non_dependent_expr (op1);
4794       op2 = build_non_dependent_expr (op2);
4795     }
4796
4797   result = build_new_op (COMPOUND_EXPR, LOOKUP_NORMAL, op1, op2, NULL_TREE,
4798                          /*overloaded_p=*/NULL);
4799   if (!result)
4800     result = build_compound_expr (op1, op2);
4801
4802   if (processing_template_decl && result != error_mark_node)
4803     return build_min_non_dep (COMPOUND_EXPR, result, orig_op1, orig_op2);
4804
4805   return result;
4806 }
4807
4808 /* Build a compound expression.  */
4809
4810 tree
4811 build_compound_expr (tree lhs, tree rhs)
4812 {
4813   lhs = convert_to_void (lhs, "left-hand operand of comma");
4814
4815   if (lhs == error_mark_node || rhs == error_mark_node)
4816     return error_mark_node;
4817
4818   if (TREE_CODE (rhs) == TARGET_EXPR)
4819     {
4820       /* If the rhs is a TARGET_EXPR, then build the compound
4821          expression inside the target_expr's initializer. This
4822          helps the compiler to eliminate unnecessary temporaries.  */
4823       tree init = TREE_OPERAND (rhs, 1);
4824
4825       init = build2 (COMPOUND_EXPR, TREE_TYPE (init), lhs, init);
4826       TREE_OPERAND (rhs, 1) = init;
4827
4828       return rhs;
4829     }
4830
4831   return build2 (COMPOUND_EXPR, TREE_TYPE (rhs), lhs, rhs);
4832 }
4833
4834 /* Issue a diagnostic message if casting from SRC_TYPE to DEST_TYPE
4835    casts away constness.  DIAG_FN gives the function to call if we
4836    need to issue a diagnostic; if it is NULL, no diagnostic will be
4837    issued.  DESCRIPTION explains what operation is taking place.  */
4838
4839 static void
4840 check_for_casting_away_constness (tree src_type, tree dest_type,
4841                                   void (*diag_fn)(const char *, ...) ATTRIBUTE_GCC_CXXDIAG(1,2),
4842                                   const char *description)
4843 {
4844   if (diag_fn && casts_away_constness (src_type, dest_type))
4845     diag_fn ("%s from type %qT to type %qT casts away constness",
4846              description, src_type, dest_type);
4847 }
4848
4849 /* Convert EXPR (an expression with pointer-to-member type) to TYPE
4850    (another pointer-to-member type in the same hierarchy) and return
4851    the converted expression.  If ALLOW_INVERSE_P is permitted, a
4852    pointer-to-derived may be converted to pointer-to-base; otherwise,
4853    only the other direction is permitted.  If C_CAST_P is true, this
4854    conversion is taking place as part of a C-style cast.  */
4855
4856 tree
4857 convert_ptrmem (tree type, tree expr, bool allow_inverse_p,
4858                 bool c_cast_p)
4859 {
4860   if (TYPE_PTRMEM_P (type))
4861     {
4862       tree delta;
4863
4864       if (TREE_CODE (expr) == PTRMEM_CST)
4865         expr = cplus_expand_constant (expr);
4866       delta = get_delta_difference (TYPE_PTRMEM_CLASS_TYPE (TREE_TYPE (expr)),
4867                                     TYPE_PTRMEM_CLASS_TYPE (type),
4868                                     allow_inverse_p,
4869                                     c_cast_p);
4870       if (!integer_zerop (delta))
4871         expr = cp_build_binary_op (PLUS_EXPR,
4872                                    build_nop (ptrdiff_type_node, expr),
4873                                    delta);
4874       return build_nop (type, expr);
4875     }
4876   else
4877     return build_ptrmemfunc (TYPE_PTRMEMFUNC_FN_TYPE (type), expr,
4878                              allow_inverse_p, c_cast_p);
4879 }
4880
4881 /* If EXPR is an INTEGER_CST and ORIG is an arithmetic constant, return
4882    a version of EXPR that has TREE_OVERFLOW and/or TREE_CONSTANT_OVERFLOW
4883    set iff they are set in ORIG.  Otherwise, return EXPR unchanged.  */
4884
4885 static tree
4886 ignore_overflows (tree expr, tree orig)
4887 {
4888   if (TREE_CODE (expr) == INTEGER_CST
4889       && CONSTANT_CLASS_P (orig)
4890       && TREE_CODE (orig) != STRING_CST
4891       && (TREE_OVERFLOW (expr) != TREE_OVERFLOW (orig)
4892           || TREE_CONSTANT_OVERFLOW (expr)
4893              != TREE_CONSTANT_OVERFLOW (orig)))
4894     {
4895       if (!TREE_OVERFLOW (orig) && !TREE_CONSTANT_OVERFLOW (orig))
4896         /* Ensure constant sharing.  */
4897         expr = build_int_cst_wide (TREE_TYPE (expr),
4898                                    TREE_INT_CST_LOW (expr),
4899                                    TREE_INT_CST_HIGH (expr));
4900       else
4901         {
4902           /* Avoid clobbering a shared constant.  */
4903           expr = copy_node (expr);
4904           TREE_OVERFLOW (expr) = TREE_OVERFLOW (orig);
4905           TREE_CONSTANT_OVERFLOW (expr)
4906             = TREE_CONSTANT_OVERFLOW (orig);
4907         }
4908     }
4909   return expr;
4910 }
4911
4912 /* Perform a static_cast from EXPR to TYPE.  When C_CAST_P is true,
4913    this static_cast is being attempted as one of the possible casts
4914    allowed by a C-style cast.  (In that case, accessibility of base
4915    classes is not considered, and it is OK to cast away
4916    constness.)  Return the result of the cast.  *VALID_P is set to
4917    indicate whether or not the cast was valid.  */
4918
4919 static tree
4920 build_static_cast_1 (tree type, tree expr, bool c_cast_p,
4921                      bool *valid_p)
4922 {
4923   tree intype;
4924   tree result;
4925   tree orig;
4926   void (*diag_fn)(const char*, ...) ATTRIBUTE_GCC_CXXDIAG(1,2);
4927   const char *desc;
4928
4929   /* Assume the cast is valid.  */
4930   *valid_p = true;
4931
4932   intype = TREE_TYPE (expr);
4933
4934   /* Save casted types in the function's used types hash table.  */
4935   used_types_insert (type);
4936
4937   /* Determine what to do when casting away constness.  */
4938   if (c_cast_p)
4939     {
4940       /* C-style casts are allowed to cast away constness.  With
4941          WARN_CAST_QUAL, we still want to issue a warning.  */
4942       diag_fn = warn_cast_qual ? warning0 : NULL;
4943       desc = "cast";
4944     }
4945   else
4946     {
4947       /* A static_cast may not cast away constness.  */
4948       diag_fn = error;
4949       desc = "static_cast";
4950     }
4951
4952   /* [expr.static.cast]
4953
4954      An lvalue of type "cv1 B", where B is a class type, can be cast
4955      to type "reference to cv2 D", where D is a class derived (clause
4956      _class.derived_) from B, if a valid standard conversion from
4957      "pointer to D" to "pointer to B" exists (_conv.ptr_), cv2 is the
4958      same cv-qualification as, or greater cv-qualification than, cv1,
4959      and B is not a virtual base class of D.  */
4960   /* We check this case before checking the validity of "TYPE t =
4961      EXPR;" below because for this case:
4962
4963        struct B {};
4964        struct D : public B { D(const B&); };
4965        extern B& b;
4966        void f() { static_cast<const D&>(b); }
4967
4968      we want to avoid constructing a new D.  The standard is not
4969      completely clear about this issue, but our interpretation is
4970      consistent with other compilers.  */
4971   if (TREE_CODE (type) == REFERENCE_TYPE
4972       && CLASS_TYPE_P (TREE_TYPE (type))
4973       && CLASS_TYPE_P (intype)
4974       && real_lvalue_p (expr)
4975       && DERIVED_FROM_P (intype, TREE_TYPE (type))
4976       && can_convert (build_pointer_type (TYPE_MAIN_VARIANT (intype)),
4977                       build_pointer_type (TYPE_MAIN_VARIANT
4978                                           (TREE_TYPE (type))))
4979       && (c_cast_p
4980           || at_least_as_qualified_p (TREE_TYPE (type), intype)))
4981     {
4982       tree base;
4983
4984       /* There is a standard conversion from "D*" to "B*" even if "B"
4985          is ambiguous or inaccessible.  If this is really a
4986          static_cast, then we check both for inaccessibility and
4987          ambiguity.  However, if this is a static_cast being performed
4988          because the user wrote a C-style cast, then accessibility is
4989          not considered.  */
4990       base = lookup_base (TREE_TYPE (type), intype,
4991                           c_cast_p ? ba_unique : ba_check,
4992                           NULL);
4993
4994       /* Convert from "B*" to "D*".  This function will check that "B"
4995          is not a virtual base of "D".  */
4996       expr = build_base_path (MINUS_EXPR, build_address (expr),
4997                               base, /*nonnull=*/false);
4998       /* Convert the pointer to a reference -- but then remember that
4999          there are no expressions with reference type in C++.  */
5000       return convert_from_reference (build_nop (type, expr));
5001     }
5002
5003   orig = expr;
5004
5005   /* [expr.static.cast]
5006
5007      An expression e can be explicitly converted to a type T using a
5008      static_cast of the form static_cast<T>(e) if the declaration T
5009      t(e);" is well-formed, for some invented temporary variable
5010      t.  */
5011   result = perform_direct_initialization_if_possible (type, expr,
5012                                                       c_cast_p);
5013   if (result)
5014     {
5015       result = convert_from_reference (result);
5016
5017       /* Ignore any integer overflow caused by the cast.  */
5018       result = ignore_overflows (result, orig);
5019
5020       /* [expr.static.cast]
5021
5022          If T is a reference type, the result is an lvalue; otherwise,
5023          the result is an rvalue.  */
5024       if (TREE_CODE (type) != REFERENCE_TYPE)
5025         result = rvalue (result);
5026       return result;
5027     }
5028
5029   /* [expr.static.cast]
5030
5031      Any expression can be explicitly converted to type cv void.  */
5032   if (TREE_CODE (type) == VOID_TYPE)
5033     return convert_to_void (expr, /*implicit=*/NULL);
5034
5035   /* [expr.static.cast]
5036
5037      The inverse of any standard conversion sequence (clause _conv_),
5038      other than the lvalue-to-rvalue (_conv.lval_), array-to-pointer
5039      (_conv.array_), function-to-pointer (_conv.func_), and boolean
5040      (_conv.bool_) conversions, can be performed explicitly using
5041      static_cast subject to the restriction that the explicit
5042      conversion does not cast away constness (_expr.const.cast_), and
5043      the following additional rules for specific cases:  */
5044   /* For reference, the conversions not excluded are: integral
5045      promotions, floating point promotion, integral conversions,
5046      floating point conversions, floating-integral conversions,
5047      pointer conversions, and pointer to member conversions.  */
5048   /* DR 128
5049
5050      A value of integral _or enumeration_ type can be explicitly
5051      converted to an enumeration type.  */
5052   /* The effect of all that is that any conversion between any two
5053      types which are integral, floating, or enumeration types can be
5054      performed.  */
5055   if ((INTEGRAL_TYPE_P (type) || SCALAR_FLOAT_TYPE_P (type))
5056       && (INTEGRAL_TYPE_P (intype) || SCALAR_FLOAT_TYPE_P (intype)))
5057     {
5058       expr = ocp_convert (type, expr, CONV_C_CAST, LOOKUP_NORMAL);
5059
5060       /* Ignore any integer overflow caused by the cast.  */
5061       expr = ignore_overflows (expr, orig);
5062       return expr;
5063     }
5064
5065   if (TYPE_PTR_P (type) && TYPE_PTR_P (intype)
5066       && CLASS_TYPE_P (TREE_TYPE (type))
5067       && CLASS_TYPE_P (TREE_TYPE (intype))
5068       && can_convert (build_pointer_type (TYPE_MAIN_VARIANT
5069                                           (TREE_TYPE (intype))),
5070                       build_pointer_type (TYPE_MAIN_VARIANT
5071                                           (TREE_TYPE (type)))))
5072     {
5073       tree base;
5074
5075       if (!c_cast_p)
5076         check_for_casting_away_constness (intype, type, diag_fn, desc);
5077       base = lookup_base (TREE_TYPE (type), TREE_TYPE (intype),
5078                           c_cast_p ? ba_unique : ba_check,
5079                           NULL);
5080       return build_base_path (MINUS_EXPR, expr, base, /*nonnull=*/false);
5081     }
5082
5083   if ((TYPE_PTRMEM_P (type) && TYPE_PTRMEM_P (intype))
5084       || (TYPE_PTRMEMFUNC_P (type) && TYPE_PTRMEMFUNC_P (intype)))
5085     {
5086       tree c1;
5087       tree c2;
5088       tree t1;
5089       tree t2;
5090
5091       c1 = TYPE_PTRMEM_CLASS_TYPE (intype);
5092       c2 = TYPE_PTRMEM_CLASS_TYPE (type);
5093
5094       if (TYPE_PTRMEM_P (type))
5095         {
5096           t1 = (build_ptrmem_type
5097                 (c1,
5098                  TYPE_MAIN_VARIANT (TYPE_PTRMEM_POINTED_TO_TYPE (intype))));
5099           t2 = (build_ptrmem_type
5100                 (c2,
5101                  TYPE_MAIN_VARIANT (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
5102         }
5103       else
5104         {
5105           t1 = intype;
5106           t2 = type;
5107         }
5108       if (can_convert (t1, t2))
5109         {
5110           if (!c_cast_p)
5111             check_for_casting_away_constness (intype, type, diag_fn,
5112                                               desc);
5113           return convert_ptrmem (type, expr, /*allow_inverse_p=*/1,
5114                                  c_cast_p);
5115         }
5116     }
5117
5118   /* [expr.static.cast]
5119
5120      An rvalue of type "pointer to cv void" can be explicitly
5121      converted to a pointer to object type.  A value of type pointer
5122      to object converted to "pointer to cv void" and back to the
5123      original pointer type will have its original value.  */
5124   if (TREE_CODE (intype) == POINTER_TYPE
5125       && VOID_TYPE_P (TREE_TYPE (intype))
5126       && TYPE_PTROB_P (type))
5127     {
5128       if (!c_cast_p)
5129         check_for_casting_away_constness (intype, type, diag_fn, desc);
5130       return build_nop (type, expr);
5131     }
5132
5133   *valid_p = false;
5134   return error_mark_node;
5135 }
5136
5137 /* Return an expression representing static_cast<TYPE>(EXPR).  */
5138
5139 tree
5140 build_static_cast (tree type, tree expr)
5141 {
5142   tree result;
5143   bool valid_p;
5144
5145   if (type == error_mark_node || expr == error_mark_node)
5146     return error_mark_node;
5147
5148   if (processing_template_decl)
5149     {
5150       expr = build_min (STATIC_CAST_EXPR, type, expr);
5151       /* We don't know if it will or will not have side effects.  */
5152       TREE_SIDE_EFFECTS (expr) = 1;
5153       return convert_from_reference (expr);
5154     }
5155
5156   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
5157      Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
5158   if (TREE_CODE (type) != REFERENCE_TYPE
5159       && TREE_CODE (expr) == NOP_EXPR
5160       && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
5161     expr = TREE_OPERAND (expr, 0);
5162
5163   result = build_static_cast_1 (type, expr, /*c_cast_p=*/false, &valid_p);
5164   if (valid_p)
5165     return result;
5166
5167   error ("invalid static_cast from type %qT to type %qT",
5168          TREE_TYPE (expr), type);
5169   return error_mark_node;
5170 }
5171
5172 /* EXPR is an expression with member function or pointer-to-member
5173    function type.  TYPE is a pointer type.  Converting EXPR to TYPE is
5174    not permitted by ISO C++, but we accept it in some modes.  If we
5175    are not in one of those modes, issue a diagnostic.  Return the
5176    converted expression.  */
5177
5178 tree
5179 convert_member_func_to_ptr (tree type, tree expr)
5180 {
5181   tree intype;
5182   tree decl;
5183
5184   intype = TREE_TYPE (expr);
5185   gcc_assert (TYPE_PTRMEMFUNC_P (intype)
5186               || TREE_CODE (intype) == METHOD_TYPE);
5187
5188   if (pedantic || warn_pmf2ptr)
5189     pedwarn ("converting from %qT to %qT", intype, type);
5190
5191   if (TREE_CODE (intype) == METHOD_TYPE)
5192     expr = build_addr_func (expr);
5193   else if (TREE_CODE (expr) == PTRMEM_CST)
5194     expr = build_address (PTRMEM_CST_MEMBER (expr));
5195   else
5196     {
5197       decl = maybe_dummy_object (TYPE_PTRMEM_CLASS_TYPE (intype), 0);
5198       decl = build_address (decl);
5199       expr = get_member_function_from_ptrfunc (&decl, expr);
5200     }
5201
5202   return build_nop (type, expr);
5203 }
5204
5205 /* Return a representation for a reinterpret_cast from EXPR to TYPE.
5206    If C_CAST_P is true, this reinterpret cast is being done as part of
5207    a C-style cast.  If VALID_P is non-NULL, *VALID_P is set to
5208    indicate whether or not reinterpret_cast was valid.  */
5209
5210 static tree
5211 build_reinterpret_cast_1 (tree type, tree expr, bool c_cast_p,
5212                           bool *valid_p)
5213 {
5214   tree intype;
5215
5216   /* Assume the cast is invalid.  */
5217   if (valid_p)
5218     *valid_p = true;
5219
5220   if (type == error_mark_node || error_operand_p (expr))
5221     return error_mark_node;
5222
5223   intype = TREE_TYPE (expr);
5224
5225   /* Save casted types in the function's used types hash table.  */
5226   used_types_insert (type);
5227
5228   /* [expr.reinterpret.cast]
5229      An lvalue expression of type T1 can be cast to the type
5230      "reference to T2" if an expression of type "pointer to T1" can be
5231      explicitly converted to the type "pointer to T2" using a
5232      reinterpret_cast.  */
5233   if (TREE_CODE (type) == REFERENCE_TYPE)
5234     {
5235       if (! real_lvalue_p (expr))
5236         {
5237           error ("invalid cast of an rvalue expression of type "
5238                  "%qT to type %qT",
5239                  intype, type);
5240           return error_mark_node;
5241         }
5242
5243       /* Warn about a reinterpret_cast from "A*" to "B&" if "A" and
5244          "B" are related class types; the reinterpret_cast does not
5245          adjust the pointer.  */
5246       if (TYPE_PTR_P (intype)
5247           && (comptypes (TREE_TYPE (intype), TREE_TYPE (type),
5248                          COMPARE_BASE | COMPARE_DERIVED)))
5249         warning (0, "casting %qT to %qT does not dereference pointer",
5250                  intype, type);
5251
5252       expr = build_unary_op (ADDR_EXPR, expr, 0);
5253       if (expr != error_mark_node)
5254         expr = build_reinterpret_cast_1
5255           (build_pointer_type (TREE_TYPE (type)), expr, c_cast_p,
5256            valid_p);
5257       if (expr != error_mark_node)
5258         expr = build_indirect_ref (expr, 0);
5259       return expr;
5260     }
5261
5262   /* As a G++ extension, we consider conversions from member
5263      functions, and pointers to member functions to
5264      pointer-to-function and pointer-to-void types.  If
5265      -Wno-pmf-conversions has not been specified,
5266      convert_member_func_to_ptr will issue an error message.  */
5267   if ((TYPE_PTRMEMFUNC_P (intype)
5268        || TREE_CODE (intype) == METHOD_TYPE)
5269       && TYPE_PTR_P (type)
5270       && (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE
5271           || VOID_TYPE_P (TREE_TYPE (type))))
5272     return convert_member_func_to_ptr (type, expr);
5273
5274   /* If the cast is not to a reference type, the lvalue-to-rvalue,
5275      array-to-pointer, and function-to-pointer conversions are
5276      performed.  */
5277   expr = decay_conversion (expr);
5278
5279   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
5280      Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
5281   if (TREE_CODE (expr) == NOP_EXPR
5282       && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
5283     expr = TREE_OPERAND (expr, 0);
5284
5285   if (error_operand_p (expr))
5286     return error_mark_node;
5287
5288   intype = TREE_TYPE (expr);
5289
5290   /* [expr.reinterpret.cast]
5291      A pointer can be converted to any integral type large enough to
5292      hold it.  */
5293   if (CP_INTEGRAL_TYPE_P (type) && TYPE_PTR_P (intype))
5294     {
5295       if (TYPE_PRECISION (type) < TYPE_PRECISION (intype))
5296         pedwarn ("cast from %qT to %qT loses precision",
5297                  intype, type);
5298     }
5299   /* [expr.reinterpret.cast]
5300      A value of integral or enumeration type can be explicitly
5301      converted to a pointer.  */
5302   else if (TYPE_PTR_P (type) && INTEGRAL_OR_ENUMERATION_TYPE_P (intype))
5303     /* OK */
5304     ;
5305   else if ((TYPE_PTRFN_P (type) && TYPE_PTRFN_P (intype))
5306            || (TYPE_PTRMEMFUNC_P (type) && TYPE_PTRMEMFUNC_P (intype)))
5307     return fold_if_not_in_template (build_nop (type, expr));
5308   else if ((TYPE_PTRMEM_P (type) && TYPE_PTRMEM_P (intype))
5309            || (TYPE_PTROBV_P (type) && TYPE_PTROBV_P (intype)))
5310     {
5311       tree sexpr = expr;
5312
5313       if (!c_cast_p)
5314         check_for_casting_away_constness (intype, type, error,
5315                                           "reinterpret_cast");
5316       /* Warn about possible alignment problems.  */
5317       if (STRICT_ALIGNMENT && warn_cast_align
5318           && !VOID_TYPE_P (type)
5319           && TREE_CODE (TREE_TYPE (intype)) != FUNCTION_TYPE
5320           && COMPLETE_TYPE_P (TREE_TYPE (type))
5321           && COMPLETE_TYPE_P (TREE_TYPE (intype))
5322           && TYPE_ALIGN (TREE_TYPE (type)) > TYPE_ALIGN (TREE_TYPE (intype)))
5323         warning (0, "cast from %qT to %qT increases required alignment of "
5324                  "target type",
5325                  intype, type);
5326
5327       /* We need to strip nops here, because the frontend likes to
5328          create (int *)&a for array-to-pointer decay, instead of &a[0].  */
5329       STRIP_NOPS (sexpr);
5330       strict_aliasing_warning (intype, type, sexpr);
5331
5332       return fold_if_not_in_template (build_nop (type, expr));
5333     }
5334   else if ((TYPE_PTRFN_P (type) && TYPE_PTROBV_P (intype))
5335            || (TYPE_PTRFN_P (intype) && TYPE_PTROBV_P (type)))
5336     {
5337       if (pedantic)
5338         /* Only issue a warning, as we have always supported this
5339            where possible, and it is necessary in some cases.  DR 195
5340            addresses this issue, but as of 2004/10/26 is still in
5341            drafting.  */
5342         warning (0, "ISO C++ forbids casting between pointer-to-function and pointer-to-object");
5343       return fold_if_not_in_template (build_nop (type, expr));
5344     }
5345   else if (TREE_CODE (type) == VECTOR_TYPE)
5346     return fold_if_not_in_template (convert_to_vector (type, expr));
5347   else if (TREE_CODE (intype) == VECTOR_TYPE)
5348     return fold_if_not_in_template (convert_to_integer (type, expr));
5349   else
5350     {
5351       if (valid_p)
5352         *valid_p = false;
5353       error ("invalid cast from type %qT to type %qT", intype, type);
5354       return error_mark_node;
5355     }
5356
5357   return cp_convert (type, expr);
5358 }
5359
5360 tree
5361 build_reinterpret_cast (tree type, tree expr)
5362 {
5363   if (type == error_mark_node || expr == error_mark_node)
5364     return error_mark_node;
5365
5366   if (processing_template_decl)
5367     {
5368       tree t = build_min (REINTERPRET_CAST_EXPR, type, expr);
5369
5370       if (!TREE_SIDE_EFFECTS (t)
5371           && type_dependent_expression_p (expr))
5372         /* There might turn out to be side effects inside expr.  */
5373         TREE_SIDE_EFFECTS (t) = 1;
5374       return convert_from_reference (t);
5375     }
5376
5377   return build_reinterpret_cast_1 (type, expr, /*c_cast_p=*/false,
5378                                    /*valid_p=*/NULL);
5379 }
5380
5381 /* Perform a const_cast from EXPR to TYPE.  If the cast is valid,
5382    return an appropriate expression.  Otherwise, return
5383    error_mark_node.  If the cast is not valid, and COMPLAIN is true,
5384    then a diagnostic will be issued.  If VALID_P is non-NULL, we are
5385    performing a C-style cast, its value upon return will indicate
5386    whether or not the conversion succeeded.  */
5387
5388 static tree
5389 build_const_cast_1 (tree dst_type, tree expr, bool complain,
5390                     bool *valid_p)
5391 {
5392   tree src_type;
5393   tree reference_type;
5394
5395   /* Callers are responsible for handling error_mark_node as a
5396      destination type.  */
5397   gcc_assert (dst_type != error_mark_node);
5398   /* In a template, callers should be building syntactic
5399      representations of casts, not using this machinery.  */
5400   gcc_assert (!processing_template_decl);
5401
5402   /* Assume the conversion is invalid.  */
5403   if (valid_p)
5404     *valid_p = false;
5405
5406   if (!POINTER_TYPE_P (dst_type) && !TYPE_PTRMEM_P (dst_type))
5407     {
5408       if (complain)
5409         error ("invalid use of const_cast with type %qT, "
5410                "which is not a pointer, "
5411                "reference, nor a pointer-to-data-member type", dst_type);
5412       return error_mark_node;
5413     }
5414
5415   if (TREE_CODE (TREE_TYPE (dst_type)) == FUNCTION_TYPE)
5416     {
5417       if (complain)
5418         error ("invalid use of const_cast with type %qT, which is a pointer "
5419                "or reference to a function type", dst_type);
5420       return error_mark_node;
5421     }
5422
5423   /* Save casted types in the function's used types hash table.  */
5424   used_types_insert (dst_type);
5425
5426   src_type = TREE_TYPE (expr);
5427   /* Expressions do not really have reference types.  */
5428   if (TREE_CODE (src_type) == REFERENCE_TYPE)
5429     src_type = TREE_TYPE (src_type);
5430
5431   /* [expr.const.cast]
5432
5433      An lvalue of type T1 can be explicitly converted to an lvalue of
5434      type T2 using the cast const_cast<T2&> (where T1 and T2 are object
5435      types) if a pointer to T1 can be explicitly converted to the type
5436      pointer to T2 using a const_cast.  */
5437   if (TREE_CODE (dst_type) == REFERENCE_TYPE)
5438     {
5439       reference_type = dst_type;
5440       if (! real_lvalue_p (expr))
5441         {
5442           if (complain)
5443             error ("invalid const_cast of an rvalue of type %qT to type %qT",
5444                    src_type, dst_type);
5445           return error_mark_node;
5446         }
5447       dst_type = build_pointer_type (TREE_TYPE (dst_type));
5448       src_type = build_pointer_type (src_type);
5449     }
5450   else
5451     {
5452       reference_type = NULL_TREE;
5453       /* If the destination type is not a reference type, the
5454          lvalue-to-rvalue, array-to-pointer, and function-to-pointer
5455          conversions are performed.  */
5456       src_type = type_decays_to (src_type);
5457       if (src_type == error_mark_node)
5458         return error_mark_node;
5459     }
5460
5461   if ((TYPE_PTR_P (src_type) || TYPE_PTRMEM_P (src_type))
5462       && comp_ptr_ttypes_const (dst_type, src_type))
5463     {
5464       if (valid_p)
5465         {
5466           *valid_p = true;
5467           /* This cast is actually a C-style cast.  Issue a warning if
5468              the user is making a potentially unsafe cast.  */
5469           if (warn_cast_qual)
5470             check_for_casting_away_constness (src_type, dst_type,
5471                                               warning0,
5472                                               "cast");
5473         }
5474       if (reference_type)
5475         {
5476           expr = build_unary_op (ADDR_EXPR, expr, 0);
5477           expr = build_nop (reference_type, expr);
5478           return convert_from_reference (expr);
5479         }
5480       else
5481         {
5482           expr = decay_conversion (expr);
5483           /* build_c_cast puts on a NOP_EXPR to make the result not an
5484              lvalue.  Strip such NOP_EXPRs if VALUE is being used in
5485              non-lvalue context.  */
5486           if (TREE_CODE (expr) == NOP_EXPR
5487               && TREE_TYPE (expr) == TREE_TYPE (TREE_OPERAND (expr, 0)))
5488             expr = TREE_OPERAND (expr, 0);
5489           return build_nop (dst_type, expr);
5490         }
5491     }
5492
5493   if (complain)
5494     error ("invalid const_cast from type %qT to type %qT",
5495            src_type, dst_type);
5496   return error_mark_node;
5497 }
5498
5499 tree
5500 build_const_cast (tree type, tree expr)
5501 {
5502   if (type == error_mark_node || error_operand_p (expr))
5503     return error_mark_node;
5504
5505   if (processing_template_decl)
5506     {
5507       tree t = build_min (CONST_CAST_EXPR, type, expr);
5508
5509       if (!TREE_SIDE_EFFECTS (t)
5510           && type_dependent_expression_p (expr))
5511         /* There might turn out to be side effects inside expr.  */
5512         TREE_SIDE_EFFECTS (t) = 1;
5513       return convert_from_reference (t);
5514     }
5515
5516   return build_const_cast_1 (type, expr, /*complain=*/true,
5517                              /*valid_p=*/NULL);
5518 }
5519
5520 /* Build an expression representing an explicit C-style cast to type
5521    TYPE of expression EXPR.  */
5522
5523 tree
5524 build_c_cast (tree type, tree expr)
5525 {
5526   tree value = expr;
5527   tree result;
5528   bool valid_p;
5529
5530   if (type == error_mark_node || error_operand_p (expr))
5531     return error_mark_node;
5532
5533   if (processing_template_decl)
5534     {
5535       tree t = build_min (CAST_EXPR, type,
5536                           tree_cons (NULL_TREE, value, NULL_TREE));
5537       /* We don't know if it will or will not have side effects.  */
5538       TREE_SIDE_EFFECTS (t) = 1;
5539       return convert_from_reference (t);
5540     }
5541
5542   /* Casts to a (pointer to a) specific ObjC class (or 'id' or
5543      'Class') should always be retained, because this information aids
5544      in method lookup.  */
5545   if (objc_is_object_ptr (type)
5546       && objc_is_object_ptr (TREE_TYPE (expr)))
5547     return build_nop (type, expr);
5548
5549   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
5550      Strip such NOP_EXPRs if VALUE is being used in non-lvalue context.  */
5551   if (TREE_CODE (type) != REFERENCE_TYPE
5552       && TREE_CODE (value) == NOP_EXPR
5553       && TREE_TYPE (value) == TREE_TYPE (TREE_OPERAND (value, 0)))
5554     value = TREE_OPERAND (value, 0);
5555
5556   if (TREE_CODE (type) == ARRAY_TYPE)
5557     {
5558       /* Allow casting from T1* to T2[] because Cfront allows it.
5559          NIHCL uses it. It is not valid ISO C++ however.  */
5560       if (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE)
5561         {
5562           pedwarn ("ISO C++ forbids casting to an array type %qT", type);
5563           type = build_pointer_type (TREE_TYPE (type));
5564         }
5565       else
5566         {
5567           error ("ISO C++ forbids casting to an array type %qT", type);
5568           return error_mark_node;
5569         }
5570     }
5571
5572   if (TREE_CODE (type) == FUNCTION_TYPE
5573       || TREE_CODE (type) == METHOD_TYPE)
5574     {
5575       error ("invalid cast to function type %qT", type);
5576       return error_mark_node;
5577     }
5578
5579   /* A C-style cast can be a const_cast.  */
5580   result = build_const_cast_1 (type, value, /*complain=*/false,
5581                                &valid_p);
5582   if (valid_p)
5583     return result;
5584
5585   /* Or a static cast.  */
5586   result = build_static_cast_1 (type, value, /*c_cast_p=*/true,
5587                                 &valid_p);
5588   /* Or a reinterpret_cast.  */
5589   if (!valid_p)
5590     result = build_reinterpret_cast_1 (type, value, /*c_cast_p=*/true,
5591                                        &valid_p);
5592   /* The static_cast or reinterpret_cast may be followed by a
5593      const_cast.  */
5594   if (valid_p
5595       /* A valid cast may result in errors if, for example, a
5596          conversion to am ambiguous base class is required.  */
5597       && !error_operand_p (result))
5598     {
5599       tree result_type;
5600
5601       /* Non-class rvalues always have cv-unqualified type.  */
5602       if (!CLASS_TYPE_P (type))
5603         type = TYPE_MAIN_VARIANT (type);
5604       result_type = TREE_TYPE (result);
5605       if (!CLASS_TYPE_P (result_type))
5606         result_type = TYPE_MAIN_VARIANT (result_type);
5607       /* If the type of RESULT does not match TYPE, perform a
5608          const_cast to make it match.  If the static_cast or
5609          reinterpret_cast succeeded, we will differ by at most
5610          cv-qualification, so the follow-on const_cast is guaranteed
5611          to succeed.  */
5612       if (!same_type_p (non_reference (type), non_reference (result_type)))
5613         {
5614           result = build_const_cast_1 (type, result, false, &valid_p);
5615           gcc_assert (valid_p);
5616         }
5617       return result;
5618     }
5619
5620   return error_mark_node;
5621 }
5622 \f
5623 /* Build an assignment expression of lvalue LHS from value RHS.
5624    MODIFYCODE is the code for a binary operator that we use
5625    to combine the old value of LHS with RHS to get the new value.
5626    Or else MODIFYCODE is NOP_EXPR meaning do a simple assignment.
5627
5628    C++: If MODIFYCODE is INIT_EXPR, then leave references unbashed.  */
5629
5630 tree
5631 build_modify_expr (tree lhs, enum tree_code modifycode, tree rhs)
5632 {
5633   tree result;
5634   tree newrhs = rhs;
5635   tree lhstype = TREE_TYPE (lhs);
5636   tree olhstype = lhstype;
5637   tree olhs = NULL_TREE;
5638   bool plain_assign = (modifycode == NOP_EXPR);
5639
5640   /* Avoid duplicate error messages from operands that had errors.  */
5641   if (error_operand_p (lhs) || error_operand_p (rhs))
5642     return error_mark_node;
5643
5644   /* Handle control structure constructs used as "lvalues".  */
5645   switch (TREE_CODE (lhs))
5646     {
5647       /* Handle --foo = 5; as these are valid constructs in C++.  */
5648     case PREDECREMENT_EXPR:
5649     case PREINCREMENT_EXPR:
5650       if (TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0)))
5651         lhs = build2 (TREE_CODE (lhs), TREE_TYPE (lhs),
5652                       stabilize_reference (TREE_OPERAND (lhs, 0)),
5653                       TREE_OPERAND (lhs, 1));
5654       return build2 (COMPOUND_EXPR, lhstype,
5655                      lhs,
5656                      build_modify_expr (TREE_OPERAND (lhs, 0),
5657                                         modifycode, rhs));
5658
5659       /* Handle (a, b) used as an "lvalue".  */
5660     case COMPOUND_EXPR:
5661       newrhs = build_modify_expr (TREE_OPERAND (lhs, 1),
5662                                   modifycode, rhs);
5663       if (newrhs == error_mark_node)
5664         return error_mark_node;
5665       return build2 (COMPOUND_EXPR, lhstype,
5666                      TREE_OPERAND (lhs, 0), newrhs);
5667
5668     case MODIFY_EXPR:
5669       if (TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0)))
5670         lhs = build2 (TREE_CODE (lhs), TREE_TYPE (lhs),
5671                       stabilize_reference (TREE_OPERAND (lhs, 0)),
5672                       TREE_OPERAND (lhs, 1));
5673       newrhs = build_modify_expr (TREE_OPERAND (lhs, 0), modifycode, rhs);
5674       if (newrhs == error_mark_node)
5675         return error_mark_node;
5676       return build2 (COMPOUND_EXPR, lhstype, lhs, newrhs);
5677
5678     case MIN_EXPR:
5679     case MAX_EXPR:
5680       /* MIN_EXPR and MAX_EXPR are currently only permitted as lvalues,
5681          when neither operand has side-effects.  */
5682       if (!lvalue_or_else (lhs, lv_assign))
5683         return error_mark_node;
5684
5685       gcc_assert (!TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 0))
5686                   && !TREE_SIDE_EFFECTS (TREE_OPERAND (lhs, 1)));
5687
5688       lhs = build3 (COND_EXPR, TREE_TYPE (lhs),
5689                     build2 (TREE_CODE (lhs) == MIN_EXPR ? LE_EXPR : GE_EXPR,
5690                             boolean_type_node,
5691                             TREE_OPERAND (lhs, 0),
5692                             TREE_OPERAND (lhs, 1)),
5693                     TREE_OPERAND (lhs, 0),
5694                     TREE_OPERAND (lhs, 1));
5695       /* Fall through.  */
5696
5697       /* Handle (a ? b : c) used as an "lvalue".  */
5698     case COND_EXPR:
5699       {
5700         /* Produce (a ? (b = rhs) : (c = rhs))
5701            except that the RHS goes through a save-expr
5702            so the code to compute it is only emitted once.  */
5703         tree cond;
5704         tree preeval = NULL_TREE;
5705
5706         rhs = stabilize_expr (rhs, &preeval);
5707
5708         /* Check this here to avoid odd errors when trying to convert
5709            a throw to the type of the COND_EXPR.  */
5710         if (!lvalue_or_else (lhs, lv_assign))
5711           return error_mark_node;
5712
5713         cond = build_conditional_expr
5714           (TREE_OPERAND (lhs, 0),
5715            build_modify_expr (TREE_OPERAND (lhs, 1),
5716                               modifycode, rhs),
5717            build_modify_expr (TREE_OPERAND (lhs, 2),
5718                               modifycode, rhs));
5719
5720         if (cond == error_mark_node)
5721           return cond;
5722         /* Make sure the code to compute the rhs comes out
5723            before the split.  */
5724         if (preeval)
5725           cond = build2 (COMPOUND_EXPR, TREE_TYPE (lhs), preeval, cond);
5726         return cond;
5727       }
5728
5729     default:
5730       break;
5731     }
5732
5733   if (modifycode == INIT_EXPR)
5734     {
5735       if (TREE_CODE (rhs) == CONSTRUCTOR)
5736         {
5737           if (! same_type_p (TREE_TYPE (rhs), lhstype))
5738             /* Call convert to generate an error; see PR 11063.  */
5739             rhs = convert (lhstype, rhs);
5740           result = build2 (INIT_EXPR, lhstype, lhs, rhs);
5741           TREE_SIDE_EFFECTS (result) = 1;
5742           return result;
5743         }
5744       else if (! IS_AGGR_TYPE (lhstype))
5745         /* Do the default thing.  */;
5746       else
5747         {
5748           result = build_special_member_call (lhs, complete_ctor_identifier,
5749                                               build_tree_list (NULL_TREE, rhs),
5750                                               lhstype, LOOKUP_NORMAL);
5751           if (result == NULL_TREE)
5752             return error_mark_node;
5753           return result;
5754         }
5755     }
5756   else
5757     {
5758       lhs = require_complete_type (lhs);
5759       if (lhs == error_mark_node)
5760         return error_mark_node;
5761
5762       if (modifycode == NOP_EXPR)
5763         {
5764           /* `operator=' is not an inheritable operator.  */
5765           if (! IS_AGGR_TYPE (lhstype))
5766             /* Do the default thing.  */;
5767           else
5768             {
5769               result = build_new_op (MODIFY_EXPR, LOOKUP_NORMAL,
5770                                      lhs, rhs, make_node (NOP_EXPR),
5771                                      /*overloaded_p=*/NULL);
5772               if (result == NULL_TREE)
5773                 return error_mark_node;
5774               return result;
5775             }
5776           lhstype = olhstype;
5777         }
5778       else
5779         {
5780           /* A binary op has been requested.  Combine the old LHS
5781              value with the RHS producing the value we should actually
5782              store into the LHS.  */
5783
5784           gcc_assert (!PROMOTES_TO_AGGR_TYPE (lhstype, REFERENCE_TYPE));
5785           lhs = stabilize_reference (lhs);
5786           newrhs = cp_build_binary_op (modifycode, lhs, rhs);
5787           if (newrhs == error_mark_node)
5788             {
5789               error ("  in evaluation of %<%Q(%#T, %#T)%>", modifycode,
5790                      TREE_TYPE (lhs), TREE_TYPE (rhs));
5791               return error_mark_node;
5792             }
5793
5794           /* Now it looks like a plain assignment.  */
5795           modifycode = NOP_EXPR;
5796         }
5797       gcc_assert (TREE_CODE (lhstype) != REFERENCE_TYPE);
5798       gcc_assert (TREE_CODE (TREE_TYPE (newrhs)) != REFERENCE_TYPE);
5799     }
5800
5801   /* The left-hand side must be an lvalue.  */
5802   if (!lvalue_or_else (lhs, lv_assign))
5803     return error_mark_node;
5804
5805   /* Warn about modifying something that is `const'.  Don't warn if
5806      this is initialization.  */
5807   if (modifycode != INIT_EXPR
5808       && (TREE_READONLY (lhs) || CP_TYPE_CONST_P (lhstype)
5809           /* Functions are not modifiable, even though they are
5810              lvalues.  */
5811           || TREE_CODE (TREE_TYPE (lhs)) == FUNCTION_TYPE
5812           || TREE_CODE (TREE_TYPE (lhs)) == METHOD_TYPE
5813           /* If it's an aggregate and any field is const, then it is
5814              effectively const.  */
5815           || (CLASS_TYPE_P (lhstype)
5816               && C_TYPE_FIELDS_READONLY (lhstype))))
5817     readonly_error (lhs, "assignment", 0);
5818
5819   /* If storing into a structure or union member, it has probably been
5820      given type `int'.  Compute the type that would go with the actual
5821      amount of storage the member occupies.  */
5822
5823   if (TREE_CODE (lhs) == COMPONENT_REF
5824       && (TREE_CODE (lhstype) == INTEGER_TYPE
5825           || TREE_CODE (lhstype) == REAL_TYPE
5826           || TREE_CODE (lhstype) == ENUMERAL_TYPE))
5827     {
5828       lhstype = TREE_TYPE (get_unwidened (lhs, 0));
5829
5830       /* If storing in a field that is in actuality a short or narrower
5831          than one, we must store in the field in its actual type.  */
5832
5833       if (lhstype != TREE_TYPE (lhs))
5834         {
5835           /* Avoid warnings converting integral types back into enums for
5836              enum bit fields.  */
5837           if (TREE_CODE (lhstype) == INTEGER_TYPE
5838               && TREE_CODE (olhstype) == ENUMERAL_TYPE)
5839             {
5840               if (TREE_SIDE_EFFECTS (lhs))
5841                 lhs = stabilize_reference (lhs);
5842               olhs = lhs;
5843             }
5844           lhs = copy_node (lhs);
5845           TREE_TYPE (lhs) = lhstype;
5846         }
5847     }
5848
5849   /* Convert new value to destination type.  */
5850
5851   if (TREE_CODE (lhstype) == ARRAY_TYPE)
5852     {
5853       int from_array;
5854
5855       if (!same_or_base_type_p (TYPE_MAIN_VARIANT (lhstype),
5856                                 TYPE_MAIN_VARIANT (TREE_TYPE (rhs))))
5857         {
5858           error ("incompatible types in assignment of %qT to %qT",
5859                  TREE_TYPE (rhs), lhstype);
5860           return error_mark_node;
5861         }
5862
5863       /* Allow array assignment in compiler-generated code.  */
5864       if (! DECL_ARTIFICIAL (current_function_decl))
5865         {
5866           /* This routine is used for both initialization and assignment.
5867              Make sure the diagnostic message differentiates the context.  */
5868           if (modifycode == INIT_EXPR)
5869             error ("array used as initializer");
5870           else
5871             error ("invalid array assignment");
5872           return error_mark_node;
5873         }
5874
5875       from_array = TREE_CODE (TREE_TYPE (newrhs)) == ARRAY_TYPE
5876                    ? 1 + (modifycode != INIT_EXPR): 0;
5877       return build_vec_init (lhs, NULL_TREE, newrhs,
5878                              /*explicit_default_init_p=*/false,
5879                              from_array);
5880     }
5881
5882   if (modifycode == INIT_EXPR)
5883     newrhs = convert_for_initialization (lhs, lhstype, newrhs, LOOKUP_NORMAL,
5884                                          "initialization", NULL_TREE, 0);
5885   else
5886     {
5887       /* Avoid warnings on enum bit fields.  */
5888       if (TREE_CODE (olhstype) == ENUMERAL_TYPE
5889           && TREE_CODE (lhstype) == INTEGER_TYPE)
5890         {
5891           newrhs = convert_for_assignment (olhstype, newrhs, "assignment",
5892                                            NULL_TREE, 0);
5893           newrhs = convert_force (lhstype, newrhs, 0);
5894         }
5895       else
5896         newrhs = convert_for_assignment (lhstype, newrhs, "assignment",
5897                                          NULL_TREE, 0);
5898       if (TREE_CODE (newrhs) == CALL_EXPR
5899           && TYPE_NEEDS_CONSTRUCTING (lhstype))
5900         newrhs = build_cplus_new (lhstype, newrhs);
5901
5902       /* Can't initialize directly from a TARGET_EXPR, since that would
5903          cause the lhs to be constructed twice, and possibly result in
5904          accidental self-initialization.  So we force the TARGET_EXPR to be
5905          expanded without a target.  */
5906       if (TREE_CODE (newrhs) == TARGET_EXPR)
5907         newrhs = build2 (COMPOUND_EXPR, TREE_TYPE (newrhs), newrhs,
5908                          TREE_OPERAND (newrhs, 0));
5909     }
5910
5911   if (newrhs == error_mark_node)
5912     return error_mark_node;
5913
5914   if (c_dialect_objc () && flag_objc_gc)
5915     {
5916       result = objc_generate_write_barrier (lhs, modifycode, newrhs);
5917
5918       if (result)
5919         return result;
5920     }
5921
5922   result = build2 (modifycode == NOP_EXPR ? MODIFY_EXPR : INIT_EXPR,
5923                    lhstype, lhs, newrhs);
5924
5925   TREE_SIDE_EFFECTS (result) = 1;
5926   if (!plain_assign)
5927     TREE_NO_WARNING (result) = 1;
5928
5929   /* If we got the LHS in a different type for storing in,
5930      convert the result back to the nominal type of LHS
5931      so that the value we return always has the same type
5932      as the LHS argument.  */
5933
5934   if (olhstype == TREE_TYPE (result))
5935     return result;
5936   if (olhs)
5937     {
5938       result = build2 (COMPOUND_EXPR, olhstype, result, olhs);
5939       TREE_NO_WARNING (result) = 1;
5940       return result;
5941     }
5942   return convert_for_assignment (olhstype, result, "assignment",
5943                                  NULL_TREE, 0);
5944 }
5945
5946 tree
5947 build_x_modify_expr (tree lhs, enum tree_code modifycode, tree rhs)
5948 {
5949   if (processing_template_decl)
5950     return build_min_nt (MODOP_EXPR, lhs,
5951                          build_min_nt (modifycode, NULL_TREE, NULL_TREE), rhs);
5952
5953   if (modifycode != NOP_EXPR)
5954     {
5955       tree rval = build_new_op (MODIFY_EXPR, LOOKUP_NORMAL, lhs, rhs,
5956                                 make_node (modifycode),
5957                                 /*overloaded_p=*/NULL);
5958       if (rval)
5959         {
5960           TREE_NO_WARNING (rval) = 1;
5961           return rval;
5962         }
5963     }
5964   return build_modify_expr (lhs, modifycode, rhs);
5965 }
5966
5967 \f
5968 /* Get difference in deltas for different pointer to member function
5969    types.  Returns an integer constant of type PTRDIFF_TYPE_NODE.  If
5970    the conversion is invalid, the constant is zero.  If
5971    ALLOW_INVERSE_P is true, then allow reverse conversions as well.
5972    If C_CAST_P is true this conversion is taking place as part of a
5973    C-style cast.
5974
5975    Note that the naming of FROM and TO is kind of backwards; the return
5976    value is what we add to a TO in order to get a FROM.  They are named
5977    this way because we call this function to find out how to convert from
5978    a pointer to member of FROM to a pointer to member of TO.  */
5979
5980 static tree
5981 get_delta_difference (tree from, tree to,
5982                       bool allow_inverse_p,
5983                       bool c_cast_p)
5984 {
5985   tree binfo;
5986   base_kind kind;
5987   tree result;
5988
5989   /* Assume no conversion is required.  */
5990   result = integer_zero_node;
5991   binfo = lookup_base (to, from, c_cast_p ? ba_unique : ba_check, &kind);
5992   if (kind == bk_inaccessible || kind == bk_ambig)
5993     error ("   in pointer to member function conversion");
5994   else if (binfo)
5995     {
5996       if (kind != bk_via_virtual)
5997         result = BINFO_OFFSET (binfo);
5998       else
5999         {
6000           tree virt_binfo = binfo_from_vbase (binfo);
6001
6002           /* This is a reinterpret cast, we choose to do nothing.  */
6003           if (allow_inverse_p)
6004             warning (0, "pointer to member cast via virtual base %qT",
6005                      BINFO_TYPE (virt_binfo));
6006           else
6007             error ("pointer to member conversion via virtual base %qT",
6008                    BINFO_TYPE (virt_binfo));
6009         }
6010     }
6011   else if (same_type_ignoring_top_level_qualifiers_p (from, to))
6012     /* Pointer to member of incomplete class is permitted*/;
6013   else if (!allow_inverse_p)
6014     {
6015       error_not_base_type (from, to);
6016       error ("   in pointer to member conversion");
6017     }
6018   else
6019     {
6020       binfo = lookup_base (from, to, c_cast_p ? ba_unique : ba_check, &kind);
6021       if (binfo)
6022         {
6023           if (kind != bk_via_virtual)
6024             result = size_diffop (size_zero_node, BINFO_OFFSET (binfo));
6025           else
6026             {
6027               /* This is a reinterpret cast, we choose to do nothing.  */
6028               tree virt_binfo = binfo_from_vbase (binfo);
6029
6030               warning (0, "pointer to member cast via virtual base %qT",
6031                        BINFO_TYPE (virt_binfo));
6032             }
6033         }
6034     }
6035
6036   return fold_if_not_in_template (convert_to_integer (ptrdiff_type_node,
6037                                                       result));
6038 }
6039
6040 /* Return a constructor for the pointer-to-member-function TYPE using
6041    the other components as specified.  */
6042
6043 tree
6044 build_ptrmemfunc1 (tree type, tree delta, tree pfn)
6045 {
6046   tree u = NULL_TREE;
6047   tree delta_field;
6048   tree pfn_field;
6049   VEC(constructor_elt, gc) *v;
6050
6051   /* Pull the FIELD_DECLs out of the type.  */
6052   pfn_field = TYPE_FIELDS (type);
6053   delta_field = TREE_CHAIN (pfn_field);
6054
6055   /* Make sure DELTA has the type we want.  */
6056   delta = convert_and_check (delta_type_node, delta);
6057
6058   /* Finish creating the initializer.  */
6059   v = VEC_alloc(constructor_elt, gc, 2);
6060   CONSTRUCTOR_APPEND_ELT(v, pfn_field, pfn);
6061   CONSTRUCTOR_APPEND_ELT(v, delta_field, delta);
6062   u = build_constructor (type, v);
6063   TREE_CONSTANT (u) = TREE_CONSTANT (pfn) & TREE_CONSTANT (delta);
6064   TREE_INVARIANT (u) = TREE_INVARIANT (pfn) & TREE_INVARIANT (delta);
6065   TREE_STATIC (u) = (TREE_CONSTANT (u)
6066                      && (initializer_constant_valid_p (pfn, TREE_TYPE (pfn))
6067                          != NULL_TREE)
6068                      && (initializer_constant_valid_p (delta, TREE_TYPE (delta))
6069                          != NULL_TREE));
6070   return u;
6071 }
6072
6073 /* Build a constructor for a pointer to member function.  It can be
6074    used to initialize global variables, local variable, or used
6075    as a value in expressions.  TYPE is the POINTER to METHOD_TYPE we
6076    want to be.
6077
6078    If FORCE is nonzero, then force this conversion, even if
6079    we would rather not do it.  Usually set when using an explicit
6080    cast.  A C-style cast is being processed iff C_CAST_P is true.
6081
6082    Return error_mark_node, if something goes wrong.  */
6083
6084 tree
6085 build_ptrmemfunc (tree type, tree pfn, int force, bool c_cast_p)
6086 {
6087   tree fn;
6088   tree pfn_type;
6089   tree to_type;
6090
6091   if (error_operand_p (pfn))
6092     return error_mark_node;
6093
6094   pfn_type = TREE_TYPE (pfn);
6095   to_type = build_ptrmemfunc_type (type);
6096
6097   /* Handle multiple conversions of pointer to member functions.  */
6098   if (TYPE_PTRMEMFUNC_P (pfn_type))
6099     {
6100       tree delta = NULL_TREE;
6101       tree npfn = NULL_TREE;
6102       tree n;
6103
6104       if (!force
6105           && !can_convert_arg (to_type, TREE_TYPE (pfn), pfn, LOOKUP_NORMAL))
6106         error ("invalid conversion to type %qT from type %qT",
6107                to_type, pfn_type);
6108
6109       n = get_delta_difference (TYPE_PTRMEMFUNC_OBJECT_TYPE (pfn_type),
6110                                 TYPE_PTRMEMFUNC_OBJECT_TYPE (to_type),
6111                                 force,
6112                                 c_cast_p);
6113
6114       /* We don't have to do any conversion to convert a
6115          pointer-to-member to its own type.  But, we don't want to
6116          just return a PTRMEM_CST if there's an explicit cast; that
6117          cast should make the expression an invalid template argument.  */
6118       if (TREE_CODE (pfn) != PTRMEM_CST)
6119         {
6120           if (same_type_p (to_type, pfn_type))
6121             return pfn;
6122           else if (integer_zerop (n))
6123             return build_reinterpret_cast (to_type, pfn);
6124         }
6125
6126       if (TREE_SIDE_EFFECTS (pfn))
6127         pfn = save_expr (pfn);
6128
6129       /* Obtain the function pointer and the current DELTA.  */
6130       if (TREE_CODE (pfn) == PTRMEM_CST)
6131         expand_ptrmemfunc_cst (pfn, &delta, &npfn);
6132       else
6133         {
6134           npfn = build_ptrmemfunc_access_expr (pfn, pfn_identifier);
6135           delta = build_ptrmemfunc_access_expr (pfn, delta_identifier);
6136         }
6137
6138       /* Just adjust the DELTA field.  */
6139       gcc_assert  (same_type_ignoring_top_level_qualifiers_p
6140                    (TREE_TYPE (delta), ptrdiff_type_node));
6141       if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_delta)
6142         n = cp_build_binary_op (LSHIFT_EXPR, n, integer_one_node);
6143       delta = cp_build_binary_op (PLUS_EXPR, delta, n);
6144       return build_ptrmemfunc1 (to_type, delta, npfn);
6145     }
6146
6147   /* Handle null pointer to member function conversions.  */
6148   if (integer_zerop (pfn))
6149     {
6150       pfn = build_c_cast (type, integer_zero_node);
6151       return build_ptrmemfunc1 (to_type,
6152                                 integer_zero_node,
6153                                 pfn);
6154     }
6155
6156   if (type_unknown_p (pfn))
6157     return instantiate_type (type, pfn, tf_warning_or_error);
6158
6159   fn = TREE_OPERAND (pfn, 0);
6160   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL
6161               /* In a template, we will have preserved the
6162                  OFFSET_REF.  */
6163               || (processing_template_decl && TREE_CODE (fn) == OFFSET_REF));
6164   return make_ptrmem_cst (to_type, fn);
6165 }
6166
6167 /* Return the DELTA, IDX, PFN, and DELTA2 values for the PTRMEM_CST
6168    given by CST.
6169
6170    ??? There is no consistency as to the types returned for the above
6171    values.  Some code acts as if it were a sizetype and some as if it were
6172    integer_type_node.  */
6173
6174 void
6175 expand_ptrmemfunc_cst (tree cst, tree *delta, tree *pfn)
6176 {
6177   tree type = TREE_TYPE (cst);
6178   tree fn = PTRMEM_CST_MEMBER (cst);
6179   tree ptr_class, fn_class;
6180
6181   gcc_assert (TREE_CODE (fn) == FUNCTION_DECL);
6182
6183   /* The class that the function belongs to.  */
6184   fn_class = DECL_CONTEXT (fn);
6185
6186   /* The class that we're creating a pointer to member of.  */
6187   ptr_class = TYPE_PTRMEMFUNC_OBJECT_TYPE (type);
6188
6189   /* First, calculate the adjustment to the function's class.  */
6190   *delta = get_delta_difference (fn_class, ptr_class, /*force=*/0,
6191                                  /*c_cast_p=*/0);
6192
6193   if (!DECL_VIRTUAL_P (fn))
6194     *pfn = convert (TYPE_PTRMEMFUNC_FN_TYPE (type), build_addr_func (fn));
6195   else
6196     {
6197       /* If we're dealing with a virtual function, we have to adjust 'this'
6198          again, to point to the base which provides the vtable entry for
6199          fn; the call will do the opposite adjustment.  */
6200       tree orig_class = DECL_CONTEXT (fn);
6201       tree binfo = binfo_or_else (orig_class, fn_class);
6202       *delta = build2 (PLUS_EXPR, TREE_TYPE (*delta),
6203                        *delta, BINFO_OFFSET (binfo));
6204       *delta = fold_if_not_in_template (*delta);
6205
6206       /* We set PFN to the vtable offset at which the function can be
6207          found, plus one (unless ptrmemfunc_vbit_in_delta, in which
6208          case delta is shifted left, and then incremented).  */
6209       *pfn = DECL_VINDEX (fn);
6210       *pfn = build2 (MULT_EXPR, integer_type_node, *pfn,
6211                      TYPE_SIZE_UNIT (vtable_entry_type));
6212       *pfn = fold_if_not_in_template (*pfn);
6213
6214       switch (TARGET_PTRMEMFUNC_VBIT_LOCATION)
6215         {
6216         case ptrmemfunc_vbit_in_pfn:
6217           *pfn = build2 (PLUS_EXPR, integer_type_node, *pfn,
6218                          integer_one_node);
6219           *pfn = fold_if_not_in_template (*pfn);
6220           break;
6221
6222         case ptrmemfunc_vbit_in_delta:
6223           *delta = build2 (LSHIFT_EXPR, TREE_TYPE (*delta),
6224                            *delta, integer_one_node);
6225           *delta = fold_if_not_in_template (*delta);
6226           *delta = build2 (PLUS_EXPR, TREE_TYPE (*delta),
6227                            *delta, integer_one_node);
6228           *delta = fold_if_not_in_template (*delta);
6229           break;
6230
6231         default:
6232           gcc_unreachable ();
6233         }
6234
6235       *pfn = build_nop (TYPE_PTRMEMFUNC_FN_TYPE (type), *pfn);
6236       *pfn = fold_if_not_in_template (*pfn);
6237     }
6238 }
6239
6240 /* Return an expression for PFN from the pointer-to-member function
6241    given by T.  */
6242
6243 static tree
6244 pfn_from_ptrmemfunc (tree t)
6245 {
6246   if (TREE_CODE (t) == PTRMEM_CST)
6247     {
6248       tree delta;
6249       tree pfn;
6250
6251       expand_ptrmemfunc_cst (t, &delta, &pfn);
6252       if (pfn)
6253         return pfn;
6254     }
6255
6256   return build_ptrmemfunc_access_expr (t, pfn_identifier);
6257 }
6258
6259 /* Convert value RHS to type TYPE as preparation for an assignment to
6260    an lvalue of type TYPE.  ERRTYPE is a string to use in error
6261    messages: "assignment", "return", etc.  If FNDECL is non-NULL, we
6262    are doing the conversion in order to pass the PARMNUMth argument of
6263    FNDECL.  */
6264
6265 static tree
6266 convert_for_assignment (tree type, tree rhs,
6267                         const char *errtype, tree fndecl, int parmnum)
6268 {
6269   tree rhstype;
6270   enum tree_code coder;
6271
6272   /* Strip NON_LVALUE_EXPRs since we aren't using as an lvalue.  */
6273   if (TREE_CODE (rhs) == NON_LVALUE_EXPR)
6274     rhs = TREE_OPERAND (rhs, 0);
6275
6276   rhstype = TREE_TYPE (rhs);
6277   coder = TREE_CODE (rhstype);
6278
6279   if (TREE_CODE (type) == VECTOR_TYPE && coder == VECTOR_TYPE
6280       && vector_types_convertible_p (type, rhstype))
6281     return convert (type, rhs);
6282
6283   if (rhs == error_mark_node || rhstype == error_mark_node)
6284     return error_mark_node;
6285   if (TREE_CODE (rhs) == TREE_LIST && TREE_VALUE (rhs) == error_mark_node)
6286     return error_mark_node;
6287
6288   /* The RHS of an assignment cannot have void type.  */
6289   if (coder == VOID_TYPE)
6290     {
6291       error ("void value not ignored as it ought to be");
6292       return error_mark_node;
6293     }
6294
6295   /* Simplify the RHS if possible.  */
6296   if (TREE_CODE (rhs) == CONST_DECL)
6297     rhs = DECL_INITIAL (rhs);
6298
6299   if (c_dialect_objc ())
6300     {
6301       int parmno;
6302       tree rname = fndecl;
6303
6304       if (!strcmp (errtype, "assignment"))
6305         parmno = -1;
6306       else if (!strcmp (errtype, "initialization"))
6307         parmno = -2;
6308       else
6309         {
6310           tree selector = objc_message_selector ();
6311
6312           parmno = parmnum;
6313
6314           if (selector && parmno > 1)
6315             {
6316               rname = selector;
6317               parmno -= 1;
6318             }
6319         }
6320
6321       if (objc_compare_types (type, rhstype, parmno, rname))
6322         return convert (type, rhs);
6323     }
6324
6325   /* [expr.ass]
6326
6327      The expression is implicitly converted (clause _conv_) to the
6328      cv-unqualified type of the left operand.
6329
6330      We allow bad conversions here because by the time we get to this point
6331      we are committed to doing the conversion.  If we end up doing a bad
6332      conversion, convert_like will complain.  */
6333   if (!can_convert_arg_bad (type, rhstype, rhs))
6334     {
6335       /* When -Wno-pmf-conversions is use, we just silently allow
6336          conversions from pointers-to-members to plain pointers.  If
6337          the conversion doesn't work, cp_convert will complain.  */
6338       if (!warn_pmf2ptr
6339           && TYPE_PTR_P (type)
6340           && TYPE_PTRMEMFUNC_P (rhstype))
6341         rhs = cp_convert (strip_top_quals (type), rhs);
6342       else
6343         {
6344           /* If the right-hand side has unknown type, then it is an
6345              overloaded function.  Call instantiate_type to get error
6346              messages.  */
6347           if (rhstype == unknown_type_node)
6348             instantiate_type (type, rhs, tf_warning_or_error);
6349           else if (fndecl)
6350             error ("cannot convert %qT to %qT for argument %qP to %qD",
6351                    rhstype, type, parmnum, fndecl);
6352           else
6353             error ("cannot convert %qT to %qT in %s", rhstype, type, errtype);
6354           return error_mark_node;
6355         }
6356     }
6357   if (warn_missing_format_attribute)
6358     {
6359       const enum tree_code codel = TREE_CODE (type);
6360       if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE)
6361           && coder == codel
6362           && check_missing_format_attribute (type, rhstype))
6363         warning (OPT_Wmissing_format_attribute,
6364                  "%s might be a candidate for a format attribute",
6365                  errtype);
6366     }
6367
6368   return perform_implicit_conversion (strip_top_quals (type), rhs);
6369 }
6370
6371 /* Convert RHS to be of type TYPE.
6372    If EXP is nonzero, it is the target of the initialization.
6373    ERRTYPE is a string to use in error messages.
6374
6375    Two major differences between the behavior of
6376    `convert_for_assignment' and `convert_for_initialization'
6377    are that references are bashed in the former, while
6378    copied in the latter, and aggregates are assigned in
6379    the former (operator=) while initialized in the
6380    latter (X(X&)).
6381
6382    If using constructor make sure no conversion operator exists, if one does
6383    exist, an ambiguity exists.
6384
6385    If flags doesn't include LOOKUP_COMPLAIN, don't complain about anything.  */
6386
6387 tree
6388 convert_for_initialization (tree exp, tree type, tree rhs, int flags,
6389                             const char *errtype, tree fndecl, int parmnum)
6390 {
6391   enum tree_code codel = TREE_CODE (type);
6392   tree rhstype;
6393   enum tree_code coder;
6394
6395   /* build_c_cast puts on a NOP_EXPR to make the result not an lvalue.
6396      Strip such NOP_EXPRs, since RHS is used in non-lvalue context.  */
6397   if (TREE_CODE (rhs) == NOP_EXPR
6398       && TREE_TYPE (rhs) == TREE_TYPE (TREE_OPERAND (rhs, 0))
6399       && codel != REFERENCE_TYPE)
6400     rhs = TREE_OPERAND (rhs, 0);
6401
6402   if (type == error_mark_node
6403       || rhs == error_mark_node
6404       || (TREE_CODE (rhs) == TREE_LIST && TREE_VALUE (rhs) == error_mark_node))
6405     return error_mark_node;
6406
6407   if ((TREE_CODE (TREE_TYPE (rhs)) == ARRAY_TYPE
6408        && TREE_CODE (type) != ARRAY_TYPE
6409        && (TREE_CODE (type) != REFERENCE_TYPE
6410            || TREE_CODE (TREE_TYPE (type)) != ARRAY_TYPE))
6411       || (TREE_CODE (TREE_TYPE (rhs)) == FUNCTION_TYPE
6412           && (TREE_CODE (type) != REFERENCE_TYPE
6413               || TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE))
6414       || TREE_CODE (TREE_TYPE (rhs)) == METHOD_TYPE)
6415     rhs = decay_conversion (rhs);
6416
6417   rhstype = TREE_TYPE (rhs);
6418   coder = TREE_CODE (rhstype);
6419
6420   if (coder == ERROR_MARK)
6421     return error_mark_node;
6422
6423   /* We accept references to incomplete types, so we can
6424      return here before checking if RHS is of complete type.  */
6425
6426   if (codel == REFERENCE_TYPE)
6427     {
6428       /* This should eventually happen in convert_arguments.  */
6429       int savew = 0, savee = 0;
6430
6431       if (fndecl)
6432         savew = warningcount, savee = errorcount;
6433       rhs = initialize_reference (type, rhs, /*decl=*/NULL_TREE,
6434                                   /*cleanup=*/NULL);
6435       if (fndecl)
6436         {
6437           if (warningcount > savew)
6438             warning (0, "in passing argument %P of %q+D", parmnum, fndecl);
6439           else if (errorcount > savee)
6440             error ("in passing argument %P of %q+D", parmnum, fndecl);
6441         }
6442       return rhs;
6443     }
6444
6445   if (exp != 0)
6446     exp = require_complete_type (exp);
6447   if (exp == error_mark_node)
6448     return error_mark_node;
6449
6450   rhstype = non_reference (rhstype);
6451
6452   type = complete_type (type);
6453
6454   if (IS_AGGR_TYPE (type))
6455     return ocp_convert (type, rhs, CONV_IMPLICIT|CONV_FORCE_TEMP, flags);
6456
6457   return convert_for_assignment (type, rhs, errtype, fndecl, parmnum);
6458 }
6459 \f
6460 /* If RETVAL is the address of, or a reference to, a local variable or
6461    temporary give an appropriate warning.  */
6462
6463 static void
6464 maybe_warn_about_returning_address_of_local (tree retval)
6465 {
6466   tree valtype = TREE_TYPE (DECL_RESULT (current_function_decl));
6467   tree whats_returned = retval;
6468
6469   for (;;)
6470     {
6471       if (TREE_CODE (whats_returned) == COMPOUND_EXPR)
6472         whats_returned = TREE_OPERAND (whats_returned, 1);
6473       else if (TREE_CODE (whats_returned) == CONVERT_EXPR
6474                || TREE_CODE (whats_returned) == NON_LVALUE_EXPR
6475                || TREE_CODE (whats_returned) == NOP_EXPR)
6476         whats_returned = TREE_OPERAND (whats_returned, 0);
6477       else
6478         break;
6479     }
6480
6481   if (TREE_CODE (whats_returned) != ADDR_EXPR)
6482     return;
6483   whats_returned = TREE_OPERAND (whats_returned, 0);
6484
6485   if (TREE_CODE (valtype) == REFERENCE_TYPE)
6486     {
6487       if (TREE_CODE (whats_returned) == AGGR_INIT_EXPR
6488           || TREE_CODE (whats_returned) == TARGET_EXPR)
6489         {
6490           warning (0, "returning reference to temporary");
6491           return;
6492         }
6493       if (TREE_CODE (whats_returned) == VAR_DECL
6494           && DECL_NAME (whats_returned)
6495           && TEMP_NAME_P (DECL_NAME (whats_returned)))
6496         {
6497           warning (0, "reference to non-lvalue returned");
6498           return;
6499         }
6500     }
6501
6502   while (TREE_CODE (whats_returned) == COMPONENT_REF
6503          || TREE_CODE (whats_returned) == ARRAY_REF)
6504     whats_returned = TREE_OPERAND (whats_returned, 0);
6505
6506   if (DECL_P (whats_returned)
6507       && DECL_NAME (whats_returned)
6508       && DECL_FUNCTION_SCOPE_P (whats_returned)
6509       && !(TREE_STATIC (whats_returned)
6510            || TREE_PUBLIC (whats_returned)))
6511     {
6512       if (TREE_CODE (valtype) == REFERENCE_TYPE)
6513         warning (0, "reference to local variable %q+D returned",
6514                  whats_returned);
6515       else
6516         warning (0, "address of local variable %q+D returned",
6517                  whats_returned);
6518       return;
6519     }
6520 }
6521
6522 /* Check that returning RETVAL from the current function is valid.
6523    Return an expression explicitly showing all conversions required to
6524    change RETVAL into the function return type, and to assign it to
6525    the DECL_RESULT for the function.  Set *NO_WARNING to true if
6526    code reaches end of non-void function warning shouldn't be issued
6527    on this RETURN_EXPR.  */
6528
6529 tree
6530 check_return_expr (tree retval, bool *no_warning)
6531 {
6532   tree result;
6533   /* The type actually returned by the function, after any
6534      promotions.  */
6535   tree valtype;
6536   int fn_returns_value_p;
6537
6538   *no_warning = false;
6539
6540   /* A `volatile' function is one that isn't supposed to return, ever.
6541      (This is a G++ extension, used to get better code for functions
6542      that call the `volatile' function.)  */
6543   if (TREE_THIS_VOLATILE (current_function_decl))
6544     warning (0, "function declared %<noreturn%> has a %<return%> statement");
6545
6546   /* Check for various simple errors.  */
6547   if (DECL_DESTRUCTOR_P (current_function_decl))
6548     {
6549       if (retval)
6550         error ("returning a value from a destructor");
6551       return NULL_TREE;
6552     }
6553   else if (DECL_CONSTRUCTOR_P (current_function_decl))
6554     {
6555       if (in_function_try_handler)
6556         /* If a return statement appears in a handler of the
6557            function-try-block of a constructor, the program is ill-formed.  */
6558         error ("cannot return from a handler of a function-try-block of a constructor");
6559       else if (retval)
6560         /* You can't return a value from a constructor.  */
6561         error ("returning a value from a constructor");
6562       return NULL_TREE;
6563     }
6564
6565   if (processing_template_decl)
6566     {
6567       current_function_returns_value = 1;
6568       return retval;
6569     }
6570
6571   /* When no explicit return-value is given in a function with a named
6572      return value, the named return value is used.  */
6573   result = DECL_RESULT (current_function_decl);
6574   valtype = TREE_TYPE (result);
6575   gcc_assert (valtype != NULL_TREE);
6576   fn_returns_value_p = !VOID_TYPE_P (valtype);
6577   if (!retval && DECL_NAME (result) && fn_returns_value_p)
6578     retval = result;
6579
6580   /* Check for a return statement with no return value in a function
6581      that's supposed to return a value.  */
6582   if (!retval && fn_returns_value_p)
6583     {
6584       pedwarn ("return-statement with no value, in function returning %qT",
6585                valtype);
6586       /* Clear this, so finish_function won't say that we reach the
6587          end of a non-void function (which we don't, we gave a
6588          return!).  */
6589       current_function_returns_null = 0;
6590       /* And signal caller that TREE_NO_WARNING should be set on the
6591          RETURN_EXPR to avoid control reaches end of non-void function
6592          warnings in tree-cfg.c.  */
6593       *no_warning = true;
6594     }
6595   /* Check for a return statement with a value in a function that
6596      isn't supposed to return a value.  */
6597   else if (retval && !fn_returns_value_p)
6598     {
6599       if (VOID_TYPE_P (TREE_TYPE (retval)))
6600         /* You can return a `void' value from a function of `void'
6601            type.  In that case, we have to evaluate the expression for
6602            its side-effects.  */
6603           finish_expr_stmt (retval);
6604       else
6605         pedwarn ("return-statement with a value, in function "
6606                  "returning 'void'");
6607
6608       current_function_returns_null = 1;
6609
6610       /* There's really no value to return, after all.  */
6611       return NULL_TREE;
6612     }
6613   else if (!retval)
6614     /* Remember that this function can sometimes return without a
6615        value.  */
6616     current_function_returns_null = 1;
6617   else
6618     /* Remember that this function did return a value.  */
6619     current_function_returns_value = 1;
6620
6621   /* Check for erroneous operands -- but after giving ourselves a
6622      chance to provide an error about returning a value from a void
6623      function.  */
6624   if (error_operand_p (retval))
6625     {
6626       current_function_return_value = error_mark_node;
6627       return error_mark_node;
6628     }
6629
6630   /* Only operator new(...) throw(), can return NULL [expr.new/13].  */
6631   if ((DECL_OVERLOADED_OPERATOR_P (current_function_decl) == NEW_EXPR
6632        || DECL_OVERLOADED_OPERATOR_P (current_function_decl) == VEC_NEW_EXPR)
6633       && !TYPE_NOTHROW_P (TREE_TYPE (current_function_decl))
6634       && ! flag_check_new
6635       && null_ptr_cst_p (retval))
6636     warning (0, "%<operator new%> must not return NULL unless it is "
6637              "declared %<throw()%> (or -fcheck-new is in effect)");
6638
6639   /* Effective C++ rule 15.  See also start_function.  */
6640   if (warn_ecpp
6641       && DECL_NAME (current_function_decl) == ansi_assopname(NOP_EXPR))
6642     {
6643       bool warn = true;
6644
6645       /* The function return type must be a reference to the current
6646         class.  */
6647       if (TREE_CODE (valtype) == REFERENCE_TYPE
6648           && same_type_ignoring_top_level_qualifiers_p
6649               (TREE_TYPE (valtype), TREE_TYPE (current_class_ref)))
6650         {
6651           /* Returning '*this' is obviously OK.  */
6652           if (retval == current_class_ref)
6653             warn = false;
6654           /* If we are calling a function whose return type is the same of
6655              the current class reference, it is ok.  */
6656           else if (TREE_CODE (retval) == INDIRECT_REF
6657                    && TREE_CODE (TREE_OPERAND (retval, 0)) == CALL_EXPR)
6658             warn = false;
6659         }
6660
6661       if (warn)
6662         warning (OPT_Weffc__, "%<operator=%> should return a reference to %<*this%>");
6663     }
6664
6665   /* The fabled Named Return Value optimization, as per [class.copy]/15:
6666
6667      [...]      For  a function with a class return type, if the expression
6668      in the return statement is the name of a local  object,  and  the  cv-
6669      unqualified  type  of  the  local  object  is the same as the function
6670      return type, an implementation is permitted to omit creating the  tem-
6671      porary  object  to  hold  the function return value [...]
6672
6673      So, if this is a value-returning function that always returns the same
6674      local variable, remember it.
6675
6676      It might be nice to be more flexible, and choose the first suitable
6677      variable even if the function sometimes returns something else, but
6678      then we run the risk of clobbering the variable we chose if the other
6679      returned expression uses the chosen variable somehow.  And people expect
6680      this restriction, anyway.  (jason 2000-11-19)
6681
6682      See finish_function and finalize_nrv for the rest of this optimization.  */
6683
6684   if (fn_returns_value_p && flag_elide_constructors)
6685     {
6686       if (retval != NULL_TREE
6687           && (current_function_return_value == NULL_TREE
6688               || current_function_return_value == retval)
6689           && TREE_CODE (retval) == VAR_DECL
6690           && DECL_CONTEXT (retval) == current_function_decl
6691           && ! TREE_STATIC (retval)
6692           && (DECL_ALIGN (retval)
6693               >= DECL_ALIGN (DECL_RESULT (current_function_decl)))
6694           && same_type_p ((TYPE_MAIN_VARIANT
6695                            (TREE_TYPE (retval))),
6696                           (TYPE_MAIN_VARIANT
6697                            (TREE_TYPE (TREE_TYPE (current_function_decl))))))
6698         current_function_return_value = retval;
6699       else
6700         current_function_return_value = error_mark_node;
6701     }
6702
6703   /* We don't need to do any conversions when there's nothing being
6704      returned.  */
6705   if (!retval)
6706     return NULL_TREE;
6707
6708   /* Do any required conversions.  */
6709   if (retval == result || DECL_CONSTRUCTOR_P (current_function_decl))
6710     /* No conversions are required.  */
6711     ;
6712   else
6713     {
6714       /* The type the function is declared to return.  */
6715       tree functype = TREE_TYPE (TREE_TYPE (current_function_decl));
6716
6717       /* The functype's return type will have been set to void, if it
6718          was an incomplete type.  Just treat this as 'return;' */
6719       if (VOID_TYPE_P (functype))
6720         return error_mark_node;
6721
6722       /* First convert the value to the function's return type, then
6723          to the type of return value's location to handle the
6724          case that functype is smaller than the valtype.  */
6725       retval = convert_for_initialization
6726         (NULL_TREE, functype, retval, LOOKUP_NORMAL|LOOKUP_ONLYCONVERTING,
6727          "return", NULL_TREE, 0);
6728       retval = convert (valtype, retval);
6729
6730       /* If the conversion failed, treat this just like `return;'.  */
6731       if (retval == error_mark_node)
6732         return retval;
6733       /* We can't initialize a register from a AGGR_INIT_EXPR.  */
6734       else if (! current_function_returns_struct
6735                && TREE_CODE (retval) == TARGET_EXPR
6736                && TREE_CODE (TREE_OPERAND (retval, 1)) == AGGR_INIT_EXPR)
6737         retval = build2 (COMPOUND_EXPR, TREE_TYPE (retval), retval,
6738                          TREE_OPERAND (retval, 0));
6739       else
6740         maybe_warn_about_returning_address_of_local (retval);
6741     }
6742
6743   /* Actually copy the value returned into the appropriate location.  */
6744   if (retval && retval != result)
6745     retval = build2 (INIT_EXPR, TREE_TYPE (result), result, retval);
6746
6747   return retval;
6748 }
6749
6750 \f
6751 /* Returns nonzero if the pointer-type FROM can be converted to the
6752    pointer-type TO via a qualification conversion.  If CONSTP is -1,
6753    then we return nonzero if the pointers are similar, and the
6754    cv-qualification signature of FROM is a proper subset of that of TO.
6755
6756    If CONSTP is positive, then all outer pointers have been
6757    const-qualified.  */
6758
6759 static int
6760 comp_ptr_ttypes_real (tree to, tree from, int constp)
6761 {
6762   bool to_more_cv_qualified = false;
6763
6764   for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
6765     {
6766       if (TREE_CODE (to) != TREE_CODE (from))
6767         return 0;
6768
6769       if (TREE_CODE (from) == OFFSET_TYPE
6770           && !same_type_p (TYPE_OFFSET_BASETYPE (from),
6771                            TYPE_OFFSET_BASETYPE (to)))
6772         return 0;
6773
6774       /* Const and volatile mean something different for function types,
6775          so the usual checks are not appropriate.  */
6776       if (TREE_CODE (to) != FUNCTION_TYPE && TREE_CODE (to) != METHOD_TYPE)
6777         {
6778           /* In Objective-C++, some types may have been 'volatilized' by
6779              the compiler for EH; when comparing them here, the volatile
6780              qualification must be ignored.  */
6781           bool objc_quals_match = objc_type_quals_match (to, from);
6782
6783           if (!at_least_as_qualified_p (to, from) && !objc_quals_match)
6784             return 0;
6785
6786           if (!at_least_as_qualified_p (from, to) && !objc_quals_match)
6787             {
6788               if (constp == 0)
6789                 return 0;
6790               to_more_cv_qualified = true;
6791             }
6792
6793           if (constp > 0)
6794             constp &= TYPE_READONLY (to);
6795         }
6796
6797       if (TREE_CODE (to) != POINTER_TYPE && !TYPE_PTRMEM_P (to))
6798         return ((constp >= 0 || to_more_cv_qualified)
6799                 && same_type_ignoring_top_level_qualifiers_p (to, from));
6800     }
6801 }
6802
6803 /* When comparing, say, char ** to char const **, this function takes
6804    the 'char *' and 'char const *'.  Do not pass non-pointer/reference
6805    types to this function.  */
6806
6807 int
6808 comp_ptr_ttypes (tree to, tree from)
6809 {
6810   return comp_ptr_ttypes_real (to, from, 1);
6811 }
6812
6813 /* Returns 1 if to and from are (possibly multi-level) pointers to the same
6814    type or inheritance-related types, regardless of cv-quals.  */
6815
6816 int
6817 ptr_reasonably_similar (tree to, tree from)
6818 {
6819   for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
6820     {
6821       /* Any target type is similar enough to void.  */
6822       if (TREE_CODE (to) == VOID_TYPE
6823           || TREE_CODE (from) == VOID_TYPE)
6824         return 1;
6825
6826       if (TREE_CODE (to) != TREE_CODE (from))
6827         return 0;
6828
6829       if (TREE_CODE (from) == OFFSET_TYPE
6830           && comptypes (TYPE_OFFSET_BASETYPE (to),
6831                         TYPE_OFFSET_BASETYPE (from),
6832                         COMPARE_BASE | COMPARE_DERIVED))
6833         continue;
6834
6835       if (TREE_CODE (to) == VECTOR_TYPE
6836           && vector_types_convertible_p (to, from))
6837         return 1;
6838
6839       if (TREE_CODE (to) == INTEGER_TYPE
6840           && TYPE_PRECISION (to) == TYPE_PRECISION (from))
6841         return 1;
6842
6843       if (TREE_CODE (to) == FUNCTION_TYPE)
6844         return 1;
6845
6846       if (TREE_CODE (to) != POINTER_TYPE)
6847         return comptypes
6848           (TYPE_MAIN_VARIANT (to), TYPE_MAIN_VARIANT (from),
6849            COMPARE_BASE | COMPARE_DERIVED);
6850     }
6851 }
6852
6853 /* Return true if TO and FROM (both of which are POINTER_TYPEs or
6854    pointer-to-member types) are the same, ignoring cv-qualification at
6855    all levels.  */
6856
6857 bool
6858 comp_ptr_ttypes_const (tree to, tree from)
6859 {
6860   for (; ; to = TREE_TYPE (to), from = TREE_TYPE (from))
6861     {
6862       if (TREE_CODE (to) != TREE_CODE (from))
6863         return false;
6864
6865       if (TREE_CODE (from) == OFFSET_TYPE
6866           && same_type_p (TYPE_OFFSET_BASETYPE (from),
6867                           TYPE_OFFSET_BASETYPE (to)))
6868           continue;
6869
6870       if (TREE_CODE (to) != POINTER_TYPE)
6871         return same_type_ignoring_top_level_qualifiers_p (to, from);
6872     }
6873 }
6874
6875 /* Returns the type qualifiers for this type, including the qualifiers on the
6876    elements for an array type.  */
6877
6878 int
6879 cp_type_quals (tree type)
6880 {
6881   type = strip_array_types (type);
6882   if (type == error_mark_node)
6883     return TYPE_UNQUALIFIED;
6884   return TYPE_QUALS (type);
6885 }
6886
6887 /* Returns nonzero if the TYPE contains a mutable member.  */
6888
6889 bool
6890 cp_has_mutable_p (tree type)
6891 {
6892   type = strip_array_types (type);
6893
6894   return CLASS_TYPE_P (type) && CLASSTYPE_HAS_MUTABLE (type);
6895 }
6896
6897 /* Apply the TYPE_QUALS to the new DECL.  */
6898 void
6899 cp_apply_type_quals_to_decl (int type_quals, tree decl)
6900 {
6901   tree type = TREE_TYPE (decl);
6902
6903   if (type == error_mark_node)
6904     return;
6905
6906   if (TREE_CODE (type) == FUNCTION_TYPE
6907       && type_quals != TYPE_UNQUALIFIED)
6908     {
6909       /* This was an error in C++98 (cv-qualifiers cannot be added to
6910          a function type), but DR 295 makes the code well-formed by
6911          dropping the extra qualifiers. */
6912       if (pedantic)
6913         {
6914           tree bad_type = build_qualified_type (type, type_quals);
6915           pedwarn ("ignoring %qV qualifiers added to function type %qT",
6916                    bad_type, type);
6917         }
6918
6919       TREE_TYPE (decl) = TYPE_MAIN_VARIANT (type);
6920       return;
6921     }
6922
6923   /* Avoid setting TREE_READONLY incorrectly.  */
6924   if (/* If the object has a constructor, the constructor may modify
6925          the object.  */
6926       TYPE_NEEDS_CONSTRUCTING (type)
6927       /* If the type isn't complete, we don't know yet if it will need
6928          constructing.  */
6929       || !COMPLETE_TYPE_P (type)
6930       /* If the type has a mutable component, that component might be
6931          modified.  */
6932       || TYPE_HAS_MUTABLE_P (type))
6933     type_quals &= ~TYPE_QUAL_CONST;
6934
6935   c_apply_type_quals_to_decl (type_quals, decl);
6936 }
6937
6938 /* Subroutine of casts_away_constness.  Make T1 and T2 point at
6939    exemplar types such that casting T1 to T2 is casting away constness
6940    if and only if there is no implicit conversion from T1 to T2.  */
6941
6942 static void
6943 casts_away_constness_r (tree *t1, tree *t2)
6944 {
6945   int quals1;
6946   int quals2;
6947
6948   /* [expr.const.cast]
6949
6950      For multi-level pointer to members and multi-level mixed pointers
6951      and pointers to members (conv.qual), the "member" aspect of a
6952      pointer to member level is ignored when determining if a const
6953      cv-qualifier has been cast away.  */
6954   /* [expr.const.cast]
6955
6956      For  two  pointer types:
6957
6958             X1 is T1cv1,1 * ... cv1,N *   where T1 is not a pointer type
6959             X2 is T2cv2,1 * ... cv2,M *   where T2 is not a pointer type
6960             K is min(N,M)
6961
6962      casting from X1 to X2 casts away constness if, for a non-pointer
6963      type T there does not exist an implicit conversion (clause
6964      _conv_) from:
6965
6966             Tcv1,(N-K+1) * cv1,(N-K+2) * ... cv1,N *
6967
6968      to
6969
6970             Tcv2,(M-K+1) * cv2,(M-K+2) * ... cv2,M *.  */
6971   if ((!TYPE_PTR_P (*t1) && !TYPE_PTRMEM_P (*t1))
6972       || (!TYPE_PTR_P (*t2) && !TYPE_PTRMEM_P (*t2)))
6973     {
6974       *t1 = cp_build_qualified_type (void_type_node,
6975                                      cp_type_quals (*t1));
6976       *t2 = cp_build_qualified_type (void_type_node,
6977                                      cp_type_quals (*t2));
6978       return;
6979     }
6980
6981   quals1 = cp_type_quals (*t1);
6982   quals2 = cp_type_quals (*t2);
6983
6984   if (TYPE_PTRMEM_P (*t1))
6985     *t1 = TYPE_PTRMEM_POINTED_TO_TYPE (*t1);
6986   else
6987     *t1 = TREE_TYPE (*t1);
6988   if (TYPE_PTRMEM_P (*t2))
6989     *t2 = TYPE_PTRMEM_POINTED_TO_TYPE (*t2);
6990   else
6991     *t2 = TREE_TYPE (*t2);
6992
6993   casts_away_constness_r (t1, t2);
6994   *t1 = build_pointer_type (*t1);
6995   *t2 = build_pointer_type (*t2);
6996   *t1 = cp_build_qualified_type (*t1, quals1);
6997   *t2 = cp_build_qualified_type (*t2, quals2);
6998 }
6999
7000 /* Returns nonzero if casting from TYPE1 to TYPE2 casts away
7001    constness.  */
7002
7003 static bool
7004 casts_away_constness (tree t1, tree t2)
7005 {
7006   if (TREE_CODE (t2) == REFERENCE_TYPE)
7007     {
7008       /* [expr.const.cast]
7009
7010          Casting from an lvalue of type T1 to an lvalue of type T2
7011          using a reference cast casts away constness if a cast from an
7012          rvalue of type "pointer to T1" to the type "pointer to T2"
7013          casts away constness.  */
7014       t1 = (TREE_CODE (t1) == REFERENCE_TYPE ? TREE_TYPE (t1) : t1);
7015       return casts_away_constness (build_pointer_type (t1),
7016                                    build_pointer_type (TREE_TYPE (t2)));
7017     }
7018
7019   if (TYPE_PTRMEM_P (t1) && TYPE_PTRMEM_P (t2))
7020     /* [expr.const.cast]
7021
7022        Casting from an rvalue of type "pointer to data member of X
7023        of type T1" to the type "pointer to data member of Y of type
7024        T2" casts away constness if a cast from an rvalue of type
7025        "pointer to T1" to the type "pointer to T2" casts away
7026        constness.  */
7027     return casts_away_constness
7028       (build_pointer_type (TYPE_PTRMEM_POINTED_TO_TYPE (t1)),
7029        build_pointer_type (TYPE_PTRMEM_POINTED_TO_TYPE (t2)));
7030
7031   /* Casting away constness is only something that makes sense for
7032      pointer or reference types.  */
7033   if (TREE_CODE (t1) != POINTER_TYPE
7034       || TREE_CODE (t2) != POINTER_TYPE)
7035     return false;
7036
7037   /* Top-level qualifiers don't matter.  */
7038   t1 = TYPE_MAIN_VARIANT (t1);
7039   t2 = TYPE_MAIN_VARIANT (t2);
7040   casts_away_constness_r (&t1, &t2);
7041   if (!can_convert (t2, t1))
7042     return true;
7043
7044   return false;
7045 }
7046
7047 /* If T is a REFERENCE_TYPE return the type to which T refers.
7048    Otherwise, return T itself.  */
7049
7050 tree
7051 non_reference (tree t)
7052 {
7053   if (TREE_CODE (t) == REFERENCE_TYPE)
7054     t = TREE_TYPE (t);
7055   return t;
7056 }
7057
7058
7059 /* Return nonzero if REF is an lvalue valid for this language;
7060    otherwise, print an error message and return zero.  USE says
7061    how the lvalue is being used and so selects the error message.  */
7062
7063 int
7064 lvalue_or_else (tree ref, enum lvalue_use use)
7065 {
7066   int win = lvalue_p (ref);
7067
7068   if (!win)
7069     lvalue_error (use);
7070
7071   return win;
7072 }