Merge branch 'vendor/GCC44' into gcc441
[dragonfly.git] / contrib / gcc-4.4 / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48 #include "vecprim.h"
49
50 /* The type of functions taking a tree, and some additional data, and
51    returning an int.  */
52 typedef int (*tree_fn_t) (tree, void*);
53
54 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
55    instantiations have been deferred, either because their definitions
56    were not yet available, or because we were putting off doing the work.  */
57 struct pending_template GTY (()) {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 /* Contains canonical template parameter types. The vector is indexed by
86    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
87    TREE_LIST, whose TREE_VALUEs contain the canonical template
88    parameters of various types and levels.  */
89 static GTY(()) VEC(tree,gc) *canonical_template_parms;
90
91 #define UNIFY_ALLOW_NONE 0
92 #define UNIFY_ALLOW_MORE_CV_QUAL 1
93 #define UNIFY_ALLOW_LESS_CV_QUAL 2
94 #define UNIFY_ALLOW_DERIVED 4
95 #define UNIFY_ALLOW_INTEGER 8
96 #define UNIFY_ALLOW_OUTER_LEVEL 16
97 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
98 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
99
100 static void push_access_scope (tree);
101 static void pop_access_scope (tree);
102 static bool resolve_overloaded_unification (tree, tree, tree, tree,
103                                             unification_kind_t, int);
104 static int try_one_overload (tree, tree, tree, tree, tree,
105                              unification_kind_t, int, bool);
106 static int unify (tree, tree, tree, tree, int);
107 static void add_pending_template (tree);
108 static int push_tinst_level (tree);
109 static void pop_tinst_level (void);
110 static tree reopen_tinst_level (struct tinst_level *);
111 static tree tsubst_initializer_list (tree, tree);
112 static tree get_class_bindings (tree, tree, tree);
113 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
114                                    bool, bool);
115 static void tsubst_enum (tree, tree, tree);
116 static tree add_to_template_args (tree, tree);
117 static tree add_outermost_template_args (tree, tree);
118 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
119 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
120                                              tree);
121 static int  type_unification_real (tree, tree, tree, tree,
122                                    int, unification_kind_t, int);
123 static void note_template_header (int);
124 static tree convert_nontype_argument_function (tree, tree);
125 static tree convert_nontype_argument (tree, tree);
126 static tree convert_template_argument (tree, tree, tree,
127                                        tsubst_flags_t, int, tree);
128 static int for_each_template_parm (tree, tree_fn_t, void*,
129                                    struct pointer_set_t*, bool);
130 static tree expand_template_argument_pack (tree);
131 static tree build_template_parm_index (int, int, int, tree, tree);
132 static bool inline_needs_template_parms (tree);
133 static void push_inline_template_parms_recursive (tree, int);
134 static tree retrieve_local_specialization (tree);
135 static void register_local_specialization (tree, tree);
136 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
137 static int mark_template_parm (tree, void *);
138 static int template_parm_this_level_p (tree, void *);
139 static tree tsubst_friend_function (tree, tree);
140 static tree tsubst_friend_class (tree, tree);
141 static int can_complete_type_without_circularity (tree);
142 static tree get_bindings (tree, tree, tree, bool);
143 static int template_decl_level (tree);
144 static int check_cv_quals_for_unify (int, tree, tree);
145 static void template_parm_level_and_index (tree, int*, int*);
146 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
147 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
149 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
150 static void regenerate_decl_from_template (tree, tree);
151 static tree most_specialized_class (tree, tree);
152 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
153 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
154 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
155 static bool check_specialization_scope (void);
156 static tree process_partial_specialization (tree);
157 static void set_current_access_from_decl (tree);
158 static tree get_template_base (tree, tree, tree, tree);
159 static tree try_class_unification (tree, tree, tree, tree);
160 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
161                                            tree, tree);
162 static bool template_template_parm_bindings_ok_p (tree, tree);
163 static int template_args_equal (tree, tree);
164 static void tsubst_default_arguments (tree);
165 static tree for_each_template_parm_r (tree *, int *, void *);
166 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
167 static void copy_default_args_to_explicit_spec (tree);
168 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
169 static int eq_local_specializations (const void *, const void *);
170 static bool dependent_template_arg_p (tree);
171 static bool any_template_arguments_need_structural_equality_p (tree);
172 static bool dependent_type_p_r (tree);
173 static tree tsubst (tree, tree, tsubst_flags_t, tree);
174 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
175 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
177 static tree tsubst_decl (tree, tree, tsubst_flags_t);
178
179 /* Make the current scope suitable for access checking when we are
180    processing T.  T can be FUNCTION_DECL for instantiated function
181    template, or VAR_DECL for static member variable (need by
182    instantiate_decl).  */
183
184 static void
185 push_access_scope (tree t)
186 {
187   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
188               || TREE_CODE (t) == VAR_DECL);
189
190   if (DECL_FRIEND_CONTEXT (t))
191     push_nested_class (DECL_FRIEND_CONTEXT (t));
192   else if (DECL_CLASS_SCOPE_P (t))
193     push_nested_class (DECL_CONTEXT (t));
194   else
195     push_to_top_level ();
196
197   if (TREE_CODE (t) == FUNCTION_DECL)
198     {
199       saved_access_scope = tree_cons
200         (NULL_TREE, current_function_decl, saved_access_scope);
201       current_function_decl = t;
202     }
203 }
204
205 /* Restore the scope set up by push_access_scope.  T is the node we
206    are processing.  */
207
208 static void
209 pop_access_scope (tree t)
210 {
211   if (TREE_CODE (t) == FUNCTION_DECL)
212     {
213       current_function_decl = TREE_VALUE (saved_access_scope);
214       saved_access_scope = TREE_CHAIN (saved_access_scope);
215     }
216
217   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
218     pop_nested_class ();
219   else
220     pop_from_top_level ();
221 }
222
223 /* Do any processing required when DECL (a member template
224    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
225    to DECL, unless it is a specialization, in which case the DECL
226    itself is returned.  */
227
228 tree
229 finish_member_template_decl (tree decl)
230 {
231   if (decl == error_mark_node)
232     return error_mark_node;
233
234   gcc_assert (DECL_P (decl));
235
236   if (TREE_CODE (decl) == TYPE_DECL)
237     {
238       tree type;
239
240       type = TREE_TYPE (decl);
241       if (type == error_mark_node)
242         return error_mark_node;
243       if (MAYBE_CLASS_TYPE_P (type)
244           && CLASSTYPE_TEMPLATE_INFO (type)
245           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
246         {
247           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
248           check_member_template (tmpl);
249           return tmpl;
250         }
251       return NULL_TREE;
252     }
253   else if (TREE_CODE (decl) == FIELD_DECL)
254     error ("data member %qD cannot be a member template", decl);
255   else if (DECL_TEMPLATE_INFO (decl))
256     {
257       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
258         {
259           check_member_template (DECL_TI_TEMPLATE (decl));
260           return DECL_TI_TEMPLATE (decl);
261         }
262       else
263         return decl;
264     }
265   else
266     error ("invalid member template declaration %qD", decl);
267
268   return error_mark_node;
269 }
270
271 /* Return the template info node corresponding to T, whatever T is.  */
272
273 tree
274 get_template_info (tree t)
275 {
276   tree tinfo = NULL_TREE;
277
278   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
279     tinfo = DECL_TEMPLATE_INFO (t);
280
281   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
282     t = TREE_TYPE (t);
283
284   if (TAGGED_TYPE_P (t))
285     tinfo = TYPE_TEMPLATE_INFO (t);
286
287   return tinfo;
288 }
289
290 /* Returns the template nesting level of the indicated class TYPE.
291
292    For example, in:
293      template <class T>
294      struct A
295      {
296        template <class U>
297        struct B {};
298      };
299
300    A<T>::B<U> has depth two, while A<T> has depth one.
301    Both A<T>::B<int> and A<int>::B<U> have depth one, if
302    they are instantiations, not specializations.
303
304    This function is guaranteed to return 0 if passed NULL_TREE so
305    that, for example, `template_class_depth (current_class_type)' is
306    always safe.  */
307
308 int
309 template_class_depth (tree type)
310 {
311   int depth;
312
313   for (depth = 0;
314        type && TREE_CODE (type) != NAMESPACE_DECL;
315        type = (TREE_CODE (type) == FUNCTION_DECL)
316          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
317     {
318       tree tinfo = get_template_info (type);
319
320       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
321           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
322         ++depth;
323     }
324
325   return depth;
326 }
327
328 /* Subroutine of maybe_begin_member_template_processing.
329    Returns true if processing DECL needs us to push template parms.  */
330
331 static bool
332 inline_needs_template_parms (tree decl)
333 {
334   if (! DECL_TEMPLATE_INFO (decl))
335     return false;
336
337   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
338           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
339 }
340
341 /* Subroutine of maybe_begin_member_template_processing.
342    Push the template parms in PARMS, starting from LEVELS steps into the
343    chain, and ending at the beginning, since template parms are listed
344    innermost first.  */
345
346 static void
347 push_inline_template_parms_recursive (tree parmlist, int levels)
348 {
349   tree parms = TREE_VALUE (parmlist);
350   int i;
351
352   if (levels > 1)
353     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
354
355   ++processing_template_decl;
356   current_template_parms
357     = tree_cons (size_int (processing_template_decl),
358                  parms, current_template_parms);
359   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
360
361   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
362                NULL);
363   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
364     {
365       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
366
367       if (parm == error_mark_node)
368         continue;
369
370       gcc_assert (DECL_P (parm));
371
372       switch (TREE_CODE (parm))
373         {
374         case TYPE_DECL:
375         case TEMPLATE_DECL:
376           pushdecl (parm);
377           break;
378
379         case PARM_DECL:
380           {
381             /* Make a CONST_DECL as is done in process_template_parm.
382                It is ugly that we recreate this here; the original
383                version built in process_template_parm is no longer
384                available.  */
385             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
386                                     TREE_TYPE (parm));
387             DECL_ARTIFICIAL (decl) = 1;
388             TREE_CONSTANT (decl) = 1;
389             TREE_READONLY (decl) = 1;
390             DECL_INITIAL (decl) = DECL_INITIAL (parm);
391             SET_DECL_TEMPLATE_PARM_P (decl);
392             pushdecl (decl);
393           }
394           break;
395
396         default:
397           gcc_unreachable ();
398         }
399     }
400 }
401
402 /* Restore the template parameter context for a member template or
403    a friend template defined in a class definition.  */
404
405 void
406 maybe_begin_member_template_processing (tree decl)
407 {
408   tree parms;
409   int levels = 0;
410
411   if (inline_needs_template_parms (decl))
412     {
413       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
414       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
415
416       if (DECL_TEMPLATE_SPECIALIZATION (decl))
417         {
418           --levels;
419           parms = TREE_CHAIN (parms);
420         }
421
422       push_inline_template_parms_recursive (parms, levels);
423     }
424
425   /* Remember how many levels of template parameters we pushed so that
426      we can pop them later.  */
427   VEC_safe_push (int, heap, inline_parm_levels, levels);
428 }
429
430 /* Undo the effects of maybe_begin_member_template_processing.  */
431
432 void
433 maybe_end_member_template_processing (void)
434 {
435   int i;
436   int last;
437
438   if (VEC_length (int, inline_parm_levels) == 0)
439     return;
440
441   last = VEC_pop (int, inline_parm_levels);
442   for (i = 0; i < last; ++i)
443     {
444       --processing_template_decl;
445       current_template_parms = TREE_CHAIN (current_template_parms);
446       poplevel (0, 0, 0);
447     }
448 }
449
450 /* Return a new template argument vector which contains all of ARGS,
451    but has as its innermost set of arguments the EXTRA_ARGS.  */
452
453 static tree
454 add_to_template_args (tree args, tree extra_args)
455 {
456   tree new_args;
457   int extra_depth;
458   int i;
459   int j;
460
461   extra_depth = TMPL_ARGS_DEPTH (extra_args);
462   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
463
464   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
465     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
466
467   for (j = 1; j <= extra_depth; ++j, ++i)
468     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
469
470   return new_args;
471 }
472
473 /* Like add_to_template_args, but only the outermost ARGS are added to
474    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
475    (EXTRA_ARGS) levels are added.  This function is used to combine
476    the template arguments from a partial instantiation with the
477    template arguments used to attain the full instantiation from the
478    partial instantiation.  */
479
480 static tree
481 add_outermost_template_args (tree args, tree extra_args)
482 {
483   tree new_args;
484
485   /* If there are more levels of EXTRA_ARGS than there are ARGS,
486      something very fishy is going on.  */
487   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
488
489   /* If *all* the new arguments will be the EXTRA_ARGS, just return
490      them.  */
491   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
492     return extra_args;
493
494   /* For the moment, we make ARGS look like it contains fewer levels.  */
495   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
496
497   new_args = add_to_template_args (args, extra_args);
498
499   /* Now, we restore ARGS to its full dimensions.  */
500   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
501
502   return new_args;
503 }
504
505 /* Return the N levels of innermost template arguments from the ARGS.  */
506
507 tree
508 get_innermost_template_args (tree args, int n)
509 {
510   tree new_args;
511   int extra_levels;
512   int i;
513
514   gcc_assert (n >= 0);
515
516   /* If N is 1, just return the innermost set of template arguments.  */
517   if (n == 1)
518     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
519
520   /* If we're not removing anything, just return the arguments we were
521      given.  */
522   extra_levels = TMPL_ARGS_DEPTH (args) - n;
523   gcc_assert (extra_levels >= 0);
524   if (extra_levels == 0)
525     return args;
526
527   /* Make a new set of arguments, not containing the outer arguments.  */
528   new_args = make_tree_vec (n);
529   for (i = 1; i <= n; ++i)
530     SET_TMPL_ARGS_LEVEL (new_args, i,
531                          TMPL_ARGS_LEVEL (args, i + extra_levels));
532
533   return new_args;
534 }
535
536 /* The inverse of get_innermost_template_args: Return all but the innermost
537    EXTRA_LEVELS levels of template arguments from the ARGS.  */
538
539 static tree
540 strip_innermost_template_args (tree args, int extra_levels)
541 {
542   tree new_args;
543   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
544   int i;
545
546   gcc_assert (n >= 0);
547
548   /* If N is 1, just return the outermost set of template arguments.  */
549   if (n == 1)
550     return TMPL_ARGS_LEVEL (args, 1);
551
552   /* If we're not removing anything, just return the arguments we were
553      given.  */
554   gcc_assert (extra_levels >= 0);
555   if (extra_levels == 0)
556     return args;
557
558   /* Make a new set of arguments, not containing the inner arguments.  */
559   new_args = make_tree_vec (n);
560   for (i = 1; i <= n; ++i)
561     SET_TMPL_ARGS_LEVEL (new_args, i,
562                          TMPL_ARGS_LEVEL (args, i));
563
564   return new_args;
565 }
566
567 /* We've got a template header coming up; push to a new level for storing
568    the parms.  */
569
570 void
571 begin_template_parm_list (void)
572 {
573   /* We use a non-tag-transparent scope here, which causes pushtag to
574      put tags in this scope, rather than in the enclosing class or
575      namespace scope.  This is the right thing, since we want
576      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
577      global template class, push_template_decl handles putting the
578      TEMPLATE_DECL into top-level scope.  For a nested template class,
579      e.g.:
580
581        template <class T> struct S1 {
582          template <class T> struct S2 {};
583        };
584
585      pushtag contains special code to call pushdecl_with_scope on the
586      TEMPLATE_DECL for S2.  */
587   begin_scope (sk_template_parms, NULL);
588   ++processing_template_decl;
589   ++processing_template_parmlist;
590   note_template_header (0);
591 }
592
593 /* This routine is called when a specialization is declared.  If it is
594    invalid to declare a specialization here, an error is reported and
595    false is returned, otherwise this routine will return true.  */
596
597 static bool
598 check_specialization_scope (void)
599 {
600   tree scope = current_scope ();
601
602   /* [temp.expl.spec]
603
604      An explicit specialization shall be declared in the namespace of
605      which the template is a member, or, for member templates, in the
606      namespace of which the enclosing class or enclosing class
607      template is a member.  An explicit specialization of a member
608      function, member class or static data member of a class template
609      shall be declared in the namespace of which the class template
610      is a member.  */
611   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
612     {
613       error ("explicit specialization in non-namespace scope %qD", scope);
614       return false;
615     }
616
617   /* [temp.expl.spec]
618
619      In an explicit specialization declaration for a member of a class
620      template or a member template that appears in namespace scope,
621      the member template and some of its enclosing class templates may
622      remain unspecialized, except that the declaration shall not
623      explicitly specialize a class member template if its enclosing
624      class templates are not explicitly specialized as well.  */
625   if (current_template_parms)
626     {
627       error ("enclosing class templates are not explicitly specialized");
628       return false;
629     }
630
631   return true;
632 }
633
634 /* We've just seen template <>.  */
635
636 bool
637 begin_specialization (void)
638 {
639   begin_scope (sk_template_spec, NULL);
640   note_template_header (1);
641   return check_specialization_scope ();
642 }
643
644 /* Called at then end of processing a declaration preceded by
645    template<>.  */
646
647 void
648 end_specialization (void)
649 {
650   finish_scope ();
651   reset_specialization ();
652 }
653
654 /* Any template <>'s that we have seen thus far are not referring to a
655    function specialization.  */
656
657 void
658 reset_specialization (void)
659 {
660   processing_specialization = 0;
661   template_header_count = 0;
662 }
663
664 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
665    it was of the form template <>.  */
666
667 static void
668 note_template_header (int specialization)
669 {
670   processing_specialization = specialization;
671   template_header_count++;
672 }
673
674 /* We're beginning an explicit instantiation.  */
675
676 void
677 begin_explicit_instantiation (void)
678 {
679   gcc_assert (!processing_explicit_instantiation);
680   processing_explicit_instantiation = true;
681 }
682
683
684 void
685 end_explicit_instantiation (void)
686 {
687   gcc_assert (processing_explicit_instantiation);
688   processing_explicit_instantiation = false;
689 }
690
691 /* An explicit specialization or partial specialization TMPL is being
692    declared.  Check that the namespace in which the specialization is
693    occurring is permissible.  Returns false iff it is invalid to
694    specialize TMPL in the current namespace.  */
695
696 static bool
697 check_specialization_namespace (tree tmpl)
698 {
699   tree tpl_ns = decl_namespace_context (tmpl);
700
701   /* [tmpl.expl.spec]
702
703      An explicit specialization shall be declared in the namespace of
704      which the template is a member, or, for member templates, in the
705      namespace of which the enclosing class or enclosing class
706      template is a member.  An explicit specialization of a member
707      function, member class or static data member of a class template
708      shall be declared in the namespace of which the class template is
709      a member.  */
710   if (is_associated_namespace (current_namespace, tpl_ns))
711     /* Same or super-using namespace.  */
712     return true;
713   else
714     {
715       permerror (input_location, "specialization of %qD in different namespace", tmpl);
716       permerror (input_location, "  from definition of %q+#D", tmpl);
717       return false;
718     }
719 }
720
721 /* SPEC is an explicit instantiation.  Check that it is valid to
722    perform this explicit instantiation in the current namespace.  */
723
724 static void
725 check_explicit_instantiation_namespace (tree spec)
726 {
727   tree ns;
728
729   /* DR 275: An explicit instantiation shall appear in an enclosing
730      namespace of its template.  */
731   ns = decl_namespace_context (spec);
732   if (!is_ancestor (current_namespace, ns))
733     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
734                "(which does not enclose namespace %qD)",
735                spec, current_namespace, ns);
736 }
737
738 /* The TYPE is being declared.  If it is a template type, that means it
739    is a partial specialization.  Do appropriate error-checking.  */
740
741 tree
742 maybe_process_partial_specialization (tree type)
743 {
744   tree context;
745
746   if (type == error_mark_node)
747     return error_mark_node;
748
749   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
750     {
751       error ("name of class shadows template template parameter %qD",
752              TYPE_NAME (type));
753       return error_mark_node;
754     }
755
756   context = TYPE_CONTEXT (type);
757
758   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
759     {
760       /* This is for ordinary explicit specialization and partial
761          specialization of a template class such as:
762
763            template <> class C<int>;
764
765          or:
766
767            template <class T> class C<T*>;
768
769          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
770
771       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
772           && !COMPLETE_TYPE_P (type))
773         {
774           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
775           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
776           if (processing_template_decl)
777             {
778               if (push_template_decl (TYPE_MAIN_DECL (type))
779                   == error_mark_node)
780                 return error_mark_node;
781             }
782         }
783       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
784         error ("specialization of %qT after instantiation", type);
785     }
786   else if (CLASS_TYPE_P (type)
787            && !CLASSTYPE_USE_TEMPLATE (type)
788            && CLASSTYPE_TEMPLATE_INFO (type)
789            && context && CLASS_TYPE_P (context)
790            && CLASSTYPE_TEMPLATE_INFO (context))
791     {
792       /* This is for an explicit specialization of member class
793          template according to [temp.expl.spec/18]:
794
795            template <> template <class U> class C<int>::D;
796
797          The context `C<int>' must be an implicit instantiation.
798          Otherwise this is just a member class template declared
799          earlier like:
800
801            template <> class C<int> { template <class U> class D; };
802            template <> template <class U> class C<int>::D;
803
804          In the first case, `C<int>::D' is a specialization of `C<T>::D'
805          while in the second case, `C<int>::D' is a primary template
806          and `C<T>::D' may not exist.  */
807
808       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
809           && !COMPLETE_TYPE_P (type))
810         {
811           tree t;
812
813           if (current_namespace
814               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
815             {
816               permerror (input_location, "specializing %q#T in different namespace", type);
817               permerror (input_location, "  from definition of %q+#D",
818                          CLASSTYPE_TI_TEMPLATE (type));
819             }
820
821           /* Check for invalid specialization after instantiation:
822
823                template <> template <> class C<int>::D<int>;
824                template <> template <class U> class C<int>::D;  */
825
826           for (t = DECL_TEMPLATE_INSTANTIATIONS
827                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
828                t; t = TREE_CHAIN (t))
829             if (TREE_VALUE (t) != type
830                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
831               error ("specialization %qT after instantiation %qT",
832                      type, TREE_VALUE (t));
833
834           /* Mark TYPE as a specialization.  And as a result, we only
835              have one level of template argument for the innermost
836              class template.  */
837           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
838           CLASSTYPE_TI_ARGS (type)
839             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
840         }
841     }
842   else if (processing_specialization)
843     {
844       error ("explicit specialization of non-template %qT", type);
845       return error_mark_node;
846     }
847
848   return type;
849 }
850
851 /* Returns nonzero if we can optimize the retrieval of specializations
852    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
853    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
854
855 static inline bool
856 optimize_specialization_lookup_p (tree tmpl)
857 {
858   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
859           && DECL_CLASS_SCOPE_P (tmpl)
860           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
861              parameter.  */
862           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
863           /* The optimized lookup depends on the fact that the
864              template arguments for the member function template apply
865              purely to the containing class, which is not true if the
866              containing class is an explicit or partial
867              specialization.  */
868           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
869           && !DECL_MEMBER_TEMPLATE_P (tmpl)
870           && !DECL_CONV_FN_P (tmpl)
871           /* It is possible to have a template that is not a member
872              template and is not a member of a template class:
873
874              template <typename T>
875              struct S { friend A::f(); };
876
877              Here, the friend function is a template, but the context does
878              not have template information.  The optimized lookup relies
879              on having ARGS be the template arguments for both the class
880              and the function template.  */
881           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
882 }
883
884 /* Retrieve the specialization (in the sense of [temp.spec] - a
885    specialization is either an instantiation or an explicit
886    specialization) of TMPL for the given template ARGS.  If there is
887    no such specialization, return NULL_TREE.  The ARGS are a vector of
888    arguments, or a vector of vectors of arguments, in the case of
889    templates with more than one level of parameters.
890
891    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
892    then we search for a partial specialization matching ARGS.  This
893    parameter is ignored if TMPL is not a class template.  */
894
895 static tree
896 retrieve_specialization (tree tmpl, tree args,
897                          bool class_specializations_p)
898 {
899   if (args == error_mark_node)
900     return NULL_TREE;
901
902   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
903
904   /* There should be as many levels of arguments as there are
905      levels of parameters.  */
906   gcc_assert (TMPL_ARGS_DEPTH (args)
907               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
908
909   if (optimize_specialization_lookup_p (tmpl))
910     {
911       tree class_template;
912       tree class_specialization;
913       VEC(tree,gc) *methods;
914       tree fns;
915       int idx;
916
917       /* The template arguments actually apply to the containing
918          class.  Find the class specialization with those
919          arguments.  */
920       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
921       class_specialization
922         = retrieve_specialization (class_template, args,
923                                    /*class_specializations_p=*/false);
924       if (!class_specialization)
925         return NULL_TREE;
926       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
927          for the specialization.  */
928       idx = class_method_index_for_fn (class_specialization, tmpl);
929       if (idx == -1)
930         return NULL_TREE;
931       /* Iterate through the methods with the indicated name, looking
932          for the one that has an instance of TMPL.  */
933       methods = CLASSTYPE_METHOD_VEC (class_specialization);
934       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
935         {
936           tree fn = OVL_CURRENT (fns);
937           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
938             return fn;
939         }
940       return NULL_TREE;
941     }
942   else
943     {
944       tree *sp;
945       tree *head;
946
947       /* Class templates store their instantiations on the
948          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
949          DECL_TEMPLATE_SPECIALIZATIONS list.  */
950       if (!class_specializations_p
951           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
952           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
953         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
954       else
955         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
956       head = sp;
957       /* Iterate through the list until we find a matching template.  */
958       while (*sp != NULL_TREE)
959         {
960           tree spec = *sp;
961
962           if (comp_template_args (TREE_PURPOSE (spec), args))
963             {
964               /* Use the move-to-front heuristic to speed up future
965                  searches.  */
966               if (spec != *head)
967                 {
968                   *sp = TREE_CHAIN (*sp);
969                   TREE_CHAIN (spec) = *head;
970                   *head = spec;
971                 }
972               return TREE_VALUE (spec);
973             }
974           sp = &TREE_CHAIN (spec);
975         }
976     }
977
978   return NULL_TREE;
979 }
980
981 /* Like retrieve_specialization, but for local declarations.  */
982
983 static tree
984 retrieve_local_specialization (tree tmpl)
985 {
986   tree spec;
987
988   if (local_specializations == NULL)
989     return NULL_TREE;
990
991   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
992                                      htab_hash_pointer (tmpl));
993   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
994 }
995
996 /* Returns nonzero iff DECL is a specialization of TMPL.  */
997
998 int
999 is_specialization_of (tree decl, tree tmpl)
1000 {
1001   tree t;
1002
1003   if (TREE_CODE (decl) == FUNCTION_DECL)
1004     {
1005       for (t = decl;
1006            t != NULL_TREE;
1007            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1008         if (t == tmpl)
1009           return 1;
1010     }
1011   else
1012     {
1013       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1014
1015       for (t = TREE_TYPE (decl);
1016            t != NULL_TREE;
1017            t = CLASSTYPE_USE_TEMPLATE (t)
1018              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1019         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1020           return 1;
1021     }
1022
1023   return 0;
1024 }
1025
1026 /* Returns nonzero iff DECL is a specialization of friend declaration
1027    FRIEND_DECL according to [temp.friend].  */
1028
1029 bool
1030 is_specialization_of_friend (tree decl, tree friend_decl)
1031 {
1032   bool need_template = true;
1033   int template_depth;
1034
1035   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1036               || TREE_CODE (decl) == TYPE_DECL);
1037
1038   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1039      of a template class, we want to check if DECL is a specialization
1040      if this.  */
1041   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1042       && DECL_TEMPLATE_INFO (friend_decl)
1043       && !DECL_USE_TEMPLATE (friend_decl))
1044     {
1045       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1046       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1047       need_template = false;
1048     }
1049   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1050            && !PRIMARY_TEMPLATE_P (friend_decl))
1051     need_template = false;
1052
1053   /* There is nothing to do if this is not a template friend.  */
1054   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1055     return false;
1056
1057   if (is_specialization_of (decl, friend_decl))
1058     return true;
1059
1060   /* [temp.friend/6]
1061      A member of a class template may be declared to be a friend of a
1062      non-template class.  In this case, the corresponding member of
1063      every specialization of the class template is a friend of the
1064      class granting friendship.
1065
1066      For example, given a template friend declaration
1067
1068        template <class T> friend void A<T>::f();
1069
1070      the member function below is considered a friend
1071
1072        template <> struct A<int> {
1073          void f();
1074        };
1075
1076      For this type of template friend, TEMPLATE_DEPTH below will be
1077      nonzero.  To determine if DECL is a friend of FRIEND, we first
1078      check if the enclosing class is a specialization of another.  */
1079
1080   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1081   if (template_depth
1082       && DECL_CLASS_SCOPE_P (decl)
1083       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1084                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1085     {
1086       /* Next, we check the members themselves.  In order to handle
1087          a few tricky cases, such as when FRIEND_DECL's are
1088
1089            template <class T> friend void A<T>::g(T t);
1090            template <class T> template <T t> friend void A<T>::h();
1091
1092          and DECL's are
1093
1094            void A<int>::g(int);
1095            template <int> void A<int>::h();
1096
1097          we need to figure out ARGS, the template arguments from
1098          the context of DECL.  This is required for template substitution
1099          of `T' in the function parameter of `g' and template parameter
1100          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1101
1102       tree context = DECL_CONTEXT (decl);
1103       tree args = NULL_TREE;
1104       int current_depth = 0;
1105
1106       while (current_depth < template_depth)
1107         {
1108           if (CLASSTYPE_TEMPLATE_INFO (context))
1109             {
1110               if (current_depth == 0)
1111                 args = TYPE_TI_ARGS (context);
1112               else
1113                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1114               current_depth++;
1115             }
1116           context = TYPE_CONTEXT (context);
1117         }
1118
1119       if (TREE_CODE (decl) == FUNCTION_DECL)
1120         {
1121           bool is_template;
1122           tree friend_type;
1123           tree decl_type;
1124           tree friend_args_type;
1125           tree decl_args_type;
1126
1127           /* Make sure that both DECL and FRIEND_DECL are templates or
1128              non-templates.  */
1129           is_template = DECL_TEMPLATE_INFO (decl)
1130                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1131           if (need_template ^ is_template)
1132             return false;
1133           else if (is_template)
1134             {
1135               /* If both are templates, check template parameter list.  */
1136               tree friend_parms
1137                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1138                                          args, tf_none);
1139               if (!comp_template_parms
1140                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1141                       friend_parms))
1142                 return false;
1143
1144               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1145             }
1146           else
1147             decl_type = TREE_TYPE (decl);
1148
1149           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1150                                               tf_none, NULL_TREE);
1151           if (friend_type == error_mark_node)
1152             return false;
1153
1154           /* Check if return types match.  */
1155           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1156             return false;
1157
1158           /* Check if function parameter types match, ignoring the
1159              `this' parameter.  */
1160           friend_args_type = TYPE_ARG_TYPES (friend_type);
1161           decl_args_type = TYPE_ARG_TYPES (decl_type);
1162           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1163             friend_args_type = TREE_CHAIN (friend_args_type);
1164           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1165             decl_args_type = TREE_CHAIN (decl_args_type);
1166
1167           return compparms (decl_args_type, friend_args_type);
1168         }
1169       else
1170         {
1171           /* DECL is a TYPE_DECL */
1172           bool is_template;
1173           tree decl_type = TREE_TYPE (decl);
1174
1175           /* Make sure that both DECL and FRIEND_DECL are templates or
1176              non-templates.  */
1177           is_template
1178             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1179               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1180
1181           if (need_template ^ is_template)
1182             return false;
1183           else if (is_template)
1184             {
1185               tree friend_parms;
1186               /* If both are templates, check the name of the two
1187                  TEMPLATE_DECL's first because is_friend didn't.  */
1188               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1189                   != DECL_NAME (friend_decl))
1190                 return false;
1191
1192               /* Now check template parameter list.  */
1193               friend_parms
1194                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1195                                          args, tf_none);
1196               return comp_template_parms
1197                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1198                  friend_parms);
1199             }
1200           else
1201             return (DECL_NAME (decl)
1202                     == DECL_NAME (friend_decl));
1203         }
1204     }
1205   return false;
1206 }
1207
1208 /* Register the specialization SPEC as a specialization of TMPL with
1209    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1210    is actually just a friend declaration.  Returns SPEC, or an
1211    equivalent prior declaration, if available.  */
1212
1213 static tree
1214 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1215 {
1216   tree fn;
1217
1218   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1219
1220   if (TREE_CODE (spec) == FUNCTION_DECL
1221       && uses_template_parms (DECL_TI_ARGS (spec)))
1222     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1223        register it; we want the corresponding TEMPLATE_DECL instead.
1224        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1225        the more obvious `uses_template_parms (spec)' to avoid problems
1226        with default function arguments.  In particular, given
1227        something like this:
1228
1229           template <class T> void f(T t1, T t = T())
1230
1231        the default argument expression is not substituted for in an
1232        instantiation unless and until it is actually needed.  */
1233     return spec;
1234
1235   fn = retrieve_specialization (tmpl, args,
1236                                 /*class_specializations_p=*/false);
1237   /* We can sometimes try to re-register a specialization that we've
1238      already got.  In particular, regenerate_decl_from_template calls
1239      duplicate_decls which will update the specialization list.  But,
1240      we'll still get called again here anyhow.  It's more convenient
1241      to simply allow this than to try to prevent it.  */
1242   if (fn == spec)
1243     return spec;
1244   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1245     {
1246       if (DECL_TEMPLATE_INSTANTIATION (fn))
1247         {
1248           if (TREE_USED (fn)
1249               || DECL_EXPLICIT_INSTANTIATION (fn))
1250             {
1251               error ("specialization of %qD after instantiation",
1252                      fn);
1253               return error_mark_node;
1254             }
1255           else
1256             {
1257               tree clone;
1258               /* This situation should occur only if the first
1259                  specialization is an implicit instantiation, the
1260                  second is an explicit specialization, and the
1261                  implicit instantiation has not yet been used.  That
1262                  situation can occur if we have implicitly
1263                  instantiated a member function and then specialized
1264                  it later.
1265
1266                  We can also wind up here if a friend declaration that
1267                  looked like an instantiation turns out to be a
1268                  specialization:
1269
1270                    template <class T> void foo(T);
1271                    class S { friend void foo<>(int) };
1272                    template <> void foo(int);
1273
1274                  We transform the existing DECL in place so that any
1275                  pointers to it become pointers to the updated
1276                  declaration.
1277
1278                  If there was a definition for the template, but not
1279                  for the specialization, we want this to look as if
1280                  there were no definition, and vice versa.  */
1281               DECL_INITIAL (fn) = NULL_TREE;
1282               duplicate_decls (spec, fn, is_friend);
1283               /* The call to duplicate_decls will have applied
1284                  [temp.expl.spec]:
1285
1286                    An explicit specialization of a function template
1287                    is inline only if it is explicitly declared to be,
1288                    and independently of whether its function template
1289                    is.
1290
1291                 to the primary function; now copy the inline bits to
1292                 the various clones.  */
1293               FOR_EACH_CLONE (clone, fn)
1294                 DECL_DECLARED_INLINE_P (clone)
1295                   = DECL_DECLARED_INLINE_P (fn);
1296               check_specialization_namespace (fn);
1297
1298               return fn;
1299             }
1300         }
1301       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1302         {
1303           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1304             /* Dup decl failed, but this is a new definition. Set the
1305                line number so any errors match this new
1306                definition.  */
1307             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1308
1309           return fn;
1310         }
1311     }
1312
1313   /* A specialization must be declared in the same namespace as the
1314      template it is specializing.  */
1315   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1316       && !check_specialization_namespace (tmpl))
1317     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1318
1319   if (!optimize_specialization_lookup_p (tmpl))
1320     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1321       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1322
1323   return spec;
1324 }
1325
1326 /* Unregister the specialization SPEC as a specialization of TMPL.
1327    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1328    if the SPEC was listed as a specialization of TMPL.  */
1329
1330 bool
1331 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1332 {
1333   tree* s;
1334
1335   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1336        *s != NULL_TREE;
1337        s = &TREE_CHAIN (*s))
1338     if (TREE_VALUE (*s) == spec)
1339       {
1340         if (!new_spec)
1341           *s = TREE_CHAIN (*s);
1342         else
1343           TREE_VALUE (*s) = new_spec;
1344         return 1;
1345       }
1346
1347   return 0;
1348 }
1349
1350 /* Compare an entry in the local specializations hash table P1 (which
1351    is really a pointer to a TREE_LIST) with P2 (which is really a
1352    DECL).  */
1353
1354 static int
1355 eq_local_specializations (const void *p1, const void *p2)
1356 {
1357   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1358 }
1359
1360 /* Hash P1, an entry in the local specializations table.  */
1361
1362 static hashval_t
1363 hash_local_specialization (const void* p1)
1364 {
1365   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1366 }
1367
1368 /* Like register_specialization, but for local declarations.  We are
1369    registering SPEC, an instantiation of TMPL.  */
1370
1371 static void
1372 register_local_specialization (tree spec, tree tmpl)
1373 {
1374   void **slot;
1375
1376   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1377                                    htab_hash_pointer (tmpl), INSERT);
1378   *slot = build_tree_list (spec, tmpl);
1379 }
1380
1381 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1382    specialized class.  */
1383
1384 bool
1385 explicit_class_specialization_p (tree type)
1386 {
1387   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1388     return false;
1389   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1390 }
1391
1392 /* Print the list of candidate FNS in an error message.  */
1393
1394 void
1395 print_candidates (tree fns)
1396 {
1397   tree fn;
1398
1399   const char *str = "candidates are:";
1400
1401   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1402     {
1403       tree f;
1404
1405       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1406         error ("%s %+#D", str, OVL_CURRENT (f));
1407       str = "               ";
1408     }
1409 }
1410
1411 /* Returns the template (one of the functions given by TEMPLATE_ID)
1412    which can be specialized to match the indicated DECL with the
1413    explicit template args given in TEMPLATE_ID.  The DECL may be
1414    NULL_TREE if none is available.  In that case, the functions in
1415    TEMPLATE_ID are non-members.
1416
1417    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1418    specialization of a member template.
1419
1420    The TEMPLATE_COUNT is the number of references to qualifying
1421    template classes that appeared in the name of the function. See
1422    check_explicit_specialization for a more accurate description.
1423
1424    TSK indicates what kind of template declaration (if any) is being
1425    declared.  TSK_TEMPLATE indicates that the declaration given by
1426    DECL, though a FUNCTION_DECL, has template parameters, and is
1427    therefore a template function.
1428
1429    The template args (those explicitly specified and those deduced)
1430    are output in a newly created vector *TARGS_OUT.
1431
1432    If it is impossible to determine the result, an error message is
1433    issued.  The error_mark_node is returned to indicate failure.  */
1434
1435 static tree
1436 determine_specialization (tree template_id,
1437                           tree decl,
1438                           tree* targs_out,
1439                           int need_member_template,
1440                           int template_count,
1441                           tmpl_spec_kind tsk)
1442 {
1443   tree fns;
1444   tree targs;
1445   tree explicit_targs;
1446   tree candidates = NULL_TREE;
1447   /* A TREE_LIST of templates of which DECL may be a specialization.
1448      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1449      corresponding TREE_PURPOSE is the set of template arguments that,
1450      when used to instantiate the template, would produce a function
1451      with the signature of DECL.  */
1452   tree templates = NULL_TREE;
1453   int header_count;
1454   struct cp_binding_level *b;
1455
1456   *targs_out = NULL_TREE;
1457
1458   if (template_id == error_mark_node || decl == error_mark_node)
1459     return error_mark_node;
1460
1461   fns = TREE_OPERAND (template_id, 0);
1462   explicit_targs = TREE_OPERAND (template_id, 1);
1463
1464   if (fns == error_mark_node)
1465     return error_mark_node;
1466
1467   /* Check for baselinks.  */
1468   if (BASELINK_P (fns))
1469     fns = BASELINK_FUNCTIONS (fns);
1470
1471   if (!is_overloaded_fn (fns))
1472     {
1473       error ("%qD is not a function template", fns);
1474       return error_mark_node;
1475     }
1476
1477   /* Count the number of template headers specified for this
1478      specialization.  */
1479   header_count = 0;
1480   for (b = current_binding_level;
1481        b->kind == sk_template_parms;
1482        b = b->level_chain)
1483     ++header_count;
1484
1485   for (; fns; fns = OVL_NEXT (fns))
1486     {
1487       tree fn = OVL_CURRENT (fns);
1488
1489       if (TREE_CODE (fn) == TEMPLATE_DECL)
1490         {
1491           tree decl_arg_types;
1492           tree fn_arg_types;
1493
1494           /* In case of explicit specialization, we need to check if
1495              the number of template headers appearing in the specialization
1496              is correct. This is usually done in check_explicit_specialization,
1497              but the check done there cannot be exhaustive when specializing
1498              member functions. Consider the following code:
1499
1500              template <> void A<int>::f(int);
1501              template <> template <> void A<int>::f(int);
1502
1503              Assuming that A<int> is not itself an explicit specialization
1504              already, the first line specializes "f" which is a non-template
1505              member function, whilst the second line specializes "f" which
1506              is a template member function. So both lines are syntactically
1507              correct, and check_explicit_specialization does not reject
1508              them.
1509
1510              Here, we can do better, as we are matching the specialization
1511              against the declarations. We count the number of template
1512              headers, and we check if they match TEMPLATE_COUNT + 1
1513              (TEMPLATE_COUNT is the number of qualifying template classes,
1514              plus there must be another header for the member template
1515              itself).
1516
1517              Notice that if header_count is zero, this is not a
1518              specialization but rather a template instantiation, so there
1519              is no check we can perform here.  */
1520           if (header_count && header_count != template_count + 1)
1521             continue;
1522
1523           /* Check that the number of template arguments at the
1524              innermost level for DECL is the same as for FN.  */
1525           if (current_binding_level->kind == sk_template_parms
1526               && !current_binding_level->explicit_spec_p
1527               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1528                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1529                                       (current_template_parms))))
1530             continue;
1531
1532           /* DECL might be a specialization of FN.  */
1533           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1534           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1535
1536           /* For a non-static member function, we need to make sure
1537              that the const qualification is the same.  Since
1538              get_bindings does not try to merge the "this" parameter,
1539              we must do the comparison explicitly.  */
1540           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1541               && !same_type_p (TREE_VALUE (fn_arg_types),
1542                                TREE_VALUE (decl_arg_types)))
1543             continue;
1544
1545           /* Skip the "this" parameter and, for constructors of
1546              classes with virtual bases, the VTT parameter.  A
1547              full specialization of a constructor will have a VTT
1548              parameter, but a template never will.  */ 
1549           decl_arg_types 
1550             = skip_artificial_parms_for (decl, decl_arg_types);
1551           fn_arg_types 
1552             = skip_artificial_parms_for (fn, fn_arg_types);
1553
1554           /* Check that the number of function parameters matches.
1555              For example,
1556                template <class T> void f(int i = 0);
1557                template <> void f<int>();
1558              The specialization f<int> is invalid but is not caught
1559              by get_bindings below.  */
1560           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1561             continue;
1562
1563           /* Function templates cannot be specializations; there are
1564              no partial specializations of functions.  Therefore, if
1565              the type of DECL does not match FN, there is no
1566              match.  */
1567           if (tsk == tsk_template)
1568             {
1569               if (compparms (fn_arg_types, decl_arg_types))
1570                 candidates = tree_cons (NULL_TREE, fn, candidates);
1571               continue;
1572             }
1573
1574           /* See whether this function might be a specialization of this
1575              template.  */
1576           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1577
1578           if (!targs)
1579             /* We cannot deduce template arguments that when used to
1580                specialize TMPL will produce DECL.  */
1581             continue;
1582
1583           /* Save this template, and the arguments deduced.  */
1584           templates = tree_cons (targs, fn, templates);
1585         }
1586       else if (need_member_template)
1587         /* FN is an ordinary member function, and we need a
1588            specialization of a member template.  */
1589         ;
1590       else if (TREE_CODE (fn) != FUNCTION_DECL)
1591         /* We can get IDENTIFIER_NODEs here in certain erroneous
1592            cases.  */
1593         ;
1594       else if (!DECL_FUNCTION_MEMBER_P (fn))
1595         /* This is just an ordinary non-member function.  Nothing can
1596            be a specialization of that.  */
1597         ;
1598       else if (DECL_ARTIFICIAL (fn))
1599         /* Cannot specialize functions that are created implicitly.  */
1600         ;
1601       else
1602         {
1603           tree decl_arg_types;
1604
1605           /* This is an ordinary member function.  However, since
1606              we're here, we can assume it's enclosing class is a
1607              template class.  For example,
1608
1609                template <typename T> struct S { void f(); };
1610                template <> void S<int>::f() {}
1611
1612              Here, S<int>::f is a non-template, but S<int> is a
1613              template class.  If FN has the same type as DECL, we
1614              might be in business.  */
1615
1616           if (!DECL_TEMPLATE_INFO (fn))
1617             /* Its enclosing class is an explicit specialization
1618                of a template class.  This is not a candidate.  */
1619             continue;
1620
1621           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1622                             TREE_TYPE (TREE_TYPE (fn))))
1623             /* The return types differ.  */
1624             continue;
1625
1626           /* Adjust the type of DECL in case FN is a static member.  */
1627           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1628           if (DECL_STATIC_FUNCTION_P (fn)
1629               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1630             decl_arg_types = TREE_CHAIN (decl_arg_types);
1631
1632           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1633                          decl_arg_types))
1634             /* They match!  */
1635             candidates = tree_cons (NULL_TREE, fn, candidates);
1636         }
1637     }
1638
1639   if (templates && TREE_CHAIN (templates))
1640     {
1641       /* We have:
1642
1643            [temp.expl.spec]
1644
1645            It is possible for a specialization with a given function
1646            signature to be instantiated from more than one function
1647            template.  In such cases, explicit specification of the
1648            template arguments must be used to uniquely identify the
1649            function template specialization being specialized.
1650
1651          Note that here, there's no suggestion that we're supposed to
1652          determine which of the candidate templates is most
1653          specialized.  However, we, also have:
1654
1655            [temp.func.order]
1656
1657            Partial ordering of overloaded function template
1658            declarations is used in the following contexts to select
1659            the function template to which a function template
1660            specialization refers:
1661
1662            -- when an explicit specialization refers to a function
1663               template.
1664
1665          So, we do use the partial ordering rules, at least for now.
1666          This extension can only serve to make invalid programs valid,
1667          so it's safe.  And, there is strong anecdotal evidence that
1668          the committee intended the partial ordering rules to apply;
1669          the EDG front end has that behavior, and John Spicer claims
1670          that the committee simply forgot to delete the wording in
1671          [temp.expl.spec].  */
1672       tree tmpl = most_specialized_instantiation (templates);
1673       if (tmpl != error_mark_node)
1674         {
1675           templates = tmpl;
1676           TREE_CHAIN (templates) = NULL_TREE;
1677         }
1678     }
1679
1680   if (templates == NULL_TREE && candidates == NULL_TREE)
1681     {
1682       error ("template-id %qD for %q+D does not match any template "
1683              "declaration", template_id, decl);
1684       return error_mark_node;
1685     }
1686   else if ((templates && TREE_CHAIN (templates))
1687            || (candidates && TREE_CHAIN (candidates))
1688            || (templates && candidates))
1689     {
1690       error ("ambiguous template specialization %qD for %q+D",
1691              template_id, decl);
1692       chainon (candidates, templates);
1693       print_candidates (candidates);
1694       return error_mark_node;
1695     }
1696
1697   /* We have one, and exactly one, match.  */
1698   if (candidates)
1699     {
1700       tree fn = TREE_VALUE (candidates);
1701       /* DECL is a re-declaration of a template function.  */
1702       if (TREE_CODE (fn) == TEMPLATE_DECL)
1703         return fn;
1704       /* It was a specialization of an ordinary member function in a
1705          template class.  */
1706       *targs_out = copy_node (DECL_TI_ARGS (fn));
1707       return DECL_TI_TEMPLATE (fn);
1708     }
1709
1710   /* It was a specialization of a template.  */
1711   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1712   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1713     {
1714       *targs_out = copy_node (targs);
1715       SET_TMPL_ARGS_LEVEL (*targs_out,
1716                            TMPL_ARGS_DEPTH (*targs_out),
1717                            TREE_PURPOSE (templates));
1718     }
1719   else
1720     *targs_out = TREE_PURPOSE (templates);
1721   return TREE_VALUE (templates);
1722 }
1723
1724 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1725    but with the default argument values filled in from those in the
1726    TMPL_TYPES.  */
1727
1728 static tree
1729 copy_default_args_to_explicit_spec_1 (tree spec_types,
1730                                       tree tmpl_types)
1731 {
1732   tree new_spec_types;
1733
1734   if (!spec_types)
1735     return NULL_TREE;
1736
1737   if (spec_types == void_list_node)
1738     return void_list_node;
1739
1740   /* Substitute into the rest of the list.  */
1741   new_spec_types =
1742     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1743                                           TREE_CHAIN (tmpl_types));
1744
1745   /* Add the default argument for this parameter.  */
1746   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1747                          TREE_VALUE (spec_types),
1748                          new_spec_types);
1749 }
1750
1751 /* DECL is an explicit specialization.  Replicate default arguments
1752    from the template it specializes.  (That way, code like:
1753
1754      template <class T> void f(T = 3);
1755      template <> void f(double);
1756      void g () { f (); }
1757
1758    works, as required.)  An alternative approach would be to look up
1759    the correct default arguments at the call-site, but this approach
1760    is consistent with how implicit instantiations are handled.  */
1761
1762 static void
1763 copy_default_args_to_explicit_spec (tree decl)
1764 {
1765   tree tmpl;
1766   tree spec_types;
1767   tree tmpl_types;
1768   tree new_spec_types;
1769   tree old_type;
1770   tree new_type;
1771   tree t;
1772   tree object_type = NULL_TREE;
1773   tree in_charge = NULL_TREE;
1774   tree vtt = NULL_TREE;
1775
1776   /* See if there's anything we need to do.  */
1777   tmpl = DECL_TI_TEMPLATE (decl);
1778   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1779   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1780     if (TREE_PURPOSE (t))
1781       break;
1782   if (!t)
1783     return;
1784
1785   old_type = TREE_TYPE (decl);
1786   spec_types = TYPE_ARG_TYPES (old_type);
1787
1788   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1789     {
1790       /* Remove the this pointer, but remember the object's type for
1791          CV quals.  */
1792       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1793       spec_types = TREE_CHAIN (spec_types);
1794       tmpl_types = TREE_CHAIN (tmpl_types);
1795
1796       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1797         {
1798           /* DECL may contain more parameters than TMPL due to the extra
1799              in-charge parameter in constructors and destructors.  */
1800           in_charge = spec_types;
1801           spec_types = TREE_CHAIN (spec_types);
1802         }
1803       if (DECL_HAS_VTT_PARM_P (decl))
1804         {
1805           vtt = spec_types;
1806           spec_types = TREE_CHAIN (spec_types);
1807         }
1808     }
1809
1810   /* Compute the merged default arguments.  */
1811   new_spec_types =
1812     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1813
1814   /* Compute the new FUNCTION_TYPE.  */
1815   if (object_type)
1816     {
1817       if (vtt)
1818         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1819                                          TREE_VALUE (vtt),
1820                                          new_spec_types);
1821
1822       if (in_charge)
1823         /* Put the in-charge parameter back.  */
1824         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1825                                          TREE_VALUE (in_charge),
1826                                          new_spec_types);
1827
1828       new_type = build_method_type_directly (object_type,
1829                                              TREE_TYPE (old_type),
1830                                              new_spec_types);
1831     }
1832   else
1833     new_type = build_function_type (TREE_TYPE (old_type),
1834                                     new_spec_types);
1835   new_type = cp_build_type_attribute_variant (new_type,
1836                                               TYPE_ATTRIBUTES (old_type));
1837   new_type = build_exception_variant (new_type,
1838                                       TYPE_RAISES_EXCEPTIONS (old_type));
1839   TREE_TYPE (decl) = new_type;
1840 }
1841
1842 /* Check to see if the function just declared, as indicated in
1843    DECLARATOR, and in DECL, is a specialization of a function
1844    template.  We may also discover that the declaration is an explicit
1845    instantiation at this point.
1846
1847    Returns DECL, or an equivalent declaration that should be used
1848    instead if all goes well.  Issues an error message if something is
1849    amiss.  Returns error_mark_node if the error is not easily
1850    recoverable.
1851
1852    FLAGS is a bitmask consisting of the following flags:
1853
1854    2: The function has a definition.
1855    4: The function is a friend.
1856
1857    The TEMPLATE_COUNT is the number of references to qualifying
1858    template classes that appeared in the name of the function.  For
1859    example, in
1860
1861      template <class T> struct S { void f(); };
1862      void S<int>::f();
1863
1864    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1865    classes are not counted in the TEMPLATE_COUNT, so that in
1866
1867      template <class T> struct S {};
1868      template <> struct S<int> { void f(); }
1869      template <> void S<int>::f();
1870
1871    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1872    invalid; there should be no template <>.)
1873
1874    If the function is a specialization, it is marked as such via
1875    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1876    is set up correctly, and it is added to the list of specializations
1877    for that template.  */
1878
1879 tree
1880 check_explicit_specialization (tree declarator,
1881                                tree decl,
1882                                int template_count,
1883                                int flags)
1884 {
1885   int have_def = flags & 2;
1886   int is_friend = flags & 4;
1887   int specialization = 0;
1888   int explicit_instantiation = 0;
1889   int member_specialization = 0;
1890   tree ctype = DECL_CLASS_CONTEXT (decl);
1891   tree dname = DECL_NAME (decl);
1892   tmpl_spec_kind tsk;
1893
1894   if (is_friend)
1895     {
1896       if (!processing_specialization)
1897         tsk = tsk_none;
1898       else
1899         tsk = tsk_excessive_parms;
1900     }
1901   else
1902     tsk = current_tmpl_spec_kind (template_count);
1903
1904   switch (tsk)
1905     {
1906     case tsk_none:
1907       if (processing_specialization)
1908         {
1909           specialization = 1;
1910           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1911         }
1912       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1913         {
1914           if (is_friend)
1915             /* This could be something like:
1916
1917                template <class T> void f(T);
1918                class S { friend void f<>(int); }  */
1919             specialization = 1;
1920           else
1921             {
1922               /* This case handles bogus declarations like template <>
1923                  template <class T> void f<int>(); */
1924
1925               error ("template-id %qD in declaration of primary template",
1926                      declarator);
1927               return decl;
1928             }
1929         }
1930       break;
1931
1932     case tsk_invalid_member_spec:
1933       /* The error has already been reported in
1934          check_specialization_scope.  */
1935       return error_mark_node;
1936
1937     case tsk_invalid_expl_inst:
1938       error ("template parameter list used in explicit instantiation");
1939
1940       /* Fall through.  */
1941
1942     case tsk_expl_inst:
1943       if (have_def)
1944         error ("definition provided for explicit instantiation");
1945
1946       explicit_instantiation = 1;
1947       break;
1948
1949     case tsk_excessive_parms:
1950     case tsk_insufficient_parms:
1951       if (tsk == tsk_excessive_parms)
1952         error ("too many template parameter lists in declaration of %qD",
1953                decl);
1954       else if (template_header_count)
1955         error("too few template parameter lists in declaration of %qD", decl);
1956       else
1957         error("explicit specialization of %qD must be introduced by "
1958               "%<template <>%>", decl);
1959
1960       /* Fall through.  */
1961     case tsk_expl_spec:
1962       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1963       if (ctype)
1964         member_specialization = 1;
1965       else
1966         specialization = 1;
1967       break;
1968
1969     case tsk_template:
1970       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1971         {
1972           /* This case handles bogus declarations like template <>
1973              template <class T> void f<int>(); */
1974
1975           if (uses_template_parms (declarator))
1976             error ("function template partial specialization %qD "
1977                    "is not allowed", declarator);
1978           else
1979             error ("template-id %qD in declaration of primary template",
1980                    declarator);
1981           return decl;
1982         }
1983
1984       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1985         /* This is a specialization of a member template, without
1986            specialization the containing class.  Something like:
1987
1988              template <class T> struct S {
1989                template <class U> void f (U);
1990              };
1991              template <> template <class U> void S<int>::f(U) {}
1992
1993            That's a specialization -- but of the entire template.  */
1994         specialization = 1;
1995       break;
1996
1997     default:
1998       gcc_unreachable ();
1999     }
2000
2001   if (specialization || member_specialization)
2002     {
2003       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2004       for (; t; t = TREE_CHAIN (t))
2005         if (TREE_PURPOSE (t))
2006           {
2007             permerror (input_location, 
2008                        "default argument specified in explicit specialization");
2009             break;
2010           }
2011     }
2012
2013   if (specialization || member_specialization || explicit_instantiation)
2014     {
2015       tree tmpl = NULL_TREE;
2016       tree targs = NULL_TREE;
2017
2018       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2019       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2020         {
2021           tree fns;
2022
2023           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2024           if (ctype)
2025             fns = dname;
2026           else
2027             {
2028               /* If there is no class context, the explicit instantiation
2029                  must be at namespace scope.  */
2030               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2031
2032               /* Find the namespace binding, using the declaration
2033                  context.  */
2034               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2035                                            false, true);
2036               if (fns == error_mark_node || !is_overloaded_fn (fns))
2037                 {
2038                   error ("%qD is not a template function", dname);
2039                   fns = error_mark_node;
2040                 }
2041               else
2042                 {
2043                   tree fn = OVL_CURRENT (fns);
2044                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2045                                                 CP_DECL_CONTEXT (fn)))
2046                     error ("%qD is not declared in %qD",
2047                            decl, current_namespace);
2048                 }
2049             }
2050
2051           declarator = lookup_template_function (fns, NULL_TREE);
2052         }
2053
2054       if (declarator == error_mark_node)
2055         return error_mark_node;
2056
2057       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2058         {
2059           if (!explicit_instantiation)
2060             /* A specialization in class scope.  This is invalid,
2061                but the error will already have been flagged by
2062                check_specialization_scope.  */
2063             return error_mark_node;
2064           else
2065             {
2066               /* It's not valid to write an explicit instantiation in
2067                  class scope, e.g.:
2068
2069                    class C { template void f(); }
2070
2071                    This case is caught by the parser.  However, on
2072                    something like:
2073
2074                    template class C { void f(); };
2075
2076                    (which is invalid) we can get here.  The error will be
2077                    issued later.  */
2078               ;
2079             }
2080
2081           return decl;
2082         }
2083       else if (ctype != NULL_TREE
2084                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2085                    IDENTIFIER_NODE))
2086         {
2087           /* Find the list of functions in ctype that have the same
2088              name as the declared function.  */
2089           tree name = TREE_OPERAND (declarator, 0);
2090           tree fns = NULL_TREE;
2091           int idx;
2092
2093           if (constructor_name_p (name, ctype))
2094             {
2095               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2096
2097               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2098                   : !CLASSTYPE_DESTRUCTORS (ctype))
2099                 {
2100                   /* From [temp.expl.spec]:
2101
2102                      If such an explicit specialization for the member
2103                      of a class template names an implicitly-declared
2104                      special member function (clause _special_), the
2105                      program is ill-formed.
2106
2107                      Similar language is found in [temp.explicit].  */
2108                   error ("specialization of implicitly-declared special member function");
2109                   return error_mark_node;
2110                 }
2111
2112               name = is_constructor ? ctor_identifier : dtor_identifier;
2113             }
2114
2115           if (!DECL_CONV_FN_P (decl))
2116             {
2117               idx = lookup_fnfields_1 (ctype, name);
2118               if (idx >= 0)
2119                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2120             }
2121           else
2122             {
2123               VEC(tree,gc) *methods;
2124               tree ovl;
2125
2126               /* For a type-conversion operator, we cannot do a
2127                  name-based lookup.  We might be looking for `operator
2128                  int' which will be a specialization of `operator T'.
2129                  So, we find *all* the conversion operators, and then
2130                  select from them.  */
2131               fns = NULL_TREE;
2132
2133               methods = CLASSTYPE_METHOD_VEC (ctype);
2134               if (methods)
2135                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2136                      VEC_iterate (tree, methods, idx, ovl);
2137                      ++idx)
2138                   {
2139                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2140                       /* There are no more conversion functions.  */
2141                       break;
2142
2143                     /* Glue all these conversion functions together
2144                        with those we already have.  */
2145                     for (; ovl; ovl = OVL_NEXT (ovl))
2146                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2147                   }
2148             }
2149
2150           if (fns == NULL_TREE)
2151             {
2152               error ("no member function %qD declared in %qT", name, ctype);
2153               return error_mark_node;
2154             }
2155           else
2156             TREE_OPERAND (declarator, 0) = fns;
2157         }
2158
2159       /* Figure out what exactly is being specialized at this point.
2160          Note that for an explicit instantiation, even one for a
2161          member function, we cannot tell apriori whether the
2162          instantiation is for a member template, or just a member
2163          function of a template class.  Even if a member template is
2164          being instantiated, the member template arguments may be
2165          elided if they can be deduced from the rest of the
2166          declaration.  */
2167       tmpl = determine_specialization (declarator, decl,
2168                                        &targs,
2169                                        member_specialization,
2170                                        template_count,
2171                                        tsk);
2172
2173       if (!tmpl || tmpl == error_mark_node)
2174         /* We couldn't figure out what this declaration was
2175            specializing.  */
2176         return error_mark_node;
2177       else
2178         {
2179           tree gen_tmpl = most_general_template (tmpl);
2180
2181           if (explicit_instantiation)
2182             {
2183               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2184                  is done by do_decl_instantiation later.  */
2185
2186               int arg_depth = TMPL_ARGS_DEPTH (targs);
2187               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2188
2189               if (arg_depth > parm_depth)
2190                 {
2191                   /* If TMPL is not the most general template (for
2192                      example, if TMPL is a friend template that is
2193                      injected into namespace scope), then there will
2194                      be too many levels of TARGS.  Remove some of them
2195                      here.  */
2196                   int i;
2197                   tree new_targs;
2198
2199                   new_targs = make_tree_vec (parm_depth);
2200                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2201                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2202                       = TREE_VEC_ELT (targs, i);
2203                   targs = new_targs;
2204                 }
2205
2206               return instantiate_template (tmpl, targs, tf_error);
2207             }
2208
2209           /* If we thought that the DECL was a member function, but it
2210              turns out to be specializing a static member function,
2211              make DECL a static member function as well.  */
2212           if (DECL_STATIC_FUNCTION_P (tmpl)
2213               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2214             revert_static_member_fn (decl);
2215
2216           /* If this is a specialization of a member template of a
2217              template class, we want to return the TEMPLATE_DECL, not
2218              the specialization of it.  */
2219           if (tsk == tsk_template)
2220             {
2221               tree result = DECL_TEMPLATE_RESULT (tmpl);
2222               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2223               DECL_INITIAL (result) = NULL_TREE;
2224               if (have_def)
2225                 {
2226                   tree parm;
2227                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2228                   DECL_SOURCE_LOCATION (result)
2229                     = DECL_SOURCE_LOCATION (decl);
2230                   /* We want to use the argument list specified in the
2231                      definition, not in the original declaration.  */
2232                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2233                   for (parm = DECL_ARGUMENTS (result); parm;
2234                        parm = TREE_CHAIN (parm))
2235                     DECL_CONTEXT (parm) = result;
2236                 }
2237               return tmpl;
2238             }
2239
2240           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2241           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2242
2243           /* Inherit default function arguments from the template
2244              DECL is specializing.  */
2245           copy_default_args_to_explicit_spec (decl);
2246
2247           /* This specialization has the same protection as the
2248              template it specializes.  */
2249           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2250           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2251
2252           /* 7.1.1-1 [dcl.stc]
2253
2254              A storage-class-specifier shall not be specified in an
2255              explicit specialization...
2256
2257              The parser rejects these, so unless action is taken here,
2258              explicit function specializations will always appear with
2259              global linkage.
2260
2261              The action recommended by the C++ CWG in response to C++
2262              defect report 605 is to make the storage class and linkage
2263              of the explicit specialization match the templated function:
2264
2265              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2266            */
2267           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2268             {
2269               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2270               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2271
2272               /* This specialization has the same linkage and visibility as
2273                  the function template it specializes.  */
2274               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2275               if (! TREE_PUBLIC (decl))
2276                 {
2277                   DECL_INTERFACE_KNOWN (decl) = 1;
2278                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2279                 }
2280               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2281               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2282                 {
2283                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2284                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2285                 }
2286             }
2287
2288           /* If DECL is a friend declaration, declared using an
2289              unqualified name, the namespace associated with DECL may
2290              have been set incorrectly.  For example, in:
2291
2292                template <typename T> void f(T);
2293                namespace N {
2294                  struct S { friend void f<int>(int); }
2295                }
2296
2297              we will have set the DECL_CONTEXT for the friend
2298              declaration to N, rather than to the global namespace.  */
2299           if (DECL_NAMESPACE_SCOPE_P (decl))
2300             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2301
2302           if (is_friend && !have_def)
2303             /* This is not really a declaration of a specialization.
2304                It's just the name of an instantiation.  But, it's not
2305                a request for an instantiation, either.  */
2306             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2307           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2308             /* This is indeed a specialization.  In case of constructors
2309                and destructors, we need in-charge and not-in-charge
2310                versions in V3 ABI.  */
2311             clone_function_decl (decl, /*update_method_vec_p=*/0);
2312
2313           /* Register this specialization so that we can find it
2314              again.  */
2315           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2316         }
2317     }
2318
2319   return decl;
2320 }
2321
2322 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2323    parameters.  These are represented in the same format used for
2324    DECL_TEMPLATE_PARMS.  */
2325
2326 int
2327 comp_template_parms (const_tree parms1, const_tree parms2)
2328 {
2329   const_tree p1;
2330   const_tree p2;
2331
2332   if (parms1 == parms2)
2333     return 1;
2334
2335   for (p1 = parms1, p2 = parms2;
2336        p1 != NULL_TREE && p2 != NULL_TREE;
2337        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2338     {
2339       tree t1 = TREE_VALUE (p1);
2340       tree t2 = TREE_VALUE (p2);
2341       int i;
2342
2343       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2344       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2345
2346       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2347         return 0;
2348
2349       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2350         {
2351           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2352           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2353
2354           /* If either of the template parameters are invalid, assume
2355              they match for the sake of error recovery. */
2356           if (parm1 == error_mark_node || parm2 == error_mark_node)
2357             return 1;
2358
2359           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2360             return 0;
2361
2362           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2363               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2364                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2365             continue;
2366           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2367             return 0;
2368         }
2369     }
2370
2371   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2372     /* One set of parameters has more parameters lists than the
2373        other.  */
2374     return 0;
2375
2376   return 1;
2377 }
2378
2379 /* Determine whether PARM is a parameter pack.  */
2380 bool 
2381 template_parameter_pack_p (const_tree parm)
2382 {
2383   /* Determine if we have a non-type template parameter pack.  */
2384   if (TREE_CODE (parm) == PARM_DECL)
2385     return (DECL_TEMPLATE_PARM_P (parm) 
2386             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2387
2388   /* If this is a list of template parameters, we could get a
2389      TYPE_DECL or a TEMPLATE_DECL.  */ 
2390   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2391     parm = TREE_TYPE (parm);
2392
2393   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2394            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2395           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2396 }
2397
2398 /* Determine whether ARGS describes a variadic template args list,
2399    i.e., one that is terminated by a template argument pack.  */
2400 static bool 
2401 template_args_variadic_p (tree args)
2402 {
2403   int nargs;
2404   tree last_parm;
2405
2406   if (args == NULL_TREE)
2407     return false;
2408
2409   args = INNERMOST_TEMPLATE_ARGS (args);
2410   nargs = TREE_VEC_LENGTH (args);
2411
2412   if (nargs == 0)
2413     return false;
2414
2415   last_parm = TREE_VEC_ELT (args, nargs - 1);
2416
2417   return ARGUMENT_PACK_P (last_parm);
2418 }
2419
2420 /* Generate a new name for the parameter pack name NAME (an
2421    IDENTIFIER_NODE) that incorporates its */
2422 static tree
2423 make_ith_pack_parameter_name (tree name, int i)
2424 {
2425   /* Munge the name to include the parameter index.  */
2426   char numbuf[128];
2427   char* newname;
2428   
2429   sprintf(numbuf, "%i", i);
2430   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2431   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2432   return get_identifier (newname);
2433 }
2434
2435 /* Structure used to track the progress of find_parameter_packs_r.  */
2436 struct find_parameter_pack_data 
2437 {
2438   /* TREE_LIST that will contain all of the parameter packs found by
2439      the traversal.  */
2440   tree* parameter_packs;
2441
2442   /* Set of AST nodes that have been visited by the traversal.  */
2443   struct pointer_set_t *visited;
2444 };
2445
2446 /* Identifies all of the argument packs that occur in a template
2447    argument and appends them to the TREE_LIST inside DATA, which is a
2448    find_parameter_pack_data structure. This is a subroutine of
2449    make_pack_expansion and uses_parameter_packs.  */
2450 static tree
2451 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2452 {
2453   tree t = *tp;
2454   struct find_parameter_pack_data* ppd = 
2455     (struct find_parameter_pack_data*)data;
2456   bool parameter_pack_p = false;
2457
2458   /* Identify whether this is a parameter pack or not.  */
2459   switch (TREE_CODE (t))
2460     {
2461     case TEMPLATE_PARM_INDEX:
2462       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2463         parameter_pack_p = true;
2464       break;
2465
2466     case TEMPLATE_TYPE_PARM:
2467     case TEMPLATE_TEMPLATE_PARM:
2468       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2469         parameter_pack_p = true;
2470       break;
2471
2472     case PARM_DECL:
2473       if (FUNCTION_PARAMETER_PACK_P (t))
2474         {
2475           /* We don't want to walk into the type of a PARM_DECL,
2476              because we don't want to see the type parameter pack.  */
2477           *walk_subtrees = 0;
2478           parameter_pack_p = true;
2479         }
2480       break;
2481
2482     default:
2483       /* Not a parameter pack.  */
2484       break;
2485     }
2486
2487   if (parameter_pack_p)
2488     {
2489       /* Add this parameter pack to the list.  */
2490       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2491     }
2492
2493   if (TYPE_P (t))
2494     cp_walk_tree (&TYPE_CONTEXT (t), 
2495                   &find_parameter_packs_r, ppd, ppd->visited);
2496
2497   /* This switch statement will return immediately if we don't find a
2498      parameter pack.  */
2499   switch (TREE_CODE (t)) 
2500     {
2501     case TEMPLATE_PARM_INDEX:
2502       return NULL_TREE;
2503
2504     case BOUND_TEMPLATE_TEMPLATE_PARM:
2505       /* Check the template itself.  */
2506       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2507                     &find_parameter_packs_r, ppd, ppd->visited);
2508       /* Check the template arguments.  */
2509       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2510                     ppd->visited);
2511       *walk_subtrees = 0;
2512       return NULL_TREE;
2513
2514     case TEMPLATE_TYPE_PARM:
2515     case TEMPLATE_TEMPLATE_PARM:
2516       return NULL_TREE;
2517
2518     case PARM_DECL:
2519       return NULL_TREE;
2520
2521     case RECORD_TYPE:
2522       if (TYPE_PTRMEMFUNC_P (t))
2523         return NULL_TREE;
2524       /* Fall through.  */
2525
2526     case UNION_TYPE:
2527     case ENUMERAL_TYPE:
2528       if (TYPE_TEMPLATE_INFO (t))
2529         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2530                       &find_parameter_packs_r, ppd, ppd->visited);
2531
2532       *walk_subtrees = 0;
2533       return NULL_TREE;
2534
2535     case TEMPLATE_DECL:
2536       cp_walk_tree (&TREE_TYPE (t),
2537                     &find_parameter_packs_r, ppd, ppd->visited);
2538       return NULL_TREE;
2539  
2540     case TYPENAME_TYPE:
2541       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2542                    ppd, ppd->visited);
2543       *walk_subtrees = 0;
2544       return NULL_TREE;
2545       
2546     case TYPE_PACK_EXPANSION:
2547     case EXPR_PACK_EXPANSION:
2548       *walk_subtrees = 0;
2549       return NULL_TREE;
2550
2551     case INTEGER_TYPE:
2552       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2553                     ppd, ppd->visited);
2554       *walk_subtrees = 0;
2555       return NULL_TREE;
2556
2557     case IDENTIFIER_NODE:
2558       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2559                     ppd->visited);
2560       *walk_subtrees = 0;
2561       return NULL_TREE;
2562
2563     default:
2564       return NULL_TREE;
2565     }
2566
2567   return NULL_TREE;
2568 }
2569
2570 /* Determines if the expression or type T uses any parameter packs.  */
2571 bool
2572 uses_parameter_packs (tree t)
2573 {
2574   tree parameter_packs = NULL_TREE;
2575   struct find_parameter_pack_data ppd;
2576   ppd.parameter_packs = &parameter_packs;
2577   ppd.visited = pointer_set_create ();
2578   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2579   pointer_set_destroy (ppd.visited);
2580   return parameter_packs != NULL_TREE;
2581 }
2582
2583 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2584    representation a base-class initializer into a parameter pack
2585    expansion. If all goes well, the resulting node will be an
2586    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2587    respectively.  */
2588 tree 
2589 make_pack_expansion (tree arg)
2590 {
2591   tree result;
2592   tree parameter_packs = NULL_TREE;
2593   bool for_types = false;
2594   struct find_parameter_pack_data ppd;
2595
2596   if (!arg || arg == error_mark_node)
2597     return arg;
2598
2599   if (TREE_CODE (arg) == TREE_LIST)
2600     {
2601       /* The only time we will see a TREE_LIST here is for a base
2602          class initializer.  In this case, the TREE_PURPOSE will be a
2603          _TYPE node (representing the base class expansion we're
2604          initializing) and the TREE_VALUE will be a TREE_LIST
2605          containing the initialization arguments. 
2606
2607          The resulting expansion looks somewhat different from most
2608          expansions. Rather than returning just one _EXPANSION, we
2609          return a TREE_LIST whose TREE_PURPOSE is a
2610          TYPE_PACK_EXPANSION containing the bases that will be
2611          initialized.  The TREE_VALUE will be identical to the
2612          original TREE_VALUE, which is a list of arguments that will
2613          be passed to each base.  We do not introduce any new pack
2614          expansion nodes into the TREE_VALUE (although it is possible
2615          that some already exist), because the TREE_PURPOSE and
2616          TREE_VALUE all need to be expanded together with the same
2617          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2618          resulting TREE_PURPOSE will mention the parameter packs in
2619          both the bases and the arguments to the bases.  */
2620       tree purpose;
2621       tree value;
2622       tree parameter_packs = NULL_TREE;
2623
2624       /* Determine which parameter packs will be used by the base
2625          class expansion.  */
2626       ppd.visited = pointer_set_create ();
2627       ppd.parameter_packs = &parameter_packs;
2628       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2629                     &ppd, ppd.visited);
2630
2631       if (parameter_packs == NULL_TREE)
2632         {
2633           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2634           pointer_set_destroy (ppd.visited);
2635           return error_mark_node;
2636         }
2637
2638       if (TREE_VALUE (arg) != void_type_node)
2639         {
2640           /* Collect the sets of parameter packs used in each of the
2641              initialization arguments.  */
2642           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2643             {
2644               /* Determine which parameter packs will be expanded in this
2645                  argument.  */
2646               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2647                             &ppd, ppd.visited);
2648             }
2649         }
2650
2651       pointer_set_destroy (ppd.visited);
2652
2653       /* Create the pack expansion type for the base type.  */
2654       purpose = make_node (TYPE_PACK_EXPANSION);
2655       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2656       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2657
2658       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2659          they will rarely be compared to anything.  */
2660       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2661
2662       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2663     }
2664
2665   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2666     for_types = true;
2667
2668   /* Build the PACK_EXPANSION_* node.  */
2669   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2670   SET_PACK_EXPANSION_PATTERN (result, arg);
2671   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2672     {
2673       /* Propagate type and const-expression information.  */
2674       TREE_TYPE (result) = TREE_TYPE (arg);
2675       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2676     }
2677   else
2678     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2679        they will rarely be compared to anything.  */
2680     SET_TYPE_STRUCTURAL_EQUALITY (result);
2681
2682   /* Determine which parameter packs will be expanded.  */
2683   ppd.parameter_packs = &parameter_packs;
2684   ppd.visited = pointer_set_create ();
2685   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2686   pointer_set_destroy (ppd.visited);
2687
2688   /* Make sure we found some parameter packs.  */
2689   if (parameter_packs == NULL_TREE)
2690     {
2691       if (TYPE_P (arg))
2692         error ("expansion pattern %<%T%> contains no argument packs", arg);
2693       else
2694         error ("expansion pattern %<%E%> contains no argument packs", arg);
2695       return error_mark_node;
2696     }
2697   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2698
2699   return result;
2700 }
2701
2702 /* Checks T for any "bare" parameter packs, which have not yet been
2703    expanded, and issues an error if any are found. This operation can
2704    only be done on full expressions or types (e.g., an expression
2705    statement, "if" condition, etc.), because we could have expressions like:
2706
2707      foo(f(g(h(args)))...)
2708
2709    where "args" is a parameter pack. check_for_bare_parameter_packs
2710    should not be called for the subexpressions args, h(args),
2711    g(h(args)), or f(g(h(args))), because we would produce erroneous
2712    error messages. 
2713
2714    Returns TRUE and emits an error if there were bare parameter packs,
2715    returns FALSE otherwise.  */
2716 bool 
2717 check_for_bare_parameter_packs (tree t)
2718 {
2719   tree parameter_packs = NULL_TREE;
2720   struct find_parameter_pack_data ppd;
2721
2722   if (!processing_template_decl || !t || t == error_mark_node)
2723     return false;
2724
2725   if (TREE_CODE (t) == TYPE_DECL)
2726     t = TREE_TYPE (t);
2727
2728   ppd.parameter_packs = &parameter_packs;
2729   ppd.visited = pointer_set_create ();
2730   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2731   pointer_set_destroy (ppd.visited);
2732
2733   if (parameter_packs) 
2734     {
2735       error ("parameter packs not expanded with %<...%>:");
2736       while (parameter_packs)
2737         {
2738           tree pack = TREE_VALUE (parameter_packs);
2739           tree name = NULL_TREE;
2740
2741           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2742               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2743             name = TYPE_NAME (pack);
2744           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2745             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2746           else
2747             name = DECL_NAME (pack);
2748
2749           if (name)
2750             inform (input_location, "        %qD", name);
2751           else
2752             inform (input_location, "        <anonymous>");
2753
2754           parameter_packs = TREE_CHAIN (parameter_packs);
2755         }
2756
2757       return true;
2758     }
2759
2760   return false;
2761 }
2762
2763 /* Expand any parameter packs that occur in the template arguments in
2764    ARGS.  */
2765 tree
2766 expand_template_argument_pack (tree args)
2767 {
2768   tree result_args = NULL_TREE;
2769   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2770   int num_result_args = -1;
2771
2772   /* First, determine if we need to expand anything, and the number of
2773      slots we'll need.  */
2774   for (in_arg = 0; in_arg < nargs; ++in_arg)
2775     {
2776       tree arg = TREE_VEC_ELT (args, in_arg);
2777       if (ARGUMENT_PACK_P (arg))
2778         {
2779           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2780           if (num_result_args < 0)
2781             num_result_args = in_arg + num_packed;
2782           else
2783             num_result_args += num_packed;
2784         }
2785       else
2786         {
2787           if (num_result_args >= 0)
2788             num_result_args++;
2789         }
2790     }
2791
2792   /* If no expansion is necessary, we're done.  */
2793   if (num_result_args < 0)
2794     return args;
2795
2796   /* Expand arguments.  */
2797   result_args = make_tree_vec (num_result_args);
2798   for (in_arg = 0; in_arg < nargs; ++in_arg)
2799     {
2800       tree arg = TREE_VEC_ELT (args, in_arg);
2801       if (ARGUMENT_PACK_P (arg))
2802         {
2803           tree packed = ARGUMENT_PACK_ARGS (arg);
2804           int i, num_packed = TREE_VEC_LENGTH (packed);
2805           for (i = 0; i < num_packed; ++i, ++out_arg)
2806             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2807         }
2808       else
2809         {
2810           TREE_VEC_ELT (result_args, out_arg) = arg;
2811           ++out_arg;
2812         }
2813     }
2814
2815   return result_args;
2816 }
2817
2818 /* Checks if DECL shadows a template parameter.
2819
2820    [temp.local]: A template-parameter shall not be redeclared within its
2821    scope (including nested scopes).
2822
2823    Emits an error and returns TRUE if the DECL shadows a parameter,
2824    returns FALSE otherwise.  */
2825
2826 bool
2827 check_template_shadow (tree decl)
2828 {
2829   tree olddecl;
2830
2831   /* If we're not in a template, we can't possibly shadow a template
2832      parameter.  */
2833   if (!current_template_parms)
2834     return true;
2835
2836   /* Figure out what we're shadowing.  */
2837   if (TREE_CODE (decl) == OVERLOAD)
2838     decl = OVL_CURRENT (decl);
2839   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2840
2841   /* If there's no previous binding for this name, we're not shadowing
2842      anything, let alone a template parameter.  */
2843   if (!olddecl)
2844     return true;
2845
2846   /* If we're not shadowing a template parameter, we're done.  Note
2847      that OLDDECL might be an OVERLOAD (or perhaps even an
2848      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2849      node.  */
2850   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2851     return true;
2852
2853   /* We check for decl != olddecl to avoid bogus errors for using a
2854      name inside a class.  We check TPFI to avoid duplicate errors for
2855      inline member templates.  */
2856   if (decl == olddecl
2857       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2858     return true;
2859
2860   error ("declaration of %q+#D", decl);
2861   error (" shadows template parm %q+#D", olddecl);
2862   return false;
2863 }
2864
2865 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2866    ORIG_LEVEL, DECL, and TYPE.  */
2867
2868 static tree
2869 build_template_parm_index (int index,
2870                            int level,
2871                            int orig_level,
2872                            tree decl,
2873                            tree type)
2874 {
2875   tree t = make_node (TEMPLATE_PARM_INDEX);
2876   TEMPLATE_PARM_IDX (t) = index;
2877   TEMPLATE_PARM_LEVEL (t) = level;
2878   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2879   TEMPLATE_PARM_DECL (t) = decl;
2880   TREE_TYPE (t) = type;
2881   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2882   TREE_READONLY (t) = TREE_READONLY (decl);
2883
2884   return t;
2885 }
2886
2887 /* Find the canonical type parameter for the given template type
2888    parameter.  Returns the canonical type parameter, which may be TYPE
2889    if no such parameter existed.  */
2890 static tree
2891 canonical_type_parameter (tree type)
2892 {
2893   tree list;
2894   int idx = TEMPLATE_TYPE_IDX (type);
2895   if (!canonical_template_parms)
2896     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2897
2898   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2899     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2900
2901   list = VEC_index (tree, canonical_template_parms, idx);
2902   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2903     list = TREE_CHAIN (list);
2904
2905   if (list)
2906     return TREE_VALUE (list);
2907   else
2908     {
2909       VEC_replace(tree, canonical_template_parms, idx,
2910                   tree_cons (NULL_TREE, type, 
2911                              VEC_index (tree, canonical_template_parms, idx)));
2912       return type;
2913     }
2914 }
2915
2916 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2917    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2918    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2919    new one is created.  */
2920
2921 static tree
2922 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2923                             tsubst_flags_t complain)
2924 {
2925   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2926       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2927           != TEMPLATE_PARM_LEVEL (index) - levels))
2928     {
2929       tree orig_decl = TEMPLATE_PARM_DECL (index);
2930       tree decl, t;
2931
2932       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2933       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2934       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2935       DECL_ARTIFICIAL (decl) = 1;
2936       SET_DECL_TEMPLATE_PARM_P (decl);
2937
2938       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2939                                      TEMPLATE_PARM_LEVEL (index) - levels,
2940                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2941                                      decl, type);
2942       TEMPLATE_PARM_DESCENDANTS (index) = t;
2943       TEMPLATE_PARM_PARAMETER_PACK (t) 
2944         = TEMPLATE_PARM_PARAMETER_PACK (index);
2945
2946         /* Template template parameters need this.  */
2947       if (TREE_CODE (decl) == TEMPLATE_DECL)
2948         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2949           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2950            args, complain);
2951     }
2952
2953   return TEMPLATE_PARM_DESCENDANTS (index);
2954 }
2955
2956 /* Process information from new template parameter PARM and append it to the
2957    LIST being built.  This new parameter is a non-type parameter iff
2958    IS_NON_TYPE is true. This new parameter is a parameter
2959    pack iff IS_PARAMETER_PACK is true.  */
2960
2961 tree
2962 process_template_parm (tree list, tree parm, bool is_non_type, 
2963                        bool is_parameter_pack)
2964 {
2965   tree decl = 0;
2966   tree defval;
2967   tree err_parm_list;
2968   int idx = 0;
2969
2970   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2971   defval = TREE_PURPOSE (parm);
2972
2973   if (list)
2974     {
2975       tree p = tree_last (list);
2976
2977       if (p && TREE_VALUE (p) != error_mark_node)
2978         {
2979           p = TREE_VALUE (p);
2980           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2981             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2982           else
2983             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2984         }
2985
2986       ++idx;
2987     }
2988   else
2989     idx = 0;
2990
2991   if (is_non_type)
2992     {
2993       parm = TREE_VALUE (parm);
2994
2995       SET_DECL_TEMPLATE_PARM_P (parm);
2996
2997       if (TREE_TYPE (parm) == error_mark_node)
2998         {
2999           err_parm_list = build_tree_list (defval, parm);
3000           TREE_VALUE (err_parm_list) = error_mark_node;
3001            return chainon (list, err_parm_list);
3002         }
3003       else
3004       {
3005         /* [temp.param]
3006
3007            The top-level cv-qualifiers on the template-parameter are
3008            ignored when determining its type.  */
3009         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3010         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3011           {
3012             err_parm_list = build_tree_list (defval, parm);
3013             TREE_VALUE (err_parm_list) = error_mark_node;
3014              return chainon (list, err_parm_list);
3015           }
3016
3017         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3018           {
3019             /* This template parameter is not a parameter pack, but it
3020                should be. Complain about "bare" parameter packs.  */
3021             check_for_bare_parameter_packs (TREE_TYPE (parm));
3022             
3023             /* Recover by calling this a parameter pack.  */
3024             is_parameter_pack = true;
3025           }
3026       }
3027
3028       /* A template parameter is not modifiable.  */
3029       TREE_CONSTANT (parm) = 1;
3030       TREE_READONLY (parm) = 1;
3031       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3032       TREE_CONSTANT (decl) = 1;
3033       TREE_READONLY (decl) = 1;
3034       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3035         = build_template_parm_index (idx, processing_template_decl,
3036                                      processing_template_decl,
3037                                      decl, TREE_TYPE (parm));
3038
3039       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3040         = is_parameter_pack;
3041     }
3042   else
3043     {
3044       tree t;
3045       parm = TREE_VALUE (TREE_VALUE (parm));
3046
3047       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3048         {
3049           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3050           /* This is for distinguishing between real templates and template
3051              template parameters */
3052           TREE_TYPE (parm) = t;
3053           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3054           decl = parm;
3055         }
3056       else
3057         {
3058           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3059           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3060           decl = build_decl (TYPE_DECL, parm, t);
3061         }
3062
3063       TYPE_NAME (t) = decl;
3064       TYPE_STUB_DECL (t) = decl;
3065       parm = decl;
3066       TEMPLATE_TYPE_PARM_INDEX (t)
3067         = build_template_parm_index (idx, processing_template_decl,
3068                                      processing_template_decl,
3069                                      decl, TREE_TYPE (parm));
3070       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3071       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3072     }
3073   DECL_ARTIFICIAL (decl) = 1;
3074   SET_DECL_TEMPLATE_PARM_P (decl);
3075   pushdecl (decl);
3076   parm = build_tree_list (defval, parm);
3077   return chainon (list, parm);
3078 }
3079
3080 /* The end of a template parameter list has been reached.  Process the
3081    tree list into a parameter vector, converting each parameter into a more
3082    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3083    as PARM_DECLs.  */
3084
3085 tree
3086 end_template_parm_list (tree parms)
3087 {
3088   int nparms;
3089   tree parm, next;
3090   tree saved_parmlist = make_tree_vec (list_length (parms));
3091
3092   current_template_parms
3093     = tree_cons (size_int (processing_template_decl),
3094                  saved_parmlist, current_template_parms);
3095
3096   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3097     {
3098       next = TREE_CHAIN (parm);
3099       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3100       TREE_CHAIN (parm) = NULL_TREE;
3101     }
3102
3103   --processing_template_parmlist;
3104
3105   return saved_parmlist;
3106 }
3107
3108 /* end_template_decl is called after a template declaration is seen.  */
3109
3110 void
3111 end_template_decl (void)
3112 {
3113   reset_specialization ();
3114
3115   if (! processing_template_decl)
3116     return;
3117
3118   /* This matches the pushlevel in begin_template_parm_list.  */
3119   finish_scope ();
3120
3121   --processing_template_decl;
3122   current_template_parms = TREE_CHAIN (current_template_parms);
3123 }
3124
3125 /* Within the declaration of a template, return all levels of template
3126    parameters that apply.  The template parameters are represented as
3127    a TREE_VEC, in the form documented in cp-tree.h for template
3128    arguments.  */
3129
3130 static tree
3131 current_template_args (void)
3132 {
3133   tree header;
3134   tree args = NULL_TREE;
3135   int length = TMPL_PARMS_DEPTH (current_template_parms);
3136   int l = length;
3137
3138   /* If there is only one level of template parameters, we do not
3139      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3140      TREE_VEC containing the arguments.  */
3141   if (length > 1)
3142     args = make_tree_vec (length);
3143
3144   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3145     {
3146       tree a = copy_node (TREE_VALUE (header));
3147       int i;
3148
3149       TREE_TYPE (a) = NULL_TREE;
3150       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3151         {
3152           tree t = TREE_VEC_ELT (a, i);
3153
3154           /* T will be a list if we are called from within a
3155              begin/end_template_parm_list pair, but a vector directly
3156              if within a begin/end_member_template_processing pair.  */
3157           if (TREE_CODE (t) == TREE_LIST)
3158             {
3159               t = TREE_VALUE (t);
3160
3161               if (!error_operand_p (t))
3162                 {
3163                   if (TREE_CODE (t) == TYPE_DECL
3164                       || TREE_CODE (t) == TEMPLATE_DECL)
3165                     {
3166                       t = TREE_TYPE (t);
3167                       
3168                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3169                         {
3170                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3171                              with a single element, which expands T.  */
3172                           tree vec = make_tree_vec (1);
3173                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3174                           
3175                           t = make_node (TYPE_ARGUMENT_PACK);
3176                           SET_ARGUMENT_PACK_ARGS (t, vec);
3177                         }
3178                     }
3179                   else
3180                     {
3181                       t = DECL_INITIAL (t);
3182                       
3183                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3184                         {
3185                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3186                              with a single element, which expands T.  */
3187                           tree vec = make_tree_vec (1);
3188                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3189                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3190                           
3191                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3192                           SET_ARGUMENT_PACK_ARGS (t, vec);
3193                           TREE_TYPE (t) = type;
3194                         }
3195                     }
3196                   TREE_VEC_ELT (a, i) = t;
3197                 }
3198             }
3199         }
3200
3201       if (length > 1)
3202         TREE_VEC_ELT (args, --l) = a;
3203       else
3204         args = a;
3205     }
3206
3207   return args;
3208 }
3209
3210 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3211    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3212    a member template.  Used by push_template_decl below.  */
3213
3214 static tree
3215 build_template_decl (tree decl, tree parms, bool member_template_p)
3216 {
3217   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3218   DECL_TEMPLATE_PARMS (tmpl) = parms;
3219   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3220   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3221   if (DECL_LANG_SPECIFIC (decl))
3222     {
3223       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3224       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3225       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3226       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3227       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3228       if (DECL_OVERLOADED_OPERATOR_P (decl))
3229         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3230                                       DECL_OVERLOADED_OPERATOR_P (decl));
3231     }
3232
3233   return tmpl;
3234 }
3235
3236 struct template_parm_data
3237 {
3238   /* The level of the template parameters we are currently
3239      processing.  */
3240   int level;
3241
3242   /* The index of the specialization argument we are currently
3243      processing.  */
3244   int current_arg;
3245
3246   /* An array whose size is the number of template parameters.  The
3247      elements are nonzero if the parameter has been used in any one
3248      of the arguments processed so far.  */
3249   int* parms;
3250
3251   /* An array whose size is the number of template arguments.  The
3252      elements are nonzero if the argument makes use of template
3253      parameters of this level.  */
3254   int* arg_uses_template_parms;
3255 };
3256
3257 /* Subroutine of push_template_decl used to see if each template
3258    parameter in a partial specialization is used in the explicit
3259    argument list.  If T is of the LEVEL given in DATA (which is
3260    treated as a template_parm_data*), then DATA->PARMS is marked
3261    appropriately.  */
3262
3263 static int
3264 mark_template_parm (tree t, void* data)
3265 {
3266   int level;
3267   int idx;
3268   struct template_parm_data* tpd = (struct template_parm_data*) data;
3269
3270   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3271     {
3272       level = TEMPLATE_PARM_LEVEL (t);
3273       idx = TEMPLATE_PARM_IDX (t);
3274     }
3275   else
3276     {
3277       level = TEMPLATE_TYPE_LEVEL (t);
3278       idx = TEMPLATE_TYPE_IDX (t);
3279     }
3280
3281   if (level == tpd->level)
3282     {
3283       tpd->parms[idx] = 1;
3284       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3285     }
3286
3287   /* Return zero so that for_each_template_parm will continue the
3288      traversal of the tree; we want to mark *every* template parm.  */
3289   return 0;
3290 }
3291
3292 /* Process the partial specialization DECL.  */
3293
3294 static tree
3295 process_partial_specialization (tree decl)
3296 {
3297   tree type = TREE_TYPE (decl);
3298   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3299   tree specargs = CLASSTYPE_TI_ARGS (type);
3300   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3301   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3302   tree inner_parms;
3303   int nargs = TREE_VEC_LENGTH (inner_args);
3304   int ntparms;
3305   int  i;
3306   int did_error_intro = 0;
3307   struct template_parm_data tpd;
3308   struct template_parm_data tpd2;
3309
3310   gcc_assert (current_template_parms);
3311
3312   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3313   ntparms = TREE_VEC_LENGTH (inner_parms);
3314
3315   /* We check that each of the template parameters given in the
3316      partial specialization is used in the argument list to the
3317      specialization.  For example:
3318
3319        template <class T> struct S;
3320        template <class T> struct S<T*>;
3321
3322      The second declaration is OK because `T*' uses the template
3323      parameter T, whereas
3324
3325        template <class T> struct S<int>;
3326
3327      is no good.  Even trickier is:
3328
3329        template <class T>
3330        struct S1
3331        {
3332           template <class U>
3333           struct S2;
3334           template <class U>
3335           struct S2<T>;
3336        };
3337
3338      The S2<T> declaration is actually invalid; it is a
3339      full-specialization.  Of course,
3340
3341           template <class U>
3342           struct S2<T (*)(U)>;
3343
3344      or some such would have been OK.  */
3345   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3346   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3347   memset (tpd.parms, 0, sizeof (int) * ntparms);
3348
3349   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3350   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3351   for (i = 0; i < nargs; ++i)
3352     {
3353       tpd.current_arg = i;
3354       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3355                               &mark_template_parm,
3356                               &tpd,
3357                               NULL,
3358                               /*include_nondeduced_p=*/false);
3359     }
3360   for (i = 0; i < ntparms; ++i)
3361     if (tpd.parms[i] == 0)
3362       {
3363         /* One of the template parms was not used in the
3364            specialization.  */
3365         if (!did_error_intro)
3366           {
3367             error ("template parameters not used in partial specialization:");
3368             did_error_intro = 1;
3369           }
3370
3371         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3372       }
3373
3374   /* [temp.class.spec]
3375
3376      The argument list of the specialization shall not be identical to
3377      the implicit argument list of the primary template.  */
3378   if (comp_template_args
3379       (inner_args,
3380        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3381                                                    (maintmpl)))))
3382     error ("partial specialization %qT does not specialize any template arguments", type);
3383
3384   /* [temp.class.spec]
3385
3386      A partially specialized non-type argument expression shall not
3387      involve template parameters of the partial specialization except
3388      when the argument expression is a simple identifier.
3389
3390      The type of a template parameter corresponding to a specialized
3391      non-type argument shall not be dependent on a parameter of the
3392      specialization. 
3393
3394      Also, we verify that pack expansions only occur at the
3395      end of the argument list.  */
3396   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3397   tpd2.parms = 0;
3398   for (i = 0; i < nargs; ++i)
3399     {
3400       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3401       tree arg = TREE_VEC_ELT (inner_args, i);
3402       tree packed_args = NULL_TREE;
3403       int j, len = 1;
3404
3405       if (ARGUMENT_PACK_P (arg))
3406         {
3407           /* Extract the arguments from the argument pack. We'll be
3408              iterating over these in the following loop.  */
3409           packed_args = ARGUMENT_PACK_ARGS (arg);
3410           len = TREE_VEC_LENGTH (packed_args);
3411         }
3412
3413       for (j = 0; j < len; j++)
3414         {
3415           if (packed_args)
3416             /* Get the Jth argument in the parameter pack.  */
3417             arg = TREE_VEC_ELT (packed_args, j);
3418
3419           if (PACK_EXPANSION_P (arg))
3420             {
3421               /* Pack expansions must come at the end of the
3422                  argument list.  */
3423               if ((packed_args && j < len - 1)
3424                   || (!packed_args && i < nargs - 1))
3425                 {
3426                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3427                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3428                   else
3429                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3430
3431                   if (packed_args)
3432                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3433                 }
3434             }
3435
3436           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3437             /* We only care about the pattern.  */
3438             arg = PACK_EXPANSION_PATTERN (arg);
3439
3440           if (/* These first two lines are the `non-type' bit.  */
3441               !TYPE_P (arg)
3442               && TREE_CODE (arg) != TEMPLATE_DECL
3443               /* This next line is the `argument expression is not just a
3444                  simple identifier' condition and also the `specialized
3445                  non-type argument' bit.  */
3446               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3447             {
3448               if ((!packed_args && tpd.arg_uses_template_parms[i])
3449                   || (packed_args && uses_template_parms (arg)))
3450                 error ("template argument %qE involves template parameter(s)",
3451                        arg);
3452               else 
3453                 {
3454                   /* Look at the corresponding template parameter,
3455                      marking which template parameters its type depends
3456                      upon.  */
3457                   tree type = TREE_TYPE (parm);
3458
3459                   if (!tpd2.parms)
3460                     {
3461                       /* We haven't yet initialized TPD2.  Do so now.  */
3462                       tpd2.arg_uses_template_parms 
3463                         = (int *) alloca (sizeof (int) * nargs);
3464                       /* The number of parameters here is the number in the
3465                          main template, which, as checked in the assertion
3466                          above, is NARGS.  */
3467                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3468                       tpd2.level = 
3469                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3470                     }
3471
3472                   /* Mark the template parameters.  But this time, we're
3473                      looking for the template parameters of the main
3474                      template, not in the specialization.  */
3475                   tpd2.current_arg = i;
3476                   tpd2.arg_uses_template_parms[i] = 0;
3477                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3478                   for_each_template_parm (type,
3479                                           &mark_template_parm,
3480                                           &tpd2,
3481                                           NULL,
3482                                           /*include_nondeduced_p=*/false);
3483
3484                   if (tpd2.arg_uses_template_parms [i])
3485                     {
3486                       /* The type depended on some template parameters.
3487                          If they are fully specialized in the
3488                          specialization, that's OK.  */
3489                       int j;
3490                       for (j = 0; j < nargs; ++j)
3491                         if (tpd2.parms[j] != 0
3492                             && tpd.arg_uses_template_parms [j])
3493                           {
3494                             error ("type %qT of template argument %qE depends "
3495                                    "on template parameter(s)", 
3496                                    type,
3497                                    arg);
3498                             break;
3499                           }
3500                     }
3501                 }
3502             }
3503         }
3504     }
3505
3506   if (retrieve_specialization (maintmpl, specargs,
3507                                /*class_specializations_p=*/true))
3508     /* We've already got this specialization.  */
3509     return decl;
3510
3511   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3512     = tree_cons (specargs, inner_parms,
3513                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3514   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3515   return decl;
3516 }
3517
3518 /* Check that a template declaration's use of default arguments and
3519    parameter packs is not invalid.  Here, PARMS are the template
3520    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3521    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3522    specialization.
3523    
3524
3525    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3526    declaration (but not a definition); 1 indicates a declaration, 2
3527    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3528    emitted for extraneous default arguments.
3529
3530    Returns TRUE if there were no errors found, FALSE otherwise. */
3531
3532 bool
3533 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3534                          int is_partial, int is_friend_decl)
3535 {
3536   const char *msg;
3537   int last_level_to_check;
3538   tree parm_level;
3539   bool no_errors = true;
3540
3541   /* [temp.param]
3542
3543      A default template-argument shall not be specified in a
3544      function template declaration or a function template definition, nor
3545      in the template-parameter-list of the definition of a member of a
3546      class template.  */
3547
3548   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3549     /* You can't have a function template declaration in a local
3550        scope, nor you can you define a member of a class template in a
3551        local scope.  */
3552     return true;
3553
3554   if (current_class_type
3555       && !TYPE_BEING_DEFINED (current_class_type)
3556       && DECL_LANG_SPECIFIC (decl)
3557       /* If this is either a friend defined in the scope of the class
3558          or a member function.  */
3559       && (DECL_FUNCTION_MEMBER_P (decl)
3560           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3561           : DECL_FRIEND_CONTEXT (decl)
3562           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3563           : false)
3564       /* And, if it was a member function, it really was defined in
3565          the scope of the class.  */
3566       && (!DECL_FUNCTION_MEMBER_P (decl)
3567           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3568     /* We already checked these parameters when the template was
3569        declared, so there's no need to do it again now.  This function
3570        was defined in class scope, but we're processing it's body now
3571        that the class is complete.  */
3572     return true;
3573
3574   /* Core issue 226 (C++0x only): the following only applies to class
3575      templates.  */
3576   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3577     {
3578       /* [temp.param]
3579
3580          If a template-parameter has a default template-argument, all
3581          subsequent template-parameters shall have a default
3582          template-argument supplied.  */
3583       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3584         {
3585           tree inner_parms = TREE_VALUE (parm_level);
3586           int ntparms = TREE_VEC_LENGTH (inner_parms);
3587           int seen_def_arg_p = 0;
3588           int i;
3589
3590           for (i = 0; i < ntparms; ++i)
3591             {
3592               tree parm = TREE_VEC_ELT (inner_parms, i);
3593
3594               if (parm == error_mark_node)
3595                 continue;
3596
3597               if (TREE_PURPOSE (parm))
3598                 seen_def_arg_p = 1;
3599               else if (seen_def_arg_p
3600                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3601                 {
3602                   error ("no default argument for %qD", TREE_VALUE (parm));
3603                   /* For better subsequent error-recovery, we indicate that
3604                      there should have been a default argument.  */
3605                   TREE_PURPOSE (parm) = error_mark_node;
3606                   no_errors = false;
3607                 }
3608               else if (is_primary
3609                        && !is_partial
3610                        && !is_friend_decl
3611                        /* Don't complain about an enclosing partial
3612                           specialization.  */
3613                        && parm_level == parms
3614                        && TREE_CODE (decl) == TYPE_DECL
3615                        && i < ntparms - 1
3616                        && template_parameter_pack_p (TREE_VALUE (parm)))
3617                 {
3618                   /* A primary class template can only have one
3619                      parameter pack, at the end of the template
3620                      parameter list.  */
3621
3622                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3623                     error ("parameter pack %qE must be at the end of the"
3624                            " template parameter list", TREE_VALUE (parm));
3625                   else
3626                     error ("parameter pack %qT must be at the end of the"
3627                            " template parameter list", 
3628                            TREE_TYPE (TREE_VALUE (parm)));
3629
3630                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3631                     = error_mark_node;
3632                   no_errors = false;
3633                 }
3634             }
3635         }
3636     }
3637
3638   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3639       || is_partial 
3640       || !is_primary
3641       || is_friend_decl)
3642     /* For an ordinary class template, default template arguments are
3643        allowed at the innermost level, e.g.:
3644          template <class T = int>
3645          struct S {};
3646        but, in a partial specialization, they're not allowed even
3647        there, as we have in [temp.class.spec]:
3648
3649          The template parameter list of a specialization shall not
3650          contain default template argument values.
3651
3652        So, for a partial specialization, or for a function template
3653        (in C++98/C++03), we look at all of them.  */
3654     ;
3655   else
3656     /* But, for a primary class template that is not a partial
3657        specialization we look at all template parameters except the
3658        innermost ones.  */
3659     parms = TREE_CHAIN (parms);
3660
3661   /* Figure out what error message to issue.  */
3662   if (is_friend_decl == 2)
3663     msg = "default template arguments may not be used in function template friend re-declaration";
3664   else if (is_friend_decl)
3665     msg = "default template arguments may not be used in function template friend declarations";
3666   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3667     msg = "default template arguments may not be used in function templates";
3668   else if (is_partial)
3669     msg = "default template arguments may not be used in partial specializations";
3670   else
3671     msg = "default argument for template parameter for class enclosing %qD";
3672
3673   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3674     /* If we're inside a class definition, there's no need to
3675        examine the parameters to the class itself.  On the one
3676        hand, they will be checked when the class is defined, and,
3677        on the other, default arguments are valid in things like:
3678          template <class T = double>
3679          struct S { template <class U> void f(U); };
3680        Here the default argument for `S' has no bearing on the
3681        declaration of `f'.  */
3682     last_level_to_check = template_class_depth (current_class_type) + 1;
3683   else
3684     /* Check everything.  */
3685     last_level_to_check = 0;
3686
3687   for (parm_level = parms;
3688        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3689        parm_level = TREE_CHAIN (parm_level))
3690     {
3691       tree inner_parms = TREE_VALUE (parm_level);
3692       int i;
3693       int ntparms;
3694
3695       ntparms = TREE_VEC_LENGTH (inner_parms);
3696       for (i = 0; i < ntparms; ++i)
3697         {
3698           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3699             continue;
3700
3701           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3702             {
3703               if (msg)
3704                 {
3705                   no_errors = false;
3706                   if (is_friend_decl == 2)
3707                     return no_errors;
3708
3709                   error (msg, decl);
3710                   msg = 0;
3711                 }
3712
3713               /* Clear out the default argument so that we are not
3714                  confused later.  */
3715               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3716             }
3717         }
3718
3719       /* At this point, if we're still interested in issuing messages,
3720          they must apply to classes surrounding the object declared.  */
3721       if (msg)
3722         msg = "default argument for template parameter for class enclosing %qD";
3723     }
3724
3725   return no_errors;
3726 }
3727
3728 /* Worker for push_template_decl_real, called via
3729    for_each_template_parm.  DATA is really an int, indicating the
3730    level of the parameters we are interested in.  If T is a template
3731    parameter of that level, return nonzero.  */
3732
3733 static int
3734 template_parm_this_level_p (tree t, void* data)
3735 {
3736   int this_level = *(int *)data;
3737   int level;
3738
3739   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3740     level = TEMPLATE_PARM_LEVEL (t);
3741   else
3742     level = TEMPLATE_TYPE_LEVEL (t);
3743   return level == this_level;
3744 }
3745
3746 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3747    parameters given by current_template_args, or reuses a
3748    previously existing one, if appropriate.  Returns the DECL, or an
3749    equivalent one, if it is replaced via a call to duplicate_decls.
3750
3751    If IS_FRIEND is true, DECL is a friend declaration.  */
3752
3753 tree
3754 push_template_decl_real (tree decl, bool is_friend)
3755 {
3756   tree tmpl;
3757   tree args;
3758   tree info;
3759   tree ctx;
3760   int primary;
3761   int is_partial;
3762   int new_template_p = 0;
3763   /* True if the template is a member template, in the sense of
3764      [temp.mem].  */
3765   bool member_template_p = false;
3766
3767   if (decl == error_mark_node || !current_template_parms)
3768     return error_mark_node;
3769
3770   /* See if this is a partial specialization.  */
3771   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3772                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3773                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3774
3775   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3776     is_friend = true;
3777
3778   if (is_friend)
3779     /* For a friend, we want the context of the friend function, not
3780        the type of which it is a friend.  */
3781     ctx = DECL_CONTEXT (decl);
3782   else if (CP_DECL_CONTEXT (decl)
3783            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3784     /* In the case of a virtual function, we want the class in which
3785        it is defined.  */
3786     ctx = CP_DECL_CONTEXT (decl);
3787   else
3788     /* Otherwise, if we're currently defining some class, the DECL
3789        is assumed to be a member of the class.  */
3790     ctx = current_scope ();
3791
3792   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3793     ctx = NULL_TREE;
3794
3795   if (!DECL_CONTEXT (decl))
3796     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3797
3798   /* See if this is a primary template.  */
3799   if (is_friend && ctx)
3800     /* A friend template that specifies a class context, i.e.
3801          template <typename T> friend void A<T>::f();
3802        is not primary.  */
3803     primary = 0;
3804   else
3805     primary = template_parm_scope_p ();
3806
3807   if (primary)
3808     {
3809       if (DECL_CLASS_SCOPE_P (decl))
3810         member_template_p = true;
3811       if (TREE_CODE (decl) == TYPE_DECL
3812           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3813         {
3814           error ("template class without a name");
3815           return error_mark_node;
3816         }
3817       else if (TREE_CODE (decl) == FUNCTION_DECL)
3818         {
3819           if (DECL_DESTRUCTOR_P (decl))
3820             {
3821               /* [temp.mem]
3822
3823                  A destructor shall not be a member template.  */
3824               error ("destructor %qD declared as member template", decl);
3825               return error_mark_node;
3826             }
3827           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3828               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3829                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3830                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3831                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3832                       == void_list_node)))
3833             {
3834               /* [basic.stc.dynamic.allocation]
3835
3836                  An allocation function can be a function
3837                  template. ... Template allocation functions shall
3838                  have two or more parameters.  */
3839               error ("invalid template declaration of %qD", decl);
3840               return error_mark_node;
3841             }
3842         }
3843       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3844                && CLASS_TYPE_P (TREE_TYPE (decl)))
3845         /* OK */;
3846       else
3847         {
3848           error ("template declaration of %q#D", decl);
3849           return error_mark_node;
3850         }
3851     }
3852
3853   /* Check to see that the rules regarding the use of default
3854      arguments are not being violated.  */
3855   check_default_tmpl_args (decl, current_template_parms,
3856                            primary, is_partial, /*is_friend_decl=*/0);
3857
3858   /* Ensure that there are no parameter packs in the type of this
3859      declaration that have not been expanded.  */
3860   if (TREE_CODE (decl) == FUNCTION_DECL)
3861     {
3862       /* Check each of the arguments individually to see if there are
3863          any bare parameter packs.  */
3864       tree type = TREE_TYPE (decl);
3865       tree arg = DECL_ARGUMENTS (decl);
3866       tree argtype = TYPE_ARG_TYPES (type);
3867
3868       while (arg && argtype)
3869         {
3870           if (!FUNCTION_PARAMETER_PACK_P (arg)
3871               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3872             {
3873             /* This is a PARM_DECL that contains unexpanded parameter
3874                packs. We have already complained about this in the
3875                check_for_bare_parameter_packs call, so just replace
3876                these types with ERROR_MARK_NODE.  */
3877               TREE_TYPE (arg) = error_mark_node;
3878               TREE_VALUE (argtype) = error_mark_node;
3879             }
3880
3881           arg = TREE_CHAIN (arg);
3882           argtype = TREE_CHAIN (argtype);
3883         }
3884
3885       /* Check for bare parameter packs in the return type and the
3886          exception specifiers.  */
3887       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3888         /* Errors were already issued, set return type to int
3889            as the frontend doesn't expect error_mark_node as
3890            the return type.  */
3891         TREE_TYPE (type) = integer_type_node;
3892       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3893         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3894     }
3895   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3896     {
3897       TREE_TYPE (decl) = error_mark_node;
3898       return error_mark_node;
3899     }
3900
3901   if (is_partial)
3902     return process_partial_specialization (decl);
3903
3904   args = current_template_args ();
3905
3906   if (!ctx
3907       || TREE_CODE (ctx) == FUNCTION_DECL
3908       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3909       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3910     {
3911       if (DECL_LANG_SPECIFIC (decl)
3912           && DECL_TEMPLATE_INFO (decl)
3913           && DECL_TI_TEMPLATE (decl))
3914         tmpl = DECL_TI_TEMPLATE (decl);
3915       /* If DECL is a TYPE_DECL for a class-template, then there won't
3916          be DECL_LANG_SPECIFIC.  The information equivalent to
3917          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3918       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3919                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3920                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3921         {
3922           /* Since a template declaration already existed for this
3923              class-type, we must be redeclaring it here.  Make sure
3924              that the redeclaration is valid.  */
3925           redeclare_class_template (TREE_TYPE (decl),
3926                                     current_template_parms);
3927           /* We don't need to create a new TEMPLATE_DECL; just use the
3928              one we already had.  */
3929           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3930         }
3931       else
3932         {
3933           tmpl = build_template_decl (decl, current_template_parms,
3934                                       member_template_p);
3935           new_template_p = 1;
3936
3937           if (DECL_LANG_SPECIFIC (decl)
3938               && DECL_TEMPLATE_SPECIALIZATION (decl))
3939             {
3940               /* A specialization of a member template of a template
3941                  class.  */
3942               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3943               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3944               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3945             }
3946         }
3947     }
3948   else
3949     {
3950       tree a, t, current, parms;
3951       int i;
3952       tree tinfo = get_template_info (decl);
3953
3954       if (!tinfo)
3955         {
3956           error ("template definition of non-template %q#D", decl);
3957           return error_mark_node;
3958         }
3959
3960       tmpl = TI_TEMPLATE (tinfo);
3961
3962       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3963           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3964           && DECL_TEMPLATE_SPECIALIZATION (decl)
3965           && DECL_MEMBER_TEMPLATE_P (tmpl))
3966         {
3967           tree new_tmpl;
3968
3969           /* The declaration is a specialization of a member
3970              template, declared outside the class.  Therefore, the
3971              innermost template arguments will be NULL, so we
3972              replace them with the arguments determined by the
3973              earlier call to check_explicit_specialization.  */
3974           args = DECL_TI_ARGS (decl);
3975
3976           new_tmpl
3977             = build_template_decl (decl, current_template_parms,
3978                                    member_template_p);
3979           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3980           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3981           DECL_TI_TEMPLATE (decl) = new_tmpl;
3982           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3983           DECL_TEMPLATE_INFO (new_tmpl)
3984             = tree_cons (tmpl, args, NULL_TREE);
3985
3986           register_specialization (new_tmpl,
3987                                    most_general_template (tmpl),
3988                                    args,
3989                                    is_friend);
3990           return decl;
3991         }
3992
3993       /* Make sure the template headers we got make sense.  */
3994
3995       parms = DECL_TEMPLATE_PARMS (tmpl);
3996       i = TMPL_PARMS_DEPTH (parms);
3997       if (TMPL_ARGS_DEPTH (args) != i)
3998         {
3999           error ("expected %d levels of template parms for %q#D, got %d",
4000                  i, decl, TMPL_ARGS_DEPTH (args));
4001         }
4002       else
4003         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4004           {
4005             a = TMPL_ARGS_LEVEL (args, i);
4006             t = INNERMOST_TEMPLATE_PARMS (parms);
4007
4008             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4009               {
4010                 if (current == decl)
4011                   error ("got %d template parameters for %q#D",
4012                          TREE_VEC_LENGTH (a), decl);
4013                 else
4014                   error ("got %d template parameters for %q#T",
4015                          TREE_VEC_LENGTH (a), current);
4016                 error ("  but %d required", TREE_VEC_LENGTH (t));
4017                 return error_mark_node;
4018               }
4019
4020             if (current == decl)
4021               current = ctx;
4022             else
4023               current = (TYPE_P (current)
4024                          ? TYPE_CONTEXT (current)
4025                          : DECL_CONTEXT (current));
4026           }
4027
4028       /* Check that the parms are used in the appropriate qualifying scopes
4029          in the declarator.  */
4030       if (!comp_template_args
4031           (TI_ARGS (tinfo),
4032            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4033         {
4034           error ("\
4035 template arguments to %qD do not match original template %qD",
4036                  decl, DECL_TEMPLATE_RESULT (tmpl));
4037           if (!uses_template_parms (TI_ARGS (tinfo)))
4038             inform (input_location, "use template<> for an explicit specialization");
4039           /* Avoid crash in import_export_decl.  */
4040           DECL_INTERFACE_KNOWN (decl) = 1;
4041           return error_mark_node;
4042         }
4043     }
4044
4045   DECL_TEMPLATE_RESULT (tmpl) = decl;
4046   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4047
4048   /* Push template declarations for global functions and types.  Note
4049      that we do not try to push a global template friend declared in a
4050      template class; such a thing may well depend on the template
4051      parameters of the class.  */
4052   if (new_template_p && !ctx
4053       && !(is_friend && template_class_depth (current_class_type) > 0))
4054     {
4055       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4056       if (tmpl == error_mark_node)
4057         return error_mark_node;
4058
4059       /* Hide template friend classes that haven't been declared yet.  */
4060       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4061         {
4062           DECL_ANTICIPATED (tmpl) = 1;
4063           DECL_FRIEND_P (tmpl) = 1;
4064         }
4065     }
4066
4067   if (primary)
4068     {
4069       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4070       int i;
4071
4072       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4073       if (DECL_CONV_FN_P (tmpl))
4074         {
4075           int depth = TMPL_PARMS_DEPTH (parms);
4076
4077           /* It is a conversion operator. See if the type converted to
4078              depends on innermost template operands.  */
4079
4080           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4081                                          depth))
4082             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4083         }
4084
4085       /* Give template template parms a DECL_CONTEXT of the template
4086          for which they are a parameter.  */
4087       parms = INNERMOST_TEMPLATE_PARMS (parms);
4088       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4089         {
4090           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4091           if (TREE_CODE (parm) == TEMPLATE_DECL)
4092             DECL_CONTEXT (parm) = tmpl;
4093         }
4094     }
4095
4096   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4097      back to its most general template.  If TMPL is a specialization,
4098      ARGS may only have the innermost set of arguments.  Add the missing
4099      argument levels if necessary.  */
4100   if (DECL_TEMPLATE_INFO (tmpl))
4101     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4102
4103   info = tree_cons (tmpl, args, NULL_TREE);
4104
4105   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4106     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4107   else if (DECL_LANG_SPECIFIC (decl))
4108     DECL_TEMPLATE_INFO (decl) = info;
4109
4110   return DECL_TEMPLATE_RESULT (tmpl);
4111 }
4112
4113 tree
4114 push_template_decl (tree decl)
4115 {
4116   return push_template_decl_real (decl, false);
4117 }
4118
4119 /* Called when a class template TYPE is redeclared with the indicated
4120    template PARMS, e.g.:
4121
4122      template <class T> struct S;
4123      template <class T> struct S {};  */
4124
4125 bool
4126 redeclare_class_template (tree type, tree parms)
4127 {
4128   tree tmpl;
4129   tree tmpl_parms;
4130   int i;
4131
4132   if (!TYPE_TEMPLATE_INFO (type))
4133     {
4134       error ("%qT is not a template type", type);
4135       return false;
4136     }
4137
4138   tmpl = TYPE_TI_TEMPLATE (type);
4139   if (!PRIMARY_TEMPLATE_P (tmpl))
4140     /* The type is nested in some template class.  Nothing to worry
4141        about here; there are no new template parameters for the nested
4142        type.  */
4143     return true;
4144
4145   if (!parms)
4146     {
4147       error ("template specifiers not specified in declaration of %qD",
4148              tmpl);
4149       return false;
4150     }
4151
4152   parms = INNERMOST_TEMPLATE_PARMS (parms);
4153   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4154
4155   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4156     {
4157       error ("redeclared with %d template parameter(s)", 
4158              TREE_VEC_LENGTH (parms));
4159       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4160              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4161       return false;
4162     }
4163
4164   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4165     {
4166       tree tmpl_parm;
4167       tree parm;
4168       tree tmpl_default;
4169       tree parm_default;
4170
4171       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4172           || TREE_VEC_ELT (parms, i) == error_mark_node)
4173         continue;
4174
4175       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4176       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4177       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4178       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4179
4180       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4181          TEMPLATE_DECL.  */
4182       if (tmpl_parm != error_mark_node
4183           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4184               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4185                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4186               || (TREE_CODE (tmpl_parm) != PARM_DECL
4187                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4188                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4189               || (TREE_CODE (tmpl_parm) == PARM_DECL
4190                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4191                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4192         {
4193           error ("template parameter %q+#D", tmpl_parm);
4194           error ("redeclared here as %q#D", parm);
4195           return false;
4196         }
4197
4198       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4199         {
4200           /* We have in [temp.param]:
4201
4202              A template-parameter may not be given default arguments
4203              by two different declarations in the same scope.  */
4204           error ("redefinition of default argument for %q#D", parm);
4205           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4206           return false;
4207         }
4208
4209       if (parm_default != NULL_TREE)
4210         /* Update the previous template parameters (which are the ones
4211            that will really count) with the new default value.  */
4212         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4213       else if (tmpl_default != NULL_TREE)
4214         /* Update the new parameters, too; they'll be used as the
4215            parameters for any members.  */
4216         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4217     }
4218
4219     return true;
4220 }
4221
4222 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4223    (possibly simplified) expression.  */
4224
4225 tree
4226 fold_non_dependent_expr (tree expr)
4227 {
4228   if (expr == NULL_TREE)
4229     return NULL_TREE;
4230
4231   /* If we're in a template, but EXPR isn't value dependent, simplify
4232      it.  We're supposed to treat:
4233
4234        template <typename T> void f(T[1 + 1]);
4235        template <typename T> void f(T[2]);
4236
4237      as two declarations of the same function, for example.  */
4238   if (processing_template_decl
4239       && !type_dependent_expression_p (expr)
4240       && !value_dependent_expression_p (expr))
4241     {
4242       HOST_WIDE_INT saved_processing_template_decl;
4243
4244       saved_processing_template_decl = processing_template_decl;
4245       processing_template_decl = 0;
4246       expr = tsubst_copy_and_build (expr,
4247                                     /*args=*/NULL_TREE,
4248                                     tf_error,
4249                                     /*in_decl=*/NULL_TREE,
4250                                     /*function_p=*/false,
4251                                     /*integral_constant_expression_p=*/true);
4252       processing_template_decl = saved_processing_template_decl;
4253     }
4254   return expr;
4255 }
4256
4257 /* EXPR is an expression which is used in a constant-expression context.
4258    For instance, it could be a VAR_DECL with a constant initializer.
4259    Extract the innermost constant expression.
4260
4261    This is basically a more powerful version of
4262    integral_constant_value, which can be used also in templates where
4263    initializers can maintain a syntactic rather than semantic form
4264    (even if they are non-dependent, for access-checking purposes).  */
4265
4266 static tree
4267 fold_decl_constant_value (tree expr)
4268 {
4269   tree const_expr = expr;
4270   do
4271     {
4272       expr = fold_non_dependent_expr (const_expr);
4273       const_expr = integral_constant_value (expr);
4274     }
4275   while (expr != const_expr);
4276
4277   return expr;
4278 }
4279
4280 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4281    must be a function or a pointer-to-function type, as specified
4282    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4283    and check that the resulting function has external linkage.  */
4284
4285 static tree
4286 convert_nontype_argument_function (tree type, tree expr)
4287 {
4288   tree fns = expr;
4289   tree fn, fn_no_ptr;
4290
4291   fn = instantiate_type (type, fns, tf_none);
4292   if (fn == error_mark_node)
4293     return error_mark_node;
4294
4295   fn_no_ptr = fn;
4296   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4297     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4298   if (TREE_CODE (fn_no_ptr) == BASELINK)
4299     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4300  
4301   /* [temp.arg.nontype]/1
4302
4303      A template-argument for a non-type, non-template template-parameter
4304      shall be one of:
4305      [...]
4306      -- the address of an object or function with external linkage.  */
4307   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4308     {
4309       error ("%qE is not a valid template argument for type %qT "
4310              "because function %qD has not external linkage",
4311              expr, type, fn_no_ptr);
4312       return NULL_TREE;
4313     }
4314
4315   return fn;
4316 }
4317
4318 /* Attempt to convert the non-type template parameter EXPR to the
4319    indicated TYPE.  If the conversion is successful, return the
4320    converted value.  If the conversion is unsuccessful, return
4321    NULL_TREE if we issued an error message, or error_mark_node if we
4322    did not.  We issue error messages for out-and-out bad template
4323    parameters, but not simply because the conversion failed, since we
4324    might be just trying to do argument deduction.  Both TYPE and EXPR
4325    must be non-dependent.
4326
4327    The conversion follows the special rules described in
4328    [temp.arg.nontype], and it is much more strict than an implicit
4329    conversion.
4330
4331    This function is called twice for each template argument (see
4332    lookup_template_class for a more accurate description of this
4333    problem). This means that we need to handle expressions which
4334    are not valid in a C++ source, but can be created from the
4335    first call (for instance, casts to perform conversions). These
4336    hacks can go away after we fix the double coercion problem.  */
4337
4338 static tree
4339 convert_nontype_argument (tree type, tree expr)
4340 {
4341   tree expr_type;
4342
4343   /* Detect immediately string literals as invalid non-type argument.
4344      This special-case is not needed for correctness (we would easily
4345      catch this later), but only to provide better diagnostic for this
4346      common user mistake. As suggested by DR 100, we do not mention
4347      linkage issues in the diagnostic as this is not the point.  */
4348   if (TREE_CODE (expr) == STRING_CST)
4349     {
4350       error ("%qE is not a valid template argument for type %qT "
4351              "because string literals can never be used in this context",
4352              expr, type);
4353       return NULL_TREE;
4354     }
4355
4356   /* If we are in a template, EXPR may be non-dependent, but still
4357      have a syntactic, rather than semantic, form.  For example, EXPR
4358      might be a SCOPE_REF, rather than the VAR_DECL to which the
4359      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4360      so that access checking can be performed when the template is
4361      instantiated -- but here we need the resolved form so that we can
4362      convert the argument.  */
4363   expr = fold_non_dependent_expr (expr);
4364   if (error_operand_p (expr))
4365     return error_mark_node;
4366   expr_type = TREE_TYPE (expr);
4367
4368   /* HACK: Due to double coercion, we can get a
4369      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4370      which is the tree that we built on the first call (see
4371      below when coercing to reference to object or to reference to
4372      function). We just strip everything and get to the arg.
4373      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4374      for examples.  */
4375   if (TREE_CODE (expr) == NOP_EXPR)
4376     {
4377       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4378         {
4379           /* ??? Maybe we could use convert_from_reference here, but we
4380              would need to relax its constraints because the NOP_EXPR
4381              could actually change the type to something more cv-qualified,
4382              and this is not folded by convert_from_reference.  */
4383           tree addr = TREE_OPERAND (expr, 0);
4384           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4385           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4386           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4387           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4388                       (TREE_TYPE (expr_type),
4389                        TREE_TYPE (TREE_TYPE (addr))));
4390
4391           expr = TREE_OPERAND (addr, 0);
4392           expr_type = TREE_TYPE (expr);
4393         }
4394
4395       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4396          parameter is a pointer to object, through decay and
4397          qualification conversion. Let's strip everything.  */
4398       else if (TYPE_PTROBV_P (type))
4399         {
4400           STRIP_NOPS (expr);
4401           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4402           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4403           /* Skip the ADDR_EXPR only if it is part of the decay for
4404              an array. Otherwise, it is part of the original argument
4405              in the source code.  */
4406           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4407             expr = TREE_OPERAND (expr, 0);
4408           expr_type = TREE_TYPE (expr);
4409         }
4410     }
4411
4412   /* [temp.arg.nontype]/5, bullet 1
4413
4414      For a non-type template-parameter of integral or enumeration type,
4415      integral promotions (_conv.prom_) and integral conversions
4416      (_conv.integral_) are applied.  */
4417   if (INTEGRAL_TYPE_P (type))
4418     {
4419       if (!INTEGRAL_TYPE_P (expr_type))
4420         return error_mark_node;
4421
4422       expr = fold_decl_constant_value (expr);
4423       /* Notice that there are constant expressions like '4 % 0' which
4424          do not fold into integer constants.  */
4425       if (TREE_CODE (expr) != INTEGER_CST)
4426         {
4427           error ("%qE is not a valid template argument for type %qT "
4428                  "because it is a non-constant expression", expr, type);
4429           return NULL_TREE;
4430         }
4431
4432       /* At this point, an implicit conversion does what we want,
4433          because we already know that the expression is of integral
4434          type.  */
4435       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4436       if (expr == error_mark_node)
4437         return error_mark_node;
4438
4439       /* Conversion was allowed: fold it to a bare integer constant.  */
4440       expr = fold (expr);
4441     }
4442   /* [temp.arg.nontype]/5, bullet 2
4443
4444      For a non-type template-parameter of type pointer to object,
4445      qualification conversions (_conv.qual_) and the array-to-pointer
4446      conversion (_conv.array_) are applied.  */
4447   else if (TYPE_PTROBV_P (type))
4448     {
4449       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4450
4451          A template-argument for a non-type, non-template template-parameter
4452          shall be one of: [...]
4453
4454          -- the name of a non-type template-parameter;
4455          -- the address of an object or function with external linkage, [...]
4456             expressed as "& id-expression" where the & is optional if the name
4457             refers to a function or array, or if the corresponding
4458             template-parameter is a reference.
4459
4460         Here, we do not care about functions, as they are invalid anyway
4461         for a parameter of type pointer-to-object.  */
4462
4463       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4464         /* Non-type template parameters are OK.  */
4465         ;
4466       else if (TREE_CODE (expr) != ADDR_EXPR
4467                && TREE_CODE (expr_type) != ARRAY_TYPE)
4468         {
4469           if (TREE_CODE (expr) == VAR_DECL)
4470             {
4471               error ("%qD is not a valid template argument "
4472                      "because %qD is a variable, not the address of "
4473                      "a variable",
4474                      expr, expr);
4475               return NULL_TREE;
4476             }
4477           /* Other values, like integer constants, might be valid
4478              non-type arguments of some other type.  */
4479           return error_mark_node;
4480         }
4481       else
4482         {
4483           tree decl;
4484
4485           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4486                   ? TREE_OPERAND (expr, 0) : expr);
4487           if (TREE_CODE (decl) != VAR_DECL)
4488             {
4489               error ("%qE is not a valid template argument of type %qT "
4490                      "because %qE is not a variable",
4491                      expr, type, decl);
4492               return NULL_TREE;
4493             }
4494           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4495             {
4496               error ("%qE is not a valid template argument of type %qT "
4497                      "because %qD does not have external linkage",
4498                      expr, type, decl);
4499               return NULL_TREE;
4500             }
4501         }
4502
4503       expr = decay_conversion (expr);
4504       if (expr == error_mark_node)
4505         return error_mark_node;
4506
4507       expr = perform_qualification_conversions (type, expr);
4508       if (expr == error_mark_node)
4509         return error_mark_node;
4510     }
4511   /* [temp.arg.nontype]/5, bullet 3
4512
4513      For a non-type template-parameter of type reference to object, no
4514      conversions apply. The type referred to by the reference may be more
4515      cv-qualified than the (otherwise identical) type of the
4516      template-argument. The template-parameter is bound directly to the
4517      template-argument, which must be an lvalue.  */
4518   else if (TYPE_REF_OBJ_P (type))
4519     {
4520       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4521                                                       expr_type))
4522         return error_mark_node;
4523
4524       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4525         {
4526           error ("%qE is not a valid template argument for type %qT "
4527                  "because of conflicts in cv-qualification", expr, type);
4528           return NULL_TREE;
4529         }
4530
4531       if (!real_lvalue_p (expr))
4532         {
4533           error ("%qE is not a valid template argument for type %qT "
4534                  "because it is not an lvalue", expr, type);
4535           return NULL_TREE;
4536         }
4537
4538       /* [temp.arg.nontype]/1
4539
4540          A template-argument for a non-type, non-template template-parameter
4541          shall be one of: [...]
4542
4543          -- the address of an object or function with external linkage.  */
4544       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4545         {
4546           error ("%qE is not a valid template argument for type %qT "
4547                  "because object %qD has not external linkage",
4548                  expr, type, expr);
4549           return NULL_TREE;
4550         }
4551
4552       expr = build_nop (type, build_address (expr));
4553     }
4554   /* [temp.arg.nontype]/5, bullet 4
4555
4556      For a non-type template-parameter of type pointer to function, only
4557      the function-to-pointer conversion (_conv.func_) is applied. If the
4558      template-argument represents a set of overloaded functions (or a
4559      pointer to such), the matching function is selected from the set
4560      (_over.over_).  */
4561   else if (TYPE_PTRFN_P (type))
4562     {
4563       /* If the argument is a template-id, we might not have enough
4564          context information to decay the pointer.  */
4565       if (!type_unknown_p (expr_type))
4566         {
4567           expr = decay_conversion (expr);
4568           if (expr == error_mark_node)
4569             return error_mark_node;
4570         }
4571
4572       expr = convert_nontype_argument_function (type, expr);
4573       if (!expr || expr == error_mark_node)
4574         return expr;
4575
4576       if (TREE_CODE (expr) != ADDR_EXPR)
4577         {
4578           error ("%qE is not a valid template argument for type %qT", expr, type);
4579           error ("it must be the address of a function with external linkage");
4580           return NULL_TREE;
4581         }
4582     }
4583   /* [temp.arg.nontype]/5, bullet 5
4584
4585      For a non-type template-parameter of type reference to function, no
4586      conversions apply. If the template-argument represents a set of
4587      overloaded functions, the matching function is selected from the set
4588      (_over.over_).  */
4589   else if (TYPE_REFFN_P (type))
4590     {
4591       if (TREE_CODE (expr) == ADDR_EXPR)
4592         {
4593           error ("%qE is not a valid template argument for type %qT "
4594                  "because it is a pointer", expr, type);
4595           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4596           return NULL_TREE;
4597         }
4598
4599       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4600       if (!expr || expr == error_mark_node)
4601         return expr;
4602
4603       expr = build_nop (type, build_address (expr));
4604     }
4605   /* [temp.arg.nontype]/5, bullet 6
4606
4607      For a non-type template-parameter of type pointer to member function,
4608      no conversions apply. If the template-argument represents a set of
4609      overloaded member functions, the matching member function is selected
4610      from the set (_over.over_).  */
4611   else if (TYPE_PTRMEMFUNC_P (type))
4612     {
4613       expr = instantiate_type (type, expr, tf_none);
4614       if (expr == error_mark_node)
4615         return error_mark_node;
4616
4617       /* There is no way to disable standard conversions in
4618          resolve_address_of_overloaded_function (called by
4619          instantiate_type). It is possible that the call succeeded by
4620          converting &B::I to &D::I (where B is a base of D), so we need
4621          to reject this conversion here.
4622
4623          Actually, even if there was a way to disable standard conversions,
4624          it would still be better to reject them here so that we can
4625          provide a superior diagnostic.  */
4626       if (!same_type_p (TREE_TYPE (expr), type))
4627         {
4628           /* Make sure we are just one standard conversion off.  */
4629           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4630           error ("%qE is not a valid template argument for type %qT "
4631                  "because it is of type %qT", expr, type,
4632                  TREE_TYPE (expr));
4633           inform (input_location, "standard conversions are not allowed in this context");
4634           return NULL_TREE;
4635         }
4636     }
4637   /* [temp.arg.nontype]/5, bullet 7
4638
4639      For a non-type template-parameter of type pointer to data member,
4640      qualification conversions (_conv.qual_) are applied.  */
4641   else if (TYPE_PTRMEM_P (type))
4642     {
4643       expr = perform_qualification_conversions (type, expr);
4644       if (expr == error_mark_node)
4645         return expr;
4646     }
4647   /* A template non-type parameter must be one of the above.  */
4648   else
4649     gcc_unreachable ();
4650
4651   /* Sanity check: did we actually convert the argument to the
4652      right type?  */
4653   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4654   return expr;
4655 }
4656
4657 /* Subroutine of coerce_template_template_parms, which returns 1 if
4658    PARM_PARM and ARG_PARM match using the rule for the template
4659    parameters of template template parameters. Both PARM and ARG are
4660    template parameters; the rest of the arguments are the same as for
4661    coerce_template_template_parms.
4662  */
4663 static int
4664 coerce_template_template_parm (tree parm,
4665                               tree arg,
4666                               tsubst_flags_t complain,
4667                               tree in_decl,
4668                               tree outer_args)
4669 {
4670   if (arg == NULL_TREE || arg == error_mark_node
4671       || parm == NULL_TREE || parm == error_mark_node)
4672     return 0;
4673   
4674   if (TREE_CODE (arg) != TREE_CODE (parm))
4675     return 0;
4676   
4677   switch (TREE_CODE (parm))
4678     {
4679     case TEMPLATE_DECL:
4680       /* We encounter instantiations of templates like
4681          template <template <template <class> class> class TT>
4682          class C;  */
4683       {
4684         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4685         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4686         
4687         if (!coerce_template_template_parms
4688             (parmparm, argparm, complain, in_decl, outer_args))
4689           return 0;
4690       }
4691       /* Fall through.  */
4692       
4693     case TYPE_DECL:
4694       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4695           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4696         /* Argument is a parameter pack but parameter is not.  */
4697         return 0;
4698       break;
4699       
4700     case PARM_DECL:
4701       /* The tsubst call is used to handle cases such as
4702          
4703            template <int> class C {};
4704            template <class T, template <T> class TT> class D {};
4705            D<int, C> d;
4706
4707          i.e. the parameter list of TT depends on earlier parameters.  */
4708       if (!uses_template_parms (TREE_TYPE (arg))
4709           && !same_type_p
4710                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4711                  TREE_TYPE (arg)))
4712         return 0;
4713       
4714       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4715           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4716         /* Argument is a parameter pack but parameter is not.  */
4717         return 0;
4718       
4719       break;
4720
4721     default:
4722       gcc_unreachable ();
4723     }
4724
4725   return 1;
4726 }
4727
4728
4729 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4730    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4731    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4732    or PARM_DECL.
4733
4734    Consider the example:
4735      template <class T> class A;
4736      template<template <class U> class TT> class B;
4737
4738    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4739    the parameters to A, and OUTER_ARGS contains A.  */
4740
4741 static int
4742 coerce_template_template_parms (tree parm_parms,
4743                                 tree arg_parms,
4744                                 tsubst_flags_t complain,
4745                                 tree in_decl,
4746                                 tree outer_args)
4747 {
4748   int nparms, nargs, i;
4749   tree parm, arg;
4750   int variadic_p = 0;
4751
4752   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4753   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4754
4755   nparms = TREE_VEC_LENGTH (parm_parms);
4756   nargs = TREE_VEC_LENGTH (arg_parms);
4757
4758   /* Determine whether we have a parameter pack at the end of the
4759      template template parameter's template parameter list.  */
4760   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4761     {
4762       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4763       
4764       if (parm == error_mark_node)
4765         return 0;
4766
4767       switch (TREE_CODE (parm))
4768         {
4769         case TEMPLATE_DECL:
4770         case TYPE_DECL:
4771           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4772             variadic_p = 1;
4773           break;
4774           
4775         case PARM_DECL:
4776           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4777             variadic_p = 1;
4778           break;
4779           
4780         default:
4781           gcc_unreachable ();
4782         }
4783     }
4784  
4785   if (nargs != nparms
4786       && !(variadic_p && nargs >= nparms - 1))
4787     return 0;
4788
4789   /* Check all of the template parameters except the parameter pack at
4790      the end (if any).  */
4791   for (i = 0; i < nparms - variadic_p; ++i)
4792     {
4793       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4794           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4795         continue;
4796
4797       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4798       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4799
4800       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4801                                           outer_args))
4802         return 0;
4803
4804     }
4805
4806   if (variadic_p)
4807     {
4808       /* Check each of the template parameters in the template
4809          argument against the template parameter pack at the end of
4810          the template template parameter.  */
4811       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4812         return 0;
4813
4814       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4815
4816       for (; i < nargs; ++i)
4817         {
4818           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4819             continue;
4820  
4821           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4822  
4823           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4824                                               outer_args))
4825             return 0;
4826         }
4827     }
4828
4829   return 1;
4830 }
4831
4832 /* Verifies that the deduced template arguments (in TARGS) for the
4833    template template parameters (in TPARMS) represent valid bindings,
4834    by comparing the template parameter list of each template argument
4835    to the template parameter list of its corresponding template
4836    template parameter, in accordance with DR150. This
4837    routine can only be called after all template arguments have been
4838    deduced. It will return TRUE if all of the template template
4839    parameter bindings are okay, FALSE otherwise.  */
4840 bool 
4841 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4842 {
4843   int i, ntparms = TREE_VEC_LENGTH (tparms);
4844   bool ret = true;
4845
4846   /* We're dealing with template parms in this process.  */
4847   ++processing_template_decl;
4848
4849   targs = INNERMOST_TEMPLATE_ARGS (targs);
4850
4851   for (i = 0; i < ntparms; ++i)
4852     {
4853       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4854       tree targ = TREE_VEC_ELT (targs, i);
4855
4856       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4857         {
4858           tree packed_args = NULL_TREE;
4859           int idx, len = 1;
4860
4861           if (ARGUMENT_PACK_P (targ))
4862             {
4863               /* Look inside the argument pack.  */
4864               packed_args = ARGUMENT_PACK_ARGS (targ);
4865               len = TREE_VEC_LENGTH (packed_args);
4866             }
4867
4868           for (idx = 0; idx < len; ++idx)
4869             {
4870               tree targ_parms = NULL_TREE;
4871
4872               if (packed_args)
4873                 /* Extract the next argument from the argument
4874                    pack.  */
4875                 targ = TREE_VEC_ELT (packed_args, idx);
4876
4877               if (PACK_EXPANSION_P (targ))
4878                 /* Look at the pattern of the pack expansion.  */
4879                 targ = PACK_EXPANSION_PATTERN (targ);
4880
4881               /* Extract the template parameters from the template
4882                  argument.  */
4883               if (TREE_CODE (targ) == TEMPLATE_DECL)
4884                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4885               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4886                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4887
4888               /* Verify that we can coerce the template template
4889                  parameters from the template argument to the template
4890                  parameter.  This requires an exact match.  */
4891               if (targ_parms
4892                   && !coerce_template_template_parms
4893                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4894                         targ_parms,
4895                         tf_none,
4896                         tparm,
4897                         targs))
4898                 {
4899                   ret = false;
4900                   goto out;
4901                 }
4902             }
4903         }
4904     }
4905
4906  out:
4907
4908   --processing_template_decl;
4909   return ret;
4910 }
4911
4912 /* Convert the indicated template ARG as necessary to match the
4913    indicated template PARM.  Returns the converted ARG, or
4914    error_mark_node if the conversion was unsuccessful.  Error and
4915    warning messages are issued under control of COMPLAIN.  This
4916    conversion is for the Ith parameter in the parameter list.  ARGS is
4917    the full set of template arguments deduced so far.  */
4918
4919 static tree
4920 convert_template_argument (tree parm,
4921                            tree arg,
4922                            tree args,
4923                            tsubst_flags_t complain,
4924                            int i,
4925                            tree in_decl)
4926 {
4927   tree orig_arg;
4928   tree val;
4929   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4930
4931   if (TREE_CODE (arg) == TREE_LIST
4932       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4933     {
4934       /* The template argument was the name of some
4935          member function.  That's usually
4936          invalid, but static members are OK.  In any
4937          case, grab the underlying fields/functions
4938          and issue an error later if required.  */
4939       orig_arg = TREE_VALUE (arg);
4940       TREE_TYPE (arg) = unknown_type_node;
4941     }
4942
4943   orig_arg = arg;
4944
4945   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4946   requires_type = (TREE_CODE (parm) == TYPE_DECL
4947                    || requires_tmpl_type);
4948
4949   /* When determining whether an argument pack expansion is a template,
4950      look at the pattern.  */
4951   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4952     arg = PACK_EXPANSION_PATTERN (arg);
4953
4954   is_tmpl_type = 
4955     ((TREE_CODE (arg) == TEMPLATE_DECL
4956       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4957      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4958      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4959
4960   if (is_tmpl_type
4961       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4962           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4963     arg = TYPE_STUB_DECL (arg);
4964
4965   is_type = TYPE_P (arg) || is_tmpl_type;
4966
4967   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4968       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4969     {
4970       permerror (input_location, "to refer to a type member of a template parameter, "
4971                  "use %<typename %E%>", orig_arg);
4972
4973       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4974                                      TREE_OPERAND (arg, 1),
4975                                      typename_type,
4976                                      complain & tf_error);
4977       arg = orig_arg;
4978       is_type = 1;
4979     }
4980   if (is_type != requires_type)
4981     {
4982       if (in_decl)
4983         {
4984           if (complain & tf_error)
4985             {
4986               error ("type/value mismatch at argument %d in template "
4987                      "parameter list for %qD",
4988                      i + 1, in_decl);
4989               if (is_type)
4990                 error ("  expected a constant of type %qT, got %qT",
4991                        TREE_TYPE (parm),
4992                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4993               else if (requires_tmpl_type)
4994                 error ("  expected a class template, got %qE", orig_arg);
4995               else
4996                 error ("  expected a type, got %qE", orig_arg);
4997             }
4998         }
4999       return error_mark_node;
5000     }
5001   if (is_tmpl_type ^ requires_tmpl_type)
5002     {
5003       if (in_decl && (complain & tf_error))
5004         {
5005           error ("type/value mismatch at argument %d in template "
5006                  "parameter list for %qD",
5007                  i + 1, in_decl);
5008           if (is_tmpl_type)
5009             error ("  expected a type, got %qT", DECL_NAME (arg));
5010           else
5011             error ("  expected a class template, got %qT", orig_arg);
5012         }
5013       return error_mark_node;
5014     }
5015
5016   if (is_type)
5017     {
5018       if (requires_tmpl_type)
5019         {
5020           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5021             /* The number of argument required is not known yet.
5022                Just accept it for now.  */
5023             val = TREE_TYPE (arg);
5024           else
5025             {
5026               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5027               tree argparm;
5028
5029               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5030
5031               if (coerce_template_template_parms (parmparm, argparm,
5032                                                   complain, in_decl,
5033                                                   args))
5034                 {
5035                   val = orig_arg;
5036
5037                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5038                      TEMPLATE_DECL.  */
5039                   if (val != error_mark_node)
5040                     {
5041                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5042                         val = TREE_TYPE (val);
5043                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5044                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5045                         {
5046                           val = TREE_TYPE (arg);
5047                           val = make_pack_expansion (val);
5048                         }
5049                     }
5050                 }
5051               else
5052                 {
5053                   if (in_decl && (complain & tf_error))
5054                     {
5055                       error ("type/value mismatch at argument %d in "
5056                              "template parameter list for %qD",
5057                              i + 1, in_decl);
5058                       error ("  expected a template of type %qD, got %qD",
5059                              parm, orig_arg);
5060                     }
5061
5062                   val = error_mark_node;
5063                 }
5064             }
5065         }
5066       else
5067         val = orig_arg;
5068       /* We only form one instance of each template specialization.
5069          Therefore, if we use a non-canonical variant (i.e., a
5070          typedef), any future messages referring to the type will use
5071          the typedef, which is confusing if those future uses do not
5072          themselves also use the typedef.  */
5073       if (TYPE_P (val))
5074         val = canonical_type_variant (val);
5075     }
5076   else
5077     {
5078       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5079
5080       if (invalid_nontype_parm_type_p (t, complain))
5081         return error_mark_node;
5082
5083       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5084         {
5085           if (same_type_p (t, TREE_TYPE (orig_arg)))
5086             val = orig_arg;
5087           else
5088             {
5089               /* Not sure if this is reachable, but it doesn't hurt
5090                  to be robust.  */
5091               error ("type mismatch in nontype parameter pack");
5092               val = error_mark_node;
5093             }
5094         }
5095       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5096         /* We used to call digest_init here.  However, digest_init
5097            will report errors, which we don't want when complain
5098            is zero.  More importantly, digest_init will try too
5099            hard to convert things: for example, `0' should not be
5100            converted to pointer type at this point according to
5101            the standard.  Accepting this is not merely an
5102            extension, since deciding whether or not these
5103            conversions can occur is part of determining which
5104            function template to call, or whether a given explicit
5105            argument specification is valid.  */
5106         val = convert_nontype_argument (t, orig_arg);
5107       else
5108         val = orig_arg;
5109
5110       if (val == NULL_TREE)
5111         val = error_mark_node;
5112       else if (val == error_mark_node && (complain & tf_error))
5113         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5114     }
5115
5116   return val;
5117 }
5118
5119 /* Coerces the remaining template arguments in INNER_ARGS (from
5120    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5121    Returns the coerced argument pack. PARM_IDX is the position of this
5122    parameter in the template parameter list. ARGS is the original
5123    template argument list.  */
5124 static tree
5125 coerce_template_parameter_pack (tree parms,
5126                                 int parm_idx,
5127                                 tree args,
5128                                 tree inner_args,
5129                                 int arg_idx,
5130                                 tree new_args,
5131                                 int* lost,
5132                                 tree in_decl,
5133                                 tsubst_flags_t complain)
5134 {
5135   tree parm = TREE_VEC_ELT (parms, parm_idx);
5136   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5137   tree packed_args;
5138   tree argument_pack;
5139   tree packed_types = NULL_TREE;
5140
5141   if (arg_idx > nargs)
5142     arg_idx = nargs;
5143
5144   packed_args = make_tree_vec (nargs - arg_idx);
5145
5146   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5147       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5148     {
5149       /* When the template parameter is a non-type template
5150          parameter pack whose type uses parameter packs, we need
5151          to look at each of the template arguments
5152          separately. Build a vector of the types for these
5153          non-type template parameters in PACKED_TYPES.  */
5154       tree expansion 
5155         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5156       packed_types = tsubst_pack_expansion (expansion, args,
5157                                             complain, in_decl);
5158
5159       if (packed_types == error_mark_node)
5160         return error_mark_node;
5161
5162       /* Check that we have the right number of arguments.  */
5163       if (arg_idx < nargs
5164           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5165           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5166         {
5167           int needed_parms 
5168             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5169           error ("wrong number of template arguments (%d, should be %d)",
5170                  nargs, needed_parms);
5171           return error_mark_node;
5172         }
5173
5174       /* If we aren't able to check the actual arguments now
5175          (because they haven't been expanded yet), we can at least
5176          verify that all of the types used for the non-type
5177          template parameter pack are, in fact, valid for non-type
5178          template parameters.  */
5179       if (arg_idx < nargs 
5180           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5181         {
5182           int j, len = TREE_VEC_LENGTH (packed_types);
5183           for (j = 0; j < len; ++j)
5184             {
5185               tree t = TREE_VEC_ELT (packed_types, j);
5186               if (invalid_nontype_parm_type_p (t, complain))
5187                 return error_mark_node;
5188             }
5189         }
5190     }
5191
5192   /* Convert the remaining arguments, which will be a part of the
5193      parameter pack "parm".  */
5194   for (; arg_idx < nargs; ++arg_idx)
5195     {
5196       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5197       tree actual_parm = TREE_VALUE (parm);
5198
5199       if (packed_types && !PACK_EXPANSION_P (arg))
5200         {
5201           /* When we have a vector of types (corresponding to the
5202              non-type template parameter pack that uses parameter
5203              packs in its type, as mention above), and the
5204              argument is not an expansion (which expands to a
5205              currently unknown number of arguments), clone the
5206              parm and give it the next type in PACKED_TYPES.  */
5207           actual_parm = copy_node (actual_parm);
5208           TREE_TYPE (actual_parm) = 
5209             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5210         }
5211
5212       if (arg != error_mark_node)
5213         arg = convert_template_argument (actual_parm, 
5214                                          arg, new_args, complain, parm_idx,
5215                                          in_decl);
5216       if (arg == error_mark_node)
5217         (*lost)++;
5218       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5219     }
5220
5221   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5222       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5223     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5224   else
5225     {
5226       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5227       TREE_TYPE (argument_pack) 
5228         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5229       TREE_CONSTANT (argument_pack) = 1;
5230     }
5231
5232   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5233   return argument_pack;
5234 }
5235
5236 /* Convert all template arguments to their appropriate types, and
5237    return a vector containing the innermost resulting template
5238    arguments.  If any error occurs, return error_mark_node. Error and
5239    warning messages are issued under control of COMPLAIN.
5240
5241    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5242    for arguments not specified in ARGS.  Otherwise, if
5243    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5244    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5245    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5246    ARGS.  */
5247
5248 static tree
5249 coerce_template_parms (tree parms,
5250                        tree args,
5251                        tree in_decl,
5252                        tsubst_flags_t complain,
5253                        bool require_all_args,
5254                        bool use_default_args)
5255 {
5256   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5257   tree inner_args;
5258   tree new_args;
5259   tree new_inner_args;
5260   bool saved_skip_evaluation;
5261
5262   /* When used as a boolean value, indicates whether this is a
5263      variadic template parameter list. Since it's an int, we can also
5264      subtract it from nparms to get the number of non-variadic
5265      parameters.  */
5266   int variadic_p = 0;
5267
5268   nparms = TREE_VEC_LENGTH (parms);
5269
5270   /* Determine if there are any parameter packs.  */
5271   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5272     {
5273       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5274       if (template_parameter_pack_p (tparm))
5275         ++variadic_p;
5276     }
5277
5278   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5279   /* If there are 0 or 1 parameter packs, we need to expand any argument
5280      packs so that we can deduce a parameter pack from some non-packed args
5281      followed by an argument pack, as in variadic85.C.  If there are more
5282      than that, we need to leave argument packs intact so the arguments are
5283      assigned to the right parameter packs.  This should only happen when
5284      dealing with a nested class inside a partial specialization of a class
5285      template, as in variadic92.C.  */
5286   if (variadic_p <= 1)
5287     inner_args = expand_template_argument_pack (inner_args);
5288
5289   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5290   if ((nargs > nparms && !variadic_p)
5291       || (nargs < nparms - variadic_p
5292           && require_all_args
5293           && (!use_default_args
5294               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5295                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5296     {
5297       if (complain & tf_error)
5298         {
5299           const char *or_more = "";
5300           if (variadic_p)
5301             {
5302               or_more = " or more";
5303               --nparms;
5304             }
5305
5306           error ("wrong number of template arguments (%d, should be %d%s)",
5307                  nargs, nparms, or_more);
5308
5309           if (in_decl)
5310             error ("provided for %q+D", in_decl);
5311         }
5312
5313       return error_mark_node;
5314     }
5315
5316   /* We need to evaluate the template arguments, even though this
5317      template-id may be nested within a "sizeof".  */
5318   saved_skip_evaluation = skip_evaluation;
5319   skip_evaluation = false;
5320   new_inner_args = make_tree_vec (nparms);
5321   new_args = add_outermost_template_args (args, new_inner_args);
5322   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5323     {
5324       tree arg;
5325       tree parm;
5326
5327       /* Get the Ith template parameter.  */
5328       parm = TREE_VEC_ELT (parms, parm_idx);
5329  
5330       if (parm == error_mark_node)
5331       {
5332         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5333         continue;
5334       }
5335
5336       /* Calculate the next argument.  */
5337       if (arg_idx < nargs)
5338         arg = TREE_VEC_ELT (inner_args, arg_idx);
5339       else
5340         arg = NULL_TREE;
5341
5342       if (template_parameter_pack_p (TREE_VALUE (parm))
5343           && !(arg && ARGUMENT_PACK_P (arg)))
5344         {
5345           /* All remaining arguments will be placed in the
5346              template parameter pack PARM.  */
5347           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5348                                                 inner_args, arg_idx,
5349                                                 new_args, &lost,
5350                                                 in_decl, complain);
5351
5352           /* Store this argument.  */
5353           if (arg == error_mark_node)
5354             lost++;
5355           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5356
5357           /* We are done with all of the arguments.  */
5358           arg_idx = nargs;
5359           
5360           continue;
5361         }
5362       else if (arg)
5363         {
5364           if (PACK_EXPANSION_P (arg))
5365             {
5366               if (complain & tf_error)
5367                 {
5368                   /* FIXME this restriction was removed by N2555; see
5369                      bug 35722.  */
5370                   /* If ARG is a pack expansion, but PARM is not a
5371                      template parameter pack (if it were, we would have
5372                      handled it above), we're trying to expand into a
5373                      fixed-length argument list.  */
5374                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5375                     sorry ("cannot expand %<%E%> into a fixed-length "
5376                            "argument list", arg);
5377                   else
5378                     sorry ("cannot expand %<%T%> into a fixed-length "
5379                            "argument list", arg);
5380                 }
5381               return error_mark_node;
5382             }
5383         }
5384       else if (require_all_args)
5385         /* There must be a default arg in this case.  */
5386         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5387                                    complain, in_decl);
5388       else
5389         break;
5390
5391       if (arg == error_mark_node)
5392         {
5393           if (complain & tf_error)
5394             error ("template argument %d is invalid", arg_idx + 1);
5395         }
5396       else if (!arg)
5397         /* This only occurs if there was an error in the template
5398            parameter list itself (which we would already have
5399            reported) that we are trying to recover from, e.g., a class
5400            template with a parameter list such as
5401            template<typename..., typename>.  */
5402         return error_mark_node;
5403       else
5404         arg = convert_template_argument (TREE_VALUE (parm),
5405                                          arg, new_args, complain, 
5406                                          parm_idx, in_decl);
5407
5408       if (arg == error_mark_node)
5409         lost++;
5410       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5411     }
5412   skip_evaluation = saved_skip_evaluation;
5413
5414   if (lost)
5415     return error_mark_node;
5416
5417   return new_inner_args;
5418 }
5419
5420 /* Returns 1 if template args OT and NT are equivalent.  */
5421
5422 static int
5423 template_args_equal (tree ot, tree nt)
5424 {
5425   if (nt == ot)
5426     return 1;
5427
5428   if (TREE_CODE (nt) == TREE_VEC)
5429     /* For member templates */
5430     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5431   else if (PACK_EXPANSION_P (ot))
5432     return PACK_EXPANSION_P (nt) 
5433       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5434                               PACK_EXPANSION_PATTERN (nt));
5435   else if (ARGUMENT_PACK_P (ot))
5436     {
5437       int i, len;
5438       tree opack, npack;
5439
5440       if (!ARGUMENT_PACK_P (nt))
5441         return 0;
5442
5443       opack = ARGUMENT_PACK_ARGS (ot);
5444       npack = ARGUMENT_PACK_ARGS (nt);
5445       len = TREE_VEC_LENGTH (opack);
5446       if (TREE_VEC_LENGTH (npack) != len)
5447         return 0;
5448       for (i = 0; i < len; ++i)
5449         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5450                                   TREE_VEC_ELT (npack, i)))
5451           return 0;
5452       return 1;
5453     }
5454   else if (TYPE_P (nt))
5455     return TYPE_P (ot) && same_type_p (ot, nt);
5456   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5457     return 0;
5458   else
5459     return cp_tree_equal (ot, nt);
5460 }
5461
5462 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5463    of template arguments.  Returns 0 otherwise.  */
5464
5465 int
5466 comp_template_args (tree oldargs, tree newargs)
5467 {
5468   int i;
5469
5470   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5471     return 0;
5472
5473   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5474     {
5475       tree nt = TREE_VEC_ELT (newargs, i);
5476       tree ot = TREE_VEC_ELT (oldargs, i);
5477
5478       if (! template_args_equal (ot, nt))
5479         return 0;
5480     }
5481   return 1;
5482 }
5483
5484 static void
5485 add_pending_template (tree d)
5486 {
5487   tree ti = (TYPE_P (d)
5488              ? CLASSTYPE_TEMPLATE_INFO (d)
5489              : DECL_TEMPLATE_INFO (d));
5490   struct pending_template *pt;
5491   int level;
5492
5493   if (TI_PENDING_TEMPLATE_FLAG (ti))
5494     return;
5495
5496   /* We are called both from instantiate_decl, where we've already had a
5497      tinst_level pushed, and instantiate_template, where we haven't.
5498      Compensate.  */
5499   level = !current_tinst_level || current_tinst_level->decl != d;
5500
5501   if (level)
5502     push_tinst_level (d);
5503
5504   pt = GGC_NEW (struct pending_template);
5505   pt->next = NULL;
5506   pt->tinst = current_tinst_level;
5507   if (last_pending_template)
5508     last_pending_template->next = pt;
5509   else
5510     pending_templates = pt;
5511
5512   last_pending_template = pt;
5513
5514   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5515
5516   if (level)
5517     pop_tinst_level ();
5518 }
5519
5520
5521 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5522    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5523    documentation for TEMPLATE_ID_EXPR.  */
5524
5525 tree
5526 lookup_template_function (tree fns, tree arglist)
5527 {
5528   tree type;
5529
5530   if (fns == error_mark_node || arglist == error_mark_node)
5531     return error_mark_node;
5532
5533   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5534   gcc_assert (fns && (is_overloaded_fn (fns)
5535                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5536
5537   if (BASELINK_P (fns))
5538     {
5539       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5540                                          unknown_type_node,
5541                                          BASELINK_FUNCTIONS (fns),
5542                                          arglist);
5543       return fns;
5544     }
5545
5546   type = TREE_TYPE (fns);
5547   if (TREE_CODE (fns) == OVERLOAD || !type)
5548     type = unknown_type_node;
5549
5550   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5551 }
5552
5553 /* Within the scope of a template class S<T>, the name S gets bound
5554    (in build_self_reference) to a TYPE_DECL for the class, not a
5555    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5556    or one of its enclosing classes, and that type is a template,
5557    return the associated TEMPLATE_DECL.  Otherwise, the original
5558    DECL is returned.  */
5559
5560 tree
5561 maybe_get_template_decl_from_type_decl (tree decl)
5562 {
5563   return (decl != NULL_TREE
5564           && TREE_CODE (decl) == TYPE_DECL
5565           && DECL_ARTIFICIAL (decl)
5566           && CLASS_TYPE_P (TREE_TYPE (decl))
5567           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5568     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5569 }
5570
5571 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5572    parameters, find the desired type.
5573
5574    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5575
5576    IN_DECL, if non-NULL, is the template declaration we are trying to
5577    instantiate.
5578
5579    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5580    the class we are looking up.
5581
5582    Issue error and warning messages under control of COMPLAIN.
5583
5584    If the template class is really a local class in a template
5585    function, then the FUNCTION_CONTEXT is the function in which it is
5586    being instantiated.
5587
5588    ??? Note that this function is currently called *twice* for each
5589    template-id: the first time from the parser, while creating the
5590    incomplete type (finish_template_type), and the second type during the
5591    real instantiation (instantiate_template_class). This is surely something
5592    that we want to avoid. It also causes some problems with argument
5593    coercion (see convert_nontype_argument for more information on this).  */
5594
5595 tree
5596 lookup_template_class (tree d1,
5597                        tree arglist,
5598                        tree in_decl,
5599                        tree context,
5600                        int entering_scope,
5601                        tsubst_flags_t complain)
5602 {
5603   tree templ = NULL_TREE, parmlist;
5604   tree t;
5605
5606   timevar_push (TV_NAME_LOOKUP);
5607
5608   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5609     {
5610       tree value = innermost_non_namespace_value (d1);
5611       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5612         templ = value;
5613       else
5614         {
5615           if (context)
5616             push_decl_namespace (context);
5617           templ = lookup_name (d1);
5618           templ = maybe_get_template_decl_from_type_decl (templ);
5619           if (context)
5620             pop_decl_namespace ();
5621         }
5622       if (templ)
5623         context = DECL_CONTEXT (templ);
5624     }
5625   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5626     {
5627       tree type = TREE_TYPE (d1);
5628
5629       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5630          an implicit typename for the second A.  Deal with it.  */
5631       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5632         type = TREE_TYPE (type);
5633
5634       if (CLASSTYPE_TEMPLATE_INFO (type))
5635         {
5636           templ = CLASSTYPE_TI_TEMPLATE (type);
5637           d1 = DECL_NAME (templ);
5638         }
5639     }
5640   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5641            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5642     {
5643       templ = TYPE_TI_TEMPLATE (d1);
5644       d1 = DECL_NAME (templ);
5645     }
5646   else if (TREE_CODE (d1) == TEMPLATE_DECL
5647            && DECL_TEMPLATE_RESULT (d1)
5648            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5649     {
5650       templ = d1;
5651       d1 = DECL_NAME (templ);
5652       context = DECL_CONTEXT (templ);
5653     }
5654
5655   /* Issue an error message if we didn't find a template.  */
5656   if (! templ)
5657     {
5658       if (complain & tf_error)
5659         error ("%qT is not a template", d1);
5660       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5661     }
5662
5663   if (TREE_CODE (templ) != TEMPLATE_DECL
5664          /* Make sure it's a user visible template, if it was named by
5665             the user.  */
5666       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5667           && !PRIMARY_TEMPLATE_P (templ)))
5668     {
5669       if (complain & tf_error)
5670         {
5671           error ("non-template type %qT used as a template", d1);
5672           if (in_decl)
5673             error ("for template declaration %q+D", in_decl);
5674         }
5675       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5676     }
5677
5678   complain &= ~tf_user;
5679
5680   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5681     {
5682       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5683          template arguments */
5684
5685       tree parm;
5686       tree arglist2;
5687       tree outer;
5688
5689       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5690
5691       /* Consider an example where a template template parameter declared as
5692
5693            template <class T, class U = std::allocator<T> > class TT
5694
5695          The template parameter level of T and U are one level larger than
5696          of TT.  To proper process the default argument of U, say when an
5697          instantiation `TT<int>' is seen, we need to build the full
5698          arguments containing {int} as the innermost level.  Outer levels,
5699          available when not appearing as default template argument, can be
5700          obtained from the arguments of the enclosing template.
5701
5702          Suppose that TT is later substituted with std::vector.  The above
5703          instantiation is `TT<int, std::allocator<T> >' with TT at
5704          level 1, and T at level 2, while the template arguments at level 1
5705          becomes {std::vector} and the inner level 2 is {int}.  */
5706
5707       outer = DECL_CONTEXT (templ);
5708       if (outer)
5709         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5710       else if (current_template_parms)
5711         /* This is an argument of the current template, so we haven't set
5712            DECL_CONTEXT yet.  */
5713         outer = current_template_args ();
5714
5715       if (outer)
5716         arglist = add_to_template_args (outer, arglist);
5717
5718       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5719                                         complain,
5720                                         /*require_all_args=*/true,
5721                                         /*use_default_args=*/true);
5722       if (arglist2 == error_mark_node
5723           || (!uses_template_parms (arglist2)
5724               && check_instantiated_args (templ, arglist2, complain)))
5725         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5726
5727       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5728       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5729     }
5730   else
5731     {
5732       tree template_type = TREE_TYPE (templ);
5733       tree gen_tmpl;
5734       tree type_decl;
5735       tree found = NULL_TREE;
5736       int arg_depth;
5737       int parm_depth;
5738       int is_partial_instantiation;
5739
5740       gen_tmpl = most_general_template (templ);
5741       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5742       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5743       arg_depth = TMPL_ARGS_DEPTH (arglist);
5744
5745       if (arg_depth == 1 && parm_depth > 1)
5746         {
5747           /* We've been given an incomplete set of template arguments.
5748              For example, given:
5749
5750                template <class T> struct S1 {
5751                  template <class U> struct S2 {};
5752                  template <class U> struct S2<U*> {};
5753                 };
5754
5755              we will be called with an ARGLIST of `U*', but the
5756              TEMPLATE will be `template <class T> template
5757              <class U> struct S1<T>::S2'.  We must fill in the missing
5758              arguments.  */
5759           arglist
5760             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5761                                            arglist);
5762           arg_depth = TMPL_ARGS_DEPTH (arglist);
5763         }
5764
5765       /* Now we should have enough arguments.  */
5766       gcc_assert (parm_depth == arg_depth);
5767
5768       /* From here on, we're only interested in the most general
5769          template.  */
5770       templ = gen_tmpl;
5771
5772       /* Calculate the BOUND_ARGS.  These will be the args that are
5773          actually tsubst'd into the definition to create the
5774          instantiation.  */
5775       if (parm_depth > 1)
5776         {
5777           /* We have multiple levels of arguments to coerce, at once.  */
5778           int i;
5779           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5780
5781           tree bound_args = make_tree_vec (parm_depth);
5782
5783           for (i = saved_depth,
5784                  t = DECL_TEMPLATE_PARMS (templ);
5785                i > 0 && t != NULL_TREE;
5786                --i, t = TREE_CHAIN (t))
5787             {
5788               tree a = coerce_template_parms (TREE_VALUE (t),
5789                                               arglist, templ,
5790                                               complain,
5791                                               /*require_all_args=*/true,
5792                                               /*use_default_args=*/true);
5793
5794               /* Don't process further if one of the levels fails.  */
5795               if (a == error_mark_node)
5796                 {
5797                   /* Restore the ARGLIST to its full size.  */
5798                   TREE_VEC_LENGTH (arglist) = saved_depth;
5799                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5800                 }
5801
5802               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5803
5804               /* We temporarily reduce the length of the ARGLIST so
5805                  that coerce_template_parms will see only the arguments
5806                  corresponding to the template parameters it is
5807                  examining.  */
5808               TREE_VEC_LENGTH (arglist)--;
5809             }
5810
5811           /* Restore the ARGLIST to its full size.  */
5812           TREE_VEC_LENGTH (arglist) = saved_depth;
5813
5814           arglist = bound_args;
5815         }
5816       else
5817         arglist
5818           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5819                                    INNERMOST_TEMPLATE_ARGS (arglist),
5820                                    templ,
5821                                    complain,
5822                                    /*require_all_args=*/true,
5823                                    /*use_default_args=*/true);
5824
5825       if (arglist == error_mark_node)
5826         /* We were unable to bind the arguments.  */
5827         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5828
5829       /* In the scope of a template class, explicit references to the
5830          template class refer to the type of the template, not any
5831          instantiation of it.  For example, in:
5832
5833            template <class T> class C { void f(C<T>); }
5834
5835          the `C<T>' is just the same as `C'.  Outside of the
5836          class, however, such a reference is an instantiation.  */
5837       if (comp_template_args (TYPE_TI_ARGS (template_type),
5838                               arglist))
5839         {
5840           found = template_type;
5841
5842           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5843             {
5844               tree ctx;
5845
5846               for (ctx = current_class_type;
5847                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5848                    ctx = (TYPE_P (ctx)
5849                           ? TYPE_CONTEXT (ctx)
5850                           : DECL_CONTEXT (ctx)))
5851                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5852                   goto found_ctx;
5853
5854               /* We're not in the scope of the class, so the
5855                  TEMPLATE_TYPE is not the type we want after all.  */
5856               found = NULL_TREE;
5857             found_ctx:;
5858             }
5859         }
5860       if (found)
5861         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5862
5863       /* If we already have this specialization, return it.  */
5864       found = retrieve_specialization (templ, arglist,
5865                                        /*class_specializations_p=*/false);
5866       if (found)
5867         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5868
5869       /* This type is a "partial instantiation" if any of the template
5870          arguments still involve template parameters.  Note that we set
5871          IS_PARTIAL_INSTANTIATION for partial specializations as
5872          well.  */
5873       is_partial_instantiation = uses_template_parms (arglist);
5874
5875       /* If the deduced arguments are invalid, then the binding
5876          failed.  */
5877       if (!is_partial_instantiation
5878           && check_instantiated_args (templ,
5879                                       INNERMOST_TEMPLATE_ARGS (arglist),
5880                                       complain))
5881         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5882
5883       if (!is_partial_instantiation
5884           && !PRIMARY_TEMPLATE_P (templ)
5885           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5886         {
5887           found = xref_tag_from_type (TREE_TYPE (templ),
5888                                       DECL_NAME (templ),
5889                                       /*tag_scope=*/ts_global);
5890           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5891         }
5892
5893       context = tsubst (DECL_CONTEXT (templ), arglist,
5894                         complain, in_decl);
5895       if (!context)
5896         context = global_namespace;
5897
5898       /* Create the type.  */
5899       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5900         {
5901           if (!is_partial_instantiation)
5902             {
5903               set_current_access_from_decl (TYPE_NAME (template_type));
5904               t = start_enum (TYPE_IDENTIFIER (template_type),
5905                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5906                                       arglist, complain, in_decl),
5907                               SCOPED_ENUM_P (template_type));
5908             }
5909           else
5910             {
5911               /* We don't want to call start_enum for this type, since
5912                  the values for the enumeration constants may involve
5913                  template parameters.  And, no one should be interested
5914                  in the enumeration constants for such a type.  */
5915               t = make_node (ENUMERAL_TYPE);
5916               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5917             }
5918         }
5919       else
5920         {
5921           t = make_class_type (TREE_CODE (template_type));
5922           CLASSTYPE_DECLARED_CLASS (t)
5923             = CLASSTYPE_DECLARED_CLASS (template_type);
5924           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5925           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5926
5927           /* A local class.  Make sure the decl gets registered properly.  */
5928           if (context == current_function_decl)
5929             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5930
5931           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5932             /* This instantiation is another name for the primary
5933                template type. Set the TYPE_CANONICAL field
5934                appropriately. */
5935             TYPE_CANONICAL (t) = template_type;
5936           else if (any_template_arguments_need_structural_equality_p (arglist))
5937             /* Some of the template arguments require structural
5938                equality testing, so this template class requires
5939                structural equality testing. */
5940             SET_TYPE_STRUCTURAL_EQUALITY (t);
5941         }
5942
5943       /* If we called start_enum or pushtag above, this information
5944          will already be set up.  */
5945       if (!TYPE_NAME (t))
5946         {
5947           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5948
5949           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5950           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5951           TYPE_STUB_DECL (t) = type_decl;
5952           DECL_SOURCE_LOCATION (type_decl)
5953             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5954         }
5955       else
5956         type_decl = TYPE_NAME (t);
5957
5958       TREE_PRIVATE (type_decl)
5959         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5960       TREE_PROTECTED (type_decl)
5961         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5962       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5963         {
5964           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5965           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5966         }
5967
5968       /* Set up the template information.  We have to figure out which
5969          template is the immediate parent if this is a full
5970          instantiation.  */
5971       if (parm_depth == 1 || is_partial_instantiation
5972           || !PRIMARY_TEMPLATE_P (templ))
5973         /* This case is easy; there are no member templates involved.  */
5974         found = templ;
5975       else
5976         {
5977           /* This is a full instantiation of a member template.  Look
5978              for a partial instantiation of which this is an instance.  */
5979
5980           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5981                found; found = TREE_CHAIN (found))
5982             {
5983               int success;
5984               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5985
5986               /* We only want partial instantiations, here, not
5987                  specializations or full instantiations.  */
5988               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5989                   || !uses_template_parms (TREE_VALUE (found)))
5990                 continue;
5991
5992               /* Temporarily reduce by one the number of levels in the
5993                  ARGLIST and in FOUND so as to avoid comparing the
5994                  last set of arguments.  */
5995               TREE_VEC_LENGTH (arglist)--;
5996               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5997
5998               /* See if the arguments match.  If they do, then TMPL is
5999                  the partial instantiation we want.  */
6000               success = comp_template_args (TREE_PURPOSE (found), arglist);
6001
6002               /* Restore the argument vectors to their full size.  */
6003               TREE_VEC_LENGTH (arglist)++;
6004               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
6005
6006               if (success)
6007                 {
6008                   found = tmpl;
6009                   break;
6010                 }
6011             }
6012
6013           if (!found)
6014             {
6015               /* There was no partial instantiation. This happens
6016                  where C<T> is a member template of A<T> and it's used
6017                  in something like
6018
6019                   template <typename T> struct B { A<T>::C<int> m; };
6020                   B<float>;
6021
6022                  Create the partial instantiation.
6023                */
6024               TREE_VEC_LENGTH (arglist)--;
6025               found = tsubst (templ, arglist, complain, NULL_TREE);
6026               TREE_VEC_LENGTH (arglist)++;
6027             }
6028         }
6029
6030       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6031       DECL_TEMPLATE_INSTANTIATIONS (templ)
6032         = tree_cons (arglist, t,
6033                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6034
6035       if (TREE_CODE (t) == ENUMERAL_TYPE
6036           && !is_partial_instantiation)
6037         /* Now that the type has been registered on the instantiations
6038            list, we set up the enumerators.  Because the enumeration
6039            constants may involve the enumeration type itself, we make
6040            sure to register the type first, and then create the
6041            constants.  That way, doing tsubst_expr for the enumeration
6042            constants won't result in recursive calls here; we'll find
6043            the instantiation and exit above.  */
6044         tsubst_enum (template_type, t, arglist);
6045
6046       if (is_partial_instantiation)
6047         /* If the type makes use of template parameters, the
6048            code that generates debugging information will crash.  */
6049         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6050
6051       /* Possibly limit visibility based on template args.  */
6052       TREE_PUBLIC (type_decl) = 1;
6053       determine_visibility (type_decl);
6054
6055       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6056     }
6057   timevar_pop (TV_NAME_LOOKUP);
6058 }
6059 \f
6060 struct pair_fn_data
6061 {
6062   tree_fn_t fn;
6063   void *data;
6064   /* True when we should also visit template parameters that occur in
6065      non-deduced contexts.  */
6066   bool include_nondeduced_p;
6067   struct pointer_set_t *visited;
6068 };
6069
6070 /* Called from for_each_template_parm via walk_tree.  */
6071
6072 static tree
6073 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6074 {
6075   tree t = *tp;
6076   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6077   tree_fn_t fn = pfd->fn;
6078   void *data = pfd->data;
6079
6080   if (TYPE_P (t)
6081       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6082       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6083                                  pfd->include_nondeduced_p))
6084     return error_mark_node;
6085
6086   switch (TREE_CODE (t))
6087     {
6088     case RECORD_TYPE:
6089       if (TYPE_PTRMEMFUNC_P (t))
6090         break;
6091       /* Fall through.  */
6092
6093     case UNION_TYPE:
6094     case ENUMERAL_TYPE:
6095       if (!TYPE_TEMPLATE_INFO (t))
6096         *walk_subtrees = 0;
6097       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6098                                        fn, data, pfd->visited, 
6099                                        pfd->include_nondeduced_p))
6100         return error_mark_node;
6101       break;
6102
6103     case INTEGER_TYPE:
6104       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6105                                   fn, data, pfd->visited, 
6106                                   pfd->include_nondeduced_p)
6107           || for_each_template_parm (TYPE_MAX_VALUE (t),
6108                                      fn, data, pfd->visited,
6109                                      pfd->include_nondeduced_p))
6110         return error_mark_node;
6111       break;
6112
6113     case METHOD_TYPE:
6114       /* Since we're not going to walk subtrees, we have to do this
6115          explicitly here.  */
6116       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6117                                   pfd->visited, pfd->include_nondeduced_p))
6118         return error_mark_node;
6119       /* Fall through.  */
6120
6121     case FUNCTION_TYPE:
6122       /* Check the return type.  */
6123       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6124                                   pfd->include_nondeduced_p))
6125         return error_mark_node;
6126
6127       /* Check the parameter types.  Since default arguments are not
6128          instantiated until they are needed, the TYPE_ARG_TYPES may
6129          contain expressions that involve template parameters.  But,
6130          no-one should be looking at them yet.  And, once they're
6131          instantiated, they don't contain template parameters, so
6132          there's no point in looking at them then, either.  */
6133       {
6134         tree parm;
6135
6136         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6137           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6138                                       pfd->visited, pfd->include_nondeduced_p))
6139             return error_mark_node;
6140
6141         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6142            want walk_tree walking into them itself.  */
6143         *walk_subtrees = 0;
6144       }
6145       break;
6146
6147     case TYPEOF_TYPE:
6148       if (pfd->include_nondeduced_p
6149           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6150                                      pfd->visited, 
6151                                      pfd->include_nondeduced_p))
6152         return error_mark_node;
6153       break;
6154
6155     case FUNCTION_DECL:
6156     case VAR_DECL:
6157       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6158           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6159                                      pfd->visited, pfd->include_nondeduced_p))
6160         return error_mark_node;
6161       /* Fall through.  */
6162
6163     case PARM_DECL:
6164     case CONST_DECL:
6165       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6166           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6167                                      pfd->visited, pfd->include_nondeduced_p))
6168         return error_mark_node;
6169       if (DECL_CONTEXT (t)
6170           && pfd->include_nondeduced_p
6171           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6172                                      pfd->visited, pfd->include_nondeduced_p))
6173         return error_mark_node;
6174       break;
6175
6176     case BOUND_TEMPLATE_TEMPLATE_PARM:
6177       /* Record template parameters such as `T' inside `TT<T>'.  */
6178       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6179                                   pfd->include_nondeduced_p))
6180         return error_mark_node;
6181       /* Fall through.  */
6182
6183     case TEMPLATE_TEMPLATE_PARM:
6184     case TEMPLATE_TYPE_PARM:
6185     case TEMPLATE_PARM_INDEX:
6186       if (fn && (*fn)(t, data))
6187         return error_mark_node;
6188       else if (!fn)
6189         return error_mark_node;
6190       break;
6191
6192     case TEMPLATE_DECL:
6193       /* A template template parameter is encountered.  */
6194       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6195           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6196                                      pfd->include_nondeduced_p))
6197         return error_mark_node;
6198
6199       /* Already substituted template template parameter */
6200       *walk_subtrees = 0;
6201       break;
6202
6203     case TYPENAME_TYPE:
6204       if (!fn
6205           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6206                                      data, pfd->visited, 
6207                                      pfd->include_nondeduced_p))
6208         return error_mark_node;
6209       break;
6210
6211     case CONSTRUCTOR:
6212       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6213           && pfd->include_nondeduced_p
6214           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6215                                      (TREE_TYPE (t)), fn, data,
6216                                      pfd->visited, pfd->include_nondeduced_p))
6217         return error_mark_node;
6218       break;
6219
6220     case INDIRECT_REF:
6221     case COMPONENT_REF:
6222       /* If there's no type, then this thing must be some expression
6223          involving template parameters.  */
6224       if (!fn && !TREE_TYPE (t))
6225         return error_mark_node;
6226       break;
6227
6228     case MODOP_EXPR:
6229     case CAST_EXPR:
6230     case REINTERPRET_CAST_EXPR:
6231     case CONST_CAST_EXPR:
6232     case STATIC_CAST_EXPR:
6233     case DYNAMIC_CAST_EXPR:
6234     case ARROW_EXPR:
6235     case DOTSTAR_EXPR:
6236     case TYPEID_EXPR:
6237     case PSEUDO_DTOR_EXPR:
6238       if (!fn)
6239         return error_mark_node;
6240       break;
6241
6242     default:
6243       break;
6244     }
6245
6246   /* We didn't find any template parameters we liked.  */
6247   return NULL_TREE;
6248 }
6249
6250 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6251    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6252    call FN with the parameter and the DATA.
6253    If FN returns nonzero, the iteration is terminated, and
6254    for_each_template_parm returns 1.  Otherwise, the iteration
6255    continues.  If FN never returns a nonzero value, the value
6256    returned by for_each_template_parm is 0.  If FN is NULL, it is
6257    considered to be the function which always returns 1.
6258
6259    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6260    parameters that occur in non-deduced contexts.  When false, only
6261    visits those template parameters that can be deduced.  */
6262
6263 static int
6264 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6265                         struct pointer_set_t *visited,
6266                         bool include_nondeduced_p)
6267 {
6268   struct pair_fn_data pfd;
6269   int result;
6270
6271   /* Set up.  */
6272   pfd.fn = fn;
6273   pfd.data = data;
6274   pfd.include_nondeduced_p = include_nondeduced_p;
6275
6276   /* Walk the tree.  (Conceptually, we would like to walk without
6277      duplicates, but for_each_template_parm_r recursively calls
6278      for_each_template_parm, so we would need to reorganize a fair
6279      bit to use walk_tree_without_duplicates, so we keep our own
6280      visited list.)  */
6281   if (visited)
6282     pfd.visited = visited;
6283   else
6284     pfd.visited = pointer_set_create ();
6285   result = cp_walk_tree (&t,
6286                          for_each_template_parm_r,
6287                          &pfd,
6288                          pfd.visited) != NULL_TREE;
6289
6290   /* Clean up.  */
6291   if (!visited)
6292     {
6293       pointer_set_destroy (pfd.visited);
6294       pfd.visited = 0;
6295     }
6296
6297   return result;
6298 }
6299
6300 /* Returns true if T depends on any template parameter.  */
6301
6302 int
6303 uses_template_parms (tree t)
6304 {
6305   bool dependent_p;
6306   int saved_processing_template_decl;
6307
6308   saved_processing_template_decl = processing_template_decl;
6309   if (!saved_processing_template_decl)
6310     processing_template_decl = 1;
6311   if (TYPE_P (t))
6312     dependent_p = dependent_type_p (t);
6313   else if (TREE_CODE (t) == TREE_VEC)
6314     dependent_p = any_dependent_template_arguments_p (t);
6315   else if (TREE_CODE (t) == TREE_LIST)
6316     dependent_p = (uses_template_parms (TREE_VALUE (t))
6317                    || uses_template_parms (TREE_CHAIN (t)));
6318   else if (TREE_CODE (t) == TYPE_DECL)
6319     dependent_p = dependent_type_p (TREE_TYPE (t));
6320   else if (DECL_P (t)
6321            || EXPR_P (t)
6322            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6323            || TREE_CODE (t) == OVERLOAD
6324            || TREE_CODE (t) == BASELINK
6325            || TREE_CODE (t) == IDENTIFIER_NODE
6326            || TREE_CODE (t) == TRAIT_EXPR
6327            || TREE_CODE (t) == CONSTRUCTOR
6328            || CONSTANT_CLASS_P (t))
6329     dependent_p = (type_dependent_expression_p (t)
6330                    || value_dependent_expression_p (t));
6331   else
6332     {
6333       gcc_assert (t == error_mark_node);
6334       dependent_p = false;
6335     }
6336
6337   processing_template_decl = saved_processing_template_decl;
6338
6339   return dependent_p;
6340 }
6341
6342 /* Returns true if T depends on any template parameter with level LEVEL.  */
6343
6344 int
6345 uses_template_parms_level (tree t, int level)
6346 {
6347   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6348                                  /*include_nondeduced_p=*/true);
6349 }
6350
6351 static int tinst_depth;
6352 extern int max_tinst_depth;
6353 #ifdef GATHER_STATISTICS
6354 int depth_reached;
6355 #endif
6356 static int tinst_level_tick;
6357 static int last_template_error_tick;
6358
6359 /* We're starting to instantiate D; record the template instantiation context
6360    for diagnostics and to restore it later.  */
6361
6362 static int
6363 push_tinst_level (tree d)
6364 {
6365   struct tinst_level *new_level;
6366
6367   if (tinst_depth >= max_tinst_depth)
6368     {
6369       /* If the instantiation in question still has unbound template parms,
6370          we don't really care if we can't instantiate it, so just return.
6371          This happens with base instantiation for implicit `typename'.  */
6372       if (uses_template_parms (d))
6373         return 0;
6374
6375       last_template_error_tick = tinst_level_tick;
6376       error ("template instantiation depth exceeds maximum of %d (use "
6377              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6378              max_tinst_depth, d);
6379
6380       print_instantiation_context ();
6381
6382       return 0;
6383     }
6384
6385   new_level = GGC_NEW (struct tinst_level);
6386   new_level->decl = d;
6387   new_level->locus = input_location;
6388   new_level->in_system_header_p = in_system_header;
6389   new_level->next = current_tinst_level;
6390   current_tinst_level = new_level;
6391
6392   ++tinst_depth;
6393 #ifdef GATHER_STATISTICS
6394   if (tinst_depth > depth_reached)
6395     depth_reached = tinst_depth;
6396 #endif
6397
6398   ++tinst_level_tick;
6399   return 1;
6400 }
6401
6402 /* We're done instantiating this template; return to the instantiation
6403    context.  */
6404
6405 static void
6406 pop_tinst_level (void)
6407 {
6408   /* Restore the filename and line number stashed away when we started
6409      this instantiation.  */
6410   input_location = current_tinst_level->locus;
6411   current_tinst_level = current_tinst_level->next;
6412   --tinst_depth;
6413   ++tinst_level_tick;
6414 }
6415
6416 /* We're instantiating a deferred template; restore the template
6417    instantiation context in which the instantiation was requested, which
6418    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6419
6420 static tree
6421 reopen_tinst_level (struct tinst_level *level)
6422 {
6423   struct tinst_level *t;
6424
6425   tinst_depth = 0;
6426   for (t = level; t; t = t->next)
6427     ++tinst_depth;
6428
6429   current_tinst_level = level;
6430   pop_tinst_level ();
6431   return level->decl;
6432 }
6433
6434 /* Returns the TINST_LEVEL which gives the original instantiation
6435    context.  */
6436
6437 struct tinst_level *
6438 outermost_tinst_level (void)
6439 {
6440   struct tinst_level *level = current_tinst_level;
6441   if (level)
6442     while (level->next)
6443       level = level->next;
6444   return level;
6445 }
6446
6447 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6448
6449 bool
6450 parameter_of_template_p (tree parm, tree templ)
6451 {
6452   tree parms;
6453   int i;
6454
6455   if (!parm || !templ)
6456     return false;
6457
6458   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6459   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6460
6461   parms = DECL_TEMPLATE_PARMS (templ);
6462   parms = INNERMOST_TEMPLATE_PARMS (parms);
6463
6464   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6465     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6466       return true;
6467
6468   return false;
6469 }
6470
6471 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6472    vector of template arguments, as for tsubst.
6473
6474    Returns an appropriate tsubst'd friend declaration.  */
6475
6476 static tree
6477 tsubst_friend_function (tree decl, tree args)
6478 {
6479   tree new_friend;
6480
6481   if (TREE_CODE (decl) == FUNCTION_DECL
6482       && DECL_TEMPLATE_INSTANTIATION (decl)
6483       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6484     /* This was a friend declared with an explicit template
6485        argument list, e.g.:
6486
6487        friend void f<>(T);
6488
6489        to indicate that f was a template instantiation, not a new
6490        function declaration.  Now, we have to figure out what
6491        instantiation of what template.  */
6492     {
6493       tree template_id, arglist, fns;
6494       tree new_args;
6495       tree tmpl;
6496       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6497
6498       /* Friend functions are looked up in the containing namespace scope.
6499          We must enter that scope, to avoid finding member functions of the
6500          current class with same name.  */
6501       push_nested_namespace (ns);
6502       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6503                          tf_warning_or_error, NULL_TREE,
6504                          /*integral_constant_expression_p=*/false);
6505       pop_nested_namespace (ns);
6506       arglist = tsubst (DECL_TI_ARGS (decl), args,
6507                         tf_warning_or_error, NULL_TREE);
6508       template_id = lookup_template_function (fns, arglist);
6509
6510       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6511       tmpl = determine_specialization (template_id, new_friend,
6512                                        &new_args,
6513                                        /*need_member_template=*/0,
6514                                        TREE_VEC_LENGTH (args),
6515                                        tsk_none);
6516       return instantiate_template (tmpl, new_args, tf_error);
6517     }
6518
6519   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6520
6521   /* The NEW_FRIEND will look like an instantiation, to the
6522      compiler, but is not an instantiation from the point of view of
6523      the language.  For example, we might have had:
6524
6525      template <class T> struct S {
6526        template <class U> friend void f(T, U);
6527      };
6528
6529      Then, in S<int>, template <class U> void f(int, U) is not an
6530      instantiation of anything.  */
6531   if (new_friend == error_mark_node)
6532     return error_mark_node;
6533
6534   DECL_USE_TEMPLATE (new_friend) = 0;
6535   if (TREE_CODE (decl) == TEMPLATE_DECL)
6536     {
6537       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6538       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6539         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6540     }
6541
6542   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6543      is not a template instantiation and should not be mangled like
6544      one.  Therefore, we forget the mangling here; we'll recompute it
6545      later if we need it.  */
6546   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6547     {
6548       SET_DECL_RTL (new_friend, NULL_RTX);
6549       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6550     }
6551
6552   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6553     {
6554       tree old_decl;
6555       tree new_friend_template_info;
6556       tree new_friend_result_template_info;
6557       tree ns;
6558       int  new_friend_is_defn;
6559
6560       /* We must save some information from NEW_FRIEND before calling
6561          duplicate decls since that function will free NEW_FRIEND if
6562          possible.  */
6563       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6564       new_friend_is_defn =
6565             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6566                            (template_for_substitution (new_friend)))
6567              != NULL_TREE);
6568       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6569         {
6570           /* This declaration is a `primary' template.  */
6571           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6572
6573           new_friend_result_template_info
6574             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6575         }
6576       else
6577         new_friend_result_template_info = NULL_TREE;
6578
6579       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6580       if (new_friend_is_defn)
6581         DECL_INITIAL (new_friend) = error_mark_node;
6582
6583       /* Inside pushdecl_namespace_level, we will push into the
6584          current namespace. However, the friend function should go
6585          into the namespace of the template.  */
6586       ns = decl_namespace_context (new_friend);
6587       push_nested_namespace (ns);
6588       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6589       pop_nested_namespace (ns);
6590
6591       if (old_decl == error_mark_node)
6592         return error_mark_node;
6593
6594       if (old_decl != new_friend)
6595         {
6596           /* This new friend declaration matched an existing
6597              declaration.  For example, given:
6598
6599                template <class T> void f(T);
6600                template <class U> class C {
6601                  template <class T> friend void f(T) {}
6602                };
6603
6604              the friend declaration actually provides the definition
6605              of `f', once C has been instantiated for some type.  So,
6606              old_decl will be the out-of-class template declaration,
6607              while new_friend is the in-class definition.
6608
6609              But, if `f' was called before this point, the
6610              instantiation of `f' will have DECL_TI_ARGS corresponding
6611              to `T' but not to `U', references to which might appear
6612              in the definition of `f'.  Previously, the most general
6613              template for an instantiation of `f' was the out-of-class
6614              version; now it is the in-class version.  Therefore, we
6615              run through all specialization of `f', adding to their
6616              DECL_TI_ARGS appropriately.  In particular, they need a
6617              new set of outer arguments, corresponding to the
6618              arguments for this class instantiation.
6619
6620              The same situation can arise with something like this:
6621
6622                friend void f(int);
6623                template <class T> class C {
6624                  friend void f(T) {}
6625                };
6626
6627              when `C<int>' is instantiated.  Now, `f(int)' is defined
6628              in the class.  */
6629
6630           if (!new_friend_is_defn)
6631             /* On the other hand, if the in-class declaration does
6632                *not* provide a definition, then we don't want to alter
6633                existing definitions.  We can just leave everything
6634                alone.  */
6635             ;
6636           else
6637             {
6638               /* Overwrite whatever template info was there before, if
6639                  any, with the new template information pertaining to
6640                  the declaration.  */
6641               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6642
6643               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6644                 reregister_specialization (new_friend,
6645                                            most_general_template (old_decl),
6646                                            old_decl);
6647               else
6648                 {
6649                   tree t;
6650                   tree new_friend_args;
6651
6652                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6653                     = new_friend_result_template_info;
6654
6655                   new_friend_args = TI_ARGS (new_friend_template_info);
6656                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6657                        t != NULL_TREE;
6658                        t = TREE_CHAIN (t))
6659                     {
6660                       tree spec = TREE_VALUE (t);
6661
6662                       DECL_TI_ARGS (spec)
6663                         = add_outermost_template_args (new_friend_args,
6664                                                        DECL_TI_ARGS (spec));
6665                     }
6666
6667                   /* Now, since specializations are always supposed to
6668                      hang off of the most general template, we must move
6669                      them.  */
6670                   t = most_general_template (old_decl);
6671                   if (t != old_decl)
6672                     {
6673                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6674                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6675                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6676                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6677                     }
6678                 }
6679             }
6680
6681           /* The information from NEW_FRIEND has been merged into OLD_DECL
6682              by duplicate_decls.  */
6683           new_friend = old_decl;
6684         }
6685     }
6686   else
6687     {
6688       tree context = DECL_CONTEXT (new_friend);
6689       bool dependent_p;
6690
6691       /* In the code
6692            template <class T> class C {
6693              template <class U> friend void C1<U>::f (); // case 1
6694              friend void C2<T>::f ();                    // case 2
6695            };
6696          we only need to make sure CONTEXT is a complete type for
6697          case 2.  To distinguish between the two cases, we note that
6698          CONTEXT of case 1 remains dependent type after tsubst while
6699          this isn't true for case 2.  */
6700       ++processing_template_decl;
6701       dependent_p = dependent_type_p (context);
6702       --processing_template_decl;
6703
6704       if (!dependent_p
6705           && !complete_type_or_else (context, NULL_TREE))
6706         return error_mark_node;
6707
6708       if (COMPLETE_TYPE_P (context))
6709         {
6710           /* Check to see that the declaration is really present, and,
6711              possibly obtain an improved declaration.  */
6712           tree fn = check_classfn (context,
6713                                    new_friend, NULL_TREE);
6714
6715           if (fn)
6716             new_friend = fn;
6717         }
6718     }
6719
6720   return new_friend;
6721 }
6722
6723 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6724    template arguments, as for tsubst.
6725
6726    Returns an appropriate tsubst'd friend type or error_mark_node on
6727    failure.  */
6728
6729 static tree
6730 tsubst_friend_class (tree friend_tmpl, tree args)
6731 {
6732   tree friend_type;
6733   tree tmpl;
6734   tree context;
6735
6736   context = DECL_CONTEXT (friend_tmpl);
6737
6738   if (context)
6739     {
6740       if (TREE_CODE (context) == NAMESPACE_DECL)
6741         push_nested_namespace (context);
6742       else
6743         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6744     }
6745
6746   /* Look for a class template declaration.  We look for hidden names
6747      because two friend declarations of the same template are the
6748      same.  For example, in:
6749
6750        struct A { 
6751          template <typename> friend class F;
6752        };
6753        template <typename> struct B { 
6754          template <typename> friend class F;
6755        };
6756
6757      both F templates are the same.  */
6758   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6759                            /*block_p=*/true, 0, 
6760                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6761
6762   /* But, if we don't find one, it might be because we're in a
6763      situation like this:
6764
6765        template <class T>
6766        struct S {
6767          template <class U>
6768          friend struct S;
6769        };
6770
6771      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6772      for `S<int>', not the TEMPLATE_DECL.  */
6773   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6774     {
6775       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6776       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6777     }
6778
6779   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6780     {
6781       /* The friend template has already been declared.  Just
6782          check to see that the declarations match, and install any new
6783          default parameters.  We must tsubst the default parameters,
6784          of course.  We only need the innermost template parameters
6785          because that is all that redeclare_class_template will look
6786          at.  */
6787       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6788           > TMPL_ARGS_DEPTH (args))
6789         {
6790           tree parms;
6791           location_t saved_input_location;
6792           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6793                                          args, tf_warning_or_error);
6794
6795           saved_input_location = input_location;
6796           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6797           redeclare_class_template (TREE_TYPE (tmpl), parms);
6798           input_location = saved_input_location;
6799           
6800         }
6801
6802       friend_type = TREE_TYPE (tmpl);
6803     }
6804   else
6805     {
6806       /* The friend template has not already been declared.  In this
6807          case, the instantiation of the template class will cause the
6808          injection of this template into the global scope.  */
6809       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6810       if (tmpl == error_mark_node)
6811         return error_mark_node;
6812
6813       /* The new TMPL is not an instantiation of anything, so we
6814          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6815          the new type because that is supposed to be the corresponding
6816          template decl, i.e., TMPL.  */
6817       DECL_USE_TEMPLATE (tmpl) = 0;
6818       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6819       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6820       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6821         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6822
6823       /* Inject this template into the global scope.  */
6824       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6825     }
6826
6827   if (context)
6828     {
6829       if (TREE_CODE (context) == NAMESPACE_DECL)
6830         pop_nested_namespace (context);
6831       else
6832         pop_nested_class ();
6833     }
6834
6835   return friend_type;
6836 }
6837
6838 /* Returns zero if TYPE cannot be completed later due to circularity.
6839    Otherwise returns one.  */
6840
6841 static int
6842 can_complete_type_without_circularity (tree type)
6843 {
6844   if (type == NULL_TREE || type == error_mark_node)
6845     return 0;
6846   else if (COMPLETE_TYPE_P (type))
6847     return 1;
6848   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6849     return can_complete_type_without_circularity (TREE_TYPE (type));
6850   else if (CLASS_TYPE_P (type)
6851            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6852     return 0;
6853   else
6854     return 1;
6855 }
6856
6857 /* Apply any attributes which had to be deferred until instantiation
6858    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6859    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6860
6861 static void
6862 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6863                                 tree args, tsubst_flags_t complain, tree in_decl)
6864 {
6865   tree last_dep = NULL_TREE;
6866   tree t;
6867   tree *p;
6868
6869   for (t = attributes; t; t = TREE_CHAIN (t))
6870     if (ATTR_IS_DEPENDENT (t))
6871       {
6872         last_dep = t;
6873         attributes = copy_list (attributes);
6874         break;
6875       }
6876
6877   if (DECL_P (*decl_p))
6878     {
6879       if (TREE_TYPE (*decl_p) == error_mark_node)
6880         return;
6881       p = &DECL_ATTRIBUTES (*decl_p);
6882     }
6883   else
6884     p = &TYPE_ATTRIBUTES (*decl_p);
6885
6886   if (last_dep)
6887     {
6888       tree late_attrs = NULL_TREE;
6889       tree *q = &late_attrs;
6890
6891       for (*p = attributes; *p; )
6892         {
6893           t = *p;
6894           if (ATTR_IS_DEPENDENT (t))
6895             {
6896               *p = TREE_CHAIN (t);
6897               TREE_CHAIN (t) = NULL_TREE;
6898               /* If the first attribute argument is an identifier, don't
6899                  pass it through tsubst.  Attributes like mode, format,
6900                  cleanup and several target specific attributes expect it
6901                  unmodified.  */
6902               if (TREE_VALUE (t)
6903                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6904                   && TREE_VALUE (TREE_VALUE (t))
6905                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6906                       == IDENTIFIER_NODE))
6907                 {
6908                   tree chain
6909                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6910                                    in_decl,
6911                                    /*integral_constant_expression_p=*/false);
6912                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6913                     TREE_VALUE (t)
6914                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6915                                    chain);
6916                 }
6917               else
6918                 TREE_VALUE (t)
6919                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6920                                  /*integral_constant_expression_p=*/false);
6921               *q = t;
6922               q = &TREE_CHAIN (t);
6923             }
6924           else
6925             p = &TREE_CHAIN (t);
6926         }
6927
6928       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6929     }
6930 }
6931
6932 tree
6933 instantiate_class_template (tree type)
6934 {
6935   tree templ, args, pattern, t, member;
6936   tree typedecl;
6937   tree pbinfo;
6938   tree base_list;
6939
6940   if (type == error_mark_node)
6941     return error_mark_node;
6942
6943   if (TYPE_BEING_DEFINED (type)
6944       || COMPLETE_TYPE_P (type)
6945       || dependent_type_p (type))
6946     return type;
6947
6948   /* Figure out which template is being instantiated.  */
6949   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6950   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6951
6952   /* Determine what specialization of the original template to
6953      instantiate.  */
6954   t = most_specialized_class (type, templ);
6955   if (t == error_mark_node)
6956     {
6957       TYPE_BEING_DEFINED (type) = 1;
6958       return error_mark_node;
6959     }
6960   else if (t)
6961     {
6962       /* This TYPE is actually an instantiation of a partial
6963          specialization.  We replace the innermost set of ARGS with
6964          the arguments appropriate for substitution.  For example,
6965          given:
6966
6967            template <class T> struct S {};
6968            template <class T> struct S<T*> {};
6969
6970          and supposing that we are instantiating S<int*>, ARGS will
6971          presently be {int*} -- but we need {int}.  */
6972       pattern = TREE_TYPE (t);
6973       args = TREE_PURPOSE (t);
6974     }
6975   else
6976     {
6977       pattern = TREE_TYPE (templ);
6978       args = CLASSTYPE_TI_ARGS (type);
6979     }
6980
6981   /* If the template we're instantiating is incomplete, then clearly
6982      there's nothing we can do.  */
6983   if (!COMPLETE_TYPE_P (pattern))
6984     return type;
6985
6986   /* If we've recursively instantiated too many templates, stop.  */
6987   if (! push_tinst_level (type))
6988     return type;
6989
6990   /* Now we're really doing the instantiation.  Mark the type as in
6991      the process of being defined.  */
6992   TYPE_BEING_DEFINED (type) = 1;
6993
6994   /* We may be in the middle of deferred access check.  Disable
6995      it now.  */
6996   push_deferring_access_checks (dk_no_deferred);
6997
6998   push_to_top_level ();
6999
7000   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7001
7002   /* Set the input location to the template definition. This is needed
7003      if tsubsting causes an error.  */
7004   typedecl = TYPE_MAIN_DECL (type);
7005   input_location = DECL_SOURCE_LOCATION (typedecl);
7006
7007   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7008   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7009   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7010   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7011   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7012   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7013   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7014   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7015   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7016   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7017   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7018   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7019   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7020   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7021   if (ANON_AGGR_TYPE_P (pattern))
7022     SET_ANON_AGGR_TYPE_P (type);
7023   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7024     {
7025       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7026       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7027     }
7028
7029   pbinfo = TYPE_BINFO (pattern);
7030
7031   /* We should never instantiate a nested class before its enclosing
7032      class; we need to look up the nested class by name before we can
7033      instantiate it, and that lookup should instantiate the enclosing
7034      class.  */
7035   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7036               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7037               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7038
7039   base_list = NULL_TREE;
7040   if (BINFO_N_BASE_BINFOS (pbinfo))
7041     {
7042       tree pbase_binfo;
7043       tree context = TYPE_CONTEXT (type);
7044       tree pushed_scope;
7045       int i;
7046
7047       /* We must enter the scope containing the type, as that is where
7048          the accessibility of types named in dependent bases are
7049          looked up from.  */
7050       pushed_scope = push_scope (context ? context : global_namespace);
7051
7052       /* Substitute into each of the bases to determine the actual
7053          basetypes.  */
7054       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7055         {
7056           tree base;
7057           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7058           tree expanded_bases = NULL_TREE;
7059           int idx, len = 1;
7060
7061           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7062             {
7063               expanded_bases = 
7064                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7065                                        args, tf_error, NULL_TREE);
7066               if (expanded_bases == error_mark_node)
7067                 continue;
7068
7069               len = TREE_VEC_LENGTH (expanded_bases);
7070             }
7071
7072           for (idx = 0; idx < len; idx++)
7073             {
7074               if (expanded_bases)
7075                 /* Extract the already-expanded base class.  */
7076                 base = TREE_VEC_ELT (expanded_bases, idx);
7077               else
7078                 /* Substitute to figure out the base class.  */
7079                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7080                                NULL_TREE);
7081
7082               if (base == error_mark_node)
7083                 continue;
7084
7085               base_list = tree_cons (access, base, base_list);
7086               if (BINFO_VIRTUAL_P (pbase_binfo))
7087                 TREE_TYPE (base_list) = integer_type_node;
7088             }
7089         }
7090
7091       /* The list is now in reverse order; correct that.  */
7092       base_list = nreverse (base_list);
7093
7094       if (pushed_scope)
7095         pop_scope (pushed_scope);
7096     }
7097   /* Now call xref_basetypes to set up all the base-class
7098      information.  */
7099   xref_basetypes (type, base_list);
7100
7101   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7102                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7103                                   args, tf_error, NULL_TREE);
7104
7105   /* Now that our base classes are set up, enter the scope of the
7106      class, so that name lookups into base classes, etc. will work
7107      correctly.  This is precisely analogous to what we do in
7108      begin_class_definition when defining an ordinary non-template
7109      class, except we also need to push the enclosing classes.  */
7110   push_nested_class (type);
7111
7112   /* Now members are processed in the order of declaration.  */
7113   for (member = CLASSTYPE_DECL_LIST (pattern);
7114        member; member = TREE_CHAIN (member))
7115     {
7116       tree t = TREE_VALUE (member);
7117
7118       if (TREE_PURPOSE (member))
7119         {
7120           if (TYPE_P (t))
7121             {
7122               /* Build new CLASSTYPE_NESTED_UTDS.  */
7123
7124               tree newtag;
7125               bool class_template_p;
7126
7127               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7128                                   && TYPE_LANG_SPECIFIC (t)
7129                                   && CLASSTYPE_IS_TEMPLATE (t));
7130               /* If the member is a class template, then -- even after
7131                  substitution -- there may be dependent types in the
7132                  template argument list for the class.  We increment
7133                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7134                  that function will assume that no types are dependent
7135                  when outside of a template.  */
7136               if (class_template_p)
7137                 ++processing_template_decl;
7138               newtag = tsubst (t, args, tf_error, NULL_TREE);
7139               if (class_template_p)
7140                 --processing_template_decl;
7141               if (newtag == error_mark_node)
7142                 continue;
7143
7144               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7145                 {
7146                   tree name = TYPE_IDENTIFIER (t);
7147
7148                   if (class_template_p)
7149                     /* Unfortunately, lookup_template_class sets
7150                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7151                        instantiation (i.e., for the type of a member
7152                        template class nested within a template class.)
7153                        This behavior is required for
7154                        maybe_process_partial_specialization to work
7155                        correctly, but is not accurate in this case;
7156                        the TAG is not an instantiation of anything.
7157                        (The corresponding TEMPLATE_DECL is an
7158                        instantiation, but the TYPE is not.) */
7159                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7160
7161                   /* Now, we call pushtag to put this NEWTAG into the scope of
7162                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7163                      pushtag calling push_template_decl.  We don't have to do
7164                      this for enums because it will already have been done in
7165                      tsubst_enum.  */
7166                   if (name)
7167                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7168                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7169                 }
7170             }
7171           else if (TREE_CODE (t) == FUNCTION_DECL
7172                    || DECL_FUNCTION_TEMPLATE_P (t))
7173             {
7174               /* Build new TYPE_METHODS.  */
7175               tree r;
7176
7177               if (TREE_CODE (t) == TEMPLATE_DECL)
7178                 ++processing_template_decl;
7179               r = tsubst (t, args, tf_error, NULL_TREE);
7180               if (TREE_CODE (t) == TEMPLATE_DECL)
7181                 --processing_template_decl;
7182               set_current_access_from_decl (r);
7183               finish_member_declaration (r);
7184             }
7185           else
7186             {
7187               /* Build new TYPE_FIELDS.  */
7188               if (TREE_CODE (t) == STATIC_ASSERT)
7189                 {
7190                   tree condition = 
7191                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7192                                  tf_warning_or_error, NULL_TREE,
7193                                  /*integral_constant_expression_p=*/true);
7194                   finish_static_assert (condition,
7195                                         STATIC_ASSERT_MESSAGE (t), 
7196                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7197                                         /*member_p=*/true);
7198                 }
7199               else if (TREE_CODE (t) != CONST_DECL)
7200                 {
7201                   tree r;
7202
7203                   /* The file and line for this declaration, to
7204                      assist in error message reporting.  Since we
7205                      called push_tinst_level above, we don't need to
7206                      restore these.  */
7207                   input_location = DECL_SOURCE_LOCATION (t);
7208
7209                   if (TREE_CODE (t) == TEMPLATE_DECL)
7210                     ++processing_template_decl;
7211                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7212                   if (TREE_CODE (t) == TEMPLATE_DECL)
7213                     --processing_template_decl;
7214                   if (TREE_CODE (r) == VAR_DECL)
7215                     {
7216                       /* In [temp.inst]:
7217
7218                            [t]he initialization (and any associated
7219                            side-effects) of a static data member does
7220                            not occur unless the static data member is
7221                            itself used in a way that requires the
7222                            definition of the static data member to
7223                            exist.
7224
7225                          Therefore, we do not substitute into the
7226                          initialized for the static data member here.  */
7227                       finish_static_data_member_decl
7228                         (r,
7229                          /*init=*/NULL_TREE,
7230                          /*init_const_expr_p=*/false,
7231                          /*asmspec_tree=*/NULL_TREE,
7232                          /*flags=*/0);
7233                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7234                         check_static_variable_definition (r, TREE_TYPE (r));
7235                     }
7236                   else if (TREE_CODE (r) == FIELD_DECL)
7237                     {
7238                       /* Determine whether R has a valid type and can be
7239                          completed later.  If R is invalid, then it is
7240                          replaced by error_mark_node so that it will not be
7241                          added to TYPE_FIELDS.  */
7242                       tree rtype = TREE_TYPE (r);
7243                       if (can_complete_type_without_circularity (rtype))
7244                         complete_type (rtype);
7245
7246                       if (!COMPLETE_TYPE_P (rtype))
7247                         {
7248                           cxx_incomplete_type_error (r, rtype);
7249                           r = error_mark_node;
7250                         }
7251                     }
7252
7253                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7254                      such a thing will already have been added to the field
7255                      list by tsubst_enum in finish_member_declaration in the
7256                      CLASSTYPE_NESTED_UTDS case above.  */
7257                   if (!(TREE_CODE (r) == TYPE_DECL
7258                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7259                         && DECL_ARTIFICIAL (r)))
7260                     {
7261                       set_current_access_from_decl (r);
7262                       finish_member_declaration (r);
7263                     }
7264                 }
7265             }
7266         }
7267       else
7268         {
7269           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7270             {
7271               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7272
7273               tree friend_type = t;
7274               bool adjust_processing_template_decl = false;
7275
7276               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7277                 {
7278                   /* template <class T> friend class C;  */
7279                   friend_type = tsubst_friend_class (friend_type, args);
7280                   adjust_processing_template_decl = true;
7281                 }
7282               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7283                 {
7284                   /* template <class T> friend class C::D;  */
7285                   friend_type = tsubst (friend_type, args,
7286                                         tf_warning_or_error, NULL_TREE);
7287                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7288                     friend_type = TREE_TYPE (friend_type);
7289                   adjust_processing_template_decl = true;
7290                 }
7291               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7292                 {
7293                   /* This could be either
7294
7295                        friend class T::C;
7296
7297                      when dependent_type_p is false or
7298
7299                        template <class U> friend class T::C;
7300
7301                      otherwise.  */
7302                   friend_type = tsubst (friend_type, args,
7303                                         tf_warning_or_error, NULL_TREE);
7304                   /* Bump processing_template_decl for correct
7305                      dependent_type_p calculation.  */
7306                   ++processing_template_decl;
7307                   if (dependent_type_p (friend_type))
7308                     adjust_processing_template_decl = true;
7309                   --processing_template_decl;
7310                 }
7311               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7312                        && hidden_name_p (TYPE_NAME (friend_type)))
7313                 {
7314                   /* friend class C;
7315
7316                      where C hasn't been declared yet.  Let's lookup name
7317                      from namespace scope directly, bypassing any name that
7318                      come from dependent base class.  */
7319                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7320
7321                   /* The call to xref_tag_from_type does injection for friend
7322                      classes.  */
7323                   push_nested_namespace (ns);
7324                   friend_type =
7325                     xref_tag_from_type (friend_type, NULL_TREE,
7326                                         /*tag_scope=*/ts_current);
7327                   pop_nested_namespace (ns);
7328                 }
7329               else if (uses_template_parms (friend_type))
7330                 /* friend class C<T>;  */
7331                 friend_type = tsubst (friend_type, args,
7332                                       tf_warning_or_error, NULL_TREE);
7333               /* Otherwise it's
7334
7335                    friend class C;
7336
7337                  where C is already declared or
7338
7339                    friend class C<int>;
7340
7341                  We don't have to do anything in these cases.  */
7342
7343               if (adjust_processing_template_decl)
7344                 /* Trick make_friend_class into realizing that the friend
7345                    we're adding is a template, not an ordinary class.  It's
7346                    important that we use make_friend_class since it will
7347                    perform some error-checking and output cross-reference
7348                    information.  */
7349                 ++processing_template_decl;
7350
7351               if (friend_type != error_mark_node)
7352                 make_friend_class (type, friend_type, /*complain=*/false);
7353
7354               if (adjust_processing_template_decl)
7355                 --processing_template_decl;
7356             }
7357           else
7358             {
7359               /* Build new DECL_FRIENDLIST.  */
7360               tree r;
7361
7362               /* The file and line for this declaration, to
7363                  assist in error message reporting.  Since we
7364                  called push_tinst_level above, we don't need to
7365                  restore these.  */
7366               input_location = DECL_SOURCE_LOCATION (t);
7367
7368               if (TREE_CODE (t) == TEMPLATE_DECL)
7369                 {
7370                   ++processing_template_decl;
7371                   push_deferring_access_checks (dk_no_check);
7372                 }
7373
7374               r = tsubst_friend_function (t, args);
7375               add_friend (type, r, /*complain=*/false);
7376               if (TREE_CODE (t) == TEMPLATE_DECL)
7377                 {
7378                   pop_deferring_access_checks ();
7379                   --processing_template_decl;
7380                 }
7381             }
7382         }
7383     }
7384
7385   /* Set the file and line number information to whatever is given for
7386      the class itself.  This puts error messages involving generated
7387      implicit functions at a predictable point, and the same point
7388      that would be used for non-template classes.  */
7389   input_location = DECL_SOURCE_LOCATION (typedecl);
7390
7391   unreverse_member_declarations (type);
7392   finish_struct_1 (type);
7393   TYPE_BEING_DEFINED (type) = 0;
7394
7395   /* Now that the class is complete, instantiate default arguments for
7396      any member functions.  We don't do this earlier because the
7397      default arguments may reference members of the class.  */
7398   if (!PRIMARY_TEMPLATE_P (templ))
7399     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7400       if (TREE_CODE (t) == FUNCTION_DECL
7401           /* Implicitly generated member functions will not have template
7402              information; they are not instantiations, but instead are
7403              created "fresh" for each instantiation.  */
7404           && DECL_TEMPLATE_INFO (t))
7405         tsubst_default_arguments (t);
7406
7407   pop_nested_class ();
7408   pop_from_top_level ();
7409   pop_deferring_access_checks ();
7410   pop_tinst_level ();
7411
7412   /* The vtable for a template class can be emitted in any translation
7413      unit in which the class is instantiated.  When there is no key
7414      method, however, finish_struct_1 will already have added TYPE to
7415      the keyed_classes list.  */
7416   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7417     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7418
7419   return type;
7420 }
7421
7422 static tree
7423 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7424 {
7425   tree r;
7426
7427   if (!t)
7428     r = t;
7429   else if (TYPE_P (t))
7430     r = tsubst (t, args, complain, in_decl);
7431   else
7432     {
7433       r = tsubst_expr (t, args, complain, in_decl,
7434                        /*integral_constant_expression_p=*/true);
7435       r = fold_non_dependent_expr (r);
7436     }
7437   return r;
7438 }
7439
7440 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7441    NONTYPE_ARGUMENT_PACK.  */
7442
7443 static tree
7444 make_fnparm_pack (tree spec_parm)
7445 {
7446   /* Collect all of the extra "packed" parameters into an
7447      argument pack.  */
7448   tree parmvec;
7449   tree parmtypevec;
7450   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7451   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7452   int i, len = list_length (spec_parm);
7453
7454   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7455   parmvec = make_tree_vec (len);
7456   parmtypevec = make_tree_vec (len);
7457   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7458     {
7459       TREE_VEC_ELT (parmvec, i) = spec_parm;
7460       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7461     }
7462
7463   /* Build the argument packs.  */
7464   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7465   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7466   TREE_TYPE (argpack) = argtypepack;
7467
7468   return argpack;
7469 }        
7470
7471 /* Substitute ARGS into T, which is an pack expansion
7472    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7473    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7474    (if only a partial substitution could be performed) or
7475    ERROR_MARK_NODE if there was an error.  */
7476 tree
7477 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7478                        tree in_decl)
7479 {
7480   tree pattern;
7481   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7482   tree first_arg_pack; int i, len = -1;
7483   tree result;
7484   int incomplete = 0;
7485   bool very_local_specializations = false;
7486
7487   gcc_assert (PACK_EXPANSION_P (t));
7488   pattern = PACK_EXPANSION_PATTERN (t);
7489
7490   /* Determine the argument packs that will instantiate the parameter
7491      packs used in the expansion expression. While we're at it,
7492      compute the number of arguments to be expanded and make sure it
7493      is consistent.  */
7494   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7495        pack = TREE_CHAIN (pack))
7496     {
7497       tree parm_pack = TREE_VALUE (pack);
7498       tree arg_pack = NULL_TREE;
7499       tree orig_arg = NULL_TREE;
7500
7501       if (TREE_CODE (parm_pack) == PARM_DECL)
7502         {
7503           arg_pack = retrieve_local_specialization (parm_pack);
7504           if (arg_pack == NULL_TREE)
7505             {
7506               /* This can happen for a parameter name used later in a function
7507                  declaration (such as in a late-specified return type).  Just
7508                  make a dummy decl, since it's only used for its type.  */
7509               gcc_assert (skip_evaluation);
7510               arg_pack = tsubst_decl (parm_pack, args, complain);
7511               arg_pack = make_fnparm_pack (arg_pack);
7512             }
7513         }
7514       else
7515         {
7516           int level, idx, levels;
7517           template_parm_level_and_index (parm_pack, &level, &idx);
7518
7519           levels = TMPL_ARGS_DEPTH (args);
7520           if (level <= levels)
7521             arg_pack = TMPL_ARG (args, level, idx);
7522         }
7523
7524       orig_arg = arg_pack;
7525       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7526         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7527       
7528       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7529         /* This can only happen if we forget to expand an argument
7530            pack somewhere else. Just return an error, silently.  */
7531         {
7532           result = make_tree_vec (1);
7533           TREE_VEC_ELT (result, 0) = error_mark_node;
7534           return result;
7535         }
7536
7537       if (arg_pack
7538           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7539           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7540         {
7541           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7542           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7543           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7544               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7545             /* The argument pack that the parameter maps to is just an
7546                expansion of the parameter itself, such as one would
7547                find in the implicit typedef of a class inside the
7548                class itself.  Consider this parameter "unsubstituted",
7549                so that we will maintain the outer pack expansion.  */
7550             arg_pack = NULL_TREE;
7551         }
7552           
7553       if (arg_pack)
7554         {
7555           int my_len = 
7556             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7557
7558           /* It's all-or-nothing with incomplete argument packs.  */
7559           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7560             return error_mark_node;
7561           
7562           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7563             incomplete = 1;
7564
7565           if (len < 0)
7566             {
7567               len = my_len;
7568               first_arg_pack = arg_pack;
7569             }
7570           else if (len != my_len)
7571             {
7572               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7573                 error ("mismatched argument pack lengths while expanding "
7574                        "%<%T%>",
7575                        pattern);
7576               else
7577                 error ("mismatched argument pack lengths while expanding "
7578                        "%<%E%>",
7579                        pattern);
7580               return error_mark_node;
7581             }
7582
7583           /* Keep track of the parameter packs and their corresponding
7584              argument packs.  */
7585           packs = tree_cons (parm_pack, arg_pack, packs);
7586           TREE_TYPE (packs) = orig_arg;
7587         }
7588       else
7589         /* We can't substitute for this parameter pack.  */
7590         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7591                                          TREE_VALUE (pack),
7592                                          unsubstituted_packs);
7593     }
7594
7595   /* We cannot expand this expansion expression, because we don't have
7596      all of the argument packs we need. Substitute into the pattern
7597      and return a PACK_EXPANSION_*. The caller will need to deal with
7598      that.  */
7599   if (unsubstituted_packs)
7600     {
7601       tree new_pat;
7602       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7603         new_pat = tsubst_expr (pattern, args, complain, in_decl,
7604                                /*integral_constant_expression_p=*/false);
7605       else
7606         new_pat = tsubst (pattern, args, complain, in_decl);
7607       return make_pack_expansion (new_pat);
7608     }
7609
7610   /* We could not find any argument packs that work.  */
7611   if (len < 0)
7612     return error_mark_node;
7613
7614   if (!local_specializations)
7615     {
7616       /* We're in a late-specified return type, so we don't have a local
7617          specializations table.  Create one for doing this expansion.  */
7618       very_local_specializations = true;
7619       local_specializations = htab_create (37,
7620                                            hash_local_specialization,
7621                                            eq_local_specializations,
7622                                            NULL);
7623     }
7624
7625   /* For each argument in each argument pack, substitute into the
7626      pattern.  */
7627   result = make_tree_vec (len + incomplete);
7628   for (i = 0; i < len + incomplete; ++i)
7629     {
7630       /* For parameter pack, change the substitution of the parameter
7631          pack to the ith argument in its argument pack, then expand
7632          the pattern.  */
7633       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7634         {
7635           tree parm = TREE_PURPOSE (pack);
7636
7637           if (TREE_CODE (parm) == PARM_DECL)
7638             {
7639               /* Select the Ith argument from the pack.  */
7640               tree arg = make_node (ARGUMENT_PACK_SELECT);
7641               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7642               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7643               mark_used (parm);
7644               register_local_specialization (arg, parm);
7645             }
7646           else
7647             {
7648               tree value = parm;
7649               int idx, level;
7650               template_parm_level_and_index (parm, &level, &idx);
7651               
7652               if (i < len) 
7653                 {
7654                   /* Select the Ith argument from the pack. */
7655                   value = make_node (ARGUMENT_PACK_SELECT);
7656                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7657                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7658                 }
7659
7660               /* Update the corresponding argument.  */
7661               TMPL_ARG (args, level, idx) = value;
7662             }
7663         }
7664
7665       /* Substitute into the PATTERN with the altered arguments.  */
7666       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7667         TREE_VEC_ELT (result, i) = 
7668           tsubst_expr (pattern, args, complain, in_decl,
7669                        /*integral_constant_expression_p=*/false);
7670       else
7671         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7672
7673       if (i == len)
7674         /* When we have incomplete argument packs, the last "expanded"
7675            result is itself a pack expansion, which allows us
7676            to deduce more arguments.  */
7677         TREE_VEC_ELT (result, i) = 
7678           make_pack_expansion (TREE_VEC_ELT (result, i));
7679
7680       if (TREE_VEC_ELT (result, i) == error_mark_node)
7681         {
7682           result = error_mark_node;
7683           break;
7684         }
7685     }
7686
7687   /* Update ARGS to restore the substitution from parameter packs to
7688      their argument packs.  */
7689   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7690     {
7691       tree parm = TREE_PURPOSE (pack);
7692
7693       if (TREE_CODE (parm) == PARM_DECL)
7694         register_local_specialization (TREE_TYPE (pack), parm);
7695       else
7696         {
7697           int idx, level;
7698           template_parm_level_and_index (parm, &level, &idx);
7699           
7700           /* Update the corresponding argument.  */
7701           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7702             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7703               TREE_TYPE (pack);
7704           else
7705             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7706         }
7707     }
7708
7709   if (very_local_specializations)
7710     {
7711       htab_delete (local_specializations);
7712       local_specializations = NULL;
7713     }
7714   
7715   return result;
7716 }
7717
7718 /* Substitute ARGS into the vector or list of template arguments T.  */
7719
7720 static tree
7721 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7722 {
7723   tree orig_t = t;
7724   int len = TREE_VEC_LENGTH (t);
7725   int need_new = 0, i, expanded_len_adjust = 0, out;
7726   tree *elts = (tree *) alloca (len * sizeof (tree));
7727
7728   for (i = 0; i < len; i++)
7729     {
7730       tree orig_arg = TREE_VEC_ELT (t, i);
7731       tree new_arg;
7732
7733       if (TREE_CODE (orig_arg) == TREE_VEC)
7734         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7735       else if (PACK_EXPANSION_P (orig_arg))
7736         {
7737           /* Substitute into an expansion expression.  */
7738           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7739
7740           if (TREE_CODE (new_arg) == TREE_VEC)
7741             /* Add to the expanded length adjustment the number of
7742                expanded arguments. We subtract one from this
7743                measurement, because the argument pack expression
7744                itself is already counted as 1 in
7745                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7746                the argument pack is empty.  */
7747             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7748         }
7749       else if (ARGUMENT_PACK_P (orig_arg))
7750         {
7751           /* Substitute into each of the arguments.  */
7752           new_arg = make_node (TREE_CODE (orig_arg));
7753           
7754           SET_ARGUMENT_PACK_ARGS (
7755             new_arg,
7756             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7757                                   args, complain, in_decl));
7758
7759           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7760             new_arg = error_mark_node;
7761
7762           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7763             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7764                                           complain, in_decl);
7765             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7766
7767             if (TREE_TYPE (new_arg) == error_mark_node)
7768               new_arg = error_mark_node;
7769           }
7770         }
7771       else
7772         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7773
7774       if (new_arg == error_mark_node)
7775         return error_mark_node;
7776
7777       elts[i] = new_arg;
7778       if (new_arg != orig_arg)
7779         need_new = 1;
7780     }
7781
7782   if (!need_new)
7783     return t;
7784
7785   /* Make space for the expanded arguments coming from template
7786      argument packs.  */
7787   t = make_tree_vec (len + expanded_len_adjust);
7788   for (i = 0, out = 0; i < len; i++)
7789     {
7790       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7791            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7792           && TREE_CODE (elts[i]) == TREE_VEC)
7793         {
7794           int idx;
7795
7796           /* Now expand the template argument pack "in place".  */
7797           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7798             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7799         }
7800       else
7801         {
7802           TREE_VEC_ELT (t, out) = elts[i];
7803           out++;
7804         }
7805     }
7806
7807   return t;
7808 }
7809
7810 /* Return the result of substituting ARGS into the template parameters
7811    given by PARMS.  If there are m levels of ARGS and m + n levels of
7812    PARMS, then the result will contain n levels of PARMS.  For
7813    example, if PARMS is `template <class T> template <class U>
7814    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7815    result will be `template <int*, double, class V>'.  */
7816
7817 static tree
7818 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7819 {
7820   tree r = NULL_TREE;
7821   tree* new_parms;
7822
7823   /* When substituting into a template, we must set
7824      PROCESSING_TEMPLATE_DECL as the template parameters may be
7825      dependent if they are based on one-another, and the dependency
7826      predicates are short-circuit outside of templates.  */
7827   ++processing_template_decl;
7828
7829   for (new_parms = &r;
7830        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7831        new_parms = &(TREE_CHAIN (*new_parms)),
7832          parms = TREE_CHAIN (parms))
7833     {
7834       tree new_vec =
7835         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7836       int i;
7837
7838       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7839         {
7840           tree tuple;
7841           tree default_value;
7842           tree parm_decl;
7843
7844           if (parms == error_mark_node)
7845             continue;
7846
7847           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7848
7849           if (tuple == error_mark_node)
7850             continue;
7851
7852           default_value = TREE_PURPOSE (tuple);
7853           parm_decl = TREE_VALUE (tuple);
7854
7855           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7856           if (TREE_CODE (parm_decl) == PARM_DECL
7857               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7858             parm_decl = error_mark_node;
7859           default_value = tsubst_template_arg (default_value, args,
7860                                                complain, NULL_TREE);
7861
7862           tuple = build_tree_list (default_value, parm_decl);
7863           TREE_VEC_ELT (new_vec, i) = tuple;
7864         }
7865
7866       *new_parms =
7867         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7868                              - TMPL_ARGS_DEPTH (args)),
7869                    new_vec, NULL_TREE);
7870     }
7871
7872   --processing_template_decl;
7873
7874   return r;
7875 }
7876
7877 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7878    type T.  If T is not an aggregate or enumeration type, it is
7879    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7880    ENTERING_SCOPE is nonzero, T is the context for a template which
7881    we are presently tsubst'ing.  Return the substituted value.  */
7882
7883 static tree
7884 tsubst_aggr_type (tree t,
7885                   tree args,
7886                   tsubst_flags_t complain,
7887                   tree in_decl,
7888                   int entering_scope)
7889 {
7890   if (t == NULL_TREE)
7891     return NULL_TREE;
7892
7893   switch (TREE_CODE (t))
7894     {
7895     case RECORD_TYPE:
7896       if (TYPE_PTRMEMFUNC_P (t))
7897         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7898
7899       /* Else fall through.  */
7900     case ENUMERAL_TYPE:
7901     case UNION_TYPE:
7902       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7903         {
7904           tree argvec;
7905           tree context;
7906           tree r;
7907           bool saved_skip_evaluation;
7908
7909           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7910           saved_skip_evaluation = skip_evaluation;
7911           skip_evaluation = false;
7912
7913           /* First, determine the context for the type we are looking
7914              up.  */
7915           context = TYPE_CONTEXT (t);
7916           if (context)
7917             {
7918               context = tsubst_aggr_type (context, args, complain,
7919                                           in_decl, /*entering_scope=*/1);
7920               /* If context is a nested class inside a class template,
7921                  it may still need to be instantiated (c++/33959).  */
7922               if (TYPE_P (context))
7923                 context = complete_type (context);
7924             }
7925
7926           /* Then, figure out what arguments are appropriate for the
7927              type we are trying to find.  For example, given:
7928
7929                template <class T> struct S;
7930                template <class T, class U> void f(T, U) { S<U> su; }
7931
7932              and supposing that we are instantiating f<int, double>,
7933              then our ARGS will be {int, double}, but, when looking up
7934              S we only want {double}.  */
7935           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7936                                          complain, in_decl);
7937           if (argvec == error_mark_node)
7938             r = error_mark_node;
7939           else
7940             {
7941               r = lookup_template_class (t, argvec, in_decl, context,
7942                                          entering_scope, complain);
7943               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7944             }
7945
7946           skip_evaluation = saved_skip_evaluation;
7947
7948           return r;
7949         }
7950       else
7951         /* This is not a template type, so there's nothing to do.  */
7952         return t;
7953
7954     default:
7955       return tsubst (t, args, complain, in_decl);
7956     }
7957 }
7958
7959 /* Substitute into the default argument ARG (a default argument for
7960    FN), which has the indicated TYPE.  */
7961
7962 tree
7963 tsubst_default_argument (tree fn, tree type, tree arg)
7964 {
7965   tree saved_class_ptr = NULL_TREE;
7966   tree saved_class_ref = NULL_TREE;
7967
7968   /* This default argument came from a template.  Instantiate the
7969      default argument here, not in tsubst.  In the case of
7970      something like:
7971
7972        template <class T>
7973        struct S {
7974          static T t();
7975          void f(T = t());
7976        };
7977
7978      we must be careful to do name lookup in the scope of S<T>,
7979      rather than in the current class.  */
7980   push_access_scope (fn);
7981   /* The "this" pointer is not valid in a default argument.  */
7982   if (cfun)
7983     {
7984       saved_class_ptr = current_class_ptr;
7985       cp_function_chain->x_current_class_ptr = NULL_TREE;
7986       saved_class_ref = current_class_ref;
7987       cp_function_chain->x_current_class_ref = NULL_TREE;
7988     }
7989
7990   push_deferring_access_checks(dk_no_deferred);
7991   /* The default argument expression may cause implicitly defined
7992      member functions to be synthesized, which will result in garbage
7993      collection.  We must treat this situation as if we were within
7994      the body of function so as to avoid collecting live data on the
7995      stack.  */
7996   ++function_depth;
7997   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7998                      tf_warning_or_error, NULL_TREE,
7999                      /*integral_constant_expression_p=*/false);
8000   --function_depth;
8001   pop_deferring_access_checks();
8002
8003   /* Restore the "this" pointer.  */
8004   if (cfun)
8005     {
8006       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8007       cp_function_chain->x_current_class_ref = saved_class_ref;
8008     }
8009
8010   pop_access_scope (fn);
8011
8012   /* Make sure the default argument is reasonable.  */
8013   arg = check_default_argument (type, arg);
8014
8015   return arg;
8016 }
8017
8018 /* Substitute into all the default arguments for FN.  */
8019
8020 static void
8021 tsubst_default_arguments (tree fn)
8022 {
8023   tree arg;
8024   tree tmpl_args;
8025
8026   tmpl_args = DECL_TI_ARGS (fn);
8027
8028   /* If this function is not yet instantiated, we certainly don't need
8029      its default arguments.  */
8030   if (uses_template_parms (tmpl_args))
8031     return;
8032
8033   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8034        arg;
8035        arg = TREE_CHAIN (arg))
8036     if (TREE_PURPOSE (arg))
8037       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8038                                                     TREE_VALUE (arg),
8039                                                     TREE_PURPOSE (arg));
8040 }
8041
8042 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8043    result of the substitution.  Issue error and warning messages under
8044    control of COMPLAIN.  */
8045
8046 static tree
8047 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8048 {
8049   location_t saved_loc;
8050   tree r = NULL_TREE;
8051   tree in_decl = t;
8052
8053   /* Set the filename and linenumber to improve error-reporting.  */
8054   saved_loc = input_location;
8055   input_location = DECL_SOURCE_LOCATION (t);
8056
8057   switch (TREE_CODE (t))
8058     {
8059     case TEMPLATE_DECL:
8060       {
8061         /* We can get here when processing a member function template,
8062            member class template, or template template parameter.  */
8063         tree decl = DECL_TEMPLATE_RESULT (t);
8064         tree spec;
8065         tree tmpl_args;
8066         tree full_args;
8067
8068         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8069           {
8070             /* Template template parameter is treated here.  */
8071             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8072             if (new_type == error_mark_node)
8073               return error_mark_node;
8074
8075             r = copy_decl (t);
8076             TREE_CHAIN (r) = NULL_TREE;
8077             TREE_TYPE (r) = new_type;
8078             DECL_TEMPLATE_RESULT (r)
8079               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
8080             DECL_TEMPLATE_PARMS (r)
8081               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8082                                        complain);
8083             TYPE_NAME (new_type) = r;
8084             break;
8085           }
8086
8087         /* We might already have an instance of this template.
8088            The ARGS are for the surrounding class type, so the
8089            full args contain the tsubst'd args for the context,
8090            plus the innermost args from the template decl.  */
8091         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8092           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8093           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8094         /* Because this is a template, the arguments will still be
8095            dependent, even after substitution.  If
8096            PROCESSING_TEMPLATE_DECL is not set, the dependency
8097            predicates will short-circuit.  */
8098         ++processing_template_decl;
8099         full_args = tsubst_template_args (tmpl_args, args,
8100                                           complain, in_decl);
8101         --processing_template_decl;
8102         if (full_args == error_mark_node)
8103           return error_mark_node;
8104
8105         /* If this is a default template template argument,
8106            tsubst might not have changed anything.  */
8107         if (full_args == tmpl_args)
8108           return t;
8109
8110         spec = retrieve_specialization (t, full_args,
8111                                         /*class_specializations_p=*/true);
8112         if (spec != NULL_TREE)
8113           {
8114             r = spec;
8115             break;
8116           }
8117
8118         /* Make a new template decl.  It will be similar to the
8119            original, but will record the current template arguments.
8120            We also create a new function declaration, which is just
8121            like the old one, but points to this new template, rather
8122            than the old one.  */
8123         r = copy_decl (t);
8124         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8125         TREE_CHAIN (r) = NULL_TREE;
8126
8127         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8128
8129         if (TREE_CODE (decl) == TYPE_DECL)
8130           {
8131             tree new_type;
8132             ++processing_template_decl;
8133             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8134             --processing_template_decl;
8135             if (new_type == error_mark_node)
8136               return error_mark_node;
8137
8138             TREE_TYPE (r) = new_type;
8139             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8140             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8141             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8142             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8143           }
8144         else
8145           {
8146             tree new_decl;
8147             ++processing_template_decl;
8148             new_decl = tsubst (decl, args, complain, in_decl);
8149             --processing_template_decl;
8150             if (new_decl == error_mark_node)
8151               return error_mark_node;
8152
8153             DECL_TEMPLATE_RESULT (r) = new_decl;
8154             DECL_TI_TEMPLATE (new_decl) = r;
8155             TREE_TYPE (r) = TREE_TYPE (new_decl);
8156             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8157             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8158           }
8159
8160         SET_DECL_IMPLICIT_INSTANTIATION (r);
8161         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8162         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8163
8164         /* The template parameters for this new template are all the
8165            template parameters for the old template, except the
8166            outermost level of parameters.  */
8167         DECL_TEMPLATE_PARMS (r)
8168           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8169                                    complain);
8170
8171         if (PRIMARY_TEMPLATE_P (t))
8172           DECL_PRIMARY_TEMPLATE (r) = r;
8173
8174         if (TREE_CODE (decl) != TYPE_DECL)
8175           /* Record this non-type partial instantiation.  */
8176           register_specialization (r, t,
8177                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8178                                    false);
8179       }
8180       break;
8181
8182     case FUNCTION_DECL:
8183       {
8184         tree ctx;
8185         tree argvec = NULL_TREE;
8186         tree *friends;
8187         tree gen_tmpl;
8188         tree type;
8189         int member;
8190         int args_depth;
8191         int parms_depth;
8192
8193         /* Nobody should be tsubst'ing into non-template functions.  */
8194         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8195
8196         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8197           {
8198             tree spec;
8199             bool dependent_p;
8200
8201             /* If T is not dependent, just return it.  We have to
8202                increment PROCESSING_TEMPLATE_DECL because
8203                value_dependent_expression_p assumes that nothing is
8204                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8205             ++processing_template_decl;
8206             dependent_p = value_dependent_expression_p (t);
8207             --processing_template_decl;
8208             if (!dependent_p)
8209               return t;
8210
8211             /* Calculate the most general template of which R is a
8212                specialization, and the complete set of arguments used to
8213                specialize R.  */
8214             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8215             argvec = tsubst_template_args (DECL_TI_ARGS
8216                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8217                                            args, complain, in_decl);
8218
8219             /* Check to see if we already have this specialization.  */
8220             spec = retrieve_specialization (gen_tmpl, argvec,
8221                                             /*class_specializations_p=*/false);
8222
8223             if (spec)
8224               {
8225                 r = spec;
8226                 break;
8227               }
8228
8229             /* We can see more levels of arguments than parameters if
8230                there was a specialization of a member template, like
8231                this:
8232
8233                  template <class T> struct S { template <class U> void f(); }
8234                  template <> template <class U> void S<int>::f(U);
8235
8236                Here, we'll be substituting into the specialization,
8237                because that's where we can find the code we actually
8238                want to generate, but we'll have enough arguments for
8239                the most general template.
8240
8241                We also deal with the peculiar case:
8242
8243                  template <class T> struct S {
8244                    template <class U> friend void f();
8245                  };
8246                  template <class U> void f() {}
8247                  template S<int>;
8248                  template void f<double>();
8249
8250                Here, the ARGS for the instantiation of will be {int,
8251                double}.  But, we only need as many ARGS as there are
8252                levels of template parameters in CODE_PATTERN.  We are
8253                careful not to get fooled into reducing the ARGS in
8254                situations like:
8255
8256                  template <class T> struct S { template <class U> void f(U); }
8257                  template <class T> template <> void S<T>::f(int) {}
8258
8259                which we can spot because the pattern will be a
8260                specialization in this case.  */
8261             args_depth = TMPL_ARGS_DEPTH (args);
8262             parms_depth =
8263               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8264             if (args_depth > parms_depth
8265                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8266               args = get_innermost_template_args (args, parms_depth);
8267           }
8268         else
8269           {
8270             /* This special case arises when we have something like this:
8271
8272                  template <class T> struct S {
8273                    friend void f<int>(int, double);
8274                  };
8275
8276                Here, the DECL_TI_TEMPLATE for the friend declaration
8277                will be an IDENTIFIER_NODE.  We are being called from
8278                tsubst_friend_function, and we want only to create a
8279                new decl (R) with appropriate types so that we can call
8280                determine_specialization.  */
8281             gen_tmpl = NULL_TREE;
8282           }
8283
8284         if (DECL_CLASS_SCOPE_P (t))
8285           {
8286             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8287               member = 2;
8288             else
8289               member = 1;
8290             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8291                                     complain, t, /*entering_scope=*/1);
8292           }
8293         else
8294           {
8295             member = 0;
8296             ctx = DECL_CONTEXT (t);
8297           }
8298         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8299         if (type == error_mark_node)
8300           return error_mark_node;
8301
8302         /* We do NOT check for matching decls pushed separately at this
8303            point, as they may not represent instantiations of this
8304            template, and in any case are considered separate under the
8305            discrete model.  */
8306         r = copy_decl (t);
8307         DECL_USE_TEMPLATE (r) = 0;
8308         TREE_TYPE (r) = type;
8309         /* Clear out the mangled name and RTL for the instantiation.  */
8310         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8311         SET_DECL_RTL (r, NULL_RTX);
8312         /* Leave DECL_INITIAL set on deleted instantiations.  */
8313         if (!DECL_DELETED_FN (r))
8314           DECL_INITIAL (r) = NULL_TREE;
8315         DECL_CONTEXT (r) = ctx;
8316
8317         if (member && DECL_CONV_FN_P (r))
8318           /* Type-conversion operator.  Reconstruct the name, in
8319              case it's the name of one of the template's parameters.  */
8320           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8321
8322         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8323                                      complain, t);
8324         DECL_RESULT (r) = NULL_TREE;
8325
8326         TREE_STATIC (r) = 0;
8327         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8328         DECL_EXTERNAL (r) = 1;
8329         /* If this is an instantiation of a function with internal
8330            linkage, we already know what object file linkage will be
8331            assigned to the instantiation.  */
8332         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8333         DECL_DEFER_OUTPUT (r) = 0;
8334         TREE_CHAIN (r) = NULL_TREE;
8335         DECL_PENDING_INLINE_INFO (r) = 0;
8336         DECL_PENDING_INLINE_P (r) = 0;
8337         DECL_SAVED_TREE (r) = NULL_TREE;
8338         DECL_STRUCT_FUNCTION (r) = NULL;
8339         TREE_USED (r) = 0;
8340         if (DECL_CLONED_FUNCTION (r))
8341           {
8342             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8343                                                args, complain, t);
8344             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8345             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8346           }
8347
8348         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8349            this in the special friend case mentioned above where
8350            GEN_TMPL is NULL.  */
8351         if (gen_tmpl)
8352           {
8353             DECL_TEMPLATE_INFO (r)
8354               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8355             SET_DECL_IMPLICIT_INSTANTIATION (r);
8356             register_specialization (r, gen_tmpl, argvec, false);
8357
8358             /* We're not supposed to instantiate default arguments
8359                until they are called, for a template.  But, for a
8360                declaration like:
8361
8362                  template <class T> void f ()
8363                  { extern void g(int i = T()); }
8364
8365                we should do the substitution when the template is
8366                instantiated.  We handle the member function case in
8367                instantiate_class_template since the default arguments
8368                might refer to other members of the class.  */
8369             if (!member
8370                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8371                 && !uses_template_parms (argvec))
8372               tsubst_default_arguments (r);
8373           }
8374         else
8375           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8376
8377         /* Copy the list of befriending classes.  */
8378         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8379              *friends;
8380              friends = &TREE_CHAIN (*friends))
8381           {
8382             *friends = copy_node (*friends);
8383             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8384                                             args, complain,
8385                                             in_decl);
8386           }
8387
8388         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8389           {
8390             maybe_retrofit_in_chrg (r);
8391             if (DECL_CONSTRUCTOR_P (r))
8392               grok_ctor_properties (ctx, r);
8393             /* If this is an instantiation of a member template, clone it.
8394                If it isn't, that'll be handled by
8395                clone_constructors_and_destructors.  */
8396             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8397               clone_function_decl (r, /*update_method_vec_p=*/0);
8398           }
8399         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8400                  && !grok_op_properties (r, (complain & tf_error) != 0))
8401           return error_mark_node;
8402
8403         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8404           SET_DECL_FRIEND_CONTEXT (r,
8405                                    tsubst (DECL_FRIEND_CONTEXT (t),
8406                                             args, complain, in_decl));
8407
8408         /* Possibly limit visibility based on template args.  */
8409         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8410         if (DECL_VISIBILITY_SPECIFIED (t))
8411           {
8412             DECL_VISIBILITY_SPECIFIED (r) = 0;
8413             DECL_ATTRIBUTES (r)
8414               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8415           }
8416         determine_visibility (r);
8417
8418         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8419                                         args, complain, in_decl);
8420       }
8421       break;
8422
8423     case PARM_DECL:
8424       {
8425         tree type = NULL_TREE;
8426         int i, len = 1;
8427         tree expanded_types = NULL_TREE;
8428         tree prev_r = NULL_TREE;
8429         tree first_r = NULL_TREE;
8430
8431         if (FUNCTION_PARAMETER_PACK_P (t))
8432           {
8433             /* If there is a local specialization that isn't a
8434                parameter pack, it means that we're doing a "simple"
8435                substitution from inside tsubst_pack_expansion. Just
8436                return the local specialization (which will be a single
8437                parm).  */
8438             tree spec = retrieve_local_specialization (t);
8439             if (spec 
8440                 && TREE_CODE (spec) == PARM_DECL
8441                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8442               return spec;
8443
8444             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8445                the parameters in this function parameter pack.  */
8446             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8447                                                     complain, in_decl);
8448             if (TREE_CODE (expanded_types) == TREE_VEC)
8449               {
8450                 len = TREE_VEC_LENGTH (expanded_types);
8451
8452                 /* Zero-length parameter packs are boring. Just substitute
8453                    into the chain.  */
8454                 if (len == 0)
8455                   return tsubst (TREE_CHAIN (t), args, complain, 
8456                                  TREE_CHAIN (t));
8457               }
8458             else
8459               {
8460                 /* All we did was update the type. Make a note of that.  */
8461                 type = expanded_types;
8462                 expanded_types = NULL_TREE;
8463               }
8464           }
8465
8466         /* Loop through all of the parameter's we'll build. When T is
8467            a function parameter pack, LEN is the number of expanded
8468            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8469         r = NULL_TREE;
8470         for (i = 0; i < len; ++i)
8471           {
8472             prev_r = r;
8473             r = copy_node (t);
8474             if (DECL_TEMPLATE_PARM_P (t))
8475               SET_DECL_TEMPLATE_PARM_P (r);
8476
8477             if (expanded_types)
8478               /* We're on the Ith parameter of the function parameter
8479                  pack.  */
8480               {
8481                 /* Get the Ith type.  */
8482                 type = TREE_VEC_ELT (expanded_types, i);
8483
8484                 if (DECL_NAME (r))
8485                   /* Rename the parameter to include the index.  */
8486                   DECL_NAME (r) =
8487                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8488               }
8489             else if (!type)
8490               /* We're dealing with a normal parameter.  */
8491               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8492
8493             type = type_decays_to (type);
8494             TREE_TYPE (r) = type;
8495             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8496
8497             if (DECL_INITIAL (r))
8498               {
8499                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8500                   DECL_INITIAL (r) = TREE_TYPE (r);
8501                 else
8502                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8503                                              complain, in_decl);
8504               }
8505
8506             DECL_CONTEXT (r) = NULL_TREE;
8507
8508             if (!DECL_TEMPLATE_PARM_P (r))
8509               DECL_ARG_TYPE (r) = type_passed_as (type);
8510
8511             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8512                                             args, complain, in_decl);
8513
8514             /* Keep track of the first new parameter we
8515                generate. That's what will be returned to the
8516                caller.  */
8517             if (!first_r)
8518               first_r = r;
8519
8520             /* Build a proper chain of parameters when substituting
8521                into a function parameter pack.  */
8522             if (prev_r)
8523               TREE_CHAIN (prev_r) = r;
8524           }
8525
8526         if (TREE_CHAIN (t))
8527           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8528                                    complain, TREE_CHAIN (t));
8529
8530         /* FIRST_R contains the start of the chain we've built.  */
8531         r = first_r;
8532       }
8533       break;
8534
8535     case FIELD_DECL:
8536       {
8537         tree type;
8538
8539         r = copy_decl (t);
8540         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8541         if (type == error_mark_node)
8542           return error_mark_node;
8543         TREE_TYPE (r) = type;
8544         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8545
8546         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8547         DECL_INITIAL (r)
8548           = tsubst_expr (DECL_INITIAL (t), args,
8549                          complain, in_decl,
8550                          /*integral_constant_expression_p=*/true);
8551         /* We don't have to set DECL_CONTEXT here; it is set by
8552            finish_member_declaration.  */
8553         TREE_CHAIN (r) = NULL_TREE;
8554         if (VOID_TYPE_P (type))
8555           error ("instantiation of %q+D as type %qT", r, type);
8556
8557         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8558                                         args, complain, in_decl);
8559       }
8560       break;
8561
8562     case USING_DECL:
8563       /* We reach here only for member using decls.  */
8564       if (DECL_DEPENDENT_P (t))
8565         {
8566           r = do_class_using_decl
8567             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8568              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8569           if (!r)
8570             r = error_mark_node;
8571           else
8572             {
8573               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8574               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8575             }
8576         }
8577       else
8578         {
8579           r = copy_node (t);
8580           TREE_CHAIN (r) = NULL_TREE;
8581         }
8582       break;
8583
8584     case TYPE_DECL:
8585     case VAR_DECL:
8586       {
8587         tree argvec = NULL_TREE;
8588         tree gen_tmpl = NULL_TREE;
8589         tree spec;
8590         tree tmpl = NULL_TREE;
8591         tree ctx;
8592         tree type = NULL_TREE;
8593         bool local_p;
8594
8595         if (TREE_CODE (t) == TYPE_DECL
8596             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8597           {
8598             /* If this is the canonical decl, we don't have to
8599                mess with instantiations, and often we can't (for
8600                typename, template type parms and such).  Note that
8601                TYPE_NAME is not correct for the above test if
8602                we've copied the type for a typedef.  */
8603             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8604             if (type == error_mark_node)
8605               return error_mark_node;
8606             r = TYPE_NAME (type);
8607             break;
8608           }
8609
8610         /* Check to see if we already have the specialization we
8611            need.  */
8612         spec = NULL_TREE;
8613         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8614           {
8615             /* T is a static data member or namespace-scope entity.
8616                We have to substitute into namespace-scope variables
8617                (even though such entities are never templates) because
8618                of cases like:
8619                
8620                  template <class T> void f() { extern T t; }
8621
8622                where the entity referenced is not known until
8623                instantiation time.  */
8624             local_p = false;
8625             ctx = DECL_CONTEXT (t);
8626             if (DECL_CLASS_SCOPE_P (t))
8627               {
8628                 ctx = tsubst_aggr_type (ctx, args,
8629                                         complain,
8630                                         in_decl, /*entering_scope=*/1);
8631                 /* If CTX is unchanged, then T is in fact the
8632                    specialization we want.  That situation occurs when
8633                    referencing a static data member within in its own
8634                    class.  We can use pointer equality, rather than
8635                    same_type_p, because DECL_CONTEXT is always
8636                    canonical.  */
8637                 if (ctx == DECL_CONTEXT (t))
8638                   spec = t;
8639               }
8640
8641             if (!spec)
8642               {
8643                 tmpl = DECL_TI_TEMPLATE (t);
8644                 gen_tmpl = most_general_template (tmpl);
8645                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8646                 spec = (retrieve_specialization 
8647                         (gen_tmpl, argvec,
8648                          /*class_specializations_p=*/false));
8649               }
8650           }
8651         else
8652           {
8653             /* A local variable.  */
8654             local_p = true;
8655             /* Subsequent calls to pushdecl will fill this in.  */
8656             ctx = NULL_TREE;
8657             spec = retrieve_local_specialization (t);
8658           }
8659         /* If we already have the specialization we need, there is
8660            nothing more to do.  */ 
8661         if (spec)
8662           {
8663             r = spec;
8664             break;
8665           }
8666
8667         /* Create a new node for the specialization we need.  */
8668         r = copy_decl (t);
8669         if (type == NULL_TREE)
8670           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8671         if (TREE_CODE (r) == VAR_DECL)
8672           {
8673             /* Even if the original location is out of scope, the
8674                newly substituted one is not.  */
8675             DECL_DEAD_FOR_LOCAL (r) = 0;
8676             DECL_INITIALIZED_P (r) = 0;
8677             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8678             if (type == error_mark_node)
8679               return error_mark_node;
8680             if (TREE_CODE (type) == FUNCTION_TYPE)
8681               {
8682                 /* It may seem that this case cannot occur, since:
8683
8684                      typedef void f();
8685                      void g() { f x; }
8686
8687                    declares a function, not a variable.  However:
8688       
8689                      typedef void f();
8690                      template <typename T> void g() { T t; }
8691                      template void g<f>();
8692
8693                    is an attempt to declare a variable with function
8694                    type.  */
8695                 error ("variable %qD has function type",
8696                        /* R is not yet sufficiently initialized, so we
8697                           just use its name.  */
8698                        DECL_NAME (r));
8699                 return error_mark_node;
8700               }
8701             type = complete_type (type);
8702             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8703               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8704             type = check_var_type (DECL_NAME (r), type);
8705
8706             if (DECL_HAS_VALUE_EXPR_P (t))
8707               {
8708                 tree ve = DECL_VALUE_EXPR (t);
8709                 ve = tsubst_expr (ve, args, complain, in_decl,
8710                                   /*constant_expression_p=*/false);
8711                 SET_DECL_VALUE_EXPR (r, ve);
8712               }
8713           }
8714         else if (DECL_SELF_REFERENCE_P (t))
8715           SET_DECL_SELF_REFERENCE_P (r);
8716         TREE_TYPE (r) = type;
8717         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8718         DECL_CONTEXT (r) = ctx;
8719         /* Clear out the mangled name and RTL for the instantiation.  */
8720         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8721         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8722           SET_DECL_RTL (r, NULL_RTX);
8723         /* The initializer must not be expanded until it is required;
8724            see [temp.inst].  */
8725         DECL_INITIAL (r) = NULL_TREE;
8726         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8727           SET_DECL_RTL (r, NULL_RTX);
8728         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8729         if (TREE_CODE (r) == VAR_DECL)
8730           {
8731             /* Possibly limit visibility based on template args.  */
8732             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8733             if (DECL_VISIBILITY_SPECIFIED (t))
8734               {
8735                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8736                 DECL_ATTRIBUTES (r)
8737                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8738               }
8739             determine_visibility (r);
8740           }
8741         /* Preserve a typedef that names a type.  */
8742         else if (TREE_CODE (r) == TYPE_DECL
8743                  && DECL_ORIGINAL_TYPE (t)
8744                  && type != error_mark_node)
8745           {
8746             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8747                                              args, complain, in_decl);
8748             TREE_TYPE (r) = type = build_variant_type_copy (type);
8749             TYPE_NAME (type) = r;
8750           }
8751
8752         if (!local_p)
8753           {
8754             /* A static data member declaration is always marked
8755                external when it is declared in-class, even if an
8756                initializer is present.  We mimic the non-template
8757                processing here.  */
8758             DECL_EXTERNAL (r) = 1;
8759
8760             register_specialization (r, gen_tmpl, argvec, false);
8761             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8762             SET_DECL_IMPLICIT_INSTANTIATION (r);
8763           }
8764         else
8765           register_local_specialization (r, t);
8766
8767         TREE_CHAIN (r) = NULL_TREE;
8768
8769         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8770                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8771                                         args, complain, in_decl);
8772         layout_decl (r, 0);
8773       }
8774       break;
8775
8776     default:
8777       gcc_unreachable ();
8778     }
8779
8780   /* Restore the file and line information.  */
8781   input_location = saved_loc;
8782
8783   return r;
8784 }
8785
8786 /* Substitute into the ARG_TYPES of a function type.  */
8787
8788 static tree
8789 tsubst_arg_types (tree arg_types,
8790                   tree args,
8791                   tsubst_flags_t complain,
8792                   tree in_decl)
8793 {
8794   tree remaining_arg_types;
8795   tree type = NULL_TREE;
8796   int i = 1;
8797   tree expanded_args = NULL_TREE;
8798   tree default_arg;
8799
8800   if (!arg_types || arg_types == void_list_node)
8801     return arg_types;
8802
8803   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8804                                           args, complain, in_decl);
8805   if (remaining_arg_types == error_mark_node)
8806     return error_mark_node;
8807
8808   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8809     {
8810       /* For a pack expansion, perform substitution on the
8811          entire expression. Later on, we'll handle the arguments
8812          one-by-one.  */
8813       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8814                                             args, complain, in_decl);
8815
8816       if (TREE_CODE (expanded_args) == TREE_VEC)
8817         /* So that we'll spin through the parameters, one by one.  */
8818         i = TREE_VEC_LENGTH (expanded_args);
8819       else
8820         {
8821           /* We only partially substituted into the parameter
8822              pack. Our type is TYPE_PACK_EXPANSION.  */
8823           type = expanded_args;
8824           expanded_args = NULL_TREE;
8825         }
8826     }
8827
8828   while (i > 0) {
8829     --i;
8830     
8831     if (expanded_args)
8832       type = TREE_VEC_ELT (expanded_args, i);
8833     else if (!type)
8834       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8835
8836     if (type == error_mark_node)
8837       return error_mark_node;
8838     if (VOID_TYPE_P (type))
8839       {
8840         if (complain & tf_error)
8841           {
8842             error ("invalid parameter type %qT", type);
8843             if (in_decl)
8844               error ("in declaration %q+D", in_decl);
8845           }
8846         return error_mark_node;
8847     }
8848     
8849     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8850        top-level qualifiers as required.  */
8851     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8852
8853     /* We do not substitute into default arguments here.  The standard
8854        mandates that they be instantiated only when needed, which is
8855        done in build_over_call.  */
8856     default_arg = TREE_PURPOSE (arg_types);
8857
8858     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8859       {
8860         /* We've instantiated a template before its default arguments
8861            have been parsed.  This can happen for a nested template
8862            class, and is not an error unless we require the default
8863            argument in a call of this function.  */
8864         remaining_arg_types = 
8865           tree_cons (default_arg, type, remaining_arg_types);
8866         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8867                        remaining_arg_types);
8868       }
8869     else
8870       remaining_arg_types = 
8871         hash_tree_cons (default_arg, type, remaining_arg_types);
8872   }
8873         
8874   return remaining_arg_types;
8875 }
8876
8877 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8878    *not* handle the exception-specification for FNTYPE, because the
8879    initial substitution of explicitly provided template parameters
8880    during argument deduction forbids substitution into the
8881    exception-specification:
8882
8883      [temp.deduct]
8884
8885      All references in the function type of the function template to  the
8886      corresponding template parameters are replaced by the specified tem-
8887      plate argument values.  If a substitution in a template parameter or
8888      in  the function type of the function template results in an invalid
8889      type, type deduction fails.  [Note: The equivalent  substitution  in
8890      exception specifications is done only when the function is instanti-
8891      ated, at which point a program is  ill-formed  if  the  substitution
8892      results in an invalid type.]  */
8893
8894 static tree
8895 tsubst_function_type (tree t,
8896                       tree args,
8897                       tsubst_flags_t complain,
8898                       tree in_decl)
8899 {
8900   tree return_type;
8901   tree arg_types;
8902   tree fntype;
8903
8904   /* The TYPE_CONTEXT is not used for function/method types.  */
8905   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8906
8907   /* Substitute the return type.  */
8908   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8909   if (return_type == error_mark_node)
8910     return error_mark_node;
8911   /* The standard does not presently indicate that creation of a
8912      function type with an invalid return type is a deduction failure.
8913      However, that is clearly analogous to creating an array of "void"
8914      or a reference to a reference.  This is core issue #486.  */
8915   if (TREE_CODE (return_type) == ARRAY_TYPE
8916       || TREE_CODE (return_type) == FUNCTION_TYPE)
8917     {
8918       if (complain & tf_error)
8919         {
8920           if (TREE_CODE (return_type) == ARRAY_TYPE)
8921             error ("function returning an array");
8922           else
8923             error ("function returning a function");
8924         }
8925       return error_mark_node;
8926     }
8927
8928   /* Substitute the argument types.  */
8929   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8930                                 complain, in_decl);
8931   if (arg_types == error_mark_node)
8932     return error_mark_node;
8933
8934   /* Construct a new type node and return it.  */
8935   if (TREE_CODE (t) == FUNCTION_TYPE)
8936     fntype = build_function_type (return_type, arg_types);
8937   else
8938     {
8939       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8940       if (! MAYBE_CLASS_TYPE_P (r))
8941         {
8942           /* [temp.deduct]
8943
8944              Type deduction may fail for any of the following
8945              reasons:
8946
8947              -- Attempting to create "pointer to member of T" when T
8948              is not a class type.  */
8949           if (complain & tf_error)
8950             error ("creating pointer to member function of non-class type %qT",
8951                       r);
8952           return error_mark_node;
8953         }
8954
8955       fntype = build_method_type_directly (r, return_type,
8956                                            TREE_CHAIN (arg_types));
8957     }
8958   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8959   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8960
8961   return fntype;
8962 }
8963
8964 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8965    ARGS into that specification, and return the substituted
8966    specification.  If there is no specification, return NULL_TREE.  */
8967
8968 static tree
8969 tsubst_exception_specification (tree fntype,
8970                                 tree args,
8971                                 tsubst_flags_t complain,
8972                                 tree in_decl)
8973 {
8974   tree specs;
8975   tree new_specs;
8976
8977   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8978   new_specs = NULL_TREE;
8979   if (specs)
8980     {
8981       if (! TREE_VALUE (specs))
8982         new_specs = specs;
8983       else
8984         while (specs)
8985           {
8986             tree spec;
8987             int i, len = 1;
8988             tree expanded_specs = NULL_TREE;
8989
8990             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8991               {
8992                 /* Expand the pack expansion type.  */
8993                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8994                                                        args, complain,
8995                                                        in_decl);
8996
8997                 if (expanded_specs == error_mark_node)
8998                   return error_mark_node;
8999                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9000                   len = TREE_VEC_LENGTH (expanded_specs);
9001                 else
9002                   {
9003                     /* We're substituting into a member template, so
9004                        we got a TYPE_PACK_EXPANSION back.  Add that
9005                        expansion and move on.  */
9006                     gcc_assert (TREE_CODE (expanded_specs) 
9007                                 == TYPE_PACK_EXPANSION);
9008                     new_specs = add_exception_specifier (new_specs,
9009                                                          expanded_specs,
9010                                                          complain);
9011                     specs = TREE_CHAIN (specs);
9012                     continue;
9013                   }
9014               }
9015
9016             for (i = 0; i < len; ++i)
9017               {
9018                 if (expanded_specs)
9019                   spec = TREE_VEC_ELT (expanded_specs, i);
9020                 else
9021                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9022                 if (spec == error_mark_node)
9023                   return spec;
9024                 new_specs = add_exception_specifier (new_specs, spec, 
9025                                                      complain);
9026               }
9027
9028             specs = TREE_CHAIN (specs);
9029           }
9030     }
9031   return new_specs;
9032 }
9033
9034 /* Take the tree structure T and replace template parameters used
9035    therein with the argument vector ARGS.  IN_DECL is an associated
9036    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9037    Issue error and warning messages under control of COMPLAIN.  Note
9038    that we must be relatively non-tolerant of extensions here, in
9039    order to preserve conformance; if we allow substitutions that
9040    should not be allowed, we may allow argument deductions that should
9041    not succeed, and therefore report ambiguous overload situations
9042    where there are none.  In theory, we could allow the substitution,
9043    but indicate that it should have failed, and allow our caller to
9044    make sure that the right thing happens, but we don't try to do this
9045    yet.
9046
9047    This function is used for dealing with types, decls and the like;
9048    for expressions, use tsubst_expr or tsubst_copy.  */
9049
9050 static tree
9051 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9052 {
9053   tree type, r;
9054
9055   if (t == NULL_TREE || t == error_mark_node
9056       || t == integer_type_node
9057       || t == void_type_node
9058       || t == char_type_node
9059       || t == unknown_type_node
9060       || TREE_CODE (t) == NAMESPACE_DECL)
9061     return t;
9062
9063   if (DECL_P (t))
9064     return tsubst_decl (t, args, complain);
9065
9066   if (args == NULL_TREE)
9067     return t;
9068
9069   if (TREE_CODE (t) == IDENTIFIER_NODE)
9070     type = IDENTIFIER_TYPE_VALUE (t);
9071   else
9072     type = TREE_TYPE (t);
9073
9074   gcc_assert (type != unknown_type_node);
9075
9076   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9077      such as attribute aligned.  */
9078   if (TYPE_P (t)
9079       && TYPE_NAME (t)
9080       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9081     {
9082       tree decl = TYPE_NAME (t);
9083       
9084       if (DECL_CLASS_SCOPE_P (decl)
9085           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9086           && uses_template_parms (DECL_CONTEXT (decl)))
9087         {
9088           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9089           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9090           r = retrieve_specialization (tmpl, gen_args, false);
9091         }
9092       else if (DECL_FUNCTION_SCOPE_P (decl)
9093                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9094                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9095         r = retrieve_local_specialization (decl);
9096       else
9097         /* The typedef is from a non-template context.  */
9098         return t;
9099
9100       if (r)
9101         {
9102           r = TREE_TYPE (r);
9103           r = cp_build_qualified_type_real
9104             (r, cp_type_quals (t) | cp_type_quals (r),
9105              complain | tf_ignore_bad_quals);
9106           return r;
9107         }
9108       /* Else we must be instantiating the typedef, so fall through.  */
9109     }
9110
9111   if (type
9112       && TREE_CODE (t) != TYPENAME_TYPE
9113       && TREE_CODE (t) != IDENTIFIER_NODE
9114       && TREE_CODE (t) != FUNCTION_TYPE
9115       && TREE_CODE (t) != METHOD_TYPE)
9116     type = tsubst (type, args, complain, in_decl);
9117   if (type == error_mark_node)
9118     return error_mark_node;
9119
9120   switch (TREE_CODE (t))
9121     {
9122     case RECORD_TYPE:
9123     case UNION_TYPE:
9124     case ENUMERAL_TYPE:
9125       return tsubst_aggr_type (t, args, complain, in_decl,
9126                                /*entering_scope=*/0);
9127
9128     case ERROR_MARK:
9129     case IDENTIFIER_NODE:
9130     case VOID_TYPE:
9131     case REAL_TYPE:
9132     case COMPLEX_TYPE:
9133     case VECTOR_TYPE:
9134     case BOOLEAN_TYPE:
9135     case INTEGER_CST:
9136     case REAL_CST:
9137     case STRING_CST:
9138       return t;
9139
9140     case INTEGER_TYPE:
9141       if (t == integer_type_node)
9142         return t;
9143
9144       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9145           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9146         return t;
9147
9148       {
9149         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9150
9151         max = tsubst_expr (omax, args, complain, in_decl,
9152                            /*integral_constant_expression_p=*/false);
9153
9154         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9155            needed.  */
9156         if (TREE_CODE (max) == NOP_EXPR
9157             && TREE_SIDE_EFFECTS (omax)
9158             && !TREE_TYPE (max))
9159           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9160
9161         max = fold_decl_constant_value (max);
9162
9163         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9164            with TREE_SIDE_EFFECTS that indicates this is not an integral
9165            constant expression.  */
9166         if (processing_template_decl
9167             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9168           {
9169             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9170             TREE_SIDE_EFFECTS (max) = 1;
9171           }
9172
9173         if (TREE_CODE (max) != INTEGER_CST
9174             && !at_function_scope_p ()
9175             && !TREE_SIDE_EFFECTS (max)
9176             && !value_dependent_expression_p (max))
9177           {
9178             if (complain & tf_error)
9179               error ("array bound is not an integer constant");
9180             return error_mark_node;
9181           }
9182
9183         /* [temp.deduct]
9184
9185            Type deduction may fail for any of the following
9186            reasons:
9187
9188              Attempting to create an array with a size that is
9189              zero or negative.  */
9190         if (integer_zerop (max) && !(complain & tf_error))
9191           /* We must fail if performing argument deduction (as
9192              indicated by the state of complain), so that
9193              another substitution can be found.  */
9194           return error_mark_node;
9195         else if (TREE_CODE (max) == INTEGER_CST
9196                  && INT_CST_LT (max, integer_zero_node))
9197           {
9198             if (complain & tf_error)
9199               error ("creating array with negative size (%qE)", max);
9200
9201             return error_mark_node;
9202           }
9203
9204         return compute_array_index_type (NULL_TREE, max);
9205       }
9206
9207     case TEMPLATE_TYPE_PARM:
9208     case TEMPLATE_TEMPLATE_PARM:
9209     case BOUND_TEMPLATE_TEMPLATE_PARM:
9210     case TEMPLATE_PARM_INDEX:
9211       {
9212         int idx;
9213         int level;
9214         int levels;
9215         tree arg = NULL_TREE;
9216
9217         r = NULL_TREE;
9218
9219         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9220         template_parm_level_and_index (t, &level, &idx); 
9221
9222         levels = TMPL_ARGS_DEPTH (args);
9223         if (level <= levels)
9224           {
9225             arg = TMPL_ARG (args, level, idx);
9226
9227             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9228               /* See through ARGUMENT_PACK_SELECT arguments. */
9229               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9230           }
9231
9232         if (arg == error_mark_node)
9233           return error_mark_node;
9234         else if (arg != NULL_TREE)
9235           {
9236             if (ARGUMENT_PACK_P (arg))
9237               /* If ARG is an argument pack, we don't actually want to
9238                  perform a substitution here, because substitutions
9239                  for argument packs are only done
9240                  element-by-element. We can get to this point when
9241                  substituting the type of a non-type template
9242                  parameter pack, when that type actually contains
9243                  template parameter packs from an outer template, e.g.,
9244
9245                  template<typename... Types> struct A {
9246                    template<Types... Values> struct B { };
9247                  };  */
9248               return t;
9249
9250             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9251               {
9252                 int quals;
9253                 gcc_assert (TYPE_P (arg));
9254
9255                 /* cv-quals from the template are discarded when
9256                    substituting in a function or reference type.  */
9257                 if (TREE_CODE (arg) == FUNCTION_TYPE
9258                     || TREE_CODE (arg) == METHOD_TYPE
9259                     || TREE_CODE (arg) == REFERENCE_TYPE)
9260                   quals = cp_type_quals (arg);
9261                 else
9262                   quals = cp_type_quals (arg) | cp_type_quals (t);
9263                   
9264                 return cp_build_qualified_type_real
9265                   (arg, quals, complain | tf_ignore_bad_quals);
9266               }
9267             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9268               {
9269                 /* We are processing a type constructed from a
9270                    template template parameter.  */
9271                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9272                                       args, complain, in_decl);
9273                 if (argvec == error_mark_node)
9274                   return error_mark_node;
9275
9276                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9277                    are resolving nested-types in the signature of a
9278                    member function templates.  Otherwise ARG is a
9279                    TEMPLATE_DECL and is the real template to be
9280                    instantiated.  */
9281                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9282                   arg = TYPE_NAME (arg);
9283
9284                 r = lookup_template_class (arg,
9285                                            argvec, in_decl,
9286                                            DECL_CONTEXT (arg),
9287                                             /*entering_scope=*/0,
9288                                            complain);
9289                 return cp_build_qualified_type_real
9290                   (r, TYPE_QUALS (t), complain);
9291               }
9292             else
9293               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9294               return arg;
9295           }
9296
9297         if (level == 1)
9298           /* This can happen during the attempted tsubst'ing in
9299              unify.  This means that we don't yet have any information
9300              about the template parameter in question.  */
9301           return t;
9302
9303         /* If we get here, we must have been looking at a parm for a
9304            more deeply nested template.  Make a new version of this
9305            template parameter, but with a lower level.  */
9306         switch (TREE_CODE (t))
9307           {
9308           case TEMPLATE_TYPE_PARM:
9309           case TEMPLATE_TEMPLATE_PARM:
9310           case BOUND_TEMPLATE_TEMPLATE_PARM:
9311             if (cp_type_quals (t))
9312               {
9313                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9314                 r = cp_build_qualified_type_real
9315                   (r, cp_type_quals (t),
9316                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9317                                ? tf_ignore_bad_quals : 0));
9318               }
9319             else
9320               {
9321                 r = copy_type (t);
9322                 TEMPLATE_TYPE_PARM_INDEX (r)
9323                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9324                                                 r, levels, args, complain);
9325                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9326                 TYPE_MAIN_VARIANT (r) = r;
9327                 TYPE_POINTER_TO (r) = NULL_TREE;
9328                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9329
9330                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9331                   /* We have reduced the level of the template
9332                      template parameter, but not the levels of its
9333                      template parameters, so canonical_type_parameter
9334                      will not be able to find the canonical template
9335                      template parameter for this level. Thus, we
9336                      require structural equality checking to compare
9337                      TEMPLATE_TEMPLATE_PARMs. */
9338                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9339                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9340                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9341                 else
9342                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9343
9344                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9345                   {
9346                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9347                                           complain, in_decl);
9348                     if (argvec == error_mark_node)
9349                       return error_mark_node;
9350
9351                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9352                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9353                   }
9354               }
9355             break;
9356
9357           case TEMPLATE_PARM_INDEX:
9358             r = reduce_template_parm_level (t, type, levels, args, complain);
9359             break;
9360
9361           default:
9362             gcc_unreachable ();
9363           }
9364
9365         return r;
9366       }
9367
9368     case TREE_LIST:
9369       {
9370         tree purpose, value, chain;
9371
9372         if (t == void_list_node)
9373           return t;
9374
9375         purpose = TREE_PURPOSE (t);
9376         if (purpose)
9377           {
9378             purpose = tsubst (purpose, args, complain, in_decl);
9379             if (purpose == error_mark_node)
9380               return error_mark_node;
9381           }
9382         value = TREE_VALUE (t);
9383         if (value)
9384           {
9385             value = tsubst (value, args, complain, in_decl);
9386             if (value == error_mark_node)
9387               return error_mark_node;
9388           }
9389         chain = TREE_CHAIN (t);
9390         if (chain && chain != void_type_node)
9391           {
9392             chain = tsubst (chain, args, complain, in_decl);
9393             if (chain == error_mark_node)
9394               return error_mark_node;
9395           }
9396         if (purpose == TREE_PURPOSE (t)
9397             && value == TREE_VALUE (t)
9398             && chain == TREE_CHAIN (t))
9399           return t;
9400         return hash_tree_cons (purpose, value, chain);
9401       }
9402
9403     case TREE_BINFO:
9404       /* We should never be tsubsting a binfo.  */
9405       gcc_unreachable ();
9406
9407     case TREE_VEC:
9408       /* A vector of template arguments.  */
9409       gcc_assert (!type);
9410       return tsubst_template_args (t, args, complain, in_decl);
9411
9412     case POINTER_TYPE:
9413     case REFERENCE_TYPE:
9414       {
9415         enum tree_code code;
9416
9417         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9418           return t;
9419
9420         code = TREE_CODE (t);
9421
9422
9423         /* [temp.deduct]
9424
9425            Type deduction may fail for any of the following
9426            reasons:
9427
9428            -- Attempting to create a pointer to reference type.
9429            -- Attempting to create a reference to a reference type or
9430               a reference to void.
9431
9432           Core issue 106 says that creating a reference to a reference
9433           during instantiation is no longer a cause for failure. We
9434           only enforce this check in strict C++98 mode.  */
9435         if ((TREE_CODE (type) == REFERENCE_TYPE
9436              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9437             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9438           {
9439             static location_t last_loc;
9440
9441             /* We keep track of the last time we issued this error
9442                message to avoid spewing a ton of messages during a
9443                single bad template instantiation.  */
9444             if (complain & tf_error
9445                 && last_loc != input_location)
9446               {
9447                 if (TREE_CODE (type) == VOID_TYPE)
9448                   error ("forming reference to void");
9449                 else
9450                   error ("forming %s to reference type %qT",
9451                          (code == POINTER_TYPE) ? "pointer" : "reference",
9452                          type);
9453                 last_loc = input_location;
9454               }
9455
9456             return error_mark_node;
9457           }
9458         else if (code == POINTER_TYPE)
9459           {
9460             r = build_pointer_type (type);
9461             if (TREE_CODE (type) == METHOD_TYPE)
9462               r = build_ptrmemfunc_type (r);
9463           }
9464         else if (TREE_CODE (type) == REFERENCE_TYPE)
9465           /* In C++0x, during template argument substitution, when there is an
9466              attempt to create a reference to a reference type, reference
9467              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9468
9469              "If a template-argument for a template-parameter T names a type
9470              that is a reference to a type A, an attempt to create the type
9471              'lvalue reference to cv T' creates the type 'lvalue reference to
9472              A,' while an attempt to create the type type rvalue reference to
9473              cv T' creates the type T"
9474           */
9475           r = cp_build_reference_type
9476               (TREE_TYPE (type),
9477                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9478         else
9479           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9480         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9481
9482         if (r != error_mark_node)
9483           /* Will this ever be needed for TYPE_..._TO values?  */
9484           layout_type (r);
9485
9486         return r;
9487       }
9488     case OFFSET_TYPE:
9489       {
9490         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9491         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9492           {
9493             /* [temp.deduct]
9494
9495                Type deduction may fail for any of the following
9496                reasons:
9497
9498                -- Attempting to create "pointer to member of T" when T
9499                   is not a class type.  */
9500             if (complain & tf_error)
9501               error ("creating pointer to member of non-class type %qT", r);
9502             return error_mark_node;
9503           }
9504         if (TREE_CODE (type) == REFERENCE_TYPE)
9505           {
9506             if (complain & tf_error)
9507               error ("creating pointer to member reference type %qT", type);
9508             return error_mark_node;
9509           }
9510         if (TREE_CODE (type) == VOID_TYPE)
9511           {
9512             if (complain & tf_error)
9513               error ("creating pointer to member of type void");
9514             return error_mark_node;
9515           }
9516         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9517         if (TREE_CODE (type) == FUNCTION_TYPE)
9518           {
9519             /* The type of the implicit object parameter gets its
9520                cv-qualifiers from the FUNCTION_TYPE. */
9521             tree method_type;
9522             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9523                                                       cp_type_quals (type));
9524             tree memptr;
9525             method_type = build_method_type_directly (this_type,
9526                                                       TREE_TYPE (type),
9527                                                       TYPE_ARG_TYPES (type));
9528             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9529             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9530                                                  complain);
9531           }
9532         else
9533           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9534                                                TYPE_QUALS (t),
9535                                                complain);
9536       }
9537     case FUNCTION_TYPE:
9538     case METHOD_TYPE:
9539       {
9540         tree fntype;
9541         tree specs;
9542         fntype = tsubst_function_type (t, args, complain, in_decl);
9543         if (fntype == error_mark_node)
9544           return error_mark_node;
9545
9546         /* Substitute the exception specification.  */
9547         specs = tsubst_exception_specification (t, args, complain,
9548                                                 in_decl);
9549         if (specs == error_mark_node)
9550           return error_mark_node;
9551         if (specs)
9552           fntype = build_exception_variant (fntype, specs);
9553         return fntype;
9554       }
9555     case ARRAY_TYPE:
9556       {
9557         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9558         if (domain == error_mark_node)
9559           return error_mark_node;
9560
9561         /* As an optimization, we avoid regenerating the array type if
9562            it will obviously be the same as T.  */
9563         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9564           return t;
9565
9566         /* These checks should match the ones in grokdeclarator.
9567
9568            [temp.deduct]
9569
9570            The deduction may fail for any of the following reasons:
9571
9572            -- Attempting to create an array with an element type that
9573               is void, a function type, or a reference type, or [DR337]
9574               an abstract class type.  */
9575         if (TREE_CODE (type) == VOID_TYPE
9576             || TREE_CODE (type) == FUNCTION_TYPE
9577             || TREE_CODE (type) == REFERENCE_TYPE)
9578           {
9579             if (complain & tf_error)
9580               error ("creating array of %qT", type);
9581             return error_mark_node;
9582           }
9583         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9584           {
9585             if (complain & tf_error)
9586               error ("creating array of %qT, which is an abstract class type",
9587                      type);
9588             return error_mark_node;
9589           }
9590
9591         r = build_cplus_array_type (type, domain);
9592
9593         if (TYPE_USER_ALIGN (t))
9594           {
9595             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9596             TYPE_USER_ALIGN (r) = 1;
9597           }
9598
9599         return r;
9600       }
9601
9602     case PLUS_EXPR:
9603     case MINUS_EXPR:
9604       {
9605         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9606         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9607
9608         if (e1 == error_mark_node || e2 == error_mark_node)
9609           return error_mark_node;
9610
9611         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9612       }
9613
9614     case NEGATE_EXPR:
9615     case NOP_EXPR:
9616       {
9617         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9618         if (e == error_mark_node)
9619           return error_mark_node;
9620
9621         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9622       }
9623
9624     case TYPENAME_TYPE:
9625       {
9626         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9627                                      in_decl, /*entering_scope=*/1);
9628         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9629                               complain, in_decl);
9630
9631         if (ctx == error_mark_node || f == error_mark_node)
9632           return error_mark_node;
9633
9634         if (!MAYBE_CLASS_TYPE_P (ctx))
9635           {
9636             if (complain & tf_error)
9637               error ("%qT is not a class, struct, or union type", ctx);
9638             return error_mark_node;
9639           }
9640         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9641           {
9642             /* Normally, make_typename_type does not require that the CTX
9643                have complete type in order to allow things like:
9644
9645                  template <class T> struct S { typename S<T>::X Y; };
9646
9647                But, such constructs have already been resolved by this
9648                point, so here CTX really should have complete type, unless
9649                it's a partial instantiation.  */
9650             ctx = complete_type (ctx);
9651             if (!COMPLETE_TYPE_P (ctx))
9652               {
9653                 if (complain & tf_error)
9654                   cxx_incomplete_type_error (NULL_TREE, ctx);
9655                 return error_mark_node;
9656               }
9657           }
9658
9659         f = make_typename_type (ctx, f, typename_type,
9660                                 (complain & tf_error) | tf_keep_type_decl);
9661         if (f == error_mark_node)
9662           return f;
9663         if (TREE_CODE (f) == TYPE_DECL)
9664           {
9665             complain |= tf_ignore_bad_quals;
9666             f = TREE_TYPE (f);
9667           }
9668
9669         if (TREE_CODE (f) != TYPENAME_TYPE)
9670           {
9671             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9672               error ("%qT resolves to %qT, which is not an enumeration type",
9673                      t, f);
9674             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9675               error ("%qT resolves to %qT, which is is not a class type",
9676                      t, f);
9677           }
9678
9679         return cp_build_qualified_type_real
9680           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9681       }
9682
9683     case UNBOUND_CLASS_TEMPLATE:
9684       {
9685         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9686                                      in_decl, /*entering_scope=*/1);
9687         tree name = TYPE_IDENTIFIER (t);
9688         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9689
9690         if (ctx == error_mark_node || name == error_mark_node)
9691           return error_mark_node;
9692
9693         if (parm_list)
9694           parm_list = tsubst_template_parms (parm_list, args, complain);
9695         return make_unbound_class_template (ctx, name, parm_list, complain);
9696       }
9697
9698     case INDIRECT_REF:
9699     case ADDR_EXPR:
9700     case CALL_EXPR:
9701       gcc_unreachable ();
9702
9703     case ARRAY_REF:
9704       {
9705         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9706         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9707                                /*integral_constant_expression_p=*/false);
9708         if (e1 == error_mark_node || e2 == error_mark_node)
9709           return error_mark_node;
9710
9711         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9712       }
9713
9714     case SCOPE_REF:
9715       {
9716         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9717         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9718         if (e1 == error_mark_node || e2 == error_mark_node)
9719           return error_mark_node;
9720
9721         return build_qualified_name (/*type=*/NULL_TREE,
9722                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9723       }
9724
9725     case TYPEOF_TYPE:
9726       {
9727         tree type;
9728
9729         type = finish_typeof (tsubst_expr 
9730                               (TYPEOF_TYPE_EXPR (t), args,
9731                                complain, in_decl,
9732                                /*integral_constant_expression_p=*/false));
9733         return cp_build_qualified_type_real (type,
9734                                              cp_type_quals (t)
9735                                              | cp_type_quals (type),
9736                                              complain);
9737       }
9738
9739     case DECLTYPE_TYPE:
9740       {
9741         tree type;
9742
9743         ++skip_evaluation;
9744
9745         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9746                             complain, in_decl,
9747                             /*integral_constant_expression_p=*/false);
9748
9749         --skip_evaluation;
9750
9751         type =
9752           finish_decltype_type (type,
9753                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9754         return cp_build_qualified_type_real (type,
9755                                              cp_type_quals (t)
9756                                              | cp_type_quals (type),
9757                                              complain);
9758       }
9759
9760     case TYPE_ARGUMENT_PACK:
9761     case NONTYPE_ARGUMENT_PACK:
9762       {
9763         tree r = make_node (TREE_CODE (t));
9764         tree packed_out = 
9765           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9766                                 args,
9767                                 complain,
9768                                 in_decl);
9769         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9770
9771         /* For template nontype argument packs, also substitute into
9772            the type.  */
9773         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9774           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9775
9776         return r;
9777       }
9778       break;
9779
9780     default:
9781       sorry ("use of %qs in template",
9782              tree_code_name [(int) TREE_CODE (t)]);
9783       return error_mark_node;
9784     }
9785 }
9786
9787 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9788    type of the expression on the left-hand side of the "." or "->"
9789    operator.  */
9790
9791 static tree
9792 tsubst_baselink (tree baselink, tree object_type,
9793                  tree args, tsubst_flags_t complain, tree in_decl)
9794 {
9795     tree name;
9796     tree qualifying_scope;
9797     tree fns;
9798     tree optype;
9799     tree template_args = 0;
9800     bool template_id_p = false;
9801
9802     /* A baselink indicates a function from a base class.  Both the
9803        BASELINK_ACCESS_BINFO and the base class referenced may
9804        indicate bases of the template class, rather than the
9805        instantiated class.  In addition, lookups that were not
9806        ambiguous before may be ambiguous now.  Therefore, we perform
9807        the lookup again.  */
9808     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9809     qualifying_scope = tsubst (qualifying_scope, args,
9810                                complain, in_decl);
9811     fns = BASELINK_FUNCTIONS (baselink);
9812     optype = BASELINK_OPTYPE (baselink);
9813     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9814       {
9815         template_id_p = true;
9816         template_args = TREE_OPERAND (fns, 1);
9817         fns = TREE_OPERAND (fns, 0);
9818         if (template_args)
9819           template_args = tsubst_template_args (template_args, args,
9820                                                 complain, in_decl);
9821       }
9822     name = DECL_NAME (get_first_fn (fns));
9823     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9824
9825     /* If lookup found a single function, mark it as used at this
9826        point.  (If it lookup found multiple functions the one selected
9827        later by overload resolution will be marked as used at that
9828        point.)  */
9829     if (BASELINK_P (baselink))
9830       fns = BASELINK_FUNCTIONS (baselink);
9831     if (!template_id_p && !really_overloaded_fn (fns))
9832       mark_used (OVL_CURRENT (fns));
9833
9834     /* Add back the template arguments, if present.  */
9835     if (BASELINK_P (baselink) && template_id_p)
9836       BASELINK_FUNCTIONS (baselink)
9837         = build_nt (TEMPLATE_ID_EXPR,
9838                     BASELINK_FUNCTIONS (baselink),
9839                     template_args);
9840     /* Update the conversion operator type.  */
9841     BASELINK_OPTYPE (baselink) 
9842       = tsubst (optype, args, complain, in_decl);
9843
9844     if (!object_type)
9845       object_type = current_class_type;
9846     return adjust_result_of_qualified_name_lookup (baselink,
9847                                                    qualifying_scope,
9848                                                    object_type);
9849 }
9850
9851 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9852    true if the qualified-id will be a postfix-expression in-and-of
9853    itself; false if more of the postfix-expression follows the
9854    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9855    of "&".  */
9856
9857 static tree
9858 tsubst_qualified_id (tree qualified_id, tree args,
9859                      tsubst_flags_t complain, tree in_decl,
9860                      bool done, bool address_p)
9861 {
9862   tree expr;
9863   tree scope;
9864   tree name;
9865   bool is_template;
9866   tree template_args;
9867
9868   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9869
9870   /* Figure out what name to look up.  */
9871   name = TREE_OPERAND (qualified_id, 1);
9872   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9873     {
9874       is_template = true;
9875       template_args = TREE_OPERAND (name, 1);
9876       if (template_args)
9877         template_args = tsubst_template_args (template_args, args,
9878                                               complain, in_decl);
9879       name = TREE_OPERAND (name, 0);
9880     }
9881   else
9882     {
9883       is_template = false;
9884       template_args = NULL_TREE;
9885     }
9886
9887   /* Substitute into the qualifying scope.  When there are no ARGS, we
9888      are just trying to simplify a non-dependent expression.  In that
9889      case the qualifying scope may be dependent, and, in any case,
9890      substituting will not help.  */
9891   scope = TREE_OPERAND (qualified_id, 0);
9892   if (args)
9893     {
9894       scope = tsubst (scope, args, complain, in_decl);
9895       expr = tsubst_copy (name, args, complain, in_decl);
9896     }
9897   else
9898     expr = name;
9899
9900   if (dependent_type_p (scope))
9901     return build_qualified_name (/*type=*/NULL_TREE,
9902                                  scope, expr,
9903                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9904
9905   if (!BASELINK_P (name) && !DECL_P (expr))
9906     {
9907       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9908         /* If this were actually a destructor call, it would have been
9909            parsed as such by the parser.  */
9910         expr = error_mark_node;
9911       else
9912         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9913       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9914                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9915         {
9916           if (complain & tf_error)
9917             {
9918               error ("dependent-name %qE is parsed as a non-type, but "
9919                      "instantiation yields a type", qualified_id);
9920               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9921             }
9922           return error_mark_node;
9923         }
9924     }
9925
9926   if (DECL_P (expr))
9927     {
9928       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9929                                            scope);
9930       /* Remember that there was a reference to this entity.  */
9931       mark_used (expr);
9932     }
9933
9934   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9935     {
9936       if (complain & tf_error)
9937         qualified_name_lookup_error (scope,
9938                                      TREE_OPERAND (qualified_id, 1),
9939                                      expr, input_location);
9940       return error_mark_node;
9941     }
9942
9943   if (is_template)
9944     expr = lookup_template_function (expr, template_args);
9945
9946   if (expr == error_mark_node && complain & tf_error)
9947     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9948                                  expr, input_location);
9949   else if (TYPE_P (scope))
9950     {
9951       expr = (adjust_result_of_qualified_name_lookup
9952               (expr, scope, current_class_type));
9953       expr = (finish_qualified_id_expr
9954               (scope, expr, done, address_p,
9955                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9956                /*template_arg_p=*/false));
9957     }
9958
9959   /* Expressions do not generally have reference type.  */
9960   if (TREE_CODE (expr) != SCOPE_REF
9961       /* However, if we're about to form a pointer-to-member, we just
9962          want the referenced member referenced.  */
9963       && TREE_CODE (expr) != OFFSET_REF)
9964     expr = convert_from_reference (expr);
9965
9966   return expr;
9967 }
9968
9969 /* Like tsubst, but deals with expressions.  This function just replaces
9970    template parms; to finish processing the resultant expression, use
9971    tsubst_expr.  */
9972
9973 static tree
9974 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9975 {
9976   enum tree_code code;
9977   tree r;
9978
9979   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
9980     return t;
9981
9982   code = TREE_CODE (t);
9983
9984   switch (code)
9985     {
9986     case PARM_DECL:
9987       r = retrieve_local_specialization (t);
9988
9989       if (r == NULL)
9990         {
9991           tree c;
9992           /* This can happen for a parameter name used later in a function
9993              declaration (such as in a late-specified return type).  Just
9994              make a dummy decl, since it's only used for its type.  */
9995           gcc_assert (skip_evaluation);   
9996           /* We copy T because want to tsubst the PARM_DECL only,
9997              not the following PARM_DECLs that are chained to T.  */
9998           c = copy_node (t);
9999           r = tsubst_decl (c, args, complain);
10000           /* Give it the template pattern as its context; its true context
10001              hasn't been instantiated yet and this is good enough for
10002              mangling.  */
10003           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10004         }
10005       
10006       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10007         r = ARGUMENT_PACK_SELECT_ARG (r);
10008       mark_used (r);
10009       return r;
10010
10011     case CONST_DECL:
10012       {
10013         tree enum_type;
10014         tree v;
10015
10016         if (DECL_TEMPLATE_PARM_P (t))
10017           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10018         /* There is no need to substitute into namespace-scope
10019            enumerators.  */
10020         if (DECL_NAMESPACE_SCOPE_P (t))
10021           return t;
10022         /* If ARGS is NULL, then T is known to be non-dependent.  */
10023         if (args == NULL_TREE)
10024           return integral_constant_value (t);
10025
10026         /* Unfortunately, we cannot just call lookup_name here.
10027            Consider:
10028
10029              template <int I> int f() {
10030              enum E { a = I };
10031              struct S { void g() { E e = a; } };
10032              };
10033
10034            When we instantiate f<7>::S::g(), say, lookup_name is not
10035            clever enough to find f<7>::a.  */
10036         enum_type
10037           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10038                               /*entering_scope=*/0);
10039
10040         for (v = TYPE_VALUES (enum_type);
10041              v != NULL_TREE;
10042              v = TREE_CHAIN (v))
10043           if (TREE_PURPOSE (v) == DECL_NAME (t))
10044             return TREE_VALUE (v);
10045
10046           /* We didn't find the name.  That should never happen; if
10047              name-lookup found it during preliminary parsing, we
10048              should find it again here during instantiation.  */
10049         gcc_unreachable ();
10050       }
10051       return t;
10052
10053     case FIELD_DECL:
10054       if (DECL_CONTEXT (t))
10055         {
10056           tree ctx;
10057
10058           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10059                                   /*entering_scope=*/1);
10060           if (ctx != DECL_CONTEXT (t))
10061             {
10062               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10063               if (!r)
10064                 {
10065                   if (complain & tf_error)
10066                     error ("using invalid field %qD", t);
10067                   return error_mark_node;
10068                 }
10069               return r;
10070             }
10071         }
10072
10073       return t;
10074
10075     case VAR_DECL:
10076     case FUNCTION_DECL:
10077       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10078           || local_variable_p (t))
10079         t = tsubst (t, args, complain, in_decl);
10080       mark_used (t);
10081       return t;
10082
10083     case BASELINK:
10084       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10085
10086     case TEMPLATE_DECL:
10087       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10088         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10089                        args, complain, in_decl);
10090       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10091         return tsubst (t, args, complain, in_decl);
10092       else if (DECL_CLASS_SCOPE_P (t)
10093                && uses_template_parms (DECL_CONTEXT (t)))
10094         {
10095           /* Template template argument like the following example need
10096              special treatment:
10097
10098                template <template <class> class TT> struct C {};
10099                template <class T> struct D {
10100                  template <class U> struct E {};
10101                  C<E> c;                                // #1
10102                };
10103                D<int> d;                                // #2
10104
10105              We are processing the template argument `E' in #1 for
10106              the template instantiation #2.  Originally, `E' is a
10107              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10108              have to substitute this with one having context `D<int>'.  */
10109
10110           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10111           return lookup_field (context, DECL_NAME(t), 0, false);
10112         }
10113       else
10114         /* Ordinary template template argument.  */
10115         return t;
10116
10117     case CAST_EXPR:
10118     case REINTERPRET_CAST_EXPR:
10119     case CONST_CAST_EXPR:
10120     case STATIC_CAST_EXPR:
10121     case DYNAMIC_CAST_EXPR:
10122     case NOP_EXPR:
10123       return build1
10124         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10125          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10126
10127     case SIZEOF_EXPR:
10128       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10129         {
10130           /* We only want to compute the number of arguments.  */
10131           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10132                                                 complain, in_decl);
10133           int len = 0;
10134
10135           if (TREE_CODE (expanded) == TREE_VEC)
10136             len = TREE_VEC_LENGTH (expanded);
10137
10138           if (expanded == error_mark_node)
10139             return error_mark_node;
10140           else if (PACK_EXPANSION_P (expanded)
10141                    || (TREE_CODE (expanded) == TREE_VEC
10142                        && len > 0
10143                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10144             {
10145               if (TREE_CODE (expanded) == TREE_VEC)
10146                 expanded = TREE_VEC_ELT (expanded, len - 1);
10147
10148               if (TYPE_P (expanded))
10149                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10150                                                    complain & tf_error);
10151               else
10152                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10153                                                    complain & tf_error);
10154             }
10155           else
10156             return build_int_cst (size_type_node, len);
10157         }
10158       /* Fall through */
10159
10160     case INDIRECT_REF:
10161     case NEGATE_EXPR:
10162     case TRUTH_NOT_EXPR:
10163     case BIT_NOT_EXPR:
10164     case ADDR_EXPR:
10165     case UNARY_PLUS_EXPR:      /* Unary + */
10166     case ALIGNOF_EXPR:
10167     case ARROW_EXPR:
10168     case THROW_EXPR:
10169     case TYPEID_EXPR:
10170     case REALPART_EXPR:
10171     case IMAGPART_EXPR:
10172       return build1
10173         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10174          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10175
10176     case COMPONENT_REF:
10177       {
10178         tree object;
10179         tree name;
10180
10181         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10182         name = TREE_OPERAND (t, 1);
10183         if (TREE_CODE (name) == BIT_NOT_EXPR)
10184           {
10185             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10186                                 complain, in_decl);
10187             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10188           }
10189         else if (TREE_CODE (name) == SCOPE_REF
10190                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10191           {
10192             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10193                                      complain, in_decl);
10194             name = TREE_OPERAND (name, 1);
10195             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10196                                 complain, in_decl);
10197             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10198             name = build_qualified_name (/*type=*/NULL_TREE,
10199                                          base, name,
10200                                          /*template_p=*/false);
10201           }
10202         else if (TREE_CODE (name) == BASELINK)
10203           name = tsubst_baselink (name,
10204                                   non_reference (TREE_TYPE (object)),
10205                                   args, complain,
10206                                   in_decl);
10207         else
10208           name = tsubst_copy (name, args, complain, in_decl);
10209         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10210       }
10211
10212     case PLUS_EXPR:
10213     case MINUS_EXPR:
10214     case MULT_EXPR:
10215     case TRUNC_DIV_EXPR:
10216     case CEIL_DIV_EXPR:
10217     case FLOOR_DIV_EXPR:
10218     case ROUND_DIV_EXPR:
10219     case EXACT_DIV_EXPR:
10220     case BIT_AND_EXPR:
10221     case BIT_IOR_EXPR:
10222     case BIT_XOR_EXPR:
10223     case TRUNC_MOD_EXPR:
10224     case FLOOR_MOD_EXPR:
10225     case TRUTH_ANDIF_EXPR:
10226     case TRUTH_ORIF_EXPR:
10227     case TRUTH_AND_EXPR:
10228     case TRUTH_OR_EXPR:
10229     case RSHIFT_EXPR:
10230     case LSHIFT_EXPR:
10231     case RROTATE_EXPR:
10232     case LROTATE_EXPR:
10233     case EQ_EXPR:
10234     case NE_EXPR:
10235     case MAX_EXPR:
10236     case MIN_EXPR:
10237     case LE_EXPR:
10238     case GE_EXPR:
10239     case LT_EXPR:
10240     case GT_EXPR:
10241     case COMPOUND_EXPR:
10242     case DOTSTAR_EXPR:
10243     case MEMBER_REF:
10244     case PREDECREMENT_EXPR:
10245     case PREINCREMENT_EXPR:
10246     case POSTDECREMENT_EXPR:
10247     case POSTINCREMENT_EXPR:
10248       return build_nt
10249         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10250          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10251
10252     case SCOPE_REF:
10253       return build_qualified_name (/*type=*/NULL_TREE,
10254                                    tsubst_copy (TREE_OPERAND (t, 0),
10255                                                 args, complain, in_decl),
10256                                    tsubst_copy (TREE_OPERAND (t, 1),
10257                                                 args, complain, in_decl),
10258                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10259
10260     case ARRAY_REF:
10261       return build_nt
10262         (ARRAY_REF,
10263          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10264          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10265          NULL_TREE, NULL_TREE);
10266
10267     case CALL_EXPR:
10268       {
10269         int n = VL_EXP_OPERAND_LENGTH (t);
10270         tree result = build_vl_exp (CALL_EXPR, n);
10271         int i;
10272         for (i = 0; i < n; i++)
10273           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10274                                              complain, in_decl);
10275         return result;
10276       }
10277
10278     case COND_EXPR:
10279     case MODOP_EXPR:
10280     case PSEUDO_DTOR_EXPR:
10281       {
10282         r = build_nt
10283           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10284            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10285            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10286         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10287         return r;
10288       }
10289
10290     case NEW_EXPR:
10291       {
10292         r = build_nt
10293         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10294          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10295          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10296         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10297         return r;
10298       }
10299
10300     case DELETE_EXPR:
10301       {
10302         r = build_nt
10303         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10304          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10305         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10306         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10307         return r;
10308       }
10309
10310     case TEMPLATE_ID_EXPR:
10311       {
10312         /* Substituted template arguments */
10313         tree fn = TREE_OPERAND (t, 0);
10314         tree targs = TREE_OPERAND (t, 1);
10315
10316         fn = tsubst_copy (fn, args, complain, in_decl);
10317         if (targs)
10318           targs = tsubst_template_args (targs, args, complain, in_decl);
10319
10320         return lookup_template_function (fn, targs);
10321       }
10322
10323     case TREE_LIST:
10324       {
10325         tree purpose, value, chain;
10326
10327         if (t == void_list_node)
10328           return t;
10329
10330         purpose = TREE_PURPOSE (t);
10331         if (purpose)
10332           purpose = tsubst_copy (purpose, args, complain, in_decl);
10333         value = TREE_VALUE (t);
10334         if (value)
10335           value = tsubst_copy (value, args, complain, in_decl);
10336         chain = TREE_CHAIN (t);
10337         if (chain && chain != void_type_node)
10338           chain = tsubst_copy (chain, args, complain, in_decl);
10339         if (purpose == TREE_PURPOSE (t)
10340             && value == TREE_VALUE (t)
10341             && chain == TREE_CHAIN (t))
10342           return t;
10343         return tree_cons (purpose, value, chain);
10344       }
10345
10346     case RECORD_TYPE:
10347     case UNION_TYPE:
10348     case ENUMERAL_TYPE:
10349     case INTEGER_TYPE:
10350     case TEMPLATE_TYPE_PARM:
10351     case TEMPLATE_TEMPLATE_PARM:
10352     case BOUND_TEMPLATE_TEMPLATE_PARM:
10353     case TEMPLATE_PARM_INDEX:
10354     case POINTER_TYPE:
10355     case REFERENCE_TYPE:
10356     case OFFSET_TYPE:
10357     case FUNCTION_TYPE:
10358     case METHOD_TYPE:
10359     case ARRAY_TYPE:
10360     case TYPENAME_TYPE:
10361     case UNBOUND_CLASS_TEMPLATE:
10362     case TYPEOF_TYPE:
10363     case DECLTYPE_TYPE:
10364     case TYPE_DECL:
10365       return tsubst (t, args, complain, in_decl);
10366
10367     case IDENTIFIER_NODE:
10368       if (IDENTIFIER_TYPENAME_P (t))
10369         {
10370           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10371           return mangle_conv_op_name_for_type (new_type);
10372         }
10373       else
10374         return t;
10375
10376     case CONSTRUCTOR:
10377       /* This is handled by tsubst_copy_and_build.  */
10378       gcc_unreachable ();
10379
10380     case VA_ARG_EXPR:
10381       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10382                                           in_decl),
10383                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10384
10385     case CLEANUP_POINT_EXPR:
10386       /* We shouldn't have built any of these during initial template
10387          generation.  Instead, they should be built during instantiation
10388          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10389       gcc_unreachable ();
10390
10391     case OFFSET_REF:
10392       mark_used (TREE_OPERAND (t, 1));
10393       return t;
10394
10395     case EXPR_PACK_EXPANSION:
10396       error ("invalid use of pack expansion expression");
10397       return error_mark_node;
10398
10399     case NONTYPE_ARGUMENT_PACK:
10400       error ("use %<...%> to expand argument pack");
10401       return error_mark_node;
10402
10403     default:
10404       return t;
10405     }
10406 }
10407
10408 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10409
10410 static tree
10411 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10412                     tree in_decl)
10413 {
10414   tree new_clauses = NULL, nc, oc;
10415
10416   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10417     {
10418       nc = copy_node (oc);
10419       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10420       new_clauses = nc;
10421
10422       switch (OMP_CLAUSE_CODE (nc))
10423         {
10424         case OMP_CLAUSE_LASTPRIVATE:
10425           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10426             {
10427               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10428               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10429                            in_decl, /*integral_constant_expression_p=*/false);
10430               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10431                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10432             }
10433           /* FALLTHRU */
10434         case OMP_CLAUSE_PRIVATE:
10435         case OMP_CLAUSE_SHARED:
10436         case OMP_CLAUSE_FIRSTPRIVATE:
10437         case OMP_CLAUSE_REDUCTION:
10438         case OMP_CLAUSE_COPYIN:
10439         case OMP_CLAUSE_COPYPRIVATE:
10440         case OMP_CLAUSE_IF:
10441         case OMP_CLAUSE_NUM_THREADS:
10442         case OMP_CLAUSE_SCHEDULE:
10443         case OMP_CLAUSE_COLLAPSE:
10444           OMP_CLAUSE_OPERAND (nc, 0)
10445             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10446                            in_decl, /*integral_constant_expression_p=*/false);
10447           break;
10448         case OMP_CLAUSE_NOWAIT:
10449         case OMP_CLAUSE_ORDERED:
10450         case OMP_CLAUSE_DEFAULT:
10451         case OMP_CLAUSE_UNTIED:
10452           break;
10453         default:
10454           gcc_unreachable ();
10455         }
10456     }
10457
10458   return finish_omp_clauses (nreverse (new_clauses));
10459 }
10460
10461 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10462
10463 static tree
10464 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10465                           tree in_decl)
10466 {
10467 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10468
10469   tree purpose, value, chain;
10470
10471   if (t == NULL)
10472     return t;
10473
10474   if (TREE_CODE (t) != TREE_LIST)
10475     return tsubst_copy_and_build (t, args, complain, in_decl,
10476                                   /*function_p=*/false,
10477                                   /*integral_constant_expression_p=*/false);
10478
10479   if (t == void_list_node)
10480     return t;
10481
10482   purpose = TREE_PURPOSE (t);
10483   if (purpose)
10484     purpose = RECUR (purpose);
10485   value = TREE_VALUE (t);
10486   if (value)
10487     value = RECUR (value);
10488   chain = TREE_CHAIN (t);
10489   if (chain && chain != void_type_node)
10490     chain = RECUR (chain);
10491   return tree_cons (purpose, value, chain);
10492 #undef RECUR
10493 }
10494
10495 /* Substitute one OMP_FOR iterator.  */
10496
10497 static void
10498 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10499                          tree condv, tree incrv, tree *clauses,
10500                          tree args, tsubst_flags_t complain, tree in_decl,
10501                          bool integral_constant_expression_p)
10502 {
10503 #define RECUR(NODE)                             \
10504   tsubst_expr ((NODE), args, complain, in_decl, \
10505                integral_constant_expression_p)
10506   tree decl, init, cond, incr, auto_node;
10507
10508   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10509   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10510   decl = RECUR (TREE_OPERAND (init, 0));
10511   init = TREE_OPERAND (init, 1);
10512   auto_node = type_uses_auto (TREE_TYPE (decl));
10513   if (auto_node && init)
10514     {
10515       tree init_expr = init;
10516       if (TREE_CODE (init_expr) == DECL_EXPR)
10517         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10518       init_expr = RECUR (init_expr);
10519       TREE_TYPE (decl)
10520         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10521     }
10522   gcc_assert (!type_dependent_expression_p (decl));
10523
10524   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10525     {
10526       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10527       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10528       if (TREE_CODE (incr) == MODIFY_EXPR)
10529         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10530                                     RECUR (TREE_OPERAND (incr, 1)),
10531                                     complain);
10532       else
10533         incr = RECUR (incr);
10534       TREE_VEC_ELT (declv, i) = decl;
10535       TREE_VEC_ELT (initv, i) = init;
10536       TREE_VEC_ELT (condv, i) = cond;
10537       TREE_VEC_ELT (incrv, i) = incr;
10538       return;
10539     }
10540
10541   if (init && TREE_CODE (init) != DECL_EXPR)
10542     {
10543       tree c;
10544       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10545         {
10546           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10547                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10548               && OMP_CLAUSE_DECL (c) == decl)
10549             break;
10550           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10551                    && OMP_CLAUSE_DECL (c) == decl)
10552             error ("iteration variable %qD should not be firstprivate", decl);
10553           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10554                    && OMP_CLAUSE_DECL (c) == decl)
10555             error ("iteration variable %qD should not be reduction", decl);
10556         }
10557       if (c == NULL)
10558         {
10559           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10560           OMP_CLAUSE_DECL (c) = decl;
10561           c = finish_omp_clauses (c);
10562           if (c)
10563             {
10564               OMP_CLAUSE_CHAIN (c) = *clauses;
10565               *clauses = c;
10566             }
10567         }
10568     }
10569   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10570   if (COMPARISON_CLASS_P (cond))
10571     cond = build2 (TREE_CODE (cond), boolean_type_node,
10572                    RECUR (TREE_OPERAND (cond, 0)),
10573                    RECUR (TREE_OPERAND (cond, 1)));
10574   else
10575     cond = RECUR (cond);
10576   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10577   switch (TREE_CODE (incr))
10578     {
10579     case PREINCREMENT_EXPR:
10580     case PREDECREMENT_EXPR:
10581     case POSTINCREMENT_EXPR:
10582     case POSTDECREMENT_EXPR:
10583       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10584                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10585       break;
10586     case MODIFY_EXPR:
10587       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10588           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10589         {
10590           tree rhs = TREE_OPERAND (incr, 1);
10591           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10592                          RECUR (TREE_OPERAND (incr, 0)),
10593                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10594                                  RECUR (TREE_OPERAND (rhs, 0)),
10595                                  RECUR (TREE_OPERAND (rhs, 1))));
10596         }
10597       else
10598         incr = RECUR (incr);
10599       break;
10600     case MODOP_EXPR:
10601       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10602           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10603         {
10604           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10605           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10606                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10607                                  TREE_TYPE (decl), lhs,
10608                                  RECUR (TREE_OPERAND (incr, 2))));
10609         }
10610       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10611                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10612                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10613         {
10614           tree rhs = TREE_OPERAND (incr, 2);
10615           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10616                          RECUR (TREE_OPERAND (incr, 0)),
10617                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10618                                  RECUR (TREE_OPERAND (rhs, 0)),
10619                                  RECUR (TREE_OPERAND (rhs, 1))));
10620         }
10621       else
10622         incr = RECUR (incr);
10623       break;
10624     default:
10625       incr = RECUR (incr);
10626       break;
10627     }
10628
10629   TREE_VEC_ELT (declv, i) = decl;
10630   TREE_VEC_ELT (initv, i) = init;
10631   TREE_VEC_ELT (condv, i) = cond;
10632   TREE_VEC_ELT (incrv, i) = incr;
10633 #undef RECUR
10634 }
10635
10636 /* Like tsubst_copy for expressions, etc. but also does semantic
10637    processing.  */
10638
10639 static tree
10640 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10641              bool integral_constant_expression_p)
10642 {
10643 #define RECUR(NODE)                             \
10644   tsubst_expr ((NODE), args, complain, in_decl, \
10645                integral_constant_expression_p)
10646
10647   tree stmt, tmp;
10648
10649   if (t == NULL_TREE || t == error_mark_node)
10650     return t;
10651
10652   if (EXPR_HAS_LOCATION (t))
10653     input_location = EXPR_LOCATION (t);
10654   if (STATEMENT_CODE_P (TREE_CODE (t)))
10655     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10656
10657   switch (TREE_CODE (t))
10658     {
10659     case STATEMENT_LIST:
10660       {
10661         tree_stmt_iterator i;
10662         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10663           RECUR (tsi_stmt (i));
10664         break;
10665       }
10666
10667     case CTOR_INITIALIZER:
10668       finish_mem_initializers (tsubst_initializer_list
10669                                (TREE_OPERAND (t, 0), args));
10670       break;
10671
10672     case RETURN_EXPR:
10673       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10674       break;
10675
10676     case EXPR_STMT:
10677       tmp = RECUR (EXPR_STMT_EXPR (t));
10678       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10679         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10680       else
10681         finish_expr_stmt (tmp);
10682       break;
10683
10684     case USING_STMT:
10685       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10686       break;
10687
10688     case DECL_EXPR:
10689       {
10690         tree decl;
10691         tree init;
10692
10693         decl = DECL_EXPR_DECL (t);
10694         if (TREE_CODE (decl) == LABEL_DECL)
10695           finish_label_decl (DECL_NAME (decl));
10696         else if (TREE_CODE (decl) == USING_DECL)
10697           {
10698             tree scope = USING_DECL_SCOPE (decl);
10699             tree name = DECL_NAME (decl);
10700             tree decl;
10701
10702             scope = RECUR (scope);
10703             decl = lookup_qualified_name (scope, name,
10704                                           /*is_type_p=*/false,
10705                                           /*complain=*/false);
10706             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10707               qualified_name_lookup_error (scope, name, decl, input_location);
10708             else
10709               do_local_using_decl (decl, scope, name);
10710           }
10711         else
10712           {
10713             init = DECL_INITIAL (decl);
10714             decl = tsubst (decl, args, complain, in_decl);
10715             if (decl != error_mark_node)
10716               {
10717                 /* By marking the declaration as instantiated, we avoid
10718                    trying to instantiate it.  Since instantiate_decl can't
10719                    handle local variables, and since we've already done
10720                    all that needs to be done, that's the right thing to
10721                    do.  */
10722                 if (TREE_CODE (decl) == VAR_DECL)
10723                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10724                 if (TREE_CODE (decl) == VAR_DECL
10725                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10726                   /* Anonymous aggregates are a special case.  */
10727                   finish_anon_union (decl);
10728                 else
10729                   {
10730                     maybe_push_decl (decl);
10731                     if (TREE_CODE (decl) == VAR_DECL
10732                         && DECL_PRETTY_FUNCTION_P (decl))
10733                       {
10734                         /* For __PRETTY_FUNCTION__ we have to adjust the
10735                            initializer.  */
10736                         const char *const name
10737                           = cxx_printable_name (current_function_decl, 2);
10738                         init = cp_fname_init (name, &TREE_TYPE (decl));
10739                       }
10740                     else
10741                       {
10742                         tree t = RECUR (init);
10743
10744                         if (init && !t)
10745                           /* If we had an initializer but it
10746                              instantiated to nothing,
10747                              value-initialize the object.  This will
10748                              only occur when the initializer was a
10749                              pack expansion where the parameter packs
10750                              used in that expansion were of length
10751                              zero.  */
10752                           init = build_value_init (TREE_TYPE (decl));
10753                         else
10754                           init = t;
10755                       }
10756
10757                     finish_decl (decl, init, NULL_TREE);
10758                   }
10759               }
10760           }
10761
10762         /* A DECL_EXPR can also be used as an expression, in the condition
10763            clause of an if/for/while construct.  */
10764         return decl;
10765       }
10766
10767     case FOR_STMT:
10768       stmt = begin_for_stmt ();
10769                           RECUR (FOR_INIT_STMT (t));
10770       finish_for_init_stmt (stmt);
10771       tmp = RECUR (FOR_COND (t));
10772       finish_for_cond (tmp, stmt);
10773       tmp = RECUR (FOR_EXPR (t));
10774       finish_for_expr (tmp, stmt);
10775       RECUR (FOR_BODY (t));
10776       finish_for_stmt (stmt);
10777       break;
10778
10779     case WHILE_STMT:
10780       stmt = begin_while_stmt ();
10781       tmp = RECUR (WHILE_COND (t));
10782       finish_while_stmt_cond (tmp, stmt);
10783       RECUR (WHILE_BODY (t));
10784       finish_while_stmt (stmt);
10785       break;
10786
10787     case DO_STMT:
10788       stmt = begin_do_stmt ();
10789       RECUR (DO_BODY (t));
10790       finish_do_body (stmt);
10791       tmp = RECUR (DO_COND (t));
10792       finish_do_stmt (tmp, stmt);
10793       break;
10794
10795     case IF_STMT:
10796       stmt = begin_if_stmt ();
10797       tmp = RECUR (IF_COND (t));
10798       finish_if_stmt_cond (tmp, stmt);
10799       RECUR (THEN_CLAUSE (t));
10800       finish_then_clause (stmt);
10801
10802       if (ELSE_CLAUSE (t))
10803         {
10804           begin_else_clause (stmt);
10805           RECUR (ELSE_CLAUSE (t));
10806           finish_else_clause (stmt);
10807         }
10808
10809       finish_if_stmt (stmt);
10810       break;
10811
10812     case BIND_EXPR:
10813       if (BIND_EXPR_BODY_BLOCK (t))
10814         stmt = begin_function_body ();
10815       else
10816         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10817                                     ? BCS_TRY_BLOCK : 0);
10818
10819       RECUR (BIND_EXPR_BODY (t));
10820
10821       if (BIND_EXPR_BODY_BLOCK (t))
10822         finish_function_body (stmt);
10823       else
10824         finish_compound_stmt (stmt);
10825       break;
10826
10827     case BREAK_STMT:
10828       finish_break_stmt ();
10829       break;
10830
10831     case CONTINUE_STMT:
10832       finish_continue_stmt ();
10833       break;
10834
10835     case SWITCH_STMT:
10836       stmt = begin_switch_stmt ();
10837       tmp = RECUR (SWITCH_STMT_COND (t));
10838       finish_switch_cond (tmp, stmt);
10839       RECUR (SWITCH_STMT_BODY (t));
10840       finish_switch_stmt (stmt);
10841       break;
10842
10843     case CASE_LABEL_EXPR:
10844       finish_case_label (RECUR (CASE_LOW (t)),
10845                          RECUR (CASE_HIGH (t)));
10846       break;
10847
10848     case LABEL_EXPR:
10849       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10850       break;
10851
10852     case GOTO_EXPR:
10853       tmp = GOTO_DESTINATION (t);
10854       if (TREE_CODE (tmp) != LABEL_DECL)
10855         /* Computed goto's must be tsubst'd into.  On the other hand,
10856            non-computed gotos must not be; the identifier in question
10857            will have no binding.  */
10858         tmp = RECUR (tmp);
10859       else
10860         tmp = DECL_NAME (tmp);
10861       finish_goto_stmt (tmp);
10862       break;
10863
10864     case ASM_EXPR:
10865       tmp = finish_asm_stmt
10866         (ASM_VOLATILE_P (t),
10867          RECUR (ASM_STRING (t)),
10868          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10869          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10870          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10871       {
10872         tree asm_expr = tmp;
10873         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10874           asm_expr = TREE_OPERAND (asm_expr, 0);
10875         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10876       }
10877       break;
10878
10879     case TRY_BLOCK:
10880       if (CLEANUP_P (t))
10881         {
10882           stmt = begin_try_block ();
10883           RECUR (TRY_STMTS (t));
10884           finish_cleanup_try_block (stmt);
10885           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10886         }
10887       else
10888         {
10889           tree compound_stmt = NULL_TREE;
10890
10891           if (FN_TRY_BLOCK_P (t))
10892             stmt = begin_function_try_block (&compound_stmt);
10893           else
10894             stmt = begin_try_block ();
10895
10896           RECUR (TRY_STMTS (t));
10897
10898           if (FN_TRY_BLOCK_P (t))
10899             finish_function_try_block (stmt);
10900           else
10901             finish_try_block (stmt);
10902
10903           RECUR (TRY_HANDLERS (t));
10904           if (FN_TRY_BLOCK_P (t))
10905             finish_function_handler_sequence (stmt, compound_stmt);
10906           else
10907             finish_handler_sequence (stmt);
10908         }
10909       break;
10910
10911     case HANDLER:
10912       {
10913         tree decl = HANDLER_PARMS (t);
10914
10915         if (decl)
10916           {
10917             decl = tsubst (decl, args, complain, in_decl);
10918             /* Prevent instantiate_decl from trying to instantiate
10919                this variable.  We've already done all that needs to be
10920                done.  */
10921             if (decl != error_mark_node)
10922               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10923           }
10924         stmt = begin_handler ();
10925         finish_handler_parms (decl, stmt);
10926         RECUR (HANDLER_BODY (t));
10927         finish_handler (stmt);
10928       }
10929       break;
10930
10931     case TAG_DEFN:
10932       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10933       break;
10934
10935     case STATIC_ASSERT:
10936       {
10937         tree condition = 
10938           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10939                        args,
10940                        complain, in_decl,
10941                        /*integral_constant_expression_p=*/true);
10942         finish_static_assert (condition,
10943                               STATIC_ASSERT_MESSAGE (t),
10944                               STATIC_ASSERT_SOURCE_LOCATION (t),
10945                               /*member_p=*/false);
10946       }
10947       break;
10948
10949     case OMP_PARALLEL:
10950       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10951                                 args, complain, in_decl);
10952       stmt = begin_omp_parallel ();
10953       RECUR (OMP_PARALLEL_BODY (t));
10954       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10955         = OMP_PARALLEL_COMBINED (t);
10956       break;
10957
10958     case OMP_TASK:
10959       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
10960                                 args, complain, in_decl);
10961       stmt = begin_omp_task ();
10962       RECUR (OMP_TASK_BODY (t));
10963       finish_omp_task (tmp, stmt);
10964       break;
10965
10966     case OMP_FOR:
10967       {
10968         tree clauses, body, pre_body;
10969         tree declv, initv, condv, incrv;
10970         int i;
10971
10972         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10973                                       args, complain, in_decl);
10974         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10975         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10976         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10977         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10978
10979         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
10980           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
10981                                    &clauses, args, complain, in_decl,
10982                                    integral_constant_expression_p);
10983
10984         stmt = begin_omp_structured_block ();
10985
10986         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
10987           if (TREE_VEC_ELT (initv, i) == NULL
10988               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
10989             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
10990           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
10991             {
10992               tree init = RECUR (TREE_VEC_ELT (initv, i));
10993               gcc_assert (init == TREE_VEC_ELT (declv, i));
10994               TREE_VEC_ELT (initv, i) = NULL_TREE;
10995             }
10996           else
10997             {
10998               tree decl_expr = TREE_VEC_ELT (initv, i);
10999               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11000               gcc_assert (init != NULL);
11001               TREE_VEC_ELT (initv, i) = RECUR (init);
11002               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11003               RECUR (decl_expr);
11004               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11005             }
11006
11007         pre_body = push_stmt_list ();
11008         RECUR (OMP_FOR_PRE_BODY (t));
11009         pre_body = pop_stmt_list (pre_body);
11010
11011         body = push_stmt_list ();
11012         RECUR (OMP_FOR_BODY (t));
11013         body = pop_stmt_list (body);
11014
11015         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11016                             body, pre_body, clauses);
11017
11018         add_stmt (finish_omp_structured_block (stmt));
11019       }
11020       break;
11021
11022     case OMP_SECTIONS:
11023     case OMP_SINGLE:
11024       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11025       stmt = push_stmt_list ();
11026       RECUR (OMP_BODY (t));
11027       stmt = pop_stmt_list (stmt);
11028
11029       t = copy_node (t);
11030       OMP_BODY (t) = stmt;
11031       OMP_CLAUSES (t) = tmp;
11032       add_stmt (t);
11033       break;
11034
11035     case OMP_SECTION:
11036     case OMP_CRITICAL:
11037     case OMP_MASTER:
11038     case OMP_ORDERED:
11039       stmt = push_stmt_list ();
11040       RECUR (OMP_BODY (t));
11041       stmt = pop_stmt_list (stmt);
11042
11043       t = copy_node (t);
11044       OMP_BODY (t) = stmt;
11045       add_stmt (t);
11046       break;
11047
11048     case OMP_ATOMIC:
11049       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11050       {
11051         tree op1 = TREE_OPERAND (t, 1);
11052         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11053         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11054         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11055       }
11056       break;
11057
11058     case EXPR_PACK_EXPANSION:
11059       error ("invalid use of pack expansion expression");
11060       return error_mark_node;
11061
11062     case NONTYPE_ARGUMENT_PACK:
11063       error ("use %<...%> to expand argument pack");
11064       return error_mark_node;
11065
11066     default:
11067       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11068
11069       return tsubst_copy_and_build (t, args, complain, in_decl,
11070                                     /*function_p=*/false,
11071                                     integral_constant_expression_p);
11072     }
11073
11074   return NULL_TREE;
11075 #undef RECUR
11076 }
11077
11078 /* T is a postfix-expression that is not being used in a function
11079    call.  Return the substituted version of T.  */
11080
11081 static tree
11082 tsubst_non_call_postfix_expression (tree t, tree args,
11083                                     tsubst_flags_t complain,
11084                                     tree in_decl)
11085 {
11086   if (TREE_CODE (t) == SCOPE_REF)
11087     t = tsubst_qualified_id (t, args, complain, in_decl,
11088                              /*done=*/false, /*address_p=*/false);
11089   else
11090     t = tsubst_copy_and_build (t, args, complain, in_decl,
11091                                /*function_p=*/false,
11092                                /*integral_constant_expression_p=*/false);
11093
11094   return t;
11095 }
11096
11097 /* Like tsubst but deals with expressions and performs semantic
11098    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11099
11100 tree
11101 tsubst_copy_and_build (tree t,
11102                        tree args,
11103                        tsubst_flags_t complain,
11104                        tree in_decl,
11105                        bool function_p,
11106                        bool integral_constant_expression_p)
11107 {
11108 #define RECUR(NODE)                                             \
11109   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11110                          /*function_p=*/false,                  \
11111                          integral_constant_expression_p)
11112
11113   tree op1;
11114
11115   if (t == NULL_TREE || t == error_mark_node)
11116     return t;
11117
11118   switch (TREE_CODE (t))
11119     {
11120     case USING_DECL:
11121       t = DECL_NAME (t);
11122       /* Fall through.  */
11123     case IDENTIFIER_NODE:
11124       {
11125         tree decl;
11126         cp_id_kind idk;
11127         bool non_integral_constant_expression_p;
11128         const char *error_msg;
11129
11130         if (IDENTIFIER_TYPENAME_P (t))
11131           {
11132             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11133             t = mangle_conv_op_name_for_type (new_type);
11134           }
11135
11136         /* Look up the name.  */
11137         decl = lookup_name (t);
11138
11139         /* By convention, expressions use ERROR_MARK_NODE to indicate
11140            failure, not NULL_TREE.  */
11141         if (decl == NULL_TREE)
11142           decl = error_mark_node;
11143
11144         decl = finish_id_expression (t, decl, NULL_TREE,
11145                                      &idk,
11146                                      integral_constant_expression_p,
11147                                      /*allow_non_integral_constant_expression_p=*/false,
11148                                      &non_integral_constant_expression_p,
11149                                      /*template_p=*/false,
11150                                      /*done=*/true,
11151                                      /*address_p=*/false,
11152                                      /*template_arg_p=*/false,
11153                                      &error_msg,
11154                                      input_location);
11155         if (error_msg)
11156           error (error_msg);
11157         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11158           decl = unqualified_name_lookup_error (decl);
11159         return decl;
11160       }
11161
11162     case TEMPLATE_ID_EXPR:
11163       {
11164         tree object;
11165         tree templ = RECUR (TREE_OPERAND (t, 0));
11166         tree targs = TREE_OPERAND (t, 1);
11167
11168         if (targs)
11169           targs = tsubst_template_args (targs, args, complain, in_decl);
11170
11171         if (TREE_CODE (templ) == COMPONENT_REF)
11172           {
11173             object = TREE_OPERAND (templ, 0);
11174             templ = TREE_OPERAND (templ, 1);
11175           }
11176         else
11177           object = NULL_TREE;
11178         templ = lookup_template_function (templ, targs);
11179
11180         if (object)
11181           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11182                          object, templ, NULL_TREE);
11183         else
11184           return baselink_for_fns (templ);
11185       }
11186
11187     case INDIRECT_REF:
11188       {
11189         tree r = RECUR (TREE_OPERAND (t, 0));
11190
11191         if (REFERENCE_REF_P (t))
11192           {
11193             /* A type conversion to reference type will be enclosed in
11194                such an indirect ref, but the substitution of the cast
11195                will have also added such an indirect ref.  */
11196             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11197               r = convert_from_reference (r);
11198           }
11199         else
11200           r = build_x_indirect_ref (r, "unary *", complain);
11201         return r;
11202       }
11203
11204     case NOP_EXPR:
11205       return build_nop
11206         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11207          RECUR (TREE_OPERAND (t, 0)));
11208
11209     case CAST_EXPR:
11210     case REINTERPRET_CAST_EXPR:
11211     case CONST_CAST_EXPR:
11212     case DYNAMIC_CAST_EXPR:
11213     case STATIC_CAST_EXPR:
11214       {
11215         tree type;
11216         tree op;
11217
11218         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11219         if (integral_constant_expression_p
11220             && !cast_valid_in_integral_constant_expression_p (type))
11221           {
11222             if (complain & tf_error)
11223               error ("a cast to a type other than an integral or "
11224                      "enumeration type cannot appear in a constant-expression");
11225             return error_mark_node; 
11226           }
11227
11228         op = RECUR (TREE_OPERAND (t, 0));
11229
11230         switch (TREE_CODE (t))
11231           {
11232           case CAST_EXPR:
11233             return build_functional_cast (type, op, complain);
11234           case REINTERPRET_CAST_EXPR:
11235             return build_reinterpret_cast (type, op, complain);
11236           case CONST_CAST_EXPR:
11237             return build_const_cast (type, op, complain);
11238           case DYNAMIC_CAST_EXPR:
11239             return build_dynamic_cast (type, op, complain);
11240           case STATIC_CAST_EXPR:
11241             return build_static_cast (type, op, complain);
11242           default:
11243             gcc_unreachable ();
11244           }
11245       }
11246
11247     case POSTDECREMENT_EXPR:
11248     case POSTINCREMENT_EXPR:
11249       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11250                                                 args, complain, in_decl);
11251       return build_x_unary_op (TREE_CODE (t), op1, complain);
11252
11253     case PREDECREMENT_EXPR:
11254     case PREINCREMENT_EXPR:
11255     case NEGATE_EXPR:
11256     case BIT_NOT_EXPR:
11257     case ABS_EXPR:
11258     case TRUTH_NOT_EXPR:
11259     case UNARY_PLUS_EXPR:  /* Unary + */
11260     case REALPART_EXPR:
11261     case IMAGPART_EXPR:
11262       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11263                                complain);
11264
11265     case ADDR_EXPR:
11266       op1 = TREE_OPERAND (t, 0);
11267       if (TREE_CODE (op1) == SCOPE_REF)
11268         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11269                                    /*done=*/true, /*address_p=*/true);
11270       else
11271         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11272                                                   in_decl);
11273       if (TREE_CODE (op1) == LABEL_DECL)
11274         return finish_label_address_expr (DECL_NAME (op1),
11275                                           EXPR_LOCATION (op1));
11276       return build_x_unary_op (ADDR_EXPR, op1, complain);
11277
11278     case PLUS_EXPR:
11279     case MINUS_EXPR:
11280     case MULT_EXPR:
11281     case TRUNC_DIV_EXPR:
11282     case CEIL_DIV_EXPR:
11283     case FLOOR_DIV_EXPR:
11284     case ROUND_DIV_EXPR:
11285     case EXACT_DIV_EXPR:
11286     case BIT_AND_EXPR:
11287     case BIT_IOR_EXPR:
11288     case BIT_XOR_EXPR:
11289     case TRUNC_MOD_EXPR:
11290     case FLOOR_MOD_EXPR:
11291     case TRUTH_ANDIF_EXPR:
11292     case TRUTH_ORIF_EXPR:
11293     case TRUTH_AND_EXPR:
11294     case TRUTH_OR_EXPR:
11295     case RSHIFT_EXPR:
11296     case LSHIFT_EXPR:
11297     case RROTATE_EXPR:
11298     case LROTATE_EXPR:
11299     case EQ_EXPR:
11300     case NE_EXPR:
11301     case MAX_EXPR:
11302     case MIN_EXPR:
11303     case LE_EXPR:
11304     case GE_EXPR:
11305     case LT_EXPR:
11306     case GT_EXPR:
11307     case MEMBER_REF:
11308     case DOTSTAR_EXPR:
11309       return build_x_binary_op
11310         (TREE_CODE (t),
11311          RECUR (TREE_OPERAND (t, 0)),
11312          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11313           ? ERROR_MARK
11314           : TREE_CODE (TREE_OPERAND (t, 0))),
11315          RECUR (TREE_OPERAND (t, 1)),
11316          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11317           ? ERROR_MARK
11318           : TREE_CODE (TREE_OPERAND (t, 1))),
11319          /*overloaded_p=*/NULL,
11320          complain);
11321
11322     case SCOPE_REF:
11323       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11324                                   /*address_p=*/false);
11325     case ARRAY_REF:
11326       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11327                                                 args, complain, in_decl);
11328       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11329
11330     case SIZEOF_EXPR:
11331       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11332         return tsubst_copy (t, args, complain, in_decl);
11333       /* Fall through */
11334       
11335     case ALIGNOF_EXPR:
11336       op1 = TREE_OPERAND (t, 0);
11337       if (!args)
11338         {
11339           /* When there are no ARGS, we are trying to evaluate a
11340              non-dependent expression from the parser.  Trying to do
11341              the substitutions may not work.  */
11342           if (!TYPE_P (op1))
11343             op1 = TREE_TYPE (op1);
11344         }
11345       else
11346         {
11347           ++skip_evaluation;
11348           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11349                                        /*function_p=*/false,
11350                                        /*integral_constant_expression_p=*/false);
11351           --skip_evaluation;
11352         }
11353       if (TYPE_P (op1))
11354         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11355                                            complain & tf_error);
11356       else
11357         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11358                                            complain & tf_error);
11359
11360     case MODOP_EXPR:
11361       {
11362         tree r = build_x_modify_expr
11363           (RECUR (TREE_OPERAND (t, 0)),
11364            TREE_CODE (TREE_OPERAND (t, 1)),
11365            RECUR (TREE_OPERAND (t, 2)),
11366            complain);
11367         /* TREE_NO_WARNING must be set if either the expression was
11368            parenthesized or it uses an operator such as >>= rather
11369            than plain assignment.  In the former case, it was already
11370            set and must be copied.  In the latter case,
11371            build_x_modify_expr sets it and it must not be reset
11372            here.  */
11373         if (TREE_NO_WARNING (t))
11374           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11375         return r;
11376       }
11377
11378     case ARROW_EXPR:
11379       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11380                                                 args, complain, in_decl);
11381       /* Remember that there was a reference to this entity.  */
11382       if (DECL_P (op1))
11383         mark_used (op1);
11384       return build_x_arrow (op1);
11385
11386     case NEW_EXPR:
11387       {
11388         tree init = RECUR (TREE_OPERAND (t, 3));
11389
11390         if (TREE_OPERAND (t, 3) && !init)
11391           /* If there was an initializer in the original tree, but
11392              it instantiated to an empty list, then we should pass on
11393              VOID_ZERO_NODE to tell build_new that it was an empty
11394              initializer () rather than no initializer.  This can only
11395              happen when the initializer is a pack expansion whose
11396              parameter packs are of length zero.  */
11397           init = void_zero_node;
11398
11399         return build_new
11400           (RECUR (TREE_OPERAND (t, 0)),
11401            RECUR (TREE_OPERAND (t, 1)),
11402            RECUR (TREE_OPERAND (t, 2)),
11403            init,
11404            NEW_EXPR_USE_GLOBAL (t),
11405            complain);
11406       }
11407
11408     case DELETE_EXPR:
11409      return delete_sanity
11410        (RECUR (TREE_OPERAND (t, 0)),
11411         RECUR (TREE_OPERAND (t, 1)),
11412         DELETE_EXPR_USE_VEC (t),
11413         DELETE_EXPR_USE_GLOBAL (t));
11414
11415     case COMPOUND_EXPR:
11416       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11417                                     RECUR (TREE_OPERAND (t, 1)),
11418                                     complain);
11419
11420     case CALL_EXPR:
11421       {
11422         tree function;
11423         tree call_args;
11424         bool qualified_p;
11425         bool koenig_p;
11426
11427         function = CALL_EXPR_FN (t);
11428         /* When we parsed the expression,  we determined whether or
11429            not Koenig lookup should be performed.  */
11430         koenig_p = KOENIG_LOOKUP_P (t);
11431         if (TREE_CODE (function) == SCOPE_REF)
11432           {
11433             qualified_p = true;
11434             function = tsubst_qualified_id (function, args, complain, in_decl,
11435                                             /*done=*/false,
11436                                             /*address_p=*/false);
11437           }
11438         else
11439           {
11440             if (TREE_CODE (function) == COMPONENT_REF)
11441               {
11442                 tree op = TREE_OPERAND (function, 1);
11443
11444                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11445                                || (BASELINK_P (op)
11446                                    && BASELINK_QUALIFIED_P (op)));
11447               }
11448             else
11449               qualified_p = false;
11450
11451             function = tsubst_copy_and_build (function, args, complain,
11452                                               in_decl,
11453                                               !qualified_p,
11454                                               integral_constant_expression_p);
11455
11456             if (BASELINK_P (function))
11457               qualified_p = true;
11458           }
11459
11460         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11461         call_args = RECUR (CALL_EXPR_ARGS (t));
11462
11463         /* We do not perform argument-dependent lookup if normal
11464            lookup finds a non-function, in accordance with the
11465            expected resolution of DR 218.  */
11466         if (koenig_p
11467             && ((is_overloaded_fn (function)
11468                  /* If lookup found a member function, the Koenig lookup is
11469                     not appropriate, even if an unqualified-name was used
11470                     to denote the function.  */
11471                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11472                 || TREE_CODE (function) == IDENTIFIER_NODE)
11473             /* Only do this when substitution turns a dependent call
11474                into a non-dependent call.  */
11475             && type_dependent_expression_p_push (t)
11476             && !any_type_dependent_arguments_p (call_args))
11477           function = perform_koenig_lookup (function, call_args);
11478
11479         if (TREE_CODE (function) == IDENTIFIER_NODE)
11480           {
11481             unqualified_name_lookup_error (function);
11482             return error_mark_node;
11483           }
11484
11485         /* Remember that there was a reference to this entity.  */
11486         if (DECL_P (function))
11487           mark_used (function);
11488
11489         if (TREE_CODE (function) == OFFSET_REF)
11490           return build_offset_ref_call_from_tree (function, call_args);
11491         if (TREE_CODE (function) == COMPONENT_REF)
11492           {
11493             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11494               return finish_call_expr (function, call_args,
11495                                        /*disallow_virtual=*/false,
11496                                        /*koenig_p=*/false,
11497                                        complain);
11498             else
11499               return (build_new_method_call
11500                       (TREE_OPERAND (function, 0),
11501                        TREE_OPERAND (function, 1),
11502                        call_args, NULL_TREE,
11503                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11504                        /*fn_p=*/NULL,
11505                        complain));
11506           }
11507         return finish_call_expr (function, call_args,
11508                                  /*disallow_virtual=*/qualified_p,
11509                                  koenig_p,
11510                                  complain);
11511       }
11512
11513     case COND_EXPR:
11514       return build_x_conditional_expr
11515         (RECUR (TREE_OPERAND (t, 0)),
11516          RECUR (TREE_OPERAND (t, 1)),
11517          RECUR (TREE_OPERAND (t, 2)),
11518          complain);
11519
11520     case PSEUDO_DTOR_EXPR:
11521       return finish_pseudo_destructor_expr
11522         (RECUR (TREE_OPERAND (t, 0)),
11523          RECUR (TREE_OPERAND (t, 1)),
11524          RECUR (TREE_OPERAND (t, 2)));
11525
11526     case TREE_LIST:
11527       {
11528         tree purpose, value, chain;
11529
11530         if (t == void_list_node)
11531           return t;
11532
11533         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11534             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11535           {
11536             /* We have pack expansions, so expand those and
11537                create a new list out of it.  */
11538             tree purposevec = NULL_TREE;
11539             tree valuevec = NULL_TREE;
11540             tree chain;
11541             int i, len = -1;
11542
11543             /* Expand the argument expressions.  */
11544             if (TREE_PURPOSE (t))
11545               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11546                                                  complain, in_decl);
11547             if (TREE_VALUE (t))
11548               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11549                                                complain, in_decl);
11550
11551             /* Build the rest of the list.  */
11552             chain = TREE_CHAIN (t);
11553             if (chain && chain != void_type_node)
11554               chain = RECUR (chain);
11555
11556             /* Determine the number of arguments.  */
11557             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11558               {
11559                 len = TREE_VEC_LENGTH (purposevec);
11560                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11561               }
11562             else if (TREE_CODE (valuevec) == TREE_VEC)
11563               len = TREE_VEC_LENGTH (valuevec);
11564             else
11565               {
11566                 /* Since we only performed a partial substitution into
11567                    the argument pack, we only return a single list
11568                    node.  */
11569                 if (purposevec == TREE_PURPOSE (t)
11570                     && valuevec == TREE_VALUE (t)
11571                     && chain == TREE_CHAIN (t))
11572                   return t;
11573
11574                 return tree_cons (purposevec, valuevec, chain);
11575               }
11576             
11577             /* Convert the argument vectors into a TREE_LIST */
11578             i = len;
11579             while (i > 0)
11580               {
11581                 /* Grab the Ith values.  */
11582                 i--;
11583                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11584                                      : NULL_TREE;
11585                 value 
11586                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11587                              : NULL_TREE;
11588
11589                 /* Build the list (backwards).  */
11590                 chain = tree_cons (purpose, value, chain);
11591               }
11592
11593             return chain;
11594           }
11595
11596         purpose = TREE_PURPOSE (t);
11597         if (purpose)
11598           purpose = RECUR (purpose);
11599         value = TREE_VALUE (t);
11600         if (value)
11601           value = RECUR (value);
11602         chain = TREE_CHAIN (t);
11603         if (chain && chain != void_type_node)
11604           chain = RECUR (chain);
11605         if (purpose == TREE_PURPOSE (t)
11606             && value == TREE_VALUE (t)
11607             && chain == TREE_CHAIN (t))
11608           return t;
11609         return tree_cons (purpose, value, chain);
11610       }
11611
11612     case COMPONENT_REF:
11613       {
11614         tree object;
11615         tree object_type;
11616         tree member;
11617
11618         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11619                                                      args, complain, in_decl);
11620         /* Remember that there was a reference to this entity.  */
11621         if (DECL_P (object))
11622           mark_used (object);
11623         object_type = TREE_TYPE (object);
11624
11625         member = TREE_OPERAND (t, 1);
11626         if (BASELINK_P (member))
11627           member = tsubst_baselink (member,
11628                                     non_reference (TREE_TYPE (object)),
11629                                     args, complain, in_decl);
11630         else
11631           member = tsubst_copy (member, args, complain, in_decl);
11632         if (member == error_mark_node)
11633           return error_mark_node;
11634
11635         if (object_type && !CLASS_TYPE_P (object_type))
11636           {
11637             if (SCALAR_TYPE_P (object_type))
11638               {
11639                 tree s = NULL_TREE;
11640                 tree dtor = member;
11641
11642                 if (TREE_CODE (dtor) == SCOPE_REF)
11643                   {
11644                     s = TREE_OPERAND (dtor, 0);
11645                     dtor = TREE_OPERAND (dtor, 1);
11646                   }
11647                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11648                   {
11649                     dtor = TREE_OPERAND (dtor, 0);
11650                     if (TYPE_P (dtor))
11651                       return finish_pseudo_destructor_expr (object, s, dtor);
11652                   }
11653               }
11654           }
11655         else if (TREE_CODE (member) == SCOPE_REF
11656                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11657           {
11658             tree tmpl;
11659             tree args;
11660
11661             /* Lookup the template functions now that we know what the
11662                scope is.  */
11663             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11664             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11665             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11666                                             /*is_type_p=*/false,
11667                                             /*complain=*/false);
11668             if (BASELINK_P (member))
11669               {
11670                 BASELINK_FUNCTIONS (member)
11671                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11672                               args);
11673                 member = (adjust_result_of_qualified_name_lookup
11674                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11675                            object_type));
11676               }
11677             else
11678               {
11679                 qualified_name_lookup_error (object_type, tmpl, member,
11680                                              input_location);
11681                 return error_mark_node;
11682               }
11683           }
11684         else if (TREE_CODE (member) == SCOPE_REF
11685                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11686                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11687           {
11688             if (complain & tf_error)
11689               {
11690                 if (TYPE_P (TREE_OPERAND (member, 0)))
11691                   error ("%qT is not a class or namespace",
11692                          TREE_OPERAND (member, 0));
11693                 else
11694                   error ("%qD is not a class or namespace",
11695                          TREE_OPERAND (member, 0));
11696               }
11697             return error_mark_node;
11698           }
11699         else if (TREE_CODE (member) == FIELD_DECL)
11700           return finish_non_static_data_member (member, object, NULL_TREE);
11701
11702         return finish_class_member_access_expr (object, member,
11703                                                 /*template_p=*/false,
11704                                                 complain);
11705       }
11706
11707     case THROW_EXPR:
11708       return build_throw
11709         (RECUR (TREE_OPERAND (t, 0)));
11710
11711     case CONSTRUCTOR:
11712       {
11713         VEC(constructor_elt,gc) *n;
11714         constructor_elt *ce;
11715         unsigned HOST_WIDE_INT idx;
11716         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11717         bool process_index_p;
11718         int newlen;
11719         bool need_copy_p = false;
11720         tree r;
11721
11722         if (type == error_mark_node)
11723           return error_mark_node;
11724
11725         /* digest_init will do the wrong thing if we let it.  */
11726         if (type && TYPE_PTRMEMFUNC_P (type))
11727           return t;
11728
11729         /* We do not want to process the index of aggregate
11730            initializers as they are identifier nodes which will be
11731            looked up by digest_init.  */
11732         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11733
11734         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11735         newlen = VEC_length (constructor_elt, n);
11736         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11737           {
11738             if (ce->index && process_index_p)
11739               ce->index = RECUR (ce->index);
11740
11741             if (PACK_EXPANSION_P (ce->value))
11742               {
11743                 /* Substitute into the pack expansion.  */
11744                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11745                                                   in_decl);
11746
11747                 if (ce->value == error_mark_node)
11748                   ;
11749                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11750                   /* Just move the argument into place.  */
11751                   ce->value = TREE_VEC_ELT (ce->value, 0);
11752                 else
11753                   {
11754                     /* Update the length of the final CONSTRUCTOR
11755                        arguments vector, and note that we will need to
11756                        copy.*/
11757                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11758                     need_copy_p = true;
11759                   }
11760               }
11761             else
11762               ce->value = RECUR (ce->value);
11763           }
11764
11765         if (need_copy_p)
11766           {
11767             VEC(constructor_elt,gc) *old_n = n;
11768
11769             n = VEC_alloc (constructor_elt, gc, newlen);
11770             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11771                  idx++)
11772               {
11773                 if (TREE_CODE (ce->value) == TREE_VEC)
11774                   {
11775                     int i, len = TREE_VEC_LENGTH (ce->value);
11776                     for (i = 0; i < len; ++i)
11777                       CONSTRUCTOR_APPEND_ELT (n, 0,
11778                                               TREE_VEC_ELT (ce->value, i));
11779                   }
11780                 else
11781                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11782               }
11783           }
11784
11785         r = build_constructor (init_list_type_node, n);
11786         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11787
11788         if (TREE_HAS_CONSTRUCTOR (t))
11789           return finish_compound_literal (type, r);
11790
11791         return r;
11792       }
11793
11794     case TYPEID_EXPR:
11795       {
11796         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11797         if (TYPE_P (operand_0))
11798           return get_typeid (operand_0);
11799         return build_typeid (operand_0);
11800       }
11801
11802     case VAR_DECL:
11803       if (!args)
11804         return t;
11805       /* Fall through */
11806
11807     case PARM_DECL:
11808       {
11809         tree r = tsubst_copy (t, args, complain, in_decl);
11810
11811         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11812           /* If the original type was a reference, we'll be wrapped in
11813              the appropriate INDIRECT_REF.  */
11814           r = convert_from_reference (r);
11815         return r;
11816       }
11817
11818     case VA_ARG_EXPR:
11819       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11820                              tsubst_copy (TREE_TYPE (t), args, complain,
11821                                           in_decl));
11822
11823     case OFFSETOF_EXPR:
11824       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11825
11826     case TRAIT_EXPR:
11827       {
11828         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11829                                   complain, in_decl);
11830
11831         tree type2 = TRAIT_EXPR_TYPE2 (t);
11832         if (type2)
11833           type2 = tsubst_copy (type2, args, complain, in_decl);
11834         
11835         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11836       }
11837
11838     case STMT_EXPR:
11839       {
11840         tree old_stmt_expr = cur_stmt_expr;
11841         tree stmt_expr = begin_stmt_expr ();
11842
11843         cur_stmt_expr = stmt_expr;
11844         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11845                      integral_constant_expression_p);
11846         stmt_expr = finish_stmt_expr (stmt_expr, false);
11847         cur_stmt_expr = old_stmt_expr;
11848
11849         return stmt_expr;
11850       }
11851
11852     case CONST_DECL:
11853       t = tsubst_copy (t, args, complain, in_decl);
11854       /* As in finish_id_expression, we resolve enumeration constants
11855          to their underlying values.  */
11856       if (TREE_CODE (t) == CONST_DECL)
11857         {
11858           used_types_insert (TREE_TYPE (t));
11859           return DECL_INITIAL (t);
11860         }
11861       return t;
11862
11863     default:
11864       /* Handle Objective-C++ constructs, if appropriate.  */
11865       {
11866         tree subst
11867           = objcp_tsubst_copy_and_build (t, args, complain,
11868                                          in_decl, /*function_p=*/false);
11869         if (subst)
11870           return subst;
11871       }
11872       return tsubst_copy (t, args, complain, in_decl);
11873     }
11874
11875 #undef RECUR
11876 }
11877
11878 /* Verify that the instantiated ARGS are valid. For type arguments,
11879    make sure that the type's linkage is ok. For non-type arguments,
11880    make sure they are constants if they are integral or enumerations.
11881    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11882
11883 static bool
11884 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
11885 {
11886   if (ARGUMENT_PACK_P (t))
11887     {
11888       tree vec = ARGUMENT_PACK_ARGS (t);
11889       int len = TREE_VEC_LENGTH (vec);
11890       bool result = false;
11891       int i;
11892
11893       for (i = 0; i < len; ++i)
11894         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
11895           result = true;
11896       return result;
11897     }
11898   else if (TYPE_P (t))
11899     {
11900       /* [basic.link]: A name with no linkage (notably, the name
11901          of a class or enumeration declared in a local scope)
11902          shall not be used to declare an entity with linkage.
11903          This implies that names with no linkage cannot be used as
11904          template arguments.  */
11905       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11906
11907       if (nt)
11908         {
11909           /* DR 488 makes use of a type with no linkage cause
11910              type deduction to fail.  */
11911           if (complain & tf_error)
11912             {
11913               if (TYPE_ANONYMOUS_P (nt))
11914                 error ("%qT is/uses anonymous type", t);
11915               else
11916                 error ("template argument for %qD uses local type %qT",
11917                        tmpl, t);
11918             }
11919           return true;
11920         }
11921       /* In order to avoid all sorts of complications, we do not
11922          allow variably-modified types as template arguments.  */
11923       else if (variably_modified_type_p (t, NULL_TREE))
11924         {
11925           if (complain & tf_error)
11926             error ("%qT is a variably modified type", t);
11927           return true;
11928         }
11929     }
11930   /* A non-type argument of integral or enumerated type must be a
11931      constant.  */
11932   else if (TREE_TYPE (t)
11933            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11934            && !TREE_CONSTANT (t))
11935     {
11936       if (complain & tf_error)
11937         error ("integral expression %qE is not constant", t);
11938       return true;
11939     }
11940   return false;
11941 }
11942
11943 static bool
11944 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11945 {
11946   int ix, len = DECL_NTPARMS (tmpl);
11947   bool result = false;
11948
11949   for (ix = 0; ix != len; ix++)
11950     {
11951       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
11952         result = true;
11953     }
11954   if (result && (complain & tf_error))
11955     error ("  trying to instantiate %qD", tmpl);
11956   return result;
11957 }
11958
11959 /* Instantiate the indicated variable or function template TMPL with
11960    the template arguments in TARG_PTR.  */
11961
11962 tree
11963 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11964 {
11965   tree fndecl;
11966   tree gen_tmpl;
11967   tree spec;
11968   HOST_WIDE_INT saved_processing_template_decl;
11969
11970   if (tmpl == error_mark_node)
11971     return error_mark_node;
11972
11973   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11974
11975   /* If this function is a clone, handle it specially.  */
11976   if (DECL_CLONED_FUNCTION_P (tmpl))
11977     {
11978       tree spec;
11979       tree clone;
11980
11981       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11982                                    complain);
11983       if (spec == error_mark_node)
11984         return error_mark_node;
11985
11986       /* Look for the clone.  */
11987       FOR_EACH_CLONE (clone, spec)
11988         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11989           return clone;
11990       /* We should always have found the clone by now.  */
11991       gcc_unreachable ();
11992       return NULL_TREE;
11993     }
11994
11995   /* Check to see if we already have this specialization.  */
11996   spec = retrieve_specialization (tmpl, targ_ptr,
11997                                   /*class_specializations_p=*/false);
11998   if (spec != NULL_TREE)
11999     return spec;
12000
12001   gen_tmpl = most_general_template (tmpl);
12002   if (tmpl != gen_tmpl)
12003     {
12004       /* The TMPL is a partial instantiation.  To get a full set of
12005          arguments we must add the arguments used to perform the
12006          partial instantiation.  */
12007       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12008                                               targ_ptr);
12009
12010       /* Check to see if we already have this specialization.  */
12011       spec = retrieve_specialization (gen_tmpl, targ_ptr,
12012                                       /*class_specializations_p=*/false);
12013       if (spec != NULL_TREE)
12014         return spec;
12015     }
12016
12017   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12018                                complain))
12019     return error_mark_node;
12020
12021   /* We are building a FUNCTION_DECL, during which the access of its
12022      parameters and return types have to be checked.  However this
12023      FUNCTION_DECL which is the desired context for access checking
12024      is not built yet.  We solve this chicken-and-egg problem by
12025      deferring all checks until we have the FUNCTION_DECL.  */
12026   push_deferring_access_checks (dk_deferred);
12027
12028   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12029      (because, for example, we have encountered a non-dependent
12030      function call in the body of a template function and must now
12031      determine which of several overloaded functions will be called),
12032      within the instantiation itself we are not processing a
12033      template.  */  
12034   saved_processing_template_decl = processing_template_decl;
12035   processing_template_decl = 0;
12036   /* Substitute template parameters to obtain the specialization.  */
12037   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12038                    targ_ptr, complain, gen_tmpl);
12039   processing_template_decl = saved_processing_template_decl;
12040   if (fndecl == error_mark_node)
12041     return error_mark_node;
12042
12043   /* Now we know the specialization, compute access previously
12044      deferred.  */
12045   push_access_scope (fndecl);
12046   perform_deferred_access_checks ();
12047   pop_access_scope (fndecl);
12048   pop_deferring_access_checks ();
12049
12050   /* The DECL_TI_TEMPLATE should always be the immediate parent
12051      template, not the most general template.  */
12052   DECL_TI_TEMPLATE (fndecl) = tmpl;
12053
12054   /* If we've just instantiated the main entry point for a function,
12055      instantiate all the alternate entry points as well.  We do this
12056      by cloning the instantiation of the main entry point, not by
12057      instantiating the template clones.  */
12058   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12059     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12060
12061   return fndecl;
12062 }
12063
12064 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
12065    arguments that are being used when calling it.  TARGS is a vector
12066    into which the deduced template arguments are placed.
12067
12068    Return zero for success, 2 for an incomplete match that doesn't resolve
12069    all the types, and 1 for complete failure.  An error message will be
12070    printed only for an incomplete match.
12071
12072    If FN is a conversion operator, or we are trying to produce a specific
12073    specialization, RETURN_TYPE is the return type desired.
12074
12075    The EXPLICIT_TARGS are explicit template arguments provided via a
12076    template-id.
12077
12078    The parameter STRICT is one of:
12079
12080    DEDUCE_CALL:
12081      We are deducing arguments for a function call, as in
12082      [temp.deduct.call].
12083
12084    DEDUCE_CONV:
12085      We are deducing arguments for a conversion function, as in
12086      [temp.deduct.conv].
12087
12088    DEDUCE_EXACT:
12089      We are deducing arguments when doing an explicit instantiation
12090      as in [temp.explicit], when determining an explicit specialization
12091      as in [temp.expl.spec], or when taking the address of a function
12092      template, as in [temp.deduct.funcaddr].  */
12093
12094 int
12095 fn_type_unification (tree fn,
12096                      tree explicit_targs,
12097                      tree targs,
12098                      tree args,
12099                      tree return_type,
12100                      unification_kind_t strict,
12101                      int flags)
12102 {
12103   tree parms;
12104   tree fntype;
12105   int result;
12106   bool incomplete_argument_packs_p = false;
12107
12108   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12109
12110   fntype = TREE_TYPE (fn);
12111   if (explicit_targs)
12112     {
12113       /* [temp.deduct]
12114
12115          The specified template arguments must match the template
12116          parameters in kind (i.e., type, nontype, template), and there
12117          must not be more arguments than there are parameters;
12118          otherwise type deduction fails.
12119
12120          Nontype arguments must match the types of the corresponding
12121          nontype template parameters, or must be convertible to the
12122          types of the corresponding nontype parameters as specified in
12123          _temp.arg.nontype_, otherwise type deduction fails.
12124
12125          All references in the function type of the function template
12126          to the corresponding template parameters are replaced by the
12127          specified template argument values.  If a substitution in a
12128          template parameter or in the function type of the function
12129          template results in an invalid type, type deduction fails.  */
12130       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12131       int i, len = TREE_VEC_LENGTH (tparms);
12132       tree converted_args;
12133       bool incomplete = false;
12134
12135       if (explicit_targs == error_mark_node)
12136         return 1;
12137
12138       converted_args
12139         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12140                                   /*require_all_args=*/false,
12141                                   /*use_default_args=*/false));
12142       if (converted_args == error_mark_node)
12143         return 1;
12144
12145       /* Substitute the explicit args into the function type.  This is
12146          necessary so that, for instance, explicitly declared function
12147          arguments can match null pointed constants.  If we were given
12148          an incomplete set of explicit args, we must not do semantic
12149          processing during substitution as we could create partial
12150          instantiations.  */
12151       for (i = 0; i < len; i++)
12152         {
12153           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12154           bool parameter_pack = false;
12155
12156           /* Dig out the actual parm.  */
12157           if (TREE_CODE (parm) == TYPE_DECL
12158               || TREE_CODE (parm) == TEMPLATE_DECL)
12159             {
12160               parm = TREE_TYPE (parm);
12161               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12162             }
12163           else if (TREE_CODE (parm) == PARM_DECL)
12164             {
12165               parm = DECL_INITIAL (parm);
12166               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12167             }
12168
12169           if (parameter_pack)
12170             {
12171               int level, idx;
12172               tree targ;
12173               template_parm_level_and_index (parm, &level, &idx);
12174
12175               /* Mark the argument pack as "incomplete". We could
12176                  still deduce more arguments during unification.  */
12177               targ = TMPL_ARG (converted_args, level, idx);
12178               if (targ)
12179                 {
12180                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12181                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12182                     = ARGUMENT_PACK_ARGS (targ);
12183                 }
12184
12185               /* We have some incomplete argument packs.  */
12186               incomplete_argument_packs_p = true;
12187             }
12188         }
12189
12190       if (incomplete_argument_packs_p)
12191         /* Any substitution is guaranteed to be incomplete if there
12192            are incomplete argument packs, because we can still deduce
12193            more arguments.  */
12194         incomplete = 1;
12195       else
12196         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12197
12198       processing_template_decl += incomplete;
12199       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12200       processing_template_decl -= incomplete;
12201
12202       if (fntype == error_mark_node)
12203         return 1;
12204
12205       /* Place the explicitly specified arguments in TARGS.  */
12206       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12207         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12208     }
12209
12210   /* Never do unification on the 'this' parameter.  */
12211   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12212
12213   if (return_type)
12214     {
12215       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12216       args = tree_cons (NULL_TREE, return_type, args);
12217     }
12218
12219   /* We allow incomplete unification without an error message here
12220      because the standard doesn't seem to explicitly prohibit it.  Our
12221      callers must be ready to deal with unification failures in any
12222      event.  */
12223   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12224                                   targs, parms, args, /*subr=*/0,
12225                                   strict, flags);
12226
12227   if (result == 0 && incomplete_argument_packs_p)
12228     {
12229       int i, len = NUM_TMPL_ARGS (targs);
12230
12231       /* Clear the "incomplete" flags on all argument packs.  */
12232       for (i = 0; i < len; i++)
12233         {
12234           tree arg = TREE_VEC_ELT (targs, i);
12235           if (ARGUMENT_PACK_P (arg))
12236             {
12237               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12238               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12239             }
12240         }
12241     }
12242
12243   /* Now that we have bindings for all of the template arguments,
12244      ensure that the arguments deduced for the template template
12245      parameters have compatible template parameter lists.  We cannot
12246      check this property before we have deduced all template
12247      arguments, because the template parameter types of a template
12248      template parameter might depend on prior template parameters
12249      deduced after the template template parameter.  The following
12250      ill-formed example illustrates this issue:
12251
12252        template<typename T, template<T> class C> void f(C<5>, T);
12253
12254        template<int N> struct X {};
12255
12256        void g() {
12257          f(X<5>(), 5l); // error: template argument deduction fails
12258        }
12259
12260      The template parameter list of 'C' depends on the template type
12261      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12262      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12263      time that we deduce 'C'.  */
12264   if (result == 0
12265       && !template_template_parm_bindings_ok_p 
12266            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12267     return 1;
12268
12269   if (result == 0)
12270     /* All is well so far.  Now, check:
12271
12272        [temp.deduct]
12273
12274        When all template arguments have been deduced, all uses of
12275        template parameters in nondeduced contexts are replaced with
12276        the corresponding deduced argument values.  If the
12277        substitution results in an invalid type, as described above,
12278        type deduction fails.  */
12279     {
12280       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12281       if (substed == error_mark_node)
12282         return 1;
12283
12284       /* If we're looking for an exact match, check that what we got
12285          is indeed an exact match.  It might not be if some template
12286          parameters are used in non-deduced contexts.  */
12287       if (strict == DEDUCE_EXACT)
12288         {
12289           tree sarg
12290             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12291           tree arg = args;
12292           if (return_type)
12293             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12294           for (; arg && sarg;
12295                arg = TREE_CHAIN (arg), sarg = TREE_CHAIN (sarg))
12296             if (!same_type_p (TREE_VALUE (arg), TREE_VALUE (sarg)))
12297               return 1;
12298         }
12299     }
12300
12301   return result;
12302 }
12303
12304 /* Adjust types before performing type deduction, as described in
12305    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12306    sections are symmetric.  PARM is the type of a function parameter
12307    or the return type of the conversion function.  ARG is the type of
12308    the argument passed to the call, or the type of the value
12309    initialized with the result of the conversion function.
12310    ARG_EXPR is the original argument expression, which may be null.  */
12311
12312 static int
12313 maybe_adjust_types_for_deduction (unification_kind_t strict,
12314                                   tree* parm,
12315                                   tree* arg,
12316                                   tree arg_expr)
12317 {
12318   int result = 0;
12319
12320   switch (strict)
12321     {
12322     case DEDUCE_CALL:
12323       break;
12324
12325     case DEDUCE_CONV:
12326       {
12327         /* Swap PARM and ARG throughout the remainder of this
12328            function; the handling is precisely symmetric since PARM
12329            will initialize ARG rather than vice versa.  */
12330         tree* temp = parm;
12331         parm = arg;
12332         arg = temp;
12333         break;
12334       }
12335
12336     case DEDUCE_EXACT:
12337       /* There is nothing to do in this case.  */
12338       return 0;
12339
12340     default:
12341       gcc_unreachable ();
12342     }
12343
12344   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12345     {
12346       /* [temp.deduct.call]
12347
12348          If P is not a reference type:
12349
12350          --If A is an array type, the pointer type produced by the
12351          array-to-pointer standard conversion (_conv.array_) is
12352          used in place of A for type deduction; otherwise,
12353
12354          --If A is a function type, the pointer type produced by
12355          the function-to-pointer standard conversion
12356          (_conv.func_) is used in place of A for type deduction;
12357          otherwise,
12358
12359          --If A is a cv-qualified type, the top level
12360          cv-qualifiers of A's type are ignored for type
12361          deduction.  */
12362       if (TREE_CODE (*arg) == ARRAY_TYPE)
12363         *arg = build_pointer_type (TREE_TYPE (*arg));
12364       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12365         *arg = build_pointer_type (*arg);
12366       else
12367         *arg = TYPE_MAIN_VARIANT (*arg);
12368     }
12369
12370   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12371      of the form T&&, where T is a template parameter, and the argument
12372      is an lvalue, T is deduced as A& */
12373   if (TREE_CODE (*parm) == REFERENCE_TYPE
12374       && TYPE_REF_IS_RVALUE (*parm)
12375       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12376       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12377       && arg_expr && real_lvalue_p (arg_expr))
12378     *arg = build_reference_type (*arg);
12379
12380   /* [temp.deduct.call]
12381
12382      If P is a cv-qualified type, the top level cv-qualifiers
12383      of P's type are ignored for type deduction.  If P is a
12384      reference type, the type referred to by P is used for
12385      type deduction.  */
12386   *parm = TYPE_MAIN_VARIANT (*parm);
12387   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12388     {
12389       *parm = TREE_TYPE (*parm);
12390       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12391     }
12392
12393   /* DR 322. For conversion deduction, remove a reference type on parm
12394      too (which has been swapped into ARG).  */
12395   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12396     *arg = TREE_TYPE (*arg);
12397
12398   return result;
12399 }
12400
12401 /* Most parms like fn_type_unification.
12402
12403    If SUBR is 1, we're being called recursively (to unify the
12404    arguments of a function or method parameter of a function
12405    template). */
12406
12407 static int
12408 type_unification_real (tree tparms,
12409                        tree targs,
12410                        tree xparms,
12411                        tree xargs,
12412                        int subr,
12413                        unification_kind_t strict,
12414                        int flags)
12415 {
12416   tree parm, arg, arg_expr;
12417   int i;
12418   int ntparms = TREE_VEC_LENGTH (tparms);
12419   int sub_strict;
12420   int saw_undeduced = 0;
12421   tree parms, args;
12422
12423   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12424   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12425   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12426   gcc_assert (ntparms > 0);
12427
12428   switch (strict)
12429     {
12430     case DEDUCE_CALL:
12431       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12432                     | UNIFY_ALLOW_DERIVED);
12433       break;
12434
12435     case DEDUCE_CONV:
12436       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12437       break;
12438
12439     case DEDUCE_EXACT:
12440       sub_strict = UNIFY_ALLOW_NONE;
12441       break;
12442
12443     default:
12444       gcc_unreachable ();
12445     }
12446
12447  again:
12448   parms = xparms;
12449   args = xargs;
12450
12451   while (parms && parms != void_list_node
12452          && args && args != void_list_node)
12453     {
12454       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12455         break;
12456
12457       parm = TREE_VALUE (parms);
12458       parms = TREE_CHAIN (parms);
12459       arg = TREE_VALUE (args);
12460       args = TREE_CHAIN (args);
12461       arg_expr = NULL;
12462
12463       if (arg == error_mark_node)
12464         return 1;
12465       if (arg == unknown_type_node)
12466         /* We can't deduce anything from this, but we might get all the
12467            template args from other function args.  */
12468         continue;
12469
12470       /* Conversions will be performed on a function argument that
12471          corresponds with a function parameter that contains only
12472          non-deducible template parameters and explicitly specified
12473          template parameters.  */
12474       if (!uses_template_parms (parm))
12475         {
12476           tree type;
12477
12478           if (!TYPE_P (arg))
12479             type = TREE_TYPE (arg);
12480           else
12481             type = arg;
12482
12483           if (same_type_p (parm, type))
12484             continue;
12485           if (strict != DEDUCE_EXACT
12486               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12487                                   flags))
12488             continue;
12489
12490           return 1;
12491         }
12492
12493       if (!TYPE_P (arg))
12494         {
12495           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12496           if (type_unknown_p (arg))
12497             {
12498               /* [temp.deduct.type] 
12499
12500                  A template-argument can be deduced from a pointer to
12501                  function or pointer to member function argument if
12502                  the set of overloaded functions does not contain
12503                  function templates and at most one of a set of
12504                  overloaded functions provides a unique match.  */
12505               if (resolve_overloaded_unification
12506                   (tparms, targs, parm, arg, strict, sub_strict))
12507                 continue;
12508
12509               return 1;
12510             }
12511           arg_expr = arg;
12512           arg = unlowered_expr_type (arg);
12513           if (arg == error_mark_node)
12514             return 1;
12515         }
12516
12517       {
12518         int arg_strict = sub_strict;
12519
12520         if (!subr)
12521           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12522                                                           arg_expr);
12523
12524         if (arg == init_list_type_node && arg_expr)
12525           arg = arg_expr;
12526         if (unify (tparms, targs, parm, arg, arg_strict))
12527           return 1;
12528       }
12529     }
12530
12531
12532   if (parms 
12533       && parms != void_list_node
12534       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12535     {
12536       /* Unify the remaining arguments with the pack expansion type.  */
12537       tree argvec;
12538       tree parmvec = make_tree_vec (1);
12539       int len = 0;
12540       tree t;
12541
12542       /* Count the number of arguments that remain.  */
12543       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12544         len++;
12545         
12546       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12547       argvec = make_tree_vec (len);
12548       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12549         {
12550           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12551           ++i;
12552         }
12553
12554       /* Copy the parameter into parmvec.  */
12555       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12556       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12557                                 /*call_args_p=*/true, /*subr=*/subr))
12558         return 1;
12559
12560       /* Advance to the end of the list of parameters.  */
12561       parms = TREE_CHAIN (parms);
12562     }
12563
12564   /* Fail if we've reached the end of the parm list, and more args
12565      are present, and the parm list isn't variadic.  */
12566   if (args && args != void_list_node && parms == void_list_node)
12567     return 1;
12568   /* Fail if parms are left and they don't have default values.  */
12569   if (parms && parms != void_list_node
12570       && TREE_PURPOSE (parms) == NULL_TREE)
12571     return 1;
12572
12573   if (!subr)
12574     for (i = 0; i < ntparms; i++)
12575       if (!TREE_VEC_ELT (targs, i))
12576         {
12577           tree tparm;
12578
12579           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12580             continue;
12581
12582           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12583
12584           /* If this is an undeduced nontype parameter that depends on
12585              a type parameter, try another pass; its type may have been
12586              deduced from a later argument than the one from which
12587              this parameter can be deduced.  */
12588           if (TREE_CODE (tparm) == PARM_DECL
12589               && uses_template_parms (TREE_TYPE (tparm))
12590               && !saw_undeduced++)
12591             goto again;
12592
12593           /* Core issue #226 (C++0x) [temp.deduct]:
12594
12595                If a template argument has not been deduced, its
12596                default template argument, if any, is used. 
12597
12598              When we are in C++98 mode, TREE_PURPOSE will either
12599              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12600              to explicitly check cxx_dialect here.  */
12601           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12602             {
12603               tree arg = tsubst_template_arg
12604                                 (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)),
12605                                  targs, tf_none, NULL_TREE);
12606               if (arg == error_mark_node)
12607                 return 1;
12608               else
12609                 {
12610                   TREE_VEC_ELT (targs, i) = arg;
12611                   continue;
12612                 }
12613             }
12614
12615           /* If the type parameter is a parameter pack, then it will
12616              be deduced to an empty parameter pack.  */
12617           if (template_parameter_pack_p (tparm))
12618             {
12619               tree arg;
12620
12621               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12622                 {
12623                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12624                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12625                   TREE_CONSTANT (arg) = 1;
12626                 }
12627               else
12628                 arg = make_node (TYPE_ARGUMENT_PACK);
12629
12630               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12631
12632               TREE_VEC_ELT (targs, i) = arg;
12633               continue;
12634             }
12635
12636           return 2;
12637         }
12638
12639   return 0;
12640 }
12641
12642 /* Subroutine of type_unification_real.  Args are like the variables
12643    at the call site.  ARG is an overloaded function (or template-id);
12644    we try deducing template args from each of the overloads, and if
12645    only one succeeds, we go with that.  Modifies TARGS and returns
12646    true on success.  */
12647
12648 static bool
12649 resolve_overloaded_unification (tree tparms,
12650                                 tree targs,
12651                                 tree parm,
12652                                 tree arg,
12653                                 unification_kind_t strict,
12654                                 int sub_strict)
12655 {
12656   tree tempargs = copy_node (targs);
12657   int good = 0;
12658   tree goodfn = NULL_TREE;
12659   bool addr_p;
12660
12661   if (TREE_CODE (arg) == ADDR_EXPR)
12662     {
12663       arg = TREE_OPERAND (arg, 0);
12664       addr_p = true;
12665     }
12666   else
12667     addr_p = false;
12668
12669   if (TREE_CODE (arg) == COMPONENT_REF)
12670     /* Handle `&x' where `x' is some static or non-static member
12671        function name.  */
12672     arg = TREE_OPERAND (arg, 1);
12673
12674   if (TREE_CODE (arg) == OFFSET_REF)
12675     arg = TREE_OPERAND (arg, 1);
12676
12677   /* Strip baselink information.  */
12678   if (BASELINK_P (arg))
12679     arg = BASELINK_FUNCTIONS (arg);
12680
12681   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12682     {
12683       /* If we got some explicit template args, we need to plug them into
12684          the affected templates before we try to unify, in case the
12685          explicit args will completely resolve the templates in question.  */
12686
12687       tree expl_subargs = TREE_OPERAND (arg, 1);
12688       arg = TREE_OPERAND (arg, 0);
12689
12690       for (; arg; arg = OVL_NEXT (arg))
12691         {
12692           tree fn = OVL_CURRENT (arg);
12693           tree subargs, elem;
12694
12695           if (TREE_CODE (fn) != TEMPLATE_DECL)
12696             continue;
12697
12698           ++processing_template_decl;
12699           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12700                                   expl_subargs, /*check_ret=*/false);
12701           if (subargs)
12702             {
12703               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12704               if (try_one_overload (tparms, targs, tempargs, parm,
12705                                     elem, strict, sub_strict, addr_p)
12706                   && (!goodfn || !decls_match (goodfn, elem)))
12707                 {
12708                   goodfn = elem;
12709                   ++good;
12710                 }
12711             }
12712           --processing_template_decl;
12713         }
12714     }
12715   else if (TREE_CODE (arg) != OVERLOAD
12716            && TREE_CODE (arg) != FUNCTION_DECL)
12717     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12718        -- but the deduction does not succeed because the expression is
12719        not just the function on its own.  */
12720     return false;
12721   else
12722     for (; arg; arg = OVL_NEXT (arg))
12723       if (try_one_overload (tparms, targs, tempargs, parm,
12724                             TREE_TYPE (OVL_CURRENT (arg)),
12725                             strict, sub_strict, addr_p)
12726           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
12727         {
12728           goodfn = OVL_CURRENT (arg);
12729           ++good;
12730         }
12731
12732   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12733      to function or pointer to member function argument if the set of
12734      overloaded functions does not contain function templates and at most
12735      one of a set of overloaded functions provides a unique match.
12736
12737      So if we found multiple possibilities, we return success but don't
12738      deduce anything.  */
12739
12740   if (good == 1)
12741     {
12742       int i = TREE_VEC_LENGTH (targs);
12743       for (; i--; )
12744         if (TREE_VEC_ELT (tempargs, i))
12745           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12746     }
12747   if (good)
12748     return true;
12749
12750   return false;
12751 }
12752
12753 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12754    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12755    different overloads deduce different arguments for a given parm.
12756    ADDR_P is true if the expression for which deduction is being
12757    performed was of the form "& fn" rather than simply "fn".
12758
12759    Returns 1 on success.  */
12760
12761 static int
12762 try_one_overload (tree tparms,
12763                   tree orig_targs,
12764                   tree targs,
12765                   tree parm,
12766                   tree arg,
12767                   unification_kind_t strict,
12768                   int sub_strict,
12769                   bool addr_p)
12770 {
12771   int nargs;
12772   tree tempargs;
12773   int i;
12774
12775   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12776      to function or pointer to member function argument if the set of
12777      overloaded functions does not contain function templates and at most
12778      one of a set of overloaded functions provides a unique match.
12779
12780      So if this is a template, just return success.  */
12781
12782   if (uses_template_parms (arg))
12783     return 1;
12784
12785   if (TREE_CODE (arg) == METHOD_TYPE)
12786     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12787   else if (addr_p)
12788     arg = build_pointer_type (arg);
12789
12790   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12791
12792   /* We don't copy orig_targs for this because if we have already deduced
12793      some template args from previous args, unify would complain when we
12794      try to deduce a template parameter for the same argument, even though
12795      there isn't really a conflict.  */
12796   nargs = TREE_VEC_LENGTH (targs);
12797   tempargs = make_tree_vec (nargs);
12798
12799   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12800     return 0;
12801
12802   /* First make sure we didn't deduce anything that conflicts with
12803      explicitly specified args.  */
12804   for (i = nargs; i--; )
12805     {
12806       tree elt = TREE_VEC_ELT (tempargs, i);
12807       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12808
12809       if (!elt)
12810         /*NOP*/;
12811       else if (uses_template_parms (elt))
12812         /* Since we're unifying against ourselves, we will fill in
12813            template args used in the function parm list with our own
12814            template parms.  Discard them.  */
12815         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12816       else if (oldelt && !template_args_equal (oldelt, elt))
12817         return 0;
12818     }
12819
12820   for (i = nargs; i--; )
12821     {
12822       tree elt = TREE_VEC_ELT (tempargs, i);
12823
12824       if (elt)
12825         TREE_VEC_ELT (targs, i) = elt;
12826     }
12827
12828   return 1;
12829 }
12830
12831 /* PARM is a template class (perhaps with unbound template
12832    parameters).  ARG is a fully instantiated type.  If ARG can be
12833    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12834    TARGS are as for unify.  */
12835
12836 static tree
12837 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12838 {
12839   tree copy_of_targs;
12840
12841   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12842       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12843           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12844     return NULL_TREE;
12845
12846   /* We need to make a new template argument vector for the call to
12847      unify.  If we used TARGS, we'd clutter it up with the result of
12848      the attempted unification, even if this class didn't work out.
12849      We also don't want to commit ourselves to all the unifications
12850      we've already done, since unification is supposed to be done on
12851      an argument-by-argument basis.  In other words, consider the
12852      following pathological case:
12853
12854        template <int I, int J, int K>
12855        struct S {};
12856
12857        template <int I, int J>
12858        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12859
12860        template <int I, int J, int K>
12861        void f(S<I, J, K>, S<I, I, I>);
12862
12863        void g() {
12864          S<0, 0, 0> s0;
12865          S<0, 1, 2> s2;
12866
12867          f(s0, s2);
12868        }
12869
12870      Now, by the time we consider the unification involving `s2', we
12871      already know that we must have `f<0, 0, 0>'.  But, even though
12872      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12873      because there are two ways to unify base classes of S<0, 1, 2>
12874      with S<I, I, I>.  If we kept the already deduced knowledge, we
12875      would reject the possibility I=1.  */
12876   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12877
12878   /* If unification failed, we're done.  */
12879   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12880              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12881     return NULL_TREE;
12882
12883   return arg;
12884 }
12885
12886 /* Given a template type PARM and a class type ARG, find the unique
12887    base type in ARG that is an instance of PARM.  We do not examine
12888    ARG itself; only its base-classes.  If there is not exactly one
12889    appropriate base class, return NULL_TREE.  PARM may be the type of
12890    a partial specialization, as well as a plain template type.  Used
12891    by unify.  */
12892
12893 static tree
12894 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12895 {
12896   tree rval = NULL_TREE;
12897   tree binfo;
12898
12899   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12900
12901   binfo = TYPE_BINFO (complete_type (arg));
12902   if (!binfo)
12903     /* The type could not be completed.  */
12904     return NULL_TREE;
12905
12906   /* Walk in inheritance graph order.  The search order is not
12907      important, and this avoids multiple walks of virtual bases.  */
12908   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12909     {
12910       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12911
12912       if (r)
12913         {
12914           /* If there is more than one satisfactory baseclass, then:
12915
12916                [temp.deduct.call]
12917
12918               If they yield more than one possible deduced A, the type
12919               deduction fails.
12920
12921              applies.  */
12922           if (rval && !same_type_p (r, rval))
12923             return NULL_TREE;
12924
12925           rval = r;
12926         }
12927     }
12928
12929   return rval;
12930 }
12931
12932 /* Returns the level of DECL, which declares a template parameter.  */
12933
12934 static int
12935 template_decl_level (tree decl)
12936 {
12937   switch (TREE_CODE (decl))
12938     {
12939     case TYPE_DECL:
12940     case TEMPLATE_DECL:
12941       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12942
12943     case PARM_DECL:
12944       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12945
12946     default:
12947       gcc_unreachable ();
12948     }
12949   return 0;
12950 }
12951
12952 /* Decide whether ARG can be unified with PARM, considering only the
12953    cv-qualifiers of each type, given STRICT as documented for unify.
12954    Returns nonzero iff the unification is OK on that basis.  */
12955
12956 static int
12957 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12958 {
12959   int arg_quals = cp_type_quals (arg);
12960   int parm_quals = cp_type_quals (parm);
12961
12962   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12963       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12964     {
12965       /*  Although a CVR qualifier is ignored when being applied to a
12966           substituted template parameter ([8.3.2]/1 for example), that
12967           does not apply during deduction [14.8.2.4]/1, (even though
12968           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12969           this).  Except when we're allowing additional CV qualifiers
12970           at the outer level [14.8.2.1]/3,1st bullet.  */
12971       if ((TREE_CODE (arg) == REFERENCE_TYPE
12972            || TREE_CODE (arg) == FUNCTION_TYPE
12973            || TREE_CODE (arg) == METHOD_TYPE)
12974           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12975         return 0;
12976
12977       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12978           && (parm_quals & TYPE_QUAL_RESTRICT))
12979         return 0;
12980     }
12981
12982   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12983       && (arg_quals & parm_quals) != parm_quals)
12984     return 0;
12985
12986   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12987       && (parm_quals & arg_quals) != arg_quals)
12988     return 0;
12989
12990   return 1;
12991 }
12992
12993 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12994 void 
12995 template_parm_level_and_index (tree parm, int* level, int* index)
12996 {
12997   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12998       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12999       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13000     {
13001       *index = TEMPLATE_TYPE_IDX (parm);
13002       *level = TEMPLATE_TYPE_LEVEL (parm);
13003     }
13004   else
13005     {
13006       *index = TEMPLATE_PARM_IDX (parm);
13007       *level = TEMPLATE_PARM_LEVEL (parm);
13008     }
13009 }
13010
13011 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13012    expansion at the end of PACKED_PARMS. Returns 0 if the type
13013    deduction succeeds, 1 otherwise. STRICT is the same as in
13014    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13015    call argument list. We'll need to adjust the arguments to make them
13016    types. SUBR tells us if this is from a recursive call to
13017    type_unification_real.  */
13018 int
13019 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13020                       tree packed_args, int strict, bool call_args_p,
13021                       bool subr)
13022 {
13023   tree parm 
13024     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13025   tree pattern = PACK_EXPANSION_PATTERN (parm);
13026   tree pack, packs = NULL_TREE;
13027   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13028   int len = TREE_VEC_LENGTH (packed_args);
13029
13030   /* Determine the parameter packs we will be deducing from the
13031      pattern, and record their current deductions.  */
13032   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13033        pack; pack = TREE_CHAIN (pack))
13034     {
13035       tree parm_pack = TREE_VALUE (pack);
13036       int idx, level;
13037
13038       /* Determine the index and level of this parameter pack.  */
13039       template_parm_level_and_index (parm_pack, &level, &idx);
13040
13041       /* Keep track of the parameter packs and their corresponding
13042          argument packs.  */
13043       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13044       TREE_TYPE (packs) = make_tree_vec (len - start);
13045     }
13046   
13047   /* Loop through all of the arguments that have not yet been
13048      unified and unify each with the pattern.  */
13049   for (i = start; i < len; i++)
13050     {
13051       tree parm = pattern;
13052
13053       /* For each parameter pack, clear out the deduced value so that
13054          we can deduce it again.  */
13055       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13056         {
13057           int idx, level;
13058           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13059
13060           TMPL_ARG (targs, level, idx) = NULL_TREE;
13061         }
13062
13063       /* Unify the pattern with the current argument.  */
13064       {
13065         tree arg = TREE_VEC_ELT (packed_args, i);
13066         tree arg_expr = NULL_TREE;
13067         int arg_strict = strict;
13068         bool skip_arg_p = false;
13069
13070         if (call_args_p)
13071           {
13072             int sub_strict;
13073
13074             /* This mirrors what we do in type_unification_real.  */
13075             switch (strict)
13076               {
13077               case DEDUCE_CALL:
13078                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13079                               | UNIFY_ALLOW_MORE_CV_QUAL
13080                               | UNIFY_ALLOW_DERIVED);
13081                 break;
13082                 
13083               case DEDUCE_CONV:
13084                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13085                 break;
13086                 
13087               case DEDUCE_EXACT:
13088                 sub_strict = UNIFY_ALLOW_NONE;
13089                 break;
13090                 
13091               default:
13092                 gcc_unreachable ();
13093               }
13094
13095             if (!TYPE_P (arg))
13096               {
13097                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13098                 if (type_unknown_p (arg))
13099                   {
13100                     /* [temp.deduct.type] A template-argument can be
13101                        deduced from a pointer to function or pointer
13102                        to member function argument if the set of
13103                        overloaded functions does not contain function
13104                        templates and at most one of a set of
13105                        overloaded functions provides a unique
13106                        match.  */
13107
13108                     if (resolve_overloaded_unification
13109                         (tparms, targs, parm, arg, strict, sub_strict)
13110                         != 0)
13111                       return 1;
13112                     skip_arg_p = true;
13113                   }
13114
13115                 if (!skip_arg_p)
13116                   {
13117                     arg_expr = arg;
13118                     arg = unlowered_expr_type (arg);
13119                     if (arg == error_mark_node)
13120                       return 1;
13121                   }
13122               }
13123       
13124             arg_strict = sub_strict;
13125
13126             if (!subr)
13127               arg_strict |= 
13128                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
13129                                                   arg_expr);
13130           }
13131
13132         if (!skip_arg_p)
13133           {
13134             if (unify (tparms, targs, parm, arg, arg_strict))
13135               return 1;
13136           }
13137       }
13138
13139       /* For each parameter pack, collect the deduced value.  */
13140       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13141         {
13142           int idx, level;
13143           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13144
13145           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13146             TMPL_ARG (targs, level, idx);
13147         }
13148     }
13149
13150   /* Verify that the results of unification with the parameter packs
13151      produce results consistent with what we've seen before, and make
13152      the deduced argument packs available.  */
13153   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13154     {
13155       tree old_pack = TREE_VALUE (pack);
13156       tree new_args = TREE_TYPE (pack);
13157       int i, len = TREE_VEC_LENGTH (new_args);
13158       bool nondeduced_p = false;
13159
13160       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13161          actually deduce anything.  */
13162       for (i = 0; i < len && !nondeduced_p; ++i)
13163         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13164           nondeduced_p = true;
13165       if (nondeduced_p)
13166         continue;
13167
13168       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13169         {
13170           /* Prepend the explicit arguments onto NEW_ARGS.  */
13171           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13172           tree old_args = new_args;
13173           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13174           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13175
13176           /* Copy the explicit arguments.  */
13177           new_args = make_tree_vec (len);
13178           for (i = 0; i < explicit_len; i++)
13179             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13180
13181           /* Copy the deduced arguments.  */
13182           for (; i < len; i++)
13183             TREE_VEC_ELT (new_args, i) =
13184               TREE_VEC_ELT (old_args, i - explicit_len);
13185         }
13186
13187       if (!old_pack)
13188         {
13189           tree result;
13190           int idx, level;
13191           
13192           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13193
13194           /* Build the deduced *_ARGUMENT_PACK.  */
13195           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13196             {
13197               result = make_node (NONTYPE_ARGUMENT_PACK);
13198               TREE_TYPE (result) = 
13199                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13200               TREE_CONSTANT (result) = 1;
13201             }
13202           else
13203             result = make_node (TYPE_ARGUMENT_PACK);
13204
13205           SET_ARGUMENT_PACK_ARGS (result, new_args);
13206
13207           /* Note the deduced argument packs for this parameter
13208              pack.  */
13209           TMPL_ARG (targs, level, idx) = result;
13210         }
13211       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13212                && (ARGUMENT_PACK_ARGS (old_pack) 
13213                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13214         {
13215           /* We only had the explicitly-provided arguments before, but
13216              now we have a complete set of arguments.  */
13217           int idx, level;
13218           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13219           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13220
13221           /* Keep the original deduced argument pack.  */
13222           TMPL_ARG (targs, level, idx) = old_pack;
13223
13224           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13225           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13226           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13227         }
13228       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13229                                     new_args))
13230         /* Inconsistent unification of this parameter pack.  */
13231         return 1;
13232       else
13233         {
13234           int idx, level;
13235           
13236           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13237
13238           /* Keep the original deduced argument pack.  */
13239           TMPL_ARG (targs, level, idx) = old_pack;
13240         }
13241     }
13242
13243   return 0;
13244 }
13245
13246 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13247    set of template parameters to a template.  TARGS is the bindings
13248    for those template parameters, as determined thus far; TARGS may
13249    include template arguments for outer levels of template parameters
13250    as well.  PARM is a parameter to a template function, or a
13251    subcomponent of that parameter; ARG is the corresponding argument.
13252    This function attempts to match PARM with ARG in a manner
13253    consistent with the existing assignments in TARGS.  If more values
13254    are deduced, then TARGS is updated.
13255
13256    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13257    parameter STRICT is a bitwise or of the following flags:
13258
13259      UNIFY_ALLOW_NONE:
13260        Require an exact match between PARM and ARG.
13261      UNIFY_ALLOW_MORE_CV_QUAL:
13262        Allow the deduced ARG to be more cv-qualified (by qualification
13263        conversion) than ARG.
13264      UNIFY_ALLOW_LESS_CV_QUAL:
13265        Allow the deduced ARG to be less cv-qualified than ARG.
13266      UNIFY_ALLOW_DERIVED:
13267        Allow the deduced ARG to be a template base class of ARG,
13268        or a pointer to a template base class of the type pointed to by
13269        ARG.
13270      UNIFY_ALLOW_INTEGER:
13271        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13272        case for more information.
13273      UNIFY_ALLOW_OUTER_LEVEL:
13274        This is the outermost level of a deduction. Used to determine validity
13275        of qualification conversions. A valid qualification conversion must
13276        have const qualified pointers leading up to the inner type which
13277        requires additional CV quals, except at the outer level, where const
13278        is not required [conv.qual]. It would be normal to set this flag in
13279        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13280      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13281        This is the outermost level of a deduction, and PARM can be more CV
13282        qualified at this point.
13283      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13284        This is the outermost level of a deduction, and PARM can be less CV
13285        qualified at this point.  */
13286
13287 static int
13288 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13289 {
13290   int idx;
13291   tree targ;
13292   tree tparm;
13293   int strict_in = strict;
13294
13295   /* I don't think this will do the right thing with respect to types.
13296      But the only case I've seen it in so far has been array bounds, where
13297      signedness is the only information lost, and I think that will be
13298      okay.  */
13299   while (TREE_CODE (parm) == NOP_EXPR)
13300     parm = TREE_OPERAND (parm, 0);
13301
13302   if (arg == error_mark_node)
13303     return 1;
13304   if (arg == unknown_type_node
13305       || arg == init_list_type_node)
13306     /* We can't deduce anything from this, but we might get all the
13307        template args from other function args.  */
13308     return 0;
13309
13310   /* If PARM uses template parameters, then we can't bail out here,
13311      even if ARG == PARM, since we won't record unifications for the
13312      template parameters.  We might need them if we're trying to
13313      figure out which of two things is more specialized.  */
13314   if (arg == parm && !uses_template_parms (parm))
13315     return 0;
13316
13317   /* Handle init lists early, so the rest of the function can assume
13318      we're dealing with a type. */
13319   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13320     {
13321       tree elt, elttype;
13322       unsigned i;
13323
13324       if (!is_std_init_list (parm))
13325         /* We can only deduce from an initializer list argument if the
13326            parameter is std::initializer_list; otherwise this is a
13327            non-deduced context. */
13328         return 0;
13329
13330       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13331
13332       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13333         {
13334           int elt_strict = strict;
13335           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13336             {
13337               tree type = TREE_TYPE (elt);
13338               /* It should only be possible to get here for a call.  */
13339               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13340               elt_strict |= maybe_adjust_types_for_deduction
13341                 (DEDUCE_CALL, &elttype, &type, elt);
13342               elt = type;
13343             }
13344
13345           if (unify (tparms, targs, elttype, elt, elt_strict))
13346             return 1;
13347         }
13348       return 0;
13349     }
13350
13351   /* Immediately reject some pairs that won't unify because of
13352      cv-qualification mismatches.  */
13353   if (TREE_CODE (arg) == TREE_CODE (parm)
13354       && TYPE_P (arg)
13355       /* It is the elements of the array which hold the cv quals of an array
13356          type, and the elements might be template type parms. We'll check
13357          when we recurse.  */
13358       && TREE_CODE (arg) != ARRAY_TYPE
13359       /* We check the cv-qualifiers when unifying with template type
13360          parameters below.  We want to allow ARG `const T' to unify with
13361          PARM `T' for example, when computing which of two templates
13362          is more specialized, for example.  */
13363       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13364       && !check_cv_quals_for_unify (strict_in, arg, parm))
13365     return 1;
13366
13367   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13368       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13369     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13370   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13371   strict &= ~UNIFY_ALLOW_DERIVED;
13372   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13373   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13374
13375   switch (TREE_CODE (parm))
13376     {
13377     case TYPENAME_TYPE:
13378     case SCOPE_REF:
13379     case UNBOUND_CLASS_TEMPLATE:
13380       /* In a type which contains a nested-name-specifier, template
13381          argument values cannot be deduced for template parameters used
13382          within the nested-name-specifier.  */
13383       return 0;
13384
13385     case TEMPLATE_TYPE_PARM:
13386     case TEMPLATE_TEMPLATE_PARM:
13387     case BOUND_TEMPLATE_TEMPLATE_PARM:
13388       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13389       if (tparm == error_mark_node)
13390         return 1;
13391
13392       if (TEMPLATE_TYPE_LEVEL (parm)
13393           != template_decl_level (tparm))
13394         /* The PARM is not one we're trying to unify.  Just check
13395            to see if it matches ARG.  */
13396         return (TREE_CODE (arg) == TREE_CODE (parm)
13397                 && same_type_p (parm, arg)) ? 0 : 1;
13398       idx = TEMPLATE_TYPE_IDX (parm);
13399       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13400       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13401
13402       /* Check for mixed types and values.  */
13403       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13404            && TREE_CODE (tparm) != TYPE_DECL)
13405           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13406               && TREE_CODE (tparm) != TEMPLATE_DECL))
13407         return 1;
13408
13409       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13410         {
13411           /* ARG must be constructed from a template class or a template
13412              template parameter.  */
13413           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13414               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13415             return 1;
13416
13417           {
13418             tree parmvec = TYPE_TI_ARGS (parm);
13419             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13420             tree parm_parms 
13421               = DECL_INNERMOST_TEMPLATE_PARMS
13422                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13423             int i, len;
13424             int parm_variadic_p = 0;
13425
13426             /* The resolution to DR150 makes clear that default
13427                arguments for an N-argument may not be used to bind T
13428                to a template template parameter with fewer than N
13429                parameters.  It is not safe to permit the binding of
13430                default arguments as an extension, as that may change
13431                the meaning of a conforming program.  Consider:
13432
13433                   struct Dense { static const unsigned int dim = 1; };
13434
13435                   template <template <typename> class View,
13436                             typename Block>
13437                   void operator+(float, View<Block> const&);
13438
13439                   template <typename Block,
13440                             unsigned int Dim = Block::dim>
13441                   struct Lvalue_proxy { operator float() const; };
13442
13443                   void
13444                   test_1d (void) {
13445                     Lvalue_proxy<Dense> p;
13446                     float b;
13447                     b + p;
13448                   }
13449
13450               Here, if Lvalue_proxy is permitted to bind to View, then
13451               the global operator+ will be used; if they are not, the
13452               Lvalue_proxy will be converted to float.  */
13453             if (coerce_template_parms (parm_parms,
13454                                        argvec,
13455                                        TYPE_TI_TEMPLATE (parm),
13456                                        tf_none,
13457                                        /*require_all_args=*/true,
13458                                        /*use_default_args=*/false)
13459                 == error_mark_node)
13460               return 1;
13461
13462             /* Deduce arguments T, i from TT<T> or TT<i>.
13463                We check each element of PARMVEC and ARGVEC individually
13464                rather than the whole TREE_VEC since they can have
13465                different number of elements.  */
13466
13467             parmvec = expand_template_argument_pack (parmvec);
13468             argvec = expand_template_argument_pack (argvec);
13469
13470             len = TREE_VEC_LENGTH (parmvec);
13471
13472             /* Check if the parameters end in a pack, making them
13473                variadic.  */
13474             if (len > 0
13475                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13476               parm_variadic_p = 1;
13477             
13478             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13479               return 1;
13480
13481              for (i = 0; i < len - parm_variadic_p; ++i)
13482               {
13483                 if (unify (tparms, targs,
13484                            TREE_VEC_ELT (parmvec, i),
13485                            TREE_VEC_ELT (argvec, i),
13486                            UNIFY_ALLOW_NONE))
13487                   return 1;
13488               }
13489
13490             if (parm_variadic_p
13491                 && unify_pack_expansion (tparms, targs,
13492                                          parmvec, argvec,
13493                                          UNIFY_ALLOW_NONE,
13494                                          /*call_args_p=*/false,
13495                                          /*subr=*/false))
13496               return 1;
13497           }
13498           arg = TYPE_TI_TEMPLATE (arg);
13499
13500           /* Fall through to deduce template name.  */
13501         }
13502
13503       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13504           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13505         {
13506           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13507
13508           /* Simple cases: Value already set, does match or doesn't.  */
13509           if (targ != NULL_TREE && template_args_equal (targ, arg))
13510             return 0;
13511           else if (targ)
13512             return 1;
13513         }
13514       else
13515         {
13516           /* If PARM is `const T' and ARG is only `int', we don't have
13517              a match unless we are allowing additional qualification.
13518              If ARG is `const int' and PARM is just `T' that's OK;
13519              that binds `const int' to `T'.  */
13520           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13521                                          arg, parm))
13522             return 1;
13523
13524           /* Consider the case where ARG is `const volatile int' and
13525              PARM is `const T'.  Then, T should be `volatile int'.  */
13526           arg = cp_build_qualified_type_real
13527             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13528           if (arg == error_mark_node)
13529             return 1;
13530
13531           /* Simple cases: Value already set, does match or doesn't.  */
13532           if (targ != NULL_TREE && same_type_p (targ, arg))
13533             return 0;
13534           else if (targ)
13535             return 1;
13536
13537           /* Make sure that ARG is not a variable-sized array.  (Note
13538              that were talking about variable-sized arrays (like
13539              `int[n]'), rather than arrays of unknown size (like
13540              `int[]').)  We'll get very confused by such a type since
13541              the bound of the array will not be computable in an
13542              instantiation.  Besides, such types are not allowed in
13543              ISO C++, so we can do as we please here.  */
13544           if (variably_modified_type_p (arg, NULL_TREE))
13545             return 1;
13546         }
13547
13548       /* If ARG is a parameter pack or an expansion, we cannot unify
13549          against it unless PARM is also a parameter pack.  */
13550       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13551           && !template_parameter_pack_p (parm))
13552         return 1;
13553
13554       /* If the argument deduction results is a METHOD_TYPE,
13555          then there is a problem.
13556          METHOD_TYPE doesn't map to any real C++ type the result of
13557          the deduction can not be of that type.  */
13558       if (TREE_CODE (arg) == METHOD_TYPE)
13559         return 1;
13560
13561       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13562       return 0;
13563
13564     case TEMPLATE_PARM_INDEX:
13565       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13566       if (tparm == error_mark_node)
13567         return 1;
13568
13569       if (TEMPLATE_PARM_LEVEL (parm)
13570           != template_decl_level (tparm))
13571         /* The PARM is not one we're trying to unify.  Just check
13572            to see if it matches ARG.  */
13573         return !(TREE_CODE (arg) == TREE_CODE (parm)
13574                  && cp_tree_equal (parm, arg));
13575
13576       idx = TEMPLATE_PARM_IDX (parm);
13577       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13578
13579       if (targ)
13580         return !cp_tree_equal (targ, arg);
13581
13582       /* [temp.deduct.type] If, in the declaration of a function template
13583          with a non-type template-parameter, the non-type
13584          template-parameter is used in an expression in the function
13585          parameter-list and, if the corresponding template-argument is
13586          deduced, the template-argument type shall match the type of the
13587          template-parameter exactly, except that a template-argument
13588          deduced from an array bound may be of any integral type.
13589          The non-type parameter might use already deduced type parameters.  */
13590       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13591       if (!TREE_TYPE (arg))
13592         /* Template-parameter dependent expression.  Just accept it for now.
13593            It will later be processed in convert_template_argument.  */
13594         ;
13595       else if (same_type_p (TREE_TYPE (arg), tparm))
13596         /* OK */;
13597       else if ((strict & UNIFY_ALLOW_INTEGER)
13598                && (TREE_CODE (tparm) == INTEGER_TYPE
13599                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13600         /* Convert the ARG to the type of PARM; the deduced non-type
13601            template argument must exactly match the types of the
13602            corresponding parameter.  */
13603         arg = fold (build_nop (tparm, arg));
13604       else if (uses_template_parms (tparm))
13605         /* We haven't deduced the type of this parameter yet.  Try again
13606            later.  */
13607         return 0;
13608       else
13609         return 1;
13610
13611       /* If ARG is a parameter pack or an expansion, we cannot unify
13612          against it unless PARM is also a parameter pack.  */
13613       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13614           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13615         return 1;
13616
13617       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13618       return 0;
13619
13620     case PTRMEM_CST:
13621      {
13622         /* A pointer-to-member constant can be unified only with
13623          another constant.  */
13624       if (TREE_CODE (arg) != PTRMEM_CST)
13625         return 1;
13626
13627       /* Just unify the class member. It would be useless (and possibly
13628          wrong, depending on the strict flags) to unify also
13629          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13630          arg refer to the same variable, even if through different
13631          classes. For instance:
13632
13633          struct A { int x; };
13634          struct B : A { };
13635
13636          Unification of &A::x and &B::x must succeed.  */
13637       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13638                     PTRMEM_CST_MEMBER (arg), strict);
13639      }
13640
13641     case POINTER_TYPE:
13642       {
13643         if (TREE_CODE (arg) != POINTER_TYPE)
13644           return 1;
13645
13646         /* [temp.deduct.call]
13647
13648            A can be another pointer or pointer to member type that can
13649            be converted to the deduced A via a qualification
13650            conversion (_conv.qual_).
13651
13652            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13653            This will allow for additional cv-qualification of the
13654            pointed-to types if appropriate.  */
13655
13656         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13657           /* The derived-to-base conversion only persists through one
13658              level of pointers.  */
13659           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13660
13661         return unify (tparms, targs, TREE_TYPE (parm),
13662                       TREE_TYPE (arg), strict);
13663       }
13664
13665     case REFERENCE_TYPE:
13666       if (TREE_CODE (arg) != REFERENCE_TYPE)
13667         return 1;
13668       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13669                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13670
13671     case ARRAY_TYPE:
13672       if (TREE_CODE (arg) != ARRAY_TYPE)
13673         return 1;
13674       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13675           != (TYPE_DOMAIN (arg) == NULL_TREE))
13676         return 1;
13677       if (TYPE_DOMAIN (parm) != NULL_TREE)
13678         {
13679           tree parm_max;
13680           tree arg_max;
13681           bool parm_cst;
13682           bool arg_cst;
13683
13684           /* Our representation of array types uses "N - 1" as the
13685              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13686              not an integer constant.  We cannot unify arbitrarily
13687              complex expressions, so we eliminate the MINUS_EXPRs
13688              here.  */
13689           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13690           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13691           if (!parm_cst)
13692             {
13693               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13694               parm_max = TREE_OPERAND (parm_max, 0);
13695             }
13696           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13697           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13698           if (!arg_cst)
13699             {
13700               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13701                  trying to unify the type of a variable with the type
13702                  of a template parameter.  For example:
13703
13704                    template <unsigned int N>
13705                    void f (char (&) [N]);
13706                    int g(); 
13707                    void h(int i) {
13708                      char a[g(i)];
13709                      f(a); 
13710                    }
13711
13712                 Here, the type of the ARG will be "int [g(i)]", and
13713                 may be a SAVE_EXPR, etc.  */
13714               if (TREE_CODE (arg_max) != MINUS_EXPR)
13715                 return 1;
13716               arg_max = TREE_OPERAND (arg_max, 0);
13717             }
13718
13719           /* If only one of the bounds used a MINUS_EXPR, compensate
13720              by adding one to the other bound.  */
13721           if (parm_cst && !arg_cst)
13722             parm_max = fold_build2 (PLUS_EXPR,
13723                                     integer_type_node,
13724                                     parm_max,
13725                                     integer_one_node);
13726           else if (arg_cst && !parm_cst)
13727             arg_max = fold_build2 (PLUS_EXPR,
13728                                    integer_type_node,
13729                                    arg_max,
13730                                    integer_one_node);
13731
13732           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13733             return 1;
13734         }
13735       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13736                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13737
13738     case REAL_TYPE:
13739     case COMPLEX_TYPE:
13740     case VECTOR_TYPE:
13741     case INTEGER_TYPE:
13742     case BOOLEAN_TYPE:
13743     case ENUMERAL_TYPE:
13744     case VOID_TYPE:
13745       if (TREE_CODE (arg) != TREE_CODE (parm))
13746         return 1;
13747
13748       /* We have already checked cv-qualification at the top of the
13749          function.  */
13750       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13751         return 1;
13752
13753       /* As far as unification is concerned, this wins.  Later checks
13754          will invalidate it if necessary.  */
13755       return 0;
13756
13757       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13758       /* Type INTEGER_CST can come from ordinary constant template args.  */
13759     case INTEGER_CST:
13760       while (TREE_CODE (arg) == NOP_EXPR)
13761         arg = TREE_OPERAND (arg, 0);
13762
13763       if (TREE_CODE (arg) != INTEGER_CST)
13764         return 1;
13765       return !tree_int_cst_equal (parm, arg);
13766
13767     case TREE_VEC:
13768       {
13769         int i;
13770         if (TREE_CODE (arg) != TREE_VEC)
13771           return 1;
13772         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13773           return 1;
13774         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13775           if (unify (tparms, targs,
13776                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13777                      UNIFY_ALLOW_NONE))
13778             return 1;
13779         return 0;
13780       }
13781
13782     case RECORD_TYPE:
13783     case UNION_TYPE:
13784       if (TREE_CODE (arg) != TREE_CODE (parm))
13785         return 1;
13786
13787       if (TYPE_PTRMEMFUNC_P (parm))
13788         {
13789           if (!TYPE_PTRMEMFUNC_P (arg))
13790             return 1;
13791
13792           return unify (tparms, targs,
13793                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13794                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13795                         strict);
13796         }
13797
13798       if (CLASSTYPE_TEMPLATE_INFO (parm))
13799         {
13800           tree t = NULL_TREE;
13801
13802           if (strict_in & UNIFY_ALLOW_DERIVED)
13803             {
13804               /* First, we try to unify the PARM and ARG directly.  */
13805               t = try_class_unification (tparms, targs,
13806                                          parm, arg);
13807
13808               if (!t)
13809                 {
13810                   /* Fallback to the special case allowed in
13811                      [temp.deduct.call]:
13812
13813                        If P is a class, and P has the form
13814                        template-id, then A can be a derived class of
13815                        the deduced A.  Likewise, if P is a pointer to
13816                        a class of the form template-id, A can be a
13817                        pointer to a derived class pointed to by the
13818                        deduced A.  */
13819                   t = get_template_base (tparms, targs, parm, arg);
13820
13821                   if (!t)
13822                     return 1;
13823                 }
13824             }
13825           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13826                    && (CLASSTYPE_TI_TEMPLATE (parm)
13827                        == CLASSTYPE_TI_TEMPLATE (arg)))
13828             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13829                Then, we should unify `int' and `U'.  */
13830             t = arg;
13831           else
13832             /* There's no chance of unification succeeding.  */
13833             return 1;
13834
13835           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13836                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13837         }
13838       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13839         return 1;
13840       return 0;
13841
13842     case METHOD_TYPE:
13843     case FUNCTION_TYPE:
13844       if (TREE_CODE (arg) != TREE_CODE (parm))
13845         return 1;
13846
13847       /* CV qualifications for methods can never be deduced, they must
13848          match exactly.  We need to check them explicitly here,
13849          because type_unification_real treats them as any other
13850          cv-qualified parameter.  */
13851       if (TREE_CODE (parm) == METHOD_TYPE
13852           && (!check_cv_quals_for_unify
13853               (UNIFY_ALLOW_NONE,
13854                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13855                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13856         return 1;
13857
13858       if (unify (tparms, targs, TREE_TYPE (parm),
13859                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13860         return 1;
13861       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13862                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13863                                     LOOKUP_NORMAL);
13864
13865     case OFFSET_TYPE:
13866       /* Unify a pointer to member with a pointer to member function, which
13867          deduces the type of the member as a function type. */
13868       if (TYPE_PTRMEMFUNC_P (arg))
13869         {
13870           tree method_type;
13871           tree fntype;
13872           cp_cv_quals cv_quals;
13873
13874           /* Check top-level cv qualifiers */
13875           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13876             return 1;
13877
13878           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13879                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13880             return 1;
13881
13882           /* Determine the type of the function we are unifying against. */
13883           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13884           fntype =
13885             build_function_type (TREE_TYPE (method_type),
13886                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13887
13888           /* Extract the cv-qualifiers of the member function from the
13889              implicit object parameter and place them on the function
13890              type to be restored later. */
13891           cv_quals =
13892             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13893           fntype = build_qualified_type (fntype, cv_quals);
13894           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13895         }
13896
13897       if (TREE_CODE (arg) != OFFSET_TYPE)
13898         return 1;
13899       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13900                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13901         return 1;
13902       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13903                     strict);
13904
13905     case CONST_DECL:
13906       if (DECL_TEMPLATE_PARM_P (parm))
13907         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13908       if (arg != integral_constant_value (parm))
13909         return 1;
13910       return 0;
13911
13912     case FIELD_DECL:
13913     case TEMPLATE_DECL:
13914       /* Matched cases are handled by the ARG == PARM test above.  */
13915       return 1;
13916
13917     case TYPE_ARGUMENT_PACK:
13918     case NONTYPE_ARGUMENT_PACK:
13919       {
13920         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13921         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13922         int i, len = TREE_VEC_LENGTH (packed_parms);
13923         int argslen = TREE_VEC_LENGTH (packed_args);
13924         int parm_variadic_p = 0;
13925
13926         for (i = 0; i < len; ++i)
13927           {
13928             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13929               {
13930                 if (i == len - 1)
13931                   /* We can unify against something with a trailing
13932                      parameter pack.  */
13933                   parm_variadic_p = 1;
13934                 else
13935                   /* Since there is something following the pack
13936                      expansion, we cannot unify this template argument
13937                      list.  */
13938                   return 0;
13939               }
13940           }
13941           
13942
13943         /* If we don't have enough arguments to satisfy the parameters
13944            (not counting the pack expression at the end), or we have
13945            too many arguments for a parameter list that doesn't end in
13946            a pack expression, we can't unify.  */
13947         if (argslen < (len - parm_variadic_p)
13948             || (argslen > len && !parm_variadic_p))
13949           return 1;
13950
13951         /* Unify all of the parameters that precede the (optional)
13952            pack expression.  */
13953         for (i = 0; i < len - parm_variadic_p; ++i)
13954           {
13955             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13956                        TREE_VEC_ELT (packed_args, i), strict))
13957               return 1;
13958           }
13959
13960         if (parm_variadic_p)
13961           return unify_pack_expansion (tparms, targs, 
13962                                        packed_parms, packed_args,
13963                                        strict, /*call_args_p=*/false,
13964                                        /*subr=*/false);
13965         return 0;
13966       }
13967
13968       break;
13969
13970     case TYPEOF_TYPE:
13971     case DECLTYPE_TYPE:
13972       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13973          nodes.  */
13974       return 0;
13975
13976     case ERROR_MARK:
13977       /* Unification fails if we hit an error node.  */
13978       return 1;
13979
13980     default:
13981       gcc_assert (EXPR_P (parm));
13982
13983       /* We must be looking at an expression.  This can happen with
13984          something like:
13985
13986            template <int I>
13987            void foo(S<I>, S<I + 2>);
13988
13989          This is a "nondeduced context":
13990
13991            [deduct.type]
13992
13993            The nondeduced contexts are:
13994
13995            --A type that is a template-id in which one or more of
13996              the template-arguments is an expression that references
13997              a template-parameter.
13998
13999          In these cases, we assume deduction succeeded, but don't
14000          actually infer any unifications.  */
14001
14002       if (!uses_template_parms (parm)
14003           && !template_args_equal (parm, arg))
14004         return 1;
14005       else
14006         return 0;
14007     }
14008 }
14009 \f
14010 /* Note that DECL can be defined in this translation unit, if
14011    required.  */
14012
14013 static void
14014 mark_definable (tree decl)
14015 {
14016   tree clone;
14017   DECL_NOT_REALLY_EXTERN (decl) = 1;
14018   FOR_EACH_CLONE (clone, decl)
14019     DECL_NOT_REALLY_EXTERN (clone) = 1;
14020 }
14021
14022 /* Called if RESULT is explicitly instantiated, or is a member of an
14023    explicitly instantiated class.  */
14024
14025 void
14026 mark_decl_instantiated (tree result, int extern_p)
14027 {
14028   SET_DECL_EXPLICIT_INSTANTIATION (result);
14029
14030   /* If this entity has already been written out, it's too late to
14031      make any modifications.  */
14032   if (TREE_ASM_WRITTEN (result))
14033     return;
14034
14035   if (TREE_CODE (result) != FUNCTION_DECL)
14036     /* The TREE_PUBLIC flag for function declarations will have been
14037        set correctly by tsubst.  */
14038     TREE_PUBLIC (result) = 1;
14039
14040   /* This might have been set by an earlier implicit instantiation.  */
14041   DECL_COMDAT (result) = 0;
14042
14043   if (extern_p)
14044     DECL_NOT_REALLY_EXTERN (result) = 0;
14045   else
14046     {
14047       mark_definable (result);
14048       /* Always make artificials weak.  */
14049       if (DECL_ARTIFICIAL (result) && flag_weak)
14050         comdat_linkage (result);
14051       /* For WIN32 we also want to put explicit instantiations in
14052          linkonce sections.  */
14053       else if (TREE_PUBLIC (result))
14054         maybe_make_one_only (result);
14055     }
14056
14057   /* If EXTERN_P, then this function will not be emitted -- unless
14058      followed by an explicit instantiation, at which point its linkage
14059      will be adjusted.  If !EXTERN_P, then this function will be
14060      emitted here.  In neither circumstance do we want
14061      import_export_decl to adjust the linkage.  */
14062   DECL_INTERFACE_KNOWN (result) = 1;
14063 }
14064
14065 /* Given two function templates PAT1 and PAT2, return:
14066
14067    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14068    -1 if PAT2 is more specialized than PAT1.
14069    0 if neither is more specialized.
14070
14071    LEN indicates the number of parameters we should consider
14072    (defaulted parameters should not be considered).
14073
14074    The 1998 std underspecified function template partial ordering, and
14075    DR214 addresses the issue.  We take pairs of arguments, one from
14076    each of the templates, and deduce them against each other.  One of
14077    the templates will be more specialized if all the *other*
14078    template's arguments deduce against its arguments and at least one
14079    of its arguments *does* *not* deduce against the other template's
14080    corresponding argument.  Deduction is done as for class templates.
14081    The arguments used in deduction have reference and top level cv
14082    qualifiers removed.  Iff both arguments were originally reference
14083    types *and* deduction succeeds in both directions, the template
14084    with the more cv-qualified argument wins for that pairing (if
14085    neither is more cv-qualified, they both are equal).  Unlike regular
14086    deduction, after all the arguments have been deduced in this way,
14087    we do *not* verify the deduced template argument values can be
14088    substituted into non-deduced contexts, nor do we have to verify
14089    that all template arguments have been deduced.  */
14090
14091 int
14092 more_specialized_fn (tree pat1, tree pat2, int len)
14093 {
14094   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14095   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14096   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14097   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14098   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14099   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14100   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14101   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14102   int better1 = 0;
14103   int better2 = 0;
14104
14105   /* Remove the this parameter from non-static member functions.  If
14106      one is a non-static member function and the other is not a static
14107      member function, remove the first parameter from that function
14108      also.  This situation occurs for operator functions where we
14109      locate both a member function (with this pointer) and non-member
14110      operator (with explicit first operand).  */
14111   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14112     {
14113       len--; /* LEN is the number of significant arguments for DECL1 */
14114       args1 = TREE_CHAIN (args1);
14115       if (!DECL_STATIC_FUNCTION_P (decl2))
14116         args2 = TREE_CHAIN (args2);
14117     }
14118   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14119     {
14120       args2 = TREE_CHAIN (args2);
14121       if (!DECL_STATIC_FUNCTION_P (decl1))
14122         {
14123           len--;
14124           args1 = TREE_CHAIN (args1);
14125         }
14126     }
14127
14128   /* If only one is a conversion operator, they are unordered.  */
14129   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14130     return 0;
14131
14132   /* Consider the return type for a conversion function */
14133   if (DECL_CONV_FN_P (decl1))
14134     {
14135       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14136       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14137       len++;
14138     }
14139
14140   processing_template_decl++;
14141
14142   while (len--
14143          /* Stop when an ellipsis is seen.  */
14144          && args1 != NULL_TREE && args2 != NULL_TREE)
14145     {
14146       tree arg1 = TREE_VALUE (args1);
14147       tree arg2 = TREE_VALUE (args2);
14148       int deduce1, deduce2;
14149       int quals1 = -1;
14150       int quals2 = -1;
14151
14152       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14153           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14154         {
14155           /* When both arguments are pack expansions, we need only
14156              unify the patterns themselves.  */
14157           arg1 = PACK_EXPANSION_PATTERN (arg1);
14158           arg2 = PACK_EXPANSION_PATTERN (arg2);
14159
14160           /* This is the last comparison we need to do.  */
14161           len = 0;
14162         }
14163
14164       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14165         {
14166           arg1 = TREE_TYPE (arg1);
14167           quals1 = cp_type_quals (arg1);
14168         }
14169
14170       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14171         {
14172           arg2 = TREE_TYPE (arg2);
14173           quals2 = cp_type_quals (arg2);
14174         }
14175
14176       if ((quals1 < 0) != (quals2 < 0))
14177         {
14178           /* Only of the args is a reference, see if we should apply
14179              array/function pointer decay to it.  This is not part of
14180              DR214, but is, IMHO, consistent with the deduction rules
14181              for the function call itself, and with our earlier
14182              implementation of the underspecified partial ordering
14183              rules.  (nathan).  */
14184           if (quals1 >= 0)
14185             {
14186               switch (TREE_CODE (arg1))
14187                 {
14188                 case ARRAY_TYPE:
14189                   arg1 = TREE_TYPE (arg1);
14190                   /* FALLTHROUGH. */
14191                 case FUNCTION_TYPE:
14192                   arg1 = build_pointer_type (arg1);
14193                   break;
14194
14195                 default:
14196                   break;
14197                 }
14198             }
14199           else
14200             {
14201               switch (TREE_CODE (arg2))
14202                 {
14203                 case ARRAY_TYPE:
14204                   arg2 = TREE_TYPE (arg2);
14205                   /* FALLTHROUGH. */
14206                 case FUNCTION_TYPE:
14207                   arg2 = build_pointer_type (arg2);
14208                   break;
14209
14210                 default:
14211                   break;
14212                 }
14213             }
14214         }
14215
14216       arg1 = TYPE_MAIN_VARIANT (arg1);
14217       arg2 = TYPE_MAIN_VARIANT (arg2);
14218
14219       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14220         {
14221           int i, len2 = list_length (args2);
14222           tree parmvec = make_tree_vec (1);
14223           tree argvec = make_tree_vec (len2);
14224           tree ta = args2;
14225
14226           /* Setup the parameter vector, which contains only ARG1.  */
14227           TREE_VEC_ELT (parmvec, 0) = arg1;
14228
14229           /* Setup the argument vector, which contains the remaining
14230              arguments.  */
14231           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14232             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14233
14234           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14235                                            argvec, UNIFY_ALLOW_NONE, 
14236                                            /*call_args_p=*/false, 
14237                                            /*subr=*/0);
14238
14239           /* We cannot deduce in the other direction, because ARG1 is
14240              a pack expansion but ARG2 is not.  */
14241           deduce2 = 0;
14242         }
14243       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14244         {
14245           int i, len1 = list_length (args1);
14246           tree parmvec = make_tree_vec (1);
14247           tree argvec = make_tree_vec (len1);
14248           tree ta = args1;
14249
14250           /* Setup the parameter vector, which contains only ARG1.  */
14251           TREE_VEC_ELT (parmvec, 0) = arg2;
14252
14253           /* Setup the argument vector, which contains the remaining
14254              arguments.  */
14255           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14256             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14257
14258           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14259                                            argvec, UNIFY_ALLOW_NONE, 
14260                                            /*call_args_p=*/false, 
14261                                            /*subr=*/0);
14262
14263           /* We cannot deduce in the other direction, because ARG2 is
14264              a pack expansion but ARG1 is not.*/
14265           deduce1 = 0;
14266         }
14267
14268       else
14269         {
14270           /* The normal case, where neither argument is a pack
14271              expansion.  */
14272           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14273           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14274         }
14275
14276       if (!deduce1)
14277         better2 = -1;
14278       if (!deduce2)
14279         better1 = -1;
14280       if (better1 < 0 && better2 < 0)
14281         /* We've failed to deduce something in either direction.
14282            These must be unordered.  */
14283         break;
14284
14285       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14286         {
14287           /* Deduces in both directions, see if quals can
14288              disambiguate.  Pretend the worse one failed to deduce. */
14289           if ((quals1 & quals2) == quals2)
14290             deduce1 = 0;
14291           if ((quals1 & quals2) == quals1)
14292             deduce2 = 0;
14293         }
14294       if (deduce1 && !deduce2 && !better2)
14295         better2 = 1;
14296       if (deduce2 && !deduce1 && !better1)
14297         better1 = 1;
14298
14299       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14300           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14301         /* We have already processed all of the arguments in our
14302            handing of the pack expansion type.  */
14303         len = 0;
14304
14305       args1 = TREE_CHAIN (args1);
14306       args2 = TREE_CHAIN (args2);
14307     }
14308
14309   processing_template_decl--;
14310
14311   /* All things being equal, if the next argument is a pack expansion
14312      for one function but not for the other, prefer the
14313      non-variadic function.  */
14314   if ((better1 > 0) - (better2 > 0) == 0
14315       && args1 && TREE_VALUE (args1)
14316       && args2 && TREE_VALUE (args2))
14317     {
14318       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14319         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14320       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14321         return 1;
14322     }
14323
14324   return (better1 > 0) - (better2 > 0);
14325 }
14326
14327 /* Determine which of two partial specializations is more specialized.
14328
14329    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14330    to the first partial specialization.  The TREE_VALUE is the
14331    innermost set of template parameters for the partial
14332    specialization.  PAT2 is similar, but for the second template.
14333
14334    Return 1 if the first partial specialization is more specialized;
14335    -1 if the second is more specialized; 0 if neither is more
14336    specialized.
14337
14338    See [temp.class.order] for information about determining which of
14339    two templates is more specialized.  */
14340
14341 static int
14342 more_specialized_class (tree pat1, tree pat2)
14343 {
14344   tree targs;
14345   tree tmpl1, tmpl2;
14346   int winner = 0;
14347   bool any_deductions = false;
14348
14349   tmpl1 = TREE_TYPE (pat1);
14350   tmpl2 = TREE_TYPE (pat2);
14351
14352   /* Just like what happens for functions, if we are ordering between
14353      different class template specializations, we may encounter dependent
14354      types in the arguments, and we need our dependency check functions
14355      to behave correctly.  */
14356   ++processing_template_decl;
14357   targs = get_class_bindings (TREE_VALUE (pat1),
14358                               CLASSTYPE_TI_ARGS (tmpl1),
14359                               CLASSTYPE_TI_ARGS (tmpl2));
14360   if (targs)
14361     {
14362       --winner;
14363       any_deductions = true;
14364     }
14365
14366   targs = get_class_bindings (TREE_VALUE (pat2),
14367                               CLASSTYPE_TI_ARGS (tmpl2),
14368                               CLASSTYPE_TI_ARGS (tmpl1));
14369   if (targs)
14370     {
14371       ++winner;
14372       any_deductions = true;
14373     }
14374   --processing_template_decl;
14375
14376   /* In the case of a tie where at least one of the class templates
14377      has a parameter pack at the end, the template with the most
14378      non-packed parameters wins.  */
14379   if (winner == 0
14380       && any_deductions
14381       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14382           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14383     {
14384       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14385       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14386       int len1 = TREE_VEC_LENGTH (args1);
14387       int len2 = TREE_VEC_LENGTH (args2);
14388
14389       /* We don't count the pack expansion at the end.  */
14390       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14391         --len1;
14392       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14393         --len2;
14394
14395       if (len1 > len2)
14396         return 1;
14397       else if (len1 < len2)
14398         return -1;
14399     }
14400
14401   return winner;
14402 }
14403
14404 /* Return the template arguments that will produce the function signature
14405    DECL from the function template FN, with the explicit template
14406    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14407    also match.  Return NULL_TREE if no satisfactory arguments could be
14408    found.  */
14409
14410 static tree
14411 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14412 {
14413   int ntparms = DECL_NTPARMS (fn);
14414   tree targs = make_tree_vec (ntparms);
14415   tree decl_type;
14416   tree decl_arg_types;
14417
14418   /* Substitute the explicit template arguments into the type of DECL.
14419      The call to fn_type_unification will handle substitution into the
14420      FN.  */
14421   decl_type = TREE_TYPE (decl);
14422   if (explicit_args && uses_template_parms (decl_type))
14423     {
14424       tree tmpl;
14425       tree converted_args;
14426
14427       if (DECL_TEMPLATE_INFO (decl))
14428         tmpl = DECL_TI_TEMPLATE (decl);
14429       else
14430         /* We can get here for some invalid specializations.  */
14431         return NULL_TREE;
14432
14433       converted_args
14434         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14435                                  explicit_args, NULL_TREE,
14436                                  tf_none,
14437                                  /*require_all_args=*/false,
14438                                  /*use_default_args=*/false);
14439       if (converted_args == error_mark_node)
14440         return NULL_TREE;
14441
14442       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14443       if (decl_type == error_mark_node)
14444         return NULL_TREE;
14445     }
14446
14447   /* Never do unification on the 'this' parameter.  */
14448   decl_arg_types = skip_artificial_parms_for (decl, 
14449                                               TYPE_ARG_TYPES (decl_type));
14450
14451   if (fn_type_unification (fn, explicit_args, targs,
14452                            decl_arg_types,
14453                            (check_rettype || DECL_CONV_FN_P (fn)
14454                             ? TREE_TYPE (decl_type) : NULL_TREE),
14455                            DEDUCE_EXACT, LOOKUP_NORMAL))
14456     return NULL_TREE;
14457
14458   return targs;
14459 }
14460
14461 /* Return the innermost template arguments that, when applied to a
14462    template specialization whose innermost template parameters are
14463    TPARMS, and whose specialization arguments are PARMS, yield the
14464    ARGS.
14465
14466    For example, suppose we have:
14467
14468      template <class T, class U> struct S {};
14469      template <class T> struct S<T*, int> {};
14470
14471    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14472    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14473    int}.  The resulting vector will be {double}, indicating that `T'
14474    is bound to `double'.  */
14475
14476 static tree
14477 get_class_bindings (tree tparms, tree spec_args, tree args)
14478 {
14479   int i, ntparms = TREE_VEC_LENGTH (tparms);
14480   tree deduced_args;
14481   tree innermost_deduced_args;
14482
14483   innermost_deduced_args = make_tree_vec (ntparms);
14484   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14485     {
14486       deduced_args = copy_node (args);
14487       SET_TMPL_ARGS_LEVEL (deduced_args,
14488                            TMPL_ARGS_DEPTH (deduced_args),
14489                            innermost_deduced_args);
14490     }
14491   else
14492     deduced_args = innermost_deduced_args;
14493
14494   if (unify (tparms, deduced_args,
14495              INNERMOST_TEMPLATE_ARGS (spec_args),
14496              INNERMOST_TEMPLATE_ARGS (args),
14497              UNIFY_ALLOW_NONE))
14498     return NULL_TREE;
14499
14500   for (i =  0; i < ntparms; ++i)
14501     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14502       return NULL_TREE;
14503
14504   /* Verify that nondeduced template arguments agree with the type
14505      obtained from argument deduction.
14506
14507      For example:
14508
14509        struct A { typedef int X; };
14510        template <class T, class U> struct C {};
14511        template <class T> struct C<T, typename T::X> {};
14512
14513      Then with the instantiation `C<A, int>', we can deduce that
14514      `T' is `A' but unify () does not check whether `typename T::X'
14515      is `int'.  */
14516   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14517   if (spec_args == error_mark_node
14518       /* We only need to check the innermost arguments; the other
14519          arguments will always agree.  */
14520       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14521                               INNERMOST_TEMPLATE_ARGS (args)))
14522     return NULL_TREE;
14523
14524   /* Now that we have bindings for all of the template arguments,
14525      ensure that the arguments deduced for the template template
14526      parameters have compatible template parameter lists.  See the use
14527      of template_template_parm_bindings_ok_p in fn_type_unification
14528      for more information.  */
14529   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14530     return NULL_TREE;
14531
14532   return deduced_args;
14533 }
14534
14535 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14536    Return the TREE_LIST node with the most specialized template, if
14537    any.  If there is no most specialized template, the error_mark_node
14538    is returned.
14539
14540    Note that this function does not look at, or modify, the
14541    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14542    returned is one of the elements of INSTANTIATIONS, callers may
14543    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14544    and retrieve it from the value returned.  */
14545
14546 tree
14547 most_specialized_instantiation (tree templates)
14548 {
14549   tree fn, champ;
14550
14551   ++processing_template_decl;
14552
14553   champ = templates;
14554   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14555     {
14556       int fate = 0;
14557
14558       if (get_bindings (TREE_VALUE (champ),
14559                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14560                         NULL_TREE, /*check_ret=*/false))
14561         fate--;
14562
14563       if (get_bindings (TREE_VALUE (fn),
14564                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14565                         NULL_TREE, /*check_ret=*/false))
14566         fate++;
14567
14568       if (fate == -1)
14569         champ = fn;
14570       else if (!fate)
14571         {
14572           /* Equally specialized, move to next function.  If there
14573              is no next function, nothing's most specialized.  */
14574           fn = TREE_CHAIN (fn);
14575           champ = fn;
14576           if (!fn)
14577             break;
14578         }
14579     }
14580
14581   if (champ)
14582     /* Now verify that champ is better than everything earlier in the
14583        instantiation list.  */
14584     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14585       if (get_bindings (TREE_VALUE (champ),
14586                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14587                         NULL_TREE, /*check_ret=*/false)
14588           || !get_bindings (TREE_VALUE (fn),
14589                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14590                             NULL_TREE, /*check_ret=*/false))
14591         {
14592           champ = NULL_TREE;
14593           break;
14594         }
14595
14596   processing_template_decl--;
14597
14598   if (!champ)
14599     return error_mark_node;
14600
14601   return champ;
14602 }
14603
14604 /* If DECL is a specialization of some template, return the most
14605    general such template.  Otherwise, returns NULL_TREE.
14606
14607    For example, given:
14608
14609      template <class T> struct S { template <class U> void f(U); };
14610
14611    if TMPL is `template <class U> void S<int>::f(U)' this will return
14612    the full template.  This function will not trace past partial
14613    specializations, however.  For example, given in addition:
14614
14615      template <class T> struct S<T*> { template <class U> void f(U); };
14616
14617    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14618    `template <class T> template <class U> S<T*>::f(U)'.  */
14619
14620 tree
14621 most_general_template (tree decl)
14622 {
14623   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14624      an immediate specialization.  */
14625   if (TREE_CODE (decl) == FUNCTION_DECL)
14626     {
14627       if (DECL_TEMPLATE_INFO (decl)) {
14628         decl = DECL_TI_TEMPLATE (decl);
14629
14630         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14631            template friend.  */
14632         if (TREE_CODE (decl) != TEMPLATE_DECL)
14633           return NULL_TREE;
14634       } else
14635         return NULL_TREE;
14636     }
14637
14638   /* Look for more and more general templates.  */
14639   while (DECL_TEMPLATE_INFO (decl))
14640     {
14641       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14642          (See cp-tree.h for details.)  */
14643       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14644         break;
14645
14646       if (CLASS_TYPE_P (TREE_TYPE (decl))
14647           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14648         break;
14649
14650       /* Stop if we run into an explicitly specialized class template.  */
14651       if (!DECL_NAMESPACE_SCOPE_P (decl)
14652           && DECL_CONTEXT (decl)
14653           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14654         break;
14655
14656       decl = DECL_TI_TEMPLATE (decl);
14657     }
14658
14659   return decl;
14660 }
14661
14662 /* Return the most specialized of the class template partial
14663    specializations of TMPL which can produce TYPE, a specialization of
14664    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14665    a _TYPE node corresponding to the partial specialization, while the
14666    TREE_PURPOSE is the set of template arguments that must be
14667    substituted into the TREE_TYPE in order to generate TYPE.
14668
14669    If the choice of partial specialization is ambiguous, a diagnostic
14670    is issued, and the error_mark_node is returned.  If there are no
14671    partial specializations of TMPL matching TYPE, then NULL_TREE is
14672    returned.  */
14673
14674 static tree
14675 most_specialized_class (tree type, tree tmpl)
14676 {
14677   tree list = NULL_TREE;
14678   tree t;
14679   tree champ;
14680   int fate;
14681   bool ambiguous_p;
14682   tree args;
14683   tree outer_args = NULL_TREE;
14684
14685   tmpl = most_general_template (tmpl);
14686   args = CLASSTYPE_TI_ARGS (type);
14687
14688   /* For determining which partial specialization to use, only the
14689      innermost args are interesting.  */
14690   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14691     {
14692       outer_args = strip_innermost_template_args (args, 1);
14693       args = INNERMOST_TEMPLATE_ARGS (args);
14694     }
14695
14696   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14697     {
14698       tree partial_spec_args;
14699       tree spec_args;
14700       tree parms = TREE_VALUE (t);
14701
14702       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14703       if (outer_args)
14704         {
14705           int i;
14706
14707           ++processing_template_decl;
14708
14709           /* Discard the outer levels of args, and then substitute in the
14710              template args from the enclosing class.  */
14711           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14712           partial_spec_args = tsubst_template_args
14713             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14714
14715           /* PARMS already refers to just the innermost parms, but the
14716              template parms in partial_spec_args had their levels lowered
14717              by tsubst, so we need to do the same for the parm list.  We
14718              can't just tsubst the TREE_VEC itself, as tsubst wants to
14719              treat a TREE_VEC as an argument vector.  */
14720           parms = copy_node (parms);
14721           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14722             TREE_VEC_ELT (parms, i) =
14723               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14724
14725           --processing_template_decl;
14726         }
14727       spec_args = get_class_bindings (parms,
14728                                       partial_spec_args,
14729                                       args);
14730       if (spec_args)
14731         {
14732           if (outer_args)
14733             spec_args = add_to_template_args (outer_args, spec_args);
14734           list = tree_cons (spec_args, TREE_VALUE (t), list);
14735           TREE_TYPE (list) = TREE_TYPE (t);
14736         }
14737     }
14738
14739   if (! list)
14740     return NULL_TREE;
14741
14742   ambiguous_p = false;
14743   t = list;
14744   champ = t;
14745   t = TREE_CHAIN (t);
14746   for (; t; t = TREE_CHAIN (t))
14747     {
14748       fate = more_specialized_class (champ, t);
14749       if (fate == 1)
14750         ;
14751       else
14752         {
14753           if (fate == 0)
14754             {
14755               t = TREE_CHAIN (t);
14756               if (! t)
14757                 {
14758                   ambiguous_p = true;
14759                   break;
14760                 }
14761             }
14762           champ = t;
14763         }
14764     }
14765
14766   if (!ambiguous_p)
14767     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14768       {
14769         fate = more_specialized_class (champ, t);
14770         if (fate != 1)
14771           {
14772             ambiguous_p = true;
14773             break;
14774           }
14775       }
14776
14777   if (ambiguous_p)
14778     {
14779       const char *str = "candidates are:";
14780       error ("ambiguous class template instantiation for %q#T", type);
14781       for (t = list; t; t = TREE_CHAIN (t))
14782         {
14783           error ("%s %+#T", str, TREE_TYPE (t));
14784           str = "               ";
14785         }
14786       return error_mark_node;
14787     }
14788
14789   return champ;
14790 }
14791
14792 /* Explicitly instantiate DECL.  */
14793
14794 void
14795 do_decl_instantiation (tree decl, tree storage)
14796 {
14797   tree result = NULL_TREE;
14798   int extern_p = 0;
14799
14800   if (!decl || decl == error_mark_node)
14801     /* An error occurred, for which grokdeclarator has already issued
14802        an appropriate message.  */
14803     return;
14804   else if (! DECL_LANG_SPECIFIC (decl))
14805     {
14806       error ("explicit instantiation of non-template %q#D", decl);
14807       return;
14808     }
14809   else if (TREE_CODE (decl) == VAR_DECL)
14810     {
14811       /* There is an asymmetry here in the way VAR_DECLs and
14812          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14813          the latter, the DECL we get back will be marked as a
14814          template instantiation, and the appropriate
14815          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14816          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14817          should handle VAR_DECLs as it currently handles
14818          FUNCTION_DECLs.  */
14819       if (!DECL_CLASS_SCOPE_P (decl))
14820         {
14821           error ("%qD is not a static data member of a class template", decl);
14822           return;
14823         }
14824       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14825       if (!result || TREE_CODE (result) != VAR_DECL)
14826         {
14827           error ("no matching template for %qD found", decl);
14828           return;
14829         }
14830       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14831         {
14832           error ("type %qT for explicit instantiation %qD does not match "
14833                  "declared type %qT", TREE_TYPE (result), decl,
14834                  TREE_TYPE (decl));
14835           return;
14836         }
14837     }
14838   else if (TREE_CODE (decl) != FUNCTION_DECL)
14839     {
14840       error ("explicit instantiation of %q#D", decl);
14841       return;
14842     }
14843   else
14844     result = decl;
14845
14846   /* Check for various error cases.  Note that if the explicit
14847      instantiation is valid the RESULT will currently be marked as an
14848      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14849      until we get here.  */
14850
14851   if (DECL_TEMPLATE_SPECIALIZATION (result))
14852     {
14853       /* DR 259 [temp.spec].
14854
14855          Both an explicit instantiation and a declaration of an explicit
14856          specialization shall not appear in a program unless the explicit
14857          instantiation follows a declaration of the explicit specialization.
14858
14859          For a given set of template parameters, if an explicit
14860          instantiation of a template appears after a declaration of an
14861          explicit specialization for that template, the explicit
14862          instantiation has no effect.  */
14863       return;
14864     }
14865   else if (DECL_EXPLICIT_INSTANTIATION (result))
14866     {
14867       /* [temp.spec]
14868
14869          No program shall explicitly instantiate any template more
14870          than once.
14871
14872          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14873          the first instantiation was `extern' and the second is not,
14874          and EXTERN_P for the opposite case.  */
14875       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14876         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14877       /* If an "extern" explicit instantiation follows an ordinary
14878          explicit instantiation, the template is instantiated.  */
14879       if (extern_p)
14880         return;
14881     }
14882   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14883     {
14884       error ("no matching template for %qD found", result);
14885       return;
14886     }
14887   else if (!DECL_TEMPLATE_INFO (result))
14888     {
14889       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14890       return;
14891     }
14892
14893   if (storage == NULL_TREE)
14894     ;
14895   else if (storage == ridpointers[(int) RID_EXTERN])
14896     {
14897       if (!in_system_header && (cxx_dialect == cxx98))
14898         pedwarn (input_location, OPT_pedantic, 
14899                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14900                  "instantiations");
14901       extern_p = 1;
14902     }
14903   else
14904     error ("storage class %qD applied to template instantiation", storage);
14905
14906   check_explicit_instantiation_namespace (result);
14907   mark_decl_instantiated (result, extern_p);
14908   if (! extern_p)
14909     instantiate_decl (result, /*defer_ok=*/1,
14910                       /*expl_inst_class_mem_p=*/false);
14911 }
14912
14913 static void
14914 mark_class_instantiated (tree t, int extern_p)
14915 {
14916   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14917   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14918   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14919   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14920   if (! extern_p)
14921     {
14922       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14923       rest_of_type_compilation (t, 1);
14924     }
14925 }
14926
14927 /* Called from do_type_instantiation through binding_table_foreach to
14928    do recursive instantiation for the type bound in ENTRY.  */
14929 static void
14930 bt_instantiate_type_proc (binding_entry entry, void *data)
14931 {
14932   tree storage = *(tree *) data;
14933
14934   if (MAYBE_CLASS_TYPE_P (entry->type)
14935       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14936     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14937 }
14938
14939 /* Called from do_type_instantiation to instantiate a member
14940    (a member function or a static member variable) of an
14941    explicitly instantiated class template.  */
14942 static void
14943 instantiate_class_member (tree decl, int extern_p)
14944 {
14945   mark_decl_instantiated (decl, extern_p);
14946   if (! extern_p)
14947     instantiate_decl (decl, /*defer_ok=*/1,
14948                       /*expl_inst_class_mem_p=*/true);
14949 }
14950
14951 /* Perform an explicit instantiation of template class T.  STORAGE, if
14952    non-null, is the RID for extern, inline or static.  COMPLAIN is
14953    nonzero if this is called from the parser, zero if called recursively,
14954    since the standard is unclear (as detailed below).  */
14955
14956 void
14957 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14958 {
14959   int extern_p = 0;
14960   int nomem_p = 0;
14961   int static_p = 0;
14962   int previous_instantiation_extern_p = 0;
14963
14964   if (TREE_CODE (t) == TYPE_DECL)
14965     t = TREE_TYPE (t);
14966
14967   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14968     {
14969       error ("explicit instantiation of non-template type %qT", t);
14970       return;
14971     }
14972
14973   complete_type (t);
14974
14975   if (!COMPLETE_TYPE_P (t))
14976     {
14977       if (complain & tf_error)
14978         error ("explicit instantiation of %q#T before definition of template",
14979                t);
14980       return;
14981     }
14982
14983   if (storage != NULL_TREE)
14984     {
14985       if (!in_system_header)
14986         {
14987           if (storage == ridpointers[(int) RID_EXTERN])
14988             {
14989               if (cxx_dialect == cxx98)
14990                 pedwarn (input_location, OPT_pedantic, 
14991                          "ISO C++ 1998 forbids the use of %<extern%> on "
14992                          "explicit instantiations");
14993             }
14994           else
14995             pedwarn (input_location, OPT_pedantic, 
14996                      "ISO C++ forbids the use of %qE"
14997                      " on explicit instantiations", storage);
14998         }
14999
15000       if (storage == ridpointers[(int) RID_INLINE])
15001         nomem_p = 1;
15002       else if (storage == ridpointers[(int) RID_EXTERN])
15003         extern_p = 1;
15004       else if (storage == ridpointers[(int) RID_STATIC])
15005         static_p = 1;
15006       else
15007         {
15008           error ("storage class %qD applied to template instantiation",
15009                  storage);
15010           extern_p = 0;
15011         }
15012     }
15013
15014   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15015     {
15016       /* DR 259 [temp.spec].
15017
15018          Both an explicit instantiation and a declaration of an explicit
15019          specialization shall not appear in a program unless the explicit
15020          instantiation follows a declaration of the explicit specialization.
15021
15022          For a given set of template parameters, if an explicit
15023          instantiation of a template appears after a declaration of an
15024          explicit specialization for that template, the explicit
15025          instantiation has no effect.  */
15026       return;
15027     }
15028   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15029     {
15030       /* [temp.spec]
15031
15032          No program shall explicitly instantiate any template more
15033          than once.
15034
15035          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15036          instantiation was `extern'.  If EXTERN_P then the second is.
15037          These cases are OK.  */
15038       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15039
15040       if (!previous_instantiation_extern_p && !extern_p
15041           && (complain & tf_error))
15042         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15043
15044       /* If we've already instantiated the template, just return now.  */
15045       if (!CLASSTYPE_INTERFACE_ONLY (t))
15046         return;
15047     }
15048
15049   check_explicit_instantiation_namespace (TYPE_NAME (t));
15050   mark_class_instantiated (t, extern_p);
15051
15052   if (nomem_p)
15053     return;
15054
15055   {
15056     tree tmp;
15057
15058     /* In contrast to implicit instantiation, where only the
15059        declarations, and not the definitions, of members are
15060        instantiated, we have here:
15061
15062          [temp.explicit]
15063
15064          The explicit instantiation of a class template specialization
15065          implies the instantiation of all of its members not
15066          previously explicitly specialized in the translation unit
15067          containing the explicit instantiation.
15068
15069        Of course, we can't instantiate member template classes, since
15070        we don't have any arguments for them.  Note that the standard
15071        is unclear on whether the instantiation of the members are
15072        *explicit* instantiations or not.  However, the most natural
15073        interpretation is that it should be an explicit instantiation.  */
15074
15075     if (! static_p)
15076       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15077         if (TREE_CODE (tmp) == FUNCTION_DECL
15078             && DECL_TEMPLATE_INSTANTIATION (tmp))
15079           instantiate_class_member (tmp, extern_p);
15080
15081     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15082       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15083         instantiate_class_member (tmp, extern_p);
15084
15085     if (CLASSTYPE_NESTED_UTDS (t))
15086       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15087                              bt_instantiate_type_proc, &storage);
15088   }
15089 }
15090
15091 /* Given a function DECL, which is a specialization of TMPL, modify
15092    DECL to be a re-instantiation of TMPL with the same template
15093    arguments.  TMPL should be the template into which tsubst'ing
15094    should occur for DECL, not the most general template.
15095
15096    One reason for doing this is a scenario like this:
15097
15098      template <class T>
15099      void f(const T&, int i);
15100
15101      void g() { f(3, 7); }
15102
15103      template <class T>
15104      void f(const T& t, const int i) { }
15105
15106    Note that when the template is first instantiated, with
15107    instantiate_template, the resulting DECL will have no name for the
15108    first parameter, and the wrong type for the second.  So, when we go
15109    to instantiate the DECL, we regenerate it.  */
15110
15111 static void
15112 regenerate_decl_from_template (tree decl, tree tmpl)
15113 {
15114   /* The arguments used to instantiate DECL, from the most general
15115      template.  */
15116   tree args;
15117   tree code_pattern;
15118
15119   args = DECL_TI_ARGS (decl);
15120   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15121
15122   /* Make sure that we can see identifiers, and compute access
15123      correctly.  */
15124   push_access_scope (decl);
15125
15126   if (TREE_CODE (decl) == FUNCTION_DECL)
15127     {
15128       tree decl_parm;
15129       tree pattern_parm;
15130       tree specs;
15131       int args_depth;
15132       int parms_depth;
15133
15134       args_depth = TMPL_ARGS_DEPTH (args);
15135       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15136       if (args_depth > parms_depth)
15137         args = get_innermost_template_args (args, parms_depth);
15138
15139       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15140                                               args, tf_error, NULL_TREE);
15141       if (specs)
15142         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15143                                                     specs);
15144
15145       /* Merge parameter declarations.  */
15146       decl_parm = skip_artificial_parms_for (decl,
15147                                              DECL_ARGUMENTS (decl));
15148       pattern_parm
15149         = skip_artificial_parms_for (code_pattern,
15150                                      DECL_ARGUMENTS (code_pattern));
15151       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15152         {
15153           tree parm_type;
15154           tree attributes;
15155           
15156           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15157             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15158           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15159                               NULL_TREE);
15160           parm_type = type_decays_to (parm_type);
15161           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15162             TREE_TYPE (decl_parm) = parm_type;
15163           attributes = DECL_ATTRIBUTES (pattern_parm);
15164           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15165             {
15166               DECL_ATTRIBUTES (decl_parm) = attributes;
15167               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15168             }
15169           decl_parm = TREE_CHAIN (decl_parm);
15170           pattern_parm = TREE_CHAIN (pattern_parm);
15171         }
15172       /* Merge any parameters that match with the function parameter
15173          pack.  */
15174       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15175         {
15176           int i, len;
15177           tree expanded_types;
15178           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15179              the parameters in this function parameter pack.  */
15180           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15181                                                  args, tf_error, NULL_TREE);
15182           len = TREE_VEC_LENGTH (expanded_types);
15183           for (i = 0; i < len; i++)
15184             {
15185               tree parm_type;
15186               tree attributes;
15187           
15188               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15189                 /* Rename the parameter to include the index.  */
15190                 DECL_NAME (decl_parm) = 
15191                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15192               parm_type = TREE_VEC_ELT (expanded_types, i);
15193               parm_type = type_decays_to (parm_type);
15194               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15195                 TREE_TYPE (decl_parm) = parm_type;
15196               attributes = DECL_ATTRIBUTES (pattern_parm);
15197               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15198                 {
15199                   DECL_ATTRIBUTES (decl_parm) = attributes;
15200                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15201                 }
15202               decl_parm = TREE_CHAIN (decl_parm);
15203             }
15204         }
15205       /* Merge additional specifiers from the CODE_PATTERN.  */
15206       if (DECL_DECLARED_INLINE_P (code_pattern)
15207           && !DECL_DECLARED_INLINE_P (decl))
15208         DECL_DECLARED_INLINE_P (decl) = 1;
15209     }
15210   else if (TREE_CODE (decl) == VAR_DECL)
15211     DECL_INITIAL (decl) =
15212       tsubst_expr (DECL_INITIAL (code_pattern), args,
15213                    tf_error, DECL_TI_TEMPLATE (decl),
15214                    /*integral_constant_expression_p=*/false);
15215   else
15216     gcc_unreachable ();
15217
15218   pop_access_scope (decl);
15219 }
15220
15221 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15222    substituted to get DECL.  */
15223
15224 tree
15225 template_for_substitution (tree decl)
15226 {
15227   tree tmpl = DECL_TI_TEMPLATE (decl);
15228
15229   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15230      for the instantiation.  This is not always the most general
15231      template.  Consider, for example:
15232
15233         template <class T>
15234         struct S { template <class U> void f();
15235                    template <> void f<int>(); };
15236
15237      and an instantiation of S<double>::f<int>.  We want TD to be the
15238      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15239   while (/* An instantiation cannot have a definition, so we need a
15240             more general template.  */
15241          DECL_TEMPLATE_INSTANTIATION (tmpl)
15242            /* We must also deal with friend templates.  Given:
15243
15244                 template <class T> struct S {
15245                   template <class U> friend void f() {};
15246                 };
15247
15248               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15249               so far as the language is concerned, but that's still
15250               where we get the pattern for the instantiation from.  On
15251               other hand, if the definition comes outside the class, say:
15252
15253                 template <class T> struct S {
15254                   template <class U> friend void f();
15255                 };
15256                 template <class U> friend void f() {}
15257
15258               we don't need to look any further.  That's what the check for
15259               DECL_INITIAL is for.  */
15260           || (TREE_CODE (decl) == FUNCTION_DECL
15261               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15262               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15263     {
15264       /* The present template, TD, should not be a definition.  If it
15265          were a definition, we should be using it!  Note that we
15266          cannot restructure the loop to just keep going until we find
15267          a template with a definition, since that might go too far if
15268          a specialization was declared, but not defined.  */
15269       gcc_assert (TREE_CODE (decl) != VAR_DECL
15270                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15271
15272       /* Fetch the more general template.  */
15273       tmpl = DECL_TI_TEMPLATE (tmpl);
15274     }
15275
15276   return tmpl;
15277 }
15278
15279 /* Produce the definition of D, a _DECL generated from a template.  If
15280    DEFER_OK is nonzero, then we don't have to actually do the
15281    instantiation now; we just have to do it sometime.  Normally it is
15282    an error if this is an explicit instantiation but D is undefined.
15283    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15284    explicitly instantiated class template.  */
15285
15286 tree
15287 instantiate_decl (tree d, int defer_ok,
15288                   bool expl_inst_class_mem_p)
15289 {
15290   tree tmpl = DECL_TI_TEMPLATE (d);
15291   tree gen_args;
15292   tree args;
15293   tree td;
15294   tree code_pattern;
15295   tree spec;
15296   tree gen_tmpl;
15297   bool pattern_defined;
15298   int need_push;
15299   location_t saved_loc = input_location;
15300   bool external_p;
15301
15302   /* This function should only be used to instantiate templates for
15303      functions and static member variables.  */
15304   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15305               || TREE_CODE (d) == VAR_DECL);
15306
15307   /* Variables are never deferred; if instantiation is required, they
15308      are instantiated right away.  That allows for better code in the
15309      case that an expression refers to the value of the variable --
15310      if the variable has a constant value the referring expression can
15311      take advantage of that fact.  */
15312   if (TREE_CODE (d) == VAR_DECL)
15313     defer_ok = 0;
15314
15315   /* Don't instantiate cloned functions.  Instead, instantiate the
15316      functions they cloned.  */
15317   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15318     d = DECL_CLONED_FUNCTION (d);
15319
15320   if (DECL_TEMPLATE_INSTANTIATED (d))
15321     /* D has already been instantiated.  It might seem reasonable to
15322        check whether or not D is an explicit instantiation, and, if so,
15323        stop here.  But when an explicit instantiation is deferred
15324        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15325        is set, even though we still need to do the instantiation.  */
15326     return d;
15327
15328   /* If we already have a specialization of this declaration, then
15329      there's no reason to instantiate it.  Note that
15330      retrieve_specialization gives us both instantiations and
15331      specializations, so we must explicitly check
15332      DECL_TEMPLATE_SPECIALIZATION.  */
15333   gen_tmpl = most_general_template (tmpl);
15334   gen_args = DECL_TI_ARGS (d);
15335   spec = retrieve_specialization (gen_tmpl, gen_args,
15336                                   /*class_specializations_p=*/false);
15337   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15338     return spec;
15339
15340   /* This needs to happen before any tsubsting.  */
15341   if (! push_tinst_level (d))
15342     return d;
15343
15344   timevar_push (TV_PARSE);
15345
15346   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15347      for the instantiation.  */
15348   td = template_for_substitution (d);
15349   code_pattern = DECL_TEMPLATE_RESULT (td);
15350
15351   /* We should never be trying to instantiate a member of a class
15352      template or partial specialization.  */
15353   gcc_assert (d != code_pattern);
15354
15355   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15356       || DECL_TEMPLATE_SPECIALIZATION (td))
15357     /* In the case of a friend template whose definition is provided
15358        outside the class, we may have too many arguments.  Drop the
15359        ones we don't need.  The same is true for specializations.  */
15360     args = get_innermost_template_args
15361       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15362   else
15363     args = gen_args;
15364
15365   if (TREE_CODE (d) == FUNCTION_DECL)
15366     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15367   else
15368     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15369
15370   /* We may be in the middle of deferred access check.  Disable it now.  */
15371   push_deferring_access_checks (dk_no_deferred);
15372
15373   /* Unless an explicit instantiation directive has already determined
15374      the linkage of D, remember that a definition is available for
15375      this entity.  */
15376   if (pattern_defined
15377       && !DECL_INTERFACE_KNOWN (d)
15378       && !DECL_NOT_REALLY_EXTERN (d))
15379     mark_definable (d);
15380
15381   input_location = DECL_SOURCE_LOCATION (d);
15382
15383   /* If D is a member of an explicitly instantiated class template,
15384      and no definition is available, treat it like an implicit
15385      instantiation.  */
15386   if (!pattern_defined && expl_inst_class_mem_p
15387       && DECL_EXPLICIT_INSTANTIATION (d))
15388     {
15389       DECL_NOT_REALLY_EXTERN (d) = 0;
15390       DECL_INTERFACE_KNOWN (d) = 0;
15391       SET_DECL_IMPLICIT_INSTANTIATION (d);
15392     }
15393
15394   if (!defer_ok)
15395     {
15396       /* Recheck the substitutions to obtain any warning messages
15397          about ignoring cv qualifiers.  */
15398       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15399       tree type = TREE_TYPE (gen);
15400
15401       /* Make sure that we can see identifiers, and compute access
15402          correctly.  D is already the target FUNCTION_DECL with the
15403          right context.  */
15404       push_access_scope (d);
15405
15406       if (TREE_CODE (gen) == FUNCTION_DECL)
15407         {
15408           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15409           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15410                                           d);
15411           /* Don't simply tsubst the function type, as that will give
15412              duplicate warnings about poor parameter qualifications.
15413              The function arguments are the same as the decl_arguments
15414              without the top level cv qualifiers.  */
15415           type = TREE_TYPE (type);
15416         }
15417       tsubst (type, gen_args, tf_warning_or_error, d);
15418
15419       pop_access_scope (d);
15420     }
15421
15422   /* Check to see whether we know that this template will be
15423      instantiated in some other file, as with "extern template"
15424      extension.  */
15425   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15426   /* In general, we do not instantiate such templates...  */
15427   if (external_p
15428       /* ... but we instantiate inline functions so that we can inline
15429          them.  An explicit instantiation declaration prohibits implicit
15430          instantiation of non-inline functions.  With high levels of
15431          optimization, we would normally inline non-inline functions
15432          -- but we're not allowed to do that for "extern template" functions.
15433          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15434          possibly_inlined_p.  And ...  */
15435       && ! (TREE_CODE (d) == FUNCTION_DECL
15436             && DECL_DECLARED_INLINE_P (d))
15437       /* ... we instantiate static data members whose values are
15438          needed in integral constant expressions.  */
15439       && ! (TREE_CODE (d) == VAR_DECL
15440             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15441     goto out;
15442   /* Defer all other templates, unless we have been explicitly
15443      forbidden from doing so.  */
15444   if (/* If there is no definition, we cannot instantiate the
15445          template.  */
15446       ! pattern_defined
15447       /* If it's OK to postpone instantiation, do so.  */
15448       || defer_ok
15449       /* If this is a static data member that will be defined
15450          elsewhere, we don't want to instantiate the entire data
15451          member, but we do want to instantiate the initializer so that
15452          we can substitute that elsewhere.  */
15453       || (external_p && TREE_CODE (d) == VAR_DECL))
15454     {
15455       /* The definition of the static data member is now required so
15456          we must substitute the initializer.  */
15457       if (TREE_CODE (d) == VAR_DECL
15458           && !DECL_INITIAL (d)
15459           && DECL_INITIAL (code_pattern))
15460         {
15461           tree ns;
15462           tree init;
15463
15464           ns = decl_namespace_context (d);
15465           push_nested_namespace (ns);
15466           push_nested_class (DECL_CONTEXT (d));
15467           init = tsubst_expr (DECL_INITIAL (code_pattern),
15468                               args,
15469                               tf_warning_or_error, NULL_TREE,
15470                               /*integral_constant_expression_p=*/false);
15471           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15472                           /*asmspec_tree=*/NULL_TREE,
15473                           LOOKUP_ONLYCONVERTING);
15474           pop_nested_class ();
15475           pop_nested_namespace (ns);
15476         }
15477
15478       /* We restore the source position here because it's used by
15479          add_pending_template.  */
15480       input_location = saved_loc;
15481
15482       if (at_eof && !pattern_defined
15483           && DECL_EXPLICIT_INSTANTIATION (d)
15484           && DECL_NOT_REALLY_EXTERN (d))
15485         /* [temp.explicit]
15486
15487            The definition of a non-exported function template, a
15488            non-exported member function template, or a non-exported
15489            member function or static data member of a class template
15490            shall be present in every translation unit in which it is
15491            explicitly instantiated.  */
15492         permerror (input_location,  "explicit instantiation of %qD "
15493                    "but no definition available", d);
15494
15495       /* ??? Historically, we have instantiated inline functions, even
15496          when marked as "extern template".  */
15497       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15498         add_pending_template (d);
15499       goto out;
15500     }
15501   /* Tell the repository that D is available in this translation unit
15502      -- and see if it is supposed to be instantiated here.  */
15503   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15504     {
15505       /* In a PCH file, despite the fact that the repository hasn't
15506          requested instantiation in the PCH it is still possible that
15507          an instantiation will be required in a file that includes the
15508          PCH.  */
15509       if (pch_file)
15510         add_pending_template (d);
15511       /* Instantiate inline functions so that the inliner can do its
15512          job, even though we'll not be emitting a copy of this
15513          function.  */
15514       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15515         goto out;
15516     }
15517
15518   need_push = !cfun || !global_bindings_p ();
15519   if (need_push)
15520     push_to_top_level ();
15521
15522   /* Mark D as instantiated so that recursive calls to
15523      instantiate_decl do not try to instantiate it again.  */
15524   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15525
15526   /* Regenerate the declaration in case the template has been modified
15527      by a subsequent redeclaration.  */
15528   regenerate_decl_from_template (d, td);
15529
15530   /* We already set the file and line above.  Reset them now in case
15531      they changed as a result of calling regenerate_decl_from_template.  */
15532   input_location = DECL_SOURCE_LOCATION (d);
15533
15534   if (TREE_CODE (d) == VAR_DECL)
15535     {
15536       tree init;
15537
15538       /* Clear out DECL_RTL; whatever was there before may not be right
15539          since we've reset the type of the declaration.  */
15540       SET_DECL_RTL (d, NULL_RTX);
15541       DECL_IN_AGGR_P (d) = 0;
15542
15543       /* The initializer is placed in DECL_INITIAL by
15544          regenerate_decl_from_template.  Pull it out so that
15545          finish_decl can process it.  */
15546       init = DECL_INITIAL (d);
15547       DECL_INITIAL (d) = NULL_TREE;
15548       DECL_INITIALIZED_P (d) = 0;
15549
15550       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15551          initializer.  That function will defer actual emission until
15552          we have a chance to determine linkage.  */
15553       DECL_EXTERNAL (d) = 0;
15554
15555       /* Enter the scope of D so that access-checking works correctly.  */
15556       push_nested_class (DECL_CONTEXT (d));
15557       finish_decl (d, init, NULL_TREE);
15558       pop_nested_class ();
15559     }
15560   else if (TREE_CODE (d) == FUNCTION_DECL)
15561     {
15562       htab_t saved_local_specializations;
15563       tree subst_decl;
15564       tree tmpl_parm;
15565       tree spec_parm;
15566
15567       /* Save away the current list, in case we are instantiating one
15568          template from within the body of another.  */
15569       saved_local_specializations = local_specializations;
15570
15571       /* Set up the list of local specializations.  */
15572       local_specializations = htab_create (37,
15573                                            hash_local_specialization,
15574                                            eq_local_specializations,
15575                                            NULL);
15576
15577       /* Set up context.  */
15578       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15579
15580       /* Create substitution entries for the parameters.  */
15581       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15582       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15583       spec_parm = DECL_ARGUMENTS (d);
15584       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15585         {
15586           register_local_specialization (spec_parm, tmpl_parm);
15587           spec_parm = skip_artificial_parms_for (d, spec_parm);
15588           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15589         }
15590       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15591         {
15592           register_local_specialization (spec_parm, tmpl_parm);
15593           tmpl_parm = TREE_CHAIN (tmpl_parm);
15594           spec_parm = TREE_CHAIN (spec_parm);
15595         }
15596       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15597         {
15598           /* Register the (value) argument pack as a specialization of
15599              TMPL_PARM, then move on.  */
15600           tree argpack = make_fnparm_pack (spec_parm);
15601           register_local_specialization (argpack, tmpl_parm);
15602           tmpl_parm = TREE_CHAIN (tmpl_parm);
15603           spec_parm = NULL_TREE;
15604         }
15605       gcc_assert (!spec_parm);
15606
15607       /* Substitute into the body of the function.  */
15608       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15609                    tf_warning_or_error, tmpl,
15610                    /*integral_constant_expression_p=*/false);
15611
15612       /* Set the current input_location to the end of the function
15613          so that finish_function knows where we are.  */
15614       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15615
15616       /* We don't need the local specializations any more.  */
15617       htab_delete (local_specializations);
15618       local_specializations = saved_local_specializations;
15619
15620       /* Finish the function.  */
15621       d = finish_function (0);
15622       expand_or_defer_fn (d);
15623     }
15624
15625   /* We're not deferring instantiation any more.  */
15626   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15627
15628   if (need_push)
15629     pop_from_top_level ();
15630
15631 out:
15632   input_location = saved_loc;
15633   pop_deferring_access_checks ();
15634   pop_tinst_level ();
15635
15636   timevar_pop (TV_PARSE);
15637
15638   return d;
15639 }
15640
15641 /* Run through the list of templates that we wish we could
15642    instantiate, and instantiate any we can.  RETRIES is the
15643    number of times we retry pending template instantiation.  */
15644
15645 void
15646 instantiate_pending_templates (int retries)
15647 {
15648   int reconsider;
15649   location_t saved_loc = input_location;
15650
15651   /* Instantiating templates may trigger vtable generation.  This in turn
15652      may require further template instantiations.  We place a limit here
15653      to avoid infinite loop.  */
15654   if (pending_templates && retries >= max_tinst_depth)
15655     {
15656       tree decl = pending_templates->tinst->decl;
15657
15658       error ("template instantiation depth exceeds maximum of %d"
15659              " instantiating %q+D, possibly from virtual table generation"
15660              " (use -ftemplate-depth-NN to increase the maximum)",
15661              max_tinst_depth, decl);
15662       if (TREE_CODE (decl) == FUNCTION_DECL)
15663         /* Pretend that we defined it.  */
15664         DECL_INITIAL (decl) = error_mark_node;
15665       return;
15666     }
15667
15668   do
15669     {
15670       struct pending_template **t = &pending_templates;
15671       struct pending_template *last = NULL;
15672       reconsider = 0;
15673       while (*t)
15674         {
15675           tree instantiation = reopen_tinst_level ((*t)->tinst);
15676           bool complete = false;
15677
15678           if (TYPE_P (instantiation))
15679             {
15680               tree fn;
15681
15682               if (!COMPLETE_TYPE_P (instantiation))
15683                 {
15684                   instantiate_class_template (instantiation);
15685                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15686                     for (fn = TYPE_METHODS (instantiation);
15687                          fn;
15688                          fn = TREE_CHAIN (fn))
15689                       if (! DECL_ARTIFICIAL (fn))
15690                         instantiate_decl (fn,
15691                                           /*defer_ok=*/0,
15692                                           /*expl_inst_class_mem_p=*/false);
15693                   if (COMPLETE_TYPE_P (instantiation))
15694                     reconsider = 1;
15695                 }
15696
15697               complete = COMPLETE_TYPE_P (instantiation);
15698             }
15699           else
15700             {
15701               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15702                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15703                 {
15704                   instantiation
15705                     = instantiate_decl (instantiation,
15706                                         /*defer_ok=*/0,
15707                                         /*expl_inst_class_mem_p=*/false);
15708                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15709                     reconsider = 1;
15710                 }
15711
15712               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15713                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15714             }
15715
15716           if (complete)
15717             /* If INSTANTIATION has been instantiated, then we don't
15718                need to consider it again in the future.  */
15719             *t = (*t)->next;
15720           else
15721             {
15722               last = *t;
15723               t = &(*t)->next;
15724             }
15725           tinst_depth = 0;
15726           current_tinst_level = NULL;
15727         }
15728       last_pending_template = last;
15729     }
15730   while (reconsider);
15731
15732   input_location = saved_loc;
15733 }
15734
15735 /* Substitute ARGVEC into T, which is a list of initializers for
15736    either base class or a non-static data member.  The TREE_PURPOSEs
15737    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15738    instantiate_decl.  */
15739
15740 static tree
15741 tsubst_initializer_list (tree t, tree argvec)
15742 {
15743   tree inits = NULL_TREE;
15744
15745   for (; t; t = TREE_CHAIN (t))
15746     {
15747       tree decl;
15748       tree init;
15749       tree expanded_bases = NULL_TREE;
15750       tree expanded_arguments = NULL_TREE;
15751       int i, len = 1;
15752
15753       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15754         {
15755           tree expr;
15756           tree arg;
15757
15758           /* Expand the base class expansion type into separate base
15759              classes.  */
15760           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15761                                                  tf_warning_or_error,
15762                                                  NULL_TREE);
15763           if (expanded_bases == error_mark_node)
15764             continue;
15765           
15766           /* We'll be building separate TREE_LISTs of arguments for
15767              each base.  */
15768           len = TREE_VEC_LENGTH (expanded_bases);
15769           expanded_arguments = make_tree_vec (len);
15770           for (i = 0; i < len; i++)
15771             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15772
15773           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15774              expand each argument in the TREE_VALUE of t.  */
15775           expr = make_node (EXPR_PACK_EXPANSION);
15776           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15777             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15778
15779           if (TREE_VALUE (t) == void_type_node)
15780             /* VOID_TYPE_NODE is used to indicate
15781                value-initialization.  */
15782             {
15783               for (i = 0; i < len; i++)
15784                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15785             }
15786           else
15787             {
15788               /* Substitute parameter packs into each argument in the
15789                  TREE_LIST.  */
15790               in_base_initializer = 1;
15791               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15792                 {
15793                   tree expanded_exprs;
15794
15795                   /* Expand the argument.  */
15796                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15797                   expanded_exprs 
15798                     = tsubst_pack_expansion (expr, argvec,
15799                                              tf_warning_or_error,
15800                                              NULL_TREE);
15801                   if (expanded_exprs == error_mark_node)
15802                     continue;
15803
15804                   /* Prepend each of the expanded expressions to the
15805                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15806                   for (i = 0; i < len; i++)
15807                     {
15808                       TREE_VEC_ELT (expanded_arguments, i) = 
15809                         tree_cons (NULL_TREE, 
15810                                    TREE_VEC_ELT (expanded_exprs, i),
15811                                    TREE_VEC_ELT (expanded_arguments, i));
15812                     }
15813                 }
15814               in_base_initializer = 0;
15815
15816               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15817                  since we built them backwards.  */
15818               for (i = 0; i < len; i++)
15819                 {
15820                   TREE_VEC_ELT (expanded_arguments, i) = 
15821                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15822                 }
15823             }
15824         }
15825
15826       for (i = 0; i < len; ++i)
15827         {
15828           if (expanded_bases)
15829             {
15830               decl = TREE_VEC_ELT (expanded_bases, i);
15831               decl = expand_member_init (decl);
15832               init = TREE_VEC_ELT (expanded_arguments, i);
15833             }
15834           else
15835             {
15836               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15837                                   tf_warning_or_error, NULL_TREE);
15838
15839               decl = expand_member_init (decl);
15840               if (decl && !DECL_P (decl))
15841                 in_base_initializer = 1;
15842
15843               init = tsubst_expr (TREE_VALUE (t), argvec, 
15844                                   tf_warning_or_error, NULL_TREE,
15845                                   /*integral_constant_expression_p=*/false);
15846               in_base_initializer = 0;
15847             }
15848
15849           if (decl)
15850             {
15851               init = build_tree_list (decl, init);
15852               TREE_CHAIN (init) = inits;
15853               inits = init;
15854             }
15855         }
15856     }
15857   return inits;
15858 }
15859
15860 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15861
15862 static void
15863 set_current_access_from_decl (tree decl)
15864 {
15865   if (TREE_PRIVATE (decl))
15866     current_access_specifier = access_private_node;
15867   else if (TREE_PROTECTED (decl))
15868     current_access_specifier = access_protected_node;
15869   else
15870     current_access_specifier = access_public_node;
15871 }
15872
15873 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15874    is the instantiation (which should have been created with
15875    start_enum) and ARGS are the template arguments to use.  */
15876
15877 static void
15878 tsubst_enum (tree tag, tree newtag, tree args)
15879 {
15880   tree e;
15881
15882   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15883     {
15884       tree value;
15885       tree decl;
15886
15887       decl = TREE_VALUE (e);
15888       /* Note that in a template enum, the TREE_VALUE is the
15889          CONST_DECL, not the corresponding INTEGER_CST.  */
15890       value = tsubst_expr (DECL_INITIAL (decl),
15891                            args, tf_warning_or_error, NULL_TREE,
15892                            /*integral_constant_expression_p=*/true);
15893
15894       /* Give this enumeration constant the correct access.  */
15895       set_current_access_from_decl (decl);
15896
15897       /* Actually build the enumerator itself.  */
15898       build_enumerator (DECL_NAME (decl), value, newtag);
15899     }
15900
15901   finish_enum (newtag);
15902   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15903     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15904 }
15905
15906 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15907    its type -- but without substituting the innermost set of template
15908    arguments.  So, innermost set of template parameters will appear in
15909    the type.  */
15910
15911 tree
15912 get_mostly_instantiated_function_type (tree decl)
15913 {
15914   tree fn_type;
15915   tree tmpl;
15916   tree targs;
15917   tree tparms;
15918   int parm_depth;
15919
15920   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15921   targs = DECL_TI_ARGS (decl);
15922   tparms = DECL_TEMPLATE_PARMS (tmpl);
15923   parm_depth = TMPL_PARMS_DEPTH (tparms);
15924
15925   /* There should be as many levels of arguments as there are levels
15926      of parameters.  */
15927   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15928
15929   fn_type = TREE_TYPE (tmpl);
15930
15931   if (parm_depth == 1)
15932     /* No substitution is necessary.  */
15933     ;
15934   else
15935     {
15936       int i, save_access_control;
15937       tree partial_args;
15938
15939       /* Replace the innermost level of the TARGS with NULL_TREEs to
15940          let tsubst know not to substitute for those parameters.  */
15941       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15942       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15943         SET_TMPL_ARGS_LEVEL (partial_args, i,
15944                              TMPL_ARGS_LEVEL (targs, i));
15945       SET_TMPL_ARGS_LEVEL (partial_args,
15946                            TMPL_ARGS_DEPTH (targs),
15947                            make_tree_vec (DECL_NTPARMS (tmpl)));
15948
15949       /* Disable access control as this function is used only during
15950          name-mangling.  */
15951       save_access_control = flag_access_control;
15952       flag_access_control = 0;
15953
15954       ++processing_template_decl;
15955       /* Now, do the (partial) substitution to figure out the
15956          appropriate function type.  */
15957       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15958       --processing_template_decl;
15959
15960       /* Substitute into the template parameters to obtain the real
15961          innermost set of parameters.  This step is important if the
15962          innermost set of template parameters contains value
15963          parameters whose types depend on outer template parameters.  */
15964       TREE_VEC_LENGTH (partial_args)--;
15965       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15966
15967       flag_access_control = save_access_control;
15968     }
15969
15970   return fn_type;
15971 }
15972
15973 /* Return truthvalue if we're processing a template different from
15974    the last one involved in diagnostics.  */
15975 int
15976 problematic_instantiation_changed (void)
15977 {
15978   return last_template_error_tick != tinst_level_tick;
15979 }
15980
15981 /* Remember current template involved in diagnostics.  */
15982 void
15983 record_last_problematic_instantiation (void)
15984 {
15985   last_template_error_tick = tinst_level_tick;
15986 }
15987
15988 struct tinst_level *
15989 current_instantiation (void)
15990 {
15991   return current_tinst_level;
15992 }
15993
15994 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15995    type. Return zero for ok, nonzero for disallowed. Issue error and
15996    warning messages under control of COMPLAIN.  */
15997
15998 static int
15999 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16000 {
16001   if (INTEGRAL_TYPE_P (type))
16002     return 0;
16003   else if (POINTER_TYPE_P (type))
16004     return 0;
16005   else if (TYPE_PTR_TO_MEMBER_P (type))
16006     return 0;
16007   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16008     return 0;
16009   else if (TREE_CODE (type) == TYPENAME_TYPE)
16010     return 0;
16011
16012   if (complain & tf_error)
16013     error ("%q#T is not a valid type for a template constant parameter", type);
16014   return 1;
16015 }
16016
16017 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16018    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16019
16020 static bool
16021 dependent_type_p_r (tree type)
16022 {
16023   tree scope;
16024
16025   /* [temp.dep.type]
16026
16027      A type is dependent if it is:
16028
16029      -- a template parameter. Template template parameters are types
16030         for us (since TYPE_P holds true for them) so we handle
16031         them here.  */
16032   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16033       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16034     return true;
16035   /* -- a qualified-id with a nested-name-specifier which contains a
16036         class-name that names a dependent type or whose unqualified-id
16037         names a dependent type.  */
16038   if (TREE_CODE (type) == TYPENAME_TYPE)
16039     return true;
16040   /* -- a cv-qualified type where the cv-unqualified type is
16041         dependent.  */
16042   type = TYPE_MAIN_VARIANT (type);
16043   /* -- a compound type constructed from any dependent type.  */
16044   if (TYPE_PTR_TO_MEMBER_P (type))
16045     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16046             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16047                                            (type)));
16048   else if (TREE_CODE (type) == POINTER_TYPE
16049            || TREE_CODE (type) == REFERENCE_TYPE)
16050     return dependent_type_p (TREE_TYPE (type));
16051   else if (TREE_CODE (type) == FUNCTION_TYPE
16052            || TREE_CODE (type) == METHOD_TYPE)
16053     {
16054       tree arg_type;
16055
16056       if (dependent_type_p (TREE_TYPE (type)))
16057         return true;
16058       for (arg_type = TYPE_ARG_TYPES (type);
16059            arg_type;
16060            arg_type = TREE_CHAIN (arg_type))
16061         if (dependent_type_p (TREE_VALUE (arg_type)))
16062           return true;
16063       return false;
16064     }
16065   /* -- an array type constructed from any dependent type or whose
16066         size is specified by a constant expression that is
16067         value-dependent.  */
16068   if (TREE_CODE (type) == ARRAY_TYPE)
16069     {
16070       if (TYPE_DOMAIN (type)
16071           && dependent_type_p (TYPE_DOMAIN (type)))
16072         return true;
16073       return dependent_type_p (TREE_TYPE (type));
16074     }
16075   else if (TREE_CODE (type) == INTEGER_TYPE
16076            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16077     {
16078       /* If this is the TYPE_DOMAIN of an array type, consider it
16079          dependent.  We already checked for value-dependence in
16080          compute_array_index_type.  */
16081       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16082     }
16083
16084   /* -- a template-id in which either the template name is a template
16085      parameter ...  */
16086   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16087     return true;
16088   /* ... or any of the template arguments is a dependent type or
16089         an expression that is type-dependent or value-dependent.  */
16090   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16091            && (any_dependent_template_arguments_p
16092                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16093     return true;
16094
16095   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16096      argument of the `typeof' expression is not type-dependent, then
16097      it should already been have resolved.  */
16098   if (TREE_CODE (type) == TYPEOF_TYPE
16099       || TREE_CODE (type) == DECLTYPE_TYPE)
16100     return true;
16101
16102   /* A template argument pack is dependent if any of its packed
16103      arguments are.  */
16104   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16105     {
16106       tree args = ARGUMENT_PACK_ARGS (type);
16107       int i, len = TREE_VEC_LENGTH (args);
16108       for (i = 0; i < len; ++i)
16109         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16110           return true;
16111     }
16112
16113   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16114      be template parameters.  */
16115   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16116     return true;
16117
16118   /* The standard does not specifically mention types that are local
16119      to template functions or local classes, but they should be
16120      considered dependent too.  For example:
16121
16122        template <int I> void f() {
16123          enum E { a = I };
16124          S<sizeof (E)> s;
16125        }
16126
16127      The size of `E' cannot be known until the value of `I' has been
16128      determined.  Therefore, `E' must be considered dependent.  */
16129   scope = TYPE_CONTEXT (type);
16130   if (scope && TYPE_P (scope))
16131     return dependent_type_p (scope);
16132   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16133     return type_dependent_expression_p (scope);
16134
16135   /* Other types are non-dependent.  */
16136   return false;
16137 }
16138
16139 /* Returns TRUE if TYPE is dependent, in the sense of
16140    [temp.dep.type].  */
16141
16142 bool
16143 dependent_type_p (tree type)
16144 {
16145   /* If there are no template parameters in scope, then there can't be
16146      any dependent types.  */
16147   if (!processing_template_decl)
16148     {
16149       /* If we are not processing a template, then nobody should be
16150          providing us with a dependent type.  */
16151       gcc_assert (type);
16152       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16153       return false;
16154     }
16155
16156   /* If the type is NULL, we have not computed a type for the entity
16157      in question; in that case, the type is dependent.  */
16158   if (!type)
16159     return true;
16160
16161   /* Erroneous types can be considered non-dependent.  */
16162   if (type == error_mark_node)
16163     return false;
16164
16165   /* If we have not already computed the appropriate value for TYPE,
16166      do so now.  */
16167   if (!TYPE_DEPENDENT_P_VALID (type))
16168     {
16169       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16170       TYPE_DEPENDENT_P_VALID (type) = 1;
16171     }
16172
16173   return TYPE_DEPENDENT_P (type);
16174 }
16175
16176 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16177    lookup.  In other words, a dependent type that is not the current
16178    instantiation.  */
16179
16180 bool
16181 dependent_scope_p (tree scope)
16182 {
16183   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16184           && !currently_open_class (scope));
16185 }
16186
16187 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16188
16189 static bool
16190 dependent_scope_ref_p (tree expression, bool criterion (tree))
16191 {
16192   tree scope;
16193   tree name;
16194
16195   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16196
16197   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16198     return true;
16199
16200   scope = TREE_OPERAND (expression, 0);
16201   name = TREE_OPERAND (expression, 1);
16202
16203   /* [temp.dep.expr]
16204
16205      An id-expression is type-dependent if it contains a
16206      nested-name-specifier that contains a class-name that names a
16207      dependent type.  */
16208   /* The suggested resolution to Core Issue 224 implies that if the
16209      qualifying type is the current class, then we must peek
16210      inside it.  */
16211   if (DECL_P (name)
16212       && currently_open_class (scope)
16213       && !criterion (name))
16214     return false;
16215   if (dependent_type_p (scope))
16216     return true;
16217
16218   return false;
16219 }
16220
16221 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16222    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16223    expression.  */
16224
16225 bool
16226 value_dependent_expression_p (tree expression)
16227 {
16228   if (!processing_template_decl)
16229     return false;
16230
16231   /* A name declared with a dependent type.  */
16232   if (DECL_P (expression) && type_dependent_expression_p (expression))
16233     return true;
16234
16235   switch (TREE_CODE (expression))
16236     {
16237     case IDENTIFIER_NODE:
16238       /* A name that has not been looked up -- must be dependent.  */
16239       return true;
16240
16241     case TEMPLATE_PARM_INDEX:
16242       /* A non-type template parm.  */
16243       return true;
16244
16245     case CONST_DECL:
16246       /* A non-type template parm.  */
16247       if (DECL_TEMPLATE_PARM_P (expression))
16248         return true;
16249       return value_dependent_expression_p (DECL_INITIAL (expression));
16250
16251     case VAR_DECL:
16252        /* A constant with integral or enumeration type and is initialized
16253           with an expression that is value-dependent.  */
16254       if (DECL_INITIAL (expression)
16255           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16256           && value_dependent_expression_p (DECL_INITIAL (expression)))
16257         return true;
16258       return false;
16259
16260     case DYNAMIC_CAST_EXPR:
16261     case STATIC_CAST_EXPR:
16262     case CONST_CAST_EXPR:
16263     case REINTERPRET_CAST_EXPR:
16264     case CAST_EXPR:
16265       /* These expressions are value-dependent if the type to which
16266          the cast occurs is dependent or the expression being casted
16267          is value-dependent.  */
16268       {
16269         tree type = TREE_TYPE (expression);
16270
16271         if (dependent_type_p (type))
16272           return true;
16273
16274         /* A functional cast has a list of operands.  */
16275         expression = TREE_OPERAND (expression, 0);
16276         if (!expression)
16277           {
16278             /* If there are no operands, it must be an expression such
16279                as "int()". This should not happen for aggregate types
16280                because it would form non-constant expressions.  */
16281             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16282
16283             return false;
16284           }
16285
16286         if (TREE_CODE (expression) == TREE_LIST)
16287           return any_value_dependent_elements_p (expression);
16288
16289         return value_dependent_expression_p (expression);
16290       }
16291
16292     case SIZEOF_EXPR:
16293     case ALIGNOF_EXPR:
16294       /* A `sizeof' expression is value-dependent if the operand is
16295          type-dependent or is a pack expansion.  */
16296       expression = TREE_OPERAND (expression, 0);
16297       if (PACK_EXPANSION_P (expression))
16298         return true;
16299       else if (TYPE_P (expression))
16300         return dependent_type_p (expression);
16301       return type_dependent_expression_p (expression);
16302
16303     case SCOPE_REF:
16304       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16305
16306     case COMPONENT_REF:
16307       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16308               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16309
16310     case CALL_EXPR:
16311       /* A CALL_EXPR may appear in a constant expression if it is a
16312          call to a builtin function, e.g., __builtin_constant_p.  All
16313          such calls are value-dependent.  */
16314       return true;
16315
16316     case NONTYPE_ARGUMENT_PACK:
16317       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16318          is value-dependent.  */
16319       {
16320         tree values = ARGUMENT_PACK_ARGS (expression);
16321         int i, len = TREE_VEC_LENGTH (values);
16322         
16323         for (i = 0; i < len; ++i)
16324           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16325             return true;
16326         
16327         return false;
16328       }
16329
16330     case TRAIT_EXPR:
16331       {
16332         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16333         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16334                 || (type2 ? dependent_type_p (type2) : false));
16335       }
16336
16337     case MODOP_EXPR:
16338       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16339               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16340
16341     default:
16342       /* A constant expression is value-dependent if any subexpression is
16343          value-dependent.  */
16344       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16345         {
16346         case tcc_reference:
16347         case tcc_unary:
16348           return (value_dependent_expression_p
16349                   (TREE_OPERAND (expression, 0)));
16350
16351         case tcc_comparison:
16352         case tcc_binary:
16353           return ((value_dependent_expression_p
16354                    (TREE_OPERAND (expression, 0)))
16355                   || (value_dependent_expression_p
16356                       (TREE_OPERAND (expression, 1))));
16357
16358         case tcc_expression:
16359         case tcc_vl_exp:
16360           {
16361             int i;
16362             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16363               /* In some cases, some of the operands may be missing.
16364                  (For example, in the case of PREDECREMENT_EXPR, the
16365                  amount to increment by may be missing.)  That doesn't
16366                  make the expression dependent.  */
16367               if (TREE_OPERAND (expression, i)
16368                   && (value_dependent_expression_p
16369                       (TREE_OPERAND (expression, i))))
16370                 return true;
16371             return false;
16372           }
16373
16374         default:
16375           break;
16376         }
16377     }
16378
16379   /* The expression is not value-dependent.  */
16380   return false;
16381 }
16382
16383 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16384    [temp.dep.expr].  */
16385
16386 bool
16387 type_dependent_expression_p (tree expression)
16388 {
16389   if (!processing_template_decl)
16390     return false;
16391
16392   if (expression == error_mark_node)
16393     return false;
16394
16395   /* An unresolved name is always dependent.  */
16396   if (TREE_CODE (expression) == IDENTIFIER_NODE
16397       || TREE_CODE (expression) == USING_DECL)
16398     return true;
16399
16400   /* Some expression forms are never type-dependent.  */
16401   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16402       || TREE_CODE (expression) == SIZEOF_EXPR
16403       || TREE_CODE (expression) == ALIGNOF_EXPR
16404       || TREE_CODE (expression) == TRAIT_EXPR
16405       || TREE_CODE (expression) == TYPEID_EXPR
16406       || TREE_CODE (expression) == DELETE_EXPR
16407       || TREE_CODE (expression) == VEC_DELETE_EXPR
16408       || TREE_CODE (expression) == THROW_EXPR)
16409     return false;
16410
16411   /* The types of these expressions depends only on the type to which
16412      the cast occurs.  */
16413   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16414       || TREE_CODE (expression) == STATIC_CAST_EXPR
16415       || TREE_CODE (expression) == CONST_CAST_EXPR
16416       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16417       || TREE_CODE (expression) == CAST_EXPR)
16418     return dependent_type_p (TREE_TYPE (expression));
16419
16420   /* The types of these expressions depends only on the type created
16421      by the expression.  */
16422   if (TREE_CODE (expression) == NEW_EXPR
16423       || TREE_CODE (expression) == VEC_NEW_EXPR)
16424     {
16425       /* For NEW_EXPR tree nodes created inside a template, either
16426          the object type itself or a TREE_LIST may appear as the
16427          operand 1.  */
16428       tree type = TREE_OPERAND (expression, 1);
16429       if (TREE_CODE (type) == TREE_LIST)
16430         /* This is an array type.  We need to check array dimensions
16431            as well.  */
16432         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16433                || value_dependent_expression_p
16434                     (TREE_OPERAND (TREE_VALUE (type), 1));
16435       else
16436         return dependent_type_p (type);
16437     }
16438
16439   if (TREE_CODE (expression) == SCOPE_REF
16440       && dependent_scope_ref_p (expression,
16441                                 type_dependent_expression_p))
16442     return true;
16443
16444   if (TREE_CODE (expression) == FUNCTION_DECL
16445       && DECL_LANG_SPECIFIC (expression)
16446       && DECL_TEMPLATE_INFO (expression)
16447       && (any_dependent_template_arguments_p
16448           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16449     return true;
16450
16451   if (TREE_CODE (expression) == TEMPLATE_DECL
16452       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16453     return false;
16454
16455   if (TREE_CODE (expression) == STMT_EXPR)
16456     expression = stmt_expr_value_expr (expression);
16457
16458   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16459     {
16460       tree elt;
16461       unsigned i;
16462
16463       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16464         {
16465           if (type_dependent_expression_p (elt))
16466             return true;
16467         }
16468       return false;
16469     }
16470
16471   if (TREE_TYPE (expression) == unknown_type_node)
16472     {
16473       if (TREE_CODE (expression) == ADDR_EXPR)
16474         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16475       if (TREE_CODE (expression) == COMPONENT_REF
16476           || TREE_CODE (expression) == OFFSET_REF)
16477         {
16478           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16479             return true;
16480           expression = TREE_OPERAND (expression, 1);
16481           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16482             return false;
16483         }
16484       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16485       if (TREE_CODE (expression) == SCOPE_REF)
16486         return false;
16487
16488       if (TREE_CODE (expression) == BASELINK)
16489         expression = BASELINK_FUNCTIONS (expression);
16490
16491       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16492         {
16493           if (any_dependent_template_arguments_p
16494               (TREE_OPERAND (expression, 1)))
16495             return true;
16496           expression = TREE_OPERAND (expression, 0);
16497         }
16498       gcc_assert (TREE_CODE (expression) == OVERLOAD
16499                   || TREE_CODE (expression) == FUNCTION_DECL);
16500
16501       while (expression)
16502         {
16503           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16504             return true;
16505           expression = OVL_NEXT (expression);
16506         }
16507       return false;
16508     }
16509
16510   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16511
16512   return (dependent_type_p (TREE_TYPE (expression)));
16513 }
16514
16515 /* Like type_dependent_expression_p, but it also works while not processing
16516    a template definition, i.e. during substitution or mangling.  */
16517
16518 bool
16519 type_dependent_expression_p_push (tree expr)
16520 {
16521   bool b;
16522   ++processing_template_decl;
16523   b = type_dependent_expression_p (expr);
16524   --processing_template_decl;
16525   return b;
16526 }
16527
16528 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16529    contains a type-dependent expression.  */
16530
16531 bool
16532 any_type_dependent_arguments_p (const_tree args)
16533 {
16534   while (args)
16535     {
16536       tree arg = TREE_VALUE (args);
16537
16538       if (type_dependent_expression_p (arg))
16539         return true;
16540       args = TREE_CHAIN (args);
16541     }
16542   return false;
16543 }
16544
16545 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16546    expressions) contains any value-dependent expressions.  */
16547
16548 bool
16549 any_value_dependent_elements_p (const_tree list)
16550 {
16551   for (; list; list = TREE_CHAIN (list))
16552     if (value_dependent_expression_p (TREE_VALUE (list)))
16553       return true;
16554
16555   return false;
16556 }
16557
16558 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16559
16560 bool
16561 dependent_template_arg_p (tree arg)
16562 {
16563   if (!processing_template_decl)
16564     return false;
16565
16566   if (TREE_CODE (arg) == TEMPLATE_DECL
16567       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16568     return dependent_template_p (arg);
16569   else if (ARGUMENT_PACK_P (arg))
16570     {
16571       tree args = ARGUMENT_PACK_ARGS (arg);
16572       int i, len = TREE_VEC_LENGTH (args);
16573       for (i = 0; i < len; ++i)
16574         {
16575           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16576             return true;
16577         }
16578
16579       return false;
16580     }
16581   else if (TYPE_P (arg))
16582     return dependent_type_p (arg);
16583   else
16584     return (type_dependent_expression_p (arg)
16585             || value_dependent_expression_p (arg));
16586 }
16587
16588 /* Returns true if ARGS (a collection of template arguments) contains
16589    any types that require structural equality testing.  */
16590
16591 bool
16592 any_template_arguments_need_structural_equality_p (tree args)
16593 {
16594   int i;
16595   int j;
16596
16597   if (!args)
16598     return false;
16599   if (args == error_mark_node)
16600     return true;
16601
16602   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16603     {
16604       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16605       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16606         {
16607           tree arg = TREE_VEC_ELT (level, j);
16608           tree packed_args = NULL_TREE;
16609           int k, len = 1;
16610
16611           if (ARGUMENT_PACK_P (arg))
16612             {
16613               /* Look inside the argument pack.  */
16614               packed_args = ARGUMENT_PACK_ARGS (arg);
16615               len = TREE_VEC_LENGTH (packed_args);
16616             }
16617
16618           for (k = 0; k < len; ++k)
16619             {
16620               if (packed_args)
16621                 arg = TREE_VEC_ELT (packed_args, k);
16622
16623               if (error_operand_p (arg))
16624                 return true;
16625               else if (TREE_CODE (arg) == TEMPLATE_DECL
16626                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16627                 continue;
16628               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16629                 return true;
16630               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16631                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16632                 return true;
16633             }
16634         }
16635     }
16636
16637   return false;
16638 }
16639
16640 /* Returns true if ARGS (a collection of template arguments) contains
16641    any dependent arguments.  */
16642
16643 bool
16644 any_dependent_template_arguments_p (const_tree args)
16645 {
16646   int i;
16647   int j;
16648
16649   if (!args)
16650     return false;
16651   if (args == error_mark_node)
16652     return true;
16653
16654   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16655     {
16656       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16657       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16658         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16659           return true;
16660     }
16661
16662   return false;
16663 }
16664
16665 /* Returns TRUE if the template TMPL is dependent.  */
16666
16667 bool
16668 dependent_template_p (tree tmpl)
16669 {
16670   if (TREE_CODE (tmpl) == OVERLOAD)
16671     {
16672       while (tmpl)
16673         {
16674           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16675             return true;
16676           tmpl = OVL_CHAIN (tmpl);
16677         }
16678       return false;
16679     }
16680
16681   /* Template template parameters are dependent.  */
16682   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16683       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16684     return true;
16685   /* So are names that have not been looked up.  */
16686   if (TREE_CODE (tmpl) == SCOPE_REF
16687       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16688     return true;
16689   /* So are member templates of dependent classes.  */
16690   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16691     return dependent_type_p (DECL_CONTEXT (tmpl));
16692   return false;
16693 }
16694
16695 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16696
16697 bool
16698 dependent_template_id_p (tree tmpl, tree args)
16699 {
16700   return (dependent_template_p (tmpl)
16701           || any_dependent_template_arguments_p (args));
16702 }
16703
16704 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16705    is dependent.  */
16706
16707 bool
16708 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16709 {
16710   int i;
16711
16712   if (!processing_template_decl)
16713     return false;
16714
16715   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16716     {
16717       tree decl = TREE_VEC_ELT (declv, i);
16718       tree init = TREE_VEC_ELT (initv, i);
16719       tree cond = TREE_VEC_ELT (condv, i);
16720       tree incr = TREE_VEC_ELT (incrv, i);
16721
16722       if (type_dependent_expression_p (decl))
16723         return true;
16724
16725       if (init && type_dependent_expression_p (init))
16726         return true;
16727
16728       if (type_dependent_expression_p (cond))
16729         return true;
16730
16731       if (COMPARISON_CLASS_P (cond)
16732           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16733               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16734         return true;
16735
16736       if (TREE_CODE (incr) == MODOP_EXPR)
16737         {
16738           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16739               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16740             return true;
16741         }
16742       else if (type_dependent_expression_p (incr))
16743         return true;
16744       else if (TREE_CODE (incr) == MODIFY_EXPR)
16745         {
16746           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16747             return true;
16748           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16749             {
16750               tree t = TREE_OPERAND (incr, 1);
16751               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16752                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16753                 return true;
16754             }
16755         }
16756     }
16757
16758   return false;
16759 }
16760
16761 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16762    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16763    no such TYPE can be found.  Note that this function peers inside
16764    uninstantiated templates and therefore should be used only in
16765    extremely limited situations.  ONLY_CURRENT_P restricts this
16766    peering to the currently open classes hierarchy (which is required
16767    when comparing types).  */
16768
16769 tree
16770 resolve_typename_type (tree type, bool only_current_p)
16771 {
16772   tree scope;
16773   tree name;
16774   tree decl;
16775   int quals;
16776   tree pushed_scope;
16777   tree result;
16778
16779   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16780
16781   scope = TYPE_CONTEXT (type);
16782   name = TYPE_IDENTIFIER (type);
16783
16784   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16785      it first before we can figure out what NAME refers to.  */
16786   if (TREE_CODE (scope) == TYPENAME_TYPE)
16787     scope = resolve_typename_type (scope, only_current_p);
16788   /* If we don't know what SCOPE refers to, then we cannot resolve the
16789      TYPENAME_TYPE.  */
16790   if (TREE_CODE (scope) == TYPENAME_TYPE)
16791     return type;
16792   /* If the SCOPE is a template type parameter, we have no way of
16793      resolving the name.  */
16794   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16795     return type;
16796   /* If the SCOPE is not the current instantiation, there's no reason
16797      to look inside it.  */
16798   if (only_current_p && !currently_open_class (scope))
16799     return type;
16800   /* If SCOPE isn't the template itself, it will not have a valid
16801      TYPE_FIELDS list.  */
16802   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16803     /* scope is either the template itself or a compatible instantiation
16804        like X<T>, so look up the name in the original template.  */
16805     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16806   else
16807     /* scope is a partial instantiation, so we can't do the lookup or we
16808        will lose the template arguments.  */
16809     return type;
16810   /* Enter the SCOPE so that name lookup will be resolved as if we
16811      were in the class definition.  In particular, SCOPE will no
16812      longer be considered a dependent type.  */
16813   pushed_scope = push_scope (scope);
16814   /* Look up the declaration.  */
16815   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16816
16817   result = NULL_TREE;
16818   
16819   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16820      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16821   if (!decl)
16822     /*nop*/;
16823   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16824            && TREE_CODE (decl) == TYPE_DECL)
16825     {
16826       result = TREE_TYPE (decl);
16827       if (result == error_mark_node)
16828         result = NULL_TREE;
16829     }
16830   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16831            && DECL_CLASS_TEMPLATE_P (decl))
16832     {
16833       tree tmpl;
16834       tree args;
16835       /* Obtain the template and the arguments.  */
16836       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16837       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16838       /* Instantiate the template.  */
16839       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16840                                       /*entering_scope=*/0,
16841                                       tf_error | tf_user);
16842       if (result == error_mark_node)
16843         result = NULL_TREE;
16844     }
16845   
16846   /* Leave the SCOPE.  */
16847   if (pushed_scope)
16848     pop_scope (pushed_scope);
16849
16850   /* If we failed to resolve it, return the original typename.  */
16851   if (!result)
16852     return type;
16853   
16854   /* If lookup found a typename type, resolve that too.  */
16855   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16856     {
16857       /* Ill-formed programs can cause infinite recursion here, so we
16858          must catch that.  */
16859       TYPENAME_IS_RESOLVING_P (type) = 1;
16860       result = resolve_typename_type (result, only_current_p);
16861       TYPENAME_IS_RESOLVING_P (type) = 0;
16862     }
16863   
16864   /* Qualify the resulting type.  */
16865   quals = cp_type_quals (type);
16866   if (quals)
16867     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16868
16869   return result;
16870 }
16871
16872 /* EXPR is an expression which is not type-dependent.  Return a proxy
16873    for EXPR that can be used to compute the types of larger
16874    expressions containing EXPR.  */
16875
16876 tree
16877 build_non_dependent_expr (tree expr)
16878 {
16879   tree inner_expr;
16880
16881   /* Preserve null pointer constants so that the type of things like
16882      "p == 0" where "p" is a pointer can be determined.  */
16883   if (null_ptr_cst_p (expr))
16884     return expr;
16885   /* Preserve OVERLOADs; the functions must be available to resolve
16886      types.  */
16887   inner_expr = expr;
16888   if (TREE_CODE (inner_expr) == STMT_EXPR)
16889     inner_expr = stmt_expr_value_expr (inner_expr);
16890   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16891     inner_expr = TREE_OPERAND (inner_expr, 0);
16892   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16893     inner_expr = TREE_OPERAND (inner_expr, 1);
16894   if (is_overloaded_fn (inner_expr)
16895       || TREE_CODE (inner_expr) == OFFSET_REF)
16896     return expr;
16897   /* There is no need to return a proxy for a variable.  */
16898   if (TREE_CODE (expr) == VAR_DECL)
16899     return expr;
16900   /* Preserve string constants; conversions from string constants to
16901      "char *" are allowed, even though normally a "const char *"
16902      cannot be used to initialize a "char *".  */
16903   if (TREE_CODE (expr) == STRING_CST)
16904     return expr;
16905   /* Preserve arithmetic constants, as an optimization -- there is no
16906      reason to create a new node.  */
16907   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16908     return expr;
16909   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16910      There is at least one place where we want to know that a
16911      particular expression is a throw-expression: when checking a ?:
16912      expression, there are special rules if the second or third
16913      argument is a throw-expression.  */
16914   if (TREE_CODE (expr) == THROW_EXPR)
16915     return expr;
16916
16917   if (TREE_CODE (expr) == COND_EXPR)
16918     return build3 (COND_EXPR,
16919                    TREE_TYPE (expr),
16920                    TREE_OPERAND (expr, 0),
16921                    (TREE_OPERAND (expr, 1)
16922                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16923                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16924                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16925   if (TREE_CODE (expr) == COMPOUND_EXPR
16926       && !COMPOUND_EXPR_OVERLOADED (expr))
16927     return build2 (COMPOUND_EXPR,
16928                    TREE_TYPE (expr),
16929                    TREE_OPERAND (expr, 0),
16930                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16931
16932   /* If the type is unknown, it can't really be non-dependent */
16933   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16934
16935   /* Otherwise, build a NON_DEPENDENT_EXPR.
16936
16937      REFERENCE_TYPEs are not stripped for expressions in templates
16938      because doing so would play havoc with mangling.  Consider, for
16939      example:
16940
16941        template <typename T> void f<T& g>() { g(); }
16942
16943      In the body of "f", the expression for "g" will have
16944      REFERENCE_TYPE, even though the standard says that it should
16945      not.  The reason is that we must preserve the syntactic form of
16946      the expression so that mangling (say) "f<g>" inside the body of
16947      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16948      stripped here.  */
16949   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16950 }
16951
16952 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16953    Return a new TREE_LIST with the various arguments replaced with
16954    equivalent non-dependent expressions.  */
16955
16956 tree
16957 build_non_dependent_args (tree args)
16958 {
16959   tree a;
16960   tree new_args;
16961
16962   new_args = NULL_TREE;
16963   for (a = args; a; a = TREE_CHAIN (a))
16964     new_args = tree_cons (NULL_TREE,
16965                           build_non_dependent_expr (TREE_VALUE (a)),
16966                           new_args);
16967   return nreverse (new_args);
16968 }
16969
16970 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
16971    with a level one deeper than the actual template parms.  */
16972
16973 tree
16974 make_auto (void)
16975 {
16976   tree au;
16977
16978   /* ??? Is it worth caching this for multiple autos at the same level?  */
16979   au = cxx_make_type (TEMPLATE_TYPE_PARM);
16980   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
16981   TYPE_STUB_DECL (au) = TYPE_NAME (au);
16982   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
16983     (0, processing_template_decl + 1, processing_template_decl + 1,
16984      TYPE_NAME (au), NULL_TREE);
16985   TYPE_CANONICAL (au) = canonical_type_parameter (au);
16986   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
16987   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
16988
16989   return au;
16990 }
16991
16992 /* Replace auto in TYPE with std::initializer_list<auto>.  */
16993
16994 static tree
16995 listify_autos (tree type, tree auto_node)
16996 {
16997   tree std_init_list = namespace_binding
16998     (get_identifier ("initializer_list"), std_node);
16999   tree argvec;
17000   tree init_auto;
17001   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17002     {    
17003       error ("deducing auto from brace-enclosed initializer list requires "
17004              "#include <initializer_list>");
17005       return error_mark_node;
17006     }
17007   argvec = make_tree_vec (1);
17008   TREE_VEC_ELT (argvec, 0) = auto_node;
17009   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
17010                                      NULL_TREE, 0, tf_warning_or_error);
17011
17012   TREE_VEC_ELT (argvec, 0) = init_auto;
17013   if (processing_template_decl)
17014     argvec = add_to_template_args (current_template_args (), argvec);
17015   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17016 }
17017
17018 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17019    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17020
17021 tree
17022 do_auto_deduction (tree type, tree init, tree auto_node)
17023 {
17024   tree parms, args, tparms, targs;
17025   int val;
17026
17027   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17028      with either a new invented type template parameter U or, if the
17029      initializer is a braced-init-list (8.5.4), with
17030      std::initializer_list<U>.  */
17031   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17032     type = listify_autos (type, auto_node);
17033
17034   parms = build_tree_list (NULL_TREE, type);
17035   args = build_tree_list (NULL_TREE, init);
17036   tparms = make_tree_vec (1);
17037   targs = make_tree_vec (1);
17038   TREE_VEC_ELT (tparms, 0)
17039     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17040   val = type_unification_real (tparms, targs, parms, args, 0,
17041                                DEDUCE_CALL, LOOKUP_NORMAL);
17042   if (val > 0)
17043     {
17044       error ("unable to deduce %qT from %qE", type, init);
17045       return error_mark_node;
17046     }
17047
17048   if (processing_template_decl)
17049     targs = add_to_template_args (current_template_args (), targs);
17050   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17051 }
17052
17053 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17054    result.  */
17055
17056 tree
17057 splice_late_return_type (tree type, tree late_return_type)
17058 {
17059   tree argvec;
17060
17061   if (late_return_type == NULL_TREE)
17062     return type;
17063   argvec = make_tree_vec (1);
17064   TREE_VEC_ELT (argvec, 0) = late_return_type;
17065   if (processing_template_decl)
17066     argvec = add_to_template_args (current_template_args (), argvec);
17067   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17068 }
17069
17070 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17071
17072 bool
17073 is_auto (const_tree type)
17074 {
17075   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17076       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17077     return true;
17078   else
17079     return false;
17080 }
17081
17082 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17083    appear as a type-specifier for the declaration in question, we don't
17084    have to look through the whole type.  */
17085
17086 tree
17087 type_uses_auto (tree type)
17088 {
17089   enum tree_code code;
17090   if (is_auto (type))
17091     return type;
17092
17093   code = TREE_CODE (type);
17094
17095   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17096       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17097       || code == METHOD_TYPE || code == ARRAY_TYPE)
17098     return type_uses_auto (TREE_TYPE (type));
17099
17100   if (TYPE_PTRMEMFUNC_P (type))
17101     return type_uses_auto (TREE_TYPE (TREE_TYPE
17102                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17103
17104   return NULL_TREE;
17105 }
17106
17107 #include "gt-cp-pt.h"