OSDN Git Service

PR c++/15742
[pf3gnuchains/gcc-fork.git] / gcc / cp / name-lookup.c
1 /* Definitions for C++ name lookup routines.
2    Copyright (C) 2003, 2004 Free Software Foundation, Inc.
3    Contributed by Gabriel Dos Reis <gdr@integrable-solutions.net>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "flags.h"
27 #include "tree.h"
28 #include "cp-tree.h"
29 #include "name-lookup.h"
30 #include "timevar.h"
31 #include "toplev.h"
32 #include "diagnostic.h"
33 #include "debug.h"
34
35 /* The bindings for a particular name in a particular scope.  */
36
37 struct scope_binding {
38   tree value;
39   tree type;
40 };
41 #define EMPTY_SCOPE_BINDING { NULL_TREE, NULL_TREE }
42
43 static cxx_scope *innermost_nonclass_level (void);
44 static tree select_decl (const struct scope_binding *, int);
45 static cxx_binding *binding_for_name (cxx_scope *, tree);
46 static tree lookup_name_current_level (tree);
47 static tree push_overloaded_decl (tree, int);
48 static bool lookup_using_namespace (tree, struct scope_binding *, tree,
49                                     tree, int);
50 static bool qualified_lookup_using_namespace (tree, tree,
51                                               struct scope_binding *, int);
52 static tree lookup_type_current_level (tree);
53 static tree push_using_directive (tree);
54 static void cp_emit_debug_info_for_using (tree, tree);
55
56 /* The :: namespace.  */
57
58 tree global_namespace;
59
60 /* The name of the anonymous namespace, throughout this translation
61    unit.  */
62 static GTY(()) tree anonymous_namespace_name;
63
64
65 /* Compute the chain index of a binding_entry given the HASH value of its
66    name and the total COUNT of chains.  COUNT is assumed to be a power
67    of 2.  */
68
69 #define ENTRY_INDEX(HASH, COUNT) (((HASH) >> 3) & ((COUNT) - 1))
70
71 /* A free list of "binding_entry"s awaiting for re-use.  */
72
73 static GTY((deletable)) binding_entry free_binding_entry = NULL;
74
75 /* Create a binding_entry object for (NAME, TYPE).  */
76
77 static inline binding_entry
78 binding_entry_make (tree name, tree type)
79 {
80   binding_entry entry;
81
82   if (free_binding_entry)
83     {
84       entry = free_binding_entry;
85       free_binding_entry = entry->chain;
86     }
87   else
88     entry = ggc_alloc (sizeof (struct binding_entry_s));
89
90   entry->name = name;
91   entry->type = type;
92   entry->chain = NULL;
93
94   return entry;
95 }
96
97 /* Put ENTRY back on the free list.  */
98
99 static inline void
100 binding_entry_free (binding_entry entry)
101 {
102   entry->name = NULL;
103   entry->type = NULL;
104   entry->chain = free_binding_entry;
105   free_binding_entry = entry;
106 }
107
108 /* The datatype used to implement the mapping from names to types at
109    a given scope.  */
110 struct binding_table_s GTY(())
111 {
112   /* Array of chains of "binding_entry"s  */
113   binding_entry * GTY((length ("%h.chain_count"))) chain;
114
115   /* The number of chains in this table.  This is the length of the
116      the member "chain" considered as an array.  */
117   size_t chain_count;
118
119   /* Number of "binding_entry"s in this table.  */
120   size_t entry_count;
121 };
122
123 /* Construct TABLE with an initial CHAIN_COUNT.  */
124
125 static inline void
126 binding_table_construct (binding_table table, size_t chain_count)
127 {
128   table->chain_count = chain_count;
129   table->entry_count = 0;
130   table->chain = ggc_alloc_cleared
131     (table->chain_count * sizeof (binding_entry));
132 }
133
134 /* Make TABLE's entries ready for reuse.  */
135
136 static void
137 binding_table_free (binding_table table)
138 {
139   size_t i;
140   size_t count;
141
142   if (table == NULL)
143     return;
144
145   for (i = 0, count = table->chain_count; i < count; ++i)
146     {
147       binding_entry temp = table->chain[i];
148       while (temp != NULL)
149         {
150           binding_entry entry = temp;
151           temp = entry->chain;
152           binding_entry_free (entry);
153         }
154       table->chain[i] = NULL;
155     }
156   table->entry_count = 0;
157 }
158
159 /* Allocate a table with CHAIN_COUNT, assumed to be a power of two.  */
160
161 static inline binding_table
162 binding_table_new (size_t chain_count)
163 {
164   binding_table table = ggc_alloc (sizeof (struct binding_table_s));
165   table->chain = NULL;
166   binding_table_construct (table, chain_count);
167   return table;
168 }
169
170 /* Expand TABLE to twice its current chain_count.  */
171
172 static void
173 binding_table_expand (binding_table table)
174 {
175   const size_t old_chain_count = table->chain_count;
176   const size_t old_entry_count = table->entry_count;
177   const size_t new_chain_count = 2 * old_chain_count;
178   binding_entry *old_chains = table->chain;
179   size_t i;
180
181   binding_table_construct (table, new_chain_count);
182   for (i = 0; i < old_chain_count; ++i)
183     {
184       binding_entry entry = old_chains[i];
185       for (; entry != NULL; entry = old_chains[i])
186         {
187           const unsigned int hash = IDENTIFIER_HASH_VALUE (entry->name);
188           const size_t j = ENTRY_INDEX (hash, new_chain_count);
189
190           old_chains[i] = entry->chain;
191           entry->chain = table->chain[j];
192           table->chain[j] = entry;
193         }
194     }
195   table->entry_count = old_entry_count;
196 }
197
198 /* Insert a binding for NAME to TYPE into TABLE.  */
199
200 static void
201 binding_table_insert (binding_table table, tree name, tree type)
202 {
203   const unsigned int hash = IDENTIFIER_HASH_VALUE (name);
204   const size_t i = ENTRY_INDEX (hash, table->chain_count);
205   binding_entry entry = binding_entry_make (name, type);
206
207   entry->chain = table->chain[i];
208   table->chain[i] = entry;
209   ++table->entry_count;
210
211   if (3 * table->chain_count < 5 * table->entry_count)
212     binding_table_expand (table);
213 }
214
215 /* Return the binding_entry, if any, that maps NAME.  */
216
217 binding_entry
218 binding_table_find (binding_table table, tree name)
219 {
220   const unsigned int hash = IDENTIFIER_HASH_VALUE (name);
221   binding_entry entry = table->chain[ENTRY_INDEX (hash, table->chain_count)];
222
223   while (entry != NULL && entry->name != name)
224     entry = entry->chain;
225
226   return entry;
227 }
228
229 /* Return the binding_entry, if any, that maps NAME to an anonymous type.  */
230
231 static tree
232 binding_table_find_anon_type (binding_table table, tree name)
233 {
234   const unsigned int hash = IDENTIFIER_HASH_VALUE (name);
235   binding_entry entry = table->chain[ENTRY_INDEX (hash, table->chain_count)];
236
237   while (entry != NULL && TYPE_IDENTIFIER (entry->type) != name)
238     entry = entry->chain;
239
240   return entry ? entry->type : NULL;
241 }
242
243 /* Return the binding_entry, if any, that has TYPE as target.  If NAME
244    is non-null, then set the domain and rehash that entry.  */
245
246 static binding_entry
247 binding_table_reverse_maybe_remap (binding_table table, tree type, tree name)
248 {
249   const size_t chain_count = table->chain_count;
250   binding_entry entry = NULL;
251   binding_entry *p = NULL;
252   size_t i;
253
254   for (i = 0; i < chain_count && entry == NULL; ++i)
255     {
256       p = &table->chain[i];
257       while (*p != NULL && entry == NULL)
258         if ((*p)->type == type)
259           entry = *p;
260         else
261           p = &(*p)->chain;
262     }
263
264   if (entry != NULL && name != NULL && entry->name != name)
265     {
266       /* Remove the bucket from the previous chain.  */
267       *p = (*p)->chain;
268
269       /* Remap the name type to type.  */
270       i = ENTRY_INDEX (IDENTIFIER_HASH_VALUE (name), chain_count);
271       entry->chain = table->chain[i];
272       entry->name = name;
273       table->chain[i] = entry;
274     }
275
276   return entry;
277 }
278
279 /* Remove from TABLE all entries that map to anonymous enums or
280    class-types.  */
281
282 void
283 binding_table_remove_anonymous_types (binding_table table)
284 {
285   const size_t chain_count = table->chain_count;
286   size_t i;
287
288   for (i = 0; i < chain_count; ++i)
289     {
290       binding_entry *p = &table->chain[i];
291
292       while (*p != NULL)
293         if (ANON_AGGRNAME_P ((*p)->name))
294           {
295             binding_entry e = *p;
296             *p = (*p)->chain;
297             --table->entry_count;
298             binding_entry_free (e);
299           }
300         else
301           p = &(*p)->chain;
302     }
303 }
304
305 /* Apply PROC -- with DATA -- to all entries in TABLE.  */
306
307 void
308 binding_table_foreach (binding_table table, bt_foreach_proc proc, void *data)
309 {
310   const size_t chain_count = table->chain_count;
311   size_t i;
312
313   for (i = 0; i < chain_count; ++i)
314     {
315       binding_entry entry = table->chain[i];
316       for (; entry != NULL; entry = entry->chain)
317         proc (entry, data);
318     }
319 }
320 \f
321 #ifndef ENABLE_SCOPE_CHECKING
322 #  define ENABLE_SCOPE_CHECKING 0
323 #else
324 #  define ENABLE_SCOPE_CHECKING 1
325 #endif
326
327 /* A free list of "cxx_binding"s, connected by their PREVIOUS.  */
328
329 static GTY((deletable)) cxx_binding *free_bindings;
330
331 /* (GC)-allocate a binding object with VALUE and TYPE member initialized.  */
332
333 static cxx_binding *
334 cxx_binding_make (tree value, tree type)
335 {
336   cxx_binding *binding;
337   if (free_bindings)
338     {
339       binding = free_bindings;
340       free_bindings = binding->previous;
341     }
342   else
343     binding = ggc_alloc (sizeof (cxx_binding));
344
345   binding->value = value;
346   binding->type = type;
347   binding->previous = NULL;
348
349   return binding;
350 }
351
352 /* Put BINDING back on the free list.  */
353
354 static inline void
355 cxx_binding_free (cxx_binding *binding)
356 {
357   binding->scope = NULL;
358   binding->previous = free_bindings;
359   free_bindings = binding;
360 }
361
362 /* Make DECL the innermost binding for ID.  The LEVEL is the binding
363    level at which this declaration is being bound.  */
364
365 static void
366 push_binding (tree id, tree decl, cxx_scope* level)
367 {
368    cxx_binding *binding = cxx_binding_make (decl, NULL);
369
370   /* Now, fill in the binding information.  */
371   binding->previous = IDENTIFIER_BINDING (id);
372   binding->scope = level;
373   INHERITED_VALUE_BINDING_P (binding) = 0;
374   LOCAL_BINDING_P (binding) = (level != class_binding_level);
375
376   /* And put it on the front of the list of bindings for ID.  */
377   IDENTIFIER_BINDING (id) = binding;
378 }
379
380 /* Remove the binding for DECL which should be the innermost binding
381    for ID.  */
382
383 void
384 pop_binding (tree id, tree decl)
385 {
386   cxx_binding *binding;
387
388   if (id == NULL_TREE)
389     /* It's easiest to write the loops that call this function without
390        checking whether or not the entities involved have names.  We
391        get here for such an entity.  */
392     return;
393
394   /* Get the innermost binding for ID.  */
395   binding = IDENTIFIER_BINDING (id);
396
397   /* The name should be bound.  */
398   my_friendly_assert (binding != NULL, 0);
399
400   /* The DECL will be either the ordinary binding or the type
401      binding for this identifier.  Remove that binding.  */
402   if (binding->value == decl)
403     binding->value = NULL_TREE;
404   else if (binding->type == decl)
405     binding->type = NULL_TREE;
406   else
407     abort ();
408
409   if (!binding->value && !binding->type)
410     {
411       /* We're completely done with the innermost binding for this
412          identifier.  Unhook it from the list of bindings.  */
413       IDENTIFIER_BINDING (id) = binding->previous;
414
415       /* Add it to the free list.  */
416       cxx_binding_free (binding);
417     }
418 }
419
420 /* BINDING records an existing declaration for a namein the current scope.
421    But, DECL is another declaration for that same identifier in the
422    same scope.  This is the `struct stat' hack whereby a non-typedef
423    class name or enum-name can be bound at the same level as some other
424    kind of entity.
425    3.3.7/1
426
427      A class name (9.1) or enumeration name (7.2) can be hidden by the
428      name of an object, function, or enumerator declared in the same scope.
429      If a class or enumeration name and an object, function, or enumerator
430      are declared in the same scope (in any order) with the same name, the
431      class or enumeration name is hidden wherever the object, function, or
432      enumerator name is visible.
433
434    It's the responsibility of the caller to check that
435    inserting this name is valid here.  Returns nonzero if the new binding
436    was successful.  */
437
438 static bool
439 supplement_binding (cxx_binding *binding, tree decl)
440 {
441   tree bval = binding->value;
442   bool ok = true;
443
444   timevar_push (TV_NAME_LOOKUP);
445   if (TREE_CODE (decl) == TYPE_DECL && DECL_ARTIFICIAL (decl))
446     /* The new name is the type name.  */
447     binding->type = decl;
448   else if (/* BVAL is null when push_class_level_binding moves an
449               inherited type-binding out of the way to make room for a
450               new value binding.  */
451            !bval 
452            /* BVAL is error_mark_node when DECL's name has been used
453               in a non-class scope prior declaration.  In that case,
454               we should have already issued a diagnostic; for graceful
455               error recovery purpose, pretend this was the intended
456               declaration for that name.  */
457            || bval == error_mark_node
458            /* If BVAL is a built-in that has not yet been declared,
459               pretend it is not there at all.  */
460            || (TREE_CODE (bval) == FUNCTION_DECL
461                && DECL_ANTICIPATED (bval)))
462     binding->value = decl;
463   else if (TREE_CODE (bval) == TYPE_DECL && DECL_ARTIFICIAL (bval))
464     {
465       /* The old binding was a type name.  It was placed in
466          VALUE field because it was thought, at the point it was
467          declared, to be the only entity with such a name.  Move the
468          type name into the type slot; it is now hidden by the new
469          binding.  */
470       binding->type = bval;
471       binding->value = decl;
472       binding->value_is_inherited = false;
473     }
474   else if (TREE_CODE (bval) == TYPE_DECL
475            && TREE_CODE (decl) == TYPE_DECL
476            && DECL_NAME (decl) == DECL_NAME (bval)
477            && (same_type_p (TREE_TYPE (decl), TREE_TYPE (bval))
478                /* If either type involves template parameters, we must
479                   wait until instantiation.  */
480                || uses_template_parms (TREE_TYPE (decl))
481                || uses_template_parms (TREE_TYPE (bval))))
482     /* We have two typedef-names, both naming the same type to have
483        the same name.  This is OK because of:
484
485          [dcl.typedef]
486
487          In a given scope, a typedef specifier can be used to redefine
488          the name of any type declared in that scope to refer to the
489          type to which it already refers.  */
490     ok = false;
491   /* There can be two block-scope declarations of the same variable,
492      so long as they are `extern' declarations.  However, there cannot
493      be two declarations of the same static data member:
494
495        [class.mem]
496
497        A member shall not be declared twice in the
498        member-specification.  */
499   else if (TREE_CODE (decl) == VAR_DECL && TREE_CODE (bval) == VAR_DECL
500            && DECL_EXTERNAL (decl) && DECL_EXTERNAL (bval)
501            && !DECL_CLASS_SCOPE_P (decl))
502     {
503       duplicate_decls (decl, binding->value);
504       ok = false;
505     }
506   else if (TREE_CODE (decl) == NAMESPACE_DECL
507            && TREE_CODE (bval) == NAMESPACE_DECL
508            && DECL_NAMESPACE_ALIAS (decl)
509            && DECL_NAMESPACE_ALIAS (bval)
510            && ORIGINAL_NAMESPACE (bval) == ORIGINAL_NAMESPACE (decl))
511     /* [namespace.alias]
512        
513       In a declarative region, a namespace-alias-definition can be
514       used to redefine a namespace-alias declared in that declarative
515       region to refer only to the namespace to which it already
516       refers.  */
517     ok = false;
518   else
519     {
520       error ("declaration of `%#D'", decl);
521       cp_error_at ("conflicts with previous declaration `%#D'", bval);
522       ok = false;
523     }
524
525   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ok);
526 }
527
528 /* Add DECL to the list of things declared in B.  */
529
530 static void
531 add_decl_to_level (tree decl, cxx_scope *b)
532 {
533   if (TREE_CODE (decl) == NAMESPACE_DECL 
534       && !DECL_NAMESPACE_ALIAS (decl))
535     {
536       TREE_CHAIN (decl) = b->namespaces;
537       b->namespaces = decl;
538     }
539   else if (TREE_CODE (decl) == VAR_DECL && DECL_VIRTUAL_P (decl))
540     {
541       TREE_CHAIN (decl) = b->vtables;
542       b->vtables = decl;
543     }
544   else       
545     {
546       /* We build up the list in reverse order, and reverse it later if
547          necessary.  */
548       TREE_CHAIN (decl) = b->names;
549       b->names = decl;
550       b->names_size++;
551
552       /* If appropriate, add decl to separate list of statics.  We
553          include extern variables because they might turn out to be 
554          static later.  It's OK for this list to contain a few false
555          positives.  */
556       if (b->kind == sk_namespace)
557         if ((TREE_CODE (decl) == VAR_DECL
558              && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
559             || (TREE_CODE (decl) == FUNCTION_DECL
560                 && (!TREE_PUBLIC (decl) || DECL_DECLARED_INLINE_P (decl))))
561           VARRAY_PUSH_TREE (b->static_decls, decl);
562     }
563 }
564
565 /* Record a decl-node X as belonging to the current lexical scope.
566    Check for errors (such as an incompatible declaration for the same
567    name already seen in the same scope).
568
569    Returns either X or an old decl for the same name.
570    If an old decl is returned, it may have been smashed
571    to agree with what X says.  */
572
573 tree
574 pushdecl (tree x)
575 {
576   tree t;
577   tree name;
578   int need_new_binding;
579
580   timevar_push (TV_NAME_LOOKUP);
581
582   need_new_binding = 1;
583
584   if (DECL_TEMPLATE_PARM_P (x))
585     /* Template parameters have no context; they are not X::T even
586        when declared within a class or namespace.  */
587     ;
588   else
589     {
590       if (current_function_decl && x != current_function_decl
591           /* A local declaration for a function doesn't constitute
592              nesting.  */
593           && TREE_CODE (x) != FUNCTION_DECL
594           /* A local declaration for an `extern' variable is in the
595              scope of the current namespace, not the current
596              function.  */
597           && !(TREE_CODE (x) == VAR_DECL && DECL_EXTERNAL (x))
598           && !DECL_CONTEXT (x))
599         DECL_CONTEXT (x) = current_function_decl;
600
601       /* If this is the declaration for a namespace-scope function,
602          but the declaration itself is in a local scope, mark the
603          declaration.  */
604       if (TREE_CODE (x) == FUNCTION_DECL
605           && DECL_NAMESPACE_SCOPE_P (x)
606           && current_function_decl
607           && x != current_function_decl)
608         DECL_LOCAL_FUNCTION_P (x) = 1;
609     }
610
611   name = DECL_NAME (x);
612   if (name)
613     {
614       int different_binding_level = 0;
615
616       if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
617         name = TREE_OPERAND (name, 0);
618
619       /* In case this decl was explicitly namespace-qualified, look it
620          up in its namespace context.  */
621       if (DECL_NAMESPACE_SCOPE_P (x) && namespace_bindings_p ())
622         t = namespace_binding (name, DECL_CONTEXT (x));
623       else
624         t = lookup_name_current_level (name);
625
626       /* [basic.link] If there is a visible declaration of an entity
627          with linkage having the same name and type, ignoring entities
628          declared outside the innermost enclosing namespace scope, the
629          block scope declaration declares that same entity and
630          receives the linkage of the previous declaration.  */
631       if (! t && current_function_decl && x != current_function_decl
632           && (TREE_CODE (x) == FUNCTION_DECL || TREE_CODE (x) == VAR_DECL)
633           && DECL_EXTERNAL (x))
634         {
635           /* Look in block scope.  */
636           t = IDENTIFIER_VALUE (name);
637           /* Or in the innermost namespace.  */
638           if (! t)
639             t = namespace_binding (name, DECL_CONTEXT (x));
640           /* Does it have linkage?  Note that if this isn't a DECL, it's an
641              OVERLOAD, which is OK.  */
642           if (t && DECL_P (t) && ! (TREE_STATIC (t) || DECL_EXTERNAL (t)))
643             t = NULL_TREE;
644           if (t)
645             different_binding_level = 1;
646         }
647
648       /* If we are declaring a function, and the result of name-lookup
649          was an OVERLOAD, look for an overloaded instance that is
650          actually the same as the function we are declaring.  (If
651          there is one, we have to merge our declaration with the
652          previous declaration.)  */
653       if (t && TREE_CODE (t) == OVERLOAD)
654         {
655           tree match;
656
657           if (TREE_CODE (x) == FUNCTION_DECL)
658             for (match = t; match; match = OVL_NEXT (match))
659               {
660                 if (decls_match (OVL_CURRENT (match), x))
661                   break;
662               }
663           else
664             /* Just choose one.  */
665             match = t;
666
667           if (match)
668             t = OVL_CURRENT (match);
669           else
670             t = NULL_TREE;
671         }
672
673       if (t && t != error_mark_node)
674         {
675           if (different_binding_level)
676             {
677               if (decls_match (x, t))
678                 /* The standard only says that the local extern
679                    inherits linkage from the previous decl; in
680                    particular, default args are not shared.  It would
681                    be nice to propagate inlining info, though.  FIXME.  */
682                 TREE_PUBLIC (x) = TREE_PUBLIC (t);
683             }
684           else if (TREE_CODE (t) == PARM_DECL)
685             {
686               if (DECL_CONTEXT (t) == NULL_TREE)
687                 /* This is probably caused by too many errors, but calling
688                    abort will say that if errors have occurred.  */
689                 abort ();
690
691               /* Check for duplicate params.  */
692               if (duplicate_decls (x, t))
693                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
694             }
695           else if ((DECL_EXTERN_C_FUNCTION_P (x)
696                     || DECL_FUNCTION_TEMPLATE_P (x))
697                    && is_overloaded_fn (t))
698             /* Don't do anything just yet.  */;
699           else if (t == wchar_decl_node)
700             {
701               if (pedantic && ! DECL_IN_SYSTEM_HEADER (x))
702                 pedwarn ("redeclaration of `wchar_t' as `%T'",
703                             TREE_TYPE (x));
704
705               /* Throw away the redeclaration.  */
706               POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
707             }
708           else
709             {
710               tree olddecl = duplicate_decls (x, t);
711               
712               /* If the redeclaration failed, we can stop at this
713                  point.  */
714               if (olddecl == error_mark_node)
715                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
716
717               if (olddecl)
718                 {
719                   if (TREE_CODE (t) == TYPE_DECL)
720                     SET_IDENTIFIER_TYPE_VALUE (name, TREE_TYPE (t));
721                   else if (TREE_CODE (t) == FUNCTION_DECL)
722                     check_default_args (t);
723
724                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
725                 }
726               else if (DECL_MAIN_P (x) && TREE_CODE (t) == FUNCTION_DECL)
727                 {
728                   /* A redeclaration of main, but not a duplicate of the
729                      previous one.
730                      
731                      [basic.start.main]
732                      
733                      This function shall not be overloaded.  */
734                   cp_error_at ("invalid redeclaration of `%D'", t);
735                   error ("as `%D'", x);
736                   /* We don't try to push this declaration since that
737                      causes a crash.  */
738                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
739                 }
740             }
741         }
742
743       check_template_shadow (x);
744
745       /* If this is a function conjured up by the backend, massage it
746          so it looks friendly.  */
747       if (DECL_NON_THUNK_FUNCTION_P (x) && ! DECL_LANG_SPECIFIC (x))
748         {
749           retrofit_lang_decl (x);
750           SET_DECL_LANGUAGE (x, lang_c);
751         }
752
753       if (DECL_NON_THUNK_FUNCTION_P (x) && ! DECL_FUNCTION_MEMBER_P (x))
754         {
755           t = push_overloaded_decl (x, PUSH_LOCAL);
756           if (t != x)
757             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
758           if (!namespace_bindings_p ())
759             /* We do not need to create a binding for this name;
760                push_overloaded_decl will have already done so if
761                necessary.  */
762             need_new_binding = 0;
763         }
764       else if (DECL_FUNCTION_TEMPLATE_P (x) && DECL_NAMESPACE_SCOPE_P (x))
765         {
766           t = push_overloaded_decl (x, PUSH_GLOBAL);
767           if (t == x)
768             add_decl_to_level (x, NAMESPACE_LEVEL (CP_DECL_CONTEXT (t)));
769           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
770         }
771
772       /* If declaring a type as a typedef, copy the type (unless we're
773          at line 0), and install this TYPE_DECL as the new type's typedef
774          name.  See the extensive comment in ../c-decl.c (pushdecl).  */
775       if (TREE_CODE (x) == TYPE_DECL)
776         {
777           tree type = TREE_TYPE (x);
778           if (DECL_SOURCE_LINE (x) == 0)
779             {
780               if (TYPE_NAME (type) == 0)
781                 TYPE_NAME (type) = x;
782             }
783           else if (type != error_mark_node && TYPE_NAME (type) != x
784                    /* We don't want to copy the type when all we're
785                       doing is making a TYPE_DECL for the purposes of
786                       inlining.  */
787                    && (!TYPE_NAME (type)
788                        || TYPE_NAME (type) != DECL_ABSTRACT_ORIGIN (x)))
789             {
790               DECL_ORIGINAL_TYPE (x) = type;
791               type = build_type_copy (type);
792               TYPE_STUB_DECL (type) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
793               TYPE_NAME (type) = x;
794               TREE_TYPE (x) = type;
795             }
796
797           if (type != error_mark_node
798               && TYPE_NAME (type)
799               && TYPE_IDENTIFIER (type))
800             set_identifier_type_value (DECL_NAME (x), x);
801         }
802
803       /* Multiple external decls of the same identifier ought to match.
804
805          We get warnings about inline functions where they are defined.
806          We get warnings about other functions from push_overloaded_decl.
807
808          Avoid duplicate warnings where they are used.  */
809       if (TREE_PUBLIC (x) && TREE_CODE (x) != FUNCTION_DECL)
810         {
811           tree decl;
812
813           decl = IDENTIFIER_NAMESPACE_VALUE (name);
814           if (decl && TREE_CODE (decl) == OVERLOAD)
815             decl = OVL_FUNCTION (decl);
816
817           if (decl && decl != error_mark_node
818               && (DECL_EXTERNAL (decl) || TREE_PUBLIC (decl))
819               /* If different sort of thing, we already gave an error.  */
820               && TREE_CODE (decl) == TREE_CODE (x)
821               && !same_type_p (TREE_TYPE (x), TREE_TYPE (decl)))
822             {
823               pedwarn ("type mismatch with previous external decl of `%#D'", x);
824               cp_pedwarn_at ("previous external decl of `%#D'", decl);
825             }
826         }
827
828       /* This name is new in its binding level.
829          Install the new declaration and return it.  */
830       if (namespace_bindings_p ())
831         {
832           /* Install a global value.  */
833
834           /* If the first global decl has external linkage,
835              warn if we later see static one.  */
836           if (IDENTIFIER_GLOBAL_VALUE (name) == NULL_TREE && TREE_PUBLIC (x))
837             TREE_PUBLIC (name) = 1;
838
839           /* Bind the name for the entity.  */
840           if (!(TREE_CODE (x) == TYPE_DECL && DECL_ARTIFICIAL (x)
841                 && t != NULL_TREE)
842               && (TREE_CODE (x) == TYPE_DECL
843                   || TREE_CODE (x) == VAR_DECL
844                   || TREE_CODE (x) == ALIAS_DECL
845                   || TREE_CODE (x) == NAMESPACE_DECL
846                   || TREE_CODE (x) == CONST_DECL
847                   || TREE_CODE (x) == TEMPLATE_DECL))
848             SET_IDENTIFIER_NAMESPACE_VALUE (name, x);
849
850           /* If new decl is `static' and an `extern' was seen previously,
851              warn about it.  */
852           if (x != NULL_TREE && t != NULL_TREE && decls_match (x, t))
853             warn_extern_redeclared_static (x, t);
854         }
855       else
856         {
857           /* Here to install a non-global value.  */
858           tree oldlocal = IDENTIFIER_VALUE (name);
859           tree oldglobal = IDENTIFIER_NAMESPACE_VALUE (name);
860
861           if (need_new_binding)
862             {
863               push_local_binding (name, x, 0);
864               /* Because push_local_binding will hook X on to the
865                  current_binding_level's name list, we don't want to
866                  do that again below.  */
867               need_new_binding = 0;
868             }
869
870           /* If this is a TYPE_DECL, push it into the type value slot.  */
871           if (TREE_CODE (x) == TYPE_DECL)
872             set_identifier_type_value (name, x);
873
874           /* Clear out any TYPE_DECL shadowed by a namespace so that
875              we won't think this is a type.  The C struct hack doesn't
876              go through namespaces.  */
877           if (TREE_CODE (x) == NAMESPACE_DECL)
878             set_identifier_type_value (name, NULL_TREE);
879
880           if (oldlocal)
881             {
882               tree d = oldlocal;
883
884               while (oldlocal
885                      && TREE_CODE (oldlocal) == VAR_DECL
886                      && DECL_DEAD_FOR_LOCAL (oldlocal))
887                 oldlocal = DECL_SHADOWED_FOR_VAR (oldlocal);
888
889               if (oldlocal == NULL_TREE)
890                 oldlocal = IDENTIFIER_NAMESPACE_VALUE (DECL_NAME (d));
891             }
892
893           /* If this is an extern function declaration, see if we
894              have a global definition or declaration for the function.  */
895           if (oldlocal == NULL_TREE
896               && DECL_EXTERNAL (x)
897               && oldglobal != NULL_TREE
898               && TREE_CODE (x) == FUNCTION_DECL
899               && TREE_CODE (oldglobal) == FUNCTION_DECL)
900             {
901               /* We have one.  Their types must agree.  */
902               if (decls_match (x, oldglobal))
903                 /* OK */;
904               else
905                 {
906                   warning ("extern declaration of `%#D' doesn't match", x);
907                   cp_warning_at ("global declaration `%#D'", oldglobal);
908                 }
909             }
910           /* If we have a local external declaration,
911              and no file-scope declaration has yet been seen,
912              then if we later have a file-scope decl it must not be static.  */
913           if (oldlocal == NULL_TREE
914               && oldglobal == NULL_TREE
915               && DECL_EXTERNAL (x)
916               && TREE_PUBLIC (x))
917             TREE_PUBLIC (name) = 1;
918
919           /* Warn if shadowing an argument at the top level of the body.  */
920           if (oldlocal != NULL_TREE && !DECL_EXTERNAL (x)
921               /* Inline decls shadow nothing.  */
922               && !DECL_FROM_INLINE (x)
923               && TREE_CODE (oldlocal) == PARM_DECL
924               /* Don't check the `this' parameter.  */
925               && !DECL_ARTIFICIAL (oldlocal))
926             {
927               bool err = false;
928
929               /* Don't complain if it's from an enclosing function.  */
930               if (DECL_CONTEXT (oldlocal) == current_function_decl
931                   && TREE_CODE (x) != PARM_DECL)
932                 {
933                   /* Go to where the parms should be and see if we find
934                      them there.  */
935                   struct cp_binding_level *b = current_binding_level->level_chain;
936
937                   /* Skip the ctor/dtor cleanup level.  */
938                   b = b->level_chain;
939
940                   /* ARM $8.3 */
941                   if (b->kind == sk_function_parms)
942                     {
943                       error ("declaration of '%#D' shadows a parameter", x);
944                       err = true;
945                     }
946                 }
947
948               if (warn_shadow && !err)
949                 {
950                   warning ("declaration of '%#D' shadows a parameter", x);
951                   warning ("%Jshadowed declaration is here", oldlocal);
952                 }
953             }
954
955           /* Maybe warn if shadowing something else.  */
956           else if (warn_shadow && !DECL_EXTERNAL (x)
957               /* No shadow warnings for internally generated vars.  */
958               && ! DECL_ARTIFICIAL (x)
959               /* No shadow warnings for vars made for inlining.  */
960               && ! DECL_FROM_INLINE (x))
961             {
962               if (IDENTIFIER_CLASS_VALUE (name) != NULL_TREE
963                        && current_class_ptr
964                        && !TREE_STATIC (name))
965                 {
966                   /* Location of previous decl is not useful in this case.  */
967                   warning ("declaration of '%D' shadows a member of 'this'",
968                            x);
969                 }
970               else if (oldlocal != NULL_TREE
971                        && TREE_CODE (oldlocal) == VAR_DECL)
972                 {
973                   warning ("declaration of '%D' shadows a previous local", x);
974                   warning ("%Jshadowed declaration is here", oldlocal);
975                 }
976               else if (oldglobal != NULL_TREE
977                        && TREE_CODE (oldglobal) == VAR_DECL)
978                 /* XXX shadow warnings in outer-more namespaces */
979                 {
980                   warning ("declaration of '%D' shadows a global declaration",
981                            x);
982                   warning ("%Jshadowed declaration is here", oldglobal);
983                 }
984             }
985         }
986
987       if (TREE_CODE (x) == FUNCTION_DECL)
988         check_default_args (x);
989
990       if (TREE_CODE (x) == VAR_DECL)
991         maybe_register_incomplete_var (x);
992     }
993
994   if (need_new_binding)
995     add_decl_to_level (x,
996                        DECL_NAMESPACE_SCOPE_P (x)
997                        ? NAMESPACE_LEVEL (CP_DECL_CONTEXT (x))
998                        : current_binding_level);
999
1000   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
1001 }
1002
1003 /* Enter DECL into the symbol table, if that's appropriate.  Returns
1004    DECL, or a modified version thereof.  */
1005
1006 tree
1007 maybe_push_decl (tree decl)
1008 {
1009   tree type = TREE_TYPE (decl);
1010
1011   /* Add this decl to the current binding level, but not if it comes
1012      from another scope, e.g. a static member variable.  TEM may equal
1013      DECL or it may be a previous decl of the same name.  */
1014   if (decl == error_mark_node
1015       || (TREE_CODE (decl) != PARM_DECL
1016           && DECL_CONTEXT (decl) != NULL_TREE
1017           /* Definitions of namespace members outside their namespace are
1018              possible.  */
1019           && TREE_CODE (DECL_CONTEXT (decl)) != NAMESPACE_DECL)
1020       || (TREE_CODE (decl) == TEMPLATE_DECL && !namespace_bindings_p ())
1021       || TREE_CODE (type) == UNKNOWN_TYPE
1022       /* The declaration of a template specialization does not affect
1023          the functions available for overload resolution, so we do not
1024          call pushdecl.  */
1025       || (TREE_CODE (decl) == FUNCTION_DECL
1026           && DECL_TEMPLATE_SPECIALIZATION (decl)))
1027     return decl;
1028   else
1029     return pushdecl (decl);
1030 }
1031
1032 /* Bind DECL to ID in the current_binding_level, assumed to be a local
1033    binding level.  If PUSH_USING is set in FLAGS, we know that DECL
1034    doesn't really belong to this binding level, that it got here
1035    through a using-declaration.  */
1036
1037 void
1038 push_local_binding (tree id, tree decl, int flags)
1039 {
1040   struct cp_binding_level *b;
1041
1042   /* Skip over any local classes.  This makes sense if we call
1043      push_local_binding with a friend decl of a local class.  */
1044   b = innermost_nonclass_level ();
1045
1046   if (lookup_name_current_level (id))
1047     {
1048       /* Supplement the existing binding.  */
1049       if (!supplement_binding (IDENTIFIER_BINDING (id), decl))
1050         /* It didn't work.  Something else must be bound at this
1051            level.  Do not add DECL to the list of things to pop
1052            later.  */
1053         return;
1054     }
1055   else
1056     /* Create a new binding.  */
1057     push_binding (id, decl, b);
1058
1059   if (TREE_CODE (decl) == OVERLOAD || (flags & PUSH_USING))
1060     /* We must put the OVERLOAD into a TREE_LIST since the
1061        TREE_CHAIN of an OVERLOAD is already used.  Similarly for
1062        decls that got here through a using-declaration.  */
1063     decl = build_tree_list (NULL_TREE, decl);
1064
1065   /* And put DECL on the list of things declared by the current
1066      binding level.  */
1067   add_decl_to_level (decl, b);
1068 }
1069
1070 /* The old ARM scoping rules injected variables declared in the
1071    initialization statement of a for-statement into the surrounding
1072    scope.  We support this usage, in order to be backward-compatible.
1073    DECL is a just-declared VAR_DECL; if necessary inject its
1074    declaration into the surrounding scope.  */
1075
1076 void
1077 maybe_inject_for_scope_var (tree decl)
1078 {
1079   timevar_push (TV_NAME_LOOKUP);
1080   if (!DECL_NAME (decl))
1081     {
1082       timevar_pop (TV_NAME_LOOKUP);
1083       return;
1084     }
1085   
1086   /* Declarations of __FUNCTION__ and its ilk appear magically when
1087      the variable is first used.  If that happens to be inside a
1088      for-loop, we don't want to do anything special.  */
1089   if (DECL_PRETTY_FUNCTION_P (decl))
1090     {
1091       timevar_pop (TV_NAME_LOOKUP);
1092       return;
1093     }
1094
1095   if (current_binding_level->kind == sk_for)
1096     {
1097       struct cp_binding_level *outer
1098         = current_binding_level->level_chain;
1099
1100       /* Check to see if the same name is already bound at the outer
1101          level, either because it was directly declared, or because a
1102          dead for-decl got preserved.  In either case, the code would
1103          not have been valid under the ARM scope rules, so clear
1104          is_for_scope for the current_binding_level.
1105
1106          Otherwise, we need to preserve the temp slot for decl to last
1107          into the outer binding level.  */
1108
1109       cxx_binding *outer_binding
1110         = IDENTIFIER_BINDING (DECL_NAME (decl))->previous;
1111
1112       if (outer_binding && outer_binding->scope == outer
1113           && (TREE_CODE (outer_binding->value) == VAR_DECL)
1114           && DECL_DEAD_FOR_LOCAL (outer_binding->value))
1115         {
1116           outer_binding->value = DECL_SHADOWED_FOR_VAR (outer_binding->value);
1117           current_binding_level->kind = sk_block;
1118         }
1119     }
1120   timevar_pop (TV_NAME_LOOKUP);
1121 }
1122
1123 /* Check to see whether or not DECL is a variable that would have been
1124    in scope under the ARM, but is not in scope under the ANSI/ISO
1125    standard.  If so, issue an error message.  If name lookup would
1126    work in both cases, but return a different result, this function
1127    returns the result of ANSI/ISO lookup.  Otherwise, it returns
1128    DECL.  */
1129
1130 tree
1131 check_for_out_of_scope_variable (tree decl)
1132 {
1133   tree shadowed;
1134
1135   /* We only care about out of scope variables.  */
1136   if (!(TREE_CODE (decl) == VAR_DECL && DECL_DEAD_FOR_LOCAL (decl)))
1137     return decl;
1138
1139   shadowed = DECL_SHADOWED_FOR_VAR (decl);
1140   while (shadowed != NULL_TREE && TREE_CODE (shadowed) == VAR_DECL
1141          && DECL_DEAD_FOR_LOCAL (shadowed))
1142     shadowed = DECL_SHADOWED_FOR_VAR (shadowed);
1143   if (!shadowed)
1144     shadowed = IDENTIFIER_NAMESPACE_VALUE (DECL_NAME (decl));
1145   if (shadowed)
1146     {
1147       if (!DECL_ERROR_REPORTED (decl))
1148         {
1149           warning ("name lookup of `%D' changed",
1150                       DECL_NAME (decl));
1151           cp_warning_at ("  matches this `%D' under ISO standard rules",
1152                          shadowed);
1153           cp_warning_at ("  matches this `%D' under old rules", decl);
1154           DECL_ERROR_REPORTED (decl) = 1;
1155         }
1156       return shadowed;
1157     }
1158
1159   /* If we have already complained about this declaration, there's no
1160      need to do it again.  */
1161   if (DECL_ERROR_REPORTED (decl))
1162     return decl;
1163
1164   DECL_ERROR_REPORTED (decl) = 1;
1165
1166   if (TREE_TYPE (decl) == error_mark_node)
1167     return decl;
1168
1169   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
1170     {
1171       error ("name lookup of `%D' changed for new ISO `for' scoping",
1172              DECL_NAME (decl));
1173       cp_error_at ("  cannot use obsolete binding at `%D' because it has a destructor", decl);
1174       return error_mark_node;
1175     }
1176   else
1177     {
1178       pedwarn ("name lookup of `%D' changed for new ISO `for' scoping",
1179                DECL_NAME (decl));
1180       cp_pedwarn_at ("  using obsolete binding at `%D'", decl);
1181     }
1182
1183   return decl;
1184 }
1185 \f
1186 /* true means unconditionally make a BLOCK for the next level pushed.  */
1187
1188 static bool keep_next_level_flag;
1189
1190 static int binding_depth = 0;
1191 static int is_class_level = 0;
1192
1193 static void
1194 indent (int depth)
1195 {
1196   int i;
1197
1198   for (i = 0; i < depth * 2; i++)
1199     putc (' ', stderr);
1200 }
1201
1202 /* Return a string describing the kind of SCOPE we have.  */
1203 static const char *
1204 cxx_scope_descriptor (cxx_scope *scope)
1205 {
1206   /* The order of this table must match the "scope_kind"
1207      enumerators.  */
1208   static const char* scope_kind_names[] = {
1209     "block-scope",
1210     "cleanup-scope",
1211     "try-scope",
1212     "catch-scope",
1213     "for-scope",
1214     "function-parameter-scope",
1215     "class-scope",
1216     "namespace-scope",
1217     "template-parameter-scope",
1218     "template-explicit-spec-scope"
1219   };
1220   const scope_kind kind = scope->explicit_spec_p
1221     ? sk_template_spec : scope->kind;
1222
1223   return scope_kind_names[kind];
1224 }
1225
1226 /* Output a debugging information about SCOPE when performing
1227    ACTION at LINE.  */
1228 static void
1229 cxx_scope_debug (cxx_scope *scope, int line, const char *action)
1230 {
1231   const char *desc = cxx_scope_descriptor (scope);
1232   if (scope->this_entity)
1233     verbatim ("%s %s(%E) %p %d\n", action, desc,
1234               scope->this_entity, (void *) scope, line);
1235   else
1236     verbatim ("%s %s %p %d\n", action, desc, (void *) scope, line);
1237 }
1238
1239 /* Return the estimated initial size of the hashtable of a NAMESPACE
1240    scope.  */
1241
1242 static inline size_t
1243 namespace_scope_ht_size (tree ns)
1244 {
1245   tree name = DECL_NAME (ns);
1246
1247   return name == std_identifier
1248     ? NAMESPACE_STD_HT_SIZE
1249     : (name == global_scope_name
1250        ? GLOBAL_SCOPE_HT_SIZE
1251        : NAMESPACE_ORDINARY_HT_SIZE);
1252 }
1253
1254 /* A chain of binding_level structures awaiting reuse.  */
1255
1256 static GTY((deletable)) struct cp_binding_level *free_binding_level;
1257
1258 /* Create a new KIND scope and make it the top of the active scopes stack.
1259    ENTITY is the scope of the associated C++ entity (namespace, class,
1260    function); it is NULL otherwise.  */
1261
1262 cxx_scope *
1263 begin_scope (scope_kind kind, tree entity)
1264 {
1265   cxx_scope *scope;
1266   
1267   /* Reuse or create a struct for this binding level.  */
1268   if (!ENABLE_SCOPE_CHECKING && free_binding_level)
1269     {
1270       scope = free_binding_level;
1271       free_binding_level = scope->level_chain;
1272     }
1273   else
1274     scope = ggc_alloc (sizeof (cxx_scope));
1275   memset (scope, 0, sizeof (cxx_scope));
1276
1277   scope->this_entity = entity;
1278   scope->more_cleanups_ok = true;
1279   switch (kind)
1280     {
1281     case sk_cleanup:
1282       scope->keep = true;
1283       break;
1284       
1285     case sk_template_spec:
1286       scope->explicit_spec_p = true;
1287       kind = sk_template_parms;
1288       /* Fall through.  */
1289     case sk_template_parms:
1290     case sk_block:
1291     case sk_try:
1292     case sk_catch:
1293     case sk_for:
1294     case sk_class:
1295     case sk_function_parms:
1296       scope->keep = keep_next_level_flag;
1297       break;
1298
1299     case sk_namespace:
1300       scope->type_decls = binding_table_new (namespace_scope_ht_size (entity));
1301       NAMESPACE_LEVEL (entity) = scope;
1302       VARRAY_TREE_INIT (scope->static_decls,
1303                         DECL_NAME (entity) == std_identifier
1304                         || DECL_NAME (entity) == global_scope_name
1305                         ? 200 : 10,
1306                         "Static declarations");
1307       break;
1308
1309     default:
1310       /* Should not happen.  */
1311       my_friendly_assert (false, 20030922);
1312       break;
1313     }
1314   scope->kind = kind;
1315
1316   /* Add it to the front of currently active scopes stack.  */
1317   scope->level_chain = current_binding_level;
1318   current_binding_level = scope;
1319   keep_next_level_flag = false;
1320
1321   if (ENABLE_SCOPE_CHECKING)
1322     {
1323       scope->binding_depth = binding_depth;
1324       indent (binding_depth);
1325       cxx_scope_debug (scope, input_location.line, "push");
1326       is_class_level = 0;
1327       binding_depth++;
1328     }
1329
1330   return scope;
1331 }
1332
1333 /* We're about to leave current scope.  Pop the top of the stack of
1334    currently active scopes.  Return the enclosing scope, now active.  */
1335
1336 cxx_scope *
1337 leave_scope (void)
1338 {
1339   cxx_scope *scope = current_binding_level;
1340
1341   if (scope->kind == sk_namespace && class_binding_level)
1342     current_binding_level = class_binding_level;
1343
1344   /* We cannot leave a scope, if there are none left.  */
1345   if (NAMESPACE_LEVEL (global_namespace))
1346     my_friendly_assert (!global_scope_p (scope), 20030527);
1347   
1348   if (ENABLE_SCOPE_CHECKING)
1349     {
1350       indent (--binding_depth);
1351       cxx_scope_debug (scope, input_location.line, "leave");
1352       if (is_class_level != (scope == class_binding_level))
1353         {
1354           indent (binding_depth);
1355           verbatim ("XXX is_class_level != (current_scope == class_scope)\n");
1356         }
1357       is_class_level = 0;
1358     }
1359
1360   /* Move one nesting level up.  */
1361   current_binding_level = scope->level_chain;
1362
1363   /* Namespace-scopes are left most probably temporarily, not completely;
1364      they can be reopen later, e.g. in namespace-extension or any name
1365      binding activity that requires us to resume a namespace.  For other
1366      scopes, we just make the structure available for reuse.  */
1367   if (scope->kind != sk_namespace)
1368     {
1369       scope->level_chain = free_binding_level;
1370       if (scope->kind == sk_class)
1371         scope->type_decls = NULL;
1372       else
1373         binding_table_free (scope->type_decls);
1374       my_friendly_assert (!ENABLE_SCOPE_CHECKING
1375                           || scope->binding_depth == binding_depth,
1376                           20030529);
1377       free_binding_level = scope;
1378     }
1379
1380   /* Find the innermost enclosing class scope, and reset
1381      CLASS_BINDING_LEVEL appropriately.  */
1382   for (scope = current_binding_level;
1383        scope && scope->kind != sk_class;
1384        scope = scope->level_chain)
1385     ;
1386   class_binding_level = scope && scope->kind == sk_class ? scope : NULL;
1387
1388   return current_binding_level;
1389 }
1390
1391 static void
1392 resume_scope (struct cp_binding_level* b)
1393 {
1394   /* Resuming binding levels is meant only for namespaces,
1395      and those cannot nest into classes.  */
1396   my_friendly_assert(!class_binding_level, 386);
1397   /* Also, resuming a non-directly nested namespace is a no-no.  */
1398   my_friendly_assert(b->level_chain == current_binding_level, 386);
1399   current_binding_level = b;
1400   if (ENABLE_SCOPE_CHECKING)
1401     {
1402       b->binding_depth = binding_depth;
1403       indent (binding_depth);
1404       cxx_scope_debug (b, input_location.line, "resume");
1405       is_class_level = 0;
1406       binding_depth++;
1407     }
1408 }
1409
1410 /* Return the innermost binding level that is not for a class scope.  */
1411
1412 static cxx_scope *
1413 innermost_nonclass_level (void)
1414 {
1415   cxx_scope *b;
1416
1417   b = current_binding_level;
1418   while (b->kind == sk_class)
1419     b = b->level_chain;
1420
1421   return b;
1422 }
1423
1424 /* We're defining an object of type TYPE.  If it needs a cleanup, but
1425    we're not allowed to add any more objects with cleanups to the current
1426    scope, create a new binding level.  */
1427
1428 void
1429 maybe_push_cleanup_level (tree type)
1430 {
1431   if (type != error_mark_node
1432       && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
1433       && current_binding_level->more_cleanups_ok == 0)
1434     {
1435       begin_scope (sk_cleanup, NULL);
1436       clear_last_expr ();
1437       add_scope_stmt (/*begin_p=*/1, /*partial_p=*/1);
1438     }
1439 }
1440
1441 /* Nonzero if we are currently in the global binding level.  */
1442
1443 int
1444 global_bindings_p (void)
1445 {
1446   return global_scope_p (current_binding_level);
1447 }
1448
1449 /* True if we are currently in a toplevel binding level.  This
1450    means either the global binding level or a namespace in a toplevel
1451    binding level.  Since there are no non-toplevel namespace levels,
1452    this really means any namespace or template parameter level.  We
1453    also include a class whose context is toplevel.  */
1454
1455 bool
1456 toplevel_bindings_p (void)
1457 {
1458   struct cp_binding_level *b = innermost_nonclass_level ();
1459
1460   return b->kind == sk_namespace || b->kind == sk_template_parms;
1461 }
1462
1463 /* True if this is a namespace scope, or if we are defining a class
1464    which is itself at namespace scope, or whose enclosing class is
1465    such a class, etc.  */
1466
1467 bool
1468 namespace_bindings_p (void)
1469 {
1470   struct cp_binding_level *b = innermost_nonclass_level ();
1471
1472   return b->kind == sk_namespace;
1473 }
1474
1475 /* True if the current level needs to have a BLOCK made.  */
1476
1477 bool
1478 kept_level_p (void)
1479 {
1480   return (current_binding_level->blocks != NULL_TREE
1481           || current_binding_level->keep
1482           || current_binding_level->kind == sk_cleanup
1483           || current_binding_level->names != NULL_TREE
1484           || current_binding_level->type_decls != NULL);
1485 }
1486
1487 /* Returns the kind of the innermost scope.  */
1488
1489 scope_kind
1490 innermost_scope_kind (void)
1491 {
1492   return current_binding_level->kind;
1493 }
1494
1495 /* Returns true if this scope was created to store template parameters.  */
1496
1497 bool
1498 template_parm_scope_p (void)
1499 {
1500   return innermost_scope_kind () == sk_template_parms;
1501 }
1502
1503 /* If KEEP is true, make a BLOCK node for the next binding level,
1504    unconditionally.  Otherwise, use the normal logic to decide whether
1505    or not to create a BLOCK.  */
1506
1507 void
1508 keep_next_level (bool keep)
1509 {
1510   keep_next_level_flag = keep;
1511 }
1512
1513 /* Return the list of declarations of the current level.
1514    Note that this list is in reverse order unless/until
1515    you nreverse it; and when you do nreverse it, you must
1516    store the result back using `storedecls' or you will lose.  */
1517
1518 tree
1519 getdecls (void)
1520 {
1521   return current_binding_level->names;
1522 }
1523
1524 /* Set the current binding TABLE for type declarations..  This is a
1525    temporary workaround of the fact that the data structure classtypes
1526    does not currently carry its allocated cxx_scope structure.  */
1527 void
1528 cxx_remember_type_decls (binding_table table)
1529 {
1530   current_binding_level->type_decls = table;
1531 }
1532
1533 /* For debugging.  */
1534 static int no_print_functions = 0;
1535 static int no_print_builtins = 0;
1536
1537 /* Called from print_binding_level through binding_table_foreach to
1538    print the content of binding ENTRY.  DATA is a pointer to line offset
1539    marker.  */
1540 static void
1541 bt_print_entry (binding_entry entry, void *data)
1542 {
1543   int *p = (int *) data;
1544   int len;
1545
1546   if (entry->name == NULL)
1547     len = 3;
1548   else if (entry->name == TYPE_IDENTIFIER (entry->type))
1549     len = 2;
1550   else
1551     len = 4;
1552     len = 4;
1553
1554   *p += len;
1555
1556   if (*p > 5)
1557     {
1558       fprintf (stderr, "\n\t");
1559       *p = len;
1560     }
1561   if (entry->name == NULL)
1562     {
1563       print_node_brief (stderr, "<unnamed-typedef", entry->type, 0);
1564       fprintf (stderr, ">");
1565     }
1566   else if (entry->name == TYPE_IDENTIFIER (entry->type))
1567     print_node_brief (stderr, "", entry->type, 0);
1568   else
1569     {
1570       print_node_brief (stderr, "<typedef", entry->name, 0);
1571       print_node_brief (stderr, "", entry->type, 0);
1572       fprintf (stderr, ">");
1573     }
1574 }
1575
1576 void
1577 print_binding_level (struct cp_binding_level* lvl)
1578 {
1579   tree t;
1580   int i = 0, len;
1581   fprintf (stderr, " blocks=" HOST_PTR_PRINTF, (void *) lvl->blocks);
1582   if (lvl->more_cleanups_ok)
1583     fprintf (stderr, " more-cleanups-ok");
1584   if (lvl->have_cleanups)
1585     fprintf (stderr, " have-cleanups");
1586   fprintf (stderr, "\n");
1587   if (lvl->names)
1588     {
1589       fprintf (stderr, " names:\t");
1590       /* We can probably fit 3 names to a line?  */
1591       for (t = lvl->names; t; t = TREE_CHAIN (t))
1592         {
1593           if (no_print_functions && (TREE_CODE (t) == FUNCTION_DECL))
1594             continue;
1595           if (no_print_builtins
1596               && (TREE_CODE (t) == TYPE_DECL)
1597               && (!strcmp (DECL_SOURCE_FILE (t),"<built-in>")))
1598             continue;
1599
1600           /* Function decls tend to have longer names.  */
1601           if (TREE_CODE (t) == FUNCTION_DECL)
1602             len = 3;
1603           else
1604             len = 2;
1605           i += len;
1606           if (i > 6)
1607             {
1608               fprintf (stderr, "\n\t");
1609               i = len;
1610             }
1611           print_node_brief (stderr, "", t, 0);
1612           if (t == error_mark_node)
1613             break;
1614         }
1615       if (i)
1616         fprintf (stderr, "\n");
1617     }
1618   if (lvl->type_decls)
1619     {
1620       fprintf (stderr, " tags:\t");
1621       i = 0;
1622       binding_table_foreach (lvl->type_decls, bt_print_entry, &i);
1623       if (i)
1624         fprintf (stderr, "\n");
1625     }
1626   if (lvl->class_shadowed)
1627     {
1628       fprintf (stderr, " class-shadowed:");
1629       for (t = lvl->class_shadowed; t; t = TREE_CHAIN (t))
1630         {
1631           fprintf (stderr, " %s ", IDENTIFIER_POINTER (TREE_PURPOSE (t)));
1632         }
1633       fprintf (stderr, "\n");
1634     }
1635   if (lvl->type_shadowed)
1636     {
1637       fprintf (stderr, " type-shadowed:");
1638       for (t = lvl->type_shadowed; t; t = TREE_CHAIN (t))
1639         {
1640           fprintf (stderr, " %s ", IDENTIFIER_POINTER (TREE_PURPOSE (t)));
1641         }
1642       fprintf (stderr, "\n");
1643     }
1644 }
1645
1646 void
1647 print_other_binding_stack (struct cp_binding_level *stack)
1648 {
1649   struct cp_binding_level *level;
1650   for (level = stack; !global_scope_p (level); level = level->level_chain)
1651     {
1652       fprintf (stderr, "binding level " HOST_PTR_PRINTF "\n", (void *) level);
1653       print_binding_level (level);
1654     }
1655 }
1656
1657 void
1658 print_binding_stack (void)
1659 {
1660   struct cp_binding_level *b;
1661   fprintf (stderr, "current_binding_level=" HOST_PTR_PRINTF
1662            "\nclass_binding_level=" HOST_PTR_PRINTF
1663            "\nNAMESPACE_LEVEL (global_namespace)=" HOST_PTR_PRINTF "\n",
1664            (void *) current_binding_level, (void *) class_binding_level,
1665            (void *) NAMESPACE_LEVEL (global_namespace));
1666   if (class_binding_level)
1667     {
1668       for (b = class_binding_level; b; b = b->level_chain)
1669         if (b == current_binding_level)
1670           break;
1671       if (b)
1672         b = class_binding_level;
1673       else
1674         b = current_binding_level;
1675     }
1676   else
1677     b = current_binding_level;
1678   print_other_binding_stack (b);
1679   fprintf (stderr, "global:\n");
1680   print_binding_level (NAMESPACE_LEVEL (global_namespace));
1681 }
1682 \f
1683 /* Return the type associated with id.  */
1684
1685 tree
1686 identifier_type_value (tree id)
1687 {
1688   timevar_push (TV_NAME_LOOKUP);
1689   /* There is no type with that name, anywhere.  */
1690   if (REAL_IDENTIFIER_TYPE_VALUE (id) == NULL_TREE)
1691     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
1692   /* This is not the type marker, but the real thing.  */
1693   if (REAL_IDENTIFIER_TYPE_VALUE (id) != global_type_node)
1694     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, REAL_IDENTIFIER_TYPE_VALUE (id));
1695   /* Have to search for it. It must be on the global level, now.
1696      Ask lookup_name not to return non-types.  */
1697   id = lookup_name_real (id, 2, 1, 0, LOOKUP_COMPLAIN);
1698   if (id)
1699     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, TREE_TYPE (id));
1700   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
1701 }
1702
1703 /* Return the IDENTIFIER_GLOBAL_VALUE of T, for use in common code, since
1704    the definition of IDENTIFIER_GLOBAL_VALUE is different for C and C++.  */
1705
1706 tree
1707 identifier_global_value (tree t)
1708 {
1709   return IDENTIFIER_GLOBAL_VALUE (t);
1710 }
1711
1712 /* Push a definition of struct, union or enum tag named ID.  into
1713    binding_level B.  DECL is a TYPE_DECL for the type.  We assume that
1714    the tag ID is not already defined.  */
1715
1716 static void
1717 set_identifier_type_value_with_scope (tree id, tree decl, cxx_scope *b)
1718 {
1719   tree type;
1720
1721   if (b->kind != sk_namespace)
1722     {
1723       /* Shadow the marker, not the real thing, so that the marker
1724          gets restored later.  */
1725       tree old_type_value = REAL_IDENTIFIER_TYPE_VALUE (id);
1726       b->type_shadowed
1727         = tree_cons (id, old_type_value, b->type_shadowed);
1728       type = decl ? TREE_TYPE (decl) : NULL_TREE;
1729     }
1730   else
1731     {
1732       cxx_binding *binding =
1733         binding_for_name (NAMESPACE_LEVEL (current_namespace), id);
1734       if (decl)
1735         {
1736           if (binding->value)
1737             supplement_binding (binding, decl);
1738           else
1739             binding->value = decl;
1740         }
1741       else
1742         abort ();
1743       /* Store marker instead of real type.  */
1744       type = global_type_node;
1745     }
1746   SET_IDENTIFIER_TYPE_VALUE (id, type);
1747 }
1748
1749 /* As set_identifier_type_value_with_scope, but using
1750    current_binding_level.  */
1751
1752 void
1753 set_identifier_type_value (tree id, tree decl)
1754 {
1755   set_identifier_type_value_with_scope (id, decl, current_binding_level);
1756 }
1757
1758 /* Return the name for the constructor (or destructor) for the
1759    specified class TYPE.  When given a template, this routine doesn't
1760    lose the specialization.  */
1761
1762 tree
1763 constructor_name_full (tree type)
1764 {
1765   type = TYPE_MAIN_VARIANT (type);
1766   if (CLASS_TYPE_P (type) && TYPE_WAS_ANONYMOUS (type) 
1767       && TYPE_HAS_CONSTRUCTOR (type))
1768     return DECL_NAME (OVL_CURRENT (CLASSTYPE_CONSTRUCTORS (type)));
1769   else
1770     return TYPE_IDENTIFIER (type);
1771 }
1772
1773 /* Return the name for the constructor (or destructor) for the
1774    specified class.  When given a template, return the plain
1775    unspecialized name.  */
1776
1777 tree
1778 constructor_name (tree type)
1779 {
1780   tree name;
1781   name = constructor_name_full (type);
1782   if (IDENTIFIER_TEMPLATE (name))
1783     name = IDENTIFIER_TEMPLATE (name);
1784   return name;
1785 }
1786
1787 /* Returns TRUE if NAME is the name for the constructor for TYPE.  */
1788
1789 bool
1790 constructor_name_p (tree name, tree type)
1791 {
1792   tree ctor_name;
1793
1794   if (!name)
1795     return false;
1796   
1797   if (TREE_CODE (name) != IDENTIFIER_NODE)
1798     return false;
1799   
1800   ctor_name = constructor_name_full (type);
1801   if (name == ctor_name)
1802     return true;
1803   if (IDENTIFIER_TEMPLATE (ctor_name)
1804       && name == IDENTIFIER_TEMPLATE (ctor_name))
1805     return true;
1806   return false;
1807 }
1808
1809 /* Counter used to create anonymous type names.  */
1810
1811 static GTY(()) int anon_cnt;
1812
1813 /* Return an IDENTIFIER which can be used as a name for
1814    anonymous structs and unions.  */
1815
1816 tree
1817 make_anon_name (void)
1818 {
1819   char buf[32];
1820
1821   sprintf (buf, ANON_AGGRNAME_FORMAT, anon_cnt++);
1822   return get_identifier (buf);
1823 }
1824
1825 /* Clear the TREE_PURPOSE slot of UTDs which have anonymous typenames.
1826    This keeps dbxout from getting confused.  */
1827
1828 void
1829 clear_anon_tags (void)
1830 {
1831   struct cp_binding_level *b;
1832   static int last_cnt = 0;
1833
1834   /* Fast out if no new anon names were declared.  */
1835   if (last_cnt == anon_cnt)
1836     return;
1837
1838   b = current_binding_level;
1839   while (b->kind == sk_cleanup)
1840     b = b->level_chain;
1841   if (b->type_decls != NULL)
1842     binding_table_remove_anonymous_types (b->type_decls);
1843   last_cnt = anon_cnt;
1844 }
1845 \f
1846 /* Return (from the stack of) the BINDING, if any, established at SCOPE.  */ 
1847
1848 static inline cxx_binding *
1849 find_binding (cxx_scope *scope, cxx_binding *binding)
1850 {
1851   timevar_push (TV_NAME_LOOKUP);
1852
1853   for (; binding != NULL; binding = binding->previous)
1854     if (binding->scope == scope)
1855       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, binding);
1856
1857   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, (cxx_binding *)0);
1858 }
1859
1860 /* Return the binding for NAME in SCOPE, if any.  Otherwise, return NULL.  */
1861
1862 static inline cxx_binding *
1863 cxx_scope_find_binding_for_name (cxx_scope *scope, tree name)
1864 {
1865   cxx_binding *b = IDENTIFIER_NAMESPACE_BINDINGS (name);
1866   if (b)
1867     {
1868       /* Fold-in case where NAME is used only once.  */
1869       if (scope == b->scope && b->previous == NULL)
1870         return b;
1871       return find_binding (scope, b);
1872     }
1873   return NULL;
1874 }
1875
1876 /* Always returns a binding for name in scope.  If no binding is
1877    found, make a new one.  */
1878
1879 static cxx_binding *
1880 binding_for_name (cxx_scope *scope, tree name)
1881 {
1882   cxx_binding *result;
1883
1884   result = cxx_scope_find_binding_for_name (scope, name);
1885   if (result)
1886     return result;
1887   /* Not found, make a new one.  */
1888   result = cxx_binding_make (NULL, NULL);
1889   result->previous = IDENTIFIER_NAMESPACE_BINDINGS (name);
1890   result->scope = scope;
1891   result->is_local = false;
1892   result->value_is_inherited = false;
1893   IDENTIFIER_NAMESPACE_BINDINGS (name) = result;
1894   return result;
1895 }
1896
1897 /* Insert another USING_DECL into the current binding level, returning
1898    this declaration. If this is a redeclaration, do nothing, and
1899    return NULL_TREE if this not in namespace scope (in namespace
1900    scope, a using decl might extend any previous bindings).  */
1901
1902 tree
1903 push_using_decl (tree scope, tree name)
1904 {
1905   tree decl;
1906
1907   timevar_push (TV_NAME_LOOKUP);
1908   my_friendly_assert (TREE_CODE (scope) == NAMESPACE_DECL, 383);
1909   my_friendly_assert (TREE_CODE (name) == IDENTIFIER_NODE, 384);
1910   for (decl = current_binding_level->usings; decl; decl = TREE_CHAIN (decl))
1911     if (DECL_INITIAL (decl) == scope && DECL_NAME (decl) == name)
1912       break;
1913   if (decl)
1914     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
1915                             namespace_bindings_p () ? decl : NULL_TREE);
1916   decl = build_lang_decl (USING_DECL, name, void_type_node);
1917   DECL_INITIAL (decl) = scope;
1918   TREE_CHAIN (decl) = current_binding_level->usings;
1919   current_binding_level->usings = decl;
1920   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
1921 }
1922
1923 /* Same as pushdecl, but define X in binding-level LEVEL.  We rely on the
1924    caller to set DECL_CONTEXT properly.  */
1925
1926 tree
1927 pushdecl_with_scope (tree x, cxx_scope *level)
1928 {
1929   struct cp_binding_level *b;
1930   tree function_decl = current_function_decl;
1931
1932   timevar_push (TV_NAME_LOOKUP);
1933   current_function_decl = NULL_TREE;
1934   if (level->kind == sk_class)
1935     {
1936       b = class_binding_level;
1937       class_binding_level = level;
1938       pushdecl_class_level (x);
1939       class_binding_level = b;
1940     }
1941   else
1942     {
1943       b = current_binding_level;
1944       current_binding_level = level;
1945       x = pushdecl (x);
1946       current_binding_level = b;
1947     }
1948   current_function_decl = function_decl;
1949   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
1950 }
1951
1952 /* DECL is a FUNCTION_DECL for a non-member function, which may have
1953    other definitions already in place.  We get around this by making
1954    the value of the identifier point to a list of all the things that
1955    want to be referenced by that name.  It is then up to the users of
1956    that name to decide what to do with that list.
1957
1958    DECL may also be a TEMPLATE_DECL, with a FUNCTION_DECL in its
1959    DECL_TEMPLATE_RESULT.  It is dealt with the same way.
1960
1961    FLAGS is a bitwise-or of the following values:
1962      PUSH_LOCAL: Bind DECL in the current scope, rather than at
1963                  namespace scope.
1964      PUSH_USING: DECL is being pushed as the result of a using
1965                  declaration.
1966
1967    The value returned may be a previous declaration if we guessed wrong
1968    about what language DECL should belong to (C or C++).  Otherwise,
1969    it's always DECL (and never something that's not a _DECL).  */
1970
1971 static tree
1972 push_overloaded_decl (tree decl, int flags)
1973 {
1974   tree name = DECL_NAME (decl);
1975   tree old;
1976   tree new_binding;
1977   int doing_global = (namespace_bindings_p () || !(flags & PUSH_LOCAL));
1978
1979   timevar_push (TV_NAME_LOOKUP);
1980   if (doing_global)
1981     old = namespace_binding (name, DECL_CONTEXT (decl));
1982   else
1983     old = lookup_name_current_level (name);
1984
1985   if (old)
1986     {
1987       if (TREE_CODE (old) == TYPE_DECL && DECL_ARTIFICIAL (old))
1988         {
1989           tree t = TREE_TYPE (old);
1990           if (IS_AGGR_TYPE (t) && warn_shadow
1991               && (! DECL_IN_SYSTEM_HEADER (decl)
1992                   || ! DECL_IN_SYSTEM_HEADER (old)))
1993             warning ("`%#D' hides constructor for `%#T'", decl, t);
1994           old = NULL_TREE;
1995         }
1996       else if (is_overloaded_fn (old))
1997         {
1998           tree tmp;
1999
2000           for (tmp = old; tmp; tmp = OVL_NEXT (tmp))
2001             {
2002               tree fn = OVL_CURRENT (tmp);
2003
2004               if (TREE_CODE (tmp) == OVERLOAD && OVL_USED (tmp)
2005                   && !(flags & PUSH_USING)
2006                   && compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2007                                 TYPE_ARG_TYPES (TREE_TYPE (decl))))
2008                 error ("`%#D' conflicts with previous using declaration `%#D'",
2009                           decl, fn);
2010
2011               if (duplicate_decls (decl, fn) == fn)
2012                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, fn);
2013             }
2014         }
2015       else if (old == error_mark_node)
2016         /* Ignore the undefined symbol marker.  */
2017         old = NULL_TREE;
2018       else
2019         {
2020           cp_error_at ("previous non-function declaration `%#D'", old);
2021           error ("conflicts with function declaration `%#D'", decl);
2022           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2023         }
2024     }
2025
2026   if (old || TREE_CODE (decl) == TEMPLATE_DECL
2027       /* If it's a using declaration, we always need to build an OVERLOAD,
2028          because it's the only way to remember that the declaration comes
2029          from 'using', and have the lookup behave correctly.  */
2030       || (flags & PUSH_USING))
2031     {
2032       if (old && TREE_CODE (old) != OVERLOAD)
2033         new_binding = ovl_cons (decl, ovl_cons (old, NULL_TREE));
2034       else
2035         new_binding = ovl_cons (decl, old);
2036       if (flags & PUSH_USING)
2037         OVL_USED (new_binding) = 1;
2038     }
2039   else
2040     /* NAME is not ambiguous.  */
2041     new_binding = decl;
2042
2043   if (doing_global)
2044     set_namespace_binding (name, current_namespace, new_binding);
2045   else
2046     {
2047       /* We only create an OVERLOAD if there was a previous binding at
2048          this level, or if decl is a template. In the former case, we
2049          need to remove the old binding and replace it with the new
2050          binding.  We must also run through the NAMES on the binding
2051          level where the name was bound to update the chain.  */
2052
2053       if (TREE_CODE (new_binding) == OVERLOAD && old)
2054         {
2055           tree *d;
2056
2057           for (d = &IDENTIFIER_BINDING (name)->scope->names;
2058                *d;
2059                d = &TREE_CHAIN (*d))
2060             if (*d == old
2061                 || (TREE_CODE (*d) == TREE_LIST
2062                     && TREE_VALUE (*d) == old))
2063               {
2064                 if (TREE_CODE (*d) == TREE_LIST)
2065                   /* Just replace the old binding with the new.  */
2066                   TREE_VALUE (*d) = new_binding;
2067                 else
2068                   /* Build a TREE_LIST to wrap the OVERLOAD.  */
2069                   *d = tree_cons (NULL_TREE, new_binding,
2070                                   TREE_CHAIN (*d));
2071
2072                 /* And update the cxx_binding node.  */
2073                 IDENTIFIER_BINDING (name)->value = new_binding;
2074                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2075               }
2076
2077           /* We should always find a previous binding in this case.  */
2078           abort ();
2079         }
2080
2081       /* Install the new binding.  */
2082       push_local_binding (name, new_binding, flags);
2083     }
2084
2085   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2086 }
2087
2088 /* Check a non-member using-declaration. Return the name and scope
2089    being used, and the USING_DECL, or NULL_TREE on failure.  */
2090
2091 static tree
2092 validate_nonmember_using_decl (tree decl, tree scope, tree name)
2093 {
2094   if (TREE_CODE (decl) == TEMPLATE_ID_EXPR)
2095     {
2096       /* 7.3.3/5
2097            A using-declaration shall not name a template-id.  */
2098       error ("a using-declaration cannot specify a template-id.  Try `using %D'", name);
2099       return NULL_TREE;
2100     }
2101
2102   if (TREE_CODE (decl) == NAMESPACE_DECL)
2103     {
2104       error ("namespace `%D' not allowed in using-declaration", decl);
2105       return NULL_TREE;
2106     }
2107
2108   if (TREE_CODE (decl) == SCOPE_REF)
2109     {
2110       /* It's a nested name with template parameter dependent scope.
2111          This can only be using-declaration for class member.  */
2112       error ("`%T' is not a namespace", TREE_OPERAND (decl, 0));
2113       return NULL_TREE;
2114     }
2115
2116   if (is_overloaded_fn (decl))
2117     decl = get_first_fn (decl);
2118
2119   my_friendly_assert (DECL_P (decl), 20020908);
2120
2121   /* [namespace.udecl]
2122        A using-declaration for a class member shall be a
2123        member-declaration.  */
2124   if (TYPE_P (scope))
2125     {
2126       error ("`%T' is not a namespace", scope);
2127       return NULL_TREE;
2128     }
2129
2130   /* Make a USING_DECL.  */
2131   return push_using_decl (scope, name);
2132 }
2133
2134 /* Process local and global using-declarations.  */
2135
2136 static void
2137 do_nonmember_using_decl (tree scope, tree name, tree oldval, tree oldtype,
2138                          tree *newval, tree *newtype)
2139 {
2140   struct scope_binding decls = EMPTY_SCOPE_BINDING;
2141
2142   *newval = *newtype = NULL_TREE;
2143   if (!qualified_lookup_using_namespace (name, scope, &decls, 0))
2144     /* Lookup error */
2145     return;
2146
2147   if (!decls.value && !decls.type)
2148     {
2149       error ("`%D' not declared", name);
2150       return;
2151     }
2152
2153   /* Check for using functions.  */
2154   if (decls.value && is_overloaded_fn (decls.value))
2155     {
2156       tree tmp, tmp1;
2157
2158       if (oldval && !is_overloaded_fn (oldval))
2159         {
2160           if (!DECL_IMPLICIT_TYPEDEF_P (oldval))
2161             error ("`%D' is already declared in this scope", name);
2162           oldval = NULL_TREE;
2163         }
2164
2165       *newval = oldval;
2166       for (tmp = decls.value; tmp; tmp = OVL_NEXT (tmp))
2167         {
2168           tree new_fn = OVL_CURRENT (tmp);
2169
2170           /* [namespace.udecl]
2171
2172              If a function declaration in namespace scope or block
2173              scope has the same name and the same parameter types as a
2174              function introduced by a using declaration the program is
2175              ill-formed.  */
2176           for (tmp1 = oldval; tmp1; tmp1 = OVL_NEXT (tmp1))
2177             {
2178               tree old_fn = OVL_CURRENT (tmp1);
2179
2180               if (new_fn == old_fn)
2181                 /* The function already exists in the current namespace.  */
2182                 break;
2183               else if (OVL_USED (tmp1))
2184                 continue; /* this is a using decl */
2185               else if (compparms (TYPE_ARG_TYPES (TREE_TYPE (new_fn)),
2186                                   TYPE_ARG_TYPES (TREE_TYPE (old_fn))))
2187                 {
2188                   /* There was already a non-using declaration in
2189                      this scope with the same parameter types. If both
2190                      are the same extern "C" functions, that's ok.  */
2191                   if (decls_match (new_fn, old_fn))
2192                     {
2193                       /* If the OLD_FN was a builtin, there is now a
2194                          real declaration.  */
2195                       if (DECL_ANTICIPATED (old_fn))
2196                         DECL_ANTICIPATED (old_fn) = 0;
2197                       break;
2198                     }
2199                   else if (!DECL_ANTICIPATED (old_fn))
2200                     {
2201                       /* If the OLD_FN was really declared, the
2202                          declarations don't match.  */
2203                       error ("`%D' is already declared in this scope", name);
2204                       break;
2205                     }
2206
2207                   /* If the OLD_FN was not really there, just ignore
2208                      it and keep going.  */
2209                 }
2210             }
2211
2212           /* If we broke out of the loop, there's no reason to add
2213              this function to the using declarations for this
2214              scope.  */
2215           if (tmp1)
2216             continue;
2217             
2218           /* If we are adding to an existing OVERLOAD, then we no
2219              longer know the type of the set of functions.  */
2220           if (*newval && TREE_CODE (*newval) == OVERLOAD)
2221             TREE_TYPE (*newval) = unknown_type_node;
2222           /* Add this new function to the set.  */
2223           *newval = build_overload (OVL_CURRENT (tmp), *newval);
2224           /* If there is only one function, then we use its type.  (A
2225              using-declaration naming a single function can be used in
2226              contexts where overload resolution cannot be
2227              performed.)  */
2228           if (TREE_CODE (*newval) != OVERLOAD)
2229             {
2230               *newval = ovl_cons (*newval, NULL_TREE);
2231               TREE_TYPE (*newval) = TREE_TYPE (OVL_CURRENT (tmp));
2232             }
2233           OVL_USED (*newval) = 1;
2234         }
2235     }
2236   else 
2237     {
2238       *newval = decls.value;
2239       if (oldval && !decls_match (*newval, oldval))
2240         error ("`%D' is already declared in this scope", name);
2241     }
2242
2243   *newtype = decls.type;
2244   if (oldtype && *newtype && !same_type_p (oldtype, *newtype))
2245     {
2246       error ("using declaration `%D' introduced ambiguous type `%T'",
2247                 name, oldtype);
2248       return;
2249     }
2250 }
2251
2252 /* Process a using-declaration at function scope.  */
2253
2254 void
2255 do_local_using_decl (tree decl, tree scope, tree name)
2256 {
2257   tree oldval, oldtype, newval, newtype;
2258   tree orig_decl = decl;
2259
2260   decl = validate_nonmember_using_decl (decl, scope, name);
2261   if (decl == NULL_TREE)
2262     return;
2263
2264   if (building_stmt_tree ()
2265       && at_function_scope_p ())
2266     add_decl_stmt (decl);
2267
2268   oldval = lookup_name_current_level (name);
2269   oldtype = lookup_type_current_level (name);
2270
2271   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
2272
2273   if (newval)
2274     {
2275       if (is_overloaded_fn (newval))
2276         {
2277           tree fn, term;
2278
2279           /* We only need to push declarations for those functions
2280              that were not already bound in the current level.
2281              The old value might be NULL_TREE, it might be a single
2282              function, or an OVERLOAD.  */
2283           if (oldval && TREE_CODE (oldval) == OVERLOAD)
2284             term = OVL_FUNCTION (oldval);
2285           else
2286             term = oldval;
2287           for (fn = newval; fn && OVL_CURRENT (fn) != term; 
2288                fn = OVL_NEXT (fn))
2289             push_overloaded_decl (OVL_CURRENT (fn), 
2290                                   PUSH_LOCAL | PUSH_USING);
2291         }
2292       else
2293         push_local_binding (name, newval, PUSH_USING);
2294     }
2295   if (newtype)
2296     {
2297       push_local_binding (name, newtype, PUSH_USING);
2298       set_identifier_type_value (name, newtype);
2299     }
2300
2301   /* Emit debug info.  */
2302   if (!processing_template_decl)
2303     cp_emit_debug_info_for_using (orig_decl, current_scope());
2304 }
2305
2306 /* Return the type that should be used when TYPE's name is preceded
2307    by a tag such as 'struct' or 'union', or null if the name cannot
2308    be used in this way.
2309
2310    For example, when processing the third line of:
2311
2312         struct A;
2313         typedef struct A A;
2314         struct A;
2315
2316    lookup of A will find the typedef.  Given A's typedef, this function
2317    will return the type associated with "struct A".  For the tag to be
2318    anything other than TYPE, TYPE must be a typedef whose original type
2319    has the same name and context as TYPE itself.
2320
2321    It is not valid for a typedef of an anonymous type to be used with
2322    an explicit tag:
2323
2324        typedef struct { ... } B;
2325        struct B;
2326
2327    Return null for this case.  */
2328
2329 static tree
2330 follow_tag_typedef (tree type)
2331 {
2332   tree original;
2333
2334   original = original_type (type);
2335   if (! TYPE_NAME (original))
2336     return NULL_TREE;
2337   if (TYPE_IDENTIFIER (original) == TYPE_IDENTIFIER (type)
2338       && (CP_DECL_CONTEXT (TYPE_NAME (original))
2339           == CP_DECL_CONTEXT (TYPE_NAME (type)))
2340       && !(CLASS_TYPE_P (original) && TYPE_WAS_ANONYMOUS (original)))
2341     return original;
2342   else
2343     return NULL_TREE;
2344 }
2345
2346 /* Given NAME, an IDENTIFIER_NODE,
2347    return the structure (or union or enum) definition for that name.
2348    Searches binding levels from its SCOPE up to the global level.
2349    If THISLEVEL_ONLY is nonzero, searches only the specified context
2350    (but skips any sk_cleanup contexts to find one that is
2351    meaningful for tags).
2352    FORM says which kind of type the caller wants;
2353    it is RECORD_TYPE or UNION_TYPE or ENUMERAL_TYPE.
2354    If the wrong kind of type is found, and it's not a template, an error is
2355    reported.  */
2356
2357 tree
2358 lookup_tag (enum tree_code form, tree name,
2359             cxx_scope *binding_level, int thislevel_only)
2360 {
2361   struct cp_binding_level *level;
2362   /* Nonzero if, we should look past a template parameter level, even
2363      if THISLEVEL_ONLY.  */
2364   int allow_template_parms_p = 1;
2365   bool type_is_anonymous = ANON_AGGRNAME_P (name);
2366
2367   timevar_push (TV_NAME_LOOKUP);
2368   for (level = binding_level; level; level = level->level_chain)
2369     {
2370       tree tail;
2371       if (type_is_anonymous && level->type_decls != NULL)
2372         {
2373           tree type = binding_table_find_anon_type (level->type_decls, name);
2374           /* There is no need for error checking here, because
2375            anon names are unique throughout the compilation.  */
2376           if (type != NULL)
2377             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, type);
2378         }
2379       else if (level->kind == sk_namespace)
2380         /* Do namespace lookup.  */
2381         for (tail = current_namespace; 1; tail = CP_DECL_CONTEXT (tail))
2382           {
2383             cxx_binding *binding =
2384               cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (tail), name);
2385
2386             if (binding && (binding->type
2387                             || (binding->value 
2388                                 && DECL_DECLARES_TYPE_P (binding->value))))
2389               {
2390                 tree old;
2391                 
2392                 /* If we just skipped past a template parameter level,
2393                    even though THISLEVEL_ONLY, and we find a template
2394                    class declaration, then we use the _TYPE node for the
2395                    template.  See the example below.  */
2396                 if (thislevel_only && !allow_template_parms_p
2397                     && binding->value
2398                     && DECL_CLASS_TEMPLATE_P (binding->value))
2399                   old = binding->value;
2400                 else
2401                   old = binding->type ? binding->type : binding->value;
2402
2403                 /* We've found something at this binding level.  If it is
2404                    a typedef, extract the tag it refers to.  Lookup fails
2405                    if the typedef doesn't refer to a taggable type.  */
2406                 old = TREE_TYPE (old);
2407                 old = follow_tag_typedef (old);
2408                 if (!old)
2409                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2410                 if (TREE_CODE (old) != form
2411                     && (form == ENUMERAL_TYPE
2412                         || TREE_CODE (old) == ENUMERAL_TYPE))
2413                   {
2414                     error ("`%#D' redeclared as %C", old, form);
2415                     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2416                   }
2417                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, old);
2418               }
2419             if (thislevel_only || tail == global_namespace)
2420               POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2421           }
2422       else if (level->type_decls != NULL)
2423         {
2424           binding_entry entry = binding_table_find (level->type_decls, name);
2425           if (entry != NULL)
2426             {
2427               enum tree_code code = TREE_CODE (entry->type);
2428                 
2429               if (code != form
2430                   && (form == ENUMERAL_TYPE || code == ENUMERAL_TYPE))
2431                 {
2432                   /* Definition isn't the kind we were looking for.  */
2433                   error ("`%#D' redeclared as %C", entry->type, form);
2434                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2435                 }
2436               POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->type);
2437             }
2438           }
2439       if (thislevel_only && level->kind != sk_cleanup)
2440         {
2441           if (level->kind == sk_template_parms && allow_template_parms_p)
2442             {
2443               /* We must deal with cases like this:
2444
2445                    template <class T> struct S;
2446                    template <class T> struct S {};
2447
2448                  When looking up `S', for the second declaration, we
2449                  would like to find the first declaration.  But, we
2450                  are in the pseudo-global level created for the
2451                  template parameters, rather than the (surrounding)
2452                  namespace level.  Thus, we keep going one more level,
2453                  even though THISLEVEL_ONLY is nonzero.  */
2454               allow_template_parms_p = 0;
2455               continue;
2456             }
2457           else
2458             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2459         }
2460     }
2461   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2462 }
2463
2464 /* Given a type, find the tag that was defined for it and return the tag name.
2465    Otherwise return 0.  However, the value can never be 0
2466    in the cases in which this is used.
2467
2468    C++: If NAME is nonzero, this is the new name to install.  This is
2469    done when replacing anonymous tags with real tag names.  */
2470
2471 tree
2472 lookup_tag_reverse (tree type, tree name)
2473 {
2474   struct cp_binding_level *level;
2475
2476   timevar_push (TV_NAME_LOOKUP);
2477   for (level = current_binding_level; level; level = level->level_chain)
2478     {
2479       binding_entry entry = level->type_decls == NULL
2480         ? NULL
2481         : binding_table_reverse_maybe_remap (level->type_decls, type, name);
2482       if (entry)
2483         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->name);
2484     }
2485   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
2486 }
2487
2488 /* Returns true if ROOT (a namespace, class, or function) encloses
2489    CHILD.  CHILD may be either a class type or a namespace.  */
2490
2491 bool
2492 is_ancestor (tree root, tree child)
2493 {
2494   my_friendly_assert ((TREE_CODE (root) == NAMESPACE_DECL
2495                        || TREE_CODE (root) == FUNCTION_DECL
2496                        || CLASS_TYPE_P (root)), 20030307);
2497   my_friendly_assert ((TREE_CODE (child) == NAMESPACE_DECL
2498                        || CLASS_TYPE_P (child)),
2499                       20030307);
2500   
2501   /* The global namespace encloses everything.  */
2502   if (root == global_namespace)
2503     return true;
2504
2505   while (true)
2506     {
2507       /* If we've run out of scopes, stop.  */
2508       if (!child)
2509         return false;
2510       /* If we've reached the ROOT, it encloses CHILD.  */
2511       if (root == child)
2512         return true;
2513       /* Go out one level.  */
2514       if (TYPE_P (child))
2515         child = TYPE_NAME (child);
2516       child = DECL_CONTEXT (child);
2517     }
2518 }
2519
2520 /* Enter the class or namespace scope indicated by T.  Returns TRUE iff
2521    pop_scope should be called later to exit this scope.  */
2522
2523 bool
2524 push_scope (tree t)
2525 {
2526   bool pop = true;
2527
2528   if (TREE_CODE (t) == NAMESPACE_DECL)
2529     push_decl_namespace (t);
2530   else if (CLASS_TYPE_P (t))
2531     {
2532       if (!at_class_scope_p ()
2533           || !same_type_p (current_class_type, t))
2534         push_nested_class (t);
2535       else
2536         /* T is the same as the current scope.  There is therefore no
2537            need to re-enter the scope.  Since we are not actually
2538            pushing a new scope, our caller should not call
2539            pop_scope.  */
2540         pop = false;
2541     }
2542
2543   return pop;
2544 }
2545
2546 /* Leave scope pushed by push_scope.  */
2547
2548 void
2549 pop_scope (tree t)
2550 {
2551   if (TREE_CODE (t) == NAMESPACE_DECL)
2552     pop_decl_namespace ();
2553   else if CLASS_TYPE_P (t)
2554     pop_nested_class ();
2555 }
2556 \f
2557 /* Do a pushlevel for class declarations.  */
2558
2559 void
2560 pushlevel_class (void)
2561 {
2562   if (ENABLE_SCOPE_CHECKING)
2563     is_class_level = 1;
2564
2565   class_binding_level = begin_scope (sk_class, current_class_type);
2566 }
2567
2568 /* ...and a poplevel for class declarations.  */
2569
2570 void
2571 poplevel_class (void)
2572 {
2573   struct cp_binding_level *level = class_binding_level;
2574   tree shadowed;
2575
2576   timevar_push (TV_NAME_LOOKUP);
2577   my_friendly_assert (level != 0, 354);
2578
2579   /* If we're leaving a toplevel class, don't bother to do the setting
2580      of IDENTIFIER_CLASS_VALUE to NULL_TREE, since first of all this slot
2581      shouldn't even be used when current_class_type isn't set, and second,
2582      if we don't touch it here, we're able to use the cache effect if the
2583      next time we're entering a class scope, it is the same class.  */
2584   if (current_class_depth != 1)
2585     {
2586       struct cp_binding_level* b;
2587
2588       /* Clear out our IDENTIFIER_CLASS_VALUEs.  */
2589       for (shadowed = level->class_shadowed;
2590            shadowed;
2591            shadowed = TREE_CHAIN (shadowed))
2592         IDENTIFIER_CLASS_VALUE (TREE_PURPOSE (shadowed)) = NULL_TREE;
2593
2594       /* Find the next enclosing class, and recreate
2595          IDENTIFIER_CLASS_VALUEs appropriate for that class.  */
2596       b = level->level_chain;
2597       while (b && b->kind != sk_class)
2598         b = b->level_chain;
2599
2600       if (b)
2601         for (shadowed = b->class_shadowed;
2602              shadowed;
2603              shadowed = TREE_CHAIN (shadowed))
2604           {
2605             cxx_binding *binding;
2606             
2607             binding = IDENTIFIER_BINDING (TREE_PURPOSE (shadowed));
2608             while (binding && binding->scope != b)
2609               binding = binding->previous;
2610
2611             if (binding)
2612               IDENTIFIER_CLASS_VALUE (TREE_PURPOSE (shadowed))
2613                 = binding->value;
2614           }
2615     }
2616   else
2617     /* Remember to save what IDENTIFIER's were bound in this scope so we
2618        can recover from cache misses.  */
2619     {
2620       previous_class_type = current_class_type;
2621       previous_class_values = class_binding_level->class_shadowed;
2622     }
2623   for (shadowed = level->type_shadowed;
2624        shadowed;
2625        shadowed = TREE_CHAIN (shadowed))
2626     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (shadowed), TREE_VALUE (shadowed));
2627
2628   /* Remove the bindings for all of the class-level declarations.  */
2629   for (shadowed = level->class_shadowed;
2630        shadowed;
2631        shadowed = TREE_CHAIN (shadowed))
2632     pop_binding (TREE_PURPOSE (shadowed), TREE_TYPE (shadowed));
2633
2634   /* Now, pop out of the binding level which we created up in the
2635      `pushlevel_class' routine.  */
2636   if (ENABLE_SCOPE_CHECKING)
2637     is_class_level = 1;
2638
2639   leave_scope ();
2640   timevar_pop (TV_NAME_LOOKUP);
2641 }
2642
2643 /* Bind DECL to ID in the class_binding_level.  Returns nonzero if the
2644    binding was successful.  */
2645
2646 int
2647 push_class_binding (tree id, tree decl)
2648 {
2649   int result = 1;
2650   cxx_binding *binding = IDENTIFIER_BINDING (id);
2651   tree context;
2652
2653   timevar_push (TV_NAME_LOOKUP);
2654   /* Note that we declared this value so that we can issue an error if
2655      this is an invalid redeclaration of a name already used for some
2656      other purpose.  */
2657   note_name_declared_in_class (id, decl);
2658
2659   if (binding && binding->scope == class_binding_level)
2660     /* Supplement the existing binding.  */
2661     result = supplement_binding (IDENTIFIER_BINDING (id), decl);
2662   else
2663     /* Create a new binding.  */
2664     push_binding (id, decl, class_binding_level);
2665
2666   /* Update the IDENTIFIER_CLASS_VALUE for this ID to be the
2667      class-level declaration.  Note that we do not use DECL here
2668      because of the possibility of the `struct stat' hack; if DECL is
2669      a class-name or enum-name we might prefer a field-name, or some
2670      such.  */
2671   IDENTIFIER_CLASS_VALUE (id) = IDENTIFIER_BINDING (id)->value;
2672
2673   /* If this is a binding from a base class, mark it as such.  */
2674   binding = IDENTIFIER_BINDING (id);
2675   if (binding->value == decl && TREE_CODE (decl) != TREE_LIST)
2676     {
2677       if (TREE_CODE (decl) == OVERLOAD)
2678         context = CP_DECL_CONTEXT (OVL_CURRENT (decl));
2679       else
2680         {
2681           my_friendly_assert (DECL_P (decl), 0);
2682           context = context_for_name_lookup (decl);
2683         }
2684
2685       if (is_properly_derived_from (current_class_type, context))
2686         INHERITED_VALUE_BINDING_P (binding) = 1;
2687       else
2688         INHERITED_VALUE_BINDING_P (binding) = 0;
2689     }
2690   else if (binding->value == decl)
2691     /* We only encounter a TREE_LIST when push_class_decls detects an
2692        ambiguity.  Such an ambiguity can be overridden by a definition
2693        in this class.  */
2694     INHERITED_VALUE_BINDING_P (binding) = 1;
2695
2696   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, result);
2697 }
2698
2699 /* We are entering the scope of a class.  Clear IDENTIFIER_CLASS_VALUE
2700    for any names in enclosing classes.  */
2701
2702 void
2703 clear_identifier_class_values (void)
2704 {
2705   tree t;
2706
2707   if (!class_binding_level)
2708     return;
2709
2710   for (t = class_binding_level->class_shadowed;
2711        t;
2712        t = TREE_CHAIN (t))
2713     IDENTIFIER_CLASS_VALUE (TREE_PURPOSE (t)) = NULL_TREE;
2714 }
2715
2716 /* Make the declaration of X appear in CLASS scope.  */
2717
2718 bool
2719 pushdecl_class_level (tree x)
2720 {
2721   tree name;
2722   bool is_valid = true;
2723
2724   timevar_push (TV_NAME_LOOKUP);
2725   /* Get the name of X.  */
2726   if (TREE_CODE (x) == OVERLOAD)
2727     name = DECL_NAME (get_first_fn (x));
2728   else
2729     name = DECL_NAME (x);
2730
2731   if (name)
2732     {
2733       is_valid = push_class_level_binding (name, x);
2734       if (TREE_CODE (x) == TYPE_DECL)
2735         set_identifier_type_value (name, x);
2736     }
2737   else if (ANON_AGGR_TYPE_P (TREE_TYPE (x)))
2738     {
2739       /* If X is an anonymous aggregate, all of its members are
2740          treated as if they were members of the class containing the
2741          aggregate, for naming purposes.  */
2742       tree f;
2743
2744       for (f = TYPE_FIELDS (TREE_TYPE (x)); f; f = TREE_CHAIN (f))
2745         {
2746           location_t save_location = input_location;
2747           input_location = DECL_SOURCE_LOCATION (f);
2748           if (!pushdecl_class_level (f))
2749             is_valid = false;
2750           input_location = save_location;
2751         }
2752     }
2753   timevar_pop (TV_NAME_LOOKUP);
2754
2755   return is_valid;
2756 }
2757
2758 /* Make the declaration(s) of X appear in CLASS scope under the name
2759    NAME.  Returns true if the binding is valid.  */
2760
2761 bool
2762 push_class_level_binding (tree name, tree x)
2763 {
2764   cxx_binding *binding;
2765
2766   timevar_push (TV_NAME_LOOKUP);
2767   /* The class_binding_level will be NULL if x is a template
2768      parameter name in a member template.  */
2769   if (!class_binding_level)
2770     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2771
2772   /* Make sure that this new member does not have the same name
2773      as a template parameter.  */
2774   if (TYPE_BEING_DEFINED (current_class_type))
2775     check_template_shadow (x);
2776
2777   /* [class.mem]
2778
2779      If T is the name of a class, then each of the following shall
2780      have a name different from T:
2781
2782      -- every static data member of class T;
2783
2784      -- every member of class T that is itself a type;
2785
2786      -- every enumerator of every member of class T that is an
2787         enumerated type;
2788
2789      -- every member of every anonymous union that is a member of
2790         class T.
2791
2792      (Non-static data members were also forbidden to have the same
2793      name as T until TC1.)  */
2794   if ((TREE_CODE (x) == VAR_DECL
2795        || TREE_CODE (x) == CONST_DECL
2796        || (TREE_CODE (x) == TYPE_DECL
2797            && !DECL_SELF_REFERENCE_P (x))
2798        /* A data member of an anonymous union.  */
2799        || (TREE_CODE (x) == FIELD_DECL
2800            && DECL_CONTEXT (x) != current_class_type))
2801       && DECL_NAME (x) == constructor_name (current_class_type))
2802     {
2803       tree scope = context_for_name_lookup (x);
2804       if (TYPE_P (scope) && same_type_p (scope, current_class_type))
2805         {
2806           error ("`%D' has the same name as the class in which it is declared",
2807                  x);
2808           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, false);
2809         }
2810     }
2811
2812   /* If this declaration shadows a declaration from an enclosing
2813      class, then we will need to restore IDENTIFIER_CLASS_VALUE when
2814      we leave this class.  Record the shadowed declaration here.  */
2815   binding = IDENTIFIER_BINDING (name);
2816   if (binding && binding->value)
2817     {
2818       tree bval = binding->value;
2819       tree old_decl = NULL_TREE;
2820
2821       if (INHERITED_VALUE_BINDING_P (binding))
2822         {
2823           /* If the old binding was from a base class, and was for a
2824              tag name, slide it over to make room for the new binding.
2825              The old binding is still visible if explicitly qualified
2826              with a class-key.  */
2827           if (TREE_CODE (bval) == TYPE_DECL && DECL_ARTIFICIAL (bval)
2828               && !(TREE_CODE (x) == TYPE_DECL && DECL_ARTIFICIAL (x)))
2829             {
2830               old_decl = binding->type;
2831               binding->type = bval;
2832               binding->value = NULL_TREE;
2833               INHERITED_VALUE_BINDING_P (binding) = 0;
2834             }
2835           else
2836             old_decl = bval;
2837         }
2838       else if (TREE_CODE (x) == OVERLOAD && is_overloaded_fn (bval))
2839         old_decl = bval;
2840       else if (TREE_CODE (x) == USING_DECL && TREE_CODE (bval) == USING_DECL)
2841         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2842       else if (TREE_CODE (x) == USING_DECL && is_overloaded_fn (bval))
2843         old_decl = bval;
2844       else if (TREE_CODE (bval) == USING_DECL && is_overloaded_fn (x))
2845         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2846       
2847       if (old_decl)
2848         {
2849           tree shadow;
2850           
2851           /* Find the previous binding of name on the class-shadowed
2852              list, and update it.  */
2853           for (shadow = class_binding_level->class_shadowed;
2854                shadow;
2855                shadow = TREE_CHAIN (shadow))
2856             if (TREE_PURPOSE (shadow) == name
2857                 && TREE_TYPE (shadow) == old_decl)
2858               {
2859                 binding->value = x;
2860                 INHERITED_VALUE_BINDING_P (binding) = 0;
2861                 TREE_TYPE (shadow) = x;
2862                 IDENTIFIER_CLASS_VALUE (name) = x;
2863                 POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2864               }
2865         }
2866     }
2867
2868   /* If we didn't replace an existing binding, put the binding on the
2869      stack of bindings for the identifier, and update the shadowed list.  */
2870   if (push_class_binding (name, x))
2871     {
2872       class_binding_level->class_shadowed
2873         = tree_cons (name, NULL,
2874                      class_binding_level->class_shadowed);
2875       /* Record the value we are binding NAME to so that we can know
2876          what to pop later.  */
2877       TREE_TYPE (class_binding_level->class_shadowed) = x;
2878       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, true);
2879     }
2880
2881   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, false);
2882 }
2883
2884 tree
2885 do_class_using_decl (tree decl)
2886 {
2887   tree name, value, scope, type;
2888   
2889   if (TREE_CODE (decl) != SCOPE_REF
2890       || !TREE_OPERAND (decl, 0)
2891       || !TYPE_P (TREE_OPERAND (decl, 0)))
2892     {
2893       error ("using-declaration for non-member at class scope");
2894       return NULL_TREE;
2895     }
2896   scope = TREE_OPERAND (decl, 0);
2897   name = TREE_OPERAND (decl, 1);
2898   if (TREE_CODE (name) == BIT_NOT_EXPR)
2899     {
2900       error ("using-declaration cannot name destructor");
2901       return NULL_TREE;
2902     }
2903   if (TREE_CODE (name) == TYPE_DECL)
2904     name = DECL_NAME (name);
2905   else if (TREE_CODE (name) == TEMPLATE_DECL)
2906      name = DECL_NAME (name);
2907   else if (BASELINK_P (name))
2908     {
2909       tree fns = BASELINK_FUNCTIONS (name);
2910       name = DECL_NAME (get_first_fn (fns));
2911     }
2912
2913   my_friendly_assert (TREE_CODE (name) == IDENTIFIER_NODE, 980716);
2914
2915   /* Dependent using decls have a NULL type, non-dependent ones have a
2916      void type.  */
2917   type = dependent_type_p (scope) ? NULL_TREE : void_type_node;
2918   value = build_lang_decl (USING_DECL, name, type);
2919   DECL_INITIAL (value) = scope;
2920
2921   if (scope && !processing_template_decl)
2922     {
2923       tree r;
2924
2925       r = lookup_qualified_name (scope, name, false, false);
2926       if (r && TREE_CODE (r) != ERROR_MARK)
2927         cp_emit_debug_info_for_using (r, scope);
2928     }
2929   return value;
2930 }
2931
2932 void
2933 set_class_shadows (tree shadows)
2934 {
2935   class_binding_level->class_shadowed = shadows;
2936 }
2937 \f
2938 /* Return the binding value for name in scope.  */
2939
2940 tree
2941 namespace_binding (tree name, tree scope)
2942 {
2943   cxx_binding *binding;
2944
2945   if (scope == NULL)
2946     scope = global_namespace;
2947   scope = ORIGINAL_NAMESPACE (scope);
2948   binding = cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (scope), name);
2949
2950   return binding ? binding->value : NULL_TREE;
2951 }
2952
2953 /* Set the binding value for name in scope.  */
2954
2955 void
2956 set_namespace_binding (tree name, tree scope, tree val)
2957 {
2958   cxx_binding *b;
2959
2960   timevar_push (TV_NAME_LOOKUP);
2961   if (scope == NULL_TREE)
2962     scope = global_namespace;
2963   b = binding_for_name (NAMESPACE_LEVEL (scope), name);
2964   if (!b->value || TREE_CODE (val) == OVERLOAD || val == error_mark_node)
2965     b->value = val;
2966   else
2967     supplement_binding (b, val);
2968   timevar_pop (TV_NAME_LOOKUP);
2969 }
2970
2971 /* Compute the namespace where a declaration is defined.  */
2972
2973 static tree
2974 decl_namespace (tree decl)
2975 {
2976   timevar_push (TV_NAME_LOOKUP);
2977   if (TYPE_P (decl))
2978     decl = TYPE_STUB_DECL (decl);
2979   while (DECL_CONTEXT (decl))
2980     {
2981       decl = DECL_CONTEXT (decl);
2982       if (TREE_CODE (decl) == NAMESPACE_DECL)
2983         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, decl);
2984       if (TYPE_P (decl))
2985         decl = TYPE_STUB_DECL (decl);
2986       my_friendly_assert (DECL_P (decl), 390);
2987     }
2988
2989   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, global_namespace);
2990 }
2991
2992 /* Set the context of a declaration to scope. Complain if we are not
2993    outside scope.  */
2994
2995 void
2996 set_decl_namespace (tree decl, tree scope, bool friendp)
2997 {
2998   tree old;
2999   
3000   /* Get rid of namespace aliases.  */
3001   scope = ORIGINAL_NAMESPACE (scope);
3002   
3003   /* It is ok for friends to be qualified in parallel space.  */
3004   if (!friendp && !is_ancestor (current_namespace, scope))
3005     error ("declaration of `%D' not in a namespace surrounding `%D'",
3006               decl, scope);
3007   DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
3008   if (scope != current_namespace)
3009     {
3010       /* See whether this has been declared in the namespace.  */
3011       old = namespace_binding (DECL_NAME (decl), scope);
3012       if (!old)
3013         /* No old declaration at all.  */
3014         goto complain;
3015       /* A template can be explicitly specialized in any namespace.  */
3016       if (processing_explicit_instantiation)
3017         return;
3018       if (!is_overloaded_fn (decl))
3019         /* Don't compare non-function decls with decls_match here,
3020            since it can't check for the correct constness at this
3021            point. pushdecl will find those errors later.  */
3022         return;
3023       /* Since decl is a function, old should contain a function decl.  */
3024       if (!is_overloaded_fn (old))
3025         goto complain;
3026       if (processing_template_decl || processing_specialization)
3027         /* We have not yet called push_template_decl to turn a
3028            FUNCTION_DECL into a TEMPLATE_DECL, so the declarations
3029            won't match.  But, we'll check later, when we construct the
3030            template.  */
3031         return;
3032       if (is_overloaded_fn (old))
3033         {
3034           for (; old; old = OVL_NEXT (old))
3035             if (decls_match (decl, OVL_CURRENT (old)))
3036               return;
3037         }
3038       else
3039         if (decls_match (decl, old))
3040           return;
3041     }
3042   else
3043     return;
3044  complain:
3045   error ("`%D' should have been declared inside `%D'",
3046             decl, scope);
3047
3048
3049 /* Return the namespace where the current declaration is declared.  */
3050
3051 tree
3052 current_decl_namespace (void)
3053 {
3054   tree result;
3055   /* If we have been pushed into a different namespace, use it.  */
3056   if (decl_namespace_list)
3057     return TREE_PURPOSE (decl_namespace_list);
3058
3059   if (current_class_type)
3060     result = decl_namespace (TYPE_STUB_DECL (current_class_type));
3061   else if (current_function_decl)
3062     result = decl_namespace (current_function_decl);
3063   else 
3064     result = current_namespace;
3065   return result;
3066 }
3067
3068 /* Push into the scope of the NAME namespace.  If NAME is NULL_TREE, then we
3069    select a name that is unique to this compilation unit.  */
3070
3071 void
3072 push_namespace (tree name)
3073 {
3074   tree d = NULL_TREE;
3075   int need_new = 1;
3076   int implicit_use = 0;
3077   bool anon = !name;
3078
3079   timevar_push (TV_NAME_LOOKUP);
3080   
3081   /* We should not get here if the global_namespace is not yet constructed
3082      nor if NAME designates the global namespace:  The global scope is
3083      constructed elsewhere.  */
3084   my_friendly_assert (global_namespace != NULL && name != global_scope_name,
3085                       20030531);
3086
3087   if (anon)
3088     {
3089       /* The name of anonymous namespace is unique for the translation
3090          unit.  */
3091       if (!anonymous_namespace_name)
3092         anonymous_namespace_name = get_file_function_name ('N');
3093       name = anonymous_namespace_name;
3094       d = IDENTIFIER_NAMESPACE_VALUE (name);
3095       if (d)
3096         /* Reopening anonymous namespace.  */
3097         need_new = 0;
3098       implicit_use = 1;
3099     }
3100   else
3101     {
3102       /* Check whether this is an extended namespace definition.  */
3103       d = IDENTIFIER_NAMESPACE_VALUE (name);
3104       if (d != NULL_TREE && TREE_CODE (d) == NAMESPACE_DECL)
3105         {
3106           need_new = 0;
3107           if (DECL_NAMESPACE_ALIAS (d))
3108             {
3109               error ("namespace alias `%D' not allowed here, assuming `%D'",
3110                         d, DECL_NAMESPACE_ALIAS (d));
3111               d = DECL_NAMESPACE_ALIAS (d);
3112             }
3113         }
3114     }
3115
3116   if (need_new)
3117     {
3118       /* Make a new namespace, binding the name to it.  */
3119       d = build_lang_decl (NAMESPACE_DECL, name, void_type_node);
3120       DECL_CONTEXT (d) = FROB_CONTEXT (current_namespace);
3121       pushdecl (d);
3122       if (anon)
3123         {
3124           /* Clear DECL_NAME for the benefit of debugging back ends.  */
3125           SET_DECL_ASSEMBLER_NAME (d, name);
3126           DECL_NAME (d) = NULL_TREE;
3127         }
3128       begin_scope (sk_namespace, d);
3129     }
3130   else
3131     resume_scope (NAMESPACE_LEVEL (d));
3132
3133   if (implicit_use)
3134     do_using_directive (d);
3135   /* Enter the name space.  */
3136   current_namespace = d;
3137
3138   timevar_pop (TV_NAME_LOOKUP);
3139 }
3140
3141 /* Pop from the scope of the current namespace.  */
3142
3143 void
3144 pop_namespace (void)
3145 {
3146   my_friendly_assert (current_namespace != global_namespace, 20010801);
3147   current_namespace = CP_DECL_CONTEXT (current_namespace);
3148   /* The binding level is not popped, as it might be re-opened later.  */
3149   leave_scope ();
3150 }
3151
3152 /* Push into the scope of the namespace NS, even if it is deeply
3153    nested within another namespace.  */
3154
3155 void
3156 push_nested_namespace (tree ns)
3157 {
3158   if (ns == global_namespace)
3159     push_to_top_level ();
3160   else
3161     {
3162       push_nested_namespace (CP_DECL_CONTEXT (ns));
3163       push_namespace (DECL_NAME (ns));
3164     }
3165 }
3166
3167 /* Pop back from the scope of the namespace NS, which was previously
3168    entered with push_nested_namespace.  */
3169
3170 void
3171 pop_nested_namespace (tree ns)
3172 {
3173   timevar_push (TV_NAME_LOOKUP);
3174   while (ns != global_namespace)
3175     {
3176       pop_namespace ();
3177       ns = CP_DECL_CONTEXT (ns);
3178     }
3179
3180   pop_from_top_level ();
3181   timevar_pop (TV_NAME_LOOKUP);
3182 }
3183
3184 /* Temporarily set the namespace for the current declaration.  */
3185
3186 void
3187 push_decl_namespace (tree decl)
3188 {
3189   if (TREE_CODE (decl) != NAMESPACE_DECL)
3190     decl = decl_namespace (decl);
3191   decl_namespace_list = tree_cons (ORIGINAL_NAMESPACE (decl),
3192                                    NULL_TREE, decl_namespace_list);
3193 }
3194
3195 /* [namespace.memdef]/2 */
3196
3197 void
3198 pop_decl_namespace (void)
3199 {
3200   decl_namespace_list = TREE_CHAIN (decl_namespace_list);
3201 }
3202
3203 /* Return the namespace that is the common ancestor 
3204    of two given namespaces.  */
3205
3206 static tree
3207 namespace_ancestor (tree ns1, tree ns2)
3208 {
3209   timevar_push (TV_NAME_LOOKUP);
3210   if (is_ancestor (ns1, ns2))
3211     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ns1);
3212   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
3213                           namespace_ancestor (CP_DECL_CONTEXT (ns1), ns2));
3214 }
3215
3216 /* Process a namespace-alias declaration.  */
3217
3218 void
3219 do_namespace_alias (tree alias, tree namespace)
3220 {
3221   if (TREE_CODE (namespace) != NAMESPACE_DECL)
3222     {
3223       /* The parser did not find it, so it's not there.  */
3224       error ("unknown namespace `%D'", namespace);
3225       return;
3226     }
3227
3228   namespace = ORIGINAL_NAMESPACE (namespace);
3229
3230   /* Build the alias.  */
3231   alias = build_lang_decl (NAMESPACE_DECL, alias, void_type_node);     
3232   DECL_NAMESPACE_ALIAS (alias) = namespace;
3233   DECL_EXTERNAL (alias) = 1;
3234   pushdecl (alias);
3235
3236   /* Emit debug info for namespace alias.  */
3237   (*debug_hooks->global_decl) (alias);
3238 }
3239
3240 /* Like pushdecl, only it places X in the current namespace,
3241    if appropriate.  */
3242
3243 tree
3244 pushdecl_namespace_level (tree x)
3245 {
3246   struct cp_binding_level *b = current_binding_level;
3247   tree t;
3248
3249   timevar_push (TV_NAME_LOOKUP);
3250   t = pushdecl_with_scope (x, NAMESPACE_LEVEL (current_namespace));
3251
3252   /* Now, the type_shadowed stack may screw us.  Munge it so it does
3253      what we want.  */
3254   if (TREE_CODE (x) == TYPE_DECL)
3255     {
3256       tree name = DECL_NAME (x);
3257       tree newval;
3258       tree *ptr = (tree *)0;
3259       for (; !global_scope_p (b); b = b->level_chain)
3260         {
3261           tree shadowed = b->type_shadowed;
3262           for (; shadowed; shadowed = TREE_CHAIN (shadowed))
3263             if (TREE_PURPOSE (shadowed) == name)
3264               {
3265                 ptr = &TREE_VALUE (shadowed);
3266                 /* Can't break out of the loop here because sometimes
3267                    a binding level will have duplicate bindings for
3268                    PT names.  It's gross, but I haven't time to fix it.  */
3269               }
3270         }
3271       newval = TREE_TYPE (x);
3272       if (ptr == (tree *)0)
3273         {
3274           /* @@ This shouldn't be needed.  My test case "zstring.cc" trips
3275              up here if this is changed to an assertion.  --KR  */
3276           SET_IDENTIFIER_TYPE_VALUE (name, x);
3277         }
3278       else
3279         {
3280           *ptr = newval;
3281         }
3282     }
3283   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
3284 }
3285
3286 /* Insert USED into the using list of USER. Set INDIRECT_flag if this
3287    directive is not directly from the source. Also find the common
3288    ancestor and let our users know about the new namespace */
3289 static void 
3290 add_using_namespace (tree user, tree used, bool indirect)
3291 {
3292   tree t;
3293   timevar_push (TV_NAME_LOOKUP);
3294   /* Using oneself is a no-op.  */
3295   if (user == used)
3296     {
3297       timevar_pop (TV_NAME_LOOKUP);
3298       return;
3299     }
3300   my_friendly_assert (TREE_CODE (user) == NAMESPACE_DECL, 380);
3301   my_friendly_assert (TREE_CODE (used) == NAMESPACE_DECL, 380);
3302   /* Check if we already have this.  */
3303   t = purpose_member (used, DECL_NAMESPACE_USING (user));
3304   if (t != NULL_TREE)
3305     {
3306       if (!indirect)
3307         /* Promote to direct usage.  */
3308         TREE_INDIRECT_USING (t) = 0;
3309       timevar_pop (TV_NAME_LOOKUP);
3310       return;
3311     }
3312
3313   /* Add used to the user's using list.  */
3314   DECL_NAMESPACE_USING (user) 
3315     = tree_cons (used, namespace_ancestor (user, used), 
3316                  DECL_NAMESPACE_USING (user));
3317
3318   TREE_INDIRECT_USING (DECL_NAMESPACE_USING (user)) = indirect;
3319
3320   /* Add user to the used's users list.  */
3321   DECL_NAMESPACE_USERS (used)
3322     = tree_cons (user, 0, DECL_NAMESPACE_USERS (used));
3323
3324   /* Recursively add all namespaces used.  */
3325   for (t = DECL_NAMESPACE_USING (used); t; t = TREE_CHAIN (t))
3326     /* indirect usage */
3327     add_using_namespace (user, TREE_PURPOSE (t), 1);
3328
3329   /* Tell everyone using us about the new used namespaces.  */
3330   for (t = DECL_NAMESPACE_USERS (user); t; t = TREE_CHAIN (t))
3331     add_using_namespace (TREE_PURPOSE (t), used, 1);
3332   timevar_pop (TV_NAME_LOOKUP);
3333 }
3334
3335 /* Process a using-declaration not appearing in class or local scope.  */
3336
3337 void
3338 do_toplevel_using_decl (tree decl, tree scope, tree name)
3339 {
3340   tree oldval, oldtype, newval, newtype;
3341   tree orig_decl = decl;
3342   cxx_binding *binding;
3343
3344   decl = validate_nonmember_using_decl (decl, scope, name);
3345   if (decl == NULL_TREE)
3346     return;
3347   
3348   binding = binding_for_name (NAMESPACE_LEVEL (current_namespace), name);
3349
3350   oldval = binding->value;
3351   oldtype = binding->type;
3352
3353   do_nonmember_using_decl (scope, name, oldval, oldtype, &newval, &newtype);
3354
3355   /* Emit debug info.  */
3356   if (!processing_template_decl)
3357     cp_emit_debug_info_for_using (orig_decl, current_namespace);
3358
3359   /* Copy declarations found.  */
3360   if (newval)
3361     binding->value = newval;
3362   if (newtype)
3363     binding->type = newtype;
3364   return;
3365 }
3366
3367 /* Process a using-directive.  */
3368
3369 void
3370 do_using_directive (tree namespace)
3371 {
3372   tree context = NULL_TREE;
3373
3374   if (building_stmt_tree ())
3375     add_stmt (build_stmt (USING_STMT, namespace));
3376   
3377   /* using namespace A::B::C; */
3378   if (TREE_CODE (namespace) == SCOPE_REF)
3379       namespace = TREE_OPERAND (namespace, 1);
3380   if (TREE_CODE (namespace) == IDENTIFIER_NODE)
3381     {
3382       /* Lookup in lexer did not find a namespace.  */
3383       if (!processing_template_decl)
3384         error ("namespace `%T' undeclared", namespace);
3385       return;
3386     }
3387   if (TREE_CODE (namespace) != NAMESPACE_DECL)
3388     {
3389       if (!processing_template_decl)
3390         error ("`%T' is not a namespace", namespace);
3391       return;
3392     }
3393   namespace = ORIGINAL_NAMESPACE (namespace);
3394   if (!toplevel_bindings_p ())
3395     {
3396       push_using_directive (namespace);
3397       context = current_scope ();
3398     }
3399   else
3400     {
3401       /* direct usage */
3402       add_using_namespace (current_namespace, namespace, 0);
3403       if (current_namespace != global_namespace)
3404         context = current_namespace;
3405     }
3406       
3407   /* Emit debugging info.  */
3408   if (!processing_template_decl)
3409     (*debug_hooks->imported_module_or_decl) (namespace, context);
3410 }
3411
3412 /* Deal with a using-directive seen by the parser.  Currently we only
3413    handle attributes here, since they cannot appear inside a template.  */
3414
3415 void
3416 parse_using_directive (tree namespace, tree attribs)
3417 {
3418   tree a;
3419
3420   do_using_directive (namespace);
3421
3422   for (a = attribs; a; a = TREE_CHAIN (a))
3423     {
3424       tree name = TREE_PURPOSE (a);
3425       if (is_attribute_p ("strong", name))
3426         {
3427           if (!toplevel_bindings_p ())
3428             error ("strong using only meaningful at namespace scope");
3429           else
3430             DECL_NAMESPACE_ASSOCIATIONS (namespace)
3431               = tree_cons (current_namespace, 0,
3432                            DECL_NAMESPACE_ASSOCIATIONS (namespace));
3433         }
3434       else
3435         warning ("`%D' attribute directive ignored", name);
3436     }
3437 }
3438
3439 /* Like pushdecl, only it places X in the global scope if appropriate.
3440    Calls cp_finish_decl to register the variable, initializing it with
3441    *INIT, if INIT is non-NULL.  */
3442
3443 static tree
3444 pushdecl_top_level_1 (tree x, tree *init)
3445 {
3446   timevar_push (TV_NAME_LOOKUP);
3447   push_to_top_level ();
3448   x = pushdecl_namespace_level (x);
3449   if (init)
3450     cp_finish_decl (x, *init, NULL_TREE, 0);
3451   pop_from_top_level ();
3452   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, x);
3453 }
3454
3455 /* Like pushdecl, only it places X in the global scope if appropriate.  */
3456
3457 tree
3458 pushdecl_top_level (tree x)
3459 {
3460   return pushdecl_top_level_1 (x, NULL);
3461 }
3462
3463 /* Like pushdecl, only it places X in the global scope if
3464    appropriate.  Calls cp_finish_decl to register the variable,
3465    initializing it with INIT.  */
3466
3467 tree
3468 pushdecl_top_level_and_finish (tree x, tree init)
3469 {
3470   return pushdecl_top_level_1 (x, &init);
3471 }
3472
3473 /* Combines two sets of overloaded functions into an OVERLOAD chain, removing
3474    duplicates.  The first list becomes the tail of the result.
3475
3476    The algorithm is O(n^2).  We could get this down to O(n log n) by
3477    doing a sort on the addresses of the functions, if that becomes
3478    necessary.  */
3479
3480 static tree
3481 merge_functions (tree s1, tree s2)
3482 {
3483   for (; s2; s2 = OVL_NEXT (s2))
3484     {
3485       tree fn2 = OVL_CURRENT (s2);
3486       tree fns1;
3487
3488       for (fns1 = s1; fns1; fns1 = OVL_NEXT (fns1))
3489         {
3490           tree fn1 = OVL_CURRENT (fns1);
3491
3492           /* If the function from S2 is already in S1, there is no
3493              need to add it again.  For `extern "C"' functions, we
3494              might have two FUNCTION_DECLs for the same function, in
3495              different namespaces; again, we only need one of them.  */
3496           if (fn1 == fn2 
3497               || (DECL_EXTERN_C_P (fn1) && DECL_EXTERN_C_P (fn2)
3498                   && DECL_NAME (fn1) == DECL_NAME (fn2)))
3499             break;
3500         }
3501       
3502       /* If we exhausted all of the functions in S1, FN2 is new.  */
3503       if (!fns1)
3504         s1 = build_overload (fn2, s1);
3505     }
3506   return s1;
3507 }
3508
3509 /* This should return an error not all definitions define functions.
3510    It is not an error if we find two functions with exactly the
3511    same signature, only if these are selected in overload resolution.
3512    old is the current set of bindings, new the freshly-found binding.
3513    XXX Do we want to give *all* candidates in case of ambiguity?
3514    XXX In what way should I treat extern declarations?
3515    XXX I don't want to repeat the entire duplicate_decls here */
3516
3517 static void
3518 ambiguous_decl (tree name, struct scope_binding *old, cxx_binding *new,
3519                 int flags)
3520 {
3521   tree val, type;
3522   my_friendly_assert (old != NULL, 393);
3523   /* Copy the value.  */
3524   val = new->value;
3525   if (val)
3526     switch (TREE_CODE (val))
3527       {
3528       case TEMPLATE_DECL:
3529         /* If we expect types or namespaces, and not templates,
3530            or this is not a template class.  */
3531         if (LOOKUP_QUALIFIERS_ONLY (flags)
3532             && !DECL_CLASS_TEMPLATE_P (val))
3533           val = NULL_TREE;
3534         break;
3535       case TYPE_DECL:
3536         if (LOOKUP_NAMESPACES_ONLY (flags))
3537           val = NULL_TREE;
3538         break;
3539       case NAMESPACE_DECL:
3540         if (LOOKUP_TYPES_ONLY (flags))
3541           val = NULL_TREE;
3542         break;
3543       case FUNCTION_DECL:
3544         /* Ignore built-in functions that are still anticipated.  */
3545         if (LOOKUP_QUALIFIERS_ONLY (flags) || DECL_ANTICIPATED (val))
3546           val = NULL_TREE;
3547         break;
3548       default:
3549         if (LOOKUP_QUALIFIERS_ONLY (flags))
3550           val = NULL_TREE;
3551       }
3552         
3553   if (!old->value)
3554     old->value = val;
3555   else if (val && val != old->value)
3556     {
3557       if (is_overloaded_fn (old->value) && is_overloaded_fn (val))
3558         old->value = merge_functions (old->value, val);
3559       else
3560         {
3561           /* Some declarations are functions, some are not.  */
3562           if (flags & LOOKUP_COMPLAIN)
3563             {
3564               /* If we've already given this error for this lookup,
3565                  old->value is error_mark_node, so let's not
3566                  repeat ourselves.  */
3567               if (old->value != error_mark_node)
3568                 {
3569                   error ("use of `%D' is ambiguous", name);
3570                   cp_error_at ("  first declared as `%#D' here",
3571                                old->value);
3572                 }
3573               cp_error_at ("  also declared as `%#D' here", val);
3574             }
3575           old->value = error_mark_node;
3576         }
3577     }
3578   /* ... and copy the type.  */
3579   type = new->type;
3580   if (LOOKUP_NAMESPACES_ONLY (flags))
3581     type = NULL_TREE;
3582   if (!old->type)
3583     old->type = type;
3584   else if (type && old->type != type)
3585     {
3586       if (flags & LOOKUP_COMPLAIN)
3587         {
3588           error ("`%D' denotes an ambiguous type",name);
3589           error ("%J  first type here", TYPE_MAIN_DECL (old->type));
3590           error ("%J  other type here", TYPE_MAIN_DECL (type));
3591         }
3592     }
3593 }
3594
3595 /* Return the declarations that are members of the namespace NS.  */
3596
3597 tree
3598 cp_namespace_decls (tree ns)
3599 {
3600   return NAMESPACE_LEVEL (ns)->names;
3601 }
3602
3603 /* Combine prefer_type and namespaces_only into flags.  */
3604
3605 static int
3606 lookup_flags (int prefer_type, int namespaces_only)
3607 {
3608   if (namespaces_only)
3609     return LOOKUP_PREFER_NAMESPACES;
3610   if (prefer_type > 1)
3611     return LOOKUP_PREFER_TYPES;
3612   if (prefer_type > 0)
3613     return LOOKUP_PREFER_BOTH;
3614   return 0;
3615 }
3616
3617 /* Given a lookup that returned VAL, use FLAGS to decide if we want to
3618    ignore it or not.  Subroutine of lookup_name_real.  */
3619
3620 static tree
3621 qualify_lookup (tree val, int flags)
3622 {
3623   if (val == NULL_TREE)
3624     return val;
3625   if ((flags & LOOKUP_PREFER_NAMESPACES) && TREE_CODE (val) == NAMESPACE_DECL)
3626     return val;
3627   if ((flags & LOOKUP_PREFER_TYPES)
3628       && (TREE_CODE (val) == TYPE_DECL || TREE_CODE (val) == TEMPLATE_DECL))
3629     return val;
3630   if (flags & (LOOKUP_PREFER_NAMESPACES | LOOKUP_PREFER_TYPES))
3631     return NULL_TREE;
3632   return val;
3633 }
3634
3635 /* Look up NAME in the NAMESPACE.  */
3636
3637 tree
3638 lookup_namespace_name (tree namespace, tree name)
3639 {
3640   tree val;
3641   tree template_id = NULL_TREE;
3642   struct scope_binding binding = EMPTY_SCOPE_BINDING;
3643
3644   timevar_push (TV_NAME_LOOKUP);
3645   my_friendly_assert (TREE_CODE (namespace) == NAMESPACE_DECL, 370);
3646
3647   if (TREE_CODE (name) == NAMESPACE_DECL)
3648     /* This happens for A::B<int> when B is a namespace.  */
3649     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, name);
3650   else if (TREE_CODE (name) == TEMPLATE_DECL)
3651     {
3652       /* This happens for A::B where B is a template, and there are no
3653          template arguments.  */
3654       error ("invalid use of `%D'", name);
3655       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3656     }
3657
3658   namespace = ORIGINAL_NAMESPACE (namespace);
3659
3660   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3661     {
3662       template_id = name;
3663       name = TREE_OPERAND (name, 0);
3664       if (TREE_CODE (name) == OVERLOAD)
3665         name = DECL_NAME (OVL_CURRENT (name));
3666       else if (DECL_P (name))
3667         name = DECL_NAME (name);
3668     }
3669
3670   my_friendly_assert (TREE_CODE (name) == IDENTIFIER_NODE, 373);
3671
3672   if (!qualified_lookup_using_namespace (name, namespace, &binding, 0))
3673     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3674
3675   if (binding.value)
3676     {
3677       val = binding.value;
3678
3679       if (template_id)
3680         {
3681           if (DECL_CLASS_TEMPLATE_P (val))
3682             val = lookup_template_class (val,
3683                                          TREE_OPERAND (template_id, 1),
3684                                          /*in_decl=*/NULL_TREE,
3685                                          /*context=*/NULL_TREE,
3686                                          /*entering_scope=*/0,
3687                                          tf_error | tf_warning);
3688           else if (DECL_FUNCTION_TEMPLATE_P (val)
3689                    || TREE_CODE (val) == OVERLOAD)
3690             val = lookup_template_function (val,
3691                                             TREE_OPERAND (template_id, 1));
3692           else
3693             {
3694               error ("`%D::%D' is not a template",
3695                         namespace, name);
3696               POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3697             }
3698         }
3699
3700       /* If we have a single function from a using decl, pull it out.  */
3701       if (TREE_CODE (val) == OVERLOAD && ! really_overloaded_fn (val))
3702         val = OVL_FUNCTION (val);
3703
3704       /* Ignore built-in functions that haven't been prototyped yet.  */
3705       if (!val || !DECL_P(val)
3706           || !DECL_LANG_SPECIFIC(val)
3707           || !DECL_ANTICIPATED (val))
3708         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
3709     }
3710
3711   error ("`%D' undeclared in namespace `%D'", name, namespace);
3712   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3713 }
3714
3715 /* Select the right _DECL from multiple choices.  */
3716
3717 static tree
3718 select_decl (const struct scope_binding *binding, int flags)
3719 {
3720   tree val;
3721   val = binding->value;
3722
3723   timevar_push (TV_NAME_LOOKUP);
3724   if (LOOKUP_NAMESPACES_ONLY (flags))
3725     {
3726       /* We are not interested in types.  */
3727       if (val && TREE_CODE (val) == NAMESPACE_DECL)
3728         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
3729       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
3730     }
3731
3732   /* If looking for a type, or if there is no non-type binding, select
3733      the value binding.  */
3734   if (binding->type && (!val || (flags & LOOKUP_PREFER_TYPES)))
3735     val = binding->type;
3736   /* Don't return non-types if we really prefer types.  */
3737   else if (val && LOOKUP_TYPES_ONLY (flags) 
3738            && ! DECL_DECLARES_TYPE_P (val))
3739     val = NULL_TREE;
3740
3741   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
3742 }
3743
3744 /* Unscoped lookup of a global: iterate over current namespaces,
3745    considering using-directives.  */
3746
3747 static tree
3748 unqualified_namespace_lookup (tree name, int flags)
3749 {
3750   tree initial = current_decl_namespace ();
3751   tree scope = initial;
3752   tree siter;
3753   struct cp_binding_level *level;
3754   tree val = NULL_TREE;
3755   struct scope_binding binding = EMPTY_SCOPE_BINDING;
3756
3757   timevar_push (TV_NAME_LOOKUP);
3758
3759   for (; !val; scope = CP_DECL_CONTEXT (scope))
3760     {
3761       cxx_binding *b =
3762          cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (scope), name);
3763
3764       /* Ignore anticipated built-in functions.  */
3765       if (b && b->value && DECL_P (b->value)
3766           && DECL_LANG_SPECIFIC (b->value) && DECL_ANTICIPATED (b->value))
3767         /* Keep binding cleared.  */;
3768       else if (b)
3769         {
3770           /* Initialize binding for this context.  */
3771           binding.value = b->value;
3772           binding.type = b->type;
3773         }
3774
3775       /* Add all _DECLs seen through local using-directives.  */
3776       for (level = current_binding_level;
3777            level->kind != sk_namespace;
3778            level = level->level_chain)
3779         if (!lookup_using_namespace (name, &binding, level->using_directives,
3780                                      scope, flags))
3781           /* Give up because of error.  */
3782           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3783
3784       /* Add all _DECLs seen through global using-directives.  */
3785       /* XXX local and global using lists should work equally.  */
3786       siter = initial;
3787       while (1)
3788         {
3789           if (!lookup_using_namespace (name, &binding,
3790                                        DECL_NAMESPACE_USING (siter),
3791                                        scope, flags))
3792             /* Give up because of error.  */
3793             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
3794           if (siter == scope) break;
3795           siter = CP_DECL_CONTEXT (siter);
3796         }
3797
3798       val = select_decl (&binding, flags);
3799       if (scope == global_namespace)
3800         break;
3801     }
3802   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
3803 }
3804
3805 /* Look up NAME (an IDENTIFIER_NODE) in SCOPE (either a NAMESPACE_DECL
3806    or a class TYPE).  If IS_TYPE_P is TRUE, then ignore non-type
3807    bindings.  
3808
3809    Returns a DECL (or OVERLOAD, or BASELINK) representing the
3810    declaration found.  If no suitable declaration can be found,
3811    ERROR_MARK_NODE is returned.  Iif COMPLAIN is true and SCOPE is
3812    neither a class-type nor a namespace a diagnostic is issued.  */
3813
3814 tree
3815 lookup_qualified_name (tree scope, tree name, bool is_type_p, bool complain)
3816 {
3817   int flags = 0;
3818
3819   if (TREE_CODE (scope) == NAMESPACE_DECL)
3820     {
3821       struct scope_binding binding = EMPTY_SCOPE_BINDING;
3822
3823       flags |= LOOKUP_COMPLAIN;
3824       if (is_type_p)
3825         flags |= LOOKUP_PREFER_TYPES;
3826       if (qualified_lookup_using_namespace (name, scope, &binding, flags))
3827         return select_decl (&binding, flags);
3828     }
3829   else if (is_aggr_type (scope, complain))
3830     {
3831       tree t;
3832       t = lookup_member (scope, name, 0, is_type_p);
3833       if (t)
3834         return t;
3835     }
3836
3837   return error_mark_node;
3838 }
3839
3840 /* Subroutine of unqualified_namespace_lookup:
3841    Add the bindings of NAME in used namespaces to VAL.
3842    We are currently looking for names in namespace SCOPE, so we
3843    look through USINGS for using-directives of namespaces
3844    which have SCOPE as a common ancestor with the current scope.
3845    Returns false on errors.  */
3846
3847 static bool
3848 lookup_using_namespace (tree name, struct scope_binding *val,
3849                         tree usings, tree scope, int flags)
3850 {
3851   tree iter;
3852   timevar_push (TV_NAME_LOOKUP);
3853   /* Iterate over all used namespaces in current, searching for using
3854      directives of scope.  */
3855   for (iter = usings; iter; iter = TREE_CHAIN (iter))
3856     if (TREE_VALUE (iter) == scope)
3857       {
3858         tree used = ORIGINAL_NAMESPACE (TREE_PURPOSE (iter));
3859         cxx_binding *val1 =
3860           cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (used), name);
3861         /* Resolve ambiguities.  */
3862         if (val1)
3863           ambiguous_decl (name, val, val1, flags);
3864       }
3865   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val->value != error_mark_node);
3866 }
3867
3868 /* [namespace.qual]
3869    Accepts the NAME to lookup and its qualifying SCOPE.
3870    Returns the name/type pair found into the cxx_binding *RESULT,
3871    or false on error.  */
3872
3873 static bool
3874 qualified_lookup_using_namespace (tree name, tree scope,
3875                                   struct scope_binding *result, int flags)
3876 {
3877   /* Maintain a list of namespaces visited...  */
3878   tree seen = NULL_TREE;
3879   /* ... and a list of namespace yet to see.  */
3880   tree todo = NULL_TREE;
3881   tree todo_maybe = NULL_TREE;
3882   tree usings;
3883   timevar_push (TV_NAME_LOOKUP);
3884   /* Look through namespace aliases.  */
3885   scope = ORIGINAL_NAMESPACE (scope);
3886   while (scope && result->value != error_mark_node)
3887     {
3888       cxx_binding *binding =
3889         cxx_scope_find_binding_for_name (NAMESPACE_LEVEL (scope), name);
3890       seen = tree_cons (scope, NULL_TREE, seen);
3891       if (binding)
3892         ambiguous_decl (name, result, binding, flags);
3893
3894       /* Consider strong using directives always, and non-strong ones
3895          if we haven't found a binding yet.  ??? Shouldn't we consider
3896          non-strong ones if the initial RESULT is non-NULL, but the
3897          binding in the given namespace is?  */
3898       for (usings = DECL_NAMESPACE_USING (scope); usings;
3899            usings = TREE_CHAIN (usings))
3900         /* If this was a real directive, and we have not seen it.  */
3901         if (!TREE_INDIRECT_USING (usings))
3902           {
3903             /* Try to avoid queuing the same namespace more than once,
3904                the exception being when a namespace was already
3905                enqueued for todo_maybe and then a strong using is
3906                found for it.  We could try to remove it from
3907                todo_maybe, but it's probably not worth the effort.  */
3908             if (is_associated_namespace (scope, TREE_PURPOSE (usings))
3909                 && !purpose_member (TREE_PURPOSE (usings), seen)
3910                 && !purpose_member (TREE_PURPOSE (usings), todo))
3911               todo = tree_cons (TREE_PURPOSE (usings), NULL_TREE, todo);
3912             else if ((!result->value && !result->type)
3913                      && !purpose_member (TREE_PURPOSE (usings), seen)
3914                      && !purpose_member (TREE_PURPOSE (usings), todo)
3915                      && !purpose_member (TREE_PURPOSE (usings), todo_maybe))
3916               todo_maybe = tree_cons (TREE_PURPOSE (usings), NULL_TREE,
3917                                       todo_maybe);
3918           }
3919       if (todo)
3920         {
3921           scope = TREE_PURPOSE (todo);
3922           todo = TREE_CHAIN (todo);
3923         }
3924       else if (todo_maybe
3925                && (!result->value && !result->type))
3926         {
3927           scope = TREE_PURPOSE (todo_maybe);
3928           todo = TREE_CHAIN (todo_maybe);
3929           todo_maybe = NULL_TREE;
3930         }
3931       else
3932         scope = NULL_TREE; /* If there never was a todo list.  */
3933     }
3934   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, result->value != error_mark_node);
3935 }
3936
3937 /* Look up NAME in the current binding level and its superiors in the
3938    namespace of variables, functions and typedefs.  Return a ..._DECL
3939    node of some kind representing its definition if there is only one
3940    such declaration, or return a TREE_LIST with all the overloaded
3941    definitions if there are many, or return 0 if it is undefined.
3942
3943    If PREFER_TYPE is > 0, we prefer TYPE_DECLs or namespaces.
3944    If PREFER_TYPE is > 1, we reject non-type decls (e.g. namespaces).
3945    Otherwise we prefer non-TYPE_DECLs.
3946
3947    If NONCLASS is nonzero, we don't look for the NAME in class scope,
3948    using IDENTIFIER_CLASS_VALUE.  */
3949
3950 tree
3951 lookup_name_real (tree name, int prefer_type, int nonclass, 
3952                   int namespaces_only, int flags)
3953 {
3954   cxx_binding *iter;
3955   tree val = NULL_TREE;
3956
3957   timevar_push (TV_NAME_LOOKUP);
3958   /* Conversion operators are handled specially because ordinary
3959      unqualified name lookup will not find template conversion
3960      operators.  */
3961   if (IDENTIFIER_TYPENAME_P (name)) 
3962     {
3963       struct cp_binding_level *level;
3964
3965       for (level = current_binding_level; 
3966            level && level->kind != sk_namespace;
3967            level = level->level_chain)
3968         {
3969           tree class_type;
3970           tree operators;
3971           
3972           /* A conversion operator can only be declared in a class 
3973              scope.  */
3974           if (level->kind != sk_class)
3975             continue;
3976           
3977           /* Lookup the conversion operator in the class.  */
3978           class_type = level->this_entity;
3979           operators = lookup_fnfields (class_type, name, /*protect=*/0);
3980           if (operators)
3981             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, operators);
3982         }
3983
3984       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
3985     }
3986
3987   flags |= lookup_flags (prefer_type, namespaces_only);
3988
3989   /* First, look in non-namespace scopes.  */
3990
3991   if (current_class_type == NULL_TREE)
3992     nonclass = 1;
3993
3994   for (iter = IDENTIFIER_BINDING (name); iter; iter = iter->previous)
3995     {
3996       tree binding;
3997
3998       if (!LOCAL_BINDING_P (iter) && nonclass)
3999         /* We're not looking for class-scoped bindings, so keep going.  */
4000         continue;
4001
4002       /* If this is the kind of thing we're looking for, we're done.  */
4003       if (qualify_lookup (iter->value, flags))
4004         binding = iter->value;
4005       else if ((flags & LOOKUP_PREFER_TYPES)
4006                && qualify_lookup (iter->type, flags))
4007         binding = iter->type;
4008       else
4009         binding = NULL_TREE;
4010
4011       if (binding)
4012         {
4013           val = binding;
4014           break;
4015         }
4016     }
4017
4018   /* Now lookup in namespace scopes.  */
4019   if (!val)
4020     {
4021       tree t = unqualified_namespace_lookup (name, flags);
4022       if (t)
4023         val = t;
4024     }
4025
4026   if (val)
4027     {
4028       /* If we have a single function from a using decl, pull it out.  */
4029       if (TREE_CODE (val) == OVERLOAD && ! really_overloaded_fn (val))
4030         val = OVL_FUNCTION (val);
4031     }
4032
4033   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, val);
4034 }
4035
4036 tree
4037 lookup_name_nonclass (tree name)
4038 {
4039   return lookup_name_real (name, 0, 1, 0, LOOKUP_COMPLAIN);
4040 }
4041
4042 tree
4043 lookup_function_nonclass (tree name, tree args)
4044 {
4045   return lookup_arg_dependent (name, lookup_name_nonclass (name), args);
4046 }
4047
4048 tree
4049 lookup_name (tree name, int prefer_type)
4050 {
4051   return lookup_name_real (name, prefer_type, 0, 0, LOOKUP_COMPLAIN);
4052 }
4053
4054 /* Similar to `lookup_name' but look only in the innermost non-class
4055    binding level.  */
4056
4057 static tree
4058 lookup_name_current_level (tree name)
4059 {
4060   struct cp_binding_level *b;
4061   tree t = NULL_TREE;
4062
4063   timevar_push (TV_NAME_LOOKUP);
4064   b = innermost_nonclass_level ();
4065
4066   if (b->kind == sk_namespace)
4067     {
4068       t = IDENTIFIER_NAMESPACE_VALUE (name);
4069
4070       /* extern "C" function() */
4071       if (t != NULL_TREE && TREE_CODE (t) == TREE_LIST)
4072         t = TREE_VALUE (t);
4073     }
4074   else if (IDENTIFIER_BINDING (name)
4075            && LOCAL_BINDING_P (IDENTIFIER_BINDING (name)))
4076     {
4077       while (1)
4078         {
4079           if (IDENTIFIER_BINDING (name)->scope == b)
4080             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, IDENTIFIER_VALUE (name));
4081
4082           if (b->kind == sk_cleanup)
4083             b = b->level_chain;
4084           else
4085             break;
4086         }
4087     }
4088
4089   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
4090 }
4091
4092 /* Like lookup_name_current_level, but for types.  */
4093
4094 static tree
4095 lookup_type_current_level (tree name)
4096 {
4097   tree t = NULL_TREE;
4098
4099   timevar_push (TV_NAME_LOOKUP);
4100   my_friendly_assert (current_binding_level->kind != sk_namespace, 
4101                       980716);
4102
4103   if (REAL_IDENTIFIER_TYPE_VALUE (name) != NULL_TREE
4104       && REAL_IDENTIFIER_TYPE_VALUE (name) != global_type_node)
4105     {
4106       struct cp_binding_level *b = current_binding_level;
4107       while (1)
4108         {
4109           if (purpose_member (name, b->type_shadowed))
4110             POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP,
4111                                     REAL_IDENTIFIER_TYPE_VALUE (name));
4112           if (b->kind == sk_cleanup)
4113             b = b->level_chain;
4114           else
4115             break;
4116         }
4117     }
4118
4119   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
4120 }
4121
4122 /* [basic.lookup.koenig] */
4123 /* A nonzero return value in the functions below indicates an error.  */
4124
4125 struct arg_lookup
4126 {
4127   tree name;
4128   tree namespaces;
4129   tree classes;
4130   tree functions;
4131 };
4132
4133 static bool arg_assoc (struct arg_lookup*, tree);
4134 static bool arg_assoc_args (struct arg_lookup*, tree);
4135 static bool arg_assoc_type (struct arg_lookup*, tree);
4136 static bool add_function (struct arg_lookup *, tree);
4137 static bool arg_assoc_namespace (struct arg_lookup *, tree);
4138 static bool arg_assoc_class (struct arg_lookup *, tree);
4139 static bool arg_assoc_template_arg (struct arg_lookup*, tree);
4140
4141 /* Add a function to the lookup structure.
4142    Returns true on error.  */
4143
4144 static bool
4145 add_function (struct arg_lookup *k, tree fn)
4146 {
4147   /* We used to check here to see if the function was already in the list,
4148      but that's O(n^2), which is just too expensive for function lookup.
4149      Now we deal with the occasional duplicate in joust.  In doing this, we
4150      assume that the number of duplicates will be small compared to the
4151      total number of functions being compared, which should usually be the
4152      case.  */
4153
4154   /* We must find only functions, or exactly one non-function.  */
4155   if (!k->functions) 
4156     k->functions = fn;
4157   else if (fn == k->functions)
4158     ;
4159   else if (is_overloaded_fn (k->functions) && is_overloaded_fn (fn))
4160     k->functions = build_overload (fn, k->functions);
4161   else
4162     {
4163       tree f1 = OVL_CURRENT (k->functions);
4164       tree f2 = fn;
4165       if (is_overloaded_fn (f1))
4166         {
4167           fn = f1; f1 = f2; f2 = fn;
4168         }
4169       cp_error_at ("`%D' is not a function,", f1);
4170       cp_error_at ("  conflict with `%D'", f2);
4171       error ("  in call to `%D'", k->name);
4172       return true;
4173     }
4174
4175   return false;
4176 }
4177
4178 /* Returns true iff CURRENT has declared itself to be an associated
4179    namespace of SCOPE via a strong using-directive (or transitive chain
4180    thereof).  Both are namespaces.  */
4181
4182 bool
4183 is_associated_namespace (tree current, tree scope)
4184 {
4185   tree seen = NULL_TREE;
4186   tree todo = NULL_TREE;
4187   tree t;
4188   while (1)
4189     {
4190       if (scope == current)
4191         return true;
4192       seen = tree_cons (scope, NULL_TREE, seen);
4193       for (t = DECL_NAMESPACE_ASSOCIATIONS (scope); t; t = TREE_CHAIN (t))
4194         if (!purpose_member (TREE_PURPOSE (t), seen))
4195           todo = tree_cons (TREE_PURPOSE (t), NULL_TREE, todo);
4196       if (todo)
4197         {
4198           scope = TREE_PURPOSE (todo);
4199           todo = TREE_CHAIN (todo);
4200         }
4201       else
4202         return false;
4203     }
4204 }
4205
4206 /* Add functions of a namespace to the lookup structure.
4207    Returns true on error.  */
4208
4209 static bool
4210 arg_assoc_namespace (struct arg_lookup *k, tree scope)
4211 {
4212   tree value;
4213
4214   if (purpose_member (scope, k->namespaces))
4215     return 0;
4216   k->namespaces = tree_cons (scope, NULL_TREE, k->namespaces);
4217
4218   /* Check out our super-users.  */
4219   for (value = DECL_NAMESPACE_ASSOCIATIONS (scope); value;
4220        value = TREE_CHAIN (value))
4221     if (arg_assoc_namespace (k, TREE_PURPOSE (value)))
4222       return true;
4223   
4224   value = namespace_binding (k->name, scope);
4225   if (!value)
4226     return false;
4227
4228   for (; value; value = OVL_NEXT (value))
4229     if (add_function (k, OVL_CURRENT (value)))
4230       return true;
4231   
4232   return false;
4233 }
4234
4235 /* Adds everything associated with a template argument to the lookup
4236    structure.  Returns true on error.  */
4237
4238 static bool
4239 arg_assoc_template_arg (struct arg_lookup *k, tree arg)
4240 {
4241   /* [basic.lookup.koenig]
4242
4243      If T is a template-id, its associated namespaces and classes are
4244      ... the namespaces and classes associated with the types of the
4245      template arguments provided for template type parameters
4246      (excluding template template parameters); the namespaces in which
4247      any template template arguments are defined; and the classes in
4248      which any member templates used as template template arguments
4249      are defined.  [Note: non-type template arguments do not
4250      contribute to the set of associated namespaces.  ]  */
4251
4252   /* Consider first template template arguments.  */
4253   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4254       || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
4255     return false;
4256   else if (TREE_CODE (arg) == TEMPLATE_DECL)
4257     {
4258       tree ctx = CP_DECL_CONTEXT (arg);
4259
4260       /* It's not a member template.  */
4261       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4262         return arg_assoc_namespace (k, ctx);
4263       /* Otherwise, it must be member template.  */
4264       else 
4265         return arg_assoc_class (k, ctx);
4266     }
4267   /* It's not a template template argument, but it is a type template
4268      argument.  */
4269   else if (TYPE_P (arg))
4270     return arg_assoc_type (k, arg);
4271   /* It's a non-type template argument.  */
4272   else
4273     return false;
4274 }
4275
4276 /* Adds everything associated with class to the lookup structure.
4277    Returns true on error.  */
4278
4279 static bool
4280 arg_assoc_class (struct arg_lookup *k, tree type)
4281 {
4282   tree list, friends, context;
4283   int i;
4284   
4285   /* Backend build structures, such as __builtin_va_list, aren't
4286      affected by all this.  */
4287   if (!CLASS_TYPE_P (type))
4288     return false;
4289
4290   if (purpose_member (type, k->classes))
4291     return false;
4292   k->classes = tree_cons (type, NULL_TREE, k->classes);
4293   
4294   context = decl_namespace (TYPE_MAIN_DECL (type));
4295   if (arg_assoc_namespace (k, context))
4296     return true;
4297   
4298   /* Process baseclasses.  */
4299   for (i = 0; i < CLASSTYPE_N_BASECLASSES (type); i++)
4300     if (arg_assoc_class (k, TYPE_BINFO_BASETYPE (type, i)))
4301       return true;
4302   
4303   /* Process friends.  */
4304   for (list = DECL_FRIENDLIST (TYPE_MAIN_DECL (type)); list; 
4305        list = TREE_CHAIN (list))
4306     if (k->name == FRIEND_NAME (list))
4307       for (friends = FRIEND_DECLS (list); friends; 
4308            friends = TREE_CHAIN (friends))
4309         {
4310           tree fn = TREE_VALUE (friends);
4311
4312           /* Only interested in global functions with potentially hidden
4313              (i.e. unqualified) declarations.  */
4314           if (CP_DECL_CONTEXT (fn) != context)
4315             continue;
4316           /* Template specializations are never found by name lookup.
4317              (Templates themselves can be found, but not template
4318              specializations.)  */
4319           if (TREE_CODE (fn) == FUNCTION_DECL && DECL_USE_TEMPLATE (fn))
4320             continue;
4321           if (add_function (k, fn))
4322             return true;
4323         }
4324
4325   /* Process template arguments.  */
4326   if (CLASSTYPE_TEMPLATE_INFO (type) 
4327       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
4328     {
4329       list = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
4330       for (i = 0; i < TREE_VEC_LENGTH (list); ++i) 
4331         arg_assoc_template_arg (k, TREE_VEC_ELT (list, i));
4332     }
4333
4334   return false;
4335 }
4336
4337 /* Adds everything associated with a given type.
4338    Returns 1 on error.  */
4339
4340 static bool
4341 arg_assoc_type (struct arg_lookup *k, tree type)
4342 {
4343   /* As we do not get the type of non-type dependent expressions
4344      right, we can end up with such things without a type.  */
4345   if (!type)
4346     return false;
4347
4348   if (TYPE_PTRMEM_P (type))
4349     {
4350       /* Pointer to member: associate class type and value type.  */
4351       if (arg_assoc_type (k, TYPE_PTRMEM_CLASS_TYPE (type)))
4352         return true;
4353       return arg_assoc_type (k, TYPE_PTRMEM_POINTED_TO_TYPE (type));
4354     }
4355   else switch (TREE_CODE (type))
4356     {
4357     case ERROR_MARK:
4358       return false;
4359     case VOID_TYPE:
4360     case INTEGER_TYPE:
4361     case REAL_TYPE:
4362     case COMPLEX_TYPE:
4363     case VECTOR_TYPE:
4364     case CHAR_TYPE:
4365     case BOOLEAN_TYPE:
4366       return false;
4367     case RECORD_TYPE:
4368       if (TYPE_PTRMEMFUNC_P (type))
4369         return arg_assoc_type (k, TYPE_PTRMEMFUNC_FN_TYPE (type));
4370       return arg_assoc_class (k, type);
4371     case POINTER_TYPE:
4372     case REFERENCE_TYPE:
4373     case ARRAY_TYPE:
4374       return arg_assoc_type (k, TREE_TYPE (type));
4375     case UNION_TYPE:
4376     case ENUMERAL_TYPE:
4377       return arg_assoc_namespace (k, decl_namespace (TYPE_MAIN_DECL (type)));
4378     case METHOD_TYPE:
4379       /* The basetype is referenced in the first arg type, so just
4380          fall through.  */
4381     case FUNCTION_TYPE:
4382       /* Associate the parameter types.  */
4383       if (arg_assoc_args (k, TYPE_ARG_TYPES (type)))
4384         return true;
4385       /* Associate the return type.  */
4386       return arg_assoc_type (k, TREE_TYPE (type));
4387     case TEMPLATE_TYPE_PARM:
4388     case BOUND_TEMPLATE_TEMPLATE_PARM:
4389       return false;
4390     case TYPENAME_TYPE:
4391       return false;
4392     case LANG_TYPE:
4393       if (type == unknown_type_node)
4394         return false;
4395       /* else fall through */
4396     default:
4397       abort ();
4398     }
4399   return false;
4400 }
4401
4402 /* Adds everything associated with arguments.  Returns true on error.  */
4403
4404 static bool
4405 arg_assoc_args (struct arg_lookup *k, tree args)
4406 {
4407   for (; args; args = TREE_CHAIN (args))
4408     if (arg_assoc (k, TREE_VALUE (args)))
4409       return true;
4410   return false;
4411 }
4412
4413 /* Adds everything associated with a given tree_node.  Returns 1 on error.  */
4414
4415 static bool
4416 arg_assoc (struct arg_lookup *k, tree n)
4417 {
4418   if (n == error_mark_node)
4419     return false;
4420
4421   if (TYPE_P (n))
4422     return arg_assoc_type (k, n);
4423
4424   if (! type_unknown_p (n))
4425     return arg_assoc_type (k, TREE_TYPE (n));
4426
4427   if (TREE_CODE (n) == ADDR_EXPR)
4428     n = TREE_OPERAND (n, 0);
4429   if (TREE_CODE (n) == COMPONENT_REF)
4430     n = TREE_OPERAND (n, 1);
4431   if (TREE_CODE (n) == OFFSET_REF)
4432     n = TREE_OPERAND (n, 1);
4433   while (TREE_CODE (n) == TREE_LIST)
4434     n = TREE_VALUE (n);
4435   if (TREE_CODE (n) == BASELINK)
4436     n = BASELINK_FUNCTIONS (n);
4437
4438   if (TREE_CODE (n) == FUNCTION_DECL)
4439     return arg_assoc_type (k, TREE_TYPE (n));
4440   if (TREE_CODE (n) == TEMPLATE_ID_EXPR)
4441     {
4442       /* [basic.lookup.koenig]
4443
4444          If T is a template-id, its associated namespaces and classes
4445          are the namespace in which the template is defined; for
4446          member templates, the member template's class...  */
4447       tree template = TREE_OPERAND (n, 0);
4448       tree args = TREE_OPERAND (n, 1);
4449       tree ctx;
4450       int ix;
4451
4452       if (TREE_CODE (template) == COMPONENT_REF)
4453         template = TREE_OPERAND (template, 1);
4454       
4455       /* First, the template.  There may actually be more than one if
4456          this is an overloaded function template.  But, in that case,
4457          we only need the first; all the functions will be in the same
4458          namespace.  */
4459       template = OVL_CURRENT (template);
4460
4461       ctx = CP_DECL_CONTEXT (template);
4462        
4463       if (TREE_CODE (ctx) == NAMESPACE_DECL)
4464         {
4465           if (arg_assoc_namespace (k, ctx) == 1)
4466             return true;
4467         }
4468       /* It must be a member template.  */
4469       else if (arg_assoc_class (k, ctx) == 1)
4470         return true;
4471
4472       /* Now the arguments.  */
4473       for (ix = TREE_VEC_LENGTH (args); ix--;)
4474         if (arg_assoc_template_arg (k, TREE_VEC_ELT (args, ix)) == 1)
4475           return true;
4476     }
4477   else if (TREE_CODE (n) == OVERLOAD)
4478     {
4479       for (; n; n = OVL_CHAIN (n))
4480         if (arg_assoc_type (k, TREE_TYPE (OVL_FUNCTION (n))))
4481           return true;
4482     }
4483
4484   return false;
4485 }
4486
4487 /* Performs Koenig lookup depending on arguments, where fns
4488    are the functions found in normal lookup.  */
4489
4490 tree
4491 lookup_arg_dependent (tree name, tree fns, tree args)
4492 {
4493   struct arg_lookup k;
4494   tree fn = NULL_TREE;
4495
4496   timevar_push (TV_NAME_LOOKUP);
4497   k.name = name;
4498   k.functions = fns;
4499   k.classes = NULL_TREE;
4500
4501   /* We've already looked at some namespaces during normal unqualified
4502      lookup -- but we don't know exactly which ones.  If the functions
4503      we found were brought into the current namespace via a using
4504      declaration, we have not really checked the namespace from which
4505      they came.  Therefore, we check all namespaces here -- unless the
4506      function we have is from the current namespace.  Even then, we
4507      must check all namespaces if the function is a local
4508      declaration; any other declarations present at namespace scope
4509      should be visible during argument-dependent lookup.  */
4510   if (fns)
4511     fn = OVL_CURRENT (fns);
4512   if (fn && TREE_CODE (fn) == FUNCTION_DECL 
4513       && (CP_DECL_CONTEXT (fn) != current_decl_namespace ()
4514           || DECL_LOCAL_FUNCTION_P (fn)))
4515     k.namespaces = NULL_TREE;
4516   else
4517     /* Setting NAMESPACES is purely an optimization; it prevents
4518        adding functions which are already in FNS.  Adding them would
4519        be safe -- "joust" will eliminate the duplicates -- but
4520        wasteful.  */
4521     k.namespaces = build_tree_list (current_decl_namespace (), NULL_TREE);
4522
4523   arg_assoc_args (&k, args);
4524   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, k.functions);
4525 }
4526
4527 /* Add namespace to using_directives. Return NULL_TREE if nothing was
4528    changed (i.e. there was already a directive), or the fresh
4529    TREE_LIST otherwise.  */
4530
4531 static tree
4532 push_using_directive (tree used)
4533 {
4534   tree ud = current_binding_level->using_directives;
4535   tree iter, ancestor;
4536
4537   timevar_push (TV_NAME_LOOKUP);
4538   /* Check if we already have this.  */
4539   if (purpose_member (used, ud) != NULL_TREE)
4540     POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, NULL_TREE);
4541
4542   ancestor = namespace_ancestor (current_decl_namespace (), used);
4543   ud = current_binding_level->using_directives;
4544   ud = tree_cons (used, ancestor, ud);
4545   current_binding_level->using_directives = ud;
4546
4547   /* Recursively add all namespaces used.  */
4548   for (iter = DECL_NAMESPACE_USING (used); iter; iter = TREE_CHAIN (iter))
4549     push_using_directive (TREE_PURPOSE (iter));
4550
4551   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, ud);
4552 }
4553
4554 /* The type TYPE is being declared.  If it is a class template, or a
4555    specialization of a class template, do any processing required and
4556    perform error-checking.  If IS_FRIEND is nonzero, this TYPE is
4557    being declared a friend.  B is the binding level at which this TYPE
4558    should be bound.
4559
4560    Returns the TYPE_DECL for TYPE, which may have been altered by this
4561    processing.  */
4562
4563 static tree
4564 maybe_process_template_type_declaration (tree type, int globalize,
4565                                          cxx_scope *b)
4566 {
4567   tree decl = TYPE_NAME (type);
4568
4569   if (processing_template_parmlist)
4570     /* You can't declare a new template type in a template parameter
4571        list.  But, you can declare a non-template type:
4572
4573          template <class A*> struct S;
4574
4575        is a forward-declaration of `A'.  */
4576     ;
4577   else
4578     {
4579       maybe_check_template_type (type);
4580
4581       my_friendly_assert (IS_AGGR_TYPE (type)
4582                           || TREE_CODE (type) == ENUMERAL_TYPE, 0);
4583
4584
4585       if (processing_template_decl)
4586         {
4587           /* This may change after the call to
4588              push_template_decl_real, but we want the original value.  */
4589           tree name = DECL_NAME (decl);
4590
4591           decl = push_template_decl_real (decl, globalize);
4592           /* If the current binding level is the binding level for the
4593              template parameters (see the comment in
4594              begin_template_parm_list) and the enclosing level is a class
4595              scope, and we're not looking at a friend, push the
4596              declaration of the member class into the class scope.  In the
4597              friend case, push_template_decl will already have put the
4598              friend into global scope, if appropriate.  */
4599           if (TREE_CODE (type) != ENUMERAL_TYPE
4600               && !globalize && b->kind == sk_template_parms
4601               && b->level_chain->kind == sk_class)
4602             {
4603               finish_member_declaration (CLASSTYPE_TI_TEMPLATE (type));
4604               /* Put this UDT in the table of UDTs for the class, since
4605                  that won't happen below because B is not the class
4606                  binding level, but is instead the pseudo-global level.  */
4607               if (b->level_chain->type_decls == NULL)
4608                 b->level_chain->type_decls =
4609                   binding_table_new (SCOPE_DEFAULT_HT_SIZE);
4610               binding_table_insert (b->level_chain->type_decls, name, type);
4611               if (!COMPLETE_TYPE_P (current_class_type))
4612                 {
4613                   maybe_add_class_template_decl_list (current_class_type,
4614                                                       type, /*friend_p=*/0);
4615                   CLASSTYPE_NESTED_UTDS (current_class_type) =
4616                     b->level_chain->type_decls;
4617                 }
4618             }
4619         }
4620     }
4621
4622   return decl;
4623 }
4624
4625 /* Push a tag name NAME for struct/class/union/enum type TYPE.
4626    Normally put it into the inner-most non-sk_cleanup scope,
4627    but if GLOBALIZE is true, put it in the inner-most non-class scope.
4628    The latter is needed for implicit declarations.  */
4629
4630 void
4631 pushtag (tree name, tree type, int globalize)
4632 {
4633   struct cp_binding_level *b;
4634
4635   timevar_push (TV_NAME_LOOKUP);
4636   b = current_binding_level;
4637   while (b->kind == sk_cleanup
4638          || (b->kind == sk_class
4639              && (globalize
4640                  /* We may be defining a new type in the initializer
4641                     of a static member variable. We allow this when
4642                     not pedantic, and it is particularly useful for
4643                     type punning via an anonymous union.  */
4644                  || COMPLETE_TYPE_P (b->this_entity))))
4645     b = b->level_chain;
4646
4647   if (b->type_decls == NULL)
4648     b->type_decls = binding_table_new (SCOPE_DEFAULT_HT_SIZE);
4649   binding_table_insert (b->type_decls, name, type);
4650
4651   if (name)
4652     {
4653       /* Do C++ gratuitous typedefing.  */
4654       if (IDENTIFIER_TYPE_VALUE (name) != type)
4655         {
4656           tree d = NULL_TREE;
4657           int in_class = 0;
4658           tree context = TYPE_CONTEXT (type);
4659
4660           if (! context)
4661             {
4662               tree cs = current_scope ();
4663
4664               if (! globalize)
4665                 context = cs;
4666               else if (cs != NULL_TREE && TYPE_P (cs))
4667                 /* When declaring a friend class of a local class, we want
4668                    to inject the newly named class into the scope
4669                    containing the local class, not the namespace scope.  */
4670                 context = decl_function_context (get_type_decl (cs));
4671             }
4672           if (!context)
4673             context = current_namespace;
4674
4675           if (b->kind == sk_class
4676               || (b->kind == sk_template_parms 
4677                   && b->level_chain->kind == sk_class))
4678             in_class = 1;
4679
4680           if (current_lang_name == lang_name_java)
4681             TYPE_FOR_JAVA (type) = 1;
4682
4683           d = create_implicit_typedef (name, type);
4684           DECL_CONTEXT (d) = FROB_CONTEXT (context);
4685           if (! in_class)
4686             set_identifier_type_value_with_scope (name, d, b);
4687
4688           d = maybe_process_template_type_declaration (type,
4689                                                        globalize, b);
4690
4691           if (b->kind == sk_class)
4692             {
4693               if (!PROCESSING_REAL_TEMPLATE_DECL_P ())
4694                 /* Put this TYPE_DECL on the TYPE_FIELDS list for the
4695                    class.  But if it's a member template class, we
4696                    want the TEMPLATE_DECL, not the TYPE_DECL, so this
4697                    is done later.  */
4698                 finish_member_declaration (d);
4699               else
4700                 pushdecl_class_level (d);
4701             }
4702           else
4703             d = pushdecl_with_scope (d, b);
4704
4705           /* FIXME what if it gets a name from typedef?  */
4706           if (ANON_AGGRNAME_P (name))
4707             DECL_IGNORED_P (d) = 1;
4708
4709           TYPE_CONTEXT (type) = DECL_CONTEXT (d);
4710
4711           /* If this is a local class, keep track of it.  We need this
4712              information for name-mangling, and so that it is possible to find
4713              all function definitions in a translation unit in a convenient
4714              way.  (It's otherwise tricky to find a member function definition
4715              it's only pointed to from within a local class.)  */
4716           if (TYPE_CONTEXT (type)
4717               && TREE_CODE (TYPE_CONTEXT (type)) == FUNCTION_DECL
4718               && !processing_template_decl)
4719             VARRAY_PUSH_TREE (local_classes, type);
4720         }
4721       if (b->kind == sk_class
4722           && !COMPLETE_TYPE_P (current_class_type))
4723         {
4724           maybe_add_class_template_decl_list (current_class_type,
4725                                               type, /*friend_p=*/0);
4726           CLASSTYPE_NESTED_UTDS (current_class_type) = b->type_decls;
4727         }
4728     }
4729
4730   if (TREE_CODE (TYPE_NAME (type)) == TYPE_DECL)
4731     /* Use the canonical TYPE_DECL for this node.  */
4732     TYPE_STUB_DECL (type) = TYPE_NAME (type);
4733   else
4734     {
4735       /* Create a fake NULL-named TYPE_DECL node whose TREE_TYPE
4736          will be the tagged type we just added to the current
4737          binding level.  This fake NULL-named TYPE_DECL node helps
4738          dwarfout.c to know when it needs to output a
4739          representation of a tagged type, and it also gives us a
4740          convenient place to record the "scope start" address for
4741          the tagged type.  */
4742
4743       tree d = build_decl (TYPE_DECL, NULL_TREE, type);
4744       TYPE_STUB_DECL (type) = pushdecl_with_scope (d, b);
4745     }
4746   timevar_pop (TV_NAME_LOOKUP);
4747 }
4748 \f
4749 /* Allocate storage for saving a C++ binding.  */
4750 #define cxx_saved_binding_make() \
4751   (ggc_alloc (sizeof (cxx_saved_binding)))
4752
4753 struct cxx_saved_binding GTY(())
4754 {
4755   /* Link that chains saved C++ bindings for a given name into a stack.  */
4756   cxx_saved_binding *previous;
4757   /* The name of the current binding.  */
4758   tree identifier;
4759   /* The binding we're saving.  */
4760   cxx_binding *binding;
4761   tree class_value;
4762   tree real_type_value;
4763 };
4764
4765 /* Subroutines for reverting temporarily to top-level for instantiation
4766    of templates and such.  We actually need to clear out the class- and
4767    local-value slots of all identifiers, so that only the global values
4768    are at all visible.  Simply setting current_binding_level to the global
4769    scope isn't enough, because more binding levels may be pushed.  */
4770 struct saved_scope *scope_chain;
4771
4772 static cxx_saved_binding *
4773 store_bindings (tree names, cxx_saved_binding *old_bindings)
4774 {
4775   tree t;
4776   cxx_saved_binding *search_bindings = old_bindings;
4777
4778   timevar_push (TV_NAME_LOOKUP);
4779   for (t = names; t; t = TREE_CHAIN (t))
4780     {
4781       tree id;
4782       cxx_saved_binding *saved;
4783       cxx_saved_binding *t1;
4784
4785       if (TREE_CODE (t) == TREE_LIST)
4786         id = TREE_PURPOSE (t);
4787       else
4788         id = DECL_NAME (t);
4789
4790       if (!id
4791           /* Note that we may have an IDENTIFIER_CLASS_VALUE even when
4792              we have no IDENTIFIER_BINDING if we have left the class
4793              scope, but cached the class-level declarations.  */
4794           || !(IDENTIFIER_BINDING (id) || IDENTIFIER_CLASS_VALUE (id)))
4795         continue;
4796
4797       for (t1 = search_bindings; t1; t1 = t1->previous)
4798         if (t1->identifier == id)
4799           goto skip_it;
4800
4801       my_friendly_assert (TREE_CODE (id) == IDENTIFIER_NODE, 135);
4802       saved = cxx_saved_binding_make ();
4803       saved->previous = old_bindings;
4804       saved->identifier = id;
4805       saved->binding = IDENTIFIER_BINDING (id);
4806       saved->class_value = IDENTIFIER_CLASS_VALUE (id);;
4807       saved->real_type_value = REAL_IDENTIFIER_TYPE_VALUE (id);
4808       IDENTIFIER_BINDING (id) = NULL;
4809       IDENTIFIER_CLASS_VALUE (id) = NULL_TREE;
4810       old_bindings = saved;
4811     skip_it:
4812       ;
4813     }
4814   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, old_bindings);
4815 }
4816
4817 void
4818 push_to_top_level (void)
4819 {
4820   struct saved_scope *s;
4821   struct cp_binding_level *b;
4822   cxx_saved_binding *old_bindings;
4823   int need_pop;
4824
4825   timevar_push (TV_NAME_LOOKUP);
4826   s = ggc_alloc_cleared (sizeof (struct saved_scope));
4827
4828   b = scope_chain ? current_binding_level : 0;
4829
4830   /* If we're in the middle of some function, save our state.  */
4831   if (cfun)
4832     {
4833       need_pop = 1;
4834       push_function_context_to (NULL_TREE);
4835     }
4836   else
4837     need_pop = 0;
4838
4839   old_bindings = NULL;
4840   if (scope_chain && previous_class_type)
4841     old_bindings = store_bindings (previous_class_values, old_bindings);
4842
4843   /* Have to include the global scope, because class-scope decls
4844      aren't listed anywhere useful.  */
4845   for (; b; b = b->level_chain)
4846     {
4847       tree t;
4848
4849       /* Template IDs are inserted into the global level. If they were
4850          inserted into namespace level, finish_file wouldn't find them
4851          when doing pending instantiations. Therefore, don't stop at
4852          namespace level, but continue until :: .  */
4853       if (global_scope_p (b))
4854         break;
4855
4856       old_bindings = store_bindings (b->names, old_bindings);
4857       /* We also need to check class_shadowed to save class-level type
4858          bindings, since pushclass doesn't fill in b->names.  */
4859       if (b->kind == sk_class)
4860         old_bindings = store_bindings (b->class_shadowed, old_bindings);
4861
4862       /* Unwind type-value slots back to top level.  */
4863       for (t = b->type_shadowed; t; t = TREE_CHAIN (t))
4864         SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (t), TREE_VALUE (t));
4865     }
4866   s->prev = scope_chain;
4867   s->old_bindings = old_bindings;
4868   s->bindings = b;
4869   s->need_pop_function_context = need_pop;
4870   s->function_decl = current_function_decl;
4871
4872   scope_chain = s;
4873   current_function_decl = NULL_TREE;
4874   VARRAY_TREE_INIT (current_lang_base, 10, "current_lang_base");
4875   current_lang_name = lang_name_cplusplus;
4876   current_namespace = global_namespace;
4877   timevar_pop (TV_NAME_LOOKUP);
4878 }
4879
4880 void
4881 pop_from_top_level (void)
4882 {
4883   struct saved_scope *s = scope_chain;
4884   cxx_saved_binding *saved;
4885
4886   timevar_push (TV_NAME_LOOKUP); 
4887   /* Clear out class-level bindings cache.  */
4888   if (previous_class_type)
4889     invalidate_class_lookup_cache ();
4890
4891   current_lang_base = 0;
4892
4893   scope_chain = s->prev;
4894   for (saved = s->old_bindings; saved; saved = saved->previous)
4895     {
4896       tree id = saved->identifier;
4897
4898       IDENTIFIER_BINDING (id) = saved->binding;
4899       IDENTIFIER_CLASS_VALUE (id) = saved->class_value;
4900       SET_IDENTIFIER_TYPE_VALUE (id, saved->real_type_value);
4901     }
4902
4903   /* If we were in the middle of compiling a function, restore our
4904      state.  */
4905   if (s->need_pop_function_context)
4906     pop_function_context_from (NULL_TREE);
4907   current_function_decl = s->function_decl;
4908   timevar_pop (TV_NAME_LOOKUP);
4909 }
4910
4911 /* Pop off extraneous binding levels left over due to syntax errors.
4912
4913    We don't pop past namespaces, as they might be valid.  */
4914
4915 void
4916 pop_everything (void)
4917 {
4918   if (ENABLE_SCOPE_CHECKING)
4919     verbatim ("XXX entering pop_everything ()\n");
4920   while (!toplevel_bindings_p ())
4921     {
4922       if (current_binding_level->kind == sk_class)
4923         pop_nested_class ();
4924       else
4925         poplevel (0, 0, 0);
4926     }
4927   if (ENABLE_SCOPE_CHECKING)
4928     verbatim ("XXX leaving pop_everything ()\n");
4929 }
4930
4931 /* Emit debugging information for using declarations and directives.
4932    If input tree is overloaded fn then emit debug info for all 
4933    candidates.  */
4934
4935 static void
4936 cp_emit_debug_info_for_using (tree t, tree context)
4937 {
4938   /* Ignore this FUNCTION_DECL if it refers to a builtin declaration 
4939      of a builtin function.  */
4940   if (TREE_CODE (t) == FUNCTION_DECL 
4941       && DECL_EXTERNAL (t)
4942       && DECL_BUILT_IN (t))
4943     return;
4944
4945   /* Do not supply context to imported_module_or_decl, if
4946      it is a global namespace.  */
4947   if (context == global_namespace)
4948     context = NULL_TREE;
4949   
4950   if (BASELINK_P (t))
4951     t = BASELINK_FUNCTIONS (t);
4952   
4953   /* FIXME: Handle TEMPLATE_DECLs.  */
4954   for (t = OVL_CURRENT (t); t; t = OVL_NEXT (t))
4955     if (TREE_CODE (t) != TEMPLATE_DECL)
4956       (*debug_hooks->imported_module_or_decl) (t, context);
4957   }
4958
4959 #include "gt-cp-name-lookup.h"