OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-stable/] [gcc-4.5.1/] [gcc/] [cp/] [pt.c] - Blame information for rev 859

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 283 jeremybenn
/* Handle parameterized types (templates) for GNU C++.
2
   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3
   2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
4
   Free Software Foundation, Inc.
5
   Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6
   Rewritten by Jason Merrill (jason@cygnus.com).
7
 
8
This file is part of GCC.
9
 
10
GCC is free software; you can redistribute it and/or modify
11
it under the terms of the GNU General Public License as published by
12
the Free Software Foundation; either version 3, or (at your option)
13
any later version.
14
 
15
GCC is distributed in the hope that it will be useful,
16
but WITHOUT ANY WARRANTY; without even the implied warranty of
17
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
GNU General Public License for more details.
19
 
20
You should have received a copy of the GNU General Public License
21
along with GCC; see the file COPYING3.  If not see
22
<http://www.gnu.org/licenses/>.  */
23
 
24
/* Known bugs or deficiencies include:
25
 
26
     all methods must be provided in header files; can't use a source
27
     file that contains only the method templates and "just win".  */
28
 
29
#include "config.h"
30
#include "system.h"
31
#include "coretypes.h"
32
#include "tm.h"
33
#include "obstack.h"
34
#include "tree.h"
35
#include "intl.h"
36
#include "pointer-set.h"
37
#include "flags.h"
38
#include "c-common.h"
39
#include "cp-tree.h"
40
#include "cp-objcp-common.h"
41
#include "tree-inline.h"
42
#include "decl.h"
43
#include "output.h"
44
#include "except.h"
45
#include "toplev.h"
46
#include "rtl.h"
47
#include "timevar.h"
48
#include "tree-iterator.h"
49
#include "vecprim.h"
50
 
51
/* The type of functions taking a tree, and some additional data, and
52
   returning an int.  */
53
typedef int (*tree_fn_t) (tree, void*);
54
 
55
/* The PENDING_TEMPLATES is a TREE_LIST of templates whose
56
   instantiations have been deferred, either because their definitions
57
   were not yet available, or because we were putting off doing the work.  */
58
struct GTY (()) pending_template {
59
  struct pending_template *next;
60
  struct tinst_level *tinst;
61
};
62
 
63
static GTY(()) struct pending_template *pending_templates;
64
static GTY(()) struct pending_template *last_pending_template;
65
 
66
int processing_template_parmlist;
67
static int template_header_count;
68
 
69
static GTY(()) tree saved_trees;
70
static VEC(int,heap) *inline_parm_levels;
71
 
72
static GTY(()) struct tinst_level *current_tinst_level;
73
 
74
static GTY(()) tree saved_access_scope;
75
 
76
/* Live only within one (recursive) call to tsubst_expr.  We use
77
   this to pass the statement expression node from the STMT_EXPR
78
   to the EXPR_STMT that is its result.  */
79
static tree cur_stmt_expr;
80
 
81
/* A map from local variable declarations in the body of the template
82
   presently being instantiated to the corresponding instantiated
83
   local variables.  */
84
static htab_t local_specializations;
85
 
86
typedef struct GTY(()) spec_entry
87
{
88
  tree tmpl;
89
  tree args;
90
  tree spec;
91
} spec_entry;
92
 
93
static GTY ((param_is (spec_entry)))
94
  htab_t decl_specializations;
95
 
96
static GTY ((param_is (spec_entry)))
97
  htab_t type_specializations;
98
 
99
/* Contains canonical template parameter types. The vector is indexed by
100
   the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
101
   TREE_LIST, whose TREE_VALUEs contain the canonical template
102
   parameters of various types and levels.  */
103
static GTY(()) VEC(tree,gc) *canonical_template_parms;
104
 
105
#define UNIFY_ALLOW_NONE 0
106
#define UNIFY_ALLOW_MORE_CV_QUAL 1
107
#define UNIFY_ALLOW_LESS_CV_QUAL 2
108
#define UNIFY_ALLOW_DERIVED 4
109
#define UNIFY_ALLOW_INTEGER 8
110
#define UNIFY_ALLOW_OUTER_LEVEL 16
111
#define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
112
#define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
113
 
114
static void push_access_scope (tree);
115
static void pop_access_scope (tree);
116
static bool resolve_overloaded_unification (tree, tree, tree, tree,
117
                                            unification_kind_t, int);
118
static int try_one_overload (tree, tree, tree, tree, tree,
119
                             unification_kind_t, int, bool);
120
static int unify (tree, tree, tree, tree, int);
121
static void add_pending_template (tree);
122
static tree reopen_tinst_level (struct tinst_level *);
123
static tree tsubst_initializer_list (tree, tree);
124
static tree get_class_bindings (tree, tree, tree);
125
static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126
                                   bool, bool);
127
static void tsubst_enum (tree, tree, tree);
128
static tree add_to_template_args (tree, tree);
129
static tree add_outermost_template_args (tree, tree);
130
static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131
static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132
                                             tree);
133
static int type_unification_real (tree, tree, tree, const tree *,
134
                                  unsigned int, int, unification_kind_t, int);
135
static void note_template_header (int);
136
static tree convert_nontype_argument_function (tree, tree);
137
static tree convert_nontype_argument (tree, tree);
138
static tree convert_template_argument (tree, tree, tree,
139
                                       tsubst_flags_t, int, tree);
140
static int for_each_template_parm (tree, tree_fn_t, void*,
141
                                   struct pointer_set_t*, bool);
142
static tree expand_template_argument_pack (tree);
143
static tree build_template_parm_index (int, int, int, tree, tree);
144
static bool inline_needs_template_parms (tree);
145
static void push_inline_template_parms_recursive (tree, int);
146
static tree retrieve_local_specialization (tree);
147
static void register_local_specialization (tree, tree);
148
static hashval_t hash_specialization (const void *p);
149
static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150
static int mark_template_parm (tree, void *);
151
static int template_parm_this_level_p (tree, void *);
152
static tree tsubst_friend_function (tree, tree);
153
static tree tsubst_friend_class (tree, tree);
154
static int can_complete_type_without_circularity (tree);
155
static tree get_bindings (tree, tree, tree, bool);
156
static int template_decl_level (tree);
157
static int check_cv_quals_for_unify (int, tree, tree);
158
static void template_parm_level_and_index (tree, int*, int*);
159
static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160
static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161
static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162
static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163
static void regenerate_decl_from_template (tree, tree);
164
static tree most_specialized_class (tree, tree);
165
static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166
static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167
static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168
static bool check_specialization_scope (void);
169
static tree process_partial_specialization (tree);
170
static void set_current_access_from_decl (tree);
171
static tree get_template_base (tree, tree, tree, tree);
172
static tree try_class_unification (tree, tree, tree, tree);
173
static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174
                                           tree, tree);
175
static bool template_template_parm_bindings_ok_p (tree, tree);
176
static int template_args_equal (tree, tree);
177
static void tsubst_default_arguments (tree);
178
static tree for_each_template_parm_r (tree *, int *, void *);
179
static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180
static void copy_default_args_to_explicit_spec (tree);
181
static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182
static int eq_local_specializations (const void *, const void *);
183
static bool dependent_template_arg_p (tree);
184
static bool any_template_arguments_need_structural_equality_p (tree);
185
static bool dependent_type_p_r (tree);
186
static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
187
static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
188
static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189
static tree tsubst_decl (tree, tree, tsubst_flags_t);
190
static void perform_typedefs_access_check (tree tmpl, tree targs);
191
static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192
                                                        location_t);
193
static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194
static tree listify (tree);
195
static tree listify_autos (tree, tree);
196
 
197
/* Make the current scope suitable for access checking when we are
198
   processing T.  T can be FUNCTION_DECL for instantiated function
199
   template, or VAR_DECL for static member variable (need by
200
   instantiate_decl).  */
201
 
202
static void
203
push_access_scope (tree t)
204
{
205
  gcc_assert (TREE_CODE (t) == FUNCTION_DECL
206
              || TREE_CODE (t) == VAR_DECL);
207
 
208
  if (DECL_FRIEND_CONTEXT (t))
209
    push_nested_class (DECL_FRIEND_CONTEXT (t));
210
  else if (DECL_CLASS_SCOPE_P (t))
211
    push_nested_class (DECL_CONTEXT (t));
212
  else
213
    push_to_top_level ();
214
 
215
  if (TREE_CODE (t) == FUNCTION_DECL)
216
    {
217
      saved_access_scope = tree_cons
218
        (NULL_TREE, current_function_decl, saved_access_scope);
219
      current_function_decl = t;
220
    }
221
}
222
 
223
/* Restore the scope set up by push_access_scope.  T is the node we
224
   are processing.  */
225
 
226
static void
227
pop_access_scope (tree t)
228
{
229
  if (TREE_CODE (t) == FUNCTION_DECL)
230
    {
231
      current_function_decl = TREE_VALUE (saved_access_scope);
232
      saved_access_scope = TREE_CHAIN (saved_access_scope);
233
    }
234
 
235
  if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
236
    pop_nested_class ();
237
  else
238
    pop_from_top_level ();
239
}
240
 
241
/* Do any processing required when DECL (a member template
242
   declaration) is finished.  Returns the TEMPLATE_DECL corresponding
243
   to DECL, unless it is a specialization, in which case the DECL
244
   itself is returned.  */
245
 
246
tree
247
finish_member_template_decl (tree decl)
248
{
249
  if (decl == error_mark_node)
250
    return error_mark_node;
251
 
252
  gcc_assert (DECL_P (decl));
253
 
254
  if (TREE_CODE (decl) == TYPE_DECL)
255
    {
256
      tree type;
257
 
258
      type = TREE_TYPE (decl);
259
      if (type == error_mark_node)
260
        return error_mark_node;
261
      if (MAYBE_CLASS_TYPE_P (type)
262
          && CLASSTYPE_TEMPLATE_INFO (type)
263
          && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
264
        {
265
          tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
266
          check_member_template (tmpl);
267
          return tmpl;
268
        }
269
      return NULL_TREE;
270
    }
271
  else if (TREE_CODE (decl) == FIELD_DECL)
272
    error ("data member %qD cannot be a member template", decl);
273
  else if (DECL_TEMPLATE_INFO (decl))
274
    {
275
      if (!DECL_TEMPLATE_SPECIALIZATION (decl))
276
        {
277
          check_member_template (DECL_TI_TEMPLATE (decl));
278
          return DECL_TI_TEMPLATE (decl);
279
        }
280
      else
281
        return decl;
282
    }
283
  else
284
    error ("invalid member template declaration %qD", decl);
285
 
286
  return error_mark_node;
287
}
288
 
289
/* Create a template info node.  */
290
 
291
tree
292
build_template_info (tree template_decl, tree template_args)
293
{
294
  tree result = make_node (TEMPLATE_INFO);
295
  TI_TEMPLATE (result) = template_decl;
296
  TI_ARGS (result) = template_args;
297
  return result;
298
}
299
 
300
/* Return the template info node corresponding to T, whatever T is.  */
301
 
302
tree
303
get_template_info (const_tree t)
304
{
305
  tree tinfo = NULL_TREE;
306
 
307
  if (!t || t == error_mark_node)
308
    return NULL;
309
 
310
  if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
311
    tinfo = DECL_TEMPLATE_INFO (t);
312
 
313
  if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
314
    t = TREE_TYPE (t);
315
 
316
  if (TAGGED_TYPE_P (t))
317
    tinfo = TYPE_TEMPLATE_INFO (t);
318
  else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
319
    tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
320
 
321
  return tinfo;
322
}
323
 
324
/* Returns the template nesting level of the indicated class TYPE.
325
 
326
   For example, in:
327
     template <class T>
328
     struct A
329
     {
330
       template <class U>
331
       struct B {};
332
     };
333
 
334
   A<T>::B<U> has depth two, while A<T> has depth one.
335
   Both A<T>::B<int> and A<int>::B<U> have depth one, if
336
   they are instantiations, not specializations.
337
 
338
   This function is guaranteed to return 0 if passed NULL_TREE so
339
   that, for example, `template_class_depth (current_class_type)' is
340
   always safe.  */
341
 
342
int
343
template_class_depth (tree type)
344
{
345
  int depth;
346
 
347
  for (depth = 0;
348
       type && TREE_CODE (type) != NAMESPACE_DECL;
349
       type = (TREE_CODE (type) == FUNCTION_DECL)
350
         ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
351
    {
352
      tree tinfo = get_template_info (type);
353
 
354
      if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
355
          && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
356
        ++depth;
357
    }
358
 
359
  return depth;
360
}
361
 
362
/* Subroutine of maybe_begin_member_template_processing.
363
   Returns true if processing DECL needs us to push template parms.  */
364
 
365
static bool
366
inline_needs_template_parms (tree decl)
367
{
368
  if (! DECL_TEMPLATE_INFO (decl))
369
    return false;
370
 
371
  return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
372
          > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
373
}
374
 
375
/* Subroutine of maybe_begin_member_template_processing.
376
   Push the template parms in PARMS, starting from LEVELS steps into the
377
   chain, and ending at the beginning, since template parms are listed
378
   innermost first.  */
379
 
380
static void
381
push_inline_template_parms_recursive (tree parmlist, int levels)
382
{
383
  tree parms = TREE_VALUE (parmlist);
384
  int i;
385
 
386
  if (levels > 1)
387
    push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
388
 
389
  ++processing_template_decl;
390
  current_template_parms
391
    = tree_cons (size_int (processing_template_decl),
392
                 parms, current_template_parms);
393
  TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
394
 
395
  begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
396
               NULL);
397
  for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
398
    {
399
      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
400
 
401
      if (parm == error_mark_node)
402
        continue;
403
 
404
      gcc_assert (DECL_P (parm));
405
 
406
      switch (TREE_CODE (parm))
407
        {
408
        case TYPE_DECL:
409
        case TEMPLATE_DECL:
410
          pushdecl (parm);
411
          break;
412
 
413
        case PARM_DECL:
414
          {
415
            /* Make a CONST_DECL as is done in process_template_parm.
416
               It is ugly that we recreate this here; the original
417
               version built in process_template_parm is no longer
418
               available.  */
419
            tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
420
                                    CONST_DECL, DECL_NAME (parm),
421
                                    TREE_TYPE (parm));
422
            DECL_ARTIFICIAL (decl) = 1;
423
            TREE_CONSTANT (decl) = 1;
424
            TREE_READONLY (decl) = 1;
425
            DECL_INITIAL (decl) = DECL_INITIAL (parm);
426
            SET_DECL_TEMPLATE_PARM_P (decl);
427
            pushdecl (decl);
428
          }
429
          break;
430
 
431
        default:
432
          gcc_unreachable ();
433
        }
434
    }
435
}
436
 
437
/* Restore the template parameter context for a member template or
438
   a friend template defined in a class definition.  */
439
 
440
void
441
maybe_begin_member_template_processing (tree decl)
442
{
443
  tree parms;
444
  int levels = 0;
445
 
446
  if (inline_needs_template_parms (decl))
447
    {
448
      parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
449
      levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
450
 
451
      if (DECL_TEMPLATE_SPECIALIZATION (decl))
452
        {
453
          --levels;
454
          parms = TREE_CHAIN (parms);
455
        }
456
 
457
      push_inline_template_parms_recursive (parms, levels);
458
    }
459
 
460
  /* Remember how many levels of template parameters we pushed so that
461
     we can pop them later.  */
462
  VEC_safe_push (int, heap, inline_parm_levels, levels);
463
}
464
 
465
/* Undo the effects of maybe_begin_member_template_processing.  */
466
 
467
void
468
maybe_end_member_template_processing (void)
469
{
470
  int i;
471
  int last;
472
 
473
  if (VEC_length (int, inline_parm_levels) == 0)
474
    return;
475
 
476
  last = VEC_pop (int, inline_parm_levels);
477
  for (i = 0; i < last; ++i)
478
    {
479
      --processing_template_decl;
480
      current_template_parms = TREE_CHAIN (current_template_parms);
481
      poplevel (0, 0, 0);
482
    }
483
}
484
 
485
/* Return a new template argument vector which contains all of ARGS,
486
   but has as its innermost set of arguments the EXTRA_ARGS.  */
487
 
488
static tree
489
add_to_template_args (tree args, tree extra_args)
490
{
491
  tree new_args;
492
  int extra_depth;
493
  int i;
494
  int j;
495
 
496
  if (args == NULL_TREE)
497
    return extra_args;
498
 
499
  extra_depth = TMPL_ARGS_DEPTH (extra_args);
500
  new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
501
 
502
  for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
503
    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
504
 
505
  for (j = 1; j <= extra_depth; ++j, ++i)
506
    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
507
 
508
  return new_args;
509
}
510
 
511
/* Like add_to_template_args, but only the outermost ARGS are added to
512
   the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
513
   (EXTRA_ARGS) levels are added.  This function is used to combine
514
   the template arguments from a partial instantiation with the
515
   template arguments used to attain the full instantiation from the
516
   partial instantiation.  */
517
 
518
static tree
519
add_outermost_template_args (tree args, tree extra_args)
520
{
521
  tree new_args;
522
 
523
  /* If there are more levels of EXTRA_ARGS than there are ARGS,
524
     something very fishy is going on.  */
525
  gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
526
 
527
  /* If *all* the new arguments will be the EXTRA_ARGS, just return
528
     them.  */
529
  if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
530
    return extra_args;
531
 
532
  /* For the moment, we make ARGS look like it contains fewer levels.  */
533
  TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
534
 
535
  new_args = add_to_template_args (args, extra_args);
536
 
537
  /* Now, we restore ARGS to its full dimensions.  */
538
  TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
539
 
540
  return new_args;
541
}
542
 
543
/* Return the N levels of innermost template arguments from the ARGS.  */
544
 
545
tree
546
get_innermost_template_args (tree args, int n)
547
{
548
  tree new_args;
549
  int extra_levels;
550
  int i;
551
 
552
  gcc_assert (n >= 0);
553
 
554
  /* If N is 1, just return the innermost set of template arguments.  */
555
  if (n == 1)
556
    return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
557
 
558
  /* If we're not removing anything, just return the arguments we were
559
     given.  */
560
  extra_levels = TMPL_ARGS_DEPTH (args) - n;
561
  gcc_assert (extra_levels >= 0);
562
  if (extra_levels == 0)
563
    return args;
564
 
565
  /* Make a new set of arguments, not containing the outer arguments.  */
566
  new_args = make_tree_vec (n);
567
  for (i = 1; i <= n; ++i)
568
    SET_TMPL_ARGS_LEVEL (new_args, i,
569
                         TMPL_ARGS_LEVEL (args, i + extra_levels));
570
 
571
  return new_args;
572
}
573
 
574
/* The inverse of get_innermost_template_args: Return all but the innermost
575
   EXTRA_LEVELS levels of template arguments from the ARGS.  */
576
 
577
static tree
578
strip_innermost_template_args (tree args, int extra_levels)
579
{
580
  tree new_args;
581
  int n = TMPL_ARGS_DEPTH (args) - extra_levels;
582
  int i;
583
 
584
  gcc_assert (n >= 0);
585
 
586
  /* If N is 1, just return the outermost set of template arguments.  */
587
  if (n == 1)
588
    return TMPL_ARGS_LEVEL (args, 1);
589
 
590
  /* If we're not removing anything, just return the arguments we were
591
     given.  */
592
  gcc_assert (extra_levels >= 0);
593
  if (extra_levels == 0)
594
    return args;
595
 
596
  /* Make a new set of arguments, not containing the inner arguments.  */
597
  new_args = make_tree_vec (n);
598
  for (i = 1; i <= n; ++i)
599
    SET_TMPL_ARGS_LEVEL (new_args, i,
600
                         TMPL_ARGS_LEVEL (args, i));
601
 
602
  return new_args;
603
}
604
 
605
/* We've got a template header coming up; push to a new level for storing
606
   the parms.  */
607
 
608
void
609
begin_template_parm_list (void)
610
{
611
  /* We use a non-tag-transparent scope here, which causes pushtag to
612
     put tags in this scope, rather than in the enclosing class or
613
     namespace scope.  This is the right thing, since we want
614
     TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
615
     global template class, push_template_decl handles putting the
616
     TEMPLATE_DECL into top-level scope.  For a nested template class,
617
     e.g.:
618
 
619
       template <class T> struct S1 {
620
         template <class T> struct S2 {};
621
       };
622
 
623
     pushtag contains special code to call pushdecl_with_scope on the
624
     TEMPLATE_DECL for S2.  */
625
  begin_scope (sk_template_parms, NULL);
626
  ++processing_template_decl;
627
  ++processing_template_parmlist;
628
  note_template_header (0);
629
}
630
 
631
/* This routine is called when a specialization is declared.  If it is
632
   invalid to declare a specialization here, an error is reported and
633
   false is returned, otherwise this routine will return true.  */
634
 
635
static bool
636
check_specialization_scope (void)
637
{
638
  tree scope = current_scope ();
639
 
640
  /* [temp.expl.spec]
641
 
642
     An explicit specialization shall be declared in the namespace of
643
     which the template is a member, or, for member templates, in the
644
     namespace of which the enclosing class or enclosing class
645
     template is a member.  An explicit specialization of a member
646
     function, member class or static data member of a class template
647
     shall be declared in the namespace of which the class template
648
     is a member.  */
649
  if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
650
    {
651
      error ("explicit specialization in non-namespace scope %qD", scope);
652
      return false;
653
    }
654
 
655
  /* [temp.expl.spec]
656
 
657
     In an explicit specialization declaration for a member of a class
658
     template or a member template that appears in namespace scope,
659
     the member template and some of its enclosing class templates may
660
     remain unspecialized, except that the declaration shall not
661
     explicitly specialize a class member template if its enclosing
662
     class templates are not explicitly specialized as well.  */
663
  if (current_template_parms)
664
    {
665
      error ("enclosing class templates are not explicitly specialized");
666
      return false;
667
    }
668
 
669
  return true;
670
}
671
 
672
/* We've just seen template <>.  */
673
 
674
bool
675
begin_specialization (void)
676
{
677
  begin_scope (sk_template_spec, NULL);
678
  note_template_header (1);
679
  return check_specialization_scope ();
680
}
681
 
682
/* Called at then end of processing a declaration preceded by
683
   template<>.  */
684
 
685
void
686
end_specialization (void)
687
{
688
  finish_scope ();
689
  reset_specialization ();
690
}
691
 
692
/* Any template <>'s that we have seen thus far are not referring to a
693
   function specialization.  */
694
 
695
void
696
reset_specialization (void)
697
{
698
  processing_specialization = 0;
699
  template_header_count = 0;
700
}
701
 
702
/* We've just seen a template header.  If SPECIALIZATION is nonzero,
703
   it was of the form template <>.  */
704
 
705
static void
706
note_template_header (int specialization)
707
{
708
  processing_specialization = specialization;
709
  template_header_count++;
710
}
711
 
712
/* We're beginning an explicit instantiation.  */
713
 
714
void
715
begin_explicit_instantiation (void)
716
{
717
  gcc_assert (!processing_explicit_instantiation);
718
  processing_explicit_instantiation = true;
719
}
720
 
721
 
722
void
723
end_explicit_instantiation (void)
724
{
725
  gcc_assert (processing_explicit_instantiation);
726
  processing_explicit_instantiation = false;
727
}
728
 
729
/* An explicit specialization or partial specialization TMPL is being
730
   declared.  Check that the namespace in which the specialization is
731
   occurring is permissible.  Returns false iff it is invalid to
732
   specialize TMPL in the current namespace.  */
733
 
734
static bool
735
check_specialization_namespace (tree tmpl)
736
{
737
  tree tpl_ns = decl_namespace_context (tmpl);
738
 
739
  /* [tmpl.expl.spec]
740
 
741
     An explicit specialization shall be declared in the namespace of
742
     which the template is a member, or, for member templates, in the
743
     namespace of which the enclosing class or enclosing class
744
     template is a member.  An explicit specialization of a member
745
     function, member class or static data member of a class template
746
     shall be declared in the namespace of which the class template is
747
     a member.  */
748
  if (current_scope() != DECL_CONTEXT (tmpl)
749
      && !at_namespace_scope_p ())
750
    {
751
      error ("specialization of %qD must appear at namespace scope", tmpl);
752
      return false;
753
    }
754
  if (is_associated_namespace (current_namespace, tpl_ns))
755
    /* Same or super-using namespace.  */
756
    return true;
757
  else
758
    {
759
      permerror (input_location, "specialization of %qD in different namespace", tmpl);
760
      permerror (input_location, "  from definition of %q+#D", tmpl);
761
      return false;
762
    }
763
}
764
 
765
/* SPEC is an explicit instantiation.  Check that it is valid to
766
   perform this explicit instantiation in the current namespace.  */
767
 
768
static void
769
check_explicit_instantiation_namespace (tree spec)
770
{
771
  tree ns;
772
 
773
  /* DR 275: An explicit instantiation shall appear in an enclosing
774
     namespace of its template.  */
775
  ns = decl_namespace_context (spec);
776
  if (!is_ancestor (current_namespace, ns))
777
    permerror (input_location, "explicit instantiation of %qD in namespace %qD "
778
               "(which does not enclose namespace %qD)",
779
               spec, current_namespace, ns);
780
}
781
 
782
/* The TYPE is being declared.  If it is a template type, that means it
783
   is a partial specialization.  Do appropriate error-checking.  */
784
 
785
tree
786
maybe_process_partial_specialization (tree type)
787
{
788
  tree context;
789
 
790
  if (type == error_mark_node)
791
    return error_mark_node;
792
 
793
  if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
794
    {
795
      error ("name of class shadows template template parameter %qD",
796
             TYPE_NAME (type));
797
      return error_mark_node;
798
    }
799
 
800
  context = TYPE_CONTEXT (type);
801
 
802
  if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
803
    {
804
      /* This is for ordinary explicit specialization and partial
805
         specialization of a template class such as:
806
 
807
           template <> class C<int>;
808
 
809
         or:
810
 
811
           template <class T> class C<T*>;
812
 
813
         Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
814
 
815
      if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
816
          && !COMPLETE_TYPE_P (type))
817
        {
818
          check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
819
          SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
820
          if (processing_template_decl)
821
            {
822
              if (push_template_decl (TYPE_MAIN_DECL (type))
823
                  == error_mark_node)
824
                return error_mark_node;
825
            }
826
        }
827
      else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
828
        error ("specialization of %qT after instantiation", type);
829
    }
830
  else if (CLASS_TYPE_P (type)
831
           && !CLASSTYPE_USE_TEMPLATE (type)
832
           && CLASSTYPE_TEMPLATE_INFO (type)
833
           && context && CLASS_TYPE_P (context)
834
           && CLASSTYPE_TEMPLATE_INFO (context))
835
    {
836
      /* This is for an explicit specialization of member class
837
         template according to [temp.expl.spec/18]:
838
 
839
           template <> template <class U> class C<int>::D;
840
 
841
         The context `C<int>' must be an implicit instantiation.
842
         Otherwise this is just a member class template declared
843
         earlier like:
844
 
845
           template <> class C<int> { template <class U> class D; };
846
           template <> template <class U> class C<int>::D;
847
 
848
         In the first case, `C<int>::D' is a specialization of `C<T>::D'
849
         while in the second case, `C<int>::D' is a primary template
850
         and `C<T>::D' may not exist.  */
851
 
852
      if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
853
          && !COMPLETE_TYPE_P (type))
854
        {
855
          tree t;
856
          tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
857
 
858
          if (current_namespace
859
              != decl_namespace_context (tmpl))
860
            {
861
              permerror (input_location, "specializing %q#T in different namespace", type);
862
              permerror (input_location, "  from definition of %q+#D", tmpl);
863
            }
864
 
865
          /* Check for invalid specialization after instantiation:
866
 
867
               template <> template <> class C<int>::D<int>;
868
               template <> template <class U> class C<int>::D;  */
869
 
870
          for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
871
               t; t = TREE_CHAIN (t))
872
            {
873
              tree inst = TREE_VALUE (t);
874
              if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
875
                {
876
                  /* We already have a full specialization of this partial
877
                     instantiation.  Reassign it to the new member
878
                     specialization template.  */
879
                  spec_entry elt;
880
                  spec_entry **slot;
881
 
882
                  elt.tmpl = most_general_template (tmpl);
883
                  elt.args = CLASSTYPE_TI_ARGS (inst);
884
                  elt.spec = inst;
885
 
886
                  htab_remove_elt (type_specializations, &elt);
887
 
888
                  elt.tmpl = tmpl;
889
                  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
890
 
891
                  slot = (spec_entry **)
892
                    htab_find_slot (type_specializations, &elt, INSERT);
893
                  *slot = GGC_NEW (spec_entry);
894
                  **slot = elt;
895
                }
896
              else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
897
                /* But if we've had an implicit instantiation, that's a
898
                   problem ([temp.expl.spec]/6).  */
899
                error ("specialization %qT after instantiation %qT",
900
                       type, inst);
901
            }
902
 
903
          /* Mark TYPE as a specialization.  And as a result, we only
904
             have one level of template argument for the innermost
905
             class template.  */
906
          SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
907
          CLASSTYPE_TI_ARGS (type)
908
            = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
909
        }
910
    }
911
  else if (processing_specialization)
912
    {
913
      error ("explicit specialization of non-template %qT", type);
914
      return error_mark_node;
915
    }
916
 
917
  return type;
918
}
919
 
920
/* Returns nonzero if we can optimize the retrieval of specializations
921
   for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
922
   do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
923
 
924
static inline bool
925
optimize_specialization_lookup_p (tree tmpl)
926
{
927
  return (DECL_FUNCTION_TEMPLATE_P (tmpl)
928
          && DECL_CLASS_SCOPE_P (tmpl)
929
          /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
930
             parameter.  */
931
          && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
932
          /* The optimized lookup depends on the fact that the
933
             template arguments for the member function template apply
934
             purely to the containing class, which is not true if the
935
             containing class is an explicit or partial
936
             specialization.  */
937
          && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
938
          && !DECL_MEMBER_TEMPLATE_P (tmpl)
939
          && !DECL_CONV_FN_P (tmpl)
940
          /* It is possible to have a template that is not a member
941
             template and is not a member of a template class:
942
 
943
             template <typename T>
944
             struct S { friend A::f(); };
945
 
946
             Here, the friend function is a template, but the context does
947
             not have template information.  The optimized lookup relies
948
             on having ARGS be the template arguments for both the class
949
             and the function template.  */
950
          && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
951
}
952
 
953
/* Retrieve the specialization (in the sense of [temp.spec] - a
954
   specialization is either an instantiation or an explicit
955
   specialization) of TMPL for the given template ARGS.  If there is
956
   no such specialization, return NULL_TREE.  The ARGS are a vector of
957
   arguments, or a vector of vectors of arguments, in the case of
958
   templates with more than one level of parameters.
959
 
960
   If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
961
   then we search for a partial specialization matching ARGS.  This
962
   parameter is ignored if TMPL is not a class template.  */
963
 
964
static tree
965
retrieve_specialization (tree tmpl, tree args, hashval_t hash)
966
{
967
  if (args == error_mark_node)
968
    return NULL_TREE;
969
 
970
  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
971
 
972
  /* There should be as many levels of arguments as there are
973
     levels of parameters.  */
974
  gcc_assert (TMPL_ARGS_DEPTH (args)
975
              == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
976
 
977
  if (optimize_specialization_lookup_p (tmpl))
978
    {
979
      tree class_template;
980
      tree class_specialization;
981
      VEC(tree,gc) *methods;
982
      tree fns;
983
      int idx;
984
 
985
      /* The template arguments actually apply to the containing
986
         class.  Find the class specialization with those
987
         arguments.  */
988
      class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
989
      class_specialization
990
        = retrieve_specialization (class_template, args, 0);
991
      if (!class_specialization)
992
        return NULL_TREE;
993
      /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
994
         for the specialization.  */
995
      idx = class_method_index_for_fn (class_specialization, tmpl);
996
      if (idx == -1)
997
        return NULL_TREE;
998
      /* Iterate through the methods with the indicated name, looking
999
         for the one that has an instance of TMPL.  */
1000
      methods = CLASSTYPE_METHOD_VEC (class_specialization);
1001
      for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1002
        {
1003
          tree fn = OVL_CURRENT (fns);
1004
          if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1005
              /* using-declarations can add base methods to the method vec,
1006
                 and we don't want those here.  */
1007
              && DECL_CONTEXT (fn) == class_specialization)
1008
            return fn;
1009
        }
1010
      return NULL_TREE;
1011
    }
1012
  else
1013
    {
1014
      spec_entry *found;
1015
      spec_entry elt;
1016
      htab_t specializations;
1017
 
1018
      elt.tmpl = tmpl;
1019
      elt.args = args;
1020
      elt.spec = NULL_TREE;
1021
 
1022
      if (DECL_CLASS_TEMPLATE_P (tmpl))
1023
        specializations = type_specializations;
1024
      else
1025
        specializations = decl_specializations;
1026
 
1027
      if (hash == 0)
1028
        hash = hash_specialization (&elt);
1029
      found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1030
      if (found)
1031
        return found->spec;
1032
    }
1033
 
1034
  return NULL_TREE;
1035
}
1036
 
1037
/* Like retrieve_specialization, but for local declarations.  */
1038
 
1039
static tree
1040
retrieve_local_specialization (tree tmpl)
1041
{
1042
  tree spec;
1043
 
1044
  if (local_specializations == NULL)
1045
    return NULL_TREE;
1046
 
1047
  spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1048
                                     htab_hash_pointer (tmpl));
1049
  return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1050
}
1051
 
1052
/* Returns nonzero iff DECL is a specialization of TMPL.  */
1053
 
1054
int
1055
is_specialization_of (tree decl, tree tmpl)
1056
{
1057
  tree t;
1058
 
1059
  if (TREE_CODE (decl) == FUNCTION_DECL)
1060
    {
1061
      for (t = decl;
1062
           t != NULL_TREE;
1063
           t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1064
        if (t == tmpl)
1065
          return 1;
1066
    }
1067
  else
1068
    {
1069
      gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1070
 
1071
      for (t = TREE_TYPE (decl);
1072
           t != NULL_TREE;
1073
           t = CLASSTYPE_USE_TEMPLATE (t)
1074
             ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1075
        if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1076
          return 1;
1077
    }
1078
 
1079
  return 0;
1080
}
1081
 
1082
/* Returns nonzero iff DECL is a specialization of friend declaration
1083
   FRIEND_DECL according to [temp.friend].  */
1084
 
1085
bool
1086
is_specialization_of_friend (tree decl, tree friend_decl)
1087
{
1088
  bool need_template = true;
1089
  int template_depth;
1090
 
1091
  gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1092
              || TREE_CODE (decl) == TYPE_DECL);
1093
 
1094
  /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1095
     of a template class, we want to check if DECL is a specialization
1096
     if this.  */
1097
  if (TREE_CODE (friend_decl) == FUNCTION_DECL
1098
      && DECL_TEMPLATE_INFO (friend_decl)
1099
      && !DECL_USE_TEMPLATE (friend_decl))
1100
    {
1101
      /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1102
      friend_decl = DECL_TI_TEMPLATE (friend_decl);
1103
      need_template = false;
1104
    }
1105
  else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1106
           && !PRIMARY_TEMPLATE_P (friend_decl))
1107
    need_template = false;
1108
 
1109
  /* There is nothing to do if this is not a template friend.  */
1110
  if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1111
    return false;
1112
 
1113
  if (is_specialization_of (decl, friend_decl))
1114
    return true;
1115
 
1116
  /* [temp.friend/6]
1117
     A member of a class template may be declared to be a friend of a
1118
     non-template class.  In this case, the corresponding member of
1119
     every specialization of the class template is a friend of the
1120
     class granting friendship.
1121
 
1122
     For example, given a template friend declaration
1123
 
1124
       template <class T> friend void A<T>::f();
1125
 
1126
     the member function below is considered a friend
1127
 
1128
       template <> struct A<int> {
1129
         void f();
1130
       };
1131
 
1132
     For this type of template friend, TEMPLATE_DEPTH below will be
1133
     nonzero.  To determine if DECL is a friend of FRIEND, we first
1134
     check if the enclosing class is a specialization of another.  */
1135
 
1136
  template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1137
  if (template_depth
1138
      && DECL_CLASS_SCOPE_P (decl)
1139
      && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1140
                               CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1141
    {
1142
      /* Next, we check the members themselves.  In order to handle
1143
         a few tricky cases, such as when FRIEND_DECL's are
1144
 
1145
           template <class T> friend void A<T>::g(T t);
1146
           template <class T> template <T t> friend void A<T>::h();
1147
 
1148
         and DECL's are
1149
 
1150
           void A<int>::g(int);
1151
           template <int> void A<int>::h();
1152
 
1153
         we need to figure out ARGS, the template arguments from
1154
         the context of DECL.  This is required for template substitution
1155
         of `T' in the function parameter of `g' and template parameter
1156
         of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1157
 
1158
      tree context = DECL_CONTEXT (decl);
1159
      tree args = NULL_TREE;
1160
      int current_depth = 0;
1161
 
1162
      while (current_depth < template_depth)
1163
        {
1164
          if (CLASSTYPE_TEMPLATE_INFO (context))
1165
            {
1166
              if (current_depth == 0)
1167
                args = TYPE_TI_ARGS (context);
1168
              else
1169
                args = add_to_template_args (TYPE_TI_ARGS (context), args);
1170
              current_depth++;
1171
            }
1172
          context = TYPE_CONTEXT (context);
1173
        }
1174
 
1175
      if (TREE_CODE (decl) == FUNCTION_DECL)
1176
        {
1177
          bool is_template;
1178
          tree friend_type;
1179
          tree decl_type;
1180
          tree friend_args_type;
1181
          tree decl_args_type;
1182
 
1183
          /* Make sure that both DECL and FRIEND_DECL are templates or
1184
             non-templates.  */
1185
          is_template = DECL_TEMPLATE_INFO (decl)
1186
                        && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1187
          if (need_template ^ is_template)
1188
            return false;
1189
          else if (is_template)
1190
            {
1191
              /* If both are templates, check template parameter list.  */
1192
              tree friend_parms
1193
                = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1194
                                         args, tf_none);
1195
              if (!comp_template_parms
1196
                     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1197
                      friend_parms))
1198
                return false;
1199
 
1200
              decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1201
            }
1202
          else
1203
            decl_type = TREE_TYPE (decl);
1204
 
1205
          friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1206
                                              tf_none, NULL_TREE);
1207
          if (friend_type == error_mark_node)
1208
            return false;
1209
 
1210
          /* Check if return types match.  */
1211
          if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1212
            return false;
1213
 
1214
          /* Check if function parameter types match, ignoring the
1215
             `this' parameter.  */
1216
          friend_args_type = TYPE_ARG_TYPES (friend_type);
1217
          decl_args_type = TYPE_ARG_TYPES (decl_type);
1218
          if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1219
            friend_args_type = TREE_CHAIN (friend_args_type);
1220
          if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1221
            decl_args_type = TREE_CHAIN (decl_args_type);
1222
 
1223
          return compparms (decl_args_type, friend_args_type);
1224
        }
1225
      else
1226
        {
1227
          /* DECL is a TYPE_DECL */
1228
          bool is_template;
1229
          tree decl_type = TREE_TYPE (decl);
1230
 
1231
          /* Make sure that both DECL and FRIEND_DECL are templates or
1232
             non-templates.  */
1233
          is_template
1234
            = CLASSTYPE_TEMPLATE_INFO (decl_type)
1235
              && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1236
 
1237
          if (need_template ^ is_template)
1238
            return false;
1239
          else if (is_template)
1240
            {
1241
              tree friend_parms;
1242
              /* If both are templates, check the name of the two
1243
                 TEMPLATE_DECL's first because is_friend didn't.  */
1244
              if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1245
                  != DECL_NAME (friend_decl))
1246
                return false;
1247
 
1248
              /* Now check template parameter list.  */
1249
              friend_parms
1250
                = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1251
                                         args, tf_none);
1252
              return comp_template_parms
1253
                (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1254
                 friend_parms);
1255
            }
1256
          else
1257
            return (DECL_NAME (decl)
1258
                    == DECL_NAME (friend_decl));
1259
        }
1260
    }
1261
  return false;
1262
}
1263
 
1264
/* Register the specialization SPEC as a specialization of TMPL with
1265
   the indicated ARGS.  IS_FRIEND indicates whether the specialization
1266
   is actually just a friend declaration.  Returns SPEC, or an
1267
   equivalent prior declaration, if available.  */
1268
 
1269
static tree
1270
register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1271
                         hashval_t hash)
1272
{
1273
  tree fn;
1274
  spec_entry **slot = NULL;
1275
  spec_entry elt;
1276
 
1277
  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1278
 
1279
  if (TREE_CODE (spec) == FUNCTION_DECL
1280
      && uses_template_parms (DECL_TI_ARGS (spec)))
1281
    /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1282
       register it; we want the corresponding TEMPLATE_DECL instead.
1283
       We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1284
       the more obvious `uses_template_parms (spec)' to avoid problems
1285
       with default function arguments.  In particular, given
1286
       something like this:
1287
 
1288
          template <class T> void f(T t1, T t = T())
1289
 
1290
       the default argument expression is not substituted for in an
1291
       instantiation unless and until it is actually needed.  */
1292
    return spec;
1293
 
1294
  if (optimize_specialization_lookup_p (tmpl))
1295
    /* We don't put these specializations in the hash table, but we might
1296
       want to give an error about a mismatch.  */
1297
    fn = retrieve_specialization (tmpl, args, 0);
1298
  else
1299
    {
1300
      elt.tmpl = tmpl;
1301
      elt.args = args;
1302
      elt.spec = spec;
1303
 
1304
      if (hash == 0)
1305
        hash = hash_specialization (&elt);
1306
 
1307
      slot = (spec_entry **)
1308
        htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1309
      if (*slot)
1310
        fn = (*slot)->spec;
1311
      else
1312
        fn = NULL_TREE;
1313
    }
1314
 
1315
  /* We can sometimes try to re-register a specialization that we've
1316
     already got.  In particular, regenerate_decl_from_template calls
1317
     duplicate_decls which will update the specialization list.  But,
1318
     we'll still get called again here anyhow.  It's more convenient
1319
     to simply allow this than to try to prevent it.  */
1320
  if (fn == spec)
1321
    return spec;
1322
  else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1323
    {
1324
      if (DECL_TEMPLATE_INSTANTIATION (fn))
1325
        {
1326
          if (DECL_ODR_USED (fn)
1327
              || DECL_EXPLICIT_INSTANTIATION (fn))
1328
            {
1329
              error ("specialization of %qD after instantiation",
1330
                     fn);
1331
              return error_mark_node;
1332
            }
1333
          else
1334
            {
1335
              tree clone;
1336
              /* This situation should occur only if the first
1337
                 specialization is an implicit instantiation, the
1338
                 second is an explicit specialization, and the
1339
                 implicit instantiation has not yet been used.  That
1340
                 situation can occur if we have implicitly
1341
                 instantiated a member function and then specialized
1342
                 it later.
1343
 
1344
                 We can also wind up here if a friend declaration that
1345
                 looked like an instantiation turns out to be a
1346
                 specialization:
1347
 
1348
                   template <class T> void foo(T);
1349
                   class S { friend void foo<>(int) };
1350
                   template <> void foo(int);
1351
 
1352
                 We transform the existing DECL in place so that any
1353
                 pointers to it become pointers to the updated
1354
                 declaration.
1355
 
1356
                 If there was a definition for the template, but not
1357
                 for the specialization, we want this to look as if
1358
                 there were no definition, and vice versa.  */
1359
              DECL_INITIAL (fn) = NULL_TREE;
1360
              duplicate_decls (spec, fn, is_friend);
1361
              /* The call to duplicate_decls will have applied
1362
                 [temp.expl.spec]:
1363
 
1364
                   An explicit specialization of a function template
1365
                   is inline only if it is explicitly declared to be,
1366
                   and independently of whether its function template
1367
                   is.
1368
 
1369
                to the primary function; now copy the inline bits to
1370
                the various clones.  */
1371
              FOR_EACH_CLONE (clone, fn)
1372
                {
1373
                  DECL_DECLARED_INLINE_P (clone)
1374
                    = DECL_DECLARED_INLINE_P (fn);
1375
                  DECL_SOURCE_LOCATION (clone)
1376
                    = DECL_SOURCE_LOCATION (fn);
1377
                }
1378
              check_specialization_namespace (fn);
1379
 
1380
              return fn;
1381
            }
1382
        }
1383
      else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1384
        {
1385
          if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1386
            /* Dup decl failed, but this is a new definition. Set the
1387
               line number so any errors match this new
1388
               definition.  */
1389
            DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1390
 
1391
          return fn;
1392
        }
1393
    }
1394
  else if (fn)
1395
    return duplicate_decls (spec, fn, is_friend);
1396
 
1397
  /* A specialization must be declared in the same namespace as the
1398
     template it is specializing.  */
1399
  if (DECL_TEMPLATE_SPECIALIZATION (spec)
1400
      && !check_specialization_namespace (tmpl))
1401
    DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1402
 
1403
  if (!optimize_specialization_lookup_p (tmpl))
1404
    {
1405
      gcc_assert (tmpl && args && spec);
1406
      *slot = GGC_NEW (spec_entry);
1407
      **slot = elt;
1408
      if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1409
          && PRIMARY_TEMPLATE_P (tmpl)
1410
          && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1411
        /* TMPL is a forward declaration of a template function; keep a list
1412
           of all specializations in case we need to reassign them to a friend
1413
           template later in tsubst_friend_function.  */
1414
        DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1415
          = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1416
    }
1417
 
1418
  return spec;
1419
}
1420
 
1421
/* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1422
   TMPL and ARGS members, ignores SPEC.  */
1423
 
1424
static int
1425
eq_specializations (const void *p1, const void *p2)
1426
{
1427
  const spec_entry *e1 = (const spec_entry *)p1;
1428
  const spec_entry *e2 = (const spec_entry *)p2;
1429
 
1430
  return (e1->tmpl == e2->tmpl
1431
          && comp_template_args (e1->args, e2->args));
1432
}
1433
 
1434
/* Returns a hash for a template TMPL and template arguments ARGS.  */
1435
 
1436
static hashval_t
1437
hash_tmpl_and_args (tree tmpl, tree args)
1438
{
1439
  hashval_t val = DECL_UID (tmpl);
1440
  return iterative_hash_template_arg (args, val);
1441
}
1442
 
1443
/* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1444
   ignoring SPEC.  */
1445
 
1446
static hashval_t
1447
hash_specialization (const void *p)
1448
{
1449
  const spec_entry *e = (const spec_entry *)p;
1450
  return hash_tmpl_and_args (e->tmpl, e->args);
1451
}
1452
 
1453
/* Recursively calculate a hash value for a template argument ARG, for use
1454
   in the hash tables of template specializations.  */
1455
 
1456
static hashval_t
1457
iterative_hash_template_arg (tree arg, hashval_t val)
1458
{
1459
  unsigned HOST_WIDE_INT i;
1460
  enum tree_code code;
1461
  char tclass;
1462
 
1463
  if (arg == NULL_TREE)
1464
    return iterative_hash_object (arg, val);
1465
 
1466
  if (!TYPE_P (arg))
1467
    STRIP_NOPS (arg);
1468
 
1469
  if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1470
    /* We can get one of these when re-hashing a previous entry in the middle
1471
       of substituting into a pack expansion.  Just look through it.  */
1472
    arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1473
 
1474
  code = TREE_CODE (arg);
1475
  tclass = TREE_CODE_CLASS (code);
1476
 
1477
  val = iterative_hash_object (code, val);
1478
 
1479
  switch (code)
1480
    {
1481
    case ERROR_MARK:
1482
      return val;
1483
 
1484
    case IDENTIFIER_NODE:
1485
      return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1486
 
1487
    case TREE_VEC:
1488
      {
1489
        int i, len = TREE_VEC_LENGTH (arg);
1490
        for (i = 0; i < len; ++i)
1491
          val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1492
        return val;
1493
      }
1494
 
1495
    case TYPE_PACK_EXPANSION:
1496
    case EXPR_PACK_EXPANSION:
1497
      return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1498
 
1499
    case TYPE_ARGUMENT_PACK:
1500
    case NONTYPE_ARGUMENT_PACK:
1501
      return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1502
 
1503
    case TREE_LIST:
1504
      for (; arg; arg = TREE_CHAIN (arg))
1505
        val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1506
      return val;
1507
 
1508
    case OVERLOAD:
1509
      for (; arg; arg = OVL_CHAIN (arg))
1510
        val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1511
      return val;
1512
 
1513
    case CONSTRUCTOR:
1514
      {
1515
        tree field, value;
1516
        FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1517
          {
1518
            val = iterative_hash_template_arg (field, val);
1519
            val = iterative_hash_template_arg (value, val);
1520
          }
1521
        return val;
1522
      }
1523
 
1524
    case PARM_DECL:
1525
      if (!DECL_ARTIFICIAL (arg))
1526
        val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1527
      return iterative_hash_template_arg (TREE_TYPE (arg), val);
1528
 
1529
    case TARGET_EXPR:
1530
      return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1531
 
1532
    case PTRMEM_CST:
1533
      val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1534
      return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1535
 
1536
    case TEMPLATE_PARM_INDEX:
1537
      val = iterative_hash_template_arg
1538
        (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1539
      val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1540
      return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1541
 
1542
    case TRAIT_EXPR:
1543
      val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1544
      val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1545
      return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1546
 
1547
    case BASELINK:
1548
      val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1549
                                         val);
1550
      return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1551
                                          val);
1552
 
1553
    case MODOP_EXPR:
1554
      val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1555
      code = TREE_CODE (TREE_OPERAND (arg, 1));
1556
      val = iterative_hash_object (code, val);
1557
      return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1558
 
1559
    case ARRAY_TYPE:
1560
      /* layout_type sets structural equality for arrays of
1561
         incomplete type, so we can't rely on the canonical type
1562
         for hashing.  */
1563
      val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1564
      return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1565
 
1566
    case LAMBDA_EXPR:
1567
      /* A lambda can't appear in a template arg, but don't crash on
1568
         erroneous input.  */
1569
      gcc_assert (errorcount > 0);
1570
      return val;
1571
 
1572
    default:
1573
      switch (tclass)
1574
        {
1575
        case tcc_type:
1576
          if (TYPE_CANONICAL (arg))
1577
            return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1578
                                          val);
1579
          else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1580
            return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1581
          /* Otherwise just compare the types during lookup.  */
1582
          return val;
1583
 
1584
        case tcc_declaration:
1585
        case tcc_constant:
1586
          return iterative_hash_expr (arg, val);
1587
 
1588
        default:
1589
          gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1590
          {
1591
            unsigned n = TREE_OPERAND_LENGTH (arg);
1592
            for (i = 0; i < n; ++i)
1593
              val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1594
            return val;
1595
          }
1596
        }
1597
    }
1598
  gcc_unreachable ();
1599
  return 0;
1600
}
1601
 
1602
/* Unregister the specialization SPEC as a specialization of TMPL.
1603
   Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1604
   if the SPEC was listed as a specialization of TMPL.
1605
 
1606
   Note that SPEC has been ggc_freed, so we can't look inside it.  */
1607
 
1608
bool
1609
reregister_specialization (tree spec, tree tinfo, tree new_spec)
1610
{
1611
  spec_entry **slot;
1612
  spec_entry elt;
1613
 
1614
  elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1615
  elt.args = TI_ARGS (tinfo);
1616
  elt.spec = NULL_TREE;
1617
 
1618
  slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1619
  if (*slot)
1620
    {
1621
      gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1622
      gcc_assert (new_spec != NULL_TREE);
1623
      (*slot)->spec = new_spec;
1624
      return 1;
1625
    }
1626
 
1627
  return 0;
1628
}
1629
 
1630
/* Compare an entry in the local specializations hash table P1 (which
1631
   is really a pointer to a TREE_LIST) with P2 (which is really a
1632
   DECL).  */
1633
 
1634
static int
1635
eq_local_specializations (const void *p1, const void *p2)
1636
{
1637
  return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1638
}
1639
 
1640
/* Hash P1, an entry in the local specializations table.  */
1641
 
1642
static hashval_t
1643
hash_local_specialization (const void* p1)
1644
{
1645
  return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1646
}
1647
 
1648
/* Like register_specialization, but for local declarations.  We are
1649
   registering SPEC, an instantiation of TMPL.  */
1650
 
1651
static void
1652
register_local_specialization (tree spec, tree tmpl)
1653
{
1654
  void **slot;
1655
 
1656
  slot = htab_find_slot_with_hash (local_specializations, tmpl,
1657
                                   htab_hash_pointer (tmpl), INSERT);
1658
  *slot = build_tree_list (spec, tmpl);
1659
}
1660
 
1661
/* TYPE is a class type.  Returns true if TYPE is an explicitly
1662
   specialized class.  */
1663
 
1664
bool
1665
explicit_class_specialization_p (tree type)
1666
{
1667
  if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1668
    return false;
1669
  return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1670
}
1671
 
1672
/* Print the list of functions at FNS, going through all the overloads
1673
   for each element of the list.  Alternatively, FNS can not be a
1674
   TREE_LIST, in which case it will be printed together with all the
1675
   overloads.
1676
 
1677
   MORE and *STR should respectively be FALSE and NULL when the function
1678
   is called from the outside.  They are used internally on recursive
1679
   calls.  print_candidates manages the two parameters and leaves NULL
1680
   in *STR when it ends.  */
1681
 
1682
static void
1683
print_candidates_1 (tree fns, bool more, const char **str)
1684
{
1685
  tree fn, fn2;
1686
  char *spaces = NULL;
1687
 
1688
  for (fn = fns; fn; fn = OVL_NEXT (fn))
1689
    if (TREE_CODE (fn) == TREE_LIST)
1690
      {
1691
        gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1692
        for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1693
          print_candidates_1 (TREE_VALUE (fn2),
1694
                              TREE_CHAIN (fn2) || more, str);
1695
      }
1696
    else
1697
      {
1698
        if (!*str)
1699
          {
1700
            /* Pick the prefix string.  */
1701
            if (!more && !OVL_NEXT (fns))
1702
              {
1703
                error ("candidate is: %+#D", OVL_CURRENT (fn));
1704
                continue;
1705
              }
1706
 
1707
            *str = _("candidates are:");
1708
            spaces = get_spaces (*str);
1709
          }
1710
        error ("%s %+#D", *str, OVL_CURRENT (fn));
1711
        *str = spaces ? spaces : *str;
1712
      }
1713
 
1714
  if (!more)
1715
    {
1716
      free (spaces);
1717
      *str = NULL;
1718
    }
1719
}
1720
 
1721
/* Print the list of candidate FNS in an error message.  */
1722
 
1723
void
1724
print_candidates (tree fns)
1725
{
1726
  const char *str = NULL;
1727
  print_candidates_1 (fns, false, &str);
1728
  gcc_assert (str == NULL);
1729
}
1730
 
1731
/* Returns the template (one of the functions given by TEMPLATE_ID)
1732
   which can be specialized to match the indicated DECL with the
1733
   explicit template args given in TEMPLATE_ID.  The DECL may be
1734
   NULL_TREE if none is available.  In that case, the functions in
1735
   TEMPLATE_ID are non-members.
1736
 
1737
   If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1738
   specialization of a member template.
1739
 
1740
   The TEMPLATE_COUNT is the number of references to qualifying
1741
   template classes that appeared in the name of the function. See
1742
   check_explicit_specialization for a more accurate description.
1743
 
1744
   TSK indicates what kind of template declaration (if any) is being
1745
   declared.  TSK_TEMPLATE indicates that the declaration given by
1746
   DECL, though a FUNCTION_DECL, has template parameters, and is
1747
   therefore a template function.
1748
 
1749
   The template args (those explicitly specified and those deduced)
1750
   are output in a newly created vector *TARGS_OUT.
1751
 
1752
   If it is impossible to determine the result, an error message is
1753
   issued.  The error_mark_node is returned to indicate failure.  */
1754
 
1755
static tree
1756
determine_specialization (tree template_id,
1757
                          tree decl,
1758
                          tree* targs_out,
1759
                          int need_member_template,
1760
                          int template_count,
1761
                          tmpl_spec_kind tsk)
1762
{
1763
  tree fns;
1764
  tree targs;
1765
  tree explicit_targs;
1766
  tree candidates = NULL_TREE;
1767
  /* A TREE_LIST of templates of which DECL may be a specialization.
1768
     The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1769
     corresponding TREE_PURPOSE is the set of template arguments that,
1770
     when used to instantiate the template, would produce a function
1771
     with the signature of DECL.  */
1772
  tree templates = NULL_TREE;
1773
  int header_count;
1774
  struct cp_binding_level *b;
1775
 
1776
  *targs_out = NULL_TREE;
1777
 
1778
  if (template_id == error_mark_node || decl == error_mark_node)
1779
    return error_mark_node;
1780
 
1781
  fns = TREE_OPERAND (template_id, 0);
1782
  explicit_targs = TREE_OPERAND (template_id, 1);
1783
 
1784
  if (fns == error_mark_node)
1785
    return error_mark_node;
1786
 
1787
  /* Check for baselinks.  */
1788
  if (BASELINK_P (fns))
1789
    fns = BASELINK_FUNCTIONS (fns);
1790
 
1791
  if (!is_overloaded_fn (fns))
1792
    {
1793
      error ("%qD is not a function template", fns);
1794
      return error_mark_node;
1795
    }
1796
 
1797
  /* Count the number of template headers specified for this
1798
     specialization.  */
1799
  header_count = 0;
1800
  for (b = current_binding_level;
1801
       b->kind == sk_template_parms;
1802
       b = b->level_chain)
1803
    ++header_count;
1804
 
1805
  for (; fns; fns = OVL_NEXT (fns))
1806
    {
1807
      tree fn = OVL_CURRENT (fns);
1808
 
1809
      if (TREE_CODE (fn) == TEMPLATE_DECL)
1810
        {
1811
          tree decl_arg_types;
1812
          tree fn_arg_types;
1813
 
1814
          /* In case of explicit specialization, we need to check if
1815
             the number of template headers appearing in the specialization
1816
             is correct. This is usually done in check_explicit_specialization,
1817
             but the check done there cannot be exhaustive when specializing
1818
             member functions. Consider the following code:
1819
 
1820
             template <> void A<int>::f(int);
1821
             template <> template <> void A<int>::f(int);
1822
 
1823
             Assuming that A<int> is not itself an explicit specialization
1824
             already, the first line specializes "f" which is a non-template
1825
             member function, whilst the second line specializes "f" which
1826
             is a template member function. So both lines are syntactically
1827
             correct, and check_explicit_specialization does not reject
1828
             them.
1829
 
1830
             Here, we can do better, as we are matching the specialization
1831
             against the declarations. We count the number of template
1832
             headers, and we check if they match TEMPLATE_COUNT + 1
1833
             (TEMPLATE_COUNT is the number of qualifying template classes,
1834
             plus there must be another header for the member template
1835
             itself).
1836
 
1837
             Notice that if header_count is zero, this is not a
1838
             specialization but rather a template instantiation, so there
1839
             is no check we can perform here.  */
1840
          if (header_count && header_count != template_count + 1)
1841
            continue;
1842
 
1843
          /* Check that the number of template arguments at the
1844
             innermost level for DECL is the same as for FN.  */
1845
          if (current_binding_level->kind == sk_template_parms
1846
              && !current_binding_level->explicit_spec_p
1847
              && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1848
                  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1849
                                      (current_template_parms))))
1850
            continue;
1851
 
1852
          /* DECL might be a specialization of FN.  */
1853
          decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1854
          fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1855
 
1856
          /* For a non-static member function, we need to make sure
1857
             that the const qualification is the same.  Since
1858
             get_bindings does not try to merge the "this" parameter,
1859
             we must do the comparison explicitly.  */
1860
          if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1861
              && !same_type_p (TREE_VALUE (fn_arg_types),
1862
                               TREE_VALUE (decl_arg_types)))
1863
            continue;
1864
 
1865
          /* Skip the "this" parameter and, for constructors of
1866
             classes with virtual bases, the VTT parameter.  A
1867
             full specialization of a constructor will have a VTT
1868
             parameter, but a template never will.  */
1869
          decl_arg_types
1870
            = skip_artificial_parms_for (decl, decl_arg_types);
1871
          fn_arg_types
1872
            = skip_artificial_parms_for (fn, fn_arg_types);
1873
 
1874
          /* Check that the number of function parameters matches.
1875
             For example,
1876
               template <class T> void f(int i = 0);
1877
               template <> void f<int>();
1878
             The specialization f<int> is invalid but is not caught
1879
             by get_bindings below.  */
1880
          if (list_length (fn_arg_types) != list_length (decl_arg_types))
1881
            continue;
1882
 
1883
          /* Function templates cannot be specializations; there are
1884
             no partial specializations of functions.  Therefore, if
1885
             the type of DECL does not match FN, there is no
1886
             match.  */
1887
          if (tsk == tsk_template)
1888
            {
1889
              if (compparms (fn_arg_types, decl_arg_types))
1890
                candidates = tree_cons (NULL_TREE, fn, candidates);
1891
              continue;
1892
            }
1893
 
1894
          /* See whether this function might be a specialization of this
1895
             template.  */
1896
          targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1897
 
1898
          if (!targs)
1899
            /* We cannot deduce template arguments that when used to
1900
               specialize TMPL will produce DECL.  */
1901
            continue;
1902
 
1903
          /* Save this template, and the arguments deduced.  */
1904
          templates = tree_cons (targs, fn, templates);
1905
        }
1906
      else if (need_member_template)
1907
        /* FN is an ordinary member function, and we need a
1908
           specialization of a member template.  */
1909
        ;
1910
      else if (TREE_CODE (fn) != FUNCTION_DECL)
1911
        /* We can get IDENTIFIER_NODEs here in certain erroneous
1912
           cases.  */
1913
        ;
1914
      else if (!DECL_FUNCTION_MEMBER_P (fn))
1915
        /* This is just an ordinary non-member function.  Nothing can
1916
           be a specialization of that.  */
1917
        ;
1918
      else if (DECL_ARTIFICIAL (fn))
1919
        /* Cannot specialize functions that are created implicitly.  */
1920
        ;
1921
      else
1922
        {
1923
          tree decl_arg_types;
1924
 
1925
          /* This is an ordinary member function.  However, since
1926
             we're here, we can assume it's enclosing class is a
1927
             template class.  For example,
1928
 
1929
               template <typename T> struct S { void f(); };
1930
               template <> void S<int>::f() {}
1931
 
1932
             Here, S<int>::f is a non-template, but S<int> is a
1933
             template class.  If FN has the same type as DECL, we
1934
             might be in business.  */
1935
 
1936
          if (!DECL_TEMPLATE_INFO (fn))
1937
            /* Its enclosing class is an explicit specialization
1938
               of a template class.  This is not a candidate.  */
1939
            continue;
1940
 
1941
          if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1942
                            TREE_TYPE (TREE_TYPE (fn))))
1943
            /* The return types differ.  */
1944
            continue;
1945
 
1946
          /* Adjust the type of DECL in case FN is a static member.  */
1947
          decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1948
          if (DECL_STATIC_FUNCTION_P (fn)
1949
              && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1950
            decl_arg_types = TREE_CHAIN (decl_arg_types);
1951
 
1952
          if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1953
                         decl_arg_types))
1954
            /* They match!  */
1955
            candidates = tree_cons (NULL_TREE, fn, candidates);
1956
        }
1957
    }
1958
 
1959
  if (templates && TREE_CHAIN (templates))
1960
    {
1961
      /* We have:
1962
 
1963
           [temp.expl.spec]
1964
 
1965
           It is possible for a specialization with a given function
1966
           signature to be instantiated from more than one function
1967
           template.  In such cases, explicit specification of the
1968
           template arguments must be used to uniquely identify the
1969
           function template specialization being specialized.
1970
 
1971
         Note that here, there's no suggestion that we're supposed to
1972
         determine which of the candidate templates is most
1973
         specialized.  However, we, also have:
1974
 
1975
           [temp.func.order]
1976
 
1977
           Partial ordering of overloaded function template
1978
           declarations is used in the following contexts to select
1979
           the function template to which a function template
1980
           specialization refers:
1981
 
1982
           -- when an explicit specialization refers to a function
1983
              template.
1984
 
1985
         So, we do use the partial ordering rules, at least for now.
1986
         This extension can only serve to make invalid programs valid,
1987
         so it's safe.  And, there is strong anecdotal evidence that
1988
         the committee intended the partial ordering rules to apply;
1989
         the EDG front end has that behavior, and John Spicer claims
1990
         that the committee simply forgot to delete the wording in
1991
         [temp.expl.spec].  */
1992
      tree tmpl = most_specialized_instantiation (templates);
1993
      if (tmpl != error_mark_node)
1994
        {
1995
          templates = tmpl;
1996
          TREE_CHAIN (templates) = NULL_TREE;
1997
        }
1998
    }
1999
 
2000
  if (templates == NULL_TREE && candidates == NULL_TREE)
2001
    {
2002
      error ("template-id %qD for %q+D does not match any template "
2003
             "declaration", template_id, decl);
2004
      if (header_count && header_count != template_count + 1)
2005
        inform (input_location, "saw %d %<template<>%>, need %d for "
2006
                "specializing a member function template",
2007
                header_count, template_count + 1);
2008
      return error_mark_node;
2009
    }
2010
  else if ((templates && TREE_CHAIN (templates))
2011
           || (candidates && TREE_CHAIN (candidates))
2012
           || (templates && candidates))
2013
    {
2014
      error ("ambiguous template specialization %qD for %q+D",
2015
             template_id, decl);
2016
      candidates = chainon (candidates, templates);
2017
      print_candidates (candidates);
2018
      return error_mark_node;
2019
    }
2020
 
2021
  /* We have one, and exactly one, match.  */
2022
  if (candidates)
2023
    {
2024
      tree fn = TREE_VALUE (candidates);
2025
      *targs_out = copy_node (DECL_TI_ARGS (fn));
2026
      /* DECL is a re-declaration or partial instantiation of a template
2027
         function.  */
2028
      if (TREE_CODE (fn) == TEMPLATE_DECL)
2029
        return fn;
2030
      /* It was a specialization of an ordinary member function in a
2031
         template class.  */
2032
      return DECL_TI_TEMPLATE (fn);
2033
    }
2034
 
2035
  /* It was a specialization of a template.  */
2036
  targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2037
  if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2038
    {
2039
      *targs_out = copy_node (targs);
2040
      SET_TMPL_ARGS_LEVEL (*targs_out,
2041
                           TMPL_ARGS_DEPTH (*targs_out),
2042
                           TREE_PURPOSE (templates));
2043
    }
2044
  else
2045
    *targs_out = TREE_PURPOSE (templates);
2046
  return TREE_VALUE (templates);
2047
}
2048
 
2049
/* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2050
   but with the default argument values filled in from those in the
2051
   TMPL_TYPES.  */
2052
 
2053
static tree
2054
copy_default_args_to_explicit_spec_1 (tree spec_types,
2055
                                      tree tmpl_types)
2056
{
2057
  tree new_spec_types;
2058
 
2059
  if (!spec_types)
2060
    return NULL_TREE;
2061
 
2062
  if (spec_types == void_list_node)
2063
    return void_list_node;
2064
 
2065
  /* Substitute into the rest of the list.  */
2066
  new_spec_types =
2067
    copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2068
                                          TREE_CHAIN (tmpl_types));
2069
 
2070
  /* Add the default argument for this parameter.  */
2071
  return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2072
                         TREE_VALUE (spec_types),
2073
                         new_spec_types);
2074
}
2075
 
2076
/* DECL is an explicit specialization.  Replicate default arguments
2077
   from the template it specializes.  (That way, code like:
2078
 
2079
     template <class T> void f(T = 3);
2080
     template <> void f(double);
2081
     void g () { f (); }
2082
 
2083
   works, as required.)  An alternative approach would be to look up
2084
   the correct default arguments at the call-site, but this approach
2085
   is consistent with how implicit instantiations are handled.  */
2086
 
2087
static void
2088
copy_default_args_to_explicit_spec (tree decl)
2089
{
2090
  tree tmpl;
2091
  tree spec_types;
2092
  tree tmpl_types;
2093
  tree new_spec_types;
2094
  tree old_type;
2095
  tree new_type;
2096
  tree t;
2097
  tree object_type = NULL_TREE;
2098
  tree in_charge = NULL_TREE;
2099
  tree vtt = NULL_TREE;
2100
 
2101
  /* See if there's anything we need to do.  */
2102
  tmpl = DECL_TI_TEMPLATE (decl);
2103
  tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2104
  for (t = tmpl_types; t; t = TREE_CHAIN (t))
2105
    if (TREE_PURPOSE (t))
2106
      break;
2107
  if (!t)
2108
    return;
2109
 
2110
  old_type = TREE_TYPE (decl);
2111
  spec_types = TYPE_ARG_TYPES (old_type);
2112
 
2113
  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2114
    {
2115
      /* Remove the this pointer, but remember the object's type for
2116
         CV quals.  */
2117
      object_type = TREE_TYPE (TREE_VALUE (spec_types));
2118
      spec_types = TREE_CHAIN (spec_types);
2119
      tmpl_types = TREE_CHAIN (tmpl_types);
2120
 
2121
      if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2122
        {
2123
          /* DECL may contain more parameters than TMPL due to the extra
2124
             in-charge parameter in constructors and destructors.  */
2125
          in_charge = spec_types;
2126
          spec_types = TREE_CHAIN (spec_types);
2127
        }
2128
      if (DECL_HAS_VTT_PARM_P (decl))
2129
        {
2130
          vtt = spec_types;
2131
          spec_types = TREE_CHAIN (spec_types);
2132
        }
2133
    }
2134
 
2135
  /* Compute the merged default arguments.  */
2136
  new_spec_types =
2137
    copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2138
 
2139
  /* Compute the new FUNCTION_TYPE.  */
2140
  if (object_type)
2141
    {
2142
      if (vtt)
2143
        new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2144
                                         TREE_VALUE (vtt),
2145
                                         new_spec_types);
2146
 
2147
      if (in_charge)
2148
        /* Put the in-charge parameter back.  */
2149
        new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2150
                                         TREE_VALUE (in_charge),
2151
                                         new_spec_types);
2152
 
2153
      new_type = build_method_type_directly (object_type,
2154
                                             TREE_TYPE (old_type),
2155
                                             new_spec_types);
2156
    }
2157
  else
2158
    new_type = build_function_type (TREE_TYPE (old_type),
2159
                                    new_spec_types);
2160
  new_type = cp_build_type_attribute_variant (new_type,
2161
                                              TYPE_ATTRIBUTES (old_type));
2162
  new_type = build_exception_variant (new_type,
2163
                                      TYPE_RAISES_EXCEPTIONS (old_type));
2164
  TREE_TYPE (decl) = new_type;
2165
}
2166
 
2167
/* Check to see if the function just declared, as indicated in
2168
   DECLARATOR, and in DECL, is a specialization of a function
2169
   template.  We may also discover that the declaration is an explicit
2170
   instantiation at this point.
2171
 
2172
   Returns DECL, or an equivalent declaration that should be used
2173
   instead if all goes well.  Issues an error message if something is
2174
   amiss.  Returns error_mark_node if the error is not easily
2175
   recoverable.
2176
 
2177
   FLAGS is a bitmask consisting of the following flags:
2178
 
2179
   2: The function has a definition.
2180
   4: The function is a friend.
2181
 
2182
   The TEMPLATE_COUNT is the number of references to qualifying
2183
   template classes that appeared in the name of the function.  For
2184
   example, in
2185
 
2186
     template <class T> struct S { void f(); };
2187
     void S<int>::f();
2188
 
2189
   the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2190
   classes are not counted in the TEMPLATE_COUNT, so that in
2191
 
2192
     template <class T> struct S {};
2193
     template <> struct S<int> { void f(); }
2194
     template <> void S<int>::f();
2195
 
2196
   the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2197
   invalid; there should be no template <>.)
2198
 
2199
   If the function is a specialization, it is marked as such via
2200
   DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2201
   is set up correctly, and it is added to the list of specializations
2202
   for that template.  */
2203
 
2204
tree
2205
check_explicit_specialization (tree declarator,
2206
                               tree decl,
2207
                               int template_count,
2208
                               int flags)
2209
{
2210
  int have_def = flags & 2;
2211
  int is_friend = flags & 4;
2212
  int specialization = 0;
2213
  int explicit_instantiation = 0;
2214
  int member_specialization = 0;
2215
  tree ctype = DECL_CLASS_CONTEXT (decl);
2216
  tree dname = DECL_NAME (decl);
2217
  tmpl_spec_kind tsk;
2218
 
2219
  if (is_friend)
2220
    {
2221
      if (!processing_specialization)
2222
        tsk = tsk_none;
2223
      else
2224
        tsk = tsk_excessive_parms;
2225
    }
2226
  else
2227
    tsk = current_tmpl_spec_kind (template_count);
2228
 
2229
  switch (tsk)
2230
    {
2231
    case tsk_none:
2232
      if (processing_specialization)
2233
        {
2234
          specialization = 1;
2235
          SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2236
        }
2237
      else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2238
        {
2239
          if (is_friend)
2240
            /* This could be something like:
2241
 
2242
               template <class T> void f(T);
2243
               class S { friend void f<>(int); }  */
2244
            specialization = 1;
2245
          else
2246
            {
2247
              /* This case handles bogus declarations like template <>
2248
                 template <class T> void f<int>(); */
2249
 
2250
              error ("template-id %qD in declaration of primary template",
2251
                     declarator);
2252
              return decl;
2253
            }
2254
        }
2255
      break;
2256
 
2257
    case tsk_invalid_member_spec:
2258
      /* The error has already been reported in
2259
         check_specialization_scope.  */
2260
      return error_mark_node;
2261
 
2262
    case tsk_invalid_expl_inst:
2263
      error ("template parameter list used in explicit instantiation");
2264
 
2265
      /* Fall through.  */
2266
 
2267
    case tsk_expl_inst:
2268
      if (have_def)
2269
        error ("definition provided for explicit instantiation");
2270
 
2271
      explicit_instantiation = 1;
2272
      break;
2273
 
2274
    case tsk_excessive_parms:
2275
    case tsk_insufficient_parms:
2276
      if (tsk == tsk_excessive_parms)
2277
        error ("too many template parameter lists in declaration of %qD",
2278
               decl);
2279
      else if (template_header_count)
2280
        error("too few template parameter lists in declaration of %qD", decl);
2281
      else
2282
        error("explicit specialization of %qD must be introduced by "
2283
              "%<template <>%>", decl);
2284
 
2285
      /* Fall through.  */
2286
    case tsk_expl_spec:
2287
      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2288
      if (ctype)
2289
        member_specialization = 1;
2290
      else
2291
        specialization = 1;
2292
      break;
2293
 
2294
    case tsk_template:
2295
      if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2296
        {
2297
          /* This case handles bogus declarations like template <>
2298
             template <class T> void f<int>(); */
2299
 
2300
          if (uses_template_parms (declarator))
2301
            error ("function template partial specialization %qD "
2302
                   "is not allowed", declarator);
2303
          else
2304
            error ("template-id %qD in declaration of primary template",
2305
                   declarator);
2306
          return decl;
2307
        }
2308
 
2309
      if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2310
        /* This is a specialization of a member template, without
2311
           specialization the containing class.  Something like:
2312
 
2313
             template <class T> struct S {
2314
               template <class U> void f (U);
2315
             };
2316
             template <> template <class U> void S<int>::f(U) {}
2317
 
2318
           That's a specialization -- but of the entire template.  */
2319
        specialization = 1;
2320
      break;
2321
 
2322
    default:
2323
      gcc_unreachable ();
2324
    }
2325
 
2326
  if (specialization || member_specialization)
2327
    {
2328
      tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2329
      for (; t; t = TREE_CHAIN (t))
2330
        if (TREE_PURPOSE (t))
2331
          {
2332
            permerror (input_location,
2333
                       "default argument specified in explicit specialization");
2334
            break;
2335
          }
2336
    }
2337
 
2338
  if (specialization || member_specialization || explicit_instantiation)
2339
    {
2340
      tree tmpl = NULL_TREE;
2341
      tree targs = NULL_TREE;
2342
 
2343
      /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2344
      if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2345
        {
2346
          tree fns;
2347
 
2348
          gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2349
          if (ctype)
2350
            fns = dname;
2351
          else
2352
            {
2353
              /* If there is no class context, the explicit instantiation
2354
                 must be at namespace scope.  */
2355
              gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2356
 
2357
              /* Find the namespace binding, using the declaration
2358
                 context.  */
2359
              fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2360
                                           false, true);
2361
              if (fns == error_mark_node || !is_overloaded_fn (fns))
2362
                {
2363
                  error ("%qD is not a template function", dname);
2364
                  fns = error_mark_node;
2365
                }
2366
              else
2367
                {
2368
                  tree fn = OVL_CURRENT (fns);
2369
                  if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2370
                                                CP_DECL_CONTEXT (fn)))
2371
                    error ("%qD is not declared in %qD",
2372
                           decl, current_namespace);
2373
                }
2374
            }
2375
 
2376
          declarator = lookup_template_function (fns, NULL_TREE);
2377
        }
2378
 
2379
      if (declarator == error_mark_node)
2380
        return error_mark_node;
2381
 
2382
      if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2383
        {
2384
          if (!explicit_instantiation)
2385
            /* A specialization in class scope.  This is invalid,
2386
               but the error will already have been flagged by
2387
               check_specialization_scope.  */
2388
            return error_mark_node;
2389
          else
2390
            {
2391
              /* It's not valid to write an explicit instantiation in
2392
                 class scope, e.g.:
2393
 
2394
                   class C { template void f(); }
2395
 
2396
                   This case is caught by the parser.  However, on
2397
                   something like:
2398
 
2399
                   template class C { void f(); };
2400
 
2401
                   (which is invalid) we can get here.  The error will be
2402
                   issued later.  */
2403
              ;
2404
            }
2405
 
2406
          return decl;
2407
        }
2408
      else if (ctype != NULL_TREE
2409
               && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2410
                   IDENTIFIER_NODE))
2411
        {
2412
          /* Find the list of functions in ctype that have the same
2413
             name as the declared function.  */
2414
          tree name = TREE_OPERAND (declarator, 0);
2415
          tree fns = NULL_TREE;
2416
          int idx;
2417
 
2418
          if (constructor_name_p (name, ctype))
2419
            {
2420
              int is_constructor = DECL_CONSTRUCTOR_P (decl);
2421
 
2422
              if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2423
                  : !CLASSTYPE_DESTRUCTORS (ctype))
2424
                {
2425
                  /* From [temp.expl.spec]:
2426
 
2427
                     If such an explicit specialization for the member
2428
                     of a class template names an implicitly-declared
2429
                     special member function (clause _special_), the
2430
                     program is ill-formed.
2431
 
2432
                     Similar language is found in [temp.explicit].  */
2433
                  error ("specialization of implicitly-declared special member function");
2434
                  return error_mark_node;
2435
                }
2436
 
2437
              name = is_constructor ? ctor_identifier : dtor_identifier;
2438
            }
2439
 
2440
          if (!DECL_CONV_FN_P (decl))
2441
            {
2442
              idx = lookup_fnfields_1 (ctype, name);
2443
              if (idx >= 0)
2444
                fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2445
            }
2446
          else
2447
            {
2448
              VEC(tree,gc) *methods;
2449
              tree ovl;
2450
 
2451
              /* For a type-conversion operator, we cannot do a
2452
                 name-based lookup.  We might be looking for `operator
2453
                 int' which will be a specialization of `operator T'.
2454
                 So, we find *all* the conversion operators, and then
2455
                 select from them.  */
2456
              fns = NULL_TREE;
2457
 
2458
              methods = CLASSTYPE_METHOD_VEC (ctype);
2459
              if (methods)
2460
                for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2461
                     VEC_iterate (tree, methods, idx, ovl);
2462
                     ++idx)
2463
                  {
2464
                    if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2465
                      /* There are no more conversion functions.  */
2466
                      break;
2467
 
2468
                    /* Glue all these conversion functions together
2469
                       with those we already have.  */
2470
                    for (; ovl; ovl = OVL_NEXT (ovl))
2471
                      fns = ovl_cons (OVL_CURRENT (ovl), fns);
2472
                  }
2473
            }
2474
 
2475
          if (fns == NULL_TREE)
2476
            {
2477
              error ("no member function %qD declared in %qT", name, ctype);
2478
              return error_mark_node;
2479
            }
2480
          else
2481
            TREE_OPERAND (declarator, 0) = fns;
2482
        }
2483
 
2484
      /* Figure out what exactly is being specialized at this point.
2485
         Note that for an explicit instantiation, even one for a
2486
         member function, we cannot tell apriori whether the
2487
         instantiation is for a member template, or just a member
2488
         function of a template class.  Even if a member template is
2489
         being instantiated, the member template arguments may be
2490
         elided if they can be deduced from the rest of the
2491
         declaration.  */
2492
      tmpl = determine_specialization (declarator, decl,
2493
                                       &targs,
2494
                                       member_specialization,
2495
                                       template_count,
2496
                                       tsk);
2497
 
2498
      if (!tmpl || tmpl == error_mark_node)
2499
        /* We couldn't figure out what this declaration was
2500
           specializing.  */
2501
        return error_mark_node;
2502
      else
2503
        {
2504
          tree gen_tmpl = most_general_template (tmpl);
2505
 
2506
          if (explicit_instantiation)
2507
            {
2508
              /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2509
                 is done by do_decl_instantiation later.  */
2510
 
2511
              int arg_depth = TMPL_ARGS_DEPTH (targs);
2512
              int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2513
 
2514
              if (arg_depth > parm_depth)
2515
                {
2516
                  /* If TMPL is not the most general template (for
2517
                     example, if TMPL is a friend template that is
2518
                     injected into namespace scope), then there will
2519
                     be too many levels of TARGS.  Remove some of them
2520
                     here.  */
2521
                  int i;
2522
                  tree new_targs;
2523
 
2524
                  new_targs = make_tree_vec (parm_depth);
2525
                  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2526
                    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2527
                      = TREE_VEC_ELT (targs, i);
2528
                  targs = new_targs;
2529
                }
2530
 
2531
              return instantiate_template (tmpl, targs, tf_error);
2532
            }
2533
 
2534
          /* If we thought that the DECL was a member function, but it
2535
             turns out to be specializing a static member function,
2536
             make DECL a static member function as well.  */
2537
          if (DECL_STATIC_FUNCTION_P (tmpl)
2538
              && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2539
            revert_static_member_fn (decl);
2540
 
2541
          /* If this is a specialization of a member template of a
2542
             template class, we want to return the TEMPLATE_DECL, not
2543
             the specialization of it.  */
2544
          if (tsk == tsk_template)
2545
            {
2546
              tree result = DECL_TEMPLATE_RESULT (tmpl);
2547
              SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2548
              DECL_INITIAL (result) = NULL_TREE;
2549
              if (have_def)
2550
                {
2551
                  tree parm;
2552
                  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2553
                  DECL_SOURCE_LOCATION (result)
2554
                    = DECL_SOURCE_LOCATION (decl);
2555
                  /* We want to use the argument list specified in the
2556
                     definition, not in the original declaration.  */
2557
                  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2558
                  for (parm = DECL_ARGUMENTS (result); parm;
2559
                       parm = TREE_CHAIN (parm))
2560
                    DECL_CONTEXT (parm) = result;
2561
                }
2562
              return register_specialization (tmpl, gen_tmpl, targs,
2563
                                              is_friend, 0);
2564
            }
2565
 
2566
          /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2567
          DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2568
 
2569
          /* Inherit default function arguments from the template
2570
             DECL is specializing.  */
2571
          copy_default_args_to_explicit_spec (decl);
2572
 
2573
          /* This specialization has the same protection as the
2574
             template it specializes.  */
2575
          TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2576
          TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2577
 
2578
          /* 7.1.1-1 [dcl.stc]
2579
 
2580
             A storage-class-specifier shall not be specified in an
2581
             explicit specialization...
2582
 
2583
             The parser rejects these, so unless action is taken here,
2584
             explicit function specializations will always appear with
2585
             global linkage.
2586
 
2587
             The action recommended by the C++ CWG in response to C++
2588
             defect report 605 is to make the storage class and linkage
2589
             of the explicit specialization match the templated function:
2590
 
2591
             http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2592
           */
2593
          if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2594
            {
2595
              tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2596
              gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2597
 
2598
              /* This specialization has the same linkage and visibility as
2599
                 the function template it specializes.  */
2600
              TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2601
              if (! TREE_PUBLIC (decl))
2602
                {
2603
                  DECL_INTERFACE_KNOWN (decl) = 1;
2604
                  DECL_NOT_REALLY_EXTERN (decl) = 1;
2605
                }
2606
              DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2607
              if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2608
                {
2609
                  DECL_VISIBILITY_SPECIFIED (decl) = 1;
2610
                  DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2611
                }
2612
            }
2613
 
2614
          /* If DECL is a friend declaration, declared using an
2615
             unqualified name, the namespace associated with DECL may
2616
             have been set incorrectly.  For example, in:
2617
 
2618
               template <typename T> void f(T);
2619
               namespace N {
2620
                 struct S { friend void f<int>(int); }
2621
               }
2622
 
2623
             we will have set the DECL_CONTEXT for the friend
2624
             declaration to N, rather than to the global namespace.  */
2625
          if (DECL_NAMESPACE_SCOPE_P (decl))
2626
            DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2627
 
2628
          if (is_friend && !have_def)
2629
            /* This is not really a declaration of a specialization.
2630
               It's just the name of an instantiation.  But, it's not
2631
               a request for an instantiation, either.  */
2632
            SET_DECL_IMPLICIT_INSTANTIATION (decl);
2633
          else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2634
            /* This is indeed a specialization.  In case of constructors
2635
               and destructors, we need in-charge and not-in-charge
2636
               versions in V3 ABI.  */
2637
            clone_function_decl (decl, /*update_method_vec_p=*/0);
2638
 
2639
          /* Register this specialization so that we can find it
2640
             again.  */
2641
          decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2642
        }
2643
    }
2644
 
2645
  return decl;
2646
}
2647
 
2648
/* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2649
   parameters.  These are represented in the same format used for
2650
   DECL_TEMPLATE_PARMS.  */
2651
 
2652
int
2653
comp_template_parms (const_tree parms1, const_tree parms2)
2654
{
2655
  const_tree p1;
2656
  const_tree p2;
2657
 
2658
  if (parms1 == parms2)
2659
    return 1;
2660
 
2661
  for (p1 = parms1, p2 = parms2;
2662
       p1 != NULL_TREE && p2 != NULL_TREE;
2663
       p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2664
    {
2665
      tree t1 = TREE_VALUE (p1);
2666
      tree t2 = TREE_VALUE (p2);
2667
      int i;
2668
 
2669
      gcc_assert (TREE_CODE (t1) == TREE_VEC);
2670
      gcc_assert (TREE_CODE (t2) == TREE_VEC);
2671
 
2672
      if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2673
        return 0;
2674
 
2675
      for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2676
        {
2677
          tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2678
          tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2679
 
2680
          /* If either of the template parameters are invalid, assume
2681
             they match for the sake of error recovery. */
2682
          if (parm1 == error_mark_node || parm2 == error_mark_node)
2683
            return 1;
2684
 
2685
          if (TREE_CODE (parm1) != TREE_CODE (parm2))
2686
            return 0;
2687
 
2688
          if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2689
              && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2690
                  == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2691
            continue;
2692
          else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2693
            return 0;
2694
        }
2695
    }
2696
 
2697
  if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2698
    /* One set of parameters has more parameters lists than the
2699
       other.  */
2700
    return 0;
2701
 
2702
  return 1;
2703
}
2704
 
2705
/* Determine whether PARM is a parameter pack.  */
2706
 
2707
bool
2708
template_parameter_pack_p (const_tree parm)
2709
{
2710
  /* Determine if we have a non-type template parameter pack.  */
2711
  if (TREE_CODE (parm) == PARM_DECL)
2712
    return (DECL_TEMPLATE_PARM_P (parm)
2713
            && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2714
 
2715
  /* If this is a list of template parameters, we could get a
2716
     TYPE_DECL or a TEMPLATE_DECL.  */
2717
  if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2718
    parm = TREE_TYPE (parm);
2719
 
2720
  return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2721
           || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2722
          && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2723
}
2724
 
2725
/* Determine if T is a function parameter pack.  */
2726
 
2727
bool
2728
function_parameter_pack_p (const_tree t)
2729
{
2730
  if (t && TREE_CODE (t) == PARM_DECL)
2731
    return FUNCTION_PARAMETER_PACK_P (t);
2732
  return false;
2733
}
2734
 
2735
/* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2736
   PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2737
 
2738
tree
2739
get_function_template_decl (const_tree primary_func_tmpl_inst)
2740
{
2741
  if (! primary_func_tmpl_inst
2742
      || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2743
      || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2744
    return NULL;
2745
 
2746
  return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2747
}
2748
 
2749
/* Return true iff the function parameter PARAM_DECL was expanded
2750
   from the function parameter pack PACK.  */
2751
 
2752
bool
2753
function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2754
{
2755
  if (DECL_ARTIFICIAL (param_decl)
2756
      || !function_parameter_pack_p (pack))
2757
    return false;
2758
 
2759
  /* The parameter pack and its pack arguments have the same
2760
     DECL_PARM_INDEX.  */
2761
  return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2762
}
2763
 
2764
/* Determine whether ARGS describes a variadic template args list,
2765
   i.e., one that is terminated by a template argument pack.  */
2766
 
2767
static bool
2768
template_args_variadic_p (tree args)
2769
{
2770
  int nargs;
2771
  tree last_parm;
2772
 
2773
  if (args == NULL_TREE)
2774
    return false;
2775
 
2776
  args = INNERMOST_TEMPLATE_ARGS (args);
2777
  nargs = TREE_VEC_LENGTH (args);
2778
 
2779
  if (nargs == 0)
2780
    return false;
2781
 
2782
  last_parm = TREE_VEC_ELT (args, nargs - 1);
2783
 
2784
  return ARGUMENT_PACK_P (last_parm);
2785
}
2786
 
2787
/* Generate a new name for the parameter pack name NAME (an
2788
   IDENTIFIER_NODE) that incorporates its */
2789
 
2790
static tree
2791
make_ith_pack_parameter_name (tree name, int i)
2792
{
2793
  /* Munge the name to include the parameter index.  */
2794
#define NUMBUF_LEN 128
2795
  char numbuf[NUMBUF_LEN];
2796
  char* newname;
2797
  int newname_len;
2798
 
2799
  snprintf (numbuf, NUMBUF_LEN, "%i", i);
2800
  newname_len = IDENTIFIER_LENGTH (name)
2801
                + strlen (numbuf) + 2;
2802
  newname = (char*)alloca (newname_len);
2803
  snprintf (newname, newname_len,
2804
            "%s#%i", IDENTIFIER_POINTER (name), i);
2805
  return get_identifier (newname);
2806
}
2807
 
2808
/* Return true if T is a primary function
2809
   or class template instantiation.  */
2810
 
2811
bool
2812
primary_template_instantiation_p (const_tree t)
2813
{
2814
  if (!t)
2815
    return false;
2816
 
2817
  if (TREE_CODE (t) == FUNCTION_DECL)
2818
    return DECL_LANG_SPECIFIC (t)
2819
           && DECL_TEMPLATE_INSTANTIATION (t)
2820
           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2821
  else if (CLASS_TYPE_P (t))
2822
    return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2823
           && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2824
  return false;
2825
}
2826
 
2827
/* Return true if PARM is a template template parameter.  */
2828
 
2829
bool
2830
template_template_parameter_p (const_tree parm)
2831
{
2832
  return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2833
}
2834
 
2835
/* Return the template parameters of T if T is a
2836
   primary template instantiation, NULL otherwise.  */
2837
 
2838
tree
2839
get_primary_template_innermost_parameters (const_tree t)
2840
{
2841
  tree parms = NULL, template_info = NULL;
2842
 
2843
  if ((template_info = get_template_info (t))
2844
      && primary_template_instantiation_p (t))
2845
    parms = INNERMOST_TEMPLATE_PARMS
2846
        (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2847
 
2848
  return parms;
2849
}
2850
 
2851
/* Return the template parameters of the LEVELth level from the full list
2852
   of template parameters PARMS.  */
2853
 
2854
tree
2855
get_template_parms_at_level (tree parms, int level)
2856
{
2857
  tree p;
2858
  if (!parms
2859
      || TREE_CODE (parms) != TREE_LIST
2860
      || level > TMPL_PARMS_DEPTH (parms))
2861
    return NULL_TREE;
2862
 
2863
  for (p = parms; p; p = TREE_CHAIN (p))
2864
    if (TMPL_PARMS_DEPTH (p) == level)
2865
      return p;
2866
 
2867
  return NULL_TREE;
2868
}
2869
 
2870
/* Returns the template arguments of T if T is a template instantiation,
2871
   NULL otherwise.  */
2872
 
2873
tree
2874
get_template_innermost_arguments (const_tree t)
2875
{
2876
  tree args = NULL, template_info = NULL;
2877
 
2878
  if ((template_info = get_template_info (t))
2879
      && TI_ARGS (template_info))
2880
    args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2881
 
2882
  return args;
2883
}
2884
 
2885
/* Return the argument pack elements of T if T is a template argument pack,
2886
   NULL otherwise.  */
2887
 
2888
tree
2889
get_template_argument_pack_elems (const_tree t)
2890
{
2891
  if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2892
      && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2893
    return NULL;
2894
 
2895
  return ARGUMENT_PACK_ARGS (t);
2896
}
2897
 
2898
/* Structure used to track the progress of find_parameter_packs_r.  */
2899
struct find_parameter_pack_data
2900
{
2901
  /* TREE_LIST that will contain all of the parameter packs found by
2902
     the traversal.  */
2903
  tree* parameter_packs;
2904
 
2905
  /* Set of AST nodes that have been visited by the traversal.  */
2906
  struct pointer_set_t *visited;
2907
};
2908
 
2909
/* Identifies all of the argument packs that occur in a template
2910
   argument and appends them to the TREE_LIST inside DATA, which is a
2911
   find_parameter_pack_data structure. This is a subroutine of
2912
   make_pack_expansion and uses_parameter_packs.  */
2913
static tree
2914
find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2915
{
2916
  tree t = *tp;
2917
  struct find_parameter_pack_data* ppd =
2918
    (struct find_parameter_pack_data*)data;
2919
  bool parameter_pack_p = false;
2920
 
2921
  /* Identify whether this is a parameter pack or not.  */
2922
  switch (TREE_CODE (t))
2923
    {
2924
    case TEMPLATE_PARM_INDEX:
2925
      if (TEMPLATE_PARM_PARAMETER_PACK (t))
2926
        parameter_pack_p = true;
2927
      break;
2928
 
2929
    case TEMPLATE_TYPE_PARM:
2930
    case TEMPLATE_TEMPLATE_PARM:
2931
      if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2932
        parameter_pack_p = true;
2933
      break;
2934
 
2935
    case PARM_DECL:
2936
      if (FUNCTION_PARAMETER_PACK_P (t))
2937
        {
2938
          /* We don't want to walk into the type of a PARM_DECL,
2939
             because we don't want to see the type parameter pack.  */
2940
          *walk_subtrees = 0;
2941
          parameter_pack_p = true;
2942
        }
2943
      break;
2944
 
2945
    default:
2946
      /* Not a parameter pack.  */
2947
      break;
2948
    }
2949
 
2950
  if (parameter_pack_p)
2951
    {
2952
      /* Add this parameter pack to the list.  */
2953
      *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2954
    }
2955
 
2956
  if (TYPE_P (t))
2957
    cp_walk_tree (&TYPE_CONTEXT (t),
2958
                  &find_parameter_packs_r, ppd, ppd->visited);
2959
 
2960
  /* This switch statement will return immediately if we don't find a
2961
     parameter pack.  */
2962
  switch (TREE_CODE (t))
2963
    {
2964
    case TEMPLATE_PARM_INDEX:
2965
      return NULL_TREE;
2966
 
2967
    case BOUND_TEMPLATE_TEMPLATE_PARM:
2968
      /* Check the template itself.  */
2969
      cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
2970
                    &find_parameter_packs_r, ppd, ppd->visited);
2971
      /* Check the template arguments.  */
2972
      cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
2973
                    ppd->visited);
2974
      *walk_subtrees = 0;
2975
      return NULL_TREE;
2976
 
2977
    case TEMPLATE_TYPE_PARM:
2978
    case TEMPLATE_TEMPLATE_PARM:
2979
      return NULL_TREE;
2980
 
2981
    case PARM_DECL:
2982
      return NULL_TREE;
2983
 
2984
    case RECORD_TYPE:
2985
      if (TYPE_PTRMEMFUNC_P (t))
2986
        return NULL_TREE;
2987
      /* Fall through.  */
2988
 
2989
    case UNION_TYPE:
2990
    case ENUMERAL_TYPE:
2991
      if (TYPE_TEMPLATE_INFO (t))
2992
        cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2993
                      &find_parameter_packs_r, ppd, ppd->visited);
2994
 
2995
      *walk_subtrees = 0;
2996
      return NULL_TREE;
2997
 
2998
    case TEMPLATE_DECL:
2999
      cp_walk_tree (&TREE_TYPE (t),
3000
                    &find_parameter_packs_r, ppd, ppd->visited);
3001
      return NULL_TREE;
3002
 
3003
    case TYPENAME_TYPE:
3004
      cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3005
                   ppd, ppd->visited);
3006
      *walk_subtrees = 0;
3007
      return NULL_TREE;
3008
 
3009
    case TYPE_PACK_EXPANSION:
3010
    case EXPR_PACK_EXPANSION:
3011
      *walk_subtrees = 0;
3012
      return NULL_TREE;
3013
 
3014
    case INTEGER_TYPE:
3015
      cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3016
                    ppd, ppd->visited);
3017
      *walk_subtrees = 0;
3018
      return NULL_TREE;
3019
 
3020
    case IDENTIFIER_NODE:
3021
      cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3022
                    ppd->visited);
3023
      *walk_subtrees = 0;
3024
      return NULL_TREE;
3025
 
3026
    default:
3027
      return NULL_TREE;
3028
    }
3029
 
3030
  return NULL_TREE;
3031
}
3032
 
3033
/* Determines if the expression or type T uses any parameter packs.  */
3034
bool
3035
uses_parameter_packs (tree t)
3036
{
3037
  tree parameter_packs = NULL_TREE;
3038
  struct find_parameter_pack_data ppd;
3039
  ppd.parameter_packs = &parameter_packs;
3040
  ppd.visited = pointer_set_create ();
3041
  cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3042
  pointer_set_destroy (ppd.visited);
3043
  return parameter_packs != NULL_TREE;
3044
}
3045
 
3046
/* Turn ARG, which may be an expression, type, or a TREE_LIST
3047
   representation a base-class initializer into a parameter pack
3048
   expansion. If all goes well, the resulting node will be an
3049
   EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3050
   respectively.  */
3051
tree
3052
make_pack_expansion (tree arg)
3053
{
3054
  tree result;
3055
  tree parameter_packs = NULL_TREE;
3056
  bool for_types = false;
3057
  struct find_parameter_pack_data ppd;
3058
 
3059
  if (!arg || arg == error_mark_node)
3060
    return arg;
3061
 
3062
  if (TREE_CODE (arg) == TREE_LIST)
3063
    {
3064
      /* The only time we will see a TREE_LIST here is for a base
3065
         class initializer.  In this case, the TREE_PURPOSE will be a
3066
         _TYPE node (representing the base class expansion we're
3067
         initializing) and the TREE_VALUE will be a TREE_LIST
3068
         containing the initialization arguments.
3069
 
3070
         The resulting expansion looks somewhat different from most
3071
         expansions. Rather than returning just one _EXPANSION, we
3072
         return a TREE_LIST whose TREE_PURPOSE is a
3073
         TYPE_PACK_EXPANSION containing the bases that will be
3074
         initialized.  The TREE_VALUE will be identical to the
3075
         original TREE_VALUE, which is a list of arguments that will
3076
         be passed to each base.  We do not introduce any new pack
3077
         expansion nodes into the TREE_VALUE (although it is possible
3078
         that some already exist), because the TREE_PURPOSE and
3079
         TREE_VALUE all need to be expanded together with the same
3080
         _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3081
         resulting TREE_PURPOSE will mention the parameter packs in
3082
         both the bases and the arguments to the bases.  */
3083
      tree purpose;
3084
      tree value;
3085
      tree parameter_packs = NULL_TREE;
3086
 
3087
      /* Determine which parameter packs will be used by the base
3088
         class expansion.  */
3089
      ppd.visited = pointer_set_create ();
3090
      ppd.parameter_packs = &parameter_packs;
3091
      cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3092
                    &ppd, ppd.visited);
3093
 
3094
      if (parameter_packs == NULL_TREE)
3095
        {
3096
          error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3097
          pointer_set_destroy (ppd.visited);
3098
          return error_mark_node;
3099
        }
3100
 
3101
      if (TREE_VALUE (arg) != void_type_node)
3102
        {
3103
          /* Collect the sets of parameter packs used in each of the
3104
             initialization arguments.  */
3105
          for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3106
            {
3107
              /* Determine which parameter packs will be expanded in this
3108
                 argument.  */
3109
              cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3110
                            &ppd, ppd.visited);
3111
            }
3112
        }
3113
 
3114
      pointer_set_destroy (ppd.visited);
3115
 
3116
      /* Create the pack expansion type for the base type.  */
3117
      purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3118
      SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3119
      PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3120
 
3121
      /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3122
         they will rarely be compared to anything.  */
3123
      SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3124
 
3125
      return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3126
    }
3127
 
3128
  if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3129
    for_types = true;
3130
 
3131
  /* Build the PACK_EXPANSION_* node.  */
3132
  result = for_types
3133
     ? cxx_make_type (TYPE_PACK_EXPANSION)
3134
     : make_node (EXPR_PACK_EXPANSION);
3135
  SET_PACK_EXPANSION_PATTERN (result, arg);
3136
  if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3137
    {
3138
      /* Propagate type and const-expression information.  */
3139
      TREE_TYPE (result) = TREE_TYPE (arg);
3140
      TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3141
    }
3142
  else
3143
    /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3144
       they will rarely be compared to anything.  */
3145
    SET_TYPE_STRUCTURAL_EQUALITY (result);
3146
 
3147
  /* Determine which parameter packs will be expanded.  */
3148
  ppd.parameter_packs = &parameter_packs;
3149
  ppd.visited = pointer_set_create ();
3150
  cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3151
  pointer_set_destroy (ppd.visited);
3152
 
3153
  /* Make sure we found some parameter packs.  */
3154
  if (parameter_packs == NULL_TREE)
3155
    {
3156
      if (TYPE_P (arg))
3157
        error ("expansion pattern %<%T%> contains no argument packs", arg);
3158
      else
3159
        error ("expansion pattern %<%E%> contains no argument packs", arg);
3160
      return error_mark_node;
3161
    }
3162
  PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3163
 
3164
  return result;
3165
}
3166
 
3167
/* Checks T for any "bare" parameter packs, which have not yet been
3168
   expanded, and issues an error if any are found. This operation can
3169
   only be done on full expressions or types (e.g., an expression
3170
   statement, "if" condition, etc.), because we could have expressions like:
3171
 
3172
     foo(f(g(h(args)))...)
3173
 
3174
   where "args" is a parameter pack. check_for_bare_parameter_packs
3175
   should not be called for the subexpressions args, h(args),
3176
   g(h(args)), or f(g(h(args))), because we would produce erroneous
3177
   error messages.
3178
 
3179
   Returns TRUE and emits an error if there were bare parameter packs,
3180
   returns FALSE otherwise.  */
3181
bool
3182
check_for_bare_parameter_packs (tree t)
3183
{
3184
  tree parameter_packs = NULL_TREE;
3185
  struct find_parameter_pack_data ppd;
3186
 
3187
  if (!processing_template_decl || !t || t == error_mark_node)
3188
    return false;
3189
 
3190
  if (TREE_CODE (t) == TYPE_DECL)
3191
    t = TREE_TYPE (t);
3192
 
3193
  ppd.parameter_packs = &parameter_packs;
3194
  ppd.visited = pointer_set_create ();
3195
  cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3196
  pointer_set_destroy (ppd.visited);
3197
 
3198
  if (parameter_packs)
3199
    {
3200
      error ("parameter packs not expanded with %<...%>:");
3201
      while (parameter_packs)
3202
        {
3203
          tree pack = TREE_VALUE (parameter_packs);
3204
          tree name = NULL_TREE;
3205
 
3206
          if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3207
              || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3208
            name = TYPE_NAME (pack);
3209
          else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3210
            name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3211
          else
3212
            name = DECL_NAME (pack);
3213
 
3214
          if (name)
3215
            inform (input_location, "        %qD", name);
3216
          else
3217
            inform (input_location, "        <anonymous>");
3218
 
3219
          parameter_packs = TREE_CHAIN (parameter_packs);
3220
        }
3221
 
3222
      return true;
3223
    }
3224
 
3225
  return false;
3226
}
3227
 
3228
/* Expand any parameter packs that occur in the template arguments in
3229
   ARGS.  */
3230
tree
3231
expand_template_argument_pack (tree args)
3232
{
3233
  tree result_args = NULL_TREE;
3234
  int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3235
  int num_result_args = -1;
3236
  int non_default_args_count = -1;
3237
 
3238
  /* First, determine if we need to expand anything, and the number of
3239
     slots we'll need.  */
3240
  for (in_arg = 0; in_arg < nargs; ++in_arg)
3241
    {
3242
      tree arg = TREE_VEC_ELT (args, in_arg);
3243
      if (arg == NULL_TREE)
3244
        return args;
3245
      if (ARGUMENT_PACK_P (arg))
3246
        {
3247
          int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3248
          if (num_result_args < 0)
3249
            num_result_args = in_arg + num_packed;
3250
          else
3251
            num_result_args += num_packed;
3252
        }
3253
      else
3254
        {
3255
          if (num_result_args >= 0)
3256
            num_result_args++;
3257
        }
3258
    }
3259
 
3260
  /* If no expansion is necessary, we're done.  */
3261
  if (num_result_args < 0)
3262
    return args;
3263
 
3264
  /* Expand arguments.  */
3265
  result_args = make_tree_vec (num_result_args);
3266
  if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3267
    non_default_args_count =
3268
      GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3269
  for (in_arg = 0; in_arg < nargs; ++in_arg)
3270
    {
3271
      tree arg = TREE_VEC_ELT (args, in_arg);
3272
      if (ARGUMENT_PACK_P (arg))
3273
        {
3274
          tree packed = ARGUMENT_PACK_ARGS (arg);
3275
          int i, num_packed = TREE_VEC_LENGTH (packed);
3276
          for (i = 0; i < num_packed; ++i, ++out_arg)
3277
            TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3278
          if (non_default_args_count > 0)
3279
            non_default_args_count += num_packed;
3280
        }
3281
      else
3282
        {
3283
          TREE_VEC_ELT (result_args, out_arg) = arg;
3284
          ++out_arg;
3285
        }
3286
    }
3287
  if (non_default_args_count >= 0)
3288
    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3289
  return result_args;
3290
}
3291
 
3292
/* Checks if DECL shadows a template parameter.
3293
 
3294
   [temp.local]: A template-parameter shall not be redeclared within its
3295
   scope (including nested scopes).
3296
 
3297
   Emits an error and returns TRUE if the DECL shadows a parameter,
3298
   returns FALSE otherwise.  */
3299
 
3300
bool
3301
check_template_shadow (tree decl)
3302
{
3303
  tree olddecl;
3304
 
3305
  /* If we're not in a template, we can't possibly shadow a template
3306
     parameter.  */
3307
  if (!current_template_parms)
3308
    return true;
3309
 
3310
  /* Figure out what we're shadowing.  */
3311
  if (TREE_CODE (decl) == OVERLOAD)
3312
    decl = OVL_CURRENT (decl);
3313
  olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3314
 
3315
  /* If there's no previous binding for this name, we're not shadowing
3316
     anything, let alone a template parameter.  */
3317
  if (!olddecl)
3318
    return true;
3319
 
3320
  /* If we're not shadowing a template parameter, we're done.  Note
3321
     that OLDDECL might be an OVERLOAD (or perhaps even an
3322
     ERROR_MARK), so we can't just blithely assume it to be a _DECL
3323
     node.  */
3324
  if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3325
    return true;
3326
 
3327
  /* We check for decl != olddecl to avoid bogus errors for using a
3328
     name inside a class.  We check TPFI to avoid duplicate errors for
3329
     inline member templates.  */
3330
  if (decl == olddecl
3331
      || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3332
    return true;
3333
 
3334
  error ("declaration of %q+#D", decl);
3335
  error (" shadows template parm %q+#D", olddecl);
3336
  return false;
3337
}
3338
 
3339
/* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3340
   ORIG_LEVEL, DECL, and TYPE.  */
3341
 
3342
static tree
3343
build_template_parm_index (int index,
3344
                           int level,
3345
                           int orig_level,
3346
                           tree decl,
3347
                           tree type)
3348
{
3349
  tree t = make_node (TEMPLATE_PARM_INDEX);
3350
  TEMPLATE_PARM_IDX (t) = index;
3351
  TEMPLATE_PARM_LEVEL (t) = level;
3352
  TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3353
  TEMPLATE_PARM_DECL (t) = decl;
3354
  TREE_TYPE (t) = type;
3355
  TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3356
  TREE_READONLY (t) = TREE_READONLY (decl);
3357
 
3358
  return t;
3359
}
3360
 
3361
/* Find the canonical type parameter for the given template type
3362
   parameter.  Returns the canonical type parameter, which may be TYPE
3363
   if no such parameter existed.  */
3364
static tree
3365
canonical_type_parameter (tree type)
3366
{
3367
  tree list;
3368
  int idx = TEMPLATE_TYPE_IDX (type);
3369
  if (!canonical_template_parms)
3370
    canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3371
 
3372
  while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3373
    VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3374
 
3375
  list = VEC_index (tree, canonical_template_parms, idx);
3376
  while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3377
    list = TREE_CHAIN (list);
3378
 
3379
  if (list)
3380
    return TREE_VALUE (list);
3381
  else
3382
    {
3383
      VEC_replace(tree, canonical_template_parms, idx,
3384
                  tree_cons (NULL_TREE, type,
3385
                             VEC_index (tree, canonical_template_parms, idx)));
3386
      return type;
3387
    }
3388
}
3389
 
3390
/* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3391
   TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3392
   TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3393
   new one is created.  */
3394
 
3395
static tree
3396
reduce_template_parm_level (tree index, tree type, int levels, tree args,
3397
                            tsubst_flags_t complain)
3398
{
3399
  if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3400
      || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3401
          != TEMPLATE_PARM_LEVEL (index) - levels)
3402
      || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3403
    {
3404
      tree orig_decl = TEMPLATE_PARM_DECL (index);
3405
      tree decl, t;
3406
 
3407
      decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3408
                         TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3409
      TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3410
      TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3411
      DECL_ARTIFICIAL (decl) = 1;
3412
      SET_DECL_TEMPLATE_PARM_P (decl);
3413
 
3414
      t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3415
                                     TEMPLATE_PARM_LEVEL (index) - levels,
3416
                                     TEMPLATE_PARM_ORIG_LEVEL (index),
3417
                                     decl, type);
3418
      TEMPLATE_PARM_DESCENDANTS (index) = t;
3419
      TEMPLATE_PARM_PARAMETER_PACK (t)
3420
        = TEMPLATE_PARM_PARAMETER_PACK (index);
3421
 
3422
        /* Template template parameters need this.  */
3423
      if (TREE_CODE (decl) == TEMPLATE_DECL)
3424
        DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3425
          (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3426
           args, complain);
3427
    }
3428
 
3429
  return TEMPLATE_PARM_DESCENDANTS (index);
3430
}
3431
 
3432
/* Process information from new template parameter PARM and append it to the
3433
   LIST being built.  This new parameter is a non-type parameter iff
3434
   IS_NON_TYPE is true. This new parameter is a parameter
3435
   pack iff IS_PARAMETER_PACK is true.  The location of PARM is in
3436
   PARM_LOC.  */
3437
 
3438
tree
3439
process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type,
3440
                       bool is_parameter_pack)
3441
{
3442
  tree decl = 0;
3443
  tree defval;
3444
  tree err_parm_list;
3445
  int idx = 0;
3446
 
3447
  gcc_assert (TREE_CODE (parm) == TREE_LIST);
3448
  defval = TREE_PURPOSE (parm);
3449
 
3450
  if (list)
3451
    {
3452
      tree p = tree_last (list);
3453
 
3454
      if (p && TREE_VALUE (p) != error_mark_node)
3455
        {
3456
          p = TREE_VALUE (p);
3457
          if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3458
            idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3459
          else
3460
            idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3461
        }
3462
 
3463
      ++idx;
3464
    }
3465
  else
3466
    idx = 0;
3467
 
3468
  if (is_non_type)
3469
    {
3470
      parm = TREE_VALUE (parm);
3471
 
3472
      SET_DECL_TEMPLATE_PARM_P (parm);
3473
 
3474
      if (TREE_TYPE (parm) == error_mark_node)
3475
        {
3476
          err_parm_list = build_tree_list (defval, parm);
3477
          TREE_VALUE (err_parm_list) = error_mark_node;
3478
           return chainon (list, err_parm_list);
3479
        }
3480
      else
3481
      {
3482
        /* [temp.param]
3483
 
3484
           The top-level cv-qualifiers on the template-parameter are
3485
           ignored when determining its type.  */
3486
        TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3487
        if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3488
          {
3489
            err_parm_list = build_tree_list (defval, parm);
3490
            TREE_VALUE (err_parm_list) = error_mark_node;
3491
             return chainon (list, err_parm_list);
3492
          }
3493
 
3494
        if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3495
          {
3496
            /* This template parameter is not a parameter pack, but it
3497
               should be. Complain about "bare" parameter packs.  */
3498
            check_for_bare_parameter_packs (TREE_TYPE (parm));
3499
 
3500
            /* Recover by calling this a parameter pack.  */
3501
            is_parameter_pack = true;
3502
          }
3503
      }
3504
 
3505
      /* A template parameter is not modifiable.  */
3506
      TREE_CONSTANT (parm) = 1;
3507
      TREE_READONLY (parm) = 1;
3508
      decl = build_decl (parm_loc,
3509
                         CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3510
      TREE_CONSTANT (decl) = 1;
3511
      TREE_READONLY (decl) = 1;
3512
      DECL_INITIAL (parm) = DECL_INITIAL (decl)
3513
        = build_template_parm_index (idx, processing_template_decl,
3514
                                     processing_template_decl,
3515
                                     decl, TREE_TYPE (parm));
3516
 
3517
      TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
3518
        = is_parameter_pack;
3519
    }
3520
  else
3521
    {
3522
      tree t;
3523
      parm = TREE_VALUE (TREE_VALUE (parm));
3524
 
3525
      if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3526
        {
3527
          t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3528
          /* This is for distinguishing between real templates and template
3529
             template parameters */
3530
          TREE_TYPE (parm) = t;
3531
          TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3532
          decl = parm;
3533
        }
3534
      else
3535
        {
3536
          t = cxx_make_type (TEMPLATE_TYPE_PARM);
3537
          /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3538
          decl = build_decl (parm_loc,
3539
                             TYPE_DECL, parm, t);
3540
        }
3541
 
3542
      TYPE_NAME (t) = decl;
3543
      TYPE_STUB_DECL (t) = decl;
3544
      parm = decl;
3545
      TEMPLATE_TYPE_PARM_INDEX (t)
3546
        = build_template_parm_index (idx, processing_template_decl,
3547
                                     processing_template_decl,
3548
                                     decl, TREE_TYPE (parm));
3549
      TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3550
      TYPE_CANONICAL (t) = canonical_type_parameter (t);
3551
    }
3552
  DECL_ARTIFICIAL (decl) = 1;
3553
  SET_DECL_TEMPLATE_PARM_P (decl);
3554
  pushdecl (decl);
3555
  parm = build_tree_list (defval, parm);
3556
  return chainon (list, parm);
3557
}
3558
 
3559
/* The end of a template parameter list has been reached.  Process the
3560
   tree list into a parameter vector, converting each parameter into a more
3561
   useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3562
   as PARM_DECLs.  */
3563
 
3564
tree
3565
end_template_parm_list (tree parms)
3566
{
3567
  int nparms;
3568
  tree parm, next;
3569
  tree saved_parmlist = make_tree_vec (list_length (parms));
3570
 
3571
  current_template_parms
3572
    = tree_cons (size_int (processing_template_decl),
3573
                 saved_parmlist, current_template_parms);
3574
 
3575
  for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3576
    {
3577
      next = TREE_CHAIN (parm);
3578
      TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3579
      TREE_CHAIN (parm) = NULL_TREE;
3580
      if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3581
        TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3582
              current_template_parms;
3583
    }
3584
 
3585
  --processing_template_parmlist;
3586
 
3587
  return saved_parmlist;
3588
}
3589
 
3590
/* end_template_decl is called after a template declaration is seen.  */
3591
 
3592
void
3593
end_template_decl (void)
3594
{
3595
  reset_specialization ();
3596
 
3597
  if (! processing_template_decl)
3598
    return;
3599
 
3600
  /* This matches the pushlevel in begin_template_parm_list.  */
3601
  finish_scope ();
3602
 
3603
  --processing_template_decl;
3604
  current_template_parms = TREE_CHAIN (current_template_parms);
3605
}
3606
 
3607
/* Within the declaration of a template, return all levels of template
3608
   parameters that apply.  The template parameters are represented as
3609
   a TREE_VEC, in the form documented in cp-tree.h for template
3610
   arguments.  */
3611
 
3612
static tree
3613
current_template_args (void)
3614
{
3615
  tree header;
3616
  tree args = NULL_TREE;
3617
  int length = TMPL_PARMS_DEPTH (current_template_parms);
3618
  int l = length;
3619
 
3620
  /* If there is only one level of template parameters, we do not
3621
     create a TREE_VEC of TREE_VECs.  Instead, we return a single
3622
     TREE_VEC containing the arguments.  */
3623
  if (length > 1)
3624
    args = make_tree_vec (length);
3625
 
3626
  for (header = current_template_parms; header; header = TREE_CHAIN (header))
3627
    {
3628
      tree a = copy_node (TREE_VALUE (header));
3629
      int i;
3630
 
3631
      TREE_TYPE (a) = NULL_TREE;
3632
      for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3633
        {
3634
          tree t = TREE_VEC_ELT (a, i);
3635
 
3636
          /* T will be a list if we are called from within a
3637
             begin/end_template_parm_list pair, but a vector directly
3638
             if within a begin/end_member_template_processing pair.  */
3639
          if (TREE_CODE (t) == TREE_LIST)
3640
            {
3641
              t = TREE_VALUE (t);
3642
 
3643
              if (!error_operand_p (t))
3644
                {
3645
                  if (TREE_CODE (t) == TYPE_DECL
3646
                      || TREE_CODE (t) == TEMPLATE_DECL)
3647
                    {
3648
                      t = TREE_TYPE (t);
3649
 
3650
                      if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3651
                        {
3652
                          /* Turn this argument into a TYPE_ARGUMENT_PACK
3653
                             with a single element, which expands T.  */
3654
                          tree vec = make_tree_vec (1);
3655
#ifdef ENABLE_CHECKING
3656
                          SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3657
                                (vec, TREE_VEC_LENGTH (vec));
3658
#endif
3659
                          TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3660
 
3661
                          t = cxx_make_type (TYPE_ARGUMENT_PACK);
3662
                          SET_ARGUMENT_PACK_ARGS (t, vec);
3663
                        }
3664
                    }
3665
                  else
3666
                    {
3667
                      t = DECL_INITIAL (t);
3668
 
3669
                      if (TEMPLATE_PARM_PARAMETER_PACK (t))
3670
                        {
3671
                          /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3672
                             with a single element, which expands T.  */
3673
                          tree vec = make_tree_vec (1);
3674
                          tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3675
#ifdef ENABLE_CHECKING
3676
                          SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3677
                                (vec, TREE_VEC_LENGTH (vec));
3678
#endif
3679
                          TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3680
 
3681
                          t  = make_node (NONTYPE_ARGUMENT_PACK);
3682
                          SET_ARGUMENT_PACK_ARGS (t, vec);
3683
                          TREE_TYPE (t) = type;
3684
                        }
3685
                    }
3686
                  TREE_VEC_ELT (a, i) = t;
3687
                }
3688
            }
3689
        }
3690
 
3691
#ifdef ENABLE_CHECKING
3692
      SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3693
#endif
3694
 
3695
      if (length > 1)
3696
        TREE_VEC_ELT (args, --l) = a;
3697
      else
3698
        args = a;
3699
    }
3700
 
3701
  return args;
3702
}
3703
 
3704
/* Update the declared TYPE by doing any lookups which were thought to be
3705
   dependent, but are not now that we know the SCOPE of the declarator.  */
3706
 
3707
tree
3708
maybe_update_decl_type (tree orig_type, tree scope)
3709
{
3710
  tree type = orig_type;
3711
 
3712
  if (type == NULL_TREE)
3713
    return type;
3714
 
3715
  if (TREE_CODE (orig_type) == TYPE_DECL)
3716
    type = TREE_TYPE (type);
3717
 
3718
  if (scope && TYPE_P (scope) && dependent_type_p (scope)
3719
      && dependent_type_p (type)
3720
      /* Don't bother building up the args in this case.  */
3721
      && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3722
    {
3723
      /* tsubst in the args corresponding to the template parameters,
3724
         including auto if present.  Most things will be unchanged, but
3725
         make_typename_type and tsubst_qualified_id will resolve
3726
         TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3727
      tree args = current_template_args ();
3728
      tree auto_node = type_uses_auto (type);
3729
      tree pushed;
3730
      if (auto_node)
3731
        {
3732
          tree auto_vec = make_tree_vec (1);
3733
          TREE_VEC_ELT (auto_vec, 0) = auto_node;
3734
          args = add_to_template_args (args, auto_vec);
3735
        }
3736
      pushed = push_scope (scope);
3737
      type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3738
      if (pushed)
3739
        pop_scope (scope);
3740
    }
3741
 
3742
  if (type == error_mark_node)
3743
    return orig_type;
3744
 
3745
  if (TREE_CODE (orig_type) == TYPE_DECL)
3746
    {
3747
      if (same_type_p (type, TREE_TYPE (orig_type)))
3748
        type = orig_type;
3749
      else
3750
        type = TYPE_NAME (type);
3751
    }
3752
  return type;
3753
}
3754
 
3755
/* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3756
   template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3757
   a member template.  Used by push_template_decl below.  */
3758
 
3759
static tree
3760
build_template_decl (tree decl, tree parms, bool member_template_p)
3761
{
3762
  tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3763
  DECL_TEMPLATE_PARMS (tmpl) = parms;
3764
  DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3765
  DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3766
 
3767
  return tmpl;
3768
}
3769
 
3770
struct template_parm_data
3771
{
3772
  /* The level of the template parameters we are currently
3773
     processing.  */
3774
  int level;
3775
 
3776
  /* The index of the specialization argument we are currently
3777
     processing.  */
3778
  int current_arg;
3779
 
3780
  /* An array whose size is the number of template parameters.  The
3781
     elements are nonzero if the parameter has been used in any one
3782
     of the arguments processed so far.  */
3783
  int* parms;
3784
 
3785
  /* An array whose size is the number of template arguments.  The
3786
     elements are nonzero if the argument makes use of template
3787
     parameters of this level.  */
3788
  int* arg_uses_template_parms;
3789
};
3790
 
3791
/* Subroutine of push_template_decl used to see if each template
3792
   parameter in a partial specialization is used in the explicit
3793
   argument list.  If T is of the LEVEL given in DATA (which is
3794
   treated as a template_parm_data*), then DATA->PARMS is marked
3795
   appropriately.  */
3796
 
3797
static int
3798
mark_template_parm (tree t, void* data)
3799
{
3800
  int level;
3801
  int idx;
3802
  struct template_parm_data* tpd = (struct template_parm_data*) data;
3803
 
3804
  if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3805
    {
3806
      level = TEMPLATE_PARM_LEVEL (t);
3807
      idx = TEMPLATE_PARM_IDX (t);
3808
    }
3809
  else
3810
    {
3811
      level = TEMPLATE_TYPE_LEVEL (t);
3812
      idx = TEMPLATE_TYPE_IDX (t);
3813
    }
3814
 
3815
  if (level == tpd->level)
3816
    {
3817
      tpd->parms[idx] = 1;
3818
      tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3819
    }
3820
 
3821
  /* Return zero so that for_each_template_parm will continue the
3822
     traversal of the tree; we want to mark *every* template parm.  */
3823
  return 0;
3824
}
3825
 
3826
/* Process the partial specialization DECL.  */
3827
 
3828
static tree
3829
process_partial_specialization (tree decl)
3830
{
3831
  tree type = TREE_TYPE (decl);
3832
  tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3833
  tree specargs = CLASSTYPE_TI_ARGS (type);
3834
  tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3835
  tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3836
  tree inner_parms;
3837
  int nargs = TREE_VEC_LENGTH (inner_args);
3838
  int ntparms;
3839
  int  i;
3840
  int did_error_intro = 0;
3841
  struct template_parm_data tpd;
3842
  struct template_parm_data tpd2;
3843
 
3844
  gcc_assert (current_template_parms);
3845
 
3846
  inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3847
  ntparms = TREE_VEC_LENGTH (inner_parms);
3848
 
3849
  /* We check that each of the template parameters given in the
3850
     partial specialization is used in the argument list to the
3851
     specialization.  For example:
3852
 
3853
       template <class T> struct S;
3854
       template <class T> struct S<T*>;
3855
 
3856
     The second declaration is OK because `T*' uses the template
3857
     parameter T, whereas
3858
 
3859
       template <class T> struct S<int>;
3860
 
3861
     is no good.  Even trickier is:
3862
 
3863
       template <class T>
3864
       struct S1
3865
       {
3866
          template <class U>
3867
          struct S2;
3868
          template <class U>
3869
          struct S2<T>;
3870
       };
3871
 
3872
     The S2<T> declaration is actually invalid; it is a
3873
     full-specialization.  Of course,
3874
 
3875
          template <class U>
3876
          struct S2<T (*)(U)>;
3877
 
3878
     or some such would have been OK.  */
3879
  tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3880
  tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3881
  memset (tpd.parms, 0, sizeof (int) * ntparms);
3882
 
3883
  tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3884
  memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3885
  for (i = 0; i < nargs; ++i)
3886
    {
3887
      tpd.current_arg = i;
3888
      for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3889
                              &mark_template_parm,
3890
                              &tpd,
3891
                              NULL,
3892
                              /*include_nondeduced_p=*/false);
3893
    }
3894
  for (i = 0; i < ntparms; ++i)
3895
    if (tpd.parms[i] == 0)
3896
      {
3897
        /* One of the template parms was not used in the
3898
           specialization.  */
3899
        if (!did_error_intro)
3900
          {
3901
            error ("template parameters not used in partial specialization:");
3902
            did_error_intro = 1;
3903
          }
3904
 
3905
        error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3906
      }
3907
 
3908
  /* [temp.class.spec]
3909
 
3910
     The argument list of the specialization shall not be identical to
3911
     the implicit argument list of the primary template.  */
3912
  if (comp_template_args
3913
      (inner_args,
3914
       INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3915
                                                   (maintmpl)))))
3916
    error ("partial specialization %qT does not specialize any template arguments", type);
3917
 
3918
  /* [temp.class.spec]
3919
 
3920
     A partially specialized non-type argument expression shall not
3921
     involve template parameters of the partial specialization except
3922
     when the argument expression is a simple identifier.
3923
 
3924
     The type of a template parameter corresponding to a specialized
3925
     non-type argument shall not be dependent on a parameter of the
3926
     specialization.
3927
 
3928
     Also, we verify that pack expansions only occur at the
3929
     end of the argument list.  */
3930
  gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3931
  tpd2.parms = 0;
3932
  for (i = 0; i < nargs; ++i)
3933
    {
3934
      tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3935
      tree arg = TREE_VEC_ELT (inner_args, i);
3936
      tree packed_args = NULL_TREE;
3937
      int j, len = 1;
3938
 
3939
      if (ARGUMENT_PACK_P (arg))
3940
        {
3941
          /* Extract the arguments from the argument pack. We'll be
3942
             iterating over these in the following loop.  */
3943
          packed_args = ARGUMENT_PACK_ARGS (arg);
3944
          len = TREE_VEC_LENGTH (packed_args);
3945
        }
3946
 
3947
      for (j = 0; j < len; j++)
3948
        {
3949
          if (packed_args)
3950
            /* Get the Jth argument in the parameter pack.  */
3951
            arg = TREE_VEC_ELT (packed_args, j);
3952
 
3953
          if (PACK_EXPANSION_P (arg))
3954
            {
3955
              /* Pack expansions must come at the end of the
3956
                 argument list.  */
3957
              if ((packed_args && j < len - 1)
3958
                  || (!packed_args && i < nargs - 1))
3959
                {
3960
                  if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3961
                    error ("parameter pack argument %qE must be at the "
3962
                           "end of the template argument list", arg);
3963
                  else
3964
                    error ("parameter pack argument %qT must be at the "
3965
                           "end of the template argument list", arg);
3966
                }
3967
            }
3968
 
3969
          if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3970
            /* We only care about the pattern.  */
3971
            arg = PACK_EXPANSION_PATTERN (arg);
3972
 
3973
          if (/* These first two lines are the `non-type' bit.  */
3974
              !TYPE_P (arg)
3975
              && TREE_CODE (arg) != TEMPLATE_DECL
3976
              /* This next line is the `argument expression is not just a
3977
                 simple identifier' condition and also the `specialized
3978
                 non-type argument' bit.  */
3979
              && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3980
            {
3981
              if ((!packed_args && tpd.arg_uses_template_parms[i])
3982
                  || (packed_args && uses_template_parms (arg)))
3983
                error ("template argument %qE involves template parameter(s)",
3984
                       arg);
3985
              else
3986
                {
3987
                  /* Look at the corresponding template parameter,
3988
                     marking which template parameters its type depends
3989
                     upon.  */
3990
                  tree type = TREE_TYPE (parm);
3991
 
3992
                  if (!tpd2.parms)
3993
                    {
3994
                      /* We haven't yet initialized TPD2.  Do so now.  */
3995
                      tpd2.arg_uses_template_parms
3996
                        = (int *) alloca (sizeof (int) * nargs);
3997
                      /* The number of parameters here is the number in the
3998
                         main template, which, as checked in the assertion
3999
                         above, is NARGS.  */
4000
                      tpd2.parms = (int *) alloca (sizeof (int) * nargs);
4001
                      tpd2.level =
4002
                        TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4003
                    }
4004
 
4005
                  /* Mark the template parameters.  But this time, we're
4006
                     looking for the template parameters of the main
4007
                     template, not in the specialization.  */
4008
                  tpd2.current_arg = i;
4009
                  tpd2.arg_uses_template_parms[i] = 0;
4010
                  memset (tpd2.parms, 0, sizeof (int) * nargs);
4011
                  for_each_template_parm (type,
4012
                                          &mark_template_parm,
4013
                                          &tpd2,
4014
                                          NULL,
4015
                                          /*include_nondeduced_p=*/false);
4016
 
4017
                  if (tpd2.arg_uses_template_parms [i])
4018
                    {
4019
                      /* The type depended on some template parameters.
4020
                         If they are fully specialized in the
4021
                         specialization, that's OK.  */
4022
                      int j;
4023
                      int count = 0;
4024
                      for (j = 0; j < nargs; ++j)
4025
                        if (tpd2.parms[j] != 0
4026
                            && tpd.arg_uses_template_parms [j])
4027
                          ++count;
4028
                      if (count != 0)
4029
                        error_n (input_location, count,
4030
                                 "type %qT of template argument %qE depends "
4031
                                 "on a template parameter",
4032
                                 "type %qT of template argument %qE depends "
4033
                                 "on template parameters",
4034
                                 type,
4035
                                 arg);
4036
                    }
4037
                }
4038
            }
4039
        }
4040
    }
4041
 
4042
  /* We should only get here once.  */
4043
  gcc_assert (!COMPLETE_TYPE_P (type));
4044
 
4045
  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4046
    = tree_cons (specargs, inner_parms,
4047
                 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4048
  TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4049
  return decl;
4050
}
4051
 
4052
/* Check that a template declaration's use of default arguments and
4053
   parameter packs is not invalid.  Here, PARMS are the template
4054
   parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4055
   a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4056
   specialization.
4057
 
4058
 
4059
   IS_FRIEND_DECL is nonzero if DECL is a friend function template
4060
   declaration (but not a definition); 1 indicates a declaration, 2
4061
   indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4062
   emitted for extraneous default arguments.
4063
 
4064
   Returns TRUE if there were no errors found, FALSE otherwise. */
4065
 
4066
bool
4067
check_default_tmpl_args (tree decl, tree parms, int is_primary,
4068
                         int is_partial, int is_friend_decl)
4069
{
4070
  const char *msg;
4071
  int last_level_to_check;
4072
  tree parm_level;
4073
  bool no_errors = true;
4074
 
4075
  /* [temp.param]
4076
 
4077
     A default template-argument shall not be specified in a
4078
     function template declaration or a function template definition, nor
4079
     in the template-parameter-list of the definition of a member of a
4080
     class template.  */
4081
 
4082
  if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4083
    /* You can't have a function template declaration in a local
4084
       scope, nor you can you define a member of a class template in a
4085
       local scope.  */
4086
    return true;
4087
 
4088
  if (current_class_type
4089
      && !TYPE_BEING_DEFINED (current_class_type)
4090
      && DECL_LANG_SPECIFIC (decl)
4091
      && DECL_DECLARES_FUNCTION_P (decl)
4092
      /* If this is either a friend defined in the scope of the class
4093
         or a member function.  */
4094
      && (DECL_FUNCTION_MEMBER_P (decl)
4095
          ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4096
          : DECL_FRIEND_CONTEXT (decl)
4097
          ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4098
          : false)
4099
      /* And, if it was a member function, it really was defined in
4100
         the scope of the class.  */
4101
      && (!DECL_FUNCTION_MEMBER_P (decl)
4102
          || DECL_INITIALIZED_IN_CLASS_P (decl)))
4103
    /* We already checked these parameters when the template was
4104
       declared, so there's no need to do it again now.  This function
4105
       was defined in class scope, but we're processing it's body now
4106
       that the class is complete.  */
4107
    return true;
4108
 
4109
  /* Core issue 226 (C++0x only): the following only applies to class
4110
     templates.  */
4111
  if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4112
    {
4113
      /* [temp.param]
4114
 
4115
         If a template-parameter has a default template-argument, all
4116
         subsequent template-parameters shall have a default
4117
         template-argument supplied.  */
4118
      for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4119
        {
4120
          tree inner_parms = TREE_VALUE (parm_level);
4121
          int ntparms = TREE_VEC_LENGTH (inner_parms);
4122
          int seen_def_arg_p = 0;
4123
          int i;
4124
 
4125
          for (i = 0; i < ntparms; ++i)
4126
            {
4127
              tree parm = TREE_VEC_ELT (inner_parms, i);
4128
 
4129
              if (parm == error_mark_node)
4130
                continue;
4131
 
4132
              if (TREE_PURPOSE (parm))
4133
                seen_def_arg_p = 1;
4134
              else if (seen_def_arg_p
4135
                       && !template_parameter_pack_p (TREE_VALUE (parm)))
4136
                {
4137
                  error ("no default argument for %qD", TREE_VALUE (parm));
4138
                  /* For better subsequent error-recovery, we indicate that
4139
                     there should have been a default argument.  */
4140
                  TREE_PURPOSE (parm) = error_mark_node;
4141
                  no_errors = false;
4142
                }
4143
              else if (is_primary
4144
                       && !is_partial
4145
                       && !is_friend_decl
4146
                       /* Don't complain about an enclosing partial
4147
                          specialization.  */
4148
                       && parm_level == parms
4149
                       && TREE_CODE (decl) == TYPE_DECL
4150
                       && i < ntparms - 1
4151
                       && template_parameter_pack_p (TREE_VALUE (parm)))
4152
                {
4153
                  /* A primary class template can only have one
4154
                     parameter pack, at the end of the template
4155
                     parameter list.  */
4156
 
4157
                  if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4158
                    error ("parameter pack %qE must be at the end of the"
4159
                           " template parameter list", TREE_VALUE (parm));
4160
                  else
4161
                    error ("parameter pack %qT must be at the end of the"
4162
                           " template parameter list",
4163
                           TREE_TYPE (TREE_VALUE (parm)));
4164
 
4165
                  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
4166
                    = error_mark_node;
4167
                  no_errors = false;
4168
                }
4169
            }
4170
        }
4171
    }
4172
 
4173
  if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4174
      || is_partial
4175
      || !is_primary
4176
      || is_friend_decl)
4177
    /* For an ordinary class template, default template arguments are
4178
       allowed at the innermost level, e.g.:
4179
         template <class T = int>
4180
         struct S {};
4181
       but, in a partial specialization, they're not allowed even
4182
       there, as we have in [temp.class.spec]:
4183
 
4184
         The template parameter list of a specialization shall not
4185
         contain default template argument values.
4186
 
4187
       So, for a partial specialization, or for a function template
4188
       (in C++98/C++03), we look at all of them.  */
4189
    ;
4190
  else
4191
    /* But, for a primary class template that is not a partial
4192
       specialization we look at all template parameters except the
4193
       innermost ones.  */
4194
    parms = TREE_CHAIN (parms);
4195
 
4196
  /* Figure out what error message to issue.  */
4197
  if (is_friend_decl == 2)
4198
    msg = G_("default template arguments may not be used in function template "
4199
             "friend re-declaration");
4200
  else if (is_friend_decl)
4201
    msg = G_("default template arguments may not be used in function template "
4202
             "friend declarations");
4203
  else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4204
    msg = G_("default template arguments may not be used in function templates "
4205
             "without -std=c++0x or -std=gnu++0x");
4206
  else if (is_partial)
4207
    msg = G_("default template arguments may not be used in "
4208
             "partial specializations");
4209
  else
4210
    msg = G_("default argument for template parameter for class enclosing %qD");
4211
 
4212
  if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4213
    /* If we're inside a class definition, there's no need to
4214
       examine the parameters to the class itself.  On the one
4215
       hand, they will be checked when the class is defined, and,
4216
       on the other, default arguments are valid in things like:
4217
         template <class T = double>
4218
         struct S { template <class U> void f(U); };
4219
       Here the default argument for `S' has no bearing on the
4220
       declaration of `f'.  */
4221
    last_level_to_check = template_class_depth (current_class_type) + 1;
4222
  else
4223
    /* Check everything.  */
4224
    last_level_to_check = 0;
4225
 
4226
  for (parm_level = parms;
4227
       parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4228
       parm_level = TREE_CHAIN (parm_level))
4229
    {
4230
      tree inner_parms = TREE_VALUE (parm_level);
4231
      int i;
4232
      int ntparms;
4233
 
4234
      ntparms = TREE_VEC_LENGTH (inner_parms);
4235
      for (i = 0; i < ntparms; ++i)
4236
        {
4237
          if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4238
            continue;
4239
 
4240
          if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4241
            {
4242
              if (msg)
4243
                {
4244
                  no_errors = false;
4245
                  if (is_friend_decl == 2)
4246
                    return no_errors;
4247
 
4248
                  error (msg, decl);
4249
                  msg = 0;
4250
                }
4251
 
4252
              /* Clear out the default argument so that we are not
4253
                 confused later.  */
4254
              TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4255
            }
4256
        }
4257
 
4258
      /* At this point, if we're still interested in issuing messages,
4259
         they must apply to classes surrounding the object declared.  */
4260
      if (msg)
4261
        msg = G_("default argument for template parameter for class "
4262
                 "enclosing %qD");
4263
    }
4264
 
4265
  return no_errors;
4266
}
4267
 
4268
/* Worker for push_template_decl_real, called via
4269
   for_each_template_parm.  DATA is really an int, indicating the
4270
   level of the parameters we are interested in.  If T is a template
4271
   parameter of that level, return nonzero.  */
4272
 
4273
static int
4274
template_parm_this_level_p (tree t, void* data)
4275
{
4276
  int this_level = *(int *)data;
4277
  int level;
4278
 
4279
  if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4280
    level = TEMPLATE_PARM_LEVEL (t);
4281
  else
4282
    level = TEMPLATE_TYPE_LEVEL (t);
4283
  return level == this_level;
4284
}
4285
 
4286
/* Creates a TEMPLATE_DECL for the indicated DECL using the template
4287
   parameters given by current_template_args, or reuses a
4288
   previously existing one, if appropriate.  Returns the DECL, or an
4289
   equivalent one, if it is replaced via a call to duplicate_decls.
4290
 
4291
   If IS_FRIEND is true, DECL is a friend declaration.  */
4292
 
4293
tree
4294
push_template_decl_real (tree decl, bool is_friend)
4295
{
4296
  tree tmpl;
4297
  tree args;
4298
  tree info;
4299
  tree ctx;
4300
  int primary;
4301
  int is_partial;
4302
  int new_template_p = 0;
4303
  /* True if the template is a member template, in the sense of
4304
     [temp.mem].  */
4305
  bool member_template_p = false;
4306
 
4307
  if (decl == error_mark_node || !current_template_parms)
4308
    return error_mark_node;
4309
 
4310
  /* See if this is a partial specialization.  */
4311
  is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4312
                && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4313
                && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4314
 
4315
  if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4316
    is_friend = true;
4317
 
4318
  if (is_friend)
4319
    /* For a friend, we want the context of the friend function, not
4320
       the type of which it is a friend.  */
4321
    ctx = DECL_CONTEXT (decl);
4322
  else if (CP_DECL_CONTEXT (decl)
4323
           && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4324
    /* In the case of a virtual function, we want the class in which
4325
       it is defined.  */
4326
    ctx = CP_DECL_CONTEXT (decl);
4327
  else
4328
    /* Otherwise, if we're currently defining some class, the DECL
4329
       is assumed to be a member of the class.  */
4330
    ctx = current_scope ();
4331
 
4332
  if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4333
    ctx = NULL_TREE;
4334
 
4335
  if (!DECL_CONTEXT (decl))
4336
    DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4337
 
4338
  /* See if this is a primary template.  */
4339
  if (is_friend && ctx)
4340
    /* A friend template that specifies a class context, i.e.
4341
         template <typename T> friend void A<T>::f();
4342
       is not primary.  */
4343
    primary = 0;
4344
  else
4345
    primary = template_parm_scope_p ();
4346
 
4347
  if (primary)
4348
    {
4349
      if (DECL_CLASS_SCOPE_P (decl))
4350
        member_template_p = true;
4351
      if (TREE_CODE (decl) == TYPE_DECL
4352
          && ANON_AGGRNAME_P (DECL_NAME (decl)))
4353
        {
4354
          error ("template class without a name");
4355
          return error_mark_node;
4356
        }
4357
      else if (TREE_CODE (decl) == FUNCTION_DECL)
4358
        {
4359
          if (DECL_DESTRUCTOR_P (decl))
4360
            {
4361
              /* [temp.mem]
4362
 
4363
                 A destructor shall not be a member template.  */
4364
              error ("destructor %qD declared as member template", decl);
4365
              return error_mark_node;
4366
            }
4367
          if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4368
              && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4369
                  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4370
                  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4371
                  || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4372
                      == void_list_node)))
4373
            {
4374
              /* [basic.stc.dynamic.allocation]
4375
 
4376
                 An allocation function can be a function
4377
                 template. ... Template allocation functions shall
4378
                 have two or more parameters.  */
4379
              error ("invalid template declaration of %qD", decl);
4380
              return error_mark_node;
4381
            }
4382
        }
4383
      else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4384
               && CLASS_TYPE_P (TREE_TYPE (decl)))
4385
        /* OK */;
4386
      else
4387
        {
4388
          error ("template declaration of %q#D", decl);
4389
          return error_mark_node;
4390
        }
4391
    }
4392
 
4393
  /* Check to see that the rules regarding the use of default
4394
     arguments are not being violated.  */
4395
  check_default_tmpl_args (decl, current_template_parms,
4396
                           primary, is_partial, /*is_friend_decl=*/0);
4397
 
4398
  /* Ensure that there are no parameter packs in the type of this
4399
     declaration that have not been expanded.  */
4400
  if (TREE_CODE (decl) == FUNCTION_DECL)
4401
    {
4402
      /* Check each of the arguments individually to see if there are
4403
         any bare parameter packs.  */
4404
      tree type = TREE_TYPE (decl);
4405
      tree arg = DECL_ARGUMENTS (decl);
4406
      tree argtype = TYPE_ARG_TYPES (type);
4407
 
4408
      while (arg && argtype)
4409
        {
4410
          if (!FUNCTION_PARAMETER_PACK_P (arg)
4411
              && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4412
            {
4413
            /* This is a PARM_DECL that contains unexpanded parameter
4414
               packs. We have already complained about this in the
4415
               check_for_bare_parameter_packs call, so just replace
4416
               these types with ERROR_MARK_NODE.  */
4417
              TREE_TYPE (arg) = error_mark_node;
4418
              TREE_VALUE (argtype) = error_mark_node;
4419
            }
4420
 
4421
          arg = TREE_CHAIN (arg);
4422
          argtype = TREE_CHAIN (argtype);
4423
        }
4424
 
4425
      /* Check for bare parameter packs in the return type and the
4426
         exception specifiers.  */
4427
      if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4428
        /* Errors were already issued, set return type to int
4429
           as the frontend doesn't expect error_mark_node as
4430
           the return type.  */
4431
        TREE_TYPE (type) = integer_type_node;
4432
      if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4433
        TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4434
    }
4435
  else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4436
    {
4437
      TREE_TYPE (decl) = error_mark_node;
4438
      return error_mark_node;
4439
    }
4440
 
4441
  if (is_partial)
4442
    return process_partial_specialization (decl);
4443
 
4444
  args = current_template_args ();
4445
 
4446
  if (!ctx
4447
      || TREE_CODE (ctx) == FUNCTION_DECL
4448
      || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4449
      || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4450
    {
4451
      if (DECL_LANG_SPECIFIC (decl)
4452
          && DECL_TEMPLATE_INFO (decl)
4453
          && DECL_TI_TEMPLATE (decl))
4454
        tmpl = DECL_TI_TEMPLATE (decl);
4455
      /* If DECL is a TYPE_DECL for a class-template, then there won't
4456
         be DECL_LANG_SPECIFIC.  The information equivalent to
4457
         DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4458
      else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4459
               && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4460
               && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4461
        {
4462
          /* Since a template declaration already existed for this
4463
             class-type, we must be redeclaring it here.  Make sure
4464
             that the redeclaration is valid.  */
4465
          redeclare_class_template (TREE_TYPE (decl),
4466
                                    current_template_parms);
4467
          /* We don't need to create a new TEMPLATE_DECL; just use the
4468
             one we already had.  */
4469
          tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4470
        }
4471
      else
4472
        {
4473
          tmpl = build_template_decl (decl, current_template_parms,
4474
                                      member_template_p);
4475
          new_template_p = 1;
4476
 
4477
          if (DECL_LANG_SPECIFIC (decl)
4478
              && DECL_TEMPLATE_SPECIALIZATION (decl))
4479
            {
4480
              /* A specialization of a member template of a template
4481
                 class.  */
4482
              SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4483
              DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4484
              DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4485
            }
4486
        }
4487
    }
4488
  else
4489
    {
4490
      tree a, t, current, parms;
4491
      int i;
4492
      tree tinfo = get_template_info (decl);
4493
 
4494
      if (!tinfo)
4495
        {
4496
          error ("template definition of non-template %q#D", decl);
4497
          return error_mark_node;
4498
        }
4499
 
4500
      tmpl = TI_TEMPLATE (tinfo);
4501
 
4502
      if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4503
          && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4504
          && DECL_TEMPLATE_SPECIALIZATION (decl)
4505
          && DECL_MEMBER_TEMPLATE_P (tmpl))
4506
        {
4507
          tree new_tmpl;
4508
 
4509
          /* The declaration is a specialization of a member
4510
             template, declared outside the class.  Therefore, the
4511
             innermost template arguments will be NULL, so we
4512
             replace them with the arguments determined by the
4513
             earlier call to check_explicit_specialization.  */
4514
          args = DECL_TI_ARGS (decl);
4515
 
4516
          new_tmpl
4517
            = build_template_decl (decl, current_template_parms,
4518
                                   member_template_p);
4519
          DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4520
          TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4521
          DECL_TI_TEMPLATE (decl) = new_tmpl;
4522
          SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4523
          DECL_TEMPLATE_INFO (new_tmpl)
4524
            = build_template_info (tmpl, args);
4525
 
4526
          register_specialization (new_tmpl,
4527
                                   most_general_template (tmpl),
4528
                                   args,
4529
                                   is_friend, 0);
4530
          return decl;
4531
        }
4532
 
4533
      /* Make sure the template headers we got make sense.  */
4534
 
4535
      parms = DECL_TEMPLATE_PARMS (tmpl);
4536
      i = TMPL_PARMS_DEPTH (parms);
4537
      if (TMPL_ARGS_DEPTH (args) != i)
4538
        {
4539
          error ("expected %d levels of template parms for %q#D, got %d",
4540
                 i, decl, TMPL_ARGS_DEPTH (args));
4541
        }
4542
      else
4543
        for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4544
          {
4545
            a = TMPL_ARGS_LEVEL (args, i);
4546
            t = INNERMOST_TEMPLATE_PARMS (parms);
4547
 
4548
            if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4549
              {
4550
                if (current == decl)
4551
                  error ("got %d template parameters for %q#D",
4552
                         TREE_VEC_LENGTH (a), decl);
4553
                else
4554
                  error ("got %d template parameters for %q#T",
4555
                         TREE_VEC_LENGTH (a), current);
4556
                error ("  but %d required", TREE_VEC_LENGTH (t));
4557
                return error_mark_node;
4558
              }
4559
 
4560
            if (current == decl)
4561
              current = ctx;
4562
            else if (current == NULL_TREE)
4563
              /* Can happen in erroneous input.  */
4564
              break;
4565
            else
4566
              current = (TYPE_P (current)
4567
                         ? TYPE_CONTEXT (current)
4568
                         : DECL_CONTEXT (current));
4569
          }
4570
 
4571
      /* Check that the parms are used in the appropriate qualifying scopes
4572
         in the declarator.  */
4573
      if (!comp_template_args
4574
          (TI_ARGS (tinfo),
4575
           TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4576
        {
4577
          error ("\
4578
template arguments to %qD do not match original template %qD",
4579
                 decl, DECL_TEMPLATE_RESULT (tmpl));
4580
          if (!uses_template_parms (TI_ARGS (tinfo)))
4581
            inform (input_location, "use template<> for an explicit specialization");
4582
          /* Avoid crash in import_export_decl.  */
4583
          DECL_INTERFACE_KNOWN (decl) = 1;
4584
          return error_mark_node;
4585
        }
4586
    }
4587
 
4588
  DECL_TEMPLATE_RESULT (tmpl) = decl;
4589
  TREE_TYPE (tmpl) = TREE_TYPE (decl);
4590
 
4591
  /* Push template declarations for global functions and types.  Note
4592
     that we do not try to push a global template friend declared in a
4593
     template class; such a thing may well depend on the template
4594
     parameters of the class.  */
4595
  if (new_template_p && !ctx
4596
      && !(is_friend && template_class_depth (current_class_type) > 0))
4597
    {
4598
      tmpl = pushdecl_namespace_level (tmpl, is_friend);
4599
      if (tmpl == error_mark_node)
4600
        return error_mark_node;
4601
 
4602
      /* Hide template friend classes that haven't been declared yet.  */
4603
      if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4604
        {
4605
          DECL_ANTICIPATED (tmpl) = 1;
4606
          DECL_FRIEND_P (tmpl) = 1;
4607
        }
4608
    }
4609
 
4610
  if (primary)
4611
    {
4612
      tree parms = DECL_TEMPLATE_PARMS (tmpl);
4613
      int i;
4614
 
4615
      DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4616
      if (DECL_CONV_FN_P (tmpl))
4617
        {
4618
          int depth = TMPL_PARMS_DEPTH (parms);
4619
 
4620
          /* It is a conversion operator. See if the type converted to
4621
             depends on innermost template operands.  */
4622
 
4623
          if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4624
                                         depth))
4625
            DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4626
        }
4627
 
4628
      /* Give template template parms a DECL_CONTEXT of the template
4629
         for which they are a parameter.  */
4630
      parms = INNERMOST_TEMPLATE_PARMS (parms);
4631
      for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4632
        {
4633
          tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4634
          if (TREE_CODE (parm) == TEMPLATE_DECL)
4635
            DECL_CONTEXT (parm) = tmpl;
4636
        }
4637
    }
4638
 
4639
  /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4640
     back to its most general template.  If TMPL is a specialization,
4641
     ARGS may only have the innermost set of arguments.  Add the missing
4642
     argument levels if necessary.  */
4643
  if (DECL_TEMPLATE_INFO (tmpl))
4644
    args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4645
 
4646
  info = build_template_info (tmpl, args);
4647
 
4648
  if (DECL_IMPLICIT_TYPEDEF_P (decl))
4649
    SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4650
  else if (DECL_LANG_SPECIFIC (decl))
4651
    DECL_TEMPLATE_INFO (decl) = info;
4652
 
4653
  return DECL_TEMPLATE_RESULT (tmpl);
4654
}
4655
 
4656
tree
4657
push_template_decl (tree decl)
4658
{
4659
  return push_template_decl_real (decl, false);
4660
}
4661
 
4662
/* Called when a class template TYPE is redeclared with the indicated
4663
   template PARMS, e.g.:
4664
 
4665
     template <class T> struct S;
4666
     template <class T> struct S {};  */
4667
 
4668
bool
4669
redeclare_class_template (tree type, tree parms)
4670
{
4671
  tree tmpl;
4672
  tree tmpl_parms;
4673
  int i;
4674
 
4675
  if (!TYPE_TEMPLATE_INFO (type))
4676
    {
4677
      error ("%qT is not a template type", type);
4678
      return false;
4679
    }
4680
 
4681
  tmpl = TYPE_TI_TEMPLATE (type);
4682
  if (!PRIMARY_TEMPLATE_P (tmpl))
4683
    /* The type is nested in some template class.  Nothing to worry
4684
       about here; there are no new template parameters for the nested
4685
       type.  */
4686
    return true;
4687
 
4688
  if (!parms)
4689
    {
4690
      error ("template specifiers not specified in declaration of %qD",
4691
             tmpl);
4692
      return false;
4693
    }
4694
 
4695
  parms = INNERMOST_TEMPLATE_PARMS (parms);
4696
  tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4697
 
4698
  if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4699
    {
4700
      error_n (input_location, TREE_VEC_LENGTH (parms),
4701
               "redeclared with %d template parameter",
4702
               "redeclared with %d template parameters",
4703
               TREE_VEC_LENGTH (parms));
4704
      inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4705
                "previous declaration %q+D used %d template parameter",
4706
                "previous declaration %q+D used %d template parameters",
4707
                tmpl, TREE_VEC_LENGTH (tmpl_parms));
4708
      return false;
4709
    }
4710
 
4711
  for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4712
    {
4713
      tree tmpl_parm;
4714
      tree parm;
4715
      tree tmpl_default;
4716
      tree parm_default;
4717
 
4718
      if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4719
          || TREE_VEC_ELT (parms, i) == error_mark_node)
4720
        continue;
4721
 
4722
      tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4723
      if (tmpl_parm == error_mark_node)
4724
        return false;
4725
 
4726
      parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4727
      tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4728
      parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4729
 
4730
      /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4731
         TEMPLATE_DECL.  */
4732
      if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4733
          || (TREE_CODE (tmpl_parm) != TYPE_DECL
4734
              && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4735
          || (TREE_CODE (tmpl_parm) != PARM_DECL
4736
              && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4737
                  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4738
          || (TREE_CODE (tmpl_parm) == PARM_DECL
4739
              && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4740
                  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4741
        {
4742
          error ("template parameter %q+#D", tmpl_parm);
4743
          error ("redeclared here as %q#D", parm);
4744
          return false;
4745
        }
4746
 
4747
      if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4748
        {
4749
          /* We have in [temp.param]:
4750
 
4751
             A template-parameter may not be given default arguments
4752
             by two different declarations in the same scope.  */
4753
          error_at (input_location, "redefinition of default argument for %q#D", parm);
4754
          inform (DECL_SOURCE_LOCATION (tmpl_parm),
4755
                  "original definition appeared here");
4756
          return false;
4757
        }
4758
 
4759
      if (parm_default != NULL_TREE)
4760
        /* Update the previous template parameters (which are the ones
4761
           that will really count) with the new default value.  */
4762
        TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4763
      else if (tmpl_default != NULL_TREE)
4764
        /* Update the new parameters, too; they'll be used as the
4765
           parameters for any members.  */
4766
        TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4767
    }
4768
 
4769
    return true;
4770
}
4771
 
4772
/* Simplify EXPR if it is a non-dependent expression.  Returns the
4773
   (possibly simplified) expression.  */
4774
 
4775
tree
4776
fold_non_dependent_expr (tree expr)
4777
{
4778
  if (expr == NULL_TREE)
4779
    return NULL_TREE;
4780
 
4781
  /* If we're in a template, but EXPR isn't value dependent, simplify
4782
     it.  We're supposed to treat:
4783
 
4784
       template <typename T> void f(T[1 + 1]);
4785
       template <typename T> void f(T[2]);
4786
 
4787
     as two declarations of the same function, for example.  */
4788
  if (processing_template_decl
4789
      && !type_dependent_expression_p (expr)
4790
      && !value_dependent_expression_p (expr))
4791
    {
4792
      HOST_WIDE_INT saved_processing_template_decl;
4793
 
4794
      saved_processing_template_decl = processing_template_decl;
4795
      processing_template_decl = 0;
4796
      expr = tsubst_copy_and_build (expr,
4797
                                    /*args=*/NULL_TREE,
4798
                                    tf_error,
4799
                                    /*in_decl=*/NULL_TREE,
4800
                                    /*function_p=*/false,
4801
                                    /*integral_constant_expression_p=*/true);
4802
      processing_template_decl = saved_processing_template_decl;
4803
    }
4804
  return expr;
4805
}
4806
 
4807
/* EXPR is an expression which is used in a constant-expression context.
4808
   For instance, it could be a VAR_DECL with a constant initializer.
4809
   Extract the innermost constant expression.
4810
 
4811
   This is basically a more powerful version of
4812
   integral_constant_value, which can be used also in templates where
4813
   initializers can maintain a syntactic rather than semantic form
4814
   (even if they are non-dependent, for access-checking purposes).  */
4815
 
4816
static tree
4817
fold_decl_constant_value (tree expr)
4818
{
4819
  tree const_expr = expr;
4820
  do
4821
    {
4822
      expr = fold_non_dependent_expr (const_expr);
4823
      const_expr = integral_constant_value (expr);
4824
    }
4825
  while (expr != const_expr);
4826
 
4827
  return expr;
4828
}
4829
 
4830
/* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4831
   must be a function or a pointer-to-function type, as specified
4832
   in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4833
   and check that the resulting function has external linkage.  */
4834
 
4835
static tree
4836
convert_nontype_argument_function (tree type, tree expr)
4837
{
4838
  tree fns = expr;
4839
  tree fn, fn_no_ptr;
4840
 
4841
  fn = instantiate_type (type, fns, tf_none);
4842
  if (fn == error_mark_node)
4843
    return error_mark_node;
4844
 
4845
  fn_no_ptr = fn;
4846
  if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4847
    fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4848
  if (TREE_CODE (fn_no_ptr) == BASELINK)
4849
    fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4850
 
4851
  /* [temp.arg.nontype]/1
4852
 
4853
     A template-argument for a non-type, non-template template-parameter
4854
     shall be one of:
4855
     [...]
4856
     -- the address of an object or function with external linkage.  */
4857
  if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4858
    {
4859
      error ("%qE is not a valid template argument for type %qT "
4860
             "because function %qD has not external linkage",
4861
             expr, type, fn_no_ptr);
4862
      return NULL_TREE;
4863
    }
4864
 
4865
  return fn;
4866
}
4867
 
4868
/* Subroutine of convert_nontype_argument.
4869
   Check if EXPR of type TYPE is a valid pointer-to-member constant.
4870
   Emit an error otherwise.  */
4871
 
4872
static bool
4873
check_valid_ptrmem_cst_expr (tree type, tree expr)
4874
{
4875
  STRIP_NOPS (expr);
4876
  if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4877
    return true;
4878
  error ("%qE is not a valid template argument for type %qT",
4879
         expr, type);
4880
  error ("it must be a pointer-to-member of the form `&X::Y'");
4881
  return false;
4882
}
4883
 
4884
/* Returns TRUE iff the address of OP is value-dependent.
4885
 
4886
   14.6.2.4 [temp.dep.temp]:
4887
   A non-integral non-type template-argument is dependent if its type is
4888
   dependent or it has either of the following forms
4889
     qualified-id
4890
     & qualified-id
4891
   and contains a nested-name-specifier which specifies a class-name that
4892
   names a dependent type.
4893
 
4894
   We generalize this to just say that the address of a member of a
4895
   dependent class is value-dependent; the above doesn't cover the
4896
   address of a static data member named with an unqualified-id.  */
4897
 
4898
static bool
4899
has_value_dependent_address (tree op)
4900
{
4901
  /* We could use get_inner_reference here, but there's no need;
4902
     this is only relevant for template non-type arguments, which
4903
     can only be expressed as &id-expression.  */
4904
  if (DECL_P (op))
4905
    {
4906
      tree ctx = CP_DECL_CONTEXT (op);
4907
      if (TYPE_P (ctx) && dependent_type_p (ctx))
4908
        return true;
4909
    }
4910
 
4911
  return false;
4912
}
4913
 
4914
/* Attempt to convert the non-type template parameter EXPR to the
4915
   indicated TYPE.  If the conversion is successful, return the
4916
   converted value.  If the conversion is unsuccessful, return
4917
   NULL_TREE if we issued an error message, or error_mark_node if we
4918
   did not.  We issue error messages for out-and-out bad template
4919
   parameters, but not simply because the conversion failed, since we
4920
   might be just trying to do argument deduction.  Both TYPE and EXPR
4921
   must be non-dependent.
4922
 
4923
   The conversion follows the special rules described in
4924
   [temp.arg.nontype], and it is much more strict than an implicit
4925
   conversion.
4926
 
4927
   This function is called twice for each template argument (see
4928
   lookup_template_class for a more accurate description of this
4929
   problem). This means that we need to handle expressions which
4930
   are not valid in a C++ source, but can be created from the
4931
   first call (for instance, casts to perform conversions). These
4932
   hacks can go away after we fix the double coercion problem.  */
4933
 
4934
static tree
4935
convert_nontype_argument (tree type, tree expr)
4936
{
4937
  tree expr_type;
4938
 
4939
  /* Detect immediately string literals as invalid non-type argument.
4940
     This special-case is not needed for correctness (we would easily
4941
     catch this later), but only to provide better diagnostic for this
4942
     common user mistake. As suggested by DR 100, we do not mention
4943
     linkage issues in the diagnostic as this is not the point.  */
4944
  if (TREE_CODE (expr) == STRING_CST)
4945
    {
4946
      error ("%qE is not a valid template argument for type %qT "
4947
             "because string literals can never be used in this context",
4948
             expr, type);
4949
      return NULL_TREE;
4950
    }
4951
 
4952
  /* Add the ADDR_EXPR now for the benefit of
4953
     value_dependent_expression_p.  */
4954
  if (TYPE_PTROBV_P (type))
4955
    expr = decay_conversion (expr);
4956
 
4957
  /* If we are in a template, EXPR may be non-dependent, but still
4958
     have a syntactic, rather than semantic, form.  For example, EXPR
4959
     might be a SCOPE_REF, rather than the VAR_DECL to which the
4960
     SCOPE_REF refers.  Preserving the qualifying scope is necessary
4961
     so that access checking can be performed when the template is
4962
     instantiated -- but here we need the resolved form so that we can
4963
     convert the argument.  */
4964
  if (TYPE_REF_OBJ_P (type)
4965
      && has_value_dependent_address (expr))
4966
    /* If we want the address and it's value-dependent, don't fold.  */;
4967
  else
4968
    expr = fold_non_dependent_expr (expr);
4969
  if (error_operand_p (expr))
4970
    return error_mark_node;
4971
  expr_type = TREE_TYPE (expr);
4972
 
4973
  /* HACK: Due to double coercion, we can get a
4974
     NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4975
     which is the tree that we built on the first call (see
4976
     below when coercing to reference to object or to reference to
4977
     function). We just strip everything and get to the arg.
4978
     See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4979
     for examples.  */
4980
  if (TREE_CODE (expr) == NOP_EXPR)
4981
    {
4982
      if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4983
        {
4984
          /* ??? Maybe we could use convert_from_reference here, but we
4985
             would need to relax its constraints because the NOP_EXPR
4986
             could actually change the type to something more cv-qualified,
4987
             and this is not folded by convert_from_reference.  */
4988
          tree addr = TREE_OPERAND (expr, 0);
4989
          gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4990
          gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4991
          gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4992
          gcc_assert (same_type_ignoring_top_level_qualifiers_p
4993
                      (TREE_TYPE (expr_type),
4994
                       TREE_TYPE (TREE_TYPE (addr))));
4995
 
4996
          expr = TREE_OPERAND (addr, 0);
4997
          expr_type = TREE_TYPE (expr);
4998
        }
4999
 
5000
      /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5001
         parameter is a pointer to object, through decay and
5002
         qualification conversion. Let's strip everything.  */
5003
      else if (TYPE_PTROBV_P (type))
5004
        {
5005
          STRIP_NOPS (expr);
5006
          gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5007
          gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5008
          /* Skip the ADDR_EXPR only if it is part of the decay for
5009
             an array. Otherwise, it is part of the original argument
5010
             in the source code.  */
5011
          if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5012
            expr = TREE_OPERAND (expr, 0);
5013
          expr_type = TREE_TYPE (expr);
5014
        }
5015
    }
5016
 
5017
  /* [temp.arg.nontype]/5, bullet 1
5018
 
5019
     For a non-type template-parameter of integral or enumeration type,
5020
     integral promotions (_conv.prom_) and integral conversions
5021
     (_conv.integral_) are applied.  */
5022
  if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5023
    {
5024
      if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
5025
        return error_mark_node;
5026
 
5027
      expr = fold_decl_constant_value (expr);
5028
      /* Notice that there are constant expressions like '4 % 0' which
5029
         do not fold into integer constants.  */
5030
      if (TREE_CODE (expr) != INTEGER_CST)
5031
        {
5032
          error ("%qE is not a valid template argument for type %qT "
5033
                 "because it is a non-constant expression", expr, type);
5034
          return NULL_TREE;
5035
        }
5036
 
5037
      /* At this point, an implicit conversion does what we want,
5038
         because we already know that the expression is of integral
5039
         type.  */
5040
      expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
5041
      if (expr == error_mark_node)
5042
        return error_mark_node;
5043
 
5044
      /* Conversion was allowed: fold it to a bare integer constant.  */
5045
      expr = fold (expr);
5046
    }
5047
  /* [temp.arg.nontype]/5, bullet 2
5048
 
5049
     For a non-type template-parameter of type pointer to object,
5050
     qualification conversions (_conv.qual_) and the array-to-pointer
5051
     conversion (_conv.array_) are applied.  */
5052
  else if (TYPE_PTROBV_P (type))
5053
    {
5054
      /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5055
 
5056
         A template-argument for a non-type, non-template template-parameter
5057
         shall be one of: [...]
5058
 
5059
         -- the name of a non-type template-parameter;
5060
         -- the address of an object or function with external linkage, [...]
5061
            expressed as "& id-expression" where the & is optional if the name
5062
            refers to a function or array, or if the corresponding
5063
            template-parameter is a reference.
5064
 
5065
        Here, we do not care about functions, as they are invalid anyway
5066
        for a parameter of type pointer-to-object.  */
5067
 
5068
      if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5069
        /* Non-type template parameters are OK.  */
5070
        ;
5071
      else if (TREE_CODE (expr) != ADDR_EXPR
5072
               && TREE_CODE (expr_type) != ARRAY_TYPE)
5073
        {
5074
          if (TREE_CODE (expr) == VAR_DECL)
5075
            {
5076
              error ("%qD is not a valid template argument "
5077
                     "because %qD is a variable, not the address of "
5078
                     "a variable",
5079
                     expr, expr);
5080
              return NULL_TREE;
5081
            }
5082
          /* Other values, like integer constants, might be valid
5083
             non-type arguments of some other type.  */
5084
          return error_mark_node;
5085
        }
5086
      else
5087
        {
5088
          tree decl;
5089
 
5090
          decl = ((TREE_CODE (expr) == ADDR_EXPR)
5091
                  ? TREE_OPERAND (expr, 0) : expr);
5092
          if (TREE_CODE (decl) != VAR_DECL)
5093
            {
5094
              error ("%qE is not a valid template argument of type %qT "
5095
                     "because %qE is not a variable",
5096
                     expr, type, decl);
5097
              return NULL_TREE;
5098
            }
5099
          else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5100
            {
5101
              error ("%qE is not a valid template argument of type %qT "
5102
                     "because %qD does not have external linkage",
5103
                     expr, type, decl);
5104
              return NULL_TREE;
5105
            }
5106
        }
5107
 
5108
      expr = decay_conversion (expr);
5109
      if (expr == error_mark_node)
5110
        return error_mark_node;
5111
 
5112
      expr = perform_qualification_conversions (type, expr);
5113
      if (expr == error_mark_node)
5114
        return error_mark_node;
5115
    }
5116
  /* [temp.arg.nontype]/5, bullet 3
5117
 
5118
     For a non-type template-parameter of type reference to object, no
5119
     conversions apply. The type referred to by the reference may be more
5120
     cv-qualified than the (otherwise identical) type of the
5121
     template-argument. The template-parameter is bound directly to the
5122
     template-argument, which must be an lvalue.  */
5123
  else if (TYPE_REF_OBJ_P (type))
5124
    {
5125
      if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5126
                                                      expr_type))
5127
        return error_mark_node;
5128
 
5129
      if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5130
        {
5131
          error ("%qE is not a valid template argument for type %qT "
5132
                 "because of conflicts in cv-qualification", expr, type);
5133
          return NULL_TREE;
5134
        }
5135
 
5136
      if (!real_lvalue_p (expr))
5137
        {
5138
          error ("%qE is not a valid template argument for type %qT "
5139
                 "because it is not an lvalue", expr, type);
5140
          return NULL_TREE;
5141
        }
5142
 
5143
      /* [temp.arg.nontype]/1
5144
 
5145
         A template-argument for a non-type, non-template template-parameter
5146
         shall be one of: [...]
5147
 
5148
         -- the address of an object or function with external linkage.  */
5149
      if (TREE_CODE (expr) == INDIRECT_REF
5150
          && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5151
        {
5152
          expr = TREE_OPERAND (expr, 0);
5153
          if (DECL_P (expr))
5154
            {
5155
              error ("%q#D is not a valid template argument for type %qT "
5156
                     "because a reference variable does not have a constant "
5157
                     "address", expr, type);
5158
              return NULL_TREE;
5159
            }
5160
        }
5161
 
5162
      if (!DECL_P (expr))
5163
        {
5164
          error ("%qE is not a valid template argument for type %qT "
5165
                 "because it is not an object with external linkage",
5166
                 expr, type);
5167
          return NULL_TREE;
5168
        }
5169
 
5170
      if (!DECL_EXTERNAL_LINKAGE_P (expr))
5171
        {
5172
          error ("%qE is not a valid template argument for type %qT "
5173
                 "because object %qD has not external linkage",
5174
                 expr, type, expr);
5175
          return NULL_TREE;
5176
        }
5177
 
5178
      expr = build_nop (type, build_address (expr));
5179
    }
5180
  /* [temp.arg.nontype]/5, bullet 4
5181
 
5182
     For a non-type template-parameter of type pointer to function, only
5183
     the function-to-pointer conversion (_conv.func_) is applied. If the
5184
     template-argument represents a set of overloaded functions (or a
5185
     pointer to such), the matching function is selected from the set
5186
     (_over.over_).  */
5187
  else if (TYPE_PTRFN_P (type))
5188
    {
5189
      /* If the argument is a template-id, we might not have enough
5190
         context information to decay the pointer.  */
5191
      if (!type_unknown_p (expr_type))
5192
        {
5193
          expr = decay_conversion (expr);
5194
          if (expr == error_mark_node)
5195
            return error_mark_node;
5196
        }
5197
 
5198
      expr = convert_nontype_argument_function (type, expr);
5199
      if (!expr || expr == error_mark_node)
5200
        return expr;
5201
 
5202
      if (TREE_CODE (expr) != ADDR_EXPR)
5203
        {
5204
          error ("%qE is not a valid template argument for type %qT", expr, type);
5205
          error ("it must be the address of a function with external linkage");
5206
          return NULL_TREE;
5207
        }
5208
    }
5209
  /* [temp.arg.nontype]/5, bullet 5
5210
 
5211
     For a non-type template-parameter of type reference to function, no
5212
     conversions apply. If the template-argument represents a set of
5213
     overloaded functions, the matching function is selected from the set
5214
     (_over.over_).  */
5215
  else if (TYPE_REFFN_P (type))
5216
    {
5217
      if (TREE_CODE (expr) == ADDR_EXPR)
5218
        {
5219
          error ("%qE is not a valid template argument for type %qT "
5220
                 "because it is a pointer", expr, type);
5221
          inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5222
          return NULL_TREE;
5223
        }
5224
 
5225
      expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5226
      if (!expr || expr == error_mark_node)
5227
        return expr;
5228
 
5229
      expr = build_nop (type, build_address (expr));
5230
    }
5231
  /* [temp.arg.nontype]/5, bullet 6
5232
 
5233
     For a non-type template-parameter of type pointer to member function,
5234
     no conversions apply. If the template-argument represents a set of
5235
     overloaded member functions, the matching member function is selected
5236
     from the set (_over.over_).  */
5237
  else if (TYPE_PTRMEMFUNC_P (type))
5238
    {
5239
      expr = instantiate_type (type, expr, tf_none);
5240
      if (expr == error_mark_node)
5241
        return error_mark_node;
5242
 
5243
      /* [temp.arg.nontype] bullet 1 says the pointer to member
5244
         expression must be a pointer-to-member constant.  */
5245
      if (!check_valid_ptrmem_cst_expr (type, expr))
5246
        return error_mark_node;
5247
 
5248
      /* There is no way to disable standard conversions in
5249
         resolve_address_of_overloaded_function (called by
5250
         instantiate_type). It is possible that the call succeeded by
5251
         converting &B::I to &D::I (where B is a base of D), so we need
5252
         to reject this conversion here.
5253
 
5254
         Actually, even if there was a way to disable standard conversions,
5255
         it would still be better to reject them here so that we can
5256
         provide a superior diagnostic.  */
5257
      if (!same_type_p (TREE_TYPE (expr), type))
5258
        {
5259
          error ("%qE is not a valid template argument for type %qT "
5260
                 "because it is of type %qT", expr, type,
5261
                 TREE_TYPE (expr));
5262
          /* If we are just one standard conversion off, explain.  */
5263
          if (can_convert (type, TREE_TYPE (expr)))
5264
            inform (input_location,
5265
                    "standard conversions are not allowed in this context");
5266
          return NULL_TREE;
5267
        }
5268
    }
5269
  /* [temp.arg.nontype]/5, bullet 7
5270
 
5271
     For a non-type template-parameter of type pointer to data member,
5272
     qualification conversions (_conv.qual_) are applied.  */
5273
  else if (TYPE_PTRMEM_P (type))
5274
    {
5275
      /* [temp.arg.nontype] bullet 1 says the pointer to member
5276
         expression must be a pointer-to-member constant.  */
5277
      if (!check_valid_ptrmem_cst_expr (type, expr))
5278
        return error_mark_node;
5279
 
5280
      expr = perform_qualification_conversions (type, expr);
5281
      if (expr == error_mark_node)
5282
        return expr;
5283
    }
5284
  /* A template non-type parameter must be one of the above.  */
5285
  else
5286
    gcc_unreachable ();
5287
 
5288
  /* Sanity check: did we actually convert the argument to the
5289
     right type?  */
5290
  gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5291
  return expr;
5292
}
5293
 
5294
/* Subroutine of coerce_template_template_parms, which returns 1 if
5295
   PARM_PARM and ARG_PARM match using the rule for the template
5296
   parameters of template template parameters. Both PARM and ARG are
5297
   template parameters; the rest of the arguments are the same as for
5298
   coerce_template_template_parms.
5299
 */
5300
static int
5301
coerce_template_template_parm (tree parm,
5302
                              tree arg,
5303
                              tsubst_flags_t complain,
5304
                              tree in_decl,
5305
                              tree outer_args)
5306
{
5307
  if (arg == NULL_TREE || arg == error_mark_node
5308
      || parm == NULL_TREE || parm == error_mark_node)
5309
    return 0;
5310
 
5311
  if (TREE_CODE (arg) != TREE_CODE (parm))
5312
    return 0;
5313
 
5314
  switch (TREE_CODE (parm))
5315
    {
5316
    case TEMPLATE_DECL:
5317
      /* We encounter instantiations of templates like
5318
         template <template <template <class> class> class TT>
5319
         class C;  */
5320
      {
5321
        tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5322
        tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5323
 
5324
        if (!coerce_template_template_parms
5325
            (parmparm, argparm, complain, in_decl, outer_args))
5326
          return 0;
5327
      }
5328
      /* Fall through.  */
5329
 
5330
    case TYPE_DECL:
5331
      if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5332
          && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5333
        /* Argument is a parameter pack but parameter is not.  */
5334
        return 0;
5335
      break;
5336
 
5337
    case PARM_DECL:
5338
      /* The tsubst call is used to handle cases such as
5339
 
5340
           template <int> class C {};
5341
           template <class T, template <T> class TT> class D {};
5342
           D<int, C> d;
5343
 
5344
         i.e. the parameter list of TT depends on earlier parameters.  */
5345
      if (!uses_template_parms (TREE_TYPE (arg))
5346
          && !same_type_p
5347
                (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5348
                 TREE_TYPE (arg)))
5349
        return 0;
5350
 
5351
      if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5352
          && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5353
        /* Argument is a parameter pack but parameter is not.  */
5354
        return 0;
5355
 
5356
      break;
5357
 
5358
    default:
5359
      gcc_unreachable ();
5360
    }
5361
 
5362
  return 1;
5363
}
5364
 
5365
 
5366
/* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5367
   template template parameters.  Both PARM_PARMS and ARG_PARMS are
5368
   vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5369
   or PARM_DECL.
5370
 
5371
   Consider the example:
5372
     template <class T> class A;
5373
     template<template <class U> class TT> class B;
5374
 
5375
   For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5376
   the parameters to A, and OUTER_ARGS contains A.  */
5377
 
5378
static int
5379
coerce_template_template_parms (tree parm_parms,
5380
                                tree arg_parms,
5381
                                tsubst_flags_t complain,
5382
                                tree in_decl,
5383
                                tree outer_args)
5384
{
5385
  int nparms, nargs, i;
5386
  tree parm, arg;
5387
  int variadic_p = 0;
5388
 
5389
  gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5390
  gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5391
 
5392
  nparms = TREE_VEC_LENGTH (parm_parms);
5393
  nargs = TREE_VEC_LENGTH (arg_parms);
5394
 
5395
  /* Determine whether we have a parameter pack at the end of the
5396
     template template parameter's template parameter list.  */
5397
  if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5398
    {
5399
      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5400
 
5401
      if (parm == error_mark_node)
5402
        return 0;
5403
 
5404
      switch (TREE_CODE (parm))
5405
        {
5406
        case TEMPLATE_DECL:
5407
        case TYPE_DECL:
5408
          if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5409
            variadic_p = 1;
5410
          break;
5411
 
5412
        case PARM_DECL:
5413
          if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5414
            variadic_p = 1;
5415
          break;
5416
 
5417
        default:
5418
          gcc_unreachable ();
5419
        }
5420
    }
5421
 
5422
  if (nargs != nparms
5423
      && !(variadic_p && nargs >= nparms - 1))
5424
    return 0;
5425
 
5426
  /* Check all of the template parameters except the parameter pack at
5427
     the end (if any).  */
5428
  for (i = 0; i < nparms - variadic_p; ++i)
5429
    {
5430
      if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5431
          || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5432
        continue;
5433
 
5434
      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5435
      arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5436
 
5437
      if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5438
                                          outer_args))
5439
        return 0;
5440
 
5441
    }
5442
 
5443
  if (variadic_p)
5444
    {
5445
      /* Check each of the template parameters in the template
5446
         argument against the template parameter pack at the end of
5447
         the template template parameter.  */
5448
      if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5449
        return 0;
5450
 
5451
      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5452
 
5453
      for (; i < nargs; ++i)
5454
        {
5455
          if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5456
            continue;
5457
 
5458
          arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5459
 
5460
          if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5461
                                              outer_args))
5462
            return 0;
5463
        }
5464
    }
5465
 
5466
  return 1;
5467
}
5468
 
5469
/* Verifies that the deduced template arguments (in TARGS) for the
5470
   template template parameters (in TPARMS) represent valid bindings,
5471
   by comparing the template parameter list of each template argument
5472
   to the template parameter list of its corresponding template
5473
   template parameter, in accordance with DR150. This
5474
   routine can only be called after all template arguments have been
5475
   deduced. It will return TRUE if all of the template template
5476
   parameter bindings are okay, FALSE otherwise.  */
5477
bool
5478
template_template_parm_bindings_ok_p (tree tparms, tree targs)
5479
{
5480
  int i, ntparms = TREE_VEC_LENGTH (tparms);
5481
  bool ret = true;
5482
 
5483
  /* We're dealing with template parms in this process.  */
5484
  ++processing_template_decl;
5485
 
5486
  targs = INNERMOST_TEMPLATE_ARGS (targs);
5487
 
5488
  for (i = 0; i < ntparms; ++i)
5489
    {
5490
      tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5491
      tree targ = TREE_VEC_ELT (targs, i);
5492
 
5493
      if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5494
        {
5495
          tree packed_args = NULL_TREE;
5496
          int idx, len = 1;
5497
 
5498
          if (ARGUMENT_PACK_P (targ))
5499
            {
5500
              /* Look inside the argument pack.  */
5501
              packed_args = ARGUMENT_PACK_ARGS (targ);
5502
              len = TREE_VEC_LENGTH (packed_args);
5503
            }
5504
 
5505
          for (idx = 0; idx < len; ++idx)
5506
            {
5507
              tree targ_parms = NULL_TREE;
5508
 
5509
              if (packed_args)
5510
                /* Extract the next argument from the argument
5511
                   pack.  */
5512
                targ = TREE_VEC_ELT (packed_args, idx);
5513
 
5514
              if (PACK_EXPANSION_P (targ))
5515
                /* Look at the pattern of the pack expansion.  */
5516
                targ = PACK_EXPANSION_PATTERN (targ);
5517
 
5518
              /* Extract the template parameters from the template
5519
                 argument.  */
5520
              if (TREE_CODE (targ) == TEMPLATE_DECL)
5521
                targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5522
              else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5523
                targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5524
 
5525
              /* Verify that we can coerce the template template
5526
                 parameters from the template argument to the template
5527
                 parameter.  This requires an exact match.  */
5528
              if (targ_parms
5529
                  && !coerce_template_template_parms
5530
                       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5531
                        targ_parms,
5532
                        tf_none,
5533
                        tparm,
5534
                        targs))
5535
                {
5536
                  ret = false;
5537
                  goto out;
5538
                }
5539
            }
5540
        }
5541
    }
5542
 
5543
 out:
5544
 
5545
  --processing_template_decl;
5546
  return ret;
5547
}
5548
 
5549
/* Convert the indicated template ARG as necessary to match the
5550
   indicated template PARM.  Returns the converted ARG, or
5551
   error_mark_node if the conversion was unsuccessful.  Error and
5552
   warning messages are issued under control of COMPLAIN.  This
5553
   conversion is for the Ith parameter in the parameter list.  ARGS is
5554
   the full set of template arguments deduced so far.  */
5555
 
5556
static tree
5557
convert_template_argument (tree parm,
5558
                           tree arg,
5559
                           tree args,
5560
                           tsubst_flags_t complain,
5561
                           int i,
5562
                           tree in_decl)
5563
{
5564
  tree orig_arg;
5565
  tree val;
5566
  int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5567
 
5568
  if (TREE_CODE (arg) == TREE_LIST
5569
      && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5570
    {
5571
      /* The template argument was the name of some
5572
         member function.  That's usually
5573
         invalid, but static members are OK.  In any
5574
         case, grab the underlying fields/functions
5575
         and issue an error later if required.  */
5576
      orig_arg = TREE_VALUE (arg);
5577
      TREE_TYPE (arg) = unknown_type_node;
5578
    }
5579
 
5580
  orig_arg = arg;
5581
 
5582
  requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5583
  requires_type = (TREE_CODE (parm) == TYPE_DECL
5584
                   || requires_tmpl_type);
5585
 
5586
  /* When determining whether an argument pack expansion is a template,
5587
     look at the pattern.  */
5588
  if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5589
    arg = PACK_EXPANSION_PATTERN (arg);
5590
 
5591
  /* Deal with an injected-class-name used as a template template arg.  */
5592
  if (requires_tmpl_type && CLASS_TYPE_P (arg))
5593
    {
5594
      tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5595
      if (TREE_CODE (t) == TEMPLATE_DECL)
5596
        {
5597
          if (complain & tf_warning_or_error)
5598
            pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5599
                     " used as template template argument", TYPE_NAME (arg));
5600
          else if (flag_pedantic_errors)
5601
            t = arg;
5602
 
5603
          arg = t;
5604
        }
5605
    }
5606
 
5607
  is_tmpl_type =
5608
    ((TREE_CODE (arg) == TEMPLATE_DECL
5609
      && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5610
     || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5611
     || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5612
 
5613
  if (is_tmpl_type
5614
      && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5615
          || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5616
    arg = TYPE_STUB_DECL (arg);
5617
 
5618
  is_type = TYPE_P (arg) || is_tmpl_type;
5619
 
5620
  if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5621
      && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5622
    {
5623
      permerror (input_location, "to refer to a type member of a template parameter, "
5624
                 "use %<typename %E%>", orig_arg);
5625
 
5626
      orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5627
                                     TREE_OPERAND (arg, 1),
5628
                                     typename_type,
5629
                                     complain & tf_error);
5630
      arg = orig_arg;
5631
      is_type = 1;
5632
    }
5633
  if (is_type != requires_type)
5634
    {
5635
      if (in_decl)
5636
        {
5637
          if (complain & tf_error)
5638
            {
5639
              error ("type/value mismatch at argument %d in template "
5640
                     "parameter list for %qD",
5641
                     i + 1, in_decl);
5642
              if (is_type)
5643
                error ("  expected a constant of type %qT, got %qT",
5644
                       TREE_TYPE (parm),
5645
                       (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5646
              else if (requires_tmpl_type)
5647
                error ("  expected a class template, got %qE", orig_arg);
5648
              else
5649
                error ("  expected a type, got %qE", orig_arg);
5650
            }
5651
        }
5652
      return error_mark_node;
5653
    }
5654
  if (is_tmpl_type ^ requires_tmpl_type)
5655
    {
5656
      if (in_decl && (complain & tf_error))
5657
        {
5658
          error ("type/value mismatch at argument %d in template "
5659
                 "parameter list for %qD",
5660
                 i + 1, in_decl);
5661
          if (is_tmpl_type)
5662
            error ("  expected a type, got %qT", DECL_NAME (arg));
5663
          else
5664
            error ("  expected a class template, got %qT", orig_arg);
5665
        }
5666
      return error_mark_node;
5667
    }
5668
 
5669
  if (is_type)
5670
    {
5671
      if (requires_tmpl_type)
5672
        {
5673
          if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5674
            /* The number of argument required is not known yet.
5675
               Just accept it for now.  */
5676
            val = TREE_TYPE (arg);
5677
          else
5678
            {
5679
              tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5680
              tree argparm;
5681
 
5682
              argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5683
 
5684
              if (coerce_template_template_parms (parmparm, argparm,
5685
                                                  complain, in_decl,
5686
                                                  args))
5687
                {
5688
                  val = arg;
5689
 
5690
                  /* TEMPLATE_TEMPLATE_PARM node is preferred over
5691
                     TEMPLATE_DECL.  */
5692
                  if (val != error_mark_node)
5693
                    {
5694
                      if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5695
                        val = TREE_TYPE (val);
5696
                      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5697
                        val = make_pack_expansion (val);
5698
                    }
5699
                }
5700
              else
5701
                {
5702
                  if (in_decl && (complain & tf_error))
5703
                    {
5704
                      error ("type/value mismatch at argument %d in "
5705
                             "template parameter list for %qD",
5706
                             i + 1, in_decl);
5707
                      error ("  expected a template of type %qD, got %qT",
5708
                             parm, orig_arg);
5709
                    }
5710
 
5711
                  val = error_mark_node;
5712
                }
5713
            }
5714
        }
5715
      else
5716
        val = orig_arg;
5717
      /* We only form one instance of each template specialization.
5718
         Therefore, if we use a non-canonical variant (i.e., a
5719
         typedef), any future messages referring to the type will use
5720
         the typedef, which is confusing if those future uses do not
5721
         themselves also use the typedef.  */
5722
      if (TYPE_P (val))
5723
        val = strip_typedefs (val);
5724
    }
5725
  else
5726
    {
5727
      tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5728
 
5729
      if (invalid_nontype_parm_type_p (t, complain))
5730
        return error_mark_node;
5731
 
5732
      if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5733
        {
5734
          if (same_type_p (t, TREE_TYPE (orig_arg)))
5735
            val = orig_arg;
5736
          else
5737
            {
5738
              /* Not sure if this is reachable, but it doesn't hurt
5739
                 to be robust.  */
5740
              error ("type mismatch in nontype parameter pack");
5741
              val = error_mark_node;
5742
            }
5743
        }
5744
      else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5745
        /* We used to call digest_init here.  However, digest_init
5746
           will report errors, which we don't want when complain
5747
           is zero.  More importantly, digest_init will try too
5748
           hard to convert things: for example, `0' should not be
5749
           converted to pointer type at this point according to
5750
           the standard.  Accepting this is not merely an
5751
           extension, since deciding whether or not these
5752
           conversions can occur is part of determining which
5753
           function template to call, or whether a given explicit
5754
           argument specification is valid.  */
5755
        val = convert_nontype_argument (t, orig_arg);
5756
      else
5757
        val = orig_arg;
5758
 
5759
      if (val == NULL_TREE)
5760
        val = error_mark_node;
5761
      else if (val == error_mark_node && (complain & tf_error))
5762
        error ("could not convert template argument %qE to %qT",  orig_arg, t);
5763
 
5764
      if (TREE_CODE (val) == SCOPE_REF)
5765
        {
5766
          /* Strip typedefs from the SCOPE_REF.  */
5767
          tree type = strip_typedefs (TREE_TYPE (val));
5768
          tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5769
          val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5770
                                      QUALIFIED_NAME_IS_TEMPLATE (val));
5771
        }
5772
    }
5773
 
5774
  return val;
5775
}
5776
 
5777
/* Coerces the remaining template arguments in INNER_ARGS (from
5778
   ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5779
   Returns the coerced argument pack. PARM_IDX is the position of this
5780
   parameter in the template parameter list. ARGS is the original
5781
   template argument list.  */
5782
static tree
5783
coerce_template_parameter_pack (tree parms,
5784
                                int parm_idx,
5785
                                tree args,
5786
                                tree inner_args,
5787
                                int arg_idx,
5788
                                tree new_args,
5789
                                int* lost,
5790
                                tree in_decl,
5791
                                tsubst_flags_t complain)
5792
{
5793
  tree parm = TREE_VEC_ELT (parms, parm_idx);
5794
  int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5795
  tree packed_args;
5796
  tree argument_pack;
5797
  tree packed_types = NULL_TREE;
5798
 
5799
  if (arg_idx > nargs)
5800
    arg_idx = nargs;
5801
 
5802
  packed_args = make_tree_vec (nargs - arg_idx);
5803
 
5804
  if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5805
      && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5806
    {
5807
      /* When the template parameter is a non-type template
5808
         parameter pack whose type uses parameter packs, we need
5809
         to look at each of the template arguments
5810
         separately. Build a vector of the types for these
5811
         non-type template parameters in PACKED_TYPES.  */
5812
      tree expansion
5813
        = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5814
      packed_types = tsubst_pack_expansion (expansion, args,
5815
                                            complain, in_decl);
5816
 
5817
      if (packed_types == error_mark_node)
5818
        return error_mark_node;
5819
 
5820
      /* Check that we have the right number of arguments.  */
5821
      if (arg_idx < nargs
5822
          && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5823
          && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5824
        {
5825
          int needed_parms
5826
            = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5827
          error ("wrong number of template arguments (%d, should be %d)",
5828
                 nargs, needed_parms);
5829
          return error_mark_node;
5830
        }
5831
 
5832
      /* If we aren't able to check the actual arguments now
5833
         (because they haven't been expanded yet), we can at least
5834
         verify that all of the types used for the non-type
5835
         template parameter pack are, in fact, valid for non-type
5836
         template parameters.  */
5837
      if (arg_idx < nargs
5838
          && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5839
        {
5840
          int j, len = TREE_VEC_LENGTH (packed_types);
5841
          for (j = 0; j < len; ++j)
5842
            {
5843
              tree t = TREE_VEC_ELT (packed_types, j);
5844
              if (invalid_nontype_parm_type_p (t, complain))
5845
                return error_mark_node;
5846
            }
5847
        }
5848
    }
5849
 
5850
  /* Convert the remaining arguments, which will be a part of the
5851
     parameter pack "parm".  */
5852
  for (; arg_idx < nargs; ++arg_idx)
5853
    {
5854
      tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5855
      tree actual_parm = TREE_VALUE (parm);
5856
 
5857
      if (packed_types && !PACK_EXPANSION_P (arg))
5858
        {
5859
          /* When we have a vector of types (corresponding to the
5860
             non-type template parameter pack that uses parameter
5861
             packs in its type, as mention above), and the
5862
             argument is not an expansion (which expands to a
5863
             currently unknown number of arguments), clone the
5864
             parm and give it the next type in PACKED_TYPES.  */
5865
          actual_parm = copy_node (actual_parm);
5866
          TREE_TYPE (actual_parm) =
5867
            TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5868
        }
5869
 
5870
      if (arg != error_mark_node)
5871
        arg = convert_template_argument (actual_parm,
5872
                                         arg, new_args, complain, parm_idx,
5873
                                         in_decl);
5874
      if (arg == error_mark_node)
5875
        (*lost)++;
5876
      TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg;
5877
    }
5878
 
5879
  if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5880
      || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5881
    argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5882
  else
5883
    {
5884
      argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5885
      TREE_TYPE (argument_pack)
5886
        = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5887
      TREE_CONSTANT (argument_pack) = 1;
5888
    }
5889
 
5890
  SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5891
#ifdef ENABLE_CHECKING
5892
  SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5893
                                       TREE_VEC_LENGTH (packed_args));
5894
#endif
5895
  return argument_pack;
5896
}
5897
 
5898
/* Convert all template arguments to their appropriate types, and
5899
   return a vector containing the innermost resulting template
5900
   arguments.  If any error occurs, return error_mark_node. Error and
5901
   warning messages are issued under control of COMPLAIN.
5902
 
5903
   If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5904
   for arguments not specified in ARGS.  Otherwise, if
5905
   USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5906
   unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5907
   USE_DEFAULT_ARGS is false, then all arguments must be specified in
5908
   ARGS.  */
5909
 
5910
static tree
5911
coerce_template_parms (tree parms,
5912
                       tree args,
5913
                       tree in_decl,
5914
                       tsubst_flags_t complain,
5915
                       bool require_all_args,
5916
                       bool use_default_args)
5917
{
5918
  int nparms, nargs, parm_idx, arg_idx, lost = 0;
5919
  tree inner_args;
5920
  tree new_args;
5921
  tree new_inner_args;
5922
  int saved_unevaluated_operand;
5923
  int saved_inhibit_evaluation_warnings;
5924
 
5925
  /* When used as a boolean value, indicates whether this is a
5926
     variadic template parameter list. Since it's an int, we can also
5927
     subtract it from nparms to get the number of non-variadic
5928
     parameters.  */
5929
  int variadic_p = 0;
5930
 
5931
  nparms = TREE_VEC_LENGTH (parms);
5932
 
5933
  /* Determine if there are any parameter packs.  */
5934
  for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5935
    {
5936
      tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5937
      if (template_parameter_pack_p (tparm))
5938
        ++variadic_p;
5939
    }
5940
 
5941
  inner_args = INNERMOST_TEMPLATE_ARGS (args);
5942
  /* If there are 0 or 1 parameter packs, we need to expand any argument
5943
     packs so that we can deduce a parameter pack from some non-packed args
5944
     followed by an argument pack, as in variadic85.C.  If there are more
5945
     than that, we need to leave argument packs intact so the arguments are
5946
     assigned to the right parameter packs.  This should only happen when
5947
     dealing with a nested class inside a partial specialization of a class
5948
     template, as in variadic92.C.  */
5949
  if (variadic_p <= 1)
5950
    inner_args = expand_template_argument_pack (inner_args);
5951
 
5952
  nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5953
  if ((nargs > nparms && !variadic_p)
5954
      || (nargs < nparms - variadic_p
5955
          && require_all_args
5956
          && (!use_default_args
5957
              || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5958
                  && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5959
    {
5960
      if (complain & tf_error)
5961
        {
5962
          const char *or_more = "";
5963
          if (variadic_p)
5964
            {
5965
              or_more = " or more";
5966
              --nparms;
5967
            }
5968
 
5969
          error ("wrong number of template arguments (%d, should be %d%s)",
5970
                 nargs, nparms, or_more);
5971
 
5972
          if (in_decl)
5973
            error ("provided for %q+D", in_decl);
5974
        }
5975
 
5976
      return error_mark_node;
5977
    }
5978
 
5979
  /* We need to evaluate the template arguments, even though this
5980
     template-id may be nested within a "sizeof".  */
5981
  saved_unevaluated_operand = cp_unevaluated_operand;
5982
  cp_unevaluated_operand = 0;
5983
  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5984
  c_inhibit_evaluation_warnings = 0;
5985
  new_inner_args = make_tree_vec (nparms);
5986
  new_args = add_outermost_template_args (args, new_inner_args);
5987
  for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5988
    {
5989
      tree arg;
5990
      tree parm;
5991
 
5992
      /* Get the Ith template parameter.  */
5993
      parm = TREE_VEC_ELT (parms, parm_idx);
5994
 
5995
      if (parm == error_mark_node)
5996
      {
5997
        TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5998
        continue;
5999
      }
6000
 
6001
      /* Calculate the next argument.  */
6002
      if (arg_idx < nargs)
6003
        arg = TREE_VEC_ELT (inner_args, arg_idx);
6004
      else
6005
        arg = NULL_TREE;
6006
 
6007
      if (template_parameter_pack_p (TREE_VALUE (parm))
6008
          && !(arg && ARGUMENT_PACK_P (arg)))
6009
        {
6010
          /* All remaining arguments will be placed in the
6011
             template parameter pack PARM.  */
6012
          arg = coerce_template_parameter_pack (parms, parm_idx, args,
6013
                                                inner_args, arg_idx,
6014
                                                new_args, &lost,
6015
                                                in_decl, complain);
6016
 
6017
          /* Store this argument.  */
6018
          if (arg == error_mark_node)
6019
            lost++;
6020
          TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6021
 
6022
          /* We are done with all of the arguments.  */
6023
          arg_idx = nargs;
6024
 
6025
          continue;
6026
        }
6027
      else if (arg)
6028
        {
6029
          if (PACK_EXPANSION_P (arg))
6030
            {
6031
              if (complain & tf_error)
6032
                {
6033
                  /* FIXME this restriction was removed by N2555; see
6034
                     bug 35722.  */
6035
                  /* If ARG is a pack expansion, but PARM is not a
6036
                     template parameter pack (if it were, we would have
6037
                     handled it above), we're trying to expand into a
6038
                     fixed-length argument list.  */
6039
                  if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6040
                    sorry ("cannot expand %<%E%> into a fixed-length "
6041
                           "argument list", arg);
6042
                  else
6043
                    sorry ("cannot expand %<%T%> into a fixed-length "
6044
                           "argument list", arg);
6045
                }
6046
              return error_mark_node;
6047
            }
6048
        }
6049
      else if (require_all_args)
6050
        {
6051
          /* There must be a default arg in this case.  */
6052
          arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6053
                                     complain, in_decl);
6054
          /* The position of the first default template argument,
6055
             is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6056
             Record that.  */
6057
          if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6058
            SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6059
        }
6060
      else
6061
        break;
6062
 
6063
      if (arg == error_mark_node)
6064
        {
6065
          if (complain & tf_error)
6066
            error ("template argument %d is invalid", arg_idx + 1);
6067
        }
6068
      else if (!arg)
6069
        /* This only occurs if there was an error in the template
6070
           parameter list itself (which we would already have
6071
           reported) that we are trying to recover from, e.g., a class
6072
           template with a parameter list such as
6073
           template<typename..., typename>.  */
6074
        return error_mark_node;
6075
      else
6076
        arg = convert_template_argument (TREE_VALUE (parm),
6077
                                         arg, new_args, complain,
6078
                                         parm_idx, in_decl);
6079
 
6080
      if (arg == error_mark_node)
6081
        lost++;
6082
      TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6083
    }
6084
  cp_unevaluated_operand = saved_unevaluated_operand;
6085
  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6086
 
6087
  if (lost)
6088
    return error_mark_node;
6089
 
6090
#ifdef ENABLE_CHECKING
6091
  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6092
    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6093
                                         TREE_VEC_LENGTH (new_inner_args));
6094
#endif
6095
 
6096
  return new_inner_args;
6097
}
6098
 
6099
/* Returns 1 if template args OT and NT are equivalent.  */
6100
 
6101
static int
6102
template_args_equal (tree ot, tree nt)
6103
{
6104
  if (nt == ot)
6105
    return 1;
6106
 
6107
  if (TREE_CODE (nt) == TREE_VEC)
6108
    /* For member templates */
6109
    return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6110
  else if (PACK_EXPANSION_P (ot))
6111
    return PACK_EXPANSION_P (nt)
6112
      && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6113
                              PACK_EXPANSION_PATTERN (nt));
6114
  else if (ARGUMENT_PACK_P (ot))
6115
    {
6116
      int i, len;
6117
      tree opack, npack;
6118
 
6119
      if (!ARGUMENT_PACK_P (nt))
6120
        return 0;
6121
 
6122
      opack = ARGUMENT_PACK_ARGS (ot);
6123
      npack = ARGUMENT_PACK_ARGS (nt);
6124
      len = TREE_VEC_LENGTH (opack);
6125
      if (TREE_VEC_LENGTH (npack) != len)
6126
        return 0;
6127
      for (i = 0; i < len; ++i)
6128
        if (!template_args_equal (TREE_VEC_ELT (opack, i),
6129
                                  TREE_VEC_ELT (npack, i)))
6130
          return 0;
6131
      return 1;
6132
    }
6133
  else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6134
    {
6135
      /* We get here probably because we are in the middle of substituting
6136
         into the pattern of a pack expansion. In that case the
6137
         ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6138
         interested in. So we want to use the initial pack argument for
6139
         the comparison.  */
6140
      ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6141
      if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6142
        nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6143
      return template_args_equal (ot, nt);
6144
    }
6145
  else if (TYPE_P (nt))
6146
    return TYPE_P (ot) && same_type_p (ot, nt);
6147
  else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6148
    return 0;
6149
  else
6150
    return cp_tree_equal (ot, nt);
6151
}
6152
 
6153
/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6154
   of template arguments.  Returns 0 otherwise.  */
6155
 
6156
int
6157
comp_template_args (tree oldargs, tree newargs)
6158
{
6159
  int i;
6160
 
6161
  if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6162
    return 0;
6163
 
6164
  for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6165
    {
6166
      tree nt = TREE_VEC_ELT (newargs, i);
6167
      tree ot = TREE_VEC_ELT (oldargs, i);
6168
 
6169
      if (! template_args_equal (ot, nt))
6170
        return 0;
6171
    }
6172
  return 1;
6173
}
6174
 
6175
static void
6176
add_pending_template (tree d)
6177
{
6178
  tree ti = (TYPE_P (d)
6179
             ? CLASSTYPE_TEMPLATE_INFO (d)
6180
             : DECL_TEMPLATE_INFO (d));
6181
  struct pending_template *pt;
6182
  int level;
6183
 
6184
  if (TI_PENDING_TEMPLATE_FLAG (ti))
6185
    return;
6186
 
6187
  /* We are called both from instantiate_decl, where we've already had a
6188
     tinst_level pushed, and instantiate_template, where we haven't.
6189
     Compensate.  */
6190
  level = !current_tinst_level || current_tinst_level->decl != d;
6191
 
6192
  if (level)
6193
    push_tinst_level (d);
6194
 
6195
  pt = GGC_NEW (struct pending_template);
6196
  pt->next = NULL;
6197
  pt->tinst = current_tinst_level;
6198
  if (last_pending_template)
6199
    last_pending_template->next = pt;
6200
  else
6201
    pending_templates = pt;
6202
 
6203
  last_pending_template = pt;
6204
 
6205
  TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6206
 
6207
  if (level)
6208
    pop_tinst_level ();
6209
}
6210
 
6211
 
6212
/* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6213
   ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6214
   documentation for TEMPLATE_ID_EXPR.  */
6215
 
6216
tree
6217
lookup_template_function (tree fns, tree arglist)
6218
{
6219
  tree type;
6220
 
6221
  if (fns == error_mark_node || arglist == error_mark_node)
6222
    return error_mark_node;
6223
 
6224
  gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6225
  gcc_assert (fns && (is_overloaded_fn (fns)
6226
                      || TREE_CODE (fns) == IDENTIFIER_NODE));
6227
 
6228
  if (BASELINK_P (fns))
6229
    {
6230
      BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6231
                                         unknown_type_node,
6232
                                         BASELINK_FUNCTIONS (fns),
6233
                                         arglist);
6234
      return fns;
6235
    }
6236
 
6237
  type = TREE_TYPE (fns);
6238
  if (TREE_CODE (fns) == OVERLOAD || !type)
6239
    type = unknown_type_node;
6240
 
6241
  return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6242
}
6243
 
6244
/* Within the scope of a template class S<T>, the name S gets bound
6245
   (in build_self_reference) to a TYPE_DECL for the class, not a
6246
   TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6247
   or one of its enclosing classes, and that type is a template,
6248
   return the associated TEMPLATE_DECL.  Otherwise, the original
6249
   DECL is returned.
6250
 
6251
   Also handle the case when DECL is a TREE_LIST of ambiguous
6252
   injected-class-names from different bases.  */
6253
 
6254
tree
6255
maybe_get_template_decl_from_type_decl (tree decl)
6256
{
6257
  if (decl == NULL_TREE)
6258
    return decl;
6259
 
6260
  /* DR 176: A lookup that finds an injected-class-name (10.2
6261
     [class.member.lookup]) can result in an ambiguity in certain cases
6262
     (for example, if it is found in more than one base class). If all of
6263
     the injected-class-names that are found refer to specializations of
6264
     the same class template, and if the name is followed by a
6265
     template-argument-list, the reference refers to the class template
6266
     itself and not a specialization thereof, and is not ambiguous.  */
6267
  if (TREE_CODE (decl) == TREE_LIST)
6268
    {
6269
      tree t, tmpl = NULL_TREE;
6270
      for (t = decl; t; t = TREE_CHAIN (t))
6271
        {
6272
          tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6273
          if (!tmpl)
6274
            tmpl = elt;
6275
          else if (tmpl != elt)
6276
            break;
6277
        }
6278
      if (tmpl && t == NULL_TREE)
6279
        return tmpl;
6280
      else
6281
        return decl;
6282
    }
6283
 
6284
  return (decl != NULL_TREE
6285
          && DECL_SELF_REFERENCE_P (decl)
6286
          && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6287
    ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6288
}
6289
 
6290
/* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6291
   parameters, find the desired type.
6292
 
6293
   D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6294
 
6295
   IN_DECL, if non-NULL, is the template declaration we are trying to
6296
   instantiate.
6297
 
6298
   If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6299
   the class we are looking up.
6300
 
6301
   Issue error and warning messages under control of COMPLAIN.
6302
 
6303
   If the template class is really a local class in a template
6304
   function, then the FUNCTION_CONTEXT is the function in which it is
6305
   being instantiated.
6306
 
6307
   ??? Note that this function is currently called *twice* for each
6308
   template-id: the first time from the parser, while creating the
6309
   incomplete type (finish_template_type), and the second type during the
6310
   real instantiation (instantiate_template_class). This is surely something
6311
   that we want to avoid. It also causes some problems with argument
6312
   coercion (see convert_nontype_argument for more information on this).  */
6313
 
6314
tree
6315
lookup_template_class (tree d1,
6316
                       tree arglist,
6317
                       tree in_decl,
6318
                       tree context,
6319
                       int entering_scope,
6320
                       tsubst_flags_t complain)
6321
{
6322
  tree templ = NULL_TREE, parmlist;
6323
  tree t;
6324
  spec_entry **slot;
6325
  spec_entry *entry;
6326
  spec_entry elt;
6327
  hashval_t hash;
6328
 
6329
  timevar_push (TV_NAME_LOOKUP);
6330
 
6331
  if (TREE_CODE (d1) == IDENTIFIER_NODE)
6332
    {
6333
      tree value = innermost_non_namespace_value (d1);
6334
      if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6335
        templ = value;
6336
      else
6337
        {
6338
          if (context)
6339
            push_decl_namespace (context);
6340
          templ = lookup_name (d1);
6341
          templ = maybe_get_template_decl_from_type_decl (templ);
6342
          if (context)
6343
            pop_decl_namespace ();
6344
        }
6345
      if (templ)
6346
        context = DECL_CONTEXT (templ);
6347
    }
6348
  else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6349
    {
6350
      tree type = TREE_TYPE (d1);
6351
 
6352
      /* If we are declaring a constructor, say A<T>::A<T>, we will get
6353
         an implicit typename for the second A.  Deal with it.  */
6354
      if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6355
        type = TREE_TYPE (type);
6356
 
6357
      if (CLASSTYPE_TEMPLATE_INFO (type))
6358
        {
6359
          templ = CLASSTYPE_TI_TEMPLATE (type);
6360
          d1 = DECL_NAME (templ);
6361
        }
6362
    }
6363
  else if (TREE_CODE (d1) == ENUMERAL_TYPE
6364
           || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6365
    {
6366
      templ = TYPE_TI_TEMPLATE (d1);
6367
      d1 = DECL_NAME (templ);
6368
    }
6369
  else if (TREE_CODE (d1) == TEMPLATE_DECL
6370
           && DECL_TEMPLATE_RESULT (d1)
6371
           && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6372
    {
6373
      templ = d1;
6374
      d1 = DECL_NAME (templ);
6375
      context = DECL_CONTEXT (templ);
6376
    }
6377
 
6378
  /* Issue an error message if we didn't find a template.  */
6379
  if (! templ)
6380
    {
6381
      if (complain & tf_error)
6382
        error ("%qT is not a template", d1);
6383
      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6384
    }
6385
 
6386
  if (TREE_CODE (templ) != TEMPLATE_DECL
6387
         /* Make sure it's a user visible template, if it was named by
6388
            the user.  */
6389
      || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6390
          && !PRIMARY_TEMPLATE_P (templ)))
6391
    {
6392
      if (complain & tf_error)
6393
        {
6394
          error ("non-template type %qT used as a template", d1);
6395
          if (in_decl)
6396
            error ("for template declaration %q+D", in_decl);
6397
        }
6398
      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6399
    }
6400
 
6401
  complain &= ~tf_user;
6402
 
6403
  if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6404
    {
6405
      /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6406
         template arguments */
6407
 
6408
      tree parm;
6409
      tree arglist2;
6410
      tree outer;
6411
 
6412
      parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6413
 
6414
      /* Consider an example where a template template parameter declared as
6415
 
6416
           template <class T, class U = std::allocator<T> > class TT
6417
 
6418
         The template parameter level of T and U are one level larger than
6419
         of TT.  To proper process the default argument of U, say when an
6420
         instantiation `TT<int>' is seen, we need to build the full
6421
         arguments containing {int} as the innermost level.  Outer levels,
6422
         available when not appearing as default template argument, can be
6423
         obtained from the arguments of the enclosing template.
6424
 
6425
         Suppose that TT is later substituted with std::vector.  The above
6426
         instantiation is `TT<int, std::allocator<T> >' with TT at
6427
         level 1, and T at level 2, while the template arguments at level 1
6428
         becomes {std::vector} and the inner level 2 is {int}.  */
6429
 
6430
      outer = DECL_CONTEXT (templ);
6431
      if (outer)
6432
        outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6433
      else if (current_template_parms)
6434
        /* This is an argument of the current template, so we haven't set
6435
           DECL_CONTEXT yet.  */
6436
        outer = current_template_args ();
6437
 
6438
      if (outer)
6439
        arglist = add_to_template_args (outer, arglist);
6440
 
6441
      arglist2 = coerce_template_parms (parmlist, arglist, templ,
6442
                                        complain,
6443
                                        /*require_all_args=*/true,
6444
                                        /*use_default_args=*/true);
6445
      if (arglist2 == error_mark_node
6446
          || (!uses_template_parms (arglist2)
6447
              && check_instantiated_args (templ, arglist2, complain)))
6448
        POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6449
 
6450
      parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6451
      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6452
    }
6453
  else
6454
    {
6455
      tree template_type = TREE_TYPE (templ);
6456
      tree gen_tmpl;
6457
      tree type_decl;
6458
      tree found = NULL_TREE;
6459
      int arg_depth;
6460
      int parm_depth;
6461
      int is_dependent_type;
6462
      int use_partial_inst_tmpl = false;
6463
 
6464
      gen_tmpl = most_general_template (templ);
6465
      parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6466
      parm_depth = TMPL_PARMS_DEPTH (parmlist);
6467
      arg_depth = TMPL_ARGS_DEPTH (arglist);
6468
 
6469
      if (arg_depth == 1 && parm_depth > 1)
6470
        {
6471
          /* We've been given an incomplete set of template arguments.
6472
             For example, given:
6473
 
6474
               template <class T> struct S1 {
6475
                 template <class U> struct S2 {};
6476
                 template <class U> struct S2<U*> {};
6477
                };
6478
 
6479
             we will be called with an ARGLIST of `U*', but the
6480
             TEMPLATE will be `template <class T> template
6481
             <class U> struct S1<T>::S2'.  We must fill in the missing
6482
             arguments.  */
6483
          arglist
6484
            = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6485
                                           arglist);
6486
          arg_depth = TMPL_ARGS_DEPTH (arglist);
6487
        }
6488
 
6489
      /* Now we should have enough arguments.  */
6490
      gcc_assert (parm_depth == arg_depth);
6491
 
6492
      /* From here on, we're only interested in the most general
6493
         template.  */
6494
 
6495
      /* Calculate the BOUND_ARGS.  These will be the args that are
6496
         actually tsubst'd into the definition to create the
6497
         instantiation.  */
6498
      if (parm_depth > 1)
6499
        {
6500
          /* We have multiple levels of arguments to coerce, at once.  */
6501
          int i;
6502
          int saved_depth = TMPL_ARGS_DEPTH (arglist);
6503
 
6504
          tree bound_args = make_tree_vec (parm_depth);
6505
 
6506
          for (i = saved_depth,
6507
                 t = DECL_TEMPLATE_PARMS (gen_tmpl);
6508
               i > 0 && t != NULL_TREE;
6509
               --i, t = TREE_CHAIN (t))
6510
            {
6511
              tree a = coerce_template_parms (TREE_VALUE (t),
6512
                                              arglist, gen_tmpl,
6513
                                              complain,
6514
                                              /*require_all_args=*/true,
6515
                                              /*use_default_args=*/true);
6516
 
6517
              /* Don't process further if one of the levels fails.  */
6518
              if (a == error_mark_node)
6519
                {
6520
                  /* Restore the ARGLIST to its full size.  */
6521
                  TREE_VEC_LENGTH (arglist) = saved_depth;
6522
                  POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6523
                }
6524
 
6525
              SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6526
 
6527
              /* We temporarily reduce the length of the ARGLIST so
6528
                 that coerce_template_parms will see only the arguments
6529
                 corresponding to the template parameters it is
6530
                 examining.  */
6531
              TREE_VEC_LENGTH (arglist)--;
6532
            }
6533
 
6534
          /* Restore the ARGLIST to its full size.  */
6535
          TREE_VEC_LENGTH (arglist) = saved_depth;
6536
 
6537
          arglist = bound_args;
6538
        }
6539
      else
6540
        arglist
6541
          = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6542
                                   INNERMOST_TEMPLATE_ARGS (arglist),
6543
                                   gen_tmpl,
6544
                                   complain,
6545
                                   /*require_all_args=*/true,
6546
                                   /*use_default_args=*/true);
6547
 
6548
      if (arglist == error_mark_node)
6549
        /* We were unable to bind the arguments.  */
6550
        POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6551
 
6552
      /* In the scope of a template class, explicit references to the
6553
         template class refer to the type of the template, not any
6554
         instantiation of it.  For example, in:
6555
 
6556
           template <class T> class C { void f(C<T>); }
6557
 
6558
         the `C<T>' is just the same as `C'.  Outside of the
6559
         class, however, such a reference is an instantiation.  */
6560
      if ((entering_scope
6561
           || !PRIMARY_TEMPLATE_P (gen_tmpl)
6562
           || currently_open_class (template_type))
6563
          /* comp_template_args is expensive, check it last.  */
6564
          && comp_template_args (TYPE_TI_ARGS (template_type),
6565
                                 arglist))
6566
        POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6567
 
6568
      /* If we already have this specialization, return it.  */
6569
      elt.tmpl = gen_tmpl;
6570
      elt.args = arglist;
6571
      hash = hash_specialization (&elt);
6572
      entry = (spec_entry *) htab_find_with_hash (type_specializations,
6573
                                                  &elt, hash);
6574
 
6575
      if (entry)
6576
        POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6577
 
6578
      is_dependent_type = uses_template_parms (arglist);
6579
 
6580
      /* If the deduced arguments are invalid, then the binding
6581
         failed.  */
6582
      if (!is_dependent_type
6583
          && check_instantiated_args (gen_tmpl,
6584
                                      INNERMOST_TEMPLATE_ARGS (arglist),
6585
                                      complain))
6586
        POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6587
 
6588
      if (!is_dependent_type
6589
          && !PRIMARY_TEMPLATE_P (gen_tmpl)
6590
          && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6591
          && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6592
        {
6593
          found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6594
                                      DECL_NAME (gen_tmpl),
6595
                                      /*tag_scope=*/ts_global);
6596
          POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6597
        }
6598
 
6599
      context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6600
                        complain, in_decl);
6601
      if (!context)
6602
        context = global_namespace;
6603
 
6604
      /* Create the type.  */
6605
      if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6606
        {
6607
          if (!is_dependent_type)
6608
            {
6609
              set_current_access_from_decl (TYPE_NAME (template_type));
6610
              t = start_enum (TYPE_IDENTIFIER (template_type),
6611
                              tsubst (ENUM_UNDERLYING_TYPE (template_type),
6612
                                      arglist, complain, in_decl),
6613
                              SCOPED_ENUM_P (template_type));
6614
            }
6615
          else
6616
            {
6617
              /* We don't want to call start_enum for this type, since
6618
                 the values for the enumeration constants may involve
6619
                 template parameters.  And, no one should be interested
6620
                 in the enumeration constants for such a type.  */
6621
              t = cxx_make_type (ENUMERAL_TYPE);
6622
              SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6623
            }
6624
        }
6625
      else
6626
        {
6627
          t = make_class_type (TREE_CODE (template_type));
6628
          CLASSTYPE_DECLARED_CLASS (t)
6629
            = CLASSTYPE_DECLARED_CLASS (template_type);
6630
          SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6631
          TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6632
 
6633
          /* A local class.  Make sure the decl gets registered properly.  */
6634
          if (context == current_function_decl)
6635
            pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6636
 
6637
          if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6638
            /* This instantiation is another name for the primary
6639
               template type. Set the TYPE_CANONICAL field
6640
               appropriately. */
6641
            TYPE_CANONICAL (t) = template_type;
6642
          else if (any_template_arguments_need_structural_equality_p (arglist))
6643
            /* Some of the template arguments require structural
6644
               equality testing, so this template class requires
6645
               structural equality testing. */
6646
            SET_TYPE_STRUCTURAL_EQUALITY (t);
6647
        }
6648
 
6649
      /* If we called start_enum or pushtag above, this information
6650
         will already be set up.  */
6651
      if (!TYPE_NAME (t))
6652
        {
6653
          TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6654
 
6655
          type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6656
          DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6657
          DECL_SOURCE_LOCATION (type_decl)
6658
            = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6659
        }
6660
      else
6661
        type_decl = TYPE_NAME (t);
6662
 
6663
      TREE_PRIVATE (type_decl)
6664
        = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6665
      TREE_PROTECTED (type_decl)
6666
        = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6667
      if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6668
        {
6669
          DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6670
          DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6671
        }
6672
 
6673
      /* Let's consider the explicit specialization of a member
6674
         of a class template specialization that is implicitely instantiated,
6675
         e.g.:
6676
             template<class T>
6677
             struct S
6678
             {
6679
               template<class U> struct M {}; //#0
6680
             };
6681
 
6682
             template<>
6683
             template<>
6684
             struct S<int>::M<char> //#1
6685
             {
6686
               int i;
6687
             };
6688
        [temp.expl.spec]/4 says this is valid.
6689
 
6690
        In this case, when we write:
6691
        S<int>::M<char> m;
6692
 
6693
        M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6694
        the one of #0.
6695
 
6696
        When we encounter #1, we want to store the partial instantiation
6697
        of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6698
 
6699
        For all cases other than this "explicit specialization of member of a
6700
        class template", we just want to store the most general template into
6701
        the CLASSTYPE_TI_TEMPLATE of M.
6702
 
6703
        This case of "explicit specialization of member of a class template"
6704
        only happens when:
6705
        1/ the enclosing class is an instantiation of, and therefore not
6706
        the same as, the context of the most general template, and
6707
        2/ we aren't looking at the partial instantiation itself, i.e.
6708
        the innermost arguments are not the same as the innermost parms of
6709
        the most general template.
6710
 
6711
        So it's only when 1/ and 2/ happens that we want to use the partial
6712
        instantiation of the member template in lieu of its most general
6713
        template.  */
6714
 
6715
      if (PRIMARY_TEMPLATE_P (gen_tmpl)
6716
          && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6717
          /* the enclosing class must be an instantiation...  */
6718
          && CLASS_TYPE_P (context)
6719
          && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6720
        {
6721
          tree partial_inst_args;
6722
          TREE_VEC_LENGTH (arglist)--;
6723
          ++processing_template_decl;
6724
          partial_inst_args =
6725
            tsubst (INNERMOST_TEMPLATE_ARGS
6726
                        (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6727
                    arglist, complain, NULL_TREE);
6728
          --processing_template_decl;
6729
          TREE_VEC_LENGTH (arglist)++;
6730
          use_partial_inst_tmpl =
6731
            /*...and we must not be looking at the partial instantiation
6732
             itself. */
6733
            !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6734
                                 partial_inst_args);
6735
        }
6736
 
6737
      if (!use_partial_inst_tmpl)
6738
        /* This case is easy; there are no member templates involved.  */
6739
        found = gen_tmpl;
6740
      else
6741
        {
6742
          /* This is a full instantiation of a member template.  Find
6743
             the partial instantiation of which this is an instance.  */
6744
 
6745
          /* Temporarily reduce by one the number of levels in the ARGLIST
6746
             so as to avoid comparing the last set of arguments.  */
6747
          TREE_VEC_LENGTH (arglist)--;
6748
          found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6749
          TREE_VEC_LENGTH (arglist)++;
6750
          found = CLASSTYPE_TI_TEMPLATE (found);
6751
        }
6752
 
6753
      SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6754
 
6755
      elt.spec = t;
6756
      slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6757
                                                       &elt, hash, INSERT);
6758
      *slot = GGC_NEW (spec_entry);
6759
      **slot = elt;
6760
 
6761
      /* Note this use of the partial instantiation so we can check it
6762
         later in maybe_process_partial_specialization.  */
6763
      DECL_TEMPLATE_INSTANTIATIONS (templ)
6764
        = tree_cons (arglist, t,
6765
                     DECL_TEMPLATE_INSTANTIATIONS (templ));
6766
 
6767
      if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6768
        /* Now that the type has been registered on the instantiations
6769
           list, we set up the enumerators.  Because the enumeration
6770
           constants may involve the enumeration type itself, we make
6771
           sure to register the type first, and then create the
6772
           constants.  That way, doing tsubst_expr for the enumeration
6773
           constants won't result in recursive calls here; we'll find
6774
           the instantiation and exit above.  */
6775
        tsubst_enum (template_type, t, arglist);
6776
 
6777
      if (is_dependent_type)
6778
        /* If the type makes use of template parameters, the
6779
           code that generates debugging information will crash.  */
6780
        DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6781
 
6782
      /* Possibly limit visibility based on template args.  */
6783
      TREE_PUBLIC (type_decl) = 1;
6784
      determine_visibility (type_decl);
6785
 
6786
      POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6787
    }
6788
  timevar_pop (TV_NAME_LOOKUP);
6789
}
6790
 
6791
struct pair_fn_data
6792
{
6793
  tree_fn_t fn;
6794
  void *data;
6795
  /* True when we should also visit template parameters that occur in
6796
     non-deduced contexts.  */
6797
  bool include_nondeduced_p;
6798
  struct pointer_set_t *visited;
6799
};
6800
 
6801
/* Called from for_each_template_parm via walk_tree.  */
6802
 
6803
static tree
6804
for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6805
{
6806
  tree t = *tp;
6807
  struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6808
  tree_fn_t fn = pfd->fn;
6809
  void *data = pfd->data;
6810
 
6811
  if (TYPE_P (t)
6812
      && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6813
      && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6814
                                 pfd->include_nondeduced_p))
6815
    return error_mark_node;
6816
 
6817
  switch (TREE_CODE (t))
6818
    {
6819
    case RECORD_TYPE:
6820
      if (TYPE_PTRMEMFUNC_P (t))
6821
        break;
6822
      /* Fall through.  */
6823
 
6824
    case UNION_TYPE:
6825
    case ENUMERAL_TYPE:
6826
      if (!TYPE_TEMPLATE_INFO (t))
6827
        *walk_subtrees = 0;
6828
      else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6829
                                       fn, data, pfd->visited,
6830
                                       pfd->include_nondeduced_p))
6831
        return error_mark_node;
6832
      break;
6833
 
6834
    case INTEGER_TYPE:
6835
      if (for_each_template_parm (TYPE_MIN_VALUE (t),
6836
                                  fn, data, pfd->visited,
6837
                                  pfd->include_nondeduced_p)
6838
          || for_each_template_parm (TYPE_MAX_VALUE (t),
6839
                                     fn, data, pfd->visited,
6840
                                     pfd->include_nondeduced_p))
6841
        return error_mark_node;
6842
      break;
6843
 
6844
    case METHOD_TYPE:
6845
      /* Since we're not going to walk subtrees, we have to do this
6846
         explicitly here.  */
6847
      if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6848
                                  pfd->visited, pfd->include_nondeduced_p))
6849
        return error_mark_node;
6850
      /* Fall through.  */
6851
 
6852
    case FUNCTION_TYPE:
6853
      /* Check the return type.  */
6854
      if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6855
                                  pfd->include_nondeduced_p))
6856
        return error_mark_node;
6857
 
6858
      /* Check the parameter types.  Since default arguments are not
6859
         instantiated until they are needed, the TYPE_ARG_TYPES may
6860
         contain expressions that involve template parameters.  But,
6861
         no-one should be looking at them yet.  And, once they're
6862
         instantiated, they don't contain template parameters, so
6863
         there's no point in looking at them then, either.  */
6864
      {
6865
        tree parm;
6866
 
6867
        for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6868
          if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6869
                                      pfd->visited, pfd->include_nondeduced_p))
6870
            return error_mark_node;
6871
 
6872
        /* Since we've already handled the TYPE_ARG_TYPES, we don't
6873
           want walk_tree walking into them itself.  */
6874
        *walk_subtrees = 0;
6875
      }
6876
      break;
6877
 
6878
    case TYPEOF_TYPE:
6879
      if (pfd->include_nondeduced_p
6880
          && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6881
                                     pfd->visited,
6882
                                     pfd->include_nondeduced_p))
6883
        return error_mark_node;
6884
      break;
6885
 
6886
    case FUNCTION_DECL:
6887
    case VAR_DECL:
6888
      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6889
          && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6890
                                     pfd->visited, pfd->include_nondeduced_p))
6891
        return error_mark_node;
6892
      /* Fall through.  */
6893
 
6894
    case PARM_DECL:
6895
    case CONST_DECL:
6896
      if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6897
          && for_each_template_parm (DECL_INITIAL (t), fn, data,
6898
                                     pfd->visited, pfd->include_nondeduced_p))
6899
        return error_mark_node;
6900
      if (DECL_CONTEXT (t)
6901
          && pfd->include_nondeduced_p
6902
          && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6903
                                     pfd->visited, pfd->include_nondeduced_p))
6904
        return error_mark_node;
6905
      break;
6906
 
6907
    case BOUND_TEMPLATE_TEMPLATE_PARM:
6908
      /* Record template parameters such as `T' inside `TT<T>'.  */
6909
      if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6910
                                  pfd->include_nondeduced_p))
6911
        return error_mark_node;
6912
      /* Fall through.  */
6913
 
6914
    case TEMPLATE_TEMPLATE_PARM:
6915
    case TEMPLATE_TYPE_PARM:
6916
    case TEMPLATE_PARM_INDEX:
6917
      if (fn && (*fn)(t, data))
6918
        return error_mark_node;
6919
      else if (!fn)
6920
        return error_mark_node;
6921
      break;
6922
 
6923
    case TEMPLATE_DECL:
6924
      /* A template template parameter is encountered.  */
6925
      if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6926
          && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6927
                                     pfd->include_nondeduced_p))
6928
        return error_mark_node;
6929
 
6930
      /* Already substituted template template parameter */
6931
      *walk_subtrees = 0;
6932
      break;
6933
 
6934
    case TYPENAME_TYPE:
6935
      if (!fn
6936
          || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6937
                                     data, pfd->visited,
6938
                                     pfd->include_nondeduced_p))
6939
        return error_mark_node;
6940
      break;
6941
 
6942
    case CONSTRUCTOR:
6943
      if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6944
          && pfd->include_nondeduced_p
6945
          && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6946
                                     (TREE_TYPE (t)), fn, data,
6947
                                     pfd->visited, pfd->include_nondeduced_p))
6948
        return error_mark_node;
6949
      break;
6950
 
6951
    case INDIRECT_REF:
6952
    case COMPONENT_REF:
6953
      /* If there's no type, then this thing must be some expression
6954
         involving template parameters.  */
6955
      if (!fn && !TREE_TYPE (t))
6956
        return error_mark_node;
6957
      break;
6958
 
6959
    case MODOP_EXPR:
6960
    case CAST_EXPR:
6961
    case REINTERPRET_CAST_EXPR:
6962
    case CONST_CAST_EXPR:
6963
    case STATIC_CAST_EXPR:
6964
    case DYNAMIC_CAST_EXPR:
6965
    case ARROW_EXPR:
6966
    case DOTSTAR_EXPR:
6967
    case TYPEID_EXPR:
6968
    case PSEUDO_DTOR_EXPR:
6969
      if (!fn)
6970
        return error_mark_node;
6971
      break;
6972
 
6973
    default:
6974
      break;
6975
    }
6976
 
6977
  /* We didn't find any template parameters we liked.  */
6978
  return NULL_TREE;
6979
}
6980
 
6981
/* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6982
   BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6983
   call FN with the parameter and the DATA.
6984
   If FN returns nonzero, the iteration is terminated, and
6985
   for_each_template_parm returns 1.  Otherwise, the iteration
6986
   continues.  If FN never returns a nonzero value, the value
6987
   returned by for_each_template_parm is 0.  If FN is NULL, it is
6988
   considered to be the function which always returns 1.
6989
 
6990
   If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6991
   parameters that occur in non-deduced contexts.  When false, only
6992
   visits those template parameters that can be deduced.  */
6993
 
6994
static int
6995
for_each_template_parm (tree t, tree_fn_t fn, void* data,
6996
                        struct pointer_set_t *visited,
6997
                        bool include_nondeduced_p)
6998
{
6999
  struct pair_fn_data pfd;
7000
  int result;
7001
 
7002
  /* Set up.  */
7003
  pfd.fn = fn;
7004
  pfd.data = data;
7005
  pfd.include_nondeduced_p = include_nondeduced_p;
7006
 
7007
  /* Walk the tree.  (Conceptually, we would like to walk without
7008
     duplicates, but for_each_template_parm_r recursively calls
7009
     for_each_template_parm, so we would need to reorganize a fair
7010
     bit to use walk_tree_without_duplicates, so we keep our own
7011
     visited list.)  */
7012
  if (visited)
7013
    pfd.visited = visited;
7014
  else
7015
    pfd.visited = pointer_set_create ();
7016
  result = cp_walk_tree (&t,
7017
                         for_each_template_parm_r,
7018
                         &pfd,
7019
                         pfd.visited) != NULL_TREE;
7020
 
7021
  /* Clean up.  */
7022
  if (!visited)
7023
    {
7024
      pointer_set_destroy (pfd.visited);
7025
      pfd.visited = 0;
7026
    }
7027
 
7028
  return result;
7029
}
7030
 
7031
/* Returns true if T depends on any template parameter.  */
7032
 
7033
int
7034
uses_template_parms (tree t)
7035
{
7036
  bool dependent_p;
7037
  int saved_processing_template_decl;
7038
 
7039
  saved_processing_template_decl = processing_template_decl;
7040
  if (!saved_processing_template_decl)
7041
    processing_template_decl = 1;
7042
  if (TYPE_P (t))
7043
    dependent_p = dependent_type_p (t);
7044
  else if (TREE_CODE (t) == TREE_VEC)
7045
    dependent_p = any_dependent_template_arguments_p (t);
7046
  else if (TREE_CODE (t) == TREE_LIST)
7047
    dependent_p = (uses_template_parms (TREE_VALUE (t))
7048
                   || uses_template_parms (TREE_CHAIN (t)));
7049
  else if (TREE_CODE (t) == TYPE_DECL)
7050
    dependent_p = dependent_type_p (TREE_TYPE (t));
7051
  else if (DECL_P (t)
7052
           || EXPR_P (t)
7053
           || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7054
           || TREE_CODE (t) == OVERLOAD
7055
           || TREE_CODE (t) == BASELINK
7056
           || TREE_CODE (t) == IDENTIFIER_NODE
7057
           || TREE_CODE (t) == TRAIT_EXPR
7058
           || TREE_CODE (t) == CONSTRUCTOR
7059
           || CONSTANT_CLASS_P (t))
7060
    dependent_p = (type_dependent_expression_p (t)
7061
                   || value_dependent_expression_p (t));
7062
  else
7063
    {
7064
      gcc_assert (t == error_mark_node);
7065
      dependent_p = false;
7066
    }
7067
 
7068
  processing_template_decl = saved_processing_template_decl;
7069
 
7070
  return dependent_p;
7071
}
7072
 
7073
/* Returns true if T depends on any template parameter with level LEVEL.  */
7074
 
7075
int
7076
uses_template_parms_level (tree t, int level)
7077
{
7078
  return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7079
                                 /*include_nondeduced_p=*/true);
7080
}
7081
 
7082
static int tinst_depth;
7083
extern int max_tinst_depth;
7084
#ifdef GATHER_STATISTICS
7085
int depth_reached;
7086
#endif
7087
static int tinst_level_tick;
7088
static int last_template_error_tick;
7089
 
7090
/* We're starting to instantiate D; record the template instantiation context
7091
   for diagnostics and to restore it later.  */
7092
 
7093
int
7094
push_tinst_level (tree d)
7095
{
7096
  struct tinst_level *new_level;
7097
 
7098
  if (tinst_depth >= max_tinst_depth)
7099
    {
7100
      /* If the instantiation in question still has unbound template parms,
7101
         we don't really care if we can't instantiate it, so just return.
7102
         This happens with base instantiation for implicit `typename'.  */
7103
      if (uses_template_parms (d))
7104
        return 0;
7105
 
7106
      last_template_error_tick = tinst_level_tick;
7107
      error ("template instantiation depth exceeds maximum of %d (use "
7108
             "-ftemplate-depth= to increase the maximum) instantiating %qD",
7109
             max_tinst_depth, d);
7110
 
7111
      print_instantiation_context ();
7112
 
7113
      return 0;
7114
    }
7115
 
7116
  new_level = GGC_NEW (struct tinst_level);
7117
  new_level->decl = d;
7118
  new_level->locus = input_location;
7119
  new_level->in_system_header_p = in_system_header;
7120
  new_level->next = current_tinst_level;
7121
  current_tinst_level = new_level;
7122
 
7123
  ++tinst_depth;
7124
#ifdef GATHER_STATISTICS
7125
  if (tinst_depth > depth_reached)
7126
    depth_reached = tinst_depth;
7127
#endif
7128
 
7129
  ++tinst_level_tick;
7130
  return 1;
7131
}
7132
 
7133
/* We're done instantiating this template; return to the instantiation
7134
   context.  */
7135
 
7136
void
7137
pop_tinst_level (void)
7138
{
7139
  /* Restore the filename and line number stashed away when we started
7140
     this instantiation.  */
7141
  input_location = current_tinst_level->locus;
7142
  current_tinst_level = current_tinst_level->next;
7143
  --tinst_depth;
7144
  ++tinst_level_tick;
7145
}
7146
 
7147
/* We're instantiating a deferred template; restore the template
7148
   instantiation context in which the instantiation was requested, which
7149
   is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7150
 
7151
static tree
7152
reopen_tinst_level (struct tinst_level *level)
7153
{
7154
  struct tinst_level *t;
7155
 
7156
  tinst_depth = 0;
7157
  for (t = level; t; t = t->next)
7158
    ++tinst_depth;
7159
 
7160
  current_tinst_level = level;
7161
  pop_tinst_level ();
7162
  return level->decl;
7163
}
7164
 
7165
/* Returns the TINST_LEVEL which gives the original instantiation
7166
   context.  */
7167
 
7168
struct tinst_level *
7169
outermost_tinst_level (void)
7170
{
7171
  struct tinst_level *level = current_tinst_level;
7172
  if (level)
7173
    while (level->next)
7174
      level = level->next;
7175
  return level;
7176
}
7177
 
7178
/* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7179
 
7180
bool
7181
parameter_of_template_p (tree parm, tree templ)
7182
{
7183
  tree parms;
7184
  int i;
7185
 
7186
  if (!parm || !templ)
7187
    return false;
7188
 
7189
  gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7190
  gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7191
 
7192
  parms = DECL_TEMPLATE_PARMS (templ);
7193
  parms = INNERMOST_TEMPLATE_PARMS (parms);
7194
 
7195
  for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7196
    if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7197
      return true;
7198
 
7199
  return false;
7200
}
7201
 
7202
/* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7203
   vector of template arguments, as for tsubst.
7204
 
7205
   Returns an appropriate tsubst'd friend declaration.  */
7206
 
7207
static tree
7208
tsubst_friend_function (tree decl, tree args)
7209
{
7210
  tree new_friend;
7211
 
7212
  if (TREE_CODE (decl) == FUNCTION_DECL
7213
      && DECL_TEMPLATE_INSTANTIATION (decl)
7214
      && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7215
    /* This was a friend declared with an explicit template
7216
       argument list, e.g.:
7217
 
7218
       friend void f<>(T);
7219
 
7220
       to indicate that f was a template instantiation, not a new
7221
       function declaration.  Now, we have to figure out what
7222
       instantiation of what template.  */
7223
    {
7224
      tree template_id, arglist, fns;
7225
      tree new_args;
7226
      tree tmpl;
7227
      tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7228
 
7229
      /* Friend functions are looked up in the containing namespace scope.
7230
         We must enter that scope, to avoid finding member functions of the
7231
         current class with same name.  */
7232
      push_nested_namespace (ns);
7233
      fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7234
                         tf_warning_or_error, NULL_TREE,
7235
                         /*integral_constant_expression_p=*/false);
7236
      pop_nested_namespace (ns);
7237
      arglist = tsubst (DECL_TI_ARGS (decl), args,
7238
                        tf_warning_or_error, NULL_TREE);
7239
      template_id = lookup_template_function (fns, arglist);
7240
 
7241
      new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7242
      tmpl = determine_specialization (template_id, new_friend,
7243
                                       &new_args,
7244
                                       /*need_member_template=*/0,
7245
                                       TREE_VEC_LENGTH (args),
7246
                                       tsk_none);
7247
      return instantiate_template (tmpl, new_args, tf_error);
7248
    }
7249
 
7250
  new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7251
 
7252
  /* The NEW_FRIEND will look like an instantiation, to the
7253
     compiler, but is not an instantiation from the point of view of
7254
     the language.  For example, we might have had:
7255
 
7256
     template <class T> struct S {
7257
       template <class U> friend void f(T, U);
7258
     };
7259
 
7260
     Then, in S<int>, template <class U> void f(int, U) is not an
7261
     instantiation of anything.  */
7262
  if (new_friend == error_mark_node)
7263
    return error_mark_node;
7264
 
7265
  DECL_USE_TEMPLATE (new_friend) = 0;
7266
  if (TREE_CODE (decl) == TEMPLATE_DECL)
7267
    {
7268
      DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7269
      DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7270
        = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7271
    }
7272
 
7273
  /* The mangled name for the NEW_FRIEND is incorrect.  The function
7274
     is not a template instantiation and should not be mangled like
7275
     one.  Therefore, we forget the mangling here; we'll recompute it
7276
     later if we need it.  */
7277
  if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7278
    {
7279
      SET_DECL_RTL (new_friend, NULL_RTX);
7280
      SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7281
    }
7282
 
7283
  if (DECL_NAMESPACE_SCOPE_P (new_friend))
7284
    {
7285
      tree old_decl;
7286
      tree new_friend_template_info;
7287
      tree new_friend_result_template_info;
7288
      tree ns;
7289
      int  new_friend_is_defn;
7290
 
7291
      /* We must save some information from NEW_FRIEND before calling
7292
         duplicate decls since that function will free NEW_FRIEND if
7293
         possible.  */
7294
      new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7295
      new_friend_is_defn =
7296
            (DECL_INITIAL (DECL_TEMPLATE_RESULT
7297
                           (template_for_substitution (new_friend)))
7298
             != NULL_TREE);
7299
      if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7300
        {
7301
          /* This declaration is a `primary' template.  */
7302
          DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7303
 
7304
          new_friend_result_template_info
7305
            = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7306
        }
7307
      else
7308
        new_friend_result_template_info = NULL_TREE;
7309
 
7310
      /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7311
      if (new_friend_is_defn)
7312
        DECL_INITIAL (new_friend) = error_mark_node;
7313
 
7314
      /* Inside pushdecl_namespace_level, we will push into the
7315
         current namespace. However, the friend function should go
7316
         into the namespace of the template.  */
7317
      ns = decl_namespace_context (new_friend);
7318
      push_nested_namespace (ns);
7319
      old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7320
      pop_nested_namespace (ns);
7321
 
7322
      if (old_decl == error_mark_node)
7323
        return error_mark_node;
7324
 
7325
      if (old_decl != new_friend)
7326
        {
7327
          /* This new friend declaration matched an existing
7328
             declaration.  For example, given:
7329
 
7330
               template <class T> void f(T);
7331
               template <class U> class C {
7332
                 template <class T> friend void f(T) {}
7333
               };
7334
 
7335
             the friend declaration actually provides the definition
7336
             of `f', once C has been instantiated for some type.  So,
7337
             old_decl will be the out-of-class template declaration,
7338
             while new_friend is the in-class definition.
7339
 
7340
             But, if `f' was called before this point, the
7341
             instantiation of `f' will have DECL_TI_ARGS corresponding
7342
             to `T' but not to `U', references to which might appear
7343
             in the definition of `f'.  Previously, the most general
7344
             template for an instantiation of `f' was the out-of-class
7345
             version; now it is the in-class version.  Therefore, we
7346
             run through all specialization of `f', adding to their
7347
             DECL_TI_ARGS appropriately.  In particular, they need a
7348
             new set of outer arguments, corresponding to the
7349
             arguments for this class instantiation.
7350
 
7351
             The same situation can arise with something like this:
7352
 
7353
               friend void f(int);
7354
               template <class T> class C {
7355
                 friend void f(T) {}
7356
               };
7357
 
7358
             when `C<int>' is instantiated.  Now, `f(int)' is defined
7359
             in the class.  */
7360
 
7361
          if (!new_friend_is_defn)
7362
            /* On the other hand, if the in-class declaration does
7363
               *not* provide a definition, then we don't want to alter
7364
               existing definitions.  We can just leave everything
7365
               alone.  */
7366
            ;
7367
          else
7368
            {
7369
              tree new_template = TI_TEMPLATE (new_friend_template_info);
7370
              tree new_args = TI_ARGS (new_friend_template_info);
7371
 
7372
              /* Overwrite whatever template info was there before, if
7373
                 any, with the new template information pertaining to
7374
                 the declaration.  */
7375
              DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7376
 
7377
              if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7378
                /* We should have called reregister_specialization in
7379
                   duplicate_decls.  */
7380
                gcc_assert (retrieve_specialization (new_template,
7381
                                                     new_args, 0)
7382
                            == old_decl);
7383
              else
7384
                {
7385
                  tree t;
7386
 
7387
                  /* Indicate that the old function template is a partial
7388
                     instantiation.  */
7389
                  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7390
                    = new_friend_result_template_info;
7391
 
7392
                  gcc_assert (new_template
7393
                              == most_general_template (new_template));
7394
                  gcc_assert (new_template != old_decl);
7395
 
7396
                  /* Reassign any specializations already in the hash table
7397
                     to the new more general template, and add the
7398
                     additional template args.  */
7399
                  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7400
                       t != NULL_TREE;
7401
                       t = TREE_CHAIN (t))
7402
                    {
7403
                      tree spec = TREE_VALUE (t);
7404
                      spec_entry elt;
7405
 
7406
                      elt.tmpl = old_decl;
7407
                      elt.args = DECL_TI_ARGS (spec);
7408
                      elt.spec = NULL_TREE;
7409
 
7410
                      htab_remove_elt (decl_specializations, &elt);
7411
 
7412
                      DECL_TI_ARGS (spec)
7413
                        = add_outermost_template_args (new_args,
7414
                                                       DECL_TI_ARGS (spec));
7415
 
7416
                      register_specialization
7417
                        (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7418
 
7419
                    }
7420
                  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7421
                }
7422
            }
7423
 
7424
          /* The information from NEW_FRIEND has been merged into OLD_DECL
7425
             by duplicate_decls.  */
7426
          new_friend = old_decl;
7427
        }
7428
    }
7429
  else
7430
    {
7431
      tree context = DECL_CONTEXT (new_friend);
7432
      bool dependent_p;
7433
 
7434
      /* In the code
7435
           template <class T> class C {
7436
             template <class U> friend void C1<U>::f (); // case 1
7437
             friend void C2<T>::f ();                    // case 2
7438
           };
7439
         we only need to make sure CONTEXT is a complete type for
7440
         case 2.  To distinguish between the two cases, we note that
7441
         CONTEXT of case 1 remains dependent type after tsubst while
7442
         this isn't true for case 2.  */
7443
      ++processing_template_decl;
7444
      dependent_p = dependent_type_p (context);
7445
      --processing_template_decl;
7446
 
7447
      if (!dependent_p
7448
          && !complete_type_or_else (context, NULL_TREE))
7449
        return error_mark_node;
7450
 
7451
      if (COMPLETE_TYPE_P (context))
7452
        {
7453
          /* Check to see that the declaration is really present, and,
7454
             possibly obtain an improved declaration.  */
7455
          tree fn = check_classfn (context,
7456
                                   new_friend, NULL_TREE);
7457
 
7458
          if (fn)
7459
            new_friend = fn;
7460
        }
7461
    }
7462
 
7463
  return new_friend;
7464
}
7465
 
7466
/* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7467
   template arguments, as for tsubst.
7468
 
7469
   Returns an appropriate tsubst'd friend type or error_mark_node on
7470
   failure.  */
7471
 
7472
static tree
7473
tsubst_friend_class (tree friend_tmpl, tree args)
7474
{
7475
  tree friend_type;
7476
  tree tmpl;
7477
  tree context;
7478
 
7479
  context = DECL_CONTEXT (friend_tmpl);
7480
 
7481
  if (context)
7482
    {
7483
      if (TREE_CODE (context) == NAMESPACE_DECL)
7484
        push_nested_namespace (context);
7485
      else
7486
        push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7487
    }
7488
 
7489
  /* Look for a class template declaration.  We look for hidden names
7490
     because two friend declarations of the same template are the
7491
     same.  For example, in:
7492
 
7493
       struct A {
7494
         template <typename> friend class F;
7495
       };
7496
       template <typename> struct B {
7497
         template <typename> friend class F;
7498
       };
7499
 
7500
     both F templates are the same.  */
7501
  tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7502
                           /*block_p=*/true, 0,
7503
                           LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7504
 
7505
  /* But, if we don't find one, it might be because we're in a
7506
     situation like this:
7507
 
7508
       template <class T>
7509
       struct S {
7510
         template <class U>
7511
         friend struct S;
7512
       };
7513
 
7514
     Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7515
     for `S<int>', not the TEMPLATE_DECL.  */
7516
  if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7517
    {
7518
      tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7519
      tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7520
    }
7521
 
7522
  if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7523
    {
7524
      /* The friend template has already been declared.  Just
7525
         check to see that the declarations match, and install any new
7526
         default parameters.  We must tsubst the default parameters,
7527
         of course.  We only need the innermost template parameters
7528
         because that is all that redeclare_class_template will look
7529
         at.  */
7530
      if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7531
          > TMPL_ARGS_DEPTH (args))
7532
        {
7533
          tree parms;
7534
          location_t saved_input_location;
7535
          parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7536
                                         args, tf_warning_or_error);
7537
 
7538
          saved_input_location = input_location;
7539
          input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7540
          redeclare_class_template (TREE_TYPE (tmpl), parms);
7541
          input_location = saved_input_location;
7542
 
7543
        }
7544
 
7545
      friend_type = TREE_TYPE (tmpl);
7546
    }
7547
  else
7548
    {
7549
      /* The friend template has not already been declared.  In this
7550
         case, the instantiation of the template class will cause the
7551
         injection of this template into the global scope.  */
7552
      tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7553
      if (tmpl == error_mark_node)
7554
        return error_mark_node;
7555
 
7556
      /* The new TMPL is not an instantiation of anything, so we
7557
         forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7558
         the new type because that is supposed to be the corresponding
7559
         template decl, i.e., TMPL.  */
7560
      DECL_USE_TEMPLATE (tmpl) = 0;
7561
      DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7562
      CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7563
      CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7564
        = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7565
 
7566
      /* Inject this template into the global scope.  */
7567
      friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7568
    }
7569
 
7570
  if (context)
7571
    {
7572
      if (TREE_CODE (context) == NAMESPACE_DECL)
7573
        pop_nested_namespace (context);
7574
      else
7575
        pop_nested_class ();
7576
    }
7577
 
7578
  return friend_type;
7579
}
7580
 
7581
/* Returns zero if TYPE cannot be completed later due to circularity.
7582
   Otherwise returns one.  */
7583
 
7584
static int
7585
can_complete_type_without_circularity (tree type)
7586
{
7587
  if (type == NULL_TREE || type == error_mark_node)
7588
    return 0;
7589
  else if (COMPLETE_TYPE_P (type))
7590
    return 1;
7591
  else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7592
    return can_complete_type_without_circularity (TREE_TYPE (type));
7593
  else if (CLASS_TYPE_P (type)
7594
           && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7595
    return 0;
7596
  else
7597
    return 1;
7598
}
7599
 
7600
/* Apply any attributes which had to be deferred until instantiation
7601
   time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7602
   ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7603
 
7604
static void
7605
apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7606
                                tree args, tsubst_flags_t complain, tree in_decl)
7607
{
7608
  tree last_dep = NULL_TREE;
7609
  tree t;
7610
  tree *p;
7611
 
7612
  for (t = attributes; t; t = TREE_CHAIN (t))
7613
    if (ATTR_IS_DEPENDENT (t))
7614
      {
7615
        last_dep = t;
7616
        attributes = copy_list (attributes);
7617
        break;
7618
      }
7619
 
7620
  if (DECL_P (*decl_p))
7621
    {
7622
      if (TREE_TYPE (*decl_p) == error_mark_node)
7623
        return;
7624
      p = &DECL_ATTRIBUTES (*decl_p);
7625
    }
7626
  else
7627
    p = &TYPE_ATTRIBUTES (*decl_p);
7628
 
7629
  if (last_dep)
7630
    {
7631
      tree late_attrs = NULL_TREE;
7632
      tree *q = &late_attrs;
7633
 
7634
      for (*p = attributes; *p; )
7635
        {
7636
          t = *p;
7637
          if (ATTR_IS_DEPENDENT (t))
7638
            {
7639
              *p = TREE_CHAIN (t);
7640
              TREE_CHAIN (t) = NULL_TREE;
7641
              /* If the first attribute argument is an identifier, don't
7642
                 pass it through tsubst.  Attributes like mode, format,
7643
                 cleanup and several target specific attributes expect it
7644
                 unmodified.  */
7645
              if (TREE_VALUE (t)
7646
                  && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7647
                  && TREE_VALUE (TREE_VALUE (t))
7648
                  && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7649
                      == IDENTIFIER_NODE))
7650
                {
7651
                  tree chain
7652
                    = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7653
                                   in_decl,
7654
                                   /*integral_constant_expression_p=*/false);
7655
                  if (chain != TREE_CHAIN (TREE_VALUE (t)))
7656
                    TREE_VALUE (t)
7657
                      = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7658
                                   chain);
7659
                }
7660
              else
7661
                TREE_VALUE (t)
7662
                  = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7663
                                 /*integral_constant_expression_p=*/false);
7664
              *q = t;
7665
              q = &TREE_CHAIN (t);
7666
            }
7667
          else
7668
            p = &TREE_CHAIN (t);
7669
        }
7670
 
7671
      cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7672
    }
7673
}
7674
 
7675
/* Perform (or defer) access check for typedefs that were referenced
7676
   from within the template TMPL code.
7677
   This is a subroutine of instantiate_template and instantiate_class_template.
7678
   TMPL is the template to consider and TARGS is the list of arguments of
7679
   that template.  */
7680
 
7681
static void
7682
perform_typedefs_access_check (tree tmpl, tree targs)
7683
{
7684
  location_t saved_location;
7685
  int i;
7686
  qualified_typedef_usage_t *iter;
7687
 
7688
  if (!tmpl
7689
      || (!CLASS_TYPE_P (tmpl)
7690
          && TREE_CODE (tmpl) != FUNCTION_DECL))
7691
    return;
7692
 
7693
  saved_location = input_location;
7694
  for (i = 0;
7695
       VEC_iterate (qualified_typedef_usage_t,
7696
                    get_types_needing_access_check (tmpl),
7697
                    i, iter);
7698
        ++i)
7699
    {
7700
      tree type_decl = iter->typedef_decl;
7701
      tree type_scope = iter->context;
7702
 
7703
      if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7704
        continue;
7705
 
7706
      if (uses_template_parms (type_decl))
7707
        type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7708
      if (uses_template_parms (type_scope))
7709
        type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7710
 
7711
      /* Make access check error messages point to the location
7712
         of the use of the typedef.  */
7713
      input_location = iter->locus;
7714
      perform_or_defer_access_check (TYPE_BINFO (type_scope),
7715
                                     type_decl, type_decl);
7716
    }
7717
    input_location = saved_location;
7718
}
7719
 
7720
tree
7721
instantiate_class_template (tree type)
7722
{
7723
  tree templ, args, pattern, t, member;
7724
  tree typedecl;
7725
  tree pbinfo;
7726
  tree base_list;
7727
  unsigned int saved_maximum_field_alignment;
7728
 
7729
  if (type == error_mark_node)
7730
    return error_mark_node;
7731
 
7732
  if (TYPE_BEING_DEFINED (type)
7733
      || COMPLETE_TYPE_P (type)
7734
      || uses_template_parms (type))
7735
    return type;
7736
 
7737
  /* Figure out which template is being instantiated.  */
7738
  templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7739
  gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7740
 
7741
  /* Determine what specialization of the original template to
7742
     instantiate.  */
7743
  t = most_specialized_class (type, templ);
7744
  if (t == error_mark_node)
7745
    {
7746
      TYPE_BEING_DEFINED (type) = 1;
7747
      return error_mark_node;
7748
    }
7749
  else if (t)
7750
    {
7751
      /* This TYPE is actually an instantiation of a partial
7752
         specialization.  We replace the innermost set of ARGS with
7753
         the arguments appropriate for substitution.  For example,
7754
         given:
7755
 
7756
           template <class T> struct S {};
7757
           template <class T> struct S<T*> {};
7758
 
7759
         and supposing that we are instantiating S<int*>, ARGS will
7760
         presently be {int*} -- but we need {int}.  */
7761
      pattern = TREE_TYPE (t);
7762
      args = TREE_PURPOSE (t);
7763
    }
7764
  else
7765
    {
7766
      pattern = TREE_TYPE (templ);
7767
      args = CLASSTYPE_TI_ARGS (type);
7768
    }
7769
 
7770
  /* If the template we're instantiating is incomplete, then clearly
7771
     there's nothing we can do.  */
7772
  if (!COMPLETE_TYPE_P (pattern))
7773
    return type;
7774
 
7775
  /* If we've recursively instantiated too many templates, stop.  */
7776
  if (! push_tinst_level (type))
7777
    return type;
7778
 
7779
  /* Now we're really doing the instantiation.  Mark the type as in
7780
     the process of being defined.  */
7781
  TYPE_BEING_DEFINED (type) = 1;
7782
 
7783
  /* We may be in the middle of deferred access check.  Disable
7784
     it now.  */
7785
  push_deferring_access_checks (dk_no_deferred);
7786
 
7787
  push_to_top_level ();
7788
  /* Use #pragma pack from the template context.  */
7789
  saved_maximum_field_alignment = maximum_field_alignment;
7790
  maximum_field_alignment = TYPE_PRECISION (pattern);
7791
 
7792
  SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7793
 
7794
  /* Set the input location to the most specialized template definition.
7795
     This is needed if tsubsting causes an error.  */
7796
  typedecl = TYPE_MAIN_DECL (pattern);
7797
  input_location = DECL_SOURCE_LOCATION (typedecl);
7798
 
7799
  TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7800
  TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7801
  TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7802
  TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7803
  TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7804
  TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7805
  TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7806
  TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7807
  TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7808
  TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7809
  TYPE_PACKED (type) = TYPE_PACKED (pattern);
7810
  TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7811
  TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7812
  TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7813
  if (ANON_AGGR_TYPE_P (pattern))
7814
    SET_ANON_AGGR_TYPE_P (type);
7815
  if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7816
    {
7817
      CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7818
      CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7819
    }
7820
 
7821
  pbinfo = TYPE_BINFO (pattern);
7822
 
7823
  /* We should never instantiate a nested class before its enclosing
7824
     class; we need to look up the nested class by name before we can
7825
     instantiate it, and that lookup should instantiate the enclosing
7826
     class.  */
7827
  gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7828
              || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7829
              || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7830
 
7831
  base_list = NULL_TREE;
7832
  if (BINFO_N_BASE_BINFOS (pbinfo))
7833
    {
7834
      tree pbase_binfo;
7835
      tree context = TYPE_CONTEXT (type);
7836
      tree pushed_scope;
7837
      int i;
7838
 
7839
      /* We must enter the scope containing the type, as that is where
7840
         the accessibility of types named in dependent bases are
7841
         looked up from.  */
7842
      pushed_scope = push_scope (context ? context : global_namespace);
7843
 
7844
      /* Substitute into each of the bases to determine the actual
7845
         basetypes.  */
7846
      for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7847
        {
7848
          tree base;
7849
          tree access = BINFO_BASE_ACCESS (pbinfo, i);
7850
          tree expanded_bases = NULL_TREE;
7851
          int idx, len = 1;
7852
 
7853
          if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7854
            {
7855
              expanded_bases =
7856
                tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7857
                                       args, tf_error, NULL_TREE);
7858
              if (expanded_bases == error_mark_node)
7859
                continue;
7860
 
7861
              len = TREE_VEC_LENGTH (expanded_bases);
7862
            }
7863
 
7864
          for (idx = 0; idx < len; idx++)
7865
            {
7866
              if (expanded_bases)
7867
                /* Extract the already-expanded base class.  */
7868
                base = TREE_VEC_ELT (expanded_bases, idx);
7869
              else
7870
                /* Substitute to figure out the base class.  */
7871
                base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
7872
                               NULL_TREE);
7873
 
7874
              if (base == error_mark_node)
7875
                continue;
7876
 
7877
              base_list = tree_cons (access, base, base_list);
7878
              if (BINFO_VIRTUAL_P (pbase_binfo))
7879
                TREE_TYPE (base_list) = integer_type_node;
7880
            }
7881
        }
7882
 
7883
      /* The list is now in reverse order; correct that.  */
7884
      base_list = nreverse (base_list);
7885
 
7886
      if (pushed_scope)
7887
        pop_scope (pushed_scope);
7888
    }
7889
  /* Now call xref_basetypes to set up all the base-class
7890
     information.  */
7891
  xref_basetypes (type, base_list);
7892
 
7893
  apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7894
                                  (int) ATTR_FLAG_TYPE_IN_PLACE,
7895
                                  args, tf_error, NULL_TREE);
7896
 
7897
  /* Now that our base classes are set up, enter the scope of the
7898
     class, so that name lookups into base classes, etc. will work
7899
     correctly.  This is precisely analogous to what we do in
7900
     begin_class_definition when defining an ordinary non-template
7901
     class, except we also need to push the enclosing classes.  */
7902
  push_nested_class (type);
7903
 
7904
  /* Now members are processed in the order of declaration.  */
7905
  for (member = CLASSTYPE_DECL_LIST (pattern);
7906
       member; member = TREE_CHAIN (member))
7907
    {
7908
      tree t = TREE_VALUE (member);
7909
 
7910
      if (TREE_PURPOSE (member))
7911
        {
7912
          if (TYPE_P (t))
7913
            {
7914
              /* Build new CLASSTYPE_NESTED_UTDS.  */
7915
 
7916
              tree newtag;
7917
              bool class_template_p;
7918
 
7919
              class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7920
                                  && TYPE_LANG_SPECIFIC (t)
7921
                                  && CLASSTYPE_IS_TEMPLATE (t));
7922
              /* If the member is a class template, then -- even after
7923
                 substitution -- there may be dependent types in the
7924
                 template argument list for the class.  We increment
7925
                 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7926
                 that function will assume that no types are dependent
7927
                 when outside of a template.  */
7928
              if (class_template_p)
7929
                ++processing_template_decl;
7930
              newtag = tsubst (t, args, tf_error, NULL_TREE);
7931
              if (class_template_p)
7932
                --processing_template_decl;
7933
              if (newtag == error_mark_node)
7934
                continue;
7935
 
7936
              if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7937
                {
7938
                  tree name = TYPE_IDENTIFIER (t);
7939
 
7940
                  if (class_template_p)
7941
                    /* Unfortunately, lookup_template_class sets
7942
                       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7943
                       instantiation (i.e., for the type of a member
7944
                       template class nested within a template class.)
7945
                       This behavior is required for
7946
                       maybe_process_partial_specialization to work
7947
                       correctly, but is not accurate in this case;
7948
                       the TAG is not an instantiation of anything.
7949
                       (The corresponding TEMPLATE_DECL is an
7950
                       instantiation, but the TYPE is not.) */
7951
                    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7952
 
7953
                  /* Now, we call pushtag to put this NEWTAG into the scope of
7954
                     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7955
                     pushtag calling push_template_decl.  We don't have to do
7956
                     this for enums because it will already have been done in
7957
                     tsubst_enum.  */
7958
                  if (name)
7959
                    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7960
                  pushtag (name, newtag, /*tag_scope=*/ts_current);
7961
                }
7962
            }
7963
          else if (TREE_CODE (t) == FUNCTION_DECL
7964
                   || DECL_FUNCTION_TEMPLATE_P (t))
7965
            {
7966
              /* Build new TYPE_METHODS.  */
7967
              tree r;
7968
 
7969
              if (TREE_CODE (t) == TEMPLATE_DECL)
7970
                ++processing_template_decl;
7971
              r = tsubst (t, args, tf_error, NULL_TREE);
7972
              if (TREE_CODE (t) == TEMPLATE_DECL)
7973
                --processing_template_decl;
7974
              set_current_access_from_decl (r);
7975
              finish_member_declaration (r);
7976
            }
7977
          else
7978
            {
7979
              /* Build new TYPE_FIELDS.  */
7980
              if (TREE_CODE (t) == STATIC_ASSERT)
7981
                {
7982
                  tree condition =
7983
                    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
7984
                                 tf_warning_or_error, NULL_TREE,
7985
                                 /*integral_constant_expression_p=*/true);
7986
                  finish_static_assert (condition,
7987
                                        STATIC_ASSERT_MESSAGE (t),
7988
                                        STATIC_ASSERT_SOURCE_LOCATION (t),
7989
                                        /*member_p=*/true);
7990
                }
7991
              else if (TREE_CODE (t) != CONST_DECL)
7992
                {
7993
                  tree r;
7994
 
7995
                  /* The file and line for this declaration, to
7996
                     assist in error message reporting.  Since we
7997
                     called push_tinst_level above, we don't need to
7998
                     restore these.  */
7999
                  input_location = DECL_SOURCE_LOCATION (t);
8000
 
8001
                  if (TREE_CODE (t) == TEMPLATE_DECL)
8002
                    ++processing_template_decl;
8003
                  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8004
                  if (TREE_CODE (t) == TEMPLATE_DECL)
8005
                    --processing_template_decl;
8006
                  if (TREE_CODE (r) == VAR_DECL)
8007
                    {
8008
                      /* In [temp.inst]:
8009
 
8010
                           [t]he initialization (and any associated
8011
                           side-effects) of a static data member does
8012
                           not occur unless the static data member is
8013
                           itself used in a way that requires the
8014
                           definition of the static data member to
8015
                           exist.
8016
 
8017
                         Therefore, we do not substitute into the
8018
                         initialized for the static data member here.  */
8019
                      finish_static_data_member_decl
8020
                        (r,
8021
                         /*init=*/NULL_TREE,
8022
                         /*init_const_expr_p=*/false,
8023
                         /*asmspec_tree=*/NULL_TREE,
8024
                         /*flags=*/0);
8025
                      if (DECL_INITIALIZED_IN_CLASS_P (r))
8026
                        check_static_variable_definition (r, TREE_TYPE (r));
8027
                    }
8028
                  else if (TREE_CODE (r) == FIELD_DECL)
8029
                    {
8030
                      /* Determine whether R has a valid type and can be
8031
                         completed later.  If R is invalid, then it is
8032
                         replaced by error_mark_node so that it will not be
8033
                         added to TYPE_FIELDS.  */
8034
                      tree rtype = TREE_TYPE (r);
8035
                      if (can_complete_type_without_circularity (rtype))
8036
                        complete_type (rtype);
8037
 
8038
                      if (!COMPLETE_TYPE_P (rtype))
8039
                        {
8040
                          cxx_incomplete_type_error (r, rtype);
8041
                          r = error_mark_node;
8042
                        }
8043
                    }
8044
 
8045
                  /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8046
                     such a thing will already have been added to the field
8047
                     list by tsubst_enum in finish_member_declaration in the
8048
                     CLASSTYPE_NESTED_UTDS case above.  */
8049
                  if (!(TREE_CODE (r) == TYPE_DECL
8050
                        && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8051
                        && DECL_ARTIFICIAL (r)))
8052
                    {
8053
                      set_current_access_from_decl (r);
8054
                      finish_member_declaration (r);
8055
                    }
8056
                }
8057
            }
8058
        }
8059
      else
8060
        {
8061
          if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8062
            {
8063
              /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8064
 
8065
              tree friend_type = t;
8066
              bool adjust_processing_template_decl = false;
8067
 
8068
              if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8069
                {
8070
                  /* template <class T> friend class C;  */
8071
                  friend_type = tsubst_friend_class (friend_type, args);
8072
                  adjust_processing_template_decl = true;
8073
                }
8074
              else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8075
                {
8076
                  /* template <class T> friend class C::D;  */
8077
                  friend_type = tsubst (friend_type, args,
8078
                                        tf_warning_or_error, NULL_TREE);
8079
                  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8080
                    friend_type = TREE_TYPE (friend_type);
8081
                  adjust_processing_template_decl = true;
8082
                }
8083
              else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8084
                {
8085
                  /* This could be either
8086
 
8087
                       friend class T::C;
8088
 
8089
                     when dependent_type_p is false or
8090
 
8091
                       template <class U> friend class T::C;
8092
 
8093
                     otherwise.  */
8094
                  friend_type = tsubst (friend_type, args,
8095
                                        tf_warning_or_error, NULL_TREE);
8096
                  /* Bump processing_template_decl for correct
8097
                     dependent_type_p calculation.  */
8098
                  ++processing_template_decl;
8099
                  if (dependent_type_p (friend_type))
8100
                    adjust_processing_template_decl = true;
8101
                  --processing_template_decl;
8102
                }
8103
              else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8104
                       && hidden_name_p (TYPE_NAME (friend_type)))
8105
                {
8106
                  /* friend class C;
8107
 
8108
                     where C hasn't been declared yet.  Let's lookup name
8109
                     from namespace scope directly, bypassing any name that
8110
                     come from dependent base class.  */
8111
                  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8112
 
8113
                  /* The call to xref_tag_from_type does injection for friend
8114
                     classes.  */
8115
                  push_nested_namespace (ns);
8116
                  friend_type =
8117
                    xref_tag_from_type (friend_type, NULL_TREE,
8118
                                        /*tag_scope=*/ts_current);
8119
                  pop_nested_namespace (ns);
8120
                }
8121
              else if (uses_template_parms (friend_type))
8122
                /* friend class C<T>;  */
8123
                friend_type = tsubst (friend_type, args,
8124
                                      tf_warning_or_error, NULL_TREE);
8125
              /* Otherwise it's
8126
 
8127
                   friend class C;
8128
 
8129
                 where C is already declared or
8130
 
8131
                   friend class C<int>;
8132
 
8133
                 We don't have to do anything in these cases.  */
8134
 
8135
              if (adjust_processing_template_decl)
8136
                /* Trick make_friend_class into realizing that the friend
8137
                   we're adding is a template, not an ordinary class.  It's
8138
                   important that we use make_friend_class since it will
8139
                   perform some error-checking and output cross-reference
8140
                   information.  */
8141
                ++processing_template_decl;
8142
 
8143
              if (friend_type != error_mark_node)
8144
                make_friend_class (type, friend_type, /*complain=*/false);
8145
 
8146
              if (adjust_processing_template_decl)
8147
                --processing_template_decl;
8148
            }
8149
          else
8150
            {
8151
              /* Build new DECL_FRIENDLIST.  */
8152
              tree r;
8153
 
8154
              /* The file and line for this declaration, to
8155
                 assist in error message reporting.  Since we
8156
                 called push_tinst_level above, we don't need to
8157
                 restore these.  */
8158
              input_location = DECL_SOURCE_LOCATION (t);
8159
 
8160
              if (TREE_CODE (t) == TEMPLATE_DECL)
8161
                {
8162
                  ++processing_template_decl;
8163
                  push_deferring_access_checks (dk_no_check);
8164
                }
8165
 
8166
              r = tsubst_friend_function (t, args);
8167
              add_friend (type, r, /*complain=*/false);
8168
              if (TREE_CODE (t) == TEMPLATE_DECL)
8169
                {
8170
                  pop_deferring_access_checks ();
8171
                  --processing_template_decl;
8172
                }
8173
            }
8174
        }
8175
    }
8176
 
8177
  /* Set the file and line number information to whatever is given for
8178
     the class itself.  This puts error messages involving generated
8179
     implicit functions at a predictable point, and the same point
8180
     that would be used for non-template classes.  */
8181
  input_location = DECL_SOURCE_LOCATION (typedecl);
8182
 
8183
  unreverse_member_declarations (type);
8184
  finish_struct_1 (type);
8185
  TYPE_BEING_DEFINED (type) = 0;
8186
 
8187
  /* Now that the class is complete, instantiate default arguments for
8188
     any member functions.  We don't do this earlier because the
8189
     default arguments may reference members of the class.  */
8190
  if (!PRIMARY_TEMPLATE_P (templ))
8191
    for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8192
      if (TREE_CODE (t) == FUNCTION_DECL
8193
          /* Implicitly generated member functions will not have template
8194
             information; they are not instantiations, but instead are
8195
             created "fresh" for each instantiation.  */
8196
          && DECL_TEMPLATE_INFO (t))
8197
        tsubst_default_arguments (t);
8198
 
8199
  /* Some typedefs referenced from within the template code need to be access
8200
     checked at template instantiation time, i.e now. These types were
8201
     added to the template at parsing time. Let's get those and perform
8202
     the access checks then.  */
8203
  perform_typedefs_access_check (pattern, args);
8204
  perform_deferred_access_checks ();
8205
  pop_nested_class ();
8206
  maximum_field_alignment = saved_maximum_field_alignment;
8207
  pop_from_top_level ();
8208
  pop_deferring_access_checks ();
8209
  pop_tinst_level ();
8210
 
8211
  /* The vtable for a template class can be emitted in any translation
8212
     unit in which the class is instantiated.  When there is no key
8213
     method, however, finish_struct_1 will already have added TYPE to
8214
     the keyed_classes list.  */
8215
  if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8216
    keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8217
 
8218
  return type;
8219
}
8220
 
8221
static tree
8222
tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8223
{
8224
  tree r;
8225
 
8226
  if (!t)
8227
    r = t;
8228
  else if (TYPE_P (t))
8229
    r = tsubst (t, args, complain, in_decl);
8230
  else
8231
    {
8232
      r = tsubst_expr (t, args, complain, in_decl,
8233
                       /*integral_constant_expression_p=*/true);
8234
      r = fold_non_dependent_expr (r);
8235
    }
8236
  return r;
8237
}
8238
 
8239
/* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8240
   NONTYPE_ARGUMENT_PACK.  */
8241
 
8242
static tree
8243
make_fnparm_pack (tree spec_parm)
8244
{
8245
  /* Collect all of the extra "packed" parameters into an
8246
     argument pack.  */
8247
  tree parmvec;
8248
  tree parmtypevec;
8249
  tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8250
  tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8251
  int i, len = list_length (spec_parm);
8252
 
8253
  /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8254
  parmvec = make_tree_vec (len);
8255
  parmtypevec = make_tree_vec (len);
8256
  for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8257
    {
8258
      TREE_VEC_ELT (parmvec, i) = spec_parm;
8259
      TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8260
    }
8261
 
8262
  /* Build the argument packs.  */
8263
  SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8264
  SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8265
  TREE_TYPE (argpack) = argtypepack;
8266
 
8267
  return argpack;
8268
}
8269
 
8270
/* Substitute ARGS into T, which is an pack expansion
8271
   (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8272
   TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8273
   (if only a partial substitution could be performed) or
8274
   ERROR_MARK_NODE if there was an error.  */
8275
tree
8276
tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8277
                       tree in_decl)
8278
{
8279
  tree pattern;
8280
  tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8281
  int i, len = -1;
8282
  tree result;
8283
  int incomplete = 0;
8284
  htab_t saved_local_specializations = NULL;
8285
 
8286
  gcc_assert (PACK_EXPANSION_P (t));
8287
  pattern = PACK_EXPANSION_PATTERN (t);
8288
 
8289
  /* Determine the argument packs that will instantiate the parameter
8290
     packs used in the expansion expression. While we're at it,
8291
     compute the number of arguments to be expanded and make sure it
8292
     is consistent.  */
8293
  for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
8294
       pack = TREE_CHAIN (pack))
8295
    {
8296
      tree parm_pack = TREE_VALUE (pack);
8297
      tree arg_pack = NULL_TREE;
8298
      tree orig_arg = NULL_TREE;
8299
 
8300
      if (TREE_CODE (parm_pack) == PARM_DECL)
8301
        {
8302
          if (!cp_unevaluated_operand)
8303
            arg_pack = retrieve_local_specialization (parm_pack);
8304
          else
8305
            {
8306
              /* We can't rely on local_specializations for a parameter
8307
                 name used later in a function declaration (such as in a
8308
                 late-specified return type).  Even if it exists, it might
8309
                 have the wrong value for a recursive call.  Just make a
8310
                 dummy decl, since it's only used for its type.  */
8311
              arg_pack = tsubst_decl (parm_pack, args, complain);
8312
              arg_pack = make_fnparm_pack (arg_pack);
8313
            }
8314
        }
8315
      else
8316
        {
8317
          int level, idx, levels;
8318
          template_parm_level_and_index (parm_pack, &level, &idx);
8319
 
8320
          levels = TMPL_ARGS_DEPTH (args);
8321
          if (level <= levels)
8322
            arg_pack = TMPL_ARG (args, level, idx);
8323
        }
8324
 
8325
      orig_arg = arg_pack;
8326
      if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8327
        arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8328
 
8329
      if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8330
        /* This can only happen if we forget to expand an argument
8331
           pack somewhere else. Just return an error, silently.  */
8332
        {
8333
          result = make_tree_vec (1);
8334
          TREE_VEC_ELT (result, 0) = error_mark_node;
8335
          return result;
8336
        }
8337
 
8338
      if (arg_pack
8339
          && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8340
          && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8341
        {
8342
          tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8343
          tree pattern = PACK_EXPANSION_PATTERN (expansion);
8344
          if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8345
              || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8346
            /* The argument pack that the parameter maps to is just an
8347
               expansion of the parameter itself, such as one would
8348
               find in the implicit typedef of a class inside the
8349
               class itself.  Consider this parameter "unsubstituted",
8350
               so that we will maintain the outer pack expansion.  */
8351
            arg_pack = NULL_TREE;
8352
        }
8353
 
8354
      if (arg_pack)
8355
        {
8356
          int my_len =
8357
            TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8358
 
8359
          /* It's all-or-nothing with incomplete argument packs.  */
8360
          if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8361
            return error_mark_node;
8362
 
8363
          if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8364
            incomplete = 1;
8365
 
8366
          if (len < 0)
8367
            len = my_len;
8368
          else if (len != my_len)
8369
            {
8370
              if (incomplete)
8371
                /* We got explicit args for some packs but not others;
8372
                   do nothing now and try again after deduction.  */
8373
                return t;
8374
              if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8375
                error ("mismatched argument pack lengths while expanding "
8376
                       "%<%T%>",
8377
                       pattern);
8378
              else
8379
                error ("mismatched argument pack lengths while expanding "
8380
                       "%<%E%>",
8381
                       pattern);
8382
              return error_mark_node;
8383
            }
8384
 
8385
          /* Keep track of the parameter packs and their corresponding
8386
             argument packs.  */
8387
          packs = tree_cons (parm_pack, arg_pack, packs);
8388
          TREE_TYPE (packs) = orig_arg;
8389
        }
8390
      else
8391
        /* We can't substitute for this parameter pack.  */
8392
        unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8393
                                         TREE_VALUE (pack),
8394
                                         unsubstituted_packs);
8395
    }
8396
 
8397
  /* We cannot expand this expansion expression, because we don't have
8398
     all of the argument packs we need. Substitute into the pattern
8399
     and return a PACK_EXPANSION_*. The caller will need to deal with
8400
     that.  */
8401
  if (unsubstituted_packs)
8402
    {
8403
      tree new_pat;
8404
      if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8405
        new_pat = tsubst_expr (pattern, args, complain, in_decl,
8406
                               /*integral_constant_expression_p=*/false);
8407
      else
8408
        new_pat = tsubst (pattern, args, complain, in_decl);
8409
      return make_pack_expansion (new_pat);
8410
    }
8411
 
8412
  /* We could not find any argument packs that work.  */
8413
  if (len < 0)
8414
    return error_mark_node;
8415
 
8416
  if (cp_unevaluated_operand)
8417
    {
8418
      /* We're in a late-specified return type, so create our own local
8419
         specializations table; the current table is either NULL or (in the
8420
         case of recursive unification) might have bindings that we don't
8421
         want to use or alter.  */
8422
      saved_local_specializations = local_specializations;
8423
      local_specializations = htab_create (37,
8424
                                           hash_local_specialization,
8425
                                           eq_local_specializations,
8426
                                           NULL);
8427
    }
8428
 
8429
  /* For each argument in each argument pack, substitute into the
8430
     pattern.  */
8431
  result = make_tree_vec (len + incomplete);
8432
  for (i = 0; i < len + incomplete; ++i)
8433
    {
8434
      /* For parameter pack, change the substitution of the parameter
8435
         pack to the ith argument in its argument pack, then expand
8436
         the pattern.  */
8437
      for (pack = packs; pack; pack = TREE_CHAIN (pack))
8438
        {
8439
          tree parm = TREE_PURPOSE (pack);
8440
 
8441
          if (TREE_CODE (parm) == PARM_DECL)
8442
            {
8443
              /* Select the Ith argument from the pack.  */
8444
              tree arg = make_node (ARGUMENT_PACK_SELECT);
8445
              ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8446
              ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8447
              mark_used (parm);
8448
              register_local_specialization (arg, parm);
8449
            }
8450
          else
8451
            {
8452
              tree value = parm;
8453
              int idx, level;
8454
              template_parm_level_and_index (parm, &level, &idx);
8455
 
8456
              if (i < len)
8457
                {
8458
                  /* Select the Ith argument from the pack. */
8459
                  value = make_node (ARGUMENT_PACK_SELECT);
8460
                  ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8461
                  ARGUMENT_PACK_SELECT_INDEX (value) = i;
8462
                }
8463
 
8464
              /* Update the corresponding argument.  */
8465
              TMPL_ARG (args, level, idx) = value;
8466
            }
8467
        }
8468
 
8469
      /* Substitute into the PATTERN with the altered arguments.  */
8470
      if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8471
        TREE_VEC_ELT (result, i) =
8472
          tsubst_expr (pattern, args, complain, in_decl,
8473
                       /*integral_constant_expression_p=*/false);
8474
      else
8475
        TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8476
 
8477
      if (i == len)
8478
        /* When we have incomplete argument packs, the last "expanded"
8479
           result is itself a pack expansion, which allows us
8480
           to deduce more arguments.  */
8481
        TREE_VEC_ELT (result, i) =
8482
          make_pack_expansion (TREE_VEC_ELT (result, i));
8483
 
8484
      if (TREE_VEC_ELT (result, i) == error_mark_node)
8485
        {
8486
          result = error_mark_node;
8487
          break;
8488
        }
8489
    }
8490
 
8491
  /* Update ARGS to restore the substitution from parameter packs to
8492
     their argument packs.  */
8493
  for (pack = packs; pack; pack = TREE_CHAIN (pack))
8494
    {
8495
      tree parm = TREE_PURPOSE (pack);
8496
 
8497
      if (TREE_CODE (parm) == PARM_DECL)
8498
        register_local_specialization (TREE_TYPE (pack), parm);
8499
      else
8500
        {
8501
          int idx, level;
8502
          template_parm_level_and_index (parm, &level, &idx);
8503
 
8504
          /* Update the corresponding argument.  */
8505
          if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8506
            TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8507
              TREE_TYPE (pack);
8508
          else
8509
            TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8510
        }
8511
    }
8512
 
8513
  if (saved_local_specializations)
8514
    {
8515
      htab_delete (local_specializations);
8516
      local_specializations = saved_local_specializations;
8517
    }
8518
 
8519
  return result;
8520
}
8521
 
8522
/* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8523
   TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8524
   parameter packs; all parms generated from a function parameter pack will
8525
   have the same DECL_PARM_INDEX.  */
8526
 
8527
tree
8528
get_pattern_parm (tree parm, tree tmpl)
8529
{
8530
  tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8531
  tree patparm;
8532
 
8533
  if (DECL_ARTIFICIAL (parm))
8534
    {
8535
      for (patparm = DECL_ARGUMENTS (pattern);
8536
           patparm; patparm = TREE_CHAIN (patparm))
8537
        if (DECL_ARTIFICIAL (patparm)
8538
            && DECL_NAME (parm) == DECL_NAME (patparm))
8539
          break;
8540
    }
8541
  else
8542
    {
8543
      patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8544
      patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8545
      gcc_assert (DECL_PARM_INDEX (patparm)
8546
                  == DECL_PARM_INDEX (parm));
8547
    }
8548
 
8549
  return patparm;
8550
}
8551
 
8552
/* Substitute ARGS into the vector or list of template arguments T.  */
8553
 
8554
static tree
8555
tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8556
{
8557
  tree orig_t = t;
8558
  int len = TREE_VEC_LENGTH (t);
8559
  int need_new = 0, i, expanded_len_adjust = 0, out;
8560
  tree *elts = (tree *) alloca (len * sizeof (tree));
8561
 
8562
  for (i = 0; i < len; i++)
8563
    {
8564
      tree orig_arg = TREE_VEC_ELT (t, i);
8565
      tree new_arg;
8566
 
8567
      if (TREE_CODE (orig_arg) == TREE_VEC)
8568
        new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8569
      else if (PACK_EXPANSION_P (orig_arg))
8570
        {
8571
          /* Substitute into an expansion expression.  */
8572
          new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8573
 
8574
          if (TREE_CODE (new_arg) == TREE_VEC)
8575
            /* Add to the expanded length adjustment the number of
8576
               expanded arguments. We subtract one from this
8577
               measurement, because the argument pack expression
8578
               itself is already counted as 1 in
8579
               LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8580
               the argument pack is empty.  */
8581
            expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8582
        }
8583
      else if (ARGUMENT_PACK_P (orig_arg))
8584
        {
8585
          /* Substitute into each of the arguments.  */
8586
          new_arg = TYPE_P (orig_arg)
8587
            ? cxx_make_type (TREE_CODE (orig_arg))
8588
            : make_node (TREE_CODE (orig_arg));
8589
 
8590
          SET_ARGUMENT_PACK_ARGS (
8591
            new_arg,
8592
            tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8593
                                  args, complain, in_decl));
8594
 
8595
          if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8596
            new_arg = error_mark_node;
8597
 
8598
          if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8599
            TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8600
                                          complain, in_decl);
8601
            TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8602
 
8603
            if (TREE_TYPE (new_arg) == error_mark_node)
8604
              new_arg = error_mark_node;
8605
          }
8606
        }
8607
      else
8608
        new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8609
 
8610
      if (new_arg == error_mark_node)
8611
        return error_mark_node;
8612
 
8613
      elts[i] = new_arg;
8614
      if (new_arg != orig_arg)
8615
        need_new = 1;
8616
    }
8617
 
8618
  if (!need_new)
8619
    return t;
8620
 
8621
  /* Make space for the expanded arguments coming from template
8622
     argument packs.  */
8623
  t = make_tree_vec (len + expanded_len_adjust);
8624
  /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8625
     arguments for a member template.
8626
     In that case each TREE_VEC in ORIG_T represents a level of template
8627
     arguments, and ORIG_T won't carry any non defaulted argument count.
8628
     It will rather be the nested TREE_VECs that will carry one.
8629
     In other words, ORIG_T carries a non defaulted argument count only
8630
     if it doesn't contain any nested TREE_VEC.  */
8631
  if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8632
    {
8633
      int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8634
      count += expanded_len_adjust;
8635
      SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8636
    }
8637
  for (i = 0, out = 0; i < len; i++)
8638
    {
8639
      if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8640
           || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8641
          && TREE_CODE (elts[i]) == TREE_VEC)
8642
        {
8643
          int idx;
8644
 
8645
          /* Now expand the template argument pack "in place".  */
8646
          for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8647
            TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8648
        }
8649
      else
8650
        {
8651
          TREE_VEC_ELT (t, out) = elts[i];
8652
          out++;
8653
        }
8654
    }
8655
 
8656
  return t;
8657
}
8658
 
8659
/* Return the result of substituting ARGS into the template parameters
8660
   given by PARMS.  If there are m levels of ARGS and m + n levels of
8661
   PARMS, then the result will contain n levels of PARMS.  For
8662
   example, if PARMS is `template <class T> template <class U>
8663
   template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8664
   result will be `template <int*, double, class V>'.  */
8665
 
8666
static tree
8667
tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8668
{
8669
  tree r = NULL_TREE;
8670
  tree* new_parms;
8671
 
8672
  /* When substituting into a template, we must set
8673
     PROCESSING_TEMPLATE_DECL as the template parameters may be
8674
     dependent if they are based on one-another, and the dependency
8675
     predicates are short-circuit outside of templates.  */
8676
  ++processing_template_decl;
8677
 
8678
  for (new_parms = &r;
8679
       TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8680
       new_parms = &(TREE_CHAIN (*new_parms)),
8681
         parms = TREE_CHAIN (parms))
8682
    {
8683
      tree new_vec =
8684
        make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8685
      int i;
8686
 
8687
      for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8688
        {
8689
          tree tuple;
8690
          tree default_value;
8691
          tree parm_decl;
8692
 
8693
          if (parms == error_mark_node)
8694
            continue;
8695
 
8696
          tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8697
 
8698
          if (tuple == error_mark_node)
8699
            continue;
8700
 
8701
          default_value = TREE_PURPOSE (tuple);
8702
          parm_decl = TREE_VALUE (tuple);
8703
 
8704
          parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8705
          if (TREE_CODE (parm_decl) == PARM_DECL
8706
              && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8707
            parm_decl = error_mark_node;
8708
          default_value = tsubst_template_arg (default_value, args,
8709
                                               complain, NULL_TREE);
8710
 
8711
          tuple = build_tree_list (default_value, parm_decl);
8712
          TREE_VEC_ELT (new_vec, i) = tuple;
8713
        }
8714
 
8715
      *new_parms =
8716
        tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8717
                             - TMPL_ARGS_DEPTH (args)),
8718
                   new_vec, NULL_TREE);
8719
    }
8720
 
8721
  --processing_template_decl;
8722
 
8723
  return r;
8724
}
8725
 
8726
/* Substitute the ARGS into the indicated aggregate (or enumeration)
8727
   type T.  If T is not an aggregate or enumeration type, it is
8728
   handled as if by tsubst.  IN_DECL is as for tsubst.  If
8729
   ENTERING_SCOPE is nonzero, T is the context for a template which
8730
   we are presently tsubst'ing.  Return the substituted value.  */
8731
 
8732
static tree
8733
tsubst_aggr_type (tree t,
8734
                  tree args,
8735
                  tsubst_flags_t complain,
8736
                  tree in_decl,
8737
                  int entering_scope)
8738
{
8739
  if (t == NULL_TREE)
8740
    return NULL_TREE;
8741
 
8742
  switch (TREE_CODE (t))
8743
    {
8744
    case RECORD_TYPE:
8745
      if (TYPE_PTRMEMFUNC_P (t))
8746
        return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8747
 
8748
      /* Else fall through.  */
8749
    case ENUMERAL_TYPE:
8750
    case UNION_TYPE:
8751
      if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8752
        {
8753
          tree argvec;
8754
          tree context;
8755
          tree r;
8756
          int saved_unevaluated_operand;
8757
          int saved_inhibit_evaluation_warnings;
8758
 
8759
          /* In "sizeof(X<I>)" we need to evaluate "I".  */
8760
          saved_unevaluated_operand = cp_unevaluated_operand;
8761
          cp_unevaluated_operand = 0;
8762
          saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8763
          c_inhibit_evaluation_warnings = 0;
8764
 
8765
          /* First, determine the context for the type we are looking
8766
             up.  */
8767
          context = TYPE_CONTEXT (t);
8768
          if (context)
8769
            {
8770
              context = tsubst_aggr_type (context, args, complain,
8771
                                          in_decl, /*entering_scope=*/1);
8772
              /* If context is a nested class inside a class template,
8773
                 it may still need to be instantiated (c++/33959).  */
8774
              if (TYPE_P (context))
8775
                context = complete_type (context);
8776
            }
8777
 
8778
          /* Then, figure out what arguments are appropriate for the
8779
             type we are trying to find.  For example, given:
8780
 
8781
               template <class T> struct S;
8782
               template <class T, class U> void f(T, U) { S<U> su; }
8783
 
8784
             and supposing that we are instantiating f<int, double>,
8785
             then our ARGS will be {int, double}, but, when looking up
8786
             S we only want {double}.  */
8787
          argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8788
                                         complain, in_decl);
8789
          if (argvec == error_mark_node)
8790
            r = error_mark_node;
8791
          else
8792
            {
8793
              r = lookup_template_class (t, argvec, in_decl, context,
8794
                                         entering_scope, complain);
8795
              r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8796
            }
8797
 
8798
          cp_unevaluated_operand = saved_unevaluated_operand;
8799
          c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8800
 
8801
          return r;
8802
        }
8803
      else
8804
        /* This is not a template type, so there's nothing to do.  */
8805
        return t;
8806
 
8807
    default:
8808
      return tsubst (t, args, complain, in_decl);
8809
    }
8810
}
8811
 
8812
/* Substitute into the default argument ARG (a default argument for
8813
   FN), which has the indicated TYPE.  */
8814
 
8815
tree
8816
tsubst_default_argument (tree fn, tree type, tree arg)
8817
{
8818
  tree saved_class_ptr = NULL_TREE;
8819
  tree saved_class_ref = NULL_TREE;
8820
 
8821
  /* This default argument came from a template.  Instantiate the
8822
     default argument here, not in tsubst.  In the case of
8823
     something like:
8824
 
8825
       template <class T>
8826
       struct S {
8827
         static T t();
8828
         void f(T = t());
8829
       };
8830
 
8831
     we must be careful to do name lookup in the scope of S<T>,
8832
     rather than in the current class.  */
8833
  push_access_scope (fn);
8834
  /* The "this" pointer is not valid in a default argument.  */
8835
  if (cfun)
8836
    {
8837
      saved_class_ptr = current_class_ptr;
8838
      cp_function_chain->x_current_class_ptr = NULL_TREE;
8839
      saved_class_ref = current_class_ref;
8840
      cp_function_chain->x_current_class_ref = NULL_TREE;
8841
    }
8842
 
8843
  push_deferring_access_checks(dk_no_deferred);
8844
  /* The default argument expression may cause implicitly defined
8845
     member functions to be synthesized, which will result in garbage
8846
     collection.  We must treat this situation as if we were within
8847
     the body of function so as to avoid collecting live data on the
8848
     stack.  */
8849
  ++function_depth;
8850
  arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8851
                     tf_warning_or_error, NULL_TREE,
8852
                     /*integral_constant_expression_p=*/false);
8853
  --function_depth;
8854
  pop_deferring_access_checks();
8855
 
8856
  /* Restore the "this" pointer.  */
8857
  if (cfun)
8858
    {
8859
      cp_function_chain->x_current_class_ptr = saved_class_ptr;
8860
      cp_function_chain->x_current_class_ref = saved_class_ref;
8861
    }
8862
 
8863
  /* Make sure the default argument is reasonable.  */
8864
  arg = check_default_argument (type, arg);
8865
 
8866
  pop_access_scope (fn);
8867
 
8868
  return arg;
8869
}
8870
 
8871
/* Substitute into all the default arguments for FN.  */
8872
 
8873
static void
8874
tsubst_default_arguments (tree fn)
8875
{
8876
  tree arg;
8877
  tree tmpl_args;
8878
 
8879
  tmpl_args = DECL_TI_ARGS (fn);
8880
 
8881
  /* If this function is not yet instantiated, we certainly don't need
8882
     its default arguments.  */
8883
  if (uses_template_parms (tmpl_args))
8884
    return;
8885
 
8886
  for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8887
       arg;
8888
       arg = TREE_CHAIN (arg))
8889
    if (TREE_PURPOSE (arg))
8890
      TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8891
                                                    TREE_VALUE (arg),
8892
                                                    TREE_PURPOSE (arg));
8893
}
8894
 
8895
/* Substitute the ARGS into the T, which is a _DECL.  Return the
8896
   result of the substitution.  Issue error and warning messages under
8897
   control of COMPLAIN.  */
8898
 
8899
static tree
8900
tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8901
{
8902
#define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8903
  location_t saved_loc;
8904
  tree r = NULL_TREE;
8905
  tree in_decl = t;
8906
  hashval_t hash = 0;
8907
 
8908
  /* Set the filename and linenumber to improve error-reporting.  */
8909
  saved_loc = input_location;
8910
  input_location = DECL_SOURCE_LOCATION (t);
8911
 
8912
  switch (TREE_CODE (t))
8913
    {
8914
    case TEMPLATE_DECL:
8915
      {
8916
        /* We can get here when processing a member function template,
8917
           member class template, or template template parameter.  */
8918
        tree decl = DECL_TEMPLATE_RESULT (t);
8919
        tree spec;
8920
        tree tmpl_args;
8921
        tree full_args;
8922
 
8923
        if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8924
          {
8925
            /* Template template parameter is treated here.  */
8926
            tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8927
            if (new_type == error_mark_node)
8928
              RETURN (error_mark_node);
8929
 
8930
            r = copy_decl (t);
8931
            TREE_CHAIN (r) = NULL_TREE;
8932
            TREE_TYPE (r) = new_type;
8933
            DECL_TEMPLATE_RESULT (r)
8934
              = build_decl (DECL_SOURCE_LOCATION (decl),
8935
                            TYPE_DECL, DECL_NAME (decl), new_type);
8936
            DECL_TEMPLATE_PARMS (r)
8937
              = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8938
                                       complain);
8939
            TYPE_NAME (new_type) = r;
8940
            break;
8941
          }
8942
 
8943
        /* We might already have an instance of this template.
8944
           The ARGS are for the surrounding class type, so the
8945
           full args contain the tsubst'd args for the context,
8946
           plus the innermost args from the template decl.  */
8947
        tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8948
          ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8949
          : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8950
        /* Because this is a template, the arguments will still be
8951
           dependent, even after substitution.  If
8952
           PROCESSING_TEMPLATE_DECL is not set, the dependency
8953
           predicates will short-circuit.  */
8954
        ++processing_template_decl;
8955
        full_args = tsubst_template_args (tmpl_args, args,
8956
                                          complain, in_decl);
8957
        --processing_template_decl;
8958
        if (full_args == error_mark_node)
8959
          RETURN (error_mark_node);
8960
 
8961
        /* If this is a default template template argument,
8962
           tsubst might not have changed anything.  */
8963
        if (full_args == tmpl_args)
8964
          RETURN (t);
8965
 
8966
        hash = hash_tmpl_and_args (t, full_args);
8967
        spec = retrieve_specialization (t, full_args, hash);
8968
        if (spec != NULL_TREE)
8969
          {
8970
            r = spec;
8971
            break;
8972
          }
8973
 
8974
        /* Make a new template decl.  It will be similar to the
8975
           original, but will record the current template arguments.
8976
           We also create a new function declaration, which is just
8977
           like the old one, but points to this new template, rather
8978
           than the old one.  */
8979
        r = copy_decl (t);
8980
        gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8981
        TREE_CHAIN (r) = NULL_TREE;
8982
 
8983
        DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8984
 
8985
        if (TREE_CODE (decl) == TYPE_DECL)
8986
          {
8987
            tree new_type;
8988
            ++processing_template_decl;
8989
            new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8990
            --processing_template_decl;
8991
            if (new_type == error_mark_node)
8992
              RETURN (error_mark_node);
8993
 
8994
            TREE_TYPE (r) = new_type;
8995
            CLASSTYPE_TI_TEMPLATE (new_type) = r;
8996
            DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8997
            DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8998
            DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8999
          }
9000
        else
9001
          {
9002
            tree new_decl;
9003
            ++processing_template_decl;
9004
            new_decl = tsubst (decl, args, complain, in_decl);
9005
            --processing_template_decl;
9006
            if (new_decl == error_mark_node)
9007
              RETURN (error_mark_node);
9008
 
9009
            DECL_TEMPLATE_RESULT (r) = new_decl;
9010
            DECL_TI_TEMPLATE (new_decl) = r;
9011
            TREE_TYPE (r) = TREE_TYPE (new_decl);
9012
            DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9013
            DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9014
          }
9015
 
9016
        SET_DECL_IMPLICIT_INSTANTIATION (r);
9017
        DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9018
        DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9019
 
9020
        /* The template parameters for this new template are all the
9021
           template parameters for the old template, except the
9022
           outermost level of parameters.  */
9023
        DECL_TEMPLATE_PARMS (r)
9024
          = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9025
                                   complain);
9026
 
9027
        if (PRIMARY_TEMPLATE_P (t))
9028
          DECL_PRIMARY_TEMPLATE (r) = r;
9029
 
9030
        if (TREE_CODE (decl) != TYPE_DECL)
9031
          /* Record this non-type partial instantiation.  */
9032
          register_specialization (r, t,
9033
                                   DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9034
                                   false, hash);
9035
      }
9036
      break;
9037
 
9038
    case FUNCTION_DECL:
9039
      {
9040
        tree ctx;
9041
        tree argvec = NULL_TREE;
9042
        tree *friends;
9043
        tree gen_tmpl;
9044
        tree type;
9045
        int member;
9046
        int args_depth;
9047
        int parms_depth;
9048
 
9049
        /* Nobody should be tsubst'ing into non-template functions.  */
9050
        gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9051
 
9052
        if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9053
          {
9054
            tree spec;
9055
            bool dependent_p;
9056
 
9057
            /* If T is not dependent, just return it.  We have to
9058
               increment PROCESSING_TEMPLATE_DECL because
9059
               value_dependent_expression_p assumes that nothing is
9060
               dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9061
            ++processing_template_decl;
9062
            dependent_p = value_dependent_expression_p (t);
9063
            --processing_template_decl;
9064
            if (!dependent_p)
9065
              RETURN (t);
9066
 
9067
            /* Calculate the most general template of which R is a
9068
               specialization, and the complete set of arguments used to
9069
               specialize R.  */
9070
            gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9071
            argvec = tsubst_template_args (DECL_TI_ARGS
9072
                                           (DECL_TEMPLATE_RESULT (gen_tmpl)),
9073
                                           args, complain, in_decl);
9074
 
9075
            /* Check to see if we already have this specialization.  */
9076
            hash = hash_tmpl_and_args (gen_tmpl, argvec);
9077
            spec = retrieve_specialization (gen_tmpl, argvec, hash);
9078
 
9079
            if (spec)
9080
              {
9081
                r = spec;
9082
                break;
9083
              }
9084
 
9085
            /* We can see more levels of arguments than parameters if
9086
               there was a specialization of a member template, like
9087
               this:
9088
 
9089
                 template <class T> struct S { template <class U> void f(); }
9090
                 template <> template <class U> void S<int>::f(U);
9091
 
9092
               Here, we'll be substituting into the specialization,
9093
               because that's where we can find the code we actually
9094
               want to generate, but we'll have enough arguments for
9095
               the most general template.
9096
 
9097
               We also deal with the peculiar case:
9098
 
9099
                 template <class T> struct S {
9100
                   template <class U> friend void f();
9101
                 };
9102
                 template <class U> void f() {}
9103
                 template S<int>;
9104
                 template void f<double>();
9105
 
9106
               Here, the ARGS for the instantiation of will be {int,
9107
               double}.  But, we only need as many ARGS as there are
9108
               levels of template parameters in CODE_PATTERN.  We are
9109
               careful not to get fooled into reducing the ARGS in
9110
               situations like:
9111
 
9112
                 template <class T> struct S { template <class U> void f(U); }
9113
                 template <class T> template <> void S<T>::f(int) {}
9114
 
9115
               which we can spot because the pattern will be a
9116
               specialization in this case.  */
9117
            args_depth = TMPL_ARGS_DEPTH (args);
9118
            parms_depth =
9119
              TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9120
            if (args_depth > parms_depth
9121
                && !DECL_TEMPLATE_SPECIALIZATION (t))
9122
              args = get_innermost_template_args (args, parms_depth);
9123
          }
9124
        else
9125
          {
9126
            /* This special case arises when we have something like this:
9127
 
9128
                 template <class T> struct S {
9129
                   friend void f<int>(int, double);
9130
                 };
9131
 
9132
               Here, the DECL_TI_TEMPLATE for the friend declaration
9133
               will be an IDENTIFIER_NODE.  We are being called from
9134
               tsubst_friend_function, and we want only to create a
9135
               new decl (R) with appropriate types so that we can call
9136
               determine_specialization.  */
9137
            gen_tmpl = NULL_TREE;
9138
          }
9139
 
9140
        if (DECL_CLASS_SCOPE_P (t))
9141
          {
9142
            if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9143
              member = 2;
9144
            else
9145
              member = 1;
9146
            ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9147
                                    complain, t, /*entering_scope=*/1);
9148
          }
9149
        else
9150
          {
9151
            member = 0;
9152
            ctx = DECL_CONTEXT (t);
9153
          }
9154
        type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9155
        if (type == error_mark_node)
9156
          RETURN (error_mark_node);
9157
 
9158
        /* We do NOT check for matching decls pushed separately at this
9159
           point, as they may not represent instantiations of this
9160
           template, and in any case are considered separate under the
9161
           discrete model.  */
9162
        r = copy_decl (t);
9163
        DECL_USE_TEMPLATE (r) = 0;
9164
        TREE_TYPE (r) = type;
9165
        /* Clear out the mangled name and RTL for the instantiation.  */
9166
        SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9167
        SET_DECL_RTL (r, NULL_RTX);
9168
        /* Leave DECL_INITIAL set on deleted instantiations.  */
9169
        if (!DECL_DELETED_FN (r))
9170
          DECL_INITIAL (r) = NULL_TREE;
9171
        DECL_CONTEXT (r) = ctx;
9172
 
9173
        if (member && DECL_CONV_FN_P (r))
9174
          /* Type-conversion operator.  Reconstruct the name, in
9175
             case it's the name of one of the template's parameters.  */
9176
          DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9177
 
9178
        DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9179
                                     complain, t);
9180
        DECL_RESULT (r) = NULL_TREE;
9181
 
9182
        TREE_STATIC (r) = 0;
9183
        TREE_PUBLIC (r) = TREE_PUBLIC (t);
9184
        DECL_EXTERNAL (r) = 1;
9185
        /* If this is an instantiation of a function with internal
9186
           linkage, we already know what object file linkage will be
9187
           assigned to the instantiation.  */
9188
        DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9189
        DECL_DEFER_OUTPUT (r) = 0;
9190
        TREE_CHAIN (r) = NULL_TREE;
9191
        DECL_PENDING_INLINE_INFO (r) = 0;
9192
        DECL_PENDING_INLINE_P (r) = 0;
9193
        DECL_SAVED_TREE (r) = NULL_TREE;
9194
        DECL_STRUCT_FUNCTION (r) = NULL;
9195
        TREE_USED (r) = 0;
9196
        /* We'll re-clone as appropriate in instantiate_template.  */
9197
        DECL_CLONED_FUNCTION (r) = NULL_TREE;
9198
 
9199
        /* If we aren't complaining now, return on error before we register
9200
           the specialization so that we'll complain eventually.  */
9201
        if ((complain & tf_error) == 0
9202
            && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9203
            && !grok_op_properties (r, /*complain=*/false))
9204
          RETURN (error_mark_node);
9205
 
9206
        /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9207
           this in the special friend case mentioned above where
9208
           GEN_TMPL is NULL.  */
9209
        if (gen_tmpl)
9210
          {
9211
            DECL_TEMPLATE_INFO (r)
9212
              = build_template_info (gen_tmpl, argvec);
9213
            SET_DECL_IMPLICIT_INSTANTIATION (r);
9214
            register_specialization (r, gen_tmpl, argvec, false, hash);
9215
 
9216
            /* We're not supposed to instantiate default arguments
9217
               until they are called, for a template.  But, for a
9218
               declaration like:
9219
 
9220
                 template <class T> void f ()
9221
                 { extern void g(int i = T()); }
9222
 
9223
               we should do the substitution when the template is
9224
               instantiated.  We handle the member function case in
9225
               instantiate_class_template since the default arguments
9226
               might refer to other members of the class.  */
9227
            if (!member
9228
                && !PRIMARY_TEMPLATE_P (gen_tmpl)
9229
                && !uses_template_parms (argvec))
9230
              tsubst_default_arguments (r);
9231
          }
9232
        else
9233
          DECL_TEMPLATE_INFO (r) = NULL_TREE;
9234
 
9235
        /* Copy the list of befriending classes.  */
9236
        for (friends = &DECL_BEFRIENDING_CLASSES (r);
9237
             *friends;
9238
             friends = &TREE_CHAIN (*friends))
9239
          {
9240
            *friends = copy_node (*friends);
9241
            TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9242
                                            args, complain,
9243
                                            in_decl);
9244
          }
9245
 
9246
        if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9247
          {
9248
            maybe_retrofit_in_chrg (r);
9249
            if (DECL_CONSTRUCTOR_P (r))
9250
              grok_ctor_properties (ctx, r);
9251
            /* If this is an instantiation of a member template, clone it.
9252
               If it isn't, that'll be handled by
9253
               clone_constructors_and_destructors.  */
9254
            if (PRIMARY_TEMPLATE_P (gen_tmpl))
9255
              clone_function_decl (r, /*update_method_vec_p=*/0);
9256
          }
9257
        else if ((complain & tf_error) != 0
9258
                 && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9259
                 && !grok_op_properties (r, /*complain=*/true))
9260
          RETURN (error_mark_node);
9261
 
9262
        if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9263
          SET_DECL_FRIEND_CONTEXT (r,
9264
                                   tsubst (DECL_FRIEND_CONTEXT (t),
9265
                                            args, complain, in_decl));
9266
 
9267
        /* Possibly limit visibility based on template args.  */
9268
        DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9269
        if (DECL_VISIBILITY_SPECIFIED (t))
9270
          {
9271
            DECL_VISIBILITY_SPECIFIED (r) = 0;
9272
            DECL_ATTRIBUTES (r)
9273
              = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9274
          }
9275
        determine_visibility (r);
9276
        if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9277
            && !processing_template_decl)
9278
          defaulted_late_check (r);
9279
 
9280
        apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9281
                                        args, complain, in_decl);
9282
      }
9283
      break;
9284
 
9285
    case PARM_DECL:
9286
      {
9287
        tree type = NULL_TREE;
9288
        int i, len = 1;
9289
        tree expanded_types = NULL_TREE;
9290
        tree prev_r = NULL_TREE;
9291
        tree first_r = NULL_TREE;
9292
 
9293
        if (FUNCTION_PARAMETER_PACK_P (t))
9294
          {
9295
            /* If there is a local specialization that isn't a
9296
               parameter pack, it means that we're doing a "simple"
9297
               substitution from inside tsubst_pack_expansion. Just
9298
               return the local specialization (which will be a single
9299
               parm).  */
9300
            tree spec = retrieve_local_specialization (t);
9301
            if (spec
9302
                && TREE_CODE (spec) == PARM_DECL
9303
                && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9304
              RETURN (spec);
9305
 
9306
            /* Expand the TYPE_PACK_EXPANSION that provides the types for
9307
               the parameters in this function parameter pack.  */
9308
            expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9309
                                                    complain, in_decl);
9310
            if (TREE_CODE (expanded_types) == TREE_VEC)
9311
              {
9312
                len = TREE_VEC_LENGTH (expanded_types);
9313
 
9314
                /* Zero-length parameter packs are boring. Just substitute
9315
                   into the chain.  */
9316
                if (len == 0)
9317
                  RETURN (tsubst (TREE_CHAIN (t), args, complain,
9318
                                  TREE_CHAIN (t)));
9319
              }
9320
            else
9321
              {
9322
                /* All we did was update the type. Make a note of that.  */
9323
                type = expanded_types;
9324
                expanded_types = NULL_TREE;
9325
              }
9326
          }
9327
 
9328
        /* Loop through all of the parameter's we'll build. When T is
9329
           a function parameter pack, LEN is the number of expanded
9330
           types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9331
        r = NULL_TREE;
9332
        for (i = 0; i < len; ++i)
9333
          {
9334
            prev_r = r;
9335
            r = copy_node (t);
9336
            if (DECL_TEMPLATE_PARM_P (t))
9337
              SET_DECL_TEMPLATE_PARM_P (r);
9338
 
9339
            /* An argument of a function parameter pack is not a parameter
9340
               pack.  */
9341
            FUNCTION_PARAMETER_PACK_P (r) = false;
9342
 
9343
            if (expanded_types)
9344
              /* We're on the Ith parameter of the function parameter
9345
                 pack.  */
9346
              {
9347
                /* Get the Ith type.  */
9348
                type = TREE_VEC_ELT (expanded_types, i);
9349
 
9350
                if (DECL_NAME (r))
9351
                  /* Rename the parameter to include the index.  */
9352
                  DECL_NAME (r) =
9353
                    make_ith_pack_parameter_name (DECL_NAME (r), i);
9354
              }
9355
            else if (!type)
9356
              /* We're dealing with a normal parameter.  */
9357
              type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9358
 
9359
            type = type_decays_to (type);
9360
            TREE_TYPE (r) = type;
9361
            cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9362
 
9363
            if (DECL_INITIAL (r))
9364
              {
9365
                if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9366
                  DECL_INITIAL (r) = TREE_TYPE (r);
9367
                else
9368
                  DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9369
                                             complain, in_decl);
9370
              }
9371
 
9372
            DECL_CONTEXT (r) = NULL_TREE;
9373
 
9374
            if (!DECL_TEMPLATE_PARM_P (r))
9375
              DECL_ARG_TYPE (r) = type_passed_as (type);
9376
 
9377
            apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9378
                                            args, complain, in_decl);
9379
 
9380
            /* Keep track of the first new parameter we
9381
               generate. That's what will be returned to the
9382
               caller.  */
9383
            if (!first_r)
9384
              first_r = r;
9385
 
9386
            /* Build a proper chain of parameters when substituting
9387
               into a function parameter pack.  */
9388
            if (prev_r)
9389
              TREE_CHAIN (prev_r) = r;
9390
          }
9391
 
9392
        if (TREE_CHAIN (t))
9393
          TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9394
                                   complain, TREE_CHAIN (t));
9395
 
9396
        /* FIRST_R contains the start of the chain we've built.  */
9397
        r = first_r;
9398
      }
9399
      break;
9400
 
9401
    case FIELD_DECL:
9402
      {
9403
        tree type;
9404
 
9405
        r = copy_decl (t);
9406
        type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9407
        if (type == error_mark_node)
9408
          RETURN (error_mark_node);
9409
        TREE_TYPE (r) = type;
9410
        cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9411
 
9412
        /* DECL_INITIAL gives the number of bits in a bit-field.  */
9413
        DECL_INITIAL (r)
9414
          = tsubst_expr (DECL_INITIAL (t), args,
9415
                         complain, in_decl,
9416
                         /*integral_constant_expression_p=*/true);
9417
        /* We don't have to set DECL_CONTEXT here; it is set by
9418
           finish_member_declaration.  */
9419
        TREE_CHAIN (r) = NULL_TREE;
9420
        if (VOID_TYPE_P (type))
9421
          error ("instantiation of %q+D as type %qT", r, type);
9422
 
9423
        apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9424
                                        args, complain, in_decl);
9425
      }
9426
      break;
9427
 
9428
    case USING_DECL:
9429
      /* We reach here only for member using decls.  */
9430
      if (DECL_DEPENDENT_P (t))
9431
        {
9432
          r = do_class_using_decl
9433
            (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9434
             tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9435
          if (!r)
9436
            r = error_mark_node;
9437
          else
9438
            {
9439
              TREE_PROTECTED (r) = TREE_PROTECTED (t);
9440
              TREE_PRIVATE (r) = TREE_PRIVATE (t);
9441
            }
9442
        }
9443
      else
9444
        {
9445
          r = copy_node (t);
9446
          TREE_CHAIN (r) = NULL_TREE;
9447
        }
9448
      break;
9449
 
9450
    case TYPE_DECL:
9451
    case VAR_DECL:
9452
      {
9453
        tree argvec = NULL_TREE;
9454
        tree gen_tmpl = NULL_TREE;
9455
        tree spec;
9456
        tree tmpl = NULL_TREE;
9457
        tree ctx;
9458
        tree type = NULL_TREE;
9459
        bool local_p;
9460
 
9461
        if (TREE_CODE (t) == TYPE_DECL
9462
            && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9463
          {
9464
            /* If this is the canonical decl, we don't have to
9465
               mess with instantiations, and often we can't (for
9466
               typename, template type parms and such).  Note that
9467
               TYPE_NAME is not correct for the above test if
9468
               we've copied the type for a typedef.  */
9469
            type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9470
            if (type == error_mark_node)
9471
              RETURN (error_mark_node);
9472
            r = TYPE_NAME (type);
9473
            break;
9474
          }
9475
 
9476
        /* Check to see if we already have the specialization we
9477
           need.  */
9478
        spec = NULL_TREE;
9479
        if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9480
          {
9481
            /* T is a static data member or namespace-scope entity.
9482
               We have to substitute into namespace-scope variables
9483
               (even though such entities are never templates) because
9484
               of cases like:
9485
 
9486
                 template <class T> void f() { extern T t; }
9487
 
9488
               where the entity referenced is not known until
9489
               instantiation time.  */
9490
            local_p = false;
9491
            ctx = DECL_CONTEXT (t);
9492
            if (DECL_CLASS_SCOPE_P (t))
9493
              {
9494
                ctx = tsubst_aggr_type (ctx, args,
9495
                                        complain,
9496
                                        in_decl, /*entering_scope=*/1);
9497
                /* If CTX is unchanged, then T is in fact the
9498
                   specialization we want.  That situation occurs when
9499
                   referencing a static data member within in its own
9500
                   class.  We can use pointer equality, rather than
9501
                   same_type_p, because DECL_CONTEXT is always
9502
                   canonical.  */
9503
                if (ctx == DECL_CONTEXT (t))
9504
                  spec = t;
9505
              }
9506
 
9507
            if (!spec)
9508
              {
9509
                tmpl = DECL_TI_TEMPLATE (t);
9510
                gen_tmpl = most_general_template (tmpl);
9511
                argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9512
                hash = hash_tmpl_and_args (gen_tmpl, argvec);
9513
                spec = retrieve_specialization (gen_tmpl, argvec, hash);
9514
              }
9515
          }
9516
        else
9517
          {
9518
            /* A local variable.  */
9519
            local_p = true;
9520
            /* Subsequent calls to pushdecl will fill this in.  */
9521
            ctx = NULL_TREE;
9522
            spec = retrieve_local_specialization (t);
9523
          }
9524
        /* If we already have the specialization we need, there is
9525
           nothing more to do.  */
9526
        if (spec)
9527
          {
9528
            r = spec;
9529
            break;
9530
          }
9531
 
9532
        /* Create a new node for the specialization we need.  */
9533
        r = copy_decl (t);
9534
        if (type == NULL_TREE)
9535
          {
9536
            if (is_typedef_decl (t))
9537
              type = DECL_ORIGINAL_TYPE (t);
9538
            else
9539
              type = TREE_TYPE (t);
9540
            type = tsubst (type, args, complain, in_decl);
9541
          }
9542
        if (TREE_CODE (r) == VAR_DECL)
9543
          {
9544
            /* Even if the original location is out of scope, the
9545
               newly substituted one is not.  */
9546
            DECL_DEAD_FOR_LOCAL (r) = 0;
9547
            DECL_INITIALIZED_P (r) = 0;
9548
            DECL_TEMPLATE_INSTANTIATED (r) = 0;
9549
            if (type == error_mark_node)
9550
              RETURN (error_mark_node);
9551
            if (TREE_CODE (type) == FUNCTION_TYPE)
9552
              {
9553
                /* It may seem that this case cannot occur, since:
9554
 
9555
                     typedef void f();
9556
                     void g() { f x; }
9557
 
9558
                   declares a function, not a variable.  However:
9559
 
9560
                     typedef void f();
9561
                     template <typename T> void g() { T t; }
9562
                     template void g<f>();
9563
 
9564
                   is an attempt to declare a variable with function
9565
                   type.  */
9566
                error ("variable %qD has function type",
9567
                       /* R is not yet sufficiently initialized, so we
9568
                          just use its name.  */
9569
                       DECL_NAME (r));
9570
                RETURN (error_mark_node);
9571
              }
9572
            type = complete_type (type);
9573
            DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9574
              = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9575
            type = check_var_type (DECL_NAME (r), type);
9576
 
9577
            if (DECL_HAS_VALUE_EXPR_P (t))
9578
              {
9579
                tree ve = DECL_VALUE_EXPR (t);
9580
                ve = tsubst_expr (ve, args, complain, in_decl,
9581
                                  /*constant_expression_p=*/false);
9582
                SET_DECL_VALUE_EXPR (r, ve);
9583
              }
9584
          }
9585
        else if (DECL_SELF_REFERENCE_P (t))
9586
          SET_DECL_SELF_REFERENCE_P (r);
9587
        TREE_TYPE (r) = type;
9588
        cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9589
        DECL_CONTEXT (r) = ctx;
9590
        /* Clear out the mangled name and RTL for the instantiation.  */
9591
        SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9592
        if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9593
          SET_DECL_RTL (r, NULL_RTX);
9594
        /* The initializer must not be expanded until it is required;
9595
           see [temp.inst].  */
9596
        DECL_INITIAL (r) = NULL_TREE;
9597
        if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9598
          SET_DECL_RTL (r, NULL_RTX);
9599
        DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9600
        if (TREE_CODE (r) == VAR_DECL)
9601
          {
9602
            /* Possibly limit visibility based on template args.  */
9603
            DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9604
            if (DECL_VISIBILITY_SPECIFIED (t))
9605
              {
9606
                DECL_VISIBILITY_SPECIFIED (r) = 0;
9607
                DECL_ATTRIBUTES (r)
9608
                  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9609
              }
9610
            determine_visibility (r);
9611
          }
9612
 
9613
        if (!local_p)
9614
          {
9615
            /* A static data member declaration is always marked
9616
               external when it is declared in-class, even if an
9617
               initializer is present.  We mimic the non-template
9618
               processing here.  */
9619
            DECL_EXTERNAL (r) = 1;
9620
 
9621
            register_specialization (r, gen_tmpl, argvec, false, hash);
9622
            DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9623
            SET_DECL_IMPLICIT_INSTANTIATION (r);
9624
          }
9625
        else if (cp_unevaluated_operand)
9626
          {
9627
            /* We're substituting this var in a decltype outside of its
9628
               scope, such as for a lambda return type.  Don't add it to
9629
               local_specializations, do perform auto deduction.  */
9630
            tree auto_node = type_uses_auto (type);
9631
            tree init
9632
              = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9633
                             /*constant_expression_p=*/false);
9634
 
9635
            if (auto_node && init && describable_type (init))
9636
              {
9637
                type = do_auto_deduction (type, init, auto_node);
9638
                TREE_TYPE (r) = type;
9639
              }
9640
          }
9641
        else
9642
          register_local_specialization (r, t);
9643
 
9644
        TREE_CHAIN (r) = NULL_TREE;
9645
 
9646
        apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9647
                                        /*flags=*/0,
9648
                                        args, complain, in_decl);
9649
 
9650
        /* Preserve a typedef that names a type.  */
9651
        if (is_typedef_decl (r))
9652
          {
9653
            DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9654
            set_underlying_type (r);
9655
          }
9656
 
9657
        layout_decl (r, 0);
9658
      }
9659
      break;
9660
 
9661
    default:
9662
      gcc_unreachable ();
9663
    }
9664
#undef RETURN
9665
 
9666
 out:
9667
  /* Restore the file and line information.  */
9668
  input_location = saved_loc;
9669
 
9670
  return r;
9671
}
9672
 
9673
/* Substitute into the ARG_TYPES of a function type.  */
9674
 
9675
static tree
9676
tsubst_arg_types (tree arg_types,
9677
                  tree args,
9678
                  tsubst_flags_t complain,
9679
                  tree in_decl)
9680
{
9681
  tree remaining_arg_types;
9682
  tree type = NULL_TREE;
9683
  int i = 1;
9684
  tree expanded_args = NULL_TREE;
9685
  tree default_arg;
9686
 
9687
  if (!arg_types || arg_types == void_list_node)
9688
    return arg_types;
9689
 
9690
  remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9691
                                          args, complain, in_decl);
9692
  if (remaining_arg_types == error_mark_node)
9693
    return error_mark_node;
9694
 
9695
  if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9696
    {
9697
      /* For a pack expansion, perform substitution on the
9698
         entire expression. Later on, we'll handle the arguments
9699
         one-by-one.  */
9700
      expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9701
                                            args, complain, in_decl);
9702
 
9703
      if (TREE_CODE (expanded_args) == TREE_VEC)
9704
        /* So that we'll spin through the parameters, one by one.  */
9705
        i = TREE_VEC_LENGTH (expanded_args);
9706
      else
9707
        {
9708
          /* We only partially substituted into the parameter
9709
             pack. Our type is TYPE_PACK_EXPANSION.  */
9710
          type = expanded_args;
9711
          expanded_args = NULL_TREE;
9712
        }
9713
    }
9714
 
9715
  while (i > 0) {
9716
    --i;
9717
 
9718
    if (expanded_args)
9719
      type = TREE_VEC_ELT (expanded_args, i);
9720
    else if (!type)
9721
      type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9722
 
9723
    if (type == error_mark_node)
9724
      return error_mark_node;
9725
    if (VOID_TYPE_P (type))
9726
      {
9727
        if (complain & tf_error)
9728
          {
9729
            error ("invalid parameter type %qT", type);
9730
            if (in_decl)
9731
              error ("in declaration %q+D", in_decl);
9732
          }
9733
        return error_mark_node;
9734
    }
9735
 
9736
    /* Do array-to-pointer, function-to-pointer conversion, and ignore
9737
       top-level qualifiers as required.  */
9738
    type = TYPE_MAIN_VARIANT (type_decays_to (type));
9739
 
9740
    /* We do not substitute into default arguments here.  The standard
9741
       mandates that they be instantiated only when needed, which is
9742
       done in build_over_call.  */
9743
    default_arg = TREE_PURPOSE (arg_types);
9744
 
9745
    if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9746
      {
9747
        /* We've instantiated a template before its default arguments
9748
           have been parsed.  This can happen for a nested template
9749
           class, and is not an error unless we require the default
9750
           argument in a call of this function.  */
9751
        remaining_arg_types =
9752
          tree_cons (default_arg, type, remaining_arg_types);
9753
        VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg),
9754
                       remaining_arg_types);
9755
      }
9756
    else
9757
      remaining_arg_types =
9758
        hash_tree_cons (default_arg, type, remaining_arg_types);
9759
  }
9760
 
9761
  return remaining_arg_types;
9762
}
9763
 
9764
/* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9765
   *not* handle the exception-specification for FNTYPE, because the
9766
   initial substitution of explicitly provided template parameters
9767
   during argument deduction forbids substitution into the
9768
   exception-specification:
9769
 
9770
     [temp.deduct]
9771
 
9772
     All references in the function type of the function template to  the
9773
     corresponding template parameters are replaced by the specified tem-
9774
     plate argument values.  If a substitution in a template parameter or
9775
     in  the function type of the function template results in an invalid
9776
     type, type deduction fails.  [Note: The equivalent  substitution  in
9777
     exception specifications is done only when the function is instanti-
9778
     ated, at which point a program is  ill-formed  if  the  substitution
9779
     results in an invalid type.]  */
9780
 
9781
static tree
9782
tsubst_function_type (tree t,
9783
                      tree args,
9784
                      tsubst_flags_t complain,
9785
                      tree in_decl)
9786
{
9787
  tree return_type;
9788
  tree arg_types;
9789
  tree fntype;
9790
 
9791
  /* The TYPE_CONTEXT is not used for function/method types.  */
9792
  gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9793
 
9794
  /* Substitute the return type.  */
9795
  return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9796
  if (return_type == error_mark_node)
9797
    return error_mark_node;
9798
  /* The standard does not presently indicate that creation of a
9799
     function type with an invalid return type is a deduction failure.
9800
     However, that is clearly analogous to creating an array of "void"
9801
     or a reference to a reference.  This is core issue #486.  */
9802
  if (TREE_CODE (return_type) == ARRAY_TYPE
9803
      || TREE_CODE (return_type) == FUNCTION_TYPE)
9804
    {
9805
      if (complain & tf_error)
9806
        {
9807
          if (TREE_CODE (return_type) == ARRAY_TYPE)
9808
            error ("function returning an array");
9809
          else
9810
            error ("function returning a function");
9811
        }
9812
      return error_mark_node;
9813
    }
9814
 
9815
  /* Substitute the argument types.  */
9816
  arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9817
                                complain, in_decl);
9818
  if (arg_types == error_mark_node)
9819
    return error_mark_node;
9820
 
9821
  /* Construct a new type node and return it.  */
9822
  if (TREE_CODE (t) == FUNCTION_TYPE)
9823
    fntype = build_function_type (return_type, arg_types);
9824
  else
9825
    {
9826
      tree r = TREE_TYPE (TREE_VALUE (arg_types));
9827
      if (! MAYBE_CLASS_TYPE_P (r))
9828
        {
9829
          /* [temp.deduct]
9830
 
9831
             Type deduction may fail for any of the following
9832
             reasons:
9833
 
9834
             -- Attempting to create "pointer to member of T" when T
9835
             is not a class type.  */
9836
          if (complain & tf_error)
9837
            error ("creating pointer to member function of non-class type %qT",
9838
                      r);
9839
          return error_mark_node;
9840
        }
9841
 
9842
      fntype = build_method_type_directly (r, return_type,
9843
                                           TREE_CHAIN (arg_types));
9844
    }
9845
  fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9846
  fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9847
 
9848
  return fntype;
9849
}
9850
 
9851
/* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9852
   ARGS into that specification, and return the substituted
9853
   specification.  If there is no specification, return NULL_TREE.  */
9854
 
9855
static tree
9856
tsubst_exception_specification (tree fntype,
9857
                                tree args,
9858
                                tsubst_flags_t complain,
9859
                                tree in_decl)
9860
{
9861
  tree specs;
9862
  tree new_specs;
9863
 
9864
  specs = TYPE_RAISES_EXCEPTIONS (fntype);
9865
  new_specs = NULL_TREE;
9866
  if (specs)
9867
    {
9868
      if (! TREE_VALUE (specs))
9869
        new_specs = specs;
9870
      else
9871
        while (specs)
9872
          {
9873
            tree spec;
9874
            int i, len = 1;
9875
            tree expanded_specs = NULL_TREE;
9876
 
9877
            if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9878
              {
9879
                /* Expand the pack expansion type.  */
9880
                expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9881
                                                       args, complain,
9882
                                                       in_decl);
9883
 
9884
                if (expanded_specs == error_mark_node)
9885
                  return error_mark_node;
9886
                else if (TREE_CODE (expanded_specs) == TREE_VEC)
9887
                  len = TREE_VEC_LENGTH (expanded_specs);
9888
                else
9889
                  {
9890
                    /* We're substituting into a member template, so
9891
                       we got a TYPE_PACK_EXPANSION back.  Add that
9892
                       expansion and move on.  */
9893
                    gcc_assert (TREE_CODE (expanded_specs)
9894
                                == TYPE_PACK_EXPANSION);
9895
                    new_specs = add_exception_specifier (new_specs,
9896
                                                         expanded_specs,
9897
                                                         complain);
9898
                    specs = TREE_CHAIN (specs);
9899
                    continue;
9900
                  }
9901
              }
9902
 
9903
            for (i = 0; i < len; ++i)
9904
              {
9905
                if (expanded_specs)
9906
                  spec = TREE_VEC_ELT (expanded_specs, i);
9907
                else
9908
                  spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9909
                if (spec == error_mark_node)
9910
                  return spec;
9911
                new_specs = add_exception_specifier (new_specs, spec,
9912
                                                     complain);
9913
              }
9914
 
9915
            specs = TREE_CHAIN (specs);
9916
          }
9917
    }
9918
  return new_specs;
9919
}
9920
 
9921
/* Take the tree structure T and replace template parameters used
9922
   therein with the argument vector ARGS.  IN_DECL is an associated
9923
   decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9924
   Issue error and warning messages under control of COMPLAIN.  Note
9925
   that we must be relatively non-tolerant of extensions here, in
9926
   order to preserve conformance; if we allow substitutions that
9927
   should not be allowed, we may allow argument deductions that should
9928
   not succeed, and therefore report ambiguous overload situations
9929
   where there are none.  In theory, we could allow the substitution,
9930
   but indicate that it should have failed, and allow our caller to
9931
   make sure that the right thing happens, but we don't try to do this
9932
   yet.
9933
 
9934
   This function is used for dealing with types, decls and the like;
9935
   for expressions, use tsubst_expr or tsubst_copy.  */
9936
 
9937
tree
9938
tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9939
{
9940
  tree type, r;
9941
 
9942
  if (t == NULL_TREE || t == error_mark_node
9943
      || t == integer_type_node
9944
      || t == void_type_node
9945
      || t == char_type_node
9946
      || t == unknown_type_node
9947
      || TREE_CODE (t) == NAMESPACE_DECL)
9948
    return t;
9949
 
9950
  if (DECL_P (t))
9951
    return tsubst_decl (t, args, complain);
9952
 
9953
  if (args == NULL_TREE)
9954
    return t;
9955
 
9956
  if (TREE_CODE (t) == IDENTIFIER_NODE)
9957
    type = IDENTIFIER_TYPE_VALUE (t);
9958
  else
9959
    type = TREE_TYPE (t);
9960
 
9961
  gcc_assert (type != unknown_type_node);
9962
 
9963
  /* Reuse typedefs.  We need to do this to handle dependent attributes,
9964
     such as attribute aligned.  */
9965
  if (TYPE_P (t)
9966
      && TYPE_NAME (t)
9967
      && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9968
    {
9969
      tree decl = TYPE_NAME (t);
9970
 
9971
      if (DECL_CLASS_SCOPE_P (decl)
9972
          && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9973
          && uses_template_parms (DECL_CONTEXT (decl)))
9974
        {
9975
          tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9976
          tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9977
          r = retrieve_specialization (tmpl, gen_args, 0);
9978
        }
9979
      else if (DECL_FUNCTION_SCOPE_P (decl)
9980
               && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9981
               && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9982
        r = retrieve_local_specialization (decl);
9983
      else
9984
        /* The typedef is from a non-template context.  */
9985
        return t;
9986
 
9987
      if (r)
9988
        {
9989
          r = TREE_TYPE (r);
9990
          r = cp_build_qualified_type_real
9991
            (r, cp_type_quals (t) | cp_type_quals (r),
9992
             complain | tf_ignore_bad_quals);
9993
          return r;
9994
        }
9995
      /* Else we must be instantiating the typedef, so fall through.  */
9996
    }
9997
 
9998
  if (type
9999
      && TREE_CODE (t) != TYPENAME_TYPE
10000
      && TREE_CODE (t) != TEMPLATE_TYPE_PARM
10001
      && TREE_CODE (t) != IDENTIFIER_NODE
10002
      && TREE_CODE (t) != FUNCTION_TYPE
10003
      && TREE_CODE (t) != METHOD_TYPE)
10004
    type = tsubst (type, args, complain, in_decl);
10005
  if (type == error_mark_node)
10006
    return error_mark_node;
10007
 
10008
  switch (TREE_CODE (t))
10009
    {
10010
    case RECORD_TYPE:
10011
    case UNION_TYPE:
10012
    case ENUMERAL_TYPE:
10013
      return tsubst_aggr_type (t, args, complain, in_decl,
10014
                               /*entering_scope=*/0);
10015
 
10016
    case ERROR_MARK:
10017
    case IDENTIFIER_NODE:
10018
    case VOID_TYPE:
10019
    case REAL_TYPE:
10020
    case COMPLEX_TYPE:
10021
    case VECTOR_TYPE:
10022
    case BOOLEAN_TYPE:
10023
    case INTEGER_CST:
10024
    case REAL_CST:
10025
    case STRING_CST:
10026
      return t;
10027
 
10028
    case INTEGER_TYPE:
10029
      if (t == integer_type_node)
10030
        return t;
10031
 
10032
      if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10033
          && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10034
        return t;
10035
 
10036
      {
10037
        tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10038
 
10039
        max = tsubst_expr (omax, args, complain, in_decl,
10040
                           /*integral_constant_expression_p=*/false);
10041
 
10042
        /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10043
           needed.  */
10044
        if (TREE_CODE (max) == NOP_EXPR
10045
            && TREE_SIDE_EFFECTS (omax)
10046
            && !TREE_TYPE (max))
10047
          TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10048
 
10049
        max = fold_decl_constant_value (max);
10050
 
10051
        /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10052
           with TREE_SIDE_EFFECTS that indicates this is not an integral
10053
           constant expression.  */
10054
        if (processing_template_decl
10055
            && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10056
          {
10057
            gcc_assert (TREE_CODE (max) == NOP_EXPR);
10058
            TREE_SIDE_EFFECTS (max) = 1;
10059
          }
10060
 
10061
        if (TREE_CODE (max) != INTEGER_CST
10062
            && !at_function_scope_p ()
10063
            && !TREE_SIDE_EFFECTS (max)
10064
            && !value_dependent_expression_p (max))
10065
          {
10066
            if (complain & tf_error)
10067
              error ("array bound is not an integer constant");
10068
            return error_mark_node;
10069
          }
10070
 
10071
        /* [temp.deduct]
10072
 
10073
           Type deduction may fail for any of the following
10074
           reasons:
10075
 
10076
             Attempting to create an array with a size that is
10077
             zero or negative.  */
10078
        if (integer_zerop (max) && !(complain & tf_error))
10079
          /* We must fail if performing argument deduction (as
10080
             indicated by the state of complain), so that
10081
             another substitution can be found.  */
10082
          return error_mark_node;
10083
        else if (TREE_CODE (max) == INTEGER_CST
10084
                 && INT_CST_LT (max, integer_zero_node))
10085
          {
10086
            if (complain & tf_error)
10087
              error ("creating array with negative size (%qE)", max);
10088
 
10089
            return error_mark_node;
10090
          }
10091
 
10092
        return compute_array_index_type (NULL_TREE, max);
10093
      }
10094
 
10095
    case TEMPLATE_TYPE_PARM:
10096
    case TEMPLATE_TEMPLATE_PARM:
10097
    case BOUND_TEMPLATE_TEMPLATE_PARM:
10098
    case TEMPLATE_PARM_INDEX:
10099
      {
10100
        int idx;
10101
        int level;
10102
        int levels;
10103
        tree arg = NULL_TREE;
10104
 
10105
        r = NULL_TREE;
10106
 
10107
        gcc_assert (TREE_VEC_LENGTH (args) > 0);
10108
        template_parm_level_and_index (t, &level, &idx);
10109
 
10110
        levels = TMPL_ARGS_DEPTH (args);
10111
        if (level <= levels)
10112
          {
10113
            arg = TMPL_ARG (args, level, idx);
10114
 
10115
            if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10116
              /* See through ARGUMENT_PACK_SELECT arguments. */
10117
              arg = ARGUMENT_PACK_SELECT_ARG (arg);
10118
          }
10119
 
10120
        if (arg == error_mark_node)
10121
          return error_mark_node;
10122
        else if (arg != NULL_TREE)
10123
          {
10124
            if (ARGUMENT_PACK_P (arg))
10125
              /* If ARG is an argument pack, we don't actually want to
10126
                 perform a substitution here, because substitutions
10127
                 for argument packs are only done
10128
                 element-by-element. We can get to this point when
10129
                 substituting the type of a non-type template
10130
                 parameter pack, when that type actually contains
10131
                 template parameter packs from an outer template, e.g.,
10132
 
10133
                 template<typename... Types> struct A {
10134
                   template<Types... Values> struct B { };
10135
                 };  */
10136
              return t;
10137
 
10138
            if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10139
              {
10140
                int quals;
10141
                gcc_assert (TYPE_P (arg));
10142
 
10143
                /* cv-quals from the template are discarded when
10144
                   substituting in a function or reference type.  */
10145
                if (TREE_CODE (arg) == FUNCTION_TYPE
10146
                    || TREE_CODE (arg) == METHOD_TYPE
10147
                    || TREE_CODE (arg) == REFERENCE_TYPE)
10148
                  quals = cp_type_quals (arg);
10149
                else
10150
                  quals = cp_type_quals (arg) | cp_type_quals (t);
10151
 
10152
                return cp_build_qualified_type_real
10153
                  (arg, quals, complain | tf_ignore_bad_quals);
10154
              }
10155
            else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10156
              {
10157
                /* We are processing a type constructed from a
10158
                   template template parameter.  */
10159
                tree argvec = tsubst (TYPE_TI_ARGS (t),
10160
                                      args, complain, in_decl);
10161
                if (argvec == error_mark_node)
10162
                  return error_mark_node;
10163
 
10164
                /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10165
                   are resolving nested-types in the signature of a
10166
                   member function templates.  Otherwise ARG is a
10167
                   TEMPLATE_DECL and is the real template to be
10168
                   instantiated.  */
10169
                if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10170
                  arg = TYPE_NAME (arg);
10171
 
10172
                r = lookup_template_class (arg,
10173
                                           argvec, in_decl,
10174
                                           DECL_CONTEXT (arg),
10175
                                            /*entering_scope=*/0,
10176
                                           complain);
10177
                return cp_build_qualified_type_real
10178
                  (r, TYPE_QUALS (t), complain);
10179
              }
10180
            else
10181
              /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10182
              return arg;
10183
          }
10184
 
10185
        if (level == 1)
10186
          /* This can happen during the attempted tsubst'ing in
10187
             unify.  This means that we don't yet have any information
10188
             about the template parameter in question.  */
10189
          return t;
10190
 
10191
        /* If we get here, we must have been looking at a parm for a
10192
           more deeply nested template.  Make a new version of this
10193
           template parameter, but with a lower level.  */
10194
        switch (TREE_CODE (t))
10195
          {
10196
          case TEMPLATE_TYPE_PARM:
10197
          case TEMPLATE_TEMPLATE_PARM:
10198
          case BOUND_TEMPLATE_TEMPLATE_PARM:
10199
            if (cp_type_quals (t))
10200
              {
10201
                r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10202
                r = cp_build_qualified_type_real
10203
                  (r, cp_type_quals (t),
10204
                   complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10205
                               ? tf_ignore_bad_quals : 0));
10206
              }
10207
            else
10208
              {
10209
                r = copy_type (t);
10210
                TEMPLATE_TYPE_PARM_INDEX (r)
10211
                  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10212
                                                r, levels, args, complain);
10213
                TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10214
                TYPE_MAIN_VARIANT (r) = r;
10215
                TYPE_POINTER_TO (r) = NULL_TREE;
10216
                TYPE_REFERENCE_TO (r) = NULL_TREE;
10217
 
10218
                if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10219
                  /* We have reduced the level of the template
10220
                     template parameter, but not the levels of its
10221
                     template parameters, so canonical_type_parameter
10222
                     will not be able to find the canonical template
10223
                     template parameter for this level. Thus, we
10224
                     require structural equality checking to compare
10225
                     TEMPLATE_TEMPLATE_PARMs. */
10226
                  SET_TYPE_STRUCTURAL_EQUALITY (r);
10227
                else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10228
                  SET_TYPE_STRUCTURAL_EQUALITY (r);
10229
                else
10230
                  TYPE_CANONICAL (r) = canonical_type_parameter (r);
10231
 
10232
                if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10233
                  {
10234
                    tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10235
                                          complain, in_decl);
10236
                    if (argvec == error_mark_node)
10237
                      return error_mark_node;
10238
 
10239
                    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10240
                      = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10241
                  }
10242
              }
10243
            break;
10244
 
10245
          case TEMPLATE_PARM_INDEX:
10246
            r = reduce_template_parm_level (t, type, levels, args, complain);
10247
            break;
10248
 
10249
          default:
10250
            gcc_unreachable ();
10251
          }
10252
 
10253
        return r;
10254
      }
10255
 
10256
    case TREE_LIST:
10257
      {
10258
        tree purpose, value, chain;
10259
 
10260
        if (t == void_list_node)
10261
          return t;
10262
 
10263
        purpose = TREE_PURPOSE (t);
10264
        if (purpose)
10265
          {
10266
            purpose = tsubst (purpose, args, complain, in_decl);
10267
            if (purpose == error_mark_node)
10268
              return error_mark_node;
10269
          }
10270
        value = TREE_VALUE (t);
10271
        if (value)
10272
          {
10273
            value = tsubst (value, args, complain, in_decl);
10274
            if (value == error_mark_node)
10275
              return error_mark_node;
10276
          }
10277
        chain = TREE_CHAIN (t);
10278
        if (chain && chain != void_type_node)
10279
          {
10280
            chain = tsubst (chain, args, complain, in_decl);
10281
            if (chain == error_mark_node)
10282
              return error_mark_node;
10283
          }
10284
        if (purpose == TREE_PURPOSE (t)
10285
            && value == TREE_VALUE (t)
10286
            && chain == TREE_CHAIN (t))
10287
          return t;
10288
        return hash_tree_cons (purpose, value, chain);
10289
      }
10290
 
10291
    case TREE_BINFO:
10292
      /* We should never be tsubsting a binfo.  */
10293
      gcc_unreachable ();
10294
 
10295
    case TREE_VEC:
10296
      /* A vector of template arguments.  */
10297
      gcc_assert (!type);
10298
      return tsubst_template_args (t, args, complain, in_decl);
10299
 
10300
    case POINTER_TYPE:
10301
    case REFERENCE_TYPE:
10302
      {
10303
        enum tree_code code;
10304
 
10305
        if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10306
          return t;
10307
 
10308
        code = TREE_CODE (t);
10309
 
10310
 
10311
        /* [temp.deduct]
10312
 
10313
           Type deduction may fail for any of the following
10314
           reasons:
10315
 
10316
           -- Attempting to create a pointer to reference type.
10317
           -- Attempting to create a reference to a reference type or
10318
              a reference to void.
10319
 
10320
          Core issue 106 says that creating a reference to a reference
10321
          during instantiation is no longer a cause for failure. We
10322
          only enforce this check in strict C++98 mode.  */
10323
        if ((TREE_CODE (type) == REFERENCE_TYPE
10324
             && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10325
            || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10326
          {
10327
            static location_t last_loc;
10328
 
10329
            /* We keep track of the last time we issued this error
10330
               message to avoid spewing a ton of messages during a
10331
               single bad template instantiation.  */
10332
            if (complain & tf_error
10333
                && last_loc != input_location)
10334
              {
10335
                if (TREE_CODE (type) == VOID_TYPE)
10336
                  error ("forming reference to void");
10337
               else if (code == POINTER_TYPE)
10338
                 error ("forming pointer to reference type %qT", type);
10339
               else
10340
                  error ("forming reference to reference type %qT", type);
10341
                last_loc = input_location;
10342
              }
10343
 
10344
            return error_mark_node;
10345
          }
10346
        else if (code == POINTER_TYPE)
10347
          {
10348
            r = build_pointer_type (type);
10349
            if (TREE_CODE (type) == METHOD_TYPE)
10350
              r = build_ptrmemfunc_type (r);
10351
          }
10352
        else if (TREE_CODE (type) == REFERENCE_TYPE)
10353
          /* In C++0x, during template argument substitution, when there is an
10354
             attempt to create a reference to a reference type, reference
10355
             collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10356
 
10357
             "If a template-argument for a template-parameter T names a type
10358
             that is a reference to a type A, an attempt to create the type
10359
             'lvalue reference to cv T' creates the type 'lvalue reference to
10360
             A,' while an attempt to create the type type rvalue reference to
10361
             cv T' creates the type T"
10362
          */
10363
          r = cp_build_reference_type
10364
              (TREE_TYPE (type),
10365
               TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10366
        else
10367
          r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10368
        r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10369
 
10370
        if (r != error_mark_node)
10371
          /* Will this ever be needed for TYPE_..._TO values?  */
10372
          layout_type (r);
10373
 
10374
        return r;
10375
      }
10376
    case OFFSET_TYPE:
10377
      {
10378
        r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10379
        if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10380
          {
10381
            /* [temp.deduct]
10382
 
10383
               Type deduction may fail for any of the following
10384
               reasons:
10385
 
10386
               -- Attempting to create "pointer to member of T" when T
10387
                  is not a class type.  */
10388
            if (complain & tf_error)
10389
              error ("creating pointer to member of non-class type %qT", r);
10390
            return error_mark_node;
10391
          }
10392
        if (TREE_CODE (type) == REFERENCE_TYPE)
10393
          {
10394
            if (complain & tf_error)
10395
              error ("creating pointer to member reference type %qT", type);
10396
            return error_mark_node;
10397
          }
10398
        if (TREE_CODE (type) == VOID_TYPE)
10399
          {
10400
            if (complain & tf_error)
10401
              error ("creating pointer to member of type void");
10402
            return error_mark_node;
10403
          }
10404
        gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10405
        if (TREE_CODE (type) == FUNCTION_TYPE)
10406
          {
10407
            /* The type of the implicit object parameter gets its
10408
               cv-qualifiers from the FUNCTION_TYPE. */
10409
            tree memptr;
10410
            tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10411
            memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10412
            return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10413
                                                 complain);
10414
          }
10415
        else
10416
          return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10417
                                               TYPE_QUALS (t),
10418
                                               complain);
10419
      }
10420
    case FUNCTION_TYPE:
10421
    case METHOD_TYPE:
10422
      {
10423
        tree fntype;
10424
        tree specs;
10425
        fntype = tsubst_function_type (t, args, complain, in_decl);
10426
        if (fntype == error_mark_node)
10427
          return error_mark_node;
10428
 
10429
        /* Substitute the exception specification.  */
10430
        specs = tsubst_exception_specification (t, args, complain,
10431
                                                in_decl);
10432
        if (specs == error_mark_node)
10433
          return error_mark_node;
10434
        if (specs)
10435
          fntype = build_exception_variant (fntype, specs);
10436
        return fntype;
10437
      }
10438
    case ARRAY_TYPE:
10439
      {
10440
        tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10441
        if (domain == error_mark_node)
10442
          return error_mark_node;
10443
 
10444
        /* As an optimization, we avoid regenerating the array type if
10445
           it will obviously be the same as T.  */
10446
        if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10447
          return t;
10448
 
10449
        /* These checks should match the ones in grokdeclarator.
10450
 
10451
           [temp.deduct]
10452
 
10453
           The deduction may fail for any of the following reasons:
10454
 
10455
           -- Attempting to create an array with an element type that
10456
              is void, a function type, or a reference type, or [DR337]
10457
              an abstract class type.  */
10458
        if (TREE_CODE (type) == VOID_TYPE
10459
            || TREE_CODE (type) == FUNCTION_TYPE
10460
            || TREE_CODE (type) == REFERENCE_TYPE)
10461
          {
10462
            if (complain & tf_error)
10463
              error ("creating array of %qT", type);
10464
            return error_mark_node;
10465
          }
10466
        if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10467
          {
10468
            if (complain & tf_error)
10469
              error ("creating array of %qT, which is an abstract class type",
10470
                     type);
10471
            return error_mark_node;
10472
          }
10473
 
10474
        r = build_cplus_array_type (type, domain);
10475
 
10476
        if (TYPE_USER_ALIGN (t))
10477
          {
10478
            TYPE_ALIGN (r) = TYPE_ALIGN (t);
10479
            TYPE_USER_ALIGN (r) = 1;
10480
          }
10481
 
10482
        return r;
10483
      }
10484
 
10485
    case PLUS_EXPR:
10486
    case MINUS_EXPR:
10487
      {
10488
        tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10489
        tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10490
 
10491
        if (e1 == error_mark_node || e2 == error_mark_node)
10492
          return error_mark_node;
10493
 
10494
        return fold_build2_loc (input_location,
10495
                            TREE_CODE (t), TREE_TYPE (t), e1, e2);
10496
      }
10497
 
10498
    case NEGATE_EXPR:
10499
    case NOP_EXPR:
10500
      {
10501
        tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10502
        if (e == error_mark_node)
10503
          return error_mark_node;
10504
 
10505
        return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10506
      }
10507
 
10508
    case TYPENAME_TYPE:
10509
      {
10510
        tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10511
                                     in_decl, /*entering_scope=*/1);
10512
        tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10513
                              complain, in_decl);
10514
        int quals;
10515
 
10516
        if (ctx == error_mark_node || f == error_mark_node)
10517
          return error_mark_node;
10518
 
10519
        if (!MAYBE_CLASS_TYPE_P (ctx))
10520
          {
10521
            if (complain & tf_error)
10522
              error ("%qT is not a class, struct, or union type", ctx);
10523
            return error_mark_node;
10524
          }
10525
        else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10526
          {
10527
            /* Normally, make_typename_type does not require that the CTX
10528
               have complete type in order to allow things like:
10529
 
10530
                 template <class T> struct S { typename S<T>::X Y; };
10531
 
10532
               But, such constructs have already been resolved by this
10533
               point, so here CTX really should have complete type, unless
10534
               it's a partial instantiation.  */
10535
            if (!(complain & tf_no_class_instantiations))
10536
              ctx = complete_type (ctx);
10537
            if (!COMPLETE_TYPE_P (ctx))
10538
              {
10539
                if (complain & tf_error)
10540
                  cxx_incomplete_type_error (NULL_TREE, ctx);
10541
                return error_mark_node;
10542
              }
10543
          }
10544
 
10545
        f = make_typename_type (ctx, f, typename_type,
10546
                                (complain & tf_error) | tf_keep_type_decl);
10547
        if (f == error_mark_node)
10548
          return f;
10549
        if (TREE_CODE (f) == TYPE_DECL)
10550
          {
10551
            complain |= tf_ignore_bad_quals;
10552
            f = TREE_TYPE (f);
10553
          }
10554
 
10555
        if (TREE_CODE (f) != TYPENAME_TYPE)
10556
          {
10557
            if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10558
              error ("%qT resolves to %qT, which is not an enumeration type",
10559
                     t, f);
10560
            else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10561
              error ("%qT resolves to %qT, which is is not a class type",
10562
                     t, f);
10563
          }
10564
 
10565
        /* cv-quals from the template are discarded when
10566
           substituting in a function or reference type.  */
10567
        if (TREE_CODE (f) == FUNCTION_TYPE
10568
            || TREE_CODE (f) == METHOD_TYPE
10569
            || TREE_CODE (f) == REFERENCE_TYPE)
10570
          quals = cp_type_quals (f);
10571
        else
10572
          quals = cp_type_quals (f) | cp_type_quals (t);
10573
        return cp_build_qualified_type_real (f, quals, complain);
10574
      }
10575
 
10576
    case UNBOUND_CLASS_TEMPLATE:
10577
      {
10578
        tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10579
                                     in_decl, /*entering_scope=*/1);
10580
        tree name = TYPE_IDENTIFIER (t);
10581
        tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10582
 
10583
        if (ctx == error_mark_node || name == error_mark_node)
10584
          return error_mark_node;
10585
 
10586
        if (parm_list)
10587
          parm_list = tsubst_template_parms (parm_list, args, complain);
10588
        return make_unbound_class_template (ctx, name, parm_list, complain);
10589
      }
10590
 
10591
    case INDIRECT_REF:
10592
    case ADDR_EXPR:
10593
    case CALL_EXPR:
10594
      gcc_unreachable ();
10595
 
10596
    case ARRAY_REF:
10597
      {
10598
        tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10599
        tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10600
                               /*integral_constant_expression_p=*/false);
10601
        if (e1 == error_mark_node || e2 == error_mark_node)
10602
          return error_mark_node;
10603
 
10604
        return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10605
      }
10606
 
10607
    case SCOPE_REF:
10608
      {
10609
        tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10610
        tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10611
        if (e1 == error_mark_node || e2 == error_mark_node)
10612
          return error_mark_node;
10613
 
10614
        return build_qualified_name (/*type=*/NULL_TREE,
10615
                                     e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10616
      }
10617
 
10618
    case TYPEOF_TYPE:
10619
      {
10620
        tree type;
10621
 
10622
        ++cp_unevaluated_operand;
10623
        ++c_inhibit_evaluation_warnings;
10624
 
10625
        type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10626
                            complain, in_decl,
10627
                            /*integral_constant_expression_p=*/false);
10628
 
10629
        --cp_unevaluated_operand;
10630
        --c_inhibit_evaluation_warnings;
10631
 
10632
        type = finish_typeof (type);
10633
        return cp_build_qualified_type_real (type,
10634
                                             cp_type_quals (t)
10635
                                             | cp_type_quals (type),
10636
                                             complain);
10637
      }
10638
 
10639
    case DECLTYPE_TYPE:
10640
      {
10641
        tree type;
10642
 
10643
        ++cp_unevaluated_operand;
10644
        ++c_inhibit_evaluation_warnings;
10645
 
10646
        type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10647
                            complain, in_decl,
10648
                            /*integral_constant_expression_p=*/false);
10649
 
10650
        --cp_unevaluated_operand;
10651
        --c_inhibit_evaluation_warnings;
10652
 
10653
        if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10654
          type = lambda_capture_field_type (type);
10655
        else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10656
          type = lambda_return_type (type);
10657
        else
10658
          type = finish_decltype_type
10659
            (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10660
        return cp_build_qualified_type_real (type,
10661
                                             cp_type_quals (t)
10662
                                             | cp_type_quals (type),
10663
                                             complain);
10664
      }
10665
 
10666
    case TYPE_ARGUMENT_PACK:
10667
    case NONTYPE_ARGUMENT_PACK:
10668
      {
10669
        tree r = TYPE_P (t)
10670
          ? cxx_make_type (TREE_CODE (t))
10671
          : make_node (TREE_CODE (t));
10672
        tree packed_out =
10673
          tsubst_template_args (ARGUMENT_PACK_ARGS (t),
10674
                                args,
10675
                                complain,
10676
                                in_decl);
10677
        SET_ARGUMENT_PACK_ARGS (r, packed_out);
10678
 
10679
        /* For template nontype argument packs, also substitute into
10680
           the type.  */
10681
        if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10682
          TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10683
 
10684
        return r;
10685
      }
10686
      break;
10687
 
10688
    default:
10689
      sorry ("use of %qs in template",
10690
             tree_code_name [(int) TREE_CODE (t)]);
10691
      return error_mark_node;
10692
    }
10693
}
10694
 
10695
/* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10696
   type of the expression on the left-hand side of the "." or "->"
10697
   operator.  */
10698
 
10699
static tree
10700
tsubst_baselink (tree baselink, tree object_type,
10701
                 tree args, tsubst_flags_t complain, tree in_decl)
10702
{
10703
    tree name;
10704
    tree qualifying_scope;
10705
    tree fns;
10706
    tree optype;
10707
    tree template_args = 0;
10708
    bool template_id_p = false;
10709
 
10710
    /* A baselink indicates a function from a base class.  Both the
10711
       BASELINK_ACCESS_BINFO and the base class referenced may
10712
       indicate bases of the template class, rather than the
10713
       instantiated class.  In addition, lookups that were not
10714
       ambiguous before may be ambiguous now.  Therefore, we perform
10715
       the lookup again.  */
10716
    qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10717
    qualifying_scope = tsubst (qualifying_scope, args,
10718
                               complain, in_decl);
10719
    fns = BASELINK_FUNCTIONS (baselink);
10720
    optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10721
    if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10722
      {
10723
        template_id_p = true;
10724
        template_args = TREE_OPERAND (fns, 1);
10725
        fns = TREE_OPERAND (fns, 0);
10726
        if (template_args)
10727
          template_args = tsubst_template_args (template_args, args,
10728
                                                complain, in_decl);
10729
      }
10730
    name = DECL_NAME (get_first_fn (fns));
10731
    if (IDENTIFIER_TYPENAME_P (name))
10732
      name = mangle_conv_op_name_for_type (optype);
10733
    baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10734
    if (!baselink)
10735
      return error_mark_node;
10736
 
10737
    /* If lookup found a single function, mark it as used at this
10738
       point.  (If it lookup found multiple functions the one selected
10739
       later by overload resolution will be marked as used at that
10740
       point.)  */
10741
    if (BASELINK_P (baselink))
10742
      fns = BASELINK_FUNCTIONS (baselink);
10743
    if (!template_id_p && !really_overloaded_fn (fns))
10744
      mark_used (OVL_CURRENT (fns));
10745
 
10746
    /* Add back the template arguments, if present.  */
10747
    if (BASELINK_P (baselink) && template_id_p)
10748
      BASELINK_FUNCTIONS (baselink)
10749
        = build_nt (TEMPLATE_ID_EXPR,
10750
                    BASELINK_FUNCTIONS (baselink),
10751
                    template_args);
10752
    /* Update the conversion operator type.  */
10753
    BASELINK_OPTYPE (baselink) = optype;
10754
 
10755
    if (!object_type)
10756
      object_type = current_class_type;
10757
    return adjust_result_of_qualified_name_lookup (baselink,
10758
                                                   qualifying_scope,
10759
                                                   object_type);
10760
}
10761
 
10762
/* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10763
   true if the qualified-id will be a postfix-expression in-and-of
10764
   itself; false if more of the postfix-expression follows the
10765
   QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10766
   of "&".  */
10767
 
10768
static tree
10769
tsubst_qualified_id (tree qualified_id, tree args,
10770
                     tsubst_flags_t complain, tree in_decl,
10771
                     bool done, bool address_p)
10772
{
10773
  tree expr;
10774
  tree scope;
10775
  tree name;
10776
  bool is_template;
10777
  tree template_args;
10778
 
10779
  gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10780
 
10781
  /* Figure out what name to look up.  */
10782
  name = TREE_OPERAND (qualified_id, 1);
10783
  if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10784
    {
10785
      is_template = true;
10786
      template_args = TREE_OPERAND (name, 1);
10787
      if (template_args)
10788
        template_args = tsubst_template_args (template_args, args,
10789
                                              complain, in_decl);
10790
      name = TREE_OPERAND (name, 0);
10791
    }
10792
  else
10793
    {
10794
      is_template = false;
10795
      template_args = NULL_TREE;
10796
    }
10797
 
10798
  /* Substitute into the qualifying scope.  When there are no ARGS, we
10799
     are just trying to simplify a non-dependent expression.  In that
10800
     case the qualifying scope may be dependent, and, in any case,
10801
     substituting will not help.  */
10802
  scope = TREE_OPERAND (qualified_id, 0);
10803
  if (args)
10804
    {
10805
      scope = tsubst (scope, args, complain, in_decl);
10806
      expr = tsubst_copy (name, args, complain, in_decl);
10807
    }
10808
  else
10809
    expr = name;
10810
 
10811
  if (dependent_scope_p (scope))
10812
    return build_qualified_name (NULL_TREE, scope, expr,
10813
                                 QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10814
 
10815
  if (!BASELINK_P (name) && !DECL_P (expr))
10816
    {
10817
      if (TREE_CODE (expr) == BIT_NOT_EXPR)
10818
        {
10819
          /* A BIT_NOT_EXPR is used to represent a destructor.  */
10820
          if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10821
            {
10822
              error ("qualifying type %qT does not match destructor name ~%qT",
10823
                     scope, TREE_OPERAND (expr, 0));
10824
              expr = error_mark_node;
10825
            }
10826
          else
10827
            expr = lookup_qualified_name (scope, complete_dtor_identifier,
10828
                                          /*is_type_p=*/0, false);
10829
        }
10830
      else
10831
        expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10832
      if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10833
                     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10834
        {
10835
          if (complain & tf_error)
10836
            {
10837
              error ("dependent-name %qE is parsed as a non-type, but "
10838
                     "instantiation yields a type", qualified_id);
10839
              inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10840
            }
10841
          return error_mark_node;
10842
        }
10843
    }
10844
 
10845
  if (DECL_P (expr))
10846
    {
10847
      check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10848
                                           scope);
10849
      /* Remember that there was a reference to this entity.  */
10850
      mark_used (expr);
10851
    }
10852
 
10853
  if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10854
    {
10855
      if (complain & tf_error)
10856
        qualified_name_lookup_error (scope,
10857
                                     TREE_OPERAND (qualified_id, 1),
10858
                                     expr, input_location);
10859
      return error_mark_node;
10860
    }
10861
 
10862
  if (is_template)
10863
    expr = lookup_template_function (expr, template_args);
10864
 
10865
  if (expr == error_mark_node && complain & tf_error)
10866
    qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10867
                                 expr, input_location);
10868
  else if (TYPE_P (scope))
10869
    {
10870
      expr = (adjust_result_of_qualified_name_lookup
10871
              (expr, scope, current_class_type));
10872
      expr = (finish_qualified_id_expr
10873
              (scope, expr, done, address_p,
10874
               QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10875
               /*template_arg_p=*/false));
10876
    }
10877
 
10878
  /* Expressions do not generally have reference type.  */
10879
  if (TREE_CODE (expr) != SCOPE_REF
10880
      /* However, if we're about to form a pointer-to-member, we just
10881
         want the referenced member referenced.  */
10882
      && TREE_CODE (expr) != OFFSET_REF)
10883
    expr = convert_from_reference (expr);
10884
 
10885
  return expr;
10886
}
10887
 
10888
/* Like tsubst, but deals with expressions.  This function just replaces
10889
   template parms; to finish processing the resultant expression, use
10890
   tsubst_expr.  */
10891
 
10892
static tree
10893
tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10894
{
10895
  enum tree_code code;
10896
  tree r;
10897
 
10898
  if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10899
    return t;
10900
 
10901
  code = TREE_CODE (t);
10902
 
10903
  switch (code)
10904
    {
10905
    case PARM_DECL:
10906
      r = retrieve_local_specialization (t);
10907
 
10908
      if (r == NULL)
10909
        {
10910
          tree c;
10911
          /* This can happen for a parameter name used later in a function
10912
             declaration (such as in a late-specified return type).  Just
10913
             make a dummy decl, since it's only used for its type.  */
10914
          gcc_assert (cp_unevaluated_operand != 0);
10915
          /* We copy T because want to tsubst the PARM_DECL only,
10916
             not the following PARM_DECLs that are chained to T.  */
10917
          c = copy_node (t);
10918
          r = tsubst_decl (c, args, complain);
10919
          /* Give it the template pattern as its context; its true context
10920
             hasn't been instantiated yet and this is good enough for
10921
             mangling.  */
10922
          DECL_CONTEXT (r) = DECL_CONTEXT (t);
10923
        }
10924
 
10925
      if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10926
        r = ARGUMENT_PACK_SELECT_ARG (r);
10927
      mark_used (r);
10928
      return r;
10929
 
10930
    case CONST_DECL:
10931
      {
10932
        tree enum_type;
10933
        tree v;
10934
 
10935
        if (DECL_TEMPLATE_PARM_P (t))
10936
          return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10937
        /* There is no need to substitute into namespace-scope
10938
           enumerators.  */
10939
        if (DECL_NAMESPACE_SCOPE_P (t))
10940
          return t;
10941
        /* If ARGS is NULL, then T is known to be non-dependent.  */
10942
        if (args == NULL_TREE)
10943
          return integral_constant_value (t);
10944
 
10945
        /* Unfortunately, we cannot just call lookup_name here.
10946
           Consider:
10947
 
10948
             template <int I> int f() {
10949
             enum E { a = I };
10950
             struct S { void g() { E e = a; } };
10951
             };
10952
 
10953
           When we instantiate f<7>::S::g(), say, lookup_name is not
10954
           clever enough to find f<7>::a.  */
10955
        enum_type
10956
          = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10957
                              /*entering_scope=*/0);
10958
 
10959
        for (v = TYPE_VALUES (enum_type);
10960
             v != NULL_TREE;
10961
             v = TREE_CHAIN (v))
10962
          if (TREE_PURPOSE (v) == DECL_NAME (t))
10963
            return TREE_VALUE (v);
10964
 
10965
          /* We didn't find the name.  That should never happen; if
10966
             name-lookup found it during preliminary parsing, we
10967
             should find it again here during instantiation.  */
10968
        gcc_unreachable ();
10969
      }
10970
      return t;
10971
 
10972
    case FIELD_DECL:
10973
      if (DECL_CONTEXT (t))
10974
        {
10975
          tree ctx;
10976
 
10977
          ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10978
                                  /*entering_scope=*/1);
10979
          if (ctx != DECL_CONTEXT (t))
10980
            {
10981
              tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10982
              if (!r)
10983
                {
10984
                  if (complain & tf_error)
10985
                    error ("using invalid field %qD", t);
10986
                  return error_mark_node;
10987
                }
10988
              return r;
10989
            }
10990
        }
10991
 
10992
      return t;
10993
 
10994
    case VAR_DECL:
10995
    case FUNCTION_DECL:
10996
      if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10997
          || local_variable_p (t))
10998
        t = tsubst (t, args, complain, in_decl);
10999
      mark_used (t);
11000
      return t;
11001
 
11002
    case BASELINK:
11003
      return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11004
 
11005
    case TEMPLATE_DECL:
11006
      if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11007
        return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11008
                       args, complain, in_decl);
11009
      else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11010
        return tsubst (t, args, complain, in_decl);
11011
      else if (DECL_CLASS_SCOPE_P (t)
11012
               && uses_template_parms (DECL_CONTEXT (t)))
11013
        {
11014
          /* Template template argument like the following example need
11015
             special treatment:
11016
 
11017
               template <template <class> class TT> struct C {};
11018
               template <class T> struct D {
11019
                 template <class U> struct E {};
11020
                 C<E> c;                                // #1
11021
               };
11022
               D<int> d;                                // #2
11023
 
11024
             We are processing the template argument `E' in #1 for
11025
             the template instantiation #2.  Originally, `E' is a
11026
             TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11027
             have to substitute this with one having context `D<int>'.  */
11028
 
11029
          tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11030
          return lookup_field (context, DECL_NAME(t), 0, false);
11031
        }
11032
      else
11033
        /* Ordinary template template argument.  */
11034
        return t;
11035
 
11036
    case CAST_EXPR:
11037
    case REINTERPRET_CAST_EXPR:
11038
    case CONST_CAST_EXPR:
11039
    case STATIC_CAST_EXPR:
11040
    case DYNAMIC_CAST_EXPR:
11041
    case NOP_EXPR:
11042
      return build1
11043
        (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11044
         tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11045
 
11046
    case SIZEOF_EXPR:
11047
      if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11048
        {
11049
          /* We only want to compute the number of arguments.  */
11050
          tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11051
                                                complain, in_decl);
11052
          int len = 0;
11053
 
11054
          if (TREE_CODE (expanded) == TREE_VEC)
11055
            len = TREE_VEC_LENGTH (expanded);
11056
 
11057
          if (expanded == error_mark_node)
11058
            return error_mark_node;
11059
          else if (PACK_EXPANSION_P (expanded)
11060
                   || (TREE_CODE (expanded) == TREE_VEC
11061
                       && len > 0
11062
                       && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11063
            {
11064
              if (TREE_CODE (expanded) == TREE_VEC)
11065
                expanded = TREE_VEC_ELT (expanded, len - 1);
11066
 
11067
              if (TYPE_P (expanded))
11068
                return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
11069
                                                   complain & tf_error);
11070
              else
11071
                return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11072
                                                   complain & tf_error);
11073
            }
11074
          else
11075
            return build_int_cst (size_type_node, len);
11076
        }
11077
      /* Fall through */
11078
 
11079
    case INDIRECT_REF:
11080
    case NEGATE_EXPR:
11081
    case TRUTH_NOT_EXPR:
11082
    case BIT_NOT_EXPR:
11083
    case ADDR_EXPR:
11084
    case UNARY_PLUS_EXPR:      /* Unary + */
11085
    case ALIGNOF_EXPR:
11086
    case ARROW_EXPR:
11087
    case THROW_EXPR:
11088
    case TYPEID_EXPR:
11089
    case REALPART_EXPR:
11090
    case IMAGPART_EXPR:
11091
      return build1
11092
        (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11093
         tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11094
 
11095
    case COMPONENT_REF:
11096
      {
11097
        tree object;
11098
        tree name;
11099
 
11100
        object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11101
        name = TREE_OPERAND (t, 1);
11102
        if (TREE_CODE (name) == BIT_NOT_EXPR)
11103
          {
11104
            name = tsubst_copy (TREE_OPERAND (name, 0), args,
11105
                                complain, in_decl);
11106
            name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11107
          }
11108
        else if (TREE_CODE (name) == SCOPE_REF
11109
                 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11110
          {
11111
            tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11112
                                     complain, in_decl);
11113
            name = TREE_OPERAND (name, 1);
11114
            name = tsubst_copy (TREE_OPERAND (name, 0), args,
11115
                                complain, in_decl);
11116
            name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11117
            name = build_qualified_name (/*type=*/NULL_TREE,
11118
                                         base, name,
11119
                                         /*template_p=*/false);
11120
          }
11121
        else if (TREE_CODE (name) == BASELINK)
11122
          name = tsubst_baselink (name,
11123
                                  non_reference (TREE_TYPE (object)),
11124
                                  args, complain,
11125
                                  in_decl);
11126
        else
11127
          name = tsubst_copy (name, args, complain, in_decl);
11128
        return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11129
      }
11130
 
11131
    case PLUS_EXPR:
11132
    case MINUS_EXPR:
11133
    case MULT_EXPR:
11134
    case TRUNC_DIV_EXPR:
11135
    case CEIL_DIV_EXPR:
11136
    case FLOOR_DIV_EXPR:
11137
    case ROUND_DIV_EXPR:
11138
    case EXACT_DIV_EXPR:
11139
    case BIT_AND_EXPR:
11140
    case BIT_IOR_EXPR:
11141
    case BIT_XOR_EXPR:
11142
    case TRUNC_MOD_EXPR:
11143
    case FLOOR_MOD_EXPR:
11144
    case TRUTH_ANDIF_EXPR:
11145
    case TRUTH_ORIF_EXPR:
11146
    case TRUTH_AND_EXPR:
11147
    case TRUTH_OR_EXPR:
11148
    case RSHIFT_EXPR:
11149
    case LSHIFT_EXPR:
11150
    case RROTATE_EXPR:
11151
    case LROTATE_EXPR:
11152
    case EQ_EXPR:
11153
    case NE_EXPR:
11154
    case MAX_EXPR:
11155
    case MIN_EXPR:
11156
    case LE_EXPR:
11157
    case GE_EXPR:
11158
    case LT_EXPR:
11159
    case GT_EXPR:
11160
    case COMPOUND_EXPR:
11161
    case DOTSTAR_EXPR:
11162
    case MEMBER_REF:
11163
    case PREDECREMENT_EXPR:
11164
    case PREINCREMENT_EXPR:
11165
    case POSTDECREMENT_EXPR:
11166
    case POSTINCREMENT_EXPR:
11167
      return build_nt
11168
        (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11169
         tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11170
 
11171
    case SCOPE_REF:
11172
      return build_qualified_name (/*type=*/NULL_TREE,
11173
                                   tsubst_copy (TREE_OPERAND (t, 0),
11174
                                                args, complain, in_decl),
11175
                                   tsubst_copy (TREE_OPERAND (t, 1),
11176
                                                args, complain, in_decl),
11177
                                   QUALIFIED_NAME_IS_TEMPLATE (t));
11178
 
11179
    case ARRAY_REF:
11180
      return build_nt
11181
        (ARRAY_REF,
11182
         tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11183
         tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11184
         NULL_TREE, NULL_TREE);
11185
 
11186
    case CALL_EXPR:
11187
      {
11188
        int n = VL_EXP_OPERAND_LENGTH (t);
11189
        tree result = build_vl_exp (CALL_EXPR, n);
11190
        int i;
11191
        for (i = 0; i < n; i++)
11192
          TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11193
                                             complain, in_decl);
11194
        return result;
11195
      }
11196
 
11197
    case COND_EXPR:
11198
    case MODOP_EXPR:
11199
    case PSEUDO_DTOR_EXPR:
11200
      {
11201
        r = build_nt
11202
          (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11203
           tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11204
           tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11205
        TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11206
        return r;
11207
      }
11208
 
11209
    case NEW_EXPR:
11210
      {
11211
        r = build_nt
11212
        (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11213
         tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11214
         tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11215
        NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11216
        return r;
11217
      }
11218
 
11219
    case DELETE_EXPR:
11220
      {
11221
        r = build_nt
11222
        (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11223
         tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11224
        DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11225
        DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11226
        return r;
11227
      }
11228
 
11229
    case TEMPLATE_ID_EXPR:
11230
      {
11231
        /* Substituted template arguments */
11232
        tree fn = TREE_OPERAND (t, 0);
11233
        tree targs = TREE_OPERAND (t, 1);
11234
 
11235
        fn = tsubst_copy (fn, args, complain, in_decl);
11236
        if (targs)
11237
          targs = tsubst_template_args (targs, args, complain, in_decl);
11238
 
11239
        return lookup_template_function (fn, targs);
11240
      }
11241
 
11242
    case TREE_LIST:
11243
      {
11244
        tree purpose, value, chain;
11245
 
11246
        if (t == void_list_node)
11247
          return t;
11248
 
11249
        purpose = TREE_PURPOSE (t);
11250
        if (purpose)
11251
          purpose = tsubst_copy (purpose, args, complain, in_decl);
11252
        value = TREE_VALUE (t);
11253
        if (value)
11254
          value = tsubst_copy (value, args, complain, in_decl);
11255
        chain = TREE_CHAIN (t);
11256
        if (chain && chain != void_type_node)
11257
          chain = tsubst_copy (chain, args, complain, in_decl);
11258
        if (purpose == TREE_PURPOSE (t)
11259
            && value == TREE_VALUE (t)
11260
            && chain == TREE_CHAIN (t))
11261
          return t;
11262
        return tree_cons (purpose, value, chain);
11263
      }
11264
 
11265
    case RECORD_TYPE:
11266
    case UNION_TYPE:
11267
    case ENUMERAL_TYPE:
11268
    case INTEGER_TYPE:
11269
    case TEMPLATE_TYPE_PARM:
11270
    case TEMPLATE_TEMPLATE_PARM:
11271
    case BOUND_TEMPLATE_TEMPLATE_PARM:
11272
    case TEMPLATE_PARM_INDEX:
11273
    case POINTER_TYPE:
11274
    case REFERENCE_TYPE:
11275
    case OFFSET_TYPE:
11276
    case FUNCTION_TYPE:
11277
    case METHOD_TYPE:
11278
    case ARRAY_TYPE:
11279
    case TYPENAME_TYPE:
11280
    case UNBOUND_CLASS_TEMPLATE:
11281
    case TYPEOF_TYPE:
11282
    case DECLTYPE_TYPE:
11283
    case TYPE_DECL:
11284
      return tsubst (t, args, complain, in_decl);
11285
 
11286
    case IDENTIFIER_NODE:
11287
      if (IDENTIFIER_TYPENAME_P (t))
11288
        {
11289
          tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11290
          return mangle_conv_op_name_for_type (new_type);
11291
        }
11292
      else
11293
        return t;
11294
 
11295
    case CONSTRUCTOR:
11296
      /* This is handled by tsubst_copy_and_build.  */
11297
      gcc_unreachable ();
11298
 
11299
    case VA_ARG_EXPR:
11300
      return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11301
                                          in_decl),
11302
                             tsubst (TREE_TYPE (t), args, complain, in_decl));
11303
 
11304
    case CLEANUP_POINT_EXPR:
11305
      /* We shouldn't have built any of these during initial template
11306
         generation.  Instead, they should be built during instantiation
11307
         in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11308
      gcc_unreachable ();
11309
 
11310
    case OFFSET_REF:
11311
      mark_used (TREE_OPERAND (t, 1));
11312
      return t;
11313
 
11314
    case EXPR_PACK_EXPANSION:
11315
      error ("invalid use of pack expansion expression");
11316
      return error_mark_node;
11317
 
11318
    case NONTYPE_ARGUMENT_PACK:
11319
      error ("use %<...%> to expand argument pack");
11320
      return error_mark_node;
11321
 
11322
    default:
11323
      return t;
11324
    }
11325
}
11326
 
11327
/* Like tsubst_copy, but specifically for OpenMP clauses.  */
11328
 
11329
static tree
11330
tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11331
                    tree in_decl)
11332
{
11333
  tree new_clauses = NULL, nc, oc;
11334
 
11335
  for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11336
    {
11337
      nc = copy_node (oc);
11338
      OMP_CLAUSE_CHAIN (nc) = new_clauses;
11339
      new_clauses = nc;
11340
 
11341
      switch (OMP_CLAUSE_CODE (nc))
11342
        {
11343
        case OMP_CLAUSE_LASTPRIVATE:
11344
          if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11345
            {
11346
              OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11347
              tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11348
                           in_decl, /*integral_constant_expression_p=*/false);
11349
              OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11350
                = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11351
            }
11352
          /* FALLTHRU */
11353
        case OMP_CLAUSE_PRIVATE:
11354
        case OMP_CLAUSE_SHARED:
11355
        case OMP_CLAUSE_FIRSTPRIVATE:
11356
        case OMP_CLAUSE_REDUCTION:
11357
        case OMP_CLAUSE_COPYIN:
11358
        case OMP_CLAUSE_COPYPRIVATE:
11359
        case OMP_CLAUSE_IF:
11360
        case OMP_CLAUSE_NUM_THREADS:
11361
        case OMP_CLAUSE_SCHEDULE:
11362
        case OMP_CLAUSE_COLLAPSE:
11363
          OMP_CLAUSE_OPERAND (nc, 0)
11364
            = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
11365
                           in_decl, /*integral_constant_expression_p=*/false);
11366
          break;
11367
        case OMP_CLAUSE_NOWAIT:
11368
        case OMP_CLAUSE_ORDERED:
11369
        case OMP_CLAUSE_DEFAULT:
11370
        case OMP_CLAUSE_UNTIED:
11371
          break;
11372
        default:
11373
          gcc_unreachable ();
11374
        }
11375
    }
11376
 
11377
  return finish_omp_clauses (nreverse (new_clauses));
11378
}
11379
 
11380
/* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11381
 
11382
static tree
11383
tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11384
                          tree in_decl)
11385
{
11386
#define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11387
 
11388
  tree purpose, value, chain;
11389
 
11390
  if (t == NULL)
11391
    return t;
11392
 
11393
  if (TREE_CODE (t) != TREE_LIST)
11394
    return tsubst_copy_and_build (t, args, complain, in_decl,
11395
                                  /*function_p=*/false,
11396
                                  /*integral_constant_expression_p=*/false);
11397
 
11398
  if (t == void_list_node)
11399
    return t;
11400
 
11401
  purpose = TREE_PURPOSE (t);
11402
  if (purpose)
11403
    purpose = RECUR (purpose);
11404
  value = TREE_VALUE (t);
11405
  if (value && TREE_CODE (value) != LABEL_DECL)
11406
    value = RECUR (value);
11407
  chain = TREE_CHAIN (t);
11408
  if (chain && chain != void_type_node)
11409
    chain = RECUR (chain);
11410
  return tree_cons (purpose, value, chain);
11411
#undef RECUR
11412
}
11413
 
11414
/* Substitute one OMP_FOR iterator.  */
11415
 
11416
static void
11417
tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11418
                         tree condv, tree incrv, tree *clauses,
11419
                         tree args, tsubst_flags_t complain, tree in_decl,
11420
                         bool integral_constant_expression_p)
11421
{
11422
#define RECUR(NODE)                             \
11423
  tsubst_expr ((NODE), args, complain, in_decl, \
11424
               integral_constant_expression_p)
11425
  tree decl, init, cond, incr, auto_node;
11426
 
11427
  init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11428
  gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11429
  decl = RECUR (TREE_OPERAND (init, 0));
11430
  init = TREE_OPERAND (init, 1);
11431
  auto_node = type_uses_auto (TREE_TYPE (decl));
11432
  if (auto_node && init)
11433
    {
11434
      tree init_expr = init;
11435
      if (TREE_CODE (init_expr) == DECL_EXPR)
11436
        init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11437
      init_expr = RECUR (init_expr);
11438
      TREE_TYPE (decl)
11439
        = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11440
    }
11441
  gcc_assert (!type_dependent_expression_p (decl));
11442
 
11443
  if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11444
    {
11445
      cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11446
      incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11447
      if (TREE_CODE (incr) == MODIFY_EXPR)
11448
        incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11449
                                    RECUR (TREE_OPERAND (incr, 1)),
11450
                                    complain);
11451
      else
11452
        incr = RECUR (incr);
11453
      TREE_VEC_ELT (declv, i) = decl;
11454
      TREE_VEC_ELT (initv, i) = init;
11455
      TREE_VEC_ELT (condv, i) = cond;
11456
      TREE_VEC_ELT (incrv, i) = incr;
11457
      return;
11458
    }
11459
 
11460
  if (init && TREE_CODE (init) != DECL_EXPR)
11461
    {
11462
      tree c;
11463
      for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11464
        {
11465
          if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11466
               || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11467
              && OMP_CLAUSE_DECL (c) == decl)
11468
            break;
11469
          else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11470
                   && OMP_CLAUSE_DECL (c) == decl)
11471
            error ("iteration variable %qD should not be firstprivate", decl);
11472
          else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11473
                   && OMP_CLAUSE_DECL (c) == decl)
11474
            error ("iteration variable %qD should not be reduction", decl);
11475
        }
11476
      if (c == NULL)
11477
        {
11478
          c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11479
          OMP_CLAUSE_DECL (c) = decl;
11480
          c = finish_omp_clauses (c);
11481
          if (c)
11482
            {
11483
              OMP_CLAUSE_CHAIN (c) = *clauses;
11484
              *clauses = c;
11485
            }
11486
        }
11487
    }
11488
  cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11489
  if (COMPARISON_CLASS_P (cond))
11490
    cond = build2 (TREE_CODE (cond), boolean_type_node,
11491
                   RECUR (TREE_OPERAND (cond, 0)),
11492
                   RECUR (TREE_OPERAND (cond, 1)));
11493
  else
11494
    cond = RECUR (cond);
11495
  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11496
  switch (TREE_CODE (incr))
11497
    {
11498
    case PREINCREMENT_EXPR:
11499
    case PREDECREMENT_EXPR:
11500
    case POSTINCREMENT_EXPR:
11501
    case POSTDECREMENT_EXPR:
11502
      incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11503
                     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11504
      break;
11505
    case MODIFY_EXPR:
11506
      if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11507
          || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11508
        {
11509
          tree rhs = TREE_OPERAND (incr, 1);
11510
          incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11511
                         RECUR (TREE_OPERAND (incr, 0)),
11512
                         build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11513
                                 RECUR (TREE_OPERAND (rhs, 0)),
11514
                                 RECUR (TREE_OPERAND (rhs, 1))));
11515
        }
11516
      else
11517
        incr = RECUR (incr);
11518
      break;
11519
    case MODOP_EXPR:
11520
      if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11521
          || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11522
        {
11523
          tree lhs = RECUR (TREE_OPERAND (incr, 0));
11524
          incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11525
                         build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11526
                                 TREE_TYPE (decl), lhs,
11527
                                 RECUR (TREE_OPERAND (incr, 2))));
11528
        }
11529
      else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11530
               && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11531
                   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11532
        {
11533
          tree rhs = TREE_OPERAND (incr, 2);
11534
          incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11535
                         RECUR (TREE_OPERAND (incr, 0)),
11536
                         build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11537
                                 RECUR (TREE_OPERAND (rhs, 0)),
11538
                                 RECUR (TREE_OPERAND (rhs, 1))));
11539
        }
11540
      else
11541
        incr = RECUR (incr);
11542
      break;
11543
    default:
11544
      incr = RECUR (incr);
11545
      break;
11546
    }
11547
 
11548
  TREE_VEC_ELT (declv, i) = decl;
11549
  TREE_VEC_ELT (initv, i) = init;
11550
  TREE_VEC_ELT (condv, i) = cond;
11551
  TREE_VEC_ELT (incrv, i) = incr;
11552
#undef RECUR
11553
}
11554
 
11555
/* Like tsubst_copy for expressions, etc. but also does semantic
11556
   processing.  */
11557
 
11558
static tree
11559
tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11560
             bool integral_constant_expression_p)
11561
{
11562
#define RECUR(NODE)                             \
11563
  tsubst_expr ((NODE), args, complain, in_decl, \
11564
               integral_constant_expression_p)
11565
 
11566
  tree stmt, tmp;
11567
 
11568
  if (t == NULL_TREE || t == error_mark_node)
11569
    return t;
11570
 
11571
  if (EXPR_HAS_LOCATION (t))
11572
    input_location = EXPR_LOCATION (t);
11573
  if (STATEMENT_CODE_P (TREE_CODE (t)))
11574
    current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11575
 
11576
  switch (TREE_CODE (t))
11577
    {
11578
    case STATEMENT_LIST:
11579
      {
11580
        tree_stmt_iterator i;
11581
        for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11582
          RECUR (tsi_stmt (i));
11583
        break;
11584
      }
11585
 
11586
    case CTOR_INITIALIZER:
11587
      finish_mem_initializers (tsubst_initializer_list
11588
                               (TREE_OPERAND (t, 0), args));
11589
      break;
11590
 
11591
    case RETURN_EXPR:
11592
      finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11593
      break;
11594
 
11595
    case EXPR_STMT:
11596
      tmp = RECUR (EXPR_STMT_EXPR (t));
11597
      if (EXPR_STMT_STMT_EXPR_RESULT (t))
11598
        finish_stmt_expr_expr (tmp, cur_stmt_expr);
11599
      else
11600
        finish_expr_stmt (tmp);
11601
      break;
11602
 
11603
    case USING_STMT:
11604
      do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11605
      break;
11606
 
11607
    case DECL_EXPR:
11608
      {
11609
        tree decl;
11610
        tree init;
11611
 
11612
        decl = DECL_EXPR_DECL (t);
11613
        if (TREE_CODE (decl) == LABEL_DECL)
11614
          finish_label_decl (DECL_NAME (decl));
11615
        else if (TREE_CODE (decl) == USING_DECL)
11616
          {
11617
            tree scope = USING_DECL_SCOPE (decl);
11618
            tree name = DECL_NAME (decl);
11619
            tree decl;
11620
 
11621
            scope = RECUR (scope);
11622
            decl = lookup_qualified_name (scope, name,
11623
                                          /*is_type_p=*/false,
11624
                                          /*complain=*/false);
11625
            if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11626
              qualified_name_lookup_error (scope, name, decl, input_location);
11627
            else
11628
              do_local_using_decl (decl, scope, name);
11629
          }
11630
        else
11631
          {
11632
            init = DECL_INITIAL (decl);
11633
            decl = tsubst (decl, args, complain, in_decl);
11634
            if (decl != error_mark_node)
11635
              {
11636
                /* By marking the declaration as instantiated, we avoid
11637
                   trying to instantiate it.  Since instantiate_decl can't
11638
                   handle local variables, and since we've already done
11639
                   all that needs to be done, that's the right thing to
11640
                   do.  */
11641
                if (TREE_CODE (decl) == VAR_DECL)
11642
                  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11643
                if (TREE_CODE (decl) == VAR_DECL
11644
                    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11645
                  /* Anonymous aggregates are a special case.  */
11646
                  finish_anon_union (decl);
11647
                else
11648
                  {
11649
                    maybe_push_decl (decl);
11650
                    if (TREE_CODE (decl) == VAR_DECL
11651
                        && DECL_PRETTY_FUNCTION_P (decl))
11652
                      {
11653
                        /* For __PRETTY_FUNCTION__ we have to adjust the
11654
                           initializer.  */
11655
                        const char *const name
11656
                          = cxx_printable_name (current_function_decl, 2);
11657
                        init = cp_fname_init (name, &TREE_TYPE (decl));
11658
                      }
11659
                    else
11660
                      {
11661
                        tree t = RECUR (init);
11662
 
11663
                        if (init && !t)
11664
                          /* If we had an initializer but it
11665
                             instantiated to nothing,
11666
                             value-initialize the object.  This will
11667
                             only occur when the initializer was a
11668
                             pack expansion where the parameter packs
11669
                             used in that expansion were of length
11670
                             zero.  */
11671
                          init = build_value_init (TREE_TYPE (decl));
11672
                        else
11673
                          init = t;
11674
                      }
11675
 
11676
                    cp_finish_decl (decl, init, false, NULL_TREE, 0);
11677
                  }
11678
              }
11679
          }
11680
 
11681
        /* A DECL_EXPR can also be used as an expression, in the condition
11682
           clause of an if/for/while construct.  */
11683
        return decl;
11684
      }
11685
 
11686
    case FOR_STMT:
11687
      stmt = begin_for_stmt ();
11688
                          RECUR (FOR_INIT_STMT (t));
11689
      finish_for_init_stmt (stmt);
11690
      tmp = RECUR (FOR_COND (t));
11691
      finish_for_cond (tmp, stmt);
11692
      tmp = RECUR (FOR_EXPR (t));
11693
      finish_for_expr (tmp, stmt);
11694
      RECUR (FOR_BODY (t));
11695
      finish_for_stmt (stmt);
11696
      break;
11697
 
11698
    case WHILE_STMT:
11699
      stmt = begin_while_stmt ();
11700
      tmp = RECUR (WHILE_COND (t));
11701
      finish_while_stmt_cond (tmp, stmt);
11702
      RECUR (WHILE_BODY (t));
11703
      finish_while_stmt (stmt);
11704
      break;
11705
 
11706
    case DO_STMT:
11707
      stmt = begin_do_stmt ();
11708
      RECUR (DO_BODY (t));
11709
      finish_do_body (stmt);
11710
      tmp = RECUR (DO_COND (t));
11711
      finish_do_stmt (tmp, stmt);
11712
      break;
11713
 
11714
    case IF_STMT:
11715
      stmt = begin_if_stmt ();
11716
      tmp = RECUR (IF_COND (t));
11717
      finish_if_stmt_cond (tmp, stmt);
11718
      RECUR (THEN_CLAUSE (t));
11719
      finish_then_clause (stmt);
11720
 
11721
      if (ELSE_CLAUSE (t))
11722
        {
11723
          begin_else_clause (stmt);
11724
          RECUR (ELSE_CLAUSE (t));
11725
          finish_else_clause (stmt);
11726
        }
11727
 
11728
      finish_if_stmt (stmt);
11729
      break;
11730
 
11731
    case BIND_EXPR:
11732
      if (BIND_EXPR_BODY_BLOCK (t))
11733
        stmt = begin_function_body ();
11734
      else
11735
        stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11736
                                    ? BCS_TRY_BLOCK : 0);
11737
 
11738
      RECUR (BIND_EXPR_BODY (t));
11739
 
11740
      if (BIND_EXPR_BODY_BLOCK (t))
11741
        finish_function_body (stmt);
11742
      else
11743
        finish_compound_stmt (stmt);
11744
      break;
11745
 
11746
    case BREAK_STMT:
11747
      finish_break_stmt ();
11748
      break;
11749
 
11750
    case CONTINUE_STMT:
11751
      finish_continue_stmt ();
11752
      break;
11753
 
11754
    case SWITCH_STMT:
11755
      stmt = begin_switch_stmt ();
11756
      tmp = RECUR (SWITCH_STMT_COND (t));
11757
      finish_switch_cond (tmp, stmt);
11758
      RECUR (SWITCH_STMT_BODY (t));
11759
      finish_switch_stmt (stmt);
11760
      break;
11761
 
11762
    case CASE_LABEL_EXPR:
11763
      finish_case_label (EXPR_LOCATION (t),
11764
                         RECUR (CASE_LOW (t)),
11765
                         RECUR (CASE_HIGH (t)));
11766
      break;
11767
 
11768
    case LABEL_EXPR:
11769
      {
11770
        tree decl = LABEL_EXPR_LABEL (t);
11771
        tree label;
11772
 
11773
        label = finish_label_stmt (DECL_NAME (decl));
11774
        if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11775
          cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11776
      }
11777
      break;
11778
 
11779
    case GOTO_EXPR:
11780
      tmp = GOTO_DESTINATION (t);
11781
      if (TREE_CODE (tmp) != LABEL_DECL)
11782
        /* Computed goto's must be tsubst'd into.  On the other hand,
11783
           non-computed gotos must not be; the identifier in question
11784
           will have no binding.  */
11785
        tmp = RECUR (tmp);
11786
      else
11787
        tmp = DECL_NAME (tmp);
11788
      finish_goto_stmt (tmp);
11789
      break;
11790
 
11791
    case ASM_EXPR:
11792
      tmp = finish_asm_stmt
11793
        (ASM_VOLATILE_P (t),
11794
         RECUR (ASM_STRING (t)),
11795
         tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11796
         tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11797
         tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11798
         tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11799
      {
11800
        tree asm_expr = tmp;
11801
        if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11802
          asm_expr = TREE_OPERAND (asm_expr, 0);
11803
        ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11804
      }
11805
      break;
11806
 
11807
    case TRY_BLOCK:
11808
      if (CLEANUP_P (t))
11809
        {
11810
          stmt = begin_try_block ();
11811
          RECUR (TRY_STMTS (t));
11812
          finish_cleanup_try_block (stmt);
11813
          finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11814
        }
11815
      else
11816
        {
11817
          tree compound_stmt = NULL_TREE;
11818
 
11819
          if (FN_TRY_BLOCK_P (t))
11820
            stmt = begin_function_try_block (&compound_stmt);
11821
          else
11822
            stmt = begin_try_block ();
11823
 
11824
          RECUR (TRY_STMTS (t));
11825
 
11826
          if (FN_TRY_BLOCK_P (t))
11827
            finish_function_try_block (stmt);
11828
          else
11829
            finish_try_block (stmt);
11830
 
11831
          RECUR (TRY_HANDLERS (t));
11832
          if (FN_TRY_BLOCK_P (t))
11833
            finish_function_handler_sequence (stmt, compound_stmt);
11834
          else
11835
            finish_handler_sequence (stmt);
11836
        }
11837
      break;
11838
 
11839
    case HANDLER:
11840
      {
11841
        tree decl = HANDLER_PARMS (t);
11842
 
11843
        if (decl)
11844
          {
11845
            decl = tsubst (decl, args, complain, in_decl);
11846
            /* Prevent instantiate_decl from trying to instantiate
11847
               this variable.  We've already done all that needs to be
11848
               done.  */
11849
            if (decl != error_mark_node)
11850
              DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11851
          }
11852
        stmt = begin_handler ();
11853
        finish_handler_parms (decl, stmt);
11854
        RECUR (HANDLER_BODY (t));
11855
        finish_handler (stmt);
11856
      }
11857
      break;
11858
 
11859
    case TAG_DEFN:
11860
      tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11861
      break;
11862
 
11863
    case STATIC_ASSERT:
11864
      {
11865
        tree condition =
11866
          tsubst_expr (STATIC_ASSERT_CONDITION (t),
11867
                       args,
11868
                       complain, in_decl,
11869
                       /*integral_constant_expression_p=*/true);
11870
        finish_static_assert (condition,
11871
                              STATIC_ASSERT_MESSAGE (t),
11872
                              STATIC_ASSERT_SOURCE_LOCATION (t),
11873
                              /*member_p=*/false);
11874
      }
11875
      break;
11876
 
11877
    case OMP_PARALLEL:
11878
      tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11879
                                args, complain, in_decl);
11880
      stmt = begin_omp_parallel ();
11881
      RECUR (OMP_PARALLEL_BODY (t));
11882
      OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11883
        = OMP_PARALLEL_COMBINED (t);
11884
      break;
11885
 
11886
    case OMP_TASK:
11887
      tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11888
                                args, complain, in_decl);
11889
      stmt = begin_omp_task ();
11890
      RECUR (OMP_TASK_BODY (t));
11891
      finish_omp_task (tmp, stmt);
11892
      break;
11893
 
11894
    case OMP_FOR:
11895
      {
11896
        tree clauses, body, pre_body;
11897
        tree declv, initv, condv, incrv;
11898
        int i;
11899
 
11900
        clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11901
                                      args, complain, in_decl);
11902
        declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11903
        initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11904
        condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11905
        incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11906
 
11907
        for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11908
          tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11909
                                   &clauses, args, complain, in_decl,
11910
                                   integral_constant_expression_p);
11911
 
11912
        stmt = begin_omp_structured_block ();
11913
 
11914
        for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11915
          if (TREE_VEC_ELT (initv, i) == NULL
11916
              || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11917
            TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11918
          else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11919
            {
11920
              tree init = RECUR (TREE_VEC_ELT (initv, i));
11921
              gcc_assert (init == TREE_VEC_ELT (declv, i));
11922
              TREE_VEC_ELT (initv, i) = NULL_TREE;
11923
            }
11924
          else
11925
            {
11926
              tree decl_expr = TREE_VEC_ELT (initv, i);
11927
              tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11928
              gcc_assert (init != NULL);
11929
              TREE_VEC_ELT (initv, i) = RECUR (init);
11930
              DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11931
              RECUR (decl_expr);
11932
              DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11933
            }
11934
 
11935
        pre_body = push_stmt_list ();
11936
        RECUR (OMP_FOR_PRE_BODY (t));
11937
        pre_body = pop_stmt_list (pre_body);
11938
 
11939
        body = push_stmt_list ();
11940
        RECUR (OMP_FOR_BODY (t));
11941
        body = pop_stmt_list (body);
11942
 
11943
        t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11944
                            body, pre_body, clauses);
11945
 
11946
        add_stmt (finish_omp_structured_block (stmt));
11947
      }
11948
      break;
11949
 
11950
    case OMP_SECTIONS:
11951
    case OMP_SINGLE:
11952
      tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11953
      stmt = push_stmt_list ();
11954
      RECUR (OMP_BODY (t));
11955
      stmt = pop_stmt_list (stmt);
11956
 
11957
      t = copy_node (t);
11958
      OMP_BODY (t) = stmt;
11959
      OMP_CLAUSES (t) = tmp;
11960
      add_stmt (t);
11961
      break;
11962
 
11963
    case OMP_SECTION:
11964
    case OMP_CRITICAL:
11965
    case OMP_MASTER:
11966
    case OMP_ORDERED:
11967
      stmt = push_stmt_list ();
11968
      RECUR (OMP_BODY (t));
11969
      stmt = pop_stmt_list (stmt);
11970
 
11971
      t = copy_node (t);
11972
      OMP_BODY (t) = stmt;
11973
      add_stmt (t);
11974
      break;
11975
 
11976
    case OMP_ATOMIC:
11977
      gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11978
      {
11979
        tree op1 = TREE_OPERAND (t, 1);
11980
        tree lhs = RECUR (TREE_OPERAND (op1, 0));
11981
        tree rhs = RECUR (TREE_OPERAND (op1, 1));
11982
        finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11983
      }
11984
      break;
11985
 
11986
    case EXPR_PACK_EXPANSION:
11987
      error ("invalid use of pack expansion expression");
11988
      return error_mark_node;
11989
 
11990
    case NONTYPE_ARGUMENT_PACK:
11991
      error ("use %<...%> to expand argument pack");
11992
      return error_mark_node;
11993
 
11994
    default:
11995
      gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11996
 
11997
      return tsubst_copy_and_build (t, args, complain, in_decl,
11998
                                    /*function_p=*/false,
11999
                                    integral_constant_expression_p);
12000
    }
12001
 
12002
  return NULL_TREE;
12003
#undef RECUR
12004
}
12005
 
12006
/* T is a postfix-expression that is not being used in a function
12007
   call.  Return the substituted version of T.  */
12008
 
12009
static tree
12010
tsubst_non_call_postfix_expression (tree t, tree args,
12011
                                    tsubst_flags_t complain,
12012
                                    tree in_decl)
12013
{
12014
  if (TREE_CODE (t) == SCOPE_REF)
12015
    t = tsubst_qualified_id (t, args, complain, in_decl,
12016
                             /*done=*/false, /*address_p=*/false);
12017
  else
12018
    t = tsubst_copy_and_build (t, args, complain, in_decl,
12019
                               /*function_p=*/false,
12020
                               /*integral_constant_expression_p=*/false);
12021
 
12022
  return t;
12023
}
12024
 
12025
/* Like tsubst but deals with expressions and performs semantic
12026
   analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12027
 
12028
tree
12029
tsubst_copy_and_build (tree t,
12030
                       tree args,
12031
                       tsubst_flags_t complain,
12032
                       tree in_decl,
12033
                       bool function_p,
12034
                       bool integral_constant_expression_p)
12035
{
12036
#define RECUR(NODE)                                             \
12037
  tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12038
                         /*function_p=*/false,                  \
12039
                         integral_constant_expression_p)
12040
 
12041
  tree op1;
12042
 
12043
  if (t == NULL_TREE || t == error_mark_node)
12044
    return t;
12045
 
12046
  switch (TREE_CODE (t))
12047
    {
12048
    case USING_DECL:
12049
      t = DECL_NAME (t);
12050
      /* Fall through.  */
12051
    case IDENTIFIER_NODE:
12052
      {
12053
        tree decl;
12054
        cp_id_kind idk;
12055
        bool non_integral_constant_expression_p;
12056
        const char *error_msg;
12057
 
12058
        if (IDENTIFIER_TYPENAME_P (t))
12059
          {
12060
            tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12061
            t = mangle_conv_op_name_for_type (new_type);
12062
          }
12063
 
12064
        /* Look up the name.  */
12065
        decl = lookup_name (t);
12066
 
12067
        /* By convention, expressions use ERROR_MARK_NODE to indicate
12068
           failure, not NULL_TREE.  */
12069
        if (decl == NULL_TREE)
12070
          decl = error_mark_node;
12071
 
12072
        decl = finish_id_expression (t, decl, NULL_TREE,
12073
                                     &idk,
12074
                                     integral_constant_expression_p,
12075
                                     /*allow_non_integral_constant_expression_p=*/false,
12076
                                     &non_integral_constant_expression_p,
12077
                                     /*template_p=*/false,
12078
                                     /*done=*/true,
12079
                                     /*address_p=*/false,
12080
                                     /*template_arg_p=*/false,
12081
                                     &error_msg,
12082
                                     input_location);
12083
        if (error_msg)
12084
          error (error_msg);
12085
        if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12086
          decl = unqualified_name_lookup_error (decl);
12087
        return decl;
12088
      }
12089
 
12090
    case TEMPLATE_ID_EXPR:
12091
      {
12092
        tree object;
12093
        tree templ = RECUR (TREE_OPERAND (t, 0));
12094
        tree targs = TREE_OPERAND (t, 1);
12095
 
12096
        if (targs)
12097
          targs = tsubst_template_args (targs, args, complain, in_decl);
12098
 
12099
        if (TREE_CODE (templ) == COMPONENT_REF)
12100
          {
12101
            object = TREE_OPERAND (templ, 0);
12102
            templ = TREE_OPERAND (templ, 1);
12103
          }
12104
        else
12105
          object = NULL_TREE;
12106
        templ = lookup_template_function (templ, targs);
12107
 
12108
        if (object)
12109
          return build3 (COMPONENT_REF, TREE_TYPE (templ),
12110
                         object, templ, NULL_TREE);
12111
        else
12112
          return baselink_for_fns (templ);
12113
      }
12114
 
12115
    case INDIRECT_REF:
12116
      {
12117
        tree r = RECUR (TREE_OPERAND (t, 0));
12118
 
12119
        if (REFERENCE_REF_P (t))
12120
          {
12121
            /* A type conversion to reference type will be enclosed in
12122
               such an indirect ref, but the substitution of the cast
12123
               will have also added such an indirect ref.  */
12124
            if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12125
              r = convert_from_reference (r);
12126
          }
12127
        else
12128
          r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12129
        return r;
12130
      }
12131
 
12132
    case NOP_EXPR:
12133
      return build_nop
12134
        (tsubst (TREE_TYPE (t), args, complain, in_decl),
12135
         RECUR (TREE_OPERAND (t, 0)));
12136
 
12137
    case CAST_EXPR:
12138
    case REINTERPRET_CAST_EXPR:
12139
    case CONST_CAST_EXPR:
12140
    case DYNAMIC_CAST_EXPR:
12141
    case STATIC_CAST_EXPR:
12142
      {
12143
        tree type;
12144
        tree op;
12145
 
12146
        type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12147
        if (integral_constant_expression_p
12148
            && !cast_valid_in_integral_constant_expression_p (type))
12149
          {
12150
            if (complain & tf_error)
12151
              error ("a cast to a type other than an integral or "
12152
                     "enumeration type cannot appear in a constant-expression");
12153
            return error_mark_node;
12154
          }
12155
 
12156
        op = RECUR (TREE_OPERAND (t, 0));
12157
 
12158
        switch (TREE_CODE (t))
12159
          {
12160
          case CAST_EXPR:
12161
            return build_functional_cast (type, op, complain);
12162
          case REINTERPRET_CAST_EXPR:
12163
            return build_reinterpret_cast (type, op, complain);
12164
          case CONST_CAST_EXPR:
12165
            return build_const_cast (type, op, complain);
12166
          case DYNAMIC_CAST_EXPR:
12167
            return build_dynamic_cast (type, op, complain);
12168
          case STATIC_CAST_EXPR:
12169
            return build_static_cast (type, op, complain);
12170
          default:
12171
            gcc_unreachable ();
12172
          }
12173
      }
12174
 
12175
    case POSTDECREMENT_EXPR:
12176
    case POSTINCREMENT_EXPR:
12177
      op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12178
                                                args, complain, in_decl);
12179
      return build_x_unary_op (TREE_CODE (t), op1, complain);
12180
 
12181
    case PREDECREMENT_EXPR:
12182
    case PREINCREMENT_EXPR:
12183
    case NEGATE_EXPR:
12184
    case BIT_NOT_EXPR:
12185
    case ABS_EXPR:
12186
    case TRUTH_NOT_EXPR:
12187
    case UNARY_PLUS_EXPR:  /* Unary + */
12188
    case REALPART_EXPR:
12189
    case IMAGPART_EXPR:
12190
      return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12191
                               complain);
12192
 
12193
    case ADDR_EXPR:
12194
      op1 = TREE_OPERAND (t, 0);
12195
      if (TREE_CODE (op1) == SCOPE_REF)
12196
        op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12197
                                   /*done=*/true, /*address_p=*/true);
12198
      else
12199
        op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12200
                                                  in_decl);
12201
      if (TREE_CODE (op1) == LABEL_DECL)
12202
        return finish_label_address_expr (DECL_NAME (op1),
12203
                                          EXPR_LOCATION (op1));
12204
      return build_x_unary_op (ADDR_EXPR, op1, complain);
12205
 
12206
    case PLUS_EXPR:
12207
    case MINUS_EXPR:
12208
    case MULT_EXPR:
12209
    case TRUNC_DIV_EXPR:
12210
    case CEIL_DIV_EXPR:
12211
    case FLOOR_DIV_EXPR:
12212
    case ROUND_DIV_EXPR:
12213
    case EXACT_DIV_EXPR:
12214
    case BIT_AND_EXPR:
12215
    case BIT_IOR_EXPR:
12216
    case BIT_XOR_EXPR:
12217
    case TRUNC_MOD_EXPR:
12218
    case FLOOR_MOD_EXPR:
12219
    case TRUTH_ANDIF_EXPR:
12220
    case TRUTH_ORIF_EXPR:
12221
    case TRUTH_AND_EXPR:
12222
    case TRUTH_OR_EXPR:
12223
    case RSHIFT_EXPR:
12224
    case LSHIFT_EXPR:
12225
    case RROTATE_EXPR:
12226
    case LROTATE_EXPR:
12227
    case EQ_EXPR:
12228
    case NE_EXPR:
12229
    case MAX_EXPR:
12230
    case MIN_EXPR:
12231
    case LE_EXPR:
12232
    case GE_EXPR:
12233
    case LT_EXPR:
12234
    case GT_EXPR:
12235
    case MEMBER_REF:
12236
    case DOTSTAR_EXPR:
12237
      return build_x_binary_op
12238
        (TREE_CODE (t),
12239
         RECUR (TREE_OPERAND (t, 0)),
12240
         (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12241
          ? ERROR_MARK
12242
          : TREE_CODE (TREE_OPERAND (t, 0))),
12243
         RECUR (TREE_OPERAND (t, 1)),
12244
         (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12245
          ? ERROR_MARK
12246
          : TREE_CODE (TREE_OPERAND (t, 1))),
12247
         /*overloaded_p=*/NULL,
12248
         complain);
12249
 
12250
    case SCOPE_REF:
12251
      return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12252
                                  /*address_p=*/false);
12253
    case ARRAY_REF:
12254
      op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12255
                                                args, complain, in_decl);
12256
      return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12257
 
12258
    case SIZEOF_EXPR:
12259
      if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12260
        return tsubst_copy (t, args, complain, in_decl);
12261
      /* Fall through */
12262
 
12263
    case ALIGNOF_EXPR:
12264
      op1 = TREE_OPERAND (t, 0);
12265
      if (!args)
12266
        {
12267
          /* When there are no ARGS, we are trying to evaluate a
12268
             non-dependent expression from the parser.  Trying to do
12269
             the substitutions may not work.  */
12270
          if (!TYPE_P (op1))
12271
            op1 = TREE_TYPE (op1);
12272
        }
12273
      else
12274
        {
12275
          ++cp_unevaluated_operand;
12276
          ++c_inhibit_evaluation_warnings;
12277
          op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12278
                                       /*function_p=*/false,
12279
                                       /*integral_constant_expression_p=*/false);
12280
          --cp_unevaluated_operand;
12281
          --c_inhibit_evaluation_warnings;
12282
        }
12283
      if (TYPE_P (op1))
12284
        return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
12285
                                           complain & tf_error);
12286
      else
12287
        return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
12288
                                           complain & tf_error);
12289
 
12290
    case MODOP_EXPR:
12291
      {
12292
        tree r = build_x_modify_expr
12293
          (RECUR (TREE_OPERAND (t, 0)),
12294
           TREE_CODE (TREE_OPERAND (t, 1)),
12295
           RECUR (TREE_OPERAND (t, 2)),
12296
           complain);
12297
        /* TREE_NO_WARNING must be set if either the expression was
12298
           parenthesized or it uses an operator such as >>= rather
12299
           than plain assignment.  In the former case, it was already
12300
           set and must be copied.  In the latter case,
12301
           build_x_modify_expr sets it and it must not be reset
12302
           here.  */
12303
        if (TREE_NO_WARNING (t))
12304
          TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12305
        return r;
12306
      }
12307
 
12308
    case ARROW_EXPR:
12309
      op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12310
                                                args, complain, in_decl);
12311
      /* Remember that there was a reference to this entity.  */
12312
      if (DECL_P (op1))
12313
        mark_used (op1);
12314
      return build_x_arrow (op1);
12315
 
12316
    case NEW_EXPR:
12317
      {
12318
        tree placement = RECUR (TREE_OPERAND (t, 0));
12319
        tree init = RECUR (TREE_OPERAND (t, 3));
12320
        VEC(tree,gc) *placement_vec;
12321
        VEC(tree,gc) *init_vec;
12322
        tree ret;
12323
 
12324
        if (placement == NULL_TREE)
12325
          placement_vec = NULL;
12326
        else
12327
          {
12328
            placement_vec = make_tree_vector ();
12329
            for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12330
              VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12331
          }
12332
 
12333
        /* If there was an initializer in the original tree, but it
12334
           instantiated to an empty list, then we should pass a
12335
           non-NULL empty vector to tell build_new that it was an
12336
           empty initializer() rather than no initializer.  This can
12337
           only happen when the initializer is a pack expansion whose
12338
           parameter packs are of length zero.  */
12339
        if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12340
          init_vec = NULL;
12341
        else
12342
          {
12343
            init_vec = make_tree_vector ();
12344
            if (init == void_zero_node)
12345
              gcc_assert (init_vec != NULL);
12346
            else
12347
              {
12348
                for (; init != NULL_TREE; init = TREE_CHAIN (init))
12349
                  VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12350
              }
12351
          }
12352
 
12353
        ret = build_new (&placement_vec,
12354
                         RECUR (TREE_OPERAND (t, 1)),
12355
                         RECUR (TREE_OPERAND (t, 2)),
12356
                         &init_vec,
12357
                         NEW_EXPR_USE_GLOBAL (t),
12358
                         complain);
12359
 
12360
        if (placement_vec != NULL)
12361
          release_tree_vector (placement_vec);
12362
        if (init_vec != NULL)
12363
          release_tree_vector (init_vec);
12364
 
12365
        return ret;
12366
      }
12367
 
12368
    case DELETE_EXPR:
12369
     return delete_sanity
12370
       (RECUR (TREE_OPERAND (t, 0)),
12371
        RECUR (TREE_OPERAND (t, 1)),
12372
        DELETE_EXPR_USE_VEC (t),
12373
        DELETE_EXPR_USE_GLOBAL (t));
12374
 
12375
    case COMPOUND_EXPR:
12376
      return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12377
                                    RECUR (TREE_OPERAND (t, 1)),
12378
                                    complain);
12379
 
12380
    case CALL_EXPR:
12381
      {
12382
        tree function;
12383
        VEC(tree,gc) *call_args;
12384
        unsigned int nargs, i;
12385
        bool qualified_p;
12386
        bool koenig_p;
12387
        tree ret;
12388
 
12389
        function = CALL_EXPR_FN (t);
12390
        /* When we parsed the expression,  we determined whether or
12391
           not Koenig lookup should be performed.  */
12392
        koenig_p = KOENIG_LOOKUP_P (t);
12393
        if (TREE_CODE (function) == SCOPE_REF)
12394
          {
12395
            qualified_p = true;
12396
            function = tsubst_qualified_id (function, args, complain, in_decl,
12397
                                            /*done=*/false,
12398
                                            /*address_p=*/false);
12399
          }
12400
        else
12401
          {
12402
            if (TREE_CODE (function) == COMPONENT_REF)
12403
              {
12404
                tree op = TREE_OPERAND (function, 1);
12405
 
12406
                qualified_p = (TREE_CODE (op) == SCOPE_REF
12407
                               || (BASELINK_P (op)
12408
                                   && BASELINK_QUALIFIED_P (op)));
12409
              }
12410
            else
12411
              qualified_p = false;
12412
 
12413
            function = tsubst_copy_and_build (function, args, complain,
12414
                                              in_decl,
12415
                                              !qualified_p,
12416
                                              integral_constant_expression_p);
12417
 
12418
            if (BASELINK_P (function))
12419
              qualified_p = true;
12420
          }
12421
 
12422
        nargs = call_expr_nargs (t);
12423
        call_args = make_tree_vector ();
12424
        for (i = 0; i < nargs; ++i)
12425
          {
12426
            tree arg = CALL_EXPR_ARG (t, i);
12427
 
12428
            if (!PACK_EXPANSION_P (arg))
12429
              VEC_safe_push (tree, gc, call_args,
12430
                             RECUR (CALL_EXPR_ARG (t, i)));
12431
            else
12432
              {
12433
                /* Expand the pack expansion and push each entry onto
12434
                   CALL_ARGS.  */
12435
                arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12436
                if (TREE_CODE (arg) == TREE_VEC)
12437
                  {
12438
                    unsigned int len, j;
12439
 
12440
                    len = TREE_VEC_LENGTH (arg);
12441
                    for (j = 0; j < len; ++j)
12442
                      {
12443
                        tree value = TREE_VEC_ELT (arg, j);
12444
                        if (value != NULL_TREE)
12445
                          value = convert_from_reference (value);
12446
                        VEC_safe_push (tree, gc, call_args, value);
12447
                      }
12448
                  }
12449
                else
12450
                  {
12451
                    /* A partial substitution.  Add one entry.  */
12452
                    VEC_safe_push (tree, gc, call_args, arg);
12453
                  }
12454
              }
12455
          }
12456
 
12457
        /* We do not perform argument-dependent lookup if normal
12458
           lookup finds a non-function, in accordance with the
12459
           expected resolution of DR 218.  */
12460
        if (koenig_p
12461
            && ((is_overloaded_fn (function)
12462
                 /* If lookup found a member function, the Koenig lookup is
12463
                    not appropriate, even if an unqualified-name was used
12464
                    to denote the function.  */
12465
                 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12466
                || TREE_CODE (function) == IDENTIFIER_NODE)
12467
            /* Only do this when substitution turns a dependent call
12468
               into a non-dependent call.  */
12469
            && type_dependent_expression_p_push (t)
12470
            && !any_type_dependent_arguments_p (call_args))
12471
          function = perform_koenig_lookup (function, call_args);
12472
 
12473
        if (TREE_CODE (function) == IDENTIFIER_NODE)
12474
          {
12475
            unqualified_name_lookup_error (function);
12476
            release_tree_vector (call_args);
12477
            return error_mark_node;
12478
          }
12479
 
12480
        /* Remember that there was a reference to this entity.  */
12481
        if (DECL_P (function))
12482
          mark_used (function);
12483
 
12484
        if (TREE_CODE (function) == OFFSET_REF)
12485
          ret = build_offset_ref_call_from_tree (function, &call_args);
12486
        else if (TREE_CODE (function) == COMPONENT_REF)
12487
          {
12488
            if (!BASELINK_P (TREE_OPERAND (function, 1)))
12489
              ret = finish_call_expr (function, &call_args,
12490
                                       /*disallow_virtual=*/false,
12491
                                       /*koenig_p=*/false,
12492
                                       complain);
12493
            else
12494
              ret = (build_new_method_call
12495
                      (TREE_OPERAND (function, 0),
12496
                       TREE_OPERAND (function, 1),
12497
                       &call_args, NULL_TREE,
12498
                       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12499
                       /*fn_p=*/NULL,
12500
                       complain));
12501
          }
12502
        else
12503
          ret = finish_call_expr (function, &call_args,
12504
                                  /*disallow_virtual=*/qualified_p,
12505
                                  koenig_p,
12506
                                  complain);
12507
 
12508
        release_tree_vector (call_args);
12509
 
12510
        return ret;
12511
      }
12512
 
12513
    case COND_EXPR:
12514
      return build_x_conditional_expr
12515
        (RECUR (TREE_OPERAND (t, 0)),
12516
         RECUR (TREE_OPERAND (t, 1)),
12517
         RECUR (TREE_OPERAND (t, 2)),
12518
         complain);
12519
 
12520
    case PSEUDO_DTOR_EXPR:
12521
      return finish_pseudo_destructor_expr
12522
        (RECUR (TREE_OPERAND (t, 0)),
12523
         RECUR (TREE_OPERAND (t, 1)),
12524
         RECUR (TREE_OPERAND (t, 2)));
12525
 
12526
    case TREE_LIST:
12527
      {
12528
        tree purpose, value, chain;
12529
 
12530
        if (t == void_list_node)
12531
          return t;
12532
 
12533
        if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12534
            || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12535
          {
12536
            /* We have pack expansions, so expand those and
12537
               create a new list out of it.  */
12538
            tree purposevec = NULL_TREE;
12539
            tree valuevec = NULL_TREE;
12540
            tree chain;
12541
            int i, len = -1;
12542
 
12543
            /* Expand the argument expressions.  */
12544
            if (TREE_PURPOSE (t))
12545
              purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12546
                                                 complain, in_decl);
12547
            if (TREE_VALUE (t))
12548
              valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12549
                                               complain, in_decl);
12550
 
12551
            /* Build the rest of the list.  */
12552
            chain = TREE_CHAIN (t);
12553
            if (chain && chain != void_type_node)
12554
              chain = RECUR (chain);
12555
 
12556
            /* Determine the number of arguments.  */
12557
            if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12558
              {
12559
                len = TREE_VEC_LENGTH (purposevec);
12560
                gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12561
              }
12562
            else if (TREE_CODE (valuevec) == TREE_VEC)
12563
              len = TREE_VEC_LENGTH (valuevec);
12564
            else
12565
              {
12566
                /* Since we only performed a partial substitution into
12567
                   the argument pack, we only return a single list
12568
                   node.  */
12569
                if (purposevec == TREE_PURPOSE (t)
12570
                    && valuevec == TREE_VALUE (t)
12571
                    && chain == TREE_CHAIN (t))
12572
                  return t;
12573
 
12574
                return tree_cons (purposevec, valuevec, chain);
12575
              }
12576
 
12577
            /* Convert the argument vectors into a TREE_LIST */
12578
            i = len;
12579
            while (i > 0)
12580
              {
12581
                /* Grab the Ith values.  */
12582
                i--;
12583
                purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
12584
                                     : NULL_TREE;
12585
                value
12586
                  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
12587
                             : NULL_TREE;
12588
 
12589
                /* Build the list (backwards).  */
12590
                chain = tree_cons (purpose, value, chain);
12591
              }
12592
 
12593
            return chain;
12594
          }
12595
 
12596
        purpose = TREE_PURPOSE (t);
12597
        if (purpose)
12598
          purpose = RECUR (purpose);
12599
        value = TREE_VALUE (t);
12600
        if (value)
12601
          value = RECUR (value);
12602
        chain = TREE_CHAIN (t);
12603
        if (chain && chain != void_type_node)
12604
          chain = RECUR (chain);
12605
        if (purpose == TREE_PURPOSE (t)
12606
            && value == TREE_VALUE (t)
12607
            && chain == TREE_CHAIN (t))
12608
          return t;
12609
        return tree_cons (purpose, value, chain);
12610
      }
12611
 
12612
    case COMPONENT_REF:
12613
      {
12614
        tree object;
12615
        tree object_type;
12616
        tree member;
12617
 
12618
        object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12619
                                                     args, complain, in_decl);
12620
        /* Remember that there was a reference to this entity.  */
12621
        if (DECL_P (object))
12622
          mark_used (object);
12623
        object_type = TREE_TYPE (object);
12624
 
12625
        member = TREE_OPERAND (t, 1);
12626
        if (BASELINK_P (member))
12627
          member = tsubst_baselink (member,
12628
                                    non_reference (TREE_TYPE (object)),
12629
                                    args, complain, in_decl);
12630
        else
12631
          member = tsubst_copy (member, args, complain, in_decl);
12632
        if (member == error_mark_node)
12633
          return error_mark_node;
12634
 
12635
        if (object_type && !CLASS_TYPE_P (object_type))
12636
          {
12637
            if (SCALAR_TYPE_P (object_type))
12638
              {
12639
                tree s = NULL_TREE;
12640
                tree dtor = member;
12641
 
12642
                if (TREE_CODE (dtor) == SCOPE_REF)
12643
                  {
12644
                    s = TREE_OPERAND (dtor, 0);
12645
                    dtor = TREE_OPERAND (dtor, 1);
12646
                  }
12647
                if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12648
                  {
12649
                    dtor = TREE_OPERAND (dtor, 0);
12650
                    if (TYPE_P (dtor))
12651
                      return finish_pseudo_destructor_expr (object, s, dtor);
12652
                  }
12653
              }
12654
          }
12655
        else if (TREE_CODE (member) == SCOPE_REF
12656
                 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12657
          {
12658
            tree tmpl;
12659
            tree args;
12660
 
12661
            /* Lookup the template functions now that we know what the
12662
               scope is.  */
12663
            tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12664
            args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12665
            member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12666
                                            /*is_type_p=*/false,
12667
                                            /*complain=*/false);
12668
            if (BASELINK_P (member))
12669
              {
12670
                BASELINK_FUNCTIONS (member)
12671
                  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12672
                              args);
12673
                member = (adjust_result_of_qualified_name_lookup
12674
                          (member, BINFO_TYPE (BASELINK_BINFO (member)),
12675
                           object_type));
12676
              }
12677
            else
12678
              {
12679
                qualified_name_lookup_error (object_type, tmpl, member,
12680
                                             input_location);
12681
                return error_mark_node;
12682
              }
12683
          }
12684
        else if (TREE_CODE (member) == SCOPE_REF
12685
                 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12686
                 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12687
          {
12688
            if (complain & tf_error)
12689
              {
12690
                if (TYPE_P (TREE_OPERAND (member, 0)))
12691
                  error ("%qT is not a class or namespace",
12692
                         TREE_OPERAND (member, 0));
12693
                else
12694
                  error ("%qD is not a class or namespace",
12695
                         TREE_OPERAND (member, 0));
12696
              }
12697
            return error_mark_node;
12698
          }
12699
        else if (TREE_CODE (member) == FIELD_DECL)
12700
          return finish_non_static_data_member (member, object, NULL_TREE);
12701
 
12702
        return finish_class_member_access_expr (object, member,
12703
                                                /*template_p=*/false,
12704
                                                complain);
12705
      }
12706
 
12707
    case THROW_EXPR:
12708
      return build_throw
12709
        (RECUR (TREE_OPERAND (t, 0)));
12710
 
12711
    case CONSTRUCTOR:
12712
      {
12713
        VEC(constructor_elt,gc) *n;
12714
        constructor_elt *ce;
12715
        unsigned HOST_WIDE_INT idx;
12716
        tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12717
        bool process_index_p;
12718
        int newlen;
12719
        bool need_copy_p = false;
12720
        tree r;
12721
 
12722
        if (type == error_mark_node)
12723
          return error_mark_node;
12724
 
12725
        /* digest_init will do the wrong thing if we let it.  */
12726
        if (type && TYPE_PTRMEMFUNC_P (type))
12727
          return t;
12728
 
12729
        /* We do not want to process the index of aggregate
12730
           initializers as they are identifier nodes which will be
12731
           looked up by digest_init.  */
12732
        process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12733
 
12734
        n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12735
        newlen = VEC_length (constructor_elt, n);
12736
        for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12737
          {
12738
            if (ce->index && process_index_p)
12739
              ce->index = RECUR (ce->index);
12740
 
12741
            if (PACK_EXPANSION_P (ce->value))
12742
              {
12743
                /* Substitute into the pack expansion.  */
12744
                ce->value = tsubst_pack_expansion (ce->value, args, complain,
12745
                                                  in_decl);
12746
 
12747
                if (ce->value == error_mark_node)
12748
                  ;
12749
                else if (TREE_VEC_LENGTH (ce->value) == 1)
12750
                  /* Just move the argument into place.  */
12751
                  ce->value = TREE_VEC_ELT (ce->value, 0);
12752
                else
12753
                  {
12754
                    /* Update the length of the final CONSTRUCTOR
12755
                       arguments vector, and note that we will need to
12756
                       copy.*/
12757
                    newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12758
                    need_copy_p = true;
12759
                  }
12760
              }
12761
            else
12762
              ce->value = RECUR (ce->value);
12763
          }
12764
 
12765
        if (need_copy_p)
12766
          {
12767
            VEC(constructor_elt,gc) *old_n = n;
12768
 
12769
            n = VEC_alloc (constructor_elt, gc, newlen);
12770
            for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce);
12771
                 idx++)
12772
              {
12773
                if (TREE_CODE (ce->value) == TREE_VEC)
12774
                  {
12775
                    int i, len = TREE_VEC_LENGTH (ce->value);
12776
                    for (i = 0; i < len; ++i)
12777
                      CONSTRUCTOR_APPEND_ELT (n, 0,
12778
                                              TREE_VEC_ELT (ce->value, i));
12779
                  }
12780
                else
12781
                  CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12782
              }
12783
          }
12784
 
12785
        r = build_constructor (init_list_type_node, n);
12786
        CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12787
 
12788
        if (TREE_HAS_CONSTRUCTOR (t))
12789
          return finish_compound_literal (type, r);
12790
 
12791
        return r;
12792
      }
12793
 
12794
    case TYPEID_EXPR:
12795
      {
12796
        tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12797
        if (TYPE_P (operand_0))
12798
          return get_typeid (operand_0);
12799
        return build_typeid (operand_0);
12800
      }
12801
 
12802
    case VAR_DECL:
12803
      if (!args)
12804
        return t;
12805
      /* Fall through */
12806
 
12807
    case PARM_DECL:
12808
      {
12809
        tree r = tsubst_copy (t, args, complain, in_decl);
12810
 
12811
        if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12812
          /* If the original type was a reference, we'll be wrapped in
12813
             the appropriate INDIRECT_REF.  */
12814
          r = convert_from_reference (r);
12815
        return r;
12816
      }
12817
 
12818
    case VA_ARG_EXPR:
12819
      return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12820
                             tsubst_copy (TREE_TYPE (t), args, complain,
12821
                                          in_decl));
12822
 
12823
    case OFFSETOF_EXPR:
12824
      return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12825
 
12826
    case TRAIT_EXPR:
12827
      {
12828
        tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12829
                                  complain, in_decl);
12830
 
12831
        tree type2 = TRAIT_EXPR_TYPE2 (t);
12832
        if (type2)
12833
          type2 = tsubst_copy (type2, args, complain, in_decl);
12834
 
12835
        return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12836
      }
12837
 
12838
    case STMT_EXPR:
12839
      {
12840
        tree old_stmt_expr = cur_stmt_expr;
12841
        tree stmt_expr = begin_stmt_expr ();
12842
 
12843
        cur_stmt_expr = stmt_expr;
12844
        tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12845
                     integral_constant_expression_p);
12846
        stmt_expr = finish_stmt_expr (stmt_expr, false);
12847
        cur_stmt_expr = old_stmt_expr;
12848
 
12849
        /* If the resulting list of expression statement is empty,
12850
           fold it further into void_zero_node.  */
12851
        if (empty_expr_stmt_p (stmt_expr))
12852
          stmt_expr = void_zero_node;
12853
 
12854
        return stmt_expr;
12855
      }
12856
 
12857
    case CONST_DECL:
12858
      t = tsubst_copy (t, args, complain, in_decl);
12859
      /* As in finish_id_expression, we resolve enumeration constants
12860
         to their underlying values.  */
12861
      if (TREE_CODE (t) == CONST_DECL)
12862
        {
12863
          used_types_insert (TREE_TYPE (t));
12864
          return DECL_INITIAL (t);
12865
        }
12866
      return t;
12867
 
12868
    case LAMBDA_EXPR:
12869
      {
12870
        tree r = build_lambda_expr ();
12871
 
12872
        tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12873
        TREE_TYPE (r) = type;
12874
        CLASSTYPE_LAMBDA_EXPR (type) = r;
12875
 
12876
        LAMBDA_EXPR_LOCATION (r)
12877
          = LAMBDA_EXPR_LOCATION (t);
12878
        LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12879
          = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12880
        LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12881
        LAMBDA_EXPR_DISCRIMINATOR (r)
12882
          = (LAMBDA_EXPR_DISCRIMINATOR (t));
12883
        LAMBDA_EXPR_CAPTURE_LIST (r)
12884
          = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12885
        LAMBDA_EXPR_THIS_CAPTURE (r)
12886
          = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12887
        LAMBDA_EXPR_EXTRA_SCOPE (r)
12888
          = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12889
 
12890
        /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12891
        determine_visibility (TYPE_NAME (type));
12892
        /* Now that we know visibility, instantiate the type so we have a
12893
           declaration of the op() for later calls to lambda_function.  */
12894
        complete_type (type);
12895
 
12896
        type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12897
        if (type)
12898
          apply_lambda_return_type (r, type);
12899
 
12900
        return build_lambda_object (r);
12901
      }
12902
 
12903
    default:
12904
      /* Handle Objective-C++ constructs, if appropriate.  */
12905
      {
12906
        tree subst
12907
          = objcp_tsubst_copy_and_build (t, args, complain,
12908
                                         in_decl, /*function_p=*/false);
12909
        if (subst)
12910
          return subst;
12911
      }
12912
      return tsubst_copy (t, args, complain, in_decl);
12913
    }
12914
 
12915
#undef RECUR
12916
}
12917
 
12918
/* Verify that the instantiated ARGS are valid. For type arguments,
12919
   make sure that the type's linkage is ok. For non-type arguments,
12920
   make sure they are constants if they are integral or enumerations.
12921
   Emit an error under control of COMPLAIN, and return TRUE on error.  */
12922
 
12923
static bool
12924
check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12925
{
12926
  if (ARGUMENT_PACK_P (t))
12927
    {
12928
      tree vec = ARGUMENT_PACK_ARGS (t);
12929
      int len = TREE_VEC_LENGTH (vec);
12930
      bool result = false;
12931
      int i;
12932
 
12933
      for (i = 0; i < len; ++i)
12934
        if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12935
          result = true;
12936
      return result;
12937
    }
12938
  else if (TYPE_P (t))
12939
    {
12940
      /* [basic.link]: A name with no linkage (notably, the name
12941
         of a class or enumeration declared in a local scope)
12942
         shall not be used to declare an entity with linkage.
12943
         This implies that names with no linkage cannot be used as
12944
         template arguments
12945
 
12946
         DR 757 relaxes this restriction for C++0x.  */
12947
      tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12948
                 : no_linkage_check (t, /*relaxed_p=*/false));
12949
 
12950
      if (nt)
12951
        {
12952
          /* DR 488 makes use of a type with no linkage cause
12953
             type deduction to fail.  */
12954
          if (complain & tf_error)
12955
            {
12956
              if (TYPE_ANONYMOUS_P (nt))
12957
                error ("%qT is/uses anonymous type", t);
12958
              else
12959
                error ("template argument for %qD uses local type %qT",
12960
                       tmpl, t);
12961
            }
12962
          return true;
12963
        }
12964
      /* In order to avoid all sorts of complications, we do not
12965
         allow variably-modified types as template arguments.  */
12966
      else if (variably_modified_type_p (t, NULL_TREE))
12967
        {
12968
          if (complain & tf_error)
12969
            error ("%qT is a variably modified type", t);
12970
          return true;
12971
        }
12972
    }
12973
  /* A non-type argument of integral or enumerated type must be a
12974
     constant.  */
12975
  else if (TREE_TYPE (t)
12976
           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12977
           && !TREE_CONSTANT (t))
12978
    {
12979
      if (complain & tf_error)
12980
        error ("integral expression %qE is not constant", t);
12981
      return true;
12982
    }
12983
  return false;
12984
}
12985
 
12986
static bool
12987
check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12988
{
12989
  int ix, len = DECL_NTPARMS (tmpl);
12990
  bool result = false;
12991
 
12992
  for (ix = 0; ix != len; ix++)
12993
    {
12994
      if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12995
        result = true;
12996
    }
12997
  if (result && (complain & tf_error))
12998
    error ("  trying to instantiate %qD", tmpl);
12999
  return result;
13000
}
13001
 
13002
/* Instantiate the indicated variable or function template TMPL with
13003
   the template arguments in TARG_PTR.  */
13004
 
13005
tree
13006
instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13007
{
13008
  tree targ_ptr = orig_args;
13009
  tree fndecl;
13010
  tree gen_tmpl;
13011
  tree spec;
13012
  HOST_WIDE_INT saved_processing_template_decl;
13013
 
13014
  if (tmpl == error_mark_node)
13015
    return error_mark_node;
13016
 
13017
  gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13018
 
13019
  /* If this function is a clone, handle it specially.  */
13020
  if (DECL_CLONED_FUNCTION_P (tmpl))
13021
    {
13022
      tree spec;
13023
      tree clone;
13024
 
13025
      /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13026
         DECL_CLONED_FUNCTION.  */
13027
      spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13028
                                   targ_ptr, complain);
13029
      if (spec == error_mark_node)
13030
        return error_mark_node;
13031
 
13032
      /* Look for the clone.  */
13033
      FOR_EACH_CLONE (clone, spec)
13034
        if (DECL_NAME (clone) == DECL_NAME (tmpl))
13035
          return clone;
13036
      /* We should always have found the clone by now.  */
13037
      gcc_unreachable ();
13038
      return NULL_TREE;
13039
    }
13040
 
13041
  /* Check to see if we already have this specialization.  */
13042
  gen_tmpl = most_general_template (tmpl);
13043
  if (tmpl != gen_tmpl)
13044
    /* The TMPL is a partial instantiation.  To get a full set of
13045
       arguments we must add the arguments used to perform the
13046
       partial instantiation.  */
13047
    targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13048
                                            targ_ptr);
13049
 
13050
  /* It would be nice to avoid hashing here and then again in tsubst_decl,
13051
     but it doesn't seem to be on the hot path.  */
13052
  spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13053
 
13054
  gcc_assert (tmpl == gen_tmpl
13055
              || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13056
                  == spec)
13057
              || fndecl == NULL_TREE);
13058
 
13059
  if (spec != NULL_TREE)
13060
    return spec;
13061
 
13062
  if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13063
                               complain))
13064
    return error_mark_node;
13065
 
13066
  /* We are building a FUNCTION_DECL, during which the access of its
13067
     parameters and return types have to be checked.  However this
13068
     FUNCTION_DECL which is the desired context for access checking
13069
     is not built yet.  We solve this chicken-and-egg problem by
13070
     deferring all checks until we have the FUNCTION_DECL.  */
13071
  push_deferring_access_checks (dk_deferred);
13072
 
13073
  /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13074
     (because, for example, we have encountered a non-dependent
13075
     function call in the body of a template function and must now
13076
     determine which of several overloaded functions will be called),
13077
     within the instantiation itself we are not processing a
13078
     template.  */
13079
  saved_processing_template_decl = processing_template_decl;
13080
  processing_template_decl = 0;
13081
  /* Substitute template parameters to obtain the specialization.  */
13082
  fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13083
                   targ_ptr, complain, gen_tmpl);
13084
  processing_template_decl = saved_processing_template_decl;
13085
  if (fndecl == error_mark_node)
13086
    return error_mark_node;
13087
 
13088
  /* Now we know the specialization, compute access previously
13089
     deferred.  */
13090
  push_access_scope (fndecl);
13091
 
13092
  /* Some typedefs referenced from within the template code need to be access
13093
     checked at template instantiation time, i.e now. These types were
13094
     added to the template at parsing time. Let's get those and perfom
13095
     the acces checks then.  */
13096
  perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13097
  perform_deferred_access_checks ();
13098
  pop_access_scope (fndecl);
13099
  pop_deferring_access_checks ();
13100
 
13101
  /* The DECL_TI_TEMPLATE should always be the immediate parent
13102
     template, not the most general template.  */
13103
  DECL_TI_TEMPLATE (fndecl) = tmpl;
13104
 
13105
  /* If we've just instantiated the main entry point for a function,
13106
     instantiate all the alternate entry points as well.  We do this
13107
     by cloning the instantiation of the main entry point, not by
13108
     instantiating the template clones.  */
13109
  if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13110
    clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13111
 
13112
  return fndecl;
13113
}
13114
 
13115
/* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13116
   NARGS elements of the arguments that are being used when calling
13117
   it.  TARGS is a vector into which the deduced template arguments
13118
   are placed.
13119
 
13120
   Return zero for success, 2 for an incomplete match that doesn't resolve
13121
   all the types, and 1 for complete failure.  An error message will be
13122
   printed only for an incomplete match.
13123
 
13124
   If FN is a conversion operator, or we are trying to produce a specific
13125
   specialization, RETURN_TYPE is the return type desired.
13126
 
13127
   The EXPLICIT_TARGS are explicit template arguments provided via a
13128
   template-id.
13129
 
13130
   The parameter STRICT is one of:
13131
 
13132
   DEDUCE_CALL:
13133
     We are deducing arguments for a function call, as in
13134
     [temp.deduct.call].
13135
 
13136
   DEDUCE_CONV:
13137
     We are deducing arguments for a conversion function, as in
13138
     [temp.deduct.conv].
13139
 
13140
   DEDUCE_EXACT:
13141
     We are deducing arguments when doing an explicit instantiation
13142
     as in [temp.explicit], when determining an explicit specialization
13143
     as in [temp.expl.spec], or when taking the address of a function
13144
     template, as in [temp.deduct.funcaddr].  */
13145
 
13146
int
13147
fn_type_unification (tree fn,
13148
                     tree explicit_targs,
13149
                     tree targs,
13150
                     const tree *args,
13151
                     unsigned int nargs,
13152
                     tree return_type,
13153
                     unification_kind_t strict,
13154
                     int flags)
13155
{
13156
  tree parms;
13157
  tree fntype;
13158
  int result;
13159
  bool incomplete_argument_packs_p = false;
13160
 
13161
  gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13162
 
13163
  fntype = TREE_TYPE (fn);
13164
  if (explicit_targs)
13165
    {
13166
      /* [temp.deduct]
13167
 
13168
         The specified template arguments must match the template
13169
         parameters in kind (i.e., type, nontype, template), and there
13170
         must not be more arguments than there are parameters;
13171
         otherwise type deduction fails.
13172
 
13173
         Nontype arguments must match the types of the corresponding
13174
         nontype template parameters, or must be convertible to the
13175
         types of the corresponding nontype parameters as specified in
13176
         _temp.arg.nontype_, otherwise type deduction fails.
13177
 
13178
         All references in the function type of the function template
13179
         to the corresponding template parameters are replaced by the
13180
         specified template argument values.  If a substitution in a
13181
         template parameter or in the function type of the function
13182
         template results in an invalid type, type deduction fails.  */
13183
      tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13184
      int i, len = TREE_VEC_LENGTH (tparms);
13185
      tree converted_args;
13186
      bool incomplete = false;
13187
 
13188
      if (explicit_targs == error_mark_node)
13189
        return 1;
13190
 
13191
      converted_args
13192
        = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13193
                                  /*require_all_args=*/false,
13194
                                  /*use_default_args=*/false));
13195
      if (converted_args == error_mark_node)
13196
        return 1;
13197
 
13198
      /* Substitute the explicit args into the function type.  This is
13199
         necessary so that, for instance, explicitly declared function
13200
         arguments can match null pointed constants.  If we were given
13201
         an incomplete set of explicit args, we must not do semantic
13202
         processing during substitution as we could create partial
13203
         instantiations.  */
13204
      for (i = 0; i < len; i++)
13205
        {
13206
          tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13207
          bool parameter_pack = false;
13208
 
13209
          /* Dig out the actual parm.  */
13210
          if (TREE_CODE (parm) == TYPE_DECL
13211
              || TREE_CODE (parm) == TEMPLATE_DECL)
13212
            {
13213
              parm = TREE_TYPE (parm);
13214
              parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13215
            }
13216
          else if (TREE_CODE (parm) == PARM_DECL)
13217
            {
13218
              parm = DECL_INITIAL (parm);
13219
              parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13220
            }
13221
 
13222
          if (parameter_pack)
13223
            {
13224
              int level, idx;
13225
              tree targ;
13226
              template_parm_level_and_index (parm, &level, &idx);
13227
 
13228
              /* Mark the argument pack as "incomplete". We could
13229
                 still deduce more arguments during unification.  */
13230
              targ = TMPL_ARG (converted_args, level, idx);
13231
              if (targ)
13232
                {
13233
                  ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13234
                  ARGUMENT_PACK_EXPLICIT_ARGS (targ)
13235
                    = ARGUMENT_PACK_ARGS (targ);
13236
                }
13237
 
13238
              /* We have some incomplete argument packs.  */
13239
              incomplete_argument_packs_p = true;
13240
            }
13241
        }
13242
 
13243
      if (incomplete_argument_packs_p)
13244
        /* Any substitution is guaranteed to be incomplete if there
13245
           are incomplete argument packs, because we can still deduce
13246
           more arguments.  */
13247
        incomplete = 1;
13248
      else
13249
        incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13250
 
13251
      processing_template_decl += incomplete;
13252
      fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13253
      processing_template_decl -= incomplete;
13254
 
13255
      if (fntype == error_mark_node)
13256
        return 1;
13257
 
13258
      /* Place the explicitly specified arguments in TARGS.  */
13259
      for (i = NUM_TMPL_ARGS (converted_args); i--;)
13260
        TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13261
    }
13262
 
13263
  /* Never do unification on the 'this' parameter.  */
13264
  parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13265
 
13266
  if (return_type)
13267
    {
13268
      tree *new_args;
13269
 
13270
      parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13271
      new_args = XALLOCAVEC (tree, nargs + 1);
13272
      new_args[0] = return_type;
13273
      memcpy (new_args + 1, args, nargs * sizeof (tree));
13274
      args = new_args;
13275
      ++nargs;
13276
    }
13277
 
13278
  /* We allow incomplete unification without an error message here
13279
     because the standard doesn't seem to explicitly prohibit it.  Our
13280
     callers must be ready to deal with unification failures in any
13281
     event.  */
13282
  result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13283
                                  targs, parms, args, nargs, /*subr=*/0,
13284
                                  strict, flags);
13285
 
13286
  if (result == 0 && incomplete_argument_packs_p)
13287
    {
13288
      int i, len = NUM_TMPL_ARGS (targs);
13289
 
13290
      /* Clear the "incomplete" flags on all argument packs.  */
13291
      for (i = 0; i < len; i++)
13292
        {
13293
          tree arg = TREE_VEC_ELT (targs, i);
13294
          if (ARGUMENT_PACK_P (arg))
13295
            {
13296
              ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13297
              ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13298
            }
13299
        }
13300
    }
13301
 
13302
  /* Now that we have bindings for all of the template arguments,
13303
     ensure that the arguments deduced for the template template
13304
     parameters have compatible template parameter lists.  We cannot
13305
     check this property before we have deduced all template
13306
     arguments, because the template parameter types of a template
13307
     template parameter might depend on prior template parameters
13308
     deduced after the template template parameter.  The following
13309
     ill-formed example illustrates this issue:
13310
 
13311
       template<typename T, template<T> class C> void f(C<5>, T);
13312
 
13313
       template<int N> struct X {};
13314
 
13315
       void g() {
13316
         f(X<5>(), 5l); // error: template argument deduction fails
13317
       }
13318
 
13319
     The template parameter list of 'C' depends on the template type
13320
     parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13321
     'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13322
     time that we deduce 'C'.  */
13323
  if (result == 0
13324
      && !template_template_parm_bindings_ok_p
13325
           (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13326
    return 1;
13327
 
13328
  if (result == 0)
13329
    /* All is well so far.  Now, check:
13330
 
13331
       [temp.deduct]
13332
 
13333
       When all template arguments have been deduced, all uses of
13334
       template parameters in nondeduced contexts are replaced with
13335
       the corresponding deduced argument values.  If the
13336
       substitution results in an invalid type, as described above,
13337
       type deduction fails.  */
13338
    {
13339
      tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13340
      if (substed == error_mark_node)
13341
        return 1;
13342
 
13343
      /* If we're looking for an exact match, check that what we got
13344
         is indeed an exact match.  It might not be if some template
13345
         parameters are used in non-deduced contexts.  */
13346
      if (strict == DEDUCE_EXACT)
13347
        {
13348
          unsigned int i;
13349
 
13350
          tree sarg
13351
            = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13352
          if (return_type)
13353
            sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13354
          for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13355
            if (!same_type_p (args[i], TREE_VALUE (sarg)))
13356
              return 1;
13357
        }
13358
    }
13359
 
13360
  return result;
13361
}
13362
 
13363
/* Adjust types before performing type deduction, as described in
13364
   [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13365
   sections are symmetric.  PARM is the type of a function parameter
13366
   or the return type of the conversion function.  ARG is the type of
13367
   the argument passed to the call, or the type of the value
13368
   initialized with the result of the conversion function.
13369
   ARG_EXPR is the original argument expression, which may be null.  */
13370
 
13371
static int
13372
maybe_adjust_types_for_deduction (unification_kind_t strict,
13373
                                  tree* parm,
13374
                                  tree* arg,
13375
                                  tree arg_expr)
13376
{
13377
  int result = 0;
13378
 
13379
  switch (strict)
13380
    {
13381
    case DEDUCE_CALL:
13382
      break;
13383
 
13384
    case DEDUCE_CONV:
13385
      {
13386
        /* Swap PARM and ARG throughout the remainder of this
13387
           function; the handling is precisely symmetric since PARM
13388
           will initialize ARG rather than vice versa.  */
13389
        tree* temp = parm;
13390
        parm = arg;
13391
        arg = temp;
13392
        break;
13393
      }
13394
 
13395
    case DEDUCE_EXACT:
13396
      /* Core issue #873: Do the DR606 thing (see below) for these cases,
13397
         too, but here handle it by stripping the reference from PARM
13398
         rather than by adding it to ARG.  */
13399
      if (TREE_CODE (*parm) == REFERENCE_TYPE
13400
          && TYPE_REF_IS_RVALUE (*parm)
13401
          && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13402
          && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13403
          && TREE_CODE (*arg) == REFERENCE_TYPE
13404
          && !TYPE_REF_IS_RVALUE (*arg))
13405
        *parm = TREE_TYPE (*parm);
13406
      /* Nothing else to do in this case.  */
13407
      return 0;
13408
 
13409
    default:
13410
      gcc_unreachable ();
13411
    }
13412
 
13413
  if (TREE_CODE (*parm) != REFERENCE_TYPE)
13414
    {
13415
      /* [temp.deduct.call]
13416
 
13417
         If P is not a reference type:
13418
 
13419
         --If A is an array type, the pointer type produced by the
13420
         array-to-pointer standard conversion (_conv.array_) is
13421
         used in place of A for type deduction; otherwise,
13422
 
13423
         --If A is a function type, the pointer type produced by
13424
         the function-to-pointer standard conversion
13425
         (_conv.func_) is used in place of A for type deduction;
13426
         otherwise,
13427
 
13428
         --If A is a cv-qualified type, the top level
13429
         cv-qualifiers of A's type are ignored for type
13430
         deduction.  */
13431
      if (TREE_CODE (*arg) == ARRAY_TYPE)
13432
        *arg = build_pointer_type (TREE_TYPE (*arg));
13433
      else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13434
        *arg = build_pointer_type (*arg);
13435
      else
13436
        *arg = TYPE_MAIN_VARIANT (*arg);
13437
    }
13438
 
13439
  /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13440
     of the form T&&, where T is a template parameter, and the argument
13441
     is an lvalue, T is deduced as A& */
13442
  if (TREE_CODE (*parm) == REFERENCE_TYPE
13443
      && TYPE_REF_IS_RVALUE (*parm)
13444
      && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13445
      && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13446
      && arg_expr && real_lvalue_p (arg_expr))
13447
    *arg = build_reference_type (*arg);
13448
 
13449
  /* [temp.deduct.call]
13450
 
13451
     If P is a cv-qualified type, the top level cv-qualifiers
13452
     of P's type are ignored for type deduction.  If P is a
13453
     reference type, the type referred to by P is used for
13454
     type deduction.  */
13455
  *parm = TYPE_MAIN_VARIANT (*parm);
13456
  if (TREE_CODE (*parm) == REFERENCE_TYPE)
13457
    {
13458
      *parm = TREE_TYPE (*parm);
13459
      result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13460
    }
13461
 
13462
  /* DR 322. For conversion deduction, remove a reference type on parm
13463
     too (which has been swapped into ARG).  */
13464
  if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13465
    *arg = TREE_TYPE (*arg);
13466
 
13467
  return result;
13468
}
13469
 
13470
/* Most parms like fn_type_unification.
13471
 
13472
   If SUBR is 1, we're being called recursively (to unify the
13473
   arguments of a function or method parameter of a function
13474
   template). */
13475
 
13476
static int
13477
type_unification_real (tree tparms,
13478
                       tree targs,
13479
                       tree xparms,
13480
                       const tree *xargs,
13481
                       unsigned int xnargs,
13482
                       int subr,
13483
                       unification_kind_t strict,
13484
                       int flags)
13485
{
13486
  tree parm, arg, arg_expr;
13487
  int i;
13488
  int ntparms = TREE_VEC_LENGTH (tparms);
13489
  int sub_strict;
13490
  int saw_undeduced = 0;
13491
  tree parms;
13492
  const tree *args;
13493
  unsigned int nargs;
13494
  unsigned int ia;
13495
 
13496
  gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13497
  gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13498
  gcc_assert (ntparms > 0);
13499
 
13500
  /* Reset the number of non-defaulted template arguments contained
13501
     in in TARGS.  */
13502
  NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13503
 
13504
  switch (strict)
13505
    {
13506
    case DEDUCE_CALL:
13507
      sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13508
                    | UNIFY_ALLOW_DERIVED);
13509
      break;
13510
 
13511
    case DEDUCE_CONV:
13512
      sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13513
      break;
13514
 
13515
    case DEDUCE_EXACT:
13516
      sub_strict = UNIFY_ALLOW_NONE;
13517
      break;
13518
 
13519
    default:
13520
      gcc_unreachable ();
13521
    }
13522
 
13523
 again:
13524
  parms = xparms;
13525
  args = xargs;
13526
  nargs = xnargs;
13527
 
13528
  ia = 0;
13529
  while (parms && parms != void_list_node
13530
         && ia < nargs)
13531
    {
13532
      if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13533
        break;
13534
 
13535
      parm = TREE_VALUE (parms);
13536
      parms = TREE_CHAIN (parms);
13537
      arg = args[ia];
13538
      ++ia;
13539
      arg_expr = NULL;
13540
 
13541
      if (arg == error_mark_node)
13542
        return 1;
13543
      if (arg == unknown_type_node)
13544
        /* We can't deduce anything from this, but we might get all the
13545
           template args from other function args.  */
13546
        continue;
13547
 
13548
      /* Conversions will be performed on a function argument that
13549
         corresponds with a function parameter that contains only
13550
         non-deducible template parameters and explicitly specified
13551
         template parameters.  */
13552
      if (!uses_template_parms (parm))
13553
        {
13554
          tree type;
13555
 
13556
          if (!TYPE_P (arg))
13557
            type = TREE_TYPE (arg);
13558
          else
13559
            type = arg;
13560
 
13561
          if (same_type_p (parm, type))
13562
            continue;
13563
          if (strict != DEDUCE_EXACT
13564
              && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13565
                                  flags))
13566
            continue;
13567
 
13568
          return 1;
13569
        }
13570
 
13571
      if (!TYPE_P (arg))
13572
        {
13573
          gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13574
          if (type_unknown_p (arg))
13575
            {
13576
              /* [temp.deduct.type]
13577
 
13578
                 A template-argument can be deduced from a pointer to
13579
                 function or pointer to member function argument if
13580
                 the set of overloaded functions does not contain
13581
                 function templates and at most one of a set of
13582
                 overloaded functions provides a unique match.  */
13583
              if (resolve_overloaded_unification
13584
                  (tparms, targs, parm, arg, strict, sub_strict))
13585
                continue;
13586
 
13587
              return 1;
13588
            }
13589
          arg_expr = arg;
13590
          arg = unlowered_expr_type (arg);
13591
          if (arg == error_mark_node)
13592
            return 1;
13593
        }
13594
 
13595
      {
13596
        int arg_strict = sub_strict;
13597
 
13598
        if (!subr)
13599
          arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13600
                                                          arg_expr);
13601
 
13602
        if (arg == init_list_type_node && arg_expr)
13603
          arg = arg_expr;
13604
        if (unify (tparms, targs, parm, arg, arg_strict))
13605
          return 1;
13606
      }
13607
    }
13608
 
13609
 
13610
  if (parms
13611
      && parms != void_list_node
13612
      && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13613
    {
13614
      /* Unify the remaining arguments with the pack expansion type.  */
13615
      tree argvec;
13616
      tree parmvec = make_tree_vec (1);
13617
 
13618
      /* Allocate a TREE_VEC and copy in all of the arguments */
13619
      argvec = make_tree_vec (nargs - ia);
13620
      for (i = 0; ia < nargs; ++ia, ++i)
13621
        TREE_VEC_ELT (argvec, i) = args[ia];
13622
 
13623
      /* Copy the parameter into parmvec.  */
13624
      TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13625
      if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13626
                                /*call_args_p=*/true, /*subr=*/subr))
13627
        return 1;
13628
 
13629
      /* Advance to the end of the list of parameters.  */
13630
      parms = TREE_CHAIN (parms);
13631
    }
13632
 
13633
  /* Fail if we've reached the end of the parm list, and more args
13634
     are present, and the parm list isn't variadic.  */
13635
  if (ia < nargs && parms == void_list_node)
13636
    return 1;
13637
  /* Fail if parms are left and they don't have default values.  */
13638
  if (parms && parms != void_list_node
13639
      && TREE_PURPOSE (parms) == NULL_TREE)
13640
    return 1;
13641
 
13642
  if (!subr)
13643
    for (i = 0; i < ntparms; i++)
13644
      if (!TREE_VEC_ELT (targs, i))
13645
        {
13646
          tree tparm;
13647
 
13648
          if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13649
            continue;
13650
 
13651
          tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13652
 
13653
          /* If this is an undeduced nontype parameter that depends on
13654
             a type parameter, try another pass; its type may have been
13655
             deduced from a later argument than the one from which
13656
             this parameter can be deduced.  */
13657
          if (TREE_CODE (tparm) == PARM_DECL
13658
              && uses_template_parms (TREE_TYPE (tparm))
13659
              && !saw_undeduced++)
13660
            goto again;
13661
 
13662
          /* Core issue #226 (C++0x) [temp.deduct]:
13663
 
13664
               If a template argument has not been deduced, its
13665
               default template argument, if any, is used.
13666
 
13667
             When we are in C++98 mode, TREE_PURPOSE will either
13668
             be NULL_TREE or ERROR_MARK_NODE, so we do not need
13669
             to explicitly check cxx_dialect here.  */
13670
          if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13671
            {
13672
              tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13673
              tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13674
              arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13675
              arg = convert_template_argument (parm, arg, targs, tf_none,
13676
                                               i, NULL_TREE);
13677
              if (arg == error_mark_node)
13678
                return 1;
13679
              else
13680
                {
13681
                  TREE_VEC_ELT (targs, i) = arg;
13682
                  /* The position of the first default template argument,
13683
                     is also the number of non-defaulted arguments in TARGS.
13684
                     Record that.  */
13685
                  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13686
                    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13687
                  continue;
13688
                }
13689
            }
13690
 
13691
          /* If the type parameter is a parameter pack, then it will
13692
             be deduced to an empty parameter pack.  */
13693
          if (template_parameter_pack_p (tparm))
13694
            {
13695
              tree arg;
13696
 
13697
              if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13698
                {
13699
                  arg = make_node (NONTYPE_ARGUMENT_PACK);
13700
                  TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13701
                  TREE_CONSTANT (arg) = 1;
13702
                }
13703
              else
13704
                arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13705
 
13706
              SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13707
 
13708
              TREE_VEC_ELT (targs, i) = arg;
13709
              continue;
13710
            }
13711
 
13712
          return 2;
13713
        }
13714
#ifdef ENABLE_CHECKING
13715
  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13716
    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13717
#endif
13718
 
13719
  return 0;
13720
}
13721
 
13722
/* Subroutine of type_unification_real.  Args are like the variables
13723
   at the call site.  ARG is an overloaded function (or template-id);
13724
   we try deducing template args from each of the overloads, and if
13725
   only one succeeds, we go with that.  Modifies TARGS and returns
13726
   true on success.  */
13727
 
13728
static bool
13729
resolve_overloaded_unification (tree tparms,
13730
                                tree targs,
13731
                                tree parm,
13732
                                tree arg,
13733
                                unification_kind_t strict,
13734
                                int sub_strict)
13735
{
13736
  tree tempargs = copy_node (targs);
13737
  int good = 0;
13738
  tree goodfn = NULL_TREE;
13739
  bool addr_p;
13740
 
13741
  if (TREE_CODE (arg) == ADDR_EXPR)
13742
    {
13743
      arg = TREE_OPERAND (arg, 0);
13744
      addr_p = true;
13745
    }
13746
  else
13747
    addr_p = false;
13748
 
13749
  if (TREE_CODE (arg) == COMPONENT_REF)
13750
    /* Handle `&x' where `x' is some static or non-static member
13751
       function name.  */
13752
    arg = TREE_OPERAND (arg, 1);
13753
 
13754
  if (TREE_CODE (arg) == OFFSET_REF)
13755
    arg = TREE_OPERAND (arg, 1);
13756
 
13757
  /* Strip baselink information.  */
13758
  if (BASELINK_P (arg))
13759
    arg = BASELINK_FUNCTIONS (arg);
13760
 
13761
  if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13762
    {
13763
      /* If we got some explicit template args, we need to plug them into
13764
         the affected templates before we try to unify, in case the
13765
         explicit args will completely resolve the templates in question.  */
13766
 
13767
      tree expl_subargs = TREE_OPERAND (arg, 1);
13768
      arg = TREE_OPERAND (arg, 0);
13769
 
13770
      for (; arg; arg = OVL_NEXT (arg))
13771
        {
13772
          tree fn = OVL_CURRENT (arg);
13773
          tree subargs, elem;
13774
 
13775
          if (TREE_CODE (fn) != TEMPLATE_DECL)
13776
            continue;
13777
 
13778
          ++processing_template_decl;
13779
          subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13780
                                  expl_subargs, /*check_ret=*/false);
13781
          if (subargs)
13782
            {
13783
              elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13784
              if (try_one_overload (tparms, targs, tempargs, parm,
13785
                                    elem, strict, sub_strict, addr_p)
13786
                  && (!goodfn || !decls_match (goodfn, elem)))
13787
                {
13788
                  goodfn = elem;
13789
                  ++good;
13790
                }
13791
            }
13792
          --processing_template_decl;
13793
        }
13794
    }
13795
  else if (TREE_CODE (arg) != OVERLOAD
13796
           && TREE_CODE (arg) != FUNCTION_DECL)
13797
    /* If ARG is, for example, "(0, &f)" then its type will be unknown
13798
       -- but the deduction does not succeed because the expression is
13799
       not just the function on its own.  */
13800
    return false;
13801
  else
13802
    for (; arg; arg = OVL_NEXT (arg))
13803
      if (try_one_overload (tparms, targs, tempargs, parm,
13804
                            TREE_TYPE (OVL_CURRENT (arg)),
13805
                            strict, sub_strict, addr_p)
13806
          && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13807
        {
13808
          goodfn = OVL_CURRENT (arg);
13809
          ++good;
13810
        }
13811
 
13812
  /* [temp.deduct.type] A template-argument can be deduced from a pointer
13813
     to function or pointer to member function argument if the set of
13814
     overloaded functions does not contain function templates and at most
13815
     one of a set of overloaded functions provides a unique match.
13816
 
13817
     So if we found multiple possibilities, we return success but don't
13818
     deduce anything.  */
13819
 
13820
  if (good == 1)
13821
    {
13822
      int i = TREE_VEC_LENGTH (targs);
13823
      for (; i--; )
13824
        if (TREE_VEC_ELT (tempargs, i))
13825
          TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13826
    }
13827
  if (good)
13828
    return true;
13829
 
13830
  return false;
13831
}
13832
 
13833
/* Core DR 115: In contexts where deduction is done and fails, or in
13834
   contexts where deduction is not done, if a template argument list is
13835
   specified and it, along with any default template arguments, identifies
13836
   a single function template specialization, then the template-id is an
13837
   lvalue for the function template specialization.  */
13838
 
13839
tree
13840
resolve_nondeduced_context (tree orig_expr)
13841
{
13842
  tree expr, offset, baselink;
13843
  bool addr;
13844
 
13845
  if (!type_unknown_p (orig_expr))
13846
    return orig_expr;
13847
 
13848
  expr = orig_expr;
13849
  addr = false;
13850
  offset = NULL_TREE;
13851
  baselink = NULL_TREE;
13852
 
13853
  if (TREE_CODE (expr) == ADDR_EXPR)
13854
    {
13855
      expr = TREE_OPERAND (expr, 0);
13856
      addr = true;
13857
    }
13858
  if (TREE_CODE (expr) == OFFSET_REF)
13859
    {
13860
      offset = expr;
13861
      expr = TREE_OPERAND (expr, 1);
13862
    }
13863
  if (TREE_CODE (expr) == BASELINK)
13864
    {
13865
      baselink = expr;
13866
      expr = BASELINK_FUNCTIONS (expr);
13867
    }
13868
 
13869
  if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13870
    {
13871
      int good = 0;
13872
      tree goodfn = NULL_TREE;
13873
 
13874
      /* If we got some explicit template args, we need to plug them into
13875
         the affected templates before we try to unify, in case the
13876
         explicit args will completely resolve the templates in question.  */
13877
 
13878
      tree expl_subargs = TREE_OPERAND (expr, 1);
13879
      tree arg = TREE_OPERAND (expr, 0);
13880
      tree badfn = NULL_TREE;
13881
      tree badargs = NULL_TREE;
13882
 
13883
      for (; arg; arg = OVL_NEXT (arg))
13884
        {
13885
          tree fn = OVL_CURRENT (arg);
13886
          tree subargs, elem;
13887
 
13888
          if (TREE_CODE (fn) != TEMPLATE_DECL)
13889
            continue;
13890
 
13891
          ++processing_template_decl;
13892
          subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13893
                                  expl_subargs, /*check_ret=*/false);
13894
          if (subargs && !any_dependent_template_arguments_p (subargs))
13895
            {
13896
              elem = instantiate_template (fn, subargs, tf_none);
13897
              if (elem == error_mark_node)
13898
                {
13899
                  badfn = fn;
13900
                  badargs = subargs;
13901
                }
13902
              else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13903
                {
13904
                  goodfn = elem;
13905
                  ++good;
13906
                }
13907
            }
13908
          --processing_template_decl;
13909
        }
13910
      if (good == 1)
13911
        {
13912
          expr = goodfn;
13913
          if (baselink)
13914
            expr = build_baselink (BASELINK_BINFO (baselink),
13915
                                   BASELINK_ACCESS_BINFO (baselink),
13916
                                   expr, BASELINK_OPTYPE (baselink));
13917
          if (offset)
13918
            expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13919
                           TREE_OPERAND (offset, 0), expr);
13920
          if (addr)
13921
            expr = build_address (expr);
13922
          return expr;
13923
        }
13924
      else if (good == 0 && badargs)
13925
        /* There were no good options and at least one bad one, so let the
13926
           user know what the problem is.  */
13927
        instantiate_template (badfn, badargs, tf_warning_or_error);
13928
    }
13929
  return orig_expr;
13930
}
13931
 
13932
/* Subroutine of resolve_overloaded_unification; does deduction for a single
13933
   overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13934
   different overloads deduce different arguments for a given parm.
13935
   ADDR_P is true if the expression for which deduction is being
13936
   performed was of the form "& fn" rather than simply "fn".
13937
 
13938
   Returns 1 on success.  */
13939
 
13940
static int
13941
try_one_overload (tree tparms,
13942
                  tree orig_targs,
13943
                  tree targs,
13944
                  tree parm,
13945
                  tree arg,
13946
                  unification_kind_t strict,
13947
                  int sub_strict,
13948
                  bool addr_p)
13949
{
13950
  int nargs;
13951
  tree tempargs;
13952
  int i;
13953
 
13954
  /* [temp.deduct.type] A template-argument can be deduced from a pointer
13955
     to function or pointer to member function argument if the set of
13956
     overloaded functions does not contain function templates and at most
13957
     one of a set of overloaded functions provides a unique match.
13958
 
13959
     So if this is a template, just return success.  */
13960
 
13961
  if (uses_template_parms (arg))
13962
    return 1;
13963
 
13964
  if (TREE_CODE (arg) == METHOD_TYPE)
13965
    arg = build_ptrmemfunc_type (build_pointer_type (arg));
13966
  else if (addr_p)
13967
    arg = build_pointer_type (arg);
13968
 
13969
  sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13970
 
13971
  /* We don't copy orig_targs for this because if we have already deduced
13972
     some template args from previous args, unify would complain when we
13973
     try to deduce a template parameter for the same argument, even though
13974
     there isn't really a conflict.  */
13975
  nargs = TREE_VEC_LENGTH (targs);
13976
  tempargs = make_tree_vec (nargs);
13977
 
13978
  if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13979
    return 0;
13980
 
13981
  /* First make sure we didn't deduce anything that conflicts with
13982
     explicitly specified args.  */
13983
  for (i = nargs; i--; )
13984
    {
13985
      tree elt = TREE_VEC_ELT (tempargs, i);
13986
      tree oldelt = TREE_VEC_ELT (orig_targs, i);
13987
 
13988
      if (!elt)
13989
        /*NOP*/;
13990
      else if (uses_template_parms (elt))
13991
        /* Since we're unifying against ourselves, we will fill in
13992
           template args used in the function parm list with our own
13993
           template parms.  Discard them.  */
13994
        TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13995
      else if (oldelt && !template_args_equal (oldelt, elt))
13996
        return 0;
13997
    }
13998
 
13999
  for (i = nargs; i--; )
14000
    {
14001
      tree elt = TREE_VEC_ELT (tempargs, i);
14002
 
14003
      if (elt)
14004
        TREE_VEC_ELT (targs, i) = elt;
14005
    }
14006
 
14007
  return 1;
14008
}
14009
 
14010
/* PARM is a template class (perhaps with unbound template
14011
   parameters).  ARG is a fully instantiated type.  If ARG can be
14012
   bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14013
   TARGS are as for unify.  */
14014
 
14015
static tree
14016
try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14017
{
14018
  tree copy_of_targs;
14019
 
14020
  if (!CLASSTYPE_TEMPLATE_INFO (arg)
14021
      || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14022
          != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14023
    return NULL_TREE;
14024
 
14025
  /* We need to make a new template argument vector for the call to
14026
     unify.  If we used TARGS, we'd clutter it up with the result of
14027
     the attempted unification, even if this class didn't work out.
14028
     We also don't want to commit ourselves to all the unifications
14029
     we've already done, since unification is supposed to be done on
14030
     an argument-by-argument basis.  In other words, consider the
14031
     following pathological case:
14032
 
14033
       template <int I, int J, int K>
14034
       struct S {};
14035
 
14036
       template <int I, int J>
14037
       struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14038
 
14039
       template <int I, int J, int K>
14040
       void f(S<I, J, K>, S<I, I, I>);
14041
 
14042
       void g() {
14043
         S<0, 0, 0> s0;
14044
         S<0, 1, 2> s2;
14045
 
14046
         f(s0, s2);
14047
       }
14048
 
14049
     Now, by the time we consider the unification involving `s2', we
14050
     already know that we must have `f<0, 0, 0>'.  But, even though
14051
     `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14052
     because there are two ways to unify base classes of S<0, 1, 2>
14053
     with S<I, I, I>.  If we kept the already deduced knowledge, we
14054
     would reject the possibility I=1.  */
14055
  copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14056
 
14057
  /* If unification failed, we're done.  */
14058
  if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14059
             CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14060
    return NULL_TREE;
14061
 
14062
  return arg;
14063
}
14064
 
14065
/* Given a template type PARM and a class type ARG, find the unique
14066
   base type in ARG that is an instance of PARM.  We do not examine
14067
   ARG itself; only its base-classes.  If there is not exactly one
14068
   appropriate base class, return NULL_TREE.  PARM may be the type of
14069
   a partial specialization, as well as a plain template type.  Used
14070
   by unify.  */
14071
 
14072
static tree
14073
get_template_base (tree tparms, tree targs, tree parm, tree arg)
14074
{
14075
  tree rval = NULL_TREE;
14076
  tree binfo;
14077
 
14078
  gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14079
 
14080
  binfo = TYPE_BINFO (complete_type (arg));
14081
  if (!binfo)
14082
    /* The type could not be completed.  */
14083
    return NULL_TREE;
14084
 
14085
  /* Walk in inheritance graph order.  The search order is not
14086
     important, and this avoids multiple walks of virtual bases.  */
14087
  for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14088
    {
14089
      tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14090
 
14091
      if (r)
14092
        {
14093
          /* If there is more than one satisfactory baseclass, then:
14094
 
14095
               [temp.deduct.call]
14096
 
14097
              If they yield more than one possible deduced A, the type
14098
              deduction fails.
14099
 
14100
             applies.  */
14101
          if (rval && !same_type_p (r, rval))
14102
            return NULL_TREE;
14103
 
14104
          rval = r;
14105
        }
14106
    }
14107
 
14108
  return rval;
14109
}
14110
 
14111
/* Returns the level of DECL, which declares a template parameter.  */
14112
 
14113
static int
14114
template_decl_level (tree decl)
14115
{
14116
  switch (TREE_CODE (decl))
14117
    {
14118
    case TYPE_DECL:
14119
    case TEMPLATE_DECL:
14120
      return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14121
 
14122
    case PARM_DECL:
14123
      return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14124
 
14125
    default:
14126
      gcc_unreachable ();
14127
    }
14128
  return 0;
14129
}
14130
 
14131
/* Decide whether ARG can be unified with PARM, considering only the
14132
   cv-qualifiers of each type, given STRICT as documented for unify.
14133
   Returns nonzero iff the unification is OK on that basis.  */
14134
 
14135
static int
14136
check_cv_quals_for_unify (int strict, tree arg, tree parm)
14137
{
14138
  int arg_quals = cp_type_quals (arg);
14139
  int parm_quals = cp_type_quals (parm);
14140
 
14141
  if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14142
      && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14143
    {
14144
      /*  Although a CVR qualifier is ignored when being applied to a
14145
          substituted template parameter ([8.3.2]/1 for example), that
14146
          does not apply during deduction [14.8.2.4]/1, (even though
14147
          that is not explicitly mentioned, [14.8.2.4]/9 indicates
14148
          this).  Except when we're allowing additional CV qualifiers
14149
          at the outer level [14.8.2.1]/3,1st bullet.  */
14150
      if ((TREE_CODE (arg) == REFERENCE_TYPE
14151
           || TREE_CODE (arg) == FUNCTION_TYPE
14152
           || TREE_CODE (arg) == METHOD_TYPE)
14153
          && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14154
        return 0;
14155
 
14156
      if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14157
          && (parm_quals & TYPE_QUAL_RESTRICT))
14158
        return 0;
14159
    }
14160
 
14161
  if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14162
      && (arg_quals & parm_quals) != parm_quals)
14163
    return 0;
14164
 
14165
  if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14166
      && (parm_quals & arg_quals) != arg_quals)
14167
    return 0;
14168
 
14169
  return 1;
14170
}
14171
 
14172
/* Determines the LEVEL and INDEX for the template parameter PARM.  */
14173
void
14174
template_parm_level_and_index (tree parm, int* level, int* index)
14175
{
14176
  if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14177
      || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14178
      || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14179
    {
14180
      *index = TEMPLATE_TYPE_IDX (parm);
14181
      *level = TEMPLATE_TYPE_LEVEL (parm);
14182
    }
14183
  else
14184
    {
14185
      *index = TEMPLATE_PARM_IDX (parm);
14186
      *level = TEMPLATE_PARM_LEVEL (parm);
14187
    }
14188
}
14189
 
14190
/* Unifies the remaining arguments in PACKED_ARGS with the pack
14191
   expansion at the end of PACKED_PARMS. Returns 0 if the type
14192
   deduction succeeds, 1 otherwise. STRICT is the same as in
14193
   unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14194
   call argument list. We'll need to adjust the arguments to make them
14195
   types. SUBR tells us if this is from a recursive call to
14196
   type_unification_real.  */
14197
int
14198
unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
14199
                      tree packed_args, int strict, bool call_args_p,
14200
                      bool subr)
14201
{
14202
  tree parm
14203
    = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14204
  tree pattern = PACK_EXPANSION_PATTERN (parm);
14205
  tree pack, packs = NULL_TREE;
14206
  int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14207
  int len = TREE_VEC_LENGTH (packed_args);
14208
 
14209
  /* Determine the parameter packs we will be deducing from the
14210
     pattern, and record their current deductions.  */
14211
  for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
14212
       pack; pack = TREE_CHAIN (pack))
14213
    {
14214
      tree parm_pack = TREE_VALUE (pack);
14215
      int idx, level;
14216
 
14217
      /* Determine the index and level of this parameter pack.  */
14218
      template_parm_level_and_index (parm_pack, &level, &idx);
14219
 
14220
      /* Keep track of the parameter packs and their corresponding
14221
         argument packs.  */
14222
      packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14223
      TREE_TYPE (packs) = make_tree_vec (len - start);
14224
    }
14225
 
14226
  /* Loop through all of the arguments that have not yet been
14227
     unified and unify each with the pattern.  */
14228
  for (i = start; i < len; i++)
14229
    {
14230
      tree parm = pattern;
14231
 
14232
      /* For each parameter pack, clear out the deduced value so that
14233
         we can deduce it again.  */
14234
      for (pack = packs; pack; pack = TREE_CHAIN (pack))
14235
        {
14236
          int idx, level;
14237
          template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14238
 
14239
          TMPL_ARG (targs, level, idx) = NULL_TREE;
14240
        }
14241
 
14242
      /* Unify the pattern with the current argument.  */
14243
      {
14244
        tree arg = TREE_VEC_ELT (packed_args, i);
14245
        tree arg_expr = NULL_TREE;
14246
        int arg_strict = strict;
14247
        bool skip_arg_p = false;
14248
 
14249
        if (call_args_p)
14250
          {
14251
            int sub_strict;
14252
 
14253
            /* This mirrors what we do in type_unification_real.  */
14254
            switch (strict)
14255
              {
14256
              case DEDUCE_CALL:
14257
                sub_strict = (UNIFY_ALLOW_OUTER_LEVEL
14258
                              | UNIFY_ALLOW_MORE_CV_QUAL
14259
                              | UNIFY_ALLOW_DERIVED);
14260
                break;
14261
 
14262
              case DEDUCE_CONV:
14263
                sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14264
                break;
14265
 
14266
              case DEDUCE_EXACT:
14267
                sub_strict = UNIFY_ALLOW_NONE;
14268
                break;
14269
 
14270
              default:
14271
                gcc_unreachable ();
14272
              }
14273
 
14274
            if (!TYPE_P (arg))
14275
              {
14276
                gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14277
                if (type_unknown_p (arg))
14278
                  {
14279
                    /* [temp.deduct.type] A template-argument can be
14280
                       deduced from a pointer to function or pointer
14281
                       to member function argument if the set of
14282
                       overloaded functions does not contain function
14283
                       templates and at most one of a set of
14284
                       overloaded functions provides a unique
14285
                       match.  */
14286
 
14287
                    if (resolve_overloaded_unification
14288
                        (tparms, targs, parm, arg,
14289
                         (unification_kind_t) strict,
14290
                         sub_strict)
14291
                        != 0)
14292
                      return 1;
14293
                    skip_arg_p = true;
14294
                  }
14295
 
14296
                if (!skip_arg_p)
14297
                  {
14298
                    arg_expr = arg;
14299
                    arg = unlowered_expr_type (arg);
14300
                    if (arg == error_mark_node)
14301
                      return 1;
14302
                  }
14303
              }
14304
 
14305
            arg_strict = sub_strict;
14306
 
14307
            if (!subr)
14308
              arg_strict |=
14309
                maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14310
                                                  &parm, &arg, arg_expr);
14311
          }
14312
 
14313
        if (!skip_arg_p)
14314
          {
14315
            /* For deduction from an init-list we need the actual list.  */
14316
            if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14317
              arg = arg_expr;
14318
            if (unify (tparms, targs, parm, arg, arg_strict))
14319
              return 1;
14320
          }
14321
      }
14322
 
14323
      /* For each parameter pack, collect the deduced value.  */
14324
      for (pack = packs; pack; pack = TREE_CHAIN (pack))
14325
        {
14326
          int idx, level;
14327
          template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14328
 
14329
          TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
14330
            TMPL_ARG (targs, level, idx);
14331
        }
14332
    }
14333
 
14334
  /* Verify that the results of unification with the parameter packs
14335
     produce results consistent with what we've seen before, and make
14336
     the deduced argument packs available.  */
14337
  for (pack = packs; pack; pack = TREE_CHAIN (pack))
14338
    {
14339
      tree old_pack = TREE_VALUE (pack);
14340
      tree new_args = TREE_TYPE (pack);
14341
      int i, len = TREE_VEC_LENGTH (new_args);
14342
      int idx, level;
14343
      bool nondeduced_p = false;
14344
 
14345
      /* By default keep the original deduced argument pack.
14346
         If necessary, more specific code is going to update the
14347
         resulting deduced argument later down in this function.  */
14348
      template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14349
      TMPL_ARG (targs, level, idx) = old_pack;
14350
 
14351
      /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14352
         actually deduce anything.  */
14353
      for (i = 0; i < len && !nondeduced_p; ++i)
14354
        if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14355
          nondeduced_p = true;
14356
      if (nondeduced_p)
14357
        continue;
14358
 
14359
      if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14360
        {
14361
          /* Prepend the explicit arguments onto NEW_ARGS.  */
14362
          tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14363
          tree old_args = new_args;
14364
          int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14365
          int len = explicit_len + TREE_VEC_LENGTH (old_args);
14366
 
14367
          /* Copy the explicit arguments.  */
14368
          new_args = make_tree_vec (len);
14369
          for (i = 0; i < explicit_len; i++)
14370
            TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14371
 
14372
          /* Copy the deduced arguments.  */
14373
          for (; i < len; i++)
14374
            TREE_VEC_ELT (new_args, i) =
14375
              TREE_VEC_ELT (old_args, i - explicit_len);
14376
        }
14377
 
14378
      if (!old_pack)
14379
        {
14380
          tree result;
14381
          /* Build the deduced *_ARGUMENT_PACK.  */
14382
          if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14383
            {
14384
              result = make_node (NONTYPE_ARGUMENT_PACK);
14385
              TREE_TYPE (result) =
14386
                TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14387
              TREE_CONSTANT (result) = 1;
14388
            }
14389
          else
14390
            result = cxx_make_type (TYPE_ARGUMENT_PACK);
14391
 
14392
          SET_ARGUMENT_PACK_ARGS (result, new_args);
14393
 
14394
          /* Note the deduced argument packs for this parameter
14395
             pack.  */
14396
          TMPL_ARG (targs, level, idx) = result;
14397
        }
14398
      else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14399
               && (ARGUMENT_PACK_ARGS (old_pack)
14400
                   == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14401
        {
14402
          /* We only had the explicitly-provided arguments before, but
14403
             now we have a complete set of arguments.  */
14404
          tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14405
 
14406
          SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14407
          ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14408
          ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14409
        }
14410
      else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14411
                                    new_args))
14412
        /* Inconsistent unification of this parameter pack.  */
14413
        return 1;
14414
    }
14415
 
14416
  return 0;
14417
}
14418
 
14419
/* Deduce the value of template parameters.  TPARMS is the (innermost)
14420
   set of template parameters to a template.  TARGS is the bindings
14421
   for those template parameters, as determined thus far; TARGS may
14422
   include template arguments for outer levels of template parameters
14423
   as well.  PARM is a parameter to a template function, or a
14424
   subcomponent of that parameter; ARG is the corresponding argument.
14425
   This function attempts to match PARM with ARG in a manner
14426
   consistent with the existing assignments in TARGS.  If more values
14427
   are deduced, then TARGS is updated.
14428
 
14429
   Returns 0 if the type deduction succeeds, 1 otherwise.  The
14430
   parameter STRICT is a bitwise or of the following flags:
14431
 
14432
     UNIFY_ALLOW_NONE:
14433
       Require an exact match between PARM and ARG.
14434
     UNIFY_ALLOW_MORE_CV_QUAL:
14435
       Allow the deduced ARG to be more cv-qualified (by qualification
14436
       conversion) than ARG.
14437
     UNIFY_ALLOW_LESS_CV_QUAL:
14438
       Allow the deduced ARG to be less cv-qualified than ARG.
14439
     UNIFY_ALLOW_DERIVED:
14440
       Allow the deduced ARG to be a template base class of ARG,
14441
       or a pointer to a template base class of the type pointed to by
14442
       ARG.
14443
     UNIFY_ALLOW_INTEGER:
14444
       Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14445
       case for more information.
14446
     UNIFY_ALLOW_OUTER_LEVEL:
14447
       This is the outermost level of a deduction. Used to determine validity
14448
       of qualification conversions. A valid qualification conversion must
14449
       have const qualified pointers leading up to the inner type which
14450
       requires additional CV quals, except at the outer level, where const
14451
       is not required [conv.qual]. It would be normal to set this flag in
14452
       addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14453
     UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14454
       This is the outermost level of a deduction, and PARM can be more CV
14455
       qualified at this point.
14456
     UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14457
       This is the outermost level of a deduction, and PARM can be less CV
14458
       qualified at this point.  */
14459
 
14460
static int
14461
unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14462
{
14463
  int idx;
14464
  tree targ;
14465
  tree tparm;
14466
  int strict_in = strict;
14467
 
14468
  /* I don't think this will do the right thing with respect to types.
14469
     But the only case I've seen it in so far has been array bounds, where
14470
     signedness is the only information lost, and I think that will be
14471
     okay.  */
14472
  while (TREE_CODE (parm) == NOP_EXPR)
14473
    parm = TREE_OPERAND (parm, 0);
14474
 
14475
  if (arg == error_mark_node)
14476
    return 1;
14477
  if (arg == unknown_type_node
14478
      || arg == init_list_type_node)
14479
    /* We can't deduce anything from this, but we might get all the
14480
       template args from other function args.  */
14481
    return 0;
14482
 
14483
  /* If PARM uses template parameters, then we can't bail out here,
14484
     even if ARG == PARM, since we won't record unifications for the
14485
     template parameters.  We might need them if we're trying to
14486
     figure out which of two things is more specialized.  */
14487
  if (arg == parm && !uses_template_parms (parm))
14488
    return 0;
14489
 
14490
  /* Handle init lists early, so the rest of the function can assume
14491
     we're dealing with a type. */
14492
  if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14493
    {
14494
      tree elt, elttype;
14495
      unsigned i;
14496
      tree orig_parm = parm;
14497
 
14498
      /* Replace T with std::initializer_list<T> for deduction.  */
14499
      if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14500
          && flag_deduce_init_list)
14501
        parm = listify (parm);
14502
 
14503
      if (!is_std_init_list (parm))
14504
        /* We can only deduce from an initializer list argument if the
14505
           parameter is std::initializer_list; otherwise this is a
14506
           non-deduced context. */
14507
        return 0;
14508
 
14509
      elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14510
 
14511
      FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14512
        {
14513
          int elt_strict = strict;
14514
          if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14515
            {
14516
              tree type = TREE_TYPE (elt);
14517
              /* It should only be possible to get here for a call.  */
14518
              gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14519
              elt_strict |= maybe_adjust_types_for_deduction
14520
                (DEDUCE_CALL, &elttype, &type, elt);
14521
              elt = type;
14522
            }
14523
 
14524
          if (unify (tparms, targs, elttype, elt, elt_strict))
14525
            return 1;
14526
        }
14527
 
14528
      /* If the std::initializer_list<T> deduction worked, replace the
14529
         deduced A with std::initializer_list<A>.  */
14530
      if (orig_parm != parm)
14531
        {
14532
          idx = TEMPLATE_TYPE_IDX (orig_parm);
14533
          targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14534
          targ = listify (targ);
14535
          TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14536
        }
14537
      return 0;
14538
    }
14539
 
14540
  /* Immediately reject some pairs that won't unify because of
14541
     cv-qualification mismatches.  */
14542
  if (TREE_CODE (arg) == TREE_CODE (parm)
14543
      && TYPE_P (arg)
14544
      /* It is the elements of the array which hold the cv quals of an array
14545
         type, and the elements might be template type parms. We'll check
14546
         when we recurse.  */
14547
      && TREE_CODE (arg) != ARRAY_TYPE
14548
      /* We check the cv-qualifiers when unifying with template type
14549
         parameters below.  We want to allow ARG `const T' to unify with
14550
         PARM `T' for example, when computing which of two templates
14551
         is more specialized, for example.  */
14552
      && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14553
      && !check_cv_quals_for_unify (strict_in, arg, parm))
14554
    return 1;
14555
 
14556
  if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14557
      && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14558
    strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14559
  strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14560
  strict &= ~UNIFY_ALLOW_DERIVED;
14561
  strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14562
  strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14563
 
14564
  switch (TREE_CODE (parm))
14565
    {
14566
    case TYPENAME_TYPE:
14567
    case SCOPE_REF:
14568
    case UNBOUND_CLASS_TEMPLATE:
14569
      /* In a type which contains a nested-name-specifier, template
14570
         argument values cannot be deduced for template parameters used
14571
         within the nested-name-specifier.  */
14572
      return 0;
14573
 
14574
    case TEMPLATE_TYPE_PARM:
14575
    case TEMPLATE_TEMPLATE_PARM:
14576
    case BOUND_TEMPLATE_TEMPLATE_PARM:
14577
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14578
      if (tparm == error_mark_node)
14579
        return 1;
14580
 
14581
      if (TEMPLATE_TYPE_LEVEL (parm)
14582
          != template_decl_level (tparm))
14583
        /* The PARM is not one we're trying to unify.  Just check
14584
           to see if it matches ARG.  */
14585
        return (TREE_CODE (arg) == TREE_CODE (parm)
14586
                && same_type_p (parm, arg)) ? 0 : 1;
14587
      idx = TEMPLATE_TYPE_IDX (parm);
14588
      targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14589
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14590
 
14591
      /* Check for mixed types and values.  */
14592
      if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14593
           && TREE_CODE (tparm) != TYPE_DECL)
14594
          || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14595
              && TREE_CODE (tparm) != TEMPLATE_DECL))
14596
        return 1;
14597
 
14598
      if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14599
        {
14600
          /* ARG must be constructed from a template class or a template
14601
             template parameter.  */
14602
          if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14603
              && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14604
            return 1;
14605
 
14606
          {
14607
            tree parmvec = TYPE_TI_ARGS (parm);
14608
            tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14609
            tree parm_parms
14610
              = DECL_INNERMOST_TEMPLATE_PARMS
14611
                  (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14612
            int i, len;
14613
            int parm_variadic_p = 0;
14614
 
14615
            /* The resolution to DR150 makes clear that default
14616
               arguments for an N-argument may not be used to bind T
14617
               to a template template parameter with fewer than N
14618
               parameters.  It is not safe to permit the binding of
14619
               default arguments as an extension, as that may change
14620
               the meaning of a conforming program.  Consider:
14621
 
14622
                  struct Dense { static const unsigned int dim = 1; };
14623
 
14624
                  template <template <typename> class View,
14625
                            typename Block>
14626
                  void operator+(float, View<Block> const&);
14627
 
14628
                  template <typename Block,
14629
                            unsigned int Dim = Block::dim>
14630
                  struct Lvalue_proxy { operator float() const; };
14631
 
14632
                  void
14633
                  test_1d (void) {
14634
                    Lvalue_proxy<Dense> p;
14635
                    float b;
14636
                    b + p;
14637
                  }
14638
 
14639
              Here, if Lvalue_proxy is permitted to bind to View, then
14640
              the global operator+ will be used; if they are not, the
14641
              Lvalue_proxy will be converted to float.  */
14642
            if (coerce_template_parms (parm_parms,
14643
                                       argvec,
14644
                                       TYPE_TI_TEMPLATE (parm),
14645
                                       tf_none,
14646
                                       /*require_all_args=*/true,
14647
                                       /*use_default_args=*/false)
14648
                == error_mark_node)
14649
              return 1;
14650
 
14651
            /* Deduce arguments T, i from TT<T> or TT<i>.
14652
               We check each element of PARMVEC and ARGVEC individually
14653
               rather than the whole TREE_VEC since they can have
14654
               different number of elements.  */
14655
 
14656
            parmvec = expand_template_argument_pack (parmvec);
14657
            argvec = expand_template_argument_pack (argvec);
14658
 
14659
            len = TREE_VEC_LENGTH (parmvec);
14660
 
14661
            /* Check if the parameters end in a pack, making them
14662
               variadic.  */
14663
            if (len > 0
14664
                && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14665
              parm_variadic_p = 1;
14666
 
14667
            if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14668
              return 1;
14669
 
14670
             for (i = 0; i < len - parm_variadic_p; ++i)
14671
              {
14672
                if (unify (tparms, targs,
14673
                           TREE_VEC_ELT (parmvec, i),
14674
                           TREE_VEC_ELT (argvec, i),
14675
                           UNIFY_ALLOW_NONE))
14676
                  return 1;
14677
              }
14678
 
14679
            if (parm_variadic_p
14680
                && unify_pack_expansion (tparms, targs,
14681
                                         parmvec, argvec,
14682
                                         UNIFY_ALLOW_NONE,
14683
                                         /*call_args_p=*/false,
14684
                                         /*subr=*/false))
14685
              return 1;
14686
          }
14687
          arg = TYPE_TI_TEMPLATE (arg);
14688
 
14689
          /* Fall through to deduce template name.  */
14690
        }
14691
 
14692
      if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14693
          || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14694
        {
14695
          /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14696
 
14697
          /* Simple cases: Value already set, does match or doesn't.  */
14698
          if (targ != NULL_TREE && template_args_equal (targ, arg))
14699
            return 0;
14700
          else if (targ)
14701
            return 1;
14702
        }
14703
      else
14704
        {
14705
          /* If PARM is `const T' and ARG is only `int', we don't have
14706
             a match unless we are allowing additional qualification.
14707
             If ARG is `const int' and PARM is just `T' that's OK;
14708
             that binds `const int' to `T'.  */
14709
          if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14710
                                         arg, parm))
14711
            return 1;
14712
 
14713
          /* Consider the case where ARG is `const volatile int' and
14714
             PARM is `const T'.  Then, T should be `volatile int'.  */
14715
          arg = cp_build_qualified_type_real
14716
            (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14717
          if (arg == error_mark_node)
14718
            return 1;
14719
 
14720
          /* Simple cases: Value already set, does match or doesn't.  */
14721
          if (targ != NULL_TREE && same_type_p (targ, arg))
14722
            return 0;
14723
          else if (targ)
14724
            return 1;
14725
 
14726
          /* Make sure that ARG is not a variable-sized array.  (Note
14727
             that were talking about variable-sized arrays (like
14728
             `int[n]'), rather than arrays of unknown size (like
14729
             `int[]').)  We'll get very confused by such a type since
14730
             the bound of the array will not be computable in an
14731
             instantiation.  Besides, such types are not allowed in
14732
             ISO C++, so we can do as we please here.  */
14733
          if (variably_modified_type_p (arg, NULL_TREE))
14734
            return 1;
14735
 
14736
          /* Strip typedefs as in convert_template_argument.  */
14737
          arg = strip_typedefs (arg);
14738
        }
14739
 
14740
      /* If ARG is a parameter pack or an expansion, we cannot unify
14741
         against it unless PARM is also a parameter pack.  */
14742
      if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14743
          && !template_parameter_pack_p (parm))
14744
        return 1;
14745
 
14746
      /* If the argument deduction results is a METHOD_TYPE,
14747
         then there is a problem.
14748
         METHOD_TYPE doesn't map to any real C++ type the result of
14749
         the deduction can not be of that type.  */
14750
      if (TREE_CODE (arg) == METHOD_TYPE)
14751
        return 1;
14752
 
14753
      TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14754
      return 0;
14755
 
14756
    case TEMPLATE_PARM_INDEX:
14757
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14758
      if (tparm == error_mark_node)
14759
        return 1;
14760
 
14761
      if (TEMPLATE_PARM_LEVEL (parm)
14762
          != template_decl_level (tparm))
14763
        /* The PARM is not one we're trying to unify.  Just check
14764
           to see if it matches ARG.  */
14765
        return !(TREE_CODE (arg) == TREE_CODE (parm)
14766
                 && cp_tree_equal (parm, arg));
14767
 
14768
      idx = TEMPLATE_PARM_IDX (parm);
14769
      targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14770
 
14771
      if (targ)
14772
        return !cp_tree_equal (targ, arg);
14773
 
14774
      /* [temp.deduct.type] If, in the declaration of a function template
14775
         with a non-type template-parameter, the non-type
14776
         template-parameter is used in an expression in the function
14777
         parameter-list and, if the corresponding template-argument is
14778
         deduced, the template-argument type shall match the type of the
14779
         template-parameter exactly, except that a template-argument
14780
         deduced from an array bound may be of any integral type.
14781
         The non-type parameter might use already deduced type parameters.  */
14782
      tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14783
      if (!TREE_TYPE (arg))
14784
        /* Template-parameter dependent expression.  Just accept it for now.
14785
           It will later be processed in convert_template_argument.  */
14786
        ;
14787
      else if (same_type_p (TREE_TYPE (arg), tparm))
14788
        /* OK */;
14789
      else if ((strict & UNIFY_ALLOW_INTEGER)
14790
               && (TREE_CODE (tparm) == INTEGER_TYPE
14791
                   || TREE_CODE (tparm) == BOOLEAN_TYPE))
14792
        /* Convert the ARG to the type of PARM; the deduced non-type
14793
           template argument must exactly match the types of the
14794
           corresponding parameter.  */
14795
        arg = fold (build_nop (tparm, arg));
14796
      else if (uses_template_parms (tparm))
14797
        /* We haven't deduced the type of this parameter yet.  Try again
14798
           later.  */
14799
        return 0;
14800
      else
14801
        return 1;
14802
 
14803
      /* If ARG is a parameter pack or an expansion, we cannot unify
14804
         against it unless PARM is also a parameter pack.  */
14805
      if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14806
          && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14807
        return 1;
14808
 
14809
      TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14810
      return 0;
14811
 
14812
    case PTRMEM_CST:
14813
     {
14814
        /* A pointer-to-member constant can be unified only with
14815
         another constant.  */
14816
      if (TREE_CODE (arg) != PTRMEM_CST)
14817
        return 1;
14818
 
14819
      /* Just unify the class member. It would be useless (and possibly
14820
         wrong, depending on the strict flags) to unify also
14821
         PTRMEM_CST_CLASS, because we want to be sure that both parm and
14822
         arg refer to the same variable, even if through different
14823
         classes. For instance:
14824
 
14825
         struct A { int x; };
14826
         struct B : A { };
14827
 
14828
         Unification of &A::x and &B::x must succeed.  */
14829
      return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14830
                    PTRMEM_CST_MEMBER (arg), strict);
14831
     }
14832
 
14833
    case POINTER_TYPE:
14834
      {
14835
        if (TREE_CODE (arg) != POINTER_TYPE)
14836
          return 1;
14837
 
14838
        /* [temp.deduct.call]
14839
 
14840
           A can be another pointer or pointer to member type that can
14841
           be converted to the deduced A via a qualification
14842
           conversion (_conv.qual_).
14843
 
14844
           We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14845
           This will allow for additional cv-qualification of the
14846
           pointed-to types if appropriate.  */
14847
 
14848
        if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14849
          /* The derived-to-base conversion only persists through one
14850
             level of pointers.  */
14851
          strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14852
 
14853
        return unify (tparms, targs, TREE_TYPE (parm),
14854
                      TREE_TYPE (arg), strict);
14855
      }
14856
 
14857
    case REFERENCE_TYPE:
14858
      if (TREE_CODE (arg) != REFERENCE_TYPE)
14859
        return 1;
14860
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14861
                    strict & UNIFY_ALLOW_MORE_CV_QUAL);
14862
 
14863
    case ARRAY_TYPE:
14864
      if (TREE_CODE (arg) != ARRAY_TYPE)
14865
        return 1;
14866
      if ((TYPE_DOMAIN (parm) == NULL_TREE)
14867
          != (TYPE_DOMAIN (arg) == NULL_TREE))
14868
        return 1;
14869
      if (TYPE_DOMAIN (parm) != NULL_TREE)
14870
        {
14871
          tree parm_max;
14872
          tree arg_max;
14873
          bool parm_cst;
14874
          bool arg_cst;
14875
 
14876
          /* Our representation of array types uses "N - 1" as the
14877
             TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14878
             not an integer constant.  We cannot unify arbitrarily
14879
             complex expressions, so we eliminate the MINUS_EXPRs
14880
             here.  */
14881
          parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14882
          parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14883
          if (!parm_cst)
14884
            {
14885
              gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14886
              parm_max = TREE_OPERAND (parm_max, 0);
14887
            }
14888
          arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14889
          arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14890
          if (!arg_cst)
14891
            {
14892
              /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14893
                 trying to unify the type of a variable with the type
14894
                 of a template parameter.  For example:
14895
 
14896
                   template <unsigned int N>
14897
                   void f (char (&) [N]);
14898
                   int g();
14899
                   void h(int i) {
14900
                     char a[g(i)];
14901
                     f(a);
14902
                   }
14903
 
14904
                Here, the type of the ARG will be "int [g(i)]", and
14905
                may be a SAVE_EXPR, etc.  */
14906
              if (TREE_CODE (arg_max) != MINUS_EXPR)
14907
                return 1;
14908
              arg_max = TREE_OPERAND (arg_max, 0);
14909
            }
14910
 
14911
          /* If only one of the bounds used a MINUS_EXPR, compensate
14912
             by adding one to the other bound.  */
14913
          if (parm_cst && !arg_cst)
14914
            parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14915
                                    integer_type_node,
14916
                                    parm_max,
14917
                                    integer_one_node);
14918
          else if (arg_cst && !parm_cst)
14919
            arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14920
                                   integer_type_node,
14921
                                   arg_max,
14922
                                   integer_one_node);
14923
 
14924
          if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14925
            return 1;
14926
        }
14927
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14928
                    strict & UNIFY_ALLOW_MORE_CV_QUAL);
14929
 
14930
    case REAL_TYPE:
14931
    case COMPLEX_TYPE:
14932
    case VECTOR_TYPE:
14933
    case INTEGER_TYPE:
14934
    case BOOLEAN_TYPE:
14935
    case ENUMERAL_TYPE:
14936
    case VOID_TYPE:
14937
      if (TREE_CODE (arg) != TREE_CODE (parm))
14938
        return 1;
14939
 
14940
      /* We have already checked cv-qualification at the top of the
14941
         function.  */
14942
      if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14943
        return 1;
14944
 
14945
      /* As far as unification is concerned, this wins.  Later checks
14946
         will invalidate it if necessary.  */
14947
      return 0;
14948
 
14949
      /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14950
      /* Type INTEGER_CST can come from ordinary constant template args.  */
14951
    case INTEGER_CST:
14952
      while (TREE_CODE (arg) == NOP_EXPR)
14953
        arg = TREE_OPERAND (arg, 0);
14954
 
14955
      if (TREE_CODE (arg) != INTEGER_CST)
14956
        return 1;
14957
      return !tree_int_cst_equal (parm, arg);
14958
 
14959
    case TREE_VEC:
14960
      {
14961
        int i;
14962
        if (TREE_CODE (arg) != TREE_VEC)
14963
          return 1;
14964
        if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14965
          return 1;
14966
        for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14967
          if (unify (tparms, targs,
14968
                     TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14969
                     UNIFY_ALLOW_NONE))
14970
            return 1;
14971
        return 0;
14972
      }
14973
 
14974
    case RECORD_TYPE:
14975
    case UNION_TYPE:
14976
      if (TREE_CODE (arg) != TREE_CODE (parm))
14977
        return 1;
14978
 
14979
      if (TYPE_PTRMEMFUNC_P (parm))
14980
        {
14981
          if (!TYPE_PTRMEMFUNC_P (arg))
14982
            return 1;
14983
 
14984
          return unify (tparms, targs,
14985
                        TYPE_PTRMEMFUNC_FN_TYPE (parm),
14986
                        TYPE_PTRMEMFUNC_FN_TYPE (arg),
14987
                        strict);
14988
        }
14989
 
14990
      if (CLASSTYPE_TEMPLATE_INFO (parm))
14991
        {
14992
          tree t = NULL_TREE;
14993
 
14994
          if (strict_in & UNIFY_ALLOW_DERIVED)
14995
            {
14996
              /* First, we try to unify the PARM and ARG directly.  */
14997
              t = try_class_unification (tparms, targs,
14998
                                         parm, arg);
14999
 
15000
              if (!t)
15001
                {
15002
                  /* Fallback to the special case allowed in
15003
                     [temp.deduct.call]:
15004
 
15005
                       If P is a class, and P has the form
15006
                       template-id, then A can be a derived class of
15007
                       the deduced A.  Likewise, if P is a pointer to
15008
                       a class of the form template-id, A can be a
15009
                       pointer to a derived class pointed to by the
15010
                       deduced A.  */
15011
                  t = get_template_base (tparms, targs, parm, arg);
15012
 
15013
                  if (!t)
15014
                    return 1;
15015
                }
15016
            }
15017
          else if (CLASSTYPE_TEMPLATE_INFO (arg)
15018
                   && (CLASSTYPE_TI_TEMPLATE (parm)
15019
                       == CLASSTYPE_TI_TEMPLATE (arg)))
15020
            /* Perhaps PARM is something like S<U> and ARG is S<int>.
15021
               Then, we should unify `int' and `U'.  */
15022
            t = arg;
15023
          else
15024
            /* There's no chance of unification succeeding.  */
15025
            return 1;
15026
 
15027
          return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15028
                        CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15029
        }
15030
      else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15031
        return 1;
15032
      return 0;
15033
 
15034
    case METHOD_TYPE:
15035
    case FUNCTION_TYPE:
15036
      {
15037
        unsigned int nargs;
15038
        tree *args;
15039
        tree a;
15040
        unsigned int i;
15041
 
15042
        if (TREE_CODE (arg) != TREE_CODE (parm))
15043
          return 1;
15044
 
15045
        /* CV qualifications for methods can never be deduced, they must
15046
           match exactly.  We need to check them explicitly here,
15047
           because type_unification_real treats them as any other
15048
           cv-qualified parameter.  */
15049
        if (TREE_CODE (parm) == METHOD_TYPE
15050
            && (!check_cv_quals_for_unify
15051
                (UNIFY_ALLOW_NONE,
15052
                 TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15053
                 TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15054
          return 1;
15055
 
15056
        if (unify (tparms, targs, TREE_TYPE (parm),
15057
                   TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15058
          return 1;
15059
 
15060
        nargs = list_length (TYPE_ARG_TYPES (arg));
15061
        args = XALLOCAVEC (tree, nargs);
15062
        for (a = TYPE_ARG_TYPES (arg), i = 0;
15063
             a != NULL_TREE && a != void_list_node;
15064
             a = TREE_CHAIN (a), ++i)
15065
          args[i] = TREE_VALUE (a);
15066
        nargs = i;
15067
 
15068
        return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15069
                                      args, nargs, 1, DEDUCE_EXACT,
15070
                                      LOOKUP_NORMAL);
15071
      }
15072
 
15073
    case OFFSET_TYPE:
15074
      /* Unify a pointer to member with a pointer to member function, which
15075
         deduces the type of the member as a function type. */
15076
      if (TYPE_PTRMEMFUNC_P (arg))
15077
        {
15078
          tree method_type;
15079
          tree fntype;
15080
          cp_cv_quals cv_quals;
15081
 
15082
          /* Check top-level cv qualifiers */
15083
          if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15084
            return 1;
15085
 
15086
          if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15087
                     TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15088
            return 1;
15089
 
15090
          /* Determine the type of the function we are unifying against. */
15091
          method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15092
          fntype =
15093
            build_function_type (TREE_TYPE (method_type),
15094
                                 TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15095
 
15096
          /* Extract the cv-qualifiers of the member function from the
15097
             implicit object parameter and place them on the function
15098
             type to be restored later. */
15099
          cv_quals =
15100
            cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15101
          fntype = build_qualified_type (fntype, cv_quals);
15102
          return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15103
        }
15104
 
15105
      if (TREE_CODE (arg) != OFFSET_TYPE)
15106
        return 1;
15107
      if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15108
                 TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15109
        return 1;
15110
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15111
                    strict);
15112
 
15113
    case CONST_DECL:
15114
      if (DECL_TEMPLATE_PARM_P (parm))
15115
        return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15116
      if (arg != integral_constant_value (parm))
15117
        return 1;
15118
      return 0;
15119
 
15120
    case FIELD_DECL:
15121
    case TEMPLATE_DECL:
15122
      /* Matched cases are handled by the ARG == PARM test above.  */
15123
      return 1;
15124
 
15125
    case VAR_DECL:
15126
      /* A non-type template parameter that is a variable should be a
15127
         an integral constant, in which case, it whould have been
15128
         folded into its (constant) value. So we should not be getting
15129
         a variable here.  */
15130
      gcc_unreachable ();
15131
 
15132
    case TYPE_ARGUMENT_PACK:
15133
    case NONTYPE_ARGUMENT_PACK:
15134
      {
15135
        tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15136
        tree packed_args = ARGUMENT_PACK_ARGS (arg);
15137
        int i, len = TREE_VEC_LENGTH (packed_parms);
15138
        int argslen = TREE_VEC_LENGTH (packed_args);
15139
        int parm_variadic_p = 0;
15140
 
15141
        for (i = 0; i < len; ++i)
15142
          {
15143
            if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15144
              {
15145
                if (i == len - 1)
15146
                  /* We can unify against something with a trailing
15147
                     parameter pack.  */
15148
                  parm_variadic_p = 1;
15149
                else
15150
                  /* Since there is something following the pack
15151
                     expansion, we cannot unify this template argument
15152
                     list.  */
15153
                  return 0;
15154
              }
15155
          }
15156
 
15157
 
15158
        /* If we don't have enough arguments to satisfy the parameters
15159
           (not counting the pack expression at the end), or we have
15160
           too many arguments for a parameter list that doesn't end in
15161
           a pack expression, we can't unify.  */
15162
        if (argslen < (len - parm_variadic_p)
15163
            || (argslen > len && !parm_variadic_p))
15164
          return 1;
15165
 
15166
        /* Unify all of the parameters that precede the (optional)
15167
           pack expression.  */
15168
        for (i = 0; i < len - parm_variadic_p; ++i)
15169
          {
15170
            if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15171
                       TREE_VEC_ELT (packed_args, i), strict))
15172
              return 1;
15173
          }
15174
 
15175
        if (parm_variadic_p)
15176
          return unify_pack_expansion (tparms, targs,
15177
                                       packed_parms, packed_args,
15178
                                       strict, /*call_args_p=*/false,
15179
                                       /*subr=*/false);
15180
        return 0;
15181
      }
15182
 
15183
      break;
15184
 
15185
    case TYPEOF_TYPE:
15186
    case DECLTYPE_TYPE:
15187
      /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15188
         nodes.  */
15189
      return 0;
15190
 
15191
    case ERROR_MARK:
15192
      /* Unification fails if we hit an error node.  */
15193
      return 1;
15194
 
15195
    default:
15196
      gcc_assert (EXPR_P (parm));
15197
 
15198
      /* We must be looking at an expression.  This can happen with
15199
         something like:
15200
 
15201
           template <int I>
15202
           void foo(S<I>, S<I + 2>);
15203
 
15204
         This is a "nondeduced context":
15205
 
15206
           [deduct.type]
15207
 
15208
           The nondeduced contexts are:
15209
 
15210
           --A type that is a template-id in which one or more of
15211
             the template-arguments is an expression that references
15212
             a template-parameter.
15213
 
15214
         In these cases, we assume deduction succeeded, but don't
15215
         actually infer any unifications.  */
15216
 
15217
      if (!uses_template_parms (parm)
15218
          && !template_args_equal (parm, arg))
15219
        return 1;
15220
      else
15221
        return 0;
15222
    }
15223
}
15224
 
15225
/* Note that DECL can be defined in this translation unit, if
15226
   required.  */
15227
 
15228
static void
15229
mark_definable (tree decl)
15230
{
15231
  tree clone;
15232
  DECL_NOT_REALLY_EXTERN (decl) = 1;
15233
  FOR_EACH_CLONE (clone, decl)
15234
    DECL_NOT_REALLY_EXTERN (clone) = 1;
15235
}
15236
 
15237
/* Called if RESULT is explicitly instantiated, or is a member of an
15238
   explicitly instantiated class.  */
15239
 
15240
void
15241
mark_decl_instantiated (tree result, int extern_p)
15242
{
15243
  SET_DECL_EXPLICIT_INSTANTIATION (result);
15244
 
15245
  /* If this entity has already been written out, it's too late to
15246
     make any modifications.  */
15247
  if (TREE_ASM_WRITTEN (result))
15248
    return;
15249
 
15250
  if (TREE_CODE (result) != FUNCTION_DECL)
15251
    /* The TREE_PUBLIC flag for function declarations will have been
15252
       set correctly by tsubst.  */
15253
    TREE_PUBLIC (result) = 1;
15254
 
15255
  /* This might have been set by an earlier implicit instantiation.  */
15256
  DECL_COMDAT (result) = 0;
15257
 
15258
  if (extern_p)
15259
    DECL_NOT_REALLY_EXTERN (result) = 0;
15260
  else
15261
    {
15262
      mark_definable (result);
15263
      /* Always make artificials weak.  */
15264
      if (DECL_ARTIFICIAL (result) && flag_weak)
15265
        comdat_linkage (result);
15266
      /* For WIN32 we also want to put explicit instantiations in
15267
         linkonce sections.  */
15268
      else if (TREE_PUBLIC (result))
15269
        maybe_make_one_only (result);
15270
    }
15271
 
15272
  /* If EXTERN_P, then this function will not be emitted -- unless
15273
     followed by an explicit instantiation, at which point its linkage
15274
     will be adjusted.  If !EXTERN_P, then this function will be
15275
     emitted here.  In neither circumstance do we want
15276
     import_export_decl to adjust the linkage.  */
15277
  DECL_INTERFACE_KNOWN (result) = 1;
15278
}
15279
 
15280
/* Subroutine of more_specialized_fn: check whether TARGS is missing any
15281
   important template arguments.  If any are missing, we check whether
15282
   they're important by using error_mark_node for substituting into any
15283
   args that were used for partial ordering (the ones between ARGS and END)
15284
   and seeing if it bubbles up.  */
15285
 
15286
static bool
15287
check_undeduced_parms (tree targs, tree args, tree end)
15288
{
15289
  bool found = false;
15290
  int i;
15291
  for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15292
    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15293
      {
15294
        found = true;
15295
        TREE_VEC_ELT (targs, i) = error_mark_node;
15296
      }
15297
  if (found)
15298
    {
15299
      for (; args != end; args = TREE_CHAIN (args))
15300
        {
15301
          tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15302
          if (substed == error_mark_node)
15303
            return true;
15304
        }
15305
    }
15306
  return false;
15307
}
15308
 
15309
/* Given two function templates PAT1 and PAT2, return:
15310
 
15311
   1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15312
   -1 if PAT2 is more specialized than PAT1.
15313
 
15314
 
15315
   LEN indicates the number of parameters we should consider
15316
   (defaulted parameters should not be considered).
15317
 
15318
   The 1998 std underspecified function template partial ordering, and
15319
   DR214 addresses the issue.  We take pairs of arguments, one from
15320
   each of the templates, and deduce them against each other.  One of
15321
   the templates will be more specialized if all the *other*
15322
   template's arguments deduce against its arguments and at least one
15323
   of its arguments *does* *not* deduce against the other template's
15324
   corresponding argument.  Deduction is done as for class templates.
15325
   The arguments used in deduction have reference and top level cv
15326
   qualifiers removed.  Iff both arguments were originally reference
15327
   types *and* deduction succeeds in both directions, the template
15328
   with the more cv-qualified argument wins for that pairing (if
15329
   neither is more cv-qualified, they both are equal).  Unlike regular
15330
   deduction, after all the arguments have been deduced in this way,
15331
   we do *not* verify the deduced template argument values can be
15332
   substituted into non-deduced contexts.
15333
 
15334
   The logic can be a bit confusing here, because we look at deduce1 and
15335
   targs1 to see if pat2 is at least as specialized, and vice versa; if we
15336
   can find template arguments for pat1 to make arg1 look like arg2, that
15337
   means that arg2 is at least as specialized as arg1.  */
15338
 
15339
int
15340
more_specialized_fn (tree pat1, tree pat2, int len)
15341
{
15342
  tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15343
  tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15344
  tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15345
  tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15346
  tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15347
  tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15348
  tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15349
  tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15350
  tree origs1, origs2;
15351
  bool lose1 = false;
15352
  bool lose2 = false;
15353
 
15354
  /* Remove the this parameter from non-static member functions.  If
15355
     one is a non-static member function and the other is not a static
15356
     member function, remove the first parameter from that function
15357
     also.  This situation occurs for operator functions where we
15358
     locate both a member function (with this pointer) and non-member
15359
     operator (with explicit first operand).  */
15360
  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15361
    {
15362
      len--; /* LEN is the number of significant arguments for DECL1 */
15363
      args1 = TREE_CHAIN (args1);
15364
      if (!DECL_STATIC_FUNCTION_P (decl2))
15365
        args2 = TREE_CHAIN (args2);
15366
    }
15367
  else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15368
    {
15369
      args2 = TREE_CHAIN (args2);
15370
      if (!DECL_STATIC_FUNCTION_P (decl1))
15371
        {
15372
          len--;
15373
          args1 = TREE_CHAIN (args1);
15374
        }
15375
    }
15376
 
15377
  /* If only one is a conversion operator, they are unordered.  */
15378
  if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15379
    return 0;
15380
 
15381
  /* Consider the return type for a conversion function */
15382
  if (DECL_CONV_FN_P (decl1))
15383
    {
15384
      args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15385
      args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15386
      len++;
15387
    }
15388
 
15389
  processing_template_decl++;
15390
 
15391
  origs1 = args1;
15392
  origs2 = args2;
15393
 
15394
  while (len--
15395
         /* Stop when an ellipsis is seen.  */
15396
         && args1 != NULL_TREE && args2 != NULL_TREE)
15397
    {
15398
      tree arg1 = TREE_VALUE (args1);
15399
      tree arg2 = TREE_VALUE (args2);
15400
      int deduce1, deduce2;
15401
      int quals1 = -1;
15402
      int quals2 = -1;
15403
 
15404
      if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15405
          && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15406
        {
15407
          /* When both arguments are pack expansions, we need only
15408
             unify the patterns themselves.  */
15409
          arg1 = PACK_EXPANSION_PATTERN (arg1);
15410
          arg2 = PACK_EXPANSION_PATTERN (arg2);
15411
 
15412
          /* This is the last comparison we need to do.  */
15413
          len = 0;
15414
        }
15415
 
15416
      if (TREE_CODE (arg1) == REFERENCE_TYPE)
15417
        {
15418
          arg1 = TREE_TYPE (arg1);
15419
          quals1 = cp_type_quals (arg1);
15420
        }
15421
 
15422
      if (TREE_CODE (arg2) == REFERENCE_TYPE)
15423
        {
15424
          arg2 = TREE_TYPE (arg2);
15425
          quals2 = cp_type_quals (arg2);
15426
        }
15427
 
15428
      if ((quals1 < 0) != (quals2 < 0))
15429
        {
15430
          /* Only of the args is a reference, see if we should apply
15431
             array/function pointer decay to it.  This is not part of
15432
             DR214, but is, IMHO, consistent with the deduction rules
15433
             for the function call itself, and with our earlier
15434
             implementation of the underspecified partial ordering
15435
             rules.  (nathan).  */
15436
          if (quals1 >= 0)
15437
            {
15438
              switch (TREE_CODE (arg1))
15439
                {
15440
                case ARRAY_TYPE:
15441
                  arg1 = TREE_TYPE (arg1);
15442
                  /* FALLTHROUGH. */
15443
                case FUNCTION_TYPE:
15444
                  arg1 = build_pointer_type (arg1);
15445
                  break;
15446
 
15447
                default:
15448
                  break;
15449
                }
15450
            }
15451
          else
15452
            {
15453
              switch (TREE_CODE (arg2))
15454
                {
15455
                case ARRAY_TYPE:
15456
                  arg2 = TREE_TYPE (arg2);
15457
                  /* FALLTHROUGH. */
15458
                case FUNCTION_TYPE:
15459
                  arg2 = build_pointer_type (arg2);
15460
                  break;
15461
 
15462
                default:
15463
                  break;
15464
                }
15465
            }
15466
        }
15467
 
15468
      arg1 = TYPE_MAIN_VARIANT (arg1);
15469
      arg2 = TYPE_MAIN_VARIANT (arg2);
15470
 
15471
      if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15472
        {
15473
          int i, len2 = list_length (args2);
15474
          tree parmvec = make_tree_vec (1);
15475
          tree argvec = make_tree_vec (len2);
15476
          tree ta = args2;
15477
 
15478
          /* Setup the parameter vector, which contains only ARG1.  */
15479
          TREE_VEC_ELT (parmvec, 0) = arg1;
15480
 
15481
          /* Setup the argument vector, which contains the remaining
15482
             arguments.  */
15483
          for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15484
            TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15485
 
15486
          deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec,
15487
                                           argvec, UNIFY_ALLOW_NONE,
15488
                                           /*call_args_p=*/false,
15489
                                           /*subr=*/0);
15490
 
15491
          /* We cannot deduce in the other direction, because ARG1 is
15492
             a pack expansion but ARG2 is not.  */
15493
          deduce2 = 0;
15494
        }
15495
      else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15496
        {
15497
          int i, len1 = list_length (args1);
15498
          tree parmvec = make_tree_vec (1);
15499
          tree argvec = make_tree_vec (len1);
15500
          tree ta = args1;
15501
 
15502
          /* Setup the parameter vector, which contains only ARG1.  */
15503
          TREE_VEC_ELT (parmvec, 0) = arg2;
15504
 
15505
          /* Setup the argument vector, which contains the remaining
15506
             arguments.  */
15507
          for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15508
            TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15509
 
15510
          deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec,
15511
                                           argvec, UNIFY_ALLOW_NONE,
15512
                                           /*call_args_p=*/false,
15513
                                           /*subr=*/0);
15514
 
15515
          /* We cannot deduce in the other direction, because ARG2 is
15516
             a pack expansion but ARG1 is not.*/
15517
          deduce1 = 0;
15518
        }
15519
 
15520
      else
15521
        {
15522
          /* The normal case, where neither argument is a pack
15523
             expansion.  */
15524
          deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15525
          deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15526
        }
15527
 
15528
      /* If we couldn't deduce arguments for tparms1 to make arg1 match
15529
         arg2, then arg2 is not as specialized as arg1.  */
15530
      if (!deduce1)
15531
        lose2 = true;
15532
      if (!deduce2)
15533
        lose1 = true;
15534
 
15535
      /* "If, for a given type, deduction succeeds in both directions
15536
         (i.e., the types are identical after the transformations above)
15537
         and if the type from the argument template is more cv-qualified
15538
         than the type from the parameter template (as described above)
15539
         that type is considered to be more specialized than the other. If
15540
         neither type is more cv-qualified than the other then neither type
15541
         is more specialized than the other."  */
15542
 
15543
      if (deduce1 && deduce2
15544
          && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15545
        {
15546
          if ((quals1 & quals2) == quals2)
15547
            lose2 = true;
15548
          if ((quals1 & quals2) == quals1)
15549
            lose1 = true;
15550
        }
15551
 
15552
      if (lose1 && lose2)
15553
        /* We've failed to deduce something in either direction.
15554
           These must be unordered.  */
15555
        break;
15556
 
15557
      if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15558
          || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15559
        /* We have already processed all of the arguments in our
15560
           handing of the pack expansion type.  */
15561
        len = 0;
15562
 
15563
      args1 = TREE_CHAIN (args1);
15564
      args2 = TREE_CHAIN (args2);
15565
    }
15566
 
15567
  /* "In most cases, all template parameters must have values in order for
15568
     deduction to succeed, but for partial ordering purposes a template
15569
     parameter may remain without a value provided it is not used in the
15570
     types being used for partial ordering."
15571
 
15572
     Thus, if we are missing any of the targs1 we need to substitute into
15573
     origs1, then pat2 is not as specialized as pat1.  This can happen when
15574
     there is a nondeduced context.  */
15575
  if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15576
    lose2 = true;
15577
  if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15578
    lose1 = true;
15579
 
15580
  processing_template_decl--;
15581
 
15582
  /* All things being equal, if the next argument is a pack expansion
15583
     for one function but not for the other, prefer the
15584
     non-variadic function.  FIXME this is bogus; see c++/41958.  */
15585
  if (lose1 == lose2
15586
      && args1 && TREE_VALUE (args1)
15587
      && args2 && TREE_VALUE (args2))
15588
    {
15589
      lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15590
      lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15591
    }
15592
 
15593
  if (lose1 == lose2)
15594
    return 0;
15595
  else if (!lose1)
15596
    return 1;
15597
  else
15598
    return -1;
15599
}
15600
 
15601
/* Determine which of two partial specializations is more specialized.
15602
 
15603
   PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15604
   to the first partial specialization.  The TREE_VALUE is the
15605
   innermost set of template parameters for the partial
15606
   specialization.  PAT2 is similar, but for the second template.
15607
 
15608
   Return 1 if the first partial specialization is more specialized;
15609
   -1 if the second is more specialized; 0 if neither is more
15610
   specialized.
15611
 
15612
   See [temp.class.order] for information about determining which of
15613
   two templates is more specialized.  */
15614
 
15615
static int
15616
more_specialized_class (tree pat1, tree pat2)
15617
{
15618
  tree targs;
15619
  tree tmpl1, tmpl2;
15620
  int winner = 0;
15621
  bool any_deductions = false;
15622
 
15623
  tmpl1 = TREE_TYPE (pat1);
15624
  tmpl2 = TREE_TYPE (pat2);
15625
 
15626
  /* Just like what happens for functions, if we are ordering between
15627
     different class template specializations, we may encounter dependent
15628
     types in the arguments, and we need our dependency check functions
15629
     to behave correctly.  */
15630
  ++processing_template_decl;
15631
  targs = get_class_bindings (TREE_VALUE (pat1),
15632
                              CLASSTYPE_TI_ARGS (tmpl1),
15633
                              CLASSTYPE_TI_ARGS (tmpl2));
15634
  if (targs)
15635
    {
15636
      --winner;
15637
      any_deductions = true;
15638
    }
15639
 
15640
  targs = get_class_bindings (TREE_VALUE (pat2),
15641
                              CLASSTYPE_TI_ARGS (tmpl2),
15642
                              CLASSTYPE_TI_ARGS (tmpl1));
15643
  if (targs)
15644
    {
15645
      ++winner;
15646
      any_deductions = true;
15647
    }
15648
  --processing_template_decl;
15649
 
15650
  /* In the case of a tie where at least one of the class templates
15651
     has a parameter pack at the end, the template with the most
15652
     non-packed parameters wins.  */
15653
  if (winner == 0
15654
      && any_deductions
15655
      && (template_args_variadic_p (TREE_PURPOSE (pat1))
15656
          || template_args_variadic_p (TREE_PURPOSE (pat2))))
15657
    {
15658
      tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15659
      tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15660
      int len1 = TREE_VEC_LENGTH (args1);
15661
      int len2 = TREE_VEC_LENGTH (args2);
15662
 
15663
      /* We don't count the pack expansion at the end.  */
15664
      if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15665
        --len1;
15666
      if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15667
        --len2;
15668
 
15669
      if (len1 > len2)
15670
        return 1;
15671
      else if (len1 < len2)
15672
        return -1;
15673
    }
15674
 
15675
  return winner;
15676
}
15677
 
15678
/* Return the template arguments that will produce the function signature
15679
   DECL from the function template FN, with the explicit template
15680
   arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15681
   also match.  Return NULL_TREE if no satisfactory arguments could be
15682
   found.  */
15683
 
15684
static tree
15685
get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15686
{
15687
  int ntparms = DECL_NTPARMS (fn);
15688
  tree targs = make_tree_vec (ntparms);
15689
  tree decl_type;
15690
  tree decl_arg_types;
15691
  tree *args;
15692
  unsigned int nargs, ix;
15693
  tree arg;
15694
 
15695
  /* Substitute the explicit template arguments into the type of DECL.
15696
     The call to fn_type_unification will handle substitution into the
15697
     FN.  */
15698
  decl_type = TREE_TYPE (decl);
15699
  if (explicit_args && uses_template_parms (decl_type))
15700
    {
15701
      tree tmpl;
15702
      tree converted_args;
15703
 
15704
      if (DECL_TEMPLATE_INFO (decl))
15705
        tmpl = DECL_TI_TEMPLATE (decl);
15706
      else
15707
        /* We can get here for some invalid specializations.  */
15708
        return NULL_TREE;
15709
 
15710
      converted_args
15711
        = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15712
                                 explicit_args, NULL_TREE,
15713
                                 tf_none,
15714
                                 /*require_all_args=*/false,
15715
                                 /*use_default_args=*/false);
15716
      if (converted_args == error_mark_node)
15717
        return NULL_TREE;
15718
 
15719
      decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15720
      if (decl_type == error_mark_node)
15721
        return NULL_TREE;
15722
    }
15723
 
15724
  /* Never do unification on the 'this' parameter.  */
15725
  decl_arg_types = skip_artificial_parms_for (decl,
15726
                                              TYPE_ARG_TYPES (decl_type));
15727
 
15728
  nargs = list_length (decl_arg_types);
15729
  args = XALLOCAVEC (tree, nargs);
15730
  for (arg = decl_arg_types, ix = 0;
15731
       arg != NULL_TREE && arg != void_list_node;
15732
       arg = TREE_CHAIN (arg), ++ix)
15733
    args[ix] = TREE_VALUE (arg);
15734
 
15735
  if (fn_type_unification (fn, explicit_args, targs,
15736
                           args, ix,
15737
                           (check_rettype || DECL_CONV_FN_P (fn)
15738
                            ? TREE_TYPE (decl_type) : NULL_TREE),
15739
                           DEDUCE_EXACT, LOOKUP_NORMAL))
15740
    return NULL_TREE;
15741
 
15742
  return targs;
15743
}
15744
 
15745
/* Return the innermost template arguments that, when applied to a
15746
   template specialization whose innermost template parameters are
15747
   TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15748
   ARGS.
15749
 
15750
   For example, suppose we have:
15751
 
15752
     template <class T, class U> struct S {};
15753
     template <class T> struct S<T*, int> {};
15754
 
15755
   Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15756
   {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15757
   int}.  The resulting vector will be {double}, indicating that `T'
15758
   is bound to `double'.  */
15759
 
15760
static tree
15761
get_class_bindings (tree tparms, tree spec_args, tree args)
15762
{
15763
  int i, ntparms = TREE_VEC_LENGTH (tparms);
15764
  tree deduced_args;
15765
  tree innermost_deduced_args;
15766
 
15767
  innermost_deduced_args = make_tree_vec (ntparms);
15768
  if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15769
    {
15770
      deduced_args = copy_node (args);
15771
      SET_TMPL_ARGS_LEVEL (deduced_args,
15772
                           TMPL_ARGS_DEPTH (deduced_args),
15773
                           innermost_deduced_args);
15774
    }
15775
  else
15776
    deduced_args = innermost_deduced_args;
15777
 
15778
  if (unify (tparms, deduced_args,
15779
             INNERMOST_TEMPLATE_ARGS (spec_args),
15780
             INNERMOST_TEMPLATE_ARGS (args),
15781
             UNIFY_ALLOW_NONE))
15782
    return NULL_TREE;
15783
 
15784
  for (i =  0; i < ntparms; ++i)
15785
    if (! TREE_VEC_ELT (innermost_deduced_args, i))
15786
      return NULL_TREE;
15787
 
15788
  /* Verify that nondeduced template arguments agree with the type
15789
     obtained from argument deduction.
15790
 
15791
     For example:
15792
 
15793
       struct A { typedef int X; };
15794
       template <class T, class U> struct C {};
15795
       template <class T> struct C<T, typename T::X> {};
15796
 
15797
     Then with the instantiation `C<A, int>', we can deduce that
15798
     `T' is `A' but unify () does not check whether `typename T::X'
15799
     is `int'.  */
15800
  spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15801
  if (spec_args == error_mark_node
15802
      /* We only need to check the innermost arguments; the other
15803
         arguments will always agree.  */
15804
      || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15805
                              INNERMOST_TEMPLATE_ARGS (args)))
15806
    return NULL_TREE;
15807
 
15808
  /* Now that we have bindings for all of the template arguments,
15809
     ensure that the arguments deduced for the template template
15810
     parameters have compatible template parameter lists.  See the use
15811
     of template_template_parm_bindings_ok_p in fn_type_unification
15812
     for more information.  */
15813
  if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15814
    return NULL_TREE;
15815
 
15816
  return deduced_args;
15817
}
15818
 
15819
/* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15820
   Return the TREE_LIST node with the most specialized template, if
15821
   any.  If there is no most specialized template, the error_mark_node
15822
   is returned.
15823
 
15824
   Note that this function does not look at, or modify, the
15825
   TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15826
   returned is one of the elements of INSTANTIATIONS, callers may
15827
   store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15828
   and retrieve it from the value returned.  */
15829
 
15830
tree
15831
most_specialized_instantiation (tree templates)
15832
{
15833
  tree fn, champ;
15834
 
15835
  ++processing_template_decl;
15836
 
15837
  champ = templates;
15838
  for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15839
    {
15840
      int fate = 0;
15841
 
15842
      if (get_bindings (TREE_VALUE (champ),
15843
                        DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15844
                        NULL_TREE, /*check_ret=*/false))
15845
        fate--;
15846
 
15847
      if (get_bindings (TREE_VALUE (fn),
15848
                        DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15849
                        NULL_TREE, /*check_ret=*/false))
15850
        fate++;
15851
 
15852
      if (fate == -1)
15853
        champ = fn;
15854
      else if (!fate)
15855
        {
15856
          /* Equally specialized, move to next function.  If there
15857
             is no next function, nothing's most specialized.  */
15858
          fn = TREE_CHAIN (fn);
15859
          champ = fn;
15860
          if (!fn)
15861
            break;
15862
        }
15863
    }
15864
 
15865
  if (champ)
15866
    /* Now verify that champ is better than everything earlier in the
15867
       instantiation list.  */
15868
    for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15869
      if (get_bindings (TREE_VALUE (champ),
15870
                        DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15871
                        NULL_TREE, /*check_ret=*/false)
15872
          || !get_bindings (TREE_VALUE (fn),
15873
                            DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15874
                            NULL_TREE, /*check_ret=*/false))
15875
        {
15876
          champ = NULL_TREE;
15877
          break;
15878
        }
15879
 
15880
  processing_template_decl--;
15881
 
15882
  if (!champ)
15883
    return error_mark_node;
15884
 
15885
  return champ;
15886
}
15887
 
15888
/* If DECL is a specialization of some template, return the most
15889
   general such template.  Otherwise, returns NULL_TREE.
15890
 
15891
   For example, given:
15892
 
15893
     template <class T> struct S { template <class U> void f(U); };
15894
 
15895
   if TMPL is `template <class U> void S<int>::f(U)' this will return
15896
   the full template.  This function will not trace past partial
15897
   specializations, however.  For example, given in addition:
15898
 
15899
     template <class T> struct S<T*> { template <class U> void f(U); };
15900
 
15901
   if TMPL is `template <class U> void S<int*>::f(U)' this will return
15902
   `template <class T> template <class U> S<T*>::f(U)'.  */
15903
 
15904
tree
15905
most_general_template (tree decl)
15906
{
15907
  /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15908
     an immediate specialization.  */
15909
  if (TREE_CODE (decl) == FUNCTION_DECL)
15910
    {
15911
      if (DECL_TEMPLATE_INFO (decl)) {
15912
        decl = DECL_TI_TEMPLATE (decl);
15913
 
15914
        /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15915
           template friend.  */
15916
        if (TREE_CODE (decl) != TEMPLATE_DECL)
15917
          return NULL_TREE;
15918
      } else
15919
        return NULL_TREE;
15920
    }
15921
 
15922
  /* Look for more and more general templates.  */
15923
  while (DECL_TEMPLATE_INFO (decl))
15924
    {
15925
      /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15926
         (See cp-tree.h for details.)  */
15927
      if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15928
        break;
15929
 
15930
      if (CLASS_TYPE_P (TREE_TYPE (decl))
15931
          && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15932
        break;
15933
 
15934
      /* Stop if we run into an explicitly specialized class template.  */
15935
      if (!DECL_NAMESPACE_SCOPE_P (decl)
15936
          && DECL_CONTEXT (decl)
15937
          && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15938
        break;
15939
 
15940
      decl = DECL_TI_TEMPLATE (decl);
15941
    }
15942
 
15943
  return decl;
15944
}
15945
 
15946
/* Return the most specialized of the class template partial
15947
   specializations of TMPL which can produce TYPE, a specialization of
15948
   TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15949
   a _TYPE node corresponding to the partial specialization, while the
15950
   TREE_PURPOSE is the set of template arguments that must be
15951
   substituted into the TREE_TYPE in order to generate TYPE.
15952
 
15953
   If the choice of partial specialization is ambiguous, a diagnostic
15954
   is issued, and the error_mark_node is returned.  If there are no
15955
   partial specializations of TMPL matching TYPE, then NULL_TREE is
15956
   returned.  */
15957
 
15958
static tree
15959
most_specialized_class (tree type, tree tmpl)
15960
{
15961
  tree list = NULL_TREE;
15962
  tree t;
15963
  tree champ;
15964
  int fate;
15965
  bool ambiguous_p;
15966
  tree args;
15967
  tree outer_args = NULL_TREE;
15968
 
15969
  tmpl = most_general_template (tmpl);
15970
  args = CLASSTYPE_TI_ARGS (type);
15971
 
15972
  /* For determining which partial specialization to use, only the
15973
     innermost args are interesting.  */
15974
  if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15975
    {
15976
      outer_args = strip_innermost_template_args (args, 1);
15977
      args = INNERMOST_TEMPLATE_ARGS (args);
15978
    }
15979
 
15980
  for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15981
    {
15982
      tree partial_spec_args;
15983
      tree spec_args;
15984
      tree parms = TREE_VALUE (t);
15985
 
15986
      partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15987
 
15988
      ++processing_template_decl;
15989
 
15990
      if (outer_args)
15991
        {
15992
          int i;
15993
 
15994
          /* Discard the outer levels of args, and then substitute in the
15995
             template args from the enclosing class.  */
15996
          partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15997
          partial_spec_args = tsubst_template_args
15998
            (partial_spec_args, outer_args, tf_none, NULL_TREE);
15999
 
16000
          /* PARMS already refers to just the innermost parms, but the
16001
             template parms in partial_spec_args had their levels lowered
16002
             by tsubst, so we need to do the same for the parm list.  We
16003
             can't just tsubst the TREE_VEC itself, as tsubst wants to
16004
             treat a TREE_VEC as an argument vector.  */
16005
          parms = copy_node (parms);
16006
          for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16007
            TREE_VEC_ELT (parms, i) =
16008
              tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16009
 
16010
        }
16011
 
16012
      partial_spec_args =
16013
          coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16014
                                 add_to_template_args (outer_args,
16015
                                                       partial_spec_args),
16016
                                 tmpl, tf_none,
16017
                                 /*require_all_args=*/true,
16018
                                 /*use_default_args=*/true);
16019
 
16020
      --processing_template_decl;
16021
 
16022
      if (partial_spec_args == error_mark_node)
16023
        return error_mark_node;
16024
 
16025
      spec_args = get_class_bindings (parms,
16026
                                      partial_spec_args,
16027
                                      args);
16028
      if (spec_args)
16029
        {
16030
          if (outer_args)
16031
            spec_args = add_to_template_args (outer_args, spec_args);
16032
          list = tree_cons (spec_args, TREE_VALUE (t), list);
16033
          TREE_TYPE (list) = TREE_TYPE (t);
16034
        }
16035
    }
16036
 
16037
  if (! list)
16038
    return NULL_TREE;
16039
 
16040
  ambiguous_p = false;
16041
  t = list;
16042
  champ = t;
16043
  t = TREE_CHAIN (t);
16044
  for (; t; t = TREE_CHAIN (t))
16045
    {
16046
      fate = more_specialized_class (champ, t);
16047
      if (fate == 1)
16048
        ;
16049
      else
16050
        {
16051
          if (fate == 0)
16052
            {
16053
              t = TREE_CHAIN (t);
16054
              if (! t)
16055
                {
16056
                  ambiguous_p = true;
16057
                  break;
16058
                }
16059
            }
16060
          champ = t;
16061
        }
16062
    }
16063
 
16064
  if (!ambiguous_p)
16065
    for (t = list; t && t != champ; t = TREE_CHAIN (t))
16066
      {
16067
        fate = more_specialized_class (champ, t);
16068
        if (fate != 1)
16069
          {
16070
            ambiguous_p = true;
16071
            break;
16072
          }
16073
      }
16074
 
16075
  if (ambiguous_p)
16076
    {
16077
      const char *str;
16078
      char *spaces = NULL;
16079
      error ("ambiguous class template instantiation for %q#T", type);
16080
      str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16081
      for (t = list; t; t = TREE_CHAIN (t))
16082
        {
16083
          error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16084
          spaces = spaces ? spaces : get_spaces (str);
16085
        }
16086
      free (spaces);
16087
      return error_mark_node;
16088
    }
16089
 
16090
  return champ;
16091
}
16092
 
16093
/* Explicitly instantiate DECL.  */
16094
 
16095
void
16096
do_decl_instantiation (tree decl, tree storage)
16097
{
16098
  tree result = NULL_TREE;
16099
  int extern_p = 0;
16100
 
16101
  if (!decl || decl == error_mark_node)
16102
    /* An error occurred, for which grokdeclarator has already issued
16103
       an appropriate message.  */
16104
    return;
16105
  else if (! DECL_LANG_SPECIFIC (decl))
16106
    {
16107
      error ("explicit instantiation of non-template %q#D", decl);
16108
      return;
16109
    }
16110
  else if (TREE_CODE (decl) == VAR_DECL)
16111
    {
16112
      /* There is an asymmetry here in the way VAR_DECLs and
16113
         FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16114
         the latter, the DECL we get back will be marked as a
16115
         template instantiation, and the appropriate
16116
         DECL_TEMPLATE_INFO will be set up.  This does not happen for
16117
         VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16118
         should handle VAR_DECLs as it currently handles
16119
         FUNCTION_DECLs.  */
16120
      if (!DECL_CLASS_SCOPE_P (decl))
16121
        {
16122
          error ("%qD is not a static data member of a class template", decl);
16123
          return;
16124
        }
16125
      result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16126
      if (!result || TREE_CODE (result) != VAR_DECL)
16127
        {
16128
          error ("no matching template for %qD found", decl);
16129
          return;
16130
        }
16131
      if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16132
        {
16133
          error ("type %qT for explicit instantiation %qD does not match "
16134
                 "declared type %qT", TREE_TYPE (result), decl,
16135
                 TREE_TYPE (decl));
16136
          return;
16137
        }
16138
    }
16139
  else if (TREE_CODE (decl) != FUNCTION_DECL)
16140
    {
16141
      error ("explicit instantiation of %q#D", decl);
16142
      return;
16143
    }
16144
  else
16145
    result = decl;
16146
 
16147
  /* Check for various error cases.  Note that if the explicit
16148
     instantiation is valid the RESULT will currently be marked as an
16149
     *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16150
     until we get here.  */
16151
 
16152
  if (DECL_TEMPLATE_SPECIALIZATION (result))
16153
    {
16154
      /* DR 259 [temp.spec].
16155
 
16156
         Both an explicit instantiation and a declaration of an explicit
16157
         specialization shall not appear in a program unless the explicit
16158
         instantiation follows a declaration of the explicit specialization.
16159
 
16160
         For a given set of template parameters, if an explicit
16161
         instantiation of a template appears after a declaration of an
16162
         explicit specialization for that template, the explicit
16163
         instantiation has no effect.  */
16164
      return;
16165
    }
16166
  else if (DECL_EXPLICIT_INSTANTIATION (result))
16167
    {
16168
      /* [temp.spec]
16169
 
16170
         No program shall explicitly instantiate any template more
16171
         than once.
16172
 
16173
         We check DECL_NOT_REALLY_EXTERN so as not to complain when
16174
         the first instantiation was `extern' and the second is not,
16175
         and EXTERN_P for the opposite case.  */
16176
      if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16177
        permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16178
      /* If an "extern" explicit instantiation follows an ordinary
16179
         explicit instantiation, the template is instantiated.  */
16180
      if (extern_p)
16181
        return;
16182
    }
16183
  else if (!DECL_IMPLICIT_INSTANTIATION (result))
16184
    {
16185
      error ("no matching template for %qD found", result);
16186
      return;
16187
    }
16188
  else if (!DECL_TEMPLATE_INFO (result))
16189
    {
16190
      permerror (input_location, "explicit instantiation of non-template %q#D", result);
16191
      return;
16192
    }
16193
 
16194
  if (storage == NULL_TREE)
16195
    ;
16196
  else if (storage == ridpointers[(int) RID_EXTERN])
16197
    {
16198
      if (!in_system_header && (cxx_dialect == cxx98))
16199
        pedwarn (input_location, OPT_pedantic,
16200
                 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16201
                 "instantiations");
16202
      extern_p = 1;
16203
    }
16204
  else
16205
    error ("storage class %qD applied to template instantiation", storage);
16206
 
16207
  check_explicit_instantiation_namespace (result);
16208
  mark_decl_instantiated (result, extern_p);
16209
  if (! extern_p)
16210
    instantiate_decl (result, /*defer_ok=*/1,
16211
                      /*expl_inst_class_mem_p=*/false);
16212
}
16213
 
16214
static void
16215
mark_class_instantiated (tree t, int extern_p)
16216
{
16217
  SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16218
  SET_CLASSTYPE_INTERFACE_KNOWN (t);
16219
  CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16220
  TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16221
  if (! extern_p)
16222
    {
16223
      CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16224
      rest_of_type_compilation (t, 1);
16225
    }
16226
}
16227
 
16228
/* Called from do_type_instantiation through binding_table_foreach to
16229
   do recursive instantiation for the type bound in ENTRY.  */
16230
static void
16231
bt_instantiate_type_proc (binding_entry entry, void *data)
16232
{
16233
  tree storage = *(tree *) data;
16234
 
16235
  if (MAYBE_CLASS_TYPE_P (entry->type)
16236
      && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16237
    do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16238
}
16239
 
16240
/* Called from do_type_instantiation to instantiate a member
16241
   (a member function or a static member variable) of an
16242
   explicitly instantiated class template.  */
16243
static void
16244
instantiate_class_member (tree decl, int extern_p)
16245
{
16246
  mark_decl_instantiated (decl, extern_p);
16247
  if (! extern_p)
16248
    instantiate_decl (decl, /*defer_ok=*/1,
16249
                      /*expl_inst_class_mem_p=*/true);
16250
}
16251
 
16252
/* Perform an explicit instantiation of template class T.  STORAGE, if
16253
   non-null, is the RID for extern, inline or static.  COMPLAIN is
16254
   nonzero if this is called from the parser, zero if called recursively,
16255
   since the standard is unclear (as detailed below).  */
16256
 
16257
void
16258
do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16259
{
16260
  int extern_p = 0;
16261
  int nomem_p = 0;
16262
  int static_p = 0;
16263
  int previous_instantiation_extern_p = 0;
16264
 
16265
  if (TREE_CODE (t) == TYPE_DECL)
16266
    t = TREE_TYPE (t);
16267
 
16268
  if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16269
    {
16270
      error ("explicit instantiation of non-template type %qT", t);
16271
      return;
16272
    }
16273
 
16274
  complete_type (t);
16275
 
16276
  if (!COMPLETE_TYPE_P (t))
16277
    {
16278
      if (complain & tf_error)
16279
        error ("explicit instantiation of %q#T before definition of template",
16280
               t);
16281
      return;
16282
    }
16283
 
16284
  if (storage != NULL_TREE)
16285
    {
16286
      if (!in_system_header)
16287
        {
16288
          if (storage == ridpointers[(int) RID_EXTERN])
16289
            {
16290
              if (cxx_dialect == cxx98)
16291
                pedwarn (input_location, OPT_pedantic,
16292
                         "ISO C++ 1998 forbids the use of %<extern%> on "
16293
                         "explicit instantiations");
16294
            }
16295
          else
16296
            pedwarn (input_location, OPT_pedantic,
16297
                     "ISO C++ forbids the use of %qE"
16298
                     " on explicit instantiations", storage);
16299
        }
16300
 
16301
      if (storage == ridpointers[(int) RID_INLINE])
16302
        nomem_p = 1;
16303
      else if (storage == ridpointers[(int) RID_EXTERN])
16304
        extern_p = 1;
16305
      else if (storage == ridpointers[(int) RID_STATIC])
16306
        static_p = 1;
16307
      else
16308
        {
16309
          error ("storage class %qD applied to template instantiation",
16310
                 storage);
16311
          extern_p = 0;
16312
        }
16313
    }
16314
 
16315
  if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16316
    {
16317
      /* DR 259 [temp.spec].
16318
 
16319
         Both an explicit instantiation and a declaration of an explicit
16320
         specialization shall not appear in a program unless the explicit
16321
         instantiation follows a declaration of the explicit specialization.
16322
 
16323
         For a given set of template parameters, if an explicit
16324
         instantiation of a template appears after a declaration of an
16325
         explicit specialization for that template, the explicit
16326
         instantiation has no effect.  */
16327
      return;
16328
    }
16329
  else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16330
    {
16331
      /* [temp.spec]
16332
 
16333
         No program shall explicitly instantiate any template more
16334
         than once.
16335
 
16336
         If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16337
         instantiation was `extern'.  If EXTERN_P then the second is.
16338
         These cases are OK.  */
16339
      previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16340
 
16341
      if (!previous_instantiation_extern_p && !extern_p
16342
          && (complain & tf_error))
16343
        permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16344
 
16345
      /* If we've already instantiated the template, just return now.  */
16346
      if (!CLASSTYPE_INTERFACE_ONLY (t))
16347
        return;
16348
    }
16349
 
16350
  check_explicit_instantiation_namespace (TYPE_NAME (t));
16351
  mark_class_instantiated (t, extern_p);
16352
 
16353
  if (nomem_p)
16354
    return;
16355
 
16356
  {
16357
    tree tmp;
16358
 
16359
    /* In contrast to implicit instantiation, where only the
16360
       declarations, and not the definitions, of members are
16361
       instantiated, we have here:
16362
 
16363
         [temp.explicit]
16364
 
16365
         The explicit instantiation of a class template specialization
16366
         implies the instantiation of all of its members not
16367
         previously explicitly specialized in the translation unit
16368
         containing the explicit instantiation.
16369
 
16370
       Of course, we can't instantiate member template classes, since
16371
       we don't have any arguments for them.  Note that the standard
16372
       is unclear on whether the instantiation of the members are
16373
       *explicit* instantiations or not.  However, the most natural
16374
       interpretation is that it should be an explicit instantiation.  */
16375
 
16376
    if (! static_p)
16377
      for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16378
        if (TREE_CODE (tmp) == FUNCTION_DECL
16379
            && DECL_TEMPLATE_INSTANTIATION (tmp))
16380
          instantiate_class_member (tmp, extern_p);
16381
 
16382
    for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16383
      if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16384
        instantiate_class_member (tmp, extern_p);
16385
 
16386
    if (CLASSTYPE_NESTED_UTDS (t))
16387
      binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16388
                             bt_instantiate_type_proc, &storage);
16389
  }
16390
}
16391
 
16392
/* Given a function DECL, which is a specialization of TMPL, modify
16393
   DECL to be a re-instantiation of TMPL with the same template
16394
   arguments.  TMPL should be the template into which tsubst'ing
16395
   should occur for DECL, not the most general template.
16396
 
16397
   One reason for doing this is a scenario like this:
16398
 
16399
     template <class T>
16400
     void f(const T&, int i);
16401
 
16402
     void g() { f(3, 7); }
16403
 
16404
     template <class T>
16405
     void f(const T& t, const int i) { }
16406
 
16407
   Note that when the template is first instantiated, with
16408
   instantiate_template, the resulting DECL will have no name for the
16409
   first parameter, and the wrong type for the second.  So, when we go
16410
   to instantiate the DECL, we regenerate it.  */
16411
 
16412
static void
16413
regenerate_decl_from_template (tree decl, tree tmpl)
16414
{
16415
  /* The arguments used to instantiate DECL, from the most general
16416
     template.  */
16417
  tree args;
16418
  tree code_pattern;
16419
 
16420
  args = DECL_TI_ARGS (decl);
16421
  code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16422
 
16423
  /* Make sure that we can see identifiers, and compute access
16424
     correctly.  */
16425
  push_access_scope (decl);
16426
 
16427
  if (TREE_CODE (decl) == FUNCTION_DECL)
16428
    {
16429
      tree decl_parm;
16430
      tree pattern_parm;
16431
      tree specs;
16432
      int args_depth;
16433
      int parms_depth;
16434
 
16435
      args_depth = TMPL_ARGS_DEPTH (args);
16436
      parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16437
      if (args_depth > parms_depth)
16438
        args = get_innermost_template_args (args, parms_depth);
16439
 
16440
      specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16441
                                              args, tf_error, NULL_TREE);
16442
      if (specs)
16443
        TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16444
                                                    specs);
16445
 
16446
      /* Merge parameter declarations.  */
16447
      decl_parm = skip_artificial_parms_for (decl,
16448
                                             DECL_ARGUMENTS (decl));
16449
      pattern_parm
16450
        = skip_artificial_parms_for (code_pattern,
16451
                                     DECL_ARGUMENTS (code_pattern));
16452
      while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16453
        {
16454
          tree parm_type;
16455
          tree attributes;
16456
 
16457
          if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16458
            DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16459
          parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16460
                              NULL_TREE);
16461
          parm_type = type_decays_to (parm_type);
16462
          if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16463
            TREE_TYPE (decl_parm) = parm_type;
16464
          attributes = DECL_ATTRIBUTES (pattern_parm);
16465
          if (DECL_ATTRIBUTES (decl_parm) != attributes)
16466
            {
16467
              DECL_ATTRIBUTES (decl_parm) = attributes;
16468
              cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16469
            }
16470
          decl_parm = TREE_CHAIN (decl_parm);
16471
          pattern_parm = TREE_CHAIN (pattern_parm);
16472
        }
16473
      /* Merge any parameters that match with the function parameter
16474
         pack.  */
16475
      if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16476
        {
16477
          int i, len;
16478
          tree expanded_types;
16479
          /* Expand the TYPE_PACK_EXPANSION that provides the types for
16480
             the parameters in this function parameter pack.  */
16481
          expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
16482
                                                 args, tf_error, NULL_TREE);
16483
          len = TREE_VEC_LENGTH (expanded_types);
16484
          for (i = 0; i < len; i++)
16485
            {
16486
              tree parm_type;
16487
              tree attributes;
16488
 
16489
              if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16490
                /* Rename the parameter to include the index.  */
16491
                DECL_NAME (decl_parm) =
16492
                  make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16493
              parm_type = TREE_VEC_ELT (expanded_types, i);
16494
              parm_type = type_decays_to (parm_type);
16495
              if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16496
                TREE_TYPE (decl_parm) = parm_type;
16497
              attributes = DECL_ATTRIBUTES (pattern_parm);
16498
              if (DECL_ATTRIBUTES (decl_parm) != attributes)
16499
                {
16500
                  DECL_ATTRIBUTES (decl_parm) = attributes;
16501
                  cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16502
                }
16503
              decl_parm = TREE_CHAIN (decl_parm);
16504
            }
16505
        }
16506
      /* Merge additional specifiers from the CODE_PATTERN.  */
16507
      if (DECL_DECLARED_INLINE_P (code_pattern)
16508
          && !DECL_DECLARED_INLINE_P (decl))
16509
        DECL_DECLARED_INLINE_P (decl) = 1;
16510
    }
16511
  else if (TREE_CODE (decl) == VAR_DECL)
16512
    DECL_INITIAL (decl) =
16513
      tsubst_expr (DECL_INITIAL (code_pattern), args,
16514
                   tf_error, DECL_TI_TEMPLATE (decl),
16515
                   /*integral_constant_expression_p=*/false);
16516
  else
16517
    gcc_unreachable ();
16518
 
16519
  pop_access_scope (decl);
16520
}
16521
 
16522
/* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16523
   substituted to get DECL.  */
16524
 
16525
tree
16526
template_for_substitution (tree decl)
16527
{
16528
  tree tmpl = DECL_TI_TEMPLATE (decl);
16529
 
16530
  /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16531
     for the instantiation.  This is not always the most general
16532
     template.  Consider, for example:
16533
 
16534
        template <class T>
16535
        struct S { template <class U> void f();
16536
                   template <> void f<int>(); };
16537
 
16538
     and an instantiation of S<double>::f<int>.  We want TD to be the
16539
     specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16540
  while (/* An instantiation cannot have a definition, so we need a
16541
            more general template.  */
16542
         DECL_TEMPLATE_INSTANTIATION (tmpl)
16543
           /* We must also deal with friend templates.  Given:
16544
 
16545
                template <class T> struct S {
16546
                  template <class U> friend void f() {};
16547
                };
16548
 
16549
              S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16550
              so far as the language is concerned, but that's still
16551
              where we get the pattern for the instantiation from.  On
16552
              other hand, if the definition comes outside the class, say:
16553
 
16554
                template <class T> struct S {
16555
                  template <class U> friend void f();
16556
                };
16557
                template <class U> friend void f() {}
16558
 
16559
              we don't need to look any further.  That's what the check for
16560
              DECL_INITIAL is for.  */
16561
          || (TREE_CODE (decl) == FUNCTION_DECL
16562
              && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16563
              && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16564
    {
16565
      /* The present template, TD, should not be a definition.  If it
16566
         were a definition, we should be using it!  Note that we
16567
         cannot restructure the loop to just keep going until we find
16568
         a template with a definition, since that might go too far if
16569
         a specialization was declared, but not defined.  */
16570
      gcc_assert (TREE_CODE (decl) != VAR_DECL
16571
                  || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16572
 
16573
      /* Fetch the more general template.  */
16574
      tmpl = DECL_TI_TEMPLATE (tmpl);
16575
    }
16576
 
16577
  return tmpl;
16578
}
16579
 
16580
/* Returns true if we need to instantiate this template instance even if we
16581
   know we aren't going to emit it..  */
16582
 
16583
bool
16584
always_instantiate_p (tree decl)
16585
{
16586
  /* We always instantiate inline functions so that we can inline them.  An
16587
     explicit instantiation declaration prohibits implicit instantiation of
16588
     non-inline functions.  With high levels of optimization, we would
16589
     normally inline non-inline functions -- but we're not allowed to do
16590
     that for "extern template" functions.  Therefore, we check
16591
     DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16592
  return ((TREE_CODE (decl) == FUNCTION_DECL
16593
           && DECL_DECLARED_INLINE_P (decl))
16594
          /* And we need to instantiate static data members so that
16595
             their initializers are available in integral constant
16596
             expressions.  */
16597
          || (TREE_CODE (decl) == VAR_DECL
16598
              && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16599
}
16600
 
16601
/* Produce the definition of D, a _DECL generated from a template.  If
16602
   DEFER_OK is nonzero, then we don't have to actually do the
16603
   instantiation now; we just have to do it sometime.  Normally it is
16604
   an error if this is an explicit instantiation but D is undefined.
16605
   EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16606
   explicitly instantiated class template.  */
16607
 
16608
tree
16609
instantiate_decl (tree d, int defer_ok,
16610
                  bool expl_inst_class_mem_p)
16611
{
16612
  tree tmpl = DECL_TI_TEMPLATE (d);
16613
  tree gen_args;
16614
  tree args;
16615
  tree td;
16616
  tree code_pattern;
16617
  tree spec;
16618
  tree gen_tmpl;
16619
  bool pattern_defined;
16620
  int need_push;
16621
  location_t saved_loc = input_location;
16622
  bool external_p;
16623
 
16624
  /* This function should only be used to instantiate templates for
16625
     functions and static member variables.  */
16626
  gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16627
              || TREE_CODE (d) == VAR_DECL);
16628
 
16629
  /* Variables are never deferred; if instantiation is required, they
16630
     are instantiated right away.  That allows for better code in the
16631
     case that an expression refers to the value of the variable --
16632
     if the variable has a constant value the referring expression can
16633
     take advantage of that fact.  */
16634
  if (TREE_CODE (d) == VAR_DECL)
16635
    defer_ok = 0;
16636
 
16637
  /* Don't instantiate cloned functions.  Instead, instantiate the
16638
     functions they cloned.  */
16639
  if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16640
    d = DECL_CLONED_FUNCTION (d);
16641
 
16642
  if (DECL_TEMPLATE_INSTANTIATED (d)
16643
      || DECL_TEMPLATE_SPECIALIZATION (d))
16644
    /* D has already been instantiated or explicitly specialized, so
16645
       there's nothing for us to do here.
16646
 
16647
       It might seem reasonable to check whether or not D is an explicit
16648
       instantiation, and, if so, stop here.  But when an explicit
16649
       instantiation is deferred until the end of the compilation,
16650
       DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16651
       the instantiation.  */
16652
    return d;
16653
 
16654
  /* Check to see whether we know that this template will be
16655
     instantiated in some other file, as with "extern template"
16656
     extension.  */
16657
  external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16658
 
16659
  /* In general, we do not instantiate such templates.  */
16660
  if (external_p && !always_instantiate_p (d))
16661
    return d;
16662
 
16663
  gen_tmpl = most_general_template (tmpl);
16664
  gen_args = DECL_TI_ARGS (d);
16665
 
16666
  if (tmpl != gen_tmpl)
16667
    /* We should already have the extra args.  */
16668
    gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16669
                == TMPL_ARGS_DEPTH (gen_args));
16670
  /* And what's in the hash table should match D.  */
16671
  gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16672
              || spec == NULL_TREE);
16673
 
16674
  /* This needs to happen before any tsubsting.  */
16675
  if (! push_tinst_level (d))
16676
    return d;
16677
 
16678
  timevar_push (TV_PARSE);
16679
 
16680
  /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16681
     for the instantiation.  */
16682
  td = template_for_substitution (d);
16683
  code_pattern = DECL_TEMPLATE_RESULT (td);
16684
 
16685
  /* We should never be trying to instantiate a member of a class
16686
     template or partial specialization.  */
16687
  gcc_assert (d != code_pattern);
16688
 
16689
  if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16690
      || DECL_TEMPLATE_SPECIALIZATION (td))
16691
    /* In the case of a friend template whose definition is provided
16692
       outside the class, we may have too many arguments.  Drop the
16693
       ones we don't need.  The same is true for specializations.  */
16694
    args = get_innermost_template_args
16695
      (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16696
  else
16697
    args = gen_args;
16698
 
16699
  if (TREE_CODE (d) == FUNCTION_DECL)
16700
    pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16701
  else
16702
    pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16703
 
16704
  /* We may be in the middle of deferred access check.  Disable it now.  */
16705
  push_deferring_access_checks (dk_no_deferred);
16706
 
16707
  /* Unless an explicit instantiation directive has already determined
16708
     the linkage of D, remember that a definition is available for
16709
     this entity.  */
16710
  if (pattern_defined
16711
      && !DECL_INTERFACE_KNOWN (d)
16712
      && !DECL_NOT_REALLY_EXTERN (d))
16713
    mark_definable (d);
16714
 
16715
  input_location = DECL_SOURCE_LOCATION (d);
16716
 
16717
  /* If D is a member of an explicitly instantiated class template,
16718
     and no definition is available, treat it like an implicit
16719
     instantiation.  */
16720
  if (!pattern_defined && expl_inst_class_mem_p
16721
      && DECL_EXPLICIT_INSTANTIATION (d))
16722
    {
16723
      DECL_NOT_REALLY_EXTERN (d) = 0;
16724
      DECL_INTERFACE_KNOWN (d) = 0;
16725
      SET_DECL_IMPLICIT_INSTANTIATION (d);
16726
    }
16727
 
16728
  /* Recheck the substitutions to obtain any warning messages
16729
     about ignoring cv qualifiers.  Don't do this for artificial decls,
16730
     as it breaks the context-sensitive substitution for lambda op(). */
16731
  if (!defer_ok && !DECL_ARTIFICIAL (d))
16732
    {
16733
      tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16734
      tree type = TREE_TYPE (gen);
16735
 
16736
      /* Make sure that we can see identifiers, and compute access
16737
         correctly.  D is already the target FUNCTION_DECL with the
16738
         right context.  */
16739
      push_access_scope (d);
16740
 
16741
      if (TREE_CODE (gen) == FUNCTION_DECL)
16742
        {
16743
          tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16744
          tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16745
                                          d);
16746
          /* Don't simply tsubst the function type, as that will give
16747
             duplicate warnings about poor parameter qualifications.
16748
             The function arguments are the same as the decl_arguments
16749
             without the top level cv qualifiers.  */
16750
          type = TREE_TYPE (type);
16751
        }
16752
      tsubst (type, gen_args, tf_warning_or_error, d);
16753
 
16754
      pop_access_scope (d);
16755
    }
16756
 
16757
  /* Defer all other templates, unless we have been explicitly
16758
     forbidden from doing so.  */
16759
  if (/* If there is no definition, we cannot instantiate the
16760
         template.  */
16761
      ! pattern_defined
16762
      /* If it's OK to postpone instantiation, do so.  */
16763
      || defer_ok
16764
      /* If this is a static data member that will be defined
16765
         elsewhere, we don't want to instantiate the entire data
16766
         member, but we do want to instantiate the initializer so that
16767
         we can substitute that elsewhere.  */
16768
      || (external_p && TREE_CODE (d) == VAR_DECL))
16769
    {
16770
      /* The definition of the static data member is now required so
16771
         we must substitute the initializer.  */
16772
      if (TREE_CODE (d) == VAR_DECL
16773
          && !DECL_INITIAL (d)
16774
          && DECL_INITIAL (code_pattern))
16775
        {
16776
          tree ns;
16777
          tree init;
16778
 
16779
          ns = decl_namespace_context (d);
16780
          push_nested_namespace (ns);
16781
          push_nested_class (DECL_CONTEXT (d));
16782
          init = tsubst_expr (DECL_INITIAL (code_pattern),
16783
                              args,
16784
                              tf_warning_or_error, NULL_TREE,
16785
                              /*integral_constant_expression_p=*/false);
16786
          cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16787
                          /*asmspec_tree=*/NULL_TREE,
16788
                          LOOKUP_ONLYCONVERTING);
16789
          pop_nested_class ();
16790
          pop_nested_namespace (ns);
16791
        }
16792
 
16793
      /* We restore the source position here because it's used by
16794
         add_pending_template.  */
16795
      input_location = saved_loc;
16796
 
16797
      if (at_eof && !pattern_defined
16798
          && DECL_EXPLICIT_INSTANTIATION (d)
16799
          && DECL_NOT_REALLY_EXTERN (d))
16800
        /* [temp.explicit]
16801
 
16802
           The definition of a non-exported function template, a
16803
           non-exported member function template, or a non-exported
16804
           member function or static data member of a class template
16805
           shall be present in every translation unit in which it is
16806
           explicitly instantiated.  */
16807
        permerror (input_location,  "explicit instantiation of %qD "
16808
                   "but no definition available", d);
16809
 
16810
      /* ??? Historically, we have instantiated inline functions, even
16811
         when marked as "extern template".  */
16812
      if (!(external_p && TREE_CODE (d) == VAR_DECL))
16813
        add_pending_template (d);
16814
      goto out;
16815
    }
16816
  /* Tell the repository that D is available in this translation unit
16817
     -- and see if it is supposed to be instantiated here.  */
16818
  if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16819
    {
16820
      /* In a PCH file, despite the fact that the repository hasn't
16821
         requested instantiation in the PCH it is still possible that
16822
         an instantiation will be required in a file that includes the
16823
         PCH.  */
16824
      if (pch_file)
16825
        add_pending_template (d);
16826
      /* Instantiate inline functions so that the inliner can do its
16827
         job, even though we'll not be emitting a copy of this
16828
         function.  */
16829
      if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16830
        goto out;
16831
    }
16832
 
16833
  need_push = !cfun || !global_bindings_p ();
16834
  if (need_push)
16835
    push_to_top_level ();
16836
 
16837
  /* Mark D as instantiated so that recursive calls to
16838
     instantiate_decl do not try to instantiate it again.  */
16839
  DECL_TEMPLATE_INSTANTIATED (d) = 1;
16840
 
16841
  /* Regenerate the declaration in case the template has been modified
16842
     by a subsequent redeclaration.  */
16843
  regenerate_decl_from_template (d, td);
16844
 
16845
  /* We already set the file and line above.  Reset them now in case
16846
     they changed as a result of calling regenerate_decl_from_template.  */
16847
  input_location = DECL_SOURCE_LOCATION (d);
16848
 
16849
  if (TREE_CODE (d) == VAR_DECL)
16850
    {
16851
      tree init;
16852
 
16853
      /* Clear out DECL_RTL; whatever was there before may not be right
16854
         since we've reset the type of the declaration.  */
16855
      SET_DECL_RTL (d, NULL_RTX);
16856
      DECL_IN_AGGR_P (d) = 0;
16857
 
16858
      /* The initializer is placed in DECL_INITIAL by
16859
         regenerate_decl_from_template.  Pull it out so that
16860
         cp_finish_decl can process it.  */
16861
      init = DECL_INITIAL (d);
16862
      DECL_INITIAL (d) = NULL_TREE;
16863
      DECL_INITIALIZED_P (d) = 0;
16864
 
16865
      /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16866
         initializer.  That function will defer actual emission until
16867
         we have a chance to determine linkage.  */
16868
      DECL_EXTERNAL (d) = 0;
16869
 
16870
      /* Enter the scope of D so that access-checking works correctly.  */
16871
      push_nested_class (DECL_CONTEXT (d));
16872
      cp_finish_decl (d, init, false, NULL_TREE, 0);
16873
      pop_nested_class ();
16874
    }
16875
  else if (TREE_CODE (d) == FUNCTION_DECL)
16876
    {
16877
      htab_t saved_local_specializations;
16878
      tree subst_decl;
16879
      tree tmpl_parm;
16880
      tree spec_parm;
16881
 
16882
      /* Save away the current list, in case we are instantiating one
16883
         template from within the body of another.  */
16884
      saved_local_specializations = local_specializations;
16885
 
16886
      /* Set up the list of local specializations.  */
16887
      local_specializations = htab_create (37,
16888
                                           hash_local_specialization,
16889
                                           eq_local_specializations,
16890
                                           NULL);
16891
 
16892
      /* Set up context.  */
16893
      start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16894
 
16895
      /* Create substitution entries for the parameters.  */
16896
      subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16897
      tmpl_parm = DECL_ARGUMENTS (subst_decl);
16898
      spec_parm = DECL_ARGUMENTS (d);
16899
      if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16900
        {
16901
          register_local_specialization (spec_parm, tmpl_parm);
16902
          spec_parm = skip_artificial_parms_for (d, spec_parm);
16903
          tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16904
        }
16905
      while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16906
        {
16907
          register_local_specialization (spec_parm, tmpl_parm);
16908
          tmpl_parm = TREE_CHAIN (tmpl_parm);
16909
          spec_parm = TREE_CHAIN (spec_parm);
16910
        }
16911
      if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16912
        {
16913
          /* Register the (value) argument pack as a specialization of
16914
             TMPL_PARM, then move on.  */
16915
          tree argpack = make_fnparm_pack (spec_parm);
16916
          register_local_specialization (argpack, tmpl_parm);
16917
          tmpl_parm = TREE_CHAIN (tmpl_parm);
16918
          spec_parm = NULL_TREE;
16919
        }
16920
      gcc_assert (!spec_parm);
16921
 
16922
      /* Substitute into the body of the function.  */
16923
      tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16924
                   tf_warning_or_error, tmpl,
16925
                   /*integral_constant_expression_p=*/false);
16926
 
16927
      /* Set the current input_location to the end of the function
16928
         so that finish_function knows where we are.  */
16929
      input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16930
 
16931
      /* We don't need the local specializations any more.  */
16932
      htab_delete (local_specializations);
16933
      local_specializations = saved_local_specializations;
16934
 
16935
      /* Finish the function.  */
16936
      d = finish_function (0);
16937
      expand_or_defer_fn (d);
16938
    }
16939
 
16940
  /* We're not deferring instantiation any more.  */
16941
  TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16942
 
16943
  if (need_push)
16944
    pop_from_top_level ();
16945
 
16946
out:
16947
  input_location = saved_loc;
16948
  pop_deferring_access_checks ();
16949
  pop_tinst_level ();
16950
 
16951
  timevar_pop (TV_PARSE);
16952
 
16953
  return d;
16954
}
16955
 
16956
/* Run through the list of templates that we wish we could
16957
   instantiate, and instantiate any we can.  RETRIES is the
16958
   number of times we retry pending template instantiation.  */
16959
 
16960
void
16961
instantiate_pending_templates (int retries)
16962
{
16963
  int reconsider;
16964
  location_t saved_loc = input_location;
16965
 
16966
  /* Instantiating templates may trigger vtable generation.  This in turn
16967
     may require further template instantiations.  We place a limit here
16968
     to avoid infinite loop.  */
16969
  if (pending_templates && retries >= max_tinst_depth)
16970
    {
16971
      tree decl = pending_templates->tinst->decl;
16972
 
16973
      error ("template instantiation depth exceeds maximum of %d"
16974
             " instantiating %q+D, possibly from virtual table generation"
16975
             " (use -ftemplate-depth= to increase the maximum)",
16976
             max_tinst_depth, decl);
16977
      if (TREE_CODE (decl) == FUNCTION_DECL)
16978
        /* Pretend that we defined it.  */
16979
        DECL_INITIAL (decl) = error_mark_node;
16980
      return;
16981
    }
16982
 
16983
  do
16984
    {
16985
      struct pending_template **t = &pending_templates;
16986
      struct pending_template *last = NULL;
16987
      reconsider = 0;
16988
      while (*t)
16989
        {
16990
          tree instantiation = reopen_tinst_level ((*t)->tinst);
16991
          bool complete = false;
16992
 
16993
          if (TYPE_P (instantiation))
16994
            {
16995
              tree fn;
16996
 
16997
              if (!COMPLETE_TYPE_P (instantiation))
16998
                {
16999
                  instantiate_class_template (instantiation);
17000
                  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17001
                    for (fn = TYPE_METHODS (instantiation);
17002
                         fn;
17003
                         fn = TREE_CHAIN (fn))
17004
                      if (! DECL_ARTIFICIAL (fn))
17005
                        instantiate_decl (fn,
17006
                                          /*defer_ok=*/0,
17007
                                          /*expl_inst_class_mem_p=*/false);
17008
                  if (COMPLETE_TYPE_P (instantiation))
17009
                    reconsider = 1;
17010
                }
17011
 
17012
              complete = COMPLETE_TYPE_P (instantiation);
17013
            }
17014
          else
17015
            {
17016
              if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17017
                  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17018
                {
17019
                  instantiation
17020
                    = instantiate_decl (instantiation,
17021
                                        /*defer_ok=*/0,
17022
                                        /*expl_inst_class_mem_p=*/false);
17023
                  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17024
                    reconsider = 1;
17025
                }
17026
 
17027
              complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17028
                          || DECL_TEMPLATE_INSTANTIATED (instantiation));
17029
            }
17030
 
17031
          if (complete)
17032
            /* If INSTANTIATION has been instantiated, then we don't
17033
               need to consider it again in the future.  */
17034
            *t = (*t)->next;
17035
          else
17036
            {
17037
              last = *t;
17038
              t = &(*t)->next;
17039
            }
17040
          tinst_depth = 0;
17041
          current_tinst_level = NULL;
17042
        }
17043
      last_pending_template = last;
17044
    }
17045
  while (reconsider);
17046
 
17047
  input_location = saved_loc;
17048
}
17049
 
17050
/* Substitute ARGVEC into T, which is a list of initializers for
17051
   either base class or a non-static data member.  The TREE_PURPOSEs
17052
   are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17053
   instantiate_decl.  */
17054
 
17055
static tree
17056
tsubst_initializer_list (tree t, tree argvec)
17057
{
17058
  tree inits = NULL_TREE;
17059
 
17060
  for (; t; t = TREE_CHAIN (t))
17061
    {
17062
      tree decl;
17063
      tree init;
17064
      tree expanded_bases = NULL_TREE;
17065
      tree expanded_arguments = NULL_TREE;
17066
      int i, len = 1;
17067
 
17068
      if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17069
        {
17070
          tree expr;
17071
          tree arg;
17072
 
17073
          /* Expand the base class expansion type into separate base
17074
             classes.  */
17075
          expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17076
                                                 tf_warning_or_error,
17077
                                                 NULL_TREE);
17078
          if (expanded_bases == error_mark_node)
17079
            continue;
17080
 
17081
          /* We'll be building separate TREE_LISTs of arguments for
17082
             each base.  */
17083
          len = TREE_VEC_LENGTH (expanded_bases);
17084
          expanded_arguments = make_tree_vec (len);
17085
          for (i = 0; i < len; i++)
17086
            TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17087
 
17088
          /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17089
             expand each argument in the TREE_VALUE of t.  */
17090
          expr = make_node (EXPR_PACK_EXPANSION);
17091
          PACK_EXPANSION_PARAMETER_PACKS (expr) =
17092
            PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17093
 
17094
          if (TREE_VALUE (t) == void_type_node)
17095
            /* VOID_TYPE_NODE is used to indicate
17096
               value-initialization.  */
17097
            {
17098
              for (i = 0; i < len; i++)
17099
                TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17100
            }
17101
          else
17102
            {
17103
              /* Substitute parameter packs into each argument in the
17104
                 TREE_LIST.  */
17105
              in_base_initializer = 1;
17106
              for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17107
                {
17108
                  tree expanded_exprs;
17109
 
17110
                  /* Expand the argument.  */
17111
                  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17112
                  expanded_exprs
17113
                    = tsubst_pack_expansion (expr, argvec,
17114
                                             tf_warning_or_error,
17115
                                             NULL_TREE);
17116
                  if (expanded_exprs == error_mark_node)
17117
                    continue;
17118
 
17119
                  /* Prepend each of the expanded expressions to the
17120
                     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17121
                  for (i = 0; i < len; i++)
17122
                    {
17123
                      TREE_VEC_ELT (expanded_arguments, i) =
17124
                        tree_cons (NULL_TREE,
17125
                                   TREE_VEC_ELT (expanded_exprs, i),
17126
                                   TREE_VEC_ELT (expanded_arguments, i));
17127
                    }
17128
                }
17129
              in_base_initializer = 0;
17130
 
17131
              /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17132
                 since we built them backwards.  */
17133
              for (i = 0; i < len; i++)
17134
                {
17135
                  TREE_VEC_ELT (expanded_arguments, i) =
17136
                    nreverse (TREE_VEC_ELT (expanded_arguments, i));
17137
                }
17138
            }
17139
        }
17140
 
17141
      for (i = 0; i < len; ++i)
17142
        {
17143
          if (expanded_bases)
17144
            {
17145
              decl = TREE_VEC_ELT (expanded_bases, i);
17146
              decl = expand_member_init (decl);
17147
              init = TREE_VEC_ELT (expanded_arguments, i);
17148
            }
17149
          else
17150
            {
17151
              decl = tsubst_copy (TREE_PURPOSE (t), argvec,
17152
                                  tf_warning_or_error, NULL_TREE);
17153
 
17154
              decl = expand_member_init (decl);
17155
              if (decl && !DECL_P (decl))
17156
                in_base_initializer = 1;
17157
 
17158
              init = tsubst_expr (TREE_VALUE (t), argvec,
17159
                                  tf_warning_or_error, NULL_TREE,
17160
                                  /*integral_constant_expression_p=*/false);
17161
              in_base_initializer = 0;
17162
            }
17163
 
17164
          if (decl)
17165
            {
17166
              init = build_tree_list (decl, init);
17167
              TREE_CHAIN (init) = inits;
17168
              inits = init;
17169
            }
17170
        }
17171
    }
17172
  return inits;
17173
}
17174
 
17175
/* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17176
 
17177
static void
17178
set_current_access_from_decl (tree decl)
17179
{
17180
  if (TREE_PRIVATE (decl))
17181
    current_access_specifier = access_private_node;
17182
  else if (TREE_PROTECTED (decl))
17183
    current_access_specifier = access_protected_node;
17184
  else
17185
    current_access_specifier = access_public_node;
17186
}
17187
 
17188
/* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17189
   is the instantiation (which should have been created with
17190
   start_enum) and ARGS are the template arguments to use.  */
17191
 
17192
static void
17193
tsubst_enum (tree tag, tree newtag, tree args)
17194
{
17195
  tree e;
17196
 
17197
  for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17198
    {
17199
      tree value;
17200
      tree decl;
17201
 
17202
      decl = TREE_VALUE (e);
17203
      /* Note that in a template enum, the TREE_VALUE is the
17204
         CONST_DECL, not the corresponding INTEGER_CST.  */
17205
      value = tsubst_expr (DECL_INITIAL (decl),
17206
                           args, tf_warning_or_error, NULL_TREE,
17207
                           /*integral_constant_expression_p=*/true);
17208
 
17209
      /* Give this enumeration constant the correct access.  */
17210
      set_current_access_from_decl (decl);
17211
 
17212
      /* Actually build the enumerator itself.  */
17213
      build_enumerator (DECL_NAME (decl), value, newtag);
17214
    }
17215
 
17216
  finish_enum (newtag);
17217
  DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17218
    = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17219
}
17220
 
17221
/* DECL is a FUNCTION_DECL that is a template specialization.  Return
17222
   its type -- but without substituting the innermost set of template
17223
   arguments.  So, innermost set of template parameters will appear in
17224
   the type.  */
17225
 
17226
tree
17227
get_mostly_instantiated_function_type (tree decl)
17228
{
17229
  tree fn_type;
17230
  tree tmpl;
17231
  tree targs;
17232
  tree tparms;
17233
  int parm_depth;
17234
 
17235
  tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17236
  targs = DECL_TI_ARGS (decl);
17237
  tparms = DECL_TEMPLATE_PARMS (tmpl);
17238
  parm_depth = TMPL_PARMS_DEPTH (tparms);
17239
 
17240
  /* There should be as many levels of arguments as there are levels
17241
     of parameters.  */
17242
  gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17243
 
17244
  fn_type = TREE_TYPE (tmpl);
17245
 
17246
  if (parm_depth == 1)
17247
    /* No substitution is necessary.  */
17248
    ;
17249
  else
17250
    {
17251
      int i, save_access_control;
17252
      tree partial_args;
17253
 
17254
      /* Replace the innermost level of the TARGS with NULL_TREEs to
17255
         let tsubst know not to substitute for those parameters.  */
17256
      partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17257
      for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17258
        SET_TMPL_ARGS_LEVEL (partial_args, i,
17259
                             TMPL_ARGS_LEVEL (targs, i));
17260
      SET_TMPL_ARGS_LEVEL (partial_args,
17261
                           TMPL_ARGS_DEPTH (targs),
17262
                           make_tree_vec (DECL_NTPARMS (tmpl)));
17263
 
17264
      /* Disable access control as this function is used only during
17265
         name-mangling.  */
17266
      save_access_control = flag_access_control;
17267
      flag_access_control = 0;
17268
 
17269
      ++processing_template_decl;
17270
      /* Now, do the (partial) substitution to figure out the
17271
         appropriate function type.  */
17272
      fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17273
      --processing_template_decl;
17274
 
17275
      /* Substitute into the template parameters to obtain the real
17276
         innermost set of parameters.  This step is important if the
17277
         innermost set of template parameters contains value
17278
         parameters whose types depend on outer template parameters.  */
17279
      TREE_VEC_LENGTH (partial_args)--;
17280
      tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17281
 
17282
      flag_access_control = save_access_control;
17283
    }
17284
 
17285
  return fn_type;
17286
}
17287
 
17288
/* Return truthvalue if we're processing a template different from
17289
   the last one involved in diagnostics.  */
17290
int
17291
problematic_instantiation_changed (void)
17292
{
17293
  return last_template_error_tick != tinst_level_tick;
17294
}
17295
 
17296
/* Remember current template involved in diagnostics.  */
17297
void
17298
record_last_problematic_instantiation (void)
17299
{
17300
  last_template_error_tick = tinst_level_tick;
17301
}
17302
 
17303
struct tinst_level *
17304
current_instantiation (void)
17305
{
17306
  return current_tinst_level;
17307
}
17308
 
17309
/* [temp.param] Check that template non-type parm TYPE is of an allowable
17310
   type. Return zero for ok, nonzero for disallowed. Issue error and
17311
   warning messages under control of COMPLAIN.  */
17312
 
17313
static int
17314
invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17315
{
17316
  if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17317
    return 0;
17318
  else if (POINTER_TYPE_P (type))
17319
    return 0;
17320
  else if (TYPE_PTR_TO_MEMBER_P (type))
17321
    return 0;
17322
  else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17323
    return 0;
17324
  else if (TREE_CODE (type) == TYPENAME_TYPE)
17325
    return 0;
17326
 
17327
  if (complain & tf_error)
17328
    error ("%q#T is not a valid type for a template constant parameter", type);
17329
  return 1;
17330
}
17331
 
17332
/* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17333
   Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17334
 
17335
static bool
17336
dependent_type_p_r (tree type)
17337
{
17338
  tree scope;
17339
 
17340
  /* [temp.dep.type]
17341
 
17342
     A type is dependent if it is:
17343
 
17344
     -- a template parameter. Template template parameters are types
17345
        for us (since TYPE_P holds true for them) so we handle
17346
        them here.  */
17347
  if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17348
      || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17349
    return true;
17350
  /* -- a qualified-id with a nested-name-specifier which contains a
17351
        class-name that names a dependent type or whose unqualified-id
17352
        names a dependent type.  */
17353
  if (TREE_CODE (type) == TYPENAME_TYPE)
17354
    return true;
17355
  /* -- a cv-qualified type where the cv-unqualified type is
17356
        dependent.  */
17357
  type = TYPE_MAIN_VARIANT (type);
17358
  /* -- a compound type constructed from any dependent type.  */
17359
  if (TYPE_PTR_TO_MEMBER_P (type))
17360
    return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17361
            || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17362
                                           (type)));
17363
  else if (TREE_CODE (type) == POINTER_TYPE
17364
           || TREE_CODE (type) == REFERENCE_TYPE)
17365
    return dependent_type_p (TREE_TYPE (type));
17366
  else if (TREE_CODE (type) == FUNCTION_TYPE
17367
           || TREE_CODE (type) == METHOD_TYPE)
17368
    {
17369
      tree arg_type;
17370
 
17371
      if (dependent_type_p (TREE_TYPE (type)))
17372
        return true;
17373
      for (arg_type = TYPE_ARG_TYPES (type);
17374
           arg_type;
17375
           arg_type = TREE_CHAIN (arg_type))
17376
        if (dependent_type_p (TREE_VALUE (arg_type)))
17377
          return true;
17378
      return false;
17379
    }
17380
  /* -- an array type constructed from any dependent type or whose
17381
        size is specified by a constant expression that is
17382
        value-dependent.  */
17383
  if (TREE_CODE (type) == ARRAY_TYPE)
17384
    {
17385
      if (TYPE_DOMAIN (type)
17386
          && dependent_type_p (TYPE_DOMAIN (type)))
17387
        return true;
17388
      return dependent_type_p (TREE_TYPE (type));
17389
    }
17390
  else if (TREE_CODE (type) == INTEGER_TYPE
17391
           && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17392
    {
17393
      /* If this is the TYPE_DOMAIN of an array type, consider it
17394
         dependent.  We already checked for value-dependence in
17395
         compute_array_index_type.  */
17396
      return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17397
    }
17398
 
17399
  /* -- a template-id in which either the template name is a template
17400
     parameter ...  */
17401
  if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17402
    return true;
17403
  /* ... or any of the template arguments is a dependent type or
17404
        an expression that is type-dependent or value-dependent.  */
17405
  else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17406
           && (any_dependent_template_arguments_p
17407
               (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17408
    return true;
17409
 
17410
  /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17411
     argument of the `typeof' expression is not type-dependent, then
17412
     it should already been have resolved.  */
17413
  if (TREE_CODE (type) == TYPEOF_TYPE
17414
      || TREE_CODE (type) == DECLTYPE_TYPE)
17415
    return true;
17416
 
17417
  /* A template argument pack is dependent if any of its packed
17418
     arguments are.  */
17419
  if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17420
    {
17421
      tree args = ARGUMENT_PACK_ARGS (type);
17422
      int i, len = TREE_VEC_LENGTH (args);
17423
      for (i = 0; i < len; ++i)
17424
        if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17425
          return true;
17426
    }
17427
 
17428
  /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17429
     be template parameters.  */
17430
  if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17431
    return true;
17432
 
17433
  /* The standard does not specifically mention types that are local
17434
     to template functions or local classes, but they should be
17435
     considered dependent too.  For example:
17436
 
17437
       template <int I> void f() {
17438
         enum E { a = I };
17439
         S<sizeof (E)> s;
17440
       }
17441
 
17442
     The size of `E' cannot be known until the value of `I' has been
17443
     determined.  Therefore, `E' must be considered dependent.  */
17444
  scope = TYPE_CONTEXT (type);
17445
  if (scope && TYPE_P (scope))
17446
    return dependent_type_p (scope);
17447
  else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17448
    return type_dependent_expression_p (scope);
17449
 
17450
  /* Other types are non-dependent.  */
17451
  return false;
17452
}
17453
 
17454
/* Returns TRUE if TYPE is dependent, in the sense of
17455
   [temp.dep.type].  */
17456
 
17457
bool
17458
dependent_type_p (tree type)
17459
{
17460
  /* If there are no template parameters in scope, then there can't be
17461
     any dependent types.  */
17462
  if (!processing_template_decl)
17463
    {
17464
      /* If we are not processing a template, then nobody should be
17465
         providing us with a dependent type.  */
17466
      gcc_assert (type);
17467
      gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17468
      return false;
17469
    }
17470
 
17471
  /* If the type is NULL, we have not computed a type for the entity
17472
     in question; in that case, the type is dependent.  */
17473
  if (!type)
17474
    return true;
17475
 
17476
  /* Erroneous types can be considered non-dependent.  */
17477
  if (type == error_mark_node)
17478
    return false;
17479
 
17480
  /* If we have not already computed the appropriate value for TYPE,
17481
     do so now.  */
17482
  if (!TYPE_DEPENDENT_P_VALID (type))
17483
    {
17484
      TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17485
      TYPE_DEPENDENT_P_VALID (type) = 1;
17486
    }
17487
 
17488
  return TYPE_DEPENDENT_P (type);
17489
}
17490
 
17491
/* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17492
   lookup.  In other words, a dependent type that is not the current
17493
   instantiation.  */
17494
 
17495
bool
17496
dependent_scope_p (tree scope)
17497
{
17498
  return (scope && TYPE_P (scope) && dependent_type_p (scope)
17499
          && !currently_open_class (scope));
17500
}
17501
 
17502
/* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17503
 
17504
static bool
17505
dependent_scope_ref_p (tree expression, bool criterion (tree))
17506
{
17507
  tree scope;
17508
  tree name;
17509
 
17510
  gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17511
 
17512
  if (!TYPE_P (TREE_OPERAND (expression, 0)))
17513
    return true;
17514
 
17515
  scope = TREE_OPERAND (expression, 0);
17516
  name = TREE_OPERAND (expression, 1);
17517
 
17518
  /* [temp.dep.expr]
17519
 
17520
     An id-expression is type-dependent if it contains a
17521
     nested-name-specifier that contains a class-name that names a
17522
     dependent type.  */
17523
  /* The suggested resolution to Core Issue 224 implies that if the
17524
     qualifying type is the current class, then we must peek
17525
     inside it.  */
17526
  if (DECL_P (name)
17527
      && currently_open_class (scope)
17528
      && !criterion (name))
17529
    return false;
17530
  if (dependent_type_p (scope))
17531
    return true;
17532
 
17533
  return false;
17534
}
17535
 
17536
/* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17537
   [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17538
   expression.  */
17539
 
17540
bool
17541
value_dependent_expression_p (tree expression)
17542
{
17543
  if (!processing_template_decl)
17544
    return false;
17545
 
17546
  /* A name declared with a dependent type.  */
17547
  if (DECL_P (expression) && type_dependent_expression_p (expression))
17548
    return true;
17549
 
17550
  switch (TREE_CODE (expression))
17551
    {
17552
    case IDENTIFIER_NODE:
17553
      /* A name that has not been looked up -- must be dependent.  */
17554
      return true;
17555
 
17556
    case TEMPLATE_PARM_INDEX:
17557
      /* A non-type template parm.  */
17558
      return true;
17559
 
17560
    case CONST_DECL:
17561
      /* A non-type template parm.  */
17562
      if (DECL_TEMPLATE_PARM_P (expression))
17563
        return true;
17564
      return value_dependent_expression_p (DECL_INITIAL (expression));
17565
 
17566
    case VAR_DECL:
17567
       /* A constant with integral or enumeration type and is initialized
17568
          with an expression that is value-dependent.  */
17569
      if (DECL_INITIAL (expression)
17570
          && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17571
          && value_dependent_expression_p (DECL_INITIAL (expression)))
17572
        return true;
17573
      return false;
17574
 
17575
    case DYNAMIC_CAST_EXPR:
17576
    case STATIC_CAST_EXPR:
17577
    case CONST_CAST_EXPR:
17578
    case REINTERPRET_CAST_EXPR:
17579
    case CAST_EXPR:
17580
      /* These expressions are value-dependent if the type to which
17581
         the cast occurs is dependent or the expression being casted
17582
         is value-dependent.  */
17583
      {
17584
        tree type = TREE_TYPE (expression);
17585
 
17586
        if (dependent_type_p (type))
17587
          return true;
17588
 
17589
        /* A functional cast has a list of operands.  */
17590
        expression = TREE_OPERAND (expression, 0);
17591
        if (!expression)
17592
          {
17593
            /* If there are no operands, it must be an expression such
17594
               as "int()". This should not happen for aggregate types
17595
               because it would form non-constant expressions.  */
17596
            gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17597
 
17598
            return false;
17599
          }
17600
 
17601
        if (TREE_CODE (expression) == TREE_LIST)
17602
          return any_value_dependent_elements_p (expression);
17603
 
17604
        return value_dependent_expression_p (expression);
17605
      }
17606
 
17607
    case SIZEOF_EXPR:
17608
    case ALIGNOF_EXPR:
17609
      /* A `sizeof' expression is value-dependent if the operand is
17610
         type-dependent or is a pack expansion.  */
17611
      expression = TREE_OPERAND (expression, 0);
17612
      if (PACK_EXPANSION_P (expression))
17613
        return true;
17614
      else if (TYPE_P (expression))
17615
        return dependent_type_p (expression);
17616
      return type_dependent_expression_p (expression);
17617
 
17618
    case SCOPE_REF:
17619
      return dependent_scope_ref_p (expression, value_dependent_expression_p);
17620
 
17621
    case COMPONENT_REF:
17622
      return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17623
              || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17624
 
17625
    case CALL_EXPR:
17626
      /* A CALL_EXPR may appear in a constant expression if it is a
17627
         call to a builtin function, e.g., __builtin_constant_p.  All
17628
         such calls are value-dependent.  */
17629
      return true;
17630
 
17631
    case NONTYPE_ARGUMENT_PACK:
17632
      /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17633
         is value-dependent.  */
17634
      {
17635
        tree values = ARGUMENT_PACK_ARGS (expression);
17636
        int i, len = TREE_VEC_LENGTH (values);
17637
 
17638
        for (i = 0; i < len; ++i)
17639
          if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17640
            return true;
17641
 
17642
        return false;
17643
      }
17644
 
17645
    case TRAIT_EXPR:
17646
      {
17647
        tree type2 = TRAIT_EXPR_TYPE2 (expression);
17648
        return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17649
                || (type2 ? dependent_type_p (type2) : false));
17650
      }
17651
 
17652
    case MODOP_EXPR:
17653
      return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17654
              || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17655
 
17656
    case ADDR_EXPR:
17657
      {
17658
        tree op = TREE_OPERAND (expression, 0);
17659
        return (value_dependent_expression_p (op)
17660
                || has_value_dependent_address (op));
17661
      }
17662
 
17663
    default:
17664
      /* A constant expression is value-dependent if any subexpression is
17665
         value-dependent.  */
17666
      switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17667
        {
17668
        case tcc_reference:
17669
        case tcc_unary:
17670
          return (value_dependent_expression_p
17671
                  (TREE_OPERAND (expression, 0)));
17672
 
17673
        case tcc_comparison:
17674
        case tcc_binary:
17675
          return ((value_dependent_expression_p
17676
                   (TREE_OPERAND (expression, 0)))
17677
                  || (value_dependent_expression_p
17678
                      (TREE_OPERAND (expression, 1))));
17679
 
17680
        case tcc_expression:
17681
        case tcc_vl_exp:
17682
          {
17683
            int i;
17684
            for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17685
              /* In some cases, some of the operands may be missing.
17686
                 (For example, in the case of PREDECREMENT_EXPR, the
17687
                 amount to increment by may be missing.)  That doesn't
17688
                 make the expression dependent.  */
17689
              if (TREE_OPERAND (expression, i)
17690
                  && (value_dependent_expression_p
17691
                      (TREE_OPERAND (expression, i))))
17692
                return true;
17693
            return false;
17694
          }
17695
 
17696
        default:
17697
          break;
17698
        }
17699
    }
17700
 
17701
  /* The expression is not value-dependent.  */
17702
  return false;
17703
}
17704
 
17705
/* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17706
   [temp.dep.expr].  */
17707
 
17708
bool
17709
type_dependent_expression_p (tree expression)
17710
{
17711
  if (!processing_template_decl)
17712
    return false;
17713
 
17714
  if (expression == error_mark_node)
17715
    return false;
17716
 
17717
  /* An unresolved name is always dependent.  */
17718
  if (TREE_CODE (expression) == IDENTIFIER_NODE
17719
      || TREE_CODE (expression) == USING_DECL)
17720
    return true;
17721
 
17722
  /* Some expression forms are never type-dependent.  */
17723
  if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17724
      || TREE_CODE (expression) == SIZEOF_EXPR
17725
      || TREE_CODE (expression) == ALIGNOF_EXPR
17726
      || TREE_CODE (expression) == TRAIT_EXPR
17727
      || TREE_CODE (expression) == TYPEID_EXPR
17728
      || TREE_CODE (expression) == DELETE_EXPR
17729
      || TREE_CODE (expression) == VEC_DELETE_EXPR
17730
      || TREE_CODE (expression) == THROW_EXPR)
17731
    return false;
17732
 
17733
  /* The types of these expressions depends only on the type to which
17734
     the cast occurs.  */
17735
  if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17736
      || TREE_CODE (expression) == STATIC_CAST_EXPR
17737
      || TREE_CODE (expression) == CONST_CAST_EXPR
17738
      || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17739
      || TREE_CODE (expression) == CAST_EXPR)
17740
    return dependent_type_p (TREE_TYPE (expression));
17741
 
17742
  /* The types of these expressions depends only on the type created
17743
     by the expression.  */
17744
  if (TREE_CODE (expression) == NEW_EXPR
17745
      || TREE_CODE (expression) == VEC_NEW_EXPR)
17746
    {
17747
      /* For NEW_EXPR tree nodes created inside a template, either
17748
         the object type itself or a TREE_LIST may appear as the
17749
         operand 1.  */
17750
      tree type = TREE_OPERAND (expression, 1);
17751
      if (TREE_CODE (type) == TREE_LIST)
17752
        /* This is an array type.  We need to check array dimensions
17753
           as well.  */
17754
        return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17755
               || value_dependent_expression_p
17756
                    (TREE_OPERAND (TREE_VALUE (type), 1));
17757
      else
17758
        return dependent_type_p (type);
17759
    }
17760
 
17761
  if (TREE_CODE (expression) == SCOPE_REF
17762
      && dependent_scope_ref_p (expression,
17763
                                type_dependent_expression_p))
17764
    return true;
17765
 
17766
  if (TREE_CODE (expression) == FUNCTION_DECL
17767
      && DECL_LANG_SPECIFIC (expression)
17768
      && DECL_TEMPLATE_INFO (expression)
17769
      && (any_dependent_template_arguments_p
17770
          (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17771
    return true;
17772
 
17773
  if (TREE_CODE (expression) == TEMPLATE_DECL
17774
      && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17775
    return false;
17776
 
17777
  if (TREE_CODE (expression) == STMT_EXPR)
17778
    expression = stmt_expr_value_expr (expression);
17779
 
17780
  if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17781
    {
17782
      tree elt;
17783
      unsigned i;
17784
 
17785
      FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17786
        {
17787
          if (type_dependent_expression_p (elt))
17788
            return true;
17789
        }
17790
      return false;
17791
    }
17792
 
17793
  if (TREE_TYPE (expression) == unknown_type_node)
17794
    {
17795
      if (TREE_CODE (expression) == ADDR_EXPR)
17796
        return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17797
      if (TREE_CODE (expression) == COMPONENT_REF
17798
          || TREE_CODE (expression) == OFFSET_REF)
17799
        {
17800
          if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17801
            return true;
17802
          expression = TREE_OPERAND (expression, 1);
17803
          if (TREE_CODE (expression) == IDENTIFIER_NODE)
17804
            return false;
17805
        }
17806
      /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17807
      if (TREE_CODE (expression) == SCOPE_REF)
17808
        return false;
17809
 
17810
      if (TREE_CODE (expression) == BASELINK)
17811
        expression = BASELINK_FUNCTIONS (expression);
17812
 
17813
      if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17814
        {
17815
          if (any_dependent_template_arguments_p
17816
              (TREE_OPERAND (expression, 1)))
17817
            return true;
17818
          expression = TREE_OPERAND (expression, 0);
17819
        }
17820
      gcc_assert (TREE_CODE (expression) == OVERLOAD
17821
                  || TREE_CODE (expression) == FUNCTION_DECL);
17822
 
17823
      while (expression)
17824
        {
17825
          if (type_dependent_expression_p (OVL_CURRENT (expression)))
17826
            return true;
17827
          expression = OVL_NEXT (expression);
17828
        }
17829
      return false;
17830
    }
17831
 
17832
  gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17833
 
17834
  return (dependent_type_p (TREE_TYPE (expression)));
17835
}
17836
 
17837
/* Like type_dependent_expression_p, but it also works while not processing
17838
   a template definition, i.e. during substitution or mangling.  */
17839
 
17840
bool
17841
type_dependent_expression_p_push (tree expr)
17842
{
17843
  bool b;
17844
  ++processing_template_decl;
17845
  b = type_dependent_expression_p (expr);
17846
  --processing_template_decl;
17847
  return b;
17848
}
17849
 
17850
/* Returns TRUE if ARGS contains a type-dependent expression.  */
17851
 
17852
bool
17853
any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17854
{
17855
  unsigned int i;
17856
  tree arg;
17857
 
17858
  for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17859
    {
17860
      if (type_dependent_expression_p (arg))
17861
        return true;
17862
    }
17863
  return false;
17864
}
17865
 
17866
/* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17867
   expressions) contains any value-dependent expressions.  */
17868
 
17869
bool
17870
any_value_dependent_elements_p (const_tree list)
17871
{
17872
  for (; list; list = TREE_CHAIN (list))
17873
    if (value_dependent_expression_p (TREE_VALUE (list)))
17874
      return true;
17875
 
17876
  return false;
17877
}
17878
 
17879
/* Returns TRUE if the ARG (a template argument) is dependent.  */
17880
 
17881
bool
17882
dependent_template_arg_p (tree arg)
17883
{
17884
  if (!processing_template_decl)
17885
    return false;
17886
 
17887
  if (TREE_CODE (arg) == TEMPLATE_DECL
17888
      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17889
    return dependent_template_p (arg);
17890
  else if (ARGUMENT_PACK_P (arg))
17891
    {
17892
      tree args = ARGUMENT_PACK_ARGS (arg);
17893
      int i, len = TREE_VEC_LENGTH (args);
17894
      for (i = 0; i < len; ++i)
17895
        {
17896
          if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17897
            return true;
17898
        }
17899
 
17900
      return false;
17901
    }
17902
  else if (TYPE_P (arg))
17903
    return dependent_type_p (arg);
17904
  else
17905
    return (type_dependent_expression_p (arg)
17906
            || value_dependent_expression_p (arg));
17907
}
17908
 
17909
/* Returns true if ARGS (a collection of template arguments) contains
17910
   any types that require structural equality testing.  */
17911
 
17912
bool
17913
any_template_arguments_need_structural_equality_p (tree args)
17914
{
17915
  int i;
17916
  int j;
17917
 
17918
  if (!args)
17919
    return false;
17920
  if (args == error_mark_node)
17921
    return true;
17922
 
17923
  for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17924
    {
17925
      tree level = TMPL_ARGS_LEVEL (args, i + 1);
17926
      for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17927
        {
17928
          tree arg = TREE_VEC_ELT (level, j);
17929
          tree packed_args = NULL_TREE;
17930
          int k, len = 1;
17931
 
17932
          if (ARGUMENT_PACK_P (arg))
17933
            {
17934
              /* Look inside the argument pack.  */
17935
              packed_args = ARGUMENT_PACK_ARGS (arg);
17936
              len = TREE_VEC_LENGTH (packed_args);
17937
            }
17938
 
17939
          for (k = 0; k < len; ++k)
17940
            {
17941
              if (packed_args)
17942
                arg = TREE_VEC_ELT (packed_args, k);
17943
 
17944
              if (error_operand_p (arg))
17945
                return true;
17946
              else if (TREE_CODE (arg) == TEMPLATE_DECL
17947
                       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17948
                continue;
17949
              else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17950
                return true;
17951
              else if (!TYPE_P (arg) && TREE_TYPE (arg)
17952
                       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17953
                return true;
17954
            }
17955
        }
17956
    }
17957
 
17958
  return false;
17959
}
17960
 
17961
/* Returns true if ARGS (a collection of template arguments) contains
17962
   any dependent arguments.  */
17963
 
17964
bool
17965
any_dependent_template_arguments_p (const_tree args)
17966
{
17967
  int i;
17968
  int j;
17969
 
17970
  if (!args)
17971
    return false;
17972
  if (args == error_mark_node)
17973
    return true;
17974
 
17975
  for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17976
    {
17977
      const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17978
      for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17979
        if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17980
          return true;
17981
    }
17982
 
17983
  return false;
17984
}
17985
 
17986
/* Returns TRUE if the template TMPL is dependent.  */
17987
 
17988
bool
17989
dependent_template_p (tree tmpl)
17990
{
17991
  if (TREE_CODE (tmpl) == OVERLOAD)
17992
    {
17993
      while (tmpl)
17994
        {
17995
          if (dependent_template_p (OVL_FUNCTION (tmpl)))
17996
            return true;
17997
          tmpl = OVL_CHAIN (tmpl);
17998
        }
17999
      return false;
18000
    }
18001
 
18002
  /* Template template parameters are dependent.  */
18003
  if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18004
      || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18005
    return true;
18006
  /* So are names that have not been looked up.  */
18007
  if (TREE_CODE (tmpl) == SCOPE_REF
18008
      || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18009
    return true;
18010
  /* So are member templates of dependent classes.  */
18011
  if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18012
    return dependent_type_p (DECL_CONTEXT (tmpl));
18013
  return false;
18014
}
18015
 
18016
/* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18017
 
18018
bool
18019
dependent_template_id_p (tree tmpl, tree args)
18020
{
18021
  return (dependent_template_p (tmpl)
18022
          || any_dependent_template_arguments_p (args));
18023
}
18024
 
18025
/* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18026
   is dependent.  */
18027
 
18028
bool
18029
dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18030
{
18031
  int i;
18032
 
18033
  if (!processing_template_decl)
18034
    return false;
18035
 
18036
  for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18037
    {
18038
      tree decl = TREE_VEC_ELT (declv, i);
18039
      tree init = TREE_VEC_ELT (initv, i);
18040
      tree cond = TREE_VEC_ELT (condv, i);
18041
      tree incr = TREE_VEC_ELT (incrv, i);
18042
 
18043
      if (type_dependent_expression_p (decl))
18044
        return true;
18045
 
18046
      if (init && type_dependent_expression_p (init))
18047
        return true;
18048
 
18049
      if (type_dependent_expression_p (cond))
18050
        return true;
18051
 
18052
      if (COMPARISON_CLASS_P (cond)
18053
          && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18054
              || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18055
        return true;
18056
 
18057
      if (TREE_CODE (incr) == MODOP_EXPR)
18058
        {
18059
          if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18060
              || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18061
            return true;
18062
        }
18063
      else if (type_dependent_expression_p (incr))
18064
        return true;
18065
      else if (TREE_CODE (incr) == MODIFY_EXPR)
18066
        {
18067
          if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18068
            return true;
18069
          else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18070
            {
18071
              tree t = TREE_OPERAND (incr, 1);
18072
              if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18073
                  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18074
                return true;
18075
            }
18076
        }
18077
    }
18078
 
18079
  return false;
18080
}
18081
 
18082
/* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18083
   TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18084
   no such TYPE can be found.  Note that this function peers inside
18085
   uninstantiated templates and therefore should be used only in
18086
   extremely limited situations.  ONLY_CURRENT_P restricts this
18087
   peering to the currently open classes hierarchy (which is required
18088
   when comparing types).  */
18089
 
18090
tree
18091
resolve_typename_type (tree type, bool only_current_p)
18092
{
18093
  tree scope;
18094
  tree name;
18095
  tree decl;
18096
  int quals;
18097
  tree pushed_scope;
18098
  tree result;
18099
 
18100
  gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18101
 
18102
  scope = TYPE_CONTEXT (type);
18103
  /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18104
     TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18105
     a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18106
     the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18107
     identifier  of the TYPENAME_TYPE anymore.
18108
     So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18109
     TYPENAME_TYPE instead, we avoid messing up with a possible
18110
     typedef variant case.  */
18111
  name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18112
 
18113
  /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18114
     it first before we can figure out what NAME refers to.  */
18115
  if (TREE_CODE (scope) == TYPENAME_TYPE)
18116
    scope = resolve_typename_type (scope, only_current_p);
18117
  /* If we don't know what SCOPE refers to, then we cannot resolve the
18118
     TYPENAME_TYPE.  */
18119
  if (TREE_CODE (scope) == TYPENAME_TYPE)
18120
    return type;
18121
  /* If the SCOPE is a template type parameter, we have no way of
18122
     resolving the name.  */
18123
  if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18124
    return type;
18125
  /* If the SCOPE is not the current instantiation, there's no reason
18126
     to look inside it.  */
18127
  if (only_current_p && !currently_open_class (scope))
18128
    return type;
18129
  /* If this is a typedef, we don't want to look inside (c++/11987).  */
18130
  if (typedef_variant_p (type))
18131
    return type;
18132
  /* If SCOPE isn't the template itself, it will not have a valid
18133
     TYPE_FIELDS list.  */
18134
  if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18135
    /* scope is either the template itself or a compatible instantiation
18136
       like X<T>, so look up the name in the original template.  */
18137
    scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18138
  else
18139
    /* scope is a partial instantiation, so we can't do the lookup or we
18140
       will lose the template arguments.  */
18141
    return type;
18142
  /* Enter the SCOPE so that name lookup will be resolved as if we
18143
     were in the class definition.  In particular, SCOPE will no
18144
     longer be considered a dependent type.  */
18145
  pushed_scope = push_scope (scope);
18146
  /* Look up the declaration.  */
18147
  decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18148
 
18149
  result = NULL_TREE;
18150
 
18151
  /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18152
     find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18153
  if (!decl)
18154
    /*nop*/;
18155
  else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18156
           && TREE_CODE (decl) == TYPE_DECL)
18157
    {
18158
      result = TREE_TYPE (decl);
18159
      if (result == error_mark_node)
18160
        result = NULL_TREE;
18161
    }
18162
  else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18163
           && DECL_CLASS_TEMPLATE_P (decl))
18164
    {
18165
      tree tmpl;
18166
      tree args;
18167
      /* Obtain the template and the arguments.  */
18168
      tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18169
      args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18170
      /* Instantiate the template.  */
18171
      result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18172
                                      /*entering_scope=*/0,
18173
                                      tf_error | tf_user);
18174
      if (result == error_mark_node)
18175
        result = NULL_TREE;
18176
    }
18177
 
18178
  /* Leave the SCOPE.  */
18179
  if (pushed_scope)
18180
    pop_scope (pushed_scope);
18181
 
18182
  /* If we failed to resolve it, return the original typename.  */
18183
  if (!result)
18184
    return type;
18185
 
18186
  /* If lookup found a typename type, resolve that too.  */
18187
  if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18188
    {
18189
      /* Ill-formed programs can cause infinite recursion here, so we
18190
         must catch that.  */
18191
      TYPENAME_IS_RESOLVING_P (type) = 1;
18192
      result = resolve_typename_type (result, only_current_p);
18193
      TYPENAME_IS_RESOLVING_P (type) = 0;
18194
    }
18195
 
18196
  /* Qualify the resulting type.  */
18197
  quals = cp_type_quals (type);
18198
  if (quals)
18199
    result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18200
 
18201
  return result;
18202
}
18203
 
18204
/* EXPR is an expression which is not type-dependent.  Return a proxy
18205
   for EXPR that can be used to compute the types of larger
18206
   expressions containing EXPR.  */
18207
 
18208
tree
18209
build_non_dependent_expr (tree expr)
18210
{
18211
  tree inner_expr;
18212
 
18213
  /* Preserve null pointer constants so that the type of things like
18214
     "p == 0" where "p" is a pointer can be determined.  */
18215
  if (null_ptr_cst_p (expr))
18216
    return expr;
18217
  /* Preserve OVERLOADs; the functions must be available to resolve
18218
     types.  */
18219
  inner_expr = expr;
18220
  if (TREE_CODE (inner_expr) == STMT_EXPR)
18221
    inner_expr = stmt_expr_value_expr (inner_expr);
18222
  if (TREE_CODE (inner_expr) == ADDR_EXPR)
18223
    inner_expr = TREE_OPERAND (inner_expr, 0);
18224
  if (TREE_CODE (inner_expr) == COMPONENT_REF)
18225
    inner_expr = TREE_OPERAND (inner_expr, 1);
18226
  if (is_overloaded_fn (inner_expr)
18227
      || TREE_CODE (inner_expr) == OFFSET_REF)
18228
    return expr;
18229
  /* There is no need to return a proxy for a variable.  */
18230
  if (TREE_CODE (expr) == VAR_DECL)
18231
    return expr;
18232
  /* Preserve string constants; conversions from string constants to
18233
     "char *" are allowed, even though normally a "const char *"
18234
     cannot be used to initialize a "char *".  */
18235
  if (TREE_CODE (expr) == STRING_CST)
18236
    return expr;
18237
  /* Preserve arithmetic constants, as an optimization -- there is no
18238
     reason to create a new node.  */
18239
  if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18240
    return expr;
18241
  /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18242
     There is at least one place where we want to know that a
18243
     particular expression is a throw-expression: when checking a ?:
18244
     expression, there are special rules if the second or third
18245
     argument is a throw-expression.  */
18246
  if (TREE_CODE (expr) == THROW_EXPR)
18247
    return expr;
18248
 
18249
  if (TREE_CODE (expr) == COND_EXPR)
18250
    return build3 (COND_EXPR,
18251
                   TREE_TYPE (expr),
18252
                   TREE_OPERAND (expr, 0),
18253
                   (TREE_OPERAND (expr, 1)
18254
                    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18255
                    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18256
                   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18257
  if (TREE_CODE (expr) == COMPOUND_EXPR
18258
      && !COMPOUND_EXPR_OVERLOADED (expr))
18259
    return build2 (COMPOUND_EXPR,
18260
                   TREE_TYPE (expr),
18261
                   TREE_OPERAND (expr, 0),
18262
                   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18263
 
18264
  /* If the type is unknown, it can't really be non-dependent */
18265
  gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18266
 
18267
  /* Otherwise, build a NON_DEPENDENT_EXPR.
18268
 
18269
     REFERENCE_TYPEs are not stripped for expressions in templates
18270
     because doing so would play havoc with mangling.  Consider, for
18271
     example:
18272
 
18273
       template <typename T> void f<T& g>() { g(); }
18274
 
18275
     In the body of "f", the expression for "g" will have
18276
     REFERENCE_TYPE, even though the standard says that it should
18277
     not.  The reason is that we must preserve the syntactic form of
18278
     the expression so that mangling (say) "f<g>" inside the body of
18279
     "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18280
     stripped here.  */
18281
  return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18282
}
18283
 
18284
/* ARGS is a vector of expressions as arguments to a function call.
18285
   Replace the arguments with equivalent non-dependent expressions.
18286
   This modifies ARGS in place.  */
18287
 
18288
void
18289
make_args_non_dependent (VEC(tree,gc) *args)
18290
{
18291
  unsigned int ix;
18292
  tree arg;
18293
 
18294
  for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18295
    {
18296
      tree newarg = build_non_dependent_expr (arg);
18297
      if (newarg != arg)
18298
        VEC_replace (tree, args, ix, newarg);
18299
    }
18300
}
18301
 
18302
/* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18303
   with a level one deeper than the actual template parms.  */
18304
 
18305
tree
18306
make_auto (void)
18307
{
18308
  tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18309
  TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18310
                               TYPE_DECL, get_identifier ("auto"), au);
18311
  TYPE_STUB_DECL (au) = TYPE_NAME (au);
18312
  TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18313
    (0, processing_template_decl + 1, processing_template_decl + 1,
18314
     TYPE_NAME (au), NULL_TREE);
18315
  TYPE_CANONICAL (au) = canonical_type_parameter (au);
18316
  DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18317
  SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18318
 
18319
  return au;
18320
}
18321
 
18322
/* Given type ARG, return std::initializer_list<ARG>.  */
18323
 
18324
static tree
18325
listify (tree arg)
18326
{
18327
  tree std_init_list = namespace_binding
18328
    (get_identifier ("initializer_list"), std_node);
18329
  tree argvec;
18330
  if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18331
    {
18332
      error ("deducing from brace-enclosed initializer list requires "
18333
             "#include <initializer_list>");
18334
      return error_mark_node;
18335
    }
18336
  argvec = make_tree_vec (1);
18337
  TREE_VEC_ELT (argvec, 0) = arg;
18338
  return lookup_template_class (std_init_list, argvec, NULL_TREE,
18339
                                NULL_TREE, 0, tf_warning_or_error);
18340
}
18341
 
18342
/* Replace auto in TYPE with std::initializer_list<auto>.  */
18343
 
18344
static tree
18345
listify_autos (tree type, tree auto_node)
18346
{
18347
  tree init_auto = listify (auto_node);
18348
  tree argvec = make_tree_vec (1);
18349
  TREE_VEC_ELT (argvec, 0) = init_auto;
18350
  if (processing_template_decl)
18351
    argvec = add_to_template_args (current_template_args (), argvec);
18352
  return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18353
}
18354
 
18355
/* walk_tree helper for do_auto_deduction.  */
18356
 
18357
static tree
18358
contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18359
                 void *type)
18360
{
18361
  /* Is this a variable with the type we're looking for?  */
18362
  if (DECL_P (*tp)
18363
      && TREE_TYPE (*tp) == type)
18364
    return *tp;
18365
  else
18366
    return NULL_TREE;
18367
}
18368
 
18369
/* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18370
   from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18371
 
18372
tree
18373
do_auto_deduction (tree type, tree init, tree auto_node)
18374
{
18375
  tree parms, tparms, targs;
18376
  tree args[1];
18377
  tree decl;
18378
  int val;
18379
 
18380
  /* The name of the object being declared shall not appear in the
18381
     initializer expression.  */
18382
  decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18383
  if (decl)
18384
    {
18385
      error ("variable %q#D with %<auto%> type used in its own "
18386
             "initializer", decl);
18387
      return error_mark_node;
18388
    }
18389
 
18390
  /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18391
     with either a new invented type template parameter U or, if the
18392
     initializer is a braced-init-list (8.5.4), with
18393
     std::initializer_list<U>.  */
18394
  if (BRACE_ENCLOSED_INITIALIZER_P (init))
18395
    type = listify_autos (type, auto_node);
18396
 
18397
  parms = build_tree_list (NULL_TREE, type);
18398
  args[0] = init;
18399
  tparms = make_tree_vec (1);
18400
  targs = make_tree_vec (1);
18401
  TREE_VEC_ELT (tparms, 0)
18402
    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18403
  val = type_unification_real (tparms, targs, parms, args, 1, 0,
18404
                               DEDUCE_CALL, LOOKUP_NORMAL);
18405
  if (val > 0)
18406
    {
18407
      error ("unable to deduce %qT from %qE", type, init);
18408
      return error_mark_node;
18409
    }
18410
 
18411
  /* If the list of declarators contains more than one declarator, the type
18412
     of each declared variable is determined as described above. If the
18413
     type deduced for the template parameter U is not the same in each
18414
     deduction, the program is ill-formed.  */
18415
  if (TREE_TYPE (auto_node)
18416
      && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18417
    {
18418
      error ("inconsistent deduction for %qT: %qT and then %qT",
18419
             auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18420
      return error_mark_node;
18421
    }
18422
  TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18423
 
18424
  if (processing_template_decl)
18425
    targs = add_to_template_args (current_template_args (), targs);
18426
  return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18427
}
18428
 
18429
/* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18430
   result.  */
18431
 
18432
tree
18433
splice_late_return_type (tree type, tree late_return_type)
18434
{
18435
  tree argvec;
18436
 
18437
  if (late_return_type == NULL_TREE)
18438
    return type;
18439
  argvec = make_tree_vec (1);
18440
  TREE_VEC_ELT (argvec, 0) = late_return_type;
18441
  if (processing_template_decl)
18442
    argvec = add_to_template_args (current_template_args (), argvec);
18443
  return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18444
}
18445
 
18446
/* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18447
 
18448
bool
18449
is_auto (const_tree type)
18450
{
18451
  if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18452
      && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18453
    return true;
18454
  else
18455
    return false;
18456
}
18457
 
18458
/* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18459
   appear as a type-specifier for the declaration in question, we don't
18460
   have to look through the whole type.  */
18461
 
18462
tree
18463
type_uses_auto (tree type)
18464
{
18465
  enum tree_code code;
18466
  if (is_auto (type))
18467
    return type;
18468
 
18469
  code = TREE_CODE (type);
18470
 
18471
  if (code == POINTER_TYPE || code == REFERENCE_TYPE
18472
      || code == OFFSET_TYPE || code == FUNCTION_TYPE
18473
      || code == METHOD_TYPE || code == ARRAY_TYPE)
18474
    return type_uses_auto (TREE_TYPE (type));
18475
 
18476
  if (TYPE_PTRMEMFUNC_P (type))
18477
    return type_uses_auto (TREE_TYPE (TREE_TYPE
18478
                                   (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18479
 
18480
  return NULL_TREE;
18481
}
18482
 
18483
/* For a given template T, return the vector of typedefs referenced
18484
   in T for which access check is needed at T instantiation time.
18485
   T is either  a FUNCTION_DECL or a RECORD_TYPE.
18486
   Those typedefs were added to T by the function
18487
   append_type_to_template_for_access_check.  */
18488
 
18489
VEC(qualified_typedef_usage_t,gc)*
18490
get_types_needing_access_check (tree t)
18491
{
18492
  tree ti;
18493
  VEC(qualified_typedef_usage_t,gc) *result = NULL;
18494
 
18495
  if (!t || t == error_mark_node)
18496
    return NULL;
18497
 
18498
  if (!(ti = get_template_info (t)))
18499
    return NULL;
18500
 
18501
  if (CLASS_TYPE_P (t)
18502
      || TREE_CODE (t) == FUNCTION_DECL)
18503
    {
18504
      if (!TI_TEMPLATE (ti))
18505
        return NULL;
18506
 
18507
      result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18508
    }
18509
 
18510
  return result;
18511
}
18512
 
18513
/* Append the typedef TYPE_DECL used in template T to a list of typedefs
18514
   tied to T. That list of typedefs will be access checked at
18515
   T instantiation time.
18516
   T is either a FUNCTION_DECL or a RECORD_TYPE.
18517
   TYPE_DECL is a TYPE_DECL node representing a typedef.
18518
   SCOPE is the scope through which TYPE_DECL is accessed.
18519
   LOCATION is the location of the usage point of TYPE_DECL.
18520
 
18521
   This function is a subroutine of
18522
   append_type_to_template_for_access_check.  */
18523
 
18524
static void
18525
append_type_to_template_for_access_check_1 (tree t,
18526
                                            tree type_decl,
18527
                                            tree scope,
18528
                                            location_t location)
18529
{
18530
  qualified_typedef_usage_t typedef_usage;
18531
  tree ti;
18532
 
18533
  if (!t || t == error_mark_node)
18534
    return;
18535
 
18536
  gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18537
               || CLASS_TYPE_P (t))
18538
              && type_decl
18539
              && TREE_CODE (type_decl) == TYPE_DECL
18540
              && scope);
18541
 
18542
  if (!(ti = get_template_info (t)))
18543
    return;
18544
 
18545
  gcc_assert (TI_TEMPLATE (ti));
18546
 
18547
  typedef_usage.typedef_decl = type_decl;
18548
  typedef_usage.context = scope;
18549
  typedef_usage.locus = location;
18550
 
18551
  VEC_safe_push (qualified_typedef_usage_t, gc,
18552
                 TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18553
                 &typedef_usage);
18554
}
18555
 
18556
/* Append TYPE_DECL to the template TEMPL.
18557
   TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18558
   At TEMPL instanciation time, TYPE_DECL will be checked to see
18559
   if it can be accessed through SCOPE.
18560
   LOCATION is the location of the usage point of TYPE_DECL.
18561
 
18562
   e.g. consider the following code snippet:
18563
 
18564
     class C
18565
     {
18566
       typedef int myint;
18567
     };
18568
 
18569
     template<class U> struct S
18570
     {
18571
       C::myint mi; // <-- usage point of the typedef C::myint
18572
     };
18573
 
18574
     S<char> s;
18575
 
18576
   At S<char> instantiation time, we need to check the access of C::myint
18577
   In other words, we need to check the access of the myint typedef through
18578
   the C scope. For that purpose, this function will add the myint typedef
18579
   and the scope C through which its being accessed to a list of typedefs
18580
   tied to the template S. That list will be walked at template instantiation
18581
   time and access check performed on each typedefs it contains.
18582
   Note that this particular code snippet should yield an error because
18583
   myint is private to C.  */
18584
 
18585
void
18586
append_type_to_template_for_access_check (tree templ,
18587
                                          tree type_decl,
18588
                                          tree scope,
18589
                                          location_t location)
18590
{
18591
  qualified_typedef_usage_t *iter;
18592
  int i;
18593
 
18594
  gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18595
 
18596
  /* Make sure we don't append the type to the template twice.  */
18597
  for (i = 0;
18598
       VEC_iterate (qualified_typedef_usage_t,
18599
                    get_types_needing_access_check (templ),
18600
                    i, iter);
18601
       ++i)
18602
    if (iter->typedef_decl == type_decl && scope == iter->context)
18603
      return;
18604
 
18605
  append_type_to_template_for_access_check_1 (templ, type_decl,
18606
                                              scope, location);
18607
}
18608
 
18609
/* Set up the hash tables for template instantiations.  */
18610
 
18611
void
18612
init_template_processing (void)
18613
{
18614
  decl_specializations = htab_create_ggc (37,
18615
                                          hash_specialization,
18616
                                          eq_specializations,
18617
                                          ggc_free);
18618
  type_specializations = htab_create_ggc (37,
18619
                                          hash_specialization,
18620
                                          eq_specializations,
18621
                                          ggc_free);
18622
}
18623
 
18624
#include "gt-cp-pt.h"

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.