nrelease - fix/improve livecd
[dragonfly.git] / contrib / gcc-8.0 / gcc / cp / name-lookup.c
1 /* Definitions for C++ name lookup routines.
2    Copyright (C) 2003-2018 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 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #define INCLUDE_UNIQUE_PTR
23 #include "system.h"
24 #include "coretypes.h"
25 #include "cp-tree.h"
26 #include "timevar.h"
27 #include "stringpool.h"
28 #include "print-tree.h"
29 #include "attribs.h"
30 #include "debug.h"
31 #include "c-family/c-pragma.h"
32 #include "params.h"
33 #include "gcc-rich-location.h"
34 #include "spellcheck-tree.h"
35 #include "parser.h"
36 #include "c-family/name-hint.h"
37 #include "c-family/known-headers.h"
38 #include "c-family/c-spellcheck.h"
39
40 static cxx_binding *cxx_binding_make (tree value, tree type);
41 static cp_binding_level *innermost_nonclass_level (void);
42 static void set_identifier_type_value_with_scope (tree id, tree decl,
43                                                   cp_binding_level *b);
44 static bool maybe_suggest_missing_std_header (location_t location, tree name);
45
46 /* Create an overload suitable for recording an artificial TYPE_DECL
47    and another decl.  We use this machanism to implement the struct
48    stat hack within a namespace.  It'd be nice to use it everywhere.  */
49
50 #define STAT_HACK_P(N) ((N) && TREE_CODE (N) == OVERLOAD && OVL_LOOKUP_P (N))
51 #define STAT_TYPE(N) TREE_TYPE (N)
52 #define STAT_DECL(N) OVL_FUNCTION (N)
53 #define MAYBE_STAT_DECL(N) (STAT_HACK_P (N) ? STAT_DECL (N) : N)
54 #define MAYBE_STAT_TYPE(N) (STAT_HACK_P (N) ? STAT_TYPE (N) : NULL_TREE)
55
56 /* Create a STAT_HACK node with DECL as the value binding and TYPE as
57    the type binding.  */
58
59 static tree
60 stat_hack (tree decl = NULL_TREE, tree type = NULL_TREE)
61 {
62   tree result = make_node (OVERLOAD);
63
64   /* Mark this as a lookup, so we can tell this is a stat hack.  */
65   OVL_LOOKUP_P (result) = true;
66   STAT_DECL (result) = decl;
67   STAT_TYPE (result) = type;
68   return result;
69 }
70
71 /* Create a local binding level for NAME.  */
72
73 static cxx_binding *
74 create_local_binding (cp_binding_level *level, tree name)
75 {
76   cxx_binding *binding = cxx_binding_make (NULL, NULL);
77
78   INHERITED_VALUE_BINDING_P (binding) = false;
79   LOCAL_BINDING_P (binding) = true;
80   binding->scope = level;
81   binding->previous = IDENTIFIER_BINDING (name);
82
83   IDENTIFIER_BINDING (name) = binding;
84   
85   return binding;
86 }
87
88 /* Find the binding for NAME in namespace NS.  If CREATE_P is true,
89    make an empty binding if there wasn't one.  */
90
91 static tree *
92 find_namespace_slot (tree ns, tree name, bool create_p = false)
93 {
94   tree *slot = DECL_NAMESPACE_BINDINGS (ns)
95     ->find_slot_with_hash (name, name ? IDENTIFIER_HASH_VALUE (name) : 0,
96                            create_p ? INSERT : NO_INSERT);
97   return slot;
98 }
99
100 static tree
101 find_namespace_value (tree ns, tree name)
102 {
103   tree *b = find_namespace_slot (ns, name);
104
105   return b ? MAYBE_STAT_DECL (*b) : NULL_TREE;
106 }
107
108 /* Add DECL to the list of things declared in B.  */
109
110 static void
111 add_decl_to_level (cp_binding_level *b, tree decl)
112 {
113   gcc_assert (b->kind != sk_class);
114
115   /* Make sure we don't create a circular list.  xref_tag can end
116      up pushing the same artificial decl more than once.  We
117      should have already detected that in update_binding.  */
118   gcc_assert (b->names != decl);
119
120   /* We build up the list in reverse order, and reverse it later if
121      necessary.  */
122   TREE_CHAIN (decl) = b->names;
123   b->names = decl;
124
125   /* If appropriate, add decl to separate list of statics.  We
126      include extern variables because they might turn out to be
127      static later.  It's OK for this list to contain a few false
128      positives.  */
129   if (b->kind == sk_namespace
130       && ((VAR_P (decl)
131            && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
132           || (TREE_CODE (decl) == FUNCTION_DECL
133               && (!TREE_PUBLIC (decl)
134                   || decl_anon_ns_mem_p (decl)
135                   || DECL_DECLARED_INLINE_P (decl)))))
136     vec_safe_push (static_decls, decl);
137 }
138
139 /* Find the binding for NAME in the local binding level B.  */
140
141 static cxx_binding *
142 find_local_binding (cp_binding_level *b, tree name)
143 {
144   if (cxx_binding *binding = IDENTIFIER_BINDING (name))
145     for (;; b = b->level_chain)
146       {
147         if (binding->scope == b
148             && !(VAR_P (binding->value)
149                  && DECL_DEAD_FOR_LOCAL (binding->value)))
150           return binding;
151
152         /* Cleanup contours are transparent to the language.  */
153         if (b->kind != sk_cleanup)
154           break;
155       }
156   return NULL;
157 }
158
159 struct name_lookup
160 {
161 public:
162   typedef std::pair<tree, tree> using_pair;
163   typedef vec<using_pair, va_heap, vl_embed> using_queue;
164
165 public:
166   tree name;    /* The identifier being looked for.  */
167   tree value;   /* A (possibly ambiguous) set of things found.  */
168   tree type;    /* A type that has been found.  */
169   int flags;    /* Lookup flags.  */
170   bool deduping; /* Full deduping is needed because using declarations
171                     are in play.  */
172   vec<tree, va_heap, vl_embed> *scopes;
173   name_lookup *previous; /* Previously active lookup.  */
174
175 protected:
176   /* Marked scope stack for outermost name lookup.  */
177   static vec<tree, va_heap, vl_embed> *shared_scopes;
178   /* Currently active lookup.  */
179   static name_lookup *active;
180
181 public:
182   name_lookup (tree n, int f = 0)
183   : name (n), value (NULL_TREE), type (NULL_TREE), flags (f),
184     deduping (false), scopes (NULL), previous (NULL)
185   {
186     preserve_state ();
187   }
188   ~name_lookup ()
189   {
190     restore_state ();
191   }
192
193 private: /* Uncopyable, unmovable, unassignable. I am a rock. */
194   name_lookup (const name_lookup &);
195   name_lookup &operator= (const name_lookup &);
196
197 protected:
198   static bool seen_p (tree scope)
199   {
200     return LOOKUP_SEEN_P (scope);
201   }
202   static bool found_p (tree scope)
203   {
204     return LOOKUP_FOUND_P (scope);
205   }
206   
207   void mark_seen (tree scope); /* Mark and add to scope vector. */
208   static void mark_found (tree scope)
209   {
210     gcc_checking_assert (seen_p (scope));
211     LOOKUP_FOUND_P (scope) = true;
212   }
213   bool see_and_mark (tree scope)
214   {
215     bool ret = seen_p (scope);
216     if (!ret)
217       mark_seen (scope);
218     return ret;
219   }
220   bool find_and_mark (tree scope);
221
222 private:
223   void preserve_state ();
224   void restore_state ();
225
226 private:
227   static tree ambiguous (tree thing, tree current);
228   void add_overload (tree fns);
229   void add_value (tree new_val);
230   void add_type (tree new_type);
231   bool process_binding (tree val_bind, tree type_bind);
232
233   /* Look in only namespace.  */
234   bool search_namespace_only (tree scope);
235   /* Look in namespace and its (recursive) inlines. Ignore using
236      directives.  Return true if something found (inc dups). */
237   bool search_namespace (tree scope);
238   /* Look in the using directives of namespace + inlines using
239      qualified lookup rules.  */
240   bool search_usings (tree scope);
241
242 private:
243   using_queue *queue_namespace (using_queue *queue, int depth, tree scope);
244   using_queue *do_queue_usings (using_queue *queue, int depth,
245                                 vec<tree, va_gc> *usings);
246   using_queue *queue_usings (using_queue *queue, int depth,
247                              vec<tree, va_gc> *usings)
248   {
249     if (usings)
250       queue = do_queue_usings (queue, depth, usings);
251     return queue;
252   }
253
254 private:
255   void add_fns (tree);
256
257   void adl_expr (tree);
258   void adl_type (tree);
259   void adl_template_arg (tree);
260   void adl_class (tree);
261   void adl_bases (tree);
262   void adl_class_only (tree);
263   void adl_namespace (tree);
264   void adl_namespace_only (tree);
265
266 public:
267   /* Search namespace + inlines + maybe usings as qualified lookup.  */
268   bool search_qualified (tree scope, bool usings = true);
269
270   /* Search namespace + inlines + usings as unqualified lookup.  */
271   bool search_unqualified (tree scope, cp_binding_level *);
272
273   /* ADL lookup of ARGS.  */
274   tree search_adl (tree fns, vec<tree, va_gc> *args);
275 };
276
277 /* Scope stack shared by all outermost lookups.  This avoids us
278    allocating and freeing on every single lookup.  */
279 vec<tree, va_heap, vl_embed> *name_lookup::shared_scopes;
280
281 /* Currently active lookup.  */
282 name_lookup *name_lookup::active;
283
284 /* Name lookup is recursive, becase ADL can cause template
285    instatiation.  This is of course a rare event, so we optimize for
286    it not happening.  When we discover an active name-lookup, which
287    must be an ADL lookup,  we need to unmark the marked scopes and also
288    unmark the lookup we might have been accumulating.  */
289
290 void
291 name_lookup::preserve_state ()
292 {
293   previous = active;
294   if (previous)
295     {
296       unsigned length = vec_safe_length (previous->scopes);
297       vec_safe_reserve (previous->scopes, length * 2);
298       for (unsigned ix = length; ix--;)
299         {
300           tree decl = (*previous->scopes)[ix];
301
302           gcc_checking_assert (LOOKUP_SEEN_P (decl));
303           LOOKUP_SEEN_P (decl) = false;
304
305           /* Preserve the FOUND_P state on the interrupted lookup's
306              stack.  */
307           if (LOOKUP_FOUND_P (decl))
308             {
309               LOOKUP_FOUND_P (decl) = false;
310               previous->scopes->quick_push (decl);
311             }
312         }
313
314       /* Unmark the outer partial lookup.  */
315       if (previous->deduping)
316         lookup_mark (previous->value, false);
317     }
318   else
319     scopes = shared_scopes;
320   active = this;
321 }
322
323 /* Restore the marking state of a lookup we interrupted.  */
324
325 void
326 name_lookup::restore_state ()
327 {
328   if (deduping)
329     lookup_mark (value, false);
330
331   /* Unmark and empty this lookup's scope stack.  */
332   for (unsigned ix = vec_safe_length (scopes); ix--;)
333     {
334       tree decl = scopes->pop ();
335       gcc_checking_assert (LOOKUP_SEEN_P (decl));
336       LOOKUP_SEEN_P (decl) = false;
337       LOOKUP_FOUND_P (decl) = false;
338     }
339
340   active = previous;
341   if (previous)
342     {
343       free (scopes);
344
345       unsigned length = vec_safe_length (previous->scopes);
346       for (unsigned ix = 0; ix != length; ix++)
347         {
348           tree decl = (*previous->scopes)[ix];
349           if (LOOKUP_SEEN_P (decl))
350             {
351               /* The remainder of the scope stack must be recording
352                  FOUND_P decls, which we want to pop off.  */
353               do
354                 {
355                   tree decl = previous->scopes->pop ();
356                   gcc_checking_assert (LOOKUP_SEEN_P (decl)
357                                        && !LOOKUP_FOUND_P (decl));
358                   LOOKUP_FOUND_P (decl) = true;
359                 }
360               while (++ix != length);
361               break;
362             }
363
364           gcc_checking_assert (!LOOKUP_FOUND_P (decl));
365           LOOKUP_SEEN_P (decl) = true;
366         }
367
368       /* Remark the outer partial lookup.  */
369       if (previous->deduping)
370         lookup_mark (previous->value, true);
371     }
372   else
373     shared_scopes = scopes;
374 }
375
376 void
377 name_lookup::mark_seen (tree scope)
378 {
379   gcc_checking_assert (!seen_p (scope));
380   LOOKUP_SEEN_P (scope) = true;
381   vec_safe_push (scopes, scope);
382 }
383
384 bool
385 name_lookup::find_and_mark (tree scope)
386 {
387   bool result = LOOKUP_FOUND_P (scope);
388   if (!result)
389     {
390       LOOKUP_FOUND_P (scope) = true;
391       if (!LOOKUP_SEEN_P (scope))
392         vec_safe_push (scopes, scope);
393     }
394
395   return result;
396 }
397
398 /* THING and CURRENT are ambiguous, concatenate them.  */
399
400 tree
401 name_lookup::ambiguous (tree thing, tree current)
402 {
403   if (TREE_CODE (current) != TREE_LIST)
404     {
405       current = build_tree_list (NULL_TREE, current);
406       TREE_TYPE (current) = error_mark_node;
407     }
408   current = tree_cons (NULL_TREE, thing, current);
409   TREE_TYPE (current) = error_mark_node;
410
411   return current;
412 }
413
414 /* FNS is a new overload set to add to the exising set.  */
415
416 void
417 name_lookup::add_overload (tree fns)
418 {
419   if (!deduping && TREE_CODE (fns) == OVERLOAD)
420     {
421       tree probe = fns;
422       if (flags & LOOKUP_HIDDEN)
423         probe = ovl_skip_hidden (probe);
424       if (probe && TREE_CODE (probe) == OVERLOAD && OVL_USING_P (probe))
425         {
426           /* We're about to add something found by a using
427              declaration, so need to engage deduping mode.  */
428           lookup_mark (value, true);
429           deduping = true;
430         }
431     }
432
433   value = lookup_maybe_add (fns, value, deduping);
434 }
435
436 /* Add a NEW_VAL, a found value binding into the current value binding.  */
437
438 void
439 name_lookup::add_value (tree new_val)
440 {
441   if (OVL_P (new_val) && (!value || OVL_P (value)))
442     add_overload (new_val);
443   else if (!value)
444     value = new_val;
445   else if (value == new_val)
446     ;
447   else if ((TREE_CODE (value) == TYPE_DECL
448             && TREE_CODE (new_val) == TYPE_DECL
449             && same_type_p (TREE_TYPE (value), TREE_TYPE (new_val))))
450     /* Typedefs to the same type. */;
451   else if (TREE_CODE (value) == NAMESPACE_DECL
452            && TREE_CODE (new_val) == NAMESPACE_DECL
453            && ORIGINAL_NAMESPACE (value) == ORIGINAL_NAMESPACE (new_val))
454     /* Namespace (possibly aliased) to the same namespace.  Locate
455        the namespace*/
456     value = ORIGINAL_NAMESPACE (value);
457   else
458     {
459       if (deduping)
460         {
461           /* Disengage deduping mode.  */
462           lookup_mark (value, false);
463           deduping = false;
464         }
465       value = ambiguous (new_val, value);
466     }
467 }
468
469 /* Add a NEW_TYPE, a found type binding into the current type binding.  */
470
471 void
472 name_lookup::add_type (tree new_type)
473 {
474   if (!type)
475     type = new_type;
476   else if (TREE_CODE (type) == TREE_LIST
477            || !same_type_p (TREE_TYPE (type), TREE_TYPE (new_type)))
478     type = ambiguous (new_type, type);
479 }
480
481 /* Process a found binding containing NEW_VAL and NEW_TYPE.  Returns
482    true if we actually found something noteworthy.  */
483
484 bool
485 name_lookup::process_binding (tree new_val, tree new_type)
486 {
487   /* Did we really see a type? */
488   if (new_type
489       && (LOOKUP_NAMESPACES_ONLY (flags)
490           || (!(flags & LOOKUP_HIDDEN)
491               && DECL_LANG_SPECIFIC (new_type)
492               && DECL_ANTICIPATED (new_type))))
493     new_type = NULL_TREE;
494
495   if (new_val && !(flags & LOOKUP_HIDDEN))
496     new_val = ovl_skip_hidden (new_val);
497
498   /* Do we really see a value? */
499   if (new_val)
500     switch (TREE_CODE (new_val))
501       {
502       case TEMPLATE_DECL:
503         /* If we expect types or namespaces, and not templates,
504            or this is not a template class.  */
505         if ((LOOKUP_QUALIFIERS_ONLY (flags)
506              && !DECL_TYPE_TEMPLATE_P (new_val)))
507           new_val = NULL_TREE;
508         break;
509       case TYPE_DECL:
510         if (LOOKUP_NAMESPACES_ONLY (flags)
511             || (new_type && (flags & LOOKUP_PREFER_TYPES)))
512           new_val = NULL_TREE;
513         break;
514       case NAMESPACE_DECL:
515         if (LOOKUP_TYPES_ONLY (flags))
516           new_val = NULL_TREE;
517         break;
518       default:
519         if (LOOKUP_QUALIFIERS_ONLY (flags))
520           new_val = NULL_TREE;
521       }
522
523   if (!new_val)
524     {
525       new_val = new_type;
526       new_type = NULL_TREE;
527     }
528
529   /* Merge into the lookup  */
530   if (new_val)
531     add_value (new_val);
532   if (new_type)
533     add_type (new_type);
534
535   return new_val != NULL_TREE;
536 }
537
538 /* Look in exactly namespace SCOPE.  */
539
540 bool
541 name_lookup::search_namespace_only (tree scope)
542 {
543   bool found = false;
544
545   if (tree *binding = find_namespace_slot (scope, name))
546     found |= process_binding (MAYBE_STAT_DECL (*binding),
547                               MAYBE_STAT_TYPE (*binding));
548
549   return found;
550 }
551
552 /* Conditionally look in namespace SCOPE and inline children.  */
553
554 bool
555 name_lookup::search_namespace (tree scope)
556 {
557   if (see_and_mark (scope))
558     /* We've visited this scope before.  Return what we found then.  */
559     return found_p (scope);
560
561   /* Look in exactly namespace. */
562   bool found = search_namespace_only (scope);
563
564   /* Don't look into inline children, if we're looking for an
565      anonymous name -- it must be in the current scope, if anywhere.  */
566   if (name)
567     /* Recursively look in its inline children.  */
568     if (vec<tree, va_gc> *inlinees = DECL_NAMESPACE_INLINEES (scope))
569       for (unsigned ix = inlinees->length (); ix--;)
570         found |= search_namespace ((*inlinees)[ix]);
571
572   if (found)
573     mark_found (scope);
574
575   return found;
576 }
577
578 /* Recursively follow using directives of SCOPE & its inline children.
579    Such following is essentially a flood-fill algorithm.  */
580
581 bool
582 name_lookup::search_usings (tree scope)
583 {
584   /* We do not check seen_p here, as that was already set during the
585      namespace_only walk.  */
586   if (found_p (scope))
587     return true;
588
589   bool found = false;
590   if (vec<tree, va_gc> *usings = DECL_NAMESPACE_USING (scope))
591     for (unsigned ix = usings->length (); ix--;)
592       found |= search_qualified ((*usings)[ix], true);
593
594   /* Look in its inline children.  */
595   if (vec<tree, va_gc> *inlinees = DECL_NAMESPACE_INLINEES (scope))
596     for (unsigned ix = inlinees->length (); ix--;)
597       found |= search_usings ((*inlinees)[ix]);
598
599   if (found)
600     mark_found (scope);
601
602   return found;
603 }
604
605 /* Qualified namespace lookup in SCOPE.
606    1) Look in SCOPE (+inlines).  If found, we're done.
607    2) Otherwise, if USINGS is true,
608       recurse for every using directive of SCOPE (+inlines).
609
610    Trickiness is (a) loops and (b) multiple paths to same namespace.
611    In both cases we want to not repeat any lookups, and know whether
612    to stop the caller's step #2.  Do this via the FOUND_P marker.  */
613
614 bool
615 name_lookup::search_qualified (tree scope, bool usings)
616 {
617   bool found = false;
618
619   if (seen_p (scope))
620     found = found_p (scope);
621   else 
622     {
623       found = search_namespace (scope);
624       if (!found && usings)
625         found = search_usings (scope);
626     }
627
628   return found;
629 }
630
631 /* Add SCOPE to the unqualified search queue, recursively add its
632    inlines and those via using directives.  */
633
634 name_lookup::using_queue *
635 name_lookup::queue_namespace (using_queue *queue, int depth, tree scope)
636 {
637   if (see_and_mark (scope))
638     return queue;
639
640   /* Record it.  */
641   tree common = scope;
642   while (SCOPE_DEPTH (common) > depth)
643     common = CP_DECL_CONTEXT (common);
644   vec_safe_push (queue, using_pair (common, scope));
645
646   /* Queue its inline children.  */
647   if (vec<tree, va_gc> *inlinees = DECL_NAMESPACE_INLINEES (scope))
648     for (unsigned ix = inlinees->length (); ix--;)
649       queue = queue_namespace (queue, depth, (*inlinees)[ix]);
650
651   /* Queue its using targets.  */
652   queue = queue_usings (queue, depth, DECL_NAMESPACE_USING (scope));
653
654   return queue;
655 }
656
657 /* Add the namespaces in USINGS to the unqualified search queue.  */
658
659 name_lookup::using_queue *
660 name_lookup::do_queue_usings (using_queue *queue, int depth,
661                               vec<tree, va_gc> *usings)
662 {
663   for (unsigned ix = usings->length (); ix--;)
664     queue = queue_namespace (queue, depth, (*usings)[ix]);
665
666   return queue;
667 }
668
669 /* Unqualified namespace lookup in SCOPE.
670    1) add scope+inlins to worklist.
671    2) recursively add target of every using directive
672    3) for each worklist item where SCOPE is common ancestor, search it
673    4) if nothing find, scope=parent, goto 1.  */
674
675 bool
676 name_lookup::search_unqualified (tree scope, cp_binding_level *level)
677 {
678   /* Make static to avoid continual reallocation.  We're not
679      recursive.  */
680   static using_queue *queue = NULL;
681   bool found = false;
682   int length = vec_safe_length (queue);
683
684   /* Queue local using-directives.  */
685   for (; level->kind != sk_namespace; level = level->level_chain)
686     queue = queue_usings (queue, SCOPE_DEPTH (scope), level->using_directives);
687
688   for (; !found; scope = CP_DECL_CONTEXT (scope))
689     {
690       gcc_assert (!DECL_NAMESPACE_ALIAS (scope));
691       int depth = SCOPE_DEPTH (scope);
692
693       /* Queue namespaces reachable from SCOPE. */
694       queue = queue_namespace (queue, depth, scope);
695
696       /* Search every queued namespace where SCOPE is the common
697          ancestor.  Adjust the others.  */
698       unsigned ix = length;
699       do
700         {
701           using_pair &pair = (*queue)[ix];
702           while (pair.first == scope)
703             {
704               found |= search_namespace_only (pair.second);
705               pair = queue->pop ();
706               if (ix == queue->length ())
707                 goto done;
708             }
709           /* The depth is the same as SCOPE, find the parent scope.  */
710           if (SCOPE_DEPTH (pair.first) == depth)
711             pair.first = CP_DECL_CONTEXT (pair.first);
712           ix++;
713         }
714       while (ix < queue->length ());
715     done:;
716       if (scope == global_namespace)
717         break;
718
719       /* If looking for hidden names, we only look in the innermost
720          namespace scope.  [namespace.memdef]/3 If a friend
721          declaration in a non-local class first declares a class,
722          function, class template or function template the friend is a
723          member of the innermost enclosing namespace.  See also
724          [basic.lookup.unqual]/7 */
725       if (flags & LOOKUP_HIDDEN)
726         break;
727     }
728
729   vec_safe_truncate (queue, length);
730
731   return found;
732 }
733
734 /* FNS is a value binding.  If it is a (set of overloaded) functions,
735    add them into the current value.  */
736
737 void
738 name_lookup::add_fns (tree fns)
739 {
740   if (!fns)
741     return;
742   else if (TREE_CODE (fns) == OVERLOAD)
743     {
744       if (TREE_TYPE (fns) != unknown_type_node)
745         fns = OVL_FUNCTION (fns);
746     }
747   else if (!DECL_DECLARES_FUNCTION_P (fns))
748     return;
749
750   add_overload (fns);
751 }
752
753 /* Add functions of a namespace to the lookup structure.  */
754
755 void
756 name_lookup::adl_namespace_only (tree scope)
757 {
758   mark_seen (scope);
759
760   /* Look down into inline namespaces.  */
761   if (vec<tree, va_gc> *inlinees = DECL_NAMESPACE_INLINEES (scope))
762     for (unsigned ix = inlinees->length (); ix--;)
763       adl_namespace_only ((*inlinees)[ix]);
764
765   if (tree fns = find_namespace_value (scope, name))
766     add_fns (ovl_skip_hidden (fns));
767 }
768
769 /* Find the containing non-inlined namespace, add it and all its
770    inlinees.  */
771
772 void
773 name_lookup::adl_namespace (tree scope)
774 {
775   if (seen_p (scope))
776     return;
777
778   /* Find the containing non-inline namespace.  */
779   while (DECL_NAMESPACE_INLINE_P (scope))
780     scope = CP_DECL_CONTEXT (scope);
781
782   adl_namespace_only (scope);
783 }
784
785 /* Adds the class and its friends to the lookup structure.  */
786
787 void
788 name_lookup::adl_class_only (tree type)
789 {
790   /* Backend-built structures, such as __builtin_va_list, aren't
791      affected by all this.  */
792   if (!CLASS_TYPE_P (type))
793     return;
794
795   type = TYPE_MAIN_VARIANT (type);
796
797   if (see_and_mark (type))
798     return;
799
800   tree context = decl_namespace_context (type);
801   adl_namespace (context);
802
803   complete_type (type);
804
805   /* Add friends.  */
806   for (tree list = DECL_FRIENDLIST (TYPE_MAIN_DECL (type)); list;
807        list = TREE_CHAIN (list))
808     if (name == FRIEND_NAME (list))
809       for (tree friends = FRIEND_DECLS (list); friends;
810            friends = TREE_CHAIN (friends))
811         {
812           tree fn = TREE_VALUE (friends);
813
814           /* Only interested in global functions with potentially hidden
815              (i.e. unqualified) declarations.  */
816           if (CP_DECL_CONTEXT (fn) != context)
817             continue;
818
819           /* Only interested in anticipated friends.  (Non-anticipated
820              ones will have been inserted during the namespace
821              adl.)  */
822           if (!DECL_ANTICIPATED (fn))
823             continue;
824
825           /* Template specializations are never found by name lookup.
826              (Templates themselves can be found, but not template
827              specializations.)  */
828           if (TREE_CODE (fn) == FUNCTION_DECL && DECL_USE_TEMPLATE (fn))
829             continue;
830
831           add_fns (fn);
832         }
833 }
834
835 /* Adds the class and its bases to the lookup structure.
836    Returns true on error.  */
837
838 void
839 name_lookup::adl_bases (tree type)
840 {
841   adl_class_only (type);
842
843   /* Process baseclasses.  */
844   if (tree binfo = TYPE_BINFO (type))
845     {
846       tree base_binfo;
847       int i;
848
849       for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
850         adl_bases (BINFO_TYPE (base_binfo));
851     }
852 }
853
854 /* Adds everything associated with a class argument type to the lookup
855    structure.  Returns true on error.
856
857    If T is a class type (including unions), its associated classes are: the
858    class itself; the class of which it is a member, if any; and its direct
859    and indirect base classes. Its associated namespaces are the namespaces
860    of which its associated classes are members. Furthermore, if T is a
861    class template specialization, its associated namespaces and classes
862    also include: the namespaces and classes associated with the types of
863    the template arguments provided for template type parameters (excluding
864    template template parameters); the namespaces of which any template
865    template arguments are members; and the classes of which any member
866    templates used as template template arguments are members. [ Note:
867    non-type template arguments do not contribute to the set of associated
868    namespaces.  --end note] */
869
870 void
871 name_lookup::adl_class (tree type)
872 {
873   /* Backend build structures, such as __builtin_va_list, aren't
874      affected by all this.  */
875   if (!CLASS_TYPE_P (type))
876     return;
877
878   type = TYPE_MAIN_VARIANT (type);
879   /* We don't set found here because we have to have set seen first,
880      which is done in the adl_bases walk.  */
881   if (found_p (type))
882     return;
883
884   adl_bases (type);
885   mark_found (type);
886
887   if (TYPE_CLASS_SCOPE_P (type))
888     adl_class_only (TYPE_CONTEXT (type));
889
890   /* Process template arguments.  */
891   if (CLASSTYPE_TEMPLATE_INFO (type)
892       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
893     {
894       tree list = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
895       for (int i = 0; i < TREE_VEC_LENGTH (list); ++i)
896         adl_template_arg (TREE_VEC_ELT (list, i));
897     }
898 }
899
900 void
901 name_lookup::adl_expr (tree expr)
902 {
903   if (!expr)
904     return;
905
906   gcc_assert (!TYPE_P (expr));
907
908   if (TREE_TYPE (expr) != unknown_type_node)
909     {
910       adl_type (TREE_TYPE (expr));
911       return;
912     }
913
914   if (TREE_CODE (expr) == ADDR_EXPR)
915     expr = TREE_OPERAND (expr, 0);
916   if (TREE_CODE (expr) == COMPONENT_REF
917       || TREE_CODE (expr) == OFFSET_REF)
918     expr = TREE_OPERAND (expr, 1);
919   expr = MAYBE_BASELINK_FUNCTIONS (expr);
920
921   if (OVL_P (expr))
922     for (lkp_iterator iter (expr); iter; ++iter)
923       adl_type (TREE_TYPE (*iter));
924   else if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
925     {
926       /* The working paper doesn't currently say how to handle
927          template-id arguments.  The sensible thing would seem to be
928          to handle the list of template candidates like a normal
929          overload set, and handle the template arguments like we do
930          for class template specializations.  */
931
932       /* First the templates.  */
933       adl_expr (TREE_OPERAND (expr, 0));
934
935       /* Now the arguments.  */
936       if (tree args = TREE_OPERAND (expr, 1))
937         for (int ix = TREE_VEC_LENGTH (args); ix--;)
938           adl_template_arg (TREE_VEC_ELT (args, ix));
939     }
940 }
941
942 void
943 name_lookup::adl_type (tree type)
944 {
945   if (!type)
946     return;
947
948   if (TYPE_PTRDATAMEM_P (type))
949     {
950       /* Pointer to member: associate class type and value type.  */
951       adl_type (TYPE_PTRMEM_CLASS_TYPE (type));
952       adl_type (TYPE_PTRMEM_POINTED_TO_TYPE (type));
953       return;
954     }
955
956   switch (TREE_CODE (type))
957     {
958     case RECORD_TYPE:
959       if (TYPE_PTRMEMFUNC_P (type))
960         {
961           adl_type (TYPE_PTRMEMFUNC_FN_TYPE (type));
962           return;
963         }
964       /* FALLTHRU */
965     case UNION_TYPE:
966       adl_class (type);
967       return;
968
969     case METHOD_TYPE:
970       /* The basetype is referenced in the first arg type, so just
971          fall through.  */
972     case FUNCTION_TYPE:
973       /* Associate the parameter types.  */
974       for (tree args = TYPE_ARG_TYPES (type); args; args = TREE_CHAIN (args))
975         adl_type (TREE_VALUE (args));
976       /* FALLTHROUGH */
977
978     case POINTER_TYPE:
979     case REFERENCE_TYPE:
980     case ARRAY_TYPE:
981       adl_type (TREE_TYPE (type));
982       return;
983
984     case ENUMERAL_TYPE:
985       if (TYPE_CLASS_SCOPE_P (type))
986         adl_class_only (TYPE_CONTEXT (type));
987       adl_namespace (decl_namespace_context (type));
988       return;
989
990     case LANG_TYPE:
991       gcc_assert (type == unknown_type_node
992                   || type == init_list_type_node);
993       return;
994
995     case TYPE_PACK_EXPANSION:
996       adl_type (PACK_EXPANSION_PATTERN (type));
997       return;
998
999     default:
1000       break;
1001     }
1002 }
1003
1004 /* Adds everything associated with a template argument to the lookup
1005    structure.  */
1006
1007 void
1008 name_lookup::adl_template_arg (tree arg)
1009 {
1010   /* [basic.lookup.koenig]
1011
1012      If T is a template-id, its associated namespaces and classes are
1013      ... the namespaces and classes associated with the types of the
1014      template arguments provided for template type parameters
1015      (excluding template template parameters); the namespaces in which
1016      any template template arguments are defined; and the classes in
1017      which any member templates used as template template arguments
1018      are defined.  [Note: non-type template arguments do not
1019      contribute to the set of associated namespaces.  ]  */
1020
1021   /* Consider first template template arguments.  */
1022   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
1023       || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
1024     ;
1025   else if (TREE_CODE (arg) == TEMPLATE_DECL)
1026     {
1027       tree ctx = CP_DECL_CONTEXT (arg);
1028
1029       /* It's not a member template.  */
1030       if (TREE_CODE (ctx) == NAMESPACE_DECL)
1031         adl_namespace (ctx);
1032       /* Otherwise, it must be member template.  */
1033       else
1034         adl_class_only (ctx);
1035     }
1036   /* It's an argument pack; handle it recursively.  */
1037   else if (ARGUMENT_PACK_P (arg))
1038     {
1039       tree args = ARGUMENT_PACK_ARGS (arg);
1040       int i, len = TREE_VEC_LENGTH (args);
1041       for (i = 0; i < len; ++i) 
1042         adl_template_arg (TREE_VEC_ELT (args, i));
1043     }
1044   /* It's not a template template argument, but it is a type template
1045      argument.  */
1046   else if (TYPE_P (arg))
1047     adl_type (arg);
1048 }
1049
1050 /* Perform ADL lookup.  FNS is the existing lookup result and ARGS are
1051    the call arguments.  */
1052
1053 tree
1054 name_lookup::search_adl (tree fns, vec<tree, va_gc> *args)
1055 {
1056   if (fns)
1057     {
1058       deduping = true;
1059       lookup_mark (fns, true);
1060     }
1061   value = fns;
1062
1063   unsigned ix;
1064   tree arg;
1065
1066   FOR_EACH_VEC_ELT_REVERSE (*args, ix, arg)
1067     /* OMP reduction operators put an ADL-significant type as the
1068        first arg. */
1069     if (TYPE_P (arg))
1070       adl_type (arg);
1071     else
1072       adl_expr (arg);
1073
1074   fns = value;
1075
1076   return fns;
1077 }
1078
1079 static bool qualified_namespace_lookup (tree, name_lookup *);
1080 static void consider_binding_level (tree name,
1081                                     best_match <tree, const char *> &bm,
1082                                     cp_binding_level *lvl,
1083                                     bool look_within_fields,
1084                                     enum lookup_name_fuzzy_kind kind);
1085 static void diagnose_name_conflict (tree, tree);
1086
1087 /* ADL lookup of NAME.  FNS is the result of regular lookup, and we
1088    don't add duplicates to it.  ARGS is the vector of call
1089    arguments (which will not be empty).  */
1090
1091 tree
1092 lookup_arg_dependent (tree name, tree fns, vec<tree, va_gc> *args)
1093 {
1094   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
1095   name_lookup lookup (name);
1096   fns = lookup.search_adl (fns, args);
1097   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
1098   return fns;
1099 }
1100
1101 /* FNS is an overload set of conversion functions.  Return the
1102    overloads converting to TYPE.  */
1103
1104 static tree
1105 extract_conversion_operator (tree fns, tree type)
1106 {
1107   tree convs = NULL_TREE;
1108   tree tpls = NULL_TREE;
1109
1110   for (ovl_iterator iter (fns); iter; ++iter)
1111     {
1112       if (same_type_p (DECL_CONV_FN_TYPE (*iter), type))
1113         convs = lookup_add (*iter, convs);
1114
1115       if (TREE_CODE (*iter) == TEMPLATE_DECL)
1116         tpls = lookup_add (*iter, tpls);
1117     }
1118
1119   if (!convs)
1120     convs = tpls;
1121
1122   return convs;
1123 }
1124
1125 /* Binary search of (ordered) MEMBER_VEC for NAME.  */
1126
1127 static tree
1128 member_vec_binary_search (vec<tree, va_gc> *member_vec, tree name)
1129 {
1130   for (unsigned lo = 0, hi = member_vec->length (); lo < hi;)
1131     {
1132       unsigned mid = (lo + hi) / 2;
1133       tree binding = (*member_vec)[mid];
1134       tree binding_name = OVL_NAME (binding);
1135
1136       if (binding_name > name)
1137         hi = mid;
1138       else if (binding_name < name)
1139         lo = mid + 1;
1140       else
1141         return binding;
1142     }
1143
1144   return NULL_TREE;
1145 }
1146
1147 /* Linear search of (unordered) MEMBER_VEC for NAME.  */
1148
1149 static tree
1150 member_vec_linear_search (vec<tree, va_gc> *member_vec, tree name)
1151 {
1152   for (int ix = member_vec->length (); ix--;)
1153     if (tree binding = (*member_vec)[ix])
1154       if (OVL_NAME (binding) == name)
1155         return binding;
1156
1157   return NULL_TREE;
1158 }
1159
1160 /* Linear search of (partially ordered) fields of KLASS for NAME.  */
1161
1162 static tree
1163 fields_linear_search (tree klass, tree name, bool want_type)
1164 {
1165   for (tree fields = TYPE_FIELDS (klass); fields; fields = DECL_CHAIN (fields))
1166     {
1167       tree decl = fields;
1168
1169       if (TREE_CODE (decl) == FIELD_DECL
1170           && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
1171         {
1172           if (tree temp = search_anon_aggr (TREE_TYPE (decl), name, want_type))
1173             return temp;
1174         }
1175
1176       if (DECL_NAME (decl) != name)
1177         continue;
1178       
1179       if (TREE_CODE (decl) == USING_DECL)
1180         {
1181           decl = strip_using_decl (decl);
1182           if (is_overloaded_fn (decl))
1183             continue;
1184         }
1185
1186       if (DECL_DECLARES_FUNCTION_P (decl))
1187         /* Functions are found separately.  */
1188         continue;
1189
1190       if (!want_type || DECL_DECLARES_TYPE_P (decl))
1191         return decl;
1192     }
1193
1194   return NULL_TREE;
1195 }
1196
1197 /* Look for NAME member inside of anonymous aggregate ANON.  Although
1198    such things should only contain FIELD_DECLs, we check that too
1199    late, and would give very confusing errors if we weren't
1200    permissive here.  */
1201
1202 tree
1203 search_anon_aggr (tree anon, tree name, bool want_type)
1204 {
1205   gcc_assert (COMPLETE_TYPE_P (anon));
1206   tree ret = get_class_binding_direct (anon, name, want_type);
1207   return ret;
1208 }
1209
1210 /* Look for NAME as an immediate member of KLASS (including
1211    anon-members or unscoped enum member).  TYPE_OR_FNS is zero for
1212    regular search.  >0 to get a type binding (if there is one) and <0
1213    if you want (just) the member function binding.
1214
1215    Use this if you do not want lazy member creation.  */
1216
1217 tree
1218 get_class_binding_direct (tree klass, tree name, int type_or_fns)
1219 {
1220   gcc_checking_assert (RECORD_OR_UNION_TYPE_P (klass));
1221
1222   /* Conversion operators can only be found by the marker conversion
1223      operator name.  */
1224   bool conv_op = IDENTIFIER_CONV_OP_P (name);
1225   tree lookup = conv_op ? conv_op_identifier : name;
1226   tree val = NULL_TREE;
1227   vec<tree, va_gc> *member_vec = CLASSTYPE_MEMBER_VEC (klass);
1228
1229   if (COMPLETE_TYPE_P (klass) && member_vec)
1230     {
1231       val = member_vec_binary_search (member_vec, lookup);
1232       if (!val)
1233         ;
1234       else if (type_or_fns > 0)
1235         {
1236           if (STAT_HACK_P (val))
1237             val = STAT_TYPE (val);
1238           else if (!DECL_DECLARES_TYPE_P (val))
1239             val = NULL_TREE;
1240         }
1241       else if (STAT_HACK_P (val))
1242         val = STAT_DECL (val);
1243     }
1244   else
1245     {
1246       if (member_vec && type_or_fns <= 0)
1247         val = member_vec_linear_search (member_vec, lookup);
1248
1249       if (type_or_fns < 0)
1250         /* Don't bother looking for field.  We don't want it.  */;
1251       else if (!val || (TREE_CODE (val) == OVERLOAD && OVL_USING_P (val)))
1252         /* Dependent using declarations are a 'field', make sure we
1253            return that even if we saw an overload already.  */
1254         if (tree field_val = fields_linear_search (klass, lookup,
1255                                                    type_or_fns > 0))
1256           if (!val || TREE_CODE (field_val) == USING_DECL)
1257             val = field_val;
1258     }
1259
1260   /* Extract the conversion operators asked for, unless the general
1261      conversion operator was requested.   */
1262   if (val && conv_op)
1263     {
1264       gcc_checking_assert (OVL_FUNCTION (val) == conv_op_marker);
1265       val = OVL_CHAIN (val);
1266       if (tree type = TREE_TYPE (name))
1267         val = extract_conversion_operator (val, type);
1268     }
1269
1270   return val;
1271 }
1272
1273 /* Look for NAME's binding in exactly KLASS.  See
1274    get_class_binding_direct for argument description.  Does lazy
1275    special function creation as necessary.  */
1276
1277 tree
1278 get_class_binding (tree klass, tree name, int type_or_fns)
1279 {
1280   klass = complete_type (klass);
1281
1282   if (COMPLETE_TYPE_P (klass))
1283     {
1284       /* Lazily declare functions, if we're going to search these.  */
1285       if (IDENTIFIER_CTOR_P (name))
1286         {
1287           if (CLASSTYPE_LAZY_DEFAULT_CTOR (klass))
1288             lazily_declare_fn (sfk_constructor, klass);
1289           if (CLASSTYPE_LAZY_COPY_CTOR (klass))
1290             lazily_declare_fn (sfk_copy_constructor, klass);
1291           if (CLASSTYPE_LAZY_MOVE_CTOR (klass))
1292             lazily_declare_fn (sfk_move_constructor, klass);
1293         }
1294       else if (IDENTIFIER_DTOR_P (name))
1295         {
1296           if (CLASSTYPE_LAZY_DESTRUCTOR (klass))
1297             lazily_declare_fn (sfk_destructor, klass);
1298         }
1299       else if (name == assign_op_identifier)
1300         {
1301           if (CLASSTYPE_LAZY_COPY_ASSIGN (klass))
1302             lazily_declare_fn (sfk_copy_assignment, klass);
1303           if (CLASSTYPE_LAZY_MOVE_ASSIGN (klass))
1304             lazily_declare_fn (sfk_move_assignment, klass);
1305         }
1306     }
1307
1308   return get_class_binding_direct (klass, name, type_or_fns);
1309 }
1310
1311 /* Find the slot containing overloads called 'NAME'.  If there is no
1312    such slot and the class is complete, create an empty one, at the
1313    correct point in the sorted member vector.  Otherwise return NULL.
1314    Deals with conv_op marker handling.  */
1315
1316 tree *
1317 find_member_slot (tree klass, tree name)
1318 {
1319   bool complete_p = COMPLETE_TYPE_P (klass);
1320
1321   vec<tree, va_gc> *member_vec = CLASSTYPE_MEMBER_VEC (klass);
1322   if (!member_vec)
1323     {
1324       vec_alloc (member_vec, 8);
1325       CLASSTYPE_MEMBER_VEC (klass) = member_vec;
1326       if (complete_p)
1327         {
1328           /* If the class is complete but had no member_vec, we need
1329              to add the TYPE_FIELDS into it.  We're also most likely
1330              to be adding ctors & dtors, so ask for 6 spare slots (the
1331              abstract cdtors and their clones).  */
1332           set_class_bindings (klass, 6);
1333           member_vec = CLASSTYPE_MEMBER_VEC (klass);
1334         }
1335     }
1336
1337   if (IDENTIFIER_CONV_OP_P (name))
1338     name = conv_op_identifier;
1339
1340   unsigned ix, length = member_vec->length ();
1341   for (ix = 0; ix < length; ix++)
1342     {
1343       tree *slot = &(*member_vec)[ix];
1344       tree fn_name = OVL_NAME (*slot);
1345
1346       if (fn_name == name)
1347         {
1348           /* If we found an existing slot, it must be a function set.
1349              Even with insertion after completion, because those only
1350              happen with artificial fns that have unspellable names.
1351              This means we do not have to deal with the stat hack
1352              either.  */
1353           gcc_checking_assert (OVL_P (*slot));
1354           if (name == conv_op_identifier)
1355             {
1356               gcc_checking_assert (OVL_FUNCTION (*slot) == conv_op_marker);
1357               /* Skip the conv-op marker. */
1358               slot = &OVL_CHAIN (*slot);
1359             }
1360           return slot;
1361         }
1362
1363       if (complete_p && fn_name > name)
1364         break;
1365     }
1366
1367   /* No slot found, add one if the class is complete.  */
1368   if (complete_p)
1369     {
1370       /* Do exact allocation, as we don't expect to add many.  */
1371       gcc_assert (name != conv_op_identifier);
1372       vec_safe_reserve_exact (member_vec, 1);
1373       CLASSTYPE_MEMBER_VEC (klass) = member_vec;
1374       member_vec->quick_insert (ix, NULL_TREE);
1375       return &(*member_vec)[ix];
1376     }
1377
1378   return NULL;
1379 }
1380
1381 /* KLASS is an incomplete class to which we're adding a method NAME.
1382    Add a slot and deal with conv_op marker handling.  */
1383
1384 tree *
1385 add_member_slot (tree klass, tree name)
1386 {
1387   gcc_assert (!COMPLETE_TYPE_P (klass));
1388
1389   vec<tree, va_gc> *member_vec = CLASSTYPE_MEMBER_VEC (klass);
1390   vec_safe_push (member_vec, NULL_TREE);
1391   CLASSTYPE_MEMBER_VEC (klass) = member_vec;
1392
1393   tree *slot = &member_vec->last ();
1394   if (IDENTIFIER_CONV_OP_P (name))
1395     {
1396       /* Install the marker prefix.  */
1397       *slot = ovl_make (conv_op_marker, NULL_TREE);
1398       slot = &OVL_CHAIN (*slot);
1399     }
1400
1401   return slot;
1402 }
1403
1404 /* Comparison function to compare two MEMBER_VEC entries by name.
1405    Because we can have duplicates during insertion of TYPE_FIELDS, we
1406    do extra checking so deduping doesn't have to deal with so many
1407    cases.  */
1408
1409 static int
1410 member_name_cmp (const void *a_p, const void *b_p)
1411 {
1412   tree a = *(const tree *)a_p;
1413   tree b = *(const tree *)b_p;
1414   tree name_a = DECL_NAME (TREE_CODE (a) == OVERLOAD ? OVL_FUNCTION (a) : a);
1415   tree name_b = DECL_NAME (TREE_CODE (b) == OVERLOAD ? OVL_FUNCTION (b) : b);
1416
1417   gcc_checking_assert (name_a && name_b);
1418   if (name_a != name_b)
1419     return name_a < name_b ? -1 : +1;
1420
1421   if (name_a == conv_op_identifier)
1422     {
1423       /* Strip the conv-op markers. */
1424       gcc_checking_assert (OVL_FUNCTION (a) == conv_op_marker
1425                            && OVL_FUNCTION (b) == conv_op_marker);
1426       a = OVL_CHAIN (a);
1427       b = OVL_CHAIN (b);
1428     }
1429
1430   if (TREE_CODE (a) == OVERLOAD)
1431     a = OVL_FUNCTION (a);
1432   if (TREE_CODE (b) == OVERLOAD)
1433     b = OVL_FUNCTION (b);
1434
1435   /* We're in STAT_HACK or USING_DECL territory (or possibly error-land). */
1436   if (TREE_CODE (a) != TREE_CODE (b))
1437     {
1438       /* If one of them is a TYPE_DECL, it loses.  */
1439       if (TREE_CODE (a) == TYPE_DECL)
1440         return +1;
1441       else if (TREE_CODE (b) == TYPE_DECL)
1442         return -1;
1443
1444       /* If one of them is a USING_DECL, it loses.  */
1445       if (TREE_CODE (a) == USING_DECL)
1446         return +1;
1447       else if (TREE_CODE (b) == USING_DECL)
1448         return -1;
1449
1450       /* There are no other cases with different kinds of decls, as
1451          duplicate detection should have kicked in earlier.  However,
1452          some erroneous cases get though. */
1453       gcc_assert (errorcount);
1454     }
1455   
1456   /* Using source location would be the best thing here, but we can
1457      get identically-located decls in the following circumstances:
1458
1459      1) duplicate artificial type-decls for the same type.
1460
1461      2) pack expansions of using-decls.
1462
1463      We should not be doing #1, but in either case it doesn't matter
1464      how we order these.  Use UID as a proxy for source ordering, so
1465      that identically-located decls still have a well-defined stable
1466      ordering.  */
1467   if (DECL_UID (a) != DECL_UID (b))
1468     return DECL_UID (a) < DECL_UID (b) ? -1 : +1;
1469   gcc_assert (a == b);
1470   return 0;
1471 }
1472
1473 static struct {
1474   gt_pointer_operator new_value;
1475   void *cookie;
1476 } resort_data;
1477
1478 /* This routine compares two fields like member_name_cmp but using the
1479    pointer operator in resort_field_decl_data.  We don't have to deal
1480    with duplicates here.  */
1481
1482 static int
1483 resort_member_name_cmp (const void *a_p, const void *b_p)
1484 {
1485   tree a = *(const tree *)a_p;
1486   tree b = *(const tree *)b_p;
1487   tree name_a = OVL_NAME (a);
1488   tree name_b = OVL_NAME (b);
1489
1490   resort_data.new_value (&name_a, resort_data.cookie);
1491   resort_data.new_value (&name_b, resort_data.cookie);
1492
1493   gcc_checking_assert (name_a != name_b);
1494
1495   return name_a < name_b ? -1 : +1;
1496 }
1497
1498 /* Resort CLASSTYPE_MEMBER_VEC because pointers have been reordered.  */
1499
1500 void
1501 resort_type_member_vec (void *obj, void */*orig_obj*/,
1502                         gt_pointer_operator new_value, void* cookie)
1503 {
1504   if (vec<tree, va_gc> *member_vec = (vec<tree, va_gc> *) obj)
1505     {
1506       resort_data.new_value = new_value;
1507       resort_data.cookie = cookie;
1508       member_vec->qsort (resort_member_name_cmp);
1509     }
1510 }
1511
1512 /* Recursively count the number of fields in KLASS, including anonymous
1513    union members.  */
1514
1515 static unsigned
1516 count_class_fields (tree klass)
1517 {
1518   unsigned n_fields = 0;
1519
1520   for (tree fields = TYPE_FIELDS (klass); fields; fields = DECL_CHAIN (fields))
1521     if (DECL_DECLARES_FUNCTION_P (fields))
1522       /* Functions are dealt with separately.  */;
1523     else if (TREE_CODE (fields) == FIELD_DECL
1524              && ANON_AGGR_TYPE_P (TREE_TYPE (fields)))
1525       n_fields += count_class_fields (TREE_TYPE (fields));
1526     else if (DECL_NAME (fields))
1527       n_fields += 1;
1528
1529   return n_fields;
1530 }
1531
1532 /* Append all the nonfunction members fields of KLASS to MEMBER_VEC.
1533    Recurse for anonymous members.  MEMBER_VEC must have space.  */
1534
1535 static void
1536 member_vec_append_class_fields (vec<tree, va_gc> *member_vec, tree klass)
1537 {
1538   for (tree fields = TYPE_FIELDS (klass); fields; fields = DECL_CHAIN (fields))
1539     if (DECL_DECLARES_FUNCTION_P (fields))
1540       /* Functions are handled separately.  */;
1541     else if (TREE_CODE (fields) == FIELD_DECL
1542              && ANON_AGGR_TYPE_P (TREE_TYPE (fields)))
1543       member_vec_append_class_fields (member_vec, TREE_TYPE (fields));
1544     else if (DECL_NAME (fields))
1545       {
1546         tree field = fields;
1547         /* Mark a conv-op USING_DECL with the conv-op-marker.  */
1548         if (TREE_CODE (field) == USING_DECL
1549             && IDENTIFIER_CONV_OP_P (DECL_NAME (field)))
1550           field = ovl_make (conv_op_marker, field);
1551         member_vec->quick_push (field);
1552       }
1553 }
1554
1555 /* Append all of the enum values of ENUMTYPE to MEMBER_VEC.
1556    MEMBER_VEC must have space.  */
1557
1558 static void
1559 member_vec_append_enum_values (vec<tree, va_gc> *member_vec, tree enumtype)
1560 {
1561   for (tree values = TYPE_VALUES (enumtype);
1562        values; values = TREE_CHAIN (values))
1563     member_vec->quick_push (TREE_VALUE (values));
1564 }
1565
1566 /* MEMBER_VEC has just had new DECLs added to it, but is sorted.
1567    DeDup adjacent DECLS of the same name.  We already dealt with
1568    conflict resolution when adding the fields or methods themselves.
1569    There are three cases (which could all be combined):
1570    1) a TYPE_DECL and non TYPE_DECL.  Deploy STAT_HACK as appropriate.
1571    2) a USING_DECL and an overload.  If the USING_DECL is dependent,
1572    it wins.  Otherwise the OVERLOAD does.
1573    3) two USING_DECLS. ...
1574
1575    member_name_cmp will have ordered duplicates as
1576    <fns><using><type>  */
1577
1578 static void
1579 member_vec_dedup (vec<tree, va_gc> *member_vec)
1580 {
1581   unsigned len = member_vec->length ();
1582   unsigned store = 0;
1583
1584   if (!len)
1585     return;
1586
1587   tree name = OVL_NAME ((*member_vec)[0]);
1588   for (unsigned jx, ix = 0; ix < len; ix = jx)
1589     {
1590       tree current = NULL_TREE;
1591       tree to_type = NULL_TREE;
1592       tree to_using = NULL_TREE;
1593       tree marker = NULL_TREE;
1594
1595       for (jx = ix; jx < len; jx++)
1596         {
1597           tree next = (*member_vec)[jx];
1598           if (jx != ix)
1599             {
1600               tree next_name = OVL_NAME (next);
1601               if (next_name != name)
1602                 {
1603                   name = next_name;
1604                   break;
1605                 }
1606             }
1607
1608           if (IDENTIFIER_CONV_OP_P (name))
1609             {
1610               marker = next;
1611               next = OVL_CHAIN (next);
1612             }
1613
1614           if (TREE_CODE (next) == USING_DECL)
1615             {
1616               if (IDENTIFIER_CTOR_P (name))
1617                 /* Dependent inherited ctor. */
1618                 continue;
1619
1620               next = strip_using_decl (next);
1621               if (TREE_CODE (next) == USING_DECL)
1622                 {
1623                   to_using = next;
1624                   continue;
1625                 }
1626
1627               if (is_overloaded_fn (next))
1628                 continue;
1629             }
1630
1631           if (DECL_DECLARES_TYPE_P (next))
1632             {
1633               to_type = next;
1634               continue;
1635             }
1636
1637           if (!current)
1638             current = next;
1639         }
1640
1641       if (to_using)
1642         {
1643           if (!current)
1644             current = to_using;
1645           else
1646             current = ovl_make (to_using, current);
1647         }
1648
1649       if (to_type)
1650         {
1651           if (!current)
1652             current = to_type;
1653           else
1654             current = stat_hack (current, to_type);
1655         }
1656
1657       if (current)
1658         {
1659           if (marker)
1660             {
1661               OVL_CHAIN (marker) = current;
1662               current = marker;
1663             }
1664           (*member_vec)[store++] = current;
1665         }
1666     }
1667
1668   while (store++ < len)
1669     member_vec->pop ();
1670 }
1671
1672 /* Add the non-function members to CLASSTYPE_MEMBER_VEC.  If there is
1673    no existing MEMBER_VEC and fewer than 8 fields, do nothing.  We
1674    know there must be at least 1 field -- the self-reference
1675    TYPE_DECL, except for anon aggregates, which will have at least
1676    one field.  */
1677
1678 void 
1679 set_class_bindings (tree klass, unsigned extra)
1680 {
1681   unsigned n_fields = count_class_fields (klass);
1682   vec<tree, va_gc> *member_vec = CLASSTYPE_MEMBER_VEC (klass);
1683
1684   if (member_vec || n_fields >= 8)
1685     {
1686       /* Append the new fields.  */
1687       vec_safe_reserve_exact (member_vec, extra + n_fields);
1688       member_vec_append_class_fields (member_vec, klass);
1689     }
1690
1691   if (member_vec)
1692     {
1693       CLASSTYPE_MEMBER_VEC (klass) = member_vec;
1694       member_vec->qsort (member_name_cmp);
1695       member_vec_dedup (member_vec);
1696     }
1697 }
1698
1699 /* Insert lately defined enum ENUMTYPE into KLASS for the sorted case.  */
1700
1701 void
1702 insert_late_enum_def_bindings (tree klass, tree enumtype)
1703 {
1704   int n_fields;
1705   vec<tree, va_gc> *member_vec = CLASSTYPE_MEMBER_VEC (klass);
1706
1707   /* The enum bindings will already be on the TYPE_FIELDS, so don't
1708      count them twice.  */
1709   if (!member_vec)
1710     n_fields = count_class_fields (klass);
1711   else
1712     n_fields = list_length (TYPE_VALUES (enumtype));
1713
1714   if (member_vec || n_fields >= 8)
1715     {
1716       vec_safe_reserve_exact (member_vec, n_fields);
1717       if (CLASSTYPE_MEMBER_VEC (klass))
1718         member_vec_append_enum_values (member_vec, enumtype);
1719       else
1720         member_vec_append_class_fields (member_vec, klass);
1721       CLASSTYPE_MEMBER_VEC (klass) = member_vec;
1722       member_vec->qsort (member_name_cmp);
1723       member_vec_dedup (member_vec);
1724     }
1725 }
1726
1727 /* Compute the chain index of a binding_entry given the HASH value of its
1728    name and the total COUNT of chains.  COUNT is assumed to be a power
1729    of 2.  */
1730
1731 #define ENTRY_INDEX(HASH, COUNT) (((HASH) >> 3) & ((COUNT) - 1))
1732
1733 /* A free list of "binding_entry"s awaiting for re-use.  */
1734
1735 static GTY((deletable)) binding_entry free_binding_entry = NULL;
1736
1737 /* The binding oracle; see cp-tree.h.  */
1738
1739 cp_binding_oracle_function *cp_binding_oracle;
1740
1741 /* If we have a binding oracle, ask it for all namespace-scoped
1742    definitions of NAME.  */
1743
1744 static inline void
1745 query_oracle (tree name)
1746 {
1747   if (!cp_binding_oracle)
1748     return;
1749
1750   /* LOOKED_UP holds the set of identifiers that we have already
1751      looked up with the oracle.  */
1752   static hash_set<tree> looked_up;
1753   if (looked_up.add (name))
1754     return;
1755
1756   cp_binding_oracle (CP_ORACLE_IDENTIFIER, name);
1757 }
1758
1759 /* Create a binding_entry object for (NAME, TYPE).  */
1760
1761 static inline binding_entry
1762 binding_entry_make (tree name, tree type)
1763 {
1764   binding_entry entry;
1765
1766   if (free_binding_entry)
1767     {
1768       entry = free_binding_entry;
1769       free_binding_entry = entry->chain;
1770     }
1771   else
1772     entry = ggc_alloc<binding_entry_s> ();
1773
1774   entry->name = name;
1775   entry->type = type;
1776   entry->chain = NULL;
1777
1778   return entry;
1779 }
1780
1781 /* Put ENTRY back on the free list.  */
1782 #if 0
1783 static inline void
1784 binding_entry_free (binding_entry entry)
1785 {
1786   entry->name = NULL;
1787   entry->type = NULL;
1788   entry->chain = free_binding_entry;
1789   free_binding_entry = entry;
1790 }
1791 #endif
1792
1793 /* The datatype used to implement the mapping from names to types at
1794    a given scope.  */
1795 struct GTY(()) binding_table_s {
1796   /* Array of chains of "binding_entry"s  */
1797   binding_entry * GTY((length ("%h.chain_count"))) chain;
1798
1799   /* The number of chains in this table.  This is the length of the
1800      member "chain" considered as an array.  */
1801   size_t chain_count;
1802
1803   /* Number of "binding_entry"s in this table.  */
1804   size_t entry_count;
1805 };
1806
1807 /* Construct TABLE with an initial CHAIN_COUNT.  */
1808
1809 static inline void
1810 binding_table_construct (binding_table table, size_t chain_count)
1811 {
1812   table->chain_count = chain_count;
1813   table->entry_count = 0;
1814   table->chain = ggc_cleared_vec_alloc<binding_entry> (table->chain_count);
1815 }
1816
1817 /* Make TABLE's entries ready for reuse.  */
1818 #if 0
1819 static void
1820 binding_table_free (binding_table table)
1821 {
1822   size_t i;
1823   size_t count;
1824
1825   if (table == NULL)
1826     return;
1827
1828   for (i = 0, count = table->chain_count; i < count; ++i)
1829     {
1830       binding_entry temp = table->chain[i];
1831       while (temp != NULL)
1832         {
1833           binding_entry entry = temp;
1834           temp = entry->chain;
1835           binding_entry_free (entry);
1836         }
1837       table->chain[i] = NULL;
1838     }
1839   table->entry_count = 0;
1840 }
1841 #endif
1842
1843 /* Allocate a table with CHAIN_COUNT, assumed to be a power of two.  */
1844
1845 static inline binding_table
1846 binding_table_new (size_t chain_count)
1847 {
1848   binding_table table = ggc_alloc<binding_table_s> ();
1849   table->chain = NULL;
1850   binding_table_construct (table, chain_count);
1851   return table;
1852 }
1853
1854 /* Expand TABLE to twice its current chain_count.  */
1855
1856 static void
1857 binding_table_expand (binding_table table)
1858 {
1859   const size_t old_chain_count = table->chain_count;
1860   const size_t old_entry_count = table->entry_count;
1861   const size_t new_chain_count = 2 * old_chain_count;
1862   binding_entry *old_chains = table->chain;
1863   size_t i;
1864
1865   binding_table_construct (table, new_chain_count);
1866   for (i = 0; i < old_chain_count; ++i)
1867     {
1868       binding_entry entry = old_chains[i];
1869       for (; entry != NULL; entry = old_chains[i])
1870         {
1871           const unsigned int hash = IDENTIFIER_HASH_VALUE (entry->name);
1872           const size_t j = ENTRY_INDEX (hash, new_chain_count);
1873
1874           old_chains[i] = entry->chain;
1875           entry->chain = table->chain[j];
1876           table->chain[j] = entry;
1877         }
1878     }
1879   table->entry_count = old_entry_count;
1880 }
1881
1882 /* Insert a binding for NAME to TYPE into TABLE.  */
1883
1884 static void
1885 binding_table_insert (binding_table table, tree name, tree type)
1886 {
1887   const unsigned int hash = IDENTIFIER_HASH_VALUE (name);
1888   const size_t i = ENTRY_INDEX (hash, table->chain_count);
1889   binding_entry entry = binding_entry_make (name, type);
1890
1891   entry->chain = table->chain[i];
1892   table->chain[i] = entry;
1893   ++table->entry_count;
1894
1895   if (3 * table->chain_count < 5 * table->entry_count)
1896     binding_table_expand (table);
1897 }
1898
1899 /* Return the binding_entry, if any, that maps NAME.  */
1900
1901 binding_entry
1902 binding_table_find (binding_table table, tree name)
1903 {
1904   const unsigned int hash = IDENTIFIER_HASH_VALUE (name);
1905   binding_entry entry = table->chain[ENTRY_INDEX (hash, table->chain_count)];
1906
1907   while (entry != NULL && entry->name != name)
1908     entry = entry->chain;
1909
1910   return entry;
1911 }
1912
1913 /* Apply PROC -- with DATA -- to all entries in TABLE.  */
1914
1915 void
1916 binding_table_foreach (binding_table table, bt_foreach_proc proc, void *data)
1917 {
1918   size_t chain_count;
1919   size_t i;
1920
1921   if (!table)
1922     return;
1923
1924   chain_count = table->chain_count;
1925   for (i = 0; i < chain_count; ++i)
1926     {
1927       binding_entry entry = table->chain[i];
1928       for (; entry != NULL; entry = entry->chain)
1929         proc (entry, data);
1930     }
1931 }
1932 \f
1933 #ifndef ENABLE_SCOPE_CHECKING
1934 #  define ENABLE_SCOPE_CHECKING 0
1935 #else
1936 #  define ENABLE_SCOPE_CHECKING 1
1937 #endif
1938
1939 /* A free list of "cxx_binding"s, connected by their PREVIOUS.  */
1940
1941 static GTY((deletable)) cxx_binding *free_bindings;
1942
1943 /* Initialize VALUE and TYPE field for BINDING, and set the PREVIOUS
1944    field to NULL.  */
1945
1946 static inline void
1947 cxx_binding_init (cxx_binding *binding, tree value, tree type)
1948 {
1949   binding->value = value;
1950   binding->type = type;
1951   binding->previous = NULL;
1952 }
1953
1954 /* (GC)-allocate a binding object with VALUE and TYPE member initialized.  */
1955
1956 static cxx_binding *
1957 cxx_binding_make (tree value, tree type)
1958 {
1959   cxx_binding *binding;
1960   if (free_bindings)
1961     {
1962       binding = free_bindings;
1963       free_bindings = binding->previous;
1964     }
1965   else
1966     binding = ggc_alloc<cxx_binding> ();
1967
1968   cxx_binding_init (binding, value, type);
1969
1970   return binding;
1971 }
1972
1973 /* Put BINDING back on the free list.  */
1974
1975 static inline void
1976 cxx_binding_free (cxx_binding *binding)
1977 {
1978   binding->scope = NULL;
1979   binding->previous = free_bindings;
1980   free_bindings = binding;
1981 }
1982
1983 /* Create a new binding for NAME (with the indicated VALUE and TYPE
1984    bindings) in the class scope indicated by SCOPE.  */
1985
1986 static cxx_binding *
1987 new_class_binding (tree name, tree value, tree type, cp_binding_level *scope)
1988 {
1989   cp_class_binding cb = {cxx_binding_make (value, type), name};
1990   cxx_binding *binding = cb.base;
1991   vec_safe_push (scope->class_shadowed, cb);
1992   binding->scope = scope;
1993   return binding;
1994 }
1995
1996 /* Make DECL the innermost binding for ID.  The LEVEL is the binding
1997    level at which this declaration is being bound.  */
1998
1999 void
2000 push_binding (tree id, tree decl, cp_binding_level* level)
2001 {
2002   cxx_binding *binding;
2003
2004   if (level != class_binding_level)
2005     {
2006       binding = cxx_binding_make (decl, NULL_TREE);
2007       binding->scope = level;
2008     }
2009   else
2010     binding = new_class_binding (id, decl, /*type=*/NULL_TREE, level);
2011
2012   /* Now, fill in the binding information.  */
2013   binding->previous = IDENTIFIER_BINDING (id);
2014   INHERITED_VALUE_BINDING_P (binding) = 0;
2015   LOCAL_BINDING_P (binding) = (level != class_binding_level);
2016
2017   /* And put it on the front of the list of bindings for ID.  */
2018   IDENTIFIER_BINDING (id) = binding;
2019 }
2020
2021 /* Remove the binding for DECL which should be the innermost binding
2022    for ID.  */
2023
2024 void
2025 pop_local_binding (tree id, tree decl)
2026 {
2027   cxx_binding *binding;
2028
2029   if (id == NULL_TREE)
2030     /* It's easiest to write the loops that call this function without
2031        checking whether or not the entities involved have names.  We
2032        get here for such an entity.  */
2033     return;
2034
2035   /* Get the innermost binding for ID.  */
2036   binding = IDENTIFIER_BINDING (id);
2037
2038   /* The name should be bound.  */
2039   gcc_assert (binding != NULL);
2040
2041   /* The DECL will be either the ordinary binding or the type
2042      binding for this identifier.  Remove that binding.  */
2043   if (binding->value == decl)
2044     binding->value = NULL_TREE;
2045   else
2046     {
2047       gcc_assert (binding->type == decl);
2048       binding->type = NULL_TREE;
2049     }
2050
2051   if (!binding->value && !binding->type)
2052     {
2053       /* We're completely done with the innermost binding for this
2054          identifier.  Unhook it from the list of bindings.  */
2055       IDENTIFIER_BINDING (id) = binding->previous;
2056
2057       /* Add it to the free list.  */
2058       cxx_binding_free (binding);
2059     }
2060 }
2061
2062 /* Remove the bindings for the decls of the current level and leave
2063    the current scope.  */
2064
2065 void
2066 pop_bindings_and_leave_scope (void)
2067 {
2068   for (tree t = get_local_decls (); t; t = DECL_CHAIN (t))
2069     {
2070       tree decl = TREE_CODE (t) == TREE_LIST ? TREE_VALUE (t) : t;
2071       tree name = OVL_NAME (decl);
2072
2073       pop_local_binding (name, decl);
2074     }
2075
2076   leave_scope ();
2077 }
2078
2079 /* Strip non dependent using declarations. If DECL is dependent,
2080    surreptitiously create a typename_type and return it.  */
2081
2082 tree
2083 strip_using_decl (tree decl)
2084 {
2085   if (decl == NULL_TREE)
2086     return NULL_TREE;
2087
2088   while (TREE_CODE (decl) == USING_DECL && !DECL_DEPENDENT_P (decl))
2089     decl = USING_DECL_DECLS (decl);
2090
2091   if (TREE_CODE (decl) == USING_DECL && DECL_DEPENDENT_P (decl)
2092       && USING_DECL_TYPENAME_P (decl))
2093     {
2094       /* We have found a type introduced by a using
2095          declaration at class scope that refers to a dependent
2096          type.
2097              
2098          using typename :: [opt] nested-name-specifier unqualified-id ;
2099       */
2100       decl = make_typename_type (TREE_TYPE (decl),
2101                                  DECL_NAME (decl),
2102                                  typename_type, tf_error);
2103       if (decl != error_mark_node)
2104         decl = TYPE_NAME (decl);
2105     }
2106
2107   return decl;
2108 }
2109
2110 /* Return true if OVL is an overload for an anticipated builtin.  */
2111
2112 static bool
2113 anticipated_builtin_p (tree ovl)
2114 {
2115   if (TREE_CODE (ovl) != OVERLOAD)
2116     return false;
2117
2118   if (!OVL_HIDDEN_P (ovl))
2119     return false;
2120
2121   tree fn = OVL_FUNCTION (ovl);
2122   gcc_checking_assert (DECL_ANTICIPATED (fn));
2123
2124   if (DECL_HIDDEN_FRIEND_P (fn))
2125     return false;
2126
2127   return true;
2128 }
2129
2130 /* BINDING records an existing declaration for a name in the current scope.
2131    But, DECL is another declaration for that same identifier in the
2132    same scope.  This is the `struct stat' hack whereby a non-typedef
2133    class name or enum-name can be bound at the same level as some other
2134    kind of entity.
2135    3.3.7/1
2136
2137      A class name (9.1) or enumeration name (7.2) can be hidden by the
2138      name of an object, function, or enumerator declared in the same scope.
2139      If a class or enumeration name and an object, function, or enumerator
2140      are declared in the same scope (in any order) with the same name, the
2141      class or enumeration name is hidden wherever the object, function, or
2142      enumerator name is visible.
2143
2144    It's the responsibility of the caller to check that
2145    inserting this name is valid here.  Returns nonzero if the new binding
2146    was successful.  */
2147
2148 static bool
2149 supplement_binding_1 (cxx_binding *binding, tree decl)
2150 {
2151   tree bval = binding->value;
2152   bool ok = true;
2153   tree target_bval = strip_using_decl (bval);
2154   tree target_decl = strip_using_decl (decl);
2155
2156   if (TREE_CODE (target_decl) == TYPE_DECL && DECL_ARTIFICIAL (target_decl)
2157       && target_decl != target_bval
2158       && (TREE_CODE (target_bval) != TYPE_DECL
2159           /* We allow pushing an enum multiple times in a class
2160              template in order to handle late matching of underlying
2161              type on an opaque-enum-declaration followed by an
2162              enum-specifier.  */
2163           || (processing_template_decl
2164               && TREE_CODE (TREE_TYPE (target_decl)) == ENUMERAL_TYPE
2165               && TREE_CODE (TREE_TYPE (target_bval)) == ENUMERAL_TYPE
2166               && (dependent_type_p (ENUM_UNDERLYING_TYPE
2167                                     (TREE_TYPE (target_decl)))
2168                   || dependent_type_p (ENUM_UNDERLYING_TYPE
2169                                        (TREE_TYPE (target_bval)))))))
2170     /* The new name is the type name.  */
2171     binding->type = decl;
2172   else if (/* TARGET_BVAL is null when push_class_level_binding moves
2173               an inherited type-binding out of the way to make room
2174               for a new value binding.  */
2175            !target_bval
2176            /* TARGET_BVAL is error_mark_node when TARGET_DECL's name
2177               has been used in a non-class scope prior declaration.
2178               In that case, we should have already issued a
2179               diagnostic; for graceful error recovery purpose, pretend
2180               this was the intended declaration for that name.  */
2181            || target_bval == error_mark_node
2182            /* If TARGET_BVAL is anticipated but has not yet been
2183               declared, pretend it is not there at all.  */
2184            || anticipated_builtin_p (target_bval))
2185     binding->value = decl;
2186   else if (TREE_CODE (target_bval) == TYPE_DECL
2187            && DECL_ARTIFICIAL (target_bval)
2188            && target_decl != target_bval
2189            && (TREE_CODE (target_decl) != TYPE_DECL
2190                || same_type_p (TREE_TYPE (target_decl),
2191                                TREE_TYPE (target_bval))))
2192     {
2193       /* The old binding was a type name.  It was placed in
2194          VALUE field because it was thought, at the point it was
2195          declared, to be the only entity with such a name.  Move the
2196          type name into the type slot; it is now hidden by the new
2197          binding.  */
2198       binding->type = bval;
2199       binding->value = decl;
2200       binding->value_is_inherited = false;
2201     }
2202   else if (TREE_CODE (target_bval) == TYPE_DECL
2203            && TREE_CODE (target_decl) == TYPE_DECL
2204            && DECL_NAME (target_decl) == DECL_NAME (target_bval)
2205            && binding->scope->kind != sk_class
2206            && (same_type_p (TREE_TYPE (target_decl), TREE_TYPE (target_bval))
2207                /* If either type involves template parameters, we must
2208                   wait until instantiation.  */
2209                || uses_template_parms (TREE_TYPE (target_decl))
2210                || uses_template_parms (TREE_TYPE (target_bval))))
2211     /* We have two typedef-names, both naming the same type to have
2212        the same name.  In general, this is OK because of:
2213
2214          [dcl.typedef]
2215
2216          In a given scope, a typedef specifier can be used to redefine
2217          the name of any type declared in that scope to refer to the
2218          type to which it already refers.
2219
2220        However, in class scopes, this rule does not apply due to the
2221        stricter language in [class.mem] prohibiting redeclarations of
2222        members.  */
2223     ok = false;
2224   /* There can be two block-scope declarations of the same variable,
2225      so long as they are `extern' declarations.  However, there cannot
2226      be two declarations of the same static data member:
2227
2228        [class.mem]
2229
2230        A member shall not be declared twice in the
2231        member-specification.  */
2232   else if (VAR_P (target_decl)
2233            && VAR_P (target_bval)
2234            && DECL_EXTERNAL (target_decl) && DECL_EXTERNAL (target_bval)
2235            && !DECL_CLASS_SCOPE_P (target_decl))
2236     {
2237       duplicate_decls (decl, binding->value, /*newdecl_is_friend=*/false);
2238       ok = false;
2239     }
2240   else if (TREE_CODE (decl) == NAMESPACE_DECL
2241            && TREE_CODE (bval) == NAMESPACE_DECL
2242            && DECL_NAMESPACE_ALIAS (decl)
2243            && DECL_NAMESPACE_ALIAS (bval)
2244            && ORIGINAL_NAMESPACE (bval) == ORIGINAL_NAMESPACE (decl))
2245     /* [namespace.alias]
2246
2247       In a declarative region, a namespace-alias-definition can be
2248       used to redefine a namespace-alias declared in that declarative
2249       region to refer only to the namespace to which it already
2250       refers.  */
2251     ok = false;
2252   else
2253     {
2254       if (!error_operand_p (bval))
2255         diagnose_name_conflict (decl, bval);
2256       ok = false;
2257     }
2258
2259   return ok;
2260 }
2261
2262 /* Diagnose a name conflict between DECL and BVAL.  */
2263
2264 static void
2265 diagnose_name_conflict (tree decl, tree bval)
2266 {
2267   if (TREE_CODE (decl) == TREE_CODE (bval)
2268       && TREE_CODE (decl) != NAMESPACE_DECL
2269       && !DECL_DECLARES_FUNCTION_P (decl)
2270       && (TREE_CODE (decl) != TYPE_DECL
2271           || DECL_ARTIFICIAL (decl) == DECL_ARTIFICIAL (bval))
2272       && CP_DECL_CONTEXT (decl) == CP_DECL_CONTEXT (bval))
2273     error ("redeclaration of %q#D", decl);
2274   else
2275     error ("%q#D conflicts with a previous declaration", decl);
2276
2277   inform (location_of (bval), "previous declaration %q#D", bval);
2278 }
2279
2280 /* Wrapper for supplement_binding_1.  */
2281
2282 static bool
2283 supplement_binding (cxx_binding *binding, tree decl)
2284 {
2285   bool ret;
2286   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
2287   ret = supplement_binding_1 (binding, decl);
2288   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
2289   return ret;
2290 }
2291
2292 /* Replace BINDING's current value on its scope's name list with
2293    NEWVAL.  */
2294
2295 static void
2296 update_local_overload (cxx_binding *binding, tree newval)
2297 {
2298   tree *d;
2299
2300   for (d = &binding->scope->names; ; d = &TREE_CHAIN (*d))
2301     if (*d == binding->value)
2302       {
2303         /* Stitch new list node in.  */
2304         *d = tree_cons (NULL_TREE, NULL_TREE, TREE_CHAIN (*d));
2305         break;
2306       }
2307     else if (TREE_CODE (*d) == TREE_LIST && TREE_VALUE (*d) == binding->value)
2308       break;
2309
2310   TREE_VALUE (*d) = newval;
2311 }
2312
2313 /* Compares the parameter-type-lists of ONE and TWO and
2314    returns false if they are different.  If the DECLs are template
2315    functions, the return types and the template parameter lists are
2316    compared too (DR 565).  */
2317
2318 static bool
2319 matching_fn_p (tree one, tree two)
2320 {
2321   if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (one)),
2322                   TYPE_ARG_TYPES (TREE_TYPE (two))))
2323     return false;
2324
2325   if (TREE_CODE (one) == TEMPLATE_DECL
2326       && TREE_CODE (two) == TEMPLATE_DECL)
2327     {
2328       /* Compare template parms.  */
2329       if (!comp_template_parms (DECL_TEMPLATE_PARMS (one),
2330                                 DECL_TEMPLATE_PARMS (two)))
2331         return false;
2332
2333       /* And return type.  */
2334       if (!same_type_p (TREE_TYPE (TREE_TYPE (one)),
2335                         TREE_TYPE (TREE_TYPE (two))))
2336         return false;
2337     }
2338
2339   return true;
2340 }
2341
2342 /* Push DECL into nonclass LEVEL BINDING or SLOT.  OLD is the current
2343    binding value (possibly with anticipated builtins stripped).
2344    Diagnose conflicts and return updated decl.  */
2345
2346 static tree
2347 update_binding (cp_binding_level *level, cxx_binding *binding, tree *slot,
2348                 tree old, tree decl, bool is_friend)
2349 {
2350   tree to_val = decl;
2351   tree old_type = slot ? MAYBE_STAT_TYPE (*slot) : binding->type;
2352   tree to_type = old_type;
2353
2354   gcc_assert (level->kind == sk_namespace ? !binding
2355               : level->kind != sk_class && !slot);
2356   if (old == error_mark_node)
2357     old = NULL_TREE;
2358
2359   if (TREE_CODE (decl) == TYPE_DECL && DECL_ARTIFICIAL (decl))
2360     {
2361       tree other = to_type;
2362
2363       if (old && TREE_CODE (old) == TYPE_DECL && DECL_ARTIFICIAL (old))
2364         other = old;
2365
2366       /* Pushing an artificial typedef.  See if this matches either
2367          the type slot or the old value slot.  */
2368       if (!other)
2369         ;
2370       else if (same_type_p (TREE_TYPE (other), TREE_TYPE (decl)))
2371         /* Two artificial decls to same type.  Do nothing.  */
2372         return other;
2373       else
2374         goto conflict;
2375
2376       if (old)
2377         {
2378           /* Slide decl into the type slot, keep old unaltered  */
2379           to_type = decl;
2380           to_val = old;
2381           goto done;
2382         }
2383     }
2384
2385   if (old && TREE_CODE (old) == TYPE_DECL && DECL_ARTIFICIAL (old))
2386     {
2387       /* Slide old into the type slot.  */
2388       to_type = old;
2389       old = NULL_TREE;
2390     }
2391
2392   if (DECL_DECLARES_FUNCTION_P (decl))
2393     {
2394       if (!old)
2395         ;
2396       else if (OVL_P (old))
2397         {
2398           for (ovl_iterator iter (old); iter; ++iter)
2399             {
2400               tree fn = *iter;
2401
2402               if (iter.using_p () && matching_fn_p (fn, decl))
2403                 {
2404                   /* If a function declaration in namespace scope or
2405                      block scope has the same name and the same
2406                      parameter-type- list (8.3.5) as a function
2407                      introduced by a using-declaration, and the
2408                      declarations do not declare the same function,
2409                      the program is ill-formed.  [namespace.udecl]/14 */
2410                   if (tree match = duplicate_decls (decl, fn, is_friend))
2411                     return match;
2412                   else
2413                     /* FIXME: To preserve existing error behavior, we
2414                        still push the decl.  This might change.  */
2415                     diagnose_name_conflict (decl, fn);
2416                 }
2417             }
2418         }
2419       else
2420         goto conflict;
2421
2422       if (to_type != old_type
2423           && warn_shadow
2424           && MAYBE_CLASS_TYPE_P (TREE_TYPE (to_type))
2425           && !(DECL_IN_SYSTEM_HEADER (decl)
2426                && DECL_IN_SYSTEM_HEADER (to_type)))
2427         warning (OPT_Wshadow, "%q#D hides constructor for %q#D",
2428                  decl, to_type);
2429
2430       to_val = ovl_insert (decl, old);
2431     }
2432   else if (!old)
2433     ;
2434   else if (TREE_CODE (old) != TREE_CODE (decl))
2435     /* Different kinds of decls conflict.  */
2436     goto conflict;
2437   else if (TREE_CODE (old) == TYPE_DECL)
2438     {
2439       if (same_type_p (TREE_TYPE (old), TREE_TYPE (decl)))
2440         /* Two type decls to the same type.  Do nothing.  */
2441         return old;
2442       else
2443         goto conflict;
2444     }
2445   else if (TREE_CODE (old) == NAMESPACE_DECL)
2446     {
2447       /* Two maybe-aliased namespaces.  If they're to the same target
2448          namespace, that's ok.  */
2449       if (ORIGINAL_NAMESPACE (old) != ORIGINAL_NAMESPACE (decl))
2450         goto conflict;
2451
2452       /* The new one must be an alias at this point.  */
2453       gcc_assert (DECL_NAMESPACE_ALIAS (decl));
2454       return old;
2455     }
2456   else if (TREE_CODE (old) == VAR_DECL)
2457     {
2458       /* There can be two block-scope declarations of the same
2459          variable, so long as they are `extern' declarations.  */
2460       if (!DECL_EXTERNAL (old) || !DECL_EXTERNAL (decl))
2461         goto conflict;
2462       else if (tree match = duplicate_decls (decl, old, false))
2463         return match;
2464       else
2465         goto conflict;
2466     }
2467   else
2468     {
2469     conflict:
2470       diagnose_name_conflict (decl, old);
2471       to_val = NULL_TREE;
2472     }
2473
2474  done:
2475   if (to_val)
2476     {
2477       if (level->kind == sk_namespace || to_type == decl || to_val == decl)
2478         add_decl_to_level (level, decl);
2479       else
2480         {
2481           gcc_checking_assert (binding->value && OVL_P (binding->value));
2482           update_local_overload (binding, to_val);
2483         }
2484
2485       if (slot)
2486         {
2487           if (STAT_HACK_P (*slot))
2488             {
2489               STAT_TYPE (*slot) = to_type;
2490               STAT_DECL (*slot) = to_val;
2491             }
2492           else if (to_type)
2493             *slot = stat_hack (to_val, to_type);
2494           else
2495             *slot = to_val;
2496         }
2497       else
2498         {
2499           binding->type = to_type;
2500           binding->value = to_val;
2501         }
2502     }
2503
2504   return decl;
2505 }
2506
2507 /* Table of identifiers to extern C declarations (or LISTS thereof).  */
2508
2509 static GTY(()) hash_table<named_decl_hash> *extern_c_decls;
2510
2511 /* DECL has C linkage. If we have an existing instance, make sure the
2512    new one is compatible.  Make sure it has the same exception
2513    specification [7.5, 7.6].  Add DECL to the map.  */
2514
2515 static void
2516 check_extern_c_conflict (tree decl)
2517 {
2518   /* Ignore artificial or system header decls.  */
2519   if (DECL_ARTIFICIAL (decl) || DECL_IN_SYSTEM_HEADER (decl))
2520     return;
2521
2522   /* This only applies to decls at namespace scope.  */
2523   if (!DECL_NAMESPACE_SCOPE_P (decl))
2524     return;
2525
2526   if (!extern_c_decls)
2527     extern_c_decls = hash_table<named_decl_hash>::create_ggc (127);
2528
2529   tree *slot = extern_c_decls
2530     ->find_slot_with_hash (DECL_NAME (decl),
2531                            IDENTIFIER_HASH_VALUE (DECL_NAME (decl)), INSERT);
2532   if (tree old = *slot)
2533     {
2534       if (TREE_CODE (old) == OVERLOAD)
2535         old = OVL_FUNCTION (old);
2536
2537       int mismatch = 0;
2538       if (DECL_CONTEXT (old) == DECL_CONTEXT (decl))
2539         ; /* If they're in the same context, we'll have already complained
2540              about a (possible) mismatch, when inserting the decl.  */
2541       else if (!decls_match (decl, old))
2542         mismatch = 1;
2543       else if (TREE_CODE (decl) == FUNCTION_DECL
2544                && !comp_except_specs (TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old)),
2545                                       TYPE_RAISES_EXCEPTIONS (TREE_TYPE (decl)),
2546                                       ce_normal))
2547         mismatch = -1;
2548       else if (DECL_ASSEMBLER_NAME_SET_P (old))
2549         SET_DECL_ASSEMBLER_NAME (decl, DECL_ASSEMBLER_NAME (old));
2550
2551       if (mismatch)
2552         {
2553           pedwarn (input_location, 0,
2554                    "conflicting C language linkage declaration %q#D", decl);
2555           inform (DECL_SOURCE_LOCATION (old),
2556                   "previous declaration %q#D", old);
2557           if (mismatch < 0)
2558             inform (input_location,
2559                     "due to different exception specifications");
2560         }
2561       else
2562         {
2563           if (old == *slot)
2564             /* The hash table expects OVERLOADS, so construct one with
2565                OLD as both the function and the chain.  This allocate
2566                an excess OVERLOAD node, but it's rare to have multiple
2567                extern "C" decls of the same name.  And we save
2568                complicating the hash table logic (which is used
2569                elsewhere).  */
2570             *slot = ovl_make (old, old);
2571
2572           slot = &OVL_CHAIN (*slot);
2573
2574           /* Chain it on for c_linkage_binding's use.  */
2575           *slot = tree_cons (NULL_TREE, decl, *slot);
2576         }
2577     }
2578   else
2579     *slot = decl;
2580 }
2581
2582 /* Returns a list of C-linkage decls with the name NAME.  Used in
2583    c-family/c-pragma.c to implement redefine_extname pragma.  */
2584
2585 tree
2586 c_linkage_bindings (tree name)
2587 {
2588   if (extern_c_decls)
2589     if (tree *slot = extern_c_decls
2590         ->find_slot_with_hash (name, IDENTIFIER_HASH_VALUE (name), NO_INSERT))
2591       {
2592         tree result = *slot;
2593         if (TREE_CODE (result) == OVERLOAD)
2594           result = OVL_CHAIN (result);
2595         return result;
2596       }
2597
2598   return NULL_TREE;
2599 }
2600
2601 /* DECL is being declared at a local scope.  Emit suitable shadow
2602    warnings.  */
2603
2604 static void
2605 check_local_shadow (tree decl)
2606 {
2607   /* Don't complain about the parms we push and then pop
2608      while tentatively parsing a function declarator.  */
2609   if (TREE_CODE (decl) == PARM_DECL && !DECL_CONTEXT (decl))
2610     return;
2611
2612   /* Inline decls shadow nothing.  */
2613   if (DECL_FROM_INLINE (decl))
2614     return;
2615
2616   /* External decls are something else.  */
2617   if (DECL_EXTERNAL (decl))
2618     return;
2619
2620   tree old = NULL_TREE;
2621   cp_binding_level *old_scope = NULL;
2622   if (cxx_binding *binding = outer_binding (DECL_NAME (decl), NULL, true))
2623     {
2624       old = binding->value;
2625       old_scope = binding->scope;
2626     }
2627   while (old && VAR_P (old) && DECL_DEAD_FOR_LOCAL (old))
2628     old = DECL_SHADOWED_FOR_VAR (old);
2629
2630   tree shadowed = NULL_TREE;
2631   if (old
2632       && (TREE_CODE (old) == PARM_DECL
2633           || VAR_P (old)
2634           || (TREE_CODE (old) == TYPE_DECL
2635               && (!DECL_ARTIFICIAL (old)
2636                   || TREE_CODE (decl) == TYPE_DECL)))
2637       && (!DECL_ARTIFICIAL (decl)
2638           || DECL_IMPLICIT_TYPEDEF_P (decl)
2639           || (VAR_P (decl) && DECL_ANON_UNION_VAR_P (decl))))
2640     {
2641       /* DECL shadows a local thing possibly of interest.  */
2642
2643       /* Don't complain if it's from an enclosing function.  */
2644       if (DECL_CONTEXT (old) == current_function_decl
2645           && TREE_CODE (decl) != PARM_DECL
2646           && TREE_CODE (old) == PARM_DECL)
2647         {
2648           /* Go to where the parms should be and see if we find
2649              them there.  */
2650           cp_binding_level *b = current_binding_level->level_chain;
2651
2652           if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
2653             /* Skip the ctor/dtor cleanup level.  */
2654             b = b->level_chain;
2655
2656           /* ARM $8.3 */
2657           if (b->kind == sk_function_parms)
2658             {
2659               error ("declaration of %q#D shadows a parameter", decl);
2660               return;
2661             }
2662         }
2663
2664       /* The local structure or class can't use parameters of
2665          the containing function anyway.  */
2666       if (DECL_CONTEXT (old) != current_function_decl)
2667         {
2668           for (cp_binding_level *scope = current_binding_level;
2669                scope != old_scope; scope = scope->level_chain)
2670             if (scope->kind == sk_class
2671                 && !LAMBDA_TYPE_P (scope->this_entity))
2672               return;
2673         }
2674       /* Error if redeclaring a local declared in a
2675          init-statement or in the condition of an if or
2676          switch statement when the new declaration is in the
2677          outermost block of the controlled statement.
2678          Redeclaring a variable from a for or while condition is
2679          detected elsewhere.  */
2680       else if (VAR_P (old)
2681                && old_scope == current_binding_level->level_chain
2682                && (old_scope->kind == sk_cond || old_scope->kind == sk_for))
2683         {
2684           error ("redeclaration of %q#D", decl);
2685           inform (DECL_SOURCE_LOCATION (old),
2686                   "%q#D previously declared here", old);
2687           return;
2688         }
2689       /* C++11:
2690          3.3.3/3:  The name declared in an exception-declaration (...)
2691          shall not be redeclared in the outermost block of the handler.
2692          3.3.3/2:  A parameter name shall not be redeclared (...) in
2693          the outermost block of any handler associated with a
2694          function-try-block.
2695          3.4.1/15: The function parameter names shall not be redeclared
2696          in the exception-declaration nor in the outermost block of a
2697          handler for the function-try-block.  */
2698       else if ((TREE_CODE (old) == VAR_DECL
2699                 && old_scope == current_binding_level->level_chain
2700                 && old_scope->kind == sk_catch)
2701                || (TREE_CODE (old) == PARM_DECL
2702                    && (current_binding_level->kind == sk_catch
2703                        || current_binding_level->level_chain->kind == sk_catch)
2704                    && in_function_try_handler))
2705         {
2706           if (permerror (input_location, "redeclaration of %q#D", decl))
2707             inform (DECL_SOURCE_LOCATION (old),
2708                     "%q#D previously declared here", old);
2709           return;
2710         }
2711
2712       /* If '-Wshadow=compatible-local' is specified without other
2713          -Wshadow= flags, we will warn only when the type of the
2714          shadowing variable (DECL) can be converted to that of the
2715          shadowed parameter (OLD_LOCAL). The reason why we only check
2716          if DECL's type can be converted to OLD_LOCAL's type (but not the
2717          other way around) is because when users accidentally shadow a
2718          parameter, more than often they would use the variable
2719          thinking (mistakenly) it's still the parameter. It would be
2720          rare that users would use the variable in the place that
2721          expects the parameter but thinking it's a new decl.  */
2722
2723       enum opt_code warning_code;
2724       if (warn_shadow)
2725         warning_code = OPT_Wshadow;
2726       else if (warn_shadow_local)
2727         warning_code = OPT_Wshadow_local;
2728       else if (warn_shadow_compatible_local
2729                && (same_type_p (TREE_TYPE (old), TREE_TYPE (decl))
2730                    || (!dependent_type_p (TREE_TYPE (decl))
2731                        && !dependent_type_p (TREE_TYPE (old))
2732                        /* If the new decl uses auto, we don't yet know
2733                           its type (the old type cannot be using auto
2734                           at this point, without also being
2735                           dependent).  This is an indication we're
2736                           (now) doing the shadow checking too
2737                           early.  */
2738                        && !type_uses_auto (TREE_TYPE (decl))
2739                        && can_convert (TREE_TYPE (old), TREE_TYPE (decl),
2740                                        tf_none))))
2741         warning_code = OPT_Wshadow_compatible_local;
2742       else
2743         return;
2744
2745       const char *msg;
2746       if (TREE_CODE (old) == PARM_DECL)
2747         msg = "declaration of %q#D shadows a parameter";
2748       else if (is_capture_proxy (old))
2749         msg = "declaration of %qD shadows a lambda capture";
2750       else
2751         msg = "declaration of %qD shadows a previous local";
2752
2753       if (warning_at (input_location, warning_code, msg, decl))
2754         {
2755           shadowed = old;
2756           goto inform_shadowed;
2757         }
2758       return;
2759     }
2760
2761   if (!warn_shadow)
2762     return;
2763
2764   /* Don't warn for artificial things that are not implicit typedefs.  */
2765   if (DECL_ARTIFICIAL (decl) && !DECL_IMPLICIT_TYPEDEF_P (decl))
2766     return;
2767   
2768   if (nonlambda_method_basetype ())
2769     if (tree member = lookup_member (current_nonlambda_class_type (),
2770                                      DECL_NAME (decl), /*protect=*/0,
2771                                      /*want_type=*/false, tf_warning_or_error))
2772       {
2773         member = MAYBE_BASELINK_FUNCTIONS (member);
2774
2775         /* Warn if a variable shadows a non-function, or the variable
2776            is a function or a pointer-to-function.  */
2777         if (!OVL_P (member)
2778             || TREE_CODE (decl) == FUNCTION_DECL
2779             || TYPE_PTRFN_P (TREE_TYPE (decl))
2780             || TYPE_PTRMEMFUNC_P (TREE_TYPE (decl)))
2781           {
2782             if (warning_at (input_location, OPT_Wshadow,
2783                             "declaration of %qD shadows a member of %qT",
2784                             decl, current_nonlambda_class_type ())
2785                 && DECL_P (member))
2786               {
2787                 shadowed = member;
2788                 goto inform_shadowed;
2789               }
2790           }
2791         return;
2792       }
2793
2794   /* Now look for a namespace shadow.  */
2795   old = find_namespace_value (current_namespace, DECL_NAME (decl));
2796   if (old
2797       && (VAR_P (old)
2798           || (TREE_CODE (old) == TYPE_DECL
2799               && (!DECL_ARTIFICIAL (old)
2800                   || TREE_CODE (decl) == TYPE_DECL)))
2801       && !instantiating_current_function_p ())
2802     /* XXX shadow warnings in outer-more namespaces */
2803     {
2804       if (warning_at (input_location, OPT_Wshadow,
2805                       "declaration of %qD shadows a global declaration",
2806                       decl))
2807         {
2808           shadowed = old;
2809           goto inform_shadowed;
2810         }
2811       return;
2812     }
2813
2814   return;
2815
2816  inform_shadowed:
2817   inform (DECL_SOURCE_LOCATION (shadowed), "shadowed declaration is here");
2818 }
2819
2820 /* DECL is being pushed inside function CTX.  Set its context, if
2821    needed.  */
2822
2823 static void
2824 set_decl_context_in_fn (tree ctx, tree decl)
2825 {
2826   if (!DECL_CONTEXT (decl)
2827       /* A local declaration for a function doesn't constitute
2828          nesting.  */
2829       && TREE_CODE (decl) != FUNCTION_DECL
2830       /* A local declaration for an `extern' variable is in the
2831          scope of the current namespace, not the current
2832          function.  */
2833       && !(VAR_P (decl) && DECL_EXTERNAL (decl))
2834       /* When parsing the parameter list of a function declarator,
2835          don't set DECL_CONTEXT to an enclosing function.  When we
2836          push the PARM_DECLs in order to process the function body,
2837          current_binding_level->this_entity will be set.  */
2838       && !(TREE_CODE (decl) == PARM_DECL
2839            && current_binding_level->kind == sk_function_parms
2840            && current_binding_level->this_entity == NULL))
2841     DECL_CONTEXT (decl) = ctx;
2842
2843   /* If this is the declaration for a namespace-scope function,
2844      but the declaration itself is in a local scope, mark the
2845      declaration.  */
2846   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (decl))
2847     DECL_LOCAL_FUNCTION_P (decl) = 1;
2848 }
2849
2850 /* DECL is a local-scope decl with linkage.  SHADOWED is true if the
2851    name is already bound at the current level.
2852
2853    [basic.link] If there is a visible declaration of an entity with
2854    linkage having the same name and type, ignoring entities declared
2855    outside the innermost enclosing namespace scope, the block scope
2856    declaration declares that same entity and receives the linkage of
2857    the previous declaration.
2858
2859    Also, make sure that this decl matches any existing external decl
2860    in the enclosing namespace.  */
2861
2862 static void
2863 set_local_extern_decl_linkage (tree decl, bool shadowed)
2864 {
2865   tree ns_value = decl; /* Unique marker.  */
2866
2867   if (!shadowed)
2868     {
2869       tree loc_value = innermost_non_namespace_value (DECL_NAME (decl));
2870       if (!loc_value)
2871         {
2872           ns_value
2873             = find_namespace_value (current_namespace, DECL_NAME (decl));
2874           loc_value = ns_value;
2875         }
2876       if (loc_value == error_mark_node
2877           /* An ambiguous lookup.  */
2878           || (loc_value && TREE_CODE (loc_value) == TREE_LIST))
2879         loc_value = NULL_TREE;
2880
2881       for (ovl_iterator iter (loc_value); iter; ++iter)
2882         if (!iter.hidden_p ()
2883             && (TREE_STATIC (*iter) || DECL_EXTERNAL (*iter))
2884             && decls_match (*iter, decl))
2885           {
2886             /* The standard only says that the local extern inherits
2887                linkage from the previous decl; in particular, default
2888                args are not shared.  Add the decl into a hash table to
2889                make sure only the previous decl in this case is seen
2890                by the middle end.  */
2891             struct cxx_int_tree_map *h;
2892
2893             /* We inherit the outer decl's linkage.  But we're a
2894                different decl.  */
2895             TREE_PUBLIC (decl) = TREE_PUBLIC (*iter);
2896
2897             if (cp_function_chain->extern_decl_map == NULL)
2898               cp_function_chain->extern_decl_map
2899                 = hash_table<cxx_int_tree_map_hasher>::create_ggc (20);
2900
2901             h = ggc_alloc<cxx_int_tree_map> ();
2902             h->uid = DECL_UID (decl);
2903             h->to = *iter;
2904             cxx_int_tree_map **loc = cp_function_chain->extern_decl_map
2905               ->find_slot (h, INSERT);
2906             *loc = h;
2907             break;
2908           }
2909     }
2910
2911   if (TREE_PUBLIC (decl))
2912     {
2913       /* DECL is externally visible.  Make sure it matches a matching
2914          decl in the namespace scope.  We only really need to check
2915          this when inserting the decl, not when we find an existing
2916          match in the current scope.  However, in practice we're
2917          going to be inserting a new decl in the majority of cases --
2918          who writes multiple extern decls for the same thing in the
2919          same local scope?  Doing it here often avoids a duplicate
2920          namespace lookup.  */
2921
2922       /* Avoid repeating a lookup.  */
2923       if (ns_value == decl)
2924         ns_value = find_namespace_value (current_namespace, DECL_NAME (decl));
2925
2926       if (ns_value == error_mark_node
2927           || (ns_value && TREE_CODE (ns_value) == TREE_LIST))
2928         ns_value = NULL_TREE;
2929
2930       for (ovl_iterator iter (ns_value); iter; ++iter)
2931         {
2932           tree other = *iter;
2933
2934           if (!(TREE_PUBLIC (other) || DECL_EXTERNAL (other)))
2935             ; /* Not externally visible.   */
2936           else if (DECL_EXTERN_C_P (decl) && DECL_EXTERN_C_P (other))
2937             ; /* Both are extern "C", we'll check via that mechanism.  */
2938           else if (TREE_CODE (other) != TREE_CODE (decl)
2939                    || ((VAR_P (decl) || matching_fn_p (other, decl))
2940                        && !comptypes (TREE_TYPE (decl), TREE_TYPE (other),
2941                                       COMPARE_REDECLARATION)))
2942             {
2943               if (permerror (DECL_SOURCE_LOCATION (decl),
2944                              "local external declaration %q#D", decl))
2945                 inform (DECL_SOURCE_LOCATION (other),
2946                         "does not match previous declaration %q#D", other);
2947               break;
2948             }
2949         }
2950     }
2951 }
2952
2953 /* Record DECL as belonging to the current lexical scope.  Check for
2954    errors (such as an incompatible declaration for the same name
2955    already seen in the same scope).  IS_FRIEND is true if DECL is
2956    declared as a friend.
2957
2958    Returns either DECL or an old decl for the same name.  If an old
2959    decl is returned, it may have been smashed to agree with what DECL
2960    says.  */
2961
2962 static tree
2963 do_pushdecl (tree decl, bool is_friend)
2964 {
2965   if (decl == error_mark_node)
2966     return error_mark_node;
2967
2968   if (!DECL_TEMPLATE_PARM_P (decl) && current_function_decl)
2969     set_decl_context_in_fn (current_function_decl, decl);
2970
2971   /* The binding level we will be pushing into.  During local class
2972      pushing, we want to push to the containing scope.  */
2973   cp_binding_level *level = current_binding_level;
2974   while (level->kind == sk_class)
2975     level = level->level_chain;
2976
2977   /* An anonymous namespace has a NULL DECL_NAME, but we still want to
2978      insert it.  Other NULL-named decls, not so much.  */
2979   tree name = DECL_NAME (decl);
2980   if (name || TREE_CODE (decl) == NAMESPACE_DECL)
2981     {
2982       cxx_binding *binding = NULL; /* Local scope binding.  */
2983       tree ns = NULL_TREE; /* Searched namespace.  */
2984       tree *slot = NULL; /* Binding slot in namespace.  */
2985       tree old = NULL_TREE;
2986
2987       if (level->kind == sk_namespace)
2988         {
2989           /* We look in the decl's namespace for an existing
2990              declaration, even though we push into the current
2991              namespace.  */
2992           ns = (DECL_NAMESPACE_SCOPE_P (decl)
2993                 ? CP_DECL_CONTEXT (decl) : current_namespace);
2994           /* Create the binding, if this is current namespace, because
2995              that's where we'll be pushing anyway.  */
2996           slot = find_namespace_slot (ns, name, ns == current_namespace);
2997           if (slot)
2998             old = MAYBE_STAT_DECL (*slot);
2999         }
3000       else
3001         {
3002           binding = find_local_binding (level, name);
3003           if (binding)
3004             old = binding->value;
3005         }
3006
3007       if (current_function_decl && VAR_OR_FUNCTION_DECL_P (decl)
3008           && DECL_EXTERNAL (decl))
3009         set_local_extern_decl_linkage (decl, old != NULL_TREE);
3010
3011       if (old == error_mark_node)
3012         old = NULL_TREE;
3013
3014       for (ovl_iterator iter (old); iter; ++iter)
3015         if (iter.using_p ())
3016           ; /* Ignore using decls here.  */
3017         else if (tree match = duplicate_decls (decl, *iter, is_friend))
3018           {
3019             if (match == error_mark_node)
3020               ;
3021             else if (TREE_CODE (match) == TYPE_DECL)
3022               /* The IDENTIFIER will have the type referring to the
3023                  now-smashed TYPE_DECL, because ...?  Reset it.  */
3024               SET_IDENTIFIER_TYPE_VALUE (name, TREE_TYPE (match));
3025             else if (iter.hidden_p () && !DECL_HIDDEN_P (match))
3026               {
3027                 /* Unhiding a previously hidden decl.  */
3028                 tree head = iter.reveal_node (old);
3029                 if (head != old)
3030                   {
3031                     if (!ns)
3032                       {
3033                         update_local_overload (binding, head);
3034                         binding->value = head;
3035                       }
3036                     else if (STAT_HACK_P (*slot))
3037                       STAT_DECL (*slot) = head;
3038                     else
3039                       *slot = head;
3040                   }
3041                 if (DECL_EXTERN_C_P (match))
3042                   /* We need to check and register the decl now.  */
3043                   check_extern_c_conflict (match);
3044               }
3045             return match;
3046           }
3047
3048       /* We are pushing a new decl.  */
3049
3050       /* Skip a hidden builtin we failed to match already.  There can
3051          only be one.  */
3052       if (old && anticipated_builtin_p (old))
3053         old = OVL_CHAIN (old);
3054
3055       check_template_shadow (decl);
3056       bool visible_injection = false;
3057
3058       if (DECL_DECLARES_FUNCTION_P (decl))
3059         {
3060           check_default_args (decl);
3061
3062           if (is_friend)
3063             {
3064               if (level->kind != sk_namespace)
3065                 {
3066                   /* In a local class, a friend function declaration must
3067                      find a matching decl in the innermost non-class scope.
3068                      [class.friend/11] */
3069                   error ("friend declaration %qD in local class without "
3070                          "prior local declaration", decl);
3071                   /* Don't attempt to push it.  */
3072                   return error_mark_node;
3073                 }
3074               if (!flag_friend_injection)
3075                 /* Hide it from ordinary lookup.  */
3076                 DECL_ANTICIPATED (decl) = DECL_HIDDEN_FRIEND_P (decl) = true;
3077               else
3078                 visible_injection = true;
3079             }
3080         }
3081
3082       if (level->kind != sk_namespace)
3083         {
3084           check_local_shadow (decl);
3085
3086           if (TREE_CODE (decl) == NAMESPACE_DECL)
3087             /* A local namespace alias.  */
3088             set_identifier_type_value (name, NULL_TREE);
3089
3090           if (!binding)
3091             binding = create_local_binding (level, name);
3092         }
3093       else if (!slot)
3094         {
3095           ns = current_namespace;
3096           slot = find_namespace_slot (ns, name, true);
3097           /* Update OLD to reflect the namespace we're going to be
3098              pushing into.  */
3099           old = MAYBE_STAT_DECL (*slot);
3100         }
3101
3102       old = update_binding (level, binding, slot, old, decl, is_friend);
3103
3104       if (old != decl)
3105         /* An existing decl matched, use it.  */
3106         decl = old;
3107       else if (TREE_CODE (decl) == TYPE_DECL)
3108         {
3109           tree type = TREE_TYPE (decl);
3110
3111           if (type != error_mark_node)
3112             {
3113               if (TYPE_NAME (type) != decl)
3114                 set_underlying_type (decl);
3115
3116               if (!ns)
3117                 set_identifier_type_value_with_scope (name, decl, level);
3118               else
3119                 SET_IDENTIFIER_TYPE_VALUE (name, global_type_node);
3120             }
3121
3122           /* If this is a locally defined typedef in a function that
3123              is not a template instantation, record it to implement
3124              -Wunused-local-typedefs.  */
3125           if (!instantiating_current_function_p ())
3126             record_locally_defined_typedef (decl);
3127         }
3128       else if (VAR_P (decl))
3129         maybe_register_incomplete_var (decl);
3130       else if (visible_injection)
3131         warning (0, "injected friend %qD is visible"
3132                 " due to %<-ffriend-injection%>", decl);
3133
3134       if ((VAR_P (decl) || TREE_CODE (decl) == FUNCTION_DECL)
3135           && DECL_EXTERN_C_P (decl))
3136         check_extern_c_conflict (decl);
3137     }
3138   else
3139     add_decl_to_level (level, decl);
3140
3141   return decl;
3142 }
3143
3144 /* Record a decl-node X as belonging to the current lexical scope.
3145    It's a friend if IS_FRIEND is true -- which affects exactly where
3146    we push it.  */
3147
3148 tree
3149 pushdecl (tree x, bool is_friend)
3150 {
3151   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3152   tree ret = do_pushdecl (x, is_friend);
3153   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
3154   return ret;
3155 }
3156
3157 /* Enter DECL into the symbol table, if that's appropriate.  Returns
3158    DECL, or a modified version thereof.  */
3159
3160 tree
3161 maybe_push_decl (tree decl)
3162 {
3163   tree type = TREE_TYPE (decl);
3164
3165   /* Add this decl to the current binding level, but not if it comes
3166      from another scope, e.g. a static member variable.  TEM may equal
3167      DECL or it may be a previous decl of the same name.  */
3168   if (decl == error_mark_node
3169       || (TREE_CODE (decl) != PARM_DECL
3170           && DECL_CONTEXT (decl) != NULL_TREE
3171           /* Definitions of namespace members outside their namespace are
3172              possible.  */
3173           && !DECL_NAMESPACE_SCOPE_P (decl))
3174       || (TREE_CODE (decl) == TEMPLATE_DECL && !namespace_bindings_p ())
3175       || type == unknown_type_node
3176       /* The declaration of a template specialization does not affect
3177          the functions available for overload resolution, so we do not
3178          call pushdecl.  */
3179       || (TREE_CODE (decl) == FUNCTION_DECL
3180           && DECL_TEMPLATE_SPECIALIZATION (decl)))
3181     return decl;
3182   else
3183     return pushdecl (decl);
3184 }
3185
3186 /* Bind DECL to ID in the current_binding_level, assumed to be a local
3187    binding level.  If IS_USING is true, DECL got here through a
3188    using-declaration.  */
3189
3190 static void
3191 push_local_binding (tree id, tree decl, bool is_using)
3192 {
3193   /* Skip over any local classes.  This makes sense if we call
3194      push_local_binding with a friend decl of a local class.  */
3195   cp_binding_level *b = innermost_nonclass_level ();
3196
3197   gcc_assert (b->kind != sk_namespace);
3198   if (find_local_binding (b, id))
3199     {
3200       /* Supplement the existing binding.  */
3201       if (!supplement_binding (IDENTIFIER_BINDING (id), decl))
3202         /* It didn't work.  Something else must be bound at this
3203            level.  Do not add DECL to the list of things to pop
3204            later.  */
3205         return;
3206     }
3207   else
3208     /* Create a new binding.  */
3209     push_binding (id, decl, b);
3210
3211   if (TREE_CODE (decl) == OVERLOAD || is_using)
3212     /* We must put the OVERLOAD or using into a TREE_LIST since we
3213        cannot use the decl's chain itself.  */
3214     decl = build_tree_list (NULL_TREE, decl);
3215
3216   /* And put DECL on the list of things declared by the current
3217      binding level.  */
3218   add_decl_to_level (b, decl);
3219 }
3220
3221 /* Check to see whether or not DECL is a variable that would have been
3222    in scope under the ARM, but is not in scope under the ANSI/ISO
3223    standard.  If so, issue an error message.  If name lookup would
3224    work in both cases, but return a different result, this function
3225    returns the result of ANSI/ISO lookup.  Otherwise, it returns
3226    DECL.
3227
3228    FIXME: Scheduled for removal after GCC-8 is done.  */
3229
3230 tree
3231 check_for_out_of_scope_variable (tree decl)
3232 {
3233   tree shadowed;
3234
3235   /* We only care about out of scope variables.  */
3236   if (!(VAR_P (decl) && DECL_DEAD_FOR_LOCAL (decl)))
3237     return decl;
3238
3239   shadowed = DECL_HAS_SHADOWED_FOR_VAR_P (decl)
3240     ? DECL_SHADOWED_FOR_VAR (decl) : NULL_TREE ;
3241   while (shadowed != NULL_TREE && VAR_P (shadowed)
3242          && DECL_DEAD_FOR_LOCAL (shadowed))
3243     shadowed = DECL_HAS_SHADOWED_FOR_VAR_P (shadowed)
3244       ? DECL_SHADOWED_FOR_VAR (shadowed) : NULL_TREE;
3245   if (!shadowed)
3246     shadowed = find_namespace_value (current_namespace, DECL_NAME (decl));
3247   if (shadowed)
3248     {
3249       if (!DECL_ERROR_REPORTED (decl)
3250           && flag_permissive
3251           && warning (0, "name lookup of %qD changed", DECL_NAME (decl)))
3252         {
3253           inform (DECL_SOURCE_LOCATION (shadowed),
3254                   "matches this %qD under ISO standard rules", shadowed);
3255           inform (DECL_SOURCE_LOCATION (decl),
3256                   "  matches this %qD under old rules", decl);
3257         }
3258       DECL_ERROR_REPORTED (decl) = 1;
3259       return shadowed;
3260     }
3261
3262   /* If we have already complained about this declaration, there's no
3263      need to do it again.  */
3264   if (DECL_ERROR_REPORTED (decl))
3265     return decl;
3266
3267   DECL_ERROR_REPORTED (decl) = 1;
3268
3269   if (TREE_TYPE (decl) == error_mark_node)
3270     return decl;
3271
3272   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl)))
3273     {
3274       error ("name lookup of %qD changed for ISO %<for%> scoping",
3275              DECL_NAME (decl));
3276       inform (DECL_SOURCE_LOCATION (decl),
3277               "cannot use obsolete binding %qD because it has a destructor",
3278               decl);
3279       return error_mark_node;
3280     }
3281   else
3282     {
3283       permerror (input_location,
3284                  "name lookup of %qD changed for ISO %<for%> scoping",
3285                  DECL_NAME (decl));
3286       if (flag_permissive)
3287         inform (DECL_SOURCE_LOCATION (decl),
3288                 "using obsolete binding %qD", decl);
3289       static bool hint;
3290       if (!hint)
3291         inform (input_location, flag_permissive
3292                 ? "this flexibility is deprecated and will be removed"
3293                 : "if you use %<-fpermissive%> G++ will accept your code");
3294       hint = true;
3295     }
3296
3297   return decl;
3298 }
3299 \f
3300 /* true means unconditionally make a BLOCK for the next level pushed.  */
3301
3302 static bool keep_next_level_flag;
3303
3304 static int binding_depth = 0;
3305
3306 static void
3307 indent (int depth)
3308 {
3309   int i;
3310
3311   for (i = 0; i < depth * 2; i++)
3312     putc (' ', stderr);
3313 }
3314
3315 /* Return a string describing the kind of SCOPE we have.  */
3316 static const char *
3317 cp_binding_level_descriptor (cp_binding_level *scope)
3318 {
3319   /* The order of this table must match the "scope_kind"
3320      enumerators.  */
3321   static const char* scope_kind_names[] = {
3322     "block-scope",
3323     "cleanup-scope",
3324     "try-scope",
3325     "catch-scope",
3326     "for-scope",
3327     "function-parameter-scope",
3328     "class-scope",
3329     "namespace-scope",
3330     "template-parameter-scope",
3331     "template-explicit-spec-scope"
3332   };
3333   const scope_kind kind = scope->explicit_spec_p
3334     ? sk_template_spec : scope->kind;
3335
3336   return scope_kind_names[kind];
3337 }
3338
3339 /* Output a debugging information about SCOPE when performing
3340    ACTION at LINE.  */
3341 static void
3342 cp_binding_level_debug (cp_binding_level *scope, int line, const char *action)
3343 {
3344   const char *desc = cp_binding_level_descriptor (scope);
3345   if (scope->this_entity)
3346     verbatim ("%s %<%s(%E)%> %p %d\n", action, desc,
3347               scope->this_entity, (void *) scope, line);
3348   else
3349     verbatim ("%s %s %p %d\n", action, desc, (void *) scope, line);
3350 }
3351
3352 /* Return the estimated initial size of the hashtable of a NAMESPACE
3353    scope.  */
3354
3355 static inline size_t
3356 namespace_scope_ht_size (tree ns)
3357 {
3358   tree name = DECL_NAME (ns);
3359
3360   return name == std_identifier
3361     ? NAMESPACE_STD_HT_SIZE
3362     : (name == global_identifier
3363        ? GLOBAL_SCOPE_HT_SIZE
3364        : NAMESPACE_ORDINARY_HT_SIZE);
3365 }
3366
3367 /* A chain of binding_level structures awaiting reuse.  */
3368
3369 static GTY((deletable)) cp_binding_level *free_binding_level;
3370
3371 /* Insert SCOPE as the innermost binding level.  */
3372
3373 void
3374 push_binding_level (cp_binding_level *scope)
3375 {
3376   /* Add it to the front of currently active scopes stack.  */
3377   scope->level_chain = current_binding_level;
3378   current_binding_level = scope;
3379   keep_next_level_flag = false;
3380
3381   if (ENABLE_SCOPE_CHECKING)
3382     {
3383       scope->binding_depth = binding_depth;
3384       indent (binding_depth);
3385       cp_binding_level_debug (scope, LOCATION_LINE (input_location),
3386                               "push");
3387       binding_depth++;
3388     }
3389 }
3390
3391 /* Create a new KIND scope and make it the top of the active scopes stack.
3392    ENTITY is the scope of the associated C++ entity (namespace, class,
3393    function, C++0x enumeration); it is NULL otherwise.  */
3394
3395 cp_binding_level *
3396 begin_scope (scope_kind kind, tree entity)
3397 {
3398   cp_binding_level *scope;
3399
3400   /* Reuse or create a struct for this binding level.  */
3401   if (!ENABLE_SCOPE_CHECKING && free_binding_level)
3402     {
3403       scope = free_binding_level;
3404       free_binding_level = scope->level_chain;
3405       memset (scope, 0, sizeof (cp_binding_level));
3406     }
3407   else
3408     scope = ggc_cleared_alloc<cp_binding_level> ();
3409
3410   scope->this_entity = entity;
3411   scope->more_cleanups_ok = true;
3412   switch (kind)
3413     {
3414     case sk_cleanup:
3415       scope->keep = true;
3416       break;
3417
3418     case sk_template_spec:
3419       scope->explicit_spec_p = true;
3420       kind = sk_template_parms;
3421       /* Fall through.  */
3422     case sk_template_parms:
3423     case sk_block:
3424     case sk_try:
3425     case sk_catch:
3426     case sk_for:
3427     case sk_cond:
3428     case sk_class:
3429     case sk_scoped_enum:
3430     case sk_function_parms:
3431     case sk_transaction:
3432     case sk_omp:
3433       scope->keep = keep_next_level_flag;
3434       break;
3435
3436     case sk_namespace:
3437       NAMESPACE_LEVEL (entity) = scope;
3438       break;
3439
3440     default:
3441       /* Should not happen.  */
3442       gcc_unreachable ();
3443       break;
3444     }
3445   scope->kind = kind;
3446
3447   push_binding_level (scope);
3448
3449   return scope;
3450 }
3451
3452 /* We're about to leave current scope.  Pop the top of the stack of
3453    currently active scopes.  Return the enclosing scope, now active.  */
3454
3455 cp_binding_level *
3456 leave_scope (void)
3457 {
3458   cp_binding_level *scope = current_binding_level;
3459
3460   if (scope->kind == sk_namespace && class_binding_level)
3461     current_binding_level = class_binding_level;
3462
3463   /* We cannot leave a scope, if there are none left.  */
3464   if (NAMESPACE_LEVEL (global_namespace))
3465     gcc_assert (!global_scope_p (scope));
3466
3467   if (ENABLE_SCOPE_CHECKING)
3468     {
3469       indent (--binding_depth);
3470       cp_binding_level_debug (scope, LOCATION_LINE (input_location),
3471                               "leave");
3472     }
3473
3474   /* Move one nesting level up.  */
3475   current_binding_level = scope->level_chain;
3476
3477   /* Namespace-scopes are left most probably temporarily, not
3478      completely; they can be reopened later, e.g. in namespace-extension
3479      or any name binding activity that requires us to resume a
3480      namespace.  For classes, we cache some binding levels.  For other
3481      scopes, we just make the structure available for reuse.  */
3482   if (scope->kind != sk_namespace
3483       && scope->kind != sk_class)
3484     {
3485       scope->level_chain = free_binding_level;
3486       gcc_assert (!ENABLE_SCOPE_CHECKING
3487                   || scope->binding_depth == binding_depth);
3488       free_binding_level = scope;
3489     }
3490
3491   if (scope->kind == sk_class)
3492     {
3493       /* Reset DEFINING_CLASS_P to allow for reuse of a
3494          class-defining scope in a non-defining context.  */
3495       scope->defining_class_p = 0;
3496
3497       /* Find the innermost enclosing class scope, and reset
3498          CLASS_BINDING_LEVEL appropriately.  */
3499       class_binding_level = NULL;
3500       for (scope = current_binding_level; scope; scope = scope->level_chain)
3501         if (scope->kind == sk_class)
3502           {
3503             class_binding_level = scope;
3504             break;
3505           }
3506     }
3507
3508   return current_binding_level;
3509 }
3510
3511 static void
3512 resume_scope (cp_binding_level* b)
3513 {
3514   /* Resuming binding levels is meant only for namespaces,
3515      and those cannot nest into classes.  */
3516   gcc_assert (!class_binding_level);
3517   /* Also, resuming a non-directly nested namespace is a no-no.  */
3518   gcc_assert (b->level_chain == current_binding_level);
3519   current_binding_level = b;
3520   if (ENABLE_SCOPE_CHECKING)
3521     {
3522       b->binding_depth = binding_depth;
3523       indent (binding_depth);
3524       cp_binding_level_debug (b, LOCATION_LINE (input_location), "resume");
3525       binding_depth++;
3526     }
3527 }
3528
3529 /* Return the innermost binding level that is not for a class scope.  */
3530
3531 static cp_binding_level *
3532 innermost_nonclass_level (void)
3533 {
3534   cp_binding_level *b;
3535
3536   b = current_binding_level;
3537   while (b->kind == sk_class)
3538     b = b->level_chain;
3539
3540   return b;
3541 }
3542
3543 /* We're defining an object of type TYPE.  If it needs a cleanup, but
3544    we're not allowed to add any more objects with cleanups to the current
3545    scope, create a new binding level.  */
3546
3547 void
3548 maybe_push_cleanup_level (tree type)
3549 {
3550   if (type != error_mark_node
3551       && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
3552       && current_binding_level->more_cleanups_ok == 0)
3553     {
3554       begin_scope (sk_cleanup, NULL);
3555       current_binding_level->statement_list = push_stmt_list ();
3556     }
3557 }
3558
3559 /* Return true if we are in the global binding level.  */
3560
3561 bool
3562 global_bindings_p (void)
3563 {
3564   return global_scope_p (current_binding_level);
3565 }
3566
3567 /* True if we are currently in a toplevel binding level.  This
3568    means either the global binding level or a namespace in a toplevel
3569    binding level.  Since there are no non-toplevel namespace levels,
3570    this really means any namespace or template parameter level.  We
3571    also include a class whose context is toplevel.  */
3572
3573 bool
3574 toplevel_bindings_p (void)
3575 {
3576   cp_binding_level *b = innermost_nonclass_level ();
3577
3578   return b->kind == sk_namespace || b->kind == sk_template_parms;
3579 }
3580
3581 /* True if this is a namespace scope, or if we are defining a class
3582    which is itself at namespace scope, or whose enclosing class is
3583    such a class, etc.  */
3584
3585 bool
3586 namespace_bindings_p (void)
3587 {
3588   cp_binding_level *b = innermost_nonclass_level ();
3589
3590   return b->kind == sk_namespace;
3591 }
3592
3593 /* True if the innermost non-class scope is a block scope.  */
3594
3595 bool
3596 local_bindings_p (void)
3597 {
3598   cp_binding_level *b = innermost_nonclass_level ();
3599   return b->kind < sk_function_parms || b->kind == sk_omp;
3600 }
3601
3602 /* True if the current level needs to have a BLOCK made.  */
3603
3604 bool
3605 kept_level_p (void)
3606 {
3607   return (current_binding_level->blocks != NULL_TREE
3608           || current_binding_level->keep
3609           || current_binding_level->kind == sk_cleanup
3610           || current_binding_level->names != NULL_TREE
3611           || current_binding_level->using_directives);
3612 }
3613
3614 /* Returns the kind of the innermost scope.  */
3615
3616 scope_kind
3617 innermost_scope_kind (void)
3618 {
3619   return current_binding_level->kind;
3620 }
3621
3622 /* Returns true if this scope was created to store template parameters.  */
3623
3624 bool
3625 template_parm_scope_p (void)
3626 {
3627   return innermost_scope_kind () == sk_template_parms;
3628 }
3629
3630 /* If KEEP is true, make a BLOCK node for the next binding level,
3631    unconditionally.  Otherwise, use the normal logic to decide whether
3632    or not to create a BLOCK.  */
3633
3634 void
3635 keep_next_level (bool keep)
3636 {
3637   keep_next_level_flag = keep;
3638 }
3639
3640 /* Return the list of declarations of the current local scope.  */
3641
3642 tree
3643 get_local_decls (void)
3644 {
3645   gcc_assert (current_binding_level->kind != sk_namespace
3646               && current_binding_level->kind != sk_class);
3647   return current_binding_level->names;
3648 }
3649
3650 /* Return how many function prototypes we are currently nested inside.  */
3651
3652 int
3653 function_parm_depth (void)
3654 {
3655   int level = 0;
3656   cp_binding_level *b;
3657
3658   for (b = current_binding_level;
3659        b->kind == sk_function_parms;
3660        b = b->level_chain)
3661     ++level;
3662
3663   return level;
3664 }
3665
3666 /* For debugging.  */
3667 static int no_print_functions = 0;
3668 static int no_print_builtins = 0;
3669
3670 static void
3671 print_binding_level (cp_binding_level* lvl)
3672 {
3673   tree t;
3674   int i = 0, len;
3675   fprintf (stderr, " blocks=%p", (void *) lvl->blocks);
3676   if (lvl->more_cleanups_ok)
3677     fprintf (stderr, " more-cleanups-ok");
3678   if (lvl->have_cleanups)
3679     fprintf (stderr, " have-cleanups");
3680   fprintf (stderr, "\n");
3681   if (lvl->names)
3682     {
3683       fprintf (stderr, " names:\t");
3684       /* We can probably fit 3 names to a line?  */
3685       for (t = lvl->names; t; t = TREE_CHAIN (t))
3686         {
3687           if (no_print_functions && (TREE_CODE (t) == FUNCTION_DECL))
3688             continue;
3689           if (no_print_builtins
3690               && (TREE_CODE (t) == TYPE_DECL)
3691               && DECL_IS_BUILTIN (t))
3692             continue;
3693
3694           /* Function decls tend to have longer names.  */
3695           if (TREE_CODE (t) == FUNCTION_DECL)
3696             len = 3;
3697           else
3698             len = 2;
3699           i += len;
3700           if (i > 6)
3701             {
3702               fprintf (stderr, "\n\t");
3703               i = len;
3704             }
3705           print_node_brief (stderr, "", t, 0);
3706           if (t == error_mark_node)
3707             break;
3708         }
3709       if (i)
3710         fprintf (stderr, "\n");
3711     }
3712   if (vec_safe_length (lvl->class_shadowed))
3713     {
3714       size_t i;
3715       cp_class_binding *b;
3716       fprintf (stderr, " class-shadowed:");
3717       FOR_EACH_VEC_ELT (*lvl->class_shadowed, i, b)
3718         fprintf (stderr, " %s ", IDENTIFIER_POINTER (b->identifier));
3719       fprintf (stderr, "\n");
3720     }
3721   if (lvl->type_shadowed)
3722     {
3723       fprintf (stderr, " type-shadowed:");
3724       for (t = lvl->type_shadowed; t; t = TREE_CHAIN (t))
3725         {
3726           fprintf (stderr, " %s ", IDENTIFIER_POINTER (TREE_PURPOSE (t)));
3727         }
3728       fprintf (stderr, "\n");
3729     }
3730 }
3731
3732 DEBUG_FUNCTION void
3733 debug (cp_binding_level &ref)
3734 {
3735   print_binding_level (&ref);
3736 }
3737
3738 DEBUG_FUNCTION void
3739 debug (cp_binding_level *ptr)
3740 {
3741   if (ptr)
3742     debug (*ptr);
3743   else
3744     fprintf (stderr, "<nil>\n");
3745 }
3746
3747
3748 void
3749 print_other_binding_stack (cp_binding_level *stack)
3750 {
3751   cp_binding_level *level;
3752   for (level = stack; !global_scope_p (level); level = level->level_chain)
3753     {
3754       fprintf (stderr, "binding level %p\n", (void *) level);
3755       print_binding_level (level);
3756     }
3757 }
3758
3759 void
3760 print_binding_stack (void)
3761 {
3762   cp_binding_level *b;
3763   fprintf (stderr, "current_binding_level=%p\n"
3764            "class_binding_level=%p\n"
3765            "NAMESPACE_LEVEL (global_namespace)=%p\n",
3766            (void *) current_binding_level, (void *) class_binding_level,
3767            (void *) NAMESPACE_LEVEL (global_namespace));
3768   if (class_binding_level)
3769     {
3770       for (b = class_binding_level; b; b = b->level_chain)
3771         if (b == current_binding_level)
3772           break;
3773       if (b)
3774         b = class_binding_level;
3775       else
3776         b = current_binding_level;
3777     }
3778   else
3779     b = current_binding_level;
3780   print_other_binding_stack (b);
3781   fprintf (stderr, "global:\n");
3782   print_binding_level (NAMESPACE_LEVEL (global_namespace));
3783 }
3784 \f
3785 /* Return the type associated with ID.  */
3786
3787 static tree
3788 identifier_type_value_1 (tree id)
3789 {
3790   /* There is no type with that name, anywhere.  */
3791   if (REAL_IDENTIFIER_TYPE_VALUE (id) == NULL_TREE)
3792     return NULL_TREE;
3793   /* This is not the type marker, but the real thing.  */
3794   if (REAL_IDENTIFIER_TYPE_VALUE (id) != global_type_node)
3795     return REAL_IDENTIFIER_TYPE_VALUE (id);
3796   /* Have to search for it. It must be on the global level, now.
3797      Ask lookup_name not to return non-types.  */
3798   id = lookup_name_real (id, 2, 1, /*block_p=*/true, 0, 0);
3799   if (id)
3800     return TREE_TYPE (id);
3801   return NULL_TREE;
3802 }
3803
3804 /* Wrapper for identifier_type_value_1.  */
3805
3806 tree
3807 identifier_type_value (tree id)
3808 {
3809   tree ret;
3810   timevar_start (TV_NAME_LOOKUP);
3811   ret = identifier_type_value_1 (id);
3812   timevar_stop (TV_NAME_LOOKUP);
3813   return ret;
3814 }
3815
3816 /* Push a definition of struct, union or enum tag named ID.  into
3817    binding_level B.  DECL is a TYPE_DECL for the type.  We assume that
3818    the tag ID is not already defined.  */
3819
3820 static void
3821 set_identifier_type_value_with_scope (tree id, tree decl, cp_binding_level *b)
3822 {
3823   tree type;
3824
3825   if (b->kind != sk_namespace)
3826     {
3827       /* Shadow the marker, not the real thing, so that the marker
3828          gets restored later.  */
3829       tree old_type_value = REAL_IDENTIFIER_TYPE_VALUE (id);
3830       b->type_shadowed
3831         = tree_cons (id, old_type_value, b->type_shadowed);
3832       type = decl ? TREE_TYPE (decl) : NULL_TREE;
3833       TREE_TYPE (b->type_shadowed) = type;
3834     }
3835   else
3836     {
3837       tree *slot = find_namespace_slot (current_namespace, id, true);
3838       gcc_assert (decl);
3839       update_binding (b, NULL, slot, MAYBE_STAT_DECL (*slot), decl, false);
3840
3841       /* Store marker instead of real type.  */
3842       type = global_type_node;
3843     }
3844   SET_IDENTIFIER_TYPE_VALUE (id, type);
3845 }
3846
3847 /* As set_identifier_type_value_with_scope, but using
3848    current_binding_level.  */
3849
3850 void
3851 set_identifier_type_value (tree id, tree decl)
3852 {
3853   set_identifier_type_value_with_scope (id, decl, current_binding_level);
3854 }
3855
3856 /* Return the name for the constructor (or destructor) for the
3857    specified class.  */
3858
3859 tree
3860 constructor_name (tree type)
3861 {
3862   tree decl = TYPE_NAME (TYPE_MAIN_VARIANT (type));
3863
3864   return decl ? DECL_NAME (decl) : NULL_TREE;
3865 }
3866
3867 /* Returns TRUE if NAME is the name for the constructor for TYPE,
3868    which must be a class type.  */
3869
3870 bool
3871 constructor_name_p (tree name, tree type)
3872 {
3873   gcc_assert (MAYBE_CLASS_TYPE_P (type));
3874
3875   /* These don't have names.  */
3876   if (TREE_CODE (type) == DECLTYPE_TYPE
3877       || TREE_CODE (type) == TYPEOF_TYPE)
3878     return false;
3879
3880   if (name && name == constructor_name (type))
3881     return true;
3882
3883   return false;
3884 }
3885
3886 /* Counter used to create anonymous type names.  */
3887
3888 static GTY(()) int anon_cnt;
3889
3890 /* Return an IDENTIFIER which can be used as a name for
3891    unnamed structs and unions.  */
3892
3893 tree
3894 make_anon_name (void)
3895 {
3896   char buf[32];
3897
3898   sprintf (buf, anon_aggrname_format (), anon_cnt++);
3899   return get_identifier (buf);
3900 }
3901
3902 /* This code is practically identical to that for creating
3903    anonymous names, but is just used for lambdas instead.  This isn't really
3904    necessary, but it's convenient to avoid treating lambdas like other
3905    unnamed types.  */
3906
3907 static GTY(()) int lambda_cnt = 0;
3908
3909 tree
3910 make_lambda_name (void)
3911 {
3912   char buf[32];
3913
3914   sprintf (buf, LAMBDANAME_FORMAT, lambda_cnt++);
3915   return get_identifier (buf);
3916 }
3917
3918 /* Insert another USING_DECL into the current binding level, returning
3919    this declaration. If this is a redeclaration, do nothing, and
3920    return NULL_TREE if this not in namespace scope (in namespace
3921    scope, a using decl might extend any previous bindings).  */
3922
3923 static tree
3924 push_using_decl_1 (tree scope, tree name)
3925 {
3926   tree decl;
3927
3928   gcc_assert (TREE_CODE (scope) == NAMESPACE_DECL);
3929   gcc_assert (identifier_p (name));
3930   for (decl = current_binding_level->usings; decl; decl = DECL_CHAIN (decl))
3931     if (USING_DECL_SCOPE (decl) == scope && DECL_NAME (decl) == name)
3932       break;
3933   if (decl)
3934     return namespace_bindings_p () ? decl : NULL_TREE;
3935   decl = build_lang_decl (USING_DECL, name, NULL_TREE);
3936   USING_DECL_SCOPE (decl) = scope;
3937   DECL_CHAIN (decl) = current_binding_level->usings;
3938   current_binding_level->usings = decl;
3939   return decl;
3940 }
3941
3942 /* Wrapper for push_using_decl_1.  */
3943
3944 static tree
3945 push_using_decl (tree scope, tree name)
3946 {
3947   tree ret;
3948   timevar_start (TV_NAME_LOOKUP);
3949   ret = push_using_decl_1 (scope, name);
3950   timevar_stop (TV_NAME_LOOKUP);
3951   return ret;
3952 }
3953
3954 /* Same as pushdecl, but define X in binding-level LEVEL.  We rely on the
3955    caller to set DECL_CONTEXT properly.
3956
3957    Note that this must only be used when X will be the new innermost
3958    binding for its name, as we tack it onto the front of IDENTIFIER_BINDING
3959    without checking to see if the current IDENTIFIER_BINDING comes from a
3960    closer binding level than LEVEL.  */
3961
3962 static tree
3963 do_pushdecl_with_scope (tree x, cp_binding_level *level, bool is_friend)
3964 {
3965   cp_binding_level *b;
3966
3967   if (level->kind == sk_class)
3968     {
3969       b = class_binding_level;
3970       class_binding_level = level;
3971       pushdecl_class_level (x);
3972       class_binding_level = b;
3973     }
3974   else
3975     {
3976       tree function_decl = current_function_decl;
3977       if (level->kind == sk_namespace)
3978         current_function_decl = NULL_TREE;
3979       b = current_binding_level;
3980       current_binding_level = level;
3981       x = pushdecl (x, is_friend);
3982       current_binding_level = b;
3983       current_function_decl = function_decl;
3984     }
3985   return x;
3986 }
3987
3988 /* Inject X into the local scope just before the function parms.  */
3989
3990 tree
3991 pushdecl_outermost_localscope (tree x)
3992 {
3993   cp_binding_level *b = NULL;
3994   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3995
3996   /* Find the scope just inside the function parms.  */
3997   for (cp_binding_level *n = current_binding_level;
3998        n->kind != sk_function_parms; n = b->level_chain)
3999     b = n;
4000
4001   tree ret = b ? do_pushdecl_with_scope (x, b, false) : error_mark_node;
4002   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
4003
4004   return ret;
4005 }
4006
4007 /* Check a non-member using-declaration. Return the name and scope
4008    being used, and the USING_DECL, or NULL_TREE on failure.  */
4009
4010 static tree
4011 validate_nonmember_using_decl (tree decl, tree scope, tree name)
4012 {
4013   /* [namespace.udecl]
4014        A using-declaration for a class member shall be a
4015        member-declaration.  */
4016   if (TYPE_P (scope))
4017     {
4018       error ("%qT is not a namespace or unscoped enum", scope);
4019       return NULL_TREE;
4020     }
4021   else if (scope == error_mark_node)
4022     return NULL_TREE;
4023
4024   if (TREE_CODE (decl) == TEMPLATE_ID_EXPR)
4025     {
4026       /* 7.3.3/5
4027            A using-declaration shall not name a template-id.  */
4028       error ("a using-declaration cannot specify a template-id.  "
4029              "Try %<using %D%>", name);
4030       return NULL_TREE;
4031     }
4032
4033   if (TREE_CODE (decl) == NAMESPACE_DECL)
4034     {
4035       error ("namespace %qD not allowed in using-declaration", decl);
4036       return NULL_TREE;
4037     }
4038
4039   if (TREE_CODE (decl) == SCOPE_REF)
4040     {
4041       /* It's a nested name with template parameter dependent scope.
4042          This can only be using-declaration for class member.  */
4043       error ("%qT is not a namespace", TREE_OPERAND (decl, 0));
4044       return NULL_TREE;
4045     }
4046
4047   decl = OVL_FIRST (decl);
4048
4049   /* Make a USING_DECL.  */
4050   tree using_decl = push_using_decl (scope, name);
4051
4052   if (using_decl == NULL_TREE
4053       && at_function_scope_p ()
4054       && VAR_P (decl))
4055     /* C++11 7.3.3/10.  */
4056     error ("%qD is already declared in this scope", name);
4057   
4058   return using_decl;
4059 }
4060
4061 /* Process a local-scope or namespace-scope using declaration.  SCOPE
4062    is the nominated scope to search for NAME.  VALUE_P and TYPE_P
4063    point to the binding for NAME in the current scope and are
4064    updated.  */
4065
4066 static void
4067 do_nonmember_using_decl (tree scope, tree name, tree *value_p, tree *type_p)
4068 {
4069   name_lookup lookup (name, 0);
4070
4071   if (!qualified_namespace_lookup (scope, &lookup))
4072     {
4073       error ("%qD not declared", name);
4074       return;
4075     }
4076   else if (TREE_CODE (lookup.value) == TREE_LIST)
4077     {
4078       error ("reference to %qD is ambiguous", name);
4079       print_candidates (lookup.value);
4080       lookup.value = NULL_TREE;
4081     }
4082
4083   if (lookup.type && TREE_CODE (lookup.type) == TREE_LIST)
4084     {
4085       error ("reference to %qD is ambiguous", name);
4086       print_candidates (lookup.type);
4087       lookup.type = NULL_TREE;
4088     }
4089
4090   tree value = *value_p;
4091   tree type = *type_p;
4092
4093   /* Shift the old and new bindings around so we're comparing class and
4094      enumeration names to each other.  */
4095   if (value && DECL_IMPLICIT_TYPEDEF_P (value))
4096     {
4097       type = value;
4098       value = NULL_TREE;
4099     }
4100
4101   if (lookup.value && DECL_IMPLICIT_TYPEDEF_P (lookup.value))
4102     {
4103       lookup.type = lookup.value;
4104       lookup.value = NULL_TREE;
4105     }
4106
4107   if (lookup.value && lookup.value != value)
4108     {
4109       /* Check for using functions.  */
4110       if (OVL_P (lookup.value) && (!value || OVL_P (value)))
4111         {
4112           for (lkp_iterator usings (lookup.value); usings; ++usings)
4113             {
4114               tree new_fn = *usings;
4115
4116               /* [namespace.udecl]
4117
4118                  If a function declaration in namespace scope or block
4119                  scope has the same name and the same parameter types as a
4120                  function introduced by a using declaration the program is
4121                  ill-formed.  */
4122               bool found = false;
4123               for (ovl_iterator old (value); !found && old; ++old)
4124                 {
4125                   tree old_fn = *old;
4126
4127                   if (new_fn == old_fn)
4128                     /* The function already exists in the current
4129                        namespace.  */
4130                     found = true;
4131                   else if (old.using_p ())
4132                     continue; /* This is a using decl. */
4133                   else if (old.hidden_p () && !DECL_HIDDEN_FRIEND_P (old_fn))
4134                     continue; /* This is an anticipated builtin.  */
4135                   else if (!matching_fn_p (new_fn, old_fn))
4136                     continue; /* Parameters do not match.  */
4137                   else if (decls_match (new_fn, old_fn))
4138                     found = true;
4139                   else
4140                     {
4141                       diagnose_name_conflict (new_fn, old_fn);
4142                       found = true;
4143                     }
4144                 }
4145
4146               if (!found)
4147                 /* Unlike the overload case we don't drop anticipated
4148                    builtins here.  They don't cause a problem, and
4149                    we'd like to match them with a future
4150                    declaration.  */
4151                 value = ovl_insert (new_fn, value, true);
4152             }
4153         }
4154       else if (value
4155                /* Ignore anticipated builtins.  */
4156                && !anticipated_builtin_p (value)
4157                && !decls_match (lookup.value, value))
4158         diagnose_name_conflict (lookup.value, value);
4159       else
4160         value = lookup.value;
4161     }
4162
4163   if (lookup.type && lookup.type != type)
4164     {
4165       if (type && !decls_match (lookup.type, type))
4166         diagnose_name_conflict (lookup.type, type);
4167       else
4168         type = lookup.type;
4169     }
4170
4171   /* If bind->value is empty, shift any class or enumeration name back.  */
4172   if (!value)
4173     {
4174       value = type;
4175       type = NULL_TREE;
4176     }
4177
4178   *value_p = value;
4179   *type_p = type;
4180 }
4181
4182 /* Returns true if ANCESTOR encloses DESCENDANT, including matching.
4183    Both are namespaces.  */
4184
4185 bool
4186 is_nested_namespace (tree ancestor, tree descendant, bool inline_only)
4187 {
4188   int depth = SCOPE_DEPTH (ancestor);
4189
4190   if (!depth && !inline_only)
4191     /* The global namespace encloses everything.  */
4192     return true;
4193
4194   while (SCOPE_DEPTH (descendant) > depth
4195          && (!inline_only || DECL_NAMESPACE_INLINE_P (descendant)))
4196     descendant = CP_DECL_CONTEXT (descendant);
4197
4198   return ancestor == descendant;
4199 }
4200
4201 /* Returns true if ROOT (a namespace, class, or function) encloses
4202    CHILD.  CHILD may be either a class type or a namespace.  */
4203
4204 bool
4205 is_ancestor (tree root, tree child)
4206 {
4207   gcc_assert ((TREE_CODE (root) == NAMESPACE_DECL
4208                || TREE_CODE (root) == FUNCTION_DECL
4209                || CLASS_TYPE_P (root)));
4210   gcc_assert ((TREE_CODE (child) == NAMESPACE_DECL
4211                || CLASS_TYPE_P (child)));
4212
4213   /* The global namespace encloses everything.  */
4214   if (root == global_namespace)
4215     return true;
4216
4217   /* Search until we reach namespace scope.  */
4218   while (TREE_CODE (child) != NAMESPACE_DECL)
4219     {
4220       /* If we've reached the ROOT, it encloses CHILD.  */
4221       if (root == child)
4222         return true;
4223       /* Go out one level.  */
4224       if (TYPE_P (child))
4225         child = TYPE_NAME (child);
4226       child = CP_DECL_CONTEXT (child);
4227     }
4228
4229   if (TREE_CODE (root) == NAMESPACE_DECL)
4230     return is_nested_namespace (root, child);
4231
4232   return false;
4233 }
4234
4235 /* Enter the class or namespace scope indicated by T suitable for name
4236    lookup.  T can be arbitrary scope, not necessary nested inside the
4237    current scope.  Returns a non-null scope to pop iff pop_scope
4238    should be called later to exit this scope.  */
4239
4240 tree
4241 push_scope (tree t)
4242 {
4243   if (TREE_CODE (t) == NAMESPACE_DECL)
4244     push_decl_namespace (t);
4245   else if (CLASS_TYPE_P (t))
4246     {
4247       if (!at_class_scope_p ()
4248           || !same_type_p (current_class_type, t))
4249         push_nested_class (t);
4250       else
4251         /* T is the same as the current scope.  There is therefore no
4252            need to re-enter the scope.  Since we are not actually
4253            pushing a new scope, our caller should not call
4254            pop_scope.  */
4255         t = NULL_TREE;
4256     }
4257
4258   return t;
4259 }
4260
4261 /* Leave scope pushed by push_scope.  */
4262
4263 void
4264 pop_scope (tree t)
4265 {
4266   if (t == NULL_TREE)
4267     return;
4268   if (TREE_CODE (t) == NAMESPACE_DECL)
4269     pop_decl_namespace ();
4270   else if CLASS_TYPE_P (t)
4271     pop_nested_class ();
4272 }
4273
4274 /* Subroutine of push_inner_scope.  */
4275
4276 static void
4277 push_inner_scope_r (tree outer, tree inner)
4278 {
4279   tree prev;
4280
4281   if (outer == inner
4282       || (TREE_CODE (inner) != NAMESPACE_DECL && !CLASS_TYPE_P (inner)))
4283     return;
4284
4285   prev = CP_DECL_CONTEXT (TREE_CODE (inner) == NAMESPACE_DECL ? inner : TYPE_NAME (inner));
4286   if (outer != prev)
4287     push_inner_scope_r (outer, prev);
4288   if (TREE_CODE (inner) == NAMESPACE_DECL)
4289     {
4290       cp_binding_level *save_template_parm = 0;
4291       /* Temporary take out template parameter scopes.  They are saved
4292          in reversed order in save_template_parm.  */
4293       while (current_binding_level->kind == sk_template_parms)
4294         {
4295           cp_binding_level *b = current_binding_level;
4296           current_binding_level = b->level_chain;
4297           b->level_chain = save_template_parm;
4298           save_template_parm = b;
4299         }
4300
4301       resume_scope (NAMESPACE_LEVEL (inner));
4302       current_namespace = inner;
4303
4304       /* Restore template parameter scopes.  */
4305       while (save_template_parm)
4306         {
4307           cp_binding_level *b = save_template_parm;
4308           save_template_parm = b->level_chain;
4309           b->level_chain = current_binding_level;
4310           current_binding_level = b;
4311         }
4312     }
4313   else
4314     pushclass (inner);
4315 }
4316
4317 /* Enter the scope INNER from current scope.  INNER must be a scope
4318    nested inside current scope.  This works with both name lookup and
4319    pushing name into scope.  In case a template parameter scope is present,
4320    namespace is pushed under the template parameter scope according to
4321    name lookup rule in 14.6.1/6.
4322
4323    Return the former current scope suitable for pop_inner_scope.  */
4324
4325 tree
4326 push_inner_scope (tree inner)
4327 {
4328   tree outer = current_scope ();
4329   if (!outer)
4330     outer = current_namespace;
4331
4332   push_inner_scope_r (outer, inner);
4333   return outer;
4334 }
4335
4336 /* Exit the current scope INNER back to scope OUTER.  */
4337
4338 void
4339 pop_inner_scope (tree outer, tree inner)
4340 {
4341   if (outer == inner
4342       || (TREE_CODE (inner) != NAMESPACE_DECL && !CLASS_TYPE_P (inner)))
4343     return;
4344
4345   while (outer != inner)
4346     {
4347       if (TREE_CODE (inner) == NAMESPACE_DECL)
4348         {
4349           cp_binding_level *save_template_parm = 0;
4350           /* Temporary take out template parameter scopes.  They are saved
4351              in reversed order in save_template_parm.  */
4352           while (current_binding_level->kind == sk_template_parms)
4353             {
4354               cp_binding_level *b = current_binding_level;
4355               current_binding_level = b->level_chain;
4356               b->level_chain = save_template_parm;
4357               save_template_parm = b;
4358             }
4359
4360           pop_namespace ();
4361
4362           /* Restore template parameter scopes.  */
4363           while (save_template_parm)
4364             {
4365               cp_binding_level *b = save_template_parm;
4366               save_template_parm = b->level_chain;
4367               b->level_chain = current_binding_level;
4368               current_binding_level = b;
4369             }
4370         }
4371       else
4372         popclass ();
4373
4374       inner = CP_DECL_CONTEXT (TREE_CODE (inner) == NAMESPACE_DECL ? inner : TYPE_NAME (inner));
4375     }
4376 }
4377 \f
4378 /* Do a pushlevel for class declarations.  */
4379
4380 void
4381 pushlevel_class (void)
4382 {
4383   class_binding_level = begin_scope (sk_class, current_class_type);
4384 }
4385
4386 /* ...and a poplevel for class declarations.  */
4387
4388 void
4389 poplevel_class (void)
4390 {
4391   cp_binding_level *level = class_binding_level;
4392   cp_class_binding *cb;
4393   size_t i;
4394   tree shadowed;
4395
4396   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
4397   gcc_assert (level != 0);
4398
4399   /* If we're leaving a toplevel class, cache its binding level.  */
4400   if (current_class_depth == 1)
4401     previous_class_level = level;
4402   for (shadowed = level->type_shadowed;
4403        shadowed;
4404        shadowed = TREE_CHAIN (shadowed))
4405     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (shadowed), TREE_VALUE (shadowed));
4406
4407   /* Remove the bindings for all of the class-level declarations.  */
4408   if (level->class_shadowed)
4409     {
4410       FOR_EACH_VEC_ELT (*level->class_shadowed, i, cb)
4411         {
4412           IDENTIFIER_BINDING (cb->identifier) = cb->base->previous;
4413           cxx_binding_free (cb->base);
4414         }
4415       ggc_free (level->class_shadowed);
4416       level->class_shadowed = NULL;
4417     }
4418
4419   /* Now, pop out of the binding level which we created up in the
4420      `pushlevel_class' routine.  */
4421   gcc_assert (current_binding_level == level);
4422   leave_scope ();
4423   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
4424 }
4425
4426 /* Set INHERITED_VALUE_BINDING_P on BINDING to true or false, as
4427    appropriate.  DECL is the value to which a name has just been
4428    bound.  CLASS_TYPE is the class in which the lookup occurred.  */
4429
4430 static void
4431 set_inherited_value_binding_p (cxx_binding *binding, tree decl,
4432                                tree class_type)
4433 {
4434   if (binding->value == decl && TREE_CODE (decl) != TREE_LIST)
4435     {
4436       tree context;
4437
4438       if (TREE_CODE (decl) == OVERLOAD)
4439         context = ovl_scope (decl);
4440       else
4441         {
4442           gcc_assert (DECL_P (decl));
4443           context = context_for_name_lookup (decl);
4444         }
4445
4446       if (is_properly_derived_from (class_type, context))
4447         INHERITED_VALUE_BINDING_P (binding) = 1;
4448       else
4449         INHERITED_VALUE_BINDING_P (binding) = 0;
4450     }
4451   else if (binding->value == decl)
4452     /* We only encounter a TREE_LIST when there is an ambiguity in the
4453        base classes.  Such an ambiguity can be overridden by a
4454        definition in this class.  */
4455     INHERITED_VALUE_BINDING_P (binding) = 1;
4456   else
4457     INHERITED_VALUE_BINDING_P (binding) = 0;
4458 }
4459
4460 /* Make the declaration of X appear in CLASS scope.  */
4461
4462 bool
4463 pushdecl_class_level (tree x)
4464 {
4465   bool is_valid = true;
4466   bool subtime;
4467
4468   /* Do nothing if we're adding to an outer lambda closure type,
4469      outer_binding will add it later if it's needed.  */
4470   if (current_class_type != class_binding_level->this_entity)
4471     return true;
4472
4473   subtime = timevar_cond_start (TV_NAME_LOOKUP);
4474   /* Get the name of X.  */
4475   tree name = OVL_NAME (x);
4476
4477   if (name)
4478     {
4479       is_valid = push_class_level_binding (name, x);
4480       if (TREE_CODE (x) == TYPE_DECL)
4481         set_identifier_type_value (name, x);
4482     }
4483   else if (ANON_AGGR_TYPE_P (TREE_TYPE (x)))
4484     {
4485       /* If X is an anonymous aggregate, all of its members are
4486          treated as if they were members of the class containing the
4487          aggregate, for naming purposes.  */
4488       location_t save_location = input_location;
4489       tree anon = TREE_TYPE (x);
4490       if (vec<tree, va_gc> *member_vec = CLASSTYPE_MEMBER_VEC (anon))
4491         for (unsigned ix = member_vec->length (); ix--;)
4492           {
4493             tree binding = (*member_vec)[ix];
4494             if (STAT_HACK_P (binding))
4495               {
4496                 if (!pushdecl_class_level (STAT_TYPE (binding)))
4497                   is_valid = false;
4498                 binding = STAT_DECL (binding);
4499               }
4500             if (!pushdecl_class_level (binding))
4501               is_valid = false;
4502         }
4503       else
4504         for (tree f = TYPE_FIELDS (anon); f; f = DECL_CHAIN (f))
4505           if (TREE_CODE (f) == FIELD_DECL)
4506             {
4507               input_location = DECL_SOURCE_LOCATION (f);
4508               if (!pushdecl_class_level (f))
4509                 is_valid = false;
4510             }
4511       input_location = save_location;
4512     }
4513   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
4514   return is_valid;
4515 }
4516
4517 /* Return the BINDING (if any) for NAME in SCOPE, which is a class
4518    scope.  If the value returned is non-NULL, and the PREVIOUS field
4519    is not set, callers must set the PREVIOUS field explicitly.  */
4520
4521 static cxx_binding *
4522 get_class_binding (tree name, cp_binding_level *scope)
4523 {
4524   tree class_type;
4525   tree type_binding;
4526   tree value_binding;
4527   cxx_binding *binding;
4528
4529   class_type = scope->this_entity;
4530
4531   /* Get the type binding.  */
4532   type_binding = lookup_member (class_type, name,
4533                                 /*protect=*/2, /*want_type=*/true,
4534                                 tf_warning_or_error);
4535   /* Get the value binding.  */
4536   value_binding = lookup_member (class_type, name,
4537                                  /*protect=*/2, /*want_type=*/false,
4538                                  tf_warning_or_error);
4539
4540   if (value_binding
4541       && (TREE_CODE (value_binding) == TYPE_DECL
4542           || DECL_CLASS_TEMPLATE_P (value_binding)
4543           || (TREE_CODE (value_binding) == TREE_LIST
4544               && TREE_TYPE (value_binding) == error_mark_node
4545               && (TREE_CODE (TREE_VALUE (value_binding))
4546                   == TYPE_DECL))))
4547     /* We found a type binding, even when looking for a non-type
4548        binding.  This means that we already processed this binding
4549        above.  */
4550     ;
4551   else if (value_binding)
4552     {
4553       if (TREE_CODE (value_binding) == TREE_LIST
4554           && TREE_TYPE (value_binding) == error_mark_node)
4555         /* NAME is ambiguous.  */
4556         ;
4557       else if (BASELINK_P (value_binding))
4558         /* NAME is some overloaded functions.  */
4559         value_binding = BASELINK_FUNCTIONS (value_binding);
4560     }
4561
4562   /* If we found either a type binding or a value binding, create a
4563      new binding object.  */
4564   if (type_binding || value_binding)
4565     {
4566       binding = new_class_binding (name,
4567                                    value_binding,
4568                                    type_binding,
4569                                    scope);
4570       /* This is a class-scope binding, not a block-scope binding.  */
4571       LOCAL_BINDING_P (binding) = 0;
4572       set_inherited_value_binding_p (binding, value_binding, class_type);
4573     }
4574   else
4575     binding = NULL;
4576
4577   return binding;
4578 }
4579
4580 /* Make the declaration(s) of X appear in CLASS scope under the name
4581    NAME.  Returns true if the binding is valid.  */
4582
4583 static bool
4584 push_class_level_binding_1 (tree name, tree x)
4585 {
4586   cxx_binding *binding;
4587   tree decl = x;
4588   bool ok;
4589
4590   /* The class_binding_level will be NULL if x is a template
4591      parameter name in a member template.  */
4592   if (!class_binding_level)
4593     return true;
4594
4595   if (name == error_mark_node)
4596     return false;
4597
4598   /* Can happen for an erroneous declaration (c++/60384).  */
4599   if (!identifier_p (name))
4600     {
4601       gcc_assert (errorcount || sorrycount);
4602       return false;
4603     }
4604
4605   /* Check for invalid member names.  But don't worry about a default
4606      argument-scope lambda being pushed after the class is complete.  */
4607   gcc_assert (TYPE_BEING_DEFINED (current_class_type)
4608               || LAMBDA_TYPE_P (TREE_TYPE (decl)));
4609   /* Check that we're pushing into the right binding level.  */
4610   gcc_assert (current_class_type == class_binding_level->this_entity);
4611
4612   /* We could have been passed a tree list if this is an ambiguous
4613      declaration. If so, pull the declaration out because
4614      check_template_shadow will not handle a TREE_LIST.  */
4615   if (TREE_CODE (decl) == TREE_LIST
4616       && TREE_TYPE (decl) == error_mark_node)
4617     decl = TREE_VALUE (decl);
4618
4619   if (!check_template_shadow (decl))
4620     return false;
4621
4622   /* [class.mem]
4623
4624      If T is the name of a class, then each of the following shall
4625      have a name different from T:
4626
4627      -- every static data member of class T;
4628
4629      -- every member of class T that is itself a type;
4630
4631      -- every enumerator of every member of class T that is an
4632         enumerated type;
4633
4634      -- every member of every anonymous union that is a member of
4635         class T.
4636
4637      (Non-static data members were also forbidden to have the same
4638      name as T until TC1.)  */
4639   if ((VAR_P (x)
4640        || TREE_CODE (x) == CONST_DECL
4641        || (TREE_CODE (x) == TYPE_DECL
4642            && !DECL_SELF_REFERENCE_P (x))
4643        /* A data member of an anonymous union.  */
4644        || (TREE_CODE (x) == FIELD_DECL
4645            && DECL_CONTEXT (x) != current_class_type))
4646       && DECL_NAME (x) == DECL_NAME (TYPE_NAME (current_class_type)))
4647     {
4648       tree scope = context_for_name_lookup (x);
4649       if (TYPE_P (scope) && same_type_p (scope, current_class_type))
4650         {
4651           error ("%qD has the same name as the class in which it is "
4652                  "declared",
4653                  x);
4654           return false;
4655         }
4656     }
4657
4658   /* Get the current binding for NAME in this class, if any.  */
4659   binding = IDENTIFIER_BINDING (name);
4660   if (!binding || binding->scope != class_binding_level)
4661     {
4662       binding = get_class_binding (name, class_binding_level);
4663       /* If a new binding was created, put it at the front of the
4664          IDENTIFIER_BINDING list.  */
4665       if (binding)
4666         {
4667           binding->previous = IDENTIFIER_BINDING (name);
4668           IDENTIFIER_BINDING (name) = binding;
4669         }
4670     }
4671
4672   /* If there is already a binding, then we may need to update the
4673      current value.  */
4674   if (binding && binding->value)
4675     {
4676       tree bval = binding->value;
4677       tree old_decl = NULL_TREE;
4678       tree target_decl = strip_using_decl (decl);
4679       tree target_bval = strip_using_decl (bval);
4680
4681       if (INHERITED_VALUE_BINDING_P (binding))
4682         {
4683           /* If the old binding was from a base class, and was for a
4684              tag name, slide it over to make room for the new binding.
4685              The old binding is still visible if explicitly qualified
4686              with a class-key.  */
4687           if (TREE_CODE (target_bval) == TYPE_DECL
4688               && DECL_ARTIFICIAL (target_bval)
4689               && !(TREE_CODE (target_decl) == TYPE_DECL
4690                    && DECL_ARTIFICIAL (target_decl)))
4691             {
4692               old_decl = binding->type;
4693               binding->type = bval;
4694               binding->value = NULL_TREE;
4695               INHERITED_VALUE_BINDING_P (binding) = 0;
4696             }
4697           else
4698             {
4699               old_decl = bval;
4700               /* Any inherited type declaration is hidden by the type
4701                  declaration in the derived class.  */
4702               if (TREE_CODE (target_decl) == TYPE_DECL
4703                   && DECL_ARTIFICIAL (target_decl))
4704                 binding->type = NULL_TREE;
4705             }
4706         }
4707       else if (TREE_CODE (target_decl) == OVERLOAD
4708                && OVL_P (target_bval))
4709         old_decl = bval;
4710       else if (TREE_CODE (decl) == USING_DECL
4711                && TREE_CODE (bval) == USING_DECL
4712                && same_type_p (USING_DECL_SCOPE (decl),
4713                                USING_DECL_SCOPE (bval)))
4714         /* This is a using redeclaration that will be diagnosed later
4715            in supplement_binding */
4716         ;
4717       else if (TREE_CODE (decl) == USING_DECL
4718                && TREE_CODE (bval) == USING_DECL
4719                && DECL_DEPENDENT_P (decl)
4720                && DECL_DEPENDENT_P (bval))
4721         return true;
4722       else if (TREE_CODE (decl) == USING_DECL
4723                && OVL_P (target_bval))
4724         old_decl = bval;
4725       else if (TREE_CODE (bval) == USING_DECL
4726                && OVL_P (target_decl))
4727         return true;
4728
4729       if (old_decl && binding->scope == class_binding_level)
4730         {
4731           binding->value = x;
4732           /* It is always safe to clear INHERITED_VALUE_BINDING_P
4733              here.  This function is only used to register bindings
4734              from with the class definition itself.  */
4735           INHERITED_VALUE_BINDING_P (binding) = 0;
4736           return true;
4737         }
4738     }
4739
4740   /* Note that we declared this value so that we can issue an error if
4741      this is an invalid redeclaration of a name already used for some
4742      other purpose.  */
4743   note_name_declared_in_class (name, decl);
4744
4745   /* If we didn't replace an existing binding, put the binding on the
4746      stack of bindings for the identifier, and update the shadowed
4747      list.  */
4748   if (binding && binding->scope == class_binding_level)
4749     /* Supplement the existing binding.  */
4750     ok = supplement_binding (binding, decl);
4751   else
4752     {
4753       /* Create a new binding.  */
4754       push_binding (name, decl, class_binding_level);
4755       ok = true;
4756     }
4757
4758   return ok;
4759 }
4760
4761 /* Wrapper for push_class_level_binding_1.  */
4762
4763 bool
4764 push_class_level_binding (tree name, tree x)
4765 {
4766   bool ret;
4767   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
4768   ret = push_class_level_binding_1 (name, x);
4769   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
4770   return ret;
4771 }
4772
4773 /* Process "using SCOPE::NAME" in a class scope.  Return the
4774    USING_DECL created.  */
4775
4776 tree
4777 do_class_using_decl (tree scope, tree name)
4778 {
4779   if (name == error_mark_node)
4780     return NULL_TREE;
4781
4782   if (!scope || !TYPE_P (scope))
4783     {
4784       error ("using-declaration for non-member at class scope");
4785       return NULL_TREE;
4786     }
4787
4788   /* Make sure the name is not invalid */
4789   if (TREE_CODE (name) == BIT_NOT_EXPR)
4790     {
4791       error ("%<%T::%D%> names destructor", scope, name);
4792       return NULL_TREE;
4793     }
4794
4795   /* Using T::T declares inheriting ctors, even if T is a typedef.  */
4796   if (MAYBE_CLASS_TYPE_P (scope)
4797       && (name == TYPE_IDENTIFIER (scope)
4798           || constructor_name_p (name, scope)))
4799     {
4800       maybe_warn_cpp0x (CPP0X_INHERITING_CTORS);
4801       name = ctor_identifier;
4802       CLASSTYPE_NON_AGGREGATE (current_class_type) = true;
4803     }
4804
4805   /* Cannot introduce a constructor name.  */
4806   if (constructor_name_p (name, current_class_type))
4807     {
4808       error ("%<%T::%D%> names constructor in %qT",
4809              scope, name, current_class_type);
4810       return NULL_TREE;
4811     }
4812
4813   /* From [namespace.udecl]:
4814
4815        A using-declaration used as a member-declaration shall refer to a
4816        member of a base class of the class being defined.
4817
4818      In general, we cannot check this constraint in a template because
4819      we do not know the entire set of base classes of the current
4820      class type. Morover, if SCOPE is dependent, it might match a
4821      non-dependent base.  */
4822
4823   tree decl = NULL_TREE;
4824   if (!dependent_scope_p (scope))
4825     {
4826       base_kind b_kind;
4827       tree binfo = lookup_base (current_class_type, scope, ba_any, &b_kind,
4828                                 tf_warning_or_error);
4829       if (b_kind < bk_proper_base)
4830         {
4831           /* If there are dependent bases, scope might resolve at
4832              instantiation time, even if it isn't exactly one of the
4833              dependent bases.  */
4834           if (b_kind == bk_same_type || !any_dependent_bases_p ())
4835             {
4836               error_not_base_type (scope, current_class_type);
4837               return NULL_TREE;
4838             }
4839         }
4840       else if (name == ctor_identifier && !binfo_direct_p (binfo))
4841         {
4842           error ("cannot inherit constructors from indirect base %qT", scope);
4843           return NULL_TREE;
4844         }
4845       else if (!IDENTIFIER_CONV_OP_P (name)
4846                || !dependent_type_p (TREE_TYPE (name)))
4847         {
4848           decl = lookup_member (binfo, name, 0, false, tf_warning_or_error);
4849           if (!decl)
4850             {
4851               error ("no members matching %<%T::%D%> in %q#T", scope, name,
4852                      scope);
4853               return NULL_TREE;
4854             }
4855
4856           /* The binfo from which the functions came does not matter.  */
4857           if (BASELINK_P (decl))
4858             decl = BASELINK_FUNCTIONS (decl);
4859         }
4860     }
4861
4862   tree value = build_lang_decl (USING_DECL, name, NULL_TREE);
4863   USING_DECL_DECLS (value) = decl;
4864   USING_DECL_SCOPE (value) = scope;
4865   DECL_DEPENDENT_P (value) = !decl;
4866
4867   return value;
4868 }
4869
4870 \f
4871 /* Return the binding for NAME in NS.  If NS is NULL, look in
4872    global_namespace.  */
4873
4874 tree
4875 get_namespace_binding (tree ns, tree name)
4876 {
4877   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
4878   if (!ns)
4879     ns = global_namespace;
4880   gcc_checking_assert (!DECL_NAMESPACE_ALIAS (ns));
4881   tree ret = find_namespace_value (ns, name);
4882   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
4883   return ret;
4884 }
4885
4886 /* Push internal DECL into the global namespace.  Does not do the
4887    full overload fn handling and does not add it to the list of things
4888    in the namespace.  */
4889
4890 void
4891 set_global_binding (tree decl)
4892 {
4893   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
4894
4895   tree *slot = find_namespace_slot (global_namespace, DECL_NAME (decl), true);
4896
4897   if (*slot)
4898     /* The user's placed something in the implementor's namespace.  */
4899     diagnose_name_conflict (decl, MAYBE_STAT_DECL (*slot));
4900
4901   /* Force the binding, so compiler internals continue to work.  */
4902   *slot = decl;
4903
4904   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
4905 }
4906
4907 /* Set the context of a declaration to scope. Complain if we are not
4908    outside scope.  */
4909
4910 void
4911 set_decl_namespace (tree decl, tree scope, bool friendp)
4912 {
4913   /* Get rid of namespace aliases.  */
4914   scope = ORIGINAL_NAMESPACE (scope);
4915
4916   /* It is ok for friends to be qualified in parallel space.  */
4917   if (!friendp && !is_nested_namespace (current_namespace, scope))
4918     error ("declaration of %qD not in a namespace surrounding %qD",
4919            decl, scope);
4920   DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
4921
4922   /* See whether this has been declared in the namespace or inline
4923      children.  */
4924   tree old = NULL_TREE;
4925   {
4926     name_lookup lookup (DECL_NAME (decl), LOOKUP_HIDDEN);
4927     if (!lookup.search_qualified (scope, /*usings=*/false))
4928       /* No old declaration at all.  */
4929       goto not_found;
4930     old = lookup.value;
4931   }
4932
4933   /* If it's a TREE_LIST, the result of the lookup was ambiguous.  */
4934   if (TREE_CODE (old) == TREE_LIST)
4935     {
4936     ambiguous:
4937       DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
4938       error ("reference to %qD is ambiguous", decl);
4939       print_candidates (old);
4940       return;
4941     }
4942
4943   if (!DECL_DECLARES_FUNCTION_P (decl))
4944     {
4945       /* Don't compare non-function decls with decls_match here, since
4946          it can't check for the correct constness at this
4947          point.  pushdecl will find those errors later.  */
4948
4949       /* We might have found it in an inline namespace child of SCOPE.  */
4950       if (TREE_CODE (decl) == TREE_CODE (old))
4951         DECL_CONTEXT (decl) = DECL_CONTEXT (old);
4952
4953     found:
4954       /* Writing "N::i" to declare something directly in "N" is invalid.  */
4955       if (CP_DECL_CONTEXT (decl) == current_namespace
4956           && at_namespace_scope_p ())
4957         error ("explicit qualification in declaration of %qD", decl);
4958       return;
4959     }
4960
4961   /* Since decl is a function, old should contain a function decl.  */
4962   if (!OVL_P (old))
4963     goto not_found;
4964
4965   /* We handle these in check_explicit_instantiation_namespace.  */
4966   if (processing_explicit_instantiation)
4967     return;
4968   if (processing_template_decl || processing_specialization)
4969     /* We have not yet called push_template_decl to turn a
4970        FUNCTION_DECL into a TEMPLATE_DECL, so the declarations won't
4971        match.  But, we'll check later, when we construct the
4972        template.  */
4973     return;
4974   /* Instantiations or specializations of templates may be declared as
4975      friends in any namespace.  */
4976   if (friendp && DECL_USE_TEMPLATE (decl))
4977     return;
4978
4979   tree found;
4980   found = NULL_TREE;
4981
4982   for (lkp_iterator iter (old); iter; ++iter)
4983     {
4984       if (iter.using_p ())
4985         continue;
4986
4987       tree ofn = *iter;
4988
4989       /* Adjust DECL_CONTEXT first so decls_match will return true
4990          if DECL will match a declaration in an inline namespace.  */
4991       DECL_CONTEXT (decl) = DECL_CONTEXT (ofn);
4992       if (decls_match (decl, ofn))
4993         {
4994           if (found)
4995             {
4996               /* We found more than one matching declaration.  */
4997               DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
4998               goto ambiguous;
4999             }
5000           found = ofn;
5001         }
5002     }
5003
5004   if (found)
5005     {
5006       if (DECL_HIDDEN_FRIEND_P (found))
5007         {
5008           pedwarn (DECL_SOURCE_LOCATION (decl), 0,
5009                    "%qD has not been declared within %qD", decl, scope);
5010           inform (DECL_SOURCE_LOCATION (found),
5011                   "only here as a %<friend%>");
5012         }
5013       DECL_CONTEXT (decl) = DECL_CONTEXT (found);
5014       goto found;
5015     }
5016
5017  not_found:
5018   /* It didn't work, go back to the explicit scope.  */
5019   DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
5020   error ("%qD should have been declared inside %qD", decl, scope);
5021 }
5022
5023 /* Return the namespace where the current declaration is declared.  */
5024
5025 tree
5026 current_decl_namespace (void)
5027 {
5028   tree result;
5029   /* If we have been pushed into a different namespace, use it.  */
5030   if (!vec_safe_is_empty (decl_namespace_list))
5031     return decl_namespace_list->last ();
5032
5033   if (current_class_type)
5034     result = decl_namespace_context (current_class_type);
5035   else if (current_function_decl)
5036     result = decl_namespace_context (current_function_decl);
5037   else
5038     result = current_namespace;
5039   return result;
5040 }
5041
5042 /* Process any ATTRIBUTES on a namespace definition.  Returns true if
5043    attribute visibility is seen.  */
5044
5045 bool
5046 handle_namespace_attrs (tree ns, tree attributes)
5047 {
5048   tree d;
5049   bool saw_vis = false;
5050
5051   if (attributes == error_mark_node)
5052     return false;
5053
5054   for (d = attributes; d; d = TREE_CHAIN (d))
5055     {
5056       tree name = get_attribute_name (d);
5057       tree args = TREE_VALUE (d);
5058
5059       if (is_attribute_p ("visibility", name))
5060         {
5061           /* attribute visibility is a property of the syntactic block
5062              rather than the namespace as a whole, so we don't touch the
5063              NAMESPACE_DECL at all.  */
5064           tree x = args ? TREE_VALUE (args) : NULL_TREE;
5065           if (x == NULL_TREE || TREE_CODE (x) != STRING_CST || TREE_CHAIN (args))
5066             {
5067               warning (OPT_Wattributes,
5068                        "%qD attribute requires a single NTBS argument",
5069                        name);
5070               continue;
5071             }
5072
5073           if (!TREE_PUBLIC (ns))
5074             warning (OPT_Wattributes,
5075                      "%qD attribute is meaningless since members of the "
5076                      "anonymous namespace get local symbols", name);
5077
5078           push_visibility (TREE_STRING_POINTER (x), 1);
5079           saw_vis = true;
5080         }
5081       else if (is_attribute_p ("abi_tag", name))
5082         {
5083           if (!DECL_NAME (ns))
5084             {
5085               warning (OPT_Wattributes, "ignoring %qD attribute on anonymous "
5086                        "namespace", name);
5087               continue;
5088             }
5089           if (!DECL_NAMESPACE_INLINE_P (ns))
5090             {
5091               warning (OPT_Wattributes, "ignoring %qD attribute on non-inline "
5092                        "namespace", name);
5093               continue;
5094             }
5095           if (!args)
5096             {
5097               tree dn = DECL_NAME (ns);
5098               args = build_string (IDENTIFIER_LENGTH (dn) + 1,
5099                                    IDENTIFIER_POINTER (dn));
5100               TREE_TYPE (args) = char_array_type_node;
5101               args = fix_string_type (args);
5102               args = build_tree_list (NULL_TREE, args);
5103             }
5104           if (check_abi_tag_args (args, name))
5105             DECL_ATTRIBUTES (ns) = tree_cons (name, args,
5106                                               DECL_ATTRIBUTES (ns));
5107         }
5108       else
5109         {
5110           warning (OPT_Wattributes, "%qD attribute directive ignored",
5111                    name);
5112           continue;
5113         }
5114     }
5115
5116   return saw_vis;
5117 }
5118
5119 /* Temporarily set the namespace for the current declaration.  */
5120
5121 void
5122 push_decl_namespace (tree decl)
5123 {
5124   if (TREE_CODE (decl) != NAMESPACE_DECL)
5125     decl = decl_namespace_context (decl);
5126   vec_safe_push (decl_namespace_list, ORIGINAL_NAMESPACE (decl));
5127 }
5128
5129 /* [namespace.memdef]/2 */
5130
5131 void
5132 pop_decl_namespace (void)
5133 {
5134   decl_namespace_list->pop ();
5135 }
5136
5137 /* Process a namespace-alias declaration.  */
5138
5139 void
5140 do_namespace_alias (tree alias, tree name_space)
5141 {
5142   if (name_space == error_mark_node)
5143     return;
5144
5145   gcc_assert (TREE_CODE (name_space) == NAMESPACE_DECL);
5146
5147   name_space = ORIGINAL_NAMESPACE (name_space);
5148
5149   /* Build the alias.  */
5150   alias = build_lang_decl (NAMESPACE_DECL, alias, void_type_node);
5151   DECL_NAMESPACE_ALIAS (alias) = name_space;
5152   DECL_EXTERNAL (alias) = 1;
5153   DECL_CONTEXT (alias) = FROB_CONTEXT (current_scope ());
5154   pushdecl (alias);
5155
5156   /* Emit debug info for namespace alias.  */
5157   if (!building_stmt_list_p ())
5158     (*debug_hooks->early_global_decl) (alias);
5159 }
5160
5161 /* Like pushdecl, only it places X in the current namespace,
5162    if appropriate.  */
5163
5164 tree
5165 pushdecl_namespace_level (tree x, bool is_friend)
5166 {
5167   cp_binding_level *b = current_binding_level;
5168   tree t;
5169
5170   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
5171   t = do_pushdecl_with_scope
5172     (x, NAMESPACE_LEVEL (current_namespace), is_friend);
5173
5174   /* Now, the type_shadowed stack may screw us.  Munge it so it does
5175      what we want.  */
5176   if (TREE_CODE (t) == TYPE_DECL)
5177     {
5178       tree name = DECL_NAME (t);
5179       tree newval;
5180       tree *ptr = (tree *)0;
5181       for (; !global_scope_p (b); b = b->level_chain)
5182         {
5183           tree shadowed = b->type_shadowed;
5184           for (; shadowed; shadowed = TREE_CHAIN (shadowed))
5185             if (TREE_PURPOSE (shadowed) == name)
5186               {
5187                 ptr = &TREE_VALUE (shadowed);
5188                 /* Can't break out of the loop here because sometimes
5189                    a binding level will have duplicate bindings for
5190                    PT names.  It's gross, but I haven't time to fix it.  */
5191               }
5192         }
5193       newval = TREE_TYPE (t);
5194       if (ptr == (tree *)0)
5195         {
5196           /* @@ This shouldn't be needed.  My test case "zstring.cc" trips
5197              up here if this is changed to an assertion.  --KR  */
5198           SET_IDENTIFIER_TYPE_VALUE (name, t);
5199         }
5200       else
5201         {
5202           *ptr = newval;
5203         }
5204     }
5205   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
5206   return t;
5207 }
5208
5209 /* Process a using-declaration appearing in namespace scope.  */
5210
5211 void
5212 finish_namespace_using_decl (tree decl, tree scope, tree name)
5213 {
5214   tree orig_decl = decl;
5215
5216   gcc_checking_assert (current_binding_level->kind == sk_namespace
5217                        && !processing_template_decl);
5218   decl = validate_nonmember_using_decl (decl, scope, name);
5219   if (decl == NULL_TREE)
5220     return;
5221
5222   tree *slot = find_namespace_slot (current_namespace, name, true);
5223   tree val = slot ? MAYBE_STAT_DECL (*slot) : NULL_TREE;
5224   tree type = slot ? MAYBE_STAT_TYPE (*slot) : NULL_TREE;
5225   do_nonmember_using_decl (scope, name, &val, &type);
5226   if (STAT_HACK_P (*slot))
5227     {
5228       STAT_DECL (*slot) = val;
5229       STAT_TYPE (*slot) = type;
5230     }
5231   else if (type)
5232     *slot = stat_hack (val, type);
5233   else
5234     *slot = val;
5235
5236   /* Emit debug info.  */
5237   cp_emit_debug_info_for_using (orig_decl, current_namespace);
5238 }
5239
5240 /* Process a using-declaration at function scope.  */
5241
5242 void
5243 finish_local_using_decl (tree decl, tree scope, tree name)
5244 {
5245   tree orig_decl = decl;
5246
5247   gcc_checking_assert (current_binding_level->kind != sk_class
5248                        && current_binding_level->kind != sk_namespace);
5249   decl = validate_nonmember_using_decl (decl, scope, name);
5250   if (decl == NULL_TREE)
5251     return;
5252
5253   add_decl_expr (decl);
5254
5255   cxx_binding *binding = find_local_binding (current_binding_level, name);
5256   tree value = binding ? binding->value : NULL_TREE;
5257   tree type = binding ? binding->type : NULL_TREE;
5258
5259   do_nonmember_using_decl (scope, name, &value, &type);
5260
5261   if (!value)
5262     ;
5263   else if (binding && value == binding->value)
5264     ;
5265   else if (binding && binding->value && TREE_CODE (value) == OVERLOAD)
5266     {
5267       update_local_overload (IDENTIFIER_BINDING (name), value);
5268       IDENTIFIER_BINDING (name)->value = value;
5269     }
5270   else
5271     /* Install the new binding.  */
5272     push_local_binding (name, value, true);
5273
5274   if (!type)
5275     ;
5276   else if (binding && type == binding->type)
5277     ;
5278   else
5279     {
5280       push_local_binding (name, type, true);
5281       set_identifier_type_value (name, type);
5282     }
5283
5284   /* Emit debug info.  */
5285   if (!processing_template_decl)
5286     cp_emit_debug_info_for_using (orig_decl, current_scope ());
5287 }
5288
5289 /* Return the declarations that are members of the namespace NS.  */
5290
5291 tree
5292 cp_namespace_decls (tree ns)
5293 {
5294   return NAMESPACE_LEVEL (ns)->names;
5295 }
5296
5297 /* Combine prefer_type and namespaces_only into flags.  */
5298
5299 static int
5300 lookup_flags (int prefer_type, int namespaces_only)
5301 {
5302   if (namespaces_only)
5303     return LOOKUP_PREFER_NAMESPACES;
5304   if (prefer_type > 1)
5305     return LOOKUP_PREFER_TYPES;
5306   if (prefer_type > 0)
5307     return LOOKUP_PREFER_BOTH;
5308   return 0;
5309 }
5310
5311 /* Given a lookup that returned VAL, use FLAGS to decide if we want to
5312    ignore it or not.  Subroutine of lookup_name_real and
5313    lookup_type_scope.  */
5314
5315 static bool
5316 qualify_lookup (tree val, int flags)
5317 {
5318   if (val == NULL_TREE)
5319     return false;
5320   if ((flags & LOOKUP_PREFER_NAMESPACES) && TREE_CODE (val) == NAMESPACE_DECL)
5321     return true;
5322   if (flags & LOOKUP_PREFER_TYPES)
5323     {
5324       tree target_val = strip_using_decl (val);
5325       if (TREE_CODE (target_val) == TYPE_DECL
5326           || TREE_CODE (target_val) == TEMPLATE_DECL)
5327         return true;
5328     }
5329   if (flags & (LOOKUP_PREFER_NAMESPACES | LOOKUP_PREFER_TYPES))
5330     return false;
5331   /* Look through lambda things that we shouldn't be able to see.  */
5332   if (!(flags & LOOKUP_HIDDEN) && is_lambda_ignored_entity (val))
5333     return false;
5334   return true;
5335 }
5336
5337 /* Is there a "using namespace std;" directive within USINGS?  */
5338
5339 static bool
5340 using_directives_contain_std_p (vec<tree, va_gc> *usings)
5341 {
5342   if (!usings)
5343     return false;
5344
5345   for (unsigned ix = usings->length (); ix--;)
5346     if ((*usings)[ix] == std_node)
5347       return true;
5348
5349   return false;
5350 }
5351
5352 /* Is there a "using namespace std;" directive within the current
5353    namespace (or its ancestors)?
5354    Compare with name_lookup::search_unqualified.  */
5355
5356 static bool
5357 has_using_namespace_std_directive_p ()
5358 {
5359   /* Look at local using-directives.  */
5360   for (cp_binding_level *level = current_binding_level;
5361        level->kind != sk_namespace;
5362        level = level->level_chain)
5363     if (using_directives_contain_std_p (level->using_directives))
5364       return true;
5365
5366   /* Look at this namespace and its ancestors.  */
5367   for (tree scope = current_namespace; scope; scope = CP_DECL_CONTEXT (scope))
5368     {
5369       if (using_directives_contain_std_p (DECL_NAMESPACE_USING (scope)))
5370         return true;
5371
5372       if (scope == global_namespace)
5373         break;
5374     }
5375
5376   return false;
5377 }
5378
5379 /* Suggest alternatives for NAME, an IDENTIFIER_NODE for which name
5380    lookup failed.  Search through all available namespaces and print out
5381    possible candidates.  If no exact matches are found, and
5382    SUGGEST_MISSPELLINGS is true, then also look for near-matches and
5383    suggest the best near-match, if there is one.  */
5384
5385 void
5386 suggest_alternatives_for (location_t location, tree name,
5387                           bool suggest_misspellings)
5388 {
5389   vec<tree> candidates = vNULL;
5390   vec<tree> worklist = vNULL;
5391   unsigned limit = PARAM_VALUE (CXX_MAX_NAMESPACES_FOR_DIAGNOSTIC_HELP);
5392   bool limited = false;
5393
5394   /* Breadth-first search of namespaces.  Up to limit namespaces
5395      searched (limit zero == unlimited).  */
5396   worklist.safe_push (global_namespace);
5397   for (unsigned ix = 0; ix != worklist.length (); ix++)
5398     {
5399       tree ns = worklist[ix];
5400       name_lookup lookup (name);
5401
5402       if (lookup.search_qualified (ns, false))
5403         candidates.safe_push (lookup.value);
5404
5405       if (!limited)
5406         {
5407           /* Look for child namespaces.  We have to do this
5408              indirectly because they are chained in reverse order,
5409              which is confusing to the user.  */
5410           vec<tree> children = vNULL;
5411
5412           for (tree decl = NAMESPACE_LEVEL (ns)->names;
5413                decl; decl = TREE_CHAIN (decl))
5414             if (TREE_CODE (decl) == NAMESPACE_DECL
5415                 && !DECL_NAMESPACE_ALIAS (decl)
5416                 && !DECL_NAMESPACE_INLINE_P (decl))
5417               children.safe_push (decl);
5418
5419           while (!limited && !children.is_empty ())
5420             {
5421               if (worklist.length () == limit)
5422                 {
5423                   /* Unconditionally warn that the search was truncated.  */
5424                   inform (location,
5425                           "maximum limit of %d namespaces searched for %qE",
5426                           limit, name);
5427                   limited = true;
5428                 }
5429               else
5430                 worklist.safe_push (children.pop ());
5431             }
5432           children.release ();
5433         }
5434     }
5435   worklist.release ();
5436
5437   if (candidates.length ())
5438     {
5439       inform_n (location, candidates.length (),
5440                 "suggested alternative:",
5441                 "suggested alternatives:");
5442       for (unsigned ix = 0; ix != candidates.length (); ix++)
5443         {
5444           tree val = candidates[ix];
5445
5446           inform (location_of (val), "  %qE", val);
5447         }
5448       candidates.release ();
5449       return;
5450     }
5451
5452   /* No candidates were found in the available namespaces.  */
5453
5454   /* If there's a "using namespace std;" active, and this
5455      is one of the most common "std::" names, then it's probably a
5456      missing #include.  */
5457   if (has_using_namespace_std_directive_p ())
5458     if (maybe_suggest_missing_std_header (location, name))
5459       return;
5460
5461   /* Otherwise, consider misspellings.  */
5462   if (!suggest_misspellings)
5463     return;
5464   if (name_hint hint = lookup_name_fuzzy (name, FUZZY_LOOKUP_NAME,
5465                                           location))
5466     {
5467       /* Show a spelling correction.  */
5468       gcc_rich_location richloc (location);
5469
5470       richloc.add_fixit_replace (hint.suggestion ());
5471       inform (&richloc, "suggested alternative: %qs", hint.suggestion ());
5472     }
5473 }
5474
5475 /* A well-known name within the C++ standard library, returned by
5476    get_std_name_hint.  */
5477
5478 struct std_name_hint
5479 {
5480   /* A name within "std::".  */
5481   const char *name;
5482
5483   /* The header name defining it within the C++ Standard Library
5484      (with '<' and '>').  */
5485   const char *header;
5486
5487   /* The dialect of C++ in which this was added.  */
5488   enum cxx_dialect min_dialect;
5489 };
5490
5491 /* Subroutine of maybe_suggest_missing_header for handling unrecognized names
5492    for some of the most common names within "std::".
5493    Given non-NULL NAME, return the std_name_hint for it, or NULL.  */
5494
5495 static const std_name_hint *
5496 get_std_name_hint (const char *name)
5497 {
5498   static const std_name_hint hints[] = {
5499     /* <any>.  */
5500     {"any", "<any>", cxx17},
5501     {"any_cast", "<any>", cxx17},
5502     {"make_any", "<any>", cxx17},
5503     /* <array>.  */
5504     {"array", "<array>", cxx11},
5505     /* <atomic>.  */
5506     {"atomic", "<atomic>", cxx11},
5507     {"atomic_flag", "<atomic>", cxx11},
5508     /* <bitset>.  */
5509     {"bitset", "<bitset>", cxx11},
5510     /* <complex>.  */
5511     {"complex", "<complex>", cxx98},
5512     {"complex_literals", "<complex>", cxx98},
5513     /* <condition_variable>. */
5514     {"condition_variable", "<condition_variable>", cxx11},
5515     {"condition_variable_any", "<condition_variable>", cxx11},
5516     /* <deque>.  */
5517     {"deque", "<deque>", cxx98},
5518     /* <forward_list>.  */
5519     {"forward_list", "<forward_list>", cxx11},
5520     /* <fstream>.  */
5521     {"basic_filebuf", "<fstream>", cxx98},
5522     {"basic_ifstream", "<fstream>", cxx98},
5523     {"basic_ofstream", "<fstream>", cxx98},
5524     {"basic_fstream", "<fstream>", cxx98},
5525     {"fstream", "<fstream>", cxx98},
5526     {"ifstream", "<fstream>", cxx98},
5527     {"ofstream", "<fstream>", cxx98},
5528     /* <functional>.  */
5529     {"bind", "<functional>", cxx11},
5530     {"function", "<functional>", cxx11},
5531     {"hash", "<functional>", cxx11},
5532     {"mem_fn", "<functional>", cxx11},
5533     /* <future>. */
5534     {"async", "<future>", cxx11},
5535     {"future", "<future>", cxx11},
5536     {"packaged_task", "<future>", cxx11},
5537     {"promise", "<future>", cxx11},
5538     /* <iostream>.  */
5539     {"cin", "<iostream>", cxx98},
5540     {"cout", "<iostream>", cxx98},
5541     {"cerr", "<iostream>", cxx98},
5542     {"clog", "<iostream>", cxx98},
5543     {"wcin", "<iostream>", cxx98},
5544     {"wcout", "<iostream>", cxx98},
5545     {"wclog", "<iostream>", cxx98},
5546     /* <istream>.  */
5547     {"istream", "<istream>", cxx98},
5548     /* <iterator>.  */
5549     {"advance", "<iterator>", cxx98},
5550     {"back_inserter", "<iterator>", cxx98},
5551     {"begin", "<iterator>", cxx11},
5552     {"distance", "<iterator>", cxx98},
5553     {"end", "<iterator>", cxx11},
5554     {"front_inserter", "<iterator>", cxx98},
5555     {"inserter", "<iterator>", cxx98},
5556     {"istream_iterator", "<iterator>", cxx98},
5557     {"istreambuf_iterator", "<iterator>", cxx98},
5558     {"iterator_traits", "<iterator>", cxx98},
5559     {"move_iterator", "<iterator>", cxx11},
5560     {"next", "<iterator>", cxx11},
5561     {"ostream_iterator", "<iterator>", cxx98},
5562     {"ostreambuf_iterator", "<iterator>", cxx98},
5563     {"prev", "<iterator>", cxx11},
5564     {"reverse_iterator", "<iterator>", cxx98},
5565     /* <ostream>.  */
5566     {"ostream", "<ostream>", cxx98},
5567     /* <list>.  */
5568     {"list", "<list>", cxx98},
5569     /* <map>.  */
5570     {"map", "<map>", cxx98},
5571     {"multimap", "<map>", cxx98},
5572     /* <memory>.  */
5573     {"make_shared", "<memory>", cxx11},
5574     {"make_unique", "<memory>", cxx11},
5575     {"shared_ptr", "<memory>", cxx11},
5576     {"unique_ptr", "<memory>", cxx11},
5577     {"weak_ptr", "<memory>", cxx11},
5578     /* <mutex>.  */
5579     {"mutex", "<mutex>", cxx11},
5580     {"timed_mutex", "<mutex>", cxx11},
5581     {"recursive_mutex", "<mutex>", cxx11},
5582     {"recursive_timed_mutex", "<mutex>", cxx11},
5583     {"once_flag", "<mutex>", cxx11},
5584     {"call_once,", "<mutex>", cxx11},
5585     {"lock", "<mutex>", cxx11},
5586     {"scoped_lock", "<mutex>", cxx17},
5587     {"try_lock", "<mutex>", cxx11},
5588     {"lock_guard", "<mutex>", cxx11},
5589     {"unique_lock", "<mutex>", cxx11},
5590     /* <optional>. */
5591     {"optional", "<optional>", cxx17},
5592     {"make_optional", "<optional>", cxx17},
5593     /* <ostream>.  */
5594     {"ostream", "<ostream>", cxx98},
5595     {"wostream", "<ostream>", cxx98},
5596     {"ends", "<ostream>", cxx98},
5597     {"flush", "<ostream>", cxx98},
5598     {"endl", "<ostream>", cxx98},
5599     /* <queue>.  */
5600     {"queue", "<queue>", cxx98},
5601     {"priority_queue", "<queue>", cxx98},
5602     /* <set>.  */
5603     {"set", "<set>", cxx98},
5604     {"multiset", "<set>", cxx98},
5605     /* <shared_mutex>.  */
5606     {"shared_lock", "<shared_mutex>", cxx14},
5607     {"shared_mutex", "<shared_mutex>", cxx17},
5608     {"shared_timed_mutex", "<shared_mutex>", cxx14},
5609     /* <sstream>.  */
5610     {"basic_stringbuf", "<sstream>", cxx98},
5611     {"basic_istringstream", "<sstream>", cxx98},
5612     {"basic_ostringstream", "<sstream>", cxx98},
5613     {"basic_stringstream", "<sstream>", cxx98},
5614     {"istringstream", "<sstream>", cxx98},
5615     {"ostringstream", "<sstream>", cxx98},
5616     {"stringstream", "<sstream>", cxx98},
5617     /* <stack>.  */
5618     {"stack", "<stack>", cxx98},
5619     /* <string>.  */
5620     {"basic_string", "<string>", cxx98},
5621     {"string", "<string>", cxx98},
5622     {"wstring", "<string>", cxx98},
5623     {"u16string", "<string>", cxx11},
5624     {"u32string", "<string>", cxx11},
5625     /* <string_view>.  */
5626     {"string_view", "<string_view>", cxx17},
5627     /* <thread>.  */
5628     {"thread", "<thread>", cxx11},
5629     /* <tuple>.  */
5630     {"make_tuple", "<tuple>", cxx11},
5631     {"tuple", "<tuple>", cxx11},
5632     {"tuple_element", "<tuple>", cxx11},
5633     {"tuple_size", "<tuple>", cxx11},
5634     /* <unordered_map>.  */
5635     {"unordered_map", "<unordered_map>", cxx11},
5636     {"unordered_multimap", "<unordered_map>", cxx11},
5637     /* <unordered_set>.  */
5638     {"unordered_set", "<unordered_set>", cxx11},
5639     {"unordered_multiset", "<unordered_set>", cxx11},
5640     /* <utility>.  */
5641     {"declval", "<utility>", cxx11},
5642     {"forward", "<utility>", cxx11},
5643     {"make_pair", "<utility>", cxx98},
5644     {"move", "<utility>", cxx11},
5645     {"pair", "<utility>", cxx98},
5646     /* <variant>.  */
5647     {"variant", "<variant>", cxx17},
5648     {"visit", "<variant>", cxx17},
5649     /* <vector>.  */
5650     {"vector", "<vector>", cxx98},
5651   };
5652   const size_t num_hints = sizeof (hints) / sizeof (hints[0]);
5653   for (size_t i = 0; i < num_hints; i++)
5654     {
5655       if (strcmp (name, hints[i].name) == 0)
5656         return &hints[i];
5657     }
5658   return NULL;
5659 }
5660
5661 /* Describe DIALECT.  */
5662
5663 static const char *
5664 get_cxx_dialect_name (enum cxx_dialect dialect)
5665 {
5666   switch (dialect)
5667     {
5668     default:
5669       gcc_unreachable ();
5670     case cxx98:
5671       return "C++98";
5672     case cxx11:
5673       return "C++11";
5674     case cxx14:
5675       return "C++14";
5676     case cxx17:
5677       return "C++17";
5678     case cxx2a:
5679       return "C++2a";
5680     }
5681 }
5682
5683 /* Suggest pertinent header files for NAME at LOCATION, for common
5684    names within the "std" namespace.
5685    Return true iff a suggestion was offered.  */
5686
5687 static bool
5688 maybe_suggest_missing_std_header (location_t location, tree name)
5689 {
5690   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
5691
5692   const char *name_str = IDENTIFIER_POINTER (name);
5693   const std_name_hint *header_hint = get_std_name_hint (name_str);
5694   if (!header_hint)
5695     return false;
5696
5697   gcc_rich_location richloc (location);
5698   if (cxx_dialect >= header_hint->min_dialect)
5699     {
5700       const char *header = header_hint->header;
5701       maybe_add_include_fixit (&richloc, header);
5702       inform (&richloc,
5703               "%<std::%s%> is defined in header %qs;"
5704               " did you forget to %<#include %s%>?",
5705               name_str, header, header);
5706     }
5707   else
5708     {
5709       inform (&richloc,
5710               "%<std::%s%> is only available from %s onwards",
5711               name_str, get_cxx_dialect_name (header_hint->min_dialect));
5712     }
5713   return true;
5714 }
5715
5716 /* If SCOPE is the "std" namespace, then suggest pertinent header
5717    files for NAME at LOCATION.
5718    Return true iff a suggestion was offered.  */
5719
5720 static bool
5721 maybe_suggest_missing_header (location_t location, tree name, tree scope)
5722 {
5723   if (scope == NULL_TREE)
5724     return false;
5725   if (TREE_CODE (scope) != NAMESPACE_DECL)
5726     return false;
5727   /* We only offer suggestions for the "std" namespace.  */
5728   if (scope != std_node)
5729     return false;
5730   return maybe_suggest_missing_std_header (location, name);
5731 }
5732
5733 /* Look for alternatives for NAME, an IDENTIFIER_NODE for which name
5734    lookup failed within the explicitly provided SCOPE.  Suggest the
5735    the best meaningful candidates (if any) as a fix-it hint.
5736    Return true iff a suggestion was provided.  */
5737
5738 bool
5739 suggest_alternative_in_explicit_scope (location_t location, tree name,
5740                                        tree scope)
5741 {
5742   /* Something went very wrong; don't suggest anything.  */
5743   if (name == error_mark_node)
5744     return false;
5745
5746   /* Resolve any namespace aliases.  */
5747   scope = ORIGINAL_NAMESPACE (scope);
5748
5749   if (maybe_suggest_missing_header (location, name, scope))
5750     return true;
5751
5752   cp_binding_level *level = NAMESPACE_LEVEL (scope);
5753
5754   best_match <tree, const char *> bm (name);
5755   consider_binding_level (name, bm, level, false, FUZZY_LOOKUP_NAME);
5756
5757   /* See if we have a good suggesion for the user.  */
5758   const char *fuzzy_name = bm.get_best_meaningful_candidate ();
5759   if (fuzzy_name)
5760     {
5761       gcc_rich_location richloc (location);
5762       richloc.add_fixit_replace (fuzzy_name);
5763       inform (&richloc, "suggested alternative: %qs",
5764               fuzzy_name);
5765       return true;
5766     }
5767
5768   return false;
5769 }
5770
5771 /* Look up NAME (an IDENTIFIER_NODE) in SCOPE (either a NAMESPACE_DECL
5772    or a class TYPE).
5773
5774    If PREFER_TYPE is > 0, we only return TYPE_DECLs or namespaces.
5775    If PREFER_TYPE is > 1, we only return TYPE_DECLs.
5776
5777    Returns a DECL (or OVERLOAD, or BASELINK) representing the
5778    declaration found.  If no suitable declaration can be found,
5779    ERROR_MARK_NODE is returned.  If COMPLAIN is true and SCOPE is
5780    neither a class-type nor a namespace a diagnostic is issued.  */
5781
5782 tree
5783 lookup_qualified_name (tree scope, tree name, int prefer_type, bool complain,
5784                        bool find_hidden)
5785 {
5786   tree t = NULL_TREE;
5787
5788   if (TREE_CODE (scope) == NAMESPACE_DECL)
5789     {
5790       int flags = lookup_flags (prefer_type, /*namespaces_only*/false);
5791       if (find_hidden)
5792         flags |= LOOKUP_HIDDEN;
5793       name_lookup lookup (name, flags);
5794
5795       if (qualified_namespace_lookup (scope, &lookup))
5796         t = lookup.value;
5797     }
5798   else if (cxx_dialect != cxx98 && TREE_CODE (scope) == ENUMERAL_TYPE)
5799     t = lookup_enumerator (scope, name);
5800   else if (is_class_type (scope, complain))
5801     t = lookup_member (scope, name, 2, prefer_type, tf_warning_or_error);
5802
5803   if (!t)
5804     return error_mark_node;
5805   return t;
5806 }
5807
5808 /* [namespace.qual]
5809    Accepts the NAME to lookup and its qualifying SCOPE.
5810    Returns the name/type pair found into the cxx_binding *RESULT,
5811    or false on error.  */
5812
5813 static bool
5814 qualified_namespace_lookup (tree scope, name_lookup *lookup)
5815 {
5816   timevar_start (TV_NAME_LOOKUP);
5817   query_oracle (lookup->name);
5818   bool found = lookup->search_qualified (ORIGINAL_NAMESPACE (scope));
5819   timevar_stop (TV_NAME_LOOKUP);
5820   return found;
5821 }
5822
5823 /* Helper function for lookup_name_fuzzy.
5824    Traverse binding level LVL, looking for good name matches for NAME
5825    (and BM).  */
5826 static void
5827 consider_binding_level (tree name, best_match <tree, const char *> &bm,
5828                         cp_binding_level *lvl, bool look_within_fields,
5829                         enum lookup_name_fuzzy_kind kind)
5830 {
5831   if (look_within_fields)
5832     if (lvl->this_entity && TREE_CODE (lvl->this_entity) == RECORD_TYPE)
5833       {
5834         tree type = lvl->this_entity;
5835         bool want_type_p = (kind == FUZZY_LOOKUP_TYPENAME);
5836         tree best_matching_field
5837           = lookup_member_fuzzy (type, name, want_type_p);
5838         if (best_matching_field)
5839           bm.consider (IDENTIFIER_POINTER (best_matching_field));
5840       }
5841
5842   /* Only suggest names reserved for the implementation if NAME begins
5843      with an underscore.  */
5844   bool consider_implementation_names = (IDENTIFIER_POINTER (name)[0] == '_');
5845
5846   for (tree t = lvl->names; t; t = TREE_CHAIN (t))
5847     {
5848       tree d = t;
5849
5850       /* OVERLOADs or decls from using declaration are wrapped into
5851          TREE_LIST.  */
5852       if (TREE_CODE (d) == TREE_LIST)
5853         d = OVL_FIRST (TREE_VALUE (d));
5854
5855       /* Don't use bindings from implicitly declared functions,
5856          as they were likely misspellings themselves.  */
5857       if (TREE_TYPE (d) == error_mark_node)
5858         continue;
5859
5860       /* Skip anticipated decls of builtin functions.  */
5861       if (TREE_CODE (d) == FUNCTION_DECL
5862           && DECL_BUILT_IN (d)
5863           && DECL_ANTICIPATED (d))
5864         continue;
5865
5866       /* Skip compiler-generated variables (e.g. __for_begin/__for_end
5867          within range for).  */
5868       if (TREE_CODE (d) == VAR_DECL
5869           && DECL_ARTIFICIAL (d))
5870         continue;
5871
5872       tree suggestion = DECL_NAME (d);
5873       if (!suggestion)
5874         continue;
5875
5876       /* Don't suggest names that are for anonymous aggregate types, as
5877          they are an implementation detail generated by the compiler.  */
5878       if (anon_aggrname_p (suggestion))
5879         continue;
5880
5881       const char *suggestion_str = IDENTIFIER_POINTER (suggestion);
5882
5883       /* Ignore internal names with spaces in them.  */
5884       if (strchr (suggestion_str, ' '))
5885         continue;
5886
5887       /* Don't suggest names that are reserved for use by the
5888          implementation, unless NAME began with an underscore.  */
5889       if (name_reserved_for_implementation_p (suggestion_str)
5890           && !consider_implementation_names)
5891         continue;
5892
5893       bm.consider (suggestion_str);
5894     }
5895 }
5896
5897 /* Subclass of deferred_diagnostic.  Notify the user that the
5898    given macro was used before it was defined.
5899    This can be done in the C++ frontend since tokenization happens
5900    upfront.  */
5901
5902 class macro_use_before_def : public deferred_diagnostic
5903 {
5904  public:
5905   /* Factory function.  Return a new macro_use_before_def instance if
5906      appropriate, or return NULL. */
5907   static macro_use_before_def *
5908   maybe_make (location_t use_loc, cpp_hashnode *macro)
5909   {
5910     source_location def_loc = cpp_macro_definition_location (macro);
5911     if (def_loc == UNKNOWN_LOCATION)
5912       return NULL;
5913
5914     /* We only want to issue a note if the macro was used *before* it was
5915        defined.
5916        We don't want to issue a note for cases where a macro was incorrectly
5917        used, leaving it unexpanded (e.g. by using the wrong argument
5918        count).  */
5919     if (!linemap_location_before_p (line_table, use_loc, def_loc))
5920       return NULL;
5921
5922     return new macro_use_before_def (use_loc, macro);
5923   }
5924
5925  private:
5926   /* Ctor.  LOC is the location of the usage.  MACRO is the
5927      macro that was used.  */
5928   macro_use_before_def (location_t loc, cpp_hashnode *macro)
5929   : deferred_diagnostic (loc), m_macro (macro)
5930   {
5931     gcc_assert (macro);
5932   }
5933
5934   ~macro_use_before_def ()
5935   {
5936     if (is_suppressed_p ())
5937       return;
5938
5939     inform (get_location (), "the macro %qs had not yet been defined",
5940             (const char *)m_macro->ident.str);
5941     inform (cpp_macro_definition_location (m_macro),
5942             "it was later defined here");
5943   }
5944
5945  private:
5946   cpp_hashnode *m_macro;
5947 };
5948
5949 /* Determine if it can ever make sense to offer RID as a suggestion for
5950    a misspelling.
5951
5952    Subroutine of lookup_name_fuzzy.  */
5953
5954 static bool
5955 suggest_rid_p  (enum rid rid)
5956 {
5957   switch (rid)
5958     {
5959     /* Support suggesting function-like keywords.  */
5960     case RID_STATIC_ASSERT:
5961       return true;
5962
5963     default:
5964       /* Support suggesting the various decl-specifier words, to handle
5965          e.g. "singed" vs "signed" typos.  */
5966       if (cp_keyword_starts_decl_specifier_p (rid))
5967         return true;
5968
5969       /* Otherwise, don't offer it.  This avoids suggesting e.g. "if"
5970          and "do" for short misspellings, which are likely to lead to
5971          nonsensical results.  */
5972       return false;
5973     }
5974 }
5975
5976 /* Search for near-matches for NAME within the current bindings, and within
5977    macro names, returning the best match as a const char *, or NULL if
5978    no reasonable match is found.
5979
5980    Use LOC for any deferred diagnostics.  */
5981
5982 name_hint
5983 lookup_name_fuzzy (tree name, enum lookup_name_fuzzy_kind kind, location_t loc)
5984 {
5985   gcc_assert (TREE_CODE (name) == IDENTIFIER_NODE);
5986
5987   /* First, try some well-known names in the C++ standard library, in case
5988      the user forgot a #include.  */
5989   const char *header_hint
5990     = get_cp_stdlib_header_for_name (IDENTIFIER_POINTER (name));
5991   if (header_hint)
5992     return name_hint (NULL,
5993                       new suggest_missing_header (loc,
5994                                                   IDENTIFIER_POINTER (name),
5995                                                   header_hint));
5996
5997   best_match <tree, const char *> bm (name);
5998
5999   cp_binding_level *lvl;
6000   for (lvl = scope_chain->class_bindings; lvl; lvl = lvl->level_chain)
6001     consider_binding_level (name, bm, lvl, true, kind);
6002
6003   for (lvl = current_binding_level; lvl; lvl = lvl->level_chain)
6004     consider_binding_level (name, bm, lvl, false, kind);
6005
6006   /* Consider macros: if the user misspelled a macro name e.g. "SOME_MACRO"
6007      as:
6008        x = SOME_OTHER_MACRO (y);
6009      then "SOME_OTHER_MACRO" will survive to the frontend and show up
6010      as a misspelled identifier.
6011
6012      Use the best distance so far so that a candidate is only set if
6013      a macro is better than anything so far.  This allows early rejection
6014      (without calculating the edit distance) of macro names that must have
6015      distance >= bm.get_best_distance (), and means that we only get a
6016      non-NULL result for best_macro_match if it's better than any of
6017      the identifiers already checked.  */
6018   best_macro_match bmm (name, bm.get_best_distance (), parse_in);
6019   cpp_hashnode *best_macro = bmm.get_best_meaningful_candidate ();
6020   /* If a macro is the closest so far to NAME, consider it.  */
6021   if (best_macro)
6022     bm.consider ((const char *)best_macro->ident.str);
6023   else if (bmm.get_best_distance () == 0)
6024     {
6025       /* If we have an exact match for a macro name, then either the
6026          macro was used with the wrong argument count, or the macro
6027          has been used before it was defined.  */
6028       cpp_hashnode *macro = bmm.blithely_get_best_candidate ();
6029       if (macro && (macro->flags & NODE_BUILTIN) == 0)
6030         return name_hint (NULL,
6031                           macro_use_before_def::maybe_make (loc, macro));
6032     }
6033
6034   /* Try the "starts_decl_specifier_p" keywords to detect
6035      "singed" vs "signed" typos.  */
6036   for (unsigned i = 0; i < num_c_common_reswords; i++)
6037     {
6038       const c_common_resword *resword = &c_common_reswords[i];
6039
6040       if (!suggest_rid_p (resword->rid))
6041         continue;
6042
6043       tree resword_identifier = ridpointers [resword->rid];
6044       if (!resword_identifier)
6045         continue;
6046       gcc_assert (TREE_CODE (resword_identifier) == IDENTIFIER_NODE);
6047
6048       /* Only consider reserved words that survived the
6049          filtering in init_reswords (e.g. for -std).  */
6050       if (!IDENTIFIER_KEYWORD_P (resword_identifier))
6051         continue;
6052
6053       bm.consider (IDENTIFIER_POINTER (resword_identifier));
6054     }
6055
6056   return name_hint (bm.get_best_meaningful_candidate (), NULL);
6057 }
6058
6059 /* Subroutine of outer_binding.
6060
6061    Returns TRUE if BINDING is a binding to a template parameter of
6062    SCOPE.  In that case SCOPE is the scope of a primary template
6063    parameter -- in the sense of G++, i.e, a template that has its own
6064    template header.
6065
6066    Returns FALSE otherwise.  */
6067
6068 static bool
6069 binding_to_template_parms_of_scope_p (cxx_binding *binding,
6070                                       cp_binding_level *scope)
6071 {
6072   tree binding_value, tmpl, tinfo;
6073   int level;
6074
6075   if (!binding || !scope || !scope->this_entity)
6076     return false;
6077
6078   binding_value = binding->value ?  binding->value : binding->type;
6079   tinfo = get_template_info (scope->this_entity);
6080
6081   /* BINDING_VALUE must be a template parm.  */
6082   if (binding_value == NULL_TREE
6083       || (!DECL_P (binding_value)
6084           || !DECL_TEMPLATE_PARM_P (binding_value)))
6085     return false;
6086
6087   /*  The level of BINDING_VALUE.  */
6088   level =
6089     template_type_parameter_p (binding_value)
6090     ? TEMPLATE_PARM_LEVEL (TEMPLATE_TYPE_PARM_INDEX
6091                          (TREE_TYPE (binding_value)))
6092     : TEMPLATE_PARM_LEVEL (DECL_INITIAL (binding_value));
6093
6094   /* The template of the current scope, iff said scope is a primary
6095      template.  */
6096   tmpl = (tinfo
6097           && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
6098           ? TI_TEMPLATE (tinfo)
6099           : NULL_TREE);
6100
6101   /* If the level of the parm BINDING_VALUE equals the depth of TMPL,
6102      then BINDING_VALUE is a parameter of TMPL.  */
6103   return (tmpl && level == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
6104 }
6105
6106 /* Return the innermost non-namespace binding for NAME from a scope
6107    containing BINDING, or, if BINDING is NULL, the current scope.
6108    Please note that for a given template, the template parameters are
6109    considered to be in the scope containing the current scope.
6110    If CLASS_P is false, then class bindings are ignored.  */
6111
6112 cxx_binding *
6113 outer_binding (tree name,
6114                cxx_binding *binding,
6115                bool class_p)
6116 {
6117   cxx_binding *outer;
6118   cp_binding_level *scope;
6119   cp_binding_level *outer_scope;
6120
6121   if (binding)
6122     {
6123       scope = binding->scope->level_chain;
6124       outer = binding->previous;
6125     }
6126   else
6127     {
6128       scope = current_binding_level;
6129       outer = IDENTIFIER_BINDING (name);
6130     }
6131   outer_scope = outer ? outer->scope : NULL;
6132
6133   /* Because we create class bindings lazily, we might be missing a
6134      class binding for NAME.  If there are any class binding levels
6135      between the LAST_BINDING_LEVEL and the scope in which OUTER was
6136      declared, we must lookup NAME in those class scopes.  */
6137   if (class_p)
6138     while (scope && scope != outer_scope && scope->kind != sk_namespace)
6139       {
6140         if (scope->kind == sk_class)
6141           {
6142             cxx_binding *class_binding;
6143
6144             class_binding = get_class_binding (name, scope);
6145             if (class_binding)
6146               {
6147                 /* Thread this new class-scope binding onto the
6148                    IDENTIFIER_BINDING list so that future lookups
6149                    find it quickly.  */
6150                 class_binding->previous = outer;
6151                 if (binding)
6152                   binding->previous = class_binding;
6153                 else
6154                   IDENTIFIER_BINDING (name) = class_binding;
6155                 return class_binding;
6156               }
6157           }
6158         /* If we are in a member template, the template parms of the member
6159            template are considered to be inside the scope of the containing
6160            class, but within G++ the class bindings are all pushed between the
6161            template parms and the function body.  So if the outer binding is
6162            a template parm for the current scope, return it now rather than
6163            look for a class binding.  */
6164         if (outer_scope && outer_scope->kind == sk_template_parms
6165             && binding_to_template_parms_of_scope_p (outer, scope))
6166           return outer;
6167
6168         scope = scope->level_chain;
6169       }
6170
6171   return outer;
6172 }
6173
6174 /* Return the innermost block-scope or class-scope value binding for
6175    NAME, or NULL_TREE if there is no such binding.  */
6176
6177 tree
6178 innermost_non_namespace_value (tree name)
6179 {
6180   cxx_binding *binding;
6181   binding = outer_binding (name, /*binding=*/NULL, /*class_p=*/true);
6182   return binding ? binding->value : NULL_TREE;
6183 }
6184
6185 /* Look up NAME in the current binding level and its superiors in the
6186    namespace of variables, functions and typedefs.  Return a ..._DECL
6187    node of some kind representing its definition if there is only one
6188    such declaration, or return a TREE_LIST with all the overloaded
6189    definitions if there are many, or return 0 if it is undefined.
6190    Hidden name, either friend declaration or built-in function, are
6191    not ignored.
6192
6193    If PREFER_TYPE is > 0, we prefer TYPE_DECLs or namespaces.
6194    If PREFER_TYPE is > 1, we reject non-type decls (e.g. namespaces).
6195    Otherwise we prefer non-TYPE_DECLs.
6196
6197    If NONCLASS is nonzero, bindings in class scopes are ignored.  If
6198    BLOCK_P is false, bindings in block scopes are ignored.  */
6199
6200 static tree
6201 lookup_name_real_1 (tree name, int prefer_type, int nonclass, bool block_p,
6202                     int namespaces_only, int flags)
6203 {
6204   cxx_binding *iter;
6205   tree val = NULL_TREE;
6206
6207   query_oracle (name);
6208
6209   /* Conversion operators are handled specially because ordinary
6210      unqualified name lookup will not find template conversion
6211      operators.  */
6212   if (IDENTIFIER_CONV_OP_P (name))
6213     {
6214       cp_binding_level *level;
6215
6216       for (level = current_binding_level;
6217            level && level->kind != sk_namespace;
6218            level = level->level_chain)
6219         {
6220           tree class_type;
6221           tree operators;
6222
6223           /* A conversion operator can only be declared in a class
6224              scope.  */
6225           if (level->kind != sk_class)
6226             continue;
6227
6228           /* Lookup the conversion operator in the class.  */
6229           class_type = level->this_entity;
6230           operators = lookup_fnfields (class_type, name, /*protect=*/0);
6231           if (operators)
6232             return operators;
6233         }
6234
6235       return NULL_TREE;
6236     }
6237
6238   flags |= lookup_flags (prefer_type, namespaces_only);
6239
6240   /* First, look in non-namespace scopes.  */
6241
6242   if (current_class_type == NULL_TREE)
6243     nonclass = 1;
6244
6245   if (block_p || !nonclass)
6246     for (iter = outer_binding (name, NULL, !nonclass);
6247          iter;
6248          iter = outer_binding (name, iter, !nonclass))
6249       {
6250         tree binding;
6251
6252         /* Skip entities we don't want.  */
6253         if (LOCAL_BINDING_P (iter) ? !block_p : nonclass)
6254           continue;
6255
6256         /* If this is the kind of thing we're looking for, we're done.  */
6257         if (qualify_lookup (iter->value, flags))
6258           binding = iter->value;
6259         else if ((flags & LOOKUP_PREFER_TYPES)
6260                  && qualify_lookup (iter->type, flags))
6261           binding = iter->type;
6262         else
6263           binding = NULL_TREE;
6264
6265         if (binding)
6266           {
6267             if (TREE_CODE (binding) == TYPE_DECL && DECL_HIDDEN_P (binding))
6268               {
6269                 /* A non namespace-scope binding can only be hidden in the
6270                    presence of a local class, due to friend declarations.
6271
6272                    In particular, consider:
6273
6274                    struct C;
6275                    void f() {
6276                      struct A {
6277                        friend struct B;
6278                        friend struct C;
6279                        void g() {
6280                          B* b; // error: B is hidden
6281                          C* c; // OK, finds ::C
6282                        } 
6283                      };
6284                      B *b;  // error: B is hidden
6285                      C *c;  // OK, finds ::C
6286                      struct B {};
6287                      B *bb; // OK
6288                    }
6289
6290                    The standard says that "B" is a local class in "f"
6291                    (but not nested within "A") -- but that name lookup
6292                    for "B" does not find this declaration until it is
6293                    declared directly with "f".
6294
6295                    In particular:
6296
6297                    [class.friend]
6298
6299                    If a friend declaration appears in a local class and
6300                    the name specified is an unqualified name, a prior
6301                    declaration is looked up without considering scopes
6302                    that are outside the innermost enclosing non-class
6303                    scope. For a friend function declaration, if there is
6304                    no prior declaration, the program is ill-formed. For a
6305                    friend class declaration, if there is no prior
6306                    declaration, the class that is specified belongs to the
6307                    innermost enclosing non-class scope, but if it is
6308                    subsequently referenced, its name is not found by name
6309                    lookup until a matching declaration is provided in the
6310                    innermost enclosing nonclass scope.
6311
6312                    So just keep looking for a non-hidden binding.
6313                 */
6314                 gcc_assert (TREE_CODE (binding) == TYPE_DECL);
6315                 continue;
6316               }
6317             val = binding;
6318             break;
6319           }
6320       }
6321
6322   /* Now lookup in namespace scopes.  */
6323   if (!val)
6324     {
6325       name_lookup lookup (name, flags);
6326       if (lookup.search_unqualified
6327           (current_decl_namespace (), current_binding_level))
6328         val = lookup.value;
6329     }
6330
6331   /* If we have a single function from a using decl, pull it out.  */
6332   if (val && TREE_CODE (val) == OVERLOAD && !really_overloaded_fn (val))
6333     val = OVL_FUNCTION (val);
6334
6335   return val;
6336 }
6337
6338 /* Wrapper for lookup_name_real_1.  */
6339
6340 tree
6341 lookup_name_real (tree name, int prefer_type, int nonclass, bool block_p,
6342                   int namespaces_only, int flags)
6343 {
6344   tree ret;
6345   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
6346   ret = lookup_name_real_1 (name, prefer_type, nonclass, block_p,
6347                             namespaces_only, flags);
6348   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
6349   return ret;
6350 }
6351
6352 tree
6353 lookup_name_nonclass (tree name)
6354 {
6355   return lookup_name_real (name, 0, 1, /*block_p=*/true, 0, 0);
6356 }
6357
6358 tree
6359 lookup_name (tree name)
6360 {
6361   return lookup_name_real (name, 0, 0, /*block_p=*/true, 0, 0);
6362 }
6363
6364 tree
6365 lookup_name_prefer_type (tree name, int prefer_type)
6366 {
6367   return lookup_name_real (name, prefer_type, 0, /*block_p=*/true, 0, 0);
6368 }
6369
6370 /* Look up NAME for type used in elaborated name specifier in
6371    the scopes given by SCOPE.  SCOPE can be either TS_CURRENT or
6372    TS_WITHIN_ENCLOSING_NON_CLASS.  Although not implied by the
6373    name, more scopes are checked if cleanup or template parameter
6374    scope is encountered.
6375
6376    Unlike lookup_name_real, we make sure that NAME is actually
6377    declared in the desired scope, not from inheritance, nor using
6378    directive.  For using declaration, there is DR138 still waiting
6379    to be resolved.  Hidden name coming from an earlier friend
6380    declaration is also returned.
6381
6382    A TYPE_DECL best matching the NAME is returned.  Catching error
6383    and issuing diagnostics are caller's responsibility.  */
6384
6385 static tree
6386 lookup_type_scope_1 (tree name, tag_scope scope)
6387 {
6388   cxx_binding *iter = NULL;
6389   tree val = NULL_TREE;
6390   cp_binding_level *level = NULL;
6391
6392   /* Look in non-namespace scope first.  */
6393   if (current_binding_level->kind != sk_namespace)
6394     iter = outer_binding (name, NULL, /*class_p=*/ true);
6395   for (; iter; iter = outer_binding (name, iter, /*class_p=*/ true))
6396     {
6397       /* Check if this is the kind of thing we're looking for.
6398          If SCOPE is TS_CURRENT, also make sure it doesn't come from
6399          base class.  For ITER->VALUE, we can simply use
6400          INHERITED_VALUE_BINDING_P.  For ITER->TYPE, we have to use
6401          our own check.
6402
6403          We check ITER->TYPE before ITER->VALUE in order to handle
6404            typedef struct C {} C;
6405          correctly.  */
6406
6407       if (qualify_lookup (iter->type, LOOKUP_PREFER_TYPES)
6408           && (scope != ts_current
6409               || LOCAL_BINDING_P (iter)
6410               || DECL_CONTEXT (iter->type) == iter->scope->this_entity))
6411         val = iter->type;
6412       else if ((scope != ts_current
6413                 || !INHERITED_VALUE_BINDING_P (iter))
6414                && qualify_lookup (iter->value, LOOKUP_PREFER_TYPES))
6415         val = iter->value;
6416
6417       if (val)
6418         break;
6419     }
6420
6421   /* Look in namespace scope.  */
6422   if (val)
6423     level = iter->scope;
6424   else
6425     {
6426       tree ns = current_decl_namespace ();
6427
6428       if (tree *slot = find_namespace_slot (ns, name))
6429         {
6430           /* If this is the kind of thing we're looking for, we're done.  */
6431           if (tree type = MAYBE_STAT_TYPE (*slot))
6432             if (qualify_lookup (type, LOOKUP_PREFER_TYPES))
6433               val = type;
6434           if (!val)
6435             {
6436               if (tree decl = MAYBE_STAT_DECL (*slot))
6437                 if (qualify_lookup (decl, LOOKUP_PREFER_TYPES))
6438                   val = decl;
6439             }
6440           level = NAMESPACE_LEVEL (ns);
6441         }
6442     }
6443
6444   /* Type found, check if it is in the allowed scopes, ignoring cleanup
6445      and template parameter scopes.  */
6446   if (val)
6447     {
6448       cp_binding_level *b = current_binding_level;
6449       while (b)
6450         {
6451           if (level == b)
6452             return val;
6453
6454           if (b->kind == sk_cleanup || b->kind == sk_template_parms
6455               || b->kind == sk_function_parms)
6456             b = b->level_chain;
6457           else if (b->kind == sk_class
6458                    && scope == ts_within_enclosing_non_class)
6459             b = b->level_chain;
6460           else
6461             break;
6462         }
6463     }
6464
6465   return NULL_TREE;
6466 }
6467  
6468 /* Wrapper for lookup_type_scope_1.  */
6469
6470 tree
6471 lookup_type_scope (tree name, tag_scope scope)
6472 {
6473   tree ret;
6474   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
6475   ret = lookup_type_scope_1 (name, scope);
6476   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
6477   return ret;
6478 }
6479
6480 /* Returns true iff DECL is a block-scope extern declaration of a function
6481    or variable.  */
6482
6483 bool
6484 is_local_extern (tree decl)
6485 {
6486   cxx_binding *binding;
6487
6488   /* For functions, this is easy.  */
6489   if (TREE_CODE (decl) == FUNCTION_DECL)
6490     return DECL_LOCAL_FUNCTION_P (decl);
6491
6492   if (!VAR_P (decl))
6493     return false;
6494   if (!current_function_decl)
6495     return false;
6496
6497   /* For variables, this is not easy.  We need to look at the binding stack
6498      for the identifier to see whether the decl we have is a local.  */
6499   for (binding = IDENTIFIER_BINDING (DECL_NAME (decl));
6500        binding && binding->scope->kind != sk_namespace;
6501        binding = binding->previous)
6502     if (binding->value == decl)
6503       return LOCAL_BINDING_P (binding);
6504
6505   return false;
6506 }
6507
6508 /* The type TYPE is being declared.  If it is a class template, or a
6509    specialization of a class template, do any processing required and
6510    perform error-checking.  If IS_FRIEND is nonzero, this TYPE is
6511    being declared a friend.  B is the binding level at which this TYPE
6512    should be bound.
6513
6514    Returns the TYPE_DECL for TYPE, which may have been altered by this
6515    processing.  */
6516
6517 static tree
6518 maybe_process_template_type_declaration (tree type, int is_friend,
6519                                          cp_binding_level *b)
6520 {
6521   tree decl = TYPE_NAME (type);
6522
6523   if (processing_template_parmlist)
6524     /* You can't declare a new template type in a template parameter
6525        list.  But, you can declare a non-template type:
6526
6527          template <class A*> struct S;
6528
6529        is a forward-declaration of `A'.  */
6530     ;
6531   else if (b->kind == sk_namespace
6532            && current_binding_level->kind != sk_namespace)
6533     /* If this new type is being injected into a containing scope,
6534        then it's not a template type.  */
6535     ;
6536   else
6537     {
6538       gcc_assert (MAYBE_CLASS_TYPE_P (type)
6539                   || TREE_CODE (type) == ENUMERAL_TYPE);
6540
6541       if (processing_template_decl)
6542         {
6543           /* This may change after the call to
6544              push_template_decl_real, but we want the original value.  */
6545           tree name = DECL_NAME (decl);
6546
6547           decl = push_template_decl_real (decl, is_friend);
6548           if (decl == error_mark_node)
6549             return error_mark_node;
6550
6551           /* If the current binding level is the binding level for the
6552              template parameters (see the comment in
6553              begin_template_parm_list) and the enclosing level is a class
6554              scope, and we're not looking at a friend, push the
6555              declaration of the member class into the class scope.  In the
6556              friend case, push_template_decl will already have put the
6557              friend into global scope, if appropriate.  */
6558           if (TREE_CODE (type) != ENUMERAL_TYPE
6559               && !is_friend && b->kind == sk_template_parms
6560               && b->level_chain->kind == sk_class)
6561             {
6562               finish_member_declaration (CLASSTYPE_TI_TEMPLATE (type));
6563
6564               if (!COMPLETE_TYPE_P (current_class_type))
6565                 {
6566                   maybe_add_class_template_decl_list (current_class_type,
6567                                                       type, /*friend_p=*/0);
6568                   /* Put this UTD in the table of UTDs for the class.  */
6569                   if (CLASSTYPE_NESTED_UTDS (current_class_type) == NULL)
6570                     CLASSTYPE_NESTED_UTDS (current_class_type) =
6571                       binding_table_new (SCOPE_DEFAULT_HT_SIZE);
6572
6573                   binding_table_insert
6574                     (CLASSTYPE_NESTED_UTDS (current_class_type), name, type);
6575                 }
6576             }
6577         }
6578     }
6579
6580   return decl;
6581 }
6582
6583 /* Push a tag name NAME for struct/class/union/enum type TYPE.  In case
6584    that the NAME is a class template, the tag is processed but not pushed.
6585
6586    The pushed scope depend on the SCOPE parameter:
6587    - When SCOPE is TS_CURRENT, put it into the inner-most non-sk_cleanup
6588      scope.
6589    - When SCOPE is TS_GLOBAL, put it in the inner-most non-class and
6590      non-template-parameter scope.  This case is needed for forward
6591      declarations.
6592    - When SCOPE is TS_WITHIN_ENCLOSING_NON_CLASS, this is similar to
6593      TS_GLOBAL case except that names within template-parameter scopes
6594      are not pushed at all.
6595
6596    Returns TYPE upon success and ERROR_MARK_NODE otherwise.  */
6597
6598 static tree
6599 do_pushtag (tree name, tree type, tag_scope scope)
6600 {
6601   tree decl;
6602
6603   cp_binding_level *b = current_binding_level;
6604   while (/* Cleanup scopes are not scopes from the point of view of
6605             the language.  */
6606          b->kind == sk_cleanup
6607          /* Neither are function parameter scopes.  */
6608          || b->kind == sk_function_parms
6609          /* Neither are the scopes used to hold template parameters
6610             for an explicit specialization.  For an ordinary template
6611             declaration, these scopes are not scopes from the point of
6612             view of the language.  */
6613          || (b->kind == sk_template_parms
6614              && (b->explicit_spec_p || scope == ts_global))
6615          || (b->kind == sk_class
6616              && (scope != ts_current
6617                  /* We may be defining a new type in the initializer
6618                     of a static member variable. We allow this when
6619                     not pedantic, and it is particularly useful for
6620                     type punning via an anonymous union.  */
6621                  || COMPLETE_TYPE_P (b->this_entity))))
6622     b = b->level_chain;
6623
6624   gcc_assert (identifier_p (name));
6625
6626   /* Do C++ gratuitous typedefing.  */
6627   if (identifier_type_value_1 (name) != type)
6628     {
6629       tree tdef;
6630       int in_class = 0;
6631       tree context = TYPE_CONTEXT (type);
6632
6633       if (! context)
6634         {
6635           tree cs = current_scope ();
6636
6637           /* Avoid setting the lambda context to a current_function_decl that
6638              we aren't actually inside, e.g. one set by push_access_scope
6639              during tsubst_default_argument.  */
6640           if (cs && TREE_CODE (cs) == FUNCTION_DECL
6641               && LAMBDA_TYPE_P (type)
6642               && !at_function_scope_p ())
6643             cs = DECL_CONTEXT (cs);
6644
6645           if (scope == ts_current
6646               || (cs && TREE_CODE (cs) == FUNCTION_DECL))
6647             context = cs;
6648           else if (cs && TYPE_P (cs))
6649             /* When declaring a friend class of a local class, we want
6650                to inject the newly named class into the scope
6651                containing the local class, not the namespace
6652                scope.  */
6653             context = decl_function_context (get_type_decl (cs));
6654         }
6655       if (!context)
6656         context = current_namespace;
6657
6658       if (b->kind == sk_class
6659           || (b->kind == sk_template_parms
6660               && b->level_chain->kind == sk_class))
6661         in_class = 1;
6662
6663       tdef = create_implicit_typedef (name, type);
6664       DECL_CONTEXT (tdef) = FROB_CONTEXT (context);
6665       if (scope == ts_within_enclosing_non_class)
6666         {
6667           /* This is a friend.  Make this TYPE_DECL node hidden from
6668              ordinary name lookup.  Its corresponding TEMPLATE_DECL
6669              will be marked in push_template_decl_real.  */
6670           retrofit_lang_decl (tdef);
6671           DECL_ANTICIPATED (tdef) = 1;
6672           DECL_FRIEND_P (tdef) = 1;
6673         }
6674
6675       decl = maybe_process_template_type_declaration
6676         (type, scope == ts_within_enclosing_non_class, b);
6677       if (decl == error_mark_node)
6678         return decl;
6679
6680       if (b->kind == sk_class)
6681         {
6682           if (!TYPE_BEING_DEFINED (current_class_type)
6683               && !LAMBDA_TYPE_P (type))
6684             return error_mark_node;
6685
6686           if (!PROCESSING_REAL_TEMPLATE_DECL_P ())
6687             /* Put this TYPE_DECL on the TYPE_FIELDS list for the
6688                class.  But if it's a member template class, we want
6689                the TEMPLATE_DECL, not the TYPE_DECL, so this is done
6690                later.  */
6691             finish_member_declaration (decl);
6692           else
6693             pushdecl_class_level (decl);
6694         }
6695       else if (b->kind != sk_template_parms)
6696         {
6697           decl = do_pushdecl_with_scope (decl, b, /*is_friend=*/false);
6698           if (decl == error_mark_node)
6699             return decl;
6700
6701           if (DECL_CONTEXT (decl) == std_node
6702               && init_list_identifier == DECL_NAME (TYPE_NAME (type))
6703               && !CLASSTYPE_TEMPLATE_INFO (type))
6704             {
6705               error ("declaration of %<std::initializer_list%> does not match "
6706                      "%<#include <initializer_list>%>, isn't a template");
6707               return error_mark_node;
6708             }
6709         }
6710
6711       if (! in_class)
6712         set_identifier_type_value_with_scope (name, tdef, b);
6713
6714       TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
6715
6716       /* If this is a local class, keep track of it.  We need this
6717          information for name-mangling, and so that it is possible to
6718          find all function definitions in a translation unit in a
6719          convenient way.  (It's otherwise tricky to find a member
6720          function definition it's only pointed to from within a local
6721          class.)  */
6722       if (TYPE_FUNCTION_SCOPE_P (type))
6723         {
6724           if (processing_template_decl)
6725             {
6726               /* Push a DECL_EXPR so we call pushtag at the right time in
6727                  template instantiation rather than in some nested context.  */
6728               add_decl_expr (decl);
6729             }
6730           /* Lambdas use LAMBDA_EXPR_DISCRIMINATOR instead.  */
6731           else if (!LAMBDA_TYPE_P (type))
6732             vec_safe_push (local_classes, type);
6733         }
6734     }
6735
6736   if (b->kind == sk_class
6737       && !COMPLETE_TYPE_P (current_class_type))
6738     {
6739       maybe_add_class_template_decl_list (current_class_type,
6740                                           type, /*friend_p=*/0);
6741
6742       if (CLASSTYPE_NESTED_UTDS (current_class_type) == NULL)
6743         CLASSTYPE_NESTED_UTDS (current_class_type)
6744           = binding_table_new (SCOPE_DEFAULT_HT_SIZE);
6745
6746       binding_table_insert
6747         (CLASSTYPE_NESTED_UTDS (current_class_type), name, type);
6748     }
6749
6750   decl = TYPE_NAME (type);
6751   gcc_assert (TREE_CODE (decl) == TYPE_DECL);
6752
6753   /* Set type visibility now if this is a forward declaration.  */
6754   TREE_PUBLIC (decl) = 1;
6755   determine_visibility (decl);
6756
6757   return type;
6758 }
6759
6760 /* Wrapper for do_pushtag.  */
6761
6762 tree
6763 pushtag (tree name, tree type, tag_scope scope)
6764 {
6765   tree ret;
6766   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
6767   ret = do_pushtag (name, type, scope);
6768   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
6769   return ret;
6770 }
6771
6772 \f
6773 /* Subroutines for reverting temporarily to top-level for instantiation
6774    of templates and such.  We actually need to clear out the class- and
6775    local-value slots of all identifiers, so that only the global values
6776    are at all visible.  Simply setting current_binding_level to the global
6777    scope isn't enough, because more binding levels may be pushed.  */
6778 struct saved_scope *scope_chain;
6779
6780 /* Return true if ID has not already been marked.  */
6781
6782 static inline bool
6783 store_binding_p (tree id)
6784 {
6785   if (!id || !IDENTIFIER_BINDING (id))
6786     return false;
6787
6788   if (IDENTIFIER_MARKED (id))
6789     return false;
6790
6791   return true;
6792 }
6793
6794 /* Add an appropriate binding to *OLD_BINDINGS which needs to already
6795    have enough space reserved.  */
6796
6797 static void
6798 store_binding (tree id, vec<cxx_saved_binding, va_gc> **old_bindings)
6799 {
6800   cxx_saved_binding saved;
6801
6802   gcc_checking_assert (store_binding_p (id));
6803
6804   IDENTIFIER_MARKED (id) = 1;
6805
6806   saved.identifier = id;
6807   saved.binding = IDENTIFIER_BINDING (id);
6808   saved.real_type_value = REAL_IDENTIFIER_TYPE_VALUE (id);
6809   (*old_bindings)->quick_push (saved);
6810   IDENTIFIER_BINDING (id) = NULL;
6811 }
6812
6813 static void
6814 store_bindings (tree names, vec<cxx_saved_binding, va_gc> **old_bindings)
6815 {
6816   static vec<tree> bindings_need_stored;
6817   tree t, id;
6818   size_t i;
6819
6820   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
6821   for (t = names; t; t = TREE_CHAIN (t))
6822     {
6823       if (TREE_CODE (t) == TREE_LIST)
6824         id = TREE_PURPOSE (t);
6825       else
6826         id = DECL_NAME (t);
6827
6828       if (store_binding_p (id))
6829         bindings_need_stored.safe_push (id);
6830     }
6831   if (!bindings_need_stored.is_empty ())
6832     {
6833       vec_safe_reserve_exact (*old_bindings, bindings_need_stored.length ());
6834       for (i = 0; bindings_need_stored.iterate (i, &id); ++i)
6835         {
6836           /* We can apparently have duplicates in NAMES.  */
6837           if (store_binding_p (id))
6838             store_binding (id, old_bindings);
6839         }
6840       bindings_need_stored.truncate (0);
6841     }
6842   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
6843 }
6844
6845 /* Like store_bindings, but NAMES is a vector of cp_class_binding
6846    objects, rather than a TREE_LIST.  */
6847
6848 static void
6849 store_class_bindings (vec<cp_class_binding, va_gc> *names,
6850                       vec<cxx_saved_binding, va_gc> **old_bindings)
6851 {
6852   static vec<tree> bindings_need_stored;
6853   size_t i;
6854   cp_class_binding *cb;
6855
6856   for (i = 0; vec_safe_iterate (names, i, &cb); ++i)
6857     if (store_binding_p (cb->identifier))
6858       bindings_need_stored.safe_push (cb->identifier);
6859   if (!bindings_need_stored.is_empty ())
6860     {
6861       tree id;
6862       vec_safe_reserve_exact (*old_bindings, bindings_need_stored.length ());
6863       for (i = 0; bindings_need_stored.iterate (i, &id); ++i)
6864         store_binding (id, old_bindings);
6865       bindings_need_stored.truncate (0);
6866     }
6867 }
6868
6869 /* A chain of saved_scope structures awaiting reuse.  */
6870
6871 static GTY((deletable)) struct saved_scope *free_saved_scope;
6872
6873 static void
6874 do_push_to_top_level (void)
6875 {
6876   struct saved_scope *s;
6877   cp_binding_level *b;
6878   cxx_saved_binding *sb;
6879   size_t i;
6880   bool need_pop;
6881
6882   /* Reuse or create a new structure for this saved scope.  */
6883   if (free_saved_scope != NULL)
6884     {
6885       s = free_saved_scope;
6886       free_saved_scope = s->prev;
6887
6888       vec<cxx_saved_binding, va_gc> *old_bindings = s->old_bindings;
6889       memset (s, 0, sizeof (*s));
6890       /* Also reuse the structure's old_bindings vector.  */
6891       vec_safe_truncate (old_bindings, 0);
6892       s->old_bindings = old_bindings;
6893     }
6894   else
6895     s = ggc_cleared_alloc<saved_scope> ();
6896
6897   b = scope_chain ? current_binding_level : 0;
6898
6899   /* If we're in the middle of some function, save our state.  */
6900   if (cfun)
6901     {
6902       need_pop = true;
6903       push_function_context ();
6904     }
6905   else
6906     need_pop = false;
6907
6908   if (scope_chain && previous_class_level)
6909     store_class_bindings (previous_class_level->class_shadowed,
6910                           &s->old_bindings);
6911
6912   /* Have to include the global scope, because class-scope decls
6913      aren't listed anywhere useful.  */
6914   for (; b; b = b->level_chain)
6915     {
6916       tree t;
6917
6918       /* Template IDs are inserted into the global level. If they were
6919          inserted into namespace level, finish_file wouldn't find them
6920          when doing pending instantiations. Therefore, don't stop at
6921          namespace level, but continue until :: .  */
6922       if (global_scope_p (b))
6923         break;
6924
6925       store_bindings (b->names, &s->old_bindings);
6926       /* We also need to check class_shadowed to save class-level type
6927          bindings, since pushclass doesn't fill in b->names.  */
6928       if (b->kind == sk_class)
6929         store_class_bindings (b->class_shadowed, &s->old_bindings);
6930
6931       /* Unwind type-value slots back to top level.  */
6932       for (t = b->type_shadowed; t; t = TREE_CHAIN (t))
6933         SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (t), TREE_VALUE (t));
6934     }
6935
6936   FOR_EACH_VEC_SAFE_ELT (s->old_bindings, i, sb)
6937     IDENTIFIER_MARKED (sb->identifier) = 0;
6938
6939   s->prev = scope_chain;
6940   s->bindings = b;
6941   s->need_pop_function_context = need_pop;
6942   s->function_decl = current_function_decl;
6943   s->unevaluated_operand = cp_unevaluated_operand;
6944   s->inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6945   s->x_stmt_tree.stmts_are_full_exprs_p = true;
6946
6947   scope_chain = s;
6948   current_function_decl = NULL_TREE;
6949   current_lang_base = NULL;
6950   current_lang_name = lang_name_cplusplus;
6951   current_namespace = global_namespace;
6952   push_class_stack ();
6953   cp_unevaluated_operand = 0;
6954   c_inhibit_evaluation_warnings = 0;
6955 }
6956
6957 static void
6958 do_pop_from_top_level (void)
6959 {
6960   struct saved_scope *s = scope_chain;
6961   cxx_saved_binding *saved;
6962   size_t i;
6963
6964   /* Clear out class-level bindings cache.  */
6965   if (previous_class_level)
6966     invalidate_class_lookup_cache ();
6967   pop_class_stack ();
6968
6969   release_tree_vector (current_lang_base);
6970
6971   scope_chain = s->prev;
6972   FOR_EACH_VEC_SAFE_ELT (s->old_bindings, i, saved)
6973     {
6974       tree id = saved->identifier;
6975
6976       IDENTIFIER_BINDING (id) = saved->binding;
6977       SET_IDENTIFIER_TYPE_VALUE (id, saved->real_type_value);
6978     }
6979
6980   /* If we were in the middle of compiling a function, restore our
6981      state.  */
6982   if (s->need_pop_function_context)
6983     pop_function_context ();
6984   current_function_decl = s->function_decl;
6985   cp_unevaluated_operand = s->unevaluated_operand;
6986   c_inhibit_evaluation_warnings = s->inhibit_evaluation_warnings;
6987
6988   /* Make this saved_scope structure available for reuse by
6989      push_to_top_level.  */
6990   s->prev = free_saved_scope;
6991   free_saved_scope = s;
6992 }
6993
6994 /* Push into the scope of the namespace NS, even if it is deeply
6995    nested within another namespace.  */
6996
6997 static void
6998 do_push_nested_namespace (tree ns)
6999 {
7000   if (ns == global_namespace)
7001     do_push_to_top_level ();
7002   else
7003     {
7004       do_push_nested_namespace (CP_DECL_CONTEXT (ns));
7005       gcc_checking_assert
7006         (find_namespace_value (current_namespace, DECL_NAME (ns)) == ns);
7007       resume_scope (NAMESPACE_LEVEL (ns));
7008       current_namespace = ns;
7009     }
7010 }
7011
7012 /* Pop back from the scope of the namespace NS, which was previously
7013    entered with push_nested_namespace.  */
7014
7015 static void
7016 do_pop_nested_namespace (tree ns)
7017 {
7018   while (ns != global_namespace)
7019     {
7020       ns = CP_DECL_CONTEXT (ns);
7021       current_namespace = ns;
7022       leave_scope ();
7023     }
7024
7025   do_pop_from_top_level ();
7026 }
7027
7028 /* Add TARGET to USINGS, if it does not already exist there.
7029    We used to build the complete graph of usings at this point, from
7030    the POV of the source namespaces.  Now we build that as we perform
7031    the unqualified search.  */
7032
7033 static void
7034 add_using_namespace (vec<tree, va_gc> *&usings, tree target)
7035 {
7036   if (usings)
7037     for (unsigned ix = usings->length (); ix--;)
7038       if ((*usings)[ix] == target)
7039         return;
7040
7041   vec_safe_push (usings, target);
7042 }
7043
7044 /* Tell the debug system of a using directive.  */
7045
7046 static void
7047 emit_debug_info_using_namespace (tree from, tree target, bool implicit)
7048 {
7049   /* Emit debugging info.  */
7050   tree context = from != global_namespace ? from : NULL_TREE;
7051   debug_hooks->imported_module_or_decl (target, NULL_TREE, context, false,
7052                                         implicit);
7053 }
7054
7055 /* Process a namespace-scope using directive.  */
7056
7057 void
7058 finish_namespace_using_directive (tree target, tree attribs)
7059 {
7060   gcc_checking_assert (namespace_bindings_p ());
7061   if (target == error_mark_node)
7062     return;
7063
7064   add_using_namespace (DECL_NAMESPACE_USING (current_namespace),
7065                        ORIGINAL_NAMESPACE (target));
7066   emit_debug_info_using_namespace (current_namespace,
7067                                    ORIGINAL_NAMESPACE (target), false);
7068
7069   if (attribs == error_mark_node)
7070     return;
7071
7072   for (tree a = attribs; a; a = TREE_CHAIN (a))
7073     {
7074       tree name = get_attribute_name (a);
7075       if (is_attribute_p ("strong", name))
7076         {
7077           warning (0, "strong using directive no longer supported");
7078           if (CP_DECL_CONTEXT (target) == current_namespace)
7079             inform (DECL_SOURCE_LOCATION (target),
7080                     "you may use an inline namespace instead");
7081         }
7082       else
7083         warning (OPT_Wattributes, "%qD attribute directive ignored", name);
7084     }
7085 }
7086
7087 /* Process a function-scope using-directive.  */
7088
7089 void
7090 finish_local_using_directive (tree target, tree attribs)
7091 {
7092   gcc_checking_assert (local_bindings_p ());
7093   if (target == error_mark_node)
7094     return;
7095
7096   if (attribs)
7097     warning (OPT_Wattributes, "attributes ignored on local using directive");
7098
7099   add_stmt (build_stmt (input_location, USING_STMT, target));
7100
7101   add_using_namespace (current_binding_level->using_directives,
7102                        ORIGINAL_NAMESPACE (target));
7103 }
7104
7105 /* Pushes X into the global namespace.  */
7106
7107 tree
7108 pushdecl_top_level (tree x, bool is_friend)
7109 {
7110   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7111   do_push_to_top_level ();
7112   x = pushdecl_namespace_level (x, is_friend);
7113   do_pop_from_top_level ();
7114   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7115   return x;
7116 }
7117
7118 /* Pushes X into the global namespace and calls cp_finish_decl to
7119    register the variable, initializing it with INIT.  */
7120
7121 tree
7122 pushdecl_top_level_and_finish (tree x, tree init)
7123 {
7124   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7125   do_push_to_top_level ();
7126   x = pushdecl_namespace_level (x, false);
7127   cp_finish_decl (x, init, false, NULL_TREE, 0);
7128   do_pop_from_top_level ();
7129   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7130   return x;
7131 }
7132
7133 /* Enter the namespaces from current_namerspace to NS.  */
7134
7135 static int
7136 push_inline_namespaces (tree ns)
7137 {
7138   int count = 0;
7139   if (ns != current_namespace)
7140     {
7141       gcc_assert (ns != global_namespace);
7142       count += push_inline_namespaces (CP_DECL_CONTEXT (ns));
7143       resume_scope (NAMESPACE_LEVEL (ns));
7144       current_namespace = ns;
7145       count++;
7146     }
7147   return count;
7148 }
7149
7150 /* Push into the scope of the NAME namespace.  If NAME is NULL_TREE,
7151    then we enter an anonymous namespace.  If MAKE_INLINE is true, then
7152    we create an inline namespace (it is up to the caller to check upon
7153    redefinition). Return the number of namespaces entered.  */
7154
7155 int
7156 push_namespace (tree name, bool make_inline)
7157 {
7158   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7159   int count = 0;
7160
7161   /* We should not get here if the global_namespace is not yet constructed
7162      nor if NAME designates the global namespace:  The global scope is
7163      constructed elsewhere.  */
7164   gcc_checking_assert (global_namespace != NULL && name != global_identifier);
7165
7166   tree ns = NULL_TREE;
7167   {
7168     name_lookup lookup (name, 0);
7169     if (!lookup.search_qualified (current_namespace, /*usings=*/false))
7170       ;
7171     else if (TREE_CODE (lookup.value) != NAMESPACE_DECL)
7172       ;
7173     else if (tree dna = DECL_NAMESPACE_ALIAS (lookup.value))
7174       {
7175         /* A namespace alias is not allowed here, but if the alias
7176            is for a namespace also inside the current scope,
7177            accept it with a diagnostic.  That's better than dying
7178            horribly.  */
7179         if (is_nested_namespace (current_namespace, CP_DECL_CONTEXT (dna)))
7180           {
7181             error ("namespace alias %qD not allowed here, "
7182                    "assuming %qD", lookup.value, dna);
7183             ns = dna;
7184           }
7185       }
7186     else
7187       ns = lookup.value;
7188   }
7189
7190   bool new_ns = false;
7191   if (ns)
7192     /* DR2061.  NS might be a member of an inline namespace.  We
7193        need to push into those namespaces.  */
7194     count += push_inline_namespaces (CP_DECL_CONTEXT (ns));
7195   else
7196     {
7197       ns = build_lang_decl (NAMESPACE_DECL, name, void_type_node);
7198       SCOPE_DEPTH (ns) = SCOPE_DEPTH (current_namespace) + 1;
7199       if (!SCOPE_DEPTH (ns))
7200         /* We only allow depth 255. */
7201         sorry ("cannot nest more than %d namespaces",
7202                SCOPE_DEPTH (current_namespace));
7203       DECL_CONTEXT (ns) = FROB_CONTEXT (current_namespace);
7204       new_ns = true;
7205
7206       if (pushdecl (ns) == error_mark_node)
7207         ns = NULL_TREE;
7208       else
7209         {
7210           if (!name)
7211             {
7212               SET_DECL_ASSEMBLER_NAME (ns, anon_identifier);
7213
7214               if (!make_inline)
7215                 add_using_namespace (DECL_NAMESPACE_USING (current_namespace),
7216                                      ns);
7217             }
7218           else if (TREE_PUBLIC (current_namespace))
7219             TREE_PUBLIC (ns) = 1;
7220
7221           if (make_inline)
7222             {
7223               DECL_NAMESPACE_INLINE_P (ns) = true;
7224               vec_safe_push (DECL_NAMESPACE_INLINEES (current_namespace), ns);
7225             }
7226
7227           if (!name || make_inline)
7228             emit_debug_info_using_namespace (current_namespace, ns, true);
7229         }
7230     }
7231
7232   if (ns)
7233     {
7234       if (make_inline && !DECL_NAMESPACE_INLINE_P (ns))
7235         {
7236           error ("inline namespace must be specified at initial definition");
7237           inform (DECL_SOURCE_LOCATION (ns), "%qD defined here", ns);
7238         }
7239       if (new_ns)
7240         begin_scope (sk_namespace, ns);
7241       else
7242         resume_scope (NAMESPACE_LEVEL (ns));
7243       current_namespace = ns;
7244       count++;
7245     }
7246
7247   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7248   return count;
7249 }
7250
7251 /* Pop from the scope of the current namespace.  */
7252
7253 void
7254 pop_namespace (void)
7255 {
7256   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7257
7258   gcc_assert (current_namespace != global_namespace);
7259   current_namespace = CP_DECL_CONTEXT (current_namespace);
7260   /* The binding level is not popped, as it might be re-opened later.  */
7261   leave_scope ();
7262
7263   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7264 }
7265
7266 /* External entry points for do_{push_to/pop_from}_top_level.  */
7267
7268 void
7269 push_to_top_level (void)
7270 {
7271   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7272   do_push_to_top_level ();
7273   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7274 }
7275
7276 void
7277 pop_from_top_level (void)
7278 {
7279   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7280   do_pop_from_top_level ();
7281   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7282 }
7283
7284 /* External entry points for do_{push,pop}_nested_namespace.  */
7285
7286 void
7287 push_nested_namespace (tree ns)
7288 {
7289   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7290   do_push_nested_namespace (ns);
7291   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7292 }
7293
7294 void
7295 pop_nested_namespace (tree ns)
7296 {
7297   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
7298   gcc_assert (current_namespace == ns);
7299   do_pop_nested_namespace (ns);
7300   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
7301 }
7302
7303 /* Pop off extraneous binding levels left over due to syntax errors.
7304    We don't pop past namespaces, as they might be valid.  */
7305
7306 void
7307 pop_everything (void)
7308 {
7309   if (ENABLE_SCOPE_CHECKING)
7310     verbatim ("XXX entering pop_everything ()\n");
7311   while (!namespace_bindings_p ())
7312     {
7313       if (current_binding_level->kind == sk_class)
7314         pop_nested_class ();
7315       else
7316         poplevel (0, 0, 0);
7317     }
7318   if (ENABLE_SCOPE_CHECKING)
7319     verbatim ("XXX leaving pop_everything ()\n");
7320 }
7321
7322 /* Emit debugging information for using declarations and directives.
7323    If input tree is overloaded fn then emit debug info for all
7324    candidates.  */
7325
7326 void
7327 cp_emit_debug_info_for_using (tree t, tree context)
7328 {
7329   /* Don't try to emit any debug information if we have errors.  */
7330   if (seen_error ())
7331     return;
7332
7333   /* Ignore this FUNCTION_DECL if it refers to a builtin declaration
7334      of a builtin function.  */
7335   if (TREE_CODE (t) == FUNCTION_DECL
7336       && DECL_EXTERNAL (t)
7337       && DECL_BUILT_IN (t))
7338     return;
7339
7340   /* Do not supply context to imported_module_or_decl, if
7341      it is a global namespace.  */
7342   if (context == global_namespace)
7343     context = NULL_TREE;
7344
7345   t = MAYBE_BASELINK_FUNCTIONS (t);
7346
7347   /* FIXME: Handle TEMPLATE_DECLs.  */
7348   for (lkp_iterator iter (t); iter; ++iter)
7349     {
7350       tree fn = *iter;
7351       if (TREE_CODE (fn) != TEMPLATE_DECL)
7352         {
7353           if (building_stmt_list_p ())
7354             add_stmt (build_stmt (input_location, USING_STMT, fn));
7355           else
7356             debug_hooks->imported_module_or_decl (fn, NULL_TREE, context,
7357                                                   false, false);
7358         }
7359     }
7360 }
7361
7362 #include "gt-cp-name-lookup.h"