Merge branch 'vendor/GCC50'
[dragonfly.git] / contrib / gcc-5.0 / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2015 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* Known bugs or deficiencies include:
23
24      all methods must be provided in header files; can't use a source
25      file that contains only the method templates and "just win".  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "hash-set.h"
32 #include "machmode.h"
33 #include "vec.h"
34 #include "double-int.h"
35 #include "input.h"
36 #include "alias.h"
37 #include "symtab.h"
38 #include "wide-int.h"
39 #include "inchash.h"
40 #include "tree.h"
41 #include "stringpool.h"
42 #include "varasm.h"
43 #include "attribs.h"
44 #include "stor-layout.h"
45 #include "intl.h"
46 #include "flags.h"
47 #include "cp-tree.h"
48 #include "c-family/c-common.h"
49 #include "c-family/c-objc.h"
50 #include "cp-objcp-common.h"
51 #include "tree-inline.h"
52 #include "decl.h"
53 #include "toplev.h"
54 #include "timevar.h"
55 #include "tree-iterator.h"
56 #include "type-utils.h"
57 #include "gimplify.h"
58
59 /* The type of functions taking a tree, and some additional data, and
60    returning an int.  */
61 typedef int (*tree_fn_t) (tree, void*);
62
63 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
64    instantiations have been deferred, either because their definitions
65    were not yet available, or because we were putting off doing the work.  */
66 struct GTY ((chain_next ("%h.next"))) pending_template {
67   struct pending_template *next;
68   struct tinst_level *tinst;
69 };
70
71 static GTY(()) struct pending_template *pending_templates;
72 static GTY(()) struct pending_template *last_pending_template;
73
74 int processing_template_parmlist;
75 static int template_header_count;
76
77 static GTY(()) tree saved_trees;
78 static vec<int> inline_parm_levels;
79
80 static GTY(()) struct tinst_level *current_tinst_level;
81
82 static GTY(()) tree saved_access_scope;
83
84 /* Live only within one (recursive) call to tsubst_expr.  We use
85    this to pass the statement expression node from the STMT_EXPR
86    to the EXPR_STMT that is its result.  */
87 static tree cur_stmt_expr;
88
89 /* True if we've recursed into fn_type_unification too many times.  */
90 static bool excessive_deduction_depth;
91
92 struct GTY((for_user)) spec_entry
93 {
94   tree tmpl;
95   tree args;
96   tree spec;
97 };
98
99 struct spec_hasher : ggc_hasher<spec_entry *>
100 {
101   static hashval_t hash (spec_entry *);
102   static bool equal (spec_entry *, spec_entry *);
103 };
104
105 static GTY (()) hash_table<spec_hasher> *decl_specializations;
106
107 static GTY (()) hash_table<spec_hasher> *type_specializations;
108
109 /* Contains canonical template parameter types. The vector is indexed by
110    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
111    TREE_LIST, whose TREE_VALUEs contain the canonical template
112    parameters of various types and levels.  */
113 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
114
115 #define UNIFY_ALLOW_NONE 0
116 #define UNIFY_ALLOW_MORE_CV_QUAL 1
117 #define UNIFY_ALLOW_LESS_CV_QUAL 2
118 #define UNIFY_ALLOW_DERIVED 4
119 #define UNIFY_ALLOW_INTEGER 8
120 #define UNIFY_ALLOW_OUTER_LEVEL 16
121 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
122 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
123
124 enum template_base_result {
125   tbr_incomplete_type,
126   tbr_ambiguous_baseclass,
127   tbr_success
128 };
129
130 static void push_access_scope (tree);
131 static void pop_access_scope (tree);
132 static bool resolve_overloaded_unification (tree, tree, tree, tree,
133                                             unification_kind_t, int,
134                                             bool);
135 static int try_one_overload (tree, tree, tree, tree, tree,
136                              unification_kind_t, int, bool, bool);
137 static int unify (tree, tree, tree, tree, int, bool);
138 static void add_pending_template (tree);
139 static tree reopen_tinst_level (struct tinst_level *);
140 static tree tsubst_initializer_list (tree, tree);
141 static tree get_partial_spec_bindings (tree, tree, tree, tree);
142 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
143                                    bool, bool);
144 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
145                                               bool, bool);
146 static void tsubst_enum (tree, tree, tree);
147 static tree add_to_template_args (tree, tree);
148 static tree add_outermost_template_args (tree, tree);
149 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
150 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
151                                              tree);
152 static int type_unification_real (tree, tree, tree, const tree *,
153                                   unsigned int, int, unification_kind_t, int,
154                                   vec<deferred_access_check, va_gc> **,
155                                   bool);
156 static void note_template_header (int);
157 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
158 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
159 static tree convert_template_argument (tree, tree, tree,
160                                        tsubst_flags_t, int, tree);
161 static int for_each_template_parm (tree, tree_fn_t, void*,
162                                    hash_set<tree> *, bool);
163 static tree expand_template_argument_pack (tree);
164 static tree build_template_parm_index (int, int, int, tree, tree);
165 static bool inline_needs_template_parms (tree, bool);
166 static void push_inline_template_parms_recursive (tree, int);
167 static tree retrieve_local_specialization (tree);
168 static void register_local_specialization (tree, tree);
169 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
170 static int mark_template_parm (tree, void *);
171 static int template_parm_this_level_p (tree, void *);
172 static tree tsubst_friend_function (tree, tree);
173 static tree tsubst_friend_class (tree, tree);
174 static int can_complete_type_without_circularity (tree);
175 static tree get_bindings (tree, tree, tree, bool);
176 static int template_decl_level (tree);
177 static int check_cv_quals_for_unify (int, tree, tree);
178 static void template_parm_level_and_index (tree, int*, int*);
179 static int unify_pack_expansion (tree, tree, tree,
180                                  tree, unification_kind_t, bool, bool);
181 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
182 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
183 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
184 static void regenerate_decl_from_template (tree, tree);
185 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
186 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
187 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
189 static bool check_specialization_scope (void);
190 static tree process_partial_specialization (tree);
191 static void set_current_access_from_decl (tree);
192 static enum template_base_result get_template_base (tree, tree, tree, tree,
193                                                     bool , tree *);
194 static tree try_class_unification (tree, tree, tree, tree, bool);
195 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
196                                            tree, tree);
197 static bool template_template_parm_bindings_ok_p (tree, tree);
198 static int template_args_equal (tree, tree);
199 static void tsubst_default_arguments (tree, tsubst_flags_t);
200 static tree for_each_template_parm_r (tree *, int *, void *);
201 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
202 static void copy_default_args_to_explicit_spec (tree);
203 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
204 static bool dependent_template_arg_p (tree);
205 static bool any_template_arguments_need_structural_equality_p (tree);
206 static bool dependent_type_p_r (tree);
207 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
208 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
209 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
210 static tree tsubst_decl (tree, tree, tsubst_flags_t);
211 static void perform_typedefs_access_check (tree tmpl, tree targs);
212 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
213                                                         location_t);
214 static tree listify (tree);
215 static tree listify_autos (tree, tree);
216 static tree template_parm_to_arg (tree t);
217 static tree current_template_args (void);
218 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
219 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
220
221 /* Make the current scope suitable for access checking when we are
222    processing T.  T can be FUNCTION_DECL for instantiated function
223    template, VAR_DECL for static member variable, or TYPE_DECL for
224    alias template (needed by instantiate_decl).  */
225
226 static void
227 push_access_scope (tree t)
228 {
229   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
230               || TREE_CODE (t) == TYPE_DECL);
231
232   if (DECL_FRIEND_CONTEXT (t))
233     push_nested_class (DECL_FRIEND_CONTEXT (t));
234   else if (DECL_CLASS_SCOPE_P (t))
235     push_nested_class (DECL_CONTEXT (t));
236   else
237     push_to_top_level ();
238
239   if (TREE_CODE (t) == FUNCTION_DECL)
240     {
241       saved_access_scope = tree_cons
242         (NULL_TREE, current_function_decl, saved_access_scope);
243       current_function_decl = t;
244     }
245 }
246
247 /* Restore the scope set up by push_access_scope.  T is the node we
248    are processing.  */
249
250 static void
251 pop_access_scope (tree t)
252 {
253   if (TREE_CODE (t) == FUNCTION_DECL)
254     {
255       current_function_decl = TREE_VALUE (saved_access_scope);
256       saved_access_scope = TREE_CHAIN (saved_access_scope);
257     }
258
259   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
260     pop_nested_class ();
261   else
262     pop_from_top_level ();
263 }
264
265 /* Do any processing required when DECL (a member template
266    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
267    to DECL, unless it is a specialization, in which case the DECL
268    itself is returned.  */
269
270 tree
271 finish_member_template_decl (tree decl)
272 {
273   if (decl == error_mark_node)
274     return error_mark_node;
275
276   gcc_assert (DECL_P (decl));
277
278   if (TREE_CODE (decl) == TYPE_DECL)
279     {
280       tree type;
281
282       type = TREE_TYPE (decl);
283       if (type == error_mark_node)
284         return error_mark_node;
285       if (MAYBE_CLASS_TYPE_P (type)
286           && CLASSTYPE_TEMPLATE_INFO (type)
287           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
288         {
289           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
290           check_member_template (tmpl);
291           return tmpl;
292         }
293       return NULL_TREE;
294     }
295   else if (TREE_CODE (decl) == FIELD_DECL)
296     error ("data member %qD cannot be a member template", decl);
297   else if (DECL_TEMPLATE_INFO (decl))
298     {
299       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
300         {
301           check_member_template (DECL_TI_TEMPLATE (decl));
302           return DECL_TI_TEMPLATE (decl);
303         }
304       else
305         return decl;
306     }
307   else
308     error ("invalid member template declaration %qD", decl);
309
310   return error_mark_node;
311 }
312
313 /* Create a template info node.  */
314
315 tree
316 build_template_info (tree template_decl, tree template_args)
317 {
318   tree result = make_node (TEMPLATE_INFO);
319   TI_TEMPLATE (result) = template_decl;
320   TI_ARGS (result) = template_args;
321   return result;
322 }
323
324 /* Return the template info node corresponding to T, whatever T is.  */
325
326 tree
327 get_template_info (const_tree t)
328 {
329   tree tinfo = NULL_TREE;
330
331   if (!t || t == error_mark_node)
332     return NULL;
333
334   if (TREE_CODE (t) == NAMESPACE_DECL)
335     return NULL;
336
337   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
338     tinfo = DECL_TEMPLATE_INFO (t);
339
340   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
341     t = TREE_TYPE (t);
342
343   if (OVERLOAD_TYPE_P (t))
344     tinfo = TYPE_TEMPLATE_INFO (t);
345   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
346     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
347
348   return tinfo;
349 }
350
351 /* Returns the template nesting level of the indicated class TYPE.
352
353    For example, in:
354      template <class T>
355      struct A
356      {
357        template <class U>
358        struct B {};
359      };
360
361    A<T>::B<U> has depth two, while A<T> has depth one.
362    Both A<T>::B<int> and A<int>::B<U> have depth one, if
363    they are instantiations, not specializations.
364
365    This function is guaranteed to return 0 if passed NULL_TREE so
366    that, for example, `template_class_depth (current_class_type)' is
367    always safe.  */
368
369 int
370 template_class_depth (tree type)
371 {
372   int depth;
373
374   for (depth = 0;
375        type && TREE_CODE (type) != NAMESPACE_DECL;
376        type = (TREE_CODE (type) == FUNCTION_DECL)
377          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
378     {
379       tree tinfo = get_template_info (type);
380
381       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
382           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
383         ++depth;
384     }
385
386   return depth;
387 }
388
389 /* Subroutine of maybe_begin_member_template_processing.
390    Returns true if processing DECL needs us to push template parms.  */
391
392 static bool
393 inline_needs_template_parms (tree decl, bool nsdmi)
394 {
395   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
396     return false;
397
398   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
399           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
400 }
401
402 /* Subroutine of maybe_begin_member_template_processing.
403    Push the template parms in PARMS, starting from LEVELS steps into the
404    chain, and ending at the beginning, since template parms are listed
405    innermost first.  */
406
407 static void
408 push_inline_template_parms_recursive (tree parmlist, int levels)
409 {
410   tree parms = TREE_VALUE (parmlist);
411   int i;
412
413   if (levels > 1)
414     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
415
416   ++processing_template_decl;
417   current_template_parms
418     = tree_cons (size_int (processing_template_decl),
419                  parms, current_template_parms);
420   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
421
422   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
423                NULL);
424   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
425     {
426       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
427
428       if (error_operand_p (parm))
429         continue;
430
431       gcc_assert (DECL_P (parm));
432
433       switch (TREE_CODE (parm))
434         {
435         case TYPE_DECL:
436         case TEMPLATE_DECL:
437           pushdecl (parm);
438           break;
439
440         case PARM_DECL:
441           {
442             /* Make a CONST_DECL as is done in process_template_parm.
443                It is ugly that we recreate this here; the original
444                version built in process_template_parm is no longer
445                available.  */
446             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
447                                     CONST_DECL, DECL_NAME (parm),
448                                     TREE_TYPE (parm));
449             DECL_ARTIFICIAL (decl) = 1;
450             TREE_CONSTANT (decl) = 1;
451             TREE_READONLY (decl) = 1;
452             DECL_INITIAL (decl) = DECL_INITIAL (parm);
453             SET_DECL_TEMPLATE_PARM_P (decl);
454             pushdecl (decl);
455           }
456           break;
457
458         default:
459           gcc_unreachable ();
460         }
461     }
462 }
463
464 /* Restore the template parameter context for a member template, a
465    friend template defined in a class definition, or a non-template
466    member of template class.  */
467
468 void
469 maybe_begin_member_template_processing (tree decl)
470 {
471   tree parms;
472   int levels = 0;
473   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
474
475   if (nsdmi)
476     {
477       tree ctx = DECL_CONTEXT (decl);
478       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
479               /* Disregard full specializations (c++/60999).  */
480               && uses_template_parms (ctx)
481               ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
482     }
483
484   if (inline_needs_template_parms (decl, nsdmi))
485     {
486       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
487       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
488
489       if (DECL_TEMPLATE_SPECIALIZATION (decl))
490         {
491           --levels;
492           parms = TREE_CHAIN (parms);
493         }
494
495       push_inline_template_parms_recursive (parms, levels);
496     }
497
498   /* Remember how many levels of template parameters we pushed so that
499      we can pop them later.  */
500   inline_parm_levels.safe_push (levels);
501 }
502
503 /* Undo the effects of maybe_begin_member_template_processing.  */
504
505 void
506 maybe_end_member_template_processing (void)
507 {
508   int i;
509   int last;
510
511   if (inline_parm_levels.length () == 0)
512     return;
513
514   last = inline_parm_levels.pop ();
515   for (i = 0; i < last; ++i)
516     {
517       --processing_template_decl;
518       current_template_parms = TREE_CHAIN (current_template_parms);
519       poplevel (0, 0, 0);
520     }
521 }
522
523 /* Return a new template argument vector which contains all of ARGS,
524    but has as its innermost set of arguments the EXTRA_ARGS.  */
525
526 static tree
527 add_to_template_args (tree args, tree extra_args)
528 {
529   tree new_args;
530   int extra_depth;
531   int i;
532   int j;
533
534   if (args == NULL_TREE || extra_args == error_mark_node)
535     return extra_args;
536
537   extra_depth = TMPL_ARGS_DEPTH (extra_args);
538   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
539
540   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
541     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
542
543   for (j = 1; j <= extra_depth; ++j, ++i)
544     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
545
546   return new_args;
547 }
548
549 /* Like add_to_template_args, but only the outermost ARGS are added to
550    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
551    (EXTRA_ARGS) levels are added.  This function is used to combine
552    the template arguments from a partial instantiation with the
553    template arguments used to attain the full instantiation from the
554    partial instantiation.  */
555
556 static tree
557 add_outermost_template_args (tree args, tree extra_args)
558 {
559   tree new_args;
560
561   /* If there are more levels of EXTRA_ARGS than there are ARGS,
562      something very fishy is going on.  */
563   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
564
565   /* If *all* the new arguments will be the EXTRA_ARGS, just return
566      them.  */
567   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
568     return extra_args;
569
570   /* For the moment, we make ARGS look like it contains fewer levels.  */
571   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
572
573   new_args = add_to_template_args (args, extra_args);
574
575   /* Now, we restore ARGS to its full dimensions.  */
576   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
577
578   return new_args;
579 }
580
581 /* Return the N levels of innermost template arguments from the ARGS.  */
582
583 tree
584 get_innermost_template_args (tree args, int n)
585 {
586   tree new_args;
587   int extra_levels;
588   int i;
589
590   gcc_assert (n >= 0);
591
592   /* If N is 1, just return the innermost set of template arguments.  */
593   if (n == 1)
594     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
595
596   /* If we're not removing anything, just return the arguments we were
597      given.  */
598   extra_levels = TMPL_ARGS_DEPTH (args) - n;
599   gcc_assert (extra_levels >= 0);
600   if (extra_levels == 0)
601     return args;
602
603   /* Make a new set of arguments, not containing the outer arguments.  */
604   new_args = make_tree_vec (n);
605   for (i = 1; i <= n; ++i)
606     SET_TMPL_ARGS_LEVEL (new_args, i,
607                          TMPL_ARGS_LEVEL (args, i + extra_levels));
608
609   return new_args;
610 }
611
612 /* The inverse of get_innermost_template_args: Return all but the innermost
613    EXTRA_LEVELS levels of template arguments from the ARGS.  */
614
615 static tree
616 strip_innermost_template_args (tree args, int extra_levels)
617 {
618   tree new_args;
619   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
620   int i;
621
622   gcc_assert (n >= 0);
623
624   /* If N is 1, just return the outermost set of template arguments.  */
625   if (n == 1)
626     return TMPL_ARGS_LEVEL (args, 1);
627
628   /* If we're not removing anything, just return the arguments we were
629      given.  */
630   gcc_assert (extra_levels >= 0);
631   if (extra_levels == 0)
632     return args;
633
634   /* Make a new set of arguments, not containing the inner arguments.  */
635   new_args = make_tree_vec (n);
636   for (i = 1; i <= n; ++i)
637     SET_TMPL_ARGS_LEVEL (new_args, i,
638                          TMPL_ARGS_LEVEL (args, i));
639
640   return new_args;
641 }
642
643 /* We've got a template header coming up; push to a new level for storing
644    the parms.  */
645
646 void
647 begin_template_parm_list (void)
648 {
649   /* We use a non-tag-transparent scope here, which causes pushtag to
650      put tags in this scope, rather than in the enclosing class or
651      namespace scope.  This is the right thing, since we want
652      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
653      global template class, push_template_decl handles putting the
654      TEMPLATE_DECL into top-level scope.  For a nested template class,
655      e.g.:
656
657        template <class T> struct S1 {
658          template <class T> struct S2 {};
659        };
660
661      pushtag contains special code to call pushdecl_with_scope on the
662      TEMPLATE_DECL for S2.  */
663   begin_scope (sk_template_parms, NULL);
664   ++processing_template_decl;
665   ++processing_template_parmlist;
666   note_template_header (0);
667 }
668
669 /* This routine is called when a specialization is declared.  If it is
670    invalid to declare a specialization here, an error is reported and
671    false is returned, otherwise this routine will return true.  */
672
673 static bool
674 check_specialization_scope (void)
675 {
676   tree scope = current_scope ();
677
678   /* [temp.expl.spec]
679
680      An explicit specialization shall be declared in the namespace of
681      which the template is a member, or, for member templates, in the
682      namespace of which the enclosing class or enclosing class
683      template is a member.  An explicit specialization of a member
684      function, member class or static data member of a class template
685      shall be declared in the namespace of which the class template
686      is a member.  */
687   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
688     {
689       error ("explicit specialization in non-namespace scope %qD", scope);
690       return false;
691     }
692
693   /* [temp.expl.spec]
694
695      In an explicit specialization declaration for a member of a class
696      template or a member template that appears in namespace scope,
697      the member template and some of its enclosing class templates may
698      remain unspecialized, except that the declaration shall not
699      explicitly specialize a class member template if its enclosing
700      class templates are not explicitly specialized as well.  */
701   if (current_template_parms)
702     {
703       error ("enclosing class templates are not explicitly specialized");
704       return false;
705     }
706
707   return true;
708 }
709
710 /* We've just seen template <>.  */
711
712 bool
713 begin_specialization (void)
714 {
715   begin_scope (sk_template_spec, NULL);
716   note_template_header (1);
717   return check_specialization_scope ();
718 }
719
720 /* Called at then end of processing a declaration preceded by
721    template<>.  */
722
723 void
724 end_specialization (void)
725 {
726   finish_scope ();
727   reset_specialization ();
728 }
729
730 /* Any template <>'s that we have seen thus far are not referring to a
731    function specialization.  */
732
733 void
734 reset_specialization (void)
735 {
736   processing_specialization = 0;
737   template_header_count = 0;
738 }
739
740 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
741    it was of the form template <>.  */
742
743 static void
744 note_template_header (int specialization)
745 {
746   processing_specialization = specialization;
747   template_header_count++;
748 }
749
750 /* We're beginning an explicit instantiation.  */
751
752 void
753 begin_explicit_instantiation (void)
754 {
755   gcc_assert (!processing_explicit_instantiation);
756   processing_explicit_instantiation = true;
757 }
758
759
760 void
761 end_explicit_instantiation (void)
762 {
763   gcc_assert (processing_explicit_instantiation);
764   processing_explicit_instantiation = false;
765 }
766
767 /* An explicit specialization or partial specialization of TMPL is being
768    declared.  Check that the namespace in which the specialization is
769    occurring is permissible.  Returns false iff it is invalid to
770    specialize TMPL in the current namespace.  */
771
772 static bool
773 check_specialization_namespace (tree tmpl)
774 {
775   tree tpl_ns = decl_namespace_context (tmpl);
776
777   /* [tmpl.expl.spec]
778
779      An explicit specialization shall be declared in the namespace of
780      which the template is a member, or, for member templates, in the
781      namespace of which the enclosing class or enclosing class
782      template is a member.  An explicit specialization of a member
783      function, member class or static data member of a class template
784      shall be declared in the namespace of which the class template is
785      a member.  */
786   if (current_scope() != DECL_CONTEXT (tmpl)
787       && !at_namespace_scope_p ())
788     {
789       error ("specialization of %qD must appear at namespace scope", tmpl);
790       return false;
791     }
792   if (is_associated_namespace (current_namespace, tpl_ns))
793     /* Same or super-using namespace.  */
794     return true;
795   else
796     {
797       permerror (input_location, "specialization of %qD in different namespace", tmpl);
798       permerror (input_location, "  from definition of %q+#D", tmpl);
799       return false;
800     }
801 }
802
803 /* SPEC is an explicit instantiation.  Check that it is valid to
804    perform this explicit instantiation in the current namespace.  */
805
806 static void
807 check_explicit_instantiation_namespace (tree spec)
808 {
809   tree ns;
810
811   /* DR 275: An explicit instantiation shall appear in an enclosing
812      namespace of its template.  */
813   ns = decl_namespace_context (spec);
814   if (!is_ancestor (current_namespace, ns))
815     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
816                "(which does not enclose namespace %qD)",
817                spec, current_namespace, ns);
818 }
819
820 /* The TYPE is being declared.  If it is a template type, that means it
821    is a partial specialization.  Do appropriate error-checking.  */
822
823 tree
824 maybe_process_partial_specialization (tree type)
825 {
826   tree context;
827
828   if (type == error_mark_node)
829     return error_mark_node;
830
831   /* A lambda that appears in specialization context is not itself a
832      specialization.  */
833   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
834     return type;
835
836   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
837     {
838       error ("name of class shadows template template parameter %qD",
839              TYPE_NAME (type));
840       return error_mark_node;
841     }
842
843   context = TYPE_CONTEXT (type);
844
845   if (TYPE_ALIAS_P (type))
846     {
847       if (TYPE_TEMPLATE_INFO (type)
848           && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
849         error ("specialization of alias template %qD",
850                TYPE_TI_TEMPLATE (type));
851       else
852         error ("explicit specialization of non-template %qT", type);
853       return error_mark_node;
854     }
855   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
856     {
857       /* This is for ordinary explicit specialization and partial
858          specialization of a template class such as:
859
860            template <> class C<int>;
861
862          or:
863
864            template <class T> class C<T*>;
865
866          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
867
868       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
869           && !COMPLETE_TYPE_P (type))
870         {
871           if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
872               && !at_namespace_scope_p ())
873             return error_mark_node;
874           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
875           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
876           if (processing_template_decl)
877             {
878               if (push_template_decl (TYPE_MAIN_DECL (type))
879                   == error_mark_node)
880                 return error_mark_node;
881             }
882         }
883       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
884         error ("specialization of %qT after instantiation", type);
885       else if (errorcount && !processing_specialization
886                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
887                && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
888         /* Trying to define a specialization either without a template<> header
889            or in an inappropriate place.  We've already given an error, so just
890            bail now so we don't actually define the specialization.  */
891         return error_mark_node;
892     }
893   else if (CLASS_TYPE_P (type)
894            && !CLASSTYPE_USE_TEMPLATE (type)
895            && CLASSTYPE_TEMPLATE_INFO (type)
896            && context && CLASS_TYPE_P (context)
897            && CLASSTYPE_TEMPLATE_INFO (context))
898     {
899       /* This is for an explicit specialization of member class
900          template according to [temp.expl.spec/18]:
901
902            template <> template <class U> class C<int>::D;
903
904          The context `C<int>' must be an implicit instantiation.
905          Otherwise this is just a member class template declared
906          earlier like:
907
908            template <> class C<int> { template <class U> class D; };
909            template <> template <class U> class C<int>::D;
910
911          In the first case, `C<int>::D' is a specialization of `C<T>::D'
912          while in the second case, `C<int>::D' is a primary template
913          and `C<T>::D' may not exist.  */
914
915       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
916           && !COMPLETE_TYPE_P (type))
917         {
918           tree t;
919           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
920
921           if (current_namespace
922               != decl_namespace_context (tmpl))
923             {
924               permerror (input_location, "specializing %q#T in different namespace", type);
925               permerror (input_location, "  from definition of %q+#D", tmpl);
926             }
927
928           /* Check for invalid specialization after instantiation:
929
930                template <> template <> class C<int>::D<int>;
931                template <> template <class U> class C<int>::D;  */
932
933           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
934                t; t = TREE_CHAIN (t))
935             {
936               tree inst = TREE_VALUE (t);
937               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
938                   || !COMPLETE_OR_OPEN_TYPE_P (inst))
939                 {
940                   /* We already have a full specialization of this partial
941                      instantiation, or a full specialization has been
942                      looked up but not instantiated.  Reassign it to the
943                      new member specialization template.  */
944                   spec_entry elt;
945                   spec_entry *entry;
946
947                   elt.tmpl = most_general_template (tmpl);
948                   elt.args = CLASSTYPE_TI_ARGS (inst);
949                   elt.spec = inst;
950
951                   type_specializations->remove_elt (&elt);
952
953                   elt.tmpl = tmpl;
954                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
955
956                   spec_entry **slot
957                     = type_specializations->find_slot (&elt, INSERT);
958                   entry = ggc_alloc<spec_entry> ();
959                   *entry = elt;
960                   *slot = entry;
961                 }
962               else
963                 /* But if we've had an implicit instantiation, that's a
964                    problem ([temp.expl.spec]/6).  */
965                 error ("specialization %qT after instantiation %qT",
966                        type, inst);
967             }
968
969           /* Mark TYPE as a specialization.  And as a result, we only
970              have one level of template argument for the innermost
971              class template.  */
972           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
973           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
974           CLASSTYPE_TI_ARGS (type)
975             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
976         }
977     }
978   else if (processing_specialization)
979     {
980        /* Someday C++0x may allow for enum template specialization.  */
981       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
982           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
983         pedwarn (input_location, OPT_Wpedantic, "template specialization "
984                  "of %qD not allowed by ISO C++", type);
985       else
986         {
987           error ("explicit specialization of non-template %qT", type);
988           return error_mark_node;
989         }
990     }
991
992   return type;
993 }
994
995 /* Returns nonzero if we can optimize the retrieval of specializations
996    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
997    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
998
999 static inline bool
1000 optimize_specialization_lookup_p (tree tmpl)
1001 {
1002   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1003           && DECL_CLASS_SCOPE_P (tmpl)
1004           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1005              parameter.  */
1006           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1007           /* The optimized lookup depends on the fact that the
1008              template arguments for the member function template apply
1009              purely to the containing class, which is not true if the
1010              containing class is an explicit or partial
1011              specialization.  */
1012           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1013           && !DECL_MEMBER_TEMPLATE_P (tmpl)
1014           && !DECL_CONV_FN_P (tmpl)
1015           /* It is possible to have a template that is not a member
1016              template and is not a member of a template class:
1017
1018              template <typename T>
1019              struct S { friend A::f(); };
1020
1021              Here, the friend function is a template, but the context does
1022              not have template information.  The optimized lookup relies
1023              on having ARGS be the template arguments for both the class
1024              and the function template.  */
1025           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1026 }
1027
1028 /* Retrieve the specialization (in the sense of [temp.spec] - a
1029    specialization is either an instantiation or an explicit
1030    specialization) of TMPL for the given template ARGS.  If there is
1031    no such specialization, return NULL_TREE.  The ARGS are a vector of
1032    arguments, or a vector of vectors of arguments, in the case of
1033    templates with more than one level of parameters.
1034
1035    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1036    then we search for a partial specialization matching ARGS.  This
1037    parameter is ignored if TMPL is not a class template.
1038
1039    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1040    result is a NONTYPE_ARGUMENT_PACK.  */
1041
1042 static tree
1043 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1044 {
1045   if (tmpl == NULL_TREE)
1046     return NULL_TREE;
1047
1048   if (args == error_mark_node)
1049     return NULL_TREE;
1050
1051   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1052               || TREE_CODE (tmpl) == FIELD_DECL);
1053
1054   /* There should be as many levels of arguments as there are
1055      levels of parameters.  */
1056   gcc_assert (TMPL_ARGS_DEPTH (args)
1057               == (TREE_CODE (tmpl) == TEMPLATE_DECL
1058                   ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1059                   : template_class_depth (DECL_CONTEXT (tmpl))));
1060
1061   if (optimize_specialization_lookup_p (tmpl))
1062     {
1063       tree class_template;
1064       tree class_specialization;
1065       vec<tree, va_gc> *methods;
1066       tree fns;
1067       int idx;
1068
1069       /* The template arguments actually apply to the containing
1070          class.  Find the class specialization with those
1071          arguments.  */
1072       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1073       class_specialization
1074         = retrieve_specialization (class_template, args, 0);
1075       if (!class_specialization)
1076         return NULL_TREE;
1077       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1078          for the specialization.  */
1079       idx = class_method_index_for_fn (class_specialization, tmpl);
1080       if (idx == -1)
1081         return NULL_TREE;
1082       /* Iterate through the methods with the indicated name, looking
1083          for the one that has an instance of TMPL.  */
1084       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1085       for (fns = (*methods)[idx]; fns; fns = OVL_NEXT (fns))
1086         {
1087           tree fn = OVL_CURRENT (fns);
1088           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1089               /* using-declarations can add base methods to the method vec,
1090                  and we don't want those here.  */
1091               && DECL_CONTEXT (fn) == class_specialization)
1092             return fn;
1093         }
1094       return NULL_TREE;
1095     }
1096   else
1097     {
1098       spec_entry *found;
1099       spec_entry elt;
1100       hash_table<spec_hasher> *specializations;
1101
1102       elt.tmpl = tmpl;
1103       elt.args = args;
1104       elt.spec = NULL_TREE;
1105
1106       if (DECL_CLASS_TEMPLATE_P (tmpl))
1107         specializations = type_specializations;
1108       else
1109         specializations = decl_specializations;
1110
1111       if (hash == 0)
1112         hash = spec_hasher::hash (&elt);
1113       found = specializations->find_with_hash (&elt, hash);
1114       if (found)
1115         return found->spec;
1116     }
1117
1118   return NULL_TREE;
1119 }
1120
1121 /* Like retrieve_specialization, but for local declarations.  */
1122
1123 static tree
1124 retrieve_local_specialization (tree tmpl)
1125 {
1126   if (local_specializations == NULL)
1127     return NULL_TREE;
1128
1129   tree *slot = local_specializations->get (tmpl);
1130   return slot ? *slot : NULL_TREE;
1131 }
1132
1133 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1134
1135 int
1136 is_specialization_of (tree decl, tree tmpl)
1137 {
1138   tree t;
1139
1140   if (TREE_CODE (decl) == FUNCTION_DECL)
1141     {
1142       for (t = decl;
1143            t != NULL_TREE;
1144            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1145         if (t == tmpl)
1146           return 1;
1147     }
1148   else
1149     {
1150       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1151
1152       for (t = TREE_TYPE (decl);
1153            t != NULL_TREE;
1154            t = CLASSTYPE_USE_TEMPLATE (t)
1155              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1156         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1157           return 1;
1158     }
1159
1160   return 0;
1161 }
1162
1163 /* Returns nonzero iff DECL is a specialization of friend declaration
1164    FRIEND_DECL according to [temp.friend].  */
1165
1166 bool
1167 is_specialization_of_friend (tree decl, tree friend_decl)
1168 {
1169   bool need_template = true;
1170   int template_depth;
1171
1172   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1173               || TREE_CODE (decl) == TYPE_DECL);
1174
1175   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1176      of a template class, we want to check if DECL is a specialization
1177      if this.  */
1178   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1179       && DECL_TEMPLATE_INFO (friend_decl)
1180       && !DECL_USE_TEMPLATE (friend_decl))
1181     {
1182       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1183       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1184       need_template = false;
1185     }
1186   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1187            && !PRIMARY_TEMPLATE_P (friend_decl))
1188     need_template = false;
1189
1190   /* There is nothing to do if this is not a template friend.  */
1191   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1192     return false;
1193
1194   if (is_specialization_of (decl, friend_decl))
1195     return true;
1196
1197   /* [temp.friend/6]
1198      A member of a class template may be declared to be a friend of a
1199      non-template class.  In this case, the corresponding member of
1200      every specialization of the class template is a friend of the
1201      class granting friendship.
1202
1203      For example, given a template friend declaration
1204
1205        template <class T> friend void A<T>::f();
1206
1207      the member function below is considered a friend
1208
1209        template <> struct A<int> {
1210          void f();
1211        };
1212
1213      For this type of template friend, TEMPLATE_DEPTH below will be
1214      nonzero.  To determine if DECL is a friend of FRIEND, we first
1215      check if the enclosing class is a specialization of another.  */
1216
1217   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1218   if (template_depth
1219       && DECL_CLASS_SCOPE_P (decl)
1220       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1221                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1222     {
1223       /* Next, we check the members themselves.  In order to handle
1224          a few tricky cases, such as when FRIEND_DECL's are
1225
1226            template <class T> friend void A<T>::g(T t);
1227            template <class T> template <T t> friend void A<T>::h();
1228
1229          and DECL's are
1230
1231            void A<int>::g(int);
1232            template <int> void A<int>::h();
1233
1234          we need to figure out ARGS, the template arguments from
1235          the context of DECL.  This is required for template substitution
1236          of `T' in the function parameter of `g' and template parameter
1237          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1238
1239       tree context = DECL_CONTEXT (decl);
1240       tree args = NULL_TREE;
1241       int current_depth = 0;
1242
1243       while (current_depth < template_depth)
1244         {
1245           if (CLASSTYPE_TEMPLATE_INFO (context))
1246             {
1247               if (current_depth == 0)
1248                 args = TYPE_TI_ARGS (context);
1249               else
1250                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1251               current_depth++;
1252             }
1253           context = TYPE_CONTEXT (context);
1254         }
1255
1256       if (TREE_CODE (decl) == FUNCTION_DECL)
1257         {
1258           bool is_template;
1259           tree friend_type;
1260           tree decl_type;
1261           tree friend_args_type;
1262           tree decl_args_type;
1263
1264           /* Make sure that both DECL and FRIEND_DECL are templates or
1265              non-templates.  */
1266           is_template = DECL_TEMPLATE_INFO (decl)
1267                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1268           if (need_template ^ is_template)
1269             return false;
1270           else if (is_template)
1271             {
1272               /* If both are templates, check template parameter list.  */
1273               tree friend_parms
1274                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1275                                          args, tf_none);
1276               if (!comp_template_parms
1277                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1278                       friend_parms))
1279                 return false;
1280
1281               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1282             }
1283           else
1284             decl_type = TREE_TYPE (decl);
1285
1286           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1287                                               tf_none, NULL_TREE);
1288           if (friend_type == error_mark_node)
1289             return false;
1290
1291           /* Check if return types match.  */
1292           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1293             return false;
1294
1295           /* Check if function parameter types match, ignoring the
1296              `this' parameter.  */
1297           friend_args_type = TYPE_ARG_TYPES (friend_type);
1298           decl_args_type = TYPE_ARG_TYPES (decl_type);
1299           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1300             friend_args_type = TREE_CHAIN (friend_args_type);
1301           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1302             decl_args_type = TREE_CHAIN (decl_args_type);
1303
1304           return compparms (decl_args_type, friend_args_type);
1305         }
1306       else
1307         {
1308           /* DECL is a TYPE_DECL */
1309           bool is_template;
1310           tree decl_type = TREE_TYPE (decl);
1311
1312           /* Make sure that both DECL and FRIEND_DECL are templates or
1313              non-templates.  */
1314           is_template
1315             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1316               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1317
1318           if (need_template ^ is_template)
1319             return false;
1320           else if (is_template)
1321             {
1322               tree friend_parms;
1323               /* If both are templates, check the name of the two
1324                  TEMPLATE_DECL's first because is_friend didn't.  */
1325               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1326                   != DECL_NAME (friend_decl))
1327                 return false;
1328
1329               /* Now check template parameter list.  */
1330               friend_parms
1331                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1332                                          args, tf_none);
1333               return comp_template_parms
1334                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1335                  friend_parms);
1336             }
1337           else
1338             return (DECL_NAME (decl)
1339                     == DECL_NAME (friend_decl));
1340         }
1341     }
1342   return false;
1343 }
1344
1345 /* Register the specialization SPEC as a specialization of TMPL with
1346    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1347    is actually just a friend declaration.  Returns SPEC, or an
1348    equivalent prior declaration, if available.
1349
1350    We also store instantiations of field packs in the hash table, even
1351    though they are not themselves templates, to make lookup easier.  */
1352
1353 static tree
1354 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1355                          hashval_t hash)
1356 {
1357   tree fn;
1358   spec_entry **slot = NULL;
1359   spec_entry elt;
1360
1361   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1362               || (TREE_CODE (tmpl) == FIELD_DECL
1363                   && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1364
1365   if (TREE_CODE (spec) == FUNCTION_DECL
1366       && uses_template_parms (DECL_TI_ARGS (spec)))
1367     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1368        register it; we want the corresponding TEMPLATE_DECL instead.
1369        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1370        the more obvious `uses_template_parms (spec)' to avoid problems
1371        with default function arguments.  In particular, given
1372        something like this:
1373
1374           template <class T> void f(T t1, T t = T())
1375
1376        the default argument expression is not substituted for in an
1377        instantiation unless and until it is actually needed.  */
1378     return spec;
1379
1380   if (optimize_specialization_lookup_p (tmpl))
1381     /* We don't put these specializations in the hash table, but we might
1382        want to give an error about a mismatch.  */
1383     fn = retrieve_specialization (tmpl, args, 0);
1384   else
1385     {
1386       elt.tmpl = tmpl;
1387       elt.args = args;
1388       elt.spec = spec;
1389
1390       if (hash == 0)
1391         hash = spec_hasher::hash (&elt);
1392
1393       slot =
1394         decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1395       if (*slot)
1396         fn = ((spec_entry *) *slot)->spec;
1397       else
1398         fn = NULL_TREE;
1399     }
1400
1401   /* We can sometimes try to re-register a specialization that we've
1402      already got.  In particular, regenerate_decl_from_template calls
1403      duplicate_decls which will update the specialization list.  But,
1404      we'll still get called again here anyhow.  It's more convenient
1405      to simply allow this than to try to prevent it.  */
1406   if (fn == spec)
1407     return spec;
1408   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1409     {
1410       if (DECL_TEMPLATE_INSTANTIATION (fn))
1411         {
1412           if (DECL_ODR_USED (fn)
1413               || DECL_EXPLICIT_INSTANTIATION (fn))
1414             {
1415               error ("specialization of %qD after instantiation",
1416                      fn);
1417               return error_mark_node;
1418             }
1419           else
1420             {
1421               tree clone;
1422               /* This situation should occur only if the first
1423                  specialization is an implicit instantiation, the
1424                  second is an explicit specialization, and the
1425                  implicit instantiation has not yet been used.  That
1426                  situation can occur if we have implicitly
1427                  instantiated a member function and then specialized
1428                  it later.
1429
1430                  We can also wind up here if a friend declaration that
1431                  looked like an instantiation turns out to be a
1432                  specialization:
1433
1434                    template <class T> void foo(T);
1435                    class S { friend void foo<>(int) };
1436                    template <> void foo(int);
1437
1438                  We transform the existing DECL in place so that any
1439                  pointers to it become pointers to the updated
1440                  declaration.
1441
1442                  If there was a definition for the template, but not
1443                  for the specialization, we want this to look as if
1444                  there were no definition, and vice versa.  */
1445               DECL_INITIAL (fn) = NULL_TREE;
1446               duplicate_decls (spec, fn, is_friend);
1447               /* The call to duplicate_decls will have applied
1448                  [temp.expl.spec]:
1449
1450                    An explicit specialization of a function template
1451                    is inline only if it is explicitly declared to be,
1452                    and independently of whether its function template
1453                    is.
1454
1455                 to the primary function; now copy the inline bits to
1456                 the various clones.  */
1457               FOR_EACH_CLONE (clone, fn)
1458                 {
1459                   DECL_DECLARED_INLINE_P (clone)
1460                     = DECL_DECLARED_INLINE_P (fn);
1461                   DECL_SOURCE_LOCATION (clone)
1462                     = DECL_SOURCE_LOCATION (fn);
1463                   DECL_DELETED_FN (clone)
1464                     = DECL_DELETED_FN (fn);
1465                 }
1466               check_specialization_namespace (tmpl);
1467
1468               return fn;
1469             }
1470         }
1471       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1472         {
1473           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1474             /* Dup decl failed, but this is a new definition. Set the
1475                line number so any errors match this new
1476                definition.  */
1477             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1478
1479           return fn;
1480         }
1481     }
1482   else if (fn)
1483     return duplicate_decls (spec, fn, is_friend);
1484
1485   /* A specialization must be declared in the same namespace as the
1486      template it is specializing.  */
1487   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1488       && !check_specialization_namespace (tmpl))
1489     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1490
1491   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1492     {
1493       spec_entry *entry = ggc_alloc<spec_entry> ();
1494       gcc_assert (tmpl && args && spec);
1495       *entry = elt;
1496       *slot = entry;
1497       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1498            && PRIMARY_TEMPLATE_P (tmpl)
1499            && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1500           || variable_template_p (tmpl))
1501         /* If TMPL is a forward declaration of a template function, keep a list
1502            of all specializations in case we need to reassign them to a friend
1503            template later in tsubst_friend_function.
1504
1505            Also keep a list of all variable template instantiations so that
1506            process_partial_specialization can check whether a later partial
1507            specialization would have used it.  */
1508         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1509           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1510     }
1511
1512   return spec;
1513 }
1514
1515 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1516    TMPL and ARGS members, ignores SPEC.  */
1517
1518 int comparing_specializations;
1519
1520 bool
1521 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1522 {
1523   int equal;
1524
1525   ++comparing_specializations;
1526   equal = (e1->tmpl == e2->tmpl
1527            && comp_template_args (e1->args, e2->args));
1528   --comparing_specializations;
1529
1530   return equal;
1531 }
1532
1533 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1534
1535 static hashval_t
1536 hash_tmpl_and_args (tree tmpl, tree args)
1537 {
1538   hashval_t val = DECL_UID (tmpl);
1539   return iterative_hash_template_arg (args, val);
1540 }
1541
1542 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1543    ignoring SPEC.  */
1544
1545 hashval_t
1546 spec_hasher::hash (spec_entry *e)
1547 {
1548   return hash_tmpl_and_args (e->tmpl, e->args);
1549 }
1550
1551 /* Recursively calculate a hash value for a template argument ARG, for use
1552    in the hash tables of template specializations.  */
1553
1554 hashval_t
1555 iterative_hash_template_arg (tree arg, hashval_t val)
1556 {
1557   unsigned HOST_WIDE_INT i;
1558   enum tree_code code;
1559   char tclass;
1560
1561   if (arg == NULL_TREE)
1562     return iterative_hash_object (arg, val);
1563
1564   if (!TYPE_P (arg))
1565     STRIP_NOPS (arg);
1566
1567   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1568     /* We can get one of these when re-hashing a previous entry in the middle
1569        of substituting into a pack expansion.  Just look through it.  */
1570     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1571
1572   code = TREE_CODE (arg);
1573   tclass = TREE_CODE_CLASS (code);
1574
1575   val = iterative_hash_object (code, val);
1576
1577   switch (code)
1578     {
1579     case ERROR_MARK:
1580       return val;
1581
1582     case IDENTIFIER_NODE:
1583       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1584
1585     case TREE_VEC:
1586       {
1587         int i, len = TREE_VEC_LENGTH (arg);
1588         for (i = 0; i < len; ++i)
1589           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1590         return val;
1591       }
1592
1593     case TYPE_PACK_EXPANSION:
1594     case EXPR_PACK_EXPANSION:
1595       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1596       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1597
1598     case TYPE_ARGUMENT_PACK:
1599     case NONTYPE_ARGUMENT_PACK:
1600       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1601
1602     case TREE_LIST:
1603       for (; arg; arg = TREE_CHAIN (arg))
1604         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1605       return val;
1606
1607     case OVERLOAD:
1608       for (; arg; arg = OVL_NEXT (arg))
1609         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1610       return val;
1611
1612     case CONSTRUCTOR:
1613       {
1614         tree field, value;
1615         iterative_hash_template_arg (TREE_TYPE (arg), val);
1616         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1617           {
1618             val = iterative_hash_template_arg (field, val);
1619             val = iterative_hash_template_arg (value, val);
1620           }
1621         return val;
1622       }
1623
1624     case PARM_DECL:
1625       if (!DECL_ARTIFICIAL (arg))
1626         {
1627           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1628           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1629         }
1630       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1631
1632     case TARGET_EXPR:
1633       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1634
1635     case PTRMEM_CST:
1636       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1637       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1638
1639     case TEMPLATE_PARM_INDEX:
1640       val = iterative_hash_template_arg
1641         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1642       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1643       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1644
1645     case TRAIT_EXPR:
1646       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1647       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1648       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1649
1650     case BASELINK:
1651       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1652                                          val);
1653       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1654                                           val);
1655
1656     case MODOP_EXPR:
1657       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1658       code = TREE_CODE (TREE_OPERAND (arg, 1));
1659       val = iterative_hash_object (code, val);
1660       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1661
1662     case LAMBDA_EXPR:
1663       /* A lambda can't appear in a template arg, but don't crash on
1664          erroneous input.  */
1665       gcc_assert (seen_error ());
1666       return val;
1667
1668     case CAST_EXPR:
1669     case IMPLICIT_CONV_EXPR:
1670     case STATIC_CAST_EXPR:
1671     case REINTERPRET_CAST_EXPR:
1672     case CONST_CAST_EXPR:
1673     case DYNAMIC_CAST_EXPR:
1674     case NEW_EXPR:
1675       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1676       /* Now hash operands as usual.  */
1677       break;
1678
1679     default:
1680       break;
1681     }
1682
1683   switch (tclass)
1684     {
1685     case tcc_type:
1686       if (alias_template_specialization_p (arg))
1687         {
1688           // We want an alias specialization that survived strip_typedefs
1689           // to hash differently from its TYPE_CANONICAL, to avoid hash
1690           // collisions that compare as different in template_args_equal.
1691           // These could be dependent specializations that strip_typedefs
1692           // left alone, or untouched specializations because
1693           // coerce_template_parms returns the unconverted template
1694           // arguments if it sees incomplete argument packs.
1695           tree ti = TYPE_TEMPLATE_INFO (arg);
1696           return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1697         }
1698       if (TYPE_CANONICAL (arg))
1699         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1700                                       val);
1701       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1702         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1703       /* Otherwise just compare the types during lookup.  */
1704       return val;
1705
1706     case tcc_declaration:
1707     case tcc_constant:
1708       return iterative_hash_expr (arg, val);
1709
1710     default:
1711       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1712       {
1713         unsigned n = cp_tree_operand_length (arg);
1714         for (i = 0; i < n; ++i)
1715           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1716         return val;
1717       }
1718     }
1719   gcc_unreachable ();
1720   return 0;
1721 }
1722
1723 /* Unregister the specialization SPEC as a specialization of TMPL.
1724    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1725    if the SPEC was listed as a specialization of TMPL.
1726
1727    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1728
1729 bool
1730 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1731 {
1732   spec_entry *entry;
1733   spec_entry elt;
1734
1735   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1736   elt.args = TI_ARGS (tinfo);
1737   elt.spec = NULL_TREE;
1738
1739   entry = decl_specializations->find (&elt);
1740   if (entry != NULL)
1741     {
1742       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1743       gcc_assert (new_spec != NULL_TREE);
1744       entry->spec = new_spec;
1745       return 1;
1746     }
1747
1748   return 0;
1749 }
1750
1751 /* Like register_specialization, but for local declarations.  We are
1752    registering SPEC, an instantiation of TMPL.  */
1753
1754 static void
1755 register_local_specialization (tree spec, tree tmpl)
1756 {
1757   local_specializations->put (tmpl, spec);
1758 }
1759
1760 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1761    specialized class.  */
1762
1763 bool
1764 explicit_class_specialization_p (tree type)
1765 {
1766   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1767     return false;
1768   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1769 }
1770
1771 /* Print the list of functions at FNS, going through all the overloads
1772    for each element of the list.  Alternatively, FNS can not be a
1773    TREE_LIST, in which case it will be printed together with all the
1774    overloads.
1775
1776    MORE and *STR should respectively be FALSE and NULL when the function
1777    is called from the outside.  They are used internally on recursive
1778    calls.  print_candidates manages the two parameters and leaves NULL
1779    in *STR when it ends.  */
1780
1781 static void
1782 print_candidates_1 (tree fns, bool more, const char **str)
1783 {
1784   tree fn, fn2;
1785   char *spaces = NULL;
1786
1787   for (fn = fns; fn; fn = OVL_NEXT (fn))
1788     if (TREE_CODE (fn) == TREE_LIST)
1789       {
1790         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1791           print_candidates_1 (TREE_VALUE (fn2),
1792                               TREE_CHAIN (fn2) || more, str);
1793       }
1794     else
1795       {
1796         tree cand = OVL_CURRENT (fn);
1797         if (!*str)
1798           {
1799             /* Pick the prefix string.  */
1800             if (!more && !OVL_NEXT (fns))
1801               {
1802                 inform (DECL_SOURCE_LOCATION (cand),
1803                         "candidate is: %#D", cand);
1804                 continue;
1805               }
1806
1807             *str = _("candidates are:");
1808             spaces = get_spaces (*str);
1809           }
1810         inform (DECL_SOURCE_LOCATION (cand), "%s %#D", *str, cand);
1811         *str = spaces ? spaces : *str;
1812       }
1813
1814   if (!more)
1815     {
1816       free (spaces);
1817       *str = NULL;
1818     }
1819 }
1820
1821 /* Print the list of candidate FNS in an error message.  FNS can also
1822    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1823
1824 void
1825 print_candidates (tree fns)
1826 {
1827   const char *str = NULL;
1828   print_candidates_1 (fns, false, &str);
1829   gcc_assert (str == NULL);
1830 }
1831
1832 /* Returns the template (one of the functions given by TEMPLATE_ID)
1833    which can be specialized to match the indicated DECL with the
1834    explicit template args given in TEMPLATE_ID.  The DECL may be
1835    NULL_TREE if none is available.  In that case, the functions in
1836    TEMPLATE_ID are non-members.
1837
1838    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1839    specialization of a member template.
1840
1841    The TEMPLATE_COUNT is the number of references to qualifying
1842    template classes that appeared in the name of the function. See
1843    check_explicit_specialization for a more accurate description.
1844
1845    TSK indicates what kind of template declaration (if any) is being
1846    declared.  TSK_TEMPLATE indicates that the declaration given by
1847    DECL, though a FUNCTION_DECL, has template parameters, and is
1848    therefore a template function.
1849
1850    The template args (those explicitly specified and those deduced)
1851    are output in a newly created vector *TARGS_OUT.
1852
1853    If it is impossible to determine the result, an error message is
1854    issued.  The error_mark_node is returned to indicate failure.  */
1855
1856 static tree
1857 determine_specialization (tree template_id,
1858                           tree decl,
1859                           tree* targs_out,
1860                           int need_member_template,
1861                           int template_count,
1862                           tmpl_spec_kind tsk)
1863 {
1864   tree fns;
1865   tree targs;
1866   tree explicit_targs;
1867   tree candidates = NULL_TREE;
1868   /* A TREE_LIST of templates of which DECL may be a specialization.
1869      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1870      corresponding TREE_PURPOSE is the set of template arguments that,
1871      when used to instantiate the template, would produce a function
1872      with the signature of DECL.  */
1873   tree templates = NULL_TREE;
1874   int header_count;
1875   cp_binding_level *b;
1876
1877   *targs_out = NULL_TREE;
1878
1879   if (template_id == error_mark_node || decl == error_mark_node)
1880     return error_mark_node;
1881
1882   /* We shouldn't be specializing a member template of an
1883      unspecialized class template; we already gave an error in
1884      check_specialization_scope, now avoid crashing.  */
1885   if (template_count && DECL_CLASS_SCOPE_P (decl)
1886       && template_class_depth (DECL_CONTEXT (decl)) > 0)
1887     {
1888       gcc_assert (errorcount);
1889       return error_mark_node;
1890     }
1891
1892   fns = TREE_OPERAND (template_id, 0);
1893   explicit_targs = TREE_OPERAND (template_id, 1);
1894
1895   if (fns == error_mark_node)
1896     return error_mark_node;
1897
1898   /* Check for baselinks.  */
1899   if (BASELINK_P (fns))
1900     fns = BASELINK_FUNCTIONS (fns);
1901
1902   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
1903     {
1904       error ("%qD is not a function template", fns);
1905       return error_mark_node;
1906     }
1907   else if (VAR_P (decl) && !variable_template_p (fns))
1908     {
1909       error ("%qD is not a variable template", fns);
1910       return error_mark_node;
1911     }
1912
1913   /* Count the number of template headers specified for this
1914      specialization.  */
1915   header_count = 0;
1916   for (b = current_binding_level;
1917        b->kind == sk_template_parms;
1918        b = b->level_chain)
1919     ++header_count;
1920
1921   if (variable_template_p (fns))
1922     templates = tree_cons (explicit_targs, fns, templates);
1923   else for (; fns; fns = OVL_NEXT (fns))
1924     {
1925       tree fn = OVL_CURRENT (fns);
1926
1927       if (TREE_CODE (fn) == TEMPLATE_DECL)
1928         {
1929           tree decl_arg_types;
1930           tree fn_arg_types;
1931           tree insttype;
1932
1933           /* In case of explicit specialization, we need to check if
1934              the number of template headers appearing in the specialization
1935              is correct. This is usually done in check_explicit_specialization,
1936              but the check done there cannot be exhaustive when specializing
1937              member functions. Consider the following code:
1938
1939              template <> void A<int>::f(int);
1940              template <> template <> void A<int>::f(int);
1941
1942              Assuming that A<int> is not itself an explicit specialization
1943              already, the first line specializes "f" which is a non-template
1944              member function, whilst the second line specializes "f" which
1945              is a template member function. So both lines are syntactically
1946              correct, and check_explicit_specialization does not reject
1947              them.
1948
1949              Here, we can do better, as we are matching the specialization
1950              against the declarations. We count the number of template
1951              headers, and we check if they match TEMPLATE_COUNT + 1
1952              (TEMPLATE_COUNT is the number of qualifying template classes,
1953              plus there must be another header for the member template
1954              itself).
1955
1956              Notice that if header_count is zero, this is not a
1957              specialization but rather a template instantiation, so there
1958              is no check we can perform here.  */
1959           if (header_count && header_count != template_count + 1)
1960             continue;
1961
1962           /* Check that the number of template arguments at the
1963              innermost level for DECL is the same as for FN.  */
1964           if (current_binding_level->kind == sk_template_parms
1965               && !current_binding_level->explicit_spec_p
1966               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1967                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1968                                       (current_template_parms))))
1969             continue;
1970
1971           /* DECL might be a specialization of FN.  */
1972           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1973           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1974
1975           /* For a non-static member function, we need to make sure
1976              that the const qualification is the same.  Since
1977              get_bindings does not try to merge the "this" parameter,
1978              we must do the comparison explicitly.  */
1979           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1980               && !same_type_p (TREE_VALUE (fn_arg_types),
1981                                TREE_VALUE (decl_arg_types)))
1982             continue;
1983
1984           /* Skip the "this" parameter and, for constructors of
1985              classes with virtual bases, the VTT parameter.  A
1986              full specialization of a constructor will have a VTT
1987              parameter, but a template never will.  */ 
1988           decl_arg_types 
1989             = skip_artificial_parms_for (decl, decl_arg_types);
1990           fn_arg_types 
1991             = skip_artificial_parms_for (fn, fn_arg_types);
1992
1993           /* Function templates cannot be specializations; there are
1994              no partial specializations of functions.  Therefore, if
1995              the type of DECL does not match FN, there is no
1996              match.  */
1997           if (tsk == tsk_template)
1998             {
1999               if (compparms (fn_arg_types, decl_arg_types))
2000                 candidates = tree_cons (NULL_TREE, fn, candidates);
2001               continue;
2002             }
2003
2004           /* See whether this function might be a specialization of this
2005              template.  Suppress access control because we might be trying
2006              to make this specialization a friend, and we have already done
2007              access control for the declaration of the specialization.  */
2008           push_deferring_access_checks (dk_no_check);
2009           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2010           pop_deferring_access_checks ();
2011
2012           if (!targs)
2013             /* We cannot deduce template arguments that when used to
2014                specialize TMPL will produce DECL.  */
2015             continue;
2016
2017           /* Make sure that the deduced arguments actually work.  */
2018           insttype = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
2019           if (insttype == error_mark_node)
2020             continue;
2021           fn_arg_types
2022             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2023           if (!compparms (fn_arg_types, decl_arg_types))
2024             continue;
2025
2026           /* Save this template, and the arguments deduced.  */
2027           templates = tree_cons (targs, fn, templates);
2028         }
2029       else if (need_member_template)
2030         /* FN is an ordinary member function, and we need a
2031            specialization of a member template.  */
2032         ;
2033       else if (TREE_CODE (fn) != FUNCTION_DECL)
2034         /* We can get IDENTIFIER_NODEs here in certain erroneous
2035            cases.  */
2036         ;
2037       else if (!DECL_FUNCTION_MEMBER_P (fn))
2038         /* This is just an ordinary non-member function.  Nothing can
2039            be a specialization of that.  */
2040         ;
2041       else if (DECL_ARTIFICIAL (fn))
2042         /* Cannot specialize functions that are created implicitly.  */
2043         ;
2044       else
2045         {
2046           tree decl_arg_types;
2047
2048           /* This is an ordinary member function.  However, since
2049              we're here, we can assume its enclosing class is a
2050              template class.  For example,
2051
2052                template <typename T> struct S { void f(); };
2053                template <> void S<int>::f() {}
2054
2055              Here, S<int>::f is a non-template, but S<int> is a
2056              template class.  If FN has the same type as DECL, we
2057              might be in business.  */
2058
2059           if (!DECL_TEMPLATE_INFO (fn))
2060             /* Its enclosing class is an explicit specialization
2061                of a template class.  This is not a candidate.  */
2062             continue;
2063
2064           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2065                             TREE_TYPE (TREE_TYPE (fn))))
2066             /* The return types differ.  */
2067             continue;
2068
2069           /* Adjust the type of DECL in case FN is a static member.  */
2070           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2071           if (DECL_STATIC_FUNCTION_P (fn)
2072               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2073             decl_arg_types = TREE_CHAIN (decl_arg_types);
2074
2075           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2076                          decl_arg_types))
2077             /* They match!  */
2078             candidates = tree_cons (NULL_TREE, fn, candidates);
2079         }
2080     }
2081
2082   if (templates && TREE_CHAIN (templates))
2083     {
2084       /* We have:
2085
2086            [temp.expl.spec]
2087
2088            It is possible for a specialization with a given function
2089            signature to be instantiated from more than one function
2090            template.  In such cases, explicit specification of the
2091            template arguments must be used to uniquely identify the
2092            function template specialization being specialized.
2093
2094          Note that here, there's no suggestion that we're supposed to
2095          determine which of the candidate templates is most
2096          specialized.  However, we, also have:
2097
2098            [temp.func.order]
2099
2100            Partial ordering of overloaded function template
2101            declarations is used in the following contexts to select
2102            the function template to which a function template
2103            specialization refers:
2104
2105            -- when an explicit specialization refers to a function
2106               template.
2107
2108          So, we do use the partial ordering rules, at least for now.
2109          This extension can only serve to make invalid programs valid,
2110          so it's safe.  And, there is strong anecdotal evidence that
2111          the committee intended the partial ordering rules to apply;
2112          the EDG front end has that behavior, and John Spicer claims
2113          that the committee simply forgot to delete the wording in
2114          [temp.expl.spec].  */
2115       tree tmpl = most_specialized_instantiation (templates);
2116       if (tmpl != error_mark_node)
2117         {
2118           templates = tmpl;
2119           TREE_CHAIN (templates) = NULL_TREE;
2120         }
2121     }
2122
2123   if (templates == NULL_TREE && candidates == NULL_TREE)
2124     {
2125       error ("template-id %qD for %q+D does not match any template "
2126              "declaration", template_id, decl);
2127       if (header_count && header_count != template_count + 1)
2128         inform (input_location, "saw %d %<template<>%>, need %d for "
2129                 "specializing a member function template",
2130                 header_count, template_count + 1);
2131       return error_mark_node;
2132     }
2133   else if ((templates && TREE_CHAIN (templates))
2134            || (candidates && TREE_CHAIN (candidates))
2135            || (templates && candidates))
2136     {
2137       error ("ambiguous template specialization %qD for %q+D",
2138              template_id, decl);
2139       candidates = chainon (candidates, templates);
2140       print_candidates (candidates);
2141       return error_mark_node;
2142     }
2143
2144   /* We have one, and exactly one, match.  */
2145   if (candidates)
2146     {
2147       tree fn = TREE_VALUE (candidates);
2148       *targs_out = copy_node (DECL_TI_ARGS (fn));
2149       /* DECL is a re-declaration or partial instantiation of a template
2150          function.  */
2151       if (TREE_CODE (fn) == TEMPLATE_DECL)
2152         return fn;
2153       /* It was a specialization of an ordinary member function in a
2154          template class.  */
2155       return DECL_TI_TEMPLATE (fn);
2156     }
2157
2158   /* It was a specialization of a template.  */
2159   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2160   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2161     {
2162       *targs_out = copy_node (targs);
2163       SET_TMPL_ARGS_LEVEL (*targs_out,
2164                            TMPL_ARGS_DEPTH (*targs_out),
2165                            TREE_PURPOSE (templates));
2166     }
2167   else
2168     *targs_out = TREE_PURPOSE (templates);
2169   return TREE_VALUE (templates);
2170 }
2171
2172 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2173    but with the default argument values filled in from those in the
2174    TMPL_TYPES.  */
2175
2176 static tree
2177 copy_default_args_to_explicit_spec_1 (tree spec_types,
2178                                       tree tmpl_types)
2179 {
2180   tree new_spec_types;
2181
2182   if (!spec_types)
2183     return NULL_TREE;
2184
2185   if (spec_types == void_list_node)
2186     return void_list_node;
2187
2188   /* Substitute into the rest of the list.  */
2189   new_spec_types =
2190     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2191                                           TREE_CHAIN (tmpl_types));
2192
2193   /* Add the default argument for this parameter.  */
2194   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2195                          TREE_VALUE (spec_types),
2196                          new_spec_types);
2197 }
2198
2199 /* DECL is an explicit specialization.  Replicate default arguments
2200    from the template it specializes.  (That way, code like:
2201
2202      template <class T> void f(T = 3);
2203      template <> void f(double);
2204      void g () { f (); }
2205
2206    works, as required.)  An alternative approach would be to look up
2207    the correct default arguments at the call-site, but this approach
2208    is consistent with how implicit instantiations are handled.  */
2209
2210 static void
2211 copy_default_args_to_explicit_spec (tree decl)
2212 {
2213   tree tmpl;
2214   tree spec_types;
2215   tree tmpl_types;
2216   tree new_spec_types;
2217   tree old_type;
2218   tree new_type;
2219   tree t;
2220   tree object_type = NULL_TREE;
2221   tree in_charge = NULL_TREE;
2222   tree vtt = NULL_TREE;
2223
2224   /* See if there's anything we need to do.  */
2225   tmpl = DECL_TI_TEMPLATE (decl);
2226   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2227   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2228     if (TREE_PURPOSE (t))
2229       break;
2230   if (!t)
2231     return;
2232
2233   old_type = TREE_TYPE (decl);
2234   spec_types = TYPE_ARG_TYPES (old_type);
2235
2236   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2237     {
2238       /* Remove the this pointer, but remember the object's type for
2239          CV quals.  */
2240       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2241       spec_types = TREE_CHAIN (spec_types);
2242       tmpl_types = TREE_CHAIN (tmpl_types);
2243
2244       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2245         {
2246           /* DECL may contain more parameters than TMPL due to the extra
2247              in-charge parameter in constructors and destructors.  */
2248           in_charge = spec_types;
2249           spec_types = TREE_CHAIN (spec_types);
2250         }
2251       if (DECL_HAS_VTT_PARM_P (decl))
2252         {
2253           vtt = spec_types;
2254           spec_types = TREE_CHAIN (spec_types);
2255         }
2256     }
2257
2258   /* Compute the merged default arguments.  */
2259   new_spec_types =
2260     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2261
2262   /* Compute the new FUNCTION_TYPE.  */
2263   if (object_type)
2264     {
2265       if (vtt)
2266         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2267                                          TREE_VALUE (vtt),
2268                                          new_spec_types);
2269
2270       if (in_charge)
2271         /* Put the in-charge parameter back.  */
2272         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2273                                          TREE_VALUE (in_charge),
2274                                          new_spec_types);
2275
2276       new_type = build_method_type_directly (object_type,
2277                                              TREE_TYPE (old_type),
2278                                              new_spec_types);
2279     }
2280   else
2281     new_type = build_function_type (TREE_TYPE (old_type),
2282                                     new_spec_types);
2283   new_type = cp_build_type_attribute_variant (new_type,
2284                                               TYPE_ATTRIBUTES (old_type));
2285   new_type = build_exception_variant (new_type,
2286                                       TYPE_RAISES_EXCEPTIONS (old_type));
2287
2288   if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2289     TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2290
2291   TREE_TYPE (decl) = new_type;
2292 }
2293
2294 /* Return the number of template headers we expect to see for a definition
2295    or specialization of CTYPE or one of its non-template members.  */
2296
2297 int
2298 num_template_headers_for_class (tree ctype)
2299 {
2300   int num_templates = 0;
2301
2302   while (ctype && CLASS_TYPE_P (ctype))
2303     {
2304       /* You're supposed to have one `template <...>' for every
2305          template class, but you don't need one for a full
2306          specialization.  For example:
2307
2308          template <class T> struct S{};
2309          template <> struct S<int> { void f(); };
2310          void S<int>::f () {}
2311
2312          is correct; there shouldn't be a `template <>' for the
2313          definition of `S<int>::f'.  */
2314       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2315         /* If CTYPE does not have template information of any
2316            kind,  then it is not a template, nor is it nested
2317            within a template.  */
2318         break;
2319       if (explicit_class_specialization_p (ctype))
2320         break;
2321       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2322         ++num_templates;
2323
2324       ctype = TYPE_CONTEXT (ctype);
2325     }
2326
2327   return num_templates;
2328 }
2329
2330 /* Do a simple sanity check on the template headers that precede the
2331    variable declaration DECL.  */
2332
2333 void
2334 check_template_variable (tree decl)
2335 {
2336   tree ctx = CP_DECL_CONTEXT (decl);
2337   int wanted = num_template_headers_for_class (ctx);
2338   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2339       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2340     {
2341       if (cxx_dialect < cxx14)
2342         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2343                  "variable templates only available with "
2344                  "-std=c++14 or -std=gnu++14");
2345
2346       // Namespace-scope variable templates should have a template header.
2347       ++wanted;
2348     }
2349   if (template_header_count > wanted)
2350     {
2351       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2352                              "too many template headers for %D (should be %d)",
2353                              decl, wanted);
2354       if (warned && CLASS_TYPE_P (ctx)
2355           && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2356         inform (DECL_SOURCE_LOCATION (decl),
2357                 "members of an explicitly specialized class are defined "
2358                 "without a template header");
2359     }
2360 }
2361
2362 /* Check to see if the function just declared, as indicated in
2363    DECLARATOR, and in DECL, is a specialization of a function
2364    template.  We may also discover that the declaration is an explicit
2365    instantiation at this point.
2366
2367    Returns DECL, or an equivalent declaration that should be used
2368    instead if all goes well.  Issues an error message if something is
2369    amiss.  Returns error_mark_node if the error is not easily
2370    recoverable.
2371
2372    FLAGS is a bitmask consisting of the following flags:
2373
2374    2: The function has a definition.
2375    4: The function is a friend.
2376
2377    The TEMPLATE_COUNT is the number of references to qualifying
2378    template classes that appeared in the name of the function.  For
2379    example, in
2380
2381      template <class T> struct S { void f(); };
2382      void S<int>::f();
2383
2384    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2385    classes are not counted in the TEMPLATE_COUNT, so that in
2386
2387      template <class T> struct S {};
2388      template <> struct S<int> { void f(); }
2389      template <> void S<int>::f();
2390
2391    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2392    invalid; there should be no template <>.)
2393
2394    If the function is a specialization, it is marked as such via
2395    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2396    is set up correctly, and it is added to the list of specializations
2397    for that template.  */
2398
2399 tree
2400 check_explicit_specialization (tree declarator,
2401                                tree decl,
2402                                int template_count,
2403                                int flags)
2404 {
2405   int have_def = flags & 2;
2406   int is_friend = flags & 4;
2407   int specialization = 0;
2408   int explicit_instantiation = 0;
2409   int member_specialization = 0;
2410   tree ctype = DECL_CLASS_CONTEXT (decl);
2411   tree dname = DECL_NAME (decl);
2412   tmpl_spec_kind tsk;
2413
2414   if (is_friend)
2415     {
2416       if (!processing_specialization)
2417         tsk = tsk_none;
2418       else
2419         tsk = tsk_excessive_parms;
2420     }
2421   else
2422     tsk = current_tmpl_spec_kind (template_count);
2423
2424   switch (tsk)
2425     {
2426     case tsk_none:
2427       if (processing_specialization)
2428         {
2429           specialization = 1;
2430           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2431         }
2432       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2433         {
2434           if (is_friend)
2435             /* This could be something like:
2436
2437                template <class T> void f(T);
2438                class S { friend void f<>(int); }  */
2439             specialization = 1;
2440           else
2441             {
2442               /* This case handles bogus declarations like template <>
2443                  template <class T> void f<int>(); */
2444
2445               error ("template-id %qD in declaration of primary template",
2446                      declarator);
2447               return decl;
2448             }
2449         }
2450       break;
2451
2452     case tsk_invalid_member_spec:
2453       /* The error has already been reported in
2454          check_specialization_scope.  */
2455       return error_mark_node;
2456
2457     case tsk_invalid_expl_inst:
2458       error ("template parameter list used in explicit instantiation");
2459
2460       /* Fall through.  */
2461
2462     case tsk_expl_inst:
2463       if (have_def)
2464         error ("definition provided for explicit instantiation");
2465
2466       explicit_instantiation = 1;
2467       break;
2468
2469     case tsk_excessive_parms:
2470     case tsk_insufficient_parms:
2471       if (tsk == tsk_excessive_parms)
2472         error ("too many template parameter lists in declaration of %qD",
2473                decl);
2474       else if (template_header_count)
2475         error("too few template parameter lists in declaration of %qD", decl);
2476       else
2477         error("explicit specialization of %qD must be introduced by "
2478               "%<template <>%>", decl);
2479
2480       /* Fall through.  */
2481     case tsk_expl_spec:
2482       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2483         /* In cases like template<> constexpr bool v = true;
2484            We'll give an error in check_template_variable.  */
2485         break;
2486
2487       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2488       if (ctype)
2489         member_specialization = 1;
2490       else
2491         specialization = 1;
2492       break;
2493
2494     case tsk_template:
2495       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2496         {
2497           /* This case handles bogus declarations like template <>
2498              template <class T> void f<int>(); */
2499
2500           if (!uses_template_parms (declarator))
2501             error ("template-id %qD in declaration of primary template",
2502                    declarator);
2503           else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2504             {
2505               /* Partial specialization of variable template.  */
2506               SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2507               specialization = 1;
2508               goto ok;
2509             }
2510           else if (cxx_dialect < cxx14)
2511             error ("non-type partial specialization %qD "
2512                    "is not allowed", declarator);
2513           else
2514             error ("non-class, non-variable partial specialization %qD "
2515                    "is not allowed", declarator);
2516           return decl;
2517         ok:;
2518         }
2519
2520       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2521         /* This is a specialization of a member template, without
2522            specialization the containing class.  Something like:
2523
2524              template <class T> struct S {
2525                template <class U> void f (U);
2526              };
2527              template <> template <class U> void S<int>::f(U) {}
2528
2529            That's a specialization -- but of the entire template.  */
2530         specialization = 1;
2531       break;
2532
2533     default:
2534       gcc_unreachable ();
2535     }
2536
2537   if ((specialization || member_specialization)
2538       /* This doesn't apply to variable templates.  */
2539       && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2540           || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2541     {
2542       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2543       for (; t; t = TREE_CHAIN (t))
2544         if (TREE_PURPOSE (t))
2545           {
2546             permerror (input_location, 
2547                        "default argument specified in explicit specialization");
2548             break;
2549           }
2550     }
2551
2552   if (specialization || member_specialization || explicit_instantiation)
2553     {
2554       tree tmpl = NULL_TREE;
2555       tree targs = NULL_TREE;
2556       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2557
2558       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2559       if (!was_template_id)
2560         {
2561           tree fns;
2562
2563           gcc_assert (identifier_p (declarator));
2564           if (ctype)
2565             fns = dname;
2566           else
2567             {
2568               /* If there is no class context, the explicit instantiation
2569                  must be at namespace scope.  */
2570               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2571
2572               /* Find the namespace binding, using the declaration
2573                  context.  */
2574               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2575                                            false, true);
2576               if (fns == error_mark_node || !is_overloaded_fn (fns))
2577                 {
2578                   error ("%qD is not a template function", dname);
2579                   fns = error_mark_node;
2580                 }
2581               else
2582                 {
2583                   tree fn = OVL_CURRENT (fns);
2584                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2585                                                 CP_DECL_CONTEXT (fn)))
2586                     error ("%qD is not declared in %qD",
2587                            decl, current_namespace);
2588                 }
2589             }
2590
2591           declarator = lookup_template_function (fns, NULL_TREE);
2592         }
2593
2594       if (declarator == error_mark_node)
2595         return error_mark_node;
2596
2597       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2598         {
2599           if (!explicit_instantiation)
2600             /* A specialization in class scope.  This is invalid,
2601                but the error will already have been flagged by
2602                check_specialization_scope.  */
2603             return error_mark_node;
2604           else
2605             {
2606               /* It's not valid to write an explicit instantiation in
2607                  class scope, e.g.:
2608
2609                    class C { template void f(); }
2610
2611                    This case is caught by the parser.  However, on
2612                    something like:
2613
2614                    template class C { void f(); };
2615
2616                    (which is invalid) we can get here.  The error will be
2617                    issued later.  */
2618               ;
2619             }
2620
2621           return decl;
2622         }
2623       else if (ctype != NULL_TREE
2624                && (identifier_p (TREE_OPERAND (declarator, 0))))
2625         {
2626           // We'll match variable templates in start_decl.
2627           if (VAR_P (decl))
2628             return decl;
2629
2630           /* Find the list of functions in ctype that have the same
2631              name as the declared function.  */
2632           tree name = TREE_OPERAND (declarator, 0);
2633           tree fns = NULL_TREE;
2634           int idx;
2635
2636           if (constructor_name_p (name, ctype))
2637             {
2638               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2639
2640               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2641                   : !CLASSTYPE_DESTRUCTORS (ctype))
2642                 {
2643                   /* From [temp.expl.spec]:
2644
2645                      If such an explicit specialization for the member
2646                      of a class template names an implicitly-declared
2647                      special member function (clause _special_), the
2648                      program is ill-formed.
2649
2650                      Similar language is found in [temp.explicit].  */
2651                   error ("specialization of implicitly-declared special member function");
2652                   return error_mark_node;
2653                 }
2654
2655               name = is_constructor ? ctor_identifier : dtor_identifier;
2656             }
2657
2658           if (!DECL_CONV_FN_P (decl))
2659             {
2660               idx = lookup_fnfields_1 (ctype, name);
2661               if (idx >= 0)
2662                 fns = (*CLASSTYPE_METHOD_VEC (ctype))[idx];
2663             }
2664           else
2665             {
2666               vec<tree, va_gc> *methods;
2667               tree ovl;
2668
2669               /* For a type-conversion operator, we cannot do a
2670                  name-based lookup.  We might be looking for `operator
2671                  int' which will be a specialization of `operator T'.
2672                  So, we find *all* the conversion operators, and then
2673                  select from them.  */
2674               fns = NULL_TREE;
2675
2676               methods = CLASSTYPE_METHOD_VEC (ctype);
2677               if (methods)
2678                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2679                      methods->iterate (idx, &ovl);
2680                      ++idx)
2681                   {
2682                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2683                       /* There are no more conversion functions.  */
2684                       break;
2685
2686                     /* Glue all these conversion functions together
2687                        with those we already have.  */
2688                     for (; ovl; ovl = OVL_NEXT (ovl))
2689                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2690                   }
2691             }
2692
2693           if (fns == NULL_TREE)
2694             {
2695               error ("no member function %qD declared in %qT", name, ctype);
2696               return error_mark_node;
2697             }
2698           else
2699             TREE_OPERAND (declarator, 0) = fns;
2700         }
2701
2702       /* Figure out what exactly is being specialized at this point.
2703          Note that for an explicit instantiation, even one for a
2704          member function, we cannot tell apriori whether the
2705          instantiation is for a member template, or just a member
2706          function of a template class.  Even if a member template is
2707          being instantiated, the member template arguments may be
2708          elided if they can be deduced from the rest of the
2709          declaration.  */
2710       tmpl = determine_specialization (declarator, decl,
2711                                        &targs,
2712                                        member_specialization,
2713                                        template_count,
2714                                        tsk);
2715
2716       if (!tmpl || tmpl == error_mark_node)
2717         /* We couldn't figure out what this declaration was
2718            specializing.  */
2719         return error_mark_node;
2720       else
2721         {
2722           tree gen_tmpl = most_general_template (tmpl);
2723
2724           if (explicit_instantiation)
2725             {
2726               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2727                  is done by do_decl_instantiation later.  */
2728
2729               int arg_depth = TMPL_ARGS_DEPTH (targs);
2730               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2731
2732               if (arg_depth > parm_depth)
2733                 {
2734                   /* If TMPL is not the most general template (for
2735                      example, if TMPL is a friend template that is
2736                      injected into namespace scope), then there will
2737                      be too many levels of TARGS.  Remove some of them
2738                      here.  */
2739                   int i;
2740                   tree new_targs;
2741
2742                   new_targs = make_tree_vec (parm_depth);
2743                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2744                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2745                       = TREE_VEC_ELT (targs, i);
2746                   targs = new_targs;
2747                 }
2748
2749               return instantiate_template (tmpl, targs, tf_error);
2750             }
2751
2752           /* If we thought that the DECL was a member function, but it
2753              turns out to be specializing a static member function,
2754              make DECL a static member function as well.  */
2755           if (DECL_FUNCTION_TEMPLATE_P (tmpl)
2756               && DECL_STATIC_FUNCTION_P (tmpl)
2757               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2758             revert_static_member_fn (decl);
2759
2760           /* If this is a specialization of a member template of a
2761              template class, we want to return the TEMPLATE_DECL, not
2762              the specialization of it.  */
2763           if (tsk == tsk_template && !was_template_id)
2764             {
2765               tree result = DECL_TEMPLATE_RESULT (tmpl);
2766               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2767               DECL_INITIAL (result) = NULL_TREE;
2768               if (have_def)
2769                 {
2770                   tree parm;
2771                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2772                   DECL_SOURCE_LOCATION (result)
2773                     = DECL_SOURCE_LOCATION (decl);
2774                   /* We want to use the argument list specified in the
2775                      definition, not in the original declaration.  */
2776                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2777                   for (parm = DECL_ARGUMENTS (result); parm;
2778                        parm = DECL_CHAIN (parm))
2779                     DECL_CONTEXT (parm) = result;
2780                 }
2781               return register_specialization (tmpl, gen_tmpl, targs,
2782                                               is_friend, 0);
2783             }
2784
2785           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2786           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2787
2788           if (was_template_id)
2789             TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
2790
2791           /* Inherit default function arguments from the template
2792              DECL is specializing.  */
2793           if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2794             copy_default_args_to_explicit_spec (decl);
2795
2796           /* This specialization has the same protection as the
2797              template it specializes.  */
2798           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2799           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2800
2801           /* 7.1.1-1 [dcl.stc]
2802
2803              A storage-class-specifier shall not be specified in an
2804              explicit specialization...
2805
2806              The parser rejects these, so unless action is taken here,
2807              explicit function specializations will always appear with
2808              global linkage.
2809
2810              The action recommended by the C++ CWG in response to C++
2811              defect report 605 is to make the storage class and linkage
2812              of the explicit specialization match the templated function:
2813
2814              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2815            */
2816           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2817             {
2818               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2819               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2820
2821               /* This specialization has the same linkage and visibility as
2822                  the function template it specializes.  */
2823               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2824               if (! TREE_PUBLIC (decl))
2825                 {
2826                   DECL_INTERFACE_KNOWN (decl) = 1;
2827                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2828                 }
2829               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2830               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2831                 {
2832                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2833                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2834                 }
2835             }
2836
2837           /* If DECL is a friend declaration, declared using an
2838              unqualified name, the namespace associated with DECL may
2839              have been set incorrectly.  For example, in:
2840
2841                template <typename T> void f(T);
2842                namespace N {
2843                  struct S { friend void f<int>(int); }
2844                }
2845
2846              we will have set the DECL_CONTEXT for the friend
2847              declaration to N, rather than to the global namespace.  */
2848           if (DECL_NAMESPACE_SCOPE_P (decl))
2849             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2850
2851           if (is_friend && !have_def)
2852             /* This is not really a declaration of a specialization.
2853                It's just the name of an instantiation.  But, it's not
2854                a request for an instantiation, either.  */
2855             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2856           else if (TREE_CODE (decl) == FUNCTION_DECL)
2857             /* A specialization is not necessarily COMDAT.  */
2858             DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
2859                                   && DECL_DECLARED_INLINE_P (decl));
2860           else if (TREE_CODE (decl) == VAR_DECL)
2861             DECL_COMDAT (decl) = false;
2862
2863           /* Register this specialization so that we can find it
2864              again.  */
2865           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2866
2867           /* A 'structor should already have clones.  */
2868           gcc_assert (decl == error_mark_node
2869                       || variable_template_p (tmpl)
2870                       || !(DECL_CONSTRUCTOR_P (decl)
2871                            || DECL_DESTRUCTOR_P (decl))
2872                       || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
2873         }
2874     }
2875
2876   return decl;
2877 }
2878
2879 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2880    parameters.  These are represented in the same format used for
2881    DECL_TEMPLATE_PARMS.  */
2882
2883 int
2884 comp_template_parms (const_tree parms1, const_tree parms2)
2885 {
2886   const_tree p1;
2887   const_tree p2;
2888
2889   if (parms1 == parms2)
2890     return 1;
2891
2892   for (p1 = parms1, p2 = parms2;
2893        p1 != NULL_TREE && p2 != NULL_TREE;
2894        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2895     {
2896       tree t1 = TREE_VALUE (p1);
2897       tree t2 = TREE_VALUE (p2);
2898       int i;
2899
2900       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2901       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2902
2903       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2904         return 0;
2905
2906       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2907         {
2908           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2909           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2910
2911           /* If either of the template parameters are invalid, assume
2912              they match for the sake of error recovery. */
2913           if (error_operand_p (parm1) || error_operand_p (parm2))
2914             return 1;
2915
2916           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2917             return 0;
2918
2919           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2920               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2921                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2922             continue;
2923           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2924             return 0;
2925         }
2926     }
2927
2928   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2929     /* One set of parameters has more parameters lists than the
2930        other.  */
2931     return 0;
2932
2933   return 1;
2934 }
2935
2936 /* Determine whether PARM is a parameter pack.  */
2937
2938 bool 
2939 template_parameter_pack_p (const_tree parm)
2940 {
2941   /* Determine if we have a non-type template parameter pack.  */
2942   if (TREE_CODE (parm) == PARM_DECL)
2943     return (DECL_TEMPLATE_PARM_P (parm) 
2944             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2945   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2946     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2947
2948   /* If this is a list of template parameters, we could get a
2949      TYPE_DECL or a TEMPLATE_DECL.  */ 
2950   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2951     parm = TREE_TYPE (parm);
2952
2953   /* Otherwise it must be a type template parameter.  */
2954   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2955            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2956           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2957 }
2958
2959 /* Determine if T is a function parameter pack.  */
2960
2961 bool
2962 function_parameter_pack_p (const_tree t)
2963 {
2964   if (t && TREE_CODE (t) == PARM_DECL)
2965     return DECL_PACK_P (t);
2966   return false;
2967 }
2968
2969 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2970    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2971
2972 tree
2973 get_function_template_decl (const_tree primary_func_tmpl_inst)
2974 {
2975   if (! primary_func_tmpl_inst
2976       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2977       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2978     return NULL;
2979
2980   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2981 }
2982
2983 /* Return true iff the function parameter PARAM_DECL was expanded
2984    from the function parameter pack PACK.  */
2985
2986 bool
2987 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2988 {
2989   if (DECL_ARTIFICIAL (param_decl)
2990       || !function_parameter_pack_p (pack))
2991     return false;
2992
2993   /* The parameter pack and its pack arguments have the same
2994      DECL_PARM_INDEX.  */
2995   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2996 }
2997
2998 /* Determine whether ARGS describes a variadic template args list,
2999    i.e., one that is terminated by a template argument pack.  */
3000
3001 static bool 
3002 template_args_variadic_p (tree args)
3003 {
3004   int nargs;
3005   tree last_parm;
3006
3007   if (args == NULL_TREE)
3008     return false;
3009
3010   args = INNERMOST_TEMPLATE_ARGS (args);
3011   nargs = TREE_VEC_LENGTH (args);
3012
3013   if (nargs == 0)
3014     return false;
3015
3016   last_parm = TREE_VEC_ELT (args, nargs - 1);
3017
3018   return ARGUMENT_PACK_P (last_parm);
3019 }
3020
3021 /* Generate a new name for the parameter pack name NAME (an
3022    IDENTIFIER_NODE) that incorporates its */
3023
3024 static tree
3025 make_ith_pack_parameter_name (tree name, int i)
3026 {
3027   /* Munge the name to include the parameter index.  */
3028 #define NUMBUF_LEN 128
3029   char numbuf[NUMBUF_LEN];
3030   char* newname;
3031   int newname_len;
3032
3033   if (name == NULL_TREE)
3034     return name;
3035   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3036   newname_len = IDENTIFIER_LENGTH (name)
3037                 + strlen (numbuf) + 2;
3038   newname = (char*)alloca (newname_len);
3039   snprintf (newname, newname_len,
3040             "%s#%i", IDENTIFIER_POINTER (name), i);
3041   return get_identifier (newname);
3042 }
3043
3044 /* Return true if T is a primary function, class or alias template
3045    instantiation.  */
3046
3047 bool
3048 primary_template_instantiation_p (const_tree t)
3049 {
3050   if (!t)
3051     return false;
3052
3053   if (TREE_CODE (t) == FUNCTION_DECL)
3054     return DECL_LANG_SPECIFIC (t)
3055            && DECL_TEMPLATE_INSTANTIATION (t)
3056            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
3057   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3058     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
3059            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
3060   else if (alias_template_specialization_p (t))
3061     return true;
3062   return false;
3063 }
3064
3065 /* Return true if PARM is a template template parameter.  */
3066
3067 bool
3068 template_template_parameter_p (const_tree parm)
3069 {
3070   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3071 }
3072
3073 /* Return true iff PARM is a DECL representing a type template
3074    parameter.  */
3075
3076 bool
3077 template_type_parameter_p (const_tree parm)
3078 {
3079   return (parm
3080           && (TREE_CODE (parm) == TYPE_DECL
3081               || TREE_CODE (parm) == TEMPLATE_DECL)
3082           && DECL_TEMPLATE_PARM_P (parm));
3083 }
3084
3085 /* Return the template parameters of T if T is a
3086    primary template instantiation, NULL otherwise.  */
3087
3088 tree
3089 get_primary_template_innermost_parameters (const_tree t)
3090 {
3091   tree parms = NULL, template_info = NULL;
3092
3093   if ((template_info = get_template_info (t))
3094       && primary_template_instantiation_p (t))
3095     parms = INNERMOST_TEMPLATE_PARMS
3096         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3097
3098   return parms;
3099 }
3100
3101 /* Return the template parameters of the LEVELth level from the full list
3102    of template parameters PARMS.  */
3103
3104 tree
3105 get_template_parms_at_level (tree parms, int level)
3106 {
3107   tree p;
3108   if (!parms
3109       || TREE_CODE (parms) != TREE_LIST
3110       || level > TMPL_PARMS_DEPTH (parms))
3111     return NULL_TREE;
3112
3113   for (p = parms; p; p = TREE_CHAIN (p))
3114     if (TMPL_PARMS_DEPTH (p) == level)
3115       return p;
3116
3117   return NULL_TREE;
3118 }
3119
3120 /* Returns the template arguments of T if T is a template instantiation,
3121    NULL otherwise.  */
3122
3123 tree
3124 get_template_innermost_arguments (const_tree t)
3125 {
3126   tree args = NULL, template_info = NULL;
3127
3128   if ((template_info = get_template_info (t))
3129       && TI_ARGS (template_info))
3130     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3131
3132   return args;
3133 }
3134
3135 /* Return the argument pack elements of T if T is a template argument pack,
3136    NULL otherwise.  */
3137
3138 tree
3139 get_template_argument_pack_elems (const_tree t)
3140 {
3141   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3142       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3143     return NULL;
3144
3145   return ARGUMENT_PACK_ARGS (t);
3146 }
3147
3148 /* Structure used to track the progress of find_parameter_packs_r.  */
3149 struct find_parameter_pack_data 
3150 {
3151   /* TREE_LIST that will contain all of the parameter packs found by
3152      the traversal.  */
3153   tree* parameter_packs;
3154
3155   /* Set of AST nodes that have been visited by the traversal.  */
3156   hash_set<tree> *visited;
3157 };
3158
3159 /* Identifies all of the argument packs that occur in a template
3160    argument and appends them to the TREE_LIST inside DATA, which is a
3161    find_parameter_pack_data structure. This is a subroutine of
3162    make_pack_expansion and uses_parameter_packs.  */
3163 static tree
3164 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3165 {
3166   tree t = *tp;
3167   struct find_parameter_pack_data* ppd = 
3168     (struct find_parameter_pack_data*)data;
3169   bool parameter_pack_p = false;
3170
3171   /* Handle type aliases/typedefs.  */
3172   if (TYPE_ALIAS_P (t))
3173     {
3174       if (TYPE_TEMPLATE_INFO (t))
3175         cp_walk_tree (&TYPE_TI_ARGS (t),
3176                       &find_parameter_packs_r,
3177                       ppd, ppd->visited);
3178       *walk_subtrees = 0;
3179       return NULL_TREE;
3180     }
3181
3182   /* Identify whether this is a parameter pack or not.  */
3183   switch (TREE_CODE (t))
3184     {
3185     case TEMPLATE_PARM_INDEX:
3186       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3187         parameter_pack_p = true;
3188       break;
3189
3190     case TEMPLATE_TYPE_PARM:
3191       t = TYPE_MAIN_VARIANT (t);
3192     case TEMPLATE_TEMPLATE_PARM:
3193       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3194         parameter_pack_p = true;
3195       break;
3196
3197     case FIELD_DECL:
3198     case PARM_DECL:
3199       if (DECL_PACK_P (t))
3200         {
3201           /* We don't want to walk into the type of a PARM_DECL,
3202              because we don't want to see the type parameter pack.  */
3203           *walk_subtrees = 0;
3204           parameter_pack_p = true;
3205         }
3206       break;
3207
3208       /* Look through a lambda capture proxy to the field pack.  */
3209     case VAR_DECL:
3210       if (DECL_HAS_VALUE_EXPR_P (t))
3211         {
3212           tree v = DECL_VALUE_EXPR (t);
3213           cp_walk_tree (&v,
3214                         &find_parameter_packs_r,
3215                         ppd, ppd->visited);
3216           *walk_subtrees = 0;
3217         }
3218       break;
3219
3220     case BASES:
3221       parameter_pack_p = true;
3222       break;
3223     default:
3224       /* Not a parameter pack.  */
3225       break;
3226     }
3227
3228   if (parameter_pack_p)
3229     {
3230       /* Add this parameter pack to the list.  */
3231       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3232     }
3233
3234   if (TYPE_P (t))
3235     cp_walk_tree (&TYPE_CONTEXT (t), 
3236                   &find_parameter_packs_r, ppd, ppd->visited);
3237
3238   /* This switch statement will return immediately if we don't find a
3239      parameter pack.  */
3240   switch (TREE_CODE (t)) 
3241     {
3242     case TEMPLATE_PARM_INDEX:
3243       return NULL_TREE;
3244
3245     case BOUND_TEMPLATE_TEMPLATE_PARM:
3246       /* Check the template itself.  */
3247       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3248                     &find_parameter_packs_r, ppd, ppd->visited);
3249       /* Check the template arguments.  */
3250       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3251                     ppd->visited);
3252       *walk_subtrees = 0;
3253       return NULL_TREE;
3254
3255     case TEMPLATE_TYPE_PARM:
3256     case TEMPLATE_TEMPLATE_PARM:
3257       return NULL_TREE;
3258
3259     case PARM_DECL:
3260       return NULL_TREE;
3261
3262     case RECORD_TYPE:
3263       if (TYPE_PTRMEMFUNC_P (t))
3264         return NULL_TREE;
3265       /* Fall through.  */
3266
3267     case UNION_TYPE:
3268     case ENUMERAL_TYPE:
3269       if (TYPE_TEMPLATE_INFO (t))
3270         cp_walk_tree (&TYPE_TI_ARGS (t),
3271                       &find_parameter_packs_r, ppd, ppd->visited);
3272
3273       *walk_subtrees = 0;
3274       return NULL_TREE;
3275
3276     case CONSTRUCTOR:
3277     case TEMPLATE_DECL:
3278       cp_walk_tree (&TREE_TYPE (t),
3279                     &find_parameter_packs_r, ppd, ppd->visited);
3280       return NULL_TREE;
3281  
3282     case TYPENAME_TYPE:
3283       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3284                    ppd, ppd->visited);
3285       *walk_subtrees = 0;
3286       return NULL_TREE;
3287       
3288     case TYPE_PACK_EXPANSION:
3289     case EXPR_PACK_EXPANSION:
3290       *walk_subtrees = 0;
3291       return NULL_TREE;
3292
3293     case INTEGER_TYPE:
3294       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3295                     ppd, ppd->visited);
3296       *walk_subtrees = 0;
3297       return NULL_TREE;
3298
3299     case IDENTIFIER_NODE:
3300       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3301                     ppd->visited);
3302       *walk_subtrees = 0;
3303       return NULL_TREE;
3304
3305     default:
3306       return NULL_TREE;
3307     }
3308
3309   return NULL_TREE;
3310 }
3311
3312 /* Determines if the expression or type T uses any parameter packs.  */
3313 bool
3314 uses_parameter_packs (tree t)
3315 {
3316   tree parameter_packs = NULL_TREE;
3317   struct find_parameter_pack_data ppd;
3318   ppd.parameter_packs = &parameter_packs;
3319   ppd.visited = new hash_set<tree>;
3320   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3321   delete ppd.visited;
3322   return parameter_packs != NULL_TREE;
3323 }
3324
3325 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3326    representation a base-class initializer into a parameter pack
3327    expansion. If all goes well, the resulting node will be an
3328    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3329    respectively.  */
3330 tree 
3331 make_pack_expansion (tree arg)
3332 {
3333   tree result;
3334   tree parameter_packs = NULL_TREE;
3335   bool for_types = false;
3336   struct find_parameter_pack_data ppd;
3337
3338   if (!arg || arg == error_mark_node)
3339     return arg;
3340
3341   if (TREE_CODE (arg) == TREE_LIST)
3342     {
3343       /* The only time we will see a TREE_LIST here is for a base
3344          class initializer.  In this case, the TREE_PURPOSE will be a
3345          _TYPE node (representing the base class expansion we're
3346          initializing) and the TREE_VALUE will be a TREE_LIST
3347          containing the initialization arguments. 
3348
3349          The resulting expansion looks somewhat different from most
3350          expansions. Rather than returning just one _EXPANSION, we
3351          return a TREE_LIST whose TREE_PURPOSE is a
3352          TYPE_PACK_EXPANSION containing the bases that will be
3353          initialized.  The TREE_VALUE will be identical to the
3354          original TREE_VALUE, which is a list of arguments that will
3355          be passed to each base.  We do not introduce any new pack
3356          expansion nodes into the TREE_VALUE (although it is possible
3357          that some already exist), because the TREE_PURPOSE and
3358          TREE_VALUE all need to be expanded together with the same
3359          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3360          resulting TREE_PURPOSE will mention the parameter packs in
3361          both the bases and the arguments to the bases.  */
3362       tree purpose;
3363       tree value;
3364       tree parameter_packs = NULL_TREE;
3365
3366       /* Determine which parameter packs will be used by the base
3367          class expansion.  */
3368       ppd.visited = new hash_set<tree>;
3369       ppd.parameter_packs = &parameter_packs;
3370       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3371                     &ppd, ppd.visited);
3372
3373       if (parameter_packs == NULL_TREE)
3374         {
3375           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3376           delete ppd.visited;
3377           return error_mark_node;
3378         }
3379
3380       if (TREE_VALUE (arg) != void_type_node)
3381         {
3382           /* Collect the sets of parameter packs used in each of the
3383              initialization arguments.  */
3384           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3385             {
3386               /* Determine which parameter packs will be expanded in this
3387                  argument.  */
3388               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3389                             &ppd, ppd.visited);
3390             }
3391         }
3392
3393       delete ppd.visited;
3394
3395       /* Create the pack expansion type for the base type.  */
3396       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3397       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3398       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3399
3400       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3401          they will rarely be compared to anything.  */
3402       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3403
3404       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3405     }
3406
3407   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3408     for_types = true;
3409
3410   /* Build the PACK_EXPANSION_* node.  */
3411   result = for_types
3412      ? cxx_make_type (TYPE_PACK_EXPANSION)
3413      : make_node (EXPR_PACK_EXPANSION);
3414   SET_PACK_EXPANSION_PATTERN (result, arg);
3415   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3416     {
3417       /* Propagate type and const-expression information.  */
3418       TREE_TYPE (result) = TREE_TYPE (arg);
3419       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3420     }
3421   else
3422     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3423        they will rarely be compared to anything.  */
3424     SET_TYPE_STRUCTURAL_EQUALITY (result);
3425
3426   /* Determine which parameter packs will be expanded.  */
3427   ppd.parameter_packs = &parameter_packs;
3428   ppd.visited = new hash_set<tree>;
3429   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3430   delete ppd.visited;
3431
3432   /* Make sure we found some parameter packs.  */
3433   if (parameter_packs == NULL_TREE)
3434     {
3435       if (TYPE_P (arg))
3436         error ("expansion pattern %<%T%> contains no argument packs", arg);
3437       else
3438         error ("expansion pattern %<%E%> contains no argument packs", arg);
3439       return error_mark_node;
3440     }
3441   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3442
3443   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
3444
3445   return result;
3446 }
3447
3448 /* Checks T for any "bare" parameter packs, which have not yet been
3449    expanded, and issues an error if any are found. This operation can
3450    only be done on full expressions or types (e.g., an expression
3451    statement, "if" condition, etc.), because we could have expressions like:
3452
3453      foo(f(g(h(args)))...)
3454
3455    where "args" is a parameter pack. check_for_bare_parameter_packs
3456    should not be called for the subexpressions args, h(args),
3457    g(h(args)), or f(g(h(args))), because we would produce erroneous
3458    error messages. 
3459
3460    Returns TRUE and emits an error if there were bare parameter packs,
3461    returns FALSE otherwise.  */
3462 bool 
3463 check_for_bare_parameter_packs (tree t)
3464 {
3465   tree parameter_packs = NULL_TREE;
3466   struct find_parameter_pack_data ppd;
3467
3468   if (!processing_template_decl || !t || t == error_mark_node)
3469     return false;
3470
3471   if (TREE_CODE (t) == TYPE_DECL)
3472     t = TREE_TYPE (t);
3473
3474   ppd.parameter_packs = &parameter_packs;
3475   ppd.visited = new hash_set<tree>;
3476   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3477   delete ppd.visited;
3478
3479   if (parameter_packs) 
3480     {
3481       error ("parameter packs not expanded with %<...%>:");
3482       while (parameter_packs)
3483         {
3484           tree pack = TREE_VALUE (parameter_packs);
3485           tree name = NULL_TREE;
3486
3487           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3488               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3489             name = TYPE_NAME (pack);
3490           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3491             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3492           else
3493             name = DECL_NAME (pack);
3494
3495           if (name)
3496             inform (input_location, "        %qD", name);
3497           else
3498             inform (input_location, "        <anonymous>");
3499
3500           parameter_packs = TREE_CHAIN (parameter_packs);
3501         }
3502
3503       return true;
3504     }
3505
3506   return false;
3507 }
3508
3509 /* Expand any parameter packs that occur in the template arguments in
3510    ARGS.  */
3511 tree
3512 expand_template_argument_pack (tree args)
3513 {
3514   tree result_args = NULL_TREE;
3515   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3516   int num_result_args = -1;
3517   int non_default_args_count = -1;
3518
3519   /* First, determine if we need to expand anything, and the number of
3520      slots we'll need.  */
3521   for (in_arg = 0; in_arg < nargs; ++in_arg)
3522     {
3523       tree arg = TREE_VEC_ELT (args, in_arg);
3524       if (arg == NULL_TREE)
3525         return args;
3526       if (ARGUMENT_PACK_P (arg))
3527         {
3528           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3529           if (num_result_args < 0)
3530             num_result_args = in_arg + num_packed;
3531           else
3532             num_result_args += num_packed;
3533         }
3534       else
3535         {
3536           if (num_result_args >= 0)
3537             num_result_args++;
3538         }
3539     }
3540
3541   /* If no expansion is necessary, we're done.  */
3542   if (num_result_args < 0)
3543     return args;
3544
3545   /* Expand arguments.  */
3546   result_args = make_tree_vec (num_result_args);
3547   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3548     non_default_args_count =
3549       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3550   for (in_arg = 0; in_arg < nargs; ++in_arg)
3551     {
3552       tree arg = TREE_VEC_ELT (args, in_arg);
3553       if (ARGUMENT_PACK_P (arg))
3554         {
3555           tree packed = ARGUMENT_PACK_ARGS (arg);
3556           int i, num_packed = TREE_VEC_LENGTH (packed);
3557           for (i = 0; i < num_packed; ++i, ++out_arg)
3558             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3559           if (non_default_args_count > 0)
3560             non_default_args_count += num_packed - 1;
3561         }
3562       else
3563         {
3564           TREE_VEC_ELT (result_args, out_arg) = arg;
3565           ++out_arg;
3566         }
3567     }
3568   if (non_default_args_count >= 0)
3569     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3570   return result_args;
3571 }
3572
3573 /* Checks if DECL shadows a template parameter.
3574
3575    [temp.local]: A template-parameter shall not be redeclared within its
3576    scope (including nested scopes).
3577
3578    Emits an error and returns TRUE if the DECL shadows a parameter,
3579    returns FALSE otherwise.  */
3580
3581 bool
3582 check_template_shadow (tree decl)
3583 {
3584   tree olddecl;
3585
3586   /* If we're not in a template, we can't possibly shadow a template
3587      parameter.  */
3588   if (!current_template_parms)
3589     return true;
3590
3591   /* Figure out what we're shadowing.  */
3592   if (TREE_CODE (decl) == OVERLOAD)
3593     decl = OVL_CURRENT (decl);
3594   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3595
3596   /* If there's no previous binding for this name, we're not shadowing
3597      anything, let alone a template parameter.  */
3598   if (!olddecl)
3599     return true;
3600
3601   /* If we're not shadowing a template parameter, we're done.  Note
3602      that OLDDECL might be an OVERLOAD (or perhaps even an
3603      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3604      node.  */
3605   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3606     return true;
3607
3608   /* We check for decl != olddecl to avoid bogus errors for using a
3609      name inside a class.  We check TPFI to avoid duplicate errors for
3610      inline member templates.  */
3611   if (decl == olddecl
3612       || (DECL_TEMPLATE_PARM_P (decl)
3613           && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
3614     return true;
3615
3616   /* Don't complain about the injected class name, as we've already
3617      complained about the class itself.  */
3618   if (DECL_SELF_REFERENCE_P (decl))
3619     return false;
3620
3621   error ("declaration of %q+#D", decl);
3622   error (" shadows template parm %q+#D", olddecl);
3623   return false;
3624 }
3625
3626 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3627    ORIG_LEVEL, DECL, and TYPE.  */
3628
3629 static tree
3630 build_template_parm_index (int index,
3631                            int level,
3632                            int orig_level,
3633                            tree decl,
3634                            tree type)
3635 {
3636   tree t = make_node (TEMPLATE_PARM_INDEX);
3637   TEMPLATE_PARM_IDX (t) = index;
3638   TEMPLATE_PARM_LEVEL (t) = level;
3639   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3640   TEMPLATE_PARM_DECL (t) = decl;
3641   TREE_TYPE (t) = type;
3642   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3643   TREE_READONLY (t) = TREE_READONLY (decl);
3644
3645   return t;
3646 }
3647
3648 /* Find the canonical type parameter for the given template type
3649    parameter.  Returns the canonical type parameter, which may be TYPE
3650    if no such parameter existed.  */
3651
3652 static tree
3653 canonical_type_parameter (tree type)
3654 {
3655   tree list;
3656   int idx = TEMPLATE_TYPE_IDX (type);
3657   if (!canonical_template_parms)
3658     vec_alloc (canonical_template_parms, idx+1);
3659
3660   while (canonical_template_parms->length () <= (unsigned)idx)
3661     vec_safe_push (canonical_template_parms, NULL_TREE);
3662
3663   list = (*canonical_template_parms)[idx];
3664   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3665     list = TREE_CHAIN (list);
3666
3667   if (list)
3668     return TREE_VALUE (list);
3669   else
3670     {
3671       (*canonical_template_parms)[idx]
3672                 = tree_cons (NULL_TREE, type,
3673                              (*canonical_template_parms)[idx]);
3674       return type;
3675     }
3676 }
3677
3678 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3679    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3680    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3681    new one is created.  */
3682
3683 static tree
3684 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3685                             tsubst_flags_t complain)
3686 {
3687   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3688       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3689           != TEMPLATE_PARM_LEVEL (index) - levels)
3690       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3691     {
3692       tree orig_decl = TEMPLATE_PARM_DECL (index);
3693       tree decl, t;
3694
3695       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3696                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3697       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3698       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3699       DECL_ARTIFICIAL (decl) = 1;
3700       SET_DECL_TEMPLATE_PARM_P (decl);
3701
3702       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3703                                      TEMPLATE_PARM_LEVEL (index) - levels,
3704                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3705                                      decl, type);
3706       TEMPLATE_PARM_DESCENDANTS (index) = t;
3707       TEMPLATE_PARM_PARAMETER_PACK (t) 
3708         = TEMPLATE_PARM_PARAMETER_PACK (index);
3709
3710         /* Template template parameters need this.  */
3711       if (TREE_CODE (decl) == TEMPLATE_DECL)
3712         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3713           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3714            args, complain);
3715     }
3716
3717   return TEMPLATE_PARM_DESCENDANTS (index);
3718 }
3719
3720 /* Process information from new template parameter PARM and append it
3721    to the LIST being built.  This new parameter is a non-type
3722    parameter iff IS_NON_TYPE is true. This new parameter is a
3723    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3724    is in PARM_LOC.  */
3725
3726 tree
3727 process_template_parm (tree list, location_t parm_loc, tree parm,
3728                        bool is_non_type, bool is_parameter_pack)
3729 {
3730   tree decl = 0;
3731   tree defval;
3732   int idx = 0;
3733
3734   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3735   defval = TREE_PURPOSE (parm);
3736
3737   if (list)
3738     {
3739       tree p = tree_last (list);
3740
3741       if (p && TREE_VALUE (p) != error_mark_node)
3742         {
3743           p = TREE_VALUE (p);
3744           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3745             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3746           else
3747             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3748         }
3749
3750       ++idx;
3751     }
3752
3753   if (is_non_type)
3754     {
3755       parm = TREE_VALUE (parm);
3756
3757       SET_DECL_TEMPLATE_PARM_P (parm);
3758
3759       if (TREE_TYPE (parm) != error_mark_node)
3760         {
3761           /* [temp.param]
3762
3763              The top-level cv-qualifiers on the template-parameter are
3764              ignored when determining its type.  */
3765           TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3766           if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3767             TREE_TYPE (parm) = error_mark_node;
3768           else if (uses_parameter_packs (TREE_TYPE (parm))
3769                    && !is_parameter_pack
3770                    /* If we're in a nested template parameter list, the template
3771                       template parameter could be a parameter pack.  */
3772                    && processing_template_parmlist == 1)
3773             {
3774               /* This template parameter is not a parameter pack, but it
3775                  should be. Complain about "bare" parameter packs.  */
3776               check_for_bare_parameter_packs (TREE_TYPE (parm));
3777
3778               /* Recover by calling this a parameter pack.  */
3779               is_parameter_pack = true;
3780             }
3781         }
3782
3783       /* A template parameter is not modifiable.  */
3784       TREE_CONSTANT (parm) = 1;
3785       TREE_READONLY (parm) = 1;
3786       decl = build_decl (parm_loc,
3787                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3788       TREE_CONSTANT (decl) = 1;
3789       TREE_READONLY (decl) = 1;
3790       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3791         = build_template_parm_index (idx, processing_template_decl,
3792                                      processing_template_decl,
3793                                      decl, TREE_TYPE (parm));
3794
3795       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3796         = is_parameter_pack;
3797     }
3798   else
3799     {
3800       tree t;
3801       parm = TREE_VALUE (TREE_VALUE (parm));
3802
3803       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3804         {
3805           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3806           /* This is for distinguishing between real templates and template
3807              template parameters */
3808           TREE_TYPE (parm) = t;
3809           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3810           decl = parm;
3811         }
3812       else
3813         {
3814           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3815           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3816           decl = build_decl (parm_loc,
3817                              TYPE_DECL, parm, t);
3818         }
3819
3820       TYPE_NAME (t) = decl;
3821       TYPE_STUB_DECL (t) = decl;
3822       parm = decl;
3823       TEMPLATE_TYPE_PARM_INDEX (t)
3824         = build_template_parm_index (idx, processing_template_decl,
3825                                      processing_template_decl,
3826                                      decl, TREE_TYPE (parm));
3827       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3828       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3829     }
3830   DECL_ARTIFICIAL (decl) = 1;
3831   SET_DECL_TEMPLATE_PARM_P (decl);
3832   pushdecl (decl);
3833   parm = build_tree_list (defval, parm);
3834   return chainon (list, parm);
3835 }
3836
3837 /* The end of a template parameter list has been reached.  Process the
3838    tree list into a parameter vector, converting each parameter into a more
3839    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3840    as PARM_DECLs.  */
3841
3842 tree
3843 end_template_parm_list (tree parms)
3844 {
3845   int nparms;
3846   tree parm, next;
3847   tree saved_parmlist = make_tree_vec (list_length (parms));
3848
3849   current_template_parms
3850     = tree_cons (size_int (processing_template_decl),
3851                  saved_parmlist, current_template_parms);
3852
3853   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3854     {
3855       next = TREE_CHAIN (parm);
3856       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3857       TREE_CHAIN (parm) = NULL_TREE;
3858     }
3859
3860   --processing_template_parmlist;
3861
3862   return saved_parmlist;
3863 }
3864
3865 /* end_template_decl is called after a template declaration is seen.  */
3866
3867 void
3868 end_template_decl (void)
3869 {
3870   reset_specialization ();
3871
3872   if (! processing_template_decl)
3873     return;
3874
3875   /* This matches the pushlevel in begin_template_parm_list.  */
3876   finish_scope ();
3877
3878   --processing_template_decl;
3879   current_template_parms = TREE_CHAIN (current_template_parms);
3880 }
3881
3882 /* Takes a TREE_LIST representing a template parameter and convert it
3883    into an argument suitable to be passed to the type substitution
3884    functions.  Note that If the TREE_LIST contains an error_mark
3885    node, the returned argument is error_mark_node.  */
3886
3887 static tree
3888 template_parm_to_arg (tree t)
3889 {
3890
3891   if (t == NULL_TREE
3892       || TREE_CODE (t) != TREE_LIST)
3893     return t;
3894
3895   if (error_operand_p (TREE_VALUE (t)))
3896     return error_mark_node;
3897
3898   t = TREE_VALUE (t);
3899
3900   if (TREE_CODE (t) == TYPE_DECL
3901       || TREE_CODE (t) == TEMPLATE_DECL)
3902     {
3903       t = TREE_TYPE (t);
3904
3905       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3906         {
3907           /* Turn this argument into a TYPE_ARGUMENT_PACK
3908              with a single element, which expands T.  */
3909           tree vec = make_tree_vec (1);
3910 #ifdef ENABLE_CHECKING
3911           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3912             (vec, TREE_VEC_LENGTH (vec));
3913 #endif
3914           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3915
3916           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3917           SET_ARGUMENT_PACK_ARGS (t, vec);
3918         }
3919     }
3920   else
3921     {
3922       t = DECL_INITIAL (t);
3923
3924       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3925         {
3926           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3927              with a single element, which expands T.  */
3928           tree vec = make_tree_vec (1);
3929           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3930 #ifdef ENABLE_CHECKING
3931           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3932             (vec, TREE_VEC_LENGTH (vec));
3933 #endif
3934           t = convert_from_reference (t);
3935           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3936
3937           t  = make_node (NONTYPE_ARGUMENT_PACK);
3938           SET_ARGUMENT_PACK_ARGS (t, vec);
3939           TREE_TYPE (t) = type;
3940         }
3941       else
3942         t = convert_from_reference (t);
3943     }
3944   return t;
3945 }
3946
3947 /* Given a set of template parameters, return them as a set of template
3948    arguments.  The template parameters are represented as a TREE_VEC, in
3949    the form documented in cp-tree.h for template arguments.  */
3950
3951 static tree
3952 template_parms_to_args (tree parms)
3953 {
3954   tree header;
3955   tree args = NULL_TREE;
3956   int length = TMPL_PARMS_DEPTH (parms);
3957   int l = length;
3958
3959   /* If there is only one level of template parameters, we do not
3960      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3961      TREE_VEC containing the arguments.  */
3962   if (length > 1)
3963     args = make_tree_vec (length);
3964
3965   for (header = parms; header; header = TREE_CHAIN (header))
3966     {
3967       tree a = copy_node (TREE_VALUE (header));
3968       int i;
3969
3970       TREE_TYPE (a) = NULL_TREE;
3971       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3972         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
3973
3974 #ifdef ENABLE_CHECKING
3975       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3976 #endif
3977
3978       if (length > 1)
3979         TREE_VEC_ELT (args, --l) = a;
3980       else
3981         args = a;
3982     }
3983
3984     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
3985       /* This can happen for template parms of a template template
3986          parameter, e.g:
3987
3988          template<template<class T, class U> class TT> struct S;
3989
3990          Consider the level of the parms of TT; T and U both have
3991          level 2; TT has no template parm of level 1. So in this case
3992          the first element of full_template_args is NULL_TREE. If we
3993          leave it like this TMPL_ARGS_DEPTH on args returns 1 instead
3994          of 2. This will make tsubst wrongly consider that T and U
3995          have level 1. Instead, let's create a dummy vector as the
3996          first element of full_template_args so that TMPL_ARGS_DEPTH
3997          returns the correct depth for args.  */
3998       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
3999   return args;
4000 }
4001
4002 /* Within the declaration of a template, return the currently active
4003    template parameters as an argument TREE_VEC.  */
4004
4005 static tree
4006 current_template_args (void)
4007 {
4008   return template_parms_to_args (current_template_parms);
4009 }
4010
4011 /* Update the declared TYPE by doing any lookups which were thought to be
4012    dependent, but are not now that we know the SCOPE of the declarator.  */
4013
4014 tree
4015 maybe_update_decl_type (tree orig_type, tree scope)
4016 {
4017   tree type = orig_type;
4018
4019   if (type == NULL_TREE)
4020     return type;
4021
4022   if (TREE_CODE (orig_type) == TYPE_DECL)
4023     type = TREE_TYPE (type);
4024
4025   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4026       && dependent_type_p (type)
4027       /* Don't bother building up the args in this case.  */
4028       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4029     {
4030       /* tsubst in the args corresponding to the template parameters,
4031          including auto if present.  Most things will be unchanged, but
4032          make_typename_type and tsubst_qualified_id will resolve
4033          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4034       tree args = current_template_args ();
4035       tree auto_node = type_uses_auto (type);
4036       tree pushed;
4037       if (auto_node)
4038         {
4039           tree auto_vec = make_tree_vec (1);
4040           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4041           args = add_to_template_args (args, auto_vec);
4042         }
4043       pushed = push_scope (scope);
4044       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4045       if (pushed)
4046         pop_scope (scope);
4047     }
4048
4049   if (type == error_mark_node)
4050     return orig_type;
4051
4052   if (TREE_CODE (orig_type) == TYPE_DECL)
4053     {
4054       if (same_type_p (type, TREE_TYPE (orig_type)))
4055         type = orig_type;
4056       else
4057         type = TYPE_NAME (type);
4058     }
4059   return type;
4060 }
4061
4062 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4063    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4064    a member template.  Used by push_template_decl below.  */
4065
4066 static tree
4067 build_template_decl (tree decl, tree parms, bool member_template_p)
4068 {
4069   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4070   DECL_TEMPLATE_PARMS (tmpl) = parms;
4071   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4072   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4073   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4074
4075   return tmpl;
4076 }
4077
4078 struct template_parm_data
4079 {
4080   /* The level of the template parameters we are currently
4081      processing.  */
4082   int level;
4083
4084   /* The index of the specialization argument we are currently
4085      processing.  */
4086   int current_arg;
4087
4088   /* An array whose size is the number of template parameters.  The
4089      elements are nonzero if the parameter has been used in any one
4090      of the arguments processed so far.  */
4091   int* parms;
4092
4093   /* An array whose size is the number of template arguments.  The
4094      elements are nonzero if the argument makes use of template
4095      parameters of this level.  */
4096   int* arg_uses_template_parms;
4097 };
4098
4099 /* Subroutine of push_template_decl used to see if each template
4100    parameter in a partial specialization is used in the explicit
4101    argument list.  If T is of the LEVEL given in DATA (which is
4102    treated as a template_parm_data*), then DATA->PARMS is marked
4103    appropriately.  */
4104
4105 static int
4106 mark_template_parm (tree t, void* data)
4107 {
4108   int level;
4109   int idx;
4110   struct template_parm_data* tpd = (struct template_parm_data*) data;
4111
4112   template_parm_level_and_index (t, &level, &idx);
4113
4114   if (level == tpd->level)
4115     {
4116       tpd->parms[idx] = 1;
4117       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4118     }
4119
4120   /* Return zero so that for_each_template_parm will continue the
4121      traversal of the tree; we want to mark *every* template parm.  */
4122   return 0;
4123 }
4124
4125 /* Process the partial specialization DECL.  */
4126
4127 static tree
4128 process_partial_specialization (tree decl)
4129 {
4130   tree type = TREE_TYPE (decl);
4131   tree tinfo = get_template_info (decl);
4132   tree maintmpl = TI_TEMPLATE (tinfo);
4133   tree specargs = TI_ARGS (tinfo);
4134   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4135   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4136   tree inner_parms;
4137   tree inst;
4138   int nargs = TREE_VEC_LENGTH (inner_args);
4139   int ntparms;
4140   int  i;
4141   bool did_error_intro = false;
4142   struct template_parm_data tpd;
4143   struct template_parm_data tpd2;
4144
4145   gcc_assert (current_template_parms);
4146
4147   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4148   ntparms = TREE_VEC_LENGTH (inner_parms);
4149
4150   /* We check that each of the template parameters given in the
4151      partial specialization is used in the argument list to the
4152      specialization.  For example:
4153
4154        template <class T> struct S;
4155        template <class T> struct S<T*>;
4156
4157      The second declaration is OK because `T*' uses the template
4158      parameter T, whereas
4159
4160        template <class T> struct S<int>;
4161
4162      is no good.  Even trickier is:
4163
4164        template <class T>
4165        struct S1
4166        {
4167           template <class U>
4168           struct S2;
4169           template <class U>
4170           struct S2<T>;
4171        };
4172
4173      The S2<T> declaration is actually invalid; it is a
4174      full-specialization.  Of course,
4175
4176           template <class U>
4177           struct S2<T (*)(U)>;
4178
4179      or some such would have been OK.  */
4180   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4181   tpd.parms = XALLOCAVEC (int, ntparms);
4182   memset (tpd.parms, 0, sizeof (int) * ntparms);
4183
4184   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4185   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4186   for (i = 0; i < nargs; ++i)
4187     {
4188       tpd.current_arg = i;
4189       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4190                               &mark_template_parm,
4191                               &tpd,
4192                               NULL,
4193                               /*include_nondeduced_p=*/false);
4194     }
4195   for (i = 0; i < ntparms; ++i)
4196     if (tpd.parms[i] == 0)
4197       {
4198         /* One of the template parms was not used in a deduced context in the
4199            specialization.  */
4200         if (!did_error_intro)
4201           {
4202             error ("template parameters not deducible in "
4203                    "partial specialization:");
4204             did_error_intro = true;
4205           }
4206
4207         inform (input_location, "        %qD",
4208                 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4209       }
4210
4211   if (did_error_intro)
4212     return error_mark_node;
4213
4214   /* [temp.class.spec]
4215
4216      The argument list of the specialization shall not be identical to
4217      the implicit argument list of the primary template.  */
4218   tree main_args
4219     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4220   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args)))
4221     error ("partial specialization %qD does not specialize "
4222            "any template arguments", decl);
4223
4224   /* A partial specialization that replaces multiple parameters of the
4225      primary template with a pack expansion is less specialized for those
4226      parameters.  */
4227   if (nargs < DECL_NTPARMS (maintmpl))
4228     {
4229       error ("partial specialization is not more specialized than the "
4230              "primary template because it replaces multiple parameters "
4231              "with a pack expansion");
4232       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4233       return decl;
4234     }
4235
4236   /* [temp.class.spec]
4237
4238      A partially specialized non-type argument expression shall not
4239      involve template parameters of the partial specialization except
4240      when the argument expression is a simple identifier.
4241
4242      The type of a template parameter corresponding to a specialized
4243      non-type argument shall not be dependent on a parameter of the
4244      specialization. 
4245
4246      Also, we verify that pack expansions only occur at the
4247      end of the argument list.  */
4248   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4249   tpd2.parms = 0;
4250   for (i = 0; i < nargs; ++i)
4251     {
4252       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4253       tree arg = TREE_VEC_ELT (inner_args, i);
4254       tree packed_args = NULL_TREE;
4255       int j, len = 1;
4256
4257       if (ARGUMENT_PACK_P (arg))
4258         {
4259           /* Extract the arguments from the argument pack. We'll be
4260              iterating over these in the following loop.  */
4261           packed_args = ARGUMENT_PACK_ARGS (arg);
4262           len = TREE_VEC_LENGTH (packed_args);
4263         }
4264
4265       for (j = 0; j < len; j++)
4266         {
4267           if (packed_args)
4268             /* Get the Jth argument in the parameter pack.  */
4269             arg = TREE_VEC_ELT (packed_args, j);
4270
4271           if (PACK_EXPANSION_P (arg))
4272             {
4273               /* Pack expansions must come at the end of the
4274                  argument list.  */
4275               if ((packed_args && j < len - 1)
4276                   || (!packed_args && i < nargs - 1))
4277                 {
4278                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4279                     error ("parameter pack argument %qE must be at the "
4280                            "end of the template argument list", arg);
4281                   else
4282                     error ("parameter pack argument %qT must be at the "
4283                            "end of the template argument list", arg);
4284                 }
4285             }
4286
4287           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4288             /* We only care about the pattern.  */
4289             arg = PACK_EXPANSION_PATTERN (arg);
4290
4291           if (/* These first two lines are the `non-type' bit.  */
4292               !TYPE_P (arg)
4293               && TREE_CODE (arg) != TEMPLATE_DECL
4294               /* This next two lines are the `argument expression is not just a
4295                  simple identifier' condition and also the `specialized
4296                  non-type argument' bit.  */
4297               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4298               && !(REFERENCE_REF_P (arg)
4299                    && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4300             {
4301               if ((!packed_args && tpd.arg_uses_template_parms[i])
4302                   || (packed_args && uses_template_parms (arg)))
4303                 error ("template argument %qE involves template parameter(s)",
4304                        arg);
4305               else 
4306                 {
4307                   /* Look at the corresponding template parameter,
4308                      marking which template parameters its type depends
4309                      upon.  */
4310                   tree type = TREE_TYPE (parm);
4311
4312                   if (!tpd2.parms)
4313                     {
4314                       /* We haven't yet initialized TPD2.  Do so now.  */
4315                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4316                       /* The number of parameters here is the number in the
4317                          main template, which, as checked in the assertion
4318                          above, is NARGS.  */
4319                       tpd2.parms = XALLOCAVEC (int, nargs);
4320                       tpd2.level = 
4321                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4322                     }
4323
4324                   /* Mark the template parameters.  But this time, we're
4325                      looking for the template parameters of the main
4326                      template, not in the specialization.  */
4327                   tpd2.current_arg = i;
4328                   tpd2.arg_uses_template_parms[i] = 0;
4329                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4330                   for_each_template_parm (type,
4331                                           &mark_template_parm,
4332                                           &tpd2,
4333                                           NULL,
4334                                           /*include_nondeduced_p=*/false);
4335
4336                   if (tpd2.arg_uses_template_parms [i])
4337                     {
4338                       /* The type depended on some template parameters.
4339                          If they are fully specialized in the
4340                          specialization, that's OK.  */
4341                       int j;
4342                       int count = 0;
4343                       for (j = 0; j < nargs; ++j)
4344                         if (tpd2.parms[j] != 0
4345                             && tpd.arg_uses_template_parms [j])
4346                           ++count;
4347                       if (count != 0)
4348                         error_n (input_location, count,
4349                                  "type %qT of template argument %qE depends "
4350                                  "on a template parameter",
4351                                  "type %qT of template argument %qE depends "
4352                                  "on template parameters",
4353                                  type,
4354                                  arg);
4355                     }
4356                 }
4357             }
4358         }
4359     }
4360
4361   /* We should only get here once.  */
4362   if (TREE_CODE (decl) == TYPE_DECL)
4363     gcc_assert (!COMPLETE_TYPE_P (type));
4364
4365   tree tmpl = build_template_decl (decl, current_template_parms,
4366                                    DECL_MEMBER_TEMPLATE_P (maintmpl));
4367   TREE_TYPE (tmpl) = type;
4368   DECL_TEMPLATE_RESULT (tmpl) = decl;
4369   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4370   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
4371   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
4372
4373   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4374     = tree_cons (specargs, tmpl,
4375                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4376   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4377
4378   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4379        inst = TREE_CHAIN (inst))
4380     {
4381       tree instance = TREE_VALUE (inst);
4382       if (TYPE_P (instance)
4383           ? (COMPLETE_TYPE_P (instance)
4384              && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
4385           : DECL_TEMPLATE_INSTANTIATION (instance))
4386         {
4387           tree spec = most_specialized_partial_spec (instance, tf_none);
4388           if (spec && TREE_VALUE (spec) == tmpl)
4389             {
4390               tree inst_decl = (DECL_P (instance)
4391                                 ? instance : TYPE_NAME (instance));
4392               permerror (input_location,
4393                          "partial specialization of %qD after instantiation "
4394                          "of %qD", decl, inst_decl);
4395             }
4396         }
4397     }
4398
4399   return decl;
4400 }
4401
4402 /* PARM is a template parameter of some form; return the corresponding
4403    TEMPLATE_PARM_INDEX.  */
4404
4405 static tree
4406 get_template_parm_index (tree parm)
4407 {
4408   if (TREE_CODE (parm) == PARM_DECL
4409       || TREE_CODE (parm) == CONST_DECL)
4410     parm = DECL_INITIAL (parm);
4411   else if (TREE_CODE (parm) == TYPE_DECL
4412            || TREE_CODE (parm) == TEMPLATE_DECL)
4413     parm = TREE_TYPE (parm);
4414   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
4415       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
4416     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
4417   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
4418   return parm;
4419 }
4420
4421 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
4422    parameter packs used by the template parameter PARM.  */
4423
4424 static void
4425 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
4426 {
4427   /* A type parm can't refer to another parm.  */
4428   if (TREE_CODE (parm) == TYPE_DECL)
4429     return;
4430   else if (TREE_CODE (parm) == PARM_DECL)
4431     {
4432       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
4433                     ppd, ppd->visited);
4434       return;
4435     }
4436
4437   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
4438
4439   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
4440   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
4441     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
4442 }
4443
4444 /* PARM is a template parameter pack.  Return any parameter packs used in
4445    its type or the type of any of its template parameters.  If there are
4446    any such packs, it will be instantiated into a fixed template parameter
4447    list by partial instantiation rather than be fully deduced.  */
4448
4449 tree
4450 fixed_parameter_pack_p (tree parm)
4451 {
4452   /* This can only be true in a member template.  */
4453   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
4454     return NULL_TREE;
4455   /* This can only be true for a parameter pack.  */
4456   if (!template_parameter_pack_p (parm))
4457     return NULL_TREE;
4458   /* A type parm can't refer to another parm.  */
4459   if (TREE_CODE (parm) == TYPE_DECL)
4460     return NULL_TREE;
4461
4462   tree parameter_packs = NULL_TREE;
4463   struct find_parameter_pack_data ppd;
4464   ppd.parameter_packs = &parameter_packs;
4465   ppd.visited = new hash_set<tree>;
4466
4467   fixed_parameter_pack_p_1 (parm, &ppd);
4468
4469   delete ppd.visited;
4470   return parameter_packs;
4471 }
4472
4473 /* Check that a template declaration's use of default arguments and
4474    parameter packs is not invalid.  Here, PARMS are the template
4475    parameters.  IS_PRIMARY is true if DECL is the thing declared by
4476    a primary template.  IS_PARTIAL is true if DECL is a partial
4477    specialization.
4478
4479    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4480    declaration (but not a definition); 1 indicates a declaration, 2
4481    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4482    emitted for extraneous default arguments.
4483
4484    Returns TRUE if there were no errors found, FALSE otherwise. */
4485
4486 bool
4487 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
4488                          bool is_partial, int is_friend_decl)
4489 {
4490   const char *msg;
4491   int last_level_to_check;
4492   tree parm_level;
4493   bool no_errors = true;
4494
4495   /* [temp.param]
4496
4497      A default template-argument shall not be specified in a
4498      function template declaration or a function template definition, nor
4499      in the template-parameter-list of the definition of a member of a
4500      class template.  */
4501
4502   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
4503       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
4504     /* You can't have a function template declaration in a local
4505        scope, nor you can you define a member of a class template in a
4506        local scope.  */
4507     return true;
4508
4509   if ((TREE_CODE (decl) == TYPE_DECL
4510        && TREE_TYPE (decl)
4511        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4512       || (TREE_CODE (decl) == FUNCTION_DECL
4513           && LAMBDA_FUNCTION_P (decl)))
4514     /* A lambda doesn't have an explicit declaration; don't complain
4515        about the parms of the enclosing class.  */
4516     return true;
4517
4518   if (current_class_type
4519       && !TYPE_BEING_DEFINED (current_class_type)
4520       && DECL_LANG_SPECIFIC (decl)
4521       && DECL_DECLARES_FUNCTION_P (decl)
4522       /* If this is either a friend defined in the scope of the class
4523          or a member function.  */
4524       && (DECL_FUNCTION_MEMBER_P (decl)
4525           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4526           : DECL_FRIEND_CONTEXT (decl)
4527           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4528           : false)
4529       /* And, if it was a member function, it really was defined in
4530          the scope of the class.  */
4531       && (!DECL_FUNCTION_MEMBER_P (decl)
4532           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4533     /* We already checked these parameters when the template was
4534        declared, so there's no need to do it again now.  This function
4535        was defined in class scope, but we're processing its body now
4536        that the class is complete.  */
4537     return true;
4538
4539   /* Core issue 226 (C++0x only): the following only applies to class
4540      templates.  */
4541   if (is_primary
4542       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
4543     {
4544       /* [temp.param]
4545
4546          If a template-parameter has a default template-argument, all
4547          subsequent template-parameters shall have a default
4548          template-argument supplied.  */
4549       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4550         {
4551           tree inner_parms = TREE_VALUE (parm_level);
4552           int ntparms = TREE_VEC_LENGTH (inner_parms);
4553           int seen_def_arg_p = 0;
4554           int i;
4555
4556           for (i = 0; i < ntparms; ++i)
4557             {
4558               tree parm = TREE_VEC_ELT (inner_parms, i);
4559
4560               if (parm == error_mark_node)
4561                 continue;
4562
4563               if (TREE_PURPOSE (parm))
4564                 seen_def_arg_p = 1;
4565               else if (seen_def_arg_p
4566                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4567                 {
4568                   error ("no default argument for %qD", TREE_VALUE (parm));
4569                   /* For better subsequent error-recovery, we indicate that
4570                      there should have been a default argument.  */
4571                   TREE_PURPOSE (parm) = error_mark_node;
4572                   no_errors = false;
4573                 }
4574               else if (!is_partial
4575                        && !is_friend_decl
4576                        /* Don't complain about an enclosing partial
4577                           specialization.  */
4578                        && parm_level == parms
4579                        && TREE_CODE (decl) == TYPE_DECL
4580                        && i < ntparms - 1
4581                        && template_parameter_pack_p (TREE_VALUE (parm))
4582                        /* A fixed parameter pack will be partially
4583                           instantiated into a fixed length list.  */
4584                        && !fixed_parameter_pack_p (TREE_VALUE (parm)))
4585                 {
4586                   /* A primary class template can only have one
4587                      parameter pack, at the end of the template
4588                      parameter list.  */
4589
4590                   error ("parameter pack %q+D must be at the end of the"
4591                          " template parameter list", TREE_VALUE (parm));
4592
4593                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4594                     = error_mark_node;
4595                   no_errors = false;
4596                 }
4597             }
4598         }
4599     }
4600
4601   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4602       || is_partial 
4603       || !is_primary
4604       || is_friend_decl)
4605     /* For an ordinary class template, default template arguments are
4606        allowed at the innermost level, e.g.:
4607          template <class T = int>
4608          struct S {};
4609        but, in a partial specialization, they're not allowed even
4610        there, as we have in [temp.class.spec]:
4611
4612          The template parameter list of a specialization shall not
4613          contain default template argument values.
4614
4615        So, for a partial specialization, or for a function template
4616        (in C++98/C++03), we look at all of them.  */
4617     ;
4618   else
4619     /* But, for a primary class template that is not a partial
4620        specialization we look at all template parameters except the
4621        innermost ones.  */
4622     parms = TREE_CHAIN (parms);
4623
4624   /* Figure out what error message to issue.  */
4625   if (is_friend_decl == 2)
4626     msg = G_("default template arguments may not be used in function template "
4627              "friend re-declaration");
4628   else if (is_friend_decl)
4629     msg = G_("default template arguments may not be used in function template "
4630              "friend declarations");
4631   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4632     msg = G_("default template arguments may not be used in function templates "
4633              "without -std=c++11 or -std=gnu++11");
4634   else if (is_partial)
4635     msg = G_("default template arguments may not be used in "
4636              "partial specializations");
4637   else
4638     msg = G_("default argument for template parameter for class enclosing %qD");
4639
4640   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4641     /* If we're inside a class definition, there's no need to
4642        examine the parameters to the class itself.  On the one
4643        hand, they will be checked when the class is defined, and,
4644        on the other, default arguments are valid in things like:
4645          template <class T = double>
4646          struct S { template <class U> void f(U); };
4647        Here the default argument for `S' has no bearing on the
4648        declaration of `f'.  */
4649     last_level_to_check = template_class_depth (current_class_type) + 1;
4650   else
4651     /* Check everything.  */
4652     last_level_to_check = 0;
4653
4654   for (parm_level = parms;
4655        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4656        parm_level = TREE_CHAIN (parm_level))
4657     {
4658       tree inner_parms = TREE_VALUE (parm_level);
4659       int i;
4660       int ntparms;
4661
4662       ntparms = TREE_VEC_LENGTH (inner_parms);
4663       for (i = 0; i < ntparms; ++i)
4664         {
4665           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4666             continue;
4667
4668           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4669             {
4670               if (msg)
4671                 {
4672                   no_errors = false;
4673                   if (is_friend_decl == 2)
4674                     return no_errors;
4675
4676                   error (msg, decl);
4677                   msg = 0;
4678                 }
4679
4680               /* Clear out the default argument so that we are not
4681                  confused later.  */
4682               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4683             }
4684         }
4685
4686       /* At this point, if we're still interested in issuing messages,
4687          they must apply to classes surrounding the object declared.  */
4688       if (msg)
4689         msg = G_("default argument for template parameter for class "
4690                  "enclosing %qD");
4691     }
4692
4693   return no_errors;
4694 }
4695
4696 /* Worker for push_template_decl_real, called via
4697    for_each_template_parm.  DATA is really an int, indicating the
4698    level of the parameters we are interested in.  If T is a template
4699    parameter of that level, return nonzero.  */
4700
4701 static int
4702 template_parm_this_level_p (tree t, void* data)
4703 {
4704   int this_level = *(int *)data;
4705   int level;
4706
4707   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4708     level = TEMPLATE_PARM_LEVEL (t);
4709   else
4710     level = TEMPLATE_TYPE_LEVEL (t);
4711   return level == this_level;
4712 }
4713
4714 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4715    parameters given by current_template_args, or reuses a
4716    previously existing one, if appropriate.  Returns the DECL, or an
4717    equivalent one, if it is replaced via a call to duplicate_decls.
4718
4719    If IS_FRIEND is true, DECL is a friend declaration.  */
4720
4721 tree
4722 push_template_decl_real (tree decl, bool is_friend)
4723 {
4724   tree tmpl;
4725   tree args;
4726   tree info;
4727   tree ctx;
4728   bool is_primary;
4729   bool is_partial;
4730   int new_template_p = 0;
4731   /* True if the template is a member template, in the sense of
4732      [temp.mem].  */
4733   bool member_template_p = false;
4734
4735   if (decl == error_mark_node || !current_template_parms)
4736     return error_mark_node;
4737
4738   /* See if this is a partial specialization.  */
4739   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
4740                  && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4741                  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
4742                 || (TREE_CODE (decl) == VAR_DECL
4743                     && DECL_LANG_SPECIFIC (decl)
4744                     && DECL_TEMPLATE_SPECIALIZATION (decl)
4745                     && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
4746
4747   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4748     is_friend = true;
4749
4750   if (is_friend)
4751     /* For a friend, we want the context of the friend function, not
4752        the type of which it is a friend.  */
4753     ctx = CP_DECL_CONTEXT (decl);
4754   else if (CP_DECL_CONTEXT (decl)
4755            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4756     /* In the case of a virtual function, we want the class in which
4757        it is defined.  */
4758     ctx = CP_DECL_CONTEXT (decl);
4759   else
4760     /* Otherwise, if we're currently defining some class, the DECL
4761        is assumed to be a member of the class.  */
4762     ctx = current_scope ();
4763
4764   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4765     ctx = NULL_TREE;
4766
4767   if (!DECL_CONTEXT (decl))
4768     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4769
4770   /* See if this is a primary template.  */
4771   if (is_friend && ctx
4772       && uses_template_parms_level (ctx, processing_template_decl))
4773     /* A friend template that specifies a class context, i.e.
4774          template <typename T> friend void A<T>::f();
4775        is not primary.  */
4776     is_primary = false;
4777   else if (TREE_CODE (decl) == TYPE_DECL
4778            && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4779     is_primary = false;
4780   else
4781     is_primary = template_parm_scope_p ();
4782
4783   if (is_primary)
4784     {
4785       if (DECL_CLASS_SCOPE_P (decl))
4786         member_template_p = true;
4787       if (TREE_CODE (decl) == TYPE_DECL
4788           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4789         {
4790           error ("template class without a name");
4791           return error_mark_node;
4792         }
4793       else if (TREE_CODE (decl) == FUNCTION_DECL)
4794         {
4795           if (member_template_p)
4796             {
4797               if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
4798                 error ("member template %qD may not have virt-specifiers", decl);
4799             }
4800           if (DECL_DESTRUCTOR_P (decl))
4801             {
4802               /* [temp.mem]
4803
4804                  A destructor shall not be a member template.  */
4805               error ("destructor %qD declared as member template", decl);
4806               return error_mark_node;
4807             }
4808           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4809               && (!prototype_p (TREE_TYPE (decl))
4810                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4811                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4812                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4813                       == void_list_node)))
4814             {
4815               /* [basic.stc.dynamic.allocation]
4816
4817                  An allocation function can be a function
4818                  template. ... Template allocation functions shall
4819                  have two or more parameters.  */
4820               error ("invalid template declaration of %qD", decl);
4821               return error_mark_node;
4822             }
4823         }
4824       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4825                && CLASS_TYPE_P (TREE_TYPE (decl)))
4826         /* OK */;
4827       else if (TREE_CODE (decl) == TYPE_DECL
4828                && TYPE_DECL_ALIAS_P (decl))
4829         /* alias-declaration */
4830         gcc_assert (!DECL_ARTIFICIAL (decl));
4831       else if (VAR_P (decl))
4832         /* C++14 variable template. */;
4833       else
4834         {
4835           error ("template declaration of %q#D", decl);
4836           return error_mark_node;
4837         }
4838     }
4839
4840   /* Check to see that the rules regarding the use of default
4841      arguments are not being violated.  */
4842   check_default_tmpl_args (decl, current_template_parms,
4843                            is_primary, is_partial, /*is_friend_decl=*/0);
4844
4845   /* Ensure that there are no parameter packs in the type of this
4846      declaration that have not been expanded.  */
4847   if (TREE_CODE (decl) == FUNCTION_DECL)
4848     {
4849       /* Check each of the arguments individually to see if there are
4850          any bare parameter packs.  */
4851       tree type = TREE_TYPE (decl);
4852       tree arg = DECL_ARGUMENTS (decl);
4853       tree argtype = TYPE_ARG_TYPES (type);
4854
4855       while (arg && argtype)
4856         {
4857           if (!DECL_PACK_P (arg)
4858               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4859             {
4860             /* This is a PARM_DECL that contains unexpanded parameter
4861                packs. We have already complained about this in the
4862                check_for_bare_parameter_packs call, so just replace
4863                these types with ERROR_MARK_NODE.  */
4864               TREE_TYPE (arg) = error_mark_node;
4865               TREE_VALUE (argtype) = error_mark_node;
4866             }
4867
4868           arg = DECL_CHAIN (arg);
4869           argtype = TREE_CHAIN (argtype);
4870         }
4871
4872       /* Check for bare parameter packs in the return type and the
4873          exception specifiers.  */
4874       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4875         /* Errors were already issued, set return type to int
4876            as the frontend doesn't expect error_mark_node as
4877            the return type.  */
4878         TREE_TYPE (type) = integer_type_node;
4879       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4880         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4881     }
4882   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
4883                                             && TYPE_DECL_ALIAS_P (decl))
4884                                            ? DECL_ORIGINAL_TYPE (decl)
4885                                            : TREE_TYPE (decl)))
4886     {
4887       TREE_TYPE (decl) = error_mark_node;
4888       return error_mark_node;
4889     }
4890
4891   if (is_partial)
4892     return process_partial_specialization (decl);
4893
4894   args = current_template_args ();
4895
4896   if (!ctx
4897       || TREE_CODE (ctx) == FUNCTION_DECL
4898       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4899       || (TREE_CODE (decl) == TYPE_DECL
4900           && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4901       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4902     {
4903       if (DECL_LANG_SPECIFIC (decl)
4904           && DECL_TEMPLATE_INFO (decl)
4905           && DECL_TI_TEMPLATE (decl))
4906         tmpl = DECL_TI_TEMPLATE (decl);
4907       /* If DECL is a TYPE_DECL for a class-template, then there won't
4908          be DECL_LANG_SPECIFIC.  The information equivalent to
4909          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4910       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4911                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4912                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4913         {
4914           /* Since a template declaration already existed for this
4915              class-type, we must be redeclaring it here.  Make sure
4916              that the redeclaration is valid.  */
4917           redeclare_class_template (TREE_TYPE (decl),
4918                                     current_template_parms);
4919           /* We don't need to create a new TEMPLATE_DECL; just use the
4920              one we already had.  */
4921           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4922         }
4923       else
4924         {
4925           tmpl = build_template_decl (decl, current_template_parms,
4926                                       member_template_p);
4927           new_template_p = 1;
4928
4929           if (DECL_LANG_SPECIFIC (decl)
4930               && DECL_TEMPLATE_SPECIALIZATION (decl))
4931             {
4932               /* A specialization of a member template of a template
4933                  class.  */
4934               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4935               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4936               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4937             }
4938         }
4939     }
4940   else
4941     {
4942       tree a, t, current, parms;
4943       int i;
4944       tree tinfo = get_template_info (decl);
4945
4946       if (!tinfo)
4947         {
4948           error ("template definition of non-template %q#D", decl);
4949           return error_mark_node;
4950         }
4951
4952       tmpl = TI_TEMPLATE (tinfo);
4953
4954       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4955           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4956           && DECL_TEMPLATE_SPECIALIZATION (decl)
4957           && DECL_MEMBER_TEMPLATE_P (tmpl))
4958         {
4959           tree new_tmpl;
4960
4961           /* The declaration is a specialization of a member
4962              template, declared outside the class.  Therefore, the
4963              innermost template arguments will be NULL, so we
4964              replace them with the arguments determined by the
4965              earlier call to check_explicit_specialization.  */
4966           args = DECL_TI_ARGS (decl);
4967
4968           new_tmpl
4969             = build_template_decl (decl, current_template_parms,
4970                                    member_template_p);
4971           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4972           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4973           DECL_TI_TEMPLATE (decl) = new_tmpl;
4974           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4975           DECL_TEMPLATE_INFO (new_tmpl)
4976             = build_template_info (tmpl, args);
4977
4978           register_specialization (new_tmpl,
4979                                    most_general_template (tmpl),
4980                                    args,
4981                                    is_friend, 0);
4982           return decl;
4983         }
4984
4985       /* Make sure the template headers we got make sense.  */
4986
4987       parms = DECL_TEMPLATE_PARMS (tmpl);
4988       i = TMPL_PARMS_DEPTH (parms);
4989       if (TMPL_ARGS_DEPTH (args) != i)
4990         {
4991           error ("expected %d levels of template parms for %q#D, got %d",
4992                  i, decl, TMPL_ARGS_DEPTH (args));
4993           DECL_INTERFACE_KNOWN (decl) = 1;
4994           return error_mark_node;
4995         }
4996       else
4997         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4998           {
4999             a = TMPL_ARGS_LEVEL (args, i);
5000             t = INNERMOST_TEMPLATE_PARMS (parms);
5001
5002             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5003               {
5004                 if (current == decl)
5005                   error ("got %d template parameters for %q#D",
5006                          TREE_VEC_LENGTH (a), decl);
5007                 else
5008                   error ("got %d template parameters for %q#T",
5009                          TREE_VEC_LENGTH (a), current);
5010                 error ("  but %d required", TREE_VEC_LENGTH (t));
5011                 /* Avoid crash in import_export_decl.  */
5012                 DECL_INTERFACE_KNOWN (decl) = 1;
5013                 return error_mark_node;
5014               }
5015
5016             if (current == decl)
5017               current = ctx;
5018             else if (current == NULL_TREE)
5019               /* Can happen in erroneous input.  */
5020               break;
5021             else
5022               current = get_containing_scope (current);
5023           }
5024
5025       /* Check that the parms are used in the appropriate qualifying scopes
5026          in the declarator.  */
5027       if (!comp_template_args
5028           (TI_ARGS (tinfo),
5029            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5030         {
5031           error ("\
5032 template arguments to %qD do not match original template %qD",
5033                  decl, DECL_TEMPLATE_RESULT (tmpl));
5034           if (!uses_template_parms (TI_ARGS (tinfo)))
5035             inform (input_location, "use template<> for an explicit specialization");
5036           /* Avoid crash in import_export_decl.  */
5037           DECL_INTERFACE_KNOWN (decl) = 1;
5038           return error_mark_node;
5039         }
5040     }
5041
5042   DECL_TEMPLATE_RESULT (tmpl) = decl;
5043   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5044
5045   /* Push template declarations for global functions and types.  Note
5046      that we do not try to push a global template friend declared in a
5047      template class; such a thing may well depend on the template
5048      parameters of the class.  */
5049   if (new_template_p && !ctx
5050       && !(is_friend && template_class_depth (current_class_type) > 0))
5051     {
5052       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5053       if (tmpl == error_mark_node)
5054         return error_mark_node;
5055
5056       /* Hide template friend classes that haven't been declared yet.  */
5057       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5058         {
5059           DECL_ANTICIPATED (tmpl) = 1;
5060           DECL_FRIEND_P (tmpl) = 1;
5061         }
5062     }
5063
5064   if (is_primary)
5065     {
5066       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5067       int i;
5068
5069       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5070       if (DECL_CONV_FN_P (tmpl))
5071         {
5072           int depth = TMPL_PARMS_DEPTH (parms);
5073
5074           /* It is a conversion operator. See if the type converted to
5075              depends on innermost template operands.  */
5076
5077           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5078                                          depth))
5079             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5080         }
5081
5082       /* Give template template parms a DECL_CONTEXT of the template
5083          for which they are a parameter.  */
5084       parms = INNERMOST_TEMPLATE_PARMS (parms);
5085       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5086         {
5087           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5088           if (TREE_CODE (parm) == TEMPLATE_DECL)
5089             DECL_CONTEXT (parm) = tmpl;
5090         }
5091     }
5092
5093   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5094      back to its most general template.  If TMPL is a specialization,
5095      ARGS may only have the innermost set of arguments.  Add the missing
5096      argument levels if necessary.  */
5097   if (DECL_TEMPLATE_INFO (tmpl))
5098     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5099
5100   info = build_template_info (tmpl, args);
5101
5102   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5103     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5104   else
5105     {
5106       if (is_primary && !DECL_LANG_SPECIFIC (decl))
5107         retrofit_lang_decl (decl);
5108       if (DECL_LANG_SPECIFIC (decl))
5109         DECL_TEMPLATE_INFO (decl) = info;
5110     }
5111
5112   if (flag_implicit_templates
5113       && !is_friend
5114       && TREE_PUBLIC (decl)
5115       && VAR_OR_FUNCTION_DECL_P (decl))
5116     /* Set DECL_COMDAT on template instantiations; if we force
5117        them to be emitted by explicit instantiation or -frepo,
5118        mark_needed will tell cgraph to do the right thing.  */
5119     DECL_COMDAT (decl) = true;
5120
5121   return DECL_TEMPLATE_RESULT (tmpl);
5122 }
5123
5124 tree
5125 push_template_decl (tree decl)
5126 {
5127   return push_template_decl_real (decl, false);
5128 }
5129
5130 /* FN is an inheriting constructor that inherits from the constructor
5131    template INHERITED; turn FN into a constructor template with a matching
5132    template header.  */
5133
5134 tree
5135 add_inherited_template_parms (tree fn, tree inherited)
5136 {
5137   tree inner_parms
5138     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5139   inner_parms = copy_node (inner_parms);
5140   tree parms
5141     = tree_cons (size_int (processing_template_decl + 1),
5142                  inner_parms, current_template_parms);
5143   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5144   tree args = template_parms_to_args (parms);
5145   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5146   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5147   DECL_TEMPLATE_RESULT (tmpl) = fn;
5148   DECL_ARTIFICIAL (tmpl) = true;
5149   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5150   return tmpl;
5151 }
5152
5153 /* Called when a class template TYPE is redeclared with the indicated
5154    template PARMS, e.g.:
5155
5156      template <class T> struct S;
5157      template <class T> struct S {};  */
5158
5159 bool
5160 redeclare_class_template (tree type, tree parms)
5161 {
5162   tree tmpl;
5163   tree tmpl_parms;
5164   int i;
5165
5166   if (!TYPE_TEMPLATE_INFO (type))
5167     {
5168       error ("%qT is not a template type", type);
5169       return false;
5170     }
5171
5172   tmpl = TYPE_TI_TEMPLATE (type);
5173   if (!PRIMARY_TEMPLATE_P (tmpl))
5174     /* The type is nested in some template class.  Nothing to worry
5175        about here; there are no new template parameters for the nested
5176        type.  */
5177     return true;
5178
5179   if (!parms)
5180     {
5181       error ("template specifiers not specified in declaration of %qD",
5182              tmpl);
5183       return false;
5184     }
5185
5186   parms = INNERMOST_TEMPLATE_PARMS (parms);
5187   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5188
5189   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5190     {
5191       error_n (input_location, TREE_VEC_LENGTH (parms),
5192                "redeclared with %d template parameter",
5193                "redeclared with %d template parameters",
5194                TREE_VEC_LENGTH (parms));
5195       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5196                 "previous declaration %q+D used %d template parameter",
5197                 "previous declaration %q+D used %d template parameters",
5198                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5199       return false;
5200     }
5201
5202   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5203     {
5204       tree tmpl_parm;
5205       tree parm;
5206       tree tmpl_default;
5207       tree parm_default;
5208
5209       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5210           || TREE_VEC_ELT (parms, i) == error_mark_node)
5211         continue;
5212
5213       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5214       if (error_operand_p (tmpl_parm))
5215         return false;
5216
5217       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5218       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5219       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5220
5221       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5222          TEMPLATE_DECL.  */
5223       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5224           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5225               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5226           || (TREE_CODE (tmpl_parm) != PARM_DECL
5227               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5228                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5229           || (TREE_CODE (tmpl_parm) == PARM_DECL
5230               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5231                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5232         {
5233           error ("template parameter %q+#D", tmpl_parm);
5234           error ("redeclared here as %q#D", parm);
5235           return false;
5236         }
5237
5238       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5239         {
5240           /* We have in [temp.param]:
5241
5242              A template-parameter may not be given default arguments
5243              by two different declarations in the same scope.  */
5244           error_at (input_location, "redefinition of default argument for %q#D", parm);
5245           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5246                   "original definition appeared here");
5247           return false;
5248         }
5249
5250       if (parm_default != NULL_TREE)
5251         /* Update the previous template parameters (which are the ones
5252            that will really count) with the new default value.  */
5253         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5254       else if (tmpl_default != NULL_TREE)
5255         /* Update the new parameters, too; they'll be used as the
5256            parameters for any members.  */
5257         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5258     }
5259
5260     return true;
5261 }
5262
5263 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
5264    to be used when the caller has already checked
5265    (processing_template_decl
5266     && !instantiation_dependent_expression_p (expr)
5267     && potential_constant_expression (expr))
5268    and cleared processing_template_decl.  */
5269
5270 tree
5271 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
5272 {
5273   return tsubst_copy_and_build (expr,
5274                                 /*args=*/NULL_TREE,
5275                                 complain,
5276                                 /*in_decl=*/NULL_TREE,
5277                                 /*function_p=*/false,
5278                                 /*integral_constant_expression_p=*/true);
5279 }
5280
5281 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5282    (possibly simplified) expression.  */
5283
5284 tree
5285 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5286 {
5287   if (expr == NULL_TREE)
5288     return NULL_TREE;
5289
5290   /* If we're in a template, but EXPR isn't value dependent, simplify
5291      it.  We're supposed to treat:
5292
5293        template <typename T> void f(T[1 + 1]);
5294        template <typename T> void f(T[2]);
5295
5296      as two declarations of the same function, for example.  */
5297   if (processing_template_decl
5298       && !instantiation_dependent_expression_p (expr)
5299       && potential_constant_expression (expr))
5300     {
5301       processing_template_decl_sentinel s;
5302       expr = instantiate_non_dependent_expr_internal (expr, complain);
5303     }
5304   return expr;
5305 }
5306
5307 tree
5308 instantiate_non_dependent_expr (tree expr)
5309 {
5310   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
5311 }
5312
5313 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
5314    template declaration, or a TYPE_DECL for an alias declaration.  */
5315
5316 bool
5317 alias_type_or_template_p (tree t)
5318 {
5319   if (t == NULL_TREE)
5320     return false;
5321   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5322           || (TYPE_P (t)
5323               && TYPE_NAME (t)
5324               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5325           || DECL_ALIAS_TEMPLATE_P (t));
5326 }
5327
5328 /* Return TRUE iff T is a specialization of an alias template.  */
5329
5330 bool
5331 alias_template_specialization_p (const_tree t)
5332 {
5333   /* It's an alias template specialization if it's an alias and its
5334      TYPE_NAME is a specialization of a primary template.  */
5335   if (TYPE_ALIAS_P (t))
5336     {
5337       tree name = TYPE_NAME (t);
5338       if (DECL_LANG_SPECIFIC (name))
5339         if (tree ti = DECL_TEMPLATE_INFO (name))
5340           {
5341             tree tmpl = TI_TEMPLATE (ti);
5342             return PRIMARY_TEMPLATE_P (tmpl);
5343           }
5344     }
5345   return false;
5346 }
5347
5348 /* Return TRUE iff T is a specialization of an alias template with
5349    dependent template-arguments.  */
5350
5351 bool
5352 dependent_alias_template_spec_p (const_tree t)
5353 {
5354   return (alias_template_specialization_p (t)
5355           && (any_dependent_template_arguments_p
5356               (INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (t)))));
5357 }
5358
5359 /* Return the number of innermost template parameters in TMPL.  */
5360
5361 static int
5362 num_innermost_template_parms (tree tmpl)
5363 {
5364   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
5365   return TREE_VEC_LENGTH (parms);
5366 }
5367
5368 /* Return either TMPL or another template that it is equivalent to under DR
5369    1286: An alias that just changes the name of a template is equivalent to
5370    the other template.  */
5371
5372 static tree
5373 get_underlying_template (tree tmpl)
5374 {
5375   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
5376   while (DECL_ALIAS_TEMPLATE_P (tmpl))
5377     {
5378       tree result = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
5379       if (TYPE_TEMPLATE_INFO (result))
5380         {
5381           tree sub = TYPE_TI_TEMPLATE (result);
5382           if (PRIMARY_TEMPLATE_P (sub)
5383               && (num_innermost_template_parms (tmpl)
5384                   == num_innermost_template_parms (sub)))
5385             {
5386               tree alias_args = INNERMOST_TEMPLATE_ARGS
5387                 (template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
5388               if (!comp_template_args (TYPE_TI_ARGS (result), alias_args))
5389                 break;
5390               /* The alias type is equivalent to the pattern of the
5391                  underlying template, so strip the alias.  */
5392               tmpl = sub;
5393               continue;
5394             }
5395         }
5396       break;
5397     }
5398   return tmpl;
5399 }
5400
5401 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5402    must be a function or a pointer-to-function type, as specified
5403    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5404    and check that the resulting function has external linkage.  */
5405
5406 static tree
5407 convert_nontype_argument_function (tree type, tree expr,
5408                                    tsubst_flags_t complain)
5409 {
5410   tree fns = expr;
5411   tree fn, fn_no_ptr;
5412   linkage_kind linkage;
5413
5414   fn = instantiate_type (type, fns, tf_none);
5415   if (fn == error_mark_node)
5416     return error_mark_node;
5417
5418   fn_no_ptr = fn;
5419   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5420     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5421   if (BASELINK_P (fn_no_ptr))
5422     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5423  
5424   /* [temp.arg.nontype]/1
5425
5426      A template-argument for a non-type, non-template template-parameter
5427      shall be one of:
5428      [...]
5429      -- the address of an object or function with external [C++11: or
5430         internal] linkage.  */
5431
5432   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
5433     {
5434       if (complain & tf_error)
5435         {
5436           error ("%qE is not a valid template argument for type %qT",
5437                  expr, type);
5438           if (TYPE_PTR_P (type))
5439             error ("it must be the address of a function with "
5440                    "external linkage");
5441           else
5442             error ("it must be the name of a function with "
5443                    "external linkage");
5444         }
5445       return NULL_TREE;
5446     }
5447
5448   linkage = decl_linkage (fn_no_ptr);
5449   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
5450     {
5451       if (complain & tf_error)
5452         {
5453           if (cxx_dialect >= cxx11)
5454             error ("%qE is not a valid template argument for type %qT "
5455                    "because %qD has no linkage",
5456                    expr, type, fn_no_ptr);
5457           else
5458             error ("%qE is not a valid template argument for type %qT "
5459                    "because %qD does not have external linkage",
5460                    expr, type, fn_no_ptr);
5461         }
5462       return NULL_TREE;
5463     }
5464
5465   return fn;
5466 }
5467
5468 /* Subroutine of convert_nontype_argument.
5469    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5470    Emit an error otherwise.  */
5471
5472 static bool
5473 check_valid_ptrmem_cst_expr (tree type, tree expr,
5474                              tsubst_flags_t complain)
5475 {
5476   STRIP_NOPS (expr);
5477   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5478     return true;
5479   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
5480     return true;
5481   if (processing_template_decl
5482       && TREE_CODE (expr) == ADDR_EXPR
5483       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
5484     return true;
5485   if (complain & tf_error)
5486     {
5487       error ("%qE is not a valid template argument for type %qT",
5488              expr, type);
5489       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5490     }
5491   return false;
5492 }
5493
5494 /* Returns TRUE iff the address of OP is value-dependent.
5495
5496    14.6.2.4 [temp.dep.temp]:
5497    A non-integral non-type template-argument is dependent if its type is
5498    dependent or it has either of the following forms
5499      qualified-id
5500      & qualified-id
5501    and contains a nested-name-specifier which specifies a class-name that
5502    names a dependent type.
5503
5504    We generalize this to just say that the address of a member of a
5505    dependent class is value-dependent; the above doesn't cover the
5506    address of a static data member named with an unqualified-id.  */
5507
5508 static bool
5509 has_value_dependent_address (tree op)
5510 {
5511   /* We could use get_inner_reference here, but there's no need;
5512      this is only relevant for template non-type arguments, which
5513      can only be expressed as &id-expression.  */
5514   if (DECL_P (op))
5515     {
5516       tree ctx = CP_DECL_CONTEXT (op);
5517       if (TYPE_P (ctx) && dependent_type_p (ctx))
5518         return true;
5519     }
5520
5521   return false;
5522 }
5523
5524 /* The next set of functions are used for providing helpful explanatory
5525    diagnostics for failed overload resolution.  Their messages should be
5526    indented by two spaces for consistency with the messages in
5527    call.c  */
5528
5529 static int
5530 unify_success (bool /*explain_p*/)
5531 {
5532   return 0;
5533 }
5534
5535 static int
5536 unify_parameter_deduction_failure (bool explain_p, tree parm)
5537 {
5538   if (explain_p)
5539     inform (input_location,
5540             "  couldn't deduce template parameter %qD", parm);
5541   return 1;
5542 }
5543
5544 static int
5545 unify_invalid (bool /*explain_p*/)
5546 {
5547   return 1;
5548 }
5549
5550 static int
5551 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5552 {
5553   if (explain_p)
5554     inform (input_location,
5555             "  types %qT and %qT have incompatible cv-qualifiers",
5556             parm, arg);
5557   return 1;
5558 }
5559
5560 static int
5561 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5562 {
5563   if (explain_p)
5564     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5565   return 1;
5566 }
5567
5568 static int
5569 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5570 {
5571   if (explain_p)
5572     inform (input_location,
5573             "  template parameter %qD is not a parameter pack, but "
5574             "argument %qD is",
5575             parm, arg);
5576   return 1;
5577 }
5578
5579 static int
5580 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5581 {
5582   if (explain_p)
5583     inform (input_location,
5584             "  template argument %qE does not match "
5585             "pointer-to-member constant %qE",
5586             arg, parm);
5587   return 1;
5588 }
5589
5590 static int
5591 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5592 {
5593   if (explain_p)
5594     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5595   return 1;
5596 }
5597
5598 static int
5599 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5600 {
5601   if (explain_p)
5602     inform (input_location,
5603             "  inconsistent parameter pack deduction with %qT and %qT",
5604             old_arg, new_arg);
5605   return 1;
5606 }
5607
5608 static int
5609 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5610 {
5611   if (explain_p)
5612     {
5613       if (TYPE_P (parm))
5614         inform (input_location,
5615                 "  deduced conflicting types for parameter %qT (%qT and %qT)",
5616                 parm, first, second);
5617       else
5618         inform (input_location,
5619                 "  deduced conflicting values for non-type parameter "
5620                 "%qE (%qE and %qE)", parm, first, second);
5621     }
5622   return 1;
5623 }
5624
5625 static int
5626 unify_vla_arg (bool explain_p, tree arg)
5627 {
5628   if (explain_p)
5629     inform (input_location,
5630             "  variable-sized array type %qT is not "
5631             "a valid template argument",
5632             arg);
5633   return 1;
5634 }
5635
5636 static int
5637 unify_method_type_error (bool explain_p, tree arg)
5638 {
5639   if (explain_p)
5640     inform (input_location,
5641             "  member function type %qT is not a valid template argument",
5642             arg);
5643   return 1;
5644 }
5645
5646 static int
5647 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
5648 {
5649   if (explain_p)
5650     {
5651       if (least_p)
5652         inform_n (input_location, wanted,
5653                   "  candidate expects at least %d argument, %d provided",
5654                   "  candidate expects at least %d arguments, %d provided",
5655                   wanted, have);
5656       else
5657         inform_n (input_location, wanted,
5658                   "  candidate expects %d argument, %d provided",
5659                   "  candidate expects %d arguments, %d provided",
5660                   wanted, have);
5661     }
5662   return 1;
5663 }
5664
5665 static int
5666 unify_too_many_arguments (bool explain_p, int have, int wanted)
5667 {
5668   return unify_arity (explain_p, have, wanted);
5669 }
5670
5671 static int
5672 unify_too_few_arguments (bool explain_p, int have, int wanted,
5673                          bool least_p = false)
5674 {
5675   return unify_arity (explain_p, have, wanted, least_p);
5676 }
5677
5678 static int
5679 unify_arg_conversion (bool explain_p, tree to_type,
5680                       tree from_type, tree arg)
5681 {
5682   if (explain_p)
5683     inform (EXPR_LOC_OR_LOC (arg, input_location),
5684             "  cannot convert %qE (type %qT) to type %qT",
5685             arg, from_type, to_type);
5686   return 1;
5687 }
5688
5689 static int
5690 unify_no_common_base (bool explain_p, enum template_base_result r,
5691                       tree parm, tree arg)
5692 {
5693   if (explain_p)
5694     switch (r)
5695       {
5696       case tbr_ambiguous_baseclass:
5697         inform (input_location, "  %qT is an ambiguous base class of %qT",
5698                 parm, arg);
5699         break;
5700       default:
5701         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5702         break;
5703       }
5704   return 1;
5705 }
5706
5707 static int
5708 unify_inconsistent_template_template_parameters (bool explain_p)
5709 {
5710   if (explain_p)
5711     inform (input_location,
5712             "  template parameters of a template template argument are "
5713             "inconsistent with other deduced template arguments");
5714   return 1;
5715 }
5716
5717 static int
5718 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5719 {
5720   if (explain_p)
5721     inform (input_location,
5722             "  can't deduce a template for %qT from non-template type %qT",
5723             parm, arg);
5724   return 1;
5725 }
5726
5727 static int
5728 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5729 {
5730   if (explain_p)
5731     inform (input_location,
5732             "  template argument %qE does not match %qD", arg, parm);
5733   return 1;
5734 }
5735
5736 static int
5737 unify_overload_resolution_failure (bool explain_p, tree arg)
5738 {
5739   if (explain_p)
5740     inform (input_location,
5741             "  could not resolve address from overloaded function %qE",
5742             arg);
5743   return 1;
5744 }
5745
5746 /* Attempt to convert the non-type template parameter EXPR to the
5747    indicated TYPE.  If the conversion is successful, return the
5748    converted value.  If the conversion is unsuccessful, return
5749    NULL_TREE if we issued an error message, or error_mark_node if we
5750    did not.  We issue error messages for out-and-out bad template
5751    parameters, but not simply because the conversion failed, since we
5752    might be just trying to do argument deduction.  Both TYPE and EXPR
5753    must be non-dependent.
5754
5755    The conversion follows the special rules described in
5756    [temp.arg.nontype], and it is much more strict than an implicit
5757    conversion.
5758
5759    This function is called twice for each template argument (see
5760    lookup_template_class for a more accurate description of this
5761    problem). This means that we need to handle expressions which
5762    are not valid in a C++ source, but can be created from the
5763    first call (for instance, casts to perform conversions). These
5764    hacks can go away after we fix the double coercion problem.  */
5765
5766 static tree
5767 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5768 {
5769   tree expr_type;
5770
5771   /* Detect immediately string literals as invalid non-type argument.
5772      This special-case is not needed for correctness (we would easily
5773      catch this later), but only to provide better diagnostic for this
5774      common user mistake. As suggested by DR 100, we do not mention
5775      linkage issues in the diagnostic as this is not the point.  */
5776   /* FIXME we're making this OK.  */
5777   if (TREE_CODE (expr) == STRING_CST)
5778     {
5779       if (complain & tf_error)
5780         error ("%qE is not a valid template argument for type %qT "
5781                "because string literals can never be used in this context",
5782                expr, type);
5783       return NULL_TREE;
5784     }
5785
5786   /* Add the ADDR_EXPR now for the benefit of
5787      value_dependent_expression_p.  */
5788   if (TYPE_PTROBV_P (type)
5789       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5790     {
5791       expr = decay_conversion (expr, complain);
5792       if (expr == error_mark_node)
5793         return error_mark_node;
5794     }
5795
5796   /* If we are in a template, EXPR may be non-dependent, but still
5797      have a syntactic, rather than semantic, form.  For example, EXPR
5798      might be a SCOPE_REF, rather than the VAR_DECL to which the
5799      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5800      so that access checking can be performed when the template is
5801      instantiated -- but here we need the resolved form so that we can
5802      convert the argument.  */
5803   bool non_dep = false;
5804   if (TYPE_REF_OBJ_P (type)
5805       && has_value_dependent_address (expr))
5806     /* If we want the address and it's value-dependent, don't fold.  */;
5807   else if (!type_unknown_p (expr)
5808            && processing_template_decl
5809            && !instantiation_dependent_expression_p (expr)
5810            && potential_constant_expression (expr))
5811     non_dep = true;
5812   if (error_operand_p (expr))
5813     return error_mark_node;
5814   expr_type = TREE_TYPE (expr);
5815   if (TREE_CODE (type) == REFERENCE_TYPE)
5816     expr = mark_lvalue_use (expr);
5817   else
5818     expr = mark_rvalue_use (expr);
5819
5820   /* If the argument is non-dependent, perform any conversions in
5821      non-dependent context as well.  */
5822   processing_template_decl_sentinel s (non_dep);
5823   if (non_dep)
5824     expr = instantiate_non_dependent_expr_internal (expr, complain);
5825
5826   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5827      to a non-type argument of "nullptr".  */
5828   if (expr == nullptr_node && TYPE_PTR_OR_PTRMEM_P (type))
5829     expr = convert (type, expr);
5830
5831   /* In C++11, integral or enumeration non-type template arguments can be
5832      arbitrary constant expressions.  Pointer and pointer to
5833      member arguments can be general constant expressions that evaluate
5834      to a null value, but otherwise still need to be of a specific form.  */
5835   if (cxx_dialect >= cxx11)
5836     {
5837       if (TREE_CODE (expr) == PTRMEM_CST)
5838         /* A PTRMEM_CST is already constant, and a valid template
5839            argument for a parameter of pointer to member type, we just want
5840            to leave it in that form rather than lower it to a
5841            CONSTRUCTOR.  */;
5842       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5843         expr = maybe_constant_value (expr);
5844       else if (TYPE_PTR_OR_PTRMEM_P (type))
5845         {
5846           tree folded = maybe_constant_value (expr);
5847           if (TYPE_PTR_P (type) ? integer_zerop (folded)
5848               : null_member_pointer_value_p (folded))
5849             expr = folded;
5850         }
5851     }
5852
5853   /* HACK: Due to double coercion, we can get a
5854      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5855      which is the tree that we built on the first call (see
5856      below when coercing to reference to object or to reference to
5857      function). We just strip everything and get to the arg.
5858      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5859      for examples.  */
5860   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5861     {
5862       tree probe_type, probe = expr;
5863       if (REFERENCE_REF_P (probe))
5864         probe = TREE_OPERAND (probe, 0);
5865       probe_type = TREE_TYPE (probe);
5866       if (TREE_CODE (probe) == NOP_EXPR)
5867         {
5868           /* ??? Maybe we could use convert_from_reference here, but we
5869              would need to relax its constraints because the NOP_EXPR
5870              could actually change the type to something more cv-qualified,
5871              and this is not folded by convert_from_reference.  */
5872           tree addr = TREE_OPERAND (probe, 0);
5873           if (TREE_CODE (probe_type) == REFERENCE_TYPE
5874               && TREE_CODE (addr) == ADDR_EXPR
5875               && TYPE_PTR_P (TREE_TYPE (addr))
5876               && (same_type_ignoring_top_level_qualifiers_p
5877                   (TREE_TYPE (probe_type),
5878                    TREE_TYPE (TREE_TYPE (addr)))))
5879             {
5880               expr = TREE_OPERAND (addr, 0);
5881               expr_type = TREE_TYPE (probe_type);
5882             }
5883         }
5884     }
5885
5886   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5887      parameter is a pointer to object, through decay and
5888      qualification conversion. Let's strip everything.  */
5889   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5890     {
5891       tree probe = expr;
5892       STRIP_NOPS (probe);
5893       if (TREE_CODE (probe) == ADDR_EXPR
5894           && TYPE_PTR_P (TREE_TYPE (probe)))
5895         {
5896           /* Skip the ADDR_EXPR only if it is part of the decay for
5897              an array. Otherwise, it is part of the original argument
5898              in the source code.  */
5899           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (probe, 0))) == ARRAY_TYPE)
5900             probe = TREE_OPERAND (probe, 0);
5901           expr = probe;
5902           expr_type = TREE_TYPE (expr);
5903         }
5904     }
5905
5906   /* [temp.arg.nontype]/5, bullet 1
5907
5908      For a non-type template-parameter of integral or enumeration type,
5909      integral promotions (_conv.prom_) and integral conversions
5910      (_conv.integral_) are applied.  */
5911   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5912     {
5913       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5914       t = maybe_constant_value (t);
5915       if (t != error_mark_node)
5916         expr = t;
5917
5918       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5919         return error_mark_node;
5920
5921       /* Notice that there are constant expressions like '4 % 0' which
5922          do not fold into integer constants.  */
5923       if (TREE_CODE (expr) != INTEGER_CST)
5924         {
5925           if (complain & tf_error)
5926             {
5927               int errs = errorcount, warns = warningcount + werrorcount;
5928               if (processing_template_decl
5929                   && !require_potential_constant_expression (expr))
5930                 return NULL_TREE;
5931               expr = cxx_constant_value (expr);
5932               if (errorcount > errs || warningcount + werrorcount > warns)
5933                 inform (EXPR_LOC_OR_LOC (expr, input_location),
5934                         "in template argument for type %qT ", type);
5935               if (expr == error_mark_node)
5936                 return NULL_TREE;
5937               /* else cxx_constant_value complained but gave us
5938                  a real constant, so go ahead.  */
5939               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5940             }
5941           else
5942             return NULL_TREE;
5943         }
5944
5945       /* Avoid typedef problems.  */
5946       if (TREE_TYPE (expr) != type)
5947         expr = fold_convert (type, expr);
5948     }
5949   /* [temp.arg.nontype]/5, bullet 2
5950
5951      For a non-type template-parameter of type pointer to object,
5952      qualification conversions (_conv.qual_) and the array-to-pointer
5953      conversion (_conv.array_) are applied.  */
5954   else if (TYPE_PTROBV_P (type))
5955     {
5956       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5957
5958          A template-argument for a non-type, non-template template-parameter
5959          shall be one of: [...]
5960
5961          -- the name of a non-type template-parameter;
5962          -- the address of an object or function with external linkage, [...]
5963             expressed as "& id-expression" where the & is optional if the name
5964             refers to a function or array, or if the corresponding
5965             template-parameter is a reference.
5966
5967         Here, we do not care about functions, as they are invalid anyway
5968         for a parameter of type pointer-to-object.  */
5969
5970       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5971         /* Non-type template parameters are OK.  */
5972         ;
5973       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
5974         /* Null pointer values are OK in C++11.  */;
5975       else if (TREE_CODE (expr) != ADDR_EXPR
5976                && TREE_CODE (expr_type) != ARRAY_TYPE)
5977         {
5978           if (VAR_P (expr))
5979             {
5980               if (complain & tf_error)
5981                 error ("%qD is not a valid template argument "
5982                        "because %qD is a variable, not the address of "
5983                        "a variable", expr, expr);
5984               return NULL_TREE;
5985             }
5986           if (POINTER_TYPE_P (expr_type))
5987             {
5988               if (complain & tf_error)
5989                 error ("%qE is not a valid template argument for %qT "
5990                        "because it is not the address of a variable",
5991                        expr, type);
5992               return NULL_TREE;
5993             }
5994           /* Other values, like integer constants, might be valid
5995              non-type arguments of some other type.  */
5996           return error_mark_node;
5997         }
5998       else
5999         {
6000           tree decl;
6001
6002           decl = ((TREE_CODE (expr) == ADDR_EXPR)
6003                   ? TREE_OPERAND (expr, 0) : expr);
6004           if (!VAR_P (decl))
6005             {
6006               if (complain & tf_error)
6007                 error ("%qE is not a valid template argument of type %qT "
6008                        "because %qE is not a variable", expr, type, decl);
6009               return NULL_TREE;
6010             }
6011           else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6012             {
6013               if (complain & tf_error)
6014                 error ("%qE is not a valid template argument of type %qT "
6015                        "because %qD does not have external linkage",
6016                        expr, type, decl);
6017               return NULL_TREE;
6018             }
6019           else if (cxx_dialect >= cxx11 && decl_linkage (decl) == lk_none)
6020             {
6021               if (complain & tf_error)
6022                 error ("%qE is not a valid template argument of type %qT "
6023                        "because %qD has no linkage", expr, type, decl);
6024               return NULL_TREE;
6025             }
6026         }
6027
6028       expr = decay_conversion (expr, complain);
6029       if (expr == error_mark_node)
6030         return error_mark_node;
6031
6032       expr = perform_qualification_conversions (type, expr);
6033       if (expr == error_mark_node)
6034         return error_mark_node;
6035     }
6036   /* [temp.arg.nontype]/5, bullet 3
6037
6038      For a non-type template-parameter of type reference to object, no
6039      conversions apply. The type referred to by the reference may be more
6040      cv-qualified than the (otherwise identical) type of the
6041      template-argument. The template-parameter is bound directly to the
6042      template-argument, which must be an lvalue.  */
6043   else if (TYPE_REF_OBJ_P (type))
6044     {
6045       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6046                                                       expr_type))
6047         return error_mark_node;
6048
6049       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6050         {
6051           if (complain & tf_error)
6052             error ("%qE is not a valid template argument for type %qT "
6053                    "because of conflicts in cv-qualification", expr, type);
6054           return NULL_TREE;
6055         }
6056
6057       if (!real_lvalue_p (expr))
6058         {
6059           if (complain & tf_error)
6060             error ("%qE is not a valid template argument for type %qT "
6061                    "because it is not an lvalue", expr, type);
6062           return NULL_TREE;
6063         }
6064
6065       /* [temp.arg.nontype]/1
6066
6067          A template-argument for a non-type, non-template template-parameter
6068          shall be one of: [...]
6069
6070          -- the address of an object or function with external linkage.  */
6071       if (INDIRECT_REF_P (expr)
6072           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6073         {
6074           expr = TREE_OPERAND (expr, 0);
6075           if (DECL_P (expr))
6076             {
6077               if (complain & tf_error)
6078                 error ("%q#D is not a valid template argument for type %qT "
6079                        "because a reference variable does not have a constant "
6080                        "address", expr, type);
6081               return NULL_TREE;
6082             }
6083         }
6084
6085       if (!DECL_P (expr))
6086         {
6087           if (complain & tf_error)
6088             error ("%qE is not a valid template argument for type %qT "
6089                    "because it is not an object with external linkage",
6090                    expr, type);
6091           return NULL_TREE;
6092         }
6093
6094       if (!DECL_EXTERNAL_LINKAGE_P (expr))
6095         {
6096           if (complain & tf_error)
6097             error ("%qE is not a valid template argument for type %qT "
6098                    "because object %qD has not external linkage",
6099                    expr, type, expr);
6100           return NULL_TREE;
6101         }
6102
6103       expr = build_nop (type, build_address (expr));
6104     }
6105   /* [temp.arg.nontype]/5, bullet 4
6106
6107      For a non-type template-parameter of type pointer to function, only
6108      the function-to-pointer conversion (_conv.func_) is applied. If the
6109      template-argument represents a set of overloaded functions (or a
6110      pointer to such), the matching function is selected from the set
6111      (_over.over_).  */
6112   else if (TYPE_PTRFN_P (type))
6113     {
6114       /* If the argument is a template-id, we might not have enough
6115          context information to decay the pointer.  */
6116       if (!type_unknown_p (expr_type))
6117         {
6118           expr = decay_conversion (expr, complain);
6119           if (expr == error_mark_node)
6120             return error_mark_node;
6121         }
6122
6123       if (cxx_dialect >= cxx11 && integer_zerop (expr))
6124         /* Null pointer values are OK in C++11.  */
6125         return perform_qualification_conversions (type, expr);
6126
6127       expr = convert_nontype_argument_function (type, expr, complain);
6128       if (!expr || expr == error_mark_node)
6129         return expr;
6130     }
6131   /* [temp.arg.nontype]/5, bullet 5
6132
6133      For a non-type template-parameter of type reference to function, no
6134      conversions apply. If the template-argument represents a set of
6135      overloaded functions, the matching function is selected from the set
6136      (_over.over_).  */
6137   else if (TYPE_REFFN_P (type))
6138     {
6139       if (TREE_CODE (expr) == ADDR_EXPR)
6140         {
6141           if (complain & tf_error)
6142             {
6143               error ("%qE is not a valid template argument for type %qT "
6144                      "because it is a pointer", expr, type);
6145               inform (input_location, "try using %qE instead",
6146                       TREE_OPERAND (expr, 0));
6147             }
6148           return NULL_TREE;
6149         }
6150
6151       expr = convert_nontype_argument_function (type, expr, complain);
6152       if (!expr || expr == error_mark_node)
6153         return expr;
6154
6155       expr = build_nop (type, build_address (expr));
6156     }
6157   /* [temp.arg.nontype]/5, bullet 6
6158
6159      For a non-type template-parameter of type pointer to member function,
6160      no conversions apply. If the template-argument represents a set of
6161      overloaded member functions, the matching member function is selected
6162      from the set (_over.over_).  */
6163   else if (TYPE_PTRMEMFUNC_P (type))
6164     {
6165       expr = instantiate_type (type, expr, tf_none);
6166       if (expr == error_mark_node)
6167         return error_mark_node;
6168
6169       /* [temp.arg.nontype] bullet 1 says the pointer to member
6170          expression must be a pointer-to-member constant.  */
6171       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6172         return error_mark_node;
6173
6174       /* There is no way to disable standard conversions in
6175          resolve_address_of_overloaded_function (called by
6176          instantiate_type). It is possible that the call succeeded by
6177          converting &B::I to &D::I (where B is a base of D), so we need
6178          to reject this conversion here.
6179
6180          Actually, even if there was a way to disable standard conversions,
6181          it would still be better to reject them here so that we can
6182          provide a superior diagnostic.  */
6183       if (!same_type_p (TREE_TYPE (expr), type))
6184         {
6185           if (complain & tf_error)
6186             {
6187               error ("%qE is not a valid template argument for type %qT "
6188                      "because it is of type %qT", expr, type,
6189                      TREE_TYPE (expr));
6190               /* If we are just one standard conversion off, explain.  */
6191               if (can_convert_standard (type, TREE_TYPE (expr), complain))
6192                 inform (input_location,
6193                         "standard conversions are not allowed in this context");
6194             }
6195           return NULL_TREE;
6196         }
6197     }
6198   /* [temp.arg.nontype]/5, bullet 7
6199
6200      For a non-type template-parameter of type pointer to data member,
6201      qualification conversions (_conv.qual_) are applied.  */
6202   else if (TYPE_PTRDATAMEM_P (type))
6203     {
6204       /* [temp.arg.nontype] bullet 1 says the pointer to member
6205          expression must be a pointer-to-member constant.  */
6206       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6207         return error_mark_node;
6208
6209       expr = perform_qualification_conversions (type, expr);
6210       if (expr == error_mark_node)
6211         return expr;
6212     }
6213   else if (NULLPTR_TYPE_P (type))
6214     {
6215       if (expr != nullptr_node)
6216         {
6217           if (complain & tf_error)
6218             error ("%qE is not a valid template argument for type %qT "
6219                    "because it is of type %qT", expr, type, TREE_TYPE (expr));
6220           return NULL_TREE;
6221         }
6222       return expr;
6223     }
6224   /* A template non-type parameter must be one of the above.  */
6225   else
6226     gcc_unreachable ();
6227
6228   /* Sanity check: did we actually convert the argument to the
6229      right type?  */
6230   gcc_assert (same_type_ignoring_top_level_qualifiers_p
6231               (type, TREE_TYPE (expr)));
6232   return convert_from_reference (expr);
6233 }
6234
6235 /* Subroutine of coerce_template_template_parms, which returns 1 if
6236    PARM_PARM and ARG_PARM match using the rule for the template
6237    parameters of template template parameters. Both PARM and ARG are
6238    template parameters; the rest of the arguments are the same as for
6239    coerce_template_template_parms.
6240  */
6241 static int
6242 coerce_template_template_parm (tree parm,
6243                               tree arg,
6244                               tsubst_flags_t complain,
6245                               tree in_decl,
6246                               tree outer_args)
6247 {
6248   if (arg == NULL_TREE || error_operand_p (arg)
6249       || parm == NULL_TREE || error_operand_p (parm))
6250     return 0;
6251   
6252   if (TREE_CODE (arg) != TREE_CODE (parm))
6253     return 0;
6254   
6255   switch (TREE_CODE (parm))
6256     {
6257     case TEMPLATE_DECL:
6258       /* We encounter instantiations of templates like
6259          template <template <template <class> class> class TT>
6260          class C;  */
6261       {
6262         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6263         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6264         
6265         if (!coerce_template_template_parms
6266             (parmparm, argparm, complain, in_decl, outer_args))
6267           return 0;
6268       }
6269       /* Fall through.  */
6270       
6271     case TYPE_DECL:
6272       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6273           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6274         /* Argument is a parameter pack but parameter is not.  */
6275         return 0;
6276       break;
6277       
6278     case PARM_DECL:
6279       /* The tsubst call is used to handle cases such as
6280          
6281            template <int> class C {};
6282            template <class T, template <T> class TT> class D {};
6283            D<int, C> d;
6284
6285          i.e. the parameter list of TT depends on earlier parameters.  */
6286       if (!uses_template_parms (TREE_TYPE (arg))
6287           && !same_type_p
6288                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
6289                  TREE_TYPE (arg)))
6290         return 0;
6291       
6292       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6293           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6294         /* Argument is a parameter pack but parameter is not.  */
6295         return 0;
6296       
6297       break;
6298
6299     default:
6300       gcc_unreachable ();
6301     }
6302
6303   return 1;
6304 }
6305
6306
6307 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6308    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6309    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6310    or PARM_DECL.
6311
6312    Consider the example:
6313      template <class T> class A;
6314      template<template <class U> class TT> class B;
6315
6316    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6317    the parameters to A, and OUTER_ARGS contains A.  */
6318
6319 static int
6320 coerce_template_template_parms (tree parm_parms,
6321                                 tree arg_parms,
6322                                 tsubst_flags_t complain,
6323                                 tree in_decl,
6324                                 tree outer_args)
6325 {
6326   int nparms, nargs, i;
6327   tree parm, arg;
6328   int variadic_p = 0;
6329
6330   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6331   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6332
6333   nparms = TREE_VEC_LENGTH (parm_parms);
6334   nargs = TREE_VEC_LENGTH (arg_parms);
6335
6336   /* Determine whether we have a parameter pack at the end of the
6337      template template parameter's template parameter list.  */
6338   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6339     {
6340       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6341       
6342       if (error_operand_p (parm))
6343         return 0;
6344
6345       switch (TREE_CODE (parm))
6346         {
6347         case TEMPLATE_DECL:
6348         case TYPE_DECL:
6349           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6350             variadic_p = 1;
6351           break;
6352           
6353         case PARM_DECL:
6354           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6355             variadic_p = 1;
6356           break;
6357           
6358         default:
6359           gcc_unreachable ();
6360         }
6361     }
6362  
6363   if (nargs != nparms
6364       && !(variadic_p && nargs >= nparms - 1))
6365     return 0;
6366
6367   /* Check all of the template parameters except the parameter pack at
6368      the end (if any).  */
6369   for (i = 0; i < nparms - variadic_p; ++i)
6370     {
6371       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6372           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6373         continue;
6374
6375       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6376       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6377
6378       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6379                                           outer_args))
6380         return 0;
6381
6382     }
6383
6384   if (variadic_p)
6385     {
6386       /* Check each of the template parameters in the template
6387          argument against the template parameter pack at the end of
6388          the template template parameter.  */
6389       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6390         return 0;
6391
6392       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6393
6394       for (; i < nargs; ++i)
6395         {
6396           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6397             continue;
6398  
6399           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6400  
6401           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6402                                               outer_args))
6403             return 0;
6404         }
6405     }
6406
6407   return 1;
6408 }
6409
6410 /* Verifies that the deduced template arguments (in TARGS) for the
6411    template template parameters (in TPARMS) represent valid bindings,
6412    by comparing the template parameter list of each template argument
6413    to the template parameter list of its corresponding template
6414    template parameter, in accordance with DR150. This
6415    routine can only be called after all template arguments have been
6416    deduced. It will return TRUE if all of the template template
6417    parameter bindings are okay, FALSE otherwise.  */
6418 bool 
6419 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6420 {
6421   int i, ntparms = TREE_VEC_LENGTH (tparms);
6422   bool ret = true;
6423
6424   /* We're dealing with template parms in this process.  */
6425   ++processing_template_decl;
6426
6427   targs = INNERMOST_TEMPLATE_ARGS (targs);
6428
6429   for (i = 0; i < ntparms; ++i)
6430     {
6431       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6432       tree targ = TREE_VEC_ELT (targs, i);
6433
6434       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6435         {
6436           tree packed_args = NULL_TREE;
6437           int idx, len = 1;
6438
6439           if (ARGUMENT_PACK_P (targ))
6440             {
6441               /* Look inside the argument pack.  */
6442               packed_args = ARGUMENT_PACK_ARGS (targ);
6443               len = TREE_VEC_LENGTH (packed_args);
6444             }
6445
6446           for (idx = 0; idx < len; ++idx)
6447             {
6448               tree targ_parms = NULL_TREE;
6449
6450               if (packed_args)
6451                 /* Extract the next argument from the argument
6452                    pack.  */
6453                 targ = TREE_VEC_ELT (packed_args, idx);
6454
6455               if (PACK_EXPANSION_P (targ))
6456                 /* Look at the pattern of the pack expansion.  */
6457                 targ = PACK_EXPANSION_PATTERN (targ);
6458
6459               /* Extract the template parameters from the template
6460                  argument.  */
6461               if (TREE_CODE (targ) == TEMPLATE_DECL)
6462                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6463               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6464                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6465
6466               /* Verify that we can coerce the template template
6467                  parameters from the template argument to the template
6468                  parameter.  This requires an exact match.  */
6469               if (targ_parms
6470                   && !coerce_template_template_parms
6471                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6472                         targ_parms,
6473                         tf_none,
6474                         tparm,
6475                         targs))
6476                 {
6477                   ret = false;
6478                   goto out;
6479                 }
6480             }
6481         }
6482     }
6483
6484  out:
6485
6486   --processing_template_decl;
6487   return ret;
6488 }
6489
6490 /* Since type attributes aren't mangled, we need to strip them from
6491    template type arguments.  */
6492
6493 static tree
6494 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6495 {
6496   tree mv;
6497   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6498     return arg;
6499   mv = TYPE_MAIN_VARIANT (arg);
6500   arg = strip_typedefs (arg);
6501   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6502       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6503     {
6504       if (complain & tf_warning)
6505         warning (0, "ignoring attributes on template argument %qT", arg);
6506       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6507       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6508     }
6509   return arg;
6510 }
6511
6512 /* Convert the indicated template ARG as necessary to match the
6513    indicated template PARM.  Returns the converted ARG, or
6514    error_mark_node if the conversion was unsuccessful.  Error and
6515    warning messages are issued under control of COMPLAIN.  This
6516    conversion is for the Ith parameter in the parameter list.  ARGS is
6517    the full set of template arguments deduced so far.  */
6518
6519 static tree
6520 convert_template_argument (tree parm,
6521                            tree arg,
6522                            tree args,
6523                            tsubst_flags_t complain,
6524                            int i,
6525                            tree in_decl)
6526 {
6527   tree orig_arg;
6528   tree val;
6529   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6530
6531   if (parm == error_mark_node)
6532     return error_mark_node;
6533
6534   if (TREE_CODE (arg) == TREE_LIST
6535       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6536     {
6537       /* The template argument was the name of some
6538          member function.  That's usually
6539          invalid, but static members are OK.  In any
6540          case, grab the underlying fields/functions
6541          and issue an error later if required.  */
6542       orig_arg = TREE_VALUE (arg);
6543       TREE_TYPE (arg) = unknown_type_node;
6544     }
6545
6546   orig_arg = arg;
6547
6548   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6549   requires_type = (TREE_CODE (parm) == TYPE_DECL
6550                    || requires_tmpl_type);
6551
6552   /* When determining whether an argument pack expansion is a template,
6553      look at the pattern.  */
6554   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6555     arg = PACK_EXPANSION_PATTERN (arg);
6556
6557   /* Deal with an injected-class-name used as a template template arg.  */
6558   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6559     {
6560       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6561       if (TREE_CODE (t) == TEMPLATE_DECL)
6562         {
6563           if (cxx_dialect >= cxx11)
6564             /* OK under DR 1004.  */;
6565           else if (complain & tf_warning_or_error)
6566             pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
6567                      " used as template template argument", TYPE_NAME (arg));
6568           else if (flag_pedantic_errors)
6569             t = arg;
6570
6571           arg = t;
6572         }
6573     }
6574
6575   is_tmpl_type = 
6576     ((TREE_CODE (arg) == TEMPLATE_DECL
6577       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6578      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
6579      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6580      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6581
6582   if (is_tmpl_type
6583       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6584           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6585     arg = TYPE_STUB_DECL (arg);
6586
6587   is_type = TYPE_P (arg) || is_tmpl_type;
6588
6589   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6590       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6591     {
6592       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
6593         {
6594           if (complain & tf_error)
6595             error ("invalid use of destructor %qE as a type", orig_arg);
6596           return error_mark_node;
6597         }
6598
6599       permerror (input_location,
6600                  "to refer to a type member of a template parameter, "
6601                  "use %<typename %E%>", orig_arg);
6602
6603       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6604                                      TREE_OPERAND (arg, 1),
6605                                      typename_type,
6606                                      complain);
6607       arg = orig_arg;
6608       is_type = 1;
6609     }
6610   if (is_type != requires_type)
6611     {
6612       if (in_decl)
6613         {
6614           if (complain & tf_error)
6615             {
6616               error ("type/value mismatch at argument %d in template "
6617                      "parameter list for %qD",
6618                      i + 1, in_decl);
6619               if (is_type)
6620                 inform (input_location,
6621                         "  expected a constant of type %qT, got %qT",
6622                         TREE_TYPE (parm),
6623                         (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6624               else if (requires_tmpl_type)
6625                 inform (input_location,
6626                         "  expected a class template, got %qE", orig_arg);
6627               else
6628                 inform (input_location,
6629                         "  expected a type, got %qE", orig_arg);
6630             }
6631         }
6632       return error_mark_node;
6633     }
6634   if (is_tmpl_type ^ requires_tmpl_type)
6635     {
6636       if (in_decl && (complain & tf_error))
6637         {
6638           error ("type/value mismatch at argument %d in template "
6639                  "parameter list for %qD",
6640                  i + 1, in_decl);
6641           if (is_tmpl_type)
6642             inform (input_location,
6643                     "  expected a type, got %qT", DECL_NAME (arg));
6644           else
6645             inform (input_location,
6646                     "  expected a class template, got %qT", orig_arg);
6647         }
6648       return error_mark_node;
6649     }
6650
6651   if (is_type)
6652     {
6653       if (requires_tmpl_type)
6654         {
6655           if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6656             val = orig_arg;
6657           else if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6658             /* The number of argument required is not known yet.
6659                Just accept it for now.  */
6660             val = TREE_TYPE (arg);
6661           else
6662             {
6663               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6664               tree argparm;
6665
6666               /* Strip alias templates that are equivalent to another
6667                  template.  */
6668               arg = get_underlying_template (arg);
6669               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6670
6671               if (coerce_template_template_parms (parmparm, argparm,
6672                                                   complain, in_decl,
6673                                                   args))
6674                 {
6675                   val = arg;
6676
6677                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6678                      TEMPLATE_DECL.  */
6679                   if (val != error_mark_node)
6680                     {
6681                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6682                         val = TREE_TYPE (val);
6683                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6684                         val = make_pack_expansion (val);
6685                     }
6686                 }
6687               else
6688                 {
6689                   if (in_decl && (complain & tf_error))
6690                     {
6691                       error ("type/value mismatch at argument %d in "
6692                              "template parameter list for %qD",
6693                              i + 1, in_decl);
6694                       inform (input_location,
6695                               "  expected a template of type %qD, got %qT",
6696                               parm, orig_arg);
6697                     }
6698
6699                   val = error_mark_node;
6700                 }
6701             }
6702         }
6703       else
6704         val = orig_arg;
6705       /* We only form one instance of each template specialization.
6706          Therefore, if we use a non-canonical variant (i.e., a
6707          typedef), any future messages referring to the type will use
6708          the typedef, which is confusing if those future uses do not
6709          themselves also use the typedef.  */
6710       if (TYPE_P (val))
6711         val = canonicalize_type_argument (val, complain);
6712     }
6713   else
6714     {
6715       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6716
6717       if (invalid_nontype_parm_type_p (t, complain))
6718         return error_mark_node;
6719
6720       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6721         {
6722           if (same_type_p (t, TREE_TYPE (orig_arg)))
6723             val = orig_arg;
6724           else
6725             {
6726               /* Not sure if this is reachable, but it doesn't hurt
6727                  to be robust.  */
6728               error ("type mismatch in nontype parameter pack");
6729               val = error_mark_node;
6730             }
6731         }
6732       else if (!dependent_template_arg_p (orig_arg)
6733                && !uses_template_parms (t))
6734         /* We used to call digest_init here.  However, digest_init
6735            will report errors, which we don't want when complain
6736            is zero.  More importantly, digest_init will try too
6737            hard to convert things: for example, `0' should not be
6738            converted to pointer type at this point according to
6739            the standard.  Accepting this is not merely an
6740            extension, since deciding whether or not these
6741            conversions can occur is part of determining which
6742            function template to call, or whether a given explicit
6743            argument specification is valid.  */
6744         val = convert_nontype_argument (t, orig_arg, complain);
6745       else
6746         val = strip_typedefs_expr (orig_arg);
6747
6748       if (val == NULL_TREE)
6749         val = error_mark_node;
6750       else if (val == error_mark_node && (complain & tf_error))
6751         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6752
6753       if (TREE_CODE (val) == SCOPE_REF)
6754         {
6755           /* Strip typedefs from the SCOPE_REF.  */
6756           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6757           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6758                                                    complain);
6759           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6760                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6761         }
6762     }
6763
6764   return val;
6765 }
6766
6767 /* Coerces the remaining template arguments in INNER_ARGS (from
6768    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6769    Returns the coerced argument pack. PARM_IDX is the position of this
6770    parameter in the template parameter list. ARGS is the original
6771    template argument list.  */
6772 static tree
6773 coerce_template_parameter_pack (tree parms,
6774                                 int parm_idx,
6775                                 tree args,
6776                                 tree inner_args,
6777                                 int arg_idx,
6778                                 tree new_args,
6779                                 int* lost,
6780                                 tree in_decl,
6781                                 tsubst_flags_t complain)
6782 {
6783   tree parm = TREE_VEC_ELT (parms, parm_idx);
6784   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6785   tree packed_args;
6786   tree argument_pack;
6787   tree packed_parms = NULL_TREE;
6788
6789   if (arg_idx > nargs)
6790     arg_idx = nargs;
6791
6792   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
6793     {
6794       /* When the template parameter is a non-type template parameter pack
6795          or template template parameter pack whose type or template
6796          parameters use parameter packs, we know exactly how many arguments
6797          we are looking for.  Build a vector of the instantiated decls for
6798          these template parameters in PACKED_PARMS.  */
6799       /* We can't use make_pack_expansion here because it would interpret a
6800          _DECL as a use rather than a declaration.  */
6801       tree decl = TREE_VALUE (parm);
6802       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
6803       SET_PACK_EXPANSION_PATTERN (exp, decl);
6804       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
6805       SET_TYPE_STRUCTURAL_EQUALITY (exp);
6806
6807       TREE_VEC_LENGTH (args)--;
6808       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
6809       TREE_VEC_LENGTH (args)++;
6810
6811       if (packed_parms == error_mark_node)
6812         return error_mark_node;
6813
6814       /* If we're doing a partial instantiation of a member template,
6815          verify that all of the types used for the non-type
6816          template parameter pack are, in fact, valid for non-type
6817          template parameters.  */
6818       if (arg_idx < nargs
6819           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6820         {
6821           int j, len = TREE_VEC_LENGTH (packed_parms);
6822           for (j = 0; j < len; ++j)
6823             {
6824               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
6825               if (invalid_nontype_parm_type_p (t, complain))
6826                 return error_mark_node;
6827             }
6828           /* We don't know how many args we have yet, just
6829              use the unconverted ones for now.  */
6830           return NULL_TREE;
6831         }
6832
6833       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
6834     }
6835   else
6836     packed_args = make_tree_vec (nargs - arg_idx);
6837
6838   /* Convert the remaining arguments, which will be a part of the
6839      parameter pack "parm".  */
6840   for (; arg_idx < nargs; ++arg_idx)
6841     {
6842       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6843       tree actual_parm = TREE_VALUE (parm);
6844       int pack_idx = arg_idx - parm_idx;
6845
6846       if (packed_parms)
6847         {
6848           /* Once we've packed as many args as we have types, stop.  */
6849           if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
6850             break;
6851           else if (PACK_EXPANSION_P (arg))
6852             /* We don't know how many args we have yet, just
6853                use the unconverted ones for now.  */
6854             return NULL_TREE;
6855           else
6856             actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
6857         }
6858
6859       if (arg == error_mark_node)
6860         {
6861           if (complain & tf_error)
6862             error ("template argument %d is invalid", arg_idx + 1);
6863         }
6864       else
6865         arg = convert_template_argument (actual_parm, 
6866                                          arg, new_args, complain, parm_idx,
6867                                          in_decl);
6868       if (arg == error_mark_node)
6869         (*lost)++;
6870       TREE_VEC_ELT (packed_args, pack_idx) = arg;
6871     }
6872
6873   if (arg_idx - parm_idx < TREE_VEC_LENGTH (packed_args)
6874       && TREE_VEC_LENGTH (packed_args) > 0)
6875     {
6876       if (complain & tf_error)
6877         error ("wrong number of template arguments (%d, should be %d)",
6878                arg_idx - parm_idx, TREE_VEC_LENGTH (packed_args));
6879       return error_mark_node;
6880     }
6881
6882   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6883       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6884     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6885   else
6886     {
6887       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6888       TREE_TYPE (argument_pack) 
6889         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6890       TREE_CONSTANT (argument_pack) = 1;
6891     }
6892
6893   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6894 #ifdef ENABLE_CHECKING
6895   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6896                                        TREE_VEC_LENGTH (packed_args));
6897 #endif
6898   return argument_pack;
6899 }
6900
6901 /* Returns the number of pack expansions in the template argument vector
6902    ARGS.  */
6903
6904 static int
6905 pack_expansion_args_count (tree args)
6906 {
6907   int i;
6908   int count = 0;
6909   if (args)
6910     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
6911       {
6912         tree elt = TREE_VEC_ELT (args, i);
6913         if (elt && PACK_EXPANSION_P (elt))
6914           ++count;
6915       }
6916   return count;
6917 }
6918
6919 /* Convert all template arguments to their appropriate types, and
6920    return a vector containing the innermost resulting template
6921    arguments.  If any error occurs, return error_mark_node. Error and
6922    warning messages are issued under control of COMPLAIN.
6923
6924    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6925    for arguments not specified in ARGS.  Otherwise, if
6926    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6927    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6928    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6929    ARGS.  */
6930
6931 static tree
6932 coerce_template_parms (tree parms,
6933                        tree args,
6934                        tree in_decl,
6935                        tsubst_flags_t complain,
6936                        bool require_all_args,
6937                        bool use_default_args)
6938 {
6939   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6940   tree orig_inner_args;
6941   tree inner_args;
6942   tree new_args;
6943   tree new_inner_args;
6944   int saved_unevaluated_operand;
6945   int saved_inhibit_evaluation_warnings;
6946
6947   /* When used as a boolean value, indicates whether this is a
6948      variadic template parameter list. Since it's an int, we can also
6949      subtract it from nparms to get the number of non-variadic
6950      parameters.  */
6951   int variadic_p = 0;
6952   int variadic_args_p = 0;
6953   int post_variadic_parms = 0;
6954
6955   /* Likewise for parameters with default arguments.  */
6956   int default_p = 0;
6957
6958   if (args == error_mark_node)
6959     return error_mark_node;
6960
6961   nparms = TREE_VEC_LENGTH (parms);
6962
6963   /* Determine if there are any parameter packs or default arguments.  */
6964   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6965     {
6966       tree parm = TREE_VEC_ELT (parms, parm_idx);
6967       if (variadic_p)
6968         ++post_variadic_parms;
6969       if (template_parameter_pack_p (TREE_VALUE (parm)))
6970         ++variadic_p;
6971       if (TREE_PURPOSE (parm))
6972         ++default_p;
6973     }
6974
6975   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
6976   /* If there are no parameters that follow a parameter pack, we need to
6977      expand any argument packs so that we can deduce a parameter pack from
6978      some non-packed args followed by an argument pack, as in variadic85.C.
6979      If there are such parameters, we need to leave argument packs intact
6980      so the arguments are assigned properly.  This can happen when dealing
6981      with a nested class inside a partial specialization of a class
6982      template, as in variadic92.C, or when deducing a template parameter pack
6983      from a sub-declarator, as in variadic114.C.  */
6984   if (!post_variadic_parms)
6985     inner_args = expand_template_argument_pack (inner_args);
6986
6987   /* Count any pack expansion args.  */
6988   variadic_args_p = pack_expansion_args_count (inner_args);
6989
6990   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6991   if ((nargs > nparms && !variadic_p)
6992       || (nargs < nparms - variadic_p
6993           && require_all_args
6994           && !variadic_args_p
6995           && (!use_default_args
6996               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6997                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6998     {
6999       if (complain & tf_error)
7000         {
7001           if (variadic_p || default_p)
7002             {
7003               nparms -= variadic_p + default_p;
7004               error ("wrong number of template arguments "
7005                      "(%d, should be at least %d)", nargs, nparms);
7006             }
7007           else
7008              error ("wrong number of template arguments "
7009                     "(%d, should be %d)", nargs, nparms);
7010
7011           if (in_decl)
7012             inform (input_location, "provided for %q+D", in_decl);
7013         }
7014
7015       return error_mark_node;
7016     }
7017   /* We can't pass a pack expansion to a non-pack parameter of an alias
7018      template (DR 1430).  */
7019   else if (in_decl && DECL_ALIAS_TEMPLATE_P (in_decl)
7020            && variadic_args_p
7021            && nargs - variadic_args_p < nparms - variadic_p)
7022     {
7023       if (complain & tf_error)
7024         {
7025           for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
7026             {
7027               tree arg = TREE_VEC_ELT (inner_args, i);
7028               tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
7029
7030               if (PACK_EXPANSION_P (arg)
7031                   && !template_parameter_pack_p (parm))
7032                 {
7033                   error ("pack expansion argument for non-pack parameter "
7034                          "%qD of alias template %qD", parm, in_decl);
7035                   inform (DECL_SOURCE_LOCATION (parm), "declared here");
7036                   goto found;
7037                 }
7038             }
7039           gcc_unreachable ();
7040         found:;
7041         }
7042       return error_mark_node;
7043     }
7044
7045   /* We need to evaluate the template arguments, even though this
7046      template-id may be nested within a "sizeof".  */
7047   saved_unevaluated_operand = cp_unevaluated_operand;
7048   cp_unevaluated_operand = 0;
7049   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
7050   c_inhibit_evaluation_warnings = 0;
7051   new_inner_args = make_tree_vec (nparms);
7052   new_args = add_outermost_template_args (args, new_inner_args);
7053   int pack_adjust = 0;
7054   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
7055     {
7056       tree arg;
7057       tree parm;
7058
7059       /* Get the Ith template parameter.  */
7060       parm = TREE_VEC_ELT (parms, parm_idx);
7061  
7062       if (parm == error_mark_node)
7063       {
7064         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
7065         continue;
7066       }
7067
7068       /* Calculate the next argument.  */
7069       if (arg_idx < nargs)
7070         arg = TREE_VEC_ELT (inner_args, arg_idx);
7071       else
7072         arg = NULL_TREE;
7073
7074       if (template_parameter_pack_p (TREE_VALUE (parm))
7075           && !(arg && ARGUMENT_PACK_P (arg)))
7076         {
7077           /* Some arguments will be placed in the
7078              template parameter pack PARM.  */
7079           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
7080                                                 inner_args, arg_idx,
7081                                                 new_args, &lost,
7082                                                 in_decl, complain);
7083
7084           if (arg == NULL_TREE)
7085             {
7086               /* We don't know how many args we have yet, just use the
7087                  unconverted (and still packed) ones for now.  */
7088               new_inner_args = orig_inner_args;
7089               arg_idx = nargs;
7090               break;
7091             }
7092
7093           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
7094
7095           /* Store this argument.  */
7096           if (arg == error_mark_node)
7097             {
7098               lost++;
7099               /* We are done with all of the arguments.  */
7100               arg_idx = nargs;
7101             }
7102           else
7103             {
7104               pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
7105               arg_idx += pack_adjust;
7106             }
7107           
7108           continue;
7109         }
7110       else if (arg)
7111         {
7112           if (PACK_EXPANSION_P (arg))
7113             {
7114               /* "If every valid specialization of a variadic template
7115                  requires an empty template parameter pack, the template is
7116                  ill-formed, no diagnostic required."  So check that the
7117                  pattern works with this parameter.  */
7118               tree pattern = PACK_EXPANSION_PATTERN (arg);
7119               tree conv = convert_template_argument (TREE_VALUE (parm),
7120                                                      pattern, new_args,
7121                                                      complain, parm_idx,
7122                                                      in_decl);
7123               if (conv == error_mark_node)
7124                 {
7125                   inform (input_location, "so any instantiation with a "
7126                          "non-empty parameter pack would be ill-formed");
7127                   ++lost;
7128                 }
7129               else if (TYPE_P (conv) && !TYPE_P (pattern))
7130                 /* Recover from missing typename.  */
7131                 TREE_VEC_ELT (inner_args, arg_idx)
7132                   = make_pack_expansion (conv);
7133
7134               /* We don't know how many args we have yet, just
7135                  use the unconverted ones for now.  */
7136               new_inner_args = inner_args;
7137               arg_idx = nargs;
7138               break;
7139             }
7140         }
7141       else if (require_all_args)
7142         {
7143           /* There must be a default arg in this case.  */
7144           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
7145                                      complain, in_decl);
7146           /* The position of the first default template argument,
7147              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
7148              Record that.  */
7149           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7150             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7151                                                  arg_idx - pack_adjust);
7152         }
7153       else
7154         break;
7155
7156       if (arg == error_mark_node)
7157         {
7158           if (complain & tf_error)
7159             error ("template argument %d is invalid", arg_idx + 1);
7160         }
7161       else if (!arg)
7162         /* This only occurs if there was an error in the template
7163            parameter list itself (which we would already have
7164            reported) that we are trying to recover from, e.g., a class
7165            template with a parameter list such as
7166            template<typename..., typename>.  */
7167         ++lost;
7168       else
7169         arg = convert_template_argument (TREE_VALUE (parm),
7170                                          arg, new_args, complain, 
7171                                          parm_idx, in_decl);
7172
7173       if (arg == error_mark_node)
7174         lost++;
7175       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
7176     }
7177   cp_unevaluated_operand = saved_unevaluated_operand;
7178   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
7179
7180   if (variadic_p && arg_idx < nargs)
7181     {
7182       if (complain & tf_error)
7183         {
7184           error ("wrong number of template arguments "
7185                  "(%d, should be %d)", nargs, arg_idx);
7186           if (in_decl)
7187             error ("provided for %q+D", in_decl);
7188         }
7189       return error_mark_node;
7190     }
7191
7192   if (lost)
7193     return error_mark_node;
7194
7195 #ifdef ENABLE_CHECKING
7196   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7197     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7198                                          TREE_VEC_LENGTH (new_inner_args));
7199 #endif
7200
7201   return new_inner_args;
7202 }
7203
7204 /* Like coerce_template_parms.  If PARMS represents all template
7205    parameters levels, this function returns a vector of vectors
7206    representing all the resulting argument levels.  Note that in this
7207    case, only the innermost arguments are coerced because the
7208    outermost ones are supposed to have been coerced already.
7209
7210    Otherwise, if PARMS represents only (the innermost) vector of
7211    parameters, this function returns a vector containing just the
7212    innermost resulting arguments.  */
7213
7214 static tree
7215 coerce_innermost_template_parms (tree parms,
7216                                   tree args,
7217                                   tree in_decl,
7218                                   tsubst_flags_t complain,
7219                                   bool require_all_args,
7220                                   bool use_default_args)
7221 {
7222   int parms_depth = TMPL_PARMS_DEPTH (parms);
7223   int args_depth = TMPL_ARGS_DEPTH (args);
7224   tree coerced_args;
7225
7226   if (parms_depth > 1)
7227     {
7228       coerced_args = make_tree_vec (parms_depth);
7229       tree level;
7230       int cur_depth;
7231
7232       for (level = parms, cur_depth = parms_depth;
7233            parms_depth > 0 && level != NULL_TREE;
7234            level = TREE_CHAIN (level), --cur_depth)
7235         {
7236           tree l;
7237           if (cur_depth == args_depth)
7238             l = coerce_template_parms (TREE_VALUE (level),
7239                                        args, in_decl, complain,
7240                                        require_all_args,
7241                                        use_default_args);
7242           else
7243             l = TMPL_ARGS_LEVEL (args, cur_depth);
7244
7245           if (l == error_mark_node)
7246             return error_mark_node;
7247
7248           SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
7249         }
7250     }
7251   else
7252     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
7253                                           args, in_decl, complain,
7254                                           require_all_args,
7255                                           use_default_args);
7256   return coerced_args;
7257 }
7258
7259 /* Returns 1 if template args OT and NT are equivalent.  */
7260
7261 static int
7262 template_args_equal (tree ot, tree nt)
7263 {
7264   if (nt == ot)
7265     return 1;
7266   if (nt == NULL_TREE || ot == NULL_TREE)
7267     return false;
7268
7269   if (TREE_CODE (nt) == TREE_VEC)
7270     /* For member templates */
7271     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
7272   else if (PACK_EXPANSION_P (ot))
7273     return (PACK_EXPANSION_P (nt)
7274             && template_args_equal (PACK_EXPANSION_PATTERN (ot),
7275                                     PACK_EXPANSION_PATTERN (nt))
7276             && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
7277                                     PACK_EXPANSION_EXTRA_ARGS (nt)));
7278   else if (ARGUMENT_PACK_P (ot))
7279     {
7280       int i, len;
7281       tree opack, npack;
7282
7283       if (!ARGUMENT_PACK_P (nt))
7284         return 0;
7285
7286       opack = ARGUMENT_PACK_ARGS (ot);
7287       npack = ARGUMENT_PACK_ARGS (nt);
7288       len = TREE_VEC_LENGTH (opack);
7289       if (TREE_VEC_LENGTH (npack) != len)
7290         return 0;
7291       for (i = 0; i < len; ++i)
7292         if (!template_args_equal (TREE_VEC_ELT (opack, i),
7293                                   TREE_VEC_ELT (npack, i)))
7294           return 0;
7295       return 1;
7296     }
7297   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
7298     {
7299       /* We get here probably because we are in the middle of substituting
7300          into the pattern of a pack expansion. In that case the
7301          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
7302          interested in. So we want to use the initial pack argument for
7303          the comparison.  */
7304       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
7305       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
7306         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
7307       return template_args_equal (ot, nt);
7308     }
7309   else if (TYPE_P (nt))
7310     {
7311       if (!TYPE_P (ot))
7312         return false;
7313       /* Don't treat an alias template specialization with dependent
7314          arguments as equivalent to its underlying type when used as a
7315          template argument; we need them to be distinct so that we
7316          substitute into the specialization arguments at instantiation
7317          time.  And aliases can't be equivalent without being ==, so
7318          we don't need to look any deeper.  */
7319       if (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot))
7320         return false;
7321       else
7322         return same_type_p (ot, nt);
7323     }
7324   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
7325     return 0;
7326   else
7327     {
7328       /* Try to treat a template non-type argument that has been converted
7329          to the parameter type as equivalent to one that hasn't yet.  */
7330       for (enum tree_code code1 = TREE_CODE (ot);
7331            CONVERT_EXPR_CODE_P (code1)
7332              || code1 == NON_LVALUE_EXPR;
7333            code1 = TREE_CODE (ot))
7334         ot = TREE_OPERAND (ot, 0);
7335       for (enum tree_code code2 = TREE_CODE (nt);
7336            CONVERT_EXPR_CODE_P (code2)
7337              || code2 == NON_LVALUE_EXPR;
7338            code2 = TREE_CODE (nt))
7339         nt = TREE_OPERAND (nt, 0);
7340
7341       return cp_tree_equal (ot, nt);
7342     }
7343 }
7344
7345 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
7346    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
7347    NEWARG_PTR with the offending arguments if they are non-NULL.  */
7348
7349 static int
7350 comp_template_args_with_info (tree oldargs, tree newargs,
7351                               tree *oldarg_ptr, tree *newarg_ptr)
7352 {
7353   int i;
7354
7355   if (oldargs == newargs)
7356     return 1;
7357
7358   if (!oldargs || !newargs)
7359     return 0;
7360
7361   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
7362     return 0;
7363
7364   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
7365     {
7366       tree nt = TREE_VEC_ELT (newargs, i);
7367       tree ot = TREE_VEC_ELT (oldargs, i);
7368
7369       if (! template_args_equal (ot, nt))
7370         {
7371           if (oldarg_ptr != NULL)
7372             *oldarg_ptr = ot;
7373           if (newarg_ptr != NULL)
7374             *newarg_ptr = nt;
7375           return 0;
7376         }
7377     }
7378   return 1;
7379 }
7380
7381 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
7382    of template arguments.  Returns 0 otherwise.  */
7383
7384 int
7385 comp_template_args (tree oldargs, tree newargs)
7386 {
7387   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
7388 }
7389
7390 static void
7391 add_pending_template (tree d)
7392 {
7393   tree ti = (TYPE_P (d)
7394              ? CLASSTYPE_TEMPLATE_INFO (d)
7395              : DECL_TEMPLATE_INFO (d));
7396   struct pending_template *pt;
7397   int level;
7398
7399   if (TI_PENDING_TEMPLATE_FLAG (ti))
7400     return;
7401
7402   /* We are called both from instantiate_decl, where we've already had a
7403      tinst_level pushed, and instantiate_template, where we haven't.
7404      Compensate.  */
7405   level = !current_tinst_level || current_tinst_level->decl != d;
7406
7407   if (level)
7408     push_tinst_level (d);
7409
7410   pt = ggc_alloc<pending_template> ();
7411   pt->next = NULL;
7412   pt->tinst = current_tinst_level;
7413   if (last_pending_template)
7414     last_pending_template->next = pt;
7415   else
7416     pending_templates = pt;
7417
7418   last_pending_template = pt;
7419
7420   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
7421
7422   if (level)
7423     pop_tinst_level ();
7424 }
7425
7426
7427 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
7428    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
7429    documentation for TEMPLATE_ID_EXPR.  */
7430
7431 tree
7432 lookup_template_function (tree fns, tree arglist)
7433 {
7434   tree type;
7435
7436   if (fns == error_mark_node || arglist == error_mark_node)
7437     return error_mark_node;
7438
7439   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
7440
7441   if (!is_overloaded_fn (fns) && !identifier_p (fns))
7442     {
7443       error ("%q#D is not a function template", fns);
7444       return error_mark_node;
7445     }
7446
7447   if (BASELINK_P (fns))
7448     {
7449       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
7450                                          unknown_type_node,
7451                                          BASELINK_FUNCTIONS (fns),
7452                                          arglist);
7453       return fns;
7454     }
7455
7456   type = TREE_TYPE (fns);
7457   if (TREE_CODE (fns) == OVERLOAD || !type)
7458     type = unknown_type_node;
7459
7460   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
7461 }
7462
7463 /* Within the scope of a template class S<T>, the name S gets bound
7464    (in build_self_reference) to a TYPE_DECL for the class, not a
7465    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
7466    or one of its enclosing classes, and that type is a template,
7467    return the associated TEMPLATE_DECL.  Otherwise, the original
7468    DECL is returned.
7469
7470    Also handle the case when DECL is a TREE_LIST of ambiguous
7471    injected-class-names from different bases.  */
7472
7473 tree
7474 maybe_get_template_decl_from_type_decl (tree decl)
7475 {
7476   if (decl == NULL_TREE)
7477     return decl;
7478
7479   /* DR 176: A lookup that finds an injected-class-name (10.2
7480      [class.member.lookup]) can result in an ambiguity in certain cases
7481      (for example, if it is found in more than one base class). If all of
7482      the injected-class-names that are found refer to specializations of
7483      the same class template, and if the name is followed by a
7484      template-argument-list, the reference refers to the class template
7485      itself and not a specialization thereof, and is not ambiguous.  */
7486   if (TREE_CODE (decl) == TREE_LIST)
7487     {
7488       tree t, tmpl = NULL_TREE;
7489       for (t = decl; t; t = TREE_CHAIN (t))
7490         {
7491           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
7492           if (!tmpl)
7493             tmpl = elt;
7494           else if (tmpl != elt)
7495             break;
7496         }
7497       if (tmpl && t == NULL_TREE)
7498         return tmpl;
7499       else
7500         return decl;
7501     }
7502
7503   return (decl != NULL_TREE
7504           && DECL_SELF_REFERENCE_P (decl)
7505           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7506     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7507 }
7508
7509 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
7510    parameters, find the desired type.
7511
7512    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7513
7514    IN_DECL, if non-NULL, is the template declaration we are trying to
7515    instantiate.
7516
7517    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7518    the class we are looking up.
7519
7520    Issue error and warning messages under control of COMPLAIN.
7521
7522    If the template class is really a local class in a template
7523    function, then the FUNCTION_CONTEXT is the function in which it is
7524    being instantiated.
7525
7526    ??? Note that this function is currently called *twice* for each
7527    template-id: the first time from the parser, while creating the
7528    incomplete type (finish_template_type), and the second type during the
7529    real instantiation (instantiate_template_class). This is surely something
7530    that we want to avoid. It also causes some problems with argument
7531    coercion (see convert_nontype_argument for more information on this).  */
7532
7533 static tree
7534 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7535                          int entering_scope, tsubst_flags_t complain)
7536 {
7537   tree templ = NULL_TREE, parmlist;
7538   tree t;
7539   spec_entry **slot;
7540   spec_entry *entry;
7541   spec_entry elt;
7542   hashval_t hash;
7543
7544   if (identifier_p (d1))
7545     {
7546       tree value = innermost_non_namespace_value (d1);
7547       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7548         templ = value;
7549       else
7550         {
7551           if (context)
7552             push_decl_namespace (context);
7553           templ = lookup_name (d1);
7554           templ = maybe_get_template_decl_from_type_decl (templ);
7555           if (context)
7556             pop_decl_namespace ();
7557         }
7558       if (templ)
7559         context = DECL_CONTEXT (templ);
7560     }
7561   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7562     {
7563       tree type = TREE_TYPE (d1);
7564
7565       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7566          an implicit typename for the second A.  Deal with it.  */
7567       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7568         type = TREE_TYPE (type);
7569
7570       if (CLASSTYPE_TEMPLATE_INFO (type))
7571         {
7572           templ = CLASSTYPE_TI_TEMPLATE (type);
7573           d1 = DECL_NAME (templ);
7574         }
7575     }
7576   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7577            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7578     {
7579       templ = TYPE_TI_TEMPLATE (d1);
7580       d1 = DECL_NAME (templ);
7581     }
7582   else if (DECL_TYPE_TEMPLATE_P (d1))
7583     {
7584       templ = d1;
7585       d1 = DECL_NAME (templ);
7586       context = DECL_CONTEXT (templ);
7587     }
7588   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
7589     {
7590       templ = d1;
7591       d1 = DECL_NAME (templ);
7592     }
7593
7594   /* Issue an error message if we didn't find a template.  */
7595   if (! templ)
7596     {
7597       if (complain & tf_error)
7598         error ("%qT is not a template", d1);
7599       return error_mark_node;
7600     }
7601
7602   if (TREE_CODE (templ) != TEMPLATE_DECL
7603          /* Make sure it's a user visible template, if it was named by
7604             the user.  */
7605       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7606           && !PRIMARY_TEMPLATE_P (templ)))
7607     {
7608       if (complain & tf_error)
7609         {
7610           error ("non-template type %qT used as a template", d1);
7611           if (in_decl)
7612             error ("for template declaration %q+D", in_decl);
7613         }
7614       return error_mark_node;
7615     }
7616
7617   complain &= ~tf_user;
7618
7619   /* An alias that just changes the name of a template is equivalent to the
7620      other template, so if any of the arguments are pack expansions, strip
7621      the alias to avoid problems with a pack expansion passed to a non-pack
7622      alias template parameter (DR 1430).  */
7623   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
7624     templ = get_underlying_template (templ);
7625
7626   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7627     {
7628       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7629          template arguments */
7630
7631       tree parm;
7632       tree arglist2;
7633       tree outer;
7634
7635       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7636
7637       /* Consider an example where a template template parameter declared as
7638
7639            template <class T, class U = std::allocator<T> > class TT
7640
7641          The template parameter level of T and U are one level larger than
7642          of TT.  To proper process the default argument of U, say when an
7643          instantiation `TT<int>' is seen, we need to build the full
7644          arguments containing {int} as the innermost level.  Outer levels,
7645          available when not appearing as default template argument, can be
7646          obtained from the arguments of the enclosing template.
7647
7648          Suppose that TT is later substituted with std::vector.  The above
7649          instantiation is `TT<int, std::allocator<T> >' with TT at
7650          level 1, and T at level 2, while the template arguments at level 1
7651          becomes {std::vector} and the inner level 2 is {int}.  */
7652
7653       outer = DECL_CONTEXT (templ);
7654       if (outer)
7655         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7656       else if (current_template_parms)
7657         /* This is an argument of the current template, so we haven't set
7658            DECL_CONTEXT yet.  */
7659         outer = current_template_args ();
7660
7661       if (outer)
7662         arglist = add_to_template_args (outer, arglist);
7663
7664       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7665                                         complain,
7666                                         /*require_all_args=*/true,
7667                                         /*use_default_args=*/true);
7668       if (arglist2 == error_mark_node
7669           || (!uses_template_parms (arglist2)
7670               && check_instantiated_args (templ, arglist2, complain)))
7671         return error_mark_node;
7672
7673       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7674       return parm;
7675     }
7676   else
7677     {
7678       tree template_type = TREE_TYPE (templ);
7679       tree gen_tmpl;
7680       tree type_decl;
7681       tree found = NULL_TREE;
7682       int arg_depth;
7683       int parm_depth;
7684       int is_dependent_type;
7685       int use_partial_inst_tmpl = false;
7686
7687       if (template_type == error_mark_node)
7688         /* An error occurred while building the template TEMPL, and a
7689            diagnostic has most certainly been emitted for that
7690            already.  Let's propagate that error.  */
7691         return error_mark_node;
7692
7693       gen_tmpl = most_general_template (templ);
7694       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7695       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7696       arg_depth = TMPL_ARGS_DEPTH (arglist);
7697
7698       if (arg_depth == 1 && parm_depth > 1)
7699         {
7700           /* We've been given an incomplete set of template arguments.
7701              For example, given:
7702
7703                template <class T> struct S1 {
7704                  template <class U> struct S2 {};
7705                  template <class U> struct S2<U*> {};
7706                 };
7707
7708              we will be called with an ARGLIST of `U*', but the
7709              TEMPLATE will be `template <class T> template
7710              <class U> struct S1<T>::S2'.  We must fill in the missing
7711              arguments.  */
7712           arglist
7713             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7714                                            arglist);
7715           arg_depth = TMPL_ARGS_DEPTH (arglist);
7716         }
7717
7718       /* Now we should have enough arguments.  */
7719       gcc_assert (parm_depth == arg_depth);
7720
7721       /* From here on, we're only interested in the most general
7722          template.  */
7723
7724       /* Calculate the BOUND_ARGS.  These will be the args that are
7725          actually tsubst'd into the definition to create the
7726          instantiation.  */
7727       if (parm_depth > 1)
7728         {
7729           /* We have multiple levels of arguments to coerce, at once.  */
7730           int i;
7731           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7732
7733           tree bound_args = make_tree_vec (parm_depth);
7734
7735           for (i = saved_depth,
7736                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7737                i > 0 && t != NULL_TREE;
7738                --i, t = TREE_CHAIN (t))
7739             {
7740               tree a;
7741               if (i == saved_depth)
7742                 a = coerce_template_parms (TREE_VALUE (t),
7743                                            arglist, gen_tmpl,
7744                                            complain,
7745                                            /*require_all_args=*/true,
7746                                            /*use_default_args=*/true);
7747               else
7748                 /* Outer levels should have already been coerced.  */
7749                 a = TMPL_ARGS_LEVEL (arglist, i);
7750
7751               /* Don't process further if one of the levels fails.  */
7752               if (a == error_mark_node)
7753                 {
7754                   /* Restore the ARGLIST to its full size.  */
7755                   TREE_VEC_LENGTH (arglist) = saved_depth;
7756                   return error_mark_node;
7757                 }
7758
7759               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7760
7761               /* We temporarily reduce the length of the ARGLIST so
7762                  that coerce_template_parms will see only the arguments
7763                  corresponding to the template parameters it is
7764                  examining.  */
7765               TREE_VEC_LENGTH (arglist)--;
7766             }
7767
7768           /* Restore the ARGLIST to its full size.  */
7769           TREE_VEC_LENGTH (arglist) = saved_depth;
7770
7771           arglist = bound_args;
7772         }
7773       else
7774         arglist
7775           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7776                                    INNERMOST_TEMPLATE_ARGS (arglist),
7777                                    gen_tmpl,
7778                                    complain,
7779                                    /*require_all_args=*/true,
7780                                    /*use_default_args=*/true);
7781
7782       if (arglist == error_mark_node)
7783         /* We were unable to bind the arguments.  */
7784         return error_mark_node;
7785
7786       /* In the scope of a template class, explicit references to the
7787          template class refer to the type of the template, not any
7788          instantiation of it.  For example, in:
7789
7790            template <class T> class C { void f(C<T>); }
7791
7792          the `C<T>' is just the same as `C'.  Outside of the
7793          class, however, such a reference is an instantiation.  */
7794       if ((entering_scope
7795            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7796            || currently_open_class (template_type))
7797           /* comp_template_args is expensive, check it last.  */
7798           && comp_template_args (TYPE_TI_ARGS (template_type),
7799                                  arglist))
7800         return template_type;
7801
7802       /* If we already have this specialization, return it.  */
7803       elt.tmpl = gen_tmpl;
7804       elt.args = arglist;
7805       hash = spec_hasher::hash (&elt);
7806       entry = type_specializations->find_with_hash (&elt, hash);
7807
7808       if (entry)
7809         return entry->spec;
7810
7811       is_dependent_type = uses_template_parms (arglist);
7812
7813       /* If the deduced arguments are invalid, then the binding
7814          failed.  */
7815       if (!is_dependent_type
7816           && check_instantiated_args (gen_tmpl,
7817                                       INNERMOST_TEMPLATE_ARGS (arglist),
7818                                       complain))
7819         return error_mark_node;
7820
7821       if (!is_dependent_type
7822           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7823           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7824           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7825         {
7826           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7827                                       DECL_NAME (gen_tmpl),
7828                                       /*tag_scope=*/ts_global);
7829           return found;
7830         }
7831
7832       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7833                         complain, in_decl);
7834       if (context == error_mark_node)
7835         return error_mark_node;
7836
7837       if (!context)
7838         context = global_namespace;
7839
7840       /* Create the type.  */
7841       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
7842         {
7843           /* The user referred to a specialization of an alias
7844             template represented by GEN_TMPL.
7845
7846             [temp.alias]/2 says:
7847
7848                 When a template-id refers to the specialization of an
7849                 alias template, it is equivalent to the associated
7850                 type obtained by substitution of its
7851                 template-arguments for the template-parameters in the
7852                 type-id of the alias template.  */
7853
7854           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
7855           /* Note that the call above (by indirectly calling
7856              register_specialization in tsubst_decl) registers the
7857              TYPE_DECL representing the specialization of the alias
7858              template.  So next time someone substitutes ARGLIST for
7859              the template parms into the alias template (GEN_TMPL),
7860              she'll get that TYPE_DECL back.  */
7861
7862           if (t == error_mark_node)
7863             return t;
7864         }
7865       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7866         {
7867           if (!is_dependent_type)
7868             {
7869               set_current_access_from_decl (TYPE_NAME (template_type));
7870               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7871                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7872                                       arglist, complain, in_decl),
7873                               SCOPED_ENUM_P (template_type), NULL);
7874
7875               if (t == error_mark_node)
7876                 return t;
7877             }
7878           else
7879             {
7880               /* We don't want to call start_enum for this type, since
7881                  the values for the enumeration constants may involve
7882                  template parameters.  And, no one should be interested
7883                  in the enumeration constants for such a type.  */
7884               t = cxx_make_type (ENUMERAL_TYPE);
7885               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7886             }
7887           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7888           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7889             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7890         }
7891       else if (CLASS_TYPE_P (template_type))
7892         {
7893           t = make_class_type (TREE_CODE (template_type));
7894           CLASSTYPE_DECLARED_CLASS (t)
7895             = CLASSTYPE_DECLARED_CLASS (template_type);
7896           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7897           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7898
7899           /* A local class.  Make sure the decl gets registered properly.  */
7900           if (context == current_function_decl)
7901             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7902
7903           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7904             /* This instantiation is another name for the primary
7905                template type. Set the TYPE_CANONICAL field
7906                appropriately. */
7907             TYPE_CANONICAL (t) = template_type;
7908           else if (any_template_arguments_need_structural_equality_p (arglist))
7909             /* Some of the template arguments require structural
7910                equality testing, so this template class requires
7911                structural equality testing. */
7912             SET_TYPE_STRUCTURAL_EQUALITY (t);
7913         }
7914       else
7915         gcc_unreachable ();
7916
7917       /* If we called start_enum or pushtag above, this information
7918          will already be set up.  */
7919       if (!TYPE_NAME (t))
7920         {
7921           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7922
7923           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7924           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7925           DECL_SOURCE_LOCATION (type_decl)
7926             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7927         }
7928       else
7929         type_decl = TYPE_NAME (t);
7930
7931       if (CLASS_TYPE_P (template_type))
7932         {
7933           TREE_PRIVATE (type_decl)
7934             = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
7935           TREE_PROTECTED (type_decl)
7936             = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
7937           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7938             {
7939               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7940               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7941             }
7942         }
7943
7944       if (OVERLOAD_TYPE_P (t)
7945           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
7946         {
7947           if (tree attributes
7948               = lookup_attribute ("abi_tag", TYPE_ATTRIBUTES (template_type)))
7949             {
7950               if (!TREE_CHAIN (attributes))
7951                 TYPE_ATTRIBUTES (t) = attributes;
7952               else
7953                 TYPE_ATTRIBUTES (t)
7954                   = build_tree_list (TREE_PURPOSE (attributes),
7955                                      TREE_VALUE (attributes));
7956             }
7957         }
7958
7959       /* Let's consider the explicit specialization of a member
7960          of a class template specialization that is implicitly instantiated,
7961          e.g.:
7962              template<class T>
7963              struct S
7964              {
7965                template<class U> struct M {}; //#0
7966              };
7967
7968              template<>
7969              template<>
7970              struct S<int>::M<char> //#1
7971              {
7972                int i;
7973              };
7974         [temp.expl.spec]/4 says this is valid.
7975
7976         In this case, when we write:
7977         S<int>::M<char> m;
7978
7979         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7980         the one of #0.
7981
7982         When we encounter #1, we want to store the partial instantiation
7983         of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
7984
7985         For all cases other than this "explicit specialization of member of a
7986         class template", we just want to store the most general template into
7987         the CLASSTYPE_TI_TEMPLATE of M.
7988
7989         This case of "explicit specialization of member of a class template"
7990         only happens when:
7991         1/ the enclosing class is an instantiation of, and therefore not
7992         the same as, the context of the most general template, and
7993         2/ we aren't looking at the partial instantiation itself, i.e.
7994         the innermost arguments are not the same as the innermost parms of
7995         the most general template.
7996
7997         So it's only when 1/ and 2/ happens that we want to use the partial
7998         instantiation of the member template in lieu of its most general
7999         template.  */
8000
8001       if (PRIMARY_TEMPLATE_P (gen_tmpl)
8002           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
8003           /* the enclosing class must be an instantiation...  */
8004           && CLASS_TYPE_P (context)
8005           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
8006         {
8007           tree partial_inst_args;
8008           TREE_VEC_LENGTH (arglist)--;
8009           ++processing_template_decl;
8010           partial_inst_args =
8011             tsubst (INNERMOST_TEMPLATE_ARGS
8012                         (TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
8013                     arglist, complain, NULL_TREE);
8014           --processing_template_decl;
8015           TREE_VEC_LENGTH (arglist)++;
8016           use_partial_inst_tmpl =
8017             /*...and we must not be looking at the partial instantiation
8018              itself. */
8019             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
8020                                  partial_inst_args);
8021         }
8022
8023       if (!use_partial_inst_tmpl)
8024         /* This case is easy; there are no member templates involved.  */
8025         found = gen_tmpl;
8026       else
8027         {
8028           /* This is a full instantiation of a member template.  Find
8029              the partial instantiation of which this is an instance.  */
8030
8031           /* Temporarily reduce by one the number of levels in the ARGLIST
8032              so as to avoid comparing the last set of arguments.  */
8033           TREE_VEC_LENGTH (arglist)--;
8034           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
8035           TREE_VEC_LENGTH (arglist)++;
8036           /* FOUND is either a proper class type, or an alias
8037              template specialization.  In the later case, it's a
8038              TYPE_DECL, resulting from the substituting of arguments
8039              for parameters in the TYPE_DECL of the alias template
8040              done earlier.  So be careful while getting the template
8041              of FOUND.  */
8042           found = TREE_CODE (found) == TYPE_DECL
8043             ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
8044             : CLASSTYPE_TI_TEMPLATE (found);
8045         }
8046
8047       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
8048
8049       elt.spec = t;
8050       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
8051       entry = ggc_alloc<spec_entry> ();
8052       *entry = elt;
8053       *slot = entry;
8054
8055       /* Note this use of the partial instantiation so we can check it
8056          later in maybe_process_partial_specialization.  */
8057       DECL_TEMPLATE_INSTANTIATIONS (found)
8058         = tree_cons (arglist, t,
8059                      DECL_TEMPLATE_INSTANTIATIONS (found));
8060
8061       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
8062           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8063         /* Now that the type has been registered on the instantiations
8064            list, we set up the enumerators.  Because the enumeration
8065            constants may involve the enumeration type itself, we make
8066            sure to register the type first, and then create the
8067            constants.  That way, doing tsubst_expr for the enumeration
8068            constants won't result in recursive calls here; we'll find
8069            the instantiation and exit above.  */
8070         tsubst_enum (template_type, t, arglist);
8071
8072       if (CLASS_TYPE_P (template_type) && is_dependent_type)
8073         /* If the type makes use of template parameters, the
8074            code that generates debugging information will crash.  */
8075         DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
8076
8077       /* Possibly limit visibility based on template args.  */
8078       TREE_PUBLIC (type_decl) = 1;
8079       determine_visibility (type_decl);
8080
8081       inherit_targ_abi_tags (t);
8082
8083       return t;
8084     }
8085 }
8086
8087 /* Wrapper for lookup_template_class_1.  */
8088
8089 tree
8090 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
8091                        int entering_scope, tsubst_flags_t complain)
8092 {
8093   tree ret;
8094   timevar_push (TV_TEMPLATE_INST);
8095   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
8096                                  entering_scope, complain);
8097   timevar_pop (TV_TEMPLATE_INST);
8098   return ret;
8099 }
8100
8101 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.
8102    The type of the expression is the unknown_type_node since the
8103    template-id could refer to an explicit or partial specialization. */
8104
8105 tree
8106 lookup_template_variable (tree templ, tree arglist)
8107 {
8108   tree type = unknown_type_node;
8109   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
8110 }
8111
8112 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
8113
8114 tree
8115 finish_template_variable (tree var)
8116 {
8117   tree templ = TREE_OPERAND (var, 0);
8118
8119   tree arglist = TREE_OPERAND (var, 1);
8120   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
8121   arglist = add_outermost_template_args (tmpl_args, arglist);
8122
8123   tree parms = DECL_TEMPLATE_PARMS (templ);
8124   tsubst_flags_t complain = tf_warning_or_error;
8125   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
8126                                              /*req_all*/true,
8127                                              /*use_default*/true);
8128
8129   return instantiate_template (templ, arglist, complain);
8130 }
8131 \f
8132 struct pair_fn_data
8133 {
8134   tree_fn_t fn;
8135   void *data;
8136   /* True when we should also visit template parameters that occur in
8137      non-deduced contexts.  */
8138   bool include_nondeduced_p;
8139   hash_set<tree> *visited;
8140 };
8141
8142 /* Called from for_each_template_parm via walk_tree.  */
8143
8144 static tree
8145 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
8146 {
8147   tree t = *tp;
8148   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
8149   tree_fn_t fn = pfd->fn;
8150   void *data = pfd->data;
8151
8152   if (TYPE_P (t)
8153       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
8154       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
8155                                  pfd->include_nondeduced_p))
8156     return error_mark_node;
8157
8158   switch (TREE_CODE (t))
8159     {
8160     case RECORD_TYPE:
8161       if (TYPE_PTRMEMFUNC_P (t))
8162         break;
8163       /* Fall through.  */
8164
8165     case UNION_TYPE:
8166     case ENUMERAL_TYPE:
8167       if (!TYPE_TEMPLATE_INFO (t))
8168         *walk_subtrees = 0;
8169       else if (for_each_template_parm (TYPE_TI_ARGS (t),
8170                                        fn, data, pfd->visited, 
8171                                        pfd->include_nondeduced_p))
8172         return error_mark_node;
8173       break;
8174
8175     case INTEGER_TYPE:
8176       if (for_each_template_parm (TYPE_MIN_VALUE (t),
8177                                   fn, data, pfd->visited, 
8178                                   pfd->include_nondeduced_p)
8179           || for_each_template_parm (TYPE_MAX_VALUE (t),
8180                                      fn, data, pfd->visited,
8181                                      pfd->include_nondeduced_p))
8182         return error_mark_node;
8183       break;
8184
8185     case METHOD_TYPE:
8186       /* Since we're not going to walk subtrees, we have to do this
8187          explicitly here.  */
8188       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
8189                                   pfd->visited, pfd->include_nondeduced_p))
8190         return error_mark_node;
8191       /* Fall through.  */
8192
8193     case FUNCTION_TYPE:
8194       /* Check the return type.  */
8195       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
8196                                   pfd->include_nondeduced_p))
8197         return error_mark_node;
8198
8199       /* Check the parameter types.  Since default arguments are not
8200          instantiated until they are needed, the TYPE_ARG_TYPES may
8201          contain expressions that involve template parameters.  But,
8202          no-one should be looking at them yet.  And, once they're
8203          instantiated, they don't contain template parameters, so
8204          there's no point in looking at them then, either.  */
8205       {
8206         tree parm;
8207
8208         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
8209           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
8210                                       pfd->visited, pfd->include_nondeduced_p))
8211             return error_mark_node;
8212
8213         /* Since we've already handled the TYPE_ARG_TYPES, we don't
8214            want walk_tree walking into them itself.  */
8215         *walk_subtrees = 0;
8216       }
8217       break;
8218
8219     case TYPEOF_TYPE:
8220     case UNDERLYING_TYPE:
8221       if (pfd->include_nondeduced_p
8222           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
8223                                      pfd->visited, 
8224                                      pfd->include_nondeduced_p))
8225         return error_mark_node;
8226       break;
8227
8228     case FUNCTION_DECL:
8229     case VAR_DECL:
8230       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
8231           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
8232                                      pfd->visited, pfd->include_nondeduced_p))
8233         return error_mark_node;
8234       /* Fall through.  */
8235
8236     case PARM_DECL:
8237     case CONST_DECL:
8238       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
8239           && for_each_template_parm (DECL_INITIAL (t), fn, data,
8240                                      pfd->visited, pfd->include_nondeduced_p))
8241         return error_mark_node;
8242       if (DECL_CONTEXT (t)
8243           && pfd->include_nondeduced_p
8244           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
8245                                      pfd->visited, pfd->include_nondeduced_p))
8246         return error_mark_node;
8247       break;
8248
8249     case BOUND_TEMPLATE_TEMPLATE_PARM:
8250       /* Record template parameters such as `T' inside `TT<T>'.  */
8251       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
8252                                   pfd->include_nondeduced_p))
8253         return error_mark_node;
8254       /* Fall through.  */
8255
8256     case TEMPLATE_TEMPLATE_PARM:
8257     case TEMPLATE_TYPE_PARM:
8258     case TEMPLATE_PARM_INDEX:
8259       if (fn && (*fn)(t, data))
8260         return error_mark_node;
8261       else if (!fn)
8262         return error_mark_node;
8263       break;
8264
8265     case TEMPLATE_DECL:
8266       /* A template template parameter is encountered.  */
8267       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
8268           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
8269                                      pfd->include_nondeduced_p))
8270         return error_mark_node;
8271
8272       /* Already substituted template template parameter */
8273       *walk_subtrees = 0;
8274       break;
8275
8276     case TYPENAME_TYPE:
8277       if (!fn
8278           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
8279                                      data, pfd->visited, 
8280                                      pfd->include_nondeduced_p))
8281         return error_mark_node;
8282       break;
8283
8284     case CONSTRUCTOR:
8285       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
8286           && pfd->include_nondeduced_p
8287           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
8288                                      (TREE_TYPE (t)), fn, data,
8289                                      pfd->visited, pfd->include_nondeduced_p))
8290         return error_mark_node;
8291       break;
8292
8293     case INDIRECT_REF:
8294     case COMPONENT_REF:
8295       /* If there's no type, then this thing must be some expression
8296          involving template parameters.  */
8297       if (!fn && !TREE_TYPE (t))
8298         return error_mark_node;
8299       break;
8300
8301     case MODOP_EXPR:
8302     case CAST_EXPR:
8303     case IMPLICIT_CONV_EXPR:
8304     case REINTERPRET_CAST_EXPR:
8305     case CONST_CAST_EXPR:
8306     case STATIC_CAST_EXPR:
8307     case DYNAMIC_CAST_EXPR:
8308     case ARROW_EXPR:
8309     case DOTSTAR_EXPR:
8310     case TYPEID_EXPR:
8311     case PSEUDO_DTOR_EXPR:
8312       if (!fn)
8313         return error_mark_node;
8314       break;
8315
8316     default:
8317       break;
8318     }
8319
8320   /* We didn't find any template parameters we liked.  */
8321   return NULL_TREE;
8322 }
8323
8324 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
8325    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
8326    call FN with the parameter and the DATA.
8327    If FN returns nonzero, the iteration is terminated, and
8328    for_each_template_parm returns 1.  Otherwise, the iteration
8329    continues.  If FN never returns a nonzero value, the value
8330    returned by for_each_template_parm is 0.  If FN is NULL, it is
8331    considered to be the function which always returns 1.
8332
8333    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
8334    parameters that occur in non-deduced contexts.  When false, only
8335    visits those template parameters that can be deduced.  */
8336
8337 static int
8338 for_each_template_parm (tree t, tree_fn_t fn, void* data,
8339                         hash_set<tree> *visited,
8340                         bool include_nondeduced_p)
8341 {
8342   struct pair_fn_data pfd;
8343   int result;
8344
8345   /* Set up.  */
8346   pfd.fn = fn;
8347   pfd.data = data;
8348   pfd.include_nondeduced_p = include_nondeduced_p;
8349
8350   /* Walk the tree.  (Conceptually, we would like to walk without
8351      duplicates, but for_each_template_parm_r recursively calls
8352      for_each_template_parm, so we would need to reorganize a fair
8353      bit to use walk_tree_without_duplicates, so we keep our own
8354      visited list.)  */
8355   if (visited)
8356     pfd.visited = visited;
8357   else
8358     pfd.visited = new hash_set<tree>;
8359   result = cp_walk_tree (&t,
8360                          for_each_template_parm_r,
8361                          &pfd,
8362                          pfd.visited) != NULL_TREE;
8363
8364   /* Clean up.  */
8365   if (!visited)
8366     {
8367       delete pfd.visited;
8368       pfd.visited = 0;
8369     }
8370
8371   return result;
8372 }
8373
8374 /* Returns true if T depends on any template parameter.  */
8375
8376 int
8377 uses_template_parms (tree t)
8378 {
8379   if (t == NULL_TREE)
8380     return false;
8381
8382   bool dependent_p;
8383   int saved_processing_template_decl;
8384
8385   saved_processing_template_decl = processing_template_decl;
8386   if (!saved_processing_template_decl)
8387     processing_template_decl = 1;
8388   if (TYPE_P (t))
8389     dependent_p = dependent_type_p (t);
8390   else if (TREE_CODE (t) == TREE_VEC)
8391     dependent_p = any_dependent_template_arguments_p (t);
8392   else if (TREE_CODE (t) == TREE_LIST)
8393     dependent_p = (uses_template_parms (TREE_VALUE (t))
8394                    || uses_template_parms (TREE_CHAIN (t)));
8395   else if (TREE_CODE (t) == TYPE_DECL)
8396     dependent_p = dependent_type_p (TREE_TYPE (t));
8397   else if (DECL_P (t)
8398            || EXPR_P (t)
8399            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
8400            || TREE_CODE (t) == OVERLOAD
8401            || BASELINK_P (t)
8402            || identifier_p (t)
8403            || TREE_CODE (t) == TRAIT_EXPR
8404            || TREE_CODE (t) == CONSTRUCTOR
8405            || CONSTANT_CLASS_P (t))
8406     dependent_p = (type_dependent_expression_p (t)
8407                    || value_dependent_expression_p (t));
8408   else
8409     {
8410       gcc_assert (t == error_mark_node);
8411       dependent_p = false;
8412     }
8413
8414   processing_template_decl = saved_processing_template_decl;
8415
8416   return dependent_p;
8417 }
8418
8419 /* Returns true iff current_function_decl is an incompletely instantiated
8420    template.  Useful instead of processing_template_decl because the latter
8421    is set to 0 during instantiate_non_dependent_expr.  */
8422
8423 bool
8424 in_template_function (void)
8425 {
8426   tree fn = current_function_decl;
8427   bool ret;
8428   ++processing_template_decl;
8429   ret = (fn && DECL_LANG_SPECIFIC (fn)
8430          && DECL_TEMPLATE_INFO (fn)
8431          && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
8432   --processing_template_decl;
8433   return ret;
8434 }
8435
8436 /* Returns true if T depends on any template parameter with level LEVEL.  */
8437
8438 int
8439 uses_template_parms_level (tree t, int level)
8440 {
8441   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
8442                                  /*include_nondeduced_p=*/true);
8443 }
8444
8445 /* Returns TRUE iff INST is an instantiation we don't need to do in an
8446    ill-formed translation unit, i.e. a variable or function that isn't
8447    usable in a constant expression.  */
8448
8449 static inline bool
8450 neglectable_inst_p (tree d)
8451 {
8452   return (DECL_P (d)
8453           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
8454                : decl_maybe_constant_var_p (d)));
8455 }
8456
8457 /* Returns TRUE iff we should refuse to instantiate DECL because it's
8458    neglectable and instantiated from within an erroneous instantiation.  */
8459
8460 static bool
8461 limit_bad_template_recursion (tree decl)
8462 {
8463   struct tinst_level *lev = current_tinst_level;
8464   int errs = errorcount + sorrycount;
8465   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
8466     return false;
8467
8468   for (; lev; lev = lev->next)
8469     if (neglectable_inst_p (lev->decl))
8470       break;
8471
8472   return (lev && errs > lev->errors);
8473 }
8474
8475 static int tinst_depth;
8476 extern int max_tinst_depth;
8477 int depth_reached;
8478
8479 static GTY(()) struct tinst_level *last_error_tinst_level;
8480
8481 /* We're starting to instantiate D; record the template instantiation context
8482    for diagnostics and to restore it later.  */
8483
8484 bool
8485 push_tinst_level (tree d)
8486 {
8487   return push_tinst_level_loc (d, input_location);
8488 }
8489
8490 /* We're starting to instantiate D; record the template instantiation context
8491    at LOC for diagnostics and to restore it later.  */
8492
8493 bool
8494 push_tinst_level_loc (tree d, location_t loc)
8495 {
8496   struct tinst_level *new_level;
8497
8498   if (tinst_depth >= max_tinst_depth)
8499     {
8500       fatal_error (input_location,
8501                    "template instantiation depth exceeds maximum of %d"
8502                    " (use -ftemplate-depth= to increase the maximum)",
8503                    max_tinst_depth);
8504       return false;
8505     }
8506
8507   /* If the current instantiation caused problems, don't let it instantiate
8508      anything else.  Do allow deduction substitution and decls usable in
8509      constant expressions.  */
8510   if (limit_bad_template_recursion (d))
8511     return false;
8512
8513   new_level = ggc_alloc<tinst_level> ();
8514   new_level->decl = d;
8515   new_level->locus = loc;
8516   new_level->errors = errorcount+sorrycount;
8517   new_level->in_system_header_p = in_system_header_at (input_location);
8518   new_level->next = current_tinst_level;
8519   current_tinst_level = new_level;
8520
8521   ++tinst_depth;
8522   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
8523     depth_reached = tinst_depth;
8524
8525   return true;
8526 }
8527
8528 /* We're done instantiating this template; return to the instantiation
8529    context.  */
8530
8531 void
8532 pop_tinst_level (void)
8533 {
8534   /* Restore the filename and line number stashed away when we started
8535      this instantiation.  */
8536   input_location = current_tinst_level->locus;
8537   current_tinst_level = current_tinst_level->next;
8538   --tinst_depth;
8539 }
8540
8541 /* We're instantiating a deferred template; restore the template
8542    instantiation context in which the instantiation was requested, which
8543    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
8544
8545 static tree
8546 reopen_tinst_level (struct tinst_level *level)
8547 {
8548   struct tinst_level *t;
8549
8550   tinst_depth = 0;
8551   for (t = level; t; t = t->next)
8552     ++tinst_depth;
8553
8554   current_tinst_level = level;
8555   pop_tinst_level ();
8556   if (current_tinst_level)
8557     current_tinst_level->errors = errorcount+sorrycount;
8558   return level->decl;
8559 }
8560
8561 /* Returns the TINST_LEVEL which gives the original instantiation
8562    context.  */
8563
8564 struct tinst_level *
8565 outermost_tinst_level (void)
8566 {
8567   struct tinst_level *level = current_tinst_level;
8568   if (level)
8569     while (level->next)
8570       level = level->next;
8571   return level;
8572 }
8573
8574 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
8575    vector of template arguments, as for tsubst.
8576
8577    Returns an appropriate tsubst'd friend declaration.  */
8578
8579 static tree
8580 tsubst_friend_function (tree decl, tree args)
8581 {
8582   tree new_friend;
8583
8584   if (TREE_CODE (decl) == FUNCTION_DECL
8585       && DECL_TEMPLATE_INSTANTIATION (decl)
8586       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8587     /* This was a friend declared with an explicit template
8588        argument list, e.g.:
8589
8590        friend void f<>(T);
8591
8592        to indicate that f was a template instantiation, not a new
8593        function declaration.  Now, we have to figure out what
8594        instantiation of what template.  */
8595     {
8596       tree template_id, arglist, fns;
8597       tree new_args;
8598       tree tmpl;
8599       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8600
8601       /* Friend functions are looked up in the containing namespace scope.
8602          We must enter that scope, to avoid finding member functions of the
8603          current class with same name.  */
8604       push_nested_namespace (ns);
8605       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8606                          tf_warning_or_error, NULL_TREE,
8607                          /*integral_constant_expression_p=*/false);
8608       pop_nested_namespace (ns);
8609       arglist = tsubst (DECL_TI_ARGS (decl), args,
8610                         tf_warning_or_error, NULL_TREE);
8611       template_id = lookup_template_function (fns, arglist);
8612
8613       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8614       tmpl = determine_specialization (template_id, new_friend,
8615                                        &new_args,
8616                                        /*need_member_template=*/0,
8617                                        TREE_VEC_LENGTH (args),
8618                                        tsk_none);
8619       return instantiate_template (tmpl, new_args, tf_error);
8620     }
8621
8622   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8623
8624   /* The NEW_FRIEND will look like an instantiation, to the
8625      compiler, but is not an instantiation from the point of view of
8626      the language.  For example, we might have had:
8627
8628      template <class T> struct S {
8629        template <class U> friend void f(T, U);
8630      };
8631
8632      Then, in S<int>, template <class U> void f(int, U) is not an
8633      instantiation of anything.  */
8634   if (new_friend == error_mark_node)
8635     return error_mark_node;
8636
8637   DECL_USE_TEMPLATE (new_friend) = 0;
8638   if (TREE_CODE (decl) == TEMPLATE_DECL)
8639     {
8640       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8641       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8642         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8643     }
8644
8645   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8646      is not a template instantiation and should not be mangled like
8647      one.  Therefore, we forget the mangling here; we'll recompute it
8648      later if we need it.  */
8649   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8650     {
8651       SET_DECL_RTL (new_friend, NULL);
8652       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8653     }
8654
8655   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8656     {
8657       tree old_decl;
8658       tree new_friend_template_info;
8659       tree new_friend_result_template_info;
8660       tree ns;
8661       int  new_friend_is_defn;
8662
8663       /* We must save some information from NEW_FRIEND before calling
8664          duplicate decls since that function will free NEW_FRIEND if
8665          possible.  */
8666       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8667       new_friend_is_defn =
8668             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8669                            (template_for_substitution (new_friend)))
8670              != NULL_TREE);
8671       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8672         {
8673           /* This declaration is a `primary' template.  */
8674           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8675
8676           new_friend_result_template_info
8677             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8678         }
8679       else
8680         new_friend_result_template_info = NULL_TREE;
8681
8682       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8683       if (new_friend_is_defn)
8684         DECL_INITIAL (new_friend) = error_mark_node;
8685
8686       /* Inside pushdecl_namespace_level, we will push into the
8687          current namespace. However, the friend function should go
8688          into the namespace of the template.  */
8689       ns = decl_namespace_context (new_friend);
8690       push_nested_namespace (ns);
8691       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8692       pop_nested_namespace (ns);
8693
8694       if (old_decl == error_mark_node)
8695         return error_mark_node;
8696
8697       if (old_decl != new_friend)
8698         {
8699           /* This new friend declaration matched an existing
8700              declaration.  For example, given:
8701
8702                template <class T> void f(T);
8703                template <class U> class C {
8704                  template <class T> friend void f(T) {}
8705                };
8706
8707              the friend declaration actually provides the definition
8708              of `f', once C has been instantiated for some type.  So,
8709              old_decl will be the out-of-class template declaration,
8710              while new_friend is the in-class definition.
8711
8712              But, if `f' was called before this point, the
8713              instantiation of `f' will have DECL_TI_ARGS corresponding
8714              to `T' but not to `U', references to which might appear
8715              in the definition of `f'.  Previously, the most general
8716              template for an instantiation of `f' was the out-of-class
8717              version; now it is the in-class version.  Therefore, we
8718              run through all specialization of `f', adding to their
8719              DECL_TI_ARGS appropriately.  In particular, they need a
8720              new set of outer arguments, corresponding to the
8721              arguments for this class instantiation.
8722
8723              The same situation can arise with something like this:
8724
8725                friend void f(int);
8726                template <class T> class C {
8727                  friend void f(T) {}
8728                };
8729
8730              when `C<int>' is instantiated.  Now, `f(int)' is defined
8731              in the class.  */
8732
8733           if (!new_friend_is_defn)
8734             /* On the other hand, if the in-class declaration does
8735                *not* provide a definition, then we don't want to alter
8736                existing definitions.  We can just leave everything
8737                alone.  */
8738             ;
8739           else
8740             {
8741               tree new_template = TI_TEMPLATE (new_friend_template_info);
8742               tree new_args = TI_ARGS (new_friend_template_info);
8743
8744               /* Overwrite whatever template info was there before, if
8745                  any, with the new template information pertaining to
8746                  the declaration.  */
8747               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8748
8749               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8750                 {
8751                   /* We should have called reregister_specialization in
8752                      duplicate_decls.  */
8753                   gcc_assert (retrieve_specialization (new_template,
8754                                                        new_args, 0)
8755                               == old_decl);
8756
8757                   /* Instantiate it if the global has already been used.  */
8758                   if (DECL_ODR_USED (old_decl))
8759                     instantiate_decl (old_decl, /*defer_ok=*/true,
8760                                       /*expl_inst_class_mem_p=*/false);
8761                 }
8762               else
8763                 {
8764                   tree t;
8765
8766                   /* Indicate that the old function template is a partial
8767                      instantiation.  */
8768                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8769                     = new_friend_result_template_info;
8770
8771                   gcc_assert (new_template
8772                               == most_general_template (new_template));
8773                   gcc_assert (new_template != old_decl);
8774
8775                   /* Reassign any specializations already in the hash table
8776                      to the new more general template, and add the
8777                      additional template args.  */
8778                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8779                        t != NULL_TREE;
8780                        t = TREE_CHAIN (t))
8781                     {
8782                       tree spec = TREE_VALUE (t);
8783                       spec_entry elt;
8784
8785                       elt.tmpl = old_decl;
8786                       elt.args = DECL_TI_ARGS (spec);
8787                       elt.spec = NULL_TREE;
8788
8789                       decl_specializations->remove_elt (&elt);
8790
8791                       DECL_TI_ARGS (spec)
8792                         = add_outermost_template_args (new_args,
8793                                                        DECL_TI_ARGS (spec));
8794
8795                       register_specialization
8796                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8797
8798                     }
8799                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8800                 }
8801             }
8802
8803           /* The information from NEW_FRIEND has been merged into OLD_DECL
8804              by duplicate_decls.  */
8805           new_friend = old_decl;
8806         }
8807     }
8808   else
8809     {
8810       tree context = DECL_CONTEXT (new_friend);
8811       bool dependent_p;
8812
8813       /* In the code
8814            template <class T> class C {
8815              template <class U> friend void C1<U>::f (); // case 1
8816              friend void C2<T>::f ();                    // case 2
8817            };
8818          we only need to make sure CONTEXT is a complete type for
8819          case 2.  To distinguish between the two cases, we note that
8820          CONTEXT of case 1 remains dependent type after tsubst while
8821          this isn't true for case 2.  */
8822       ++processing_template_decl;
8823       dependent_p = dependent_type_p (context);
8824       --processing_template_decl;
8825
8826       if (!dependent_p
8827           && !complete_type_or_else (context, NULL_TREE))
8828         return error_mark_node;
8829
8830       if (COMPLETE_TYPE_P (context))
8831         {
8832           tree fn = new_friend;
8833           /* do_friend adds the TEMPLATE_DECL for any member friend
8834              template even if it isn't a member template, i.e.
8835                template <class T> friend A<T>::f();
8836              Look through it in that case.  */
8837           if (TREE_CODE (fn) == TEMPLATE_DECL
8838               && !PRIMARY_TEMPLATE_P (fn))
8839             fn = DECL_TEMPLATE_RESULT (fn);
8840           /* Check to see that the declaration is really present, and,
8841              possibly obtain an improved declaration.  */
8842           fn = check_classfn (context, fn, NULL_TREE);
8843
8844           if (fn)
8845             new_friend = fn;
8846         }
8847     }
8848
8849   return new_friend;
8850 }
8851
8852 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8853    template arguments, as for tsubst.
8854
8855    Returns an appropriate tsubst'd friend type or error_mark_node on
8856    failure.  */
8857
8858 static tree
8859 tsubst_friend_class (tree friend_tmpl, tree args)
8860 {
8861   tree friend_type;
8862   tree tmpl;
8863   tree context;
8864
8865   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
8866     {
8867       tree t = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
8868       return TREE_TYPE (t);
8869     }
8870
8871   context = CP_DECL_CONTEXT (friend_tmpl);
8872
8873   if (context != global_namespace)
8874     {
8875       if (TREE_CODE (context) == NAMESPACE_DECL)
8876         push_nested_namespace (context);
8877       else
8878         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8879     }
8880
8881   /* Look for a class template declaration.  We look for hidden names
8882      because two friend declarations of the same template are the
8883      same.  For example, in:
8884
8885        struct A { 
8886          template <typename> friend class F;
8887        };
8888        template <typename> struct B { 
8889          template <typename> friend class F;
8890        };
8891
8892      both F templates are the same.  */
8893   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8894                            /*block_p=*/true, 0, LOOKUP_HIDDEN);
8895
8896   /* But, if we don't find one, it might be because we're in a
8897      situation like this:
8898
8899        template <class T>
8900        struct S {
8901          template <class U>
8902          friend struct S;
8903        };
8904
8905      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8906      for `S<int>', not the TEMPLATE_DECL.  */
8907   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8908     {
8909       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8910       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8911     }
8912
8913   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8914     {
8915       /* The friend template has already been declared.  Just
8916          check to see that the declarations match, and install any new
8917          default parameters.  We must tsubst the default parameters,
8918          of course.  We only need the innermost template parameters
8919          because that is all that redeclare_class_template will look
8920          at.  */
8921       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8922           > TMPL_ARGS_DEPTH (args))
8923         {
8924           tree parms;
8925           location_t saved_input_location;
8926           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8927                                          args, tf_warning_or_error);
8928
8929           saved_input_location = input_location;
8930           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8931           redeclare_class_template (TREE_TYPE (tmpl), parms);
8932           input_location = saved_input_location;
8933           
8934         }
8935
8936       friend_type = TREE_TYPE (tmpl);
8937     }
8938   else
8939     {
8940       /* The friend template has not already been declared.  In this
8941          case, the instantiation of the template class will cause the
8942          injection of this template into the global scope.  */
8943       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8944       if (tmpl == error_mark_node)
8945         return error_mark_node;
8946
8947       /* The new TMPL is not an instantiation of anything, so we
8948          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8949          the new type because that is supposed to be the corresponding
8950          template decl, i.e., TMPL.  */
8951       DECL_USE_TEMPLATE (tmpl) = 0;
8952       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8953       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8954       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8955         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8956
8957       /* Inject this template into the global scope.  */
8958       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8959     }
8960
8961   if (context != global_namespace)
8962     {
8963       if (TREE_CODE (context) == NAMESPACE_DECL)
8964         pop_nested_namespace (context);
8965       else
8966         pop_nested_class ();
8967     }
8968
8969   return friend_type;
8970 }
8971
8972 /* Returns zero if TYPE cannot be completed later due to circularity.
8973    Otherwise returns one.  */
8974
8975 static int
8976 can_complete_type_without_circularity (tree type)
8977 {
8978   if (type == NULL_TREE || type == error_mark_node)
8979     return 0;
8980   else if (COMPLETE_TYPE_P (type))
8981     return 1;
8982   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8983     return can_complete_type_without_circularity (TREE_TYPE (type));
8984   else if (CLASS_TYPE_P (type)
8985            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8986     return 0;
8987   else
8988     return 1;
8989 }
8990
8991 static tree tsubst_omp_clauses (tree, bool, tree, tsubst_flags_t, tree);
8992
8993 /* Apply any attributes which had to be deferred until instantiation
8994    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8995    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8996
8997 static void
8998 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8999                                 tree args, tsubst_flags_t complain, tree in_decl)
9000 {
9001   tree last_dep = NULL_TREE;
9002   tree t;
9003   tree *p;
9004
9005   for (t = attributes; t; t = TREE_CHAIN (t))
9006     if (ATTR_IS_DEPENDENT (t))
9007       {
9008         last_dep = t;
9009         attributes = copy_list (attributes);
9010         break;
9011       }
9012
9013   if (DECL_P (*decl_p))
9014     {
9015       if (TREE_TYPE (*decl_p) == error_mark_node)
9016         return;
9017       p = &DECL_ATTRIBUTES (*decl_p);
9018     }
9019   else
9020     p = &TYPE_ATTRIBUTES (*decl_p);
9021
9022   if (last_dep)
9023     {
9024       tree late_attrs = NULL_TREE;
9025       tree *q = &late_attrs;
9026
9027       for (*p = attributes; *p; )
9028         {
9029           t = *p;
9030           if (ATTR_IS_DEPENDENT (t))
9031             {
9032               *p = TREE_CHAIN (t);
9033               TREE_CHAIN (t) = NULL_TREE;
9034               if ((flag_openmp || flag_cilkplus)
9035                   && is_attribute_p ("omp declare simd",
9036                                      get_attribute_name (t))
9037                   && TREE_VALUE (t))
9038                 {
9039                   tree clauses = TREE_VALUE (TREE_VALUE (t));
9040                   clauses = tsubst_omp_clauses (clauses, true, args,
9041                                                 complain, in_decl);
9042                   c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
9043                   clauses = finish_omp_clauses (clauses);
9044                   tree parms = DECL_ARGUMENTS (*decl_p);
9045                   clauses
9046                     = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
9047                   if (clauses)
9048                     TREE_VALUE (TREE_VALUE (t)) = clauses;
9049                   else
9050                     TREE_VALUE (t) = NULL_TREE;
9051                 }
9052               /* If the first attribute argument is an identifier, don't
9053                  pass it through tsubst.  Attributes like mode, format,
9054                  cleanup and several target specific attributes expect it
9055                  unmodified.  */
9056               else if (attribute_takes_identifier_p (get_attribute_name (t))
9057                        && TREE_VALUE (t))
9058                 {
9059                   tree chain
9060                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
9061                                    in_decl,
9062                                    /*integral_constant_expression_p=*/false);
9063                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
9064                     TREE_VALUE (t)
9065                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
9066                                    chain);
9067                 }
9068               else
9069                 TREE_VALUE (t)
9070                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
9071                                  /*integral_constant_expression_p=*/false);
9072               *q = t;
9073               q = &TREE_CHAIN (t);
9074             }
9075           else
9076             p = &TREE_CHAIN (t);
9077         }
9078
9079       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
9080     }
9081 }
9082
9083 /* Perform (or defer) access check for typedefs that were referenced
9084    from within the template TMPL code.
9085    This is a subroutine of instantiate_decl and instantiate_class_template.
9086    TMPL is the template to consider and TARGS is the list of arguments of
9087    that template.  */
9088
9089 static void
9090 perform_typedefs_access_check (tree tmpl, tree targs)
9091 {
9092   location_t saved_location;
9093   unsigned i;
9094   qualified_typedef_usage_t *iter;
9095
9096   if (!tmpl
9097       || (!CLASS_TYPE_P (tmpl)
9098           && TREE_CODE (tmpl) != FUNCTION_DECL))
9099     return;
9100
9101   saved_location = input_location;
9102   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
9103     {
9104       tree type_decl = iter->typedef_decl;
9105       tree type_scope = iter->context;
9106
9107       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
9108         continue;
9109
9110       if (uses_template_parms (type_decl))
9111         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
9112       if (uses_template_parms (type_scope))
9113         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
9114
9115       /* Make access check error messages point to the location
9116          of the use of the typedef.  */
9117       input_location = iter->locus;
9118       perform_or_defer_access_check (TYPE_BINFO (type_scope),
9119                                      type_decl, type_decl,
9120                                      tf_warning_or_error);
9121     }
9122     input_location = saved_location;
9123 }
9124
9125 static tree
9126 instantiate_class_template_1 (tree type)
9127 {
9128   tree templ, args, pattern, t, member;
9129   tree typedecl;
9130   tree pbinfo;
9131   tree base_list;
9132   unsigned int saved_maximum_field_alignment;
9133   tree fn_context;
9134
9135   if (type == error_mark_node)
9136     return error_mark_node;
9137
9138   if (COMPLETE_OR_OPEN_TYPE_P (type)
9139       || uses_template_parms (type))
9140     return type;
9141
9142   /* Figure out which template is being instantiated.  */
9143   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
9144   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
9145
9146   /* Determine what specialization of the original template to
9147      instantiate.  */
9148   t = most_specialized_partial_spec (type, tf_warning_or_error);
9149   if (t == error_mark_node)
9150     {
9151       TYPE_BEING_DEFINED (type) = 1;
9152       return error_mark_node;
9153     }
9154   else if (t)
9155     {
9156       /* This TYPE is actually an instantiation of a partial
9157          specialization.  We replace the innermost set of ARGS with
9158          the arguments appropriate for substitution.  For example,
9159          given:
9160
9161            template <class T> struct S {};
9162            template <class T> struct S<T*> {};
9163
9164          and supposing that we are instantiating S<int*>, ARGS will
9165          presently be {int*} -- but we need {int}.  */
9166       pattern = TREE_TYPE (t);
9167       args = TREE_PURPOSE (t);
9168     }
9169   else
9170     {
9171       pattern = TREE_TYPE (templ);
9172       args = CLASSTYPE_TI_ARGS (type);
9173     }
9174
9175   /* If the template we're instantiating is incomplete, then clearly
9176      there's nothing we can do.  */
9177   if (!COMPLETE_TYPE_P (pattern))
9178     return type;
9179
9180   /* If we've recursively instantiated too many templates, stop.  */
9181   if (! push_tinst_level (type))
9182     return type;
9183
9184   /* Now we're really doing the instantiation.  Mark the type as in
9185      the process of being defined.  */
9186   TYPE_BEING_DEFINED (type) = 1;
9187
9188   /* We may be in the middle of deferred access check.  Disable
9189      it now.  */
9190   push_deferring_access_checks (dk_no_deferred);
9191
9192   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
9193   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
9194   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
9195     fn_context = error_mark_node;
9196   if (!fn_context)
9197     push_to_top_level ();
9198   /* Use #pragma pack from the template context.  */
9199   saved_maximum_field_alignment = maximum_field_alignment;
9200   maximum_field_alignment = TYPE_PRECISION (pattern);
9201
9202   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
9203
9204   /* Set the input location to the most specialized template definition.
9205      This is needed if tsubsting causes an error.  */
9206   typedecl = TYPE_MAIN_DECL (pattern);
9207   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
9208     DECL_SOURCE_LOCATION (typedecl);
9209
9210   TYPE_PACKED (type) = TYPE_PACKED (pattern);
9211   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
9212   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
9213   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
9214   if (ANON_AGGR_TYPE_P (pattern))
9215     SET_ANON_AGGR_TYPE_P (type);
9216   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
9217     {
9218       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
9219       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
9220       /* Adjust visibility for template arguments.  */
9221       determine_visibility (TYPE_MAIN_DECL (type));
9222     }
9223   if (CLASS_TYPE_P (type))
9224     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
9225
9226   pbinfo = TYPE_BINFO (pattern);
9227
9228   /* We should never instantiate a nested class before its enclosing
9229      class; we need to look up the nested class by name before we can
9230      instantiate it, and that lookup should instantiate the enclosing
9231      class.  */
9232   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
9233               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
9234
9235   base_list = NULL_TREE;
9236   if (BINFO_N_BASE_BINFOS (pbinfo))
9237     {
9238       tree pbase_binfo;
9239       tree pushed_scope;
9240       int i;
9241
9242       /* We must enter the scope containing the type, as that is where
9243          the accessibility of types named in dependent bases are
9244          looked up from.  */
9245       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
9246
9247       /* Substitute into each of the bases to determine the actual
9248          basetypes.  */
9249       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
9250         {
9251           tree base;
9252           tree access = BINFO_BASE_ACCESS (pbinfo, i);
9253           tree expanded_bases = NULL_TREE;
9254           int idx, len = 1;
9255
9256           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
9257             {
9258               expanded_bases = 
9259                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
9260                                        args, tf_error, NULL_TREE);
9261               if (expanded_bases == error_mark_node)
9262                 continue;
9263
9264               len = TREE_VEC_LENGTH (expanded_bases);
9265             }
9266
9267           for (idx = 0; idx < len; idx++)
9268             {
9269               if (expanded_bases)
9270                 /* Extract the already-expanded base class.  */
9271                 base = TREE_VEC_ELT (expanded_bases, idx);
9272               else
9273                 /* Substitute to figure out the base class.  */
9274                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
9275                                NULL_TREE);
9276
9277               if (base == error_mark_node)
9278                 continue;
9279
9280               base_list = tree_cons (access, base, base_list);
9281               if (BINFO_VIRTUAL_P (pbase_binfo))
9282                 TREE_TYPE (base_list) = integer_type_node;
9283             }
9284         }
9285
9286       /* The list is now in reverse order; correct that.  */
9287       base_list = nreverse (base_list);
9288
9289       if (pushed_scope)
9290         pop_scope (pushed_scope);
9291     }
9292   /* Now call xref_basetypes to set up all the base-class
9293      information.  */
9294   xref_basetypes (type, base_list);
9295
9296   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
9297                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
9298                                   args, tf_error, NULL_TREE);
9299   fixup_attribute_variants (type);
9300
9301   /* Now that our base classes are set up, enter the scope of the
9302      class, so that name lookups into base classes, etc. will work
9303      correctly.  This is precisely analogous to what we do in
9304      begin_class_definition when defining an ordinary non-template
9305      class, except we also need to push the enclosing classes.  */
9306   push_nested_class (type);
9307
9308   /* Now members are processed in the order of declaration.  */
9309   for (member = CLASSTYPE_DECL_LIST (pattern);
9310        member; member = TREE_CHAIN (member))
9311     {
9312       tree t = TREE_VALUE (member);
9313
9314       if (TREE_PURPOSE (member))
9315         {
9316           if (TYPE_P (t))
9317             {
9318               /* Build new CLASSTYPE_NESTED_UTDS.  */
9319
9320               tree newtag;
9321               bool class_template_p;
9322
9323               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
9324                                   && TYPE_LANG_SPECIFIC (t)
9325                                   && CLASSTYPE_IS_TEMPLATE (t));
9326               /* If the member is a class template, then -- even after
9327                  substitution -- there may be dependent types in the
9328                  template argument list for the class.  We increment
9329                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
9330                  that function will assume that no types are dependent
9331                  when outside of a template.  */
9332               if (class_template_p)
9333                 ++processing_template_decl;
9334               newtag = tsubst (t, args, tf_error, NULL_TREE);
9335               if (class_template_p)
9336                 --processing_template_decl;
9337               if (newtag == error_mark_node)
9338                 continue;
9339
9340               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
9341                 {
9342                   tree name = TYPE_IDENTIFIER (t);
9343
9344                   if (class_template_p)
9345                     /* Unfortunately, lookup_template_class sets
9346                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
9347                        instantiation (i.e., for the type of a member
9348                        template class nested within a template class.)
9349                        This behavior is required for
9350                        maybe_process_partial_specialization to work
9351                        correctly, but is not accurate in this case;
9352                        the TAG is not an instantiation of anything.
9353                        (The corresponding TEMPLATE_DECL is an
9354                        instantiation, but the TYPE is not.) */
9355                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
9356
9357                   /* Now, we call pushtag to put this NEWTAG into the scope of
9358                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
9359                      pushtag calling push_template_decl.  We don't have to do
9360                      this for enums because it will already have been done in
9361                      tsubst_enum.  */
9362                   if (name)
9363                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
9364                   pushtag (name, newtag, /*tag_scope=*/ts_current);
9365                 }
9366             }
9367           else if (DECL_DECLARES_FUNCTION_P (t))
9368             {
9369               /* Build new TYPE_METHODS.  */
9370               tree r;
9371
9372               if (TREE_CODE (t) == TEMPLATE_DECL)
9373                 ++processing_template_decl;
9374               r = tsubst (t, args, tf_error, NULL_TREE);
9375               if (TREE_CODE (t) == TEMPLATE_DECL)
9376                 --processing_template_decl;
9377               set_current_access_from_decl (r);
9378               finish_member_declaration (r);
9379               /* Instantiate members marked with attribute used.  */
9380               if (r != error_mark_node && DECL_PRESERVE_P (r))
9381                 mark_used (r);
9382               if (TREE_CODE (r) == FUNCTION_DECL
9383                   && DECL_OMP_DECLARE_REDUCTION_P (r))
9384                 cp_check_omp_declare_reduction (r);
9385             }
9386           else if (DECL_CLASS_TEMPLATE_P (t)
9387                    && LAMBDA_TYPE_P (TREE_TYPE (t)))
9388             /* A closure type for a lambda in a default argument for a
9389                member template.  Ignore it; it will be instantiated with
9390                the default argument.  */;
9391           else
9392             {
9393               /* Build new TYPE_FIELDS.  */
9394               if (TREE_CODE (t) == STATIC_ASSERT)
9395                 {
9396                   tree condition;
9397  
9398                   ++c_inhibit_evaluation_warnings;
9399                   condition =
9400                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
9401                                  tf_warning_or_error, NULL_TREE,
9402                                  /*integral_constant_expression_p=*/true);
9403                   --c_inhibit_evaluation_warnings;
9404
9405                   finish_static_assert (condition,
9406                                         STATIC_ASSERT_MESSAGE (t), 
9407                                         STATIC_ASSERT_SOURCE_LOCATION (t),
9408                                         /*member_p=*/true);
9409                 }
9410               else if (TREE_CODE (t) != CONST_DECL)
9411                 {
9412                   tree r;
9413                   tree vec = NULL_TREE;
9414                   int len = 1;
9415
9416                   /* The file and line for this declaration, to
9417                      assist in error message reporting.  Since we
9418                      called push_tinst_level above, we don't need to
9419                      restore these.  */
9420                   input_location = DECL_SOURCE_LOCATION (t);
9421
9422                   if (TREE_CODE (t) == TEMPLATE_DECL)
9423                     ++processing_template_decl;
9424                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
9425                   if (TREE_CODE (t) == TEMPLATE_DECL)
9426                     --processing_template_decl;
9427
9428                   if (TREE_CODE (r) == TREE_VEC)
9429                     {
9430                       /* A capture pack became multiple fields.  */
9431                       vec = r;
9432                       len = TREE_VEC_LENGTH (vec);
9433                     }
9434
9435                   for (int i = 0; i < len; ++i)
9436                     {
9437                       if (vec)
9438                         r = TREE_VEC_ELT (vec, i);
9439                       if (VAR_P (r))
9440                         {
9441                           /* In [temp.inst]:
9442
9443                              [t]he initialization (and any associated
9444                              side-effects) of a static data member does
9445                              not occur unless the static data member is
9446                              itself used in a way that requires the
9447                              definition of the static data member to
9448                              exist.
9449
9450                              Therefore, we do not substitute into the
9451                              initialized for the static data member here.  */
9452                           finish_static_data_member_decl
9453                             (r,
9454                              /*init=*/NULL_TREE,
9455                              /*init_const_expr_p=*/false,
9456                              /*asmspec_tree=*/NULL_TREE,
9457                              /*flags=*/0);
9458                           /* Instantiate members marked with attribute used. */
9459                           if (r != error_mark_node && DECL_PRESERVE_P (r))
9460                             mark_used (r);
9461                         }
9462                       else if (TREE_CODE (r) == FIELD_DECL)
9463                         {
9464                           /* Determine whether R has a valid type and can be
9465                              completed later.  If R is invalid, then its type
9466                              is replaced by error_mark_node.  */
9467                           tree rtype = TREE_TYPE (r);
9468                           if (can_complete_type_without_circularity (rtype))
9469                             complete_type (rtype);
9470
9471                           if (!COMPLETE_TYPE_P (rtype))
9472                             {
9473                               cxx_incomplete_type_error (r, rtype);
9474                               TREE_TYPE (r) = error_mark_node;
9475                             }
9476                         }
9477
9478                       /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
9479                          such a thing will already have been added to the field
9480                          list by tsubst_enum in finish_member_declaration in the
9481                          CLASSTYPE_NESTED_UTDS case above.  */
9482                       if (!(TREE_CODE (r) == TYPE_DECL
9483                             && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
9484                             && DECL_ARTIFICIAL (r)))
9485                         {
9486                           set_current_access_from_decl (r);
9487                           finish_member_declaration (r);
9488                         }
9489                     }
9490                 }
9491             }
9492         }
9493       else
9494         {
9495           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
9496               || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9497             {
9498               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
9499
9500               tree friend_type = t;
9501               bool adjust_processing_template_decl = false;
9502
9503               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
9504                 {
9505                   /* template <class T> friend class C;  */
9506                   friend_type = tsubst_friend_class (friend_type, args);
9507                   adjust_processing_template_decl = true;
9508                 }
9509               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
9510                 {
9511                   /* template <class T> friend class C::D;  */
9512                   friend_type = tsubst (friend_type, args,
9513                                         tf_warning_or_error, NULL_TREE);
9514                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
9515                     friend_type = TREE_TYPE (friend_type);
9516                   adjust_processing_template_decl = true;
9517                 }
9518               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
9519                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
9520                 {
9521                   /* This could be either
9522
9523                        friend class T::C;
9524
9525                      when dependent_type_p is false or
9526
9527                        template <class U> friend class T::C;
9528
9529                      otherwise.  */
9530                   friend_type = tsubst (friend_type, args,
9531                                         tf_warning_or_error, NULL_TREE);
9532                   /* Bump processing_template_decl for correct
9533                      dependent_type_p calculation.  */
9534                   ++processing_template_decl;
9535                   if (dependent_type_p (friend_type))
9536                     adjust_processing_template_decl = true;
9537                   --processing_template_decl;
9538                 }
9539               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
9540                        && hidden_name_p (TYPE_NAME (friend_type)))
9541                 {
9542                   /* friend class C;
9543
9544                      where C hasn't been declared yet.  Let's lookup name
9545                      from namespace scope directly, bypassing any name that
9546                      come from dependent base class.  */
9547                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
9548
9549                   /* The call to xref_tag_from_type does injection for friend
9550                      classes.  */
9551                   push_nested_namespace (ns);
9552                   friend_type =
9553                     xref_tag_from_type (friend_type, NULL_TREE,
9554                                         /*tag_scope=*/ts_current);
9555                   pop_nested_namespace (ns);
9556                 }
9557               else if (uses_template_parms (friend_type))
9558                 /* friend class C<T>;  */
9559                 friend_type = tsubst (friend_type, args,
9560                                       tf_warning_or_error, NULL_TREE);
9561               /* Otherwise it's
9562
9563                    friend class C;
9564
9565                  where C is already declared or
9566
9567                    friend class C<int>;
9568
9569                  We don't have to do anything in these cases.  */
9570
9571               if (adjust_processing_template_decl)
9572                 /* Trick make_friend_class into realizing that the friend
9573                    we're adding is a template, not an ordinary class.  It's
9574                    important that we use make_friend_class since it will
9575                    perform some error-checking and output cross-reference
9576                    information.  */
9577                 ++processing_template_decl;
9578
9579               if (friend_type != error_mark_node)
9580                 make_friend_class (type, friend_type, /*complain=*/false);
9581
9582               if (adjust_processing_template_decl)
9583                 --processing_template_decl;
9584             }
9585           else
9586             {
9587               /* Build new DECL_FRIENDLIST.  */
9588               tree r;
9589
9590               /* The file and line for this declaration, to
9591                  assist in error message reporting.  Since we
9592                  called push_tinst_level above, we don't need to
9593                  restore these.  */
9594               input_location = DECL_SOURCE_LOCATION (t);
9595
9596               if (TREE_CODE (t) == TEMPLATE_DECL)
9597                 {
9598                   ++processing_template_decl;
9599                   push_deferring_access_checks (dk_no_check);
9600                 }
9601
9602               r = tsubst_friend_function (t, args);
9603               add_friend (type, r, /*complain=*/false);
9604               if (TREE_CODE (t) == TEMPLATE_DECL)
9605                 {
9606                   pop_deferring_access_checks ();
9607                   --processing_template_decl;
9608                 }
9609             }
9610         }
9611     }
9612
9613   if (tree expr = CLASSTYPE_LAMBDA_EXPR (type))
9614     {
9615       tree decl = lambda_function (type);
9616       if (decl)
9617         {
9618           if (!DECL_TEMPLATE_INFO (decl)
9619               || DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) != decl)
9620             instantiate_decl (decl, false, false);
9621
9622           /* We need to instantiate the capture list from the template
9623              after we've instantiated the closure members, but before we
9624              consider adding the conversion op.  Also keep any captures
9625              that may have been added during instantiation of the op().  */
9626           tree tmpl_expr = CLASSTYPE_LAMBDA_EXPR (pattern);
9627           tree tmpl_cap
9628             = tsubst_copy_and_build (LAMBDA_EXPR_CAPTURE_LIST (tmpl_expr),
9629                                      args, tf_warning_or_error, NULL_TREE,
9630                                      false, false);
9631
9632           LAMBDA_EXPR_CAPTURE_LIST (expr)
9633             = chainon (tmpl_cap, nreverse (LAMBDA_EXPR_CAPTURE_LIST (expr)));
9634
9635           maybe_add_lambda_conv_op (type);
9636         }
9637       else
9638         gcc_assert (errorcount);
9639     }
9640
9641   /* Set the file and line number information to whatever is given for
9642      the class itself.  This puts error messages involving generated
9643      implicit functions at a predictable point, and the same point
9644      that would be used for non-template classes.  */
9645   input_location = DECL_SOURCE_LOCATION (typedecl);
9646
9647   unreverse_member_declarations (type);
9648   finish_struct_1 (type);
9649   TYPE_BEING_DEFINED (type) = 0;
9650
9651   /* We don't instantiate default arguments for member functions.  14.7.1:
9652
9653      The implicit instantiation of a class template specialization causes
9654      the implicit instantiation of the declarations, but not of the
9655      definitions or default arguments, of the class member functions,
9656      member classes, static data members and member templates....  */
9657
9658   /* Some typedefs referenced from within the template code need to be access
9659      checked at template instantiation time, i.e now. These types were
9660      added to the template at parsing time. Let's get those and perform
9661      the access checks then.  */
9662   perform_typedefs_access_check (pattern, args);
9663   perform_deferred_access_checks (tf_warning_or_error);
9664   pop_nested_class ();
9665   maximum_field_alignment = saved_maximum_field_alignment;
9666   if (!fn_context)
9667     pop_from_top_level ();
9668   pop_deferring_access_checks ();
9669   pop_tinst_level ();
9670
9671   /* The vtable for a template class can be emitted in any translation
9672      unit in which the class is instantiated.  When there is no key
9673      method, however, finish_struct_1 will already have added TYPE to
9674      the keyed_classes list.  */
9675   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9676     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9677
9678   return type;
9679 }
9680
9681 /* Wrapper for instantiate_class_template_1.  */
9682
9683 tree
9684 instantiate_class_template (tree type)
9685 {
9686   tree ret;
9687   timevar_push (TV_TEMPLATE_INST);
9688   ret = instantiate_class_template_1 (type);
9689   timevar_pop (TV_TEMPLATE_INST);
9690   return ret;
9691 }
9692
9693 static tree
9694 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9695 {
9696   tree r;
9697
9698   if (!t)
9699     r = t;
9700   else if (TYPE_P (t))
9701     r = tsubst (t, args, complain, in_decl);
9702   else
9703     {
9704       if (!(complain & tf_warning))
9705         ++c_inhibit_evaluation_warnings;
9706       r = tsubst_expr (t, args, complain, in_decl,
9707                        /*integral_constant_expression_p=*/true);
9708       if (!(complain & tf_warning))
9709         --c_inhibit_evaluation_warnings;
9710     }
9711   return r;
9712 }
9713
9714 /* Given a function parameter pack TMPL_PARM and some function parameters
9715    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9716    and set *SPEC_P to point at the next point in the list.  */
9717
9718 static tree
9719 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9720 {
9721   /* Collect all of the extra "packed" parameters into an
9722      argument pack.  */
9723   tree parmvec;
9724   tree parmtypevec;
9725   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9726   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9727   tree spec_parm = *spec_p;
9728   int i, len;
9729
9730   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9731     if (tmpl_parm
9732         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9733       break;
9734
9735   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9736   parmvec = make_tree_vec (len);
9737   parmtypevec = make_tree_vec (len);
9738   spec_parm = *spec_p;
9739   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9740     {
9741       TREE_VEC_ELT (parmvec, i) = spec_parm;
9742       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9743     }
9744
9745   /* Build the argument packs.  */
9746   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9747   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9748   TREE_TYPE (argpack) = argtypepack;
9749   *spec_p = spec_parm;
9750
9751   return argpack;
9752 }
9753
9754 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9755    NONTYPE_ARGUMENT_PACK.  */
9756
9757 static tree
9758 make_fnparm_pack (tree spec_parm)
9759 {
9760   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9761 }
9762
9763 /* Return true iff the Ith element of the argument pack ARG_PACK is a
9764    pack expansion.  */
9765
9766 static bool
9767 argument_pack_element_is_expansion_p (tree arg_pack, int i)
9768 {
9769   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
9770   if (i >= TREE_VEC_LENGTH (vec))
9771     return false;
9772   return PACK_EXPANSION_P (TREE_VEC_ELT (vec, i));
9773 }
9774
9775
9776 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
9777
9778 static tree
9779 make_argument_pack_select (tree arg_pack, unsigned index)
9780 {
9781   tree aps = make_node (ARGUMENT_PACK_SELECT);
9782
9783   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
9784   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
9785
9786   return aps;
9787 }
9788
9789 /*  This is a subroutine of tsubst_pack_expansion.
9790
9791     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
9792     mechanism to store the (non complete list of) arguments of the
9793     substitution and return a non substituted pack expansion, in order
9794     to wait for when we have enough arguments to really perform the
9795     substitution.  */
9796
9797 static bool
9798 use_pack_expansion_extra_args_p (tree parm_packs,
9799                                  int arg_pack_len,
9800                                  bool has_empty_arg)
9801 {
9802   /* If one pack has an expansion and another pack has a normal
9803      argument or if one pack has an empty argument and an another
9804      one hasn't then tsubst_pack_expansion cannot perform the
9805      substitution and need to fall back on the
9806      PACK_EXPANSION_EXTRA mechanism.  */
9807   if (parm_packs == NULL_TREE)
9808     return false;
9809   else if (has_empty_arg)
9810     return true;
9811
9812   bool has_expansion_arg = false;
9813   for (int i = 0 ; i < arg_pack_len; ++i)
9814     {
9815       bool has_non_expansion_arg = false;
9816       for (tree parm_pack = parm_packs;
9817            parm_pack;
9818            parm_pack = TREE_CHAIN (parm_pack))
9819         {
9820           tree arg = TREE_VALUE (parm_pack);
9821
9822           if (argument_pack_element_is_expansion_p (arg, i))
9823             has_expansion_arg = true;
9824           else
9825             has_non_expansion_arg = true;
9826         }
9827
9828       if (has_expansion_arg && has_non_expansion_arg)
9829         return true;
9830     }
9831   return false;
9832 }
9833
9834 /* [temp.variadic]/6 says that:
9835
9836        The instantiation of a pack expansion [...]
9837        produces a list E1,E2, ..., En, where N is the number of elements
9838        in the pack expansion parameters.
9839
9840    This subroutine of tsubst_pack_expansion produces one of these Ei.
9841
9842    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
9843    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
9844    PATTERN, and each TREE_VALUE is its corresponding argument pack.
9845    INDEX is the index 'i' of the element Ei to produce.  ARGS,
9846    COMPLAIN, and IN_DECL are the same parameters as for the
9847    tsubst_pack_expansion function.
9848
9849    The function returns the resulting Ei upon successful completion,
9850    or error_mark_node.
9851
9852    Note that this function possibly modifies the ARGS parameter, so
9853    it's the responsibility of the caller to restore it.  */
9854
9855 static tree
9856 gen_elem_of_pack_expansion_instantiation (tree pattern,
9857                                           tree parm_packs,
9858                                           unsigned index,
9859                                           tree args /* This parm gets
9860                                                        modified.  */,
9861                                           tsubst_flags_t complain,
9862                                           tree in_decl)
9863 {
9864   tree t;
9865   bool ith_elem_is_expansion = false;
9866
9867   /* For each parameter pack, change the substitution of the parameter
9868      pack to the ith argument in its argument pack, then expand the
9869      pattern.  */
9870   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
9871     {
9872       tree parm = TREE_PURPOSE (pack);
9873       tree arg_pack = TREE_VALUE (pack);
9874       tree aps;                 /* instance of ARGUMENT_PACK_SELECT.  */
9875
9876       ith_elem_is_expansion |=
9877         argument_pack_element_is_expansion_p (arg_pack, index);
9878
9879       /* Select the Ith argument from the pack.  */
9880       if (TREE_CODE (parm) == PARM_DECL
9881           || TREE_CODE (parm) == FIELD_DECL)
9882         {
9883           if (index == 0)
9884             {
9885               aps = make_argument_pack_select (arg_pack, index);
9886               mark_used (parm);
9887               register_local_specialization (aps, parm);
9888             }
9889           else
9890             aps = retrieve_local_specialization (parm);
9891         }
9892       else
9893         {
9894           int idx, level;
9895           template_parm_level_and_index (parm, &level, &idx);
9896
9897           if (index == 0)
9898             {
9899               aps = make_argument_pack_select (arg_pack, index);
9900               /* Update the corresponding argument.  */
9901               TMPL_ARG (args, level, idx) = aps;
9902             }
9903           else
9904             /* Re-use the ARGUMENT_PACK_SELECT.  */
9905             aps = TMPL_ARG (args, level, idx);
9906         }
9907       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
9908     }
9909
9910   /* Substitute into the PATTERN with the (possibly altered)
9911      arguments.  */
9912   if (pattern == in_decl)
9913     /* Expanding a fixed parameter pack from
9914        coerce_template_parameter_pack.  */
9915     t = tsubst_decl (pattern, args, complain);
9916   else if (!TYPE_P (pattern))
9917     t = tsubst_expr (pattern, args, complain, in_decl,
9918                      /*integral_constant_expression_p=*/false);
9919   else
9920     t = tsubst (pattern, args, complain, in_decl);
9921
9922   /*  If the Ith argument pack element is a pack expansion, then
9923       the Ith element resulting from the substituting is going to
9924       be a pack expansion as well.  */
9925   if (ith_elem_is_expansion)
9926     t = make_pack_expansion (t);
9927
9928   return t;
9929 }
9930
9931 /* Substitute ARGS into T, which is an pack expansion
9932    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9933    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9934    (if only a partial substitution could be performed) or
9935    ERROR_MARK_NODE if there was an error.  */
9936 tree
9937 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9938                        tree in_decl)
9939 {
9940   tree pattern;
9941   tree pack, packs = NULL_TREE;
9942   bool unsubstituted_packs = false;
9943   int i, len = -1;
9944   tree result;
9945   hash_map<tree, tree> *saved_local_specializations = NULL;
9946   bool need_local_specializations = false;
9947   int levels;
9948
9949   gcc_assert (PACK_EXPANSION_P (t));
9950   pattern = PACK_EXPANSION_PATTERN (t);
9951
9952   /* Add in any args remembered from an earlier partial instantiation.  */
9953   args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
9954
9955   levels = TMPL_ARGS_DEPTH (args);
9956
9957   /* Determine the argument packs that will instantiate the parameter
9958      packs used in the expansion expression. While we're at it,
9959      compute the number of arguments to be expanded and make sure it
9960      is consistent.  */
9961   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9962        pack = TREE_CHAIN (pack))
9963     {
9964       tree parm_pack = TREE_VALUE (pack);
9965       tree arg_pack = NULL_TREE;
9966       tree orig_arg = NULL_TREE;
9967       int level = 0;
9968
9969       if (TREE_CODE (parm_pack) == BASES)
9970        {
9971          if (BASES_DIRECT (parm_pack))
9972            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
9973                                                         args, complain, in_decl, false));
9974          else
9975            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
9976                                                  args, complain, in_decl, false));
9977        }
9978       if (TREE_CODE (parm_pack) == PARM_DECL)
9979         {
9980           if (PACK_EXPANSION_LOCAL_P (t))
9981             arg_pack = retrieve_local_specialization (parm_pack);
9982           else
9983             {
9984               /* We can't rely on local_specializations for a parameter
9985                  name used later in a function declaration (such as in a
9986                  late-specified return type).  Even if it exists, it might
9987                  have the wrong value for a recursive call.  Just make a
9988                  dummy decl, since it's only used for its type.  */
9989               arg_pack = tsubst_decl (parm_pack, args, complain);
9990               if (arg_pack && DECL_PACK_P (arg_pack))
9991                 /* Partial instantiation of the parm_pack, we can't build
9992                    up an argument pack yet.  */
9993                 arg_pack = NULL_TREE;
9994               else
9995                 arg_pack = make_fnparm_pack (arg_pack);
9996               need_local_specializations = true;
9997             }
9998         }
9999       else if (TREE_CODE (parm_pack) == FIELD_DECL)
10000         arg_pack = tsubst_copy (parm_pack, args, complain, in_decl);
10001       else
10002         {
10003           int idx;
10004           template_parm_level_and_index (parm_pack, &level, &idx);
10005
10006           if (level <= levels)
10007             arg_pack = TMPL_ARG (args, level, idx);
10008         }
10009
10010       orig_arg = arg_pack;
10011       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
10012         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
10013       
10014       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
10015         /* This can only happen if we forget to expand an argument
10016            pack somewhere else. Just return an error, silently.  */
10017         {
10018           result = make_tree_vec (1);
10019           TREE_VEC_ELT (result, 0) = error_mark_node;
10020           return result;
10021         }
10022
10023       if (arg_pack)
10024         {
10025           int my_len = 
10026             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
10027
10028           /* Don't bother trying to do a partial substitution with
10029              incomplete packs; we'll try again after deduction.  */
10030           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
10031             return t;
10032
10033           if (len < 0)
10034             len = my_len;
10035           else if (len != my_len)
10036             {
10037               if (!(complain & tf_error))
10038                 /* Fail quietly.  */;
10039               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
10040                 error ("mismatched argument pack lengths while expanding "
10041                        "%<%T%>",
10042                        pattern);
10043               else
10044                 error ("mismatched argument pack lengths while expanding "
10045                        "%<%E%>",
10046                        pattern);
10047               return error_mark_node;
10048             }
10049
10050           /* Keep track of the parameter packs and their corresponding
10051              argument packs.  */
10052           packs = tree_cons (parm_pack, arg_pack, packs);
10053           TREE_TYPE (packs) = orig_arg;
10054         }
10055       else
10056         {
10057           /* We can't substitute for this parameter pack.  We use a flag as
10058              well as the missing_level counter because function parameter
10059              packs don't have a level.  */
10060           unsubstituted_packs = true;
10061         }
10062     }
10063
10064   /* If the expansion is just T..., return the matching argument pack.  */
10065   if (!unsubstituted_packs
10066       && TREE_PURPOSE (packs) == pattern)
10067     {
10068       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
10069       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
10070           || pack_expansion_args_count (args))
10071         return args;
10072       /* Otherwise use the normal path so we get convert_from_reference.  */
10073     }
10074
10075   /* We cannot expand this expansion expression, because we don't have
10076      all of the argument packs we need.  */
10077   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
10078     {
10079       /* We got some full packs, but we can't substitute them in until we
10080          have values for all the packs.  So remember these until then.  */
10081
10082       t = make_pack_expansion (pattern);
10083       PACK_EXPANSION_EXTRA_ARGS (t) = args;
10084       return t;
10085     }
10086   else if (unsubstituted_packs)
10087     {
10088       /* There were no real arguments, we're just replacing a parameter
10089          pack with another version of itself. Substitute into the
10090          pattern and return a PACK_EXPANSION_*. The caller will need to
10091          deal with that.  */
10092       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
10093         t = tsubst_expr (pattern, args, complain, in_decl,
10094                          /*integral_constant_expression_p=*/false);
10095       else
10096         t = tsubst (pattern, args, complain, in_decl);
10097       t = make_pack_expansion (t);
10098       return t;
10099     }
10100
10101   gcc_assert (len >= 0);
10102
10103   if (need_local_specializations)
10104     {
10105       /* We're in a late-specified return type, so create our own local
10106          specializations map; the current map is either NULL or (in the
10107          case of recursive unification) might have bindings that we don't
10108          want to use or alter.  */
10109       saved_local_specializations = local_specializations;
10110       local_specializations = new hash_map<tree, tree>;
10111     }
10112
10113   /* For each argument in each argument pack, substitute into the
10114      pattern.  */
10115   result = make_tree_vec (len);
10116   for (i = 0; i < len; ++i)
10117     {
10118       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
10119                                                     i,
10120                                                     args, complain,
10121                                                     in_decl);
10122       TREE_VEC_ELT (result, i) = t;
10123       if (t == error_mark_node)
10124         {
10125           result = error_mark_node;
10126           break;
10127         }
10128     }
10129
10130   /* Update ARGS to restore the substitution from parameter packs to
10131      their argument packs.  */
10132   for (pack = packs; pack; pack = TREE_CHAIN (pack))
10133     {
10134       tree parm = TREE_PURPOSE (pack);
10135
10136       if (TREE_CODE (parm) == PARM_DECL
10137           || TREE_CODE (parm) == FIELD_DECL)
10138         register_local_specialization (TREE_TYPE (pack), parm);
10139       else
10140         {
10141           int idx, level;
10142
10143           if (TREE_VALUE (pack) == NULL_TREE)
10144             continue;
10145
10146           template_parm_level_and_index (parm, &level, &idx);
10147           
10148           /* Update the corresponding argument.  */
10149           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
10150             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
10151               TREE_TYPE (pack);
10152           else
10153             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
10154         }
10155     }
10156
10157   if (need_local_specializations)
10158     {
10159       delete local_specializations;
10160       local_specializations = saved_local_specializations;
10161     }
10162   
10163   return result;
10164 }
10165
10166 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
10167    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
10168    parameter packs; all parms generated from a function parameter pack will
10169    have the same DECL_PARM_INDEX.  */
10170
10171 tree
10172 get_pattern_parm (tree parm, tree tmpl)
10173 {
10174   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
10175   tree patparm;
10176
10177   if (DECL_ARTIFICIAL (parm))
10178     {
10179       for (patparm = DECL_ARGUMENTS (pattern);
10180            patparm; patparm = DECL_CHAIN (patparm))
10181         if (DECL_ARTIFICIAL (patparm)
10182             && DECL_NAME (parm) == DECL_NAME (patparm))
10183           break;
10184     }
10185   else
10186     {
10187       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
10188       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
10189       gcc_assert (DECL_PARM_INDEX (patparm)
10190                   == DECL_PARM_INDEX (parm));
10191     }
10192
10193   return patparm;
10194 }
10195
10196 /* Substitute ARGS into the vector or list of template arguments T.  */
10197
10198 static tree
10199 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10200 {
10201   tree orig_t = t;
10202   int len, need_new = 0, i, expanded_len_adjust = 0, out;
10203   tree *elts;
10204
10205   if (t == error_mark_node)
10206     return error_mark_node;
10207
10208   len = TREE_VEC_LENGTH (t);
10209   elts = XALLOCAVEC (tree, len);
10210
10211   for (i = 0; i < len; i++)
10212     {
10213       tree orig_arg = TREE_VEC_ELT (t, i);
10214       tree new_arg;
10215
10216       if (TREE_CODE (orig_arg) == TREE_VEC)
10217         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
10218       else if (PACK_EXPANSION_P (orig_arg))
10219         {
10220           /* Substitute into an expansion expression.  */
10221           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
10222
10223           if (TREE_CODE (new_arg) == TREE_VEC)
10224             /* Add to the expanded length adjustment the number of
10225                expanded arguments. We subtract one from this
10226                measurement, because the argument pack expression
10227                itself is already counted as 1 in
10228                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
10229                the argument pack is empty.  */
10230             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
10231         }
10232       else if (ARGUMENT_PACK_P (orig_arg))
10233         {
10234           /* Substitute into each of the arguments.  */
10235           new_arg = TYPE_P (orig_arg)
10236             ? cxx_make_type (TREE_CODE (orig_arg))
10237             : make_node (TREE_CODE (orig_arg));
10238           
10239           SET_ARGUMENT_PACK_ARGS (
10240             new_arg,
10241             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
10242                                   args, complain, in_decl));
10243
10244           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
10245             new_arg = error_mark_node;
10246
10247           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
10248             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
10249                                           complain, in_decl);
10250             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
10251
10252             if (TREE_TYPE (new_arg) == error_mark_node)
10253               new_arg = error_mark_node;
10254           }
10255         }
10256       else
10257         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
10258
10259       if (new_arg == error_mark_node)
10260         return error_mark_node;
10261
10262       elts[i] = new_arg;
10263       if (new_arg != orig_arg)
10264         need_new = 1;
10265     }
10266
10267   if (!need_new)
10268     return t;
10269
10270   /* Make space for the expanded arguments coming from template
10271      argument packs.  */
10272   t = make_tree_vec (len + expanded_len_adjust);
10273   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
10274      arguments for a member template.
10275      In that case each TREE_VEC in ORIG_T represents a level of template
10276      arguments, and ORIG_T won't carry any non defaulted argument count.
10277      It will rather be the nested TREE_VECs that will carry one.
10278      In other words, ORIG_T carries a non defaulted argument count only
10279      if it doesn't contain any nested TREE_VEC.  */
10280   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
10281     {
10282       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
10283       count += expanded_len_adjust;
10284       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
10285     }
10286   for (i = 0, out = 0; i < len; i++)
10287     {
10288       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
10289            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
10290           && TREE_CODE (elts[i]) == TREE_VEC)
10291         {
10292           int idx;
10293
10294           /* Now expand the template argument pack "in place".  */
10295           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
10296             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
10297         }
10298       else
10299         {
10300           TREE_VEC_ELT (t, out) = elts[i];
10301           out++;
10302         }
10303     }
10304
10305   return t;
10306 }
10307
10308 /* Return the result of substituting ARGS into the template parameters
10309    given by PARMS.  If there are m levels of ARGS and m + n levels of
10310    PARMS, then the result will contain n levels of PARMS.  For
10311    example, if PARMS is `template <class T> template <class U>
10312    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
10313    result will be `template <int*, double, class V>'.  */
10314
10315 static tree
10316 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
10317 {
10318   tree r = NULL_TREE;
10319   tree* new_parms;
10320
10321   /* When substituting into a template, we must set
10322      PROCESSING_TEMPLATE_DECL as the template parameters may be
10323      dependent if they are based on one-another, and the dependency
10324      predicates are short-circuit outside of templates.  */
10325   ++processing_template_decl;
10326
10327   for (new_parms = &r;
10328        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
10329        new_parms = &(TREE_CHAIN (*new_parms)),
10330          parms = TREE_CHAIN (parms))
10331     {
10332       tree new_vec =
10333         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
10334       int i;
10335
10336       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
10337         {
10338           tree tuple;
10339
10340           if (parms == error_mark_node)
10341             continue;
10342
10343           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
10344
10345           if (tuple == error_mark_node)
10346             continue;
10347
10348           TREE_VEC_ELT (new_vec, i) =
10349             tsubst_template_parm (tuple, args, complain);
10350         }
10351
10352       *new_parms =
10353         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
10354                              - TMPL_ARGS_DEPTH (args)),
10355                    new_vec, NULL_TREE);
10356     }
10357
10358   --processing_template_decl;
10359
10360   return r;
10361 }
10362
10363 /* Return the result of substituting ARGS into one template parameter
10364    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
10365    parameter and which TREE_PURPOSE is the default argument of the
10366    template parameter.  */
10367
10368 static tree
10369 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
10370 {
10371   tree default_value, parm_decl;
10372
10373   if (args == NULL_TREE
10374       || t == NULL_TREE
10375       || t == error_mark_node)
10376     return t;
10377
10378   gcc_assert (TREE_CODE (t) == TREE_LIST);
10379
10380   default_value = TREE_PURPOSE (t);
10381   parm_decl = TREE_VALUE (t);
10382
10383   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
10384   if (TREE_CODE (parm_decl) == PARM_DECL
10385       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
10386     parm_decl = error_mark_node;
10387   default_value = tsubst_template_arg (default_value, args,
10388                                        complain, NULL_TREE);
10389
10390   return build_tree_list (default_value, parm_decl);
10391 }
10392
10393 /* Substitute the ARGS into the indicated aggregate (or enumeration)
10394    type T.  If T is not an aggregate or enumeration type, it is
10395    handled as if by tsubst.  IN_DECL is as for tsubst.  If
10396    ENTERING_SCOPE is nonzero, T is the context for a template which
10397    we are presently tsubst'ing.  Return the substituted value.  */
10398
10399 static tree
10400 tsubst_aggr_type (tree t,
10401                   tree args,
10402                   tsubst_flags_t complain,
10403                   tree in_decl,
10404                   int entering_scope)
10405 {
10406   if (t == NULL_TREE)
10407     return NULL_TREE;
10408
10409   switch (TREE_CODE (t))
10410     {
10411     case RECORD_TYPE:
10412       if (TYPE_PTRMEMFUNC_P (t))
10413         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
10414
10415       /* Else fall through.  */
10416     case ENUMERAL_TYPE:
10417     case UNION_TYPE:
10418       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
10419         {
10420           tree argvec;
10421           tree context;
10422           tree r;
10423           int saved_unevaluated_operand;
10424           int saved_inhibit_evaluation_warnings;
10425
10426           /* In "sizeof(X<I>)" we need to evaluate "I".  */
10427           saved_unevaluated_operand = cp_unevaluated_operand;
10428           cp_unevaluated_operand = 0;
10429           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
10430           c_inhibit_evaluation_warnings = 0;
10431
10432           /* First, determine the context for the type we are looking
10433              up.  */
10434           context = TYPE_CONTEXT (t);
10435           if (context && TYPE_P (context))
10436             {
10437               context = tsubst_aggr_type (context, args, complain,
10438                                           in_decl, /*entering_scope=*/1);
10439               /* If context is a nested class inside a class template,
10440                  it may still need to be instantiated (c++/33959).  */
10441               context = complete_type (context);
10442             }
10443
10444           /* Then, figure out what arguments are appropriate for the
10445              type we are trying to find.  For example, given:
10446
10447                template <class T> struct S;
10448                template <class T, class U> void f(T, U) { S<U> su; }
10449
10450              and supposing that we are instantiating f<int, double>,
10451              then our ARGS will be {int, double}, but, when looking up
10452              S we only want {double}.  */
10453           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
10454                                          complain, in_decl);
10455           if (argvec == error_mark_node)
10456             r = error_mark_node;
10457           else
10458             {
10459               r = lookup_template_class (t, argvec, in_decl, context,
10460                                          entering_scope, complain);
10461               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10462             }
10463
10464           cp_unevaluated_operand = saved_unevaluated_operand;
10465           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
10466
10467           return r;
10468         }
10469       else
10470         /* This is not a template type, so there's nothing to do.  */
10471         return t;
10472
10473     default:
10474       return tsubst (t, args, complain, in_decl);
10475     }
10476 }
10477
10478 /* Substitute into the default argument ARG (a default argument for
10479    FN), which has the indicated TYPE.  */
10480
10481 tree
10482 tsubst_default_argument (tree fn, tree type, tree arg, tsubst_flags_t complain)
10483 {
10484   tree saved_class_ptr = NULL_TREE;
10485   tree saved_class_ref = NULL_TREE;
10486   int errs = errorcount + sorrycount;
10487
10488   /* This can happen in invalid code.  */
10489   if (TREE_CODE (arg) == DEFAULT_ARG)
10490     return arg;
10491
10492   /* This default argument came from a template.  Instantiate the
10493      default argument here, not in tsubst.  In the case of
10494      something like:
10495
10496        template <class T>
10497        struct S {
10498          static T t();
10499          void f(T = t());
10500        };
10501
10502      we must be careful to do name lookup in the scope of S<T>,
10503      rather than in the current class.  */
10504   push_access_scope (fn);
10505   /* The "this" pointer is not valid in a default argument.  */
10506   if (cfun)
10507     {
10508       saved_class_ptr = current_class_ptr;
10509       cp_function_chain->x_current_class_ptr = NULL_TREE;
10510       saved_class_ref = current_class_ref;
10511       cp_function_chain->x_current_class_ref = NULL_TREE;
10512     }
10513
10514   push_deferring_access_checks(dk_no_deferred);
10515   /* The default argument expression may cause implicitly defined
10516      member functions to be synthesized, which will result in garbage
10517      collection.  We must treat this situation as if we were within
10518      the body of function so as to avoid collecting live data on the
10519      stack.  */
10520   ++function_depth;
10521   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
10522                      complain, NULL_TREE,
10523                      /*integral_constant_expression_p=*/false);
10524   --function_depth;
10525   pop_deferring_access_checks();
10526
10527   /* Restore the "this" pointer.  */
10528   if (cfun)
10529     {
10530       cp_function_chain->x_current_class_ptr = saved_class_ptr;
10531       cp_function_chain->x_current_class_ref = saved_class_ref;
10532     }
10533
10534   if (errorcount+sorrycount > errs
10535       && (complain & tf_warning_or_error))
10536     inform (input_location,
10537             "  when instantiating default argument for call to %D", fn);
10538
10539   /* Make sure the default argument is reasonable.  */
10540   arg = check_default_argument (type, arg, complain);
10541
10542   pop_access_scope (fn);
10543
10544   return arg;
10545 }
10546
10547 /* Substitute into all the default arguments for FN.  */
10548
10549 static void
10550 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
10551 {
10552   tree arg;
10553   tree tmpl_args;
10554
10555   tmpl_args = DECL_TI_ARGS (fn);
10556
10557   /* If this function is not yet instantiated, we certainly don't need
10558      its default arguments.  */
10559   if (uses_template_parms (tmpl_args))
10560     return;
10561   /* Don't do this again for clones.  */
10562   if (DECL_CLONED_FUNCTION_P (fn))
10563     return;
10564
10565   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
10566        arg;
10567        arg = TREE_CHAIN (arg))
10568     if (TREE_PURPOSE (arg))
10569       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
10570                                                     TREE_VALUE (arg),
10571                                                     TREE_PURPOSE (arg),
10572                                                     complain);
10573 }
10574
10575 /* Substitute the ARGS into the T, which is a _DECL.  Return the
10576    result of the substitution.  Issue error and warning messages under
10577    control of COMPLAIN.  */
10578
10579 static tree
10580 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
10581 {
10582 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
10583   location_t saved_loc;
10584   tree r = NULL_TREE;
10585   tree in_decl = t;
10586   hashval_t hash = 0;
10587
10588   /* Set the filename and linenumber to improve error-reporting.  */
10589   saved_loc = input_location;
10590   input_location = DECL_SOURCE_LOCATION (t);
10591
10592   switch (TREE_CODE (t))
10593     {
10594     case TEMPLATE_DECL:
10595       {
10596         /* We can get here when processing a member function template,
10597            member class template, or template template parameter.  */
10598         tree decl = DECL_TEMPLATE_RESULT (t);
10599         tree spec;
10600         tree tmpl_args;
10601         tree full_args;
10602
10603         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10604           {
10605             /* Template template parameter is treated here.  */
10606             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10607             if (new_type == error_mark_node)
10608               RETURN (error_mark_node);
10609             /* If we get a real template back, return it.  This can happen in
10610                the context of most_specialized_partial_spec.  */
10611             if (TREE_CODE (new_type) == TEMPLATE_DECL)
10612               return new_type;
10613
10614             r = copy_decl (t);
10615             DECL_CHAIN (r) = NULL_TREE;
10616             TREE_TYPE (r) = new_type;
10617             DECL_TEMPLATE_RESULT (r)
10618               = build_decl (DECL_SOURCE_LOCATION (decl),
10619                             TYPE_DECL, DECL_NAME (decl), new_type);
10620             DECL_TEMPLATE_PARMS (r)
10621               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
10622                                        complain);
10623             TYPE_NAME (new_type) = r;
10624             break;
10625           }
10626
10627         /* We might already have an instance of this template.
10628            The ARGS are for the surrounding class type, so the
10629            full args contain the tsubst'd args for the context,
10630            plus the innermost args from the template decl.  */
10631         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
10632           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
10633           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
10634         /* Because this is a template, the arguments will still be
10635            dependent, even after substitution.  If
10636            PROCESSING_TEMPLATE_DECL is not set, the dependency
10637            predicates will short-circuit.  */
10638         ++processing_template_decl;
10639         full_args = tsubst_template_args (tmpl_args, args,
10640                                           complain, in_decl);
10641         --processing_template_decl;
10642         if (full_args == error_mark_node)
10643           RETURN (error_mark_node);
10644
10645         /* If this is a default template template argument,
10646            tsubst might not have changed anything.  */
10647         if (full_args == tmpl_args)
10648           RETURN (t);
10649
10650         hash = hash_tmpl_and_args (t, full_args);
10651         spec = retrieve_specialization (t, full_args, hash);
10652         if (spec != NULL_TREE)
10653           {
10654             r = spec;
10655             break;
10656           }
10657
10658         /* Make a new template decl.  It will be similar to the
10659            original, but will record the current template arguments.
10660            We also create a new function declaration, which is just
10661            like the old one, but points to this new template, rather
10662            than the old one.  */
10663         r = copy_decl (t);
10664         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
10665         DECL_CHAIN (r) = NULL_TREE;
10666
10667         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10668
10669         if (TREE_CODE (decl) == TYPE_DECL
10670             && !TYPE_DECL_ALIAS_P (decl))
10671           {
10672             tree new_type;
10673             ++processing_template_decl;
10674             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10675             --processing_template_decl;
10676             if (new_type == error_mark_node)
10677               RETURN (error_mark_node);
10678
10679             TREE_TYPE (r) = new_type;
10680             /* For a partial specialization, we need to keep pointing to
10681                the primary template.  */
10682             if (!DECL_TEMPLATE_SPECIALIZATION (t))
10683               CLASSTYPE_TI_TEMPLATE (new_type) = r;
10684             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
10685             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
10686             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
10687           }
10688         else
10689           {
10690             tree new_decl;
10691             ++processing_template_decl;
10692             new_decl = tsubst (decl, args, complain, in_decl);
10693             --processing_template_decl;
10694             if (new_decl == error_mark_node)
10695               RETURN (error_mark_node);
10696
10697             DECL_TEMPLATE_RESULT (r) = new_decl;
10698             DECL_TI_TEMPLATE (new_decl) = r;
10699             TREE_TYPE (r) = TREE_TYPE (new_decl);
10700             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
10701             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
10702           }
10703
10704         SET_DECL_IMPLICIT_INSTANTIATION (r);
10705         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
10706         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
10707
10708         /* The template parameters for this new template are all the
10709            template parameters for the old template, except the
10710            outermost level of parameters.  */
10711         DECL_TEMPLATE_PARMS (r)
10712           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
10713                                    complain);
10714
10715         if (PRIMARY_TEMPLATE_P (t))
10716           DECL_PRIMARY_TEMPLATE (r) = r;
10717
10718         if (TREE_CODE (decl) != TYPE_DECL && TREE_CODE (decl) != VAR_DECL)
10719           /* Record this non-type partial instantiation.  */
10720           register_specialization (r, t,
10721                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
10722                                    false, hash);
10723       }
10724       break;
10725
10726     case FUNCTION_DECL:
10727       {
10728         tree ctx;
10729         tree argvec = NULL_TREE;
10730         tree *friends;
10731         tree gen_tmpl;
10732         tree type;
10733         int member;
10734         int args_depth;
10735         int parms_depth;
10736
10737         /* Nobody should be tsubst'ing into non-template functions.  */
10738         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
10739
10740         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
10741           {
10742             tree spec;
10743             bool dependent_p;
10744
10745             /* If T is not dependent, just return it.  We have to
10746                increment PROCESSING_TEMPLATE_DECL because
10747                value_dependent_expression_p assumes that nothing is
10748                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
10749             ++processing_template_decl;
10750             dependent_p = value_dependent_expression_p (t);
10751             --processing_template_decl;
10752             if (!dependent_p)
10753               RETURN (t);
10754
10755             /* Calculate the most general template of which R is a
10756                specialization, and the complete set of arguments used to
10757                specialize R.  */
10758             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
10759             argvec = tsubst_template_args (DECL_TI_ARGS
10760                                           (DECL_TEMPLATE_RESULT
10761                                                  (DECL_TI_TEMPLATE (t))),
10762                                            args, complain, in_decl);
10763             if (argvec == error_mark_node)
10764               RETURN (error_mark_node);
10765
10766             /* Check to see if we already have this specialization.  */
10767             hash = hash_tmpl_and_args (gen_tmpl, argvec);
10768             spec = retrieve_specialization (gen_tmpl, argvec, hash);
10769
10770             if (spec)
10771               {
10772                 r = spec;
10773                 break;
10774               }
10775
10776             /* We can see more levels of arguments than parameters if
10777                there was a specialization of a member template, like
10778                this:
10779
10780                  template <class T> struct S { template <class U> void f(); }
10781                  template <> template <class U> void S<int>::f(U);
10782
10783                Here, we'll be substituting into the specialization,
10784                because that's where we can find the code we actually
10785                want to generate, but we'll have enough arguments for
10786                the most general template.
10787
10788                We also deal with the peculiar case:
10789
10790                  template <class T> struct S {
10791                    template <class U> friend void f();
10792                  };
10793                  template <class U> void f() {}
10794                  template S<int>;
10795                  template void f<double>();
10796
10797                Here, the ARGS for the instantiation of will be {int,
10798                double}.  But, we only need as many ARGS as there are
10799                levels of template parameters in CODE_PATTERN.  We are
10800                careful not to get fooled into reducing the ARGS in
10801                situations like:
10802
10803                  template <class T> struct S { template <class U> void f(U); }
10804                  template <class T> template <> void S<T>::f(int) {}
10805
10806                which we can spot because the pattern will be a
10807                specialization in this case.  */
10808             args_depth = TMPL_ARGS_DEPTH (args);
10809             parms_depth =
10810               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
10811             if (args_depth > parms_depth
10812                 && !DECL_TEMPLATE_SPECIALIZATION (t))
10813               args = get_innermost_template_args (args, parms_depth);
10814           }
10815         else
10816           {
10817             /* This special case arises when we have something like this:
10818
10819                  template <class T> struct S {
10820                    friend void f<int>(int, double);
10821                  };
10822
10823                Here, the DECL_TI_TEMPLATE for the friend declaration
10824                will be an IDENTIFIER_NODE.  We are being called from
10825                tsubst_friend_function, and we want only to create a
10826                new decl (R) with appropriate types so that we can call
10827                determine_specialization.  */
10828             gen_tmpl = NULL_TREE;
10829           }
10830
10831         if (DECL_CLASS_SCOPE_P (t))
10832           {
10833             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
10834               member = 2;
10835             else
10836               member = 1;
10837             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
10838                                     complain, t, /*entering_scope=*/1);
10839           }
10840         else
10841           {
10842             member = 0;
10843             ctx = DECL_CONTEXT (t);
10844           }
10845         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10846         if (type == error_mark_node)
10847           RETURN (error_mark_node);
10848
10849         /* If we hit excessive deduction depth, the type is bogus even if
10850            it isn't error_mark_node, so don't build a decl.  */
10851         if (excessive_deduction_depth)
10852           RETURN (error_mark_node);
10853
10854         /* We do NOT check for matching decls pushed separately at this
10855            point, as they may not represent instantiations of this
10856            template, and in any case are considered separate under the
10857            discrete model.  */
10858         r = copy_decl (t);
10859         DECL_USE_TEMPLATE (r) = 0;
10860         TREE_TYPE (r) = type;
10861         /* Clear out the mangled name and RTL for the instantiation.  */
10862         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10863         SET_DECL_RTL (r, NULL);
10864         /* Leave DECL_INITIAL set on deleted instantiations.  */
10865         if (!DECL_DELETED_FN (r))
10866           DECL_INITIAL (r) = NULL_TREE;
10867         DECL_CONTEXT (r) = ctx;
10868
10869         /* OpenMP UDRs have the only argument a reference to the declared
10870            type.  We want to diagnose if the declared type is a reference,
10871            which is invalid, but as references to references are usually
10872            quietly merged, diagnose it here.  */
10873         if (DECL_OMP_DECLARE_REDUCTION_P (t))
10874           {
10875             tree argtype
10876               = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
10877             argtype = tsubst (argtype, args, complain, in_decl);
10878             if (TREE_CODE (argtype) == REFERENCE_TYPE)
10879               error_at (DECL_SOURCE_LOCATION (t),
10880                         "reference type %qT in "
10881                         "%<#pragma omp declare reduction%>", argtype);
10882             if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
10883               DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
10884                                                 argtype);
10885           }
10886
10887         if (member && DECL_CONV_FN_P (r))
10888           /* Type-conversion operator.  Reconstruct the name, in
10889              case it's the name of one of the template's parameters.  */
10890           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10891
10892         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10893                                      complain, t);
10894         DECL_RESULT (r) = NULL_TREE;
10895
10896         TREE_STATIC (r) = 0;
10897         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10898         DECL_EXTERNAL (r) = 1;
10899         /* If this is an instantiation of a function with internal
10900            linkage, we already know what object file linkage will be
10901            assigned to the instantiation.  */
10902         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10903         DECL_DEFER_OUTPUT (r) = 0;
10904         DECL_CHAIN (r) = NULL_TREE;
10905         DECL_PENDING_INLINE_INFO (r) = 0;
10906         DECL_PENDING_INLINE_P (r) = 0;
10907         DECL_SAVED_TREE (r) = NULL_TREE;
10908         DECL_STRUCT_FUNCTION (r) = NULL;
10909         TREE_USED (r) = 0;
10910         /* We'll re-clone as appropriate in instantiate_template.  */
10911         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10912
10913         /* If we aren't complaining now, return on error before we register
10914            the specialization so that we'll complain eventually.  */
10915         if ((complain & tf_error) == 0
10916             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10917             && !grok_op_properties (r, /*complain=*/false))
10918           RETURN (error_mark_node);
10919
10920         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10921            this in the special friend case mentioned above where
10922            GEN_TMPL is NULL.  */
10923         if (gen_tmpl)
10924           {
10925             DECL_TEMPLATE_INFO (r)
10926               = build_template_info (gen_tmpl, argvec);
10927             SET_DECL_IMPLICIT_INSTANTIATION (r);
10928
10929             tree new_r
10930               = register_specialization (r, gen_tmpl, argvec, false, hash);
10931             if (new_r != r)
10932               /* We instantiated this while substituting into
10933                  the type earlier (template/friend54.C).  */
10934               RETURN (new_r);
10935
10936             /* We're not supposed to instantiate default arguments
10937                until they are called, for a template.  But, for a
10938                declaration like:
10939
10940                  template <class T> void f ()
10941                  { extern void g(int i = T()); }
10942
10943                we should do the substitution when the template is
10944                instantiated.  We handle the member function case in
10945                instantiate_class_template since the default arguments
10946                might refer to other members of the class.  */
10947             if (!member
10948                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10949                 && !uses_template_parms (argvec))
10950               tsubst_default_arguments (r, complain);
10951           }
10952         else
10953           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10954
10955         /* Copy the list of befriending classes.  */
10956         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10957              *friends;
10958              friends = &TREE_CHAIN (*friends))
10959           {
10960             *friends = copy_node (*friends);
10961             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10962                                             args, complain,
10963                                             in_decl);
10964           }
10965
10966         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10967           {
10968             maybe_retrofit_in_chrg (r);
10969             if (DECL_CONSTRUCTOR_P (r))
10970               grok_ctor_properties (ctx, r);
10971             if (DECL_INHERITED_CTOR_BASE (r))
10972               deduce_inheriting_ctor (r);
10973             /* If this is an instantiation of a member template, clone it.
10974                If it isn't, that'll be handled by
10975                clone_constructors_and_destructors.  */
10976             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10977               clone_function_decl (r, /*update_method_vec_p=*/0);
10978           }
10979         else if ((complain & tf_error) != 0
10980                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10981                  && !grok_op_properties (r, /*complain=*/true))
10982           RETURN (error_mark_node);
10983
10984         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10985           SET_DECL_FRIEND_CONTEXT (r,
10986                                    tsubst (DECL_FRIEND_CONTEXT (t),
10987                                             args, complain, in_decl));
10988
10989         /* Possibly limit visibility based on template args.  */
10990         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10991         if (DECL_VISIBILITY_SPECIFIED (t))
10992           {
10993             DECL_VISIBILITY_SPECIFIED (r) = 0;
10994             DECL_ATTRIBUTES (r)
10995               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10996           }
10997         determine_visibility (r);
10998         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10999             && !processing_template_decl)
11000           defaulted_late_check (r);
11001
11002         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
11003                                         args, complain, in_decl);
11004       }
11005       break;
11006
11007     case PARM_DECL:
11008       {
11009         tree type = NULL_TREE;
11010         int i, len = 1;
11011         tree expanded_types = NULL_TREE;
11012         tree prev_r = NULL_TREE;
11013         tree first_r = NULL_TREE;
11014
11015         if (DECL_PACK_P (t))
11016           {
11017             /* If there is a local specialization that isn't a
11018                parameter pack, it means that we're doing a "simple"
11019                substitution from inside tsubst_pack_expansion. Just
11020                return the local specialization (which will be a single
11021                parm).  */
11022             tree spec = retrieve_local_specialization (t);
11023             if (spec 
11024                 && TREE_CODE (spec) == PARM_DECL
11025                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
11026               RETURN (spec);
11027
11028             /* Expand the TYPE_PACK_EXPANSION that provides the types for
11029                the parameters in this function parameter pack.  */
11030             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
11031                                                     complain, in_decl);
11032             if (TREE_CODE (expanded_types) == TREE_VEC)
11033               {
11034                 len = TREE_VEC_LENGTH (expanded_types);
11035
11036                 /* Zero-length parameter packs are boring. Just substitute
11037                    into the chain.  */
11038                 if (len == 0)
11039                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
11040                                   TREE_CHAIN (t)));
11041               }
11042             else
11043               {
11044                 /* All we did was update the type. Make a note of that.  */
11045                 type = expanded_types;
11046                 expanded_types = NULL_TREE;
11047               }
11048           }
11049
11050         /* Loop through all of the parameters we'll build. When T is
11051            a function parameter pack, LEN is the number of expanded
11052            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
11053         r = NULL_TREE;
11054         for (i = 0; i < len; ++i)
11055           {
11056             prev_r = r;
11057             r = copy_node (t);
11058             if (DECL_TEMPLATE_PARM_P (t))
11059               SET_DECL_TEMPLATE_PARM_P (r);
11060
11061             if (expanded_types)
11062               /* We're on the Ith parameter of the function parameter
11063                  pack.  */
11064               {
11065                 /* Get the Ith type.  */
11066                 type = TREE_VEC_ELT (expanded_types, i);
11067
11068                 /* Rename the parameter to include the index.  */
11069                 DECL_NAME (r)
11070                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
11071               }
11072             else if (!type)
11073               /* We're dealing with a normal parameter.  */
11074               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11075
11076             type = type_decays_to (type);
11077             TREE_TYPE (r) = type;
11078             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
11079
11080             if (DECL_INITIAL (r))
11081               {
11082                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
11083                   DECL_INITIAL (r) = TREE_TYPE (r);
11084                 else
11085                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
11086                                              complain, in_decl);
11087               }
11088
11089             DECL_CONTEXT (r) = NULL_TREE;
11090
11091             if (!DECL_TEMPLATE_PARM_P (r))
11092               DECL_ARG_TYPE (r) = type_passed_as (type);
11093
11094             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
11095                                             args, complain, in_decl);
11096
11097             /* Keep track of the first new parameter we
11098                generate. That's what will be returned to the
11099                caller.  */
11100             if (!first_r)
11101               first_r = r;
11102
11103             /* Build a proper chain of parameters when substituting
11104                into a function parameter pack.  */
11105             if (prev_r)
11106               DECL_CHAIN (prev_r) = r;
11107           }
11108
11109         /* If cp_unevaluated_operand is set, we're just looking for a
11110            single dummy parameter, so don't keep going.  */
11111         if (DECL_CHAIN (t) && !cp_unevaluated_operand)
11112           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
11113                                    complain, DECL_CHAIN (t));
11114
11115         /* FIRST_R contains the start of the chain we've built.  */
11116         r = first_r;
11117       }
11118       break;
11119
11120     case FIELD_DECL:
11121       {
11122         tree type = NULL_TREE;
11123         tree vec = NULL_TREE;
11124         tree expanded_types = NULL_TREE;
11125         int len = 1;
11126
11127         if (PACK_EXPANSION_P (TREE_TYPE (t)))
11128           {
11129             /* This field is a lambda capture pack.  Return a TREE_VEC of
11130                the expanded fields to instantiate_class_template_1 and
11131                store them in the specializations hash table as a
11132                NONTYPE_ARGUMENT_PACK so that tsubst_copy can find them.  */
11133             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
11134                                                     complain, in_decl);
11135             if (TREE_CODE (expanded_types) == TREE_VEC)
11136               {
11137                 len = TREE_VEC_LENGTH (expanded_types);
11138                 vec = make_tree_vec (len);
11139               }
11140             else
11141               {
11142                 /* All we did was update the type. Make a note of that.  */
11143                 type = expanded_types;
11144                 expanded_types = NULL_TREE;
11145               }
11146           }
11147
11148         for (int i = 0; i < len; ++i)
11149           {
11150             r = copy_decl (t);
11151             if (expanded_types)
11152               {
11153                 type = TREE_VEC_ELT (expanded_types, i);
11154                 DECL_NAME (r)
11155                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
11156               }
11157             else if (!type)
11158               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11159
11160             if (type == error_mark_node)
11161               RETURN (error_mark_node);
11162             TREE_TYPE (r) = type;
11163             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
11164
11165             if (DECL_C_BIT_FIELD (r))
11166               /* For bit-fields, DECL_INITIAL gives the number of bits.  For
11167                  non-bit-fields DECL_INITIAL is a non-static data member
11168                  initializer, which gets deferred instantiation.  */
11169               DECL_INITIAL (r)
11170                 = tsubst_expr (DECL_INITIAL (t), args,
11171                                complain, in_decl,
11172                                /*integral_constant_expression_p=*/true);
11173             else if (DECL_INITIAL (t))
11174               {
11175                 /* Set up DECL_TEMPLATE_INFO so that we can get at the
11176                    NSDMI in perform_member_init.  Still set DECL_INITIAL
11177                    so that we know there is one.  */
11178                 DECL_INITIAL (r) = void_node;
11179                 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
11180                 retrofit_lang_decl (r);
11181                 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
11182               }
11183             /* We don't have to set DECL_CONTEXT here; it is set by
11184                finish_member_declaration.  */
11185             DECL_CHAIN (r) = NULL_TREE;
11186
11187             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
11188                                             args, complain, in_decl);
11189
11190             if (vec)
11191               TREE_VEC_ELT (vec, i) = r;
11192           }
11193
11194         if (vec)
11195           {
11196             r = vec;
11197             tree pack = make_node (NONTYPE_ARGUMENT_PACK);
11198             tree tpack = cxx_make_type (TYPE_ARGUMENT_PACK);
11199             SET_ARGUMENT_PACK_ARGS (pack, vec);
11200             SET_ARGUMENT_PACK_ARGS (tpack, expanded_types);
11201             TREE_TYPE (pack) = tpack;
11202             register_specialization (pack, t, args, false, 0);
11203           }
11204       }
11205       break;
11206
11207     case USING_DECL:
11208       /* We reach here only for member using decls.  We also need to check
11209          uses_template_parms because DECL_DEPENDENT_P is not set for a
11210          using-declaration that designates a member of the current
11211          instantiation (c++/53549).  */
11212       if (DECL_DEPENDENT_P (t)
11213           || uses_template_parms (USING_DECL_SCOPE (t)))
11214         {
11215           tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
11216                                          complain, in_decl);
11217           tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
11218           r = do_class_using_decl (inst_scope, name);
11219           if (!r)
11220             r = error_mark_node;
11221           else
11222             {
11223               TREE_PROTECTED (r) = TREE_PROTECTED (t);
11224               TREE_PRIVATE (r) = TREE_PRIVATE (t);
11225             }
11226         }
11227       else
11228         {
11229           r = copy_node (t);
11230           DECL_CHAIN (r) = NULL_TREE;
11231         }
11232       break;
11233
11234     case TYPE_DECL:
11235     case VAR_DECL:
11236       {
11237         tree argvec = NULL_TREE;
11238         tree gen_tmpl = NULL_TREE;
11239         tree spec;
11240         tree tmpl = NULL_TREE;
11241         tree ctx;
11242         tree type = NULL_TREE;
11243         bool local_p;
11244
11245         if (TREE_TYPE (t) == error_mark_node)
11246           RETURN (error_mark_node);
11247
11248         if (TREE_CODE (t) == TYPE_DECL
11249             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
11250           {
11251             /* If this is the canonical decl, we don't have to
11252                mess with instantiations, and often we can't (for
11253                typename, template type parms and such).  Note that
11254                TYPE_NAME is not correct for the above test if
11255                we've copied the type for a typedef.  */
11256             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11257             if (type == error_mark_node)
11258               RETURN (error_mark_node);
11259             r = TYPE_NAME (type);
11260             break;
11261           }
11262
11263         /* Check to see if we already have the specialization we
11264            need.  */
11265         spec = NULL_TREE;
11266         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
11267           {
11268             /* T is a static data member or namespace-scope entity.
11269                We have to substitute into namespace-scope variables
11270                (even though such entities are never templates) because
11271                of cases like:
11272                
11273                  template <class T> void f() { extern T t; }
11274
11275                where the entity referenced is not known until
11276                instantiation time.  */
11277             local_p = false;
11278             ctx = DECL_CONTEXT (t);
11279             if (DECL_CLASS_SCOPE_P (t))
11280               {
11281                 ctx = tsubst_aggr_type (ctx, args,
11282                                         complain,
11283                                         in_decl, /*entering_scope=*/1);
11284                 /* If CTX is unchanged, then T is in fact the
11285                    specialization we want.  That situation occurs when
11286                    referencing a static data member within in its own
11287                    class.  We can use pointer equality, rather than
11288                    same_type_p, because DECL_CONTEXT is always
11289                    canonical...  */
11290                 if (ctx == DECL_CONTEXT (t)
11291                     /* ... unless T is a member template; in which
11292                        case our caller can be willing to create a
11293                        specialization of that template represented
11294                        by T.  */
11295                     && !(DECL_TI_TEMPLATE (t)
11296                          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
11297                   spec = t;
11298               }
11299
11300             if (!spec)
11301               {
11302                 tmpl = DECL_TI_TEMPLATE (t);
11303                 gen_tmpl = most_general_template (tmpl);
11304                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
11305                 if (argvec == error_mark_node)
11306                   RETURN (error_mark_node);
11307                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
11308                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
11309               }
11310           }
11311         else
11312           {
11313             /* A local variable.  */
11314             local_p = true;
11315             /* Subsequent calls to pushdecl will fill this in.  */
11316             ctx = NULL_TREE;
11317             spec = retrieve_local_specialization (t);
11318           }
11319         /* If we already have the specialization we need, there is
11320            nothing more to do.  */ 
11321         if (spec)
11322           {
11323             r = spec;
11324             break;
11325           }
11326
11327         /* Create a new node for the specialization we need.  */
11328         r = copy_decl (t);
11329         if (type == NULL_TREE)
11330           {
11331             if (is_typedef_decl (t))
11332               type = DECL_ORIGINAL_TYPE (t);
11333             else
11334               type = TREE_TYPE (t);
11335             if (VAR_P (t)
11336                 && VAR_HAD_UNKNOWN_BOUND (t)
11337                 && type != error_mark_node)
11338               type = strip_array_domain (type);
11339             type = tsubst (type, args, complain, in_decl);
11340           }
11341         if (VAR_P (r))
11342           {
11343             /* Even if the original location is out of scope, the
11344                newly substituted one is not.  */
11345             DECL_DEAD_FOR_LOCAL (r) = 0;
11346             DECL_INITIALIZED_P (r) = 0;
11347             DECL_TEMPLATE_INSTANTIATED (r) = 0;
11348             if (type == error_mark_node)
11349               RETURN (error_mark_node);
11350             if (TREE_CODE (type) == FUNCTION_TYPE)
11351               {
11352                 /* It may seem that this case cannot occur, since:
11353
11354                    typedef void f();
11355                    void g() { f x; }
11356
11357                    declares a function, not a variable.  However:
11358       
11359                    typedef void f();
11360                    template <typename T> void g() { T t; }
11361                    template void g<f>();
11362
11363                    is an attempt to declare a variable with function
11364                    type.  */
11365                 error ("variable %qD has function type",
11366                        /* R is not yet sufficiently initialized, so we
11367                           just use its name.  */
11368                        DECL_NAME (r));
11369                 RETURN (error_mark_node);
11370               }
11371             type = complete_type (type);
11372             /* Wait until cp_finish_decl to set this again, to handle
11373                circular dependency (template/instantiate6.C). */
11374             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
11375             type = check_var_type (DECL_NAME (r), type);
11376
11377             if (DECL_HAS_VALUE_EXPR_P (t))
11378               {
11379                 tree ve = DECL_VALUE_EXPR (t);
11380                 ve = tsubst_expr (ve, args, complain, in_decl,
11381                                   /*constant_expression_p=*/false);
11382                 if (REFERENCE_REF_P (ve))
11383                   {
11384                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
11385                     ve = TREE_OPERAND (ve, 0);
11386                   }
11387                 SET_DECL_VALUE_EXPR (r, ve);
11388               }
11389             if (TREE_STATIC (r) || DECL_EXTERNAL (r))
11390               set_decl_tls_model (r, decl_tls_model (t));
11391           }
11392         else if (DECL_SELF_REFERENCE_P (t))
11393           SET_DECL_SELF_REFERENCE_P (r);
11394         TREE_TYPE (r) = type;
11395         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
11396         DECL_CONTEXT (r) = ctx;
11397         /* Clear out the mangled name and RTL for the instantiation.  */
11398         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
11399         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
11400           SET_DECL_RTL (r, NULL);
11401         /* The initializer must not be expanded until it is required;
11402            see [temp.inst].  */
11403         DECL_INITIAL (r) = NULL_TREE;
11404         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
11405           SET_DECL_RTL (r, NULL);
11406         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
11407         if (VAR_P (r))
11408           {
11409             /* Possibly limit visibility based on template args.  */
11410             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
11411             if (DECL_VISIBILITY_SPECIFIED (t))
11412               {
11413                 DECL_VISIBILITY_SPECIFIED (r) = 0;
11414                 DECL_ATTRIBUTES (r)
11415                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
11416               }
11417             determine_visibility (r);
11418           }
11419
11420         if (!local_p)
11421           {
11422             /* A static data member declaration is always marked
11423                external when it is declared in-class, even if an
11424                initializer is present.  We mimic the non-template
11425                processing here.  */
11426             DECL_EXTERNAL (r) = 1;
11427
11428             register_specialization (r, gen_tmpl, argvec, false, hash);
11429             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
11430             SET_DECL_IMPLICIT_INSTANTIATION (r);
11431           }
11432         else if (!cp_unevaluated_operand)
11433           register_local_specialization (r, t);
11434
11435         DECL_CHAIN (r) = NULL_TREE;
11436
11437         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
11438                                         /*flags=*/0,
11439                                         args, complain, in_decl);
11440
11441         /* Preserve a typedef that names a type.  */
11442         if (is_typedef_decl (r))
11443           {
11444             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
11445             set_underlying_type (r);
11446           }
11447
11448         layout_decl (r, 0);
11449       }
11450       break;
11451
11452     default:
11453       gcc_unreachable ();
11454     }
11455 #undef RETURN
11456
11457  out:
11458   /* Restore the file and line information.  */
11459   input_location = saved_loc;
11460
11461   return r;
11462 }
11463
11464 /* Substitute into the ARG_TYPES of a function type.
11465    If END is a TREE_CHAIN, leave it and any following types
11466    un-substituted.  */
11467
11468 static tree
11469 tsubst_arg_types (tree arg_types,
11470                   tree args,
11471                   tree end,
11472                   tsubst_flags_t complain,
11473                   tree in_decl)
11474 {
11475   tree remaining_arg_types;
11476   tree type = NULL_TREE;
11477   int i = 1;
11478   tree expanded_args = NULL_TREE;
11479   tree default_arg;
11480
11481   if (!arg_types || arg_types == void_list_node || arg_types == end)
11482     return arg_types;
11483
11484   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
11485                                           args, end, complain, in_decl);
11486   if (remaining_arg_types == error_mark_node)
11487     return error_mark_node;
11488
11489   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
11490     {
11491       /* For a pack expansion, perform substitution on the
11492          entire expression. Later on, we'll handle the arguments
11493          one-by-one.  */
11494       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
11495                                             args, complain, in_decl);
11496
11497       if (TREE_CODE (expanded_args) == TREE_VEC)
11498         /* So that we'll spin through the parameters, one by one.  */
11499         i = TREE_VEC_LENGTH (expanded_args);
11500       else
11501         {
11502           /* We only partially substituted into the parameter
11503              pack. Our type is TYPE_PACK_EXPANSION.  */
11504           type = expanded_args;
11505           expanded_args = NULL_TREE;
11506         }
11507     }
11508
11509   while (i > 0) {
11510     --i;
11511     
11512     if (expanded_args)
11513       type = TREE_VEC_ELT (expanded_args, i);
11514     else if (!type)
11515       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
11516
11517     if (type == error_mark_node)
11518       return error_mark_node;
11519     if (VOID_TYPE_P (type))
11520       {
11521         if (complain & tf_error)
11522           {
11523             error ("invalid parameter type %qT", type);
11524             if (in_decl)
11525               error ("in declaration %q+D", in_decl);
11526           }
11527         return error_mark_node;
11528     }
11529     /* DR 657. */
11530     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
11531       return error_mark_node;
11532     
11533     /* Do array-to-pointer, function-to-pointer conversion, and ignore
11534        top-level qualifiers as required.  */
11535     type = cv_unqualified (type_decays_to (type));
11536
11537     /* We do not substitute into default arguments here.  The standard
11538        mandates that they be instantiated only when needed, which is
11539        done in build_over_call.  */
11540     default_arg = TREE_PURPOSE (arg_types);
11541
11542     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
11543       {
11544         /* We've instantiated a template before its default arguments
11545            have been parsed.  This can happen for a nested template
11546            class, and is not an error unless we require the default
11547            argument in a call of this function.  */
11548         remaining_arg_types = 
11549           tree_cons (default_arg, type, remaining_arg_types);
11550         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
11551       }
11552     else
11553       remaining_arg_types = 
11554         hash_tree_cons (default_arg, type, remaining_arg_types);
11555   }
11556         
11557   return remaining_arg_types;
11558 }
11559
11560 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
11561    *not* handle the exception-specification for FNTYPE, because the
11562    initial substitution of explicitly provided template parameters
11563    during argument deduction forbids substitution into the
11564    exception-specification:
11565
11566      [temp.deduct]
11567
11568      All references in the function type of the function template to  the
11569      corresponding template parameters are replaced by the specified tem-
11570      plate argument values.  If a substitution in a template parameter or
11571      in  the function type of the function template results in an invalid
11572      type, type deduction fails.  [Note: The equivalent  substitution  in
11573      exception specifications is done only when the function is instanti-
11574      ated, at which point a program is  ill-formed  if  the  substitution
11575      results in an invalid type.]  */
11576
11577 static tree
11578 tsubst_function_type (tree t,
11579                       tree args,
11580                       tsubst_flags_t complain,
11581                       tree in_decl)
11582 {
11583   tree return_type;
11584   tree arg_types = NULL_TREE;
11585   tree fntype;
11586
11587   /* The TYPE_CONTEXT is not used for function/method types.  */
11588   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
11589
11590   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
11591      failure.  */
11592   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
11593
11594   if (late_return_type_p)
11595     {
11596       /* Substitute the argument types.  */
11597       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
11598                                     complain, in_decl);
11599       if (arg_types == error_mark_node)
11600         return error_mark_node;
11601
11602       tree save_ccp = current_class_ptr;
11603       tree save_ccr = current_class_ref;
11604       tree this_type = (TREE_CODE (t) == METHOD_TYPE
11605                         ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
11606       bool do_inject = this_type && CLASS_TYPE_P (this_type);
11607       if (do_inject)
11608         {
11609           /* DR 1207: 'this' is in scope in the trailing return type.  */
11610           inject_this_parameter (this_type, cp_type_quals (this_type));
11611         }
11612
11613       /* Substitute the return type.  */
11614       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11615
11616       if (do_inject)
11617         {
11618           current_class_ptr = save_ccp;
11619           current_class_ref = save_ccr;
11620         }
11621     }
11622   else
11623     /* Substitute the return type.  */
11624     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11625
11626   if (return_type == error_mark_node)
11627     return error_mark_node;
11628   /* DR 486 clarifies that creation of a function type with an
11629      invalid return type is a deduction failure.  */
11630   if (TREE_CODE (return_type) == ARRAY_TYPE
11631       || TREE_CODE (return_type) == FUNCTION_TYPE)
11632     {
11633       if (complain & tf_error)
11634         {
11635           if (TREE_CODE (return_type) == ARRAY_TYPE)
11636             error ("function returning an array");
11637           else
11638             error ("function returning a function");
11639         }
11640       return error_mark_node;
11641     }
11642   /* And DR 657. */
11643   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
11644     return error_mark_node;
11645
11646   if (!late_return_type_p)
11647     {
11648       /* Substitute the argument types.  */
11649       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
11650                                     complain, in_decl);
11651       if (arg_types == error_mark_node)
11652         return error_mark_node;
11653     }
11654
11655   /* Construct a new type node and return it.  */
11656   if (TREE_CODE (t) == FUNCTION_TYPE)
11657     {
11658       fntype = build_function_type (return_type, arg_types);
11659       fntype = apply_memfn_quals (fntype,
11660                                   type_memfn_quals (t),
11661                                   type_memfn_rqual (t));
11662     }
11663   else
11664     {
11665       tree r = TREE_TYPE (TREE_VALUE (arg_types));
11666       /* Don't pick up extra function qualifiers from the basetype.  */
11667       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
11668       if (! MAYBE_CLASS_TYPE_P (r))
11669         {
11670           /* [temp.deduct]
11671
11672              Type deduction may fail for any of the following
11673              reasons:
11674
11675              -- Attempting to create "pointer to member of T" when T
11676              is not a class type.  */
11677           if (complain & tf_error)
11678             error ("creating pointer to member function of non-class type %qT",
11679                       r);
11680           return error_mark_node;
11681         }
11682
11683       fntype = build_method_type_directly (r, return_type,
11684                                            TREE_CHAIN (arg_types));
11685       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
11686     }
11687   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
11688
11689   if (late_return_type_p)
11690     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
11691
11692   return fntype;
11693 }
11694
11695 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
11696    ARGS into that specification, and return the substituted
11697    specification.  If there is no specification, return NULL_TREE.  */
11698
11699 static tree
11700 tsubst_exception_specification (tree fntype,
11701                                 tree args,
11702                                 tsubst_flags_t complain,
11703                                 tree in_decl,
11704                                 bool defer_ok)
11705 {
11706   tree specs;
11707   tree new_specs;
11708
11709   specs = TYPE_RAISES_EXCEPTIONS (fntype);
11710   new_specs = NULL_TREE;
11711   if (specs && TREE_PURPOSE (specs))
11712     {
11713       /* A noexcept-specifier.  */
11714       tree expr = TREE_PURPOSE (specs);
11715       if (TREE_CODE (expr) == INTEGER_CST)
11716         new_specs = expr;
11717       else if (defer_ok)
11718         {
11719           /* Defer instantiation of noexcept-specifiers to avoid
11720              excessive instantiations (c++/49107).  */
11721           new_specs = make_node (DEFERRED_NOEXCEPT);
11722           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
11723             {
11724               /* We already partially instantiated this member template,
11725                  so combine the new args with the old.  */
11726               DEFERRED_NOEXCEPT_PATTERN (new_specs)
11727                 = DEFERRED_NOEXCEPT_PATTERN (expr);
11728               DEFERRED_NOEXCEPT_ARGS (new_specs)
11729                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
11730             }
11731           else
11732             {
11733               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
11734               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
11735             }
11736         }
11737       else
11738         new_specs = tsubst_copy_and_build
11739           (expr, args, complain, in_decl, /*function_p=*/false,
11740            /*integral_constant_expression_p=*/true);
11741       new_specs = build_noexcept_spec (new_specs, complain);
11742     }
11743   else if (specs)
11744     {
11745       if (! TREE_VALUE (specs))
11746         new_specs = specs;
11747       else
11748         while (specs)
11749           {
11750             tree spec;
11751             int i, len = 1;
11752             tree expanded_specs = NULL_TREE;
11753
11754             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
11755               {
11756                 /* Expand the pack expansion type.  */
11757                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
11758                                                        args, complain,
11759                                                        in_decl);
11760
11761                 if (expanded_specs == error_mark_node)
11762                   return error_mark_node;
11763                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
11764                   len = TREE_VEC_LENGTH (expanded_specs);
11765                 else
11766                   {
11767                     /* We're substituting into a member template, so
11768                        we got a TYPE_PACK_EXPANSION back.  Add that
11769                        expansion and move on.  */
11770                     gcc_assert (TREE_CODE (expanded_specs) 
11771                                 == TYPE_PACK_EXPANSION);
11772                     new_specs = add_exception_specifier (new_specs,
11773                                                          expanded_specs,
11774                                                          complain);
11775                     specs = TREE_CHAIN (specs);
11776                     continue;
11777                   }
11778               }
11779
11780             for (i = 0; i < len; ++i)
11781               {
11782                 if (expanded_specs)
11783                   spec = TREE_VEC_ELT (expanded_specs, i);
11784                 else
11785                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
11786                 if (spec == error_mark_node)
11787                   return spec;
11788                 new_specs = add_exception_specifier (new_specs, spec, 
11789                                                      complain);
11790               }
11791
11792             specs = TREE_CHAIN (specs);
11793           }
11794     }
11795   return new_specs;
11796 }
11797
11798 /* Take the tree structure T and replace template parameters used
11799    therein with the argument vector ARGS.  IN_DECL is an associated
11800    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
11801    Issue error and warning messages under control of COMPLAIN.  Note
11802    that we must be relatively non-tolerant of extensions here, in
11803    order to preserve conformance; if we allow substitutions that
11804    should not be allowed, we may allow argument deductions that should
11805    not succeed, and therefore report ambiguous overload situations
11806    where there are none.  In theory, we could allow the substitution,
11807    but indicate that it should have failed, and allow our caller to
11808    make sure that the right thing happens, but we don't try to do this
11809    yet.
11810
11811    This function is used for dealing with types, decls and the like;
11812    for expressions, use tsubst_expr or tsubst_copy.  */
11813
11814 tree
11815 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11816 {
11817   enum tree_code code;
11818   tree type, r = NULL_TREE;
11819
11820   if (t == NULL_TREE || t == error_mark_node
11821       || t == integer_type_node
11822       || t == void_type_node
11823       || t == char_type_node
11824       || t == unknown_type_node
11825       || TREE_CODE (t) == NAMESPACE_DECL
11826       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
11827     return t;
11828
11829   if (DECL_P (t))
11830     return tsubst_decl (t, args, complain);
11831
11832   if (args == NULL_TREE)
11833     return t;
11834
11835   code = TREE_CODE (t);
11836
11837   if (code == IDENTIFIER_NODE)
11838     type = IDENTIFIER_TYPE_VALUE (t);
11839   else
11840     type = TREE_TYPE (t);
11841
11842   gcc_assert (type != unknown_type_node);
11843
11844   /* Reuse typedefs.  We need to do this to handle dependent attributes,
11845      such as attribute aligned.  */
11846   if (TYPE_P (t)
11847       && typedef_variant_p (t))
11848     {
11849       tree decl = TYPE_NAME (t);
11850
11851       if (alias_template_specialization_p (t))
11852         {
11853           /* DECL represents an alias template and we want to
11854              instantiate it.  */
11855           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11856           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
11857           r = instantiate_alias_template (tmpl, gen_args, complain);
11858         }
11859       else if (DECL_CLASS_SCOPE_P (decl)
11860                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
11861                && uses_template_parms (DECL_CONTEXT (decl)))
11862         {
11863           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11864           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
11865           r = retrieve_specialization (tmpl, gen_args, 0);
11866         }
11867       else if (DECL_FUNCTION_SCOPE_P (decl)
11868                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
11869                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
11870         r = retrieve_local_specialization (decl);
11871       else
11872         /* The typedef is from a non-template context.  */
11873         return t;
11874
11875       if (r)
11876         {
11877           r = TREE_TYPE (r);
11878           r = cp_build_qualified_type_real
11879             (r, cp_type_quals (t) | cp_type_quals (r),
11880              complain | tf_ignore_bad_quals);
11881           return r;
11882         }
11883       else
11884         {
11885           /* We don't have an instantiation yet, so drop the typedef.  */
11886           int quals = cp_type_quals (t);
11887           t = DECL_ORIGINAL_TYPE (decl);
11888           t = cp_build_qualified_type_real (t, quals,
11889                                             complain | tf_ignore_bad_quals);
11890         }
11891     }
11892
11893   if (type
11894       && code != TYPENAME_TYPE
11895       && code != TEMPLATE_TYPE_PARM
11896       && code != IDENTIFIER_NODE
11897       && code != FUNCTION_TYPE
11898       && code != METHOD_TYPE)
11899     type = tsubst (type, args, complain, in_decl);
11900   if (type == error_mark_node)
11901     return error_mark_node;
11902
11903   switch (code)
11904     {
11905     case RECORD_TYPE:
11906     case UNION_TYPE:
11907     case ENUMERAL_TYPE:
11908       return tsubst_aggr_type (t, args, complain, in_decl,
11909                                /*entering_scope=*/0);
11910
11911     case ERROR_MARK:
11912     case IDENTIFIER_NODE:
11913     case VOID_TYPE:
11914     case REAL_TYPE:
11915     case COMPLEX_TYPE:
11916     case VECTOR_TYPE:
11917     case BOOLEAN_TYPE:
11918     case NULLPTR_TYPE:
11919     case LANG_TYPE:
11920       return t;
11921
11922     case INTEGER_TYPE:
11923       if (t == integer_type_node)
11924         return t;
11925
11926       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
11927           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
11928         return t;
11929
11930       {
11931         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
11932
11933         max = tsubst_expr (omax, args, complain, in_decl,
11934                            /*integral_constant_expression_p=*/false);
11935
11936         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
11937            needed.  */
11938         if (TREE_CODE (max) == NOP_EXPR
11939             && TREE_SIDE_EFFECTS (omax)
11940             && !TREE_TYPE (max))
11941           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
11942
11943         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
11944            with TREE_SIDE_EFFECTS that indicates this is not an integral
11945            constant expression.  */
11946         if (processing_template_decl
11947             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
11948           {
11949             gcc_assert (TREE_CODE (max) == NOP_EXPR);
11950             TREE_SIDE_EFFECTS (max) = 1;
11951           }
11952
11953         return compute_array_index_type (NULL_TREE, max, complain);
11954       }
11955
11956     case TEMPLATE_TYPE_PARM:
11957     case TEMPLATE_TEMPLATE_PARM:
11958     case BOUND_TEMPLATE_TEMPLATE_PARM:
11959     case TEMPLATE_PARM_INDEX:
11960       {
11961         int idx;
11962         int level;
11963         int levels;
11964         tree arg = NULL_TREE;
11965
11966         r = NULL_TREE;
11967
11968         gcc_assert (TREE_VEC_LENGTH (args) > 0);
11969         template_parm_level_and_index (t, &level, &idx); 
11970
11971         levels = TMPL_ARGS_DEPTH (args);
11972         if (level <= levels)
11973           {
11974             arg = TMPL_ARG (args, level, idx);
11975
11976             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
11977               {
11978                 /* See through ARGUMENT_PACK_SELECT arguments. */
11979                 arg = ARGUMENT_PACK_SELECT_ARG (arg);
11980                 /* If the selected argument is an expansion E, that most
11981                    likely means we were called from
11982                    gen_elem_of_pack_expansion_instantiation during the
11983                    substituting of pack an argument pack (which Ith
11984                    element is a pack expansion, where I is
11985                    ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
11986                    In this case, the Ith element resulting from this
11987                    substituting is going to be a pack expansion, which
11988                    pattern is the pattern of E.  Let's return the
11989                    pattern of E, and
11990                    gen_elem_of_pack_expansion_instantiation will
11991                    build the resulting pack expansion from it.  */
11992                 if (PACK_EXPANSION_P (arg))
11993                   {
11994                     /* Make sure we aren't throwing away arg info.  */
11995                     gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
11996                     arg = PACK_EXPANSION_PATTERN (arg);
11997                   }
11998               }
11999           }
12000
12001         if (arg == error_mark_node)
12002           return error_mark_node;
12003         else if (arg != NULL_TREE)
12004           {
12005             if (ARGUMENT_PACK_P (arg))
12006               /* If ARG is an argument pack, we don't actually want to
12007                  perform a substitution here, because substitutions
12008                  for argument packs are only done
12009                  element-by-element. We can get to this point when
12010                  substituting the type of a non-type template
12011                  parameter pack, when that type actually contains
12012                  template parameter packs from an outer template, e.g.,
12013
12014                  template<typename... Types> struct A {
12015                    template<Types... Values> struct B { };
12016                  };  */
12017               return t;
12018
12019             if (code == TEMPLATE_TYPE_PARM)
12020               {
12021                 int quals;
12022                 gcc_assert (TYPE_P (arg));
12023
12024                 quals = cp_type_quals (arg) | cp_type_quals (t);
12025                   
12026                 return cp_build_qualified_type_real
12027                   (arg, quals, complain | tf_ignore_bad_quals);
12028               }
12029             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
12030               {
12031                 /* We are processing a type constructed from a
12032                    template template parameter.  */
12033                 tree argvec = tsubst (TYPE_TI_ARGS (t),
12034                                       args, complain, in_decl);
12035                 if (argvec == error_mark_node)
12036                   return error_mark_node;
12037
12038                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
12039                             || TREE_CODE (arg) == TEMPLATE_DECL
12040                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
12041
12042                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
12043                   /* Consider this code:
12044
12045                         template <template <class> class Template>
12046                         struct Internal {
12047                         template <class Arg> using Bind = Template<Arg>;
12048                         };
12049
12050                         template <template <class> class Template, class Arg>
12051                         using Instantiate = Template<Arg>; //#0
12052
12053                         template <template <class> class Template,
12054                                   class Argument>
12055                         using Bind =
12056                           Instantiate<Internal<Template>::template Bind,
12057                                       Argument>; //#1
12058
12059                      When #1 is parsed, the
12060                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
12061                      parameter `Template' in #0 matches the
12062                      UNBOUND_CLASS_TEMPLATE representing the argument
12063                      `Internal<Template>::template Bind'; We then want
12064                      to assemble the type `Bind<Argument>' that can't
12065                      be fully created right now, because
12066                      `Internal<Template>' not being complete, the Bind
12067                      template cannot be looked up in that context.  So
12068                      we need to "store" `Bind<Argument>' for later
12069                      when the context of Bind becomes complete.  Let's
12070                      store that in a TYPENAME_TYPE.  */
12071                   return make_typename_type (TYPE_CONTEXT (arg),
12072                                              build_nt (TEMPLATE_ID_EXPR,
12073                                                        TYPE_IDENTIFIER (arg),
12074                                                        argvec),
12075                                              typename_type,
12076                                              complain);
12077
12078                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
12079                    are resolving nested-types in the signature of a
12080                    member function templates.  Otherwise ARG is a
12081                    TEMPLATE_DECL and is the real template to be
12082                    instantiated.  */
12083                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
12084                   arg = TYPE_NAME (arg);
12085
12086                 r = lookup_template_class (arg,
12087                                            argvec, in_decl,
12088                                            DECL_CONTEXT (arg),
12089                                             /*entering_scope=*/0,
12090                                            complain);
12091                 return cp_build_qualified_type_real
12092                   (r, cp_type_quals (t) | cp_type_quals (r), complain);
12093               }
12094             else
12095               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
12096               return convert_from_reference (unshare_expr (arg));
12097           }
12098
12099         if (level == 1)
12100           /* This can happen during the attempted tsubst'ing in
12101              unify.  This means that we don't yet have any information
12102              about the template parameter in question.  */
12103           return t;
12104
12105         /* Early in template argument deduction substitution, we don't
12106            want to reduce the level of 'auto', or it will be confused
12107            with a normal template parm in subsequent deduction.  */
12108         if (is_auto (t) && (complain & tf_partial))
12109           return t;
12110
12111         /* If we get here, we must have been looking at a parm for a
12112            more deeply nested template.  Make a new version of this
12113            template parameter, but with a lower level.  */
12114         switch (code)
12115           {
12116           case TEMPLATE_TYPE_PARM:
12117           case TEMPLATE_TEMPLATE_PARM:
12118           case BOUND_TEMPLATE_TEMPLATE_PARM:
12119             if (cp_type_quals (t))
12120               {
12121                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
12122                 r = cp_build_qualified_type_real
12123                   (r, cp_type_quals (t),
12124                    complain | (code == TEMPLATE_TYPE_PARM
12125                                ? tf_ignore_bad_quals : 0));
12126               }
12127             else
12128               {
12129                 r = copy_type (t);
12130                 TEMPLATE_TYPE_PARM_INDEX (r)
12131                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
12132                                                 r, levels, args, complain);
12133                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
12134                 TYPE_MAIN_VARIANT (r) = r;
12135                 TYPE_POINTER_TO (r) = NULL_TREE;
12136                 TYPE_REFERENCE_TO (r) = NULL_TREE;
12137
12138                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
12139                   /* We have reduced the level of the template
12140                      template parameter, but not the levels of its
12141                      template parameters, so canonical_type_parameter
12142                      will not be able to find the canonical template
12143                      template parameter for this level. Thus, we
12144                      require structural equality checking to compare
12145                      TEMPLATE_TEMPLATE_PARMs. */
12146                   SET_TYPE_STRUCTURAL_EQUALITY (r);
12147                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
12148                   SET_TYPE_STRUCTURAL_EQUALITY (r);
12149                 else
12150                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
12151
12152                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
12153                   {
12154                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
12155                                           complain, in_decl);
12156                     if (argvec == error_mark_node)
12157                       return error_mark_node;
12158
12159                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
12160                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
12161                   }
12162               }
12163             break;
12164
12165           case TEMPLATE_PARM_INDEX:
12166             r = reduce_template_parm_level (t, type, levels, args, complain);
12167             break;
12168
12169           default:
12170             gcc_unreachable ();
12171           }
12172
12173         return r;
12174       }
12175
12176     case TREE_LIST:
12177       {
12178         tree purpose, value, chain;
12179
12180         if (t == void_list_node)
12181           return t;
12182
12183         purpose = TREE_PURPOSE (t);
12184         if (purpose)
12185           {
12186             purpose = tsubst (purpose, args, complain, in_decl);
12187             if (purpose == error_mark_node)
12188               return error_mark_node;
12189           }
12190         value = TREE_VALUE (t);
12191         if (value)
12192           {
12193             value = tsubst (value, args, complain, in_decl);
12194             if (value == error_mark_node)
12195               return error_mark_node;
12196           }
12197         chain = TREE_CHAIN (t);
12198         if (chain && chain != void_type_node)
12199           {
12200             chain = tsubst (chain, args, complain, in_decl);
12201             if (chain == error_mark_node)
12202               return error_mark_node;
12203           }
12204         if (purpose == TREE_PURPOSE (t)
12205             && value == TREE_VALUE (t)
12206             && chain == TREE_CHAIN (t))
12207           return t;
12208         return hash_tree_cons (purpose, value, chain);
12209       }
12210
12211     case TREE_BINFO:
12212       /* We should never be tsubsting a binfo.  */
12213       gcc_unreachable ();
12214
12215     case TREE_VEC:
12216       /* A vector of template arguments.  */
12217       gcc_assert (!type);
12218       return tsubst_template_args (t, args, complain, in_decl);
12219
12220     case POINTER_TYPE:
12221     case REFERENCE_TYPE:
12222       {
12223         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
12224           return t;
12225
12226         /* [temp.deduct]
12227
12228            Type deduction may fail for any of the following
12229            reasons:
12230
12231            -- Attempting to create a pointer to reference type.
12232            -- Attempting to create a reference to a reference type or
12233               a reference to void.
12234
12235           Core issue 106 says that creating a reference to a reference
12236           during instantiation is no longer a cause for failure. We
12237           only enforce this check in strict C++98 mode.  */
12238         if ((TREE_CODE (type) == REFERENCE_TYPE
12239              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
12240             || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
12241           {
12242             static location_t last_loc;
12243
12244             /* We keep track of the last time we issued this error
12245                message to avoid spewing a ton of messages during a
12246                single bad template instantiation.  */
12247             if (complain & tf_error
12248                 && last_loc != input_location)
12249               {
12250                 if (VOID_TYPE_P (type))
12251                   error ("forming reference to void");
12252                else if (code == POINTER_TYPE)
12253                  error ("forming pointer to reference type %qT", type);
12254                else
12255                   error ("forming reference to reference type %qT", type);
12256                 last_loc = input_location;
12257               }
12258
12259             return error_mark_node;
12260           }
12261         else if (TREE_CODE (type) == FUNCTION_TYPE
12262                  && (type_memfn_quals (type) != TYPE_UNQUALIFIED
12263                      || type_memfn_rqual (type) != REF_QUAL_NONE))
12264           {
12265             if (complain & tf_error)
12266               {
12267                 if (code == POINTER_TYPE)
12268                   error ("forming pointer to qualified function type %qT",
12269                          type);
12270                 else
12271                   error ("forming reference to qualified function type %qT",
12272                          type);
12273               }
12274             return error_mark_node;
12275           }
12276         else if (code == POINTER_TYPE)
12277           {
12278             r = build_pointer_type (type);
12279             if (TREE_CODE (type) == METHOD_TYPE)
12280               r = build_ptrmemfunc_type (r);
12281           }
12282         else if (TREE_CODE (type) == REFERENCE_TYPE)
12283           /* In C++0x, during template argument substitution, when there is an
12284              attempt to create a reference to a reference type, reference
12285              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
12286
12287              "If a template-argument for a template-parameter T names a type
12288              that is a reference to a type A, an attempt to create the type
12289              'lvalue reference to cv T' creates the type 'lvalue reference to
12290              A,' while an attempt to create the type type rvalue reference to
12291              cv T' creates the type T"
12292           */
12293           r = cp_build_reference_type
12294               (TREE_TYPE (type),
12295                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
12296         else
12297           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
12298         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12299
12300         if (r != error_mark_node)
12301           /* Will this ever be needed for TYPE_..._TO values?  */
12302           layout_type (r);
12303
12304         return r;
12305       }
12306     case OFFSET_TYPE:
12307       {
12308         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
12309         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
12310           {
12311             /* [temp.deduct]
12312
12313                Type deduction may fail for any of the following
12314                reasons:
12315
12316                -- Attempting to create "pointer to member of T" when T
12317                   is not a class type.  */
12318             if (complain & tf_error)
12319               error ("creating pointer to member of non-class type %qT", r);
12320             return error_mark_node;
12321           }
12322         if (TREE_CODE (type) == REFERENCE_TYPE)
12323           {
12324             if (complain & tf_error)
12325               error ("creating pointer to member reference type %qT", type);
12326             return error_mark_node;
12327           }
12328         if (VOID_TYPE_P (type))
12329           {
12330             if (complain & tf_error)
12331               error ("creating pointer to member of type void");
12332             return error_mark_node;
12333           }
12334         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
12335         if (TREE_CODE (type) == FUNCTION_TYPE)
12336           {
12337             /* The type of the implicit object parameter gets its
12338                cv-qualifiers from the FUNCTION_TYPE. */
12339             tree memptr;
12340             tree method_type
12341               = build_memfn_type (type, r, type_memfn_quals (type),
12342                                   type_memfn_rqual (type));
12343             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
12344             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
12345                                                  complain);
12346           }
12347         else
12348           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
12349                                                cp_type_quals (t),
12350                                                complain);
12351       }
12352     case FUNCTION_TYPE:
12353     case METHOD_TYPE:
12354       {
12355         tree fntype;
12356         tree specs;
12357         fntype = tsubst_function_type (t, args, complain, in_decl);
12358         if (fntype == error_mark_node)
12359           return error_mark_node;
12360
12361         /* Substitute the exception specification.  */
12362         specs = tsubst_exception_specification (t, args, complain,
12363                                                 in_decl, /*defer_ok*/true);
12364         if (specs == error_mark_node)
12365           return error_mark_node;
12366         if (specs)
12367           fntype = build_exception_variant (fntype, specs);
12368         return fntype;
12369       }
12370     case ARRAY_TYPE:
12371       {
12372         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
12373         if (domain == error_mark_node)
12374           return error_mark_node;
12375
12376         /* As an optimization, we avoid regenerating the array type if
12377            it will obviously be the same as T.  */
12378         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
12379           return t;
12380
12381         /* These checks should match the ones in create_array_type_for_decl.
12382
12383            [temp.deduct]
12384
12385            The deduction may fail for any of the following reasons:
12386
12387            -- Attempting to create an array with an element type that
12388               is void, a function type, or a reference type, or [DR337]
12389               an abstract class type.  */
12390         if (VOID_TYPE_P (type)
12391             || TREE_CODE (type) == FUNCTION_TYPE
12392             || (TREE_CODE (type) == ARRAY_TYPE
12393                 && TYPE_DOMAIN (type) == NULL_TREE)
12394             || TREE_CODE (type) == REFERENCE_TYPE)
12395           {
12396             if (complain & tf_error)
12397               error ("creating array of %qT", type);
12398             return error_mark_node;
12399           }
12400
12401         if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
12402           return error_mark_node;
12403
12404         r = build_cplus_array_type (type, domain);
12405
12406         if (TYPE_USER_ALIGN (t))
12407           {
12408             TYPE_ALIGN (r) = TYPE_ALIGN (t);
12409             TYPE_USER_ALIGN (r) = 1;
12410           }
12411
12412         return r;
12413       }
12414
12415     case TYPENAME_TYPE:
12416       {
12417         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
12418                                      in_decl, /*entering_scope=*/1);
12419         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
12420                               complain, in_decl);
12421
12422         if (ctx == error_mark_node || f == error_mark_node)
12423           return error_mark_node;
12424
12425         if (!MAYBE_CLASS_TYPE_P (ctx))
12426           {
12427             if (complain & tf_error)
12428               error ("%qT is not a class, struct, or union type", ctx);
12429             return error_mark_node;
12430           }
12431         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
12432           {
12433             /* Normally, make_typename_type does not require that the CTX
12434                have complete type in order to allow things like:
12435
12436                  template <class T> struct S { typename S<T>::X Y; };
12437
12438                But, such constructs have already been resolved by this
12439                point, so here CTX really should have complete type, unless
12440                it's a partial instantiation.  */
12441             ctx = complete_type (ctx);
12442             if (!COMPLETE_TYPE_P (ctx))
12443               {
12444                 if (complain & tf_error)
12445                   cxx_incomplete_type_error (NULL_TREE, ctx);
12446                 return error_mark_node;
12447               }
12448           }
12449
12450         f = make_typename_type (ctx, f, typename_type,
12451                                 complain | tf_keep_type_decl);
12452         if (f == error_mark_node)
12453           return f;
12454         if (TREE_CODE (f) == TYPE_DECL)
12455           {
12456             complain |= tf_ignore_bad_quals;
12457             f = TREE_TYPE (f);
12458           }
12459
12460         if (TREE_CODE (f) != TYPENAME_TYPE)
12461           {
12462             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
12463               {
12464                 if (complain & tf_error)
12465                   error ("%qT resolves to %qT, which is not an enumeration type",
12466                          t, f);
12467                 else
12468                   return error_mark_node;
12469               }
12470             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
12471               {
12472                 if (complain & tf_error)
12473                   error ("%qT resolves to %qT, which is is not a class type",
12474                          t, f);
12475                 else
12476                   return error_mark_node;
12477               }
12478           }
12479
12480         return cp_build_qualified_type_real
12481           (f, cp_type_quals (f) | cp_type_quals (t), complain);
12482       }
12483
12484     case UNBOUND_CLASS_TEMPLATE:
12485       {
12486         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
12487                                      in_decl, /*entering_scope=*/1);
12488         tree name = TYPE_IDENTIFIER (t);
12489         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
12490
12491         if (ctx == error_mark_node || name == error_mark_node)
12492           return error_mark_node;
12493
12494         if (parm_list)
12495           parm_list = tsubst_template_parms (parm_list, args, complain);
12496         return make_unbound_class_template (ctx, name, parm_list, complain);
12497       }
12498
12499     case TYPEOF_TYPE:
12500       {
12501         tree type;
12502
12503         ++cp_unevaluated_operand;
12504         ++c_inhibit_evaluation_warnings;
12505
12506         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
12507                             complain, in_decl,
12508                             /*integral_constant_expression_p=*/false);
12509
12510         --cp_unevaluated_operand;
12511         --c_inhibit_evaluation_warnings;
12512
12513         type = finish_typeof (type);
12514         return cp_build_qualified_type_real (type,
12515                                              cp_type_quals (t)
12516                                              | cp_type_quals (type),
12517                                              complain);
12518       }
12519
12520     case DECLTYPE_TYPE:
12521       {
12522         tree type;
12523
12524         ++cp_unevaluated_operand;
12525         ++c_inhibit_evaluation_warnings;
12526
12527         type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
12528                                       complain|tf_decltype, in_decl,
12529                                       /*function_p*/false,
12530                                       /*integral_constant_expression*/false);
12531
12532         --cp_unevaluated_operand;
12533         --c_inhibit_evaluation_warnings;
12534
12535         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
12536           type = lambda_capture_field_type (type,
12537                                             DECLTYPE_FOR_INIT_CAPTURE (t));
12538         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
12539           type = lambda_proxy_type (type);
12540         else
12541           {
12542             bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
12543             if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
12544                 && EXPR_P (type))
12545               /* In a template ~id could be either a complement expression
12546                  or an unqualified-id naming a destructor; if instantiating
12547                  it produces an expression, it's not an id-expression or
12548                  member access.  */
12549               id = false;
12550             type = finish_decltype_type (type, id, complain);
12551           }
12552         return cp_build_qualified_type_real (type,
12553                                              cp_type_quals (t)
12554                                              | cp_type_quals (type),
12555                                              complain | tf_ignore_bad_quals);
12556       }
12557
12558     case UNDERLYING_TYPE:
12559       {
12560         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
12561                             complain, in_decl);
12562         return finish_underlying_type (type);
12563       }
12564
12565     case TYPE_ARGUMENT_PACK:
12566     case NONTYPE_ARGUMENT_PACK:
12567       {
12568         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
12569         tree packed_out = 
12570           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
12571                                 args,
12572                                 complain,
12573                                 in_decl);
12574         SET_ARGUMENT_PACK_ARGS (r, packed_out);
12575
12576         /* For template nontype argument packs, also substitute into
12577            the type.  */
12578         if (code == NONTYPE_ARGUMENT_PACK)
12579           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
12580
12581         return r;
12582       }
12583       break;
12584
12585     case VOID_CST:
12586     case INTEGER_CST:
12587     case REAL_CST:
12588     case STRING_CST:
12589     case PLUS_EXPR:
12590     case MINUS_EXPR:
12591     case NEGATE_EXPR:
12592     case NOP_EXPR:
12593     case INDIRECT_REF:
12594     case ADDR_EXPR:
12595     case CALL_EXPR:
12596     case ARRAY_REF:
12597     case SCOPE_REF:
12598       /* We should use one of the expression tsubsts for these codes.  */
12599       gcc_unreachable ();
12600
12601     default:
12602       sorry ("use of %qs in template", get_tree_code_name (code));
12603       return error_mark_node;
12604     }
12605 }
12606
12607 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
12608    type of the expression on the left-hand side of the "." or "->"
12609    operator.  */
12610
12611 static tree
12612 tsubst_baselink (tree baselink, tree object_type,
12613                  tree args, tsubst_flags_t complain, tree in_decl)
12614 {
12615     tree name;
12616     tree qualifying_scope;
12617     tree fns;
12618     tree optype;
12619     tree template_args = 0;
12620     bool template_id_p = false;
12621     bool qualified = BASELINK_QUALIFIED_P (baselink);
12622
12623     /* A baselink indicates a function from a base class.  Both the
12624        BASELINK_ACCESS_BINFO and the base class referenced may
12625        indicate bases of the template class, rather than the
12626        instantiated class.  In addition, lookups that were not
12627        ambiguous before may be ambiguous now.  Therefore, we perform
12628        the lookup again.  */
12629     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
12630     qualifying_scope = tsubst (qualifying_scope, args,
12631                                complain, in_decl);
12632     fns = BASELINK_FUNCTIONS (baselink);
12633     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
12634     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
12635       {
12636         template_id_p = true;
12637         template_args = TREE_OPERAND (fns, 1);
12638         fns = TREE_OPERAND (fns, 0);
12639         if (template_args)
12640           template_args = tsubst_template_args (template_args, args,
12641                                                 complain, in_decl);
12642       }
12643     name = DECL_NAME (get_first_fn (fns));
12644     if (IDENTIFIER_TYPENAME_P (name))
12645       name = mangle_conv_op_name_for_type (optype);
12646     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
12647     if (!baselink)
12648       return error_mark_node;
12649
12650     /* If lookup found a single function, mark it as used at this
12651        point.  (If it lookup found multiple functions the one selected
12652        later by overload resolution will be marked as used at that
12653        point.)  */
12654     if (BASELINK_P (baselink))
12655       fns = BASELINK_FUNCTIONS (baselink);
12656     if (!template_id_p && !really_overloaded_fn (fns))
12657       mark_used (OVL_CURRENT (fns));
12658
12659     /* Add back the template arguments, if present.  */
12660     if (BASELINK_P (baselink) && template_id_p)
12661       BASELINK_FUNCTIONS (baselink)
12662         = build_nt (TEMPLATE_ID_EXPR,
12663                     BASELINK_FUNCTIONS (baselink),
12664                     template_args);
12665     /* Update the conversion operator type.  */
12666     BASELINK_OPTYPE (baselink) = optype;
12667
12668     if (!object_type)
12669       object_type = current_class_type;
12670
12671     if (qualified)
12672       baselink = adjust_result_of_qualified_name_lookup (baselink,
12673                                                          qualifying_scope,
12674                                                          object_type);
12675     return baselink;
12676 }
12677
12678 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
12679    true if the qualified-id will be a postfix-expression in-and-of
12680    itself; false if more of the postfix-expression follows the
12681    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
12682    of "&".  */
12683
12684 static tree
12685 tsubst_qualified_id (tree qualified_id, tree args,
12686                      tsubst_flags_t complain, tree in_decl,
12687                      bool done, bool address_p)
12688 {
12689   tree expr;
12690   tree scope;
12691   tree name;
12692   bool is_template;
12693   tree template_args;
12694   location_t loc = UNKNOWN_LOCATION;
12695
12696   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
12697
12698   /* Figure out what name to look up.  */
12699   name = TREE_OPERAND (qualified_id, 1);
12700   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
12701     {
12702       is_template = true;
12703       loc = EXPR_LOCATION (name);
12704       template_args = TREE_OPERAND (name, 1);
12705       if (template_args)
12706         template_args = tsubst_template_args (template_args, args,
12707                                               complain, in_decl);
12708       name = TREE_OPERAND (name, 0);
12709     }
12710   else
12711     {
12712       is_template = false;
12713       template_args = NULL_TREE;
12714     }
12715
12716   /* Substitute into the qualifying scope.  When there are no ARGS, we
12717      are just trying to simplify a non-dependent expression.  In that
12718      case the qualifying scope may be dependent, and, in any case,
12719      substituting will not help.  */
12720   scope = TREE_OPERAND (qualified_id, 0);
12721   if (args)
12722     {
12723       scope = tsubst (scope, args, complain, in_decl);
12724       expr = tsubst_copy (name, args, complain, in_decl);
12725     }
12726   else
12727     expr = name;
12728
12729   if (dependent_scope_p (scope))
12730     {
12731       if (is_template)
12732         expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
12733       return build_qualified_name (NULL_TREE, scope, expr,
12734                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
12735     }
12736
12737   if (!BASELINK_P (name) && !DECL_P (expr))
12738     {
12739       if (TREE_CODE (expr) == BIT_NOT_EXPR)
12740         {
12741           /* A BIT_NOT_EXPR is used to represent a destructor.  */
12742           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
12743             {
12744               error ("qualifying type %qT does not match destructor name ~%qT",
12745                      scope, TREE_OPERAND (expr, 0));
12746               expr = error_mark_node;
12747             }
12748           else
12749             expr = lookup_qualified_name (scope, complete_dtor_identifier,
12750                                           /*is_type_p=*/0, false);
12751         }
12752       else
12753         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
12754       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
12755                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
12756         {
12757           if (complain & tf_error)
12758             {
12759               error ("dependent-name %qE is parsed as a non-type, but "
12760                      "instantiation yields a type", qualified_id);
12761               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
12762             }
12763           return error_mark_node;
12764         }
12765     }
12766
12767   if (DECL_P (expr))
12768     {
12769       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
12770                                            scope);
12771       /* Remember that there was a reference to this entity.  */
12772       mark_used (expr);
12773     }
12774
12775   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
12776     {
12777       if (complain & tf_error)
12778         qualified_name_lookup_error (scope,
12779                                      TREE_OPERAND (qualified_id, 1),
12780                                      expr, input_location);
12781       return error_mark_node;
12782     }
12783
12784   if (is_template)
12785     expr = lookup_template_function (expr, template_args);
12786
12787   if (expr == error_mark_node && complain & tf_error)
12788     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
12789                                  expr, input_location);
12790   else if (TYPE_P (scope))
12791     {
12792       expr = (adjust_result_of_qualified_name_lookup
12793               (expr, scope, current_nonlambda_class_type ()));
12794       expr = (finish_qualified_id_expr
12795               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
12796                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
12797                /*template_arg_p=*/false, complain));
12798     }
12799
12800   /* Expressions do not generally have reference type.  */
12801   if (TREE_CODE (expr) != SCOPE_REF
12802       /* However, if we're about to form a pointer-to-member, we just
12803          want the referenced member referenced.  */
12804       && TREE_CODE (expr) != OFFSET_REF)
12805     expr = convert_from_reference (expr);
12806
12807   return expr;
12808 }
12809
12810 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
12811    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
12812    for tsubst.  */
12813
12814 static tree
12815 tsubst_init (tree init, tree decl, tree args,
12816              tsubst_flags_t complain, tree in_decl)
12817 {
12818   if (!init)
12819     return NULL_TREE;
12820
12821   init = tsubst_expr (init, args, complain, in_decl, false);
12822
12823   if (!init)
12824     {
12825       /* If we had an initializer but it
12826          instantiated to nothing,
12827          value-initialize the object.  This will
12828          only occur when the initializer was a
12829          pack expansion where the parameter packs
12830          used in that expansion were of length
12831          zero.  */
12832       init = build_value_init (TREE_TYPE (decl),
12833                                complain);
12834       if (TREE_CODE (init) == AGGR_INIT_EXPR)
12835         init = get_target_expr_sfinae (init, complain);
12836     }
12837
12838   return init;
12839 }
12840
12841 /* Like tsubst, but deals with expressions.  This function just replaces
12842    template parms; to finish processing the resultant expression, use
12843    tsubst_copy_and_build or tsubst_expr.  */
12844
12845 static tree
12846 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12847 {
12848   enum tree_code code;
12849   tree r;
12850
12851   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
12852     return t;
12853
12854   code = TREE_CODE (t);
12855
12856   switch (code)
12857     {
12858     case PARM_DECL:
12859       r = retrieve_local_specialization (t);
12860
12861       if (r == NULL_TREE)
12862         {
12863           /* We get here for a use of 'this' in an NSDMI.  */
12864           if (DECL_NAME (t) == this_identifier
12865               && current_function_decl
12866               && DECL_CONSTRUCTOR_P (current_function_decl))
12867             return current_class_ptr;
12868
12869           /* This can happen for a parameter name used later in a function
12870              declaration (such as in a late-specified return type).  Just
12871              make a dummy decl, since it's only used for its type.  */
12872           gcc_assert (cp_unevaluated_operand != 0);
12873           r = tsubst_decl (t, args, complain);
12874           /* Give it the template pattern as its context; its true context
12875              hasn't been instantiated yet and this is good enough for
12876              mangling.  */
12877           DECL_CONTEXT (r) = DECL_CONTEXT (t);
12878         }
12879       
12880       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
12881         r = ARGUMENT_PACK_SELECT_ARG (r);
12882       mark_used (r);
12883       return r;
12884
12885     case CONST_DECL:
12886       {
12887         tree enum_type;
12888         tree v;
12889
12890         if (DECL_TEMPLATE_PARM_P (t))
12891           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
12892         /* There is no need to substitute into namespace-scope
12893            enumerators.  */
12894         if (DECL_NAMESPACE_SCOPE_P (t))
12895           return t;
12896         /* If ARGS is NULL, then T is known to be non-dependent.  */
12897         if (args == NULL_TREE)
12898           return scalar_constant_value (t);
12899
12900         /* Unfortunately, we cannot just call lookup_name here.
12901            Consider:
12902
12903              template <int I> int f() {
12904              enum E { a = I };
12905              struct S { void g() { E e = a; } };
12906              };
12907
12908            When we instantiate f<7>::S::g(), say, lookup_name is not
12909            clever enough to find f<7>::a.  */
12910         enum_type
12911           = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
12912                               /*entering_scope=*/0);
12913
12914         for (v = TYPE_VALUES (enum_type);
12915              v != NULL_TREE;
12916              v = TREE_CHAIN (v))
12917           if (TREE_PURPOSE (v) == DECL_NAME (t))
12918             return TREE_VALUE (v);
12919
12920           /* We didn't find the name.  That should never happen; if
12921              name-lookup found it during preliminary parsing, we
12922              should find it again here during instantiation.  */
12923         gcc_unreachable ();
12924       }
12925       return t;
12926
12927     case FIELD_DECL:
12928       if (PACK_EXPANSION_P (TREE_TYPE (t)))
12929         {
12930           /* Check for a local specialization set up by
12931              tsubst_pack_expansion.  */
12932           if (tree r = retrieve_local_specialization (t))
12933             {
12934               if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
12935                 r = ARGUMENT_PACK_SELECT_ARG (r);
12936               return r;
12937             }
12938
12939           /* When retrieving a capture pack from a generic lambda, remove the
12940              lambda call op's own template argument list from ARGS.  Only the
12941              template arguments active for the closure type should be used to
12942              retrieve the pack specialization.  */
12943           if (LAMBDA_FUNCTION_P (current_function_decl)
12944               && (template_class_depth (DECL_CONTEXT (t))
12945                   != TMPL_ARGS_DEPTH (args)))
12946             args = strip_innermost_template_args (args, 1);
12947
12948           /* Otherwise return the full NONTYPE_ARGUMENT_PACK that
12949              tsubst_decl put in the hash table.  */
12950           return retrieve_specialization (t, args, 0);
12951         }
12952
12953       if (DECL_CONTEXT (t))
12954         {
12955           tree ctx;
12956
12957           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
12958                                   /*entering_scope=*/1);
12959           if (ctx != DECL_CONTEXT (t))
12960             {
12961               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
12962               if (!r)
12963                 {
12964                   if (complain & tf_error)
12965                     error ("using invalid field %qD", t);
12966                   return error_mark_node;
12967                 }
12968               return r;
12969             }
12970         }
12971
12972       return t;
12973
12974     case VAR_DECL:
12975     case FUNCTION_DECL:
12976       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
12977         r = tsubst (t, args, complain, in_decl);
12978       else if (local_variable_p (t))
12979         {
12980           r = retrieve_local_specialization (t);
12981           if (r == NULL_TREE)
12982             {
12983               /* First try name lookup to find the instantiation.  */
12984               r = lookup_name (DECL_NAME (t));
12985               if (r)
12986                 {
12987                   /* Make sure that the one we found is the one we want.  */
12988                   tree ctx = tsubst (DECL_CONTEXT (t), args,
12989                                      complain, in_decl);
12990                   if (ctx != DECL_CONTEXT (r))
12991                     r = NULL_TREE;
12992                 }
12993
12994               if (r)
12995                 /* OK */;
12996               else
12997                 {
12998                   /* This can happen for a variable used in a
12999                      late-specified return type of a local lambda, or for a
13000                      local static or constant.  Building a new VAR_DECL
13001                      should be OK in all those cases.  */
13002                   r = tsubst_decl (t, args, complain);
13003                   if (decl_maybe_constant_var_p (r))
13004                     {
13005                       /* We can't call cp_finish_decl, so handle the
13006                          initializer by hand.  */
13007                       tree init = tsubst_init (DECL_INITIAL (t), r, args,
13008                                                complain, in_decl);
13009                       if (!processing_template_decl)
13010                         init = maybe_constant_init (init);
13011                       if (processing_template_decl
13012                           ? potential_constant_expression (init)
13013                           : reduced_constant_expression_p (init))
13014                         DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
13015                           = TREE_CONSTANT (r) = true;
13016                       DECL_INITIAL (r) = init;
13017                     }
13018                   gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
13019                               || decl_constant_var_p (r)
13020                               || errorcount || sorrycount);
13021                   if (!processing_template_decl)
13022                     {
13023                       if (TREE_STATIC (r))
13024                         rest_of_decl_compilation (r, toplevel_bindings_p (),
13025                                                   at_eof);
13026                       else if (decl_constant_var_p (r))
13027                         /* A use of a local constant decays to its value.
13028                            FIXME update for core DR 696.  */
13029                         r = scalar_constant_value (r);
13030                     }
13031                 }
13032               /* Remember this for subsequent uses.  */
13033               if (local_specializations)
13034                 register_local_specialization (r, t);
13035             }
13036         }
13037       else
13038         r = t;
13039       mark_used (r);
13040       return r;
13041
13042     case NAMESPACE_DECL:
13043       return t;
13044
13045     case OVERLOAD:
13046       /* An OVERLOAD will always be a non-dependent overload set; an
13047          overload set from function scope will just be represented with an
13048          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
13049       gcc_assert (!uses_template_parms (t));
13050       return t;
13051
13052     case BASELINK:
13053       return tsubst_baselink (t, current_nonlambda_class_type (),
13054                               args, complain, in_decl);
13055
13056     case TEMPLATE_DECL:
13057       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13058         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
13059                        args, complain, in_decl);
13060       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
13061         return tsubst (t, args, complain, in_decl);
13062       else if (DECL_CLASS_SCOPE_P (t)
13063                && uses_template_parms (DECL_CONTEXT (t)))
13064         {
13065           /* Template template argument like the following example need
13066              special treatment:
13067
13068                template <template <class> class TT> struct C {};
13069                template <class T> struct D {
13070                  template <class U> struct E {};
13071                  C<E> c;                                // #1
13072                };
13073                D<int> d;                                // #2
13074
13075              We are processing the template argument `E' in #1 for
13076              the template instantiation #2.  Originally, `E' is a
13077              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
13078              have to substitute this with one having context `D<int>'.  */
13079
13080           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
13081           return lookup_field (context, DECL_NAME(t), 0, false);
13082         }
13083       else
13084         /* Ordinary template template argument.  */
13085         return t;
13086
13087     case CAST_EXPR:
13088     case REINTERPRET_CAST_EXPR:
13089     case CONST_CAST_EXPR:
13090     case STATIC_CAST_EXPR:
13091     case DYNAMIC_CAST_EXPR:
13092     case IMPLICIT_CONV_EXPR:
13093     case CONVERT_EXPR:
13094     case NOP_EXPR:
13095       {
13096         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13097         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13098         return build1 (code, type, op0);
13099       }
13100
13101     case SIZEOF_EXPR:
13102       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13103         {
13104
13105           tree expanded, op = TREE_OPERAND (t, 0);
13106           int len = 0;
13107
13108           if (SIZEOF_EXPR_TYPE_P (t))
13109             op = TREE_TYPE (op);
13110
13111           ++cp_unevaluated_operand;
13112           ++c_inhibit_evaluation_warnings;
13113           /* We only want to compute the number of arguments.  */
13114           expanded = tsubst_pack_expansion (op, args, complain, in_decl);
13115           --cp_unevaluated_operand;
13116           --c_inhibit_evaluation_warnings;
13117
13118           if (TREE_CODE (expanded) == TREE_VEC)
13119             len = TREE_VEC_LENGTH (expanded);
13120
13121           if (expanded == error_mark_node)
13122             return error_mark_node;
13123           else if (PACK_EXPANSION_P (expanded)
13124                    || (TREE_CODE (expanded) == TREE_VEC
13125                        && len > 0
13126                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
13127             {
13128               if (TREE_CODE (expanded) == TREE_VEC)
13129                 expanded = TREE_VEC_ELT (expanded, len - 1);
13130
13131               if (TYPE_P (expanded))
13132                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
13133                                                    complain & tf_error);
13134               else
13135                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
13136                                                    complain & tf_error);
13137             }
13138           else
13139             return build_int_cst (size_type_node, len);
13140         }
13141       if (SIZEOF_EXPR_TYPE_P (t))
13142         {
13143           r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
13144                       args, complain, in_decl);
13145           r = build1 (NOP_EXPR, r, error_mark_node);
13146           r = build1 (SIZEOF_EXPR,
13147                       tsubst (TREE_TYPE (t), args, complain, in_decl), r);
13148           SIZEOF_EXPR_TYPE_P (r) = 1;
13149           return r;
13150         }
13151       /* Fall through */
13152
13153     case INDIRECT_REF:
13154     case NEGATE_EXPR:
13155     case TRUTH_NOT_EXPR:
13156     case BIT_NOT_EXPR:
13157     case ADDR_EXPR:
13158     case UNARY_PLUS_EXPR:      /* Unary + */
13159     case ALIGNOF_EXPR:
13160     case AT_ENCODE_EXPR:
13161     case ARROW_EXPR:
13162     case THROW_EXPR:
13163     case TYPEID_EXPR:
13164     case REALPART_EXPR:
13165     case IMAGPART_EXPR:
13166     case PAREN_EXPR:
13167       {
13168         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13169         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13170         return build1 (code, type, op0);
13171       }
13172
13173     case COMPONENT_REF:
13174       {
13175         tree object;
13176         tree name;
13177
13178         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13179         name = TREE_OPERAND (t, 1);
13180         if (TREE_CODE (name) == BIT_NOT_EXPR)
13181           {
13182             name = tsubst_copy (TREE_OPERAND (name, 0), args,
13183                                 complain, in_decl);
13184             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
13185           }
13186         else if (TREE_CODE (name) == SCOPE_REF
13187                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
13188           {
13189             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
13190                                      complain, in_decl);
13191             name = TREE_OPERAND (name, 1);
13192             name = tsubst_copy (TREE_OPERAND (name, 0), args,
13193                                 complain, in_decl);
13194             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
13195             name = build_qualified_name (/*type=*/NULL_TREE,
13196                                          base, name,
13197                                          /*template_p=*/false);
13198           }
13199         else if (BASELINK_P (name))
13200           name = tsubst_baselink (name,
13201                                   non_reference (TREE_TYPE (object)),
13202                                   args, complain,
13203                                   in_decl);
13204         else
13205           name = tsubst_copy (name, args, complain, in_decl);
13206         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
13207       }
13208
13209     case PLUS_EXPR:
13210     case MINUS_EXPR:
13211     case MULT_EXPR:
13212     case TRUNC_DIV_EXPR:
13213     case CEIL_DIV_EXPR:
13214     case FLOOR_DIV_EXPR:
13215     case ROUND_DIV_EXPR:
13216     case EXACT_DIV_EXPR:
13217     case BIT_AND_EXPR:
13218     case BIT_IOR_EXPR:
13219     case BIT_XOR_EXPR:
13220     case TRUNC_MOD_EXPR:
13221     case FLOOR_MOD_EXPR:
13222     case TRUTH_ANDIF_EXPR:
13223     case TRUTH_ORIF_EXPR:
13224     case TRUTH_AND_EXPR:
13225     case TRUTH_OR_EXPR:
13226     case RSHIFT_EXPR:
13227     case LSHIFT_EXPR:
13228     case RROTATE_EXPR:
13229     case LROTATE_EXPR:
13230     case EQ_EXPR:
13231     case NE_EXPR:
13232     case MAX_EXPR:
13233     case MIN_EXPR:
13234     case LE_EXPR:
13235     case GE_EXPR:
13236     case LT_EXPR:
13237     case GT_EXPR:
13238     case COMPOUND_EXPR:
13239     case DOTSTAR_EXPR:
13240     case MEMBER_REF:
13241     case PREDECREMENT_EXPR:
13242     case PREINCREMENT_EXPR:
13243     case POSTDECREMENT_EXPR:
13244     case POSTINCREMENT_EXPR:
13245       {
13246         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13247         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13248         return build_nt (code, op0, op1);
13249       }
13250
13251     case SCOPE_REF:
13252       {
13253         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13254         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13255         return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
13256                                      QUALIFIED_NAME_IS_TEMPLATE (t));
13257       }
13258
13259     case ARRAY_REF:
13260       {
13261         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13262         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13263         return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
13264       }
13265
13266     case CALL_EXPR:
13267       {
13268         int n = VL_EXP_OPERAND_LENGTH (t);
13269         tree result = build_vl_exp (CALL_EXPR, n);
13270         int i;
13271         for (i = 0; i < n; i++)
13272           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
13273                                              complain, in_decl);
13274         return result;
13275       }
13276
13277     case COND_EXPR:
13278     case MODOP_EXPR:
13279     case PSEUDO_DTOR_EXPR:
13280     case VEC_PERM_EXPR:
13281       {
13282         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13283         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13284         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
13285         r = build_nt (code, op0, op1, op2);
13286         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13287         return r;
13288       }
13289
13290     case NEW_EXPR:
13291       {
13292         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13293         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13294         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
13295         r = build_nt (code, op0, op1, op2);
13296         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
13297         return r;
13298       }
13299
13300     case DELETE_EXPR:
13301       {
13302         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13303         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13304         r = build_nt (code, op0, op1);
13305         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
13306         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
13307         return r;
13308       }
13309
13310     case TEMPLATE_ID_EXPR:
13311       {
13312         /* Substituted template arguments */
13313         tree fn = TREE_OPERAND (t, 0);
13314         tree targs = TREE_OPERAND (t, 1);
13315
13316         fn = tsubst_copy (fn, args, complain, in_decl);
13317         if (targs)
13318           targs = tsubst_template_args (targs, args, complain, in_decl);
13319
13320         return lookup_template_function (fn, targs);
13321       }
13322
13323     case TREE_LIST:
13324       {
13325         tree purpose, value, chain;
13326
13327         if (t == void_list_node)
13328           return t;
13329
13330         purpose = TREE_PURPOSE (t);
13331         if (purpose)
13332           purpose = tsubst_copy (purpose, args, complain, in_decl);
13333         value = TREE_VALUE (t);
13334         if (value)
13335           value = tsubst_copy (value, args, complain, in_decl);
13336         chain = TREE_CHAIN (t);
13337         if (chain && chain != void_type_node)
13338           chain = tsubst_copy (chain, args, complain, in_decl);
13339         if (purpose == TREE_PURPOSE (t)
13340             && value == TREE_VALUE (t)
13341             && chain == TREE_CHAIN (t))
13342           return t;
13343         return tree_cons (purpose, value, chain);
13344       }
13345
13346     case RECORD_TYPE:
13347     case UNION_TYPE:
13348     case ENUMERAL_TYPE:
13349     case INTEGER_TYPE:
13350     case TEMPLATE_TYPE_PARM:
13351     case TEMPLATE_TEMPLATE_PARM:
13352     case BOUND_TEMPLATE_TEMPLATE_PARM:
13353     case TEMPLATE_PARM_INDEX:
13354     case POINTER_TYPE:
13355     case REFERENCE_TYPE:
13356     case OFFSET_TYPE:
13357     case FUNCTION_TYPE:
13358     case METHOD_TYPE:
13359     case ARRAY_TYPE:
13360     case TYPENAME_TYPE:
13361     case UNBOUND_CLASS_TEMPLATE:
13362     case TYPEOF_TYPE:
13363     case DECLTYPE_TYPE:
13364     case TYPE_DECL:
13365       return tsubst (t, args, complain, in_decl);
13366
13367     case USING_DECL:
13368       t = DECL_NAME (t);
13369       /* Fall through.  */
13370     case IDENTIFIER_NODE:
13371       if (IDENTIFIER_TYPENAME_P (t))
13372         {
13373           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13374           return mangle_conv_op_name_for_type (new_type);
13375         }
13376       else
13377         return t;
13378
13379     case CONSTRUCTOR:
13380       /* This is handled by tsubst_copy_and_build.  */
13381       gcc_unreachable ();
13382
13383     case VA_ARG_EXPR:
13384       {
13385         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13386         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13387         return build_x_va_arg (EXPR_LOCATION (t), op0, type);
13388       }
13389
13390     case CLEANUP_POINT_EXPR:
13391       /* We shouldn't have built any of these during initial template
13392          generation.  Instead, they should be built during instantiation
13393          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
13394       gcc_unreachable ();
13395
13396     case OFFSET_REF:
13397       {
13398         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13399         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
13400         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
13401         r = build2 (code, type, op0, op1);
13402         PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
13403         mark_used (TREE_OPERAND (r, 1));
13404         return r;
13405       }
13406
13407     case EXPR_PACK_EXPANSION:
13408       error ("invalid use of pack expansion expression");
13409       return error_mark_node;
13410
13411     case NONTYPE_ARGUMENT_PACK:
13412       error ("use %<...%> to expand argument pack");
13413       return error_mark_node;
13414
13415     case VOID_CST:
13416       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
13417       return t;
13418
13419     case INTEGER_CST:
13420     case REAL_CST:
13421     case STRING_CST:
13422     case COMPLEX_CST:
13423       {
13424         /* Instantiate any typedefs in the type.  */
13425         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13426         r = fold_convert (type, t);
13427         gcc_assert (TREE_CODE (r) == code);
13428         return r;
13429       }
13430
13431     case PTRMEM_CST:
13432       /* These can sometimes show up in a partial instantiation, but never
13433          involve template parms.  */
13434       gcc_assert (!uses_template_parms (t));
13435       return t;
13436
13437     default:
13438       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
13439       gcc_checking_assert (false);
13440       return t;
13441     }
13442 }
13443
13444 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
13445
13446 static tree
13447 tsubst_omp_clauses (tree clauses, bool declare_simd,
13448                     tree args, tsubst_flags_t complain, tree in_decl)
13449 {
13450   tree new_clauses = NULL, nc, oc;
13451
13452   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
13453     {
13454       nc = copy_node (oc);
13455       OMP_CLAUSE_CHAIN (nc) = new_clauses;
13456       new_clauses = nc;
13457
13458       switch (OMP_CLAUSE_CODE (nc))
13459         {
13460         case OMP_CLAUSE_LASTPRIVATE:
13461           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
13462             {
13463               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
13464               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
13465                            in_decl, /*integral_constant_expression_p=*/false);
13466               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
13467                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
13468             }
13469           /* FALLTHRU */
13470         case OMP_CLAUSE_PRIVATE:
13471         case OMP_CLAUSE_SHARED:
13472         case OMP_CLAUSE_FIRSTPRIVATE:
13473         case OMP_CLAUSE_COPYIN:
13474         case OMP_CLAUSE_COPYPRIVATE:
13475         case OMP_CLAUSE_IF:
13476         case OMP_CLAUSE_NUM_THREADS:
13477         case OMP_CLAUSE_SCHEDULE:
13478         case OMP_CLAUSE_COLLAPSE:
13479         case OMP_CLAUSE_FINAL:
13480         case OMP_CLAUSE_DEPEND:
13481         case OMP_CLAUSE_FROM:
13482         case OMP_CLAUSE_TO:
13483         case OMP_CLAUSE_UNIFORM:
13484         case OMP_CLAUSE_MAP:
13485         case OMP_CLAUSE_DEVICE:
13486         case OMP_CLAUSE_DIST_SCHEDULE:
13487         case OMP_CLAUSE_NUM_TEAMS:
13488         case OMP_CLAUSE_THREAD_LIMIT:
13489         case OMP_CLAUSE_SAFELEN:
13490         case OMP_CLAUSE_SIMDLEN:
13491           OMP_CLAUSE_OPERAND (nc, 0)
13492             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
13493                            in_decl, /*integral_constant_expression_p=*/false);
13494           break;
13495         case OMP_CLAUSE_REDUCTION:
13496           if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
13497             {
13498               tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
13499               if (TREE_CODE (placeholder) == SCOPE_REF)
13500                 {
13501                   tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
13502                                        complain, in_decl);
13503                   OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
13504                     = build_qualified_name (NULL_TREE, scope,
13505                                             TREE_OPERAND (placeholder, 1),
13506                                             false);
13507                 }
13508               else
13509                 gcc_assert (identifier_p (placeholder));
13510             }
13511           OMP_CLAUSE_OPERAND (nc, 0)
13512             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
13513                            in_decl, /*integral_constant_expression_p=*/false);
13514           break;
13515         case OMP_CLAUSE_LINEAR:
13516         case OMP_CLAUSE_ALIGNED:
13517           OMP_CLAUSE_OPERAND (nc, 0)
13518             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
13519                            in_decl, /*integral_constant_expression_p=*/false);
13520           OMP_CLAUSE_OPERAND (nc, 1)
13521             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
13522                            in_decl, /*integral_constant_expression_p=*/false);
13523           break;
13524
13525         case OMP_CLAUSE_NOWAIT:
13526         case OMP_CLAUSE_ORDERED:
13527         case OMP_CLAUSE_DEFAULT:
13528         case OMP_CLAUSE_UNTIED:
13529         case OMP_CLAUSE_MERGEABLE:
13530         case OMP_CLAUSE_INBRANCH:
13531         case OMP_CLAUSE_NOTINBRANCH:
13532         case OMP_CLAUSE_PROC_BIND:
13533         case OMP_CLAUSE_FOR:
13534         case OMP_CLAUSE_PARALLEL:
13535         case OMP_CLAUSE_SECTIONS:
13536         case OMP_CLAUSE_TASKGROUP:
13537           break;
13538         default:
13539           gcc_unreachable ();
13540         }
13541     }
13542
13543   new_clauses = nreverse (new_clauses);
13544   if (!declare_simd)
13545     new_clauses = finish_omp_clauses (new_clauses);
13546   return new_clauses;
13547 }
13548
13549 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
13550
13551 static tree
13552 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
13553                           tree in_decl)
13554 {
13555 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
13556
13557   tree purpose, value, chain;
13558
13559   if (t == NULL)
13560     return t;
13561
13562   if (TREE_CODE (t) != TREE_LIST)
13563     return tsubst_copy_and_build (t, args, complain, in_decl,
13564                                   /*function_p=*/false,
13565                                   /*integral_constant_expression_p=*/false);
13566
13567   if (t == void_list_node)
13568     return t;
13569
13570   purpose = TREE_PURPOSE (t);
13571   if (purpose)
13572     purpose = RECUR (purpose);
13573   value = TREE_VALUE (t);
13574   if (value)
13575     {
13576       if (TREE_CODE (value) != LABEL_DECL)
13577         value = RECUR (value);
13578       else
13579         {
13580           value = lookup_label (DECL_NAME (value));
13581           gcc_assert (TREE_CODE (value) == LABEL_DECL);
13582           TREE_USED (value) = 1;
13583         }
13584     }
13585   chain = TREE_CHAIN (t);
13586   if (chain && chain != void_type_node)
13587     chain = RECUR (chain);
13588   return tree_cons (purpose, value, chain);
13589 #undef RECUR
13590 }
13591
13592 /* Substitute one OMP_FOR iterator.  */
13593
13594 static void
13595 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
13596                          tree condv, tree incrv, tree *clauses,
13597                          tree args, tsubst_flags_t complain, tree in_decl,
13598                          bool integral_constant_expression_p)
13599 {
13600 #define RECUR(NODE)                             \
13601   tsubst_expr ((NODE), args, complain, in_decl, \
13602                integral_constant_expression_p)
13603   tree decl, init, cond, incr;
13604
13605   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
13606   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
13607   decl = TREE_OPERAND (init, 0);
13608   init = TREE_OPERAND (init, 1);
13609   tree decl_expr = NULL_TREE;
13610   if (init && TREE_CODE (init) == DECL_EXPR)
13611     {
13612       /* We need to jump through some hoops to handle declarations in the
13613          for-init-statement, since we might need to handle auto deduction,
13614          but we need to keep control of initialization.  */
13615       decl_expr = init;
13616       init = DECL_INITIAL (DECL_EXPR_DECL (init));
13617       decl = tsubst_decl (decl, args, complain);
13618     }
13619   else
13620     decl = RECUR (decl);
13621   init = RECUR (init);
13622
13623   tree auto_node = type_uses_auto (TREE_TYPE (decl));
13624   if (auto_node && init)
13625     TREE_TYPE (decl)
13626       = do_auto_deduction (TREE_TYPE (decl), init, auto_node);
13627
13628   gcc_assert (!type_dependent_expression_p (decl));
13629
13630   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
13631     {
13632       if (decl_expr)
13633         {
13634           /* Declare the variable, but don't let that initialize it.  */
13635           tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
13636           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
13637           RECUR (decl_expr);
13638           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
13639         }
13640
13641       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
13642       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
13643       if (TREE_CODE (incr) == MODIFY_EXPR)
13644         {
13645           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13646           tree rhs = RECUR (TREE_OPERAND (incr, 1));
13647           incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
13648                                       NOP_EXPR, rhs, complain);
13649         }
13650       else
13651         incr = RECUR (incr);
13652       TREE_VEC_ELT (declv, i) = decl;
13653       TREE_VEC_ELT (initv, i) = init;
13654       TREE_VEC_ELT (condv, i) = cond;
13655       TREE_VEC_ELT (incrv, i) = incr;
13656       return;
13657     }
13658
13659   if (decl_expr)
13660     {
13661       /* Declare and initialize the variable.  */
13662       RECUR (decl_expr);
13663       init = NULL_TREE;
13664     }
13665   else if (init)
13666     {
13667       tree c;
13668       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
13669         {
13670           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
13671                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
13672               && OMP_CLAUSE_DECL (c) == decl)
13673             break;
13674           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
13675                    && OMP_CLAUSE_DECL (c) == decl)
13676             error ("iteration variable %qD should not be firstprivate", decl);
13677           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
13678                    && OMP_CLAUSE_DECL (c) == decl)
13679             error ("iteration variable %qD should not be reduction", decl);
13680         }
13681       if (c == NULL)
13682         {
13683           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
13684           OMP_CLAUSE_DECL (c) = decl;
13685           c = finish_omp_clauses (c);
13686           if (c)
13687             {
13688               OMP_CLAUSE_CHAIN (c) = *clauses;
13689               *clauses = c;
13690             }
13691         }
13692     }
13693   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
13694   if (COMPARISON_CLASS_P (cond))
13695     {
13696       tree op0 = RECUR (TREE_OPERAND (cond, 0));
13697       tree op1 = RECUR (TREE_OPERAND (cond, 1));
13698       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
13699     }
13700   else
13701     cond = RECUR (cond);
13702   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
13703   switch (TREE_CODE (incr))
13704     {
13705     case PREINCREMENT_EXPR:
13706     case PREDECREMENT_EXPR:
13707     case POSTINCREMENT_EXPR:
13708     case POSTDECREMENT_EXPR:
13709       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
13710                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
13711       break;
13712     case MODIFY_EXPR:
13713       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
13714           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
13715         {
13716           tree rhs = TREE_OPERAND (incr, 1);
13717           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13718           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
13719           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
13720           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
13721                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
13722                                  rhs0, rhs1));
13723         }
13724       else
13725         incr = RECUR (incr);
13726       break;
13727     case MODOP_EXPR:
13728       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
13729           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
13730         {
13731           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13732           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
13733                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
13734                                  TREE_TYPE (decl), lhs,
13735                                  RECUR (TREE_OPERAND (incr, 2))));
13736         }
13737       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
13738                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
13739                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
13740         {
13741           tree rhs = TREE_OPERAND (incr, 2);
13742           tree lhs = RECUR (TREE_OPERAND (incr, 0));
13743           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
13744           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
13745           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
13746                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
13747                                  rhs0, rhs1));
13748         }
13749       else
13750         incr = RECUR (incr);
13751       break;
13752     default:
13753       incr = RECUR (incr);
13754       break;
13755     }
13756
13757   TREE_VEC_ELT (declv, i) = decl;
13758   TREE_VEC_ELT (initv, i) = init;
13759   TREE_VEC_ELT (condv, i) = cond;
13760   TREE_VEC_ELT (incrv, i) = incr;
13761 #undef RECUR
13762 }
13763
13764 /* Like tsubst_copy for expressions, etc. but also does semantic
13765    processing.  */
13766
13767 static tree
13768 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
13769              bool integral_constant_expression_p)
13770 {
13771 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13772 #define RECUR(NODE)                             \
13773   tsubst_expr ((NODE), args, complain, in_decl, \
13774                integral_constant_expression_p)
13775
13776   tree stmt, tmp;
13777   tree r;
13778   location_t loc;
13779
13780   if (t == NULL_TREE || t == error_mark_node)
13781     return t;
13782
13783   loc = input_location;
13784   if (EXPR_HAS_LOCATION (t))
13785     input_location = EXPR_LOCATION (t);
13786   if (STATEMENT_CODE_P (TREE_CODE (t)))
13787     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
13788
13789   switch (TREE_CODE (t))
13790     {
13791     case STATEMENT_LIST:
13792       {
13793         tree_stmt_iterator i;
13794         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
13795           RECUR (tsi_stmt (i));
13796         break;
13797       }
13798
13799     case CTOR_INITIALIZER:
13800       finish_mem_initializers (tsubst_initializer_list
13801                                (TREE_OPERAND (t, 0), args));
13802       break;
13803
13804     case RETURN_EXPR:
13805       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
13806       break;
13807
13808     case EXPR_STMT:
13809       tmp = RECUR (EXPR_STMT_EXPR (t));
13810       if (EXPR_STMT_STMT_EXPR_RESULT (t))
13811         finish_stmt_expr_expr (tmp, cur_stmt_expr);
13812       else
13813         finish_expr_stmt (tmp);
13814       break;
13815
13816     case USING_STMT:
13817       do_using_directive (USING_STMT_NAMESPACE (t));
13818       break;
13819
13820     case DECL_EXPR:
13821       {
13822         tree decl, pattern_decl;
13823         tree init;
13824
13825         pattern_decl = decl = DECL_EXPR_DECL (t);
13826         if (TREE_CODE (decl) == LABEL_DECL)
13827           finish_label_decl (DECL_NAME (decl));
13828         else if (TREE_CODE (decl) == USING_DECL)
13829           {
13830             tree scope = USING_DECL_SCOPE (decl);
13831             tree name = DECL_NAME (decl);
13832             tree decl;
13833
13834             scope = tsubst (scope, args, complain, in_decl);
13835             decl = lookup_qualified_name (scope, name,
13836                                           /*is_type_p=*/false,
13837                                           /*complain=*/false);
13838             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
13839               qualified_name_lookup_error (scope, name, decl, input_location);
13840             else
13841               do_local_using_decl (decl, scope, name);
13842           }
13843         else if (DECL_PACK_P (decl))
13844           {
13845             /* Don't build up decls for a variadic capture proxy, we'll
13846                instantiate the elements directly as needed.  */
13847             break;
13848           }
13849         else
13850           {
13851             init = DECL_INITIAL (decl);
13852             decl = tsubst (decl, args, complain, in_decl);
13853             if (decl != error_mark_node)
13854               {
13855                 /* By marking the declaration as instantiated, we avoid
13856                    trying to instantiate it.  Since instantiate_decl can't
13857                    handle local variables, and since we've already done
13858                    all that needs to be done, that's the right thing to
13859                    do.  */
13860                 if (VAR_P (decl))
13861                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
13862                 if (VAR_P (decl)
13863                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
13864                   /* Anonymous aggregates are a special case.  */
13865                   finish_anon_union (decl);
13866                 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
13867                   {
13868                     DECL_CONTEXT (decl) = current_function_decl;
13869                     if (DECL_NAME (decl) == this_identifier)
13870                       {
13871                         tree lam = DECL_CONTEXT (current_function_decl);
13872                         lam = CLASSTYPE_LAMBDA_EXPR (lam);
13873                         LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
13874                       }
13875                     insert_capture_proxy (decl);
13876                   }
13877                 else if (DECL_IMPLICIT_TYPEDEF_P (t))
13878                   /* We already did a pushtag.  */;
13879                 else if (TREE_CODE (decl) == FUNCTION_DECL
13880                          && DECL_OMP_DECLARE_REDUCTION_P (decl)
13881                          && DECL_FUNCTION_SCOPE_P (pattern_decl))
13882                   {
13883                     DECL_CONTEXT (decl) = NULL_TREE;
13884                     pushdecl (decl);
13885                     DECL_CONTEXT (decl) = current_function_decl;
13886                     cp_check_omp_declare_reduction (decl);
13887                   }
13888                 else
13889                   {
13890                     int const_init = false;
13891                     maybe_push_decl (decl);
13892                     if (VAR_P (decl)
13893                         && DECL_PRETTY_FUNCTION_P (decl))
13894                       {
13895                         /* For __PRETTY_FUNCTION__ we have to adjust the
13896                            initializer.  */
13897                         const char *const name
13898                           = cxx_printable_name (current_function_decl, 2);
13899                         init = cp_fname_init (name, &TREE_TYPE (decl));
13900                       }
13901                     else
13902                       init = tsubst_init (init, decl, args, complain, in_decl);
13903
13904                     if (VAR_P (decl))
13905                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
13906                                     (pattern_decl));
13907                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
13908                   }
13909               }
13910           }
13911
13912         break;
13913       }
13914
13915     case FOR_STMT:
13916       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
13917       RECUR (FOR_INIT_STMT (t));
13918       finish_for_init_stmt (stmt);
13919       tmp = RECUR (FOR_COND (t));
13920       finish_for_cond (tmp, stmt, false);
13921       tmp = RECUR (FOR_EXPR (t));
13922       finish_for_expr (tmp, stmt);
13923       RECUR (FOR_BODY (t));
13924       finish_for_stmt (stmt);
13925       break;
13926
13927     case RANGE_FOR_STMT:
13928       {
13929         tree decl, expr;
13930         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
13931         decl = RANGE_FOR_DECL (t);
13932         decl = tsubst (decl, args, complain, in_decl);
13933         maybe_push_decl (decl);
13934         expr = RECUR (RANGE_FOR_EXPR (t));
13935         stmt = cp_convert_range_for (stmt, decl, expr, RANGE_FOR_IVDEP (t));
13936         RECUR (RANGE_FOR_BODY (t));
13937         finish_for_stmt (stmt);
13938       }
13939       break;
13940
13941     case WHILE_STMT:
13942       stmt = begin_while_stmt ();
13943       tmp = RECUR (WHILE_COND (t));
13944       finish_while_stmt_cond (tmp, stmt, false);
13945       RECUR (WHILE_BODY (t));
13946       finish_while_stmt (stmt);
13947       break;
13948
13949     case DO_STMT:
13950       stmt = begin_do_stmt ();
13951       RECUR (DO_BODY (t));
13952       finish_do_body (stmt);
13953       tmp = RECUR (DO_COND (t));
13954       finish_do_stmt (tmp, stmt, false);
13955       break;
13956
13957     case IF_STMT:
13958       stmt = begin_if_stmt ();
13959       tmp = RECUR (IF_COND (t));
13960       finish_if_stmt_cond (tmp, stmt);
13961       RECUR (THEN_CLAUSE (t));
13962       finish_then_clause (stmt);
13963
13964       if (ELSE_CLAUSE (t))
13965         {
13966           begin_else_clause (stmt);
13967           RECUR (ELSE_CLAUSE (t));
13968           finish_else_clause (stmt);
13969         }
13970
13971       finish_if_stmt (stmt);
13972       break;
13973
13974     case BIND_EXPR:
13975       if (BIND_EXPR_BODY_BLOCK (t))
13976         stmt = begin_function_body ();
13977       else
13978         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
13979                                     ? BCS_TRY_BLOCK : 0);
13980
13981       RECUR (BIND_EXPR_BODY (t));
13982
13983       if (BIND_EXPR_BODY_BLOCK (t))
13984         finish_function_body (stmt);
13985       else
13986         finish_compound_stmt (stmt);
13987       break;
13988
13989     case BREAK_STMT:
13990       finish_break_stmt ();
13991       break;
13992
13993     case CONTINUE_STMT:
13994       finish_continue_stmt ();
13995       break;
13996
13997     case SWITCH_STMT:
13998       stmt = begin_switch_stmt ();
13999       tmp = RECUR (SWITCH_STMT_COND (t));
14000       finish_switch_cond (tmp, stmt);
14001       RECUR (SWITCH_STMT_BODY (t));
14002       finish_switch_stmt (stmt);
14003       break;
14004
14005     case CASE_LABEL_EXPR:
14006       {
14007         tree low = RECUR (CASE_LOW (t));
14008         tree high = RECUR (CASE_HIGH (t));
14009         finish_case_label (EXPR_LOCATION (t), low, high);
14010       }
14011       break;
14012
14013     case LABEL_EXPR:
14014       {
14015         tree decl = LABEL_EXPR_LABEL (t);
14016         tree label;
14017
14018         label = finish_label_stmt (DECL_NAME (decl));
14019         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
14020           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
14021       }
14022       break;
14023
14024     case GOTO_EXPR:
14025       tmp = GOTO_DESTINATION (t);
14026       if (TREE_CODE (tmp) != LABEL_DECL)
14027         /* Computed goto's must be tsubst'd into.  On the other hand,
14028            non-computed gotos must not be; the identifier in question
14029            will have no binding.  */
14030         tmp = RECUR (tmp);
14031       else
14032         tmp = DECL_NAME (tmp);
14033       finish_goto_stmt (tmp);
14034       break;
14035
14036     case ASM_EXPR:
14037       {
14038         tree string = RECUR (ASM_STRING (t));
14039         tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
14040                                                  complain, in_decl);
14041         tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
14042                                                 complain, in_decl);
14043         tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
14044                                                   complain, in_decl);
14045         tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
14046                                                 complain, in_decl);
14047         tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
14048                                clobbers, labels);
14049         tree asm_expr = tmp;
14050         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
14051           asm_expr = TREE_OPERAND (asm_expr, 0);
14052         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
14053       }
14054       break;
14055
14056     case TRY_BLOCK:
14057       if (CLEANUP_P (t))
14058         {
14059           stmt = begin_try_block ();
14060           RECUR (TRY_STMTS (t));
14061           finish_cleanup_try_block (stmt);
14062           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
14063         }
14064       else
14065         {
14066           tree compound_stmt = NULL_TREE;
14067
14068           if (FN_TRY_BLOCK_P (t))
14069             stmt = begin_function_try_block (&compound_stmt);
14070           else
14071             stmt = begin_try_block ();
14072
14073           RECUR (TRY_STMTS (t));
14074
14075           if (FN_TRY_BLOCK_P (t))
14076             finish_function_try_block (stmt);
14077           else
14078             finish_try_block (stmt);
14079
14080           RECUR (TRY_HANDLERS (t));
14081           if (FN_TRY_BLOCK_P (t))
14082             finish_function_handler_sequence (stmt, compound_stmt);
14083           else
14084             finish_handler_sequence (stmt);
14085         }
14086       break;
14087
14088     case HANDLER:
14089       {
14090         tree decl = HANDLER_PARMS (t);
14091
14092         if (decl)
14093           {
14094             decl = tsubst (decl, args, complain, in_decl);
14095             /* Prevent instantiate_decl from trying to instantiate
14096                this variable.  We've already done all that needs to be
14097                done.  */
14098             if (decl != error_mark_node)
14099               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
14100           }
14101         stmt = begin_handler ();
14102         finish_handler_parms (decl, stmt);
14103         RECUR (HANDLER_BODY (t));
14104         finish_handler (stmt);
14105       }
14106       break;
14107
14108     case TAG_DEFN:
14109       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
14110       if (CLASS_TYPE_P (tmp))
14111         {
14112           /* Local classes are not independent templates; they are
14113              instantiated along with their containing function.  And this
14114              way we don't have to deal with pushing out of one local class
14115              to instantiate a member of another local class.  */
14116           tree fn;
14117           /* Closures are handled by the LAMBDA_EXPR.  */
14118           gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
14119           complete_type (tmp);
14120           for (fn = TYPE_METHODS (tmp); fn; fn = DECL_CHAIN (fn))
14121             if (!DECL_ARTIFICIAL (fn))
14122               instantiate_decl (fn, /*defer_ok*/0, /*expl_inst_class*/false);
14123         }
14124       break;
14125
14126     case STATIC_ASSERT:
14127       {
14128         tree condition;
14129
14130         ++c_inhibit_evaluation_warnings;
14131         condition = 
14132           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
14133                        args,
14134                        complain, in_decl,
14135                        /*integral_constant_expression_p=*/true);
14136         --c_inhibit_evaluation_warnings;
14137
14138         finish_static_assert (condition,
14139                               STATIC_ASSERT_MESSAGE (t),
14140                               STATIC_ASSERT_SOURCE_LOCATION (t),
14141                               /*member_p=*/false);
14142       }
14143       break;
14144
14145     case OMP_PARALLEL:
14146       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), false,
14147                                 args, complain, in_decl);
14148       stmt = begin_omp_parallel ();
14149       RECUR (OMP_PARALLEL_BODY (t));
14150       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
14151         = OMP_PARALLEL_COMBINED (t);
14152       break;
14153
14154     case OMP_TASK:
14155       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), false,
14156                                 args, complain, in_decl);
14157       stmt = begin_omp_task ();
14158       RECUR (OMP_TASK_BODY (t));
14159       finish_omp_task (tmp, stmt);
14160       break;
14161
14162     case OMP_FOR:
14163     case OMP_SIMD:
14164     case CILK_SIMD:
14165     case CILK_FOR:
14166     case OMP_DISTRIBUTE:
14167       {
14168         tree clauses, body, pre_body;
14169         tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
14170         tree incrv = NULL_TREE;
14171         int i;
14172
14173         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), false,
14174                                       args, complain, in_decl);
14175         if (OMP_FOR_INIT (t) != NULL_TREE)
14176           {
14177             declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14178             initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14179             condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14180             incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
14181           }
14182
14183         stmt = begin_omp_structured_block ();
14184
14185         pre_body = push_stmt_list ();
14186         RECUR (OMP_FOR_PRE_BODY (t));
14187         pre_body = pop_stmt_list (pre_body);
14188
14189         if (OMP_FOR_INIT (t) != NULL_TREE)
14190           for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
14191             tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
14192                                      &clauses, args, complain, in_decl,
14193                                      integral_constant_expression_p);
14194
14195         body = push_stmt_list ();
14196         RECUR (OMP_FOR_BODY (t));
14197         body = pop_stmt_list (body);
14198
14199         if (OMP_FOR_INIT (t) != NULL_TREE)
14200           t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv, initv,
14201                               condv, incrv, body, pre_body, clauses);
14202         else
14203           {
14204             t = make_node (TREE_CODE (t));
14205             TREE_TYPE (t) = void_type_node;
14206             OMP_FOR_BODY (t) = body;
14207             OMP_FOR_PRE_BODY (t) = pre_body;
14208             OMP_FOR_CLAUSES (t) = clauses;
14209             SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
14210             add_stmt (t);
14211           }
14212
14213         add_stmt (finish_omp_structured_block (stmt));
14214       }
14215       break;
14216
14217     case OMP_SECTIONS:
14218     case OMP_SINGLE:
14219     case OMP_TEAMS:
14220       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false,
14221                                 args, complain, in_decl);
14222       stmt = push_stmt_list ();
14223       RECUR (OMP_BODY (t));
14224       stmt = pop_stmt_list (stmt);
14225
14226       t = copy_node (t);
14227       OMP_BODY (t) = stmt;
14228       OMP_CLAUSES (t) = tmp;
14229       add_stmt (t);
14230       break;
14231
14232     case OMP_TARGET_DATA:
14233     case OMP_TARGET:
14234       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false,
14235                                 args, complain, in_decl);
14236       keep_next_level (true);
14237       stmt = begin_omp_structured_block ();
14238
14239       RECUR (OMP_BODY (t));
14240       stmt = finish_omp_structured_block (stmt);
14241
14242       t = copy_node (t);
14243       OMP_BODY (t) = stmt;
14244       OMP_CLAUSES (t) = tmp;
14245       add_stmt (t);
14246       break;
14247
14248     case OMP_TARGET_UPDATE:
14249       tmp = tsubst_omp_clauses (OMP_TARGET_UPDATE_CLAUSES (t), false,
14250                                 args, complain, in_decl);
14251       t = copy_node (t);
14252       OMP_CLAUSES (t) = tmp;
14253       add_stmt (t);
14254       break;
14255
14256     case OMP_SECTION:
14257     case OMP_CRITICAL:
14258     case OMP_MASTER:
14259     case OMP_TASKGROUP:
14260     case OMP_ORDERED:
14261       stmt = push_stmt_list ();
14262       RECUR (OMP_BODY (t));
14263       stmt = pop_stmt_list (stmt);
14264
14265       t = copy_node (t);
14266       OMP_BODY (t) = stmt;
14267       add_stmt (t);
14268       break;
14269
14270     case OMP_ATOMIC:
14271       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
14272       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
14273         {
14274           tree op1 = TREE_OPERAND (t, 1);
14275           tree rhs1 = NULL_TREE;
14276           tree lhs, rhs;
14277           if (TREE_CODE (op1) == COMPOUND_EXPR)
14278             {
14279               rhs1 = RECUR (TREE_OPERAND (op1, 0));
14280               op1 = TREE_OPERAND (op1, 1);
14281             }
14282           lhs = RECUR (TREE_OPERAND (op1, 0));
14283           rhs = RECUR (TREE_OPERAND (op1, 1));
14284           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
14285                              NULL_TREE, NULL_TREE, rhs1,
14286                              OMP_ATOMIC_SEQ_CST (t));
14287         }
14288       else
14289         {
14290           tree op1 = TREE_OPERAND (t, 1);
14291           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
14292           tree rhs1 = NULL_TREE;
14293           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
14294           enum tree_code opcode = NOP_EXPR;
14295           if (code == OMP_ATOMIC_READ)
14296             {
14297               v = RECUR (TREE_OPERAND (op1, 0));
14298               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
14299             }
14300           else if (code == OMP_ATOMIC_CAPTURE_OLD
14301                    || code == OMP_ATOMIC_CAPTURE_NEW)
14302             {
14303               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
14304               v = RECUR (TREE_OPERAND (op1, 0));
14305               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
14306               if (TREE_CODE (op11) == COMPOUND_EXPR)
14307                 {
14308                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
14309                   op11 = TREE_OPERAND (op11, 1);
14310                 }
14311               lhs = RECUR (TREE_OPERAND (op11, 0));
14312               rhs = RECUR (TREE_OPERAND (op11, 1));
14313               opcode = TREE_CODE (op11);
14314               if (opcode == MODIFY_EXPR)
14315                 opcode = NOP_EXPR;
14316             }
14317           else
14318             {
14319               code = OMP_ATOMIC;
14320               lhs = RECUR (TREE_OPERAND (op1, 0));
14321               rhs = RECUR (TREE_OPERAND (op1, 1));
14322             }
14323           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
14324                              OMP_ATOMIC_SEQ_CST (t));
14325         }
14326       break;
14327
14328     case TRANSACTION_EXPR:
14329       {
14330         int flags = 0;
14331         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
14332         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
14333
14334         if (TRANSACTION_EXPR_IS_STMT (t))
14335           {
14336             tree body = TRANSACTION_EXPR_BODY (t);
14337             tree noex = NULL_TREE;
14338             if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
14339               {
14340                 noex = MUST_NOT_THROW_COND (body);
14341                 if (noex == NULL_TREE)
14342                   noex = boolean_true_node;
14343                 body = TREE_OPERAND (body, 0);
14344               }
14345             stmt = begin_transaction_stmt (input_location, NULL, flags);
14346             RECUR (body);
14347             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
14348           }
14349         else
14350           {
14351             stmt = build_transaction_expr (EXPR_LOCATION (t),
14352                                            RECUR (TRANSACTION_EXPR_BODY (t)),
14353                                            flags, NULL_TREE);
14354             RETURN (stmt);
14355           }
14356       }
14357       break;
14358
14359     case MUST_NOT_THROW_EXPR:
14360       {
14361         tree op0 = RECUR (TREE_OPERAND (t, 0));
14362         tree cond = RECUR (MUST_NOT_THROW_COND (t));
14363         RETURN (build_must_not_throw_expr (op0, cond));
14364       }
14365
14366     case EXPR_PACK_EXPANSION:
14367       error ("invalid use of pack expansion expression");
14368       RETURN (error_mark_node);
14369
14370     case NONTYPE_ARGUMENT_PACK:
14371       error ("use %<...%> to expand argument pack");
14372       RETURN (error_mark_node);
14373
14374     case CILK_SPAWN_STMT:
14375       cfun->calls_cilk_spawn = 1;
14376       RETURN (build_cilk_spawn (EXPR_LOCATION (t), RECUR (CILK_SPAWN_FN (t))));
14377
14378     case CILK_SYNC_STMT:
14379       RETURN (build_cilk_sync ());
14380
14381     case COMPOUND_EXPR:
14382       tmp = RECUR (TREE_OPERAND (t, 0));
14383       if (tmp == NULL_TREE)
14384         /* If the first operand was a statement, we're done with it.  */
14385         RETURN (RECUR (TREE_OPERAND (t, 1)));
14386       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
14387                                     RECUR (TREE_OPERAND (t, 1)),
14388                                     complain));
14389
14390     case ANNOTATE_EXPR:
14391       tmp = RECUR (TREE_OPERAND (t, 0));
14392       RETURN (build2_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
14393                           TREE_TYPE (tmp), tmp, RECUR (TREE_OPERAND (t, 1))));
14394
14395     default:
14396       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
14397
14398       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
14399                                     /*function_p=*/false,
14400                                     integral_constant_expression_p));
14401     }
14402
14403   RETURN (NULL_TREE);
14404  out:
14405   input_location = loc;
14406   return r;
14407 #undef RECUR
14408 #undef RETURN
14409 }
14410
14411 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
14412    function.  For description of the body see comment above
14413    cp_parser_omp_declare_reduction_exprs.  */
14414
14415 static void
14416 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14417 {
14418   if (t == NULL_TREE || t == error_mark_node)
14419     return;
14420
14421   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
14422
14423   tree_stmt_iterator tsi;
14424   int i;
14425   tree stmts[7];
14426   memset (stmts, 0, sizeof stmts);
14427   for (i = 0, tsi = tsi_start (t);
14428        i < 7 && !tsi_end_p (tsi);
14429        i++, tsi_next (&tsi))
14430     stmts[i] = tsi_stmt (tsi);
14431   gcc_assert (tsi_end_p (tsi));
14432
14433   if (i >= 3)
14434     {
14435       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
14436                   && TREE_CODE (stmts[1]) == DECL_EXPR);
14437       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
14438                              args, complain, in_decl);
14439       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
14440                             args, complain, in_decl);
14441       DECL_CONTEXT (omp_out) = current_function_decl;
14442       DECL_CONTEXT (omp_in) = current_function_decl;
14443       keep_next_level (true);
14444       tree block = begin_omp_structured_block ();
14445       tsubst_expr (stmts[2], args, complain, in_decl, false);
14446       block = finish_omp_structured_block (block);
14447       block = maybe_cleanup_point_expr_void (block);
14448       add_decl_expr (omp_out);
14449       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
14450         TREE_NO_WARNING (omp_out) = 1;
14451       add_decl_expr (omp_in);
14452       finish_expr_stmt (block);
14453     }
14454   if (i >= 6)
14455     {
14456       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
14457                   && TREE_CODE (stmts[4]) == DECL_EXPR);
14458       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
14459                               args, complain, in_decl);
14460       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
14461                               args, complain, in_decl);
14462       DECL_CONTEXT (omp_priv) = current_function_decl;
14463       DECL_CONTEXT (omp_orig) = current_function_decl;
14464       keep_next_level (true);
14465       tree block = begin_omp_structured_block ();
14466       tsubst_expr (stmts[5], args, complain, in_decl, false);
14467       block = finish_omp_structured_block (block);
14468       block = maybe_cleanup_point_expr_void (block);
14469       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
14470       add_decl_expr (omp_priv);
14471       add_decl_expr (omp_orig);
14472       finish_expr_stmt (block);
14473       if (i == 7)
14474         add_decl_expr (omp_orig);
14475     }
14476 }
14477
14478 /* T is a postfix-expression that is not being used in a function
14479    call.  Return the substituted version of T.  */
14480
14481 static tree
14482 tsubst_non_call_postfix_expression (tree t, tree args,
14483                                     tsubst_flags_t complain,
14484                                     tree in_decl)
14485 {
14486   if (TREE_CODE (t) == SCOPE_REF)
14487     t = tsubst_qualified_id (t, args, complain, in_decl,
14488                              /*done=*/false, /*address_p=*/false);
14489   else
14490     t = tsubst_copy_and_build (t, args, complain, in_decl,
14491                                /*function_p=*/false,
14492                                /*integral_constant_expression_p=*/false);
14493
14494   return t;
14495 }
14496
14497 /* Like tsubst but deals with expressions and performs semantic
14498    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
14499
14500 tree
14501 tsubst_copy_and_build (tree t,
14502                        tree args,
14503                        tsubst_flags_t complain,
14504                        tree in_decl,
14505                        bool function_p,
14506                        bool integral_constant_expression_p)
14507 {
14508 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
14509 #define RECUR(NODE)                                             \
14510   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
14511                          /*function_p=*/false,                  \
14512                          integral_constant_expression_p)
14513
14514   tree retval, op1;
14515   location_t loc;
14516
14517   if (t == NULL_TREE || t == error_mark_node)
14518     return t;
14519
14520   loc = input_location;
14521   if (EXPR_HAS_LOCATION (t))
14522     input_location = EXPR_LOCATION (t);
14523
14524   /* N3276 decltype magic only applies to calls at the top level or on the
14525      right side of a comma.  */
14526   tsubst_flags_t decltype_flag = (complain & tf_decltype);
14527   complain &= ~tf_decltype;
14528
14529   switch (TREE_CODE (t))
14530     {
14531     case USING_DECL:
14532       t = DECL_NAME (t);
14533       /* Fall through.  */
14534     case IDENTIFIER_NODE:
14535       {
14536         tree decl;
14537         cp_id_kind idk;
14538         bool non_integral_constant_expression_p;
14539         const char *error_msg;
14540
14541         if (IDENTIFIER_TYPENAME_P (t))
14542           {
14543             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14544             t = mangle_conv_op_name_for_type (new_type);
14545           }
14546
14547         /* Look up the name.  */
14548         decl = lookup_name (t);
14549
14550         /* By convention, expressions use ERROR_MARK_NODE to indicate
14551            failure, not NULL_TREE.  */
14552         if (decl == NULL_TREE)
14553           decl = error_mark_node;
14554
14555         decl = finish_id_expression (t, decl, NULL_TREE,
14556                                      &idk,
14557                                      integral_constant_expression_p,
14558           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
14559                                      &non_integral_constant_expression_p,
14560                                      /*template_p=*/false,
14561                                      /*done=*/true,
14562                                      /*address_p=*/false,
14563                                      /*template_arg_p=*/false,
14564                                      &error_msg,
14565                                      input_location);
14566         if (error_msg)
14567           error (error_msg);
14568         if (!function_p && identifier_p (decl))
14569           {
14570             if (complain & tf_error)
14571               unqualified_name_lookup_error (decl);
14572             decl = error_mark_node;
14573           }
14574         RETURN (decl);
14575       }
14576
14577     case TEMPLATE_ID_EXPR:
14578       {
14579         tree object;
14580         tree templ = RECUR (TREE_OPERAND (t, 0));
14581         tree targs = TREE_OPERAND (t, 1);
14582
14583         if (targs)
14584           targs = tsubst_template_args (targs, args, complain, in_decl);
14585
14586         if (TREE_CODE (templ) == COMPONENT_REF)
14587           {
14588             object = TREE_OPERAND (templ, 0);
14589             templ = TREE_OPERAND (templ, 1);
14590           }
14591         else
14592           object = NULL_TREE;
14593         templ = lookup_template_function (templ, targs);
14594
14595         if (object)
14596           RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
14597                          object, templ, NULL_TREE));
14598         else
14599           RETURN (baselink_for_fns (templ));
14600       }
14601
14602     case INDIRECT_REF:
14603       {
14604         tree r = RECUR (TREE_OPERAND (t, 0));
14605
14606         if (REFERENCE_REF_P (t))
14607           {
14608             /* A type conversion to reference type will be enclosed in
14609                such an indirect ref, but the substitution of the cast
14610                will have also added such an indirect ref.  */
14611             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
14612               r = convert_from_reference (r);
14613           }
14614         else
14615           r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
14616                                     complain|decltype_flag);
14617         RETURN (r);
14618       }
14619
14620     case NOP_EXPR:
14621       {
14622         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14623         tree op0 = RECUR (TREE_OPERAND (t, 0));
14624         RETURN (build_nop (type, op0));
14625       }
14626
14627     case IMPLICIT_CONV_EXPR:
14628       {
14629         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14630         tree expr = RECUR (TREE_OPERAND (t, 0));
14631         int flags = LOOKUP_IMPLICIT;
14632         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
14633           flags = LOOKUP_NORMAL;
14634         RETURN (perform_implicit_conversion_flags (type, expr, complain,
14635                                                   flags));
14636       }
14637
14638     case CONVERT_EXPR:
14639       {
14640         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14641         tree op0 = RECUR (TREE_OPERAND (t, 0));
14642         RETURN (build1 (CONVERT_EXPR, type, op0));
14643       }
14644
14645     case CAST_EXPR:
14646     case REINTERPRET_CAST_EXPR:
14647     case CONST_CAST_EXPR:
14648     case DYNAMIC_CAST_EXPR:
14649     case STATIC_CAST_EXPR:
14650       {
14651         tree type;
14652         tree op, r = NULL_TREE;
14653
14654         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14655         if (integral_constant_expression_p
14656             && !cast_valid_in_integral_constant_expression_p (type))
14657           {
14658             if (complain & tf_error)
14659               error ("a cast to a type other than an integral or "
14660                      "enumeration type cannot appear in a constant-expression");
14661             RETURN (error_mark_node);
14662           }
14663
14664         op = RECUR (TREE_OPERAND (t, 0));
14665
14666         warning_sentinel s(warn_useless_cast);
14667         switch (TREE_CODE (t))
14668           {
14669           case CAST_EXPR:
14670             r = build_functional_cast (type, op, complain);
14671             break;
14672           case REINTERPRET_CAST_EXPR:
14673             r = build_reinterpret_cast (type, op, complain);
14674             break;
14675           case CONST_CAST_EXPR:
14676             r = build_const_cast (type, op, complain);
14677             break;
14678           case DYNAMIC_CAST_EXPR:
14679             r = build_dynamic_cast (type, op, complain);
14680             break;
14681           case STATIC_CAST_EXPR:
14682             r = build_static_cast (type, op, complain);
14683             break;
14684           default:
14685             gcc_unreachable ();
14686           }
14687
14688         RETURN (r);
14689       }
14690
14691     case POSTDECREMENT_EXPR:
14692     case POSTINCREMENT_EXPR:
14693       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
14694                                                 args, complain, in_decl);
14695       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
14696                                 complain|decltype_flag));
14697
14698     case PREDECREMENT_EXPR:
14699     case PREINCREMENT_EXPR:
14700     case NEGATE_EXPR:
14701     case BIT_NOT_EXPR:
14702     case ABS_EXPR:
14703     case TRUTH_NOT_EXPR:
14704     case UNARY_PLUS_EXPR:  /* Unary + */
14705     case REALPART_EXPR:
14706     case IMAGPART_EXPR:
14707       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
14708                                 RECUR (TREE_OPERAND (t, 0)),
14709                                 complain|decltype_flag));
14710
14711     case FIX_TRUNC_EXPR:
14712       RETURN (cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
14713                                  0, complain));
14714
14715     case ADDR_EXPR:
14716       op1 = TREE_OPERAND (t, 0);
14717       if (TREE_CODE (op1) == LABEL_DECL)
14718         RETURN (finish_label_address_expr (DECL_NAME (op1),
14719                                           EXPR_LOCATION (op1)));
14720       if (TREE_CODE (op1) == SCOPE_REF)
14721         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
14722                                    /*done=*/true, /*address_p=*/true);
14723       else
14724         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
14725                                                   in_decl);
14726       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
14727                                 complain|decltype_flag));
14728
14729     case PLUS_EXPR:
14730     case MINUS_EXPR:
14731     case MULT_EXPR:
14732     case TRUNC_DIV_EXPR:
14733     case CEIL_DIV_EXPR:
14734     case FLOOR_DIV_EXPR:
14735     case ROUND_DIV_EXPR:
14736     case EXACT_DIV_EXPR:
14737     case BIT_AND_EXPR:
14738     case BIT_IOR_EXPR:
14739     case BIT_XOR_EXPR:
14740     case TRUNC_MOD_EXPR:
14741     case FLOOR_MOD_EXPR:
14742     case TRUTH_ANDIF_EXPR:
14743     case TRUTH_ORIF_EXPR:
14744     case TRUTH_AND_EXPR:
14745     case TRUTH_OR_EXPR:
14746     case RSHIFT_EXPR:
14747     case LSHIFT_EXPR:
14748     case RROTATE_EXPR:
14749     case LROTATE_EXPR:
14750     case EQ_EXPR:
14751     case NE_EXPR:
14752     case MAX_EXPR:
14753     case MIN_EXPR:
14754     case LE_EXPR:
14755     case GE_EXPR:
14756     case LT_EXPR:
14757     case GT_EXPR:
14758     case MEMBER_REF:
14759     case DOTSTAR_EXPR:
14760       {
14761         warning_sentinel s1(warn_type_limits);
14762         warning_sentinel s2(warn_div_by_zero);
14763         tree op0 = RECUR (TREE_OPERAND (t, 0));
14764         tree op1 = RECUR (TREE_OPERAND (t, 1));
14765         tree r = build_x_binary_op
14766           (input_location, TREE_CODE (t),
14767            op0,
14768            (TREE_NO_WARNING (TREE_OPERAND (t, 0))
14769             ? ERROR_MARK
14770             : TREE_CODE (TREE_OPERAND (t, 0))),
14771            op1,
14772            (TREE_NO_WARNING (TREE_OPERAND (t, 1))
14773             ? ERROR_MARK
14774             : TREE_CODE (TREE_OPERAND (t, 1))),
14775            /*overload=*/NULL,
14776            complain|decltype_flag);
14777         if (EXPR_P (r) && TREE_NO_WARNING (t))
14778           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
14779
14780         RETURN (r);
14781       }
14782
14783     case POINTER_PLUS_EXPR:
14784       {
14785         tree op0 = RECUR (TREE_OPERAND (t, 0));
14786         tree op1 = RECUR (TREE_OPERAND (t, 1));
14787         return fold_build_pointer_plus (op0, op1);
14788       }
14789
14790     case SCOPE_REF:
14791       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
14792                                   /*address_p=*/false));
14793     case ARRAY_REF:
14794       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
14795                                                 args, complain, in_decl);
14796       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
14797                                  RECUR (TREE_OPERAND (t, 1)),
14798                                  complain|decltype_flag));
14799
14800     case ARRAY_NOTATION_REF:
14801       {
14802         tree start_index, length, stride;
14803         op1 = tsubst_non_call_postfix_expression (ARRAY_NOTATION_ARRAY (t),
14804                                                   args, complain, in_decl);
14805         start_index = RECUR (ARRAY_NOTATION_START (t));
14806         length = RECUR (ARRAY_NOTATION_LENGTH (t));
14807         stride = RECUR (ARRAY_NOTATION_STRIDE (t));
14808         RETURN (build_array_notation_ref (EXPR_LOCATION (t), op1, start_index,
14809                                           length, stride, TREE_TYPE (op1)));
14810       }
14811     case SIZEOF_EXPR:
14812       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
14813         RETURN (tsubst_copy (t, args, complain, in_decl));
14814       /* Fall through */
14815       
14816     case ALIGNOF_EXPR:
14817       {
14818         tree r;
14819
14820         op1 = TREE_OPERAND (t, 0);
14821         if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
14822           op1 = TREE_TYPE (op1);
14823         if (!args)
14824           {
14825             /* When there are no ARGS, we are trying to evaluate a
14826                non-dependent expression from the parser.  Trying to do
14827                the substitutions may not work.  */
14828             if (!TYPE_P (op1))
14829               op1 = TREE_TYPE (op1);
14830           }
14831         else
14832           {
14833             ++cp_unevaluated_operand;
14834             ++c_inhibit_evaluation_warnings;
14835             if (TYPE_P (op1))
14836               op1 = tsubst (op1, args, complain, in_decl);
14837             else
14838               op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
14839                                            /*function_p=*/false,
14840                                            /*integral_constant_expression_p=*/
14841                                            false);
14842             --cp_unevaluated_operand;
14843             --c_inhibit_evaluation_warnings;
14844           }
14845         if (TYPE_P (op1))
14846           r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
14847                                           complain & tf_error);
14848         else
14849           r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
14850                                           complain & tf_error);
14851         if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
14852           {
14853             if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
14854               {
14855                 if (!processing_template_decl && TYPE_P (op1))
14856                   {
14857                     r = build_min (SIZEOF_EXPR, size_type_node,
14858                                    build1 (NOP_EXPR, op1, error_mark_node));
14859                     SIZEOF_EXPR_TYPE_P (r) = 1;
14860                   }
14861                 else
14862                   r = build_min (SIZEOF_EXPR, size_type_node, op1);
14863                 TREE_SIDE_EFFECTS (r) = 0;
14864                 TREE_READONLY (r) = 1;
14865               }
14866             SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
14867           }
14868         RETURN (r);
14869       }
14870
14871     case AT_ENCODE_EXPR:
14872       {
14873         op1 = TREE_OPERAND (t, 0);
14874         ++cp_unevaluated_operand;
14875         ++c_inhibit_evaluation_warnings;
14876         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
14877                                      /*function_p=*/false,
14878                                      /*integral_constant_expression_p=*/false);
14879         --cp_unevaluated_operand;
14880         --c_inhibit_evaluation_warnings;
14881         RETURN (objc_build_encode_expr (op1));
14882       }
14883
14884     case NOEXCEPT_EXPR:
14885       op1 = TREE_OPERAND (t, 0);
14886       ++cp_unevaluated_operand;
14887       ++c_inhibit_evaluation_warnings;
14888       ++cp_noexcept_operand;
14889       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
14890                                    /*function_p=*/false,
14891                                    /*integral_constant_expression_p=*/false);
14892       --cp_unevaluated_operand;
14893       --c_inhibit_evaluation_warnings;
14894       --cp_noexcept_operand;
14895       RETURN (finish_noexcept_expr (op1, complain));
14896
14897     case MODOP_EXPR:
14898       {
14899         warning_sentinel s(warn_div_by_zero);
14900         tree lhs = RECUR (TREE_OPERAND (t, 0));
14901         tree rhs = RECUR (TREE_OPERAND (t, 2));
14902         tree r = build_x_modify_expr
14903           (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
14904            complain|decltype_flag);
14905         /* TREE_NO_WARNING must be set if either the expression was
14906            parenthesized or it uses an operator such as >>= rather
14907            than plain assignment.  In the former case, it was already
14908            set and must be copied.  In the latter case,
14909            build_x_modify_expr sets it and it must not be reset
14910            here.  */
14911         if (TREE_NO_WARNING (t))
14912           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
14913
14914         RETURN (r);
14915       }
14916
14917     case ARROW_EXPR:
14918       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
14919                                                 args, complain, in_decl);
14920       /* Remember that there was a reference to this entity.  */
14921       if (DECL_P (op1))
14922         mark_used (op1);
14923       RETURN (build_x_arrow (input_location, op1, complain));
14924
14925     case NEW_EXPR:
14926       {
14927         tree placement = RECUR (TREE_OPERAND (t, 0));
14928         tree init = RECUR (TREE_OPERAND (t, 3));
14929         vec<tree, va_gc> *placement_vec;
14930         vec<tree, va_gc> *init_vec;
14931         tree ret;
14932
14933         if (placement == NULL_TREE)
14934           placement_vec = NULL;
14935         else
14936           {
14937             placement_vec = make_tree_vector ();
14938             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
14939               vec_safe_push (placement_vec, TREE_VALUE (placement));
14940           }
14941
14942         /* If there was an initializer in the original tree, but it
14943            instantiated to an empty list, then we should pass a
14944            non-NULL empty vector to tell build_new that it was an
14945            empty initializer() rather than no initializer.  This can
14946            only happen when the initializer is a pack expansion whose
14947            parameter packs are of length zero.  */
14948         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
14949           init_vec = NULL;
14950         else
14951           {
14952             init_vec = make_tree_vector ();
14953             if (init == void_node)
14954               gcc_assert (init_vec != NULL);
14955             else
14956               {
14957                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
14958                   vec_safe_push (init_vec, TREE_VALUE (init));
14959               }
14960           }
14961
14962         tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
14963         tree op2 = RECUR (TREE_OPERAND (t, 2));
14964         ret = build_new (&placement_vec, op1, op2, &init_vec,
14965                          NEW_EXPR_USE_GLOBAL (t),
14966                          complain);
14967
14968         if (placement_vec != NULL)
14969           release_tree_vector (placement_vec);
14970         if (init_vec != NULL)
14971           release_tree_vector (init_vec);
14972
14973         RETURN (ret);
14974       }
14975
14976     case DELETE_EXPR:
14977       {
14978         tree op0 = RECUR (TREE_OPERAND (t, 0));
14979         tree op1 = RECUR (TREE_OPERAND (t, 1));
14980         RETURN (delete_sanity (op0, op1,
14981                                DELETE_EXPR_USE_VEC (t),
14982                                DELETE_EXPR_USE_GLOBAL (t),
14983                                complain));
14984       }
14985
14986     case COMPOUND_EXPR:
14987       {
14988         tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
14989                                           complain & ~tf_decltype, in_decl,
14990                                           /*function_p=*/false,
14991                                           integral_constant_expression_p);
14992         RETURN (build_x_compound_expr (EXPR_LOCATION (t),
14993                                        op0,
14994                                        RECUR (TREE_OPERAND (t, 1)),
14995                                        complain|decltype_flag));
14996       }
14997
14998     case CALL_EXPR:
14999       {
15000         tree function;
15001         vec<tree, va_gc> *call_args;
15002         unsigned int nargs, i;
15003         bool qualified_p;
15004         bool koenig_p;
15005         tree ret;
15006
15007         function = CALL_EXPR_FN (t);
15008         /* When we parsed the expression,  we determined whether or
15009            not Koenig lookup should be performed.  */
15010         koenig_p = KOENIG_LOOKUP_P (t);
15011         if (TREE_CODE (function) == SCOPE_REF)
15012           {
15013             qualified_p = true;
15014             function = tsubst_qualified_id (function, args, complain, in_decl,
15015                                             /*done=*/false,
15016                                             /*address_p=*/false);
15017           }
15018         else if (koenig_p && identifier_p (function))
15019           {
15020             /* Do nothing; calling tsubst_copy_and_build on an identifier
15021                would incorrectly perform unqualified lookup again.
15022
15023                Note that we can also have an IDENTIFIER_NODE if the earlier
15024                unqualified lookup found a member function; in that case
15025                koenig_p will be false and we do want to do the lookup
15026                again to find the instantiated member function.
15027
15028                FIXME but doing that causes c++/15272, so we need to stop
15029                using IDENTIFIER_NODE in that situation.  */
15030             qualified_p = false;
15031           }
15032         else
15033           {
15034             if (TREE_CODE (function) == COMPONENT_REF)
15035               {
15036                 tree op = TREE_OPERAND (function, 1);
15037
15038                 qualified_p = (TREE_CODE (op) == SCOPE_REF
15039                                || (BASELINK_P (op)
15040                                    && BASELINK_QUALIFIED_P (op)));
15041               }
15042             else
15043               qualified_p = false;
15044
15045             if (TREE_CODE (function) == ADDR_EXPR
15046                 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
15047               /* Avoid error about taking the address of a constructor.  */
15048               function = TREE_OPERAND (function, 0);
15049
15050             function = tsubst_copy_and_build (function, args, complain,
15051                                               in_decl,
15052                                               !qualified_p,
15053                                               integral_constant_expression_p);
15054
15055             if (BASELINK_P (function))
15056               qualified_p = true;
15057           }
15058
15059         nargs = call_expr_nargs (t);
15060         call_args = make_tree_vector ();
15061         for (i = 0; i < nargs; ++i)
15062           {
15063             tree arg = CALL_EXPR_ARG (t, i);
15064
15065             if (!PACK_EXPANSION_P (arg))
15066               vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
15067             else
15068               {
15069                 /* Expand the pack expansion and push each entry onto
15070                    CALL_ARGS.  */
15071                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
15072                 if (TREE_CODE (arg) == TREE_VEC)
15073                   {
15074                     unsigned int len, j;
15075
15076                     len = TREE_VEC_LENGTH (arg);
15077                     for (j = 0; j < len; ++j)
15078                       {
15079                         tree value = TREE_VEC_ELT (arg, j);
15080                         if (value != NULL_TREE)
15081                           value = convert_from_reference (value);
15082                         vec_safe_push (call_args, value);
15083                       }
15084                   }
15085                 else
15086                   {
15087                     /* A partial substitution.  Add one entry.  */
15088                     vec_safe_push (call_args, arg);
15089                   }
15090               }
15091           }
15092
15093         /* We do not perform argument-dependent lookup if normal
15094            lookup finds a non-function, in accordance with the
15095            expected resolution of DR 218.  */
15096         if (koenig_p
15097             && ((is_overloaded_fn (function)
15098                  /* If lookup found a member function, the Koenig lookup is
15099                     not appropriate, even if an unqualified-name was used
15100                     to denote the function.  */
15101                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
15102                 || identifier_p (function))
15103             /* Only do this when substitution turns a dependent call
15104                into a non-dependent call.  */
15105             && type_dependent_expression_p_push (t)
15106             && !any_type_dependent_arguments_p (call_args))
15107           function = perform_koenig_lookup (function, call_args, tf_none);
15108
15109         if (identifier_p (function)
15110             && !any_type_dependent_arguments_p (call_args))
15111           {
15112             if (koenig_p && (complain & tf_warning_or_error))
15113               {
15114                 /* For backwards compatibility and good diagnostics, try
15115                    the unqualified lookup again if we aren't in SFINAE
15116                    context.  */
15117                 tree unq = (tsubst_copy_and_build
15118                             (function, args, complain, in_decl, true,
15119                              integral_constant_expression_p));
15120                 if (unq == error_mark_node)
15121                   RETURN (error_mark_node);
15122
15123                 if (unq != function)
15124                   {
15125                     tree fn = unq;
15126                     if (INDIRECT_REF_P (fn))
15127                       fn = TREE_OPERAND (fn, 0);
15128                     if (TREE_CODE (fn) == COMPONENT_REF)
15129                       fn = TREE_OPERAND (fn, 1);
15130                     if (is_overloaded_fn (fn))
15131                       fn = get_first_fn (fn);
15132                     if (permerror (EXPR_LOC_OR_LOC (t, input_location),
15133                                    "%qD was not declared in this scope, "
15134                                    "and no declarations were found by "
15135                                    "argument-dependent lookup at the point "
15136                                    "of instantiation", function))
15137                       {
15138                         if (!DECL_P (fn))
15139                           /* Can't say anything more.  */;
15140                         else if (DECL_CLASS_SCOPE_P (fn))
15141                           {
15142                             location_t loc = EXPR_LOC_OR_LOC (t,
15143                                                               input_location);
15144                             inform (loc,
15145                                     "declarations in dependent base %qT are "
15146                                     "not found by unqualified lookup",
15147                                     DECL_CLASS_CONTEXT (fn));
15148                             if (current_class_ptr)
15149                               inform (loc,
15150                                       "use %<this->%D%> instead", function);
15151                             else
15152                               inform (loc,
15153                                       "use %<%T::%D%> instead",
15154                                       current_class_name, function);
15155                           }
15156                         else
15157                           inform (0, "%q+D declared here, later in the "
15158                                   "translation unit", fn);
15159                       }
15160                     function = unq;
15161                   }
15162               }
15163             if (identifier_p (function))
15164               {
15165                 if (complain & tf_error)
15166                   unqualified_name_lookup_error (function);
15167                 release_tree_vector (call_args);
15168                 RETURN (error_mark_node);
15169               }
15170           }
15171
15172         /* Remember that there was a reference to this entity.  */
15173         if (DECL_P (function))
15174           mark_used (function, complain);
15175
15176         /* Put back tf_decltype for the actual call.  */
15177         complain |= decltype_flag;
15178
15179         if (TREE_CODE (function) == OFFSET_REF)
15180           ret = build_offset_ref_call_from_tree (function, &call_args,
15181                                                  complain);
15182         else if (TREE_CODE (function) == COMPONENT_REF)
15183           {
15184             tree instance = TREE_OPERAND (function, 0);
15185             tree fn = TREE_OPERAND (function, 1);
15186
15187             if (processing_template_decl
15188                 && (type_dependent_expression_p (instance)
15189                     || (!BASELINK_P (fn)
15190                         && TREE_CODE (fn) != FIELD_DECL)
15191                     || type_dependent_expression_p (fn)
15192                     || any_type_dependent_arguments_p (call_args)))
15193               ret = build_nt_call_vec (function, call_args);
15194             else if (!BASELINK_P (fn))
15195               ret = finish_call_expr (function, &call_args,
15196                                        /*disallow_virtual=*/false,
15197                                        /*koenig_p=*/false,
15198                                        complain);
15199             else
15200               ret = (build_new_method_call
15201                       (instance, fn,
15202                        &call_args, NULL_TREE,
15203                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
15204                        /*fn_p=*/NULL,
15205                        complain));
15206           }
15207         else
15208           ret = finish_call_expr (function, &call_args,
15209                                   /*disallow_virtual=*/qualified_p,
15210                                   koenig_p,
15211                                   complain);
15212
15213         release_tree_vector (call_args);
15214
15215         RETURN (ret);
15216       }
15217
15218     case COND_EXPR:
15219       {
15220         tree cond = RECUR (TREE_OPERAND (t, 0));
15221         tree folded_cond = fold_non_dependent_expr (cond);
15222         tree exp1, exp2;
15223
15224         if (TREE_CODE (folded_cond) == INTEGER_CST)
15225           {
15226             if (integer_zerop (folded_cond))
15227               {
15228                 ++c_inhibit_evaluation_warnings;
15229                 exp1 = RECUR (TREE_OPERAND (t, 1));
15230                 --c_inhibit_evaluation_warnings;
15231                 exp2 = RECUR (TREE_OPERAND (t, 2));
15232               }
15233             else
15234               {
15235                 exp1 = RECUR (TREE_OPERAND (t, 1));
15236                 ++c_inhibit_evaluation_warnings;
15237                 exp2 = RECUR (TREE_OPERAND (t, 2));
15238                 --c_inhibit_evaluation_warnings;
15239               }
15240             cond = folded_cond;
15241           }
15242         else
15243           {
15244             exp1 = RECUR (TREE_OPERAND (t, 1));
15245             exp2 = RECUR (TREE_OPERAND (t, 2));
15246           }
15247
15248         RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
15249                                          cond, exp1, exp2, complain));
15250       }
15251
15252     case PSEUDO_DTOR_EXPR:
15253       {
15254         tree op0 = RECUR (TREE_OPERAND (t, 0));
15255         tree op1 = RECUR (TREE_OPERAND (t, 1));
15256         tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
15257         RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
15258                                                input_location));
15259       }
15260
15261     case TREE_LIST:
15262       {
15263         tree purpose, value, chain;
15264
15265         if (t == void_list_node)
15266           RETURN (t);
15267
15268         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
15269             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
15270           {
15271             /* We have pack expansions, so expand those and
15272                create a new list out of it.  */
15273             tree purposevec = NULL_TREE;
15274             tree valuevec = NULL_TREE;
15275             tree chain;
15276             int i, len = -1;
15277
15278             /* Expand the argument expressions.  */
15279             if (TREE_PURPOSE (t))
15280               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
15281                                                  complain, in_decl);
15282             if (TREE_VALUE (t))
15283               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
15284                                                complain, in_decl);
15285
15286             /* Build the rest of the list.  */
15287             chain = TREE_CHAIN (t);
15288             if (chain && chain != void_type_node)
15289               chain = RECUR (chain);
15290
15291             /* Determine the number of arguments.  */
15292             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
15293               {
15294                 len = TREE_VEC_LENGTH (purposevec);
15295                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15296               }
15297             else if (TREE_CODE (valuevec) == TREE_VEC)
15298               len = TREE_VEC_LENGTH (valuevec);
15299             else
15300               {
15301                 /* Since we only performed a partial substitution into
15302                    the argument pack, we only RETURN (a single list
15303                    node.  */
15304                 if (purposevec == TREE_PURPOSE (t)
15305                     && valuevec == TREE_VALUE (t)
15306                     && chain == TREE_CHAIN (t))
15307                   RETURN (t);
15308
15309                 RETURN (tree_cons (purposevec, valuevec, chain));
15310               }
15311             
15312             /* Convert the argument vectors into a TREE_LIST */
15313             i = len;
15314             while (i > 0)
15315               {
15316                 /* Grab the Ith values.  */
15317                 i--;
15318                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
15319                                      : NULL_TREE;
15320                 value 
15321                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
15322                              : NULL_TREE;
15323
15324                 /* Build the list (backwards).  */
15325                 chain = tree_cons (purpose, value, chain);
15326               }
15327
15328             RETURN (chain);
15329           }
15330
15331         purpose = TREE_PURPOSE (t);
15332         if (purpose)
15333           purpose = RECUR (purpose);
15334         value = TREE_VALUE (t);
15335         if (value)
15336           value = RECUR (value);
15337         chain = TREE_CHAIN (t);
15338         if (chain && chain != void_type_node)
15339           chain = RECUR (chain);
15340         if (purpose == TREE_PURPOSE (t)
15341             && value == TREE_VALUE (t)
15342             && chain == TREE_CHAIN (t))
15343           RETURN (t);
15344         RETURN (tree_cons (purpose, value, chain));
15345       }
15346
15347     case COMPONENT_REF:
15348       {
15349         tree object;
15350         tree object_type;
15351         tree member;
15352         tree r;
15353
15354         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
15355                                                      args, complain, in_decl);
15356         /* Remember that there was a reference to this entity.  */
15357         if (DECL_P (object))
15358           mark_used (object);
15359         object_type = TREE_TYPE (object);
15360
15361         member = TREE_OPERAND (t, 1);
15362         if (BASELINK_P (member))
15363           member = tsubst_baselink (member,
15364                                     non_reference (TREE_TYPE (object)),
15365                                     args, complain, in_decl);
15366         else
15367           member = tsubst_copy (member, args, complain, in_decl);
15368         if (member == error_mark_node)
15369           RETURN (error_mark_node);
15370
15371         if (type_dependent_expression_p (object))
15372           /* We can't do much here.  */;
15373         else if (!CLASS_TYPE_P (object_type))
15374           {
15375             if (scalarish_type_p (object_type))
15376               {
15377                 tree s = NULL_TREE;
15378                 tree dtor = member;
15379
15380                 if (TREE_CODE (dtor) == SCOPE_REF)
15381                   {
15382                     s = TREE_OPERAND (dtor, 0);
15383                     dtor = TREE_OPERAND (dtor, 1);
15384                   }
15385                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
15386                   {
15387                     dtor = TREE_OPERAND (dtor, 0);
15388                     if (TYPE_P (dtor))
15389                       RETURN (finish_pseudo_destructor_expr
15390                               (object, s, dtor, input_location));
15391                   }
15392               }
15393           }
15394         else if (TREE_CODE (member) == SCOPE_REF
15395                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
15396           {
15397             /* Lookup the template functions now that we know what the
15398                scope is.  */
15399             tree scope = TREE_OPERAND (member, 0);
15400             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
15401             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
15402             member = lookup_qualified_name (scope, tmpl,
15403                                             /*is_type_p=*/false,
15404                                             /*complain=*/false);
15405             if (BASELINK_P (member))
15406               {
15407                 BASELINK_FUNCTIONS (member)
15408                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
15409                               args);
15410                 member = (adjust_result_of_qualified_name_lookup
15411                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
15412                            object_type));
15413               }
15414             else
15415               {
15416                 qualified_name_lookup_error (scope, tmpl, member,
15417                                              input_location);
15418                 RETURN (error_mark_node);
15419               }
15420           }
15421         else if (TREE_CODE (member) == SCOPE_REF
15422                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
15423                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
15424           {
15425             if (complain & tf_error)
15426               {
15427                 if (TYPE_P (TREE_OPERAND (member, 0)))
15428                   error ("%qT is not a class or namespace",
15429                          TREE_OPERAND (member, 0));
15430                 else
15431                   error ("%qD is not a class or namespace",
15432                          TREE_OPERAND (member, 0));
15433               }
15434             RETURN (error_mark_node);
15435           }
15436         else if (TREE_CODE (member) == FIELD_DECL)
15437           {
15438             r = finish_non_static_data_member (member, object, NULL_TREE);
15439             if (TREE_CODE (r) == COMPONENT_REF)
15440               REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
15441             RETURN (r);
15442           }
15443
15444         r = finish_class_member_access_expr (object, member,
15445                                              /*template_p=*/false,
15446                                              complain);
15447         if (TREE_CODE (r) == COMPONENT_REF)
15448           REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
15449         RETURN (r);
15450       }
15451
15452     case THROW_EXPR:
15453       RETURN (build_throw
15454         (RECUR (TREE_OPERAND (t, 0))));
15455
15456     case CONSTRUCTOR:
15457       {
15458         vec<constructor_elt, va_gc> *n;
15459         constructor_elt *ce;
15460         unsigned HOST_WIDE_INT idx;
15461         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15462         bool process_index_p;
15463         int newlen;
15464         bool need_copy_p = false;
15465         tree r;
15466
15467         if (type == error_mark_node)
15468           RETURN (error_mark_node);
15469
15470         /* digest_init will do the wrong thing if we let it.  */
15471         if (type && TYPE_PTRMEMFUNC_P (type))
15472           RETURN (t);
15473
15474         /* We do not want to process the index of aggregate
15475            initializers as they are identifier nodes which will be
15476            looked up by digest_init.  */
15477         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
15478
15479         n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
15480         newlen = vec_safe_length (n);
15481         FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
15482           {
15483             if (ce->index && process_index_p
15484                 /* An identifier index is looked up in the type
15485                    being initialized, not the current scope.  */
15486                 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
15487               ce->index = RECUR (ce->index);
15488
15489             if (PACK_EXPANSION_P (ce->value))
15490               {
15491                 /* Substitute into the pack expansion.  */
15492                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
15493                                                   in_decl);
15494
15495                 if (ce->value == error_mark_node
15496                     || PACK_EXPANSION_P (ce->value))
15497                   ;
15498                 else if (TREE_VEC_LENGTH (ce->value) == 1)
15499                   /* Just move the argument into place.  */
15500                   ce->value = TREE_VEC_ELT (ce->value, 0);
15501                 else
15502                   {
15503                     /* Update the length of the final CONSTRUCTOR
15504                        arguments vector, and note that we will need to
15505                        copy.*/
15506                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
15507                     need_copy_p = true;
15508                   }
15509               }
15510             else
15511               ce->value = RECUR (ce->value);
15512           }
15513
15514         if (need_copy_p)
15515           {
15516             vec<constructor_elt, va_gc> *old_n = n;
15517
15518             vec_alloc (n, newlen);
15519             FOR_EACH_VEC_ELT (*old_n, idx, ce)
15520               {
15521                 if (TREE_CODE (ce->value) == TREE_VEC)
15522                   {
15523                     int i, len = TREE_VEC_LENGTH (ce->value);
15524                     for (i = 0; i < len; ++i)
15525                       CONSTRUCTOR_APPEND_ELT (n, 0,
15526                                               TREE_VEC_ELT (ce->value, i));
15527                   }
15528                 else
15529                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
15530               }
15531           }
15532
15533         r = build_constructor (init_list_type_node, n);
15534         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
15535
15536         if (TREE_HAS_CONSTRUCTOR (t))
15537           RETURN (finish_compound_literal (type, r, complain));
15538
15539         TREE_TYPE (r) = type;
15540         RETURN (r);
15541       }
15542
15543     case TYPEID_EXPR:
15544       {
15545         tree operand_0 = TREE_OPERAND (t, 0);
15546         if (TYPE_P (operand_0))
15547           {
15548             operand_0 = tsubst (operand_0, args, complain, in_decl);
15549             RETURN (get_typeid (operand_0, complain));
15550           }
15551         else
15552           {
15553             operand_0 = RECUR (operand_0);
15554             RETURN (build_typeid (operand_0, complain));
15555           }
15556       }
15557
15558     case VAR_DECL:
15559       if (!args)
15560         RETURN (t);
15561       else if (DECL_PACK_P (t))
15562         {
15563           /* We don't build decls for an instantiation of a
15564              variadic capture proxy, we instantiate the elements
15565              when needed.  */
15566           gcc_assert (DECL_HAS_VALUE_EXPR_P (t));
15567           return RECUR (DECL_VALUE_EXPR (t));
15568         }
15569       /* Fall through */
15570
15571     case PARM_DECL:
15572       {
15573         tree r = tsubst_copy (t, args, complain, in_decl);
15574         /* ??? We're doing a subset of finish_id_expression here.  */
15575         if (VAR_P (r)
15576             && !processing_template_decl
15577             && !cp_unevaluated_operand
15578             && (TREE_STATIC (r) || DECL_EXTERNAL (r))
15579             && DECL_THREAD_LOCAL_P (r))
15580           {
15581             if (tree wrap = get_tls_wrapper_fn (r))
15582               /* Replace an evaluated use of the thread_local variable with
15583                  a call to its wrapper.  */
15584               r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
15585           }
15586         else if (outer_automatic_var_p (r))
15587           r = process_outer_var_ref (r, complain);
15588
15589         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
15590           /* If the original type was a reference, we'll be wrapped in
15591              the appropriate INDIRECT_REF.  */
15592           r = convert_from_reference (r);
15593         RETURN (r);
15594       }
15595
15596     case VA_ARG_EXPR:
15597       {
15598         tree op0 = RECUR (TREE_OPERAND (t, 0));
15599         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15600         RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
15601       }
15602
15603     case OFFSETOF_EXPR:
15604       RETURN (finish_offsetof (RECUR (TREE_OPERAND (t, 0)),
15605                                EXPR_LOCATION (t)));
15606
15607     case TRAIT_EXPR:
15608       {
15609         tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
15610                              complain, in_decl);
15611
15612         tree type2 = TRAIT_EXPR_TYPE2 (t);
15613         if (type2 && TREE_CODE (type2) == TREE_LIST)
15614           type2 = RECUR (type2);
15615         else if (type2)
15616           type2 = tsubst (type2, args, complain, in_decl);
15617         
15618         RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
15619       }
15620
15621     case STMT_EXPR:
15622       {
15623         tree old_stmt_expr = cur_stmt_expr;
15624         tree stmt_expr = begin_stmt_expr ();
15625
15626         cur_stmt_expr = stmt_expr;
15627         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
15628                      integral_constant_expression_p);
15629         stmt_expr = finish_stmt_expr (stmt_expr, false);
15630         cur_stmt_expr = old_stmt_expr;
15631
15632         /* If the resulting list of expression statement is empty,
15633            fold it further into void_node.  */
15634         if (empty_expr_stmt_p (stmt_expr))
15635           stmt_expr = void_node;
15636
15637         RETURN (stmt_expr);
15638       }
15639
15640     case LAMBDA_EXPR:
15641       {
15642         tree r = build_lambda_expr ();
15643
15644         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
15645         LAMBDA_EXPR_CLOSURE (r) = type;
15646         CLASSTYPE_LAMBDA_EXPR (type) = r;
15647
15648         LAMBDA_EXPR_LOCATION (r)
15649           = LAMBDA_EXPR_LOCATION (t);
15650         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
15651           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
15652         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
15653         LAMBDA_EXPR_DISCRIMINATOR (r)
15654           = (LAMBDA_EXPR_DISCRIMINATOR (t));
15655         /* For a function scope, we want to use tsubst so that we don't
15656            complain about referring to an auto function before its return
15657            type has been deduced.  Otherwise, we want to use tsubst_copy so
15658            that we look up the existing field/parameter/variable rather
15659            than build a new one.  */
15660         tree scope = LAMBDA_EXPR_EXTRA_SCOPE (t);
15661         if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15662           scope = tsubst (scope, args, complain, in_decl);
15663         else if (scope && TREE_CODE (scope) == PARM_DECL)
15664           {
15665             /* Look up the parameter we want directly, as tsubst_copy
15666                doesn't do what we need.  */
15667             tree fn = tsubst (DECL_CONTEXT (scope), args, complain, in_decl);
15668             tree parm = FUNCTION_FIRST_USER_PARM (fn);
15669             while (DECL_PARM_INDEX (parm) != DECL_PARM_INDEX (scope))
15670               parm = DECL_CHAIN (parm);
15671             scope = parm;
15672             /* FIXME Work around the parm not having DECL_CONTEXT set.  */
15673             if (DECL_CONTEXT (scope) == NULL_TREE)
15674               DECL_CONTEXT (scope) = fn;
15675           }
15676         else
15677           scope = RECUR (scope);
15678         LAMBDA_EXPR_EXTRA_SCOPE (r) = scope;
15679         LAMBDA_EXPR_RETURN_TYPE (r)
15680           = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
15681
15682         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
15683                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
15684
15685         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
15686         determine_visibility (TYPE_NAME (type));
15687         /* Now that we know visibility, instantiate the type so we have a
15688            declaration of the op() for later calls to lambda_function.  */
15689         complete_type (type);
15690
15691         LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
15692
15693         RETURN (build_lambda_object (r));
15694       }
15695
15696     case TARGET_EXPR:
15697       /* We can get here for a constant initializer of non-dependent type.
15698          FIXME stop folding in cp_parser_initializer_clause.  */
15699       {
15700         tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
15701                                          complain);
15702         RETURN (r);
15703       }
15704
15705     case TRANSACTION_EXPR:
15706       RETURN (tsubst_expr(t, args, complain, in_decl,
15707              integral_constant_expression_p));
15708
15709     case PAREN_EXPR:
15710       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
15711
15712     case VEC_PERM_EXPR:
15713       {
15714         tree op0 = RECUR (TREE_OPERAND (t, 0));
15715         tree op1 = RECUR (TREE_OPERAND (t, 1));
15716         tree op2 = RECUR (TREE_OPERAND (t, 2));
15717         RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
15718                                        complain));
15719       }
15720
15721     default:
15722       /* Handle Objective-C++ constructs, if appropriate.  */
15723       {
15724         tree subst
15725           = objcp_tsubst_copy_and_build (t, args, complain,
15726                                          in_decl, /*function_p=*/false);
15727         if (subst)
15728           RETURN (subst);
15729       }
15730       RETURN (tsubst_copy (t, args, complain, in_decl));
15731     }
15732
15733 #undef RECUR
15734 #undef RETURN
15735  out:
15736   input_location = loc;
15737   return retval;
15738 }
15739
15740 /* Verify that the instantiated ARGS are valid. For type arguments,
15741    make sure that the type's linkage is ok. For non-type arguments,
15742    make sure they are constants if they are integral or enumerations.
15743    Emit an error under control of COMPLAIN, and return TRUE on error.  */
15744
15745 static bool
15746 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
15747 {
15748   if (dependent_template_arg_p (t))
15749     return false;
15750   if (ARGUMENT_PACK_P (t))
15751     {
15752       tree vec = ARGUMENT_PACK_ARGS (t);
15753       int len = TREE_VEC_LENGTH (vec);
15754       bool result = false;
15755       int i;
15756
15757       for (i = 0; i < len; ++i)
15758         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
15759           result = true;
15760       return result;
15761     }
15762   else if (TYPE_P (t))
15763     {
15764       /* [basic.link]: A name with no linkage (notably, the name
15765          of a class or enumeration declared in a local scope)
15766          shall not be used to declare an entity with linkage.
15767          This implies that names with no linkage cannot be used as
15768          template arguments
15769
15770          DR 757 relaxes this restriction for C++0x.  */
15771       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
15772                  : no_linkage_check (t, /*relaxed_p=*/false));
15773
15774       if (nt)
15775         {
15776           /* DR 488 makes use of a type with no linkage cause
15777              type deduction to fail.  */
15778           if (complain & tf_error)
15779             {
15780               if (TYPE_ANONYMOUS_P (nt))
15781                 error ("%qT is/uses anonymous type", t);
15782               else
15783                 error ("template argument for %qD uses local type %qT",
15784                        tmpl, t);
15785             }
15786           return true;
15787         }
15788       /* In order to avoid all sorts of complications, we do not
15789          allow variably-modified types as template arguments.  */
15790       else if (variably_modified_type_p (t, NULL_TREE))
15791         {
15792           if (complain & tf_error)
15793             error ("%qT is a variably modified type", t);
15794           return true;
15795         }
15796     }
15797   /* Class template and alias template arguments should be OK.  */
15798   else if (DECL_TYPE_TEMPLATE_P (t))
15799     ;
15800   /* A non-type argument of integral or enumerated type must be a
15801      constant.  */
15802   else if (TREE_TYPE (t)
15803            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
15804            && !REFERENCE_REF_P (t)
15805            && !TREE_CONSTANT (t))
15806     {
15807       if (complain & tf_error)
15808         error ("integral expression %qE is not constant", t);
15809       return true;
15810     }
15811   return false;
15812 }
15813
15814 static bool
15815 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
15816 {
15817   int ix, len = DECL_NTPARMS (tmpl);
15818   bool result = false;
15819
15820   for (ix = 0; ix != len; ix++)
15821     {
15822       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
15823         result = true;
15824     }
15825   if (result && (complain & tf_error))
15826     error ("  trying to instantiate %qD", tmpl);
15827   return result;
15828 }
15829
15830 /* We're out of SFINAE context now, so generate diagnostics for the access
15831    errors we saw earlier when instantiating D from TMPL and ARGS.  */
15832
15833 static void
15834 recheck_decl_substitution (tree d, tree tmpl, tree args)
15835 {
15836   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
15837   tree type = TREE_TYPE (pattern);
15838   location_t loc = input_location;
15839
15840   push_access_scope (d);
15841   push_deferring_access_checks (dk_no_deferred);
15842   input_location = DECL_SOURCE_LOCATION (pattern);
15843   tsubst (type, args, tf_warning_or_error, d);
15844   input_location = loc;
15845   pop_deferring_access_checks ();
15846   pop_access_scope (d);
15847 }
15848
15849 /* Instantiate the indicated variable, function, or alias template TMPL with
15850    the template arguments in TARG_PTR.  */
15851
15852 static tree
15853 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
15854 {
15855   tree targ_ptr = orig_args;
15856   tree fndecl;
15857   tree gen_tmpl;
15858   tree spec;
15859   bool access_ok = true;
15860
15861   if (tmpl == error_mark_node)
15862     return error_mark_node;
15863
15864   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
15865
15866   /* If this function is a clone, handle it specially.  */
15867   if (DECL_CLONED_FUNCTION_P (tmpl))
15868     {
15869       tree spec;
15870       tree clone;
15871
15872       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
15873          DECL_CLONED_FUNCTION.  */
15874       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
15875                                    targ_ptr, complain);
15876       if (spec == error_mark_node)
15877         return error_mark_node;
15878
15879       /* Look for the clone.  */
15880       FOR_EACH_CLONE (clone, spec)
15881         if (DECL_NAME (clone) == DECL_NAME (tmpl))
15882           return clone;
15883       /* We should always have found the clone by now.  */
15884       gcc_unreachable ();
15885       return NULL_TREE;
15886     }
15887
15888   if (targ_ptr == error_mark_node)
15889     return error_mark_node;
15890
15891   /* Check to see if we already have this specialization.  */
15892   gen_tmpl = most_general_template (tmpl);
15893   if (tmpl != gen_tmpl)
15894     /* The TMPL is a partial instantiation.  To get a full set of
15895        arguments we must add the arguments used to perform the
15896        partial instantiation.  */
15897     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
15898                                             targ_ptr);
15899
15900   /* It would be nice to avoid hashing here and then again in tsubst_decl,
15901      but it doesn't seem to be on the hot path.  */
15902   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
15903
15904   gcc_assert (tmpl == gen_tmpl
15905               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
15906                   == spec)
15907               || fndecl == NULL_TREE);
15908
15909   if (spec != NULL_TREE)
15910     {
15911       if (FNDECL_HAS_ACCESS_ERRORS (spec))
15912         {
15913           if (complain & tf_error)
15914             recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
15915           return error_mark_node;
15916         }
15917       return spec;
15918     }
15919
15920   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
15921                                complain))
15922     return error_mark_node;
15923
15924   /* We are building a FUNCTION_DECL, during which the access of its
15925      parameters and return types have to be checked.  However this
15926      FUNCTION_DECL which is the desired context for access checking
15927      is not built yet.  We solve this chicken-and-egg problem by
15928      deferring all checks until we have the FUNCTION_DECL.  */
15929   push_deferring_access_checks (dk_deferred);
15930
15931   /* Instantiation of the function happens in the context of the function
15932      template, not the context of the overload resolution we're doing.  */
15933   push_to_top_level ();
15934   /* If there are dependent arguments, e.g. because we're doing partial
15935      ordering, make sure processing_template_decl stays set.  */
15936   if (uses_template_parms (targ_ptr))
15937     ++processing_template_decl;
15938   if (DECL_CLASS_SCOPE_P (gen_tmpl))
15939     {
15940       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
15941                                    complain, gen_tmpl, true);
15942       push_nested_class (ctx);
15943     }
15944
15945   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
15946
15947   if (VAR_P (pattern))
15948     {
15949       /* We need to determine if we're using a partial or explicit
15950          specialization now, because the type of the variable could be
15951          different.  */
15952       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
15953       tree elt = most_specialized_partial_spec (tid, complain);
15954       if (elt == error_mark_node)
15955         pattern = error_mark_node;
15956       else if (elt)
15957         {
15958           tmpl = TREE_VALUE (elt);
15959           pattern = DECL_TEMPLATE_RESULT (tmpl);
15960           targ_ptr = TREE_PURPOSE (elt);
15961         }
15962     }
15963
15964   /* Substitute template parameters to obtain the specialization.  */
15965   fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
15966   if (DECL_CLASS_SCOPE_P (gen_tmpl))
15967     pop_nested_class ();
15968   pop_from_top_level ();
15969
15970   if (fndecl == error_mark_node)
15971     {
15972       pop_deferring_access_checks ();
15973       return error_mark_node;
15974     }
15975
15976   /* The DECL_TI_TEMPLATE should always be the immediate parent
15977      template, not the most general template.  */
15978   DECL_TI_TEMPLATE (fndecl) = tmpl;
15979
15980   /* Now we know the specialization, compute access previously
15981      deferred.  */
15982   push_access_scope (fndecl);
15983   if (!perform_deferred_access_checks (complain))
15984     access_ok = false;
15985   pop_access_scope (fndecl);
15986   pop_deferring_access_checks ();
15987
15988   /* If we've just instantiated the main entry point for a function,
15989      instantiate all the alternate entry points as well.  We do this
15990      by cloning the instantiation of the main entry point, not by
15991      instantiating the template clones.  */
15992   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
15993     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
15994
15995   if (!access_ok)
15996     {
15997       if (!(complain & tf_error))
15998         {
15999           /* Remember to reinstantiate when we're out of SFINAE so the user
16000              can see the errors.  */
16001           FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
16002         }
16003       return error_mark_node;
16004     }
16005   return fndecl;
16006 }
16007
16008 /* Wrapper for instantiate_template_1.  */
16009
16010 tree
16011 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
16012 {
16013   tree ret;
16014   timevar_push (TV_TEMPLATE_INST);
16015   ret = instantiate_template_1 (tmpl, orig_args,  complain);
16016   timevar_pop (TV_TEMPLATE_INST);
16017   return ret;
16018 }
16019
16020 /* Instantiate the alias template TMPL with ARGS.  Also push a template
16021    instantiation level, which instantiate_template doesn't do because
16022    functions and variables have sufficient context established by the
16023    callers.  */
16024
16025 static tree
16026 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
16027 {
16028   struct pending_template *old_last_pend = last_pending_template;
16029   struct tinst_level *old_error_tinst = last_error_tinst_level;
16030   if (tmpl == error_mark_node || args == error_mark_node)
16031     return error_mark_node;
16032   tree tinst = build_tree_list (tmpl, args);
16033   if (!push_tinst_level (tinst))
16034     {
16035       ggc_free (tinst);
16036       return error_mark_node;
16037     }
16038
16039   args =
16040     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
16041                                      args, tmpl, complain,
16042                                      /*require_all_args=*/true,
16043                                      /*use_default_args=*/true);
16044
16045   tree r = instantiate_template (tmpl, args, complain);
16046   pop_tinst_level ();
16047   /* We can't free this if a pending_template entry or last_error_tinst_level
16048      is pointing at it.  */
16049   if (last_pending_template == old_last_pend
16050       && last_error_tinst_level == old_error_tinst)
16051     ggc_free (tinst);
16052
16053   return r;
16054 }
16055
16056 /* PARM is a template parameter pack for FN.  Returns true iff
16057    PARM is used in a deducible way in the argument list of FN.  */
16058
16059 static bool
16060 pack_deducible_p (tree parm, tree fn)
16061 {
16062   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
16063   for (; t; t = TREE_CHAIN (t))
16064     {
16065       tree type = TREE_VALUE (t);
16066       tree packs;
16067       if (!PACK_EXPANSION_P (type))
16068         continue;
16069       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
16070            packs; packs = TREE_CHAIN (packs))
16071         if (template_args_equal (TREE_VALUE (packs), parm))
16072           {
16073             /* The template parameter pack is used in a function parameter
16074                pack.  If this is the end of the parameter list, the
16075                template parameter pack is deducible.  */
16076             if (TREE_CHAIN (t) == void_list_node)
16077               return true;
16078             else
16079               /* Otherwise, not.  Well, it could be deduced from
16080                  a non-pack parameter, but doing so would end up with
16081                  a deduction mismatch, so don't bother.  */
16082               return false;
16083           }
16084     }
16085   /* The template parameter pack isn't used in any function parameter
16086      packs, but it might be used deeper, e.g. tuple<Args...>.  */
16087   return true;
16088 }
16089
16090 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
16091    NARGS elements of the arguments that are being used when calling
16092    it.  TARGS is a vector into which the deduced template arguments
16093    are placed.
16094
16095    Returns either a FUNCTION_DECL for the matching specialization of FN or
16096    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
16097    true, diagnostics will be printed to explain why it failed.
16098
16099    If FN is a conversion operator, or we are trying to produce a specific
16100    specialization, RETURN_TYPE is the return type desired.
16101
16102    The EXPLICIT_TARGS are explicit template arguments provided via a
16103    template-id.
16104
16105    The parameter STRICT is one of:
16106
16107    DEDUCE_CALL:
16108      We are deducing arguments for a function call, as in
16109      [temp.deduct.call].
16110
16111    DEDUCE_CONV:
16112      We are deducing arguments for a conversion function, as in
16113      [temp.deduct.conv].
16114
16115    DEDUCE_EXACT:
16116      We are deducing arguments when doing an explicit instantiation
16117      as in [temp.explicit], when determining an explicit specialization
16118      as in [temp.expl.spec], or when taking the address of a function
16119      template, as in [temp.deduct.funcaddr].  */
16120
16121 tree
16122 fn_type_unification (tree fn,
16123                      tree explicit_targs,
16124                      tree targs,
16125                      const tree *args,
16126                      unsigned int nargs,
16127                      tree return_type,
16128                      unification_kind_t strict,
16129                      int flags,
16130                      bool explain_p,
16131                      bool decltype_p)
16132 {
16133   tree parms;
16134   tree fntype;
16135   tree decl = NULL_TREE;
16136   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
16137   bool ok;
16138   static int deduction_depth;
16139   struct pending_template *old_last_pend = last_pending_template;
16140   struct tinst_level *old_error_tinst = last_error_tinst_level;
16141   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
16142   tree tinst;
16143   tree r = error_mark_node;
16144
16145   if (decltype_p)
16146     complain |= tf_decltype;
16147
16148   /* In C++0x, it's possible to have a function template whose type depends
16149      on itself recursively.  This is most obvious with decltype, but can also
16150      occur with enumeration scope (c++/48969).  So we need to catch infinite
16151      recursion and reject the substitution at deduction time; this function
16152      will return error_mark_node for any repeated substitution.
16153
16154      This also catches excessive recursion such as when f<N> depends on
16155      f<N-1> across all integers, and returns error_mark_node for all the
16156      substitutions back up to the initial one.
16157
16158      This is, of course, not reentrant.  */
16159   if (excessive_deduction_depth)
16160     return error_mark_node;
16161   tinst = build_tree_list (fn, NULL_TREE);
16162   ++deduction_depth;
16163
16164   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
16165
16166   fntype = TREE_TYPE (fn);
16167   if (explicit_targs)
16168     {
16169       /* [temp.deduct]
16170
16171          The specified template arguments must match the template
16172          parameters in kind (i.e., type, nontype, template), and there
16173          must not be more arguments than there are parameters;
16174          otherwise type deduction fails.
16175
16176          Nontype arguments must match the types of the corresponding
16177          nontype template parameters, or must be convertible to the
16178          types of the corresponding nontype parameters as specified in
16179          _temp.arg.nontype_, otherwise type deduction fails.
16180
16181          All references in the function type of the function template
16182          to the corresponding template parameters are replaced by the
16183          specified template argument values.  If a substitution in a
16184          template parameter or in the function type of the function
16185          template results in an invalid type, type deduction fails.  */
16186       int i, len = TREE_VEC_LENGTH (tparms);
16187       location_t loc = input_location;
16188       bool incomplete = false;
16189
16190       /* Adjust any explicit template arguments before entering the
16191          substitution context.  */
16192       explicit_targs
16193         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
16194                                   complain,
16195                                   /*require_all_args=*/false,
16196                                   /*use_default_args=*/false));
16197       if (explicit_targs == error_mark_node)
16198         goto fail;
16199
16200       /* Substitute the explicit args into the function type.  This is
16201          necessary so that, for instance, explicitly declared function
16202          arguments can match null pointed constants.  If we were given
16203          an incomplete set of explicit args, we must not do semantic
16204          processing during substitution as we could create partial
16205          instantiations.  */
16206       for (i = 0; i < len; i++)
16207         {
16208           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
16209           bool parameter_pack = false;
16210           tree targ = TREE_VEC_ELT (explicit_targs, i);
16211
16212           /* Dig out the actual parm.  */
16213           if (TREE_CODE (parm) == TYPE_DECL
16214               || TREE_CODE (parm) == TEMPLATE_DECL)
16215             {
16216               parm = TREE_TYPE (parm);
16217               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
16218             }
16219           else if (TREE_CODE (parm) == PARM_DECL)
16220             {
16221               parm = DECL_INITIAL (parm);
16222               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
16223             }
16224
16225           if (!parameter_pack && targ == NULL_TREE)
16226             /* No explicit argument for this template parameter.  */
16227             incomplete = true;
16228
16229           if (parameter_pack && pack_deducible_p (parm, fn))
16230             {
16231               /* Mark the argument pack as "incomplete". We could
16232                  still deduce more arguments during unification.
16233                  We remove this mark in type_unification_real.  */
16234               if (targ)
16235                 {
16236                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
16237                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
16238                     = ARGUMENT_PACK_ARGS (targ);
16239                 }
16240
16241               /* We have some incomplete argument packs.  */
16242               incomplete = true;
16243             }
16244         }
16245
16246       TREE_VALUE (tinst) = explicit_targs;
16247       if (!push_tinst_level (tinst))
16248         {
16249           excessive_deduction_depth = true;
16250           goto fail;
16251         }
16252       processing_template_decl += incomplete;
16253       input_location = DECL_SOURCE_LOCATION (fn);
16254       /* Ignore any access checks; we'll see them again in
16255          instantiate_template and they might have the wrong
16256          access path at this point.  */
16257       push_deferring_access_checks (dk_deferred);
16258       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
16259                        complain | tf_partial, NULL_TREE);
16260       pop_deferring_access_checks ();
16261       input_location = loc;
16262       processing_template_decl -= incomplete;
16263       pop_tinst_level ();
16264
16265       if (fntype == error_mark_node)
16266         goto fail;
16267
16268       /* Place the explicitly specified arguments in TARGS.  */
16269       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
16270         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
16271     }
16272
16273   /* Never do unification on the 'this' parameter.  */
16274   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
16275
16276   if (return_type)
16277     {
16278       tree *new_args;
16279
16280       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
16281       new_args = XALLOCAVEC (tree, nargs + 1);
16282       new_args[0] = return_type;
16283       memcpy (new_args + 1, args, nargs * sizeof (tree));
16284       args = new_args;
16285       ++nargs;
16286     }
16287
16288   /* We allow incomplete unification without an error message here
16289      because the standard doesn't seem to explicitly prohibit it.  Our
16290      callers must be ready to deal with unification failures in any
16291      event.  */
16292
16293   TREE_VALUE (tinst) = targs;
16294   /* If we aren't explaining yet, push tinst context so we can see where
16295      any errors (e.g. from class instantiations triggered by instantiation
16296      of default template arguments) come from.  If we are explaining, this
16297      context is redundant.  */
16298   if (!explain_p && !push_tinst_level (tinst))
16299     {
16300       excessive_deduction_depth = true;
16301       goto fail;
16302     }
16303
16304   /* type_unification_real will pass back any access checks from default
16305      template argument substitution.  */
16306   vec<deferred_access_check, va_gc> *checks;
16307   checks = NULL;
16308
16309   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
16310                                targs, parms, args, nargs, /*subr=*/0,
16311                                strict, flags, &checks, explain_p);
16312   if (!explain_p)
16313     pop_tinst_level ();
16314   if (!ok)
16315     goto fail;
16316
16317   /* Now that we have bindings for all of the template arguments,
16318      ensure that the arguments deduced for the template template
16319      parameters have compatible template parameter lists.  We cannot
16320      check this property before we have deduced all template
16321      arguments, because the template parameter types of a template
16322      template parameter might depend on prior template parameters
16323      deduced after the template template parameter.  The following
16324      ill-formed example illustrates this issue:
16325
16326        template<typename T, template<T> class C> void f(C<5>, T);
16327
16328        template<int N> struct X {};
16329
16330        void g() {
16331          f(X<5>(), 5l); // error: template argument deduction fails
16332        }
16333
16334      The template parameter list of 'C' depends on the template type
16335      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
16336      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
16337      time that we deduce 'C'.  */
16338   if (!template_template_parm_bindings_ok_p
16339            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
16340     {
16341       unify_inconsistent_template_template_parameters (explain_p);
16342       goto fail;
16343     }
16344
16345   /* All is well so far.  Now, check:
16346
16347      [temp.deduct]
16348
16349      When all template arguments have been deduced, all uses of
16350      template parameters in nondeduced contexts are replaced with
16351      the corresponding deduced argument values.  If the
16352      substitution results in an invalid type, as described above,
16353      type deduction fails.  */
16354   TREE_VALUE (tinst) = targs;
16355   if (!push_tinst_level (tinst))
16356     {
16357       excessive_deduction_depth = true;
16358       goto fail;
16359     }
16360
16361   /* Also collect access checks from the instantiation.  */
16362   reopen_deferring_access_checks (checks);
16363
16364   decl = instantiate_template (fn, targs, complain);
16365
16366   checks = get_deferred_access_checks ();
16367   pop_deferring_access_checks ();
16368
16369   pop_tinst_level ();
16370
16371   if (decl == error_mark_node)
16372     goto fail;
16373
16374   /* Now perform any access checks encountered during substitution.  */
16375   push_access_scope (decl);
16376   ok = perform_access_checks (checks, complain);
16377   pop_access_scope (decl);
16378   if (!ok)
16379     goto fail;
16380
16381   /* If we're looking for an exact match, check that what we got
16382      is indeed an exact match.  It might not be if some template
16383      parameters are used in non-deduced contexts.  But don't check
16384      for an exact match if we have dependent template arguments;
16385      in that case we're doing partial ordering, and we already know
16386      that we have two candidates that will provide the actual type.  */
16387   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
16388     {
16389       tree substed = TREE_TYPE (decl);
16390       unsigned int i;
16391
16392       tree sarg
16393         = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
16394       if (return_type)
16395         sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
16396       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
16397         if (!same_type_p (args[i], TREE_VALUE (sarg)))
16398           {
16399             unify_type_mismatch (explain_p, args[i],
16400                                  TREE_VALUE (sarg));
16401             goto fail;
16402           }
16403     }
16404
16405   r = decl;
16406
16407  fail:
16408   --deduction_depth;
16409   if (excessive_deduction_depth)
16410     {
16411       if (deduction_depth == 0)
16412         /* Reset once we're all the way out.  */
16413         excessive_deduction_depth = false;
16414     }
16415
16416   /* We can't free this if a pending_template entry or last_error_tinst_level
16417      is pointing at it.  */
16418   if (last_pending_template == old_last_pend
16419       && last_error_tinst_level == old_error_tinst)
16420     ggc_free (tinst);
16421
16422   return r;
16423 }
16424
16425 /* Adjust types before performing type deduction, as described in
16426    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
16427    sections are symmetric.  PARM is the type of a function parameter
16428    or the return type of the conversion function.  ARG is the type of
16429    the argument passed to the call, or the type of the value
16430    initialized with the result of the conversion function.
16431    ARG_EXPR is the original argument expression, which may be null.  */
16432
16433 static int
16434 maybe_adjust_types_for_deduction (unification_kind_t strict,
16435                                   tree* parm,
16436                                   tree* arg,
16437                                   tree arg_expr)
16438 {
16439   int result = 0;
16440
16441   switch (strict)
16442     {
16443     case DEDUCE_CALL:
16444       break;
16445
16446     case DEDUCE_CONV:
16447       {
16448         /* Swap PARM and ARG throughout the remainder of this
16449            function; the handling is precisely symmetric since PARM
16450            will initialize ARG rather than vice versa.  */
16451         tree* temp = parm;
16452         parm = arg;
16453         arg = temp;
16454         break;
16455       }
16456
16457     case DEDUCE_EXACT:
16458       /* Core issue #873: Do the DR606 thing (see below) for these cases,
16459          too, but here handle it by stripping the reference from PARM
16460          rather than by adding it to ARG.  */
16461       if (TREE_CODE (*parm) == REFERENCE_TYPE
16462           && TYPE_REF_IS_RVALUE (*parm)
16463           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
16464           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
16465           && TREE_CODE (*arg) == REFERENCE_TYPE
16466           && !TYPE_REF_IS_RVALUE (*arg))
16467         *parm = TREE_TYPE (*parm);
16468       /* Nothing else to do in this case.  */
16469       return 0;
16470
16471     default:
16472       gcc_unreachable ();
16473     }
16474
16475   if (TREE_CODE (*parm) != REFERENCE_TYPE)
16476     {
16477       /* [temp.deduct.call]
16478
16479          If P is not a reference type:
16480
16481          --If A is an array type, the pointer type produced by the
16482          array-to-pointer standard conversion (_conv.array_) is
16483          used in place of A for type deduction; otherwise,
16484
16485          --If A is a function type, the pointer type produced by
16486          the function-to-pointer standard conversion
16487          (_conv.func_) is used in place of A for type deduction;
16488          otherwise,
16489
16490          --If A is a cv-qualified type, the top level
16491          cv-qualifiers of A's type are ignored for type
16492          deduction.  */
16493       if (TREE_CODE (*arg) == ARRAY_TYPE)
16494         *arg = build_pointer_type (TREE_TYPE (*arg));
16495       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
16496         *arg = build_pointer_type (*arg);
16497       else
16498         *arg = TYPE_MAIN_VARIANT (*arg);
16499     }
16500
16501   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
16502      of the form T&&, where T is a template parameter, and the argument
16503      is an lvalue, T is deduced as A& */
16504   if (TREE_CODE (*parm) == REFERENCE_TYPE
16505       && TYPE_REF_IS_RVALUE (*parm)
16506       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
16507       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
16508       && (arg_expr ? real_lvalue_p (arg_expr)
16509           /* try_one_overload doesn't provide an arg_expr, but
16510              functions are always lvalues.  */
16511           : TREE_CODE (*arg) == FUNCTION_TYPE))
16512     *arg = build_reference_type (*arg);
16513
16514   /* [temp.deduct.call]
16515
16516      If P is a cv-qualified type, the top level cv-qualifiers
16517      of P's type are ignored for type deduction.  If P is a
16518      reference type, the type referred to by P is used for
16519      type deduction.  */
16520   *parm = TYPE_MAIN_VARIANT (*parm);
16521   if (TREE_CODE (*parm) == REFERENCE_TYPE)
16522     {
16523       *parm = TREE_TYPE (*parm);
16524       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
16525     }
16526
16527   /* DR 322. For conversion deduction, remove a reference type on parm
16528      too (which has been swapped into ARG).  */
16529   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
16530     *arg = TREE_TYPE (*arg);
16531
16532   return result;
16533 }
16534
16535 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
16536    template which does contain any deducible template parameters; check if
16537    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
16538    unify_one_argument.  */
16539
16540 static int
16541 check_non_deducible_conversion (tree parm, tree arg, int strict,
16542                                 int flags, bool explain_p)
16543 {
16544   tree type;
16545
16546   if (!TYPE_P (arg))
16547     type = TREE_TYPE (arg);
16548   else
16549     type = arg;
16550
16551   if (same_type_p (parm, type))
16552     return unify_success (explain_p);
16553
16554   if (strict == DEDUCE_CONV)
16555     {
16556       if (can_convert_arg (type, parm, NULL_TREE, flags,
16557                            explain_p ? tf_warning_or_error : tf_none))
16558         return unify_success (explain_p);
16559     }
16560   else if (strict != DEDUCE_EXACT)
16561     {
16562       if (can_convert_arg (parm, type,
16563                            TYPE_P (arg) ? NULL_TREE : arg,
16564                            flags, explain_p ? tf_warning_or_error : tf_none))
16565         return unify_success (explain_p);
16566     }
16567
16568   if (strict == DEDUCE_EXACT)
16569     return unify_type_mismatch (explain_p, parm, arg);
16570   else
16571     return unify_arg_conversion (explain_p, parm, type, arg);
16572 }
16573
16574 static bool uses_deducible_template_parms (tree type);
16575
16576 /* Returns true iff the expression EXPR is one from which a template
16577    argument can be deduced.  In other words, if it's an undecorated
16578    use of a template non-type parameter.  */
16579
16580 static bool
16581 deducible_expression (tree expr)
16582 {
16583   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
16584 }
16585
16586 /* Returns true iff the array domain DOMAIN uses a template parameter in a
16587    deducible way; that is, if it has a max value of <PARM> - 1.  */
16588
16589 static bool
16590 deducible_array_bound (tree domain)
16591 {
16592   if (domain == NULL_TREE)
16593     return false;
16594
16595   tree max = TYPE_MAX_VALUE (domain);
16596   if (TREE_CODE (max) != MINUS_EXPR)
16597     return false;
16598
16599   return deducible_expression (TREE_OPERAND (max, 0));
16600 }
16601
16602 /* Returns true iff the template arguments ARGS use a template parameter
16603    in a deducible way.  */
16604
16605 static bool
16606 deducible_template_args (tree args)
16607 {
16608   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
16609     {
16610       bool deducible;
16611       tree elt = TREE_VEC_ELT (args, i);
16612       if (ARGUMENT_PACK_P (elt))
16613         deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
16614       else
16615         {
16616           if (PACK_EXPANSION_P (elt))
16617             elt = PACK_EXPANSION_PATTERN (elt);
16618           if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
16619             deducible = true;
16620           else if (TYPE_P (elt))
16621             deducible = uses_deducible_template_parms (elt);
16622           else
16623             deducible = deducible_expression (elt);
16624         }
16625       if (deducible)
16626         return true;
16627     }
16628   return false;
16629 }
16630
16631 /* Returns true iff TYPE contains any deducible references to template
16632    parameters, as per 14.8.2.5.  */
16633
16634 static bool
16635 uses_deducible_template_parms (tree type)
16636 {
16637   if (PACK_EXPANSION_P (type))
16638     type = PACK_EXPANSION_PATTERN (type);
16639
16640   /* T
16641      cv-list T
16642      TT<T>
16643      TT<i>
16644      TT<> */
16645   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16646       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16647     return true;
16648
16649   /* T*
16650      T&
16651      T&&  */
16652   if (POINTER_TYPE_P (type))
16653     return uses_deducible_template_parms (TREE_TYPE (type));
16654
16655   /* T[integer-constant ]
16656      type [i]  */
16657   if (TREE_CODE (type) == ARRAY_TYPE)
16658     return (uses_deducible_template_parms (TREE_TYPE (type))
16659             || deducible_array_bound (TYPE_DOMAIN (type)));
16660
16661   /* T type ::*
16662      type T::*
16663      T T::*
16664      T (type ::*)()
16665      type (T::*)()
16666      type (type ::*)(T)
16667      type (T::*)(T)
16668      T (type ::*)(T)
16669      T (T::*)()
16670      T (T::*)(T) */
16671   if (TYPE_PTRMEM_P (type))
16672     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
16673             || (uses_deducible_template_parms
16674                 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
16675
16676   /* template-name <T> (where template-name refers to a class template)
16677      template-name <i> (where template-name refers to a class template) */
16678   if (CLASS_TYPE_P (type)
16679       && CLASSTYPE_TEMPLATE_INFO (type)
16680       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
16681     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
16682                                     (CLASSTYPE_TI_ARGS (type)));
16683
16684   /* type (T)
16685      T()
16686      T(T)  */
16687   if (TREE_CODE (type) == FUNCTION_TYPE
16688       || TREE_CODE (type) == METHOD_TYPE)
16689     {
16690       if (uses_deducible_template_parms (TREE_TYPE (type)))
16691         return true;
16692       tree parm = TYPE_ARG_TYPES (type);
16693       if (TREE_CODE (type) == METHOD_TYPE)
16694         parm = TREE_CHAIN (parm);
16695       for (; parm; parm = TREE_CHAIN (parm))
16696         if (uses_deducible_template_parms (TREE_VALUE (parm)))
16697           return true;
16698     }
16699
16700   return false;
16701 }
16702
16703 /* Subroutine of type_unification_real and unify_pack_expansion to
16704    handle unification of a single P/A pair.  Parameters are as
16705    for those functions.  */
16706
16707 static int
16708 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
16709                     int subr, unification_kind_t strict, int flags,
16710                     bool explain_p)
16711 {
16712   tree arg_expr = NULL_TREE;
16713   int arg_strict;
16714
16715   if (arg == error_mark_node || parm == error_mark_node)
16716     return unify_invalid (explain_p);
16717   if (arg == unknown_type_node)
16718     /* We can't deduce anything from this, but we might get all the
16719        template args from other function args.  */
16720     return unify_success (explain_p);
16721
16722   /* Implicit conversions (Clause 4) will be performed on a function
16723      argument to convert it to the type of the corresponding function
16724      parameter if the parameter type contains no template-parameters that
16725      participate in template argument deduction.  */
16726   if (TYPE_P (parm) && !uses_template_parms (parm))
16727     /* For function parameters that contain no template-parameters at all,
16728        we have historically checked for convertibility in order to shortcut
16729        consideration of this candidate.  */
16730     return check_non_deducible_conversion (parm, arg, strict, flags,
16731                                            explain_p);
16732   else if (strict == DEDUCE_CALL
16733            && TYPE_P (parm) && !uses_deducible_template_parms (parm))
16734     /* For function parameters with only non-deducible template parameters,
16735        just return.  */
16736     return unify_success (explain_p);
16737
16738   switch (strict)
16739     {
16740     case DEDUCE_CALL:
16741       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
16742                     | UNIFY_ALLOW_MORE_CV_QUAL
16743                     | UNIFY_ALLOW_DERIVED);
16744       break;
16745
16746     case DEDUCE_CONV:
16747       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
16748       break;
16749
16750     case DEDUCE_EXACT:
16751       arg_strict = UNIFY_ALLOW_NONE;
16752       break;
16753
16754     default:
16755       gcc_unreachable ();
16756     }
16757
16758   /* We only do these transformations if this is the top-level
16759      parameter_type_list in a call or declaration matching; in other
16760      situations (nested function declarators, template argument lists) we
16761      won't be comparing a type to an expression, and we don't do any type
16762      adjustments.  */
16763   if (!subr)
16764     {
16765       if (!TYPE_P (arg))
16766         {
16767           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
16768           if (type_unknown_p (arg))
16769             {
16770               /* [temp.deduct.type] A template-argument can be
16771                  deduced from a pointer to function or pointer
16772                  to member function argument if the set of
16773                  overloaded functions does not contain function
16774                  templates and at most one of a set of
16775                  overloaded functions provides a unique
16776                  match.  */
16777
16778               if (resolve_overloaded_unification
16779                   (tparms, targs, parm, arg, strict,
16780                    arg_strict, explain_p))
16781                 return unify_success (explain_p);
16782               return unify_overload_resolution_failure (explain_p, arg);
16783             }
16784
16785           arg_expr = arg;
16786           arg = unlowered_expr_type (arg);
16787           if (arg == error_mark_node)
16788             return unify_invalid (explain_p);
16789         }
16790
16791       arg_strict |=
16792         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
16793     }
16794   else
16795     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
16796         != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
16797       return unify_template_argument_mismatch (explain_p, parm, arg);
16798
16799   /* For deduction from an init-list we need the actual list.  */
16800   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
16801     arg = arg_expr;
16802   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
16803 }
16804
16805 /* Most parms like fn_type_unification.
16806
16807    If SUBR is 1, we're being called recursively (to unify the
16808    arguments of a function or method parameter of a function
16809    template).
16810
16811    CHECKS is a pointer to a vector of access checks encountered while
16812    substituting default template arguments.  */
16813
16814 static int
16815 type_unification_real (tree tparms,
16816                        tree targs,
16817                        tree xparms,
16818                        const tree *xargs,
16819                        unsigned int xnargs,
16820                        int subr,
16821                        unification_kind_t strict,
16822                        int flags,
16823                        vec<deferred_access_check, va_gc> **checks,
16824                        bool explain_p)
16825 {
16826   tree parm, arg;
16827   int i;
16828   int ntparms = TREE_VEC_LENGTH (tparms);
16829   int saw_undeduced = 0;
16830   tree parms;
16831   const tree *args;
16832   unsigned int nargs;
16833   unsigned int ia;
16834
16835   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
16836   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
16837   gcc_assert (ntparms > 0);
16838
16839   /* Reset the number of non-defaulted template arguments contained
16840      in TARGS.  */
16841   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
16842
16843  again:
16844   parms = xparms;
16845   args = xargs;
16846   nargs = xnargs;
16847
16848   ia = 0;
16849   while (parms && parms != void_list_node
16850          && ia < nargs)
16851     {
16852       parm = TREE_VALUE (parms);
16853
16854       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
16855           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
16856         /* For a function parameter pack that occurs at the end of the
16857            parameter-declaration-list, the type A of each remaining
16858            argument of the call is compared with the type P of the
16859            declarator-id of the function parameter pack.  */
16860         break;
16861
16862       parms = TREE_CHAIN (parms);
16863
16864       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
16865         /* For a function parameter pack that does not occur at the
16866            end of the parameter-declaration-list, the type of the
16867            parameter pack is a non-deduced context.  */
16868         continue;
16869
16870       arg = args[ia];
16871       ++ia;
16872
16873       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
16874                               flags, explain_p))
16875         return 1;
16876     }
16877
16878   if (parms 
16879       && parms != void_list_node
16880       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
16881     {
16882       /* Unify the remaining arguments with the pack expansion type.  */
16883       tree argvec;
16884       tree parmvec = make_tree_vec (1);
16885
16886       /* Allocate a TREE_VEC and copy in all of the arguments */ 
16887       argvec = make_tree_vec (nargs - ia);
16888       for (i = 0; ia < nargs; ++ia, ++i)
16889         TREE_VEC_ELT (argvec, i) = args[ia];
16890
16891       /* Copy the parameter into parmvec.  */
16892       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
16893       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
16894                                 /*subr=*/subr, explain_p))
16895         return 1;
16896
16897       /* Advance to the end of the list of parameters.  */
16898       parms = TREE_CHAIN (parms);
16899     }
16900
16901   /* Fail if we've reached the end of the parm list, and more args
16902      are present, and the parm list isn't variadic.  */
16903   if (ia < nargs && parms == void_list_node)
16904     return unify_too_many_arguments (explain_p, nargs, ia);
16905   /* Fail if parms are left and they don't have default values and
16906      they aren't all deduced as empty packs (c++/57397).  This is
16907      consistent with sufficient_parms_p.  */
16908   if (parms && parms != void_list_node
16909       && TREE_PURPOSE (parms) == NULL_TREE)
16910     {
16911       unsigned int count = nargs;
16912       tree p = parms;
16913       bool type_pack_p;
16914       do
16915         {
16916           type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
16917           if (!type_pack_p)
16918             count++;
16919           p = TREE_CHAIN (p);
16920         }
16921       while (p && p != void_list_node);
16922       if (count != nargs)
16923         return unify_too_few_arguments (explain_p, ia, count,
16924                                         type_pack_p);
16925     }
16926
16927   if (!subr)
16928     {
16929       tsubst_flags_t complain = (explain_p
16930                                  ? tf_warning_or_error
16931                                  : tf_none);
16932
16933       for (i = 0; i < ntparms; i++)
16934         {
16935           tree targ = TREE_VEC_ELT (targs, i);
16936           tree tparm = TREE_VEC_ELT (tparms, i);
16937
16938           /* Clear the "incomplete" flags on all argument packs now so that
16939              substituting them into later default arguments works.  */
16940           if (targ && ARGUMENT_PACK_P (targ))
16941             {
16942               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
16943               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
16944             }
16945
16946           if (targ || tparm == error_mark_node)
16947             continue;
16948           tparm = TREE_VALUE (tparm);
16949
16950           /* If this is an undeduced nontype parameter that depends on
16951              a type parameter, try another pass; its type may have been
16952              deduced from a later argument than the one from which
16953              this parameter can be deduced.  */
16954           if (TREE_CODE (tparm) == PARM_DECL
16955               && uses_template_parms (TREE_TYPE (tparm))
16956               && !saw_undeduced++)
16957             goto again;
16958
16959           /* Core issue #226 (C++0x) [temp.deduct]:
16960
16961              If a template argument has not been deduced, its
16962              default template argument, if any, is used. 
16963
16964              When we are in C++98 mode, TREE_PURPOSE will either
16965              be NULL_TREE or ERROR_MARK_NODE, so we do not need
16966              to explicitly check cxx_dialect here.  */
16967           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
16968             {
16969               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
16970               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
16971               reopen_deferring_access_checks (*checks);
16972               location_t save_loc = input_location;
16973               if (DECL_P (parm))
16974                 input_location = DECL_SOURCE_LOCATION (parm);
16975               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
16976               arg = convert_template_argument (parm, arg, targs, complain,
16977                                                i, NULL_TREE);
16978               input_location = save_loc;
16979               *checks = get_deferred_access_checks ();
16980               pop_deferring_access_checks ();
16981               if (arg == error_mark_node)
16982                 return 1;
16983               else
16984                 {
16985                   TREE_VEC_ELT (targs, i) = arg;
16986                   /* The position of the first default template argument,
16987                      is also the number of non-defaulted arguments in TARGS.
16988                      Record that.  */
16989                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
16990                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
16991                   continue;
16992                 }
16993             }
16994
16995           /* If the type parameter is a parameter pack, then it will
16996              be deduced to an empty parameter pack.  */
16997           if (template_parameter_pack_p (tparm))
16998             {
16999               tree arg;
17000
17001               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
17002                 {
17003                   arg = make_node (NONTYPE_ARGUMENT_PACK);
17004                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
17005                   TREE_CONSTANT (arg) = 1;
17006                 }
17007               else
17008                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
17009
17010               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
17011
17012               TREE_VEC_ELT (targs, i) = arg;
17013               continue;
17014             }
17015
17016           return unify_parameter_deduction_failure (explain_p, tparm);
17017         }
17018     }
17019 #ifdef ENABLE_CHECKING
17020   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
17021     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
17022 #endif
17023
17024   return unify_success (explain_p);
17025 }
17026
17027 /* Subroutine of type_unification_real.  Args are like the variables
17028    at the call site.  ARG is an overloaded function (or template-id);
17029    we try deducing template args from each of the overloads, and if
17030    only one succeeds, we go with that.  Modifies TARGS and returns
17031    true on success.  */
17032
17033 static bool
17034 resolve_overloaded_unification (tree tparms,
17035                                 tree targs,
17036                                 tree parm,
17037                                 tree arg,
17038                                 unification_kind_t strict,
17039                                 int sub_strict,
17040                                 bool explain_p)
17041 {
17042   tree tempargs = copy_node (targs);
17043   int good = 0;
17044   tree goodfn = NULL_TREE;
17045   bool addr_p;
17046
17047   if (TREE_CODE (arg) == ADDR_EXPR)
17048     {
17049       arg = TREE_OPERAND (arg, 0);
17050       addr_p = true;
17051     }
17052   else
17053     addr_p = false;
17054
17055   if (TREE_CODE (arg) == COMPONENT_REF)
17056     /* Handle `&x' where `x' is some static or non-static member
17057        function name.  */
17058     arg = TREE_OPERAND (arg, 1);
17059
17060   if (TREE_CODE (arg) == OFFSET_REF)
17061     arg = TREE_OPERAND (arg, 1);
17062
17063   /* Strip baselink information.  */
17064   if (BASELINK_P (arg))
17065     arg = BASELINK_FUNCTIONS (arg);
17066
17067   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
17068     {
17069       /* If we got some explicit template args, we need to plug them into
17070          the affected templates before we try to unify, in case the
17071          explicit args will completely resolve the templates in question.  */
17072
17073       int ok = 0;
17074       tree expl_subargs = TREE_OPERAND (arg, 1);
17075       arg = TREE_OPERAND (arg, 0);
17076
17077       for (; arg; arg = OVL_NEXT (arg))
17078         {
17079           tree fn = OVL_CURRENT (arg);
17080           tree subargs, elem;
17081
17082           if (TREE_CODE (fn) != TEMPLATE_DECL)
17083             continue;
17084
17085           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
17086                                            expl_subargs, NULL_TREE, tf_none,
17087                                            /*require_all_args=*/true,
17088                                            /*use_default_args=*/true);
17089           if (subargs != error_mark_node
17090               && !any_dependent_template_arguments_p (subargs))
17091             {
17092               elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
17093               if (try_one_overload (tparms, targs, tempargs, parm,
17094                                     elem, strict, sub_strict, addr_p, explain_p)
17095                   && (!goodfn || !same_type_p (goodfn, elem)))
17096                 {
17097                   goodfn = elem;
17098                   ++good;
17099                 }
17100             }
17101           else if (subargs)
17102             ++ok;
17103         }
17104       /* If no templates (or more than one) are fully resolved by the
17105          explicit arguments, this template-id is a non-deduced context; it
17106          could still be OK if we deduce all template arguments for the
17107          enclosing call through other arguments.  */
17108       if (good != 1)
17109         good = ok;
17110     }
17111   else if (TREE_CODE (arg) != OVERLOAD
17112            && TREE_CODE (arg) != FUNCTION_DECL)
17113     /* If ARG is, for example, "(0, &f)" then its type will be unknown
17114        -- but the deduction does not succeed because the expression is
17115        not just the function on its own.  */
17116     return false;
17117   else
17118     for (; arg; arg = OVL_NEXT (arg))
17119       if (try_one_overload (tparms, targs, tempargs, parm,
17120                             TREE_TYPE (OVL_CURRENT (arg)),
17121                             strict, sub_strict, addr_p, explain_p)
17122           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
17123         {
17124           goodfn = OVL_CURRENT (arg);
17125           ++good;
17126         }
17127
17128   /* [temp.deduct.type] A template-argument can be deduced from a pointer
17129      to function or pointer to member function argument if the set of
17130      overloaded functions does not contain function templates and at most
17131      one of a set of overloaded functions provides a unique match.
17132
17133      So if we found multiple possibilities, we return success but don't
17134      deduce anything.  */
17135
17136   if (good == 1)
17137     {
17138       int i = TREE_VEC_LENGTH (targs);
17139       for (; i--; )
17140         if (TREE_VEC_ELT (tempargs, i))
17141           {
17142             tree old = TREE_VEC_ELT (targs, i);
17143             tree new_ = TREE_VEC_ELT (tempargs, i);
17144             if (new_ && old && ARGUMENT_PACK_P (old)
17145                 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
17146               /* Don't forget explicit template arguments in a pack.  */
17147               ARGUMENT_PACK_EXPLICIT_ARGS (new_)
17148                 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
17149             TREE_VEC_ELT (targs, i) = new_;
17150           }
17151     }
17152   if (good)
17153     return true;
17154
17155   return false;
17156 }
17157
17158 /* Core DR 115: In contexts where deduction is done and fails, or in
17159    contexts where deduction is not done, if a template argument list is
17160    specified and it, along with any default template arguments, identifies
17161    a single function template specialization, then the template-id is an
17162    lvalue for the function template specialization.  */
17163
17164 tree
17165 resolve_nondeduced_context (tree orig_expr)
17166 {
17167   tree expr, offset, baselink;
17168   bool addr;
17169
17170   if (!type_unknown_p (orig_expr))
17171     return orig_expr;
17172
17173   expr = orig_expr;
17174   addr = false;
17175   offset = NULL_TREE;
17176   baselink = NULL_TREE;
17177
17178   if (TREE_CODE (expr) == ADDR_EXPR)
17179     {
17180       expr = TREE_OPERAND (expr, 0);
17181       addr = true;
17182     }
17183   if (TREE_CODE (expr) == OFFSET_REF)
17184     {
17185       offset = expr;
17186       expr = TREE_OPERAND (expr, 1);
17187     }
17188   if (BASELINK_P (expr))
17189     {
17190       baselink = expr;
17191       expr = BASELINK_FUNCTIONS (expr);
17192     }
17193
17194   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
17195     {
17196       int good = 0;
17197       tree goodfn = NULL_TREE;
17198
17199       /* If we got some explicit template args, we need to plug them into
17200          the affected templates before we try to unify, in case the
17201          explicit args will completely resolve the templates in question.  */
17202
17203       tree expl_subargs = TREE_OPERAND (expr, 1);
17204       tree arg = TREE_OPERAND (expr, 0);
17205       tree badfn = NULL_TREE;
17206       tree badargs = NULL_TREE;
17207
17208       for (; arg; arg = OVL_NEXT (arg))
17209         {
17210           tree fn = OVL_CURRENT (arg);
17211           tree subargs, elem;
17212
17213           if (TREE_CODE (fn) != TEMPLATE_DECL)
17214             continue;
17215
17216           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
17217                                            expl_subargs, NULL_TREE, tf_none,
17218                                            /*require_all_args=*/true,
17219                                            /*use_default_args=*/true);
17220           if (subargs != error_mark_node
17221               && !any_dependent_template_arguments_p (subargs))
17222             {
17223               elem = instantiate_template (fn, subargs, tf_none);
17224               if (elem == error_mark_node)
17225                 {
17226                   badfn = fn;
17227                   badargs = subargs;
17228                 }
17229               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
17230                 {
17231                   goodfn = elem;
17232                   ++good;
17233                 }
17234             }
17235         }
17236       if (good == 1)
17237         {
17238           mark_used (goodfn);
17239           expr = goodfn;
17240           if (baselink)
17241             expr = build_baselink (BASELINK_BINFO (baselink),
17242                                    BASELINK_ACCESS_BINFO (baselink),
17243                                    expr, BASELINK_OPTYPE (baselink));
17244           if (offset)
17245             {
17246               tree base
17247                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
17248               expr = build_offset_ref (base, expr, addr, tf_warning_or_error);
17249             }
17250           if (addr)
17251             expr = cp_build_addr_expr (expr, tf_warning_or_error);
17252           return expr;
17253         }
17254       else if (good == 0 && badargs)
17255         /* There were no good options and at least one bad one, so let the
17256            user know what the problem is.  */
17257         instantiate_template (badfn, badargs, tf_warning_or_error);
17258     }
17259   return orig_expr;
17260 }
17261
17262 /* Subroutine of resolve_overloaded_unification; does deduction for a single
17263    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
17264    different overloads deduce different arguments for a given parm.
17265    ADDR_P is true if the expression for which deduction is being
17266    performed was of the form "& fn" rather than simply "fn".
17267
17268    Returns 1 on success.  */
17269
17270 static int
17271 try_one_overload (tree tparms,
17272                   tree orig_targs,
17273                   tree targs,
17274                   tree parm,
17275                   tree arg,
17276                   unification_kind_t strict,
17277                   int sub_strict,
17278                   bool addr_p,
17279                   bool explain_p)
17280 {
17281   int nargs;
17282   tree tempargs;
17283   int i;
17284
17285   if (arg == error_mark_node)
17286     return 0;
17287
17288   /* [temp.deduct.type] A template-argument can be deduced from a pointer
17289      to function or pointer to member function argument if the set of
17290      overloaded functions does not contain function templates and at most
17291      one of a set of overloaded functions provides a unique match.
17292
17293      So if this is a template, just return success.  */
17294
17295   if (uses_template_parms (arg))
17296     return 1;
17297
17298   if (TREE_CODE (arg) == METHOD_TYPE)
17299     arg = build_ptrmemfunc_type (build_pointer_type (arg));
17300   else if (addr_p)
17301     arg = build_pointer_type (arg);
17302
17303   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
17304
17305   /* We don't copy orig_targs for this because if we have already deduced
17306      some template args from previous args, unify would complain when we
17307      try to deduce a template parameter for the same argument, even though
17308      there isn't really a conflict.  */
17309   nargs = TREE_VEC_LENGTH (targs);
17310   tempargs = make_tree_vec (nargs);
17311
17312   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
17313     return 0;
17314
17315   /* First make sure we didn't deduce anything that conflicts with
17316      explicitly specified args.  */
17317   for (i = nargs; i--; )
17318     {
17319       tree elt = TREE_VEC_ELT (tempargs, i);
17320       tree oldelt = TREE_VEC_ELT (orig_targs, i);
17321
17322       if (!elt)
17323         /*NOP*/;
17324       else if (uses_template_parms (elt))
17325         /* Since we're unifying against ourselves, we will fill in
17326            template args used in the function parm list with our own
17327            template parms.  Discard them.  */
17328         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
17329       else if (oldelt && !template_args_equal (oldelt, elt))
17330         return 0;
17331     }
17332
17333   for (i = nargs; i--; )
17334     {
17335       tree elt = TREE_VEC_ELT (tempargs, i);
17336
17337       if (elt)
17338         TREE_VEC_ELT (targs, i) = elt;
17339     }
17340
17341   return 1;
17342 }
17343
17344 /* PARM is a template class (perhaps with unbound template
17345    parameters).  ARG is a fully instantiated type.  If ARG can be
17346    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
17347    TARGS are as for unify.  */
17348
17349 static tree
17350 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
17351                        bool explain_p)
17352 {
17353   tree copy_of_targs;
17354
17355   if (!CLASSTYPE_TEMPLATE_INFO (arg)
17356       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
17357           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
17358     return NULL_TREE;
17359
17360   /* We need to make a new template argument vector for the call to
17361      unify.  If we used TARGS, we'd clutter it up with the result of
17362      the attempted unification, even if this class didn't work out.
17363      We also don't want to commit ourselves to all the unifications
17364      we've already done, since unification is supposed to be done on
17365      an argument-by-argument basis.  In other words, consider the
17366      following pathological case:
17367
17368        template <int I, int J, int K>
17369        struct S {};
17370
17371        template <int I, int J>
17372        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
17373
17374        template <int I, int J, int K>
17375        void f(S<I, J, K>, S<I, I, I>);
17376
17377        void g() {
17378          S<0, 0, 0> s0;
17379          S<0, 1, 2> s2;
17380
17381          f(s0, s2);
17382        }
17383
17384      Now, by the time we consider the unification involving `s2', we
17385      already know that we must have `f<0, 0, 0>'.  But, even though
17386      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
17387      because there are two ways to unify base classes of S<0, 1, 2>
17388      with S<I, I, I>.  If we kept the already deduced knowledge, we
17389      would reject the possibility I=1.  */
17390   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
17391
17392   /* If unification failed, we're done.  */
17393   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
17394              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
17395     return NULL_TREE;
17396
17397   return arg;
17398 }
17399
17400 /* Given a template type PARM and a class type ARG, find the unique
17401    base type in ARG that is an instance of PARM.  We do not examine
17402    ARG itself; only its base-classes.  If there is not exactly one
17403    appropriate base class, return NULL_TREE.  PARM may be the type of
17404    a partial specialization, as well as a plain template type.  Used
17405    by unify.  */
17406
17407 static enum template_base_result
17408 get_template_base (tree tparms, tree targs, tree parm, tree arg,
17409                    bool explain_p, tree *result)
17410 {
17411   tree rval = NULL_TREE;
17412   tree binfo;
17413
17414   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
17415
17416   binfo = TYPE_BINFO (complete_type (arg));
17417   if (!binfo)
17418     {
17419       /* The type could not be completed.  */
17420       *result = NULL_TREE;
17421       return tbr_incomplete_type;
17422     }
17423
17424   /* Walk in inheritance graph order.  The search order is not
17425      important, and this avoids multiple walks of virtual bases.  */
17426   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
17427     {
17428       tree r = try_class_unification (tparms, targs, parm,
17429                                       BINFO_TYPE (binfo), explain_p);
17430
17431       if (r)
17432         {
17433           /* If there is more than one satisfactory baseclass, then:
17434
17435                [temp.deduct.call]
17436
17437               If they yield more than one possible deduced A, the type
17438               deduction fails.
17439
17440              applies.  */
17441           if (rval && !same_type_p (r, rval))
17442             {
17443               *result = NULL_TREE;
17444               return tbr_ambiguous_baseclass;
17445             }
17446
17447           rval = r;
17448         }
17449     }
17450
17451   *result = rval;
17452   return tbr_success;
17453 }
17454
17455 /* Returns the level of DECL, which declares a template parameter.  */
17456
17457 static int
17458 template_decl_level (tree decl)
17459 {
17460   switch (TREE_CODE (decl))
17461     {
17462     case TYPE_DECL:
17463     case TEMPLATE_DECL:
17464       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
17465
17466     case PARM_DECL:
17467       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
17468
17469     default:
17470       gcc_unreachable ();
17471     }
17472   return 0;
17473 }
17474
17475 /* Decide whether ARG can be unified with PARM, considering only the
17476    cv-qualifiers of each type, given STRICT as documented for unify.
17477    Returns nonzero iff the unification is OK on that basis.  */
17478
17479 static int
17480 check_cv_quals_for_unify (int strict, tree arg, tree parm)
17481 {
17482   int arg_quals = cp_type_quals (arg);
17483   int parm_quals = cp_type_quals (parm);
17484
17485   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
17486       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
17487     {
17488       /*  Although a CVR qualifier is ignored when being applied to a
17489           substituted template parameter ([8.3.2]/1 for example), that
17490           does not allow us to unify "const T" with "int&" because both
17491           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
17492           It is ok when we're allowing additional CV qualifiers
17493           at the outer level [14.8.2.1]/3,1st bullet.  */
17494       if ((TREE_CODE (arg) == REFERENCE_TYPE
17495            || TREE_CODE (arg) == FUNCTION_TYPE
17496            || TREE_CODE (arg) == METHOD_TYPE)
17497           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
17498         return 0;
17499
17500       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
17501           && (parm_quals & TYPE_QUAL_RESTRICT))
17502         return 0;
17503     }
17504
17505   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
17506       && (arg_quals & parm_quals) != parm_quals)
17507     return 0;
17508
17509   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
17510       && (parm_quals & arg_quals) != arg_quals)
17511     return 0;
17512
17513   return 1;
17514 }
17515
17516 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
17517 void 
17518 template_parm_level_and_index (tree parm, int* level, int* index)
17519 {
17520   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
17521       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
17522       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
17523     {
17524       *index = TEMPLATE_TYPE_IDX (parm);
17525       *level = TEMPLATE_TYPE_LEVEL (parm);
17526     }
17527   else
17528     {
17529       *index = TEMPLATE_PARM_IDX (parm);
17530       *level = TEMPLATE_PARM_LEVEL (parm);
17531     }
17532 }
17533
17534 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
17535   do {                                                                  \
17536     if (unify (TP, TA, P, A, S, EP))                                    \
17537       return 1;                                                         \
17538   } while (0);
17539
17540 /* Unifies the remaining arguments in PACKED_ARGS with the pack
17541    expansion at the end of PACKED_PARMS. Returns 0 if the type
17542    deduction succeeds, 1 otherwise. STRICT is the same as in
17543    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
17544    call argument list. We'll need to adjust the arguments to make them
17545    types. SUBR tells us if this is from a recursive call to
17546    type_unification_real, or for comparing two template argument
17547    lists. */
17548
17549 static int
17550 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
17551                       tree packed_args, unification_kind_t strict,
17552                       bool subr, bool explain_p)
17553 {
17554   tree parm 
17555     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
17556   tree pattern = PACK_EXPANSION_PATTERN (parm);
17557   tree pack, packs = NULL_TREE;
17558   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
17559
17560   packed_args = expand_template_argument_pack (packed_args);
17561
17562   int len = TREE_VEC_LENGTH (packed_args);
17563
17564   /* Determine the parameter packs we will be deducing from the
17565      pattern, and record their current deductions.  */
17566   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
17567        pack; pack = TREE_CHAIN (pack))
17568     {
17569       tree parm_pack = TREE_VALUE (pack);
17570       int idx, level;
17571
17572       /* Determine the index and level of this parameter pack.  */
17573       template_parm_level_and_index (parm_pack, &level, &idx);
17574
17575       /* Keep track of the parameter packs and their corresponding
17576          argument packs.  */
17577       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
17578       TREE_TYPE (packs) = make_tree_vec (len - start);
17579     }
17580   
17581   /* Loop through all of the arguments that have not yet been
17582      unified and unify each with the pattern.  */
17583   for (i = start; i < len; i++)
17584     {
17585       tree parm;
17586       bool any_explicit = false;
17587       tree arg = TREE_VEC_ELT (packed_args, i);
17588
17589       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
17590          or the element of its argument pack at the current index if
17591          this argument was explicitly specified.  */
17592       for (pack = packs; pack; pack = TREE_CHAIN (pack))
17593         {
17594           int idx, level;
17595           tree arg, pargs;
17596           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
17597
17598           arg = NULL_TREE;
17599           if (TREE_VALUE (pack)
17600               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
17601               && (i - start < TREE_VEC_LENGTH (pargs)))
17602             {
17603               any_explicit = true;
17604               arg = TREE_VEC_ELT (pargs, i - start);
17605             }
17606           TMPL_ARG (targs, level, idx) = arg;
17607         }
17608
17609       /* If we had explicit template arguments, substitute them into the
17610          pattern before deduction.  */
17611       if (any_explicit)
17612         {
17613           /* Some arguments might still be unspecified or dependent.  */
17614           bool dependent;
17615           ++processing_template_decl;
17616           dependent = any_dependent_template_arguments_p (targs);
17617           if (!dependent)
17618             --processing_template_decl;
17619           parm = tsubst (pattern, targs,
17620                          explain_p ? tf_warning_or_error : tf_none,
17621                          NULL_TREE);
17622           if (dependent)
17623             --processing_template_decl;
17624           if (parm == error_mark_node)
17625             return 1;
17626         }
17627       else
17628         parm = pattern;
17629
17630       /* Unify the pattern with the current argument.  */
17631       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
17632                               LOOKUP_IMPLICIT, explain_p))
17633         return 1;
17634
17635       /* For each parameter pack, collect the deduced value.  */
17636       for (pack = packs; pack; pack = TREE_CHAIN (pack))
17637         {
17638           int idx, level;
17639           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
17640
17641           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
17642             TMPL_ARG (targs, level, idx);
17643         }
17644     }
17645
17646   /* Verify that the results of unification with the parameter packs
17647      produce results consistent with what we've seen before, and make
17648      the deduced argument packs available.  */
17649   for (pack = packs; pack; pack = TREE_CHAIN (pack))
17650     {
17651       tree old_pack = TREE_VALUE (pack);
17652       tree new_args = TREE_TYPE (pack);
17653       int i, len = TREE_VEC_LENGTH (new_args);
17654       int idx, level;
17655       bool nondeduced_p = false;
17656
17657       /* By default keep the original deduced argument pack.
17658          If necessary, more specific code is going to update the
17659          resulting deduced argument later down in this function.  */
17660       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
17661       TMPL_ARG (targs, level, idx) = old_pack;
17662
17663       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
17664          actually deduce anything.  */
17665       for (i = 0; i < len && !nondeduced_p; ++i)
17666         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
17667           nondeduced_p = true;
17668       if (nondeduced_p)
17669         continue;
17670
17671       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
17672         {
17673           /* If we had fewer function args than explicit template args,
17674              just use the explicits.  */
17675           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
17676           int explicit_len = TREE_VEC_LENGTH (explicit_args);
17677           if (len < explicit_len)
17678             new_args = explicit_args;
17679         }
17680
17681       if (!old_pack)
17682         {
17683           tree result;
17684           /* Build the deduced *_ARGUMENT_PACK.  */
17685           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
17686             {
17687               result = make_node (NONTYPE_ARGUMENT_PACK);
17688               TREE_TYPE (result) = 
17689                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
17690               TREE_CONSTANT (result) = 1;
17691             }
17692           else
17693             result = cxx_make_type (TYPE_ARGUMENT_PACK);
17694
17695           SET_ARGUMENT_PACK_ARGS (result, new_args);
17696
17697           /* Note the deduced argument packs for this parameter
17698              pack.  */
17699           TMPL_ARG (targs, level, idx) = result;
17700         }
17701       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
17702                && (ARGUMENT_PACK_ARGS (old_pack) 
17703                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
17704         {
17705           /* We only had the explicitly-provided arguments before, but
17706              now we have a complete set of arguments.  */
17707           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
17708
17709           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
17710           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
17711           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
17712         }
17713       else
17714         {
17715           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
17716           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
17717
17718           if (!comp_template_args_with_info (old_args, new_args,
17719                                              &bad_old_arg, &bad_new_arg))
17720             /* Inconsistent unification of this parameter pack.  */
17721             return unify_parameter_pack_inconsistent (explain_p,
17722                                                       bad_old_arg,
17723                                                       bad_new_arg);
17724         }
17725     }
17726
17727   return unify_success (explain_p);
17728 }
17729
17730 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
17731    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
17732    parameters and return value are as for unify.  */
17733
17734 static int
17735 unify_array_domain (tree tparms, tree targs,
17736                     tree parm_dom, tree arg_dom,
17737                     bool explain_p)
17738 {
17739   tree parm_max;
17740   tree arg_max;
17741   bool parm_cst;
17742   bool arg_cst;
17743
17744   /* Our representation of array types uses "N - 1" as the
17745      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
17746      not an integer constant.  We cannot unify arbitrarily
17747      complex expressions, so we eliminate the MINUS_EXPRs
17748      here.  */
17749   parm_max = TYPE_MAX_VALUE (parm_dom);
17750   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
17751   if (!parm_cst)
17752     {
17753       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
17754       parm_max = TREE_OPERAND (parm_max, 0);
17755     }
17756   arg_max = TYPE_MAX_VALUE (arg_dom);
17757   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
17758   if (!arg_cst)
17759     {
17760       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
17761          trying to unify the type of a variable with the type
17762          of a template parameter.  For example:
17763
17764            template <unsigned int N>
17765            void f (char (&) [N]);
17766            int g();
17767            void h(int i) {
17768              char a[g(i)];
17769              f(a);
17770            }
17771
17772          Here, the type of the ARG will be "int [g(i)]", and
17773          may be a SAVE_EXPR, etc.  */
17774       if (TREE_CODE (arg_max) != MINUS_EXPR)
17775         return unify_vla_arg (explain_p, arg_dom);
17776       arg_max = TREE_OPERAND (arg_max, 0);
17777     }
17778
17779   /* If only one of the bounds used a MINUS_EXPR, compensate
17780      by adding one to the other bound.  */
17781   if (parm_cst && !arg_cst)
17782     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
17783                                 integer_type_node,
17784                                 parm_max,
17785                                 integer_one_node);
17786   else if (arg_cst && !parm_cst)
17787     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
17788                                integer_type_node,
17789                                arg_max,
17790                                integer_one_node);
17791
17792   return unify (tparms, targs, parm_max, arg_max,
17793                 UNIFY_ALLOW_INTEGER, explain_p);
17794 }
17795
17796 /* Deduce the value of template parameters.  TPARMS is the (innermost)
17797    set of template parameters to a template.  TARGS is the bindings
17798    for those template parameters, as determined thus far; TARGS may
17799    include template arguments for outer levels of template parameters
17800    as well.  PARM is a parameter to a template function, or a
17801    subcomponent of that parameter; ARG is the corresponding argument.
17802    This function attempts to match PARM with ARG in a manner
17803    consistent with the existing assignments in TARGS.  If more values
17804    are deduced, then TARGS is updated.
17805
17806    Returns 0 if the type deduction succeeds, 1 otherwise.  The
17807    parameter STRICT is a bitwise or of the following flags:
17808
17809      UNIFY_ALLOW_NONE:
17810        Require an exact match between PARM and ARG.
17811      UNIFY_ALLOW_MORE_CV_QUAL:
17812        Allow the deduced ARG to be more cv-qualified (by qualification
17813        conversion) than ARG.
17814      UNIFY_ALLOW_LESS_CV_QUAL:
17815        Allow the deduced ARG to be less cv-qualified than ARG.
17816      UNIFY_ALLOW_DERIVED:
17817        Allow the deduced ARG to be a template base class of ARG,
17818        or a pointer to a template base class of the type pointed to by
17819        ARG.
17820      UNIFY_ALLOW_INTEGER:
17821        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
17822        case for more information.
17823      UNIFY_ALLOW_OUTER_LEVEL:
17824        This is the outermost level of a deduction. Used to determine validity
17825        of qualification conversions. A valid qualification conversion must
17826        have const qualified pointers leading up to the inner type which
17827        requires additional CV quals, except at the outer level, where const
17828        is not required [conv.qual]. It would be normal to set this flag in
17829        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
17830      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
17831        This is the outermost level of a deduction, and PARM can be more CV
17832        qualified at this point.
17833      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
17834        This is the outermost level of a deduction, and PARM can be less CV
17835        qualified at this point.  */
17836
17837 static int
17838 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
17839        bool explain_p)
17840 {
17841   int idx;
17842   tree targ;
17843   tree tparm;
17844   int strict_in = strict;
17845
17846   /* I don't think this will do the right thing with respect to types.
17847      But the only case I've seen it in so far has been array bounds, where
17848      signedness is the only information lost, and I think that will be
17849      okay.  */
17850   while (TREE_CODE (parm) == NOP_EXPR)
17851     parm = TREE_OPERAND (parm, 0);
17852
17853   if (arg == error_mark_node)
17854     return unify_invalid (explain_p);
17855   if (arg == unknown_type_node
17856       || arg == init_list_type_node)
17857     /* We can't deduce anything from this, but we might get all the
17858        template args from other function args.  */
17859     return unify_success (explain_p);
17860
17861   /* If PARM uses template parameters, then we can't bail out here,
17862      even if ARG == PARM, since we won't record unifications for the
17863      template parameters.  We might need them if we're trying to
17864      figure out which of two things is more specialized.  */
17865   if (arg == parm && !uses_template_parms (parm))
17866     return unify_success (explain_p);
17867
17868   /* Handle init lists early, so the rest of the function can assume
17869      we're dealing with a type. */
17870   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
17871     {
17872       tree elt, elttype;
17873       unsigned i;
17874       tree orig_parm = parm;
17875
17876       /* Replace T with std::initializer_list<T> for deduction.  */
17877       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
17878           && flag_deduce_init_list)
17879         parm = listify (parm);
17880
17881       if (!is_std_init_list (parm)
17882           && TREE_CODE (parm) != ARRAY_TYPE)
17883         /* We can only deduce from an initializer list argument if the
17884            parameter is std::initializer_list or an array; otherwise this
17885            is a non-deduced context. */
17886         return unify_success (explain_p);
17887
17888       if (TREE_CODE (parm) == ARRAY_TYPE)
17889         elttype = TREE_TYPE (parm);
17890       else
17891         {
17892           elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
17893           /* Deduction is defined in terms of a single type, so just punt
17894              on the (bizarre) std::initializer_list<T...>.  */
17895           if (PACK_EXPANSION_P (elttype))
17896             return unify_success (explain_p);
17897         }
17898
17899       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
17900         {
17901           int elt_strict = strict;
17902
17903           if (elt == error_mark_node)
17904             return unify_invalid (explain_p);
17905
17906           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
17907             {
17908               tree type = TREE_TYPE (elt);
17909               if (type == error_mark_node)
17910                 return unify_invalid (explain_p);
17911               /* It should only be possible to get here for a call.  */
17912               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
17913               elt_strict |= maybe_adjust_types_for_deduction
17914                 (DEDUCE_CALL, &elttype, &type, elt);
17915               elt = type;
17916             }
17917
17918           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
17919                                    explain_p);
17920         }
17921
17922       if (TREE_CODE (parm) == ARRAY_TYPE
17923           && deducible_array_bound (TYPE_DOMAIN (parm)))
17924         {
17925           /* Also deduce from the length of the initializer list.  */
17926           tree max = size_int (CONSTRUCTOR_NELTS (arg));
17927           tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
17928           if (idx == error_mark_node)
17929             return unify_invalid (explain_p);
17930           return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
17931                                      idx, explain_p);
17932         }
17933
17934       /* If the std::initializer_list<T> deduction worked, replace the
17935          deduced A with std::initializer_list<A>.  */
17936       if (orig_parm != parm)
17937         {
17938           idx = TEMPLATE_TYPE_IDX (orig_parm);
17939           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
17940           targ = listify (targ);
17941           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
17942         }
17943       return unify_success (explain_p);
17944     }
17945
17946   /* Immediately reject some pairs that won't unify because of
17947      cv-qualification mismatches.  */
17948   if (TREE_CODE (arg) == TREE_CODE (parm)
17949       && TYPE_P (arg)
17950       /* It is the elements of the array which hold the cv quals of an array
17951          type, and the elements might be template type parms. We'll check
17952          when we recurse.  */
17953       && TREE_CODE (arg) != ARRAY_TYPE
17954       /* We check the cv-qualifiers when unifying with template type
17955          parameters below.  We want to allow ARG `const T' to unify with
17956          PARM `T' for example, when computing which of two templates
17957          is more specialized, for example.  */
17958       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
17959       && !check_cv_quals_for_unify (strict_in, arg, parm))
17960     return unify_cv_qual_mismatch (explain_p, parm, arg);
17961
17962   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
17963       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
17964     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
17965   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
17966   strict &= ~UNIFY_ALLOW_DERIVED;
17967   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
17968   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
17969
17970   switch (TREE_CODE (parm))
17971     {
17972     case TYPENAME_TYPE:
17973     case SCOPE_REF:
17974     case UNBOUND_CLASS_TEMPLATE:
17975       /* In a type which contains a nested-name-specifier, template
17976          argument values cannot be deduced for template parameters used
17977          within the nested-name-specifier.  */
17978       return unify_success (explain_p);
17979
17980     case TEMPLATE_TYPE_PARM:
17981     case TEMPLATE_TEMPLATE_PARM:
17982     case BOUND_TEMPLATE_TEMPLATE_PARM:
17983       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
17984       if (error_operand_p (tparm))
17985         return unify_invalid (explain_p);
17986
17987       if (TEMPLATE_TYPE_LEVEL (parm)
17988           != template_decl_level (tparm))
17989         /* The PARM is not one we're trying to unify.  Just check
17990            to see if it matches ARG.  */
17991         {
17992           if (TREE_CODE (arg) == TREE_CODE (parm)
17993               && (is_auto (parm) ? is_auto (arg)
17994                   : same_type_p (parm, arg)))
17995             return unify_success (explain_p);
17996           else
17997             return unify_type_mismatch (explain_p, parm, arg);
17998         }
17999       idx = TEMPLATE_TYPE_IDX (parm);
18000       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
18001       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
18002       if (error_operand_p (tparm))
18003         return unify_invalid (explain_p);
18004
18005       /* Check for mixed types and values.  */
18006       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
18007            && TREE_CODE (tparm) != TYPE_DECL)
18008           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
18009               && TREE_CODE (tparm) != TEMPLATE_DECL))
18010         gcc_unreachable ();
18011
18012       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
18013         {
18014           /* ARG must be constructed from a template class or a template
18015              template parameter.  */
18016           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
18017               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
18018             return unify_template_deduction_failure (explain_p, parm, arg);
18019           {
18020             tree parmvec = TYPE_TI_ARGS (parm);
18021             /* An alias template name is never deduced.  */
18022             if (TYPE_ALIAS_P (arg))
18023               arg = strip_typedefs (arg);
18024             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
18025             tree full_argvec = add_to_template_args (targs, argvec);
18026             tree parm_parms 
18027               = DECL_INNERMOST_TEMPLATE_PARMS
18028                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
18029             int i, len;
18030             int parm_variadic_p = 0;
18031
18032             /* The resolution to DR150 makes clear that default
18033                arguments for an N-argument may not be used to bind T
18034                to a template template parameter with fewer than N
18035                parameters.  It is not safe to permit the binding of
18036                default arguments as an extension, as that may change
18037                the meaning of a conforming program.  Consider:
18038
18039                   struct Dense { static const unsigned int dim = 1; };
18040
18041                   template <template <typename> class View,
18042                             typename Block>
18043                   void operator+(float, View<Block> const&);
18044
18045                   template <typename Block,
18046                             unsigned int Dim = Block::dim>
18047                   struct Lvalue_proxy { operator float() const; };
18048
18049                   void
18050                   test_1d (void) {
18051                     Lvalue_proxy<Dense> p;
18052                     float b;
18053                     b + p;
18054                   }
18055
18056               Here, if Lvalue_proxy is permitted to bind to View, then
18057               the global operator+ will be used; if they are not, the
18058               Lvalue_proxy will be converted to float.  */
18059             if (coerce_template_parms (parm_parms,
18060                                        full_argvec,
18061                                        TYPE_TI_TEMPLATE (parm),
18062                                        (explain_p
18063                                         ? tf_warning_or_error
18064                                         : tf_none),
18065                                        /*require_all_args=*/true,
18066                                        /*use_default_args=*/false)
18067                 == error_mark_node)
18068               return 1;
18069
18070             /* Deduce arguments T, i from TT<T> or TT<i>.
18071                We check each element of PARMVEC and ARGVEC individually
18072                rather than the whole TREE_VEC since they can have
18073                different number of elements.  */
18074
18075             parmvec = expand_template_argument_pack (parmvec);
18076             argvec = expand_template_argument_pack (argvec);
18077
18078             len = TREE_VEC_LENGTH (parmvec);
18079
18080             /* Check if the parameters end in a pack, making them
18081                variadic.  */
18082             if (len > 0
18083                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
18084               parm_variadic_p = 1;
18085             
18086              for (i = 0; i < len - parm_variadic_p; ++i)
18087                /* If the template argument list of P contains a pack
18088                   expansion that is not the last template argument, the
18089                   entire template argument list is a non-deduced
18090                   context.  */
18091                if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
18092                  return unify_success (explain_p);
18093
18094             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
18095               return unify_too_few_arguments (explain_p,
18096                                               TREE_VEC_LENGTH (argvec), len);
18097
18098              for (i = 0; i < len - parm_variadic_p; ++i)
18099               {
18100                 RECUR_AND_CHECK_FAILURE (tparms, targs,
18101                                          TREE_VEC_ELT (parmvec, i),
18102                                          TREE_VEC_ELT (argvec, i),
18103                                          UNIFY_ALLOW_NONE, explain_p);
18104               }
18105
18106             if (parm_variadic_p
18107                 && unify_pack_expansion (tparms, targs,
18108                                          parmvec, argvec,
18109                                          DEDUCE_EXACT,
18110                                          /*subr=*/true, explain_p))
18111               return 1;
18112           }
18113           arg = TYPE_TI_TEMPLATE (arg);
18114
18115           /* Fall through to deduce template name.  */
18116         }
18117
18118       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
18119           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
18120         {
18121           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
18122
18123           /* Simple cases: Value already set, does match or doesn't.  */
18124           if (targ != NULL_TREE && template_args_equal (targ, arg))
18125             return unify_success (explain_p);
18126           else if (targ)
18127             return unify_inconsistency (explain_p, parm, targ, arg);
18128         }
18129       else
18130         {
18131           /* If PARM is `const T' and ARG is only `int', we don't have
18132              a match unless we are allowing additional qualification.
18133              If ARG is `const int' and PARM is just `T' that's OK;
18134              that binds `const int' to `T'.  */
18135           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
18136                                          arg, parm))
18137             return unify_cv_qual_mismatch (explain_p, parm, arg);
18138
18139           /* Consider the case where ARG is `const volatile int' and
18140              PARM is `const T'.  Then, T should be `volatile int'.  */
18141           arg = cp_build_qualified_type_real
18142             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
18143           if (arg == error_mark_node)
18144             return unify_invalid (explain_p);
18145
18146           /* Simple cases: Value already set, does match or doesn't.  */
18147           if (targ != NULL_TREE && same_type_p (targ, arg))
18148             return unify_success (explain_p);
18149           else if (targ)
18150             return unify_inconsistency (explain_p, parm, targ, arg);
18151
18152           /* Make sure that ARG is not a variable-sized array.  (Note
18153              that were talking about variable-sized arrays (like
18154              `int[n]'), rather than arrays of unknown size (like
18155              `int[]').)  We'll get very confused by such a type since
18156              the bound of the array is not constant, and therefore
18157              not mangleable.  Besides, such types are not allowed in
18158              ISO C++, so we can do as we please here.  We do allow
18159              them for 'auto' deduction, since that isn't ABI-exposed.  */
18160           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
18161             return unify_vla_arg (explain_p, arg);
18162
18163           /* Strip typedefs as in convert_template_argument.  */
18164           arg = canonicalize_type_argument (arg, tf_none);
18165         }
18166
18167       /* If ARG is a parameter pack or an expansion, we cannot unify
18168          against it unless PARM is also a parameter pack.  */
18169       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
18170           && !template_parameter_pack_p (parm))
18171         return unify_parameter_pack_mismatch (explain_p, parm, arg);
18172
18173       /* If the argument deduction results is a METHOD_TYPE,
18174          then there is a problem.
18175          METHOD_TYPE doesn't map to any real C++ type the result of
18176          the deduction can not be of that type.  */
18177       if (TREE_CODE (arg) == METHOD_TYPE)
18178         return unify_method_type_error (explain_p, arg);
18179
18180       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
18181       return unify_success (explain_p);
18182
18183     case TEMPLATE_PARM_INDEX:
18184       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
18185       if (error_operand_p (tparm))
18186         return unify_invalid (explain_p);
18187
18188       if (TEMPLATE_PARM_LEVEL (parm)
18189           != template_decl_level (tparm))
18190         {
18191           /* The PARM is not one we're trying to unify.  Just check
18192              to see if it matches ARG.  */
18193           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
18194                          && cp_tree_equal (parm, arg));
18195           if (result)
18196             unify_expression_unequal (explain_p, parm, arg);
18197           return result;
18198         }
18199
18200       idx = TEMPLATE_PARM_IDX (parm);
18201       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
18202
18203       if (targ)
18204         {
18205           int x = !cp_tree_equal (targ, arg);
18206           if (x)
18207             unify_inconsistency (explain_p, parm, targ, arg);
18208           return x;
18209         }
18210
18211       /* [temp.deduct.type] If, in the declaration of a function template
18212          with a non-type template-parameter, the non-type
18213          template-parameter is used in an expression in the function
18214          parameter-list and, if the corresponding template-argument is
18215          deduced, the template-argument type shall match the type of the
18216          template-parameter exactly, except that a template-argument
18217          deduced from an array bound may be of any integral type.
18218          The non-type parameter might use already deduced type parameters.  */
18219       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
18220       if (!TREE_TYPE (arg))
18221         /* Template-parameter dependent expression.  Just accept it for now.
18222            It will later be processed in convert_template_argument.  */
18223         ;
18224       else if (same_type_p (TREE_TYPE (arg), tparm))
18225         /* OK */;
18226       else if ((strict & UNIFY_ALLOW_INTEGER)
18227                && CP_INTEGRAL_TYPE_P (tparm))
18228         /* Convert the ARG to the type of PARM; the deduced non-type
18229            template argument must exactly match the types of the
18230            corresponding parameter.  */
18231         arg = fold (build_nop (tparm, arg));
18232       else if (uses_template_parms (tparm))
18233         /* We haven't deduced the type of this parameter yet.  Try again
18234            later.  */
18235         return unify_success (explain_p);
18236       else
18237         return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
18238
18239       /* If ARG is a parameter pack or an expansion, we cannot unify
18240          against it unless PARM is also a parameter pack.  */
18241       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
18242           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
18243         return unify_parameter_pack_mismatch (explain_p, parm, arg);
18244
18245       arg = strip_typedefs_expr (arg);
18246       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
18247       return unify_success (explain_p);
18248
18249     case PTRMEM_CST:
18250      {
18251         /* A pointer-to-member constant can be unified only with
18252          another constant.  */
18253       if (TREE_CODE (arg) != PTRMEM_CST)
18254         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
18255
18256       /* Just unify the class member. It would be useless (and possibly
18257          wrong, depending on the strict flags) to unify also
18258          PTRMEM_CST_CLASS, because we want to be sure that both parm and
18259          arg refer to the same variable, even if through different
18260          classes. For instance:
18261
18262          struct A { int x; };
18263          struct B : A { };
18264
18265          Unification of &A::x and &B::x must succeed.  */
18266       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
18267                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
18268      }
18269
18270     case POINTER_TYPE:
18271       {
18272         if (!TYPE_PTR_P (arg))
18273           return unify_type_mismatch (explain_p, parm, arg);
18274
18275         /* [temp.deduct.call]
18276
18277            A can be another pointer or pointer to member type that can
18278            be converted to the deduced A via a qualification
18279            conversion (_conv.qual_).
18280
18281            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
18282            This will allow for additional cv-qualification of the
18283            pointed-to types if appropriate.  */
18284
18285         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
18286           /* The derived-to-base conversion only persists through one
18287              level of pointers.  */
18288           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
18289
18290         return unify (tparms, targs, TREE_TYPE (parm),
18291                       TREE_TYPE (arg), strict, explain_p);
18292       }
18293
18294     case REFERENCE_TYPE:
18295       if (TREE_CODE (arg) != REFERENCE_TYPE)
18296         return unify_type_mismatch (explain_p, parm, arg);
18297       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
18298                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
18299
18300     case ARRAY_TYPE:
18301       if (TREE_CODE (arg) != ARRAY_TYPE)
18302         return unify_type_mismatch (explain_p, parm, arg);
18303       if ((TYPE_DOMAIN (parm) == NULL_TREE)
18304           != (TYPE_DOMAIN (arg) == NULL_TREE))
18305         return unify_type_mismatch (explain_p, parm, arg);
18306       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
18307                                strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
18308       if (TYPE_DOMAIN (parm) != NULL_TREE)
18309         return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
18310                                    TYPE_DOMAIN (arg), explain_p);
18311       return unify_success (explain_p);
18312
18313     case REAL_TYPE:
18314     case COMPLEX_TYPE:
18315     case VECTOR_TYPE:
18316     case INTEGER_TYPE:
18317     case BOOLEAN_TYPE:
18318     case ENUMERAL_TYPE:
18319     case VOID_TYPE:
18320     case NULLPTR_TYPE:
18321       if (TREE_CODE (arg) != TREE_CODE (parm))
18322         return unify_type_mismatch (explain_p, parm, arg);
18323
18324       /* We have already checked cv-qualification at the top of the
18325          function.  */
18326       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
18327         return unify_type_mismatch (explain_p, parm, arg);
18328
18329       /* As far as unification is concerned, this wins.  Later checks
18330          will invalidate it if necessary.  */
18331       return unify_success (explain_p);
18332
18333       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
18334       /* Type INTEGER_CST can come from ordinary constant template args.  */
18335     case INTEGER_CST:
18336       while (TREE_CODE (arg) == NOP_EXPR)
18337         arg = TREE_OPERAND (arg, 0);
18338
18339       if (TREE_CODE (arg) != INTEGER_CST)
18340         return unify_template_argument_mismatch (explain_p, parm, arg);
18341       return (tree_int_cst_equal (parm, arg)
18342               ? unify_success (explain_p)
18343               : unify_template_argument_mismatch (explain_p, parm, arg));
18344
18345     case TREE_VEC:
18346       {
18347         int i, len, argslen;
18348         int parm_variadic_p = 0;
18349
18350         if (TREE_CODE (arg) != TREE_VEC)
18351           return unify_template_argument_mismatch (explain_p, parm, arg);
18352
18353         len = TREE_VEC_LENGTH (parm);
18354         argslen = TREE_VEC_LENGTH (arg);
18355
18356         /* Check for pack expansions in the parameters.  */
18357         for (i = 0; i < len; ++i)
18358           {
18359             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
18360               {
18361                 if (i == len - 1)
18362                   /* We can unify against something with a trailing
18363                      parameter pack.  */
18364                   parm_variadic_p = 1;
18365                 else
18366                   /* [temp.deduct.type]/9: If the template argument list of
18367                      P contains a pack expansion that is not the last
18368                      template argument, the entire template argument list
18369                      is a non-deduced context.  */
18370                   return unify_success (explain_p);
18371               }
18372           }
18373
18374         /* If we don't have enough arguments to satisfy the parameters
18375            (not counting the pack expression at the end), or we have
18376            too many arguments for a parameter list that doesn't end in
18377            a pack expression, we can't unify.  */
18378         if (parm_variadic_p
18379             ? argslen < len - parm_variadic_p
18380             : argslen != len)
18381           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
18382
18383         /* Unify all of the parameters that precede the (optional)
18384            pack expression.  */
18385         for (i = 0; i < len - parm_variadic_p; ++i)
18386           {
18387             RECUR_AND_CHECK_FAILURE (tparms, targs,
18388                                      TREE_VEC_ELT (parm, i),
18389                                      TREE_VEC_ELT (arg, i),
18390                                      UNIFY_ALLOW_NONE, explain_p);
18391           }
18392         if (parm_variadic_p)
18393           return unify_pack_expansion (tparms, targs, parm, arg,
18394                                        DEDUCE_EXACT,
18395                                        /*subr=*/true, explain_p);
18396         return unify_success (explain_p);
18397       }
18398
18399     case RECORD_TYPE:
18400     case UNION_TYPE:
18401       if (TREE_CODE (arg) != TREE_CODE (parm))
18402         return unify_type_mismatch (explain_p, parm, arg);
18403
18404       if (TYPE_PTRMEMFUNC_P (parm))
18405         {
18406           if (!TYPE_PTRMEMFUNC_P (arg))
18407             return unify_type_mismatch (explain_p, parm, arg);
18408
18409           return unify (tparms, targs,
18410                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
18411                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
18412                         strict, explain_p);
18413         }
18414       else if (TYPE_PTRMEMFUNC_P (arg))
18415         return unify_type_mismatch (explain_p, parm, arg);
18416
18417       if (CLASSTYPE_TEMPLATE_INFO (parm))
18418         {
18419           tree t = NULL_TREE;
18420
18421           if (strict_in & UNIFY_ALLOW_DERIVED)
18422             {
18423               /* First, we try to unify the PARM and ARG directly.  */
18424               t = try_class_unification (tparms, targs,
18425                                          parm, arg, explain_p);
18426
18427               if (!t)
18428                 {
18429                   /* Fallback to the special case allowed in
18430                      [temp.deduct.call]:
18431
18432                        If P is a class, and P has the form
18433                        template-id, then A can be a derived class of
18434                        the deduced A.  Likewise, if P is a pointer to
18435                        a class of the form template-id, A can be a
18436                        pointer to a derived class pointed to by the
18437                        deduced A.  */
18438                   enum template_base_result r;
18439                   r = get_template_base (tparms, targs, parm, arg,
18440                                          explain_p, &t);
18441
18442                   if (!t)
18443                     return unify_no_common_base (explain_p, r, parm, arg);
18444                 }
18445             }
18446           else if (CLASSTYPE_TEMPLATE_INFO (arg)
18447                    && (CLASSTYPE_TI_TEMPLATE (parm)
18448                        == CLASSTYPE_TI_TEMPLATE (arg)))
18449             /* Perhaps PARM is something like S<U> and ARG is S<int>.
18450                Then, we should unify `int' and `U'.  */
18451             t = arg;
18452           else
18453             /* There's no chance of unification succeeding.  */
18454             return unify_type_mismatch (explain_p, parm, arg);
18455
18456           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
18457                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
18458         }
18459       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
18460         return unify_type_mismatch (explain_p, parm, arg);
18461       return unify_success (explain_p);
18462
18463     case METHOD_TYPE:
18464     case FUNCTION_TYPE:
18465       {
18466         unsigned int nargs;
18467         tree *args;
18468         tree a;
18469         unsigned int i;
18470
18471         if (TREE_CODE (arg) != TREE_CODE (parm))
18472           return unify_type_mismatch (explain_p, parm, arg);
18473
18474         /* CV qualifications for methods can never be deduced, they must
18475            match exactly.  We need to check them explicitly here,
18476            because type_unification_real treats them as any other
18477            cv-qualified parameter.  */
18478         if (TREE_CODE (parm) == METHOD_TYPE
18479             && (!check_cv_quals_for_unify
18480                 (UNIFY_ALLOW_NONE,
18481                  class_of_this_parm (arg),
18482                  class_of_this_parm (parm))))
18483           return unify_cv_qual_mismatch (explain_p, parm, arg);
18484
18485         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
18486                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
18487
18488         nargs = list_length (TYPE_ARG_TYPES (arg));
18489         args = XALLOCAVEC (tree, nargs);
18490         for (a = TYPE_ARG_TYPES (arg), i = 0;
18491              a != NULL_TREE && a != void_list_node;
18492              a = TREE_CHAIN (a), ++i)
18493           args[i] = TREE_VALUE (a);
18494         nargs = i;
18495
18496         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
18497                                       args, nargs, 1, DEDUCE_EXACT,
18498                                       LOOKUP_NORMAL, NULL, explain_p);
18499       }
18500
18501     case OFFSET_TYPE:
18502       /* Unify a pointer to member with a pointer to member function, which
18503          deduces the type of the member as a function type. */
18504       if (TYPE_PTRMEMFUNC_P (arg))
18505         {
18506           /* Check top-level cv qualifiers */
18507           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
18508             return unify_cv_qual_mismatch (explain_p, parm, arg);
18509
18510           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
18511                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
18512                                    UNIFY_ALLOW_NONE, explain_p);
18513
18514           /* Determine the type of the function we are unifying against. */
18515           tree fntype = static_fn_type (arg);
18516
18517           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
18518         }
18519
18520       if (TREE_CODE (arg) != OFFSET_TYPE)
18521         return unify_type_mismatch (explain_p, parm, arg);
18522       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
18523                                TYPE_OFFSET_BASETYPE (arg),
18524                                UNIFY_ALLOW_NONE, explain_p);
18525       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
18526                     strict, explain_p);
18527
18528     case CONST_DECL:
18529       if (DECL_TEMPLATE_PARM_P (parm))
18530         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
18531       if (arg != scalar_constant_value (parm))
18532         return unify_template_argument_mismatch (explain_p, parm, arg);
18533       return unify_success (explain_p);
18534
18535     case FIELD_DECL:
18536     case TEMPLATE_DECL:
18537       /* Matched cases are handled by the ARG == PARM test above.  */
18538       return unify_template_argument_mismatch (explain_p, parm, arg);
18539
18540     case VAR_DECL:
18541       /* A non-type template parameter that is a variable should be a
18542          an integral constant, in which case, it whould have been
18543          folded into its (constant) value. So we should not be getting
18544          a variable here.  */
18545       gcc_unreachable ();
18546
18547     case TYPE_ARGUMENT_PACK:
18548     case NONTYPE_ARGUMENT_PACK:
18549       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
18550                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
18551
18552     case TYPEOF_TYPE:
18553     case DECLTYPE_TYPE:
18554     case UNDERLYING_TYPE:
18555       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
18556          or UNDERLYING_TYPE nodes.  */
18557       return unify_success (explain_p);
18558
18559     case ERROR_MARK:
18560       /* Unification fails if we hit an error node.  */
18561       return unify_invalid (explain_p);
18562
18563     case INDIRECT_REF:
18564       if (REFERENCE_REF_P (parm))
18565         {
18566           if (REFERENCE_REF_P (arg))
18567             arg = TREE_OPERAND (arg, 0);
18568           return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
18569                         strict, explain_p);
18570         }
18571       /* FALLTHRU */
18572
18573     default:
18574       /* An unresolved overload is a nondeduced context.  */
18575       if (is_overloaded_fn (parm) || type_unknown_p (parm))
18576         return unify_success (explain_p);
18577       gcc_assert (EXPR_P (parm));
18578
18579       /* We must be looking at an expression.  This can happen with
18580          something like:
18581
18582            template <int I>
18583            void foo(S<I>, S<I + 2>);
18584
18585          This is a "nondeduced context":
18586
18587            [deduct.type]
18588
18589            The nondeduced contexts are:
18590
18591            --A type that is a template-id in which one or more of
18592              the template-arguments is an expression that references
18593              a template-parameter.
18594
18595          In these cases, we assume deduction succeeded, but don't
18596          actually infer any unifications.  */
18597
18598       if (!uses_template_parms (parm)
18599           && !template_args_equal (parm, arg))
18600         return unify_expression_unequal (explain_p, parm, arg);
18601       else
18602         return unify_success (explain_p);
18603     }
18604 }
18605 #undef RECUR_AND_CHECK_FAILURE
18606 \f
18607 /* Note that DECL can be defined in this translation unit, if
18608    required.  */
18609
18610 static void
18611 mark_definable (tree decl)
18612 {
18613   tree clone;
18614   DECL_NOT_REALLY_EXTERN (decl) = 1;
18615   FOR_EACH_CLONE (clone, decl)
18616     DECL_NOT_REALLY_EXTERN (clone) = 1;
18617 }
18618
18619 /* Called if RESULT is explicitly instantiated, or is a member of an
18620    explicitly instantiated class.  */
18621
18622 void
18623 mark_decl_instantiated (tree result, int extern_p)
18624 {
18625   SET_DECL_EXPLICIT_INSTANTIATION (result);
18626
18627   /* If this entity has already been written out, it's too late to
18628      make any modifications.  */
18629   if (TREE_ASM_WRITTEN (result))
18630     return;
18631
18632   /* For anonymous namespace we don't need to do anything.  */
18633   if (decl_anon_ns_mem_p (result))
18634     {
18635       gcc_assert (!TREE_PUBLIC (result));
18636       return;
18637     }
18638
18639   if (TREE_CODE (result) != FUNCTION_DECL)
18640     /* The TREE_PUBLIC flag for function declarations will have been
18641        set correctly by tsubst.  */
18642     TREE_PUBLIC (result) = 1;
18643
18644   /* This might have been set by an earlier implicit instantiation.  */
18645   DECL_COMDAT (result) = 0;
18646
18647   if (extern_p)
18648     DECL_NOT_REALLY_EXTERN (result) = 0;
18649   else
18650     {
18651       mark_definable (result);
18652       mark_needed (result);
18653       /* Always make artificials weak.  */
18654       if (DECL_ARTIFICIAL (result) && flag_weak)
18655         comdat_linkage (result);
18656       /* For WIN32 we also want to put explicit instantiations in
18657          linkonce sections.  */
18658       else if (TREE_PUBLIC (result))
18659         maybe_make_one_only (result);
18660     }
18661
18662   /* If EXTERN_P, then this function will not be emitted -- unless
18663      followed by an explicit instantiation, at which point its linkage
18664      will be adjusted.  If !EXTERN_P, then this function will be
18665      emitted here.  In neither circumstance do we want
18666      import_export_decl to adjust the linkage.  */
18667   DECL_INTERFACE_KNOWN (result) = 1;
18668 }
18669
18670 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
18671    important template arguments.  If any are missing, we check whether
18672    they're important by using error_mark_node for substituting into any
18673    args that were used for partial ordering (the ones between ARGS and END)
18674    and seeing if it bubbles up.  */
18675
18676 static bool
18677 check_undeduced_parms (tree targs, tree args, tree end)
18678 {
18679   bool found = false;
18680   int i;
18681   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
18682     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
18683       {
18684         found = true;
18685         TREE_VEC_ELT (targs, i) = error_mark_node;
18686       }
18687   if (found)
18688     {
18689       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
18690       if (substed == error_mark_node)
18691         return true;
18692     }
18693   return false;
18694 }
18695
18696 /* Given two function templates PAT1 and PAT2, return:
18697
18698    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
18699    -1 if PAT2 is more specialized than PAT1.
18700    0 if neither is more specialized.
18701
18702    LEN indicates the number of parameters we should consider
18703    (defaulted parameters should not be considered).
18704
18705    The 1998 std underspecified function template partial ordering, and
18706    DR214 addresses the issue.  We take pairs of arguments, one from
18707    each of the templates, and deduce them against each other.  One of
18708    the templates will be more specialized if all the *other*
18709    template's arguments deduce against its arguments and at least one
18710    of its arguments *does* *not* deduce against the other template's
18711    corresponding argument.  Deduction is done as for class templates.
18712    The arguments used in deduction have reference and top level cv
18713    qualifiers removed.  Iff both arguments were originally reference
18714    types *and* deduction succeeds in both directions, an lvalue reference
18715    wins against an rvalue reference and otherwise the template
18716    with the more cv-qualified argument wins for that pairing (if
18717    neither is more cv-qualified, they both are equal).  Unlike regular
18718    deduction, after all the arguments have been deduced in this way,
18719    we do *not* verify the deduced template argument values can be
18720    substituted into non-deduced contexts.
18721
18722    The logic can be a bit confusing here, because we look at deduce1 and
18723    targs1 to see if pat2 is at least as specialized, and vice versa; if we
18724    can find template arguments for pat1 to make arg1 look like arg2, that
18725    means that arg2 is at least as specialized as arg1.  */
18726
18727 int
18728 more_specialized_fn (tree pat1, tree pat2, int len)
18729 {
18730   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
18731   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
18732   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
18733   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
18734   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
18735   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
18736   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
18737   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
18738   tree origs1, origs2;
18739   bool lose1 = false;
18740   bool lose2 = false;
18741
18742   /* Remove the this parameter from non-static member functions.  If
18743      one is a non-static member function and the other is not a static
18744      member function, remove the first parameter from that function
18745      also.  This situation occurs for operator functions where we
18746      locate both a member function (with this pointer) and non-member
18747      operator (with explicit first operand).  */
18748   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
18749     {
18750       len--; /* LEN is the number of significant arguments for DECL1 */
18751       args1 = TREE_CHAIN (args1);
18752       if (!DECL_STATIC_FUNCTION_P (decl2))
18753         args2 = TREE_CHAIN (args2);
18754     }
18755   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
18756     {
18757       args2 = TREE_CHAIN (args2);
18758       if (!DECL_STATIC_FUNCTION_P (decl1))
18759         {
18760           len--;
18761           args1 = TREE_CHAIN (args1);
18762         }
18763     }
18764
18765   /* If only one is a conversion operator, they are unordered.  */
18766   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
18767     return 0;
18768
18769   /* Consider the return type for a conversion function */
18770   if (DECL_CONV_FN_P (decl1))
18771     {
18772       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
18773       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
18774       len++;
18775     }
18776
18777   processing_template_decl++;
18778
18779   origs1 = args1;
18780   origs2 = args2;
18781
18782   while (len--
18783          /* Stop when an ellipsis is seen.  */
18784          && args1 != NULL_TREE && args2 != NULL_TREE)
18785     {
18786       tree arg1 = TREE_VALUE (args1);
18787       tree arg2 = TREE_VALUE (args2);
18788       int deduce1, deduce2;
18789       int quals1 = -1;
18790       int quals2 = -1;
18791       int ref1 = 0;
18792       int ref2 = 0;
18793
18794       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
18795           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
18796         {
18797           /* When both arguments are pack expansions, we need only
18798              unify the patterns themselves.  */
18799           arg1 = PACK_EXPANSION_PATTERN (arg1);
18800           arg2 = PACK_EXPANSION_PATTERN (arg2);
18801
18802           /* This is the last comparison we need to do.  */
18803           len = 0;
18804         }
18805
18806       if (TREE_CODE (arg1) == REFERENCE_TYPE)
18807         {
18808           ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
18809           arg1 = TREE_TYPE (arg1);
18810           quals1 = cp_type_quals (arg1);
18811         }
18812
18813       if (TREE_CODE (arg2) == REFERENCE_TYPE)
18814         {
18815           ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
18816           arg2 = TREE_TYPE (arg2);
18817           quals2 = cp_type_quals (arg2);
18818         }
18819
18820       arg1 = TYPE_MAIN_VARIANT (arg1);
18821       arg2 = TYPE_MAIN_VARIANT (arg2);
18822
18823       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
18824         {
18825           int i, len2 = list_length (args2);
18826           tree parmvec = make_tree_vec (1);
18827           tree argvec = make_tree_vec (len2);
18828           tree ta = args2;
18829
18830           /* Setup the parameter vector, which contains only ARG1.  */
18831           TREE_VEC_ELT (parmvec, 0) = arg1;
18832
18833           /* Setup the argument vector, which contains the remaining
18834              arguments.  */
18835           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
18836             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
18837
18838           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
18839                                            argvec, DEDUCE_EXACT,
18840                                            /*subr=*/true, /*explain_p=*/false)
18841                      == 0);
18842
18843           /* We cannot deduce in the other direction, because ARG1 is
18844              a pack expansion but ARG2 is not.  */
18845           deduce2 = 0;
18846         }
18847       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
18848         {
18849           int i, len1 = list_length (args1);
18850           tree parmvec = make_tree_vec (1);
18851           tree argvec = make_tree_vec (len1);
18852           tree ta = args1;
18853
18854           /* Setup the parameter vector, which contains only ARG1.  */
18855           TREE_VEC_ELT (parmvec, 0) = arg2;
18856
18857           /* Setup the argument vector, which contains the remaining
18858              arguments.  */
18859           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
18860             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
18861
18862           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
18863                                            argvec, DEDUCE_EXACT,
18864                                            /*subr=*/true, /*explain_p=*/false)
18865                      == 0);
18866
18867           /* We cannot deduce in the other direction, because ARG2 is
18868              a pack expansion but ARG1 is not.*/
18869           deduce1 = 0;
18870         }
18871
18872       else
18873         {
18874           /* The normal case, where neither argument is a pack
18875              expansion.  */
18876           deduce1 = (unify (tparms1, targs1, arg1, arg2,
18877                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
18878                      == 0);
18879           deduce2 = (unify (tparms2, targs2, arg2, arg1,
18880                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
18881                      == 0);
18882         }
18883
18884       /* If we couldn't deduce arguments for tparms1 to make arg1 match
18885          arg2, then arg2 is not as specialized as arg1.  */
18886       if (!deduce1)
18887         lose2 = true;
18888       if (!deduce2)
18889         lose1 = true;
18890
18891       /* "If, for a given type, deduction succeeds in both directions
18892          (i.e., the types are identical after the transformations above)
18893          and both P and A were reference types (before being replaced with
18894          the type referred to above):
18895          - if the type from the argument template was an lvalue reference and
18896          the type from the parameter template was not, the argument type is
18897          considered to be more specialized than the other; otherwise,
18898          - if the type from the argument template is more cv-qualified
18899          than the type from the parameter template (as described above),
18900          the argument type is considered to be more specialized than the other;
18901          otherwise,
18902          - neither type is more specialized than the other."  */
18903
18904       if (deduce1 && deduce2)
18905         {
18906           if (ref1 && ref2 && ref1 != ref2)
18907             {
18908               if (ref1 > ref2)
18909                 lose1 = true;
18910               else
18911                 lose2 = true;
18912             }
18913           else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
18914             {
18915               if ((quals1 & quals2) == quals2)
18916                 lose2 = true;
18917               if ((quals1 & quals2) == quals1)
18918                 lose1 = true;
18919             }
18920         }
18921
18922       if (lose1 && lose2)
18923         /* We've failed to deduce something in either direction.
18924            These must be unordered.  */
18925         break;
18926
18927       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
18928           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
18929         /* We have already processed all of the arguments in our
18930            handing of the pack expansion type.  */
18931         len = 0;
18932
18933       args1 = TREE_CHAIN (args1);
18934       args2 = TREE_CHAIN (args2);
18935     }
18936
18937   /* "In most cases, all template parameters must have values in order for
18938      deduction to succeed, but for partial ordering purposes a template
18939      parameter may remain without a value provided it is not used in the
18940      types being used for partial ordering."
18941
18942      Thus, if we are missing any of the targs1 we need to substitute into
18943      origs1, then pat2 is not as specialized as pat1.  This can happen when
18944      there is a nondeduced context.  */
18945   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
18946     lose2 = true;
18947   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
18948     lose1 = true;
18949
18950   processing_template_decl--;
18951
18952   /* All things being equal, if the next argument is a pack expansion
18953      for one function but not for the other, prefer the
18954      non-variadic function.  FIXME this is bogus; see c++/41958.  */
18955   if (lose1 == lose2
18956       && args1 && TREE_VALUE (args1)
18957       && args2 && TREE_VALUE (args2))
18958     {
18959       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
18960       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
18961     }
18962
18963   if (lose1 == lose2)
18964     return 0;
18965   else if (!lose1)
18966     return 1;
18967   else
18968     return -1;
18969 }
18970
18971 /* Determine which of two partial specializations of TMPL is more
18972    specialized.
18973
18974    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
18975    to the first partial specialization.  The TREE_PURPOSE is the
18976    innermost set of template parameters for the partial
18977    specialization.  PAT2 is similar, but for the second template.
18978
18979    Return 1 if the first partial specialization is more specialized;
18980    -1 if the second is more specialized; 0 if neither is more
18981    specialized.
18982
18983    See [temp.class.order] for information about determining which of
18984    two templates is more specialized.  */
18985
18986 static int
18987 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
18988 {
18989   tree targs;
18990   int winner = 0;
18991   bool any_deductions = false;
18992
18993   tree tmpl1 = TREE_VALUE (pat1);
18994   tree tmpl2 = TREE_VALUE (pat2);
18995   tree parms1 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl1);
18996   tree parms2 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl2);
18997   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
18998   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
18999
19000   /* Just like what happens for functions, if we are ordering between
19001      different template specializations, we may encounter dependent
19002      types in the arguments, and we need our dependency check functions
19003      to behave correctly.  */
19004   ++processing_template_decl;
19005   targs = get_partial_spec_bindings (tmpl, parms1, specargs1, specargs2);
19006   if (targs)
19007     {
19008       --winner;
19009       any_deductions = true;
19010     }
19011
19012   targs = get_partial_spec_bindings (tmpl, parms2, specargs2, specargs1);
19013   if (targs)
19014     {
19015       ++winner;
19016       any_deductions = true;
19017     }
19018   --processing_template_decl;
19019
19020   /* In the case of a tie where at least one of the templates
19021      has a parameter pack at the end, the template with the most
19022      non-packed parameters wins.  */
19023   if (winner == 0
19024       && any_deductions
19025       && (template_args_variadic_p (TREE_PURPOSE (pat1))
19026           || template_args_variadic_p (TREE_PURPOSE (pat2))))
19027     {
19028       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
19029       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
19030       int len1 = TREE_VEC_LENGTH (args1);
19031       int len2 = TREE_VEC_LENGTH (args2);
19032
19033       /* We don't count the pack expansion at the end.  */
19034       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
19035         --len1;
19036       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
19037         --len2;
19038
19039       if (len1 > len2)
19040         return 1;
19041       else if (len1 < len2)
19042         return -1;
19043     }
19044
19045   return winner;
19046 }
19047
19048 /* Return the template arguments that will produce the function signature
19049    DECL from the function template FN, with the explicit template
19050    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
19051    also match.  Return NULL_TREE if no satisfactory arguments could be
19052    found.  */
19053
19054 static tree
19055 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
19056 {
19057   int ntparms = DECL_NTPARMS (fn);
19058   tree targs = make_tree_vec (ntparms);
19059   tree decl_type = TREE_TYPE (decl);
19060   tree decl_arg_types;
19061   tree *args;
19062   unsigned int nargs, ix;
19063   tree arg;
19064
19065   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
19066
19067   /* Never do unification on the 'this' parameter.  */
19068   decl_arg_types = skip_artificial_parms_for (decl, 
19069                                               TYPE_ARG_TYPES (decl_type));
19070
19071   nargs = list_length (decl_arg_types);
19072   args = XALLOCAVEC (tree, nargs);
19073   for (arg = decl_arg_types, ix = 0;
19074        arg != NULL_TREE && arg != void_list_node;
19075        arg = TREE_CHAIN (arg), ++ix)
19076     args[ix] = TREE_VALUE (arg);
19077
19078   if (fn_type_unification (fn, explicit_args, targs,
19079                            args, ix,
19080                            (check_rettype || DECL_CONV_FN_P (fn)
19081                             ? TREE_TYPE (decl_type) : NULL_TREE),
19082                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
19083                            /*decltype*/false)
19084       == error_mark_node)
19085     return NULL_TREE;
19086
19087   return targs;
19088 }
19089
19090 /* Return the innermost template arguments that, when applied to a partial
19091    specialization of TMPL whose innermost template parameters are
19092    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
19093    ARGS.
19094
19095    For example, suppose we have:
19096
19097      template <class T, class U> struct S {};
19098      template <class T> struct S<T*, int> {};
19099
19100    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
19101    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
19102    int}.  The resulting vector will be {double}, indicating that `T'
19103    is bound to `double'.  */
19104
19105 static tree
19106 get_partial_spec_bindings (tree tmpl, tree tparms, tree spec_args, tree args)
19107 {
19108   int i, ntparms = TREE_VEC_LENGTH (tparms);
19109   tree deduced_args;
19110   tree innermost_deduced_args;
19111
19112   innermost_deduced_args = make_tree_vec (ntparms);
19113   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
19114     {
19115       deduced_args = copy_node (args);
19116       SET_TMPL_ARGS_LEVEL (deduced_args,
19117                            TMPL_ARGS_DEPTH (deduced_args),
19118                            innermost_deduced_args);
19119     }
19120   else
19121     deduced_args = innermost_deduced_args;
19122
19123   if (unify (tparms, deduced_args,
19124              INNERMOST_TEMPLATE_ARGS (spec_args),
19125              INNERMOST_TEMPLATE_ARGS (args),
19126              UNIFY_ALLOW_NONE, /*explain_p=*/false))
19127     return NULL_TREE;
19128
19129   for (i =  0; i < ntparms; ++i)
19130     if (! TREE_VEC_ELT (innermost_deduced_args, i))
19131       return NULL_TREE;
19132
19133   /* Verify that nondeduced template arguments agree with the type
19134      obtained from argument deduction.
19135
19136      For example:
19137
19138        struct A { typedef int X; };
19139        template <class T, class U> struct C {};
19140        template <class T> struct C<T, typename T::X> {};
19141
19142      Then with the instantiation `C<A, int>', we can deduce that
19143      `T' is `A' but unify () does not check whether `typename T::X'
19144      is `int'.  */
19145   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
19146   spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
19147                                      spec_args, tmpl,
19148                                      tf_none, false, false);
19149   if (spec_args == error_mark_node
19150       /* We only need to check the innermost arguments; the other
19151          arguments will always agree.  */
19152       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
19153                               INNERMOST_TEMPLATE_ARGS (args)))
19154     return NULL_TREE;
19155
19156   /* Now that we have bindings for all of the template arguments,
19157      ensure that the arguments deduced for the template template
19158      parameters have compatible template parameter lists.  See the use
19159      of template_template_parm_bindings_ok_p in fn_type_unification
19160      for more information.  */
19161   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
19162     return NULL_TREE;
19163
19164   return deduced_args;
19165 }
19166
19167 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
19168    Return the TREE_LIST node with the most specialized template, if
19169    any.  If there is no most specialized template, the error_mark_node
19170    is returned.
19171
19172    Note that this function does not look at, or modify, the
19173    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
19174    returned is one of the elements of INSTANTIATIONS, callers may
19175    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
19176    and retrieve it from the value returned.  */
19177
19178 tree
19179 most_specialized_instantiation (tree templates)
19180 {
19181   tree fn, champ;
19182
19183   ++processing_template_decl;
19184
19185   champ = templates;
19186   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
19187     {
19188       int fate = 0;
19189
19190       if (get_bindings (TREE_VALUE (champ),
19191                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
19192                         NULL_TREE, /*check_ret=*/true))
19193         fate--;
19194
19195       if (get_bindings (TREE_VALUE (fn),
19196                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
19197                         NULL_TREE, /*check_ret=*/true))
19198         fate++;
19199
19200       if (fate == -1)
19201         champ = fn;
19202       else if (!fate)
19203         {
19204           /* Equally specialized, move to next function.  If there
19205              is no next function, nothing's most specialized.  */
19206           fn = TREE_CHAIN (fn);
19207           champ = fn;
19208           if (!fn)
19209             break;
19210         }
19211     }
19212
19213   if (champ)
19214     /* Now verify that champ is better than everything earlier in the
19215        instantiation list.  */
19216     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
19217       if (get_bindings (TREE_VALUE (champ),
19218                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
19219                         NULL_TREE, /*check_ret=*/true)
19220           || !get_bindings (TREE_VALUE (fn),
19221                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
19222                             NULL_TREE, /*check_ret=*/true))
19223         {
19224           champ = NULL_TREE;
19225           break;
19226         }
19227
19228   processing_template_decl--;
19229
19230   if (!champ)
19231     return error_mark_node;
19232
19233   return champ;
19234 }
19235
19236 /* If DECL is a specialization of some template, return the most
19237    general such template.  Otherwise, returns NULL_TREE.
19238
19239    For example, given:
19240
19241      template <class T> struct S { template <class U> void f(U); };
19242
19243    if TMPL is `template <class U> void S<int>::f(U)' this will return
19244    the full template.  This function will not trace past partial
19245    specializations, however.  For example, given in addition:
19246
19247      template <class T> struct S<T*> { template <class U> void f(U); };
19248
19249    if TMPL is `template <class U> void S<int*>::f(U)' this will return
19250    `template <class T> template <class U> S<T*>::f(U)'.  */
19251
19252 tree
19253 most_general_template (tree decl)
19254 {
19255   if (TREE_CODE (decl) != TEMPLATE_DECL)
19256     {
19257       if (tree tinfo = get_template_info (decl))
19258         decl = TI_TEMPLATE (tinfo);
19259       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
19260          template friend, or a FIELD_DECL for a capture pack.  */
19261       if (TREE_CODE (decl) != TEMPLATE_DECL)
19262         return NULL_TREE;
19263     }
19264
19265   /* Look for more and more general templates.  */
19266   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
19267     {
19268       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
19269          (See cp-tree.h for details.)  */
19270       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
19271         break;
19272
19273       if (CLASS_TYPE_P (TREE_TYPE (decl))
19274           && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
19275           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
19276         break;
19277
19278       /* Stop if we run into an explicitly specialized class template.  */
19279       if (!DECL_NAMESPACE_SCOPE_P (decl)
19280           && DECL_CONTEXT (decl)
19281           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
19282         break;
19283
19284       decl = DECL_TI_TEMPLATE (decl);
19285     }
19286
19287   return decl;
19288 }
19289
19290 /* Return the most specialized of the template partial specializations
19291    which can produce TARGET, a specialization of some class or variable
19292    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
19293    a TEMPLATE_DECL node corresponding to the partial specialization, while
19294    the TREE_PURPOSE is the set of template arguments that must be
19295    substituted into the template pattern in order to generate TARGET.
19296
19297    If the choice of partial specialization is ambiguous, a diagnostic
19298    is issued, and the error_mark_node is returned.  If there are no
19299    partial specializations matching TARGET, then NULL_TREE is
19300    returned, indicating that the primary template should be used.  */
19301
19302 static tree
19303 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
19304 {
19305   tree list = NULL_TREE;
19306   tree t;
19307   tree champ;
19308   int fate;
19309   bool ambiguous_p;
19310   tree outer_args = NULL_TREE;
19311   tree tmpl, args;
19312
19313   if (TYPE_P (target))
19314     {
19315       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
19316       tmpl = TI_TEMPLATE (tinfo);
19317       args = TI_ARGS (tinfo);
19318     }
19319   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
19320     {
19321       tmpl = TREE_OPERAND (target, 0);
19322       args = TREE_OPERAND (target, 1);
19323     }
19324   else if (VAR_P (target))
19325     {
19326       tree tinfo = DECL_TEMPLATE_INFO (target);
19327       tmpl = TI_TEMPLATE (tinfo);
19328       args = TI_ARGS (tinfo);
19329     }
19330   else
19331     gcc_unreachable ();
19332
19333   tree main_tmpl = most_general_template (tmpl);
19334
19335   /* For determining which partial specialization to use, only the
19336      innermost args are interesting.  */
19337   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
19338     {
19339       outer_args = strip_innermost_template_args (args, 1);
19340       args = INNERMOST_TEMPLATE_ARGS (args);
19341     }
19342
19343   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
19344     {
19345       tree partial_spec_args;
19346       tree spec_args;
19347       tree spec_tmpl = TREE_VALUE (t);
19348
19349       partial_spec_args = TREE_PURPOSE (t);
19350
19351       ++processing_template_decl;
19352
19353       if (outer_args)
19354         {
19355           /* Discard the outer levels of args, and then substitute in the
19356              template args from the enclosing class.  */
19357           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
19358           partial_spec_args = tsubst_template_args
19359             (partial_spec_args, outer_args, tf_none, NULL_TREE);
19360
19361           /* And the same for the partial specialization TEMPLATE_DECL.  */
19362           spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
19363         }
19364
19365       partial_spec_args =
19366           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
19367                                  partial_spec_args,
19368                                  tmpl, tf_none,
19369                                  /*require_all_args=*/true,
19370                                  /*use_default_args=*/true);
19371
19372       --processing_template_decl;
19373
19374       if (partial_spec_args == error_mark_node)
19375         return error_mark_node;
19376       if (spec_tmpl == error_mark_node)
19377         return error_mark_node;
19378
19379       tree parms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
19380       spec_args = get_partial_spec_bindings (tmpl, parms,
19381                                       partial_spec_args,
19382                                       args);
19383       if (spec_args)
19384         {
19385           if (outer_args)
19386             spec_args = add_to_template_args (outer_args, spec_args);
19387           list = tree_cons (spec_args, TREE_VALUE (t), list);
19388           TREE_TYPE (list) = TREE_TYPE (t);
19389         }
19390     }
19391
19392   if (! list)
19393     return NULL_TREE;
19394
19395   ambiguous_p = false;
19396   t = list;
19397   champ = t;
19398   t = TREE_CHAIN (t);
19399   for (; t; t = TREE_CHAIN (t))
19400     {
19401       fate = more_specialized_partial_spec (tmpl, champ, t);
19402       if (fate == 1)
19403         ;
19404       else
19405         {
19406           if (fate == 0)
19407             {
19408               t = TREE_CHAIN (t);
19409               if (! t)
19410                 {
19411                   ambiguous_p = true;
19412                   break;
19413                 }
19414             }
19415           champ = t;
19416         }
19417     }
19418
19419   if (!ambiguous_p)
19420     for (t = list; t && t != champ; t = TREE_CHAIN (t))
19421       {
19422         fate = more_specialized_partial_spec (tmpl, champ, t);
19423         if (fate != 1)
19424           {
19425             ambiguous_p = true;
19426             break;
19427           }
19428       }
19429
19430   if (ambiguous_p)
19431     {
19432       const char *str;
19433       char *spaces = NULL;
19434       if (!(complain & tf_error))
19435         return error_mark_node;
19436       if (TYPE_P (target))
19437         error ("ambiguous template instantiation for %q#T", target);
19438       else
19439         error ("ambiguous template instantiation for %q#D", target);
19440       str = ngettext ("candidate is:", "candidates are:", list_length (list));
19441       for (t = list; t; t = TREE_CHAIN (t))
19442         {
19443           tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
19444           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
19445                   "%s %#S", spaces ? spaces : str, subst);
19446           spaces = spaces ? spaces : get_spaces (str);
19447         }
19448       free (spaces);
19449       return error_mark_node;
19450     }
19451
19452   return champ;
19453 }
19454
19455 /* Explicitly instantiate DECL.  */
19456
19457 void
19458 do_decl_instantiation (tree decl, tree storage)
19459 {
19460   tree result = NULL_TREE;
19461   int extern_p = 0;
19462
19463   if (!decl || decl == error_mark_node)
19464     /* An error occurred, for which grokdeclarator has already issued
19465        an appropriate message.  */
19466     return;
19467   else if (! DECL_LANG_SPECIFIC (decl))
19468     {
19469       error ("explicit instantiation of non-template %q#D", decl);
19470       return;
19471     }
19472
19473   bool var_templ = (DECL_TEMPLATE_INFO (decl)
19474                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
19475
19476   if (VAR_P (decl) && !var_templ)
19477     {
19478       /* There is an asymmetry here in the way VAR_DECLs and
19479          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
19480          the latter, the DECL we get back will be marked as a
19481          template instantiation, and the appropriate
19482          DECL_TEMPLATE_INFO will be set up.  This does not happen for
19483          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
19484          should handle VAR_DECLs as it currently handles
19485          FUNCTION_DECLs.  */
19486       if (!DECL_CLASS_SCOPE_P (decl))
19487         {
19488           error ("%qD is not a static data member of a class template", decl);
19489           return;
19490         }
19491       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
19492       if (!result || !VAR_P (result))
19493         {
19494           error ("no matching template for %qD found", decl);
19495           return;
19496         }
19497       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
19498         {
19499           error ("type %qT for explicit instantiation %qD does not match "
19500                  "declared type %qT", TREE_TYPE (result), decl,
19501                  TREE_TYPE (decl));
19502           return;
19503         }
19504     }
19505   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
19506     {
19507       error ("explicit instantiation of %q#D", decl);
19508       return;
19509     }
19510   else
19511     result = decl;
19512
19513   /* Check for various error cases.  Note that if the explicit
19514      instantiation is valid the RESULT will currently be marked as an
19515      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
19516      until we get here.  */
19517
19518   if (DECL_TEMPLATE_SPECIALIZATION (result))
19519     {
19520       /* DR 259 [temp.spec].
19521
19522          Both an explicit instantiation and a declaration of an explicit
19523          specialization shall not appear in a program unless the explicit
19524          instantiation follows a declaration of the explicit specialization.
19525
19526          For a given set of template parameters, if an explicit
19527          instantiation of a template appears after a declaration of an
19528          explicit specialization for that template, the explicit
19529          instantiation has no effect.  */
19530       return;
19531     }
19532   else if (DECL_EXPLICIT_INSTANTIATION (result))
19533     {
19534       /* [temp.spec]
19535
19536          No program shall explicitly instantiate any template more
19537          than once.
19538
19539          We check DECL_NOT_REALLY_EXTERN so as not to complain when
19540          the first instantiation was `extern' and the second is not,
19541          and EXTERN_P for the opposite case.  */
19542       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
19543         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
19544       /* If an "extern" explicit instantiation follows an ordinary
19545          explicit instantiation, the template is instantiated.  */
19546       if (extern_p)
19547         return;
19548     }
19549   else if (!DECL_IMPLICIT_INSTANTIATION (result))
19550     {
19551       error ("no matching template for %qD found", result);
19552       return;
19553     }
19554   else if (!DECL_TEMPLATE_INFO (result))
19555     {
19556       permerror (input_location, "explicit instantiation of non-template %q#D", result);
19557       return;
19558     }
19559
19560   if (storage == NULL_TREE)
19561     ;
19562   else if (storage == ridpointers[(int) RID_EXTERN])
19563     {
19564       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
19565         pedwarn (input_location, OPT_Wpedantic, 
19566                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
19567                  "instantiations");
19568       extern_p = 1;
19569     }
19570   else
19571     error ("storage class %qD applied to template instantiation", storage);
19572
19573   check_explicit_instantiation_namespace (result);
19574   mark_decl_instantiated (result, extern_p);
19575   if (! extern_p)
19576     instantiate_decl (result, /*defer_ok=*/1,
19577                       /*expl_inst_class_mem_p=*/false);
19578 }
19579
19580 static void
19581 mark_class_instantiated (tree t, int extern_p)
19582 {
19583   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
19584   SET_CLASSTYPE_INTERFACE_KNOWN (t);
19585   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
19586   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
19587   if (! extern_p)
19588     {
19589       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
19590       rest_of_type_compilation (t, 1);
19591     }
19592 }
19593
19594 /* Called from do_type_instantiation through binding_table_foreach to
19595    do recursive instantiation for the type bound in ENTRY.  */
19596 static void
19597 bt_instantiate_type_proc (binding_entry entry, void *data)
19598 {
19599   tree storage = *(tree *) data;
19600
19601   if (MAYBE_CLASS_TYPE_P (entry->type)
19602       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
19603     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
19604 }
19605
19606 /* Called from do_type_instantiation to instantiate a member
19607    (a member function or a static member variable) of an
19608    explicitly instantiated class template.  */
19609 static void
19610 instantiate_class_member (tree decl, int extern_p)
19611 {
19612   mark_decl_instantiated (decl, extern_p);
19613   if (! extern_p)
19614     instantiate_decl (decl, /*defer_ok=*/1,
19615                       /*expl_inst_class_mem_p=*/true);
19616 }
19617
19618 /* Perform an explicit instantiation of template class T.  STORAGE, if
19619    non-null, is the RID for extern, inline or static.  COMPLAIN is
19620    nonzero if this is called from the parser, zero if called recursively,
19621    since the standard is unclear (as detailed below).  */
19622
19623 void
19624 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
19625 {
19626   int extern_p = 0;
19627   int nomem_p = 0;
19628   int static_p = 0;
19629   int previous_instantiation_extern_p = 0;
19630
19631   if (TREE_CODE (t) == TYPE_DECL)
19632     t = TREE_TYPE (t);
19633
19634   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
19635     {
19636       tree tmpl =
19637         (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
19638       if (tmpl)
19639         error ("explicit instantiation of non-class template %qD", tmpl);
19640       else
19641         error ("explicit instantiation of non-template type %qT", t);
19642       return;
19643     }
19644
19645   complete_type (t);
19646
19647   if (!COMPLETE_TYPE_P (t))
19648     {
19649       if (complain & tf_error)
19650         error ("explicit instantiation of %q#T before definition of template",
19651                t);
19652       return;
19653     }
19654
19655   if (storage != NULL_TREE)
19656     {
19657       if (!in_system_header_at (input_location))
19658         {
19659           if (storage == ridpointers[(int) RID_EXTERN])
19660             {
19661               if (cxx_dialect == cxx98)
19662                 pedwarn (input_location, OPT_Wpedantic, 
19663                          "ISO C++ 1998 forbids the use of %<extern%> on "
19664                          "explicit instantiations");
19665             }
19666           else
19667             pedwarn (input_location, OPT_Wpedantic, 
19668                      "ISO C++ forbids the use of %qE"
19669                      " on explicit instantiations", storage);
19670         }
19671
19672       if (storage == ridpointers[(int) RID_INLINE])
19673         nomem_p = 1;
19674       else if (storage == ridpointers[(int) RID_EXTERN])
19675         extern_p = 1;
19676       else if (storage == ridpointers[(int) RID_STATIC])
19677         static_p = 1;
19678       else
19679         {
19680           error ("storage class %qD applied to template instantiation",
19681                  storage);
19682           extern_p = 0;
19683         }
19684     }
19685
19686   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
19687     {
19688       /* DR 259 [temp.spec].
19689
19690          Both an explicit instantiation and a declaration of an explicit
19691          specialization shall not appear in a program unless the explicit
19692          instantiation follows a declaration of the explicit specialization.
19693
19694          For a given set of template parameters, if an explicit
19695          instantiation of a template appears after a declaration of an
19696          explicit specialization for that template, the explicit
19697          instantiation has no effect.  */
19698       return;
19699     }
19700   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
19701     {
19702       /* [temp.spec]
19703
19704          No program shall explicitly instantiate any template more
19705          than once.
19706
19707          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
19708          instantiation was `extern'.  If EXTERN_P then the second is.
19709          These cases are OK.  */
19710       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
19711
19712       if (!previous_instantiation_extern_p && !extern_p
19713           && (complain & tf_error))
19714         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
19715
19716       /* If we've already instantiated the template, just return now.  */
19717       if (!CLASSTYPE_INTERFACE_ONLY (t))
19718         return;
19719     }
19720
19721   check_explicit_instantiation_namespace (TYPE_NAME (t));
19722   mark_class_instantiated (t, extern_p);
19723
19724   if (nomem_p)
19725     return;
19726
19727   {
19728     tree tmp;
19729
19730     /* In contrast to implicit instantiation, where only the
19731        declarations, and not the definitions, of members are
19732        instantiated, we have here:
19733
19734          [temp.explicit]
19735
19736          The explicit instantiation of a class template specialization
19737          implies the instantiation of all of its members not
19738          previously explicitly specialized in the translation unit
19739          containing the explicit instantiation.
19740
19741        Of course, we can't instantiate member template classes, since
19742        we don't have any arguments for them.  Note that the standard
19743        is unclear on whether the instantiation of the members are
19744        *explicit* instantiations or not.  However, the most natural
19745        interpretation is that it should be an explicit instantiation.  */
19746
19747     if (! static_p)
19748       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
19749         if (TREE_CODE (tmp) == FUNCTION_DECL
19750             && DECL_TEMPLATE_INSTANTIATION (tmp))
19751           instantiate_class_member (tmp, extern_p);
19752
19753     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
19754       if (VAR_P (tmp) && DECL_TEMPLATE_INSTANTIATION (tmp))
19755         instantiate_class_member (tmp, extern_p);
19756
19757     if (CLASSTYPE_NESTED_UTDS (t))
19758       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
19759                              bt_instantiate_type_proc, &storage);
19760   }
19761 }
19762
19763 /* Given a function DECL, which is a specialization of TMPL, modify
19764    DECL to be a re-instantiation of TMPL with the same template
19765    arguments.  TMPL should be the template into which tsubst'ing
19766    should occur for DECL, not the most general template.
19767
19768    One reason for doing this is a scenario like this:
19769
19770      template <class T>
19771      void f(const T&, int i);
19772
19773      void g() { f(3, 7); }
19774
19775      template <class T>
19776      void f(const T& t, const int i) { }
19777
19778    Note that when the template is first instantiated, with
19779    instantiate_template, the resulting DECL will have no name for the
19780    first parameter, and the wrong type for the second.  So, when we go
19781    to instantiate the DECL, we regenerate it.  */
19782
19783 static void
19784 regenerate_decl_from_template (tree decl, tree tmpl)
19785 {
19786   /* The arguments used to instantiate DECL, from the most general
19787      template.  */
19788   tree args;
19789   tree code_pattern;
19790
19791   args = DECL_TI_ARGS (decl);
19792   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
19793
19794   /* Make sure that we can see identifiers, and compute access
19795      correctly.  */
19796   push_access_scope (decl);
19797
19798   if (TREE_CODE (decl) == FUNCTION_DECL)
19799     {
19800       tree decl_parm;
19801       tree pattern_parm;
19802       tree specs;
19803       int args_depth;
19804       int parms_depth;
19805
19806       args_depth = TMPL_ARGS_DEPTH (args);
19807       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
19808       if (args_depth > parms_depth)
19809         args = get_innermost_template_args (args, parms_depth);
19810
19811       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
19812                                               args, tf_error, NULL_TREE,
19813                                               /*defer_ok*/false);
19814       if (specs && specs != error_mark_node)
19815         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
19816                                                     specs);
19817
19818       /* Merge parameter declarations.  */
19819       decl_parm = skip_artificial_parms_for (decl,
19820                                              DECL_ARGUMENTS (decl));
19821       pattern_parm
19822         = skip_artificial_parms_for (code_pattern,
19823                                      DECL_ARGUMENTS (code_pattern));
19824       while (decl_parm && !DECL_PACK_P (pattern_parm))
19825         {
19826           tree parm_type;
19827           tree attributes;
19828           
19829           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
19830             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
19831           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
19832                               NULL_TREE);
19833           parm_type = type_decays_to (parm_type);
19834           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
19835             TREE_TYPE (decl_parm) = parm_type;
19836           attributes = DECL_ATTRIBUTES (pattern_parm);
19837           if (DECL_ATTRIBUTES (decl_parm) != attributes)
19838             {
19839               DECL_ATTRIBUTES (decl_parm) = attributes;
19840               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
19841             }
19842           decl_parm = DECL_CHAIN (decl_parm);
19843           pattern_parm = DECL_CHAIN (pattern_parm);
19844         }
19845       /* Merge any parameters that match with the function parameter
19846          pack.  */
19847       if (pattern_parm && DECL_PACK_P (pattern_parm))
19848         {
19849           int i, len;
19850           tree expanded_types;
19851           /* Expand the TYPE_PACK_EXPANSION that provides the types for
19852              the parameters in this function parameter pack.  */
19853           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
19854                                                  args, tf_error, NULL_TREE);
19855           len = TREE_VEC_LENGTH (expanded_types);
19856           for (i = 0; i < len; i++)
19857             {
19858               tree parm_type;
19859               tree attributes;
19860           
19861               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
19862                 /* Rename the parameter to include the index.  */
19863                 DECL_NAME (decl_parm) = 
19864                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
19865               parm_type = TREE_VEC_ELT (expanded_types, i);
19866               parm_type = type_decays_to (parm_type);
19867               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
19868                 TREE_TYPE (decl_parm) = parm_type;
19869               attributes = DECL_ATTRIBUTES (pattern_parm);
19870               if (DECL_ATTRIBUTES (decl_parm) != attributes)
19871                 {
19872                   DECL_ATTRIBUTES (decl_parm) = attributes;
19873                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
19874                 }
19875               decl_parm = DECL_CHAIN (decl_parm);
19876             }
19877         }
19878       /* Merge additional specifiers from the CODE_PATTERN.  */
19879       if (DECL_DECLARED_INLINE_P (code_pattern)
19880           && !DECL_DECLARED_INLINE_P (decl))
19881         DECL_DECLARED_INLINE_P (decl) = 1;
19882     }
19883   else if (VAR_P (decl))
19884     {
19885       DECL_INITIAL (decl) =
19886         tsubst_expr (DECL_INITIAL (code_pattern), args,
19887                      tf_error, DECL_TI_TEMPLATE (decl),
19888                      /*integral_constant_expression_p=*/false);
19889       if (VAR_HAD_UNKNOWN_BOUND (decl))
19890         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
19891                                    tf_error, DECL_TI_TEMPLATE (decl));
19892     }
19893   else
19894     gcc_unreachable ();
19895
19896   pop_access_scope (decl);
19897 }
19898
19899 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
19900    substituted to get DECL.  */
19901
19902 tree
19903 template_for_substitution (tree decl)
19904 {
19905   tree tmpl = DECL_TI_TEMPLATE (decl);
19906
19907   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
19908      for the instantiation.  This is not always the most general
19909      template.  Consider, for example:
19910
19911         template <class T>
19912         struct S { template <class U> void f();
19913                    template <> void f<int>(); };
19914
19915      and an instantiation of S<double>::f<int>.  We want TD to be the
19916      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
19917   while (/* An instantiation cannot have a definition, so we need a
19918             more general template.  */
19919          DECL_TEMPLATE_INSTANTIATION (tmpl)
19920            /* We must also deal with friend templates.  Given:
19921
19922                 template <class T> struct S {
19923                   template <class U> friend void f() {};
19924                 };
19925
19926               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
19927               so far as the language is concerned, but that's still
19928               where we get the pattern for the instantiation from.  On
19929               other hand, if the definition comes outside the class, say:
19930
19931                 template <class T> struct S {
19932                   template <class U> friend void f();
19933                 };
19934                 template <class U> friend void f() {}
19935
19936               we don't need to look any further.  That's what the check for
19937               DECL_INITIAL is for.  */
19938           || (TREE_CODE (decl) == FUNCTION_DECL
19939               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
19940               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
19941     {
19942       /* The present template, TD, should not be a definition.  If it
19943          were a definition, we should be using it!  Note that we
19944          cannot restructure the loop to just keep going until we find
19945          a template with a definition, since that might go too far if
19946          a specialization was declared, but not defined.  */
19947
19948       /* Fetch the more general template.  */
19949       tmpl = DECL_TI_TEMPLATE (tmpl);
19950     }
19951
19952   return tmpl;
19953 }
19954
19955 /* Returns true if we need to instantiate this template instance even if we
19956    know we aren't going to emit it..  */
19957
19958 bool
19959 always_instantiate_p (tree decl)
19960 {
19961   /* We always instantiate inline functions so that we can inline them.  An
19962      explicit instantiation declaration prohibits implicit instantiation of
19963      non-inline functions.  With high levels of optimization, we would
19964      normally inline non-inline functions -- but we're not allowed to do
19965      that for "extern template" functions.  Therefore, we check
19966      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
19967   return ((TREE_CODE (decl) == FUNCTION_DECL
19968            && (DECL_DECLARED_INLINE_P (decl)
19969                || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
19970           /* And we need to instantiate static data members so that
19971              their initializers are available in integral constant
19972              expressions.  */
19973           || (VAR_P (decl)
19974               && decl_maybe_constant_var_p (decl)));
19975 }
19976
19977 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
19978    instantiate it now, modifying TREE_TYPE (fn).  */
19979
19980 void
19981 maybe_instantiate_noexcept (tree fn)
19982 {
19983   tree fntype, spec, noex, clone;
19984
19985   /* Don't instantiate a noexcept-specification from template context.  */
19986   if (processing_template_decl)
19987     return;
19988
19989   if (DECL_CLONED_FUNCTION_P (fn))
19990     fn = DECL_CLONED_FUNCTION (fn);
19991   fntype = TREE_TYPE (fn);
19992   spec = TYPE_RAISES_EXCEPTIONS (fntype);
19993
19994   if (!spec || !TREE_PURPOSE (spec))
19995     return;
19996
19997   noex = TREE_PURPOSE (spec);
19998
19999   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
20000     {
20001       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
20002         spec = get_defaulted_eh_spec (fn);
20003       else if (push_tinst_level (fn))
20004         {
20005           push_access_scope (fn);
20006           push_deferring_access_checks (dk_no_deferred);
20007           input_location = DECL_SOURCE_LOCATION (fn);
20008           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
20009                                         DEFERRED_NOEXCEPT_ARGS (noex),
20010                                         tf_warning_or_error, fn,
20011                                         /*function_p=*/false,
20012                                         /*integral_constant_expression_p=*/true);
20013           pop_deferring_access_checks ();
20014           pop_access_scope (fn);
20015           pop_tinst_level ();
20016           spec = build_noexcept_spec (noex, tf_warning_or_error);
20017           if (spec == error_mark_node)
20018             spec = noexcept_false_spec;
20019         }
20020       else
20021         spec = noexcept_false_spec;
20022
20023       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
20024     }
20025
20026   FOR_EACH_CLONE (clone, fn)
20027     {
20028       if (TREE_TYPE (clone) == fntype)
20029         TREE_TYPE (clone) = TREE_TYPE (fn);
20030       else
20031         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
20032     }
20033 }
20034
20035 /* Produce the definition of D, a _DECL generated from a template.  If
20036    DEFER_OK is nonzero, then we don't have to actually do the
20037    instantiation now; we just have to do it sometime.  Normally it is
20038    an error if this is an explicit instantiation but D is undefined.
20039    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
20040    explicitly instantiated class template.  */
20041
20042 tree
20043 instantiate_decl (tree d, int defer_ok,
20044                   bool expl_inst_class_mem_p)
20045 {
20046   tree tmpl = DECL_TI_TEMPLATE (d);
20047   tree gen_args;
20048   tree args;
20049   tree td;
20050   tree code_pattern;
20051   tree spec;
20052   tree gen_tmpl;
20053   bool pattern_defined;
20054   location_t saved_loc = input_location;
20055   int saved_unevaluated_operand = cp_unevaluated_operand;
20056   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
20057   bool external_p;
20058   bool deleted_p;
20059   tree fn_context;
20060   bool nested;
20061
20062   /* This function should only be used to instantiate templates for
20063      functions and static member variables.  */
20064   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
20065
20066   /* Variables are never deferred; if instantiation is required, they
20067      are instantiated right away.  That allows for better code in the
20068      case that an expression refers to the value of the variable --
20069      if the variable has a constant value the referring expression can
20070      take advantage of that fact.  */
20071   if (VAR_P (d)
20072       || DECL_DECLARED_CONSTEXPR_P (d))
20073     defer_ok = 0;
20074
20075   /* Don't instantiate cloned functions.  Instead, instantiate the
20076      functions they cloned.  */
20077   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
20078     d = DECL_CLONED_FUNCTION (d);
20079
20080   if (DECL_TEMPLATE_INSTANTIATED (d)
20081       || (TREE_CODE (d) == FUNCTION_DECL
20082           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
20083       || DECL_TEMPLATE_SPECIALIZATION (d))
20084     /* D has already been instantiated or explicitly specialized, so
20085        there's nothing for us to do here.
20086
20087        It might seem reasonable to check whether or not D is an explicit
20088        instantiation, and, if so, stop here.  But when an explicit
20089        instantiation is deferred until the end of the compilation,
20090        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
20091        the instantiation.  */
20092     return d;
20093
20094   /* Check to see whether we know that this template will be
20095      instantiated in some other file, as with "extern template"
20096      extension.  */
20097   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
20098
20099   /* In general, we do not instantiate such templates.  */
20100   if (external_p && !always_instantiate_p (d))
20101     return d;
20102
20103   gen_tmpl = most_general_template (tmpl);
20104   gen_args = DECL_TI_ARGS (d);
20105
20106   if (tmpl != gen_tmpl)
20107     /* We should already have the extra args.  */
20108     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
20109                 == TMPL_ARGS_DEPTH (gen_args));
20110   /* And what's in the hash table should match D.  */
20111   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
20112               || spec == NULL_TREE);
20113
20114   /* This needs to happen before any tsubsting.  */
20115   if (! push_tinst_level (d))
20116     return d;
20117
20118   timevar_push (TV_TEMPLATE_INST);
20119
20120   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
20121      for the instantiation.  */
20122   td = template_for_substitution (d);
20123   code_pattern = DECL_TEMPLATE_RESULT (td);
20124
20125   /* We should never be trying to instantiate a member of a class
20126      template or partial specialization.  */
20127   gcc_assert (d != code_pattern);
20128
20129   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
20130       || DECL_TEMPLATE_SPECIALIZATION (td))
20131     /* In the case of a friend template whose definition is provided
20132        outside the class, we may have too many arguments.  Drop the
20133        ones we don't need.  The same is true for specializations.  */
20134     args = get_innermost_template_args
20135       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
20136   else
20137     args = gen_args;
20138
20139   if (TREE_CODE (d) == FUNCTION_DECL)
20140     {
20141       deleted_p = DECL_DELETED_FN (code_pattern);
20142       pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
20143                          || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
20144                          || deleted_p);
20145     }
20146   else
20147     {
20148       deleted_p = false;
20149       pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
20150     }
20151
20152   /* We may be in the middle of deferred access check.  Disable it now.  */
20153   push_deferring_access_checks (dk_no_deferred);
20154
20155   /* Unless an explicit instantiation directive has already determined
20156      the linkage of D, remember that a definition is available for
20157      this entity.  */
20158   if (pattern_defined
20159       && !DECL_INTERFACE_KNOWN (d)
20160       && !DECL_NOT_REALLY_EXTERN (d))
20161     mark_definable (d);
20162
20163   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
20164   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
20165   input_location = DECL_SOURCE_LOCATION (d);
20166
20167   /* If D is a member of an explicitly instantiated class template,
20168      and no definition is available, treat it like an implicit
20169      instantiation.  */
20170   if (!pattern_defined && expl_inst_class_mem_p
20171       && DECL_EXPLICIT_INSTANTIATION (d))
20172     {
20173       /* Leave linkage flags alone on instantiations with anonymous
20174          visibility.  */
20175       if (TREE_PUBLIC (d))
20176         {
20177           DECL_NOT_REALLY_EXTERN (d) = 0;
20178           DECL_INTERFACE_KNOWN (d) = 0;
20179         }
20180       SET_DECL_IMPLICIT_INSTANTIATION (d);
20181     }
20182
20183   /* Defer all other templates, unless we have been explicitly
20184      forbidden from doing so.  */
20185   if (/* If there is no definition, we cannot instantiate the
20186          template.  */
20187       ! pattern_defined
20188       /* If it's OK to postpone instantiation, do so.  */
20189       || defer_ok
20190       /* If this is a static data member that will be defined
20191          elsewhere, we don't want to instantiate the entire data
20192          member, but we do want to instantiate the initializer so that
20193          we can substitute that elsewhere.  */
20194       || (external_p && VAR_P (d))
20195       /* Handle here a deleted function too, avoid generating
20196          its body (c++/61080).  */
20197       || deleted_p)
20198     {
20199       /* The definition of the static data member is now required so
20200          we must substitute the initializer.  */
20201       if (VAR_P (d)
20202           && !DECL_INITIAL (d)
20203           && DECL_INITIAL (code_pattern))
20204         {
20205           tree ns;
20206           tree init;
20207           bool const_init = false;
20208           bool enter_context = DECL_CLASS_SCOPE_P (d);
20209
20210           ns = decl_namespace_context (d);
20211           push_nested_namespace (ns);
20212           if (enter_context)
20213             push_nested_class (DECL_CONTEXT (d));
20214           init = tsubst_expr (DECL_INITIAL (code_pattern),
20215                               args,
20216                               tf_warning_or_error, NULL_TREE,
20217                               /*integral_constant_expression_p=*/false);
20218           /* If instantiating the initializer involved instantiating this
20219              again, don't call cp_finish_decl twice.  */
20220           if (!DECL_INITIAL (d))
20221             {
20222               /* Make sure the initializer is still constant, in case of
20223                  circular dependency (template/instantiate6.C). */
20224               const_init
20225                 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
20226               cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
20227                               /*asmspec_tree=*/NULL_TREE,
20228                               LOOKUP_ONLYCONVERTING);
20229             }
20230           if (enter_context)
20231             pop_nested_class ();
20232           pop_nested_namespace (ns);
20233         }
20234
20235       /* We restore the source position here because it's used by
20236          add_pending_template.  */
20237       input_location = saved_loc;
20238
20239       if (at_eof && !pattern_defined
20240           && DECL_EXPLICIT_INSTANTIATION (d)
20241           && DECL_NOT_REALLY_EXTERN (d))
20242         /* [temp.explicit]
20243
20244            The definition of a non-exported function template, a
20245            non-exported member function template, or a non-exported
20246            member function or static data member of a class template
20247            shall be present in every translation unit in which it is
20248            explicitly instantiated.  */
20249         permerror (input_location,  "explicit instantiation of %qD "
20250                    "but no definition available", d);
20251
20252       /* If we're in unevaluated context, we just wanted to get the
20253          constant value; this isn't an odr use, so don't queue
20254          a full instantiation.  */
20255       if (cp_unevaluated_operand != 0)
20256         goto out;
20257       /* ??? Historically, we have instantiated inline functions, even
20258          when marked as "extern template".  */
20259       if (!(external_p && VAR_P (d)))
20260         add_pending_template (d);
20261       goto out;
20262     }
20263   /* Tell the repository that D is available in this translation unit
20264      -- and see if it is supposed to be instantiated here.  */
20265   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
20266     {
20267       /* In a PCH file, despite the fact that the repository hasn't
20268          requested instantiation in the PCH it is still possible that
20269          an instantiation will be required in a file that includes the
20270          PCH.  */
20271       if (pch_file)
20272         add_pending_template (d);
20273       /* Instantiate inline functions so that the inliner can do its
20274          job, even though we'll not be emitting a copy of this
20275          function.  */
20276       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
20277         goto out;
20278     }
20279
20280   fn_context = decl_function_context (d);
20281   nested = (current_function_decl != NULL_TREE);
20282   if (!fn_context)
20283     push_to_top_level ();
20284   else
20285     {
20286       if (nested)
20287         push_function_context ();
20288       cp_unevaluated_operand = 0;
20289       c_inhibit_evaluation_warnings = 0;
20290     }
20291
20292   /* Mark D as instantiated so that recursive calls to
20293      instantiate_decl do not try to instantiate it again.  */
20294   DECL_TEMPLATE_INSTANTIATED (d) = 1;
20295
20296   /* Regenerate the declaration in case the template has been modified
20297      by a subsequent redeclaration.  */
20298   regenerate_decl_from_template (d, td);
20299
20300   /* We already set the file and line above.  Reset them now in case
20301      they changed as a result of calling regenerate_decl_from_template.  */
20302   input_location = DECL_SOURCE_LOCATION (d);
20303
20304   if (VAR_P (d))
20305     {
20306       tree init;
20307       bool const_init = false;
20308
20309       /* Clear out DECL_RTL; whatever was there before may not be right
20310          since we've reset the type of the declaration.  */
20311       SET_DECL_RTL (d, NULL);
20312       DECL_IN_AGGR_P (d) = 0;
20313
20314       /* The initializer is placed in DECL_INITIAL by
20315          regenerate_decl_from_template so we don't need to
20316          push/pop_access_scope again here.  Pull it out so that
20317          cp_finish_decl can process it.  */
20318       init = DECL_INITIAL (d);
20319       DECL_INITIAL (d) = NULL_TREE;
20320       DECL_INITIALIZED_P (d) = 0;
20321
20322       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
20323          initializer.  That function will defer actual emission until
20324          we have a chance to determine linkage.  */
20325       DECL_EXTERNAL (d) = 0;
20326
20327       /* Enter the scope of D so that access-checking works correctly.  */
20328       bool enter_context = DECL_CLASS_SCOPE_P (d);
20329       if (enter_context)
20330         push_nested_class (DECL_CONTEXT (d));
20331
20332       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
20333       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
20334
20335       if (enter_context)
20336         pop_nested_class ();
20337
20338       if (variable_template_p (td))
20339         note_variable_template_instantiation (d);
20340     }
20341   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
20342     synthesize_method (d);
20343   else if (TREE_CODE (d) == FUNCTION_DECL)
20344     {
20345       hash_map<tree, tree> *saved_local_specializations;
20346       tree subst_decl;
20347       tree tmpl_parm;
20348       tree spec_parm;
20349       tree block = NULL_TREE;
20350
20351       /* Save away the current list, in case we are instantiating one
20352          template from within the body of another.  */
20353       saved_local_specializations = local_specializations;
20354
20355       /* Set up the list of local specializations.  */
20356       local_specializations = new hash_map<tree, tree>;
20357
20358       /* Set up context.  */
20359       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
20360           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
20361         block = push_stmt_list ();
20362       else
20363         start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
20364
20365       /* Some typedefs referenced from within the template code need to be
20366          access checked at template instantiation time, i.e now. These
20367          types were added to the template at parsing time. Let's get those
20368          and perform the access checks then.  */
20369       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (gen_tmpl),
20370                                      gen_args);
20371
20372       /* Create substitution entries for the parameters.  */
20373       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
20374       tmpl_parm = DECL_ARGUMENTS (subst_decl);
20375       spec_parm = DECL_ARGUMENTS (d);
20376       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
20377         {
20378           register_local_specialization (spec_parm, tmpl_parm);
20379           spec_parm = skip_artificial_parms_for (d, spec_parm);
20380           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
20381         }
20382       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
20383         {
20384           if (!DECL_PACK_P (tmpl_parm))
20385             {
20386               register_local_specialization (spec_parm, tmpl_parm);
20387               spec_parm = DECL_CHAIN (spec_parm);
20388             }
20389           else
20390             {
20391               /* Register the (value) argument pack as a specialization of
20392                  TMPL_PARM, then move on.  */
20393               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
20394               register_local_specialization (argpack, tmpl_parm);
20395             }
20396         }
20397       gcc_assert (!spec_parm);
20398
20399       /* Substitute into the body of the function.  */
20400       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
20401         tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
20402                         tf_warning_or_error, tmpl);
20403       else
20404         {
20405           tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
20406                        tf_warning_or_error, tmpl,
20407                        /*integral_constant_expression_p=*/false);
20408
20409           /* Set the current input_location to the end of the function
20410              so that finish_function knows where we are.  */
20411           input_location
20412             = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
20413
20414           /* Remember if we saw an infinite loop in the template.  */
20415           current_function_infinite_loop
20416             = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
20417         }
20418
20419       /* We don't need the local specializations any more.  */
20420       delete local_specializations;
20421       local_specializations = saved_local_specializations;
20422
20423       /* Finish the function.  */
20424       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
20425           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
20426         DECL_SAVED_TREE (d) = pop_stmt_list (block);
20427       else
20428         {
20429           d = finish_function (0);
20430           expand_or_defer_fn (d);
20431         }
20432
20433       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
20434         cp_check_omp_declare_reduction (d);
20435     }
20436
20437   /* We're not deferring instantiation any more.  */
20438   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
20439
20440   if (!fn_context)
20441     pop_from_top_level ();
20442   else if (nested)
20443     pop_function_context ();
20444
20445 out:
20446   input_location = saved_loc;
20447   cp_unevaluated_operand = saved_unevaluated_operand;
20448   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
20449   pop_deferring_access_checks ();
20450   pop_tinst_level ();
20451
20452   timevar_pop (TV_TEMPLATE_INST);
20453
20454   return d;
20455 }
20456
20457 /* Run through the list of templates that we wish we could
20458    instantiate, and instantiate any we can.  RETRIES is the
20459    number of times we retry pending template instantiation.  */
20460
20461 void
20462 instantiate_pending_templates (int retries)
20463 {
20464   int reconsider;
20465   location_t saved_loc = input_location;
20466
20467   /* Instantiating templates may trigger vtable generation.  This in turn
20468      may require further template instantiations.  We place a limit here
20469      to avoid infinite loop.  */
20470   if (pending_templates && retries >= max_tinst_depth)
20471     {
20472       tree decl = pending_templates->tinst->decl;
20473
20474       fatal_error (input_location,
20475                    "template instantiation depth exceeds maximum of %d"
20476                    " instantiating %q+D, possibly from virtual table generation"
20477                    " (use -ftemplate-depth= to increase the maximum)",
20478                    max_tinst_depth, decl);
20479       if (TREE_CODE (decl) == FUNCTION_DECL)
20480         /* Pretend that we defined it.  */
20481         DECL_INITIAL (decl) = error_mark_node;
20482       return;
20483     }
20484
20485   do
20486     {
20487       struct pending_template **t = &pending_templates;
20488       struct pending_template *last = NULL;
20489       reconsider = 0;
20490       while (*t)
20491         {
20492           tree instantiation = reopen_tinst_level ((*t)->tinst);
20493           bool complete = false;
20494
20495           if (TYPE_P (instantiation))
20496             {
20497               tree fn;
20498
20499               if (!COMPLETE_TYPE_P (instantiation))
20500                 {
20501                   instantiate_class_template (instantiation);
20502                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
20503                     for (fn = TYPE_METHODS (instantiation);
20504                          fn;
20505                          fn = TREE_CHAIN (fn))
20506                       if (! DECL_ARTIFICIAL (fn))
20507                         instantiate_decl (fn,
20508                                           /*defer_ok=*/0,
20509                                           /*expl_inst_class_mem_p=*/false);
20510                   if (COMPLETE_TYPE_P (instantiation))
20511                     reconsider = 1;
20512                 }
20513
20514               complete = COMPLETE_TYPE_P (instantiation);
20515             }
20516           else
20517             {
20518               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
20519                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
20520                 {
20521                   instantiation
20522                     = instantiate_decl (instantiation,
20523                                         /*defer_ok=*/0,
20524                                         /*expl_inst_class_mem_p=*/false);
20525                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
20526                     reconsider = 1;
20527                 }
20528
20529               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
20530                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
20531             }
20532
20533           if (complete)
20534             /* If INSTANTIATION has been instantiated, then we don't
20535                need to consider it again in the future.  */
20536             *t = (*t)->next;
20537           else
20538             {
20539               last = *t;
20540               t = &(*t)->next;
20541             }
20542           tinst_depth = 0;
20543           current_tinst_level = NULL;
20544         }
20545       last_pending_template = last;
20546     }
20547   while (reconsider);
20548
20549   input_location = saved_loc;
20550 }
20551
20552 /* Substitute ARGVEC into T, which is a list of initializers for
20553    either base class or a non-static data member.  The TREE_PURPOSEs
20554    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
20555    instantiate_decl.  */
20556
20557 static tree
20558 tsubst_initializer_list (tree t, tree argvec)
20559 {
20560   tree inits = NULL_TREE;
20561
20562   for (; t; t = TREE_CHAIN (t))
20563     {
20564       tree decl;
20565       tree init;
20566       tree expanded_bases = NULL_TREE;
20567       tree expanded_arguments = NULL_TREE;
20568       int i, len = 1;
20569
20570       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
20571         {
20572           tree expr;
20573           tree arg;
20574
20575           /* Expand the base class expansion type into separate base
20576              classes.  */
20577           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
20578                                                  tf_warning_or_error,
20579                                                  NULL_TREE);
20580           if (expanded_bases == error_mark_node)
20581             continue;
20582           
20583           /* We'll be building separate TREE_LISTs of arguments for
20584              each base.  */
20585           len = TREE_VEC_LENGTH (expanded_bases);
20586           expanded_arguments = make_tree_vec (len);
20587           for (i = 0; i < len; i++)
20588             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
20589
20590           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
20591              expand each argument in the TREE_VALUE of t.  */
20592           expr = make_node (EXPR_PACK_EXPANSION);
20593           PACK_EXPANSION_LOCAL_P (expr) = true;
20594           PACK_EXPANSION_PARAMETER_PACKS (expr) =
20595             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
20596
20597           if (TREE_VALUE (t) == void_type_node)
20598             /* VOID_TYPE_NODE is used to indicate
20599                value-initialization.  */
20600             {
20601               for (i = 0; i < len; i++)
20602                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
20603             }
20604           else
20605             {
20606               /* Substitute parameter packs into each argument in the
20607                  TREE_LIST.  */
20608               in_base_initializer = 1;
20609               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
20610                 {
20611                   tree expanded_exprs;
20612
20613                   /* Expand the argument.  */
20614                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
20615                   expanded_exprs 
20616                     = tsubst_pack_expansion (expr, argvec,
20617                                              tf_warning_or_error,
20618                                              NULL_TREE);
20619                   if (expanded_exprs == error_mark_node)
20620                     continue;
20621
20622                   /* Prepend each of the expanded expressions to the
20623                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
20624                   for (i = 0; i < len; i++)
20625                     {
20626                       TREE_VEC_ELT (expanded_arguments, i) = 
20627                         tree_cons (NULL_TREE, 
20628                                    TREE_VEC_ELT (expanded_exprs, i),
20629                                    TREE_VEC_ELT (expanded_arguments, i));
20630                     }
20631                 }
20632               in_base_initializer = 0;
20633
20634               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
20635                  since we built them backwards.  */
20636               for (i = 0; i < len; i++)
20637                 {
20638                   TREE_VEC_ELT (expanded_arguments, i) = 
20639                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
20640                 }
20641             }
20642         }
20643
20644       for (i = 0; i < len; ++i)
20645         {
20646           if (expanded_bases)
20647             {
20648               decl = TREE_VEC_ELT (expanded_bases, i);
20649               decl = expand_member_init (decl);
20650               init = TREE_VEC_ELT (expanded_arguments, i);
20651             }
20652           else
20653             {
20654               tree tmp;
20655               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
20656                                   tf_warning_or_error, NULL_TREE);
20657
20658               decl = expand_member_init (decl);
20659               if (decl && !DECL_P (decl))
20660                 in_base_initializer = 1;
20661
20662               init = TREE_VALUE (t);
20663               tmp = init;
20664               if (init != void_type_node)
20665                 init = tsubst_expr (init, argvec,
20666                                     tf_warning_or_error, NULL_TREE,
20667                                     /*integral_constant_expression_p=*/false);
20668               if (init == NULL_TREE && tmp != NULL_TREE)
20669                 /* If we had an initializer but it instantiated to nothing,
20670                    value-initialize the object.  This will only occur when
20671                    the initializer was a pack expansion where the parameter
20672                    packs used in that expansion were of length zero.  */
20673                 init = void_type_node;
20674               in_base_initializer = 0;
20675             }
20676
20677           if (decl)
20678             {
20679               init = build_tree_list (decl, init);
20680               TREE_CHAIN (init) = inits;
20681               inits = init;
20682             }
20683         }
20684     }
20685   return inits;
20686 }
20687
20688 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
20689
20690 static void
20691 set_current_access_from_decl (tree decl)
20692 {
20693   if (TREE_PRIVATE (decl))
20694     current_access_specifier = access_private_node;
20695   else if (TREE_PROTECTED (decl))
20696     current_access_specifier = access_protected_node;
20697   else
20698     current_access_specifier = access_public_node;
20699 }
20700
20701 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
20702    is the instantiation (which should have been created with
20703    start_enum) and ARGS are the template arguments to use.  */
20704
20705 static void
20706 tsubst_enum (tree tag, tree newtag, tree args)
20707 {
20708   tree e;
20709
20710   if (SCOPED_ENUM_P (newtag))
20711     begin_scope (sk_scoped_enum, newtag);
20712
20713   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
20714     {
20715       tree value;
20716       tree decl;
20717
20718       decl = TREE_VALUE (e);
20719       /* Note that in a template enum, the TREE_VALUE is the
20720          CONST_DECL, not the corresponding INTEGER_CST.  */
20721       value = tsubst_expr (DECL_INITIAL (decl),
20722                            args, tf_warning_or_error, NULL_TREE,
20723                            /*integral_constant_expression_p=*/true);
20724
20725       /* Give this enumeration constant the correct access.  */
20726       set_current_access_from_decl (decl);
20727
20728       /* Actually build the enumerator itself.  */
20729       build_enumerator
20730         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
20731     }
20732
20733   if (SCOPED_ENUM_P (newtag))
20734     finish_scope ();
20735
20736   finish_enum_value_list (newtag);
20737   finish_enum (newtag);
20738
20739   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
20740     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
20741 }
20742
20743 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
20744    its type -- but without substituting the innermost set of template
20745    arguments.  So, innermost set of template parameters will appear in
20746    the type.  */
20747
20748 tree
20749 get_mostly_instantiated_function_type (tree decl)
20750 {
20751   tree fn_type;
20752   tree tmpl;
20753   tree targs;
20754   tree tparms;
20755   int parm_depth;
20756
20757   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
20758   targs = DECL_TI_ARGS (decl);
20759   tparms = DECL_TEMPLATE_PARMS (tmpl);
20760   parm_depth = TMPL_PARMS_DEPTH (tparms);
20761
20762   /* There should be as many levels of arguments as there are levels
20763      of parameters.  */
20764   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
20765
20766   fn_type = TREE_TYPE (tmpl);
20767
20768   if (parm_depth == 1)
20769     /* No substitution is necessary.  */
20770     ;
20771   else
20772     {
20773       int i;
20774       tree partial_args;
20775
20776       /* Replace the innermost level of the TARGS with NULL_TREEs to
20777          let tsubst know not to substitute for those parameters.  */
20778       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
20779       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
20780         SET_TMPL_ARGS_LEVEL (partial_args, i,
20781                              TMPL_ARGS_LEVEL (targs, i));
20782       SET_TMPL_ARGS_LEVEL (partial_args,
20783                            TMPL_ARGS_DEPTH (targs),
20784                            make_tree_vec (DECL_NTPARMS (tmpl)));
20785
20786       /* Make sure that we can see identifiers, and compute access
20787          correctly.  */
20788       push_access_scope (decl);
20789
20790       ++processing_template_decl;
20791       /* Now, do the (partial) substitution to figure out the
20792          appropriate function type.  */
20793       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
20794       --processing_template_decl;
20795
20796       /* Substitute into the template parameters to obtain the real
20797          innermost set of parameters.  This step is important if the
20798          innermost set of template parameters contains value
20799          parameters whose types depend on outer template parameters.  */
20800       TREE_VEC_LENGTH (partial_args)--;
20801       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
20802
20803       pop_access_scope (decl);
20804     }
20805
20806   return fn_type;
20807 }
20808
20809 /* Return truthvalue if we're processing a template different from
20810    the last one involved in diagnostics.  */
20811 bool
20812 problematic_instantiation_changed (void)
20813 {
20814   return current_tinst_level != last_error_tinst_level;
20815 }
20816
20817 /* Remember current template involved in diagnostics.  */
20818 void
20819 record_last_problematic_instantiation (void)
20820 {
20821   last_error_tinst_level = current_tinst_level;
20822 }
20823
20824 struct tinst_level *
20825 current_instantiation (void)
20826 {
20827   return current_tinst_level;
20828 }
20829
20830 /* [temp.param] Check that template non-type parm TYPE is of an allowable
20831    type. Return zero for ok, nonzero for disallowed. Issue error and
20832    warning messages under control of COMPLAIN.  */
20833
20834 static int
20835 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
20836 {
20837   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
20838     return 0;
20839   else if (POINTER_TYPE_P (type))
20840     return 0;
20841   else if (TYPE_PTRMEM_P (type))
20842     return 0;
20843   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
20844     return 0;
20845   else if (TREE_CODE (type) == TYPENAME_TYPE)
20846     return 0;
20847   else if (TREE_CODE (type) == DECLTYPE_TYPE)
20848     return 0;
20849   else if (TREE_CODE (type) == NULLPTR_TYPE)
20850     return 0;
20851
20852   if (complain & tf_error)
20853     {
20854       if (type == error_mark_node)
20855         inform (input_location, "invalid template non-type parameter");
20856       else
20857         error ("%q#T is not a valid type for a template non-type parameter",
20858                type);
20859     }
20860   return 1;
20861 }
20862
20863 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
20864    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
20865
20866 static bool
20867 dependent_type_p_r (tree type)
20868 {
20869   tree scope;
20870
20871   /* [temp.dep.type]
20872
20873      A type is dependent if it is:
20874
20875      -- a template parameter. Template template parameters are types
20876         for us (since TYPE_P holds true for them) so we handle
20877         them here.  */
20878   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20879       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
20880     return true;
20881   /* -- a qualified-id with a nested-name-specifier which contains a
20882         class-name that names a dependent type or whose unqualified-id
20883         names a dependent type.  */
20884   if (TREE_CODE (type) == TYPENAME_TYPE)
20885     return true;
20886   /* -- a cv-qualified type where the cv-unqualified type is
20887         dependent.
20888      No code is necessary for this bullet; the code below handles
20889      cv-qualified types, and we don't want to strip aliases with
20890      TYPE_MAIN_VARIANT because of DR 1558.  */
20891   /* -- a compound type constructed from any dependent type.  */
20892   if (TYPE_PTRMEM_P (type))
20893     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
20894             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
20895                                            (type)));
20896   else if (TYPE_PTR_P (type)
20897            || TREE_CODE (type) == REFERENCE_TYPE)
20898     return dependent_type_p (TREE_TYPE (type));
20899   else if (TREE_CODE (type) == FUNCTION_TYPE
20900            || TREE_CODE (type) == METHOD_TYPE)
20901     {
20902       tree arg_type;
20903
20904       if (dependent_type_p (TREE_TYPE (type)))
20905         return true;
20906       for (arg_type = TYPE_ARG_TYPES (type);
20907            arg_type;
20908            arg_type = TREE_CHAIN (arg_type))
20909         if (dependent_type_p (TREE_VALUE (arg_type)))
20910           return true;
20911       return false;
20912     }
20913   /* -- an array type constructed from any dependent type or whose
20914         size is specified by a constant expression that is
20915         value-dependent.
20916
20917         We checked for type- and value-dependence of the bounds in
20918         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
20919   if (TREE_CODE (type) == ARRAY_TYPE)
20920     {
20921       if (TYPE_DOMAIN (type)
20922           && dependent_type_p (TYPE_DOMAIN (type)))
20923         return true;
20924       return dependent_type_p (TREE_TYPE (type));
20925     }
20926
20927   /* -- a template-id in which either the template name is a template
20928      parameter ...  */
20929   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
20930     return true;
20931   /* ... or any of the template arguments is a dependent type or
20932         an expression that is type-dependent or value-dependent.  */
20933   else if (TYPE_TEMPLATE_INFO (type)
20934            && (any_dependent_template_arguments_p
20935                (INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (type)))))
20936     return true;
20937
20938   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
20939      dependent; if the argument of the `typeof' expression is not
20940      type-dependent, then it should already been have resolved.  */
20941   if (TREE_CODE (type) == TYPEOF_TYPE
20942       || TREE_CODE (type) == DECLTYPE_TYPE
20943       || TREE_CODE (type) == UNDERLYING_TYPE)
20944     return true;
20945
20946   /* A template argument pack is dependent if any of its packed
20947      arguments are.  */
20948   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
20949     {
20950       tree args = ARGUMENT_PACK_ARGS (type);
20951       int i, len = TREE_VEC_LENGTH (args);
20952       for (i = 0; i < len; ++i)
20953         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
20954           return true;
20955     }
20956
20957   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
20958      be template parameters.  */
20959   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
20960     return true;
20961
20962   /* The standard does not specifically mention types that are local
20963      to template functions or local classes, but they should be
20964      considered dependent too.  For example:
20965
20966        template <int I> void f() {
20967          enum E { a = I };
20968          S<sizeof (E)> s;
20969        }
20970
20971      The size of `E' cannot be known until the value of `I' has been
20972      determined.  Therefore, `E' must be considered dependent.  */
20973   scope = TYPE_CONTEXT (type);
20974   if (scope && TYPE_P (scope))
20975     return dependent_type_p (scope);
20976   /* Don't use type_dependent_expression_p here, as it can lead
20977      to infinite recursion trying to determine whether a lambda
20978      nested in a lambda is dependent (c++/47687).  */
20979   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
20980            && DECL_LANG_SPECIFIC (scope)
20981            && DECL_TEMPLATE_INFO (scope)
20982            && (any_dependent_template_arguments_p
20983                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
20984     return true;
20985
20986   /* Other types are non-dependent.  */
20987   return false;
20988 }
20989
20990 /* Returns TRUE if TYPE is dependent, in the sense of
20991    [temp.dep.type].  Note that a NULL type is considered dependent.  */
20992
20993 bool
20994 dependent_type_p (tree type)
20995 {
20996   /* If there are no template parameters in scope, then there can't be
20997      any dependent types.  */
20998   if (!processing_template_decl)
20999     {
21000       /* If we are not processing a template, then nobody should be
21001          providing us with a dependent type.  */
21002       gcc_assert (type);
21003       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
21004       return false;
21005     }
21006
21007   /* If the type is NULL, we have not computed a type for the entity
21008      in question; in that case, the type is dependent.  */
21009   if (!type)
21010     return true;
21011
21012   /* Erroneous types can be considered non-dependent.  */
21013   if (type == error_mark_node)
21014     return false;
21015
21016   /* If we have not already computed the appropriate value for TYPE,
21017      do so now.  */
21018   if (!TYPE_DEPENDENT_P_VALID (type))
21019     {
21020       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
21021       TYPE_DEPENDENT_P_VALID (type) = 1;
21022     }
21023
21024   return TYPE_DEPENDENT_P (type);
21025 }
21026
21027 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
21028    lookup.  In other words, a dependent type that is not the current
21029    instantiation.  */
21030
21031 bool
21032 dependent_scope_p (tree scope)
21033 {
21034   return (scope && TYPE_P (scope) && dependent_type_p (scope)
21035           && !currently_open_class (scope));
21036 }
21037
21038 /* T is a SCOPE_REF; return whether we need to consider it
21039     instantiation-dependent so that we can check access at instantiation
21040     time even though we know which member it resolves to.  */
21041
21042 static bool
21043 instantiation_dependent_scope_ref_p (tree t)
21044 {
21045   if (DECL_P (TREE_OPERAND (t, 1))
21046       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
21047       && accessible_in_template_p (TREE_OPERAND (t, 0),
21048                                    TREE_OPERAND (t, 1)))
21049     return false;
21050   else
21051     return true;
21052 }
21053
21054 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
21055    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
21056    expression.  */
21057
21058 /* Note that this predicate is not appropriate for general expressions;
21059    only constant expressions (that satisfy potential_constant_expression)
21060    can be tested for value dependence.  */
21061
21062 bool
21063 value_dependent_expression_p (tree expression)
21064 {
21065   if (!processing_template_decl)
21066     return false;
21067
21068   /* A name declared with a dependent type.  */
21069   if (DECL_P (expression) && type_dependent_expression_p (expression))
21070     return true;
21071
21072   switch (TREE_CODE (expression))
21073     {
21074     case IDENTIFIER_NODE:
21075       /* A name that has not been looked up -- must be dependent.  */
21076       return true;
21077
21078     case TEMPLATE_PARM_INDEX:
21079       /* A non-type template parm.  */
21080       return true;
21081
21082     case CONST_DECL:
21083       /* A non-type template parm.  */
21084       if (DECL_TEMPLATE_PARM_P (expression))
21085         return true;
21086       return value_dependent_expression_p (DECL_INITIAL (expression));
21087
21088     case VAR_DECL:
21089        /* A constant with literal type and is initialized
21090           with an expression that is value-dependent.
21091
21092           Note that a non-dependent parenthesized initializer will have
21093           already been replaced with its constant value, so if we see
21094           a TREE_LIST it must be dependent.  */
21095       if (DECL_INITIAL (expression)
21096           && decl_constant_var_p (expression)
21097           && (TREE_CODE (DECL_INITIAL (expression)) == TREE_LIST
21098               /* cp_finish_decl doesn't fold reference initializers.  */
21099               || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE
21100               || value_dependent_expression_p (DECL_INITIAL (expression))))
21101         return true;
21102       return false;
21103
21104     case DYNAMIC_CAST_EXPR:
21105     case STATIC_CAST_EXPR:
21106     case CONST_CAST_EXPR:
21107     case REINTERPRET_CAST_EXPR:
21108     case CAST_EXPR:
21109       /* These expressions are value-dependent if the type to which
21110          the cast occurs is dependent or the expression being casted
21111          is value-dependent.  */
21112       {
21113         tree type = TREE_TYPE (expression);
21114
21115         if (dependent_type_p (type))
21116           return true;
21117
21118         /* A functional cast has a list of operands.  */
21119         expression = TREE_OPERAND (expression, 0);
21120         if (!expression)
21121           {
21122             /* If there are no operands, it must be an expression such
21123                as "int()". This should not happen for aggregate types
21124                because it would form non-constant expressions.  */
21125             gcc_assert (cxx_dialect >= cxx11
21126                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
21127
21128             return false;
21129           }
21130
21131         if (TREE_CODE (expression) == TREE_LIST)
21132           return any_value_dependent_elements_p (expression);
21133
21134         return value_dependent_expression_p (expression);
21135       }
21136
21137     case SIZEOF_EXPR:
21138       if (SIZEOF_EXPR_TYPE_P (expression))
21139         return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
21140       /* FALLTHRU */
21141     case ALIGNOF_EXPR:
21142     case TYPEID_EXPR:
21143       /* A `sizeof' expression is value-dependent if the operand is
21144          type-dependent or is a pack expansion.  */
21145       expression = TREE_OPERAND (expression, 0);
21146       if (PACK_EXPANSION_P (expression))
21147         return true;
21148       else if (TYPE_P (expression))
21149         return dependent_type_p (expression);
21150       return instantiation_dependent_expression_p (expression);
21151
21152     case AT_ENCODE_EXPR:
21153       /* An 'encode' expression is value-dependent if the operand is
21154          type-dependent.  */
21155       expression = TREE_OPERAND (expression, 0);
21156       return dependent_type_p (expression);
21157
21158     case NOEXCEPT_EXPR:
21159       expression = TREE_OPERAND (expression, 0);
21160       return instantiation_dependent_expression_p (expression);
21161
21162     case SCOPE_REF:
21163       /* All instantiation-dependent expressions should also be considered
21164          value-dependent.  */
21165       return instantiation_dependent_scope_ref_p (expression);
21166
21167     case COMPONENT_REF:
21168       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
21169               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
21170
21171     case NONTYPE_ARGUMENT_PACK:
21172       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
21173          is value-dependent.  */
21174       {
21175         tree values = ARGUMENT_PACK_ARGS (expression);
21176         int i, len = TREE_VEC_LENGTH (values);
21177         
21178         for (i = 0; i < len; ++i)
21179           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
21180             return true;
21181         
21182         return false;
21183       }
21184
21185     case TRAIT_EXPR:
21186       {
21187         tree type2 = TRAIT_EXPR_TYPE2 (expression);
21188         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
21189                 || (type2 ? dependent_type_p (type2) : false));
21190       }
21191
21192     case MODOP_EXPR:
21193       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
21194               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
21195
21196     case ARRAY_REF:
21197       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
21198               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
21199
21200     case ADDR_EXPR:
21201       {
21202         tree op = TREE_OPERAND (expression, 0);
21203         return (value_dependent_expression_p (op)
21204                 || has_value_dependent_address (op));
21205       }
21206
21207     case CALL_EXPR:
21208       {
21209         tree fn = get_callee_fndecl (expression);
21210         int i, nargs;
21211         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
21212           return true;
21213         nargs = call_expr_nargs (expression);
21214         for (i = 0; i < nargs; ++i)
21215           {
21216             tree op = CALL_EXPR_ARG (expression, i);
21217             /* In a call to a constexpr member function, look through the
21218                implicit ADDR_EXPR on the object argument so that it doesn't
21219                cause the call to be considered value-dependent.  We also
21220                look through it in potential_constant_expression.  */
21221             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
21222                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21223                 && TREE_CODE (op) == ADDR_EXPR)
21224               op = TREE_OPERAND (op, 0);
21225             if (value_dependent_expression_p (op))
21226               return true;
21227           }
21228         return false;
21229       }
21230
21231     case TEMPLATE_ID_EXPR:
21232       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
21233          type-dependent.  */
21234       return type_dependent_expression_p (expression);
21235
21236     case CONSTRUCTOR:
21237       {
21238         unsigned ix;
21239         tree val;
21240         if (dependent_type_p (TREE_TYPE (expression)))
21241           return true;
21242         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
21243           if (value_dependent_expression_p (val))
21244             return true;
21245         return false;
21246       }
21247
21248     case STMT_EXPR:
21249       /* Treat a GNU statement expression as dependent to avoid crashing
21250          under instantiate_non_dependent_expr; it can't be constant.  */
21251       return true;
21252
21253     default:
21254       /* A constant expression is value-dependent if any subexpression is
21255          value-dependent.  */
21256       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
21257         {
21258         case tcc_reference:
21259         case tcc_unary:
21260         case tcc_comparison:
21261         case tcc_binary:
21262         case tcc_expression:
21263         case tcc_vl_exp:
21264           {
21265             int i, len = cp_tree_operand_length (expression);
21266
21267             for (i = 0; i < len; i++)
21268               {
21269                 tree t = TREE_OPERAND (expression, i);
21270
21271                 /* In some cases, some of the operands may be missing.l
21272                    (For example, in the case of PREDECREMENT_EXPR, the
21273                    amount to increment by may be missing.)  That doesn't
21274                    make the expression dependent.  */
21275                 if (t && value_dependent_expression_p (t))
21276                   return true;
21277               }
21278           }
21279           break;
21280         default:
21281           break;
21282         }
21283       break;
21284     }
21285
21286   /* The expression is not value-dependent.  */
21287   return false;
21288 }
21289
21290 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
21291    [temp.dep.expr].  Note that an expression with no type is
21292    considered dependent.  Other parts of the compiler arrange for an
21293    expression with type-dependent subexpressions to have no type, so
21294    this function doesn't have to be fully recursive.  */
21295
21296 bool
21297 type_dependent_expression_p (tree expression)
21298 {
21299   if (!processing_template_decl)
21300     return false;
21301
21302   if (expression == NULL_TREE || expression == error_mark_node)
21303     return false;
21304
21305   /* An unresolved name is always dependent.  */
21306   if (identifier_p (expression) || TREE_CODE (expression) == USING_DECL)
21307     return true;
21308
21309   /* Some expression forms are never type-dependent.  */
21310   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
21311       || TREE_CODE (expression) == SIZEOF_EXPR
21312       || TREE_CODE (expression) == ALIGNOF_EXPR
21313       || TREE_CODE (expression) == AT_ENCODE_EXPR
21314       || TREE_CODE (expression) == NOEXCEPT_EXPR
21315       || TREE_CODE (expression) == TRAIT_EXPR
21316       || TREE_CODE (expression) == TYPEID_EXPR
21317       || TREE_CODE (expression) == DELETE_EXPR
21318       || TREE_CODE (expression) == VEC_DELETE_EXPR
21319       || TREE_CODE (expression) == THROW_EXPR)
21320     return false;
21321
21322   /* The types of these expressions depends only on the type to which
21323      the cast occurs.  */
21324   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
21325       || TREE_CODE (expression) == STATIC_CAST_EXPR
21326       || TREE_CODE (expression) == CONST_CAST_EXPR
21327       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
21328       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
21329       || TREE_CODE (expression) == CAST_EXPR)
21330     return dependent_type_p (TREE_TYPE (expression));
21331
21332   /* The types of these expressions depends only on the type created
21333      by the expression.  */
21334   if (TREE_CODE (expression) == NEW_EXPR
21335       || TREE_CODE (expression) == VEC_NEW_EXPR)
21336     {
21337       /* For NEW_EXPR tree nodes created inside a template, either
21338          the object type itself or a TREE_LIST may appear as the
21339          operand 1.  */
21340       tree type = TREE_OPERAND (expression, 1);
21341       if (TREE_CODE (type) == TREE_LIST)
21342         /* This is an array type.  We need to check array dimensions
21343            as well.  */
21344         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
21345                || value_dependent_expression_p
21346                     (TREE_OPERAND (TREE_VALUE (type), 1));
21347       else
21348         return dependent_type_p (type);
21349     }
21350
21351   if (TREE_CODE (expression) == SCOPE_REF)
21352     {
21353       tree scope = TREE_OPERAND (expression, 0);
21354       tree name = TREE_OPERAND (expression, 1);
21355
21356       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
21357          contains an identifier associated by name lookup with one or more
21358          declarations declared with a dependent type, or...a
21359          nested-name-specifier or qualified-id that names a member of an
21360          unknown specialization.  */
21361       return (type_dependent_expression_p (name)
21362               || dependent_scope_p (scope));
21363     }
21364
21365   if (TREE_CODE (expression) == FUNCTION_DECL
21366       && DECL_LANG_SPECIFIC (expression)
21367       && DECL_TEMPLATE_INFO (expression)
21368       && (any_dependent_template_arguments_p
21369           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
21370     return true;
21371
21372   if (TREE_CODE (expression) == TEMPLATE_DECL
21373       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
21374     return false;
21375
21376   if (TREE_CODE (expression) == STMT_EXPR)
21377     expression = stmt_expr_value_expr (expression);
21378
21379   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
21380     {
21381       tree elt;
21382       unsigned i;
21383
21384       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
21385         {
21386           if (type_dependent_expression_p (elt))
21387             return true;
21388         }
21389       return false;
21390     }
21391
21392   /* A static data member of the current instantiation with incomplete
21393      array type is type-dependent, as the definition and specializations
21394      can have different bounds.  */
21395   if (VAR_P (expression)
21396       && DECL_CLASS_SCOPE_P (expression)
21397       && dependent_type_p (DECL_CONTEXT (expression))
21398       && VAR_HAD_UNKNOWN_BOUND (expression))
21399     return true;
21400
21401   /* An array of unknown bound depending on a variadic parameter, eg:
21402
21403      template<typename... Args>
21404        void foo (Args... args)
21405        {
21406          int arr[] = { args... };
21407        }
21408
21409      template<int... vals>
21410        void bar ()
21411        {
21412          int arr[] = { vals... };
21413        }
21414
21415      If the array has no length and has an initializer, it must be that
21416      we couldn't determine its length in cp_complete_array_type because
21417      it is dependent.  */
21418   if (VAR_P (expression)
21419       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
21420       && !TYPE_DOMAIN (TREE_TYPE (expression))
21421       && DECL_INITIAL (expression))
21422    return true;
21423
21424   /* A variable template specialization is type-dependent if it has any
21425      dependent template arguments.  */
21426   if (VAR_P (expression)
21427       && DECL_LANG_SPECIFIC (expression)
21428       && DECL_TEMPLATE_INFO (expression)
21429       && variable_template_p (DECL_TI_TEMPLATE (expression)))
21430     return any_dependent_template_arguments_p (DECL_TI_ARGS (expression));
21431
21432   if (TREE_TYPE (expression) == unknown_type_node)
21433     {
21434       if (TREE_CODE (expression) == ADDR_EXPR)
21435         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
21436       if (TREE_CODE (expression) == COMPONENT_REF
21437           || TREE_CODE (expression) == OFFSET_REF)
21438         {
21439           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
21440             return true;
21441           expression = TREE_OPERAND (expression, 1);
21442           if (identifier_p (expression))
21443             return false;
21444         }
21445       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
21446       if (TREE_CODE (expression) == SCOPE_REF)
21447         return false;
21448
21449       /* Always dependent, on the number of arguments if nothing else.  */
21450       if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
21451         return true;
21452
21453       if (BASELINK_P (expression))
21454         {
21455           if (BASELINK_OPTYPE (expression)
21456               && dependent_type_p (BASELINK_OPTYPE (expression)))
21457             return true;
21458           expression = BASELINK_FUNCTIONS (expression);
21459         }
21460
21461       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
21462         {
21463           if (any_dependent_template_arguments_p
21464               (TREE_OPERAND (expression, 1)))
21465             return true;
21466           expression = TREE_OPERAND (expression, 0);
21467         }
21468       gcc_assert (TREE_CODE (expression) == OVERLOAD
21469                   || TREE_CODE (expression) == FUNCTION_DECL);
21470
21471       while (expression)
21472         {
21473           if (type_dependent_expression_p (OVL_CURRENT (expression)))
21474             return true;
21475           expression = OVL_NEXT (expression);
21476         }
21477       return false;
21478     }
21479
21480   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
21481
21482   return (dependent_type_p (TREE_TYPE (expression)));
21483 }
21484
21485 /* walk_tree callback function for instantiation_dependent_expression_p,
21486    below.  Returns non-zero if a dependent subexpression is found.  */
21487
21488 static tree
21489 instantiation_dependent_r (tree *tp, int *walk_subtrees,
21490                            void * /*data*/)
21491 {
21492   if (TYPE_P (*tp))
21493     {
21494       /* We don't have to worry about decltype currently because decltype
21495          of an instantiation-dependent expr is a dependent type.  This
21496          might change depending on the resolution of DR 1172.  */
21497       *walk_subtrees = false;
21498       return NULL_TREE;
21499     }
21500   enum tree_code code = TREE_CODE (*tp);
21501   switch (code)
21502     {
21503       /* Don't treat an argument list as dependent just because it has no
21504          TREE_TYPE.  */
21505     case TREE_LIST:
21506     case TREE_VEC:
21507       return NULL_TREE;
21508
21509     case VAR_DECL:
21510     case CONST_DECL:
21511       /* A constant with a dependent initializer is dependent.  */
21512       if (value_dependent_expression_p (*tp))
21513         return *tp;
21514       break;
21515
21516     case TEMPLATE_PARM_INDEX:
21517       return *tp;
21518
21519       /* Handle expressions with type operands.  */
21520     case SIZEOF_EXPR:
21521     case ALIGNOF_EXPR:
21522     case TYPEID_EXPR:
21523     case AT_ENCODE_EXPR:
21524       {
21525         tree op = TREE_OPERAND (*tp, 0);
21526         if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
21527           op = TREE_TYPE (op);
21528         if (TYPE_P (op))
21529           {
21530             if (dependent_type_p (op))
21531               return *tp;
21532             else
21533               {
21534                 *walk_subtrees = false;
21535                 return NULL_TREE;
21536               }
21537           }
21538         break;
21539       }
21540
21541     case TRAIT_EXPR:
21542       if (dependent_type_p (TRAIT_EXPR_TYPE1 (*tp))
21543           || (TRAIT_EXPR_TYPE2 (*tp)
21544               && dependent_type_p (TRAIT_EXPR_TYPE2 (*tp))))
21545         return *tp;
21546       *walk_subtrees = false;
21547       return NULL_TREE;
21548
21549     case COMPONENT_REF:
21550       if (identifier_p (TREE_OPERAND (*tp, 1)))
21551         /* In a template, finish_class_member_access_expr creates a
21552            COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
21553            type-dependent, so that we can check access control at
21554            instantiation time (PR 42277).  See also Core issue 1273.  */
21555         return *tp;
21556       break;
21557
21558     case SCOPE_REF:
21559       if (instantiation_dependent_scope_ref_p (*tp))
21560         return *tp;
21561       else
21562         break;
21563
21564       /* Treat statement-expressions as dependent.  */
21565     case BIND_EXPR:
21566       return *tp;
21567
21568     default:
21569       break;
21570     }
21571
21572   if (type_dependent_expression_p (*tp))
21573     return *tp;
21574   else
21575     return NULL_TREE;
21576 }
21577
21578 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
21579    sense defined by the ABI:
21580
21581    "An expression is instantiation-dependent if it is type-dependent
21582    or value-dependent, or it has a subexpression that is type-dependent
21583    or value-dependent."  */
21584
21585 bool
21586 instantiation_dependent_expression_p (tree expression)
21587 {
21588   tree result;
21589
21590   if (!processing_template_decl)
21591     return false;
21592
21593   if (expression == error_mark_node)
21594     return false;
21595
21596   result = cp_walk_tree_without_duplicates (&expression,
21597                                             instantiation_dependent_r, NULL);
21598   return result != NULL_TREE;
21599 }
21600
21601 /* Like type_dependent_expression_p, but it also works while not processing
21602    a template definition, i.e. during substitution or mangling.  */
21603
21604 bool
21605 type_dependent_expression_p_push (tree expr)
21606 {
21607   bool b;
21608   ++processing_template_decl;
21609   b = type_dependent_expression_p (expr);
21610   --processing_template_decl;
21611   return b;
21612 }
21613
21614 /* Returns TRUE if ARGS contains a type-dependent expression.  */
21615
21616 bool
21617 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
21618 {
21619   unsigned int i;
21620   tree arg;
21621
21622   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
21623     {
21624       if (type_dependent_expression_p (arg))
21625         return true;
21626     }
21627   return false;
21628 }
21629
21630 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
21631    expressions) contains any type-dependent expressions.  */
21632
21633 bool
21634 any_type_dependent_elements_p (const_tree list)
21635 {
21636   for (; list; list = TREE_CHAIN (list))
21637     if (type_dependent_expression_p (TREE_VALUE (list)))
21638       return true;
21639
21640   return false;
21641 }
21642
21643 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
21644    expressions) contains any value-dependent expressions.  */
21645
21646 bool
21647 any_value_dependent_elements_p (const_tree list)
21648 {
21649   for (; list; list = TREE_CHAIN (list))
21650     if (value_dependent_expression_p (TREE_VALUE (list)))
21651       return true;
21652
21653   return false;
21654 }
21655
21656 /* Returns TRUE if the ARG (a template argument) is dependent.  */
21657
21658 bool
21659 dependent_template_arg_p (tree arg)
21660 {
21661   if (!processing_template_decl)
21662     return false;
21663
21664   /* Assume a template argument that was wrongly written by the user
21665      is dependent. This is consistent with what
21666      any_dependent_template_arguments_p [that calls this function]
21667      does.  */
21668   if (!arg || arg == error_mark_node)
21669     return true;
21670
21671   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
21672     arg = ARGUMENT_PACK_SELECT_ARG (arg);
21673
21674   if (TREE_CODE (arg) == TEMPLATE_DECL
21675       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
21676     return dependent_template_p (arg);
21677   else if (ARGUMENT_PACK_P (arg))
21678     {
21679       tree args = ARGUMENT_PACK_ARGS (arg);
21680       int i, len = TREE_VEC_LENGTH (args);
21681       for (i = 0; i < len; ++i)
21682         {
21683           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
21684             return true;
21685         }
21686
21687       return false;
21688     }
21689   else if (TYPE_P (arg))
21690     return dependent_type_p (arg);
21691   else
21692     return (type_dependent_expression_p (arg)
21693             || value_dependent_expression_p (arg));
21694 }
21695
21696 /* Returns true if ARGS (a collection of template arguments) contains
21697    any types that require structural equality testing.  */
21698
21699 bool
21700 any_template_arguments_need_structural_equality_p (tree args)
21701 {
21702   int i;
21703   int j;
21704
21705   if (!args)
21706     return false;
21707   if (args == error_mark_node)
21708     return true;
21709
21710   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
21711     {
21712       tree level = TMPL_ARGS_LEVEL (args, i + 1);
21713       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
21714         {
21715           tree arg = TREE_VEC_ELT (level, j);
21716           tree packed_args = NULL_TREE;
21717           int k, len = 1;
21718
21719           if (ARGUMENT_PACK_P (arg))
21720             {
21721               /* Look inside the argument pack.  */
21722               packed_args = ARGUMENT_PACK_ARGS (arg);
21723               len = TREE_VEC_LENGTH (packed_args);
21724             }
21725
21726           for (k = 0; k < len; ++k)
21727             {
21728               if (packed_args)
21729                 arg = TREE_VEC_ELT (packed_args, k);
21730
21731               if (error_operand_p (arg))
21732                 return true;
21733               else if (TREE_CODE (arg) == TEMPLATE_DECL)
21734                 continue;
21735               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
21736                 return true;
21737               else if (!TYPE_P (arg) && TREE_TYPE (arg)
21738                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
21739                 return true;
21740             }
21741         }
21742     }
21743
21744   return false;
21745 }
21746
21747 /* Returns true if ARGS (a collection of template arguments) contains
21748    any dependent arguments.  */
21749
21750 bool
21751 any_dependent_template_arguments_p (const_tree args)
21752 {
21753   int i;
21754   int j;
21755
21756   if (!args)
21757     return false;
21758   if (args == error_mark_node)
21759     return true;
21760
21761   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
21762     {
21763       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
21764       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
21765         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
21766           return true;
21767     }
21768
21769   return false;
21770 }
21771
21772 /* Returns TRUE if the template TMPL is dependent.  */
21773
21774 bool
21775 dependent_template_p (tree tmpl)
21776 {
21777   if (TREE_CODE (tmpl) == OVERLOAD)
21778     {
21779       while (tmpl)
21780         {
21781           if (dependent_template_p (OVL_CURRENT (tmpl)))
21782             return true;
21783           tmpl = OVL_NEXT (tmpl);
21784         }
21785       return false;
21786     }
21787
21788   /* Template template parameters are dependent.  */
21789   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
21790       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
21791     return true;
21792   /* So are names that have not been looked up.  */
21793   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
21794     return true;
21795   /* So are member templates of dependent classes.  */
21796   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
21797     return dependent_type_p (DECL_CONTEXT (tmpl));
21798   return false;
21799 }
21800
21801 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
21802
21803 bool
21804 dependent_template_id_p (tree tmpl, tree args)
21805 {
21806   return (dependent_template_p (tmpl)
21807           || any_dependent_template_arguments_p (args));
21808 }
21809
21810 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
21811    is dependent.  */
21812
21813 bool
21814 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
21815 {
21816   int i;
21817
21818   if (!processing_template_decl)
21819     return false;
21820
21821   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
21822     {
21823       tree decl = TREE_VEC_ELT (declv, i);
21824       tree init = TREE_VEC_ELT (initv, i);
21825       tree cond = TREE_VEC_ELT (condv, i);
21826       tree incr = TREE_VEC_ELT (incrv, i);
21827
21828       if (type_dependent_expression_p (decl))
21829         return true;
21830
21831       if (init && type_dependent_expression_p (init))
21832         return true;
21833
21834       if (type_dependent_expression_p (cond))
21835         return true;
21836
21837       if (COMPARISON_CLASS_P (cond)
21838           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
21839               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
21840         return true;
21841
21842       if (TREE_CODE (incr) == MODOP_EXPR)
21843         {
21844           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
21845               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
21846             return true;
21847         }
21848       else if (type_dependent_expression_p (incr))
21849         return true;
21850       else if (TREE_CODE (incr) == MODIFY_EXPR)
21851         {
21852           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
21853             return true;
21854           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
21855             {
21856               tree t = TREE_OPERAND (incr, 1);
21857               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
21858                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
21859                 return true;
21860             }
21861         }
21862     }
21863
21864   return false;
21865 }
21866
21867 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
21868    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
21869    no such TYPE can be found.  Note that this function peers inside
21870    uninstantiated templates and therefore should be used only in
21871    extremely limited situations.  ONLY_CURRENT_P restricts this
21872    peering to the currently open classes hierarchy (which is required
21873    when comparing types).  */
21874
21875 tree
21876 resolve_typename_type (tree type, bool only_current_p)
21877 {
21878   tree scope;
21879   tree name;
21880   tree decl;
21881   int quals;
21882   tree pushed_scope;
21883   tree result;
21884
21885   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
21886
21887   scope = TYPE_CONTEXT (type);
21888   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
21889      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
21890      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
21891      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
21892      identifier  of the TYPENAME_TYPE anymore.
21893      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
21894      TYPENAME_TYPE instead, we avoid messing up with a possible
21895      typedef variant case.  */
21896   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
21897
21898   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
21899      it first before we can figure out what NAME refers to.  */
21900   if (TREE_CODE (scope) == TYPENAME_TYPE)
21901     {
21902       if (TYPENAME_IS_RESOLVING_P (scope))
21903         /* Given a class template A with a dependent base with nested type C,
21904            typedef typename A::C::C C will land us here, as trying to resolve
21905            the initial A::C leads to the local C typedef, which leads back to
21906            A::C::C.  So we break the recursion now.  */
21907         return type;
21908       else
21909         scope = resolve_typename_type (scope, only_current_p);
21910     }
21911   /* If we don't know what SCOPE refers to, then we cannot resolve the
21912      TYPENAME_TYPE.  */
21913   if (TREE_CODE (scope) == TYPENAME_TYPE)
21914     return type;
21915   /* If the SCOPE is a template type parameter, we have no way of
21916      resolving the name.  */
21917   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
21918     return type;
21919   /* If the SCOPE is not the current instantiation, there's no reason
21920      to look inside it.  */
21921   if (only_current_p && !currently_open_class (scope))
21922     return type;
21923   /* If this is a typedef, we don't want to look inside (c++/11987).  */
21924   if (typedef_variant_p (type))
21925     return type;
21926   /* If SCOPE isn't the template itself, it will not have a valid
21927      TYPE_FIELDS list.  */
21928   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
21929     /* scope is either the template itself or a compatible instantiation
21930        like X<T>, so look up the name in the original template.  */
21931     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
21932   else
21933     /* scope is a partial instantiation, so we can't do the lookup or we
21934        will lose the template arguments.  */
21935     return type;
21936   /* Enter the SCOPE so that name lookup will be resolved as if we
21937      were in the class definition.  In particular, SCOPE will no
21938      longer be considered a dependent type.  */
21939   pushed_scope = push_scope (scope);
21940   /* Look up the declaration.  */
21941   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
21942                         tf_warning_or_error);
21943
21944   result = NULL_TREE;
21945   
21946   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
21947      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
21948   if (!decl)
21949     /*nop*/;
21950   else if (identifier_p (TYPENAME_TYPE_FULLNAME (type))
21951            && TREE_CODE (decl) == TYPE_DECL)
21952     {
21953       result = TREE_TYPE (decl);
21954       if (result == error_mark_node)
21955         result = NULL_TREE;
21956     }
21957   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
21958            && DECL_CLASS_TEMPLATE_P (decl))
21959     {
21960       tree tmpl;
21961       tree args;
21962       /* Obtain the template and the arguments.  */
21963       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
21964       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
21965       /* Instantiate the template.  */
21966       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
21967                                       /*entering_scope=*/0,
21968                                       tf_error | tf_user);
21969       if (result == error_mark_node)
21970         result = NULL_TREE;
21971     }
21972   
21973   /* Leave the SCOPE.  */
21974   if (pushed_scope)
21975     pop_scope (pushed_scope);
21976
21977   /* If we failed to resolve it, return the original typename.  */
21978   if (!result)
21979     return type;
21980   
21981   /* If lookup found a typename type, resolve that too.  */
21982   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
21983     {
21984       /* Ill-formed programs can cause infinite recursion here, so we
21985          must catch that.  */
21986       TYPENAME_IS_RESOLVING_P (type) = 1;
21987       result = resolve_typename_type (result, only_current_p);
21988       TYPENAME_IS_RESOLVING_P (type) = 0;
21989     }
21990   
21991   /* Qualify the resulting type.  */
21992   quals = cp_type_quals (type);
21993   if (quals)
21994     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
21995
21996   return result;
21997 }
21998
21999 /* EXPR is an expression which is not type-dependent.  Return a proxy
22000    for EXPR that can be used to compute the types of larger
22001    expressions containing EXPR.  */
22002
22003 tree
22004 build_non_dependent_expr (tree expr)
22005 {
22006   tree inner_expr;
22007
22008 #ifdef ENABLE_CHECKING
22009   /* Try to get a constant value for all non-dependent expressions in
22010       order to expose bugs in *_dependent_expression_p and constexpr.  */
22011   if (cxx_dialect >= cxx11)
22012     fold_non_dependent_expr (expr);
22013 #endif
22014
22015   /* Preserve OVERLOADs; the functions must be available to resolve
22016      types.  */
22017   inner_expr = expr;
22018   if (TREE_CODE (inner_expr) == STMT_EXPR)
22019     inner_expr = stmt_expr_value_expr (inner_expr);
22020   if (TREE_CODE (inner_expr) == ADDR_EXPR)
22021     inner_expr = TREE_OPERAND (inner_expr, 0);
22022   if (TREE_CODE (inner_expr) == COMPONENT_REF)
22023     inner_expr = TREE_OPERAND (inner_expr, 1);
22024   if (is_overloaded_fn (inner_expr)
22025       || TREE_CODE (inner_expr) == OFFSET_REF)
22026     return expr;
22027   /* There is no need to return a proxy for a variable.  */
22028   if (VAR_P (expr))
22029     return expr;
22030   /* Preserve string constants; conversions from string constants to
22031      "char *" are allowed, even though normally a "const char *"
22032      cannot be used to initialize a "char *".  */
22033   if (TREE_CODE (expr) == STRING_CST)
22034     return expr;
22035   /* Preserve void and arithmetic constants, as an optimization -- there is no
22036      reason to create a new node.  */
22037   if (TREE_CODE (expr) == VOID_CST
22038       || TREE_CODE (expr) == INTEGER_CST
22039       || TREE_CODE (expr) == REAL_CST)
22040     return expr;
22041   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
22042      There is at least one place where we want to know that a
22043      particular expression is a throw-expression: when checking a ?:
22044      expression, there are special rules if the second or third
22045      argument is a throw-expression.  */
22046   if (TREE_CODE (expr) == THROW_EXPR)
22047     return expr;
22048
22049   /* Don't wrap an initializer list, we need to be able to look inside.  */
22050   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
22051     return expr;
22052
22053   /* Don't wrap a dummy object, we need to be able to test for it.  */
22054   if (is_dummy_object (expr))
22055     return expr;
22056
22057   if (TREE_CODE (expr) == COND_EXPR)
22058     return build3 (COND_EXPR,
22059                    TREE_TYPE (expr),
22060                    TREE_OPERAND (expr, 0),
22061                    (TREE_OPERAND (expr, 1)
22062                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
22063                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
22064                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
22065   if (TREE_CODE (expr) == COMPOUND_EXPR
22066       && !COMPOUND_EXPR_OVERLOADED (expr))
22067     return build2 (COMPOUND_EXPR,
22068                    TREE_TYPE (expr),
22069                    TREE_OPERAND (expr, 0),
22070                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
22071
22072   /* If the type is unknown, it can't really be non-dependent */
22073   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
22074
22075   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
22076   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
22077 }
22078
22079 /* ARGS is a vector of expressions as arguments to a function call.
22080    Replace the arguments with equivalent non-dependent expressions.
22081    This modifies ARGS in place.  */
22082
22083 void
22084 make_args_non_dependent (vec<tree, va_gc> *args)
22085 {
22086   unsigned int ix;
22087   tree arg;
22088
22089   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
22090     {
22091       tree newarg = build_non_dependent_expr (arg);
22092       if (newarg != arg)
22093         (*args)[ix] = newarg;
22094     }
22095 }
22096
22097 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
22098    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
22099    parms.  */
22100
22101 static tree
22102 make_auto_1 (tree name)
22103 {
22104   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
22105   TYPE_NAME (au) = build_decl (input_location,
22106                                TYPE_DECL, name, au);
22107   TYPE_STUB_DECL (au) = TYPE_NAME (au);
22108   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
22109     (0, processing_template_decl + 1, processing_template_decl + 1,
22110      TYPE_NAME (au), NULL_TREE);
22111   TYPE_CANONICAL (au) = canonical_type_parameter (au);
22112   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
22113   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
22114
22115   return au;
22116 }
22117
22118 tree
22119 make_decltype_auto (void)
22120 {
22121   return make_auto_1 (get_identifier ("decltype(auto)"));
22122 }
22123
22124 tree
22125 make_auto (void)
22126 {
22127   return make_auto_1 (get_identifier ("auto"));
22128 }
22129
22130 /* Given type ARG, return std::initializer_list<ARG>.  */
22131
22132 static tree
22133 listify (tree arg)
22134 {
22135   tree std_init_list = namespace_binding
22136     (get_identifier ("initializer_list"), std_node);
22137   tree argvec;
22138   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
22139     {    
22140       error ("deducing from brace-enclosed initializer list requires "
22141              "#include <initializer_list>");
22142       return error_mark_node;
22143     }
22144   argvec = make_tree_vec (1);
22145   TREE_VEC_ELT (argvec, 0) = arg;
22146   return lookup_template_class (std_init_list, argvec, NULL_TREE,
22147                                 NULL_TREE, 0, tf_warning_or_error);
22148 }
22149
22150 /* Replace auto in TYPE with std::initializer_list<auto>.  */
22151
22152 static tree
22153 listify_autos (tree type, tree auto_node)
22154 {
22155   tree init_auto = listify (auto_node);
22156   tree argvec = make_tree_vec (1);
22157   TREE_VEC_ELT (argvec, 0) = init_auto;
22158   if (processing_template_decl)
22159     argvec = add_to_template_args (current_template_args (), argvec);
22160   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
22161 }
22162
22163 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
22164    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
22165
22166 tree
22167 do_auto_deduction (tree type, tree init, tree auto_node)
22168 {
22169   tree targs;
22170
22171   if (init == error_mark_node)
22172     return error_mark_node;
22173
22174   if (type_dependent_expression_p (init))
22175     /* Defining a subset of type-dependent expressions that we can deduce
22176        from ahead of time isn't worth the trouble.  */
22177     return type;
22178
22179   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
22180      with either a new invented type template parameter U or, if the
22181      initializer is a braced-init-list (8.5.4), with
22182      std::initializer_list<U>.  */
22183   if (BRACE_ENCLOSED_INITIALIZER_P (init))
22184     {
22185       if (!DIRECT_LIST_INIT_P (init))
22186         type = listify_autos (type, auto_node);
22187       else if (CONSTRUCTOR_NELTS (init) == 1)
22188         init = CONSTRUCTOR_ELT (init, 0)->value;
22189       else
22190         {
22191           if (permerror (input_location, "direct-list-initialization of "
22192                          "%<auto%> requires exactly one element"))
22193             inform (input_location,
22194                     "for deduction to %<std::initializer_list%>, use copy-"
22195                     "list-initialization (i.e. add %<=%> before the %<{%>)");
22196           type = listify_autos (type, auto_node);
22197         }
22198     }
22199
22200   init = resolve_nondeduced_context (init);
22201
22202   targs = make_tree_vec (1);
22203   if (AUTO_IS_DECLTYPE (auto_node))
22204     {
22205       bool id = (DECL_P (init) || (TREE_CODE (init) == COMPONENT_REF
22206                                    && !REF_PARENTHESIZED_P (init)));
22207       TREE_VEC_ELT (targs, 0)
22208         = finish_decltype_type (init, id, tf_warning_or_error);
22209       if (type != auto_node)
22210         {
22211           error ("%qT as type rather than plain %<decltype(auto)%>", type);
22212           return error_mark_node;
22213         }
22214     }
22215   else
22216     {
22217       tree parms = build_tree_list (NULL_TREE, type);
22218       tree tparms = make_tree_vec (1);
22219       int val;
22220
22221       TREE_VEC_ELT (tparms, 0)
22222         = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
22223       val = type_unification_real (tparms, targs, parms, &init, 1, 0,
22224                                    DEDUCE_CALL, LOOKUP_NORMAL,
22225                                    NULL, /*explain_p=*/false);
22226       if (val > 0)
22227         {
22228           if (processing_template_decl)
22229             /* Try again at instantiation time.  */
22230             return type;
22231           if (type && type != error_mark_node)
22232             /* If type is error_mark_node a diagnostic must have been
22233                emitted by now.  Also, having a mention to '<type error>'
22234                in the diagnostic is not really useful to the user.  */
22235             {
22236               if (cfun && auto_node == current_function_auto_return_pattern
22237                   && LAMBDA_FUNCTION_P (current_function_decl))
22238                 error ("unable to deduce lambda return type from %qE", init);
22239               else
22240                 error ("unable to deduce %qT from %qE", type, init);
22241             }
22242           return error_mark_node;
22243         }
22244     }
22245
22246   /* If the list of declarators contains more than one declarator, the type
22247      of each declared variable is determined as described above. If the
22248      type deduced for the template parameter U is not the same in each
22249      deduction, the program is ill-formed.  */
22250   if (TREE_TYPE (auto_node)
22251       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
22252     {
22253       if (cfun && auto_node == current_function_auto_return_pattern
22254           && LAMBDA_FUNCTION_P (current_function_decl))
22255         error ("inconsistent types %qT and %qT deduced for "
22256                "lambda return type", TREE_TYPE (auto_node),
22257                TREE_VEC_ELT (targs, 0));
22258       else
22259         error ("inconsistent deduction for %qT: %qT and then %qT",
22260                auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
22261       return error_mark_node;
22262     }
22263   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
22264
22265   if (processing_template_decl)
22266     targs = add_to_template_args (current_template_args (), targs);
22267   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
22268 }
22269
22270 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
22271    result.  */
22272
22273 tree
22274 splice_late_return_type (tree type, tree late_return_type)
22275 {
22276   tree argvec;
22277
22278   if (late_return_type == NULL_TREE)
22279     return type;
22280   argvec = make_tree_vec (1);
22281   TREE_VEC_ELT (argvec, 0) = late_return_type;
22282   if (processing_template_parmlist)
22283     /* For a late-specified return type in a template type-parameter, we
22284        need to add a dummy argument level for its parmlist.  */
22285     argvec = add_to_template_args
22286       (make_tree_vec (processing_template_parmlist), argvec);
22287   if (current_template_parms)
22288     argvec = add_to_template_args (current_template_args (), argvec);
22289   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
22290 }
22291
22292 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
22293    'decltype(auto)'.  */
22294
22295 bool
22296 is_auto (const_tree type)
22297 {
22298   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22299       && (TYPE_IDENTIFIER (type) == get_identifier ("auto")
22300           || TYPE_IDENTIFIER (type) == get_identifier ("decltype(auto)")))
22301     return true;
22302   else
22303     return false;
22304 }
22305
22306 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
22307    a use of `auto'.  Returns NULL_TREE otherwise.  */
22308
22309 tree
22310 type_uses_auto (tree type)
22311 {
22312   return find_type_usage (type, is_auto);
22313 }
22314
22315 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto',
22316    'decltype(auto)' or a concept.  */
22317
22318 bool
22319 is_auto_or_concept (const_tree type)
22320 {
22321   return is_auto (type); // or concept
22322 }
22323
22324 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing a generic type (`auto' or
22325    a concept identifier) iff TYPE contains a use of a generic type.  Returns
22326    NULL_TREE otherwise.  */
22327
22328 tree
22329 type_uses_auto_or_concept (tree type)
22330 {
22331   return find_type_usage (type, is_auto_or_concept);
22332 }
22333
22334
22335 /* For a given template T, return the vector of typedefs referenced
22336    in T for which access check is needed at T instantiation time.
22337    T is either  a FUNCTION_DECL or a RECORD_TYPE.
22338    Those typedefs were added to T by the function
22339    append_type_to_template_for_access_check.  */
22340
22341 vec<qualified_typedef_usage_t, va_gc> *
22342 get_types_needing_access_check (tree t)
22343 {
22344   tree ti;
22345   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
22346
22347   if (!t || t == error_mark_node)
22348     return NULL;
22349
22350   if (!(ti = get_template_info (t)))
22351     return NULL;
22352
22353   if (CLASS_TYPE_P (t)
22354       || TREE_CODE (t) == FUNCTION_DECL)
22355     {
22356       if (!TI_TEMPLATE (ti))
22357         return NULL;
22358
22359       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
22360     }
22361
22362   return result;
22363 }
22364
22365 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
22366    tied to T. That list of typedefs will be access checked at
22367    T instantiation time.
22368    T is either a FUNCTION_DECL or a RECORD_TYPE.
22369    TYPE_DECL is a TYPE_DECL node representing a typedef.
22370    SCOPE is the scope through which TYPE_DECL is accessed.
22371    LOCATION is the location of the usage point of TYPE_DECL.
22372
22373    This function is a subroutine of
22374    append_type_to_template_for_access_check.  */
22375
22376 static void
22377 append_type_to_template_for_access_check_1 (tree t,
22378                                             tree type_decl,
22379                                             tree scope,
22380                                             location_t location)
22381 {
22382   qualified_typedef_usage_t typedef_usage;
22383   tree ti;
22384
22385   if (!t || t == error_mark_node)
22386     return;
22387
22388   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
22389                || CLASS_TYPE_P (t))
22390               && type_decl
22391               && TREE_CODE (type_decl) == TYPE_DECL
22392               && scope);
22393
22394   if (!(ti = get_template_info (t)))
22395     return;
22396
22397   gcc_assert (TI_TEMPLATE (ti));
22398
22399   typedef_usage.typedef_decl = type_decl;
22400   typedef_usage.context = scope;
22401   typedef_usage.locus = location;
22402
22403   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
22404 }
22405
22406 /* Append TYPE_DECL to the template TEMPL.
22407    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
22408    At TEMPL instanciation time, TYPE_DECL will be checked to see
22409    if it can be accessed through SCOPE.
22410    LOCATION is the location of the usage point of TYPE_DECL.
22411
22412    e.g. consider the following code snippet:
22413
22414      class C
22415      {
22416        typedef int myint;
22417      };
22418
22419      template<class U> struct S
22420      {
22421        C::myint mi; // <-- usage point of the typedef C::myint
22422      };
22423
22424      S<char> s;
22425
22426    At S<char> instantiation time, we need to check the access of C::myint
22427    In other words, we need to check the access of the myint typedef through
22428    the C scope. For that purpose, this function will add the myint typedef
22429    and the scope C through which its being accessed to a list of typedefs
22430    tied to the template S. That list will be walked at template instantiation
22431    time and access check performed on each typedefs it contains.
22432    Note that this particular code snippet should yield an error because
22433    myint is private to C.  */
22434
22435 void
22436 append_type_to_template_for_access_check (tree templ,
22437                                           tree type_decl,
22438                                           tree scope,
22439                                           location_t location)
22440 {
22441   qualified_typedef_usage_t *iter;
22442   unsigned i;
22443
22444   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
22445
22446   /* Make sure we don't append the type to the template twice.  */
22447   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
22448     if (iter->typedef_decl == type_decl && scope == iter->context)
22449       return;
22450
22451   append_type_to_template_for_access_check_1 (templ, type_decl,
22452                                               scope, location);
22453 }
22454
22455 /* Convert the generic type parameters in PARM that match the types given in the
22456    range [START_IDX, END_IDX) from the current_template_parms into generic type
22457    packs.  */
22458
22459 tree
22460 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
22461 {
22462   tree current = current_template_parms;
22463   int depth = TMPL_PARMS_DEPTH (current);
22464   current = INNERMOST_TEMPLATE_PARMS (current);
22465   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
22466
22467   for (int i = 0; i < start_idx; ++i)
22468     TREE_VEC_ELT (replacement, i)
22469       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
22470
22471   for (int i = start_idx; i < end_idx; ++i)
22472     {
22473       /* Create a distinct parameter pack type from the current parm and add it
22474          to the replacement args to tsubst below into the generic function
22475          parameter.  */
22476
22477       tree o = TREE_TYPE (TREE_VALUE
22478                           (TREE_VEC_ELT (current, i)));
22479       tree t = copy_type (o);
22480       TEMPLATE_TYPE_PARM_INDEX (t)
22481         = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
22482                                       o, 0, 0, tf_none);
22483       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
22484       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
22485       TYPE_MAIN_VARIANT (t) = t;
22486       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
22487       TYPE_CANONICAL (t) = canonical_type_parameter (t);
22488       TREE_VEC_ELT (replacement, i) = t;
22489       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
22490     }
22491
22492   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
22493     TREE_VEC_ELT (replacement, i)
22494       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
22495
22496   /* If there are more levels then build up the replacement with the outer
22497      template parms.  */
22498   if (depth > 1)
22499     replacement = add_to_template_args (template_parms_to_args
22500                                         (TREE_CHAIN (current_template_parms)),
22501                                         replacement);
22502
22503   return tsubst (parm, replacement, tf_none, NULL_TREE);
22504 }
22505
22506
22507 /* Set up the hash tables for template instantiations.  */
22508
22509 void
22510 init_template_processing (void)
22511 {
22512   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
22513   type_specializations = hash_table<spec_hasher>::create_ggc (37);
22514 }
22515
22516 /* Print stats about the template hash tables for -fstats.  */
22517
22518 void
22519 print_template_statistics (void)
22520 {
22521   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
22522            "%f collisions\n", (long) decl_specializations->size (),
22523            (long) decl_specializations->elements (),
22524            decl_specializations->collisions ());
22525   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
22526            "%f collisions\n", (long) type_specializations->size (),
22527            (long) type_specializations->elements (),
22528            type_specializations->collisions ());
22529 }
22530
22531 #include "gt-cp-pt.h"