Implemented Cilk Plus Array Notation for C++
[platform/upstream/gcc.git] / gcc / cp / semantics.c
1 /* Perform the semantic phase of parsing, i.e., the process of
2    building tree structure, checking semantic consistency, and
3    building RTL.  These routines are used both during actual parsing
4    and during the instantiation of template functions.
5
6    Copyright (C) 1998-2013 Free Software Foundation, Inc.
7    Written by Mark Mitchell (mmitchell@usa.net) based on code found
8    formerly in parse.y and pt.c.
9
10    This file is part of GCC.
11
12    GCC is free software; you can redistribute it and/or modify it
13    under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3, or (at your option)
15    any later version.
16
17    GCC is distributed in the hope that it will be useful, but
18    WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20    General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with GCC; see the file COPYING3.  If not see
24 <http://www.gnu.org/licenses/>.  */
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "tree.h"
31 #include "cp-tree.h"
32 #include "c-family/c-common.h"
33 #include "c-family/c-objc.h"
34 #include "tree-inline.h"
35 #include "intl.h"
36 #include "toplev.h"
37 #include "flags.h"
38 #include "timevar.h"
39 #include "diagnostic.h"
40 #include "cgraph.h"
41 #include "tree-iterator.h"
42 #include "vec.h"
43 #include "target.h"
44 #include "gimple.h"
45 #include "bitmap.h"
46 #include "hash-table.h"
47
48 static bool verify_constant (tree, bool, bool *, bool *);
49 #define VERIFY_CONSTANT(X)                                              \
50 do {                                                                    \
51   if (verify_constant ((X), allow_non_constant, non_constant_p, overflow_p)) \
52     return t;                                                           \
53  } while (0)
54
55 /* There routines provide a modular interface to perform many parsing
56    operations.  They may therefore be used during actual parsing, or
57    during template instantiation, which may be regarded as a
58    degenerate form of parsing.  */
59
60 static tree maybe_convert_cond (tree);
61 static tree finalize_nrv_r (tree *, int *, void *);
62 static tree capture_decltype (tree);
63
64
65 /* Deferred Access Checking Overview
66    ---------------------------------
67
68    Most C++ expressions and declarations require access checking
69    to be performed during parsing.  However, in several cases,
70    this has to be treated differently.
71
72    For member declarations, access checking has to be deferred
73    until more information about the declaration is known.  For
74    example:
75
76      class A {
77          typedef int X;
78        public:
79          X f();
80      };
81
82      A::X A::f();
83      A::X g();
84
85    When we are parsing the function return type `A::X', we don't
86    really know if this is allowed until we parse the function name.
87
88    Furthermore, some contexts require that access checking is
89    never performed at all.  These include class heads, and template
90    instantiations.
91
92    Typical use of access checking functions is described here:
93
94    1. When we enter a context that requires certain access checking
95       mode, the function `push_deferring_access_checks' is called with
96       DEFERRING argument specifying the desired mode.  Access checking
97       may be performed immediately (dk_no_deferred), deferred
98       (dk_deferred), or not performed (dk_no_check).
99
100    2. When a declaration such as a type, or a variable, is encountered,
101       the function `perform_or_defer_access_check' is called.  It
102       maintains a vector of all deferred checks.
103
104    3. The global `current_class_type' or `current_function_decl' is then
105       setup by the parser.  `enforce_access' relies on these information
106       to check access.
107
108    4. Upon exiting the context mentioned in step 1,
109       `perform_deferred_access_checks' is called to check all declaration
110       stored in the vector. `pop_deferring_access_checks' is then
111       called to restore the previous access checking mode.
112
113       In case of parsing error, we simply call `pop_deferring_access_checks'
114       without `perform_deferred_access_checks'.  */
115
116 typedef struct GTY(()) deferred_access {
117   /* A vector representing name-lookups for which we have deferred
118      checking access controls.  We cannot check the accessibility of
119      names used in a decl-specifier-seq until we know what is being
120      declared because code like:
121
122        class A {
123          class B {};
124          B* f();
125        }
126
127        A::B* A::f() { return 0; }
128
129      is valid, even though `A::B' is not generally accessible.  */
130   vec<deferred_access_check, va_gc> * GTY(()) deferred_access_checks;
131
132   /* The current mode of access checks.  */
133   enum deferring_kind deferring_access_checks_kind;
134
135 } deferred_access;
136
137 /* Data for deferred access checking.  */
138 static GTY(()) vec<deferred_access, va_gc> *deferred_access_stack;
139 static GTY(()) unsigned deferred_access_no_check;
140
141 /* Save the current deferred access states and start deferred
142    access checking iff DEFER_P is true.  */
143
144 void
145 push_deferring_access_checks (deferring_kind deferring)
146 {
147   /* For context like template instantiation, access checking
148      disabling applies to all nested context.  */
149   if (deferred_access_no_check || deferring == dk_no_check)
150     deferred_access_no_check++;
151   else
152     {
153       deferred_access e = {NULL, deferring};
154       vec_safe_push (deferred_access_stack, e);
155     }
156 }
157
158 /* Resume deferring access checks again after we stopped doing
159    this previously.  */
160
161 void
162 resume_deferring_access_checks (void)
163 {
164   if (!deferred_access_no_check)
165     deferred_access_stack->last().deferring_access_checks_kind = dk_deferred;
166 }
167
168 /* Stop deferring access checks.  */
169
170 void
171 stop_deferring_access_checks (void)
172 {
173   if (!deferred_access_no_check)
174     deferred_access_stack->last().deferring_access_checks_kind = dk_no_deferred;
175 }
176
177 /* Discard the current deferred access checks and restore the
178    previous states.  */
179
180 void
181 pop_deferring_access_checks (void)
182 {
183   if (deferred_access_no_check)
184     deferred_access_no_check--;
185   else
186     deferred_access_stack->pop ();
187 }
188
189 /* Returns a TREE_LIST representing the deferred checks.
190    The TREE_PURPOSE of each node is the type through which the
191    access occurred; the TREE_VALUE is the declaration named.
192    */
193
194 vec<deferred_access_check, va_gc> *
195 get_deferred_access_checks (void)
196 {
197   if (deferred_access_no_check)
198     return NULL;
199   else
200     return (deferred_access_stack->last().deferred_access_checks);
201 }
202
203 /* Take current deferred checks and combine with the
204    previous states if we also defer checks previously.
205    Otherwise perform checks now.  */
206
207 void
208 pop_to_parent_deferring_access_checks (void)
209 {
210   if (deferred_access_no_check)
211     deferred_access_no_check--;
212   else
213     {
214       vec<deferred_access_check, va_gc> *checks;
215       deferred_access *ptr;
216
217       checks = (deferred_access_stack->last ().deferred_access_checks);
218
219       deferred_access_stack->pop ();
220       ptr = &deferred_access_stack->last ();
221       if (ptr->deferring_access_checks_kind == dk_no_deferred)
222         {
223           /* Check access.  */
224           perform_access_checks (checks, tf_warning_or_error);
225         }
226       else
227         {
228           /* Merge with parent.  */
229           int i, j;
230           deferred_access_check *chk, *probe;
231
232           FOR_EACH_VEC_SAFE_ELT (checks, i, chk)
233             {
234               FOR_EACH_VEC_SAFE_ELT (ptr->deferred_access_checks, j, probe)
235                 {
236                   if (probe->binfo == chk->binfo &&
237                       probe->decl == chk->decl &&
238                       probe->diag_decl == chk->diag_decl)
239                     goto found;
240                 }
241               /* Insert into parent's checks.  */
242               vec_safe_push (ptr->deferred_access_checks, *chk);
243             found:;
244             }
245         }
246     }
247 }
248
249 /* Perform the access checks in CHECKS.  The TREE_PURPOSE of each node
250    is the BINFO indicating the qualifying scope used to access the
251    DECL node stored in the TREE_VALUE of the node.  If CHECKS is empty
252    or we aren't in SFINAE context or all the checks succeed return TRUE,
253    otherwise FALSE.  */
254
255 bool
256 perform_access_checks (vec<deferred_access_check, va_gc> *checks,
257                        tsubst_flags_t complain)
258 {
259   int i;
260   deferred_access_check *chk;
261   location_t loc = input_location;
262   bool ok = true;
263
264   if (!checks)
265     return true;
266
267   FOR_EACH_VEC_SAFE_ELT (checks, i, chk)
268     {
269       input_location = chk->loc;
270       ok &= enforce_access (chk->binfo, chk->decl, chk->diag_decl, complain);
271     }
272
273   input_location = loc;
274   return (complain & tf_error) ? true : ok;
275 }
276
277 /* Perform the deferred access checks.
278
279    After performing the checks, we still have to keep the list
280    `deferred_access_stack->deferred_access_checks' since we may want
281    to check access for them again later in a different context.
282    For example:
283
284      class A {
285        typedef int X;
286        static X a;
287      };
288      A::X A::a, x;      // No error for `A::a', error for `x'
289
290    We have to perform deferred access of `A::X', first with `A::a',
291    next with `x'.  Return value like perform_access_checks above.  */
292
293 bool
294 perform_deferred_access_checks (tsubst_flags_t complain)
295 {
296   return perform_access_checks (get_deferred_access_checks (), complain);
297 }
298
299 /* Defer checking the accessibility of DECL, when looked up in
300    BINFO. DIAG_DECL is the declaration to use to print diagnostics.
301    Return value like perform_access_checks above.  */
302
303 bool
304 perform_or_defer_access_check (tree binfo, tree decl, tree diag_decl,
305                                tsubst_flags_t complain)
306 {
307   int i;
308   deferred_access *ptr;
309   deferred_access_check *chk;
310
311
312   /* Exit if we are in a context that no access checking is performed.
313      */
314   if (deferred_access_no_check)
315     return true;
316
317   gcc_assert (TREE_CODE (binfo) == TREE_BINFO);
318
319   ptr = &deferred_access_stack->last ();
320
321   /* If we are not supposed to defer access checks, just check now.  */
322   if (ptr->deferring_access_checks_kind == dk_no_deferred)
323     {
324       bool ok = enforce_access (binfo, decl, diag_decl, complain);
325       return (complain & tf_error) ? true : ok;
326     }
327
328   /* See if we are already going to perform this check.  */
329   FOR_EACH_VEC_SAFE_ELT (ptr->deferred_access_checks, i, chk)
330     {
331       if (chk->decl == decl && chk->binfo == binfo &&
332           chk->diag_decl == diag_decl)
333         {
334           return true;
335         }
336     }
337   /* If not, record the check.  */
338   deferred_access_check new_access = {binfo, decl, diag_decl, input_location};
339   vec_safe_push (ptr->deferred_access_checks, new_access);
340
341   return true;
342 }
343
344 /* Returns nonzero if the current statement is a full expression,
345    i.e. temporaries created during that statement should be destroyed
346    at the end of the statement.  */
347
348 int
349 stmts_are_full_exprs_p (void)
350 {
351   return current_stmt_tree ()->stmts_are_full_exprs_p;
352 }
353
354 /* T is a statement.  Add it to the statement-tree.  This is the C++
355    version.  The C/ObjC frontends have a slightly different version of
356    this function.  */
357
358 tree
359 add_stmt (tree t)
360 {
361   enum tree_code code = TREE_CODE (t);
362
363   if (EXPR_P (t) && code != LABEL_EXPR)
364     {
365       if (!EXPR_HAS_LOCATION (t))
366         SET_EXPR_LOCATION (t, input_location);
367
368       /* When we expand a statement-tree, we must know whether or not the
369          statements are full-expressions.  We record that fact here.  */
370       STMT_IS_FULL_EXPR_P (t) = stmts_are_full_exprs_p ();
371     }
372
373   /* Add T to the statement-tree.  Non-side-effect statements need to be
374      recorded during statement expressions.  */
375   gcc_checking_assert (!stmt_list_stack->is_empty ());
376   append_to_statement_list_force (t, &cur_stmt_list);
377
378   return t;
379 }
380
381 /* Returns the stmt_tree to which statements are currently being added.  */
382
383 stmt_tree
384 current_stmt_tree (void)
385 {
386   return (cfun
387           ? &cfun->language->base.x_stmt_tree
388           : &scope_chain->x_stmt_tree);
389 }
390
391 /* If statements are full expressions, wrap STMT in a CLEANUP_POINT_EXPR.  */
392
393 static tree
394 maybe_cleanup_point_expr (tree expr)
395 {
396   if (!processing_template_decl && stmts_are_full_exprs_p ())
397     expr = fold_build_cleanup_point_expr (TREE_TYPE (expr), expr);
398   return expr;
399 }
400
401 /* Like maybe_cleanup_point_expr except have the type of the new expression be
402    void so we don't need to create a temporary variable to hold the inner
403    expression.  The reason why we do this is because the original type might be
404    an aggregate and we cannot create a temporary variable for that type.  */
405
406 tree
407 maybe_cleanup_point_expr_void (tree expr)
408 {
409   if (!processing_template_decl && stmts_are_full_exprs_p ())
410     expr = fold_build_cleanup_point_expr (void_type_node, expr);
411   return expr;
412 }
413
414
415
416 /* Create a declaration statement for the declaration given by the DECL.  */
417
418 void
419 add_decl_expr (tree decl)
420 {
421   tree r = build_stmt (input_location, DECL_EXPR, decl);
422   if (DECL_INITIAL (decl)
423       || (DECL_SIZE (decl) && TREE_SIDE_EFFECTS (DECL_SIZE (decl))))
424     r = maybe_cleanup_point_expr_void (r);
425   add_stmt (r);
426 }
427
428 /* Finish a scope.  */
429
430 tree
431 do_poplevel (tree stmt_list)
432 {
433   tree block = NULL;
434
435   if (stmts_are_full_exprs_p ())
436     block = poplevel (kept_level_p (), 1, 0);
437
438   stmt_list = pop_stmt_list (stmt_list);
439
440   if (!processing_template_decl)
441     {
442       stmt_list = c_build_bind_expr (input_location, block, stmt_list);
443       /* ??? See c_end_compound_stmt re statement expressions.  */
444     }
445
446   return stmt_list;
447 }
448
449 /* Begin a new scope.  */
450
451 static tree
452 do_pushlevel (scope_kind sk)
453 {
454   tree ret = push_stmt_list ();
455   if (stmts_are_full_exprs_p ())
456     begin_scope (sk, NULL);
457   return ret;
458 }
459
460 /* Queue a cleanup.  CLEANUP is an expression/statement to be executed
461    when the current scope is exited.  EH_ONLY is true when this is not
462    meant to apply to normal control flow transfer.  */
463
464 void
465 push_cleanup (tree decl, tree cleanup, bool eh_only)
466 {
467   tree stmt = build_stmt (input_location, CLEANUP_STMT, NULL, cleanup, decl);
468   CLEANUP_EH_ONLY (stmt) = eh_only;
469   add_stmt (stmt);
470   CLEANUP_BODY (stmt) = push_stmt_list ();
471 }
472
473 /* Begin a conditional that might contain a declaration.  When generating
474    normal code, we want the declaration to appear before the statement
475    containing the conditional.  When generating template code, we want the
476    conditional to be rendered as the raw DECL_EXPR.  */
477
478 static void
479 begin_cond (tree *cond_p)
480 {
481   if (processing_template_decl)
482     *cond_p = push_stmt_list ();
483 }
484
485 /* Finish such a conditional.  */
486
487 static void
488 finish_cond (tree *cond_p, tree expr)
489 {
490   if (processing_template_decl)
491     {
492       tree cond = pop_stmt_list (*cond_p);
493
494       if (expr == NULL_TREE)
495         /* Empty condition in 'for'.  */
496         gcc_assert (empty_expr_stmt_p (cond));
497       else if (check_for_bare_parameter_packs (expr))
498         expr = error_mark_node;
499       else if (!empty_expr_stmt_p (cond))
500         expr = build2 (COMPOUND_EXPR, TREE_TYPE (expr), cond, expr);
501     }
502   *cond_p = expr;
503 }
504
505 /* If *COND_P specifies a conditional with a declaration, transform the
506    loop such that
507             while (A x = 42) { }
508             for (; A x = 42;) { }
509    becomes
510             while (true) { A x = 42; if (!x) break; }
511             for (;;) { A x = 42; if (!x) break; }
512    The statement list for BODY will be empty if the conditional did
513    not declare anything.  */
514
515 static void
516 simplify_loop_decl_cond (tree *cond_p, tree body)
517 {
518   tree cond, if_stmt;
519
520   if (!TREE_SIDE_EFFECTS (body))
521     return;
522
523   cond = *cond_p;
524   *cond_p = boolean_true_node;
525
526   if_stmt = begin_if_stmt ();
527   cond = cp_build_unary_op (TRUTH_NOT_EXPR, cond, 0, tf_warning_or_error);
528   finish_if_stmt_cond (cond, if_stmt);
529   finish_break_stmt ();
530   finish_then_clause (if_stmt);
531   finish_if_stmt (if_stmt);
532 }
533
534 /* Finish a goto-statement.  */
535
536 tree
537 finish_goto_stmt (tree destination)
538 {
539   if (identifier_p (destination))
540     destination = lookup_label (destination);
541
542   /* We warn about unused labels with -Wunused.  That means we have to
543      mark the used labels as used.  */
544   if (TREE_CODE (destination) == LABEL_DECL)
545     TREE_USED (destination) = 1;
546   else
547     {
548       destination = mark_rvalue_use (destination);
549       if (!processing_template_decl)
550         {
551           destination = cp_convert (ptr_type_node, destination,
552                                     tf_warning_or_error);
553           if (error_operand_p (destination))
554             return NULL_TREE;
555           destination
556             = fold_build_cleanup_point_expr (TREE_TYPE (destination),
557                                              destination);
558         }
559     }
560
561   check_goto (destination);
562
563   return add_stmt (build_stmt (input_location, GOTO_EXPR, destination));
564 }
565
566 /* COND is the condition-expression for an if, while, etc.,
567    statement.  Convert it to a boolean value, if appropriate.
568    In addition, verify sequence points if -Wsequence-point is enabled.  */
569
570 static tree
571 maybe_convert_cond (tree cond)
572 {
573   /* Empty conditions remain empty.  */
574   if (!cond)
575     return NULL_TREE;
576
577   /* Wait until we instantiate templates before doing conversion.  */
578   if (processing_template_decl)
579     return cond;
580
581   if (warn_sequence_point)
582     verify_sequence_points (cond);
583
584   /* Do the conversion.  */
585   cond = convert_from_reference (cond);
586
587   if (TREE_CODE (cond) == MODIFY_EXPR
588       && !TREE_NO_WARNING (cond)
589       && warn_parentheses)
590     {
591       warning (OPT_Wparentheses,
592                "suggest parentheses around assignment used as truth value");
593       TREE_NO_WARNING (cond) = 1;
594     }
595
596   return condition_conversion (cond);
597 }
598
599 /* Finish an expression-statement, whose EXPRESSION is as indicated.  */
600
601 tree
602 finish_expr_stmt (tree expr)
603 {
604   tree r = NULL_TREE;
605
606   if (expr != NULL_TREE)
607     {
608       if (!processing_template_decl)
609         {
610           if (warn_sequence_point)
611             verify_sequence_points (expr);
612           expr = convert_to_void (expr, ICV_STATEMENT, tf_warning_or_error);
613         }
614       else if (!type_dependent_expression_p (expr))
615         convert_to_void (build_non_dependent_expr (expr), ICV_STATEMENT, 
616                          tf_warning_or_error);
617
618       if (check_for_bare_parameter_packs (expr))
619         expr = error_mark_node;
620
621       /* Simplification of inner statement expressions, compound exprs,
622          etc can result in us already having an EXPR_STMT.  */
623       if (TREE_CODE (expr) != CLEANUP_POINT_EXPR)
624         {
625           if (TREE_CODE (expr) != EXPR_STMT)
626             expr = build_stmt (input_location, EXPR_STMT, expr);
627           expr = maybe_cleanup_point_expr_void (expr);
628         }
629
630       r = add_stmt (expr);
631     }
632
633   finish_stmt ();
634
635   return r;
636 }
637
638
639 /* Begin an if-statement.  Returns a newly created IF_STMT if
640    appropriate.  */
641
642 tree
643 begin_if_stmt (void)
644 {
645   tree r, scope;
646   scope = do_pushlevel (sk_cond);
647   r = build_stmt (input_location, IF_STMT, NULL_TREE,
648                   NULL_TREE, NULL_TREE, scope);
649   begin_cond (&IF_COND (r));
650   return r;
651 }
652
653 /* Process the COND of an if-statement, which may be given by
654    IF_STMT.  */
655
656 void
657 finish_if_stmt_cond (tree cond, tree if_stmt)
658 {
659   finish_cond (&IF_COND (if_stmt), maybe_convert_cond (cond));
660   add_stmt (if_stmt);
661   THEN_CLAUSE (if_stmt) = push_stmt_list ();
662 }
663
664 /* Finish the then-clause of an if-statement, which may be given by
665    IF_STMT.  */
666
667 tree
668 finish_then_clause (tree if_stmt)
669 {
670   THEN_CLAUSE (if_stmt) = pop_stmt_list (THEN_CLAUSE (if_stmt));
671   return if_stmt;
672 }
673
674 /* Begin the else-clause of an if-statement.  */
675
676 void
677 begin_else_clause (tree if_stmt)
678 {
679   ELSE_CLAUSE (if_stmt) = push_stmt_list ();
680 }
681
682 /* Finish the else-clause of an if-statement, which may be given by
683    IF_STMT.  */
684
685 void
686 finish_else_clause (tree if_stmt)
687 {
688   ELSE_CLAUSE (if_stmt) = pop_stmt_list (ELSE_CLAUSE (if_stmt));
689 }
690
691 /* Finish an if-statement.  */
692
693 void
694 finish_if_stmt (tree if_stmt)
695 {
696   tree scope = IF_SCOPE (if_stmt);
697   IF_SCOPE (if_stmt) = NULL;
698   add_stmt (do_poplevel (scope));
699   finish_stmt ();
700 }
701
702 /* Begin a while-statement.  Returns a newly created WHILE_STMT if
703    appropriate.  */
704
705 tree
706 begin_while_stmt (void)
707 {
708   tree r;
709   r = build_stmt (input_location, WHILE_STMT, NULL_TREE, NULL_TREE);
710   add_stmt (r);
711   WHILE_BODY (r) = do_pushlevel (sk_block);
712   begin_cond (&WHILE_COND (r));
713   return r;
714 }
715
716 /* Process the COND of a while-statement, which may be given by
717    WHILE_STMT.  */
718
719 void
720 finish_while_stmt_cond (tree cond, tree while_stmt)
721 {
722   finish_cond (&WHILE_COND (while_stmt), maybe_convert_cond (cond));
723   simplify_loop_decl_cond (&WHILE_COND (while_stmt), WHILE_BODY (while_stmt));
724 }
725
726 /* Finish a while-statement, which may be given by WHILE_STMT.  */
727
728 void
729 finish_while_stmt (tree while_stmt)
730 {
731   WHILE_BODY (while_stmt) = do_poplevel (WHILE_BODY (while_stmt));
732   finish_stmt ();
733 }
734
735 /* Begin a do-statement.  Returns a newly created DO_STMT if
736    appropriate.  */
737
738 tree
739 begin_do_stmt (void)
740 {
741   tree r = build_stmt (input_location, DO_STMT, NULL_TREE, NULL_TREE);
742   add_stmt (r);
743   DO_BODY (r) = push_stmt_list ();
744   return r;
745 }
746
747 /* Finish the body of a do-statement, which may be given by DO_STMT.  */
748
749 void
750 finish_do_body (tree do_stmt)
751 {
752   tree body = DO_BODY (do_stmt) = pop_stmt_list (DO_BODY (do_stmt));
753
754   if (TREE_CODE (body) == STATEMENT_LIST && STATEMENT_LIST_TAIL (body))
755     body = STATEMENT_LIST_TAIL (body)->stmt;
756
757   if (IS_EMPTY_STMT (body))
758     warning (OPT_Wempty_body,
759             "suggest explicit braces around empty body in %<do%> statement");
760 }
761
762 /* Finish a do-statement, which may be given by DO_STMT, and whose
763    COND is as indicated.  */
764
765 void
766 finish_do_stmt (tree cond, tree do_stmt)
767 {
768   cond = maybe_convert_cond (cond);
769   DO_COND (do_stmt) = cond;
770   finish_stmt ();
771 }
772
773 /* Finish a return-statement.  The EXPRESSION returned, if any, is as
774    indicated.  */
775
776 tree
777 finish_return_stmt (tree expr)
778 {
779   tree r;
780   bool no_warning;
781
782   if (flag_enable_cilkplus && contains_array_notation_expr (expr))
783     {
784       size_t rank = 0;
785       
786       if (!find_rank (input_location, expr, expr, false, &rank))
787         return error_mark_node;
788
789       /* If the return expression contains array notations, then flag it as
790          error.  */
791       if (rank >= 1)
792         {
793           error_at (input_location, "array notation expression cannot be "
794                     "used as a return value");
795           return error_mark_node;
796         }
797     }
798   expr = check_return_expr (expr, &no_warning);
799
800   if (flag_openmp && !check_omp_return ())
801     return error_mark_node;
802   if (!processing_template_decl)
803     {
804       if (warn_sequence_point)
805         verify_sequence_points (expr);
806       
807       if (DECL_DESTRUCTOR_P (current_function_decl)
808           || (DECL_CONSTRUCTOR_P (current_function_decl)
809               && targetm.cxx.cdtor_returns_this ()))
810         {
811           /* Similarly, all destructors must run destructors for
812              base-classes before returning.  So, all returns in a
813              destructor get sent to the DTOR_LABEL; finish_function emits
814              code to return a value there.  */
815           return finish_goto_stmt (cdtor_label);
816         }
817     }
818
819   r = build_stmt (input_location, RETURN_EXPR, expr);
820   TREE_NO_WARNING (r) |= no_warning;
821   r = maybe_cleanup_point_expr_void (r);
822   r = add_stmt (r);
823   finish_stmt ();
824
825   return r;
826 }
827
828 /* Begin the scope of a for-statement or a range-for-statement.
829    Both the returned trees are to be used in a call to
830    begin_for_stmt or begin_range_for_stmt.  */
831
832 tree
833 begin_for_scope (tree *init)
834 {
835   tree scope = NULL_TREE;
836   if (flag_new_for_scope > 0)
837     scope = do_pushlevel (sk_for);
838
839   if (processing_template_decl)
840     *init = push_stmt_list ();
841   else
842     *init = NULL_TREE;
843
844   return scope;
845 }
846
847 /* Begin a for-statement.  Returns a new FOR_STMT.
848    SCOPE and INIT should be the return of begin_for_scope,
849    or both NULL_TREE  */
850
851 tree
852 begin_for_stmt (tree scope, tree init)
853 {
854   tree r;
855
856   r = build_stmt (input_location, FOR_STMT, NULL_TREE, NULL_TREE,
857                   NULL_TREE, NULL_TREE, NULL_TREE);
858
859   if (scope == NULL_TREE)
860     {
861       gcc_assert (!init || !(flag_new_for_scope > 0));
862       if (!init)
863         scope = begin_for_scope (&init);
864     }
865   FOR_INIT_STMT (r) = init;
866   FOR_SCOPE (r) = scope;
867
868   return r;
869 }
870
871 /* Finish the for-init-statement of a for-statement, which may be
872    given by FOR_STMT.  */
873
874 void
875 finish_for_init_stmt (tree for_stmt)
876 {
877   if (processing_template_decl)
878     FOR_INIT_STMT (for_stmt) = pop_stmt_list (FOR_INIT_STMT (for_stmt));
879   add_stmt (for_stmt);
880   FOR_BODY (for_stmt) = do_pushlevel (sk_block);
881   begin_cond (&FOR_COND (for_stmt));
882 }
883
884 /* Finish the COND of a for-statement, which may be given by
885    FOR_STMT.  */
886
887 void
888 finish_for_cond (tree cond, tree for_stmt)
889 {
890   finish_cond (&FOR_COND (for_stmt), maybe_convert_cond (cond));
891   simplify_loop_decl_cond (&FOR_COND (for_stmt), FOR_BODY (for_stmt));
892 }
893
894 /* Finish the increment-EXPRESSION in a for-statement, which may be
895    given by FOR_STMT.  */
896
897 void
898 finish_for_expr (tree expr, tree for_stmt)
899 {
900   if (!expr)
901     return;
902   /* If EXPR is an overloaded function, issue an error; there is no
903      context available to use to perform overload resolution.  */
904   if (type_unknown_p (expr))
905     {
906       cxx_incomplete_type_error (expr, TREE_TYPE (expr));
907       expr = error_mark_node;
908     }
909   if (!processing_template_decl)
910     {
911       if (warn_sequence_point)
912         verify_sequence_points (expr);
913       expr = convert_to_void (expr, ICV_THIRD_IN_FOR,
914                               tf_warning_or_error);
915     }
916   else if (!type_dependent_expression_p (expr))
917     convert_to_void (build_non_dependent_expr (expr), ICV_THIRD_IN_FOR,
918                      tf_warning_or_error);
919   expr = maybe_cleanup_point_expr_void (expr);
920   if (check_for_bare_parameter_packs (expr))
921     expr = error_mark_node;
922   FOR_EXPR (for_stmt) = expr;
923 }
924
925 /* Finish the body of a for-statement, which may be given by
926    FOR_STMT.  The increment-EXPR for the loop must be
927    provided.
928    It can also finish RANGE_FOR_STMT. */
929
930 void
931 finish_for_stmt (tree for_stmt)
932 {
933   if (TREE_CODE (for_stmt) == RANGE_FOR_STMT)
934     RANGE_FOR_BODY (for_stmt) = do_poplevel (RANGE_FOR_BODY (for_stmt));
935   else
936     FOR_BODY (for_stmt) = do_poplevel (FOR_BODY (for_stmt));
937
938   /* Pop the scope for the body of the loop.  */
939   if (flag_new_for_scope > 0)
940     {
941       tree scope;
942       tree *scope_ptr = (TREE_CODE (for_stmt) == RANGE_FOR_STMT
943                          ? &RANGE_FOR_SCOPE (for_stmt)
944                          : &FOR_SCOPE (for_stmt));
945       scope = *scope_ptr;
946       *scope_ptr = NULL;
947       add_stmt (do_poplevel (scope));
948     }
949
950   finish_stmt ();
951 }
952
953 /* Begin a range-for-statement.  Returns a new RANGE_FOR_STMT.
954    SCOPE and INIT should be the return of begin_for_scope,
955    or both NULL_TREE  .
956    To finish it call finish_for_stmt(). */
957
958 tree
959 begin_range_for_stmt (tree scope, tree init)
960 {
961   tree r;
962
963   r = build_stmt (input_location, RANGE_FOR_STMT,
964                   NULL_TREE, NULL_TREE, NULL_TREE, NULL_TREE);
965
966   if (scope == NULL_TREE)
967     {
968       gcc_assert (!init || !(flag_new_for_scope > 0));
969       if (!init)
970         scope = begin_for_scope (&init);
971     }
972
973   /* RANGE_FOR_STMTs do not use nor save the init tree, so we
974      pop it now.  */
975   if (init)
976     pop_stmt_list (init);
977   RANGE_FOR_SCOPE (r) = scope;
978
979   return r;
980 }
981
982 /* Finish the head of a range-based for statement, which may
983    be given by RANGE_FOR_STMT. DECL must be the declaration
984    and EXPR must be the loop expression. */
985
986 void
987 finish_range_for_decl (tree range_for_stmt, tree decl, tree expr)
988 {
989   RANGE_FOR_DECL (range_for_stmt) = decl;
990   RANGE_FOR_EXPR (range_for_stmt) = expr;
991   add_stmt (range_for_stmt);
992   RANGE_FOR_BODY (range_for_stmt) = do_pushlevel (sk_block);
993 }
994
995 /* Finish a break-statement.  */
996
997 tree
998 finish_break_stmt (void)
999 {
1000   /* In switch statements break is sometimes stylistically used after
1001      a return statement.  This can lead to spurious warnings about
1002      control reaching the end of a non-void function when it is
1003      inlined.  Note that we are calling block_may_fallthru with
1004      language specific tree nodes; this works because
1005      block_may_fallthru returns true when given something it does not
1006      understand.  */
1007   if (!block_may_fallthru (cur_stmt_list))
1008     return void_zero_node;
1009   return add_stmt (build_stmt (input_location, BREAK_STMT));
1010 }
1011
1012 /* Finish a continue-statement.  */
1013
1014 tree
1015 finish_continue_stmt (void)
1016 {
1017   return add_stmt (build_stmt (input_location, CONTINUE_STMT));
1018 }
1019
1020 /* Begin a switch-statement.  Returns a new SWITCH_STMT if
1021    appropriate.  */
1022
1023 tree
1024 begin_switch_stmt (void)
1025 {
1026   tree r, scope;
1027
1028   scope = do_pushlevel (sk_cond);
1029   r = build_stmt (input_location, SWITCH_STMT, NULL_TREE, NULL_TREE, NULL_TREE, scope);
1030
1031   begin_cond (&SWITCH_STMT_COND (r));
1032
1033   return r;
1034 }
1035
1036 /* Finish the cond of a switch-statement.  */
1037
1038 void
1039 finish_switch_cond (tree cond, tree switch_stmt)
1040 {
1041   tree orig_type = NULL;
1042   if (!processing_template_decl)
1043     {
1044       /* Convert the condition to an integer or enumeration type.  */
1045       cond = build_expr_type_conversion (WANT_INT | WANT_ENUM, cond, true);
1046       if (cond == NULL_TREE)
1047         {
1048           error ("switch quantity not an integer");
1049           cond = error_mark_node;
1050         }
1051       orig_type = TREE_TYPE (cond);
1052       if (cond != error_mark_node)
1053         {
1054           /* [stmt.switch]
1055
1056              Integral promotions are performed.  */
1057           cond = perform_integral_promotions (cond);
1058           cond = maybe_cleanup_point_expr (cond);
1059         }
1060     }
1061   if (check_for_bare_parameter_packs (cond))
1062     cond = error_mark_node;
1063   else if (!processing_template_decl && warn_sequence_point)
1064     verify_sequence_points (cond);
1065
1066   finish_cond (&SWITCH_STMT_COND (switch_stmt), cond);
1067   SWITCH_STMT_TYPE (switch_stmt) = orig_type;
1068   add_stmt (switch_stmt);
1069   push_switch (switch_stmt);
1070   SWITCH_STMT_BODY (switch_stmt) = push_stmt_list ();
1071 }
1072
1073 /* Finish the body of a switch-statement, which may be given by
1074    SWITCH_STMT.  The COND to switch on is indicated.  */
1075
1076 void
1077 finish_switch_stmt (tree switch_stmt)
1078 {
1079   tree scope;
1080
1081   SWITCH_STMT_BODY (switch_stmt) =
1082     pop_stmt_list (SWITCH_STMT_BODY (switch_stmt));
1083   pop_switch ();
1084   finish_stmt ();
1085
1086   scope = SWITCH_STMT_SCOPE (switch_stmt);
1087   SWITCH_STMT_SCOPE (switch_stmt) = NULL;
1088   add_stmt (do_poplevel (scope));
1089 }
1090
1091 /* Begin a try-block.  Returns a newly-created TRY_BLOCK if
1092    appropriate.  */
1093
1094 tree
1095 begin_try_block (void)
1096 {
1097   tree r = build_stmt (input_location, TRY_BLOCK, NULL_TREE, NULL_TREE);
1098   add_stmt (r);
1099   TRY_STMTS (r) = push_stmt_list ();
1100   return r;
1101 }
1102
1103 /* Likewise, for a function-try-block.  The block returned in
1104    *COMPOUND_STMT is an artificial outer scope, containing the
1105    function-try-block.  */
1106
1107 tree
1108 begin_function_try_block (tree *compound_stmt)
1109 {
1110   tree r;
1111   /* This outer scope does not exist in the C++ standard, but we need
1112      a place to put __FUNCTION__ and similar variables.  */
1113   *compound_stmt = begin_compound_stmt (0);
1114   r = begin_try_block ();
1115   FN_TRY_BLOCK_P (r) = 1;
1116   return r;
1117 }
1118
1119 /* Finish a try-block, which may be given by TRY_BLOCK.  */
1120
1121 void
1122 finish_try_block (tree try_block)
1123 {
1124   TRY_STMTS (try_block) = pop_stmt_list (TRY_STMTS (try_block));
1125   TRY_HANDLERS (try_block) = push_stmt_list ();
1126 }
1127
1128 /* Finish the body of a cleanup try-block, which may be given by
1129    TRY_BLOCK.  */
1130
1131 void
1132 finish_cleanup_try_block (tree try_block)
1133 {
1134   TRY_STMTS (try_block) = pop_stmt_list (TRY_STMTS (try_block));
1135 }
1136
1137 /* Finish an implicitly generated try-block, with a cleanup is given
1138    by CLEANUP.  */
1139
1140 void
1141 finish_cleanup (tree cleanup, tree try_block)
1142 {
1143   TRY_HANDLERS (try_block) = cleanup;
1144   CLEANUP_P (try_block) = 1;
1145 }
1146
1147 /* Likewise, for a function-try-block.  */
1148
1149 void
1150 finish_function_try_block (tree try_block)
1151 {
1152   finish_try_block (try_block);
1153   /* FIXME : something queer about CTOR_INITIALIZER somehow following
1154      the try block, but moving it inside.  */
1155   in_function_try_handler = 1;
1156 }
1157
1158 /* Finish a handler-sequence for a try-block, which may be given by
1159    TRY_BLOCK.  */
1160
1161 void
1162 finish_handler_sequence (tree try_block)
1163 {
1164   TRY_HANDLERS (try_block) = pop_stmt_list (TRY_HANDLERS (try_block));
1165   check_handlers (TRY_HANDLERS (try_block));
1166 }
1167
1168 /* Finish the handler-seq for a function-try-block, given by
1169    TRY_BLOCK.  COMPOUND_STMT is the outer block created by
1170    begin_function_try_block.  */
1171
1172 void
1173 finish_function_handler_sequence (tree try_block, tree compound_stmt)
1174 {
1175   in_function_try_handler = 0;
1176   finish_handler_sequence (try_block);
1177   finish_compound_stmt (compound_stmt);
1178 }
1179
1180 /* Begin a handler.  Returns a HANDLER if appropriate.  */
1181
1182 tree
1183 begin_handler (void)
1184 {
1185   tree r;
1186
1187   r = build_stmt (input_location, HANDLER, NULL_TREE, NULL_TREE);
1188   add_stmt (r);
1189
1190   /* Create a binding level for the eh_info and the exception object
1191      cleanup.  */
1192   HANDLER_BODY (r) = do_pushlevel (sk_catch);
1193
1194   return r;
1195 }
1196
1197 /* Finish the handler-parameters for a handler, which may be given by
1198    HANDLER.  DECL is the declaration for the catch parameter, or NULL
1199    if this is a `catch (...)' clause.  */
1200
1201 void
1202 finish_handler_parms (tree decl, tree handler)
1203 {
1204   tree type = NULL_TREE;
1205   if (processing_template_decl)
1206     {
1207       if (decl)
1208         {
1209           decl = pushdecl (decl);
1210           decl = push_template_decl (decl);
1211           HANDLER_PARMS (handler) = decl;
1212           type = TREE_TYPE (decl);
1213         }
1214     }
1215   else
1216     type = expand_start_catch_block (decl);
1217   HANDLER_TYPE (handler) = type;
1218 }
1219
1220 /* Finish a handler, which may be given by HANDLER.  The BLOCKs are
1221    the return value from the matching call to finish_handler_parms.  */
1222
1223 void
1224 finish_handler (tree handler)
1225 {
1226   if (!processing_template_decl)
1227     expand_end_catch_block ();
1228   HANDLER_BODY (handler) = do_poplevel (HANDLER_BODY (handler));
1229 }
1230
1231 /* Begin a compound statement.  FLAGS contains some bits that control the
1232    behavior and context.  If BCS_NO_SCOPE is set, the compound statement
1233    does not define a scope.  If BCS_FN_BODY is set, this is the outermost
1234    block of a function.  If BCS_TRY_BLOCK is set, this is the block
1235    created on behalf of a TRY statement.  Returns a token to be passed to
1236    finish_compound_stmt.  */
1237
1238 tree
1239 begin_compound_stmt (unsigned int flags)
1240 {
1241   tree r;
1242
1243   if (flags & BCS_NO_SCOPE)
1244     {
1245       r = push_stmt_list ();
1246       STATEMENT_LIST_NO_SCOPE (r) = 1;
1247
1248       /* Normally, we try hard to keep the BLOCK for a statement-expression.
1249          But, if it's a statement-expression with a scopeless block, there's
1250          nothing to keep, and we don't want to accidentally keep a block
1251          *inside* the scopeless block.  */
1252       keep_next_level (false);
1253     }
1254   else
1255     r = do_pushlevel (flags & BCS_TRY_BLOCK ? sk_try : sk_block);
1256
1257   /* When processing a template, we need to remember where the braces were,
1258      so that we can set up identical scopes when instantiating the template
1259      later.  BIND_EXPR is a handy candidate for this.
1260      Note that do_poplevel won't create a BIND_EXPR itself here (and thus
1261      result in nested BIND_EXPRs), since we don't build BLOCK nodes when
1262      processing templates.  */
1263   if (processing_template_decl)
1264     {
1265       r = build3 (BIND_EXPR, NULL, NULL, r, NULL);
1266       BIND_EXPR_TRY_BLOCK (r) = (flags & BCS_TRY_BLOCK) != 0;
1267       BIND_EXPR_BODY_BLOCK (r) = (flags & BCS_FN_BODY) != 0;
1268       TREE_SIDE_EFFECTS (r) = 1;
1269     }
1270
1271   return r;
1272 }
1273
1274 /* Finish a compound-statement, which is given by STMT.  */
1275
1276 void
1277 finish_compound_stmt (tree stmt)
1278 {
1279   if (TREE_CODE (stmt) == BIND_EXPR)
1280     {
1281       tree body = do_poplevel (BIND_EXPR_BODY (stmt));
1282       /* If the STATEMENT_LIST is empty and this BIND_EXPR isn't special,
1283          discard the BIND_EXPR so it can be merged with the containing
1284          STATEMENT_LIST.  */
1285       if (TREE_CODE (body) == STATEMENT_LIST
1286           && STATEMENT_LIST_HEAD (body) == NULL
1287           && !BIND_EXPR_BODY_BLOCK (stmt)
1288           && !BIND_EXPR_TRY_BLOCK (stmt))
1289         stmt = body;
1290       else
1291         BIND_EXPR_BODY (stmt) = body;
1292     }
1293   else if (STATEMENT_LIST_NO_SCOPE (stmt))
1294     stmt = pop_stmt_list (stmt);
1295   else
1296     {
1297       /* Destroy any ObjC "super" receivers that may have been
1298          created.  */
1299       objc_clear_super_receiver ();
1300
1301       stmt = do_poplevel (stmt);
1302     }
1303
1304   /* ??? See c_end_compound_stmt wrt statement expressions.  */
1305   add_stmt (stmt);
1306   finish_stmt ();
1307 }
1308
1309 /* Finish an asm-statement, whose components are a STRING, some
1310    OUTPUT_OPERANDS, some INPUT_OPERANDS, some CLOBBERS and some
1311    LABELS.  Also note whether the asm-statement should be
1312    considered volatile.  */
1313
1314 tree
1315 finish_asm_stmt (int volatile_p, tree string, tree output_operands,
1316                  tree input_operands, tree clobbers, tree labels)
1317 {
1318   tree r;
1319   tree t;
1320   int ninputs = list_length (input_operands);
1321   int noutputs = list_length (output_operands);
1322
1323   if (!processing_template_decl)
1324     {
1325       const char *constraint;
1326       const char **oconstraints;
1327       bool allows_mem, allows_reg, is_inout;
1328       tree operand;
1329       int i;
1330
1331       oconstraints = XALLOCAVEC (const char *, noutputs);
1332
1333       string = resolve_asm_operand_names (string, output_operands,
1334                                           input_operands, labels);
1335
1336       for (i = 0, t = output_operands; t; t = TREE_CHAIN (t), ++i)
1337         {
1338           operand = TREE_VALUE (t);
1339
1340           /* ??? Really, this should not be here.  Users should be using a
1341              proper lvalue, dammit.  But there's a long history of using
1342              casts in the output operands.  In cases like longlong.h, this
1343              becomes a primitive form of typechecking -- if the cast can be
1344              removed, then the output operand had a type of the proper width;
1345              otherwise we'll get an error.  Gross, but ...  */
1346           STRIP_NOPS (operand);
1347
1348           operand = mark_lvalue_use (operand);
1349
1350           if (!lvalue_or_else (operand, lv_asm, tf_warning_or_error))
1351             operand = error_mark_node;
1352
1353           if (operand != error_mark_node
1354               && (TREE_READONLY (operand)
1355                   || CP_TYPE_CONST_P (TREE_TYPE (operand))
1356                   /* Functions are not modifiable, even though they are
1357                      lvalues.  */
1358                   || TREE_CODE (TREE_TYPE (operand)) == FUNCTION_TYPE
1359                   || TREE_CODE (TREE_TYPE (operand)) == METHOD_TYPE
1360                   /* If it's an aggregate and any field is const, then it is
1361                      effectively const.  */
1362                   || (CLASS_TYPE_P (TREE_TYPE (operand))
1363                       && C_TYPE_FIELDS_READONLY (TREE_TYPE (operand)))))
1364             cxx_readonly_error (operand, lv_asm);
1365
1366           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1367           oconstraints[i] = constraint;
1368
1369           if (parse_output_constraint (&constraint, i, ninputs, noutputs,
1370                                        &allows_mem, &allows_reg, &is_inout))
1371             {
1372               /* If the operand is going to end up in memory,
1373                  mark it addressable.  */
1374               if (!allows_reg && !cxx_mark_addressable (operand))
1375                 operand = error_mark_node;
1376             }
1377           else
1378             operand = error_mark_node;
1379
1380           TREE_VALUE (t) = operand;
1381         }
1382
1383       for (i = 0, t = input_operands; t; ++i, t = TREE_CHAIN (t))
1384         {
1385           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (t)));
1386           bool constraint_parsed
1387             = parse_input_constraint (&constraint, i, ninputs, noutputs, 0,   
1388                                       oconstraints, &allows_mem, &allows_reg);
1389           /* If the operand is going to end up in memory, don't call
1390              decay_conversion.  */
1391           if (constraint_parsed && !allows_reg && allows_mem)
1392             operand = mark_lvalue_use (TREE_VALUE (t));
1393           else
1394             operand = decay_conversion (TREE_VALUE (t), tf_warning_or_error);
1395
1396           /* If the type of the operand hasn't been determined (e.g.,
1397              because it involves an overloaded function), then issue
1398              an error message.  There's no context available to
1399              resolve the overloading.  */
1400           if (TREE_TYPE (operand) == unknown_type_node)
1401             {
1402               error ("type of asm operand %qE could not be determined",
1403                      TREE_VALUE (t));
1404               operand = error_mark_node;
1405             }
1406
1407           if (constraint_parsed)
1408             {
1409               /* If the operand is going to end up in memory,
1410                  mark it addressable.  */
1411               if (!allows_reg && allows_mem)
1412                 {
1413                   /* Strip the nops as we allow this case.  FIXME, this really
1414                      should be rejected or made deprecated.  */
1415                   STRIP_NOPS (operand);
1416                   if (!cxx_mark_addressable (operand))
1417                     operand = error_mark_node;
1418                 }
1419               else if (!allows_reg && !allows_mem)
1420                 {
1421                   /* If constraint allows neither register nor memory,
1422                      try harder to get a constant.  */
1423                   tree constop = maybe_constant_value (operand);
1424                   if (TREE_CONSTANT (constop))
1425                     operand = constop;
1426                 }
1427             }
1428           else
1429             operand = error_mark_node;
1430
1431           TREE_VALUE (t) = operand;
1432         }
1433     }
1434
1435   r = build_stmt (input_location, ASM_EXPR, string,
1436                   output_operands, input_operands,
1437                   clobbers, labels);
1438   ASM_VOLATILE_P (r) = volatile_p || noutputs == 0;
1439   r = maybe_cleanup_point_expr_void (r);
1440   return add_stmt (r);
1441 }
1442
1443 /* Finish a label with the indicated NAME.  Returns the new label.  */
1444
1445 tree
1446 finish_label_stmt (tree name)
1447 {
1448   tree decl = define_label (input_location, name);
1449
1450   if (decl == error_mark_node)
1451     return error_mark_node;
1452
1453   add_stmt (build_stmt (input_location, LABEL_EXPR, decl));
1454
1455   return decl;
1456 }
1457
1458 /* Finish a series of declarations for local labels.  G++ allows users
1459    to declare "local" labels, i.e., labels with scope.  This extension
1460    is useful when writing code involving statement-expressions.  */
1461
1462 void
1463 finish_label_decl (tree name)
1464 {
1465   if (!at_function_scope_p ())
1466     {
1467       error ("__label__ declarations are only allowed in function scopes");
1468       return;
1469     }
1470
1471   add_decl_expr (declare_local_label (name));
1472 }
1473
1474 /* When DECL goes out of scope, make sure that CLEANUP is executed.  */
1475
1476 void
1477 finish_decl_cleanup (tree decl, tree cleanup)
1478 {
1479   push_cleanup (decl, cleanup, false);
1480 }
1481
1482 /* If the current scope exits with an exception, run CLEANUP.  */
1483
1484 void
1485 finish_eh_cleanup (tree cleanup)
1486 {
1487   push_cleanup (NULL, cleanup, true);
1488 }
1489
1490 /* The MEM_INITS is a list of mem-initializers, in reverse of the
1491    order they were written by the user.  Each node is as for
1492    emit_mem_initializers.  */
1493
1494 void
1495 finish_mem_initializers (tree mem_inits)
1496 {
1497   /* Reorder the MEM_INITS so that they are in the order they appeared
1498      in the source program.  */
1499   mem_inits = nreverse (mem_inits);
1500
1501   if (processing_template_decl)
1502     {
1503       tree mem;
1504
1505       for (mem = mem_inits; mem; mem = TREE_CHAIN (mem))
1506         {
1507           /* If the TREE_PURPOSE is a TYPE_PACK_EXPANSION, skip the
1508              check for bare parameter packs in the TREE_VALUE, because
1509              any parameter packs in the TREE_VALUE have already been
1510              bound as part of the TREE_PURPOSE.  See
1511              make_pack_expansion for more information.  */
1512           if (TREE_CODE (TREE_PURPOSE (mem)) != TYPE_PACK_EXPANSION
1513               && check_for_bare_parameter_packs (TREE_VALUE (mem)))
1514             TREE_VALUE (mem) = error_mark_node;
1515         }
1516
1517       add_stmt (build_min_nt_loc (UNKNOWN_LOCATION,
1518                                   CTOR_INITIALIZER, mem_inits));
1519     }
1520   else
1521     emit_mem_initializers (mem_inits);
1522 }
1523
1524 /* Obfuscate EXPR if it looks like an id-expression or member access so
1525    that the call to finish_decltype in do_auto_deduction will give the
1526    right result.  */
1527
1528 tree
1529 force_paren_expr (tree expr)
1530 {
1531   /* This is only needed for decltype(auto) in C++14.  */
1532   if (cxx_dialect < cxx1y)
1533     return expr;
1534
1535   if (!DECL_P (expr) && TREE_CODE (expr) != COMPONENT_REF
1536       && TREE_CODE (expr) != SCOPE_REF)
1537     return expr;
1538
1539   if (processing_template_decl)
1540     expr = build1 (PAREN_EXPR, TREE_TYPE (expr), expr);
1541   else
1542     {
1543       cp_lvalue_kind kind = lvalue_kind (expr);
1544       if ((kind & ~clk_class) != clk_none)
1545         {
1546           tree type = unlowered_expr_type (expr);
1547           bool rval = !!(kind & clk_rvalueref);
1548           type = cp_build_reference_type (type, rval);
1549           expr = build_static_cast (type, expr, tf_warning_or_error);
1550         }
1551     }
1552
1553   return expr;
1554 }
1555
1556 /* Finish a parenthesized expression EXPR.  */
1557
1558 tree
1559 finish_parenthesized_expr (tree expr)
1560 {
1561   if (EXPR_P (expr))
1562     /* This inhibits warnings in c_common_truthvalue_conversion.  */
1563     TREE_NO_WARNING (expr) = 1;
1564
1565   if (TREE_CODE (expr) == OFFSET_REF
1566       || TREE_CODE (expr) == SCOPE_REF)
1567     /* [expr.unary.op]/3 The qualified id of a pointer-to-member must not be
1568        enclosed in parentheses.  */
1569     PTRMEM_OK_P (expr) = 0;
1570
1571   if (TREE_CODE (expr) == STRING_CST)
1572     PAREN_STRING_LITERAL_P (expr) = 1;
1573
1574   expr = force_paren_expr (expr);
1575
1576   return expr;
1577 }
1578
1579 /* Finish a reference to a non-static data member (DECL) that is not
1580    preceded by `.' or `->'.  */
1581
1582 tree
1583 finish_non_static_data_member (tree decl, tree object, tree qualifying_scope)
1584 {
1585   gcc_assert (TREE_CODE (decl) == FIELD_DECL);
1586
1587   if (!object)
1588     {
1589       tree scope = qualifying_scope;
1590       if (scope == NULL_TREE)
1591         scope = context_for_name_lookup (decl);
1592       object = maybe_dummy_object (scope, NULL);
1593     }
1594
1595   object = maybe_resolve_dummy (object);
1596   if (object == error_mark_node)
1597     return error_mark_node;
1598
1599   /* DR 613: Can use non-static data members without an associated
1600      object in sizeof/decltype/alignof.  */
1601   if (is_dummy_object (object) && cp_unevaluated_operand == 0
1602       && (!processing_template_decl || !current_class_ref))
1603     {
1604       if (current_function_decl
1605           && DECL_STATIC_FUNCTION_P (current_function_decl))
1606         error ("invalid use of member %q+D in static member function", decl);
1607       else
1608         error ("invalid use of non-static data member %q+D", decl);
1609       error ("from this location");
1610
1611       return error_mark_node;
1612     }
1613
1614   if (current_class_ptr)
1615     TREE_USED (current_class_ptr) = 1;
1616   if (processing_template_decl && !qualifying_scope)
1617     {
1618       tree type = TREE_TYPE (decl);
1619
1620       if (TREE_CODE (type) == REFERENCE_TYPE)
1621         /* Quals on the object don't matter.  */;
1622       else
1623         {
1624           /* Set the cv qualifiers.  */
1625           int quals = cp_type_quals (TREE_TYPE (object));
1626
1627           if (DECL_MUTABLE_P (decl))
1628             quals &= ~TYPE_QUAL_CONST;
1629
1630           quals |= cp_type_quals (TREE_TYPE (decl));
1631           type = cp_build_qualified_type (type, quals);
1632         }
1633
1634       return (convert_from_reference
1635               (build_min (COMPONENT_REF, type, object, decl, NULL_TREE)));
1636     }
1637   /* If PROCESSING_TEMPLATE_DECL is nonzero here, then
1638      QUALIFYING_SCOPE is also non-null.  Wrap this in a SCOPE_REF
1639      for now.  */
1640   else if (processing_template_decl)
1641     return build_qualified_name (TREE_TYPE (decl),
1642                                  qualifying_scope,
1643                                  decl,
1644                                  /*template_p=*/false);
1645   else
1646     {
1647       tree access_type = TREE_TYPE (object);
1648
1649       perform_or_defer_access_check (TYPE_BINFO (access_type), decl,
1650                                      decl, tf_warning_or_error);
1651
1652       /* If the data member was named `C::M', convert `*this' to `C'
1653          first.  */
1654       if (qualifying_scope)
1655         {
1656           tree binfo = NULL_TREE;
1657           object = build_scoped_ref (object, qualifying_scope,
1658                                      &binfo);
1659         }
1660
1661       return build_class_member_access_expr (object, decl,
1662                                              /*access_path=*/NULL_TREE,
1663                                              /*preserve_reference=*/false,
1664                                              tf_warning_or_error);
1665     }
1666 }
1667
1668 /* If we are currently parsing a template and we encountered a typedef
1669    TYPEDEF_DECL that is being accessed though CONTEXT, this function
1670    adds the typedef to a list tied to the current template.
1671    At template instantiation time, that list is walked and access check
1672    performed for each typedef.
1673    LOCATION is the location of the usage point of TYPEDEF_DECL.  */
1674
1675 void
1676 add_typedef_to_current_template_for_access_check (tree typedef_decl,
1677                                                   tree context,
1678                                                   location_t location)
1679 {
1680     tree template_info = NULL;
1681     tree cs = current_scope ();
1682
1683     if (!is_typedef_decl (typedef_decl)
1684         || !context
1685         || !CLASS_TYPE_P (context)
1686         || !cs)
1687       return;
1688
1689     if (CLASS_TYPE_P (cs) || TREE_CODE (cs) == FUNCTION_DECL)
1690       template_info = get_template_info (cs);
1691
1692     if (template_info
1693         && TI_TEMPLATE (template_info)
1694         && !currently_open_class (context))
1695       append_type_to_template_for_access_check (cs, typedef_decl,
1696                                                 context, location);
1697 }
1698
1699 /* DECL was the declaration to which a qualified-id resolved.  Issue
1700    an error message if it is not accessible.  If OBJECT_TYPE is
1701    non-NULL, we have just seen `x->' or `x.' and OBJECT_TYPE is the
1702    type of `*x', or `x', respectively.  If the DECL was named as
1703    `A::B' then NESTED_NAME_SPECIFIER is `A'.  */
1704
1705 void
1706 check_accessibility_of_qualified_id (tree decl,
1707                                      tree object_type,
1708                                      tree nested_name_specifier)
1709 {
1710   tree scope;
1711   tree qualifying_type = NULL_TREE;
1712
1713   /* If we are parsing a template declaration and if decl is a typedef,
1714      add it to a list tied to the template.
1715      At template instantiation time, that list will be walked and
1716      access check performed.  */
1717   add_typedef_to_current_template_for_access_check (decl,
1718                                                     nested_name_specifier
1719                                                     ? nested_name_specifier
1720                                                     : DECL_CONTEXT (decl),
1721                                                     input_location);
1722
1723   /* If we're not checking, return immediately.  */
1724   if (deferred_access_no_check)
1725     return;
1726
1727   /* Determine the SCOPE of DECL.  */
1728   scope = context_for_name_lookup (decl);
1729   /* If the SCOPE is not a type, then DECL is not a member.  */
1730   if (!TYPE_P (scope))
1731     return;
1732   /* Compute the scope through which DECL is being accessed.  */
1733   if (object_type
1734       /* OBJECT_TYPE might not be a class type; consider:
1735
1736            class A { typedef int I; };
1737            I *p;
1738            p->A::I::~I();
1739
1740          In this case, we will have "A::I" as the DECL, but "I" as the
1741          OBJECT_TYPE.  */
1742       && CLASS_TYPE_P (object_type)
1743       && DERIVED_FROM_P (scope, object_type))
1744     /* If we are processing a `->' or `.' expression, use the type of the
1745        left-hand side.  */
1746     qualifying_type = object_type;
1747   else if (nested_name_specifier)
1748     {
1749       /* If the reference is to a non-static member of the
1750          current class, treat it as if it were referenced through
1751          `this'.  */
1752       if (DECL_NONSTATIC_MEMBER_P (decl)
1753           && current_class_ptr
1754           && DERIVED_FROM_P (scope, current_class_type))
1755         qualifying_type = current_class_type;
1756       /* Otherwise, use the type indicated by the
1757          nested-name-specifier.  */
1758       else
1759         qualifying_type = nested_name_specifier;
1760     }
1761   else
1762     /* Otherwise, the name must be from the current class or one of
1763        its bases.  */
1764     qualifying_type = currently_open_derived_class (scope);
1765
1766   if (qualifying_type 
1767       /* It is possible for qualifying type to be a TEMPLATE_TYPE_PARM
1768          or similar in a default argument value.  */
1769       && CLASS_TYPE_P (qualifying_type)
1770       && !dependent_type_p (qualifying_type))
1771     perform_or_defer_access_check (TYPE_BINFO (qualifying_type), decl,
1772                                    decl, tf_warning_or_error);
1773 }
1774
1775 /* EXPR is the result of a qualified-id.  The QUALIFYING_CLASS was the
1776    class named to the left of the "::" operator.  DONE is true if this
1777    expression is a complete postfix-expression; it is false if this
1778    expression is followed by '->', '[', '(', etc.  ADDRESS_P is true
1779    iff this expression is the operand of '&'.  TEMPLATE_P is true iff
1780    the qualified-id was of the form "A::template B".  TEMPLATE_ARG_P
1781    is true iff this qualified name appears as a template argument.  */
1782
1783 tree
1784 finish_qualified_id_expr (tree qualifying_class,
1785                           tree expr,
1786                           bool done,
1787                           bool address_p,
1788                           bool template_p,
1789                           bool template_arg_p,
1790                           tsubst_flags_t complain)
1791 {
1792   gcc_assert (TYPE_P (qualifying_class));
1793
1794   if (error_operand_p (expr))
1795     return error_mark_node;
1796
1797   if ((DECL_P (expr) || BASELINK_P (expr))
1798       && !mark_used (expr, complain))
1799     return error_mark_node;
1800
1801   if (template_p)
1802     check_template_keyword (expr);
1803
1804   /* If EXPR occurs as the operand of '&', use special handling that
1805      permits a pointer-to-member.  */
1806   if (address_p && done)
1807     {
1808       if (TREE_CODE (expr) == SCOPE_REF)
1809         expr = TREE_OPERAND (expr, 1);
1810       expr = build_offset_ref (qualifying_class, expr,
1811                                /*address_p=*/true, complain);
1812       return expr;
1813     }
1814
1815   /* No need to check access within an enum.  */
1816   if (TREE_CODE (qualifying_class) == ENUMERAL_TYPE)
1817     return expr;
1818
1819   /* Within the scope of a class, turn references to non-static
1820      members into expression of the form "this->...".  */
1821   if (template_arg_p)
1822     /* But, within a template argument, we do not want make the
1823        transformation, as there is no "this" pointer.  */
1824     ;
1825   else if (TREE_CODE (expr) == FIELD_DECL)
1826     {
1827       push_deferring_access_checks (dk_no_check);
1828       expr = finish_non_static_data_member (expr, NULL_TREE,
1829                                             qualifying_class);
1830       pop_deferring_access_checks ();
1831     }
1832   else if (BASELINK_P (expr) && !processing_template_decl)
1833     {
1834       /* See if any of the functions are non-static members.  */
1835       /* If so, the expression may be relative to 'this'.  */
1836       if (!shared_member_p (expr)
1837           && current_class_ptr
1838           && DERIVED_FROM_P (qualifying_class,
1839                              current_nonlambda_class_type ()))
1840         expr = (build_class_member_access_expr
1841                 (maybe_dummy_object (qualifying_class, NULL),
1842                  expr,
1843                  BASELINK_ACCESS_BINFO (expr),
1844                  /*preserve_reference=*/false,
1845                  complain));
1846       else if (done)
1847         /* The expression is a qualified name whose address is not
1848            being taken.  */
1849         expr = build_offset_ref (qualifying_class, expr, /*address_p=*/false,
1850                                  complain);
1851     }
1852   else if (BASELINK_P (expr))
1853     ;
1854   else
1855     {
1856       /* In a template, return a SCOPE_REF for most qualified-ids
1857          so that we can check access at instantiation time.  But if
1858          we're looking at a member of the current instantiation, we
1859          know we have access and building up the SCOPE_REF confuses
1860          non-type template argument handling.  */
1861       if (processing_template_decl
1862           && !currently_open_class (qualifying_class))
1863         expr = build_qualified_name (TREE_TYPE (expr),
1864                                      qualifying_class, expr,
1865                                      template_p);
1866
1867       expr = convert_from_reference (expr);
1868     }
1869
1870   return expr;
1871 }
1872
1873 /* Begin a statement-expression.  The value returned must be passed to
1874    finish_stmt_expr.  */
1875
1876 tree
1877 begin_stmt_expr (void)
1878 {
1879   return push_stmt_list ();
1880 }
1881
1882 /* Process the final expression of a statement expression. EXPR can be
1883    NULL, if the final expression is empty.  Return a STATEMENT_LIST
1884    containing all the statements in the statement-expression, or
1885    ERROR_MARK_NODE if there was an error.  */
1886
1887 tree
1888 finish_stmt_expr_expr (tree expr, tree stmt_expr)
1889 {
1890   if (error_operand_p (expr))
1891     {
1892       /* The type of the statement-expression is the type of the last
1893          expression.  */
1894       TREE_TYPE (stmt_expr) = error_mark_node;
1895       return error_mark_node;
1896     }
1897
1898   /* If the last statement does not have "void" type, then the value
1899      of the last statement is the value of the entire expression.  */
1900   if (expr)
1901     {
1902       tree type = TREE_TYPE (expr);
1903
1904       if (processing_template_decl)
1905         {
1906           expr = build_stmt (input_location, EXPR_STMT, expr);
1907           expr = add_stmt (expr);
1908           /* Mark the last statement so that we can recognize it as such at
1909              template-instantiation time.  */
1910           EXPR_STMT_STMT_EXPR_RESULT (expr) = 1;
1911         }
1912       else if (VOID_TYPE_P (type))
1913         {
1914           /* Just treat this like an ordinary statement.  */
1915           expr = finish_expr_stmt (expr);
1916         }
1917       else
1918         {
1919           /* It actually has a value we need to deal with.  First, force it
1920              to be an rvalue so that we won't need to build up a copy
1921              constructor call later when we try to assign it to something.  */
1922           expr = force_rvalue (expr, tf_warning_or_error);
1923           if (error_operand_p (expr))
1924             return error_mark_node;
1925
1926           /* Update for array-to-pointer decay.  */
1927           type = TREE_TYPE (expr);
1928
1929           /* Wrap it in a CLEANUP_POINT_EXPR and add it to the list like a
1930              normal statement, but don't convert to void or actually add
1931              the EXPR_STMT.  */
1932           if (TREE_CODE (expr) != CLEANUP_POINT_EXPR)
1933             expr = maybe_cleanup_point_expr (expr);
1934           add_stmt (expr);
1935         }
1936
1937       /* The type of the statement-expression is the type of the last
1938          expression.  */
1939       TREE_TYPE (stmt_expr) = type;
1940     }
1941
1942   return stmt_expr;
1943 }
1944
1945 /* Finish a statement-expression.  EXPR should be the value returned
1946    by the previous begin_stmt_expr.  Returns an expression
1947    representing the statement-expression.  */
1948
1949 tree
1950 finish_stmt_expr (tree stmt_expr, bool has_no_scope)
1951 {
1952   tree type;
1953   tree result;
1954
1955   if (error_operand_p (stmt_expr))
1956     {
1957       pop_stmt_list (stmt_expr);
1958       return error_mark_node;
1959     }
1960
1961   gcc_assert (TREE_CODE (stmt_expr) == STATEMENT_LIST);
1962
1963   type = TREE_TYPE (stmt_expr);
1964   result = pop_stmt_list (stmt_expr);
1965   TREE_TYPE (result) = type;
1966
1967   if (processing_template_decl)
1968     {
1969       result = build_min (STMT_EXPR, type, result);
1970       TREE_SIDE_EFFECTS (result) = 1;
1971       STMT_EXPR_NO_SCOPE (result) = has_no_scope;
1972     }
1973   else if (CLASS_TYPE_P (type))
1974     {
1975       /* Wrap the statement-expression in a TARGET_EXPR so that the
1976          temporary object created by the final expression is destroyed at
1977          the end of the full-expression containing the
1978          statement-expression.  */
1979       result = force_target_expr (type, result, tf_warning_or_error);
1980     }
1981
1982   return result;
1983 }
1984
1985 /* Returns the expression which provides the value of STMT_EXPR.  */
1986
1987 tree
1988 stmt_expr_value_expr (tree stmt_expr)
1989 {
1990   tree t = STMT_EXPR_STMT (stmt_expr);
1991
1992   if (TREE_CODE (t) == BIND_EXPR)
1993     t = BIND_EXPR_BODY (t);
1994
1995   if (TREE_CODE (t) == STATEMENT_LIST && STATEMENT_LIST_TAIL (t))
1996     t = STATEMENT_LIST_TAIL (t)->stmt;
1997
1998   if (TREE_CODE (t) == EXPR_STMT)
1999     t = EXPR_STMT_EXPR (t);
2000
2001   return t;
2002 }
2003
2004 /* Return TRUE iff EXPR_STMT is an empty list of
2005    expression statements.  */
2006
2007 bool
2008 empty_expr_stmt_p (tree expr_stmt)
2009 {
2010   tree body = NULL_TREE;
2011
2012   if (expr_stmt == void_zero_node)
2013     return true;
2014
2015   if (expr_stmt)
2016     {
2017       if (TREE_CODE (expr_stmt) == EXPR_STMT)
2018         body = EXPR_STMT_EXPR (expr_stmt);
2019       else if (TREE_CODE (expr_stmt) == STATEMENT_LIST)
2020         body = expr_stmt;
2021     }
2022
2023   if (body)
2024     {
2025       if (TREE_CODE (body) == STATEMENT_LIST)
2026         return tsi_end_p (tsi_start (body));
2027       else
2028         return empty_expr_stmt_p (body);
2029     }
2030   return false;
2031 }
2032
2033 /* Perform Koenig lookup.  FN is the postfix-expression representing
2034    the function (or functions) to call; ARGS are the arguments to the
2035    call; if INCLUDE_STD then the `std' namespace is automatically
2036    considered an associated namespace (used in range-based for loops).
2037    Returns the functions to be considered by overload resolution.  */
2038
2039 tree
2040 perform_koenig_lookup (tree fn, vec<tree, va_gc> *args, bool include_std,
2041                        tsubst_flags_t complain)
2042 {
2043   tree identifier = NULL_TREE;
2044   tree functions = NULL_TREE;
2045   tree tmpl_args = NULL_TREE;
2046   bool template_id = false;
2047
2048   if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
2049     {
2050       /* Use a separate flag to handle null args.  */
2051       template_id = true;
2052       tmpl_args = TREE_OPERAND (fn, 1);
2053       fn = TREE_OPERAND (fn, 0);
2054     }
2055
2056   /* Find the name of the overloaded function.  */
2057   if (identifier_p (fn))
2058     identifier = fn;
2059   else if (is_overloaded_fn (fn))
2060     {
2061       functions = fn;
2062       identifier = DECL_NAME (get_first_fn (functions));
2063     }
2064   else if (DECL_P (fn))
2065     {
2066       functions = fn;
2067       identifier = DECL_NAME (fn);
2068     }
2069
2070   /* A call to a namespace-scope function using an unqualified name.
2071
2072      Do Koenig lookup -- unless any of the arguments are
2073      type-dependent.  */
2074   if (!any_type_dependent_arguments_p (args)
2075       && !any_dependent_template_arguments_p (tmpl_args))
2076     {
2077       fn = lookup_arg_dependent (identifier, functions, args, include_std);
2078       if (!fn)
2079         {
2080           /* The unqualified name could not be resolved.  */
2081           if (complain)
2082             fn = unqualified_fn_lookup_error (identifier);
2083           else
2084             fn = identifier;
2085         }
2086     }
2087
2088   if (fn && template_id)
2089     fn = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fn, tmpl_args);
2090   
2091   return fn;
2092 }
2093
2094 /* Generate an expression for `FN (ARGS)'.  This may change the
2095    contents of ARGS.
2096
2097    If DISALLOW_VIRTUAL is true, the call to FN will be not generated
2098    as a virtual call, even if FN is virtual.  (This flag is set when
2099    encountering an expression where the function name is explicitly
2100    qualified.  For example a call to `X::f' never generates a virtual
2101    call.)
2102
2103    Returns code for the call.  */
2104
2105 tree
2106 finish_call_expr (tree fn, vec<tree, va_gc> **args, bool disallow_virtual,
2107                   bool koenig_p, tsubst_flags_t complain)
2108 {
2109   tree result;
2110   tree orig_fn;
2111   vec<tree, va_gc> *orig_args = NULL;
2112
2113   if (fn == error_mark_node)
2114     return error_mark_node;
2115
2116   gcc_assert (!TYPE_P (fn));
2117
2118   orig_fn = fn;
2119
2120   if (processing_template_decl)
2121     {
2122       /* If the call expression is dependent, build a CALL_EXPR node
2123          with no type; type_dependent_expression_p recognizes
2124          expressions with no type as being dependent.  */
2125       if (type_dependent_expression_p (fn)
2126           || any_type_dependent_arguments_p (*args)
2127           /* For a non-static member function that doesn't have an
2128              explicit object argument, we need to specifically
2129              test the type dependency of the "this" pointer because it
2130              is not included in *ARGS even though it is considered to
2131              be part of the list of arguments.  Note that this is
2132              related to CWG issues 515 and 1005.  */
2133           || (TREE_CODE (fn) != COMPONENT_REF
2134               && non_static_member_function_p (fn)
2135               && current_class_ref
2136               && type_dependent_expression_p (current_class_ref)))
2137         {
2138           result = build_nt_call_vec (fn, *args);
2139           SET_EXPR_LOCATION (result, EXPR_LOC_OR_HERE (fn));
2140           KOENIG_LOOKUP_P (result) = koenig_p;
2141           if (cfun)
2142             {
2143               do
2144                 {
2145                   tree fndecl = OVL_CURRENT (fn);
2146                   if (TREE_CODE (fndecl) != FUNCTION_DECL
2147                       || !TREE_THIS_VOLATILE (fndecl))
2148                     break;
2149                   fn = OVL_NEXT (fn);
2150                 }
2151               while (fn);
2152               if (!fn)
2153                 current_function_returns_abnormally = 1;
2154             }
2155           return result;
2156         }
2157       orig_args = make_tree_vector_copy (*args);
2158       if (!BASELINK_P (fn)
2159           && TREE_CODE (fn) != PSEUDO_DTOR_EXPR
2160           && TREE_TYPE (fn) != unknown_type_node)
2161         fn = build_non_dependent_expr (fn);
2162       make_args_non_dependent (*args);
2163     }
2164
2165   if (TREE_CODE (fn) == COMPONENT_REF)
2166     {
2167       tree member = TREE_OPERAND (fn, 1);
2168       if (BASELINK_P (member))
2169         {
2170           tree object = TREE_OPERAND (fn, 0);
2171           return build_new_method_call (object, member,
2172                                         args, NULL_TREE,
2173                                         (disallow_virtual
2174                                          ? LOOKUP_NORMAL | LOOKUP_NONVIRTUAL
2175                                          : LOOKUP_NORMAL),
2176                                         /*fn_p=*/NULL,
2177                                         complain);
2178         }
2179     }
2180
2181   if (is_overloaded_fn (fn))
2182     fn = baselink_for_fns (fn);
2183
2184   result = NULL_TREE;
2185   if (BASELINK_P (fn))
2186     {
2187       tree object;
2188
2189       /* A call to a member function.  From [over.call.func]:
2190
2191            If the keyword this is in scope and refers to the class of
2192            that member function, or a derived class thereof, then the
2193            function call is transformed into a qualified function call
2194            using (*this) as the postfix-expression to the left of the
2195            . operator.... [Otherwise] a contrived object of type T
2196            becomes the implied object argument.
2197
2198         In this situation:
2199
2200           struct A { void f(); };
2201           struct B : public A {};
2202           struct C : public A { void g() { B::f(); }};
2203
2204         "the class of that member function" refers to `A'.  But 11.2
2205         [class.access.base] says that we need to convert 'this' to B* as
2206         part of the access, so we pass 'B' to maybe_dummy_object.  */
2207
2208       object = maybe_dummy_object (BINFO_TYPE (BASELINK_ACCESS_BINFO (fn)),
2209                                    NULL);
2210
2211       if (processing_template_decl)
2212         {
2213           if (type_dependent_expression_p (object))
2214             {
2215               tree ret = build_nt_call_vec (orig_fn, orig_args);
2216               release_tree_vector (orig_args);
2217               return ret;
2218             }
2219           object = build_non_dependent_expr (object);
2220         }
2221
2222       result = build_new_method_call (object, fn, args, NULL_TREE,
2223                                       (disallow_virtual
2224                                        ? LOOKUP_NORMAL|LOOKUP_NONVIRTUAL
2225                                        : LOOKUP_NORMAL),
2226                                       /*fn_p=*/NULL,
2227                                       complain);
2228     }
2229   else if (is_overloaded_fn (fn))
2230     {
2231       /* If the function is an overloaded builtin, resolve it.  */
2232       if (TREE_CODE (fn) == FUNCTION_DECL
2233           && (DECL_BUILT_IN_CLASS (fn) == BUILT_IN_NORMAL
2234               || DECL_BUILT_IN_CLASS (fn) == BUILT_IN_MD))
2235         result = resolve_overloaded_builtin (input_location, fn, *args);
2236
2237       if (!result)
2238         {
2239           if (warn_sizeof_pointer_memaccess
2240               && !vec_safe_is_empty (*args)
2241               && !processing_template_decl)
2242             {
2243               location_t sizeof_arg_loc[3];
2244               tree sizeof_arg[3];
2245               unsigned int i;
2246               for (i = 0; i < 3; i++)
2247                 {
2248                   tree t;
2249
2250                   sizeof_arg_loc[i] = UNKNOWN_LOCATION;
2251                   sizeof_arg[i] = NULL_TREE;
2252                   if (i >= (*args)->length ())
2253                     continue;
2254                   t = (**args)[i];
2255                   if (TREE_CODE (t) != SIZEOF_EXPR)
2256                     continue;
2257                   if (SIZEOF_EXPR_TYPE_P (t))
2258                     sizeof_arg[i] = TREE_TYPE (TREE_OPERAND (t, 0));
2259                   else
2260                     sizeof_arg[i] = TREE_OPERAND (t, 0);
2261                   sizeof_arg_loc[i] = EXPR_LOCATION (t);
2262                 }
2263               sizeof_pointer_memaccess_warning
2264                 (sizeof_arg_loc, fn, *args,
2265                  sizeof_arg, same_type_ignoring_top_level_qualifiers_p);
2266             }
2267
2268           /* A call to a namespace-scope function.  */
2269           result = build_new_function_call (fn, args, koenig_p, complain);
2270         }
2271     }
2272   else if (TREE_CODE (fn) == PSEUDO_DTOR_EXPR)
2273     {
2274       if (!vec_safe_is_empty (*args))
2275         error ("arguments to destructor are not allowed");
2276       /* Mark the pseudo-destructor call as having side-effects so
2277          that we do not issue warnings about its use.  */
2278       result = build1 (NOP_EXPR,
2279                        void_type_node,
2280                        TREE_OPERAND (fn, 0));
2281       TREE_SIDE_EFFECTS (result) = 1;
2282     }
2283   else if (CLASS_TYPE_P (TREE_TYPE (fn)))
2284     /* If the "function" is really an object of class type, it might
2285        have an overloaded `operator ()'.  */
2286     result = build_op_call (fn, args, complain);
2287
2288   if (!result)
2289     /* A call where the function is unknown.  */
2290     result = cp_build_function_call_vec (fn, args, complain);
2291
2292   if (processing_template_decl && result != error_mark_node)
2293     {
2294       if (INDIRECT_REF_P (result))
2295         result = TREE_OPERAND (result, 0);
2296       result = build_call_vec (TREE_TYPE (result), orig_fn, orig_args);
2297       SET_EXPR_LOCATION (result, input_location);
2298       KOENIG_LOOKUP_P (result) = koenig_p;
2299       release_tree_vector (orig_args);
2300       result = convert_from_reference (result);
2301     }
2302
2303   if (koenig_p)
2304     {
2305       /* Free garbage OVERLOADs from arg-dependent lookup.  */
2306       tree next = NULL_TREE;
2307       for (fn = orig_fn;
2308            fn && TREE_CODE (fn) == OVERLOAD && OVL_ARG_DEPENDENT (fn);
2309            fn = next)
2310         {
2311           if (processing_template_decl)
2312             /* In a template, we'll re-use them at instantiation time.  */
2313             OVL_ARG_DEPENDENT (fn) = false;
2314           else
2315             {
2316               next = OVL_CHAIN (fn);
2317               ggc_free (fn);
2318             }
2319         }
2320     }
2321
2322   return result;
2323 }
2324
2325 /* Finish a call to a postfix increment or decrement or EXPR.  (Which
2326    is indicated by CODE, which should be POSTINCREMENT_EXPR or
2327    POSTDECREMENT_EXPR.)  */
2328
2329 tree
2330 finish_increment_expr (tree expr, enum tree_code code)
2331 {
2332   return build_x_unary_op (input_location, code, expr, tf_warning_or_error);
2333 }
2334
2335 /* Finish a use of `this'.  Returns an expression for `this'.  */
2336
2337 tree
2338 finish_this_expr (void)
2339 {
2340   tree result;
2341
2342   if (current_class_ptr)
2343     {
2344       tree type = TREE_TYPE (current_class_ref);
2345
2346       /* In a lambda expression, 'this' refers to the captured 'this'.  */
2347       if (LAMBDA_TYPE_P (type))
2348         result = lambda_expr_this_capture (CLASSTYPE_LAMBDA_EXPR (type));
2349       else
2350         result = current_class_ptr;
2351     }
2352   else if (current_function_decl
2353            && DECL_STATIC_FUNCTION_P (current_function_decl))
2354     {
2355       error ("%<this%> is unavailable for static member functions");
2356       result = error_mark_node;
2357     }
2358   else
2359     {
2360       if (current_function_decl)
2361         error ("invalid use of %<this%> in non-member function");
2362       else
2363         error ("invalid use of %<this%> at top level");
2364       result = error_mark_node;
2365     }
2366
2367   /* The keyword 'this' is a prvalue expression.  */
2368   result = rvalue (result);
2369
2370   return result;
2371 }
2372
2373 /* Finish a pseudo-destructor expression.  If SCOPE is NULL, the
2374    expression was of the form `OBJECT.~DESTRUCTOR' where DESTRUCTOR is
2375    the TYPE for the type given.  If SCOPE is non-NULL, the expression
2376    was of the form `OBJECT.SCOPE::~DESTRUCTOR'.  */
2377
2378 tree
2379 finish_pseudo_destructor_expr (tree object, tree scope, tree destructor)
2380 {
2381   if (object == error_mark_node || destructor == error_mark_node)
2382     return error_mark_node;
2383
2384   gcc_assert (TYPE_P (destructor));
2385
2386   if (!processing_template_decl)
2387     {
2388       if (scope == error_mark_node)
2389         {
2390           error ("invalid qualifying scope in pseudo-destructor name");
2391           return error_mark_node;
2392         }
2393       if (is_auto (destructor))
2394         destructor = TREE_TYPE (object);
2395       if (scope && TYPE_P (scope) && !check_dtor_name (scope, destructor))
2396         {
2397           error ("qualified type %qT does not match destructor name ~%qT",
2398                  scope, destructor);
2399           return error_mark_node;
2400         }
2401
2402
2403       /* [expr.pseudo] says both:
2404
2405            The type designated by the pseudo-destructor-name shall be
2406            the same as the object type.
2407
2408          and:
2409
2410            The cv-unqualified versions of the object type and of the
2411            type designated by the pseudo-destructor-name shall be the
2412            same type.
2413
2414          We implement the more generous second sentence, since that is
2415          what most other compilers do.  */
2416       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (object),
2417                                                       destructor))
2418         {
2419           error ("%qE is not of type %qT", object, destructor);
2420           return error_mark_node;
2421         }
2422     }
2423
2424   return build3 (PSEUDO_DTOR_EXPR, void_type_node, object, scope, destructor);
2425 }
2426
2427 /* Finish an expression of the form CODE EXPR.  */
2428
2429 tree
2430 finish_unary_op_expr (location_t loc, enum tree_code code, tree expr,
2431                       tsubst_flags_t complain)
2432 {
2433   tree result = build_x_unary_op (loc, code, expr, complain);
2434   if ((complain & tf_warning)
2435       && TREE_OVERFLOW_P (result) && !TREE_OVERFLOW_P (expr))
2436     overflow_warning (input_location, result);
2437
2438   return result;
2439 }
2440
2441 /* Finish a compound-literal expression.  TYPE is the type to which
2442    the CONSTRUCTOR in COMPOUND_LITERAL is being cast.  */
2443
2444 tree
2445 finish_compound_literal (tree type, tree compound_literal,
2446                          tsubst_flags_t complain)
2447 {
2448   if (type == error_mark_node)
2449     return error_mark_node;
2450
2451   if (TREE_CODE (type) == REFERENCE_TYPE)
2452     {
2453       compound_literal
2454         = finish_compound_literal (TREE_TYPE (type), compound_literal,
2455                                    complain);
2456       return cp_build_c_cast (type, compound_literal, complain);
2457     }
2458
2459   if (!TYPE_OBJ_P (type))
2460     {
2461       if (complain & tf_error)
2462         error ("compound literal of non-object type %qT", type);
2463       return error_mark_node;
2464     }
2465
2466   if (processing_template_decl)
2467     {
2468       TREE_TYPE (compound_literal) = type;
2469       /* Mark the expression as a compound literal.  */
2470       TREE_HAS_CONSTRUCTOR (compound_literal) = 1;
2471       return compound_literal;
2472     }
2473
2474   type = complete_type (type);
2475
2476   if (TYPE_NON_AGGREGATE_CLASS (type))
2477     {
2478       /* Trying to deal with a CONSTRUCTOR instead of a TREE_LIST
2479          everywhere that deals with function arguments would be a pain, so
2480          just wrap it in a TREE_LIST.  The parser set a flag so we know
2481          that it came from T{} rather than T({}).  */
2482       CONSTRUCTOR_IS_DIRECT_INIT (compound_literal) = 1;
2483       compound_literal = build_tree_list (NULL_TREE, compound_literal);
2484       return build_functional_cast (type, compound_literal, complain);
2485     }
2486
2487   if (TREE_CODE (type) == ARRAY_TYPE
2488       && check_array_initializer (NULL_TREE, type, compound_literal))
2489     return error_mark_node;
2490   compound_literal = reshape_init (type, compound_literal, complain);
2491   if (SCALAR_TYPE_P (type)
2492       && !BRACE_ENCLOSED_INITIALIZER_P (compound_literal)
2493       && (complain & tf_warning_or_error))
2494     check_narrowing (type, compound_literal);
2495   if (TREE_CODE (type) == ARRAY_TYPE
2496       && TYPE_DOMAIN (type) == NULL_TREE)
2497     {
2498       cp_complete_array_type_or_error (&type, compound_literal,
2499                                        false, complain);
2500       if (type == error_mark_node)
2501         return error_mark_node;
2502     }
2503   compound_literal = digest_init (type, compound_literal, complain);
2504   if (TREE_CODE (compound_literal) == CONSTRUCTOR)
2505     TREE_HAS_CONSTRUCTOR (compound_literal) = true;
2506   /* Put static/constant array temporaries in static variables, but always
2507      represent class temporaries with TARGET_EXPR so we elide copies.  */
2508   if ((!at_function_scope_p () || CP_TYPE_CONST_P (type))
2509       && TREE_CODE (type) == ARRAY_TYPE
2510       && !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
2511       && initializer_constant_valid_p (compound_literal, type))
2512     {
2513       tree decl = create_temporary_var (type);
2514       DECL_INITIAL (decl) = compound_literal;
2515       TREE_STATIC (decl) = 1;
2516       if (literal_type_p (type) && CP_TYPE_CONST_NON_VOLATILE_P (type))
2517         {
2518           /* 5.19 says that a constant expression can include an
2519              lvalue-rvalue conversion applied to "a glvalue of literal type
2520              that refers to a non-volatile temporary object initialized
2521              with a constant expression".  Rather than try to communicate
2522              that this VAR_DECL is a temporary, just mark it constexpr.  */
2523           DECL_DECLARED_CONSTEXPR_P (decl) = true;
2524           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
2525           TREE_CONSTANT (decl) = true;
2526         }
2527       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
2528       decl = pushdecl_top_level (decl);
2529       DECL_NAME (decl) = make_anon_name ();
2530       SET_DECL_ASSEMBLER_NAME (decl, DECL_NAME (decl));
2531       return decl;
2532     }
2533   else
2534     return get_target_expr_sfinae (compound_literal, complain);
2535 }
2536
2537 /* Return the declaration for the function-name variable indicated by
2538    ID.  */
2539
2540 tree
2541 finish_fname (tree id)
2542 {
2543   tree decl;
2544
2545   decl = fname_decl (input_location, C_RID_CODE (id), id);
2546   if (processing_template_decl && current_function_decl)
2547     decl = DECL_NAME (decl);
2548   return decl;
2549 }
2550
2551 /* Finish a translation unit.  */
2552
2553 void
2554 finish_translation_unit (void)
2555 {
2556   /* In case there were missing closebraces,
2557      get us back to the global binding level.  */
2558   pop_everything ();
2559   while (current_namespace != global_namespace)
2560     pop_namespace ();
2561
2562   /* Do file scope __FUNCTION__ et al.  */
2563   finish_fname_decls ();
2564 }
2565
2566 /* Finish a template type parameter, specified as AGGR IDENTIFIER.
2567    Returns the parameter.  */
2568
2569 tree
2570 finish_template_type_parm (tree aggr, tree identifier)
2571 {
2572   if (aggr != class_type_node)
2573     {
2574       permerror (input_location, "template type parameters must use the keyword %<class%> or %<typename%>");
2575       aggr = class_type_node;
2576     }
2577
2578   return build_tree_list (aggr, identifier);
2579 }
2580
2581 /* Finish a template template parameter, specified as AGGR IDENTIFIER.
2582    Returns the parameter.  */
2583
2584 tree
2585 finish_template_template_parm (tree aggr, tree identifier)
2586 {
2587   tree decl = build_decl (input_location,
2588                           TYPE_DECL, identifier, NULL_TREE);
2589   tree tmpl = build_lang_decl (TEMPLATE_DECL, identifier, NULL_TREE);
2590   DECL_TEMPLATE_PARMS (tmpl) = current_template_parms;
2591   DECL_TEMPLATE_RESULT (tmpl) = decl;
2592   DECL_ARTIFICIAL (decl) = 1;
2593   end_template_decl ();
2594
2595   gcc_assert (DECL_TEMPLATE_PARMS (tmpl));
2596
2597   check_default_tmpl_args (decl, DECL_TEMPLATE_PARMS (tmpl), 
2598                            /*is_primary=*/true, /*is_partial=*/false,
2599                            /*is_friend=*/0);
2600
2601   return finish_template_type_parm (aggr, tmpl);
2602 }
2603
2604 /* ARGUMENT is the default-argument value for a template template
2605    parameter.  If ARGUMENT is invalid, issue error messages and return
2606    the ERROR_MARK_NODE.  Otherwise, ARGUMENT itself is returned.  */
2607
2608 tree
2609 check_template_template_default_arg (tree argument)
2610 {
2611   if (TREE_CODE (argument) != TEMPLATE_DECL
2612       && TREE_CODE (argument) != TEMPLATE_TEMPLATE_PARM
2613       && TREE_CODE (argument) != UNBOUND_CLASS_TEMPLATE)
2614     {
2615       if (TREE_CODE (argument) == TYPE_DECL)
2616         error ("invalid use of type %qT as a default value for a template "
2617                "template-parameter", TREE_TYPE (argument));
2618       else
2619         error ("invalid default argument for a template template parameter");
2620       return error_mark_node;
2621     }
2622
2623   return argument;
2624 }
2625
2626 /* Begin a class definition, as indicated by T.  */
2627
2628 tree
2629 begin_class_definition (tree t)
2630 {
2631   if (error_operand_p (t) || error_operand_p (TYPE_MAIN_DECL (t)))
2632     return error_mark_node;
2633
2634   if (processing_template_parmlist)
2635     {
2636       error ("definition of %q#T inside template parameter list", t);
2637       return error_mark_node;
2638     }
2639
2640   /* According to the C++ ABI, decimal classes defined in ISO/IEC TR 24733
2641      are passed the same as decimal scalar types.  */
2642   if (TREE_CODE (t) == RECORD_TYPE
2643       && !processing_template_decl)
2644     {
2645       tree ns = TYPE_CONTEXT (t);
2646       if (ns && TREE_CODE (ns) == NAMESPACE_DECL
2647           && DECL_CONTEXT (ns) == std_node
2648           && DECL_NAME (ns)
2649           && !strcmp (IDENTIFIER_POINTER (DECL_NAME (ns)), "decimal"))
2650         {
2651           const char *n = TYPE_NAME_STRING (t);
2652           if ((strcmp (n, "decimal32") == 0)
2653               || (strcmp (n, "decimal64") == 0)
2654               || (strcmp (n, "decimal128") == 0))
2655             TYPE_TRANSPARENT_AGGR (t) = 1;
2656         }
2657     }
2658
2659   /* A non-implicit typename comes from code like:
2660
2661        template <typename T> struct A {
2662          template <typename U> struct A<T>::B ...
2663
2664      This is erroneous.  */
2665   else if (TREE_CODE (t) == TYPENAME_TYPE)
2666     {
2667       error ("invalid definition of qualified type %qT", t);
2668       t = error_mark_node;
2669     }
2670
2671   if (t == error_mark_node || ! MAYBE_CLASS_TYPE_P (t))
2672     {
2673       t = make_class_type (RECORD_TYPE);
2674       pushtag (make_anon_name (), t, /*tag_scope=*/ts_current);
2675     }
2676
2677   if (TYPE_BEING_DEFINED (t))
2678     {
2679       t = make_class_type (TREE_CODE (t));
2680       pushtag (TYPE_IDENTIFIER (t), t, /*tag_scope=*/ts_current);
2681     }
2682   maybe_process_partial_specialization (t);
2683   pushclass (t);
2684   TYPE_BEING_DEFINED (t) = 1;
2685
2686   if (flag_pack_struct)
2687     {
2688       tree v;
2689       TYPE_PACKED (t) = 1;
2690       /* Even though the type is being defined for the first time
2691          here, there might have been a forward declaration, so there
2692          might be cv-qualified variants of T.  */
2693       for (v = TYPE_NEXT_VARIANT (t); v; v = TYPE_NEXT_VARIANT (v))
2694         TYPE_PACKED (v) = 1;
2695     }
2696   /* Reset the interface data, at the earliest possible
2697      moment, as it might have been set via a class foo;
2698      before.  */
2699   if (! TYPE_ANONYMOUS_P (t))
2700     {
2701       struct c_fileinfo *finfo = get_fileinfo (input_filename);
2702       CLASSTYPE_INTERFACE_ONLY (t) = finfo->interface_only;
2703       SET_CLASSTYPE_INTERFACE_UNKNOWN_X
2704         (t, finfo->interface_unknown);
2705     }
2706   reset_specialization();
2707
2708   /* Make a declaration for this class in its own scope.  */
2709   build_self_reference ();
2710
2711   return t;
2712 }
2713
2714 /* Finish the member declaration given by DECL.  */
2715
2716 void
2717 finish_member_declaration (tree decl)
2718 {
2719   if (decl == error_mark_node || decl == NULL_TREE)
2720     return;
2721
2722   if (decl == void_type_node)
2723     /* The COMPONENT was a friend, not a member, and so there's
2724        nothing for us to do.  */
2725     return;
2726
2727   /* We should see only one DECL at a time.  */
2728   gcc_assert (DECL_CHAIN (decl) == NULL_TREE);
2729
2730   /* Set up access control for DECL.  */
2731   TREE_PRIVATE (decl)
2732     = (current_access_specifier == access_private_node);
2733   TREE_PROTECTED (decl)
2734     = (current_access_specifier == access_protected_node);
2735   if (TREE_CODE (decl) == TEMPLATE_DECL)
2736     {
2737       TREE_PRIVATE (DECL_TEMPLATE_RESULT (decl)) = TREE_PRIVATE (decl);
2738       TREE_PROTECTED (DECL_TEMPLATE_RESULT (decl)) = TREE_PROTECTED (decl);
2739     }
2740
2741   /* Mark the DECL as a member of the current class, unless it's
2742      a member of an enumeration.  */
2743   if (TREE_CODE (decl) != CONST_DECL)
2744     DECL_CONTEXT (decl) = current_class_type;
2745
2746   /* Check for bare parameter packs in the member variable declaration.  */
2747   if (TREE_CODE (decl) == FIELD_DECL)
2748     {
2749       if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
2750         TREE_TYPE (decl) = error_mark_node;
2751       if (check_for_bare_parameter_packs (DECL_ATTRIBUTES (decl)))
2752         DECL_ATTRIBUTES (decl) = NULL_TREE;
2753     }
2754
2755   /* [dcl.link]
2756
2757      A C language linkage is ignored for the names of class members
2758      and the member function type of class member functions.  */
2759   if (DECL_LANG_SPECIFIC (decl) && DECL_LANGUAGE (decl) == lang_c)
2760     SET_DECL_LANGUAGE (decl, lang_cplusplus);
2761
2762   /* Put functions on the TYPE_METHODS list and everything else on the
2763      TYPE_FIELDS list.  Note that these are built up in reverse order.
2764      We reverse them (to obtain declaration order) in finish_struct.  */
2765   if (DECL_DECLARES_FUNCTION_P (decl))
2766     {
2767       /* We also need to add this function to the
2768          CLASSTYPE_METHOD_VEC.  */
2769       if (add_method (current_class_type, decl, NULL_TREE))
2770         {
2771           DECL_CHAIN (decl) = TYPE_METHODS (current_class_type);
2772           TYPE_METHODS (current_class_type) = decl;
2773
2774           maybe_add_class_template_decl_list (current_class_type, decl,
2775                                               /*friend_p=*/0);
2776         }
2777     }
2778   /* Enter the DECL into the scope of the class, if the class
2779      isn't a closure (whose fields are supposed to be unnamed).  */
2780   else if (CLASSTYPE_LAMBDA_EXPR (current_class_type)
2781            || pushdecl_class_level (decl))
2782     {
2783       if (TREE_CODE (decl) == USING_DECL)
2784         {
2785           /* For now, ignore class-scope USING_DECLS, so that
2786              debugging backends do not see them. */
2787           DECL_IGNORED_P (decl) = 1;
2788         }
2789
2790       /* All TYPE_DECLs go at the end of TYPE_FIELDS.  Ordinary fields
2791          go at the beginning.  The reason is that lookup_field_1
2792          searches the list in order, and we want a field name to
2793          override a type name so that the "struct stat hack" will
2794          work.  In particular:
2795
2796            struct S { enum E { }; int E } s;
2797            s.E = 3;
2798
2799          is valid.  In addition, the FIELD_DECLs must be maintained in
2800          declaration order so that class layout works as expected.
2801          However, we don't need that order until class layout, so we
2802          save a little time by putting FIELD_DECLs on in reverse order
2803          here, and then reversing them in finish_struct_1.  (We could
2804          also keep a pointer to the correct insertion points in the
2805          list.)  */
2806
2807       if (TREE_CODE (decl) == TYPE_DECL)
2808         TYPE_FIELDS (current_class_type)
2809           = chainon (TYPE_FIELDS (current_class_type), decl);
2810       else
2811         {
2812           DECL_CHAIN (decl) = TYPE_FIELDS (current_class_type);
2813           TYPE_FIELDS (current_class_type) = decl;
2814         }
2815
2816       maybe_add_class_template_decl_list (current_class_type, decl,
2817                                           /*friend_p=*/0);
2818     }
2819
2820   if (pch_file)
2821     note_decl_for_pch (decl);
2822 }
2823
2824 /* DECL has been declared while we are building a PCH file.  Perform
2825    actions that we might normally undertake lazily, but which can be
2826    performed now so that they do not have to be performed in
2827    translation units which include the PCH file.  */
2828
2829 void
2830 note_decl_for_pch (tree decl)
2831 {
2832   gcc_assert (pch_file);
2833
2834   /* There's a good chance that we'll have to mangle names at some
2835      point, even if only for emission in debugging information.  */
2836   if (VAR_OR_FUNCTION_DECL_P (decl)
2837       && !processing_template_decl)
2838     mangle_decl (decl);
2839 }
2840
2841 /* Finish processing a complete template declaration.  The PARMS are
2842    the template parameters.  */
2843
2844 void
2845 finish_template_decl (tree parms)
2846 {
2847   if (parms)
2848     end_template_decl ();
2849   else
2850     end_specialization ();
2851 }
2852
2853 /* Finish processing a template-id (which names a type) of the form
2854    NAME < ARGS >.  Return the TYPE_DECL for the type named by the
2855    template-id.  If ENTERING_SCOPE is nonzero we are about to enter
2856    the scope of template-id indicated.  */
2857
2858 tree
2859 finish_template_type (tree name, tree args, int entering_scope)
2860 {
2861   tree type;
2862
2863   type = lookup_template_class (name, args,
2864                                 NULL_TREE, NULL_TREE, entering_scope,
2865                                 tf_warning_or_error | tf_user);
2866   if (type == error_mark_node)
2867     return type;
2868   else if (CLASS_TYPE_P (type) && !alias_type_or_template_p (type))
2869     return TYPE_STUB_DECL (type);
2870   else
2871     return TYPE_NAME (type);
2872 }
2873
2874 /* Finish processing a BASE_CLASS with the indicated ACCESS_SPECIFIER.
2875    Return a TREE_LIST containing the ACCESS_SPECIFIER and the
2876    BASE_CLASS, or NULL_TREE if an error occurred.  The
2877    ACCESS_SPECIFIER is one of
2878    access_{default,public,protected_private}_node.  For a virtual base
2879    we set TREE_TYPE.  */
2880
2881 tree
2882 finish_base_specifier (tree base, tree access, bool virtual_p)
2883 {
2884   tree result;
2885
2886   if (base == error_mark_node)
2887     {
2888       error ("invalid base-class specification");
2889       result = NULL_TREE;
2890     }
2891   else if (! MAYBE_CLASS_TYPE_P (base))
2892     {
2893       error ("%qT is not a class type", base);
2894       result = NULL_TREE;
2895     }
2896   else
2897     {
2898       if (cp_type_quals (base) != 0)
2899         {
2900           /* DR 484: Can a base-specifier name a cv-qualified
2901              class type?  */
2902           base = TYPE_MAIN_VARIANT (base);
2903         }
2904       result = build_tree_list (access, base);
2905       if (virtual_p)
2906         TREE_TYPE (result) = integer_type_node;
2907     }
2908
2909   return result;
2910 }
2911
2912 /* If FNS is a member function, a set of member functions, or a
2913    template-id referring to one or more member functions, return a
2914    BASELINK for FNS, incorporating the current access context.
2915    Otherwise, return FNS unchanged.  */
2916
2917 tree
2918 baselink_for_fns (tree fns)
2919 {
2920   tree scope;
2921   tree cl;
2922
2923   if (BASELINK_P (fns) 
2924       || error_operand_p (fns))
2925     return fns;
2926
2927   scope = ovl_scope (fns);
2928   if (!CLASS_TYPE_P (scope))
2929     return fns;
2930
2931   cl = currently_open_derived_class (scope);
2932   if (!cl)
2933     cl = scope;
2934   cl = TYPE_BINFO (cl);
2935   return build_baselink (cl, cl, fns, /*optype=*/NULL_TREE);
2936 }
2937
2938 /* Returns true iff DECL is a variable from a function outside
2939    the current one.  */
2940
2941 static bool
2942 outer_var_p (tree decl)
2943 {
2944   return ((VAR_P (decl) || TREE_CODE (decl) == PARM_DECL)
2945           && DECL_FUNCTION_SCOPE_P (decl)
2946           && (DECL_CONTEXT (decl) != current_function_decl
2947               || parsing_nsdmi ()));
2948 }
2949
2950 /* As above, but also checks that DECL is automatic.  */
2951
2952 static bool
2953 outer_automatic_var_p (tree decl)
2954 {
2955   return (outer_var_p (decl)
2956           && !TREE_STATIC (decl));
2957 }
2958
2959 /* ID_EXPRESSION is a representation of parsed, but unprocessed,
2960    id-expression.  (See cp_parser_id_expression for details.)  SCOPE,
2961    if non-NULL, is the type or namespace used to explicitly qualify
2962    ID_EXPRESSION.  DECL is the entity to which that name has been
2963    resolved.
2964
2965    *CONSTANT_EXPRESSION_P is true if we are presently parsing a
2966    constant-expression.  In that case, *NON_CONSTANT_EXPRESSION_P will
2967    be set to true if this expression isn't permitted in a
2968    constant-expression, but it is otherwise not set by this function.
2969    *ALLOW_NON_CONSTANT_EXPRESSION_P is true if we are parsing a
2970    constant-expression, but a non-constant expression is also
2971    permissible.
2972
2973    DONE is true if this expression is a complete postfix-expression;
2974    it is false if this expression is followed by '->', '[', '(', etc.
2975    ADDRESS_P is true iff this expression is the operand of '&'.
2976    TEMPLATE_P is true iff the qualified-id was of the form
2977    "A::template B".  TEMPLATE_ARG_P is true iff this qualified name
2978    appears as a template argument.
2979
2980    If an error occurs, and it is the kind of error that might cause
2981    the parser to abort a tentative parse, *ERROR_MSG is filled in.  It
2982    is the caller's responsibility to issue the message.  *ERROR_MSG
2983    will be a string with static storage duration, so the caller need
2984    not "free" it.
2985
2986    Return an expression for the entity, after issuing appropriate
2987    diagnostics.  This function is also responsible for transforming a
2988    reference to a non-static member into a COMPONENT_REF that makes
2989    the use of "this" explicit.
2990
2991    Upon return, *IDK will be filled in appropriately.  */
2992 tree
2993 finish_id_expression (tree id_expression,
2994                       tree decl,
2995                       tree scope,
2996                       cp_id_kind *idk,
2997                       bool integral_constant_expression_p,
2998                       bool allow_non_integral_constant_expression_p,
2999                       bool *non_integral_constant_expression_p,
3000                       bool template_p,
3001                       bool done,
3002                       bool address_p,
3003                       bool template_arg_p,
3004                       const char **error_msg,
3005                       location_t location)
3006 {
3007   decl = strip_using_decl (decl);
3008
3009   /* Initialize the output parameters.  */
3010   *idk = CP_ID_KIND_NONE;
3011   *error_msg = NULL;
3012
3013   if (id_expression == error_mark_node)
3014     return error_mark_node;
3015   /* If we have a template-id, then no further lookup is
3016      required.  If the template-id was for a template-class, we
3017      will sometimes have a TYPE_DECL at this point.  */
3018   else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR
3019            || TREE_CODE (decl) == TYPE_DECL)
3020     ;
3021   /* Look up the name.  */
3022   else
3023     {
3024       if (decl == error_mark_node)
3025         {
3026           /* Name lookup failed.  */
3027           if (scope
3028               && (!TYPE_P (scope)
3029                   || (!dependent_type_p (scope)
3030                       && !(identifier_p (id_expression)
3031                            && IDENTIFIER_TYPENAME_P (id_expression)
3032                            && dependent_type_p (TREE_TYPE (id_expression))))))
3033             {
3034               /* If the qualifying type is non-dependent (and the name
3035                  does not name a conversion operator to a dependent
3036                  type), issue an error.  */
3037               qualified_name_lookup_error (scope, id_expression, decl, location);
3038               return error_mark_node;
3039             }
3040           else if (!scope)
3041             {
3042               /* It may be resolved via Koenig lookup.  */
3043               *idk = CP_ID_KIND_UNQUALIFIED;
3044               return id_expression;
3045             }
3046           else
3047             decl = id_expression;
3048         }
3049       /* If DECL is a variable that would be out of scope under
3050          ANSI/ISO rules, but in scope in the ARM, name lookup
3051          will succeed.  Issue a diagnostic here.  */
3052       else
3053         decl = check_for_out_of_scope_variable (decl);
3054
3055       /* Remember that the name was used in the definition of
3056          the current class so that we can check later to see if
3057          the meaning would have been different after the class
3058          was entirely defined.  */
3059       if (!scope && decl != error_mark_node && identifier_p (id_expression))
3060         maybe_note_name_used_in_class (id_expression, decl);
3061
3062       /* Disallow uses of local variables from containing functions, except
3063          within lambda-expressions.  */
3064       if (!outer_var_p (decl)
3065           /* It's not a use (3.2) if we're in an unevaluated context.  */
3066           || cp_unevaluated_operand)
3067         /* OK.  */;
3068       else if (TREE_STATIC (decl))
3069         {
3070           if (processing_template_decl)
3071             /* For a use of an outer static var, return the identifier so
3072                that we'll look it up again in the instantiation.  */
3073             return id_expression;
3074         }
3075       else
3076         {
3077           tree context = DECL_CONTEXT (decl);
3078           tree containing_function = current_function_decl;
3079           tree lambda_stack = NULL_TREE;
3080           tree lambda_expr = NULL_TREE;
3081           tree initializer = convert_from_reference (decl);
3082
3083           /* Mark it as used now even if the use is ill-formed.  */
3084           mark_used (decl);
3085
3086           /* Core issue 696: "[At the July 2009 meeting] the CWG expressed
3087              support for an approach in which a reference to a local
3088              [constant] automatic variable in a nested class or lambda body
3089              would enter the expression as an rvalue, which would reduce
3090              the complexity of the problem"
3091
3092              FIXME update for final resolution of core issue 696.  */
3093           if (decl_constant_var_p (decl))
3094             {
3095               if (processing_template_decl)
3096                 /* In a template, the constant value may not be in a usable
3097                    form, so look it up again at instantiation time.  */
3098                 return id_expression;
3099               else
3100                 return integral_constant_value (decl);
3101             }
3102
3103           if (parsing_nsdmi ())
3104             containing_function = NULL_TREE;
3105           /* If we are in a lambda function, we can move out until we hit
3106              1. the context,
3107              2. a non-lambda function, or
3108              3. a non-default capturing lambda function.  */
3109           else while (context != containing_function
3110                       && LAMBDA_FUNCTION_P (containing_function))
3111             {
3112               lambda_expr = CLASSTYPE_LAMBDA_EXPR
3113                 (DECL_CONTEXT (containing_function));
3114
3115               if (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr)
3116                   == CPLD_NONE)
3117                 break;
3118
3119               lambda_stack = tree_cons (NULL_TREE,
3120                                         lambda_expr,
3121                                         lambda_stack);
3122
3123               containing_function
3124                 = decl_function_context (containing_function);
3125             }
3126
3127           if (lambda_expr && TREE_CODE (decl) == VAR_DECL
3128               && DECL_ANON_UNION_VAR_P (decl))
3129             {
3130               error ("cannot capture member %qD of anonymous union", decl);
3131               return error_mark_node;
3132             }
3133           if (context == containing_function)
3134             {
3135               decl = add_default_capture (lambda_stack,
3136                                           /*id=*/DECL_NAME (decl),
3137                                           initializer);
3138             }
3139           else if (lambda_expr)
3140             {
3141               error ("%qD is not captured", decl);
3142               return error_mark_node;
3143             }
3144           else
3145             {
3146               error (VAR_P (decl)
3147                      ? G_("use of local variable with automatic storage from containing function")
3148                      : G_("use of parameter from containing function"));
3149               error ("  %q+#D declared here", decl);
3150               return error_mark_node;
3151             }
3152         }
3153
3154       /* Also disallow uses of function parameters outside the function
3155          body, except inside an unevaluated context (i.e. decltype).  */
3156       if (TREE_CODE (decl) == PARM_DECL
3157           && DECL_CONTEXT (decl) == NULL_TREE
3158           && !cp_unevaluated_operand)
3159         {
3160           error ("use of parameter %qD outside function body", decl);
3161           return error_mark_node;
3162         }
3163     }
3164
3165   /* If we didn't find anything, or what we found was a type,
3166      then this wasn't really an id-expression.  */
3167   if (TREE_CODE (decl) == TEMPLATE_DECL
3168       && !DECL_FUNCTION_TEMPLATE_P (decl))
3169     {
3170       *error_msg = "missing template arguments";
3171       return error_mark_node;
3172     }
3173   else if (TREE_CODE (decl) == TYPE_DECL
3174            || TREE_CODE (decl) == NAMESPACE_DECL)
3175     {
3176       *error_msg = "expected primary-expression";
3177       return error_mark_node;
3178     }
3179
3180   /* If the name resolved to a template parameter, there is no
3181      need to look it up again later.  */
3182   if ((TREE_CODE (decl) == CONST_DECL && DECL_TEMPLATE_PARM_P (decl))
3183       || TREE_CODE (decl) == TEMPLATE_PARM_INDEX)
3184     {
3185       tree r;
3186
3187       *idk = CP_ID_KIND_NONE;
3188       if (TREE_CODE (decl) == TEMPLATE_PARM_INDEX)
3189         decl = TEMPLATE_PARM_DECL (decl);
3190       r = convert_from_reference (DECL_INITIAL (decl));
3191
3192       if (integral_constant_expression_p
3193           && !dependent_type_p (TREE_TYPE (decl))
3194           && !(INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (r))))
3195         {
3196           if (!allow_non_integral_constant_expression_p)
3197             error ("template parameter %qD of type %qT is not allowed in "
3198                    "an integral constant expression because it is not of "
3199                    "integral or enumeration type", decl, TREE_TYPE (decl));
3200           *non_integral_constant_expression_p = true;
3201         }
3202       return r;
3203     }
3204   else
3205     {
3206       bool dependent_p;
3207
3208       /* If the declaration was explicitly qualified indicate
3209          that.  The semantics of `A::f(3)' are different than
3210          `f(3)' if `f' is virtual.  */
3211       *idk = (scope
3212               ? CP_ID_KIND_QUALIFIED
3213               : (TREE_CODE (decl) == TEMPLATE_ID_EXPR
3214                  ? CP_ID_KIND_TEMPLATE_ID
3215                  : CP_ID_KIND_UNQUALIFIED));
3216
3217
3218       /* [temp.dep.expr]
3219
3220          An id-expression is type-dependent if it contains an
3221          identifier that was declared with a dependent type.
3222
3223          The standard is not very specific about an id-expression that
3224          names a set of overloaded functions.  What if some of them
3225          have dependent types and some of them do not?  Presumably,
3226          such a name should be treated as a dependent name.  */
3227       /* Assume the name is not dependent.  */
3228       dependent_p = false;
3229       if (!processing_template_decl)
3230         /* No names are dependent outside a template.  */
3231         ;
3232       else if (TREE_CODE (decl) == CONST_DECL)
3233         /* We don't want to treat enumerators as dependent.  */
3234         ;
3235       /* A template-id where the name of the template was not resolved
3236          is definitely dependent.  */
3237       else if (TREE_CODE (decl) == TEMPLATE_ID_EXPR
3238                && (identifier_p (TREE_OPERAND (decl, 0))))
3239         dependent_p = true;
3240       /* For anything except an overloaded function, just check its
3241          type.  */
3242       else if (!is_overloaded_fn (decl))
3243         dependent_p
3244           = dependent_type_p (TREE_TYPE (decl));
3245       /* For a set of overloaded functions, check each of the
3246          functions.  */
3247       else
3248         {
3249           tree fns = decl;
3250
3251           if (BASELINK_P (fns))
3252             fns = BASELINK_FUNCTIONS (fns);
3253
3254           /* For a template-id, check to see if the template
3255              arguments are dependent.  */
3256           if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
3257             {
3258               tree args = TREE_OPERAND (fns, 1);
3259               dependent_p = any_dependent_template_arguments_p (args);
3260               /* The functions are those referred to by the
3261                  template-id.  */
3262               fns = TREE_OPERAND (fns, 0);
3263             }
3264
3265           /* If there are no dependent template arguments, go through
3266              the overloaded functions.  */
3267           while (fns && !dependent_p)
3268             {
3269               tree fn = OVL_CURRENT (fns);
3270
3271               /* Member functions of dependent classes are
3272                  dependent.  */
3273               if (TREE_CODE (fn) == FUNCTION_DECL
3274                   && type_dependent_expression_p (fn))
3275                 dependent_p = true;
3276               else if (TREE_CODE (fn) == TEMPLATE_DECL
3277                        && dependent_template_p (fn))
3278                 dependent_p = true;
3279
3280               fns = OVL_NEXT (fns);
3281             }
3282         }
3283
3284       /* If the name was dependent on a template parameter, we will
3285          resolve the name at instantiation time.  */
3286       if (dependent_p)
3287         {
3288           /* Create a SCOPE_REF for qualified names, if the scope is
3289              dependent.  */
3290           if (scope)
3291             {
3292               if (TYPE_P (scope))
3293                 {
3294                   if (address_p && done)
3295                     decl = finish_qualified_id_expr (scope, decl,
3296                                                      done, address_p,
3297                                                      template_p,
3298                                                      template_arg_p,
3299                                                      tf_warning_or_error);
3300                   else
3301                     {
3302                       tree type = NULL_TREE;
3303                       if (DECL_P (decl) && !dependent_scope_p (scope))
3304                         type = TREE_TYPE (decl);
3305                       decl = build_qualified_name (type,
3306                                                    scope,
3307                                                    id_expression,
3308                                                    template_p);
3309                     }
3310                 }
3311               if (TREE_TYPE (decl))
3312                 decl = convert_from_reference (decl);
3313               return decl;
3314             }
3315           /* A TEMPLATE_ID already contains all the information we
3316              need.  */
3317           if (TREE_CODE (id_expression) == TEMPLATE_ID_EXPR)
3318             return id_expression;
3319           *idk = CP_ID_KIND_UNQUALIFIED_DEPENDENT;
3320           /* If we found a variable, then name lookup during the
3321              instantiation will always resolve to the same VAR_DECL
3322              (or an instantiation thereof).  */
3323           if (VAR_P (decl)
3324               || TREE_CODE (decl) == PARM_DECL)
3325             {
3326               mark_used (decl);
3327               return convert_from_reference (decl);
3328             }
3329           /* The same is true for FIELD_DECL, but we also need to
3330              make sure that the syntax is correct.  */
3331           else if (TREE_CODE (decl) == FIELD_DECL)
3332             {
3333               /* Since SCOPE is NULL here, this is an unqualified name.
3334                  Access checking has been performed during name lookup
3335                  already.  Turn off checking to avoid duplicate errors.  */
3336               push_deferring_access_checks (dk_no_check);
3337               decl = finish_non_static_data_member
3338                        (decl, NULL_TREE,
3339                         /*qualifying_scope=*/NULL_TREE);
3340               pop_deferring_access_checks ();
3341               return decl;
3342             }
3343           return id_expression;
3344         }
3345
3346       if (TREE_CODE (decl) == NAMESPACE_DECL)
3347         {
3348           error ("use of namespace %qD as expression", decl);
3349           return error_mark_node;
3350         }
3351       else if (DECL_CLASS_TEMPLATE_P (decl))
3352         {
3353           error ("use of class template %qT as expression", decl);
3354           return error_mark_node;
3355         }
3356       else if (TREE_CODE (decl) == TREE_LIST)
3357         {
3358           /* Ambiguous reference to base members.  */
3359           error ("request for member %qD is ambiguous in "
3360                  "multiple inheritance lattice", id_expression);
3361           print_candidates (decl);
3362           return error_mark_node;
3363         }
3364
3365       /* Mark variable-like entities as used.  Functions are similarly
3366          marked either below or after overload resolution.  */
3367       if ((VAR_P (decl)
3368            || TREE_CODE (decl) == PARM_DECL
3369            || TREE_CODE (decl) == CONST_DECL
3370            || TREE_CODE (decl) == RESULT_DECL)
3371           && !mark_used (decl))
3372         return error_mark_node;
3373
3374       /* Only certain kinds of names are allowed in constant
3375          expression.  Template parameters have already
3376          been handled above.  */
3377       if (! error_operand_p (decl)
3378           && integral_constant_expression_p
3379           && ! decl_constant_var_p (decl)
3380           && TREE_CODE (decl) != CONST_DECL
3381           && ! builtin_valid_in_constant_expr_p (decl))
3382         {
3383           if (!allow_non_integral_constant_expression_p)
3384             {
3385               error ("%qD cannot appear in a constant-expression", decl);
3386               return error_mark_node;
3387             }
3388           *non_integral_constant_expression_p = true;
3389         }
3390
3391       tree wrap;
3392       if (VAR_P (decl)
3393           && !cp_unevaluated_operand
3394           && DECL_THREAD_LOCAL_P (decl)
3395           && (wrap = get_tls_wrapper_fn (decl)))
3396         {
3397           /* Replace an evaluated use of the thread_local variable with
3398              a call to its wrapper.  */
3399           decl = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
3400         }
3401       else if (scope)
3402         {
3403           decl = (adjust_result_of_qualified_name_lookup
3404                   (decl, scope, current_nonlambda_class_type()));
3405
3406           if (TREE_CODE (decl) == FUNCTION_DECL)
3407             mark_used (decl);
3408
3409           if (TYPE_P (scope))
3410             decl = finish_qualified_id_expr (scope,
3411                                              decl,
3412                                              done,
3413                                              address_p,
3414                                              template_p,
3415                                              template_arg_p,
3416                                              tf_warning_or_error);
3417           else
3418             decl = convert_from_reference (decl);
3419         }
3420       else if (TREE_CODE (decl) == FIELD_DECL)
3421         {
3422           /* Since SCOPE is NULL here, this is an unqualified name.
3423              Access checking has been performed during name lookup
3424              already.  Turn off checking to avoid duplicate errors.  */
3425           push_deferring_access_checks (dk_no_check);
3426           decl = finish_non_static_data_member (decl, NULL_TREE,
3427                                                 /*qualifying_scope=*/NULL_TREE);
3428           pop_deferring_access_checks ();
3429         }
3430       else if (is_overloaded_fn (decl))
3431         {
3432           tree first_fn;
3433
3434           first_fn = get_first_fn (decl);
3435           if (TREE_CODE (first_fn) == TEMPLATE_DECL)
3436             first_fn = DECL_TEMPLATE_RESULT (first_fn);
3437
3438           if (!really_overloaded_fn (decl)
3439               && !mark_used (first_fn))
3440             return error_mark_node;
3441
3442           if (!template_arg_p
3443               && TREE_CODE (first_fn) == FUNCTION_DECL
3444               && DECL_FUNCTION_MEMBER_P (first_fn)
3445               && !shared_member_p (decl))
3446             {
3447               /* A set of member functions.  */
3448               decl = maybe_dummy_object (DECL_CONTEXT (first_fn), 0);
3449               return finish_class_member_access_expr (decl, id_expression,
3450                                                       /*template_p=*/false,
3451                                                       tf_warning_or_error);
3452             }
3453
3454           decl = baselink_for_fns (decl);
3455         }
3456       else
3457         {
3458           if (DECL_P (decl) && DECL_NONLOCAL (decl)
3459               && DECL_CLASS_SCOPE_P (decl))
3460             {
3461               tree context = context_for_name_lookup (decl); 
3462               if (context != current_class_type)
3463                 {
3464                   tree path = currently_open_derived_class (context);
3465                   perform_or_defer_access_check (TYPE_BINFO (path),
3466                                                  decl, decl,
3467                                                  tf_warning_or_error);
3468                 }
3469             }
3470
3471           decl = convert_from_reference (decl);
3472         }
3473     }
3474
3475   if (TREE_DEPRECATED (decl))
3476     warn_deprecated_use (decl, NULL_TREE);
3477
3478   return decl;
3479 }
3480
3481 /* Implement the __typeof keyword: Return the type of EXPR, suitable for
3482    use as a type-specifier.  */
3483
3484 tree
3485 finish_typeof (tree expr)
3486 {
3487   tree type;
3488
3489   if (type_dependent_expression_p (expr))
3490     {
3491       type = cxx_make_type (TYPEOF_TYPE);
3492       TYPEOF_TYPE_EXPR (type) = expr;
3493       SET_TYPE_STRUCTURAL_EQUALITY (type);
3494
3495       return type;
3496     }
3497
3498   expr = mark_type_use (expr);
3499
3500   type = unlowered_expr_type (expr);
3501
3502   if (!type || type == unknown_type_node)
3503     {
3504       error ("type of %qE is unknown", expr);
3505       return error_mark_node;
3506     }
3507
3508   return type;
3509 }
3510
3511 /* Implement the __underlying_type keyword: Return the underlying
3512    type of TYPE, suitable for use as a type-specifier.  */
3513
3514 tree
3515 finish_underlying_type (tree type)
3516 {
3517   tree underlying_type;
3518
3519   if (processing_template_decl)
3520     {
3521       underlying_type = cxx_make_type (UNDERLYING_TYPE);
3522       UNDERLYING_TYPE_TYPE (underlying_type) = type;
3523       SET_TYPE_STRUCTURAL_EQUALITY (underlying_type);
3524
3525       return underlying_type;
3526     }
3527
3528   complete_type (type);
3529
3530   if (TREE_CODE (type) != ENUMERAL_TYPE)
3531     {
3532       error ("%qT is not an enumeration type", type);
3533       return error_mark_node;
3534     }
3535
3536   underlying_type = ENUM_UNDERLYING_TYPE (type);
3537
3538   /* Fixup necessary in this case because ENUM_UNDERLYING_TYPE
3539      includes TYPE_MIN_VALUE and TYPE_MAX_VALUE information.
3540      See finish_enum_value_list for details.  */
3541   if (!ENUM_FIXED_UNDERLYING_TYPE_P (type))
3542     underlying_type
3543       = c_common_type_for_mode (TYPE_MODE (underlying_type),
3544                                 TYPE_UNSIGNED (underlying_type));
3545
3546   return underlying_type;
3547 }
3548
3549 /* Implement the __direct_bases keyword: Return the direct base classes
3550    of type */
3551
3552 tree
3553 calculate_direct_bases (tree type)
3554 {
3555   vec<tree, va_gc> *vector = make_tree_vector();
3556   tree bases_vec = NULL_TREE;
3557   vec<tree, va_gc> *base_binfos;
3558   tree binfo;
3559   unsigned i;
3560
3561   complete_type (type);
3562
3563   if (!NON_UNION_CLASS_TYPE_P (type))
3564     return make_tree_vec (0);
3565
3566   base_binfos = BINFO_BASE_BINFOS (TYPE_BINFO (type));
3567
3568   /* Virtual bases are initialized first */
3569   for (i = 0; base_binfos->iterate (i, &binfo); i++)
3570     {
3571       if (BINFO_VIRTUAL_P (binfo))
3572        {
3573          vec_safe_push (vector, binfo);
3574        }
3575     }
3576
3577   /* Now non-virtuals */
3578   for (i = 0; base_binfos->iterate (i, &binfo); i++)
3579     {
3580       if (!BINFO_VIRTUAL_P (binfo))
3581        {
3582          vec_safe_push (vector, binfo);
3583        }
3584     }
3585
3586
3587   bases_vec = make_tree_vec (vector->length ());
3588
3589   for (i = 0; i < vector->length (); ++i)
3590     {
3591       TREE_VEC_ELT (bases_vec, i) = BINFO_TYPE ((*vector)[i]);
3592     }
3593   return bases_vec;
3594 }
3595
3596 /* Implement the __bases keyword: Return the base classes
3597    of type */
3598
3599 /* Find morally non-virtual base classes by walking binfo hierarchy */
3600 /* Virtual base classes are handled separately in finish_bases */
3601
3602 static tree
3603 dfs_calculate_bases_pre (tree binfo, void * /*data_*/)
3604 {
3605   /* Don't walk bases of virtual bases */
3606   return BINFO_VIRTUAL_P (binfo) ? dfs_skip_bases : NULL_TREE;
3607 }
3608
3609 static tree
3610 dfs_calculate_bases_post (tree binfo, void *data_)
3611 {
3612   vec<tree, va_gc> **data = ((vec<tree, va_gc> **) data_);
3613   if (!BINFO_VIRTUAL_P (binfo))
3614     {
3615       vec_safe_push (*data, BINFO_TYPE (binfo));
3616     }
3617   return NULL_TREE;
3618 }
3619
3620 /* Calculates the morally non-virtual base classes of a class */
3621 static vec<tree, va_gc> *
3622 calculate_bases_helper (tree type)
3623 {
3624   vec<tree, va_gc> *vector = make_tree_vector();
3625
3626   /* Now add non-virtual base classes in order of construction */
3627   dfs_walk_all (TYPE_BINFO (type),
3628                 dfs_calculate_bases_pre, dfs_calculate_bases_post, &vector);
3629   return vector;
3630 }
3631
3632 tree
3633 calculate_bases (tree type)
3634 {
3635   vec<tree, va_gc> *vector = make_tree_vector();
3636   tree bases_vec = NULL_TREE;
3637   unsigned i;
3638   vec<tree, va_gc> *vbases;
3639   vec<tree, va_gc> *nonvbases;
3640   tree binfo;
3641
3642   complete_type (type);
3643
3644   if (!NON_UNION_CLASS_TYPE_P (type))
3645     return make_tree_vec (0);
3646
3647   /* First go through virtual base classes */
3648   for (vbases = CLASSTYPE_VBASECLASSES (type), i = 0;
3649        vec_safe_iterate (vbases, i, &binfo); i++)
3650     {
3651       vec<tree, va_gc> *vbase_bases;
3652       vbase_bases = calculate_bases_helper (BINFO_TYPE (binfo));
3653       vec_safe_splice (vector, vbase_bases);
3654       release_tree_vector (vbase_bases);
3655     }
3656
3657   /* Now for the non-virtual bases */
3658   nonvbases = calculate_bases_helper (type);
3659   vec_safe_splice (vector, nonvbases);
3660   release_tree_vector (nonvbases);
3661
3662   /* Last element is entire class, so don't copy */
3663   bases_vec = make_tree_vec (vector->length () - 1);
3664
3665   for (i = 0; i < vector->length () - 1; ++i)
3666     {
3667       TREE_VEC_ELT (bases_vec, i) = (*vector)[i];
3668     }
3669   release_tree_vector (vector);
3670   return bases_vec;
3671 }
3672
3673 tree
3674 finish_bases (tree type, bool direct)
3675 {
3676   tree bases = NULL_TREE;
3677
3678   if (!processing_template_decl)
3679     {
3680       /* Parameter packs can only be used in templates */
3681       error ("Parameter pack __bases only valid in template declaration");
3682       return error_mark_node;
3683     }
3684
3685   bases = cxx_make_type (BASES);
3686   BASES_TYPE (bases) = type;
3687   BASES_DIRECT (bases) = direct;
3688   SET_TYPE_STRUCTURAL_EQUALITY (bases);
3689
3690   return bases;
3691 }
3692
3693 /* Perform C++-specific checks for __builtin_offsetof before calling
3694    fold_offsetof.  */
3695
3696 tree
3697 finish_offsetof (tree expr)
3698 {
3699   if (TREE_CODE (expr) == PSEUDO_DTOR_EXPR)
3700     {
3701       error ("cannot apply %<offsetof%> to destructor %<~%T%>",
3702               TREE_OPERAND (expr, 2));
3703       return error_mark_node;
3704     }
3705   if (TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
3706       || TREE_CODE (TREE_TYPE (expr)) == METHOD_TYPE
3707       || TREE_TYPE (expr) == unknown_type_node)
3708     {
3709       if (TREE_CODE (expr) == INDIRECT_REF)
3710         error ("second operand of %<offsetof%> is neither a single "
3711                "identifier nor a sequence of member accesses and "
3712                "array references");
3713       else
3714         {
3715           if (TREE_CODE (expr) == COMPONENT_REF
3716               || TREE_CODE (expr) == COMPOUND_EXPR)
3717             expr = TREE_OPERAND (expr, 1);
3718           error ("cannot apply %<offsetof%> to member function %qD", expr);
3719         }
3720       return error_mark_node;
3721     }
3722   if (REFERENCE_REF_P (expr))
3723     expr = TREE_OPERAND (expr, 0);
3724   if (TREE_CODE (expr) == COMPONENT_REF)
3725     {
3726       tree object = TREE_OPERAND (expr, 0);
3727       if (!complete_type_or_else (TREE_TYPE (object), object))
3728         return error_mark_node;
3729     }
3730   return fold_offsetof (expr);
3731 }
3732
3733 /* Replace the AGGR_INIT_EXPR at *TP with an equivalent CALL_EXPR.  This
3734    function is broken out from the above for the benefit of the tree-ssa
3735    project.  */
3736
3737 void
3738 simplify_aggr_init_expr (tree *tp)
3739 {
3740   tree aggr_init_expr = *tp;
3741
3742   /* Form an appropriate CALL_EXPR.  */
3743   tree fn = AGGR_INIT_EXPR_FN (aggr_init_expr);
3744   tree slot = AGGR_INIT_EXPR_SLOT (aggr_init_expr);
3745   tree type = TREE_TYPE (slot);
3746
3747   tree call_expr;
3748   enum style_t { ctor, arg, pcc } style;
3749
3750   if (AGGR_INIT_VIA_CTOR_P (aggr_init_expr))
3751     style = ctor;
3752 #ifdef PCC_STATIC_STRUCT_RETURN
3753   else if (1)
3754     style = pcc;
3755 #endif
3756   else
3757     {
3758       gcc_assert (TREE_ADDRESSABLE (type));
3759       style = arg;
3760     }
3761
3762   call_expr = build_call_array_loc (input_location,
3763                                     TREE_TYPE (TREE_TYPE (TREE_TYPE (fn))),
3764                                     fn,
3765                                     aggr_init_expr_nargs (aggr_init_expr),
3766                                     AGGR_INIT_EXPR_ARGP (aggr_init_expr));
3767   TREE_NOTHROW (call_expr) = TREE_NOTHROW (aggr_init_expr);
3768
3769   if (style == ctor)
3770     {
3771       /* Replace the first argument to the ctor with the address of the
3772          slot.  */
3773       cxx_mark_addressable (slot);
3774       CALL_EXPR_ARG (call_expr, 0) =
3775         build1 (ADDR_EXPR, build_pointer_type (type), slot);
3776     }
3777   else if (style == arg)
3778     {
3779       /* Just mark it addressable here, and leave the rest to
3780          expand_call{,_inline}.  */
3781       cxx_mark_addressable (slot);
3782       CALL_EXPR_RETURN_SLOT_OPT (call_expr) = true;
3783       call_expr = build2 (INIT_EXPR, TREE_TYPE (call_expr), slot, call_expr);
3784     }
3785   else if (style == pcc)
3786     {
3787       /* If we're using the non-reentrant PCC calling convention, then we
3788          need to copy the returned value out of the static buffer into the
3789          SLOT.  */
3790       push_deferring_access_checks (dk_no_check);
3791       call_expr = build_aggr_init (slot, call_expr,
3792                                    DIRECT_BIND | LOOKUP_ONLYCONVERTING,
3793                                    tf_warning_or_error);
3794       pop_deferring_access_checks ();
3795       call_expr = build2 (COMPOUND_EXPR, TREE_TYPE (slot), call_expr, slot);
3796     }
3797
3798   if (AGGR_INIT_ZERO_FIRST (aggr_init_expr))
3799     {
3800       tree init = build_zero_init (type, NULL_TREE,
3801                                    /*static_storage_p=*/false);
3802       init = build2 (INIT_EXPR, void_type_node, slot, init);
3803       call_expr = build2 (COMPOUND_EXPR, TREE_TYPE (call_expr),
3804                           init, call_expr);
3805     }
3806
3807   *tp = call_expr;
3808 }
3809
3810 /* Emit all thunks to FN that should be emitted when FN is emitted.  */
3811
3812 void
3813 emit_associated_thunks (tree fn)
3814 {
3815   /* When we use vcall offsets, we emit thunks with the virtual
3816      functions to which they thunk. The whole point of vcall offsets
3817      is so that you can know statically the entire set of thunks that
3818      will ever be needed for a given virtual function, thereby
3819      enabling you to output all the thunks with the function itself.  */
3820   if (DECL_VIRTUAL_P (fn)
3821       /* Do not emit thunks for extern template instantiations.  */
3822       && ! DECL_REALLY_EXTERN (fn))
3823     {
3824       tree thunk;
3825
3826       for (thunk = DECL_THUNKS (fn); thunk; thunk = DECL_CHAIN (thunk))
3827         {
3828           if (!THUNK_ALIAS (thunk))
3829             {
3830               use_thunk (thunk, /*emit_p=*/1);
3831               if (DECL_RESULT_THUNK_P (thunk))
3832                 {
3833                   tree probe;
3834
3835                   for (probe = DECL_THUNKS (thunk);
3836                        probe; probe = DECL_CHAIN (probe))
3837                     use_thunk (probe, /*emit_p=*/1);
3838                 }
3839             }
3840           else
3841             gcc_assert (!DECL_THUNKS (thunk));
3842         }
3843     }
3844 }
3845
3846 /* Returns true iff FUN is an instantiation of a constexpr function
3847    template.  */
3848
3849 static inline bool
3850 is_instantiation_of_constexpr (tree fun)
3851 {
3852   return (DECL_TEMPLOID_INSTANTIATION (fun)
3853           && DECL_DECLARED_CONSTEXPR_P (DECL_TEMPLATE_RESULT
3854                                         (DECL_TI_TEMPLATE (fun))));
3855 }
3856
3857 /* Generate RTL for FN.  */
3858
3859 bool
3860 expand_or_defer_fn_1 (tree fn)
3861 {
3862   /* When the parser calls us after finishing the body of a template
3863      function, we don't really want to expand the body.  */
3864   if (processing_template_decl)
3865     {
3866       /* Normally, collection only occurs in rest_of_compilation.  So,
3867          if we don't collect here, we never collect junk generated
3868          during the processing of templates until we hit a
3869          non-template function.  It's not safe to do this inside a
3870          nested class, though, as the parser may have local state that
3871          is not a GC root.  */
3872       if (!function_depth)
3873         ggc_collect ();
3874       return false;
3875     }
3876
3877   gcc_assert (DECL_SAVED_TREE (fn));
3878
3879   /* If this is a constructor or destructor body, we have to clone
3880      it.  */
3881   if (maybe_clone_body (fn))
3882     {
3883       /* We don't want to process FN again, so pretend we've written
3884          it out, even though we haven't.  */
3885       TREE_ASM_WRITTEN (fn) = 1;
3886       /* If this is an instantiation of a constexpr function, keep
3887          DECL_SAVED_TREE for explain_invalid_constexpr_fn.  */
3888       if (!is_instantiation_of_constexpr (fn))
3889         DECL_SAVED_TREE (fn) = NULL_TREE;
3890       return false;
3891     }
3892
3893   /* We make a decision about linkage for these functions at the end
3894      of the compilation.  Until that point, we do not want the back
3895      end to output them -- but we do want it to see the bodies of
3896      these functions so that it can inline them as appropriate.  */
3897   if (DECL_DECLARED_INLINE_P (fn) || DECL_IMPLICIT_INSTANTIATION (fn))
3898     {
3899       if (DECL_INTERFACE_KNOWN (fn))
3900         /* We've already made a decision as to how this function will
3901            be handled.  */;
3902       else if (!at_eof)
3903         {
3904           DECL_EXTERNAL (fn) = 1;
3905           DECL_NOT_REALLY_EXTERN (fn) = 1;
3906           note_vague_linkage_fn (fn);
3907           /* A non-template inline function with external linkage will
3908              always be COMDAT.  As we must eventually determine the
3909              linkage of all functions, and as that causes writes to
3910              the data mapped in from the PCH file, it's advantageous
3911              to mark the functions at this point.  */
3912           if (!DECL_IMPLICIT_INSTANTIATION (fn))
3913             {
3914               /* This function must have external linkage, as
3915                  otherwise DECL_INTERFACE_KNOWN would have been
3916                  set.  */
3917               gcc_assert (TREE_PUBLIC (fn));
3918               comdat_linkage (fn);
3919               DECL_INTERFACE_KNOWN (fn) = 1;
3920             }
3921         }
3922       else
3923         import_export_decl (fn);
3924
3925       /* If the user wants us to keep all inline functions, then mark
3926          this function as needed so that finish_file will make sure to
3927          output it later.  Similarly, all dllexport'd functions must
3928          be emitted; there may be callers in other DLLs.  */
3929       if ((flag_keep_inline_functions
3930            && DECL_DECLARED_INLINE_P (fn)
3931            && !DECL_REALLY_EXTERN (fn))
3932           || (flag_keep_inline_dllexport
3933               && lookup_attribute ("dllexport", DECL_ATTRIBUTES (fn))))
3934         {
3935           mark_needed (fn);
3936           DECL_EXTERNAL (fn) = 0;
3937         }
3938     }
3939
3940   /* There's no reason to do any of the work here if we're only doing
3941      semantic analysis; this code just generates RTL.  */
3942   if (flag_syntax_only)
3943     return false;
3944
3945   return true;
3946 }
3947
3948 void
3949 expand_or_defer_fn (tree fn)
3950 {
3951   if (expand_or_defer_fn_1 (fn))
3952     {
3953       function_depth++;
3954
3955       /* Expand or defer, at the whim of the compilation unit manager.  */
3956       cgraph_finalize_function (fn, function_depth > 1);
3957       emit_associated_thunks (fn);
3958
3959       function_depth--;
3960     }
3961 }
3962
3963 struct nrv_data
3964 {
3965   tree var;
3966   tree result;
3967   hash_table <pointer_hash <tree_node> > visited;
3968 };
3969
3970 /* Helper function for walk_tree, used by finalize_nrv below.  */
3971
3972 static tree
3973 finalize_nrv_r (tree* tp, int* walk_subtrees, void* data)
3974 {
3975   struct nrv_data *dp = (struct nrv_data *)data;
3976   tree_node **slot;
3977
3978   /* No need to walk into types.  There wouldn't be any need to walk into
3979      non-statements, except that we have to consider STMT_EXPRs.  */
3980   if (TYPE_P (*tp))
3981     *walk_subtrees = 0;
3982   /* Change all returns to just refer to the RESULT_DECL; this is a nop,
3983      but differs from using NULL_TREE in that it indicates that we care
3984      about the value of the RESULT_DECL.  */
3985   else if (TREE_CODE (*tp) == RETURN_EXPR)
3986     TREE_OPERAND (*tp, 0) = dp->result;
3987   /* Change all cleanups for the NRV to only run when an exception is
3988      thrown.  */
3989   else if (TREE_CODE (*tp) == CLEANUP_STMT
3990            && CLEANUP_DECL (*tp) == dp->var)
3991     CLEANUP_EH_ONLY (*tp) = 1;
3992   /* Replace the DECL_EXPR for the NRV with an initialization of the
3993      RESULT_DECL, if needed.  */
3994   else if (TREE_CODE (*tp) == DECL_EXPR
3995            && DECL_EXPR_DECL (*tp) == dp->var)
3996     {
3997       tree init;
3998       if (DECL_INITIAL (dp->var)
3999           && DECL_INITIAL (dp->var) != error_mark_node)
4000         init = build2 (INIT_EXPR, void_type_node, dp->result,
4001                        DECL_INITIAL (dp->var));
4002       else
4003         init = build_empty_stmt (EXPR_LOCATION (*tp));
4004       DECL_INITIAL (dp->var) = NULL_TREE;
4005       SET_EXPR_LOCATION (init, EXPR_LOCATION (*tp));
4006       *tp = init;
4007     }
4008   /* And replace all uses of the NRV with the RESULT_DECL.  */
4009   else if (*tp == dp->var)
4010     *tp = dp->result;
4011
4012   /* Avoid walking into the same tree more than once.  Unfortunately, we
4013      can't just use walk_tree_without duplicates because it would only call
4014      us for the first occurrence of dp->var in the function body.  */
4015   slot = dp->visited.find_slot (*tp, INSERT);
4016   if (*slot)
4017     *walk_subtrees = 0;
4018   else
4019     *slot = *tp;
4020
4021   /* Keep iterating.  */
4022   return NULL_TREE;
4023 }
4024
4025 /* Called from finish_function to implement the named return value
4026    optimization by overriding all the RETURN_EXPRs and pertinent
4027    CLEANUP_STMTs and replacing all occurrences of VAR with RESULT, the
4028    RESULT_DECL for the function.  */
4029
4030 void
4031 finalize_nrv (tree *tp, tree var, tree result)
4032 {
4033   struct nrv_data data;
4034
4035   /* Copy name from VAR to RESULT.  */
4036   DECL_NAME (result) = DECL_NAME (var);
4037   /* Don't forget that we take its address.  */
4038   TREE_ADDRESSABLE (result) = TREE_ADDRESSABLE (var);
4039   /* Finally set DECL_VALUE_EXPR to avoid assigning
4040      a stack slot at -O0 for the original var and debug info
4041      uses RESULT location for VAR.  */
4042   SET_DECL_VALUE_EXPR (var, result);
4043   DECL_HAS_VALUE_EXPR_P (var) = 1;
4044
4045   data.var = var;
4046   data.result = result;
4047   data.visited.create (37);
4048   cp_walk_tree (tp, finalize_nrv_r, &data, 0);
4049   data.visited.dispose ();
4050 }
4051 \f
4052 /* Create CP_OMP_CLAUSE_INFO for clause C.  Returns true if it is invalid.  */
4053
4054 bool
4055 cxx_omp_create_clause_info (tree c, tree type, bool need_default_ctor,
4056                             bool need_copy_ctor, bool need_copy_assignment)
4057 {
4058   int save_errorcount = errorcount;
4059   tree info, t;
4060
4061   /* Always allocate 3 elements for simplicity.  These are the
4062      function decls for the ctor, dtor, and assignment op.
4063      This layout is known to the three lang hooks,
4064      cxx_omp_clause_default_init, cxx_omp_clause_copy_init,
4065      and cxx_omp_clause_assign_op.  */
4066   info = make_tree_vec (3);
4067   CP_OMP_CLAUSE_INFO (c) = info;
4068
4069   if (need_default_ctor || need_copy_ctor)
4070     {
4071       if (need_default_ctor)
4072         t = get_default_ctor (type);
4073       else
4074         t = get_copy_ctor (type, tf_warning_or_error);
4075
4076       if (t && !trivial_fn_p (t))
4077         TREE_VEC_ELT (info, 0) = t;
4078     }
4079
4080   if ((need_default_ctor || need_copy_ctor)
4081       && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
4082     TREE_VEC_ELT (info, 1) = get_dtor (type, tf_warning_or_error);
4083
4084   if (need_copy_assignment)
4085     {
4086       t = get_copy_assign (type);
4087
4088       if (t && !trivial_fn_p (t))
4089         TREE_VEC_ELT (info, 2) = t;
4090     }
4091
4092   return errorcount != save_errorcount;
4093 }
4094
4095 /* For all elements of CLAUSES, validate them vs OpenMP constraints.
4096    Remove any elements from the list that are invalid.  */
4097
4098 tree
4099 finish_omp_clauses (tree clauses)
4100 {
4101   bitmap_head generic_head, firstprivate_head, lastprivate_head;
4102   tree c, t, *pc = &clauses;
4103   const char *name;
4104
4105   bitmap_obstack_initialize (NULL);
4106   bitmap_initialize (&generic_head, &bitmap_default_obstack);
4107   bitmap_initialize (&firstprivate_head, &bitmap_default_obstack);
4108   bitmap_initialize (&lastprivate_head, &bitmap_default_obstack);
4109
4110   for (pc = &clauses, c = clauses; c ; c = *pc)
4111     {
4112       bool remove = false;
4113
4114       switch (OMP_CLAUSE_CODE (c))
4115         {
4116         case OMP_CLAUSE_SHARED:
4117           name = "shared";
4118           goto check_dup_generic;
4119         case OMP_CLAUSE_PRIVATE:
4120           name = "private";
4121           goto check_dup_generic;
4122         case OMP_CLAUSE_REDUCTION:
4123           name = "reduction";
4124           goto check_dup_generic;
4125         case OMP_CLAUSE_COPYPRIVATE:
4126           name = "copyprivate";
4127           goto check_dup_generic;
4128         case OMP_CLAUSE_COPYIN:
4129           name = "copyin";
4130           goto check_dup_generic;
4131         check_dup_generic:
4132           t = OMP_CLAUSE_DECL (c);
4133           if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL)
4134             {
4135               if (processing_template_decl)
4136                 break;
4137               if (DECL_P (t))
4138                 error ("%qD is not a variable in clause %qs", t, name);
4139               else
4140                 error ("%qE is not a variable in clause %qs", t, name);
4141               remove = true;
4142             }
4143           else if (bitmap_bit_p (&generic_head, DECL_UID (t))
4144                    || bitmap_bit_p (&firstprivate_head, DECL_UID (t))
4145                    || bitmap_bit_p (&lastprivate_head, DECL_UID (t)))
4146             {
4147               error ("%qD appears more than once in data clauses", t);
4148               remove = true;
4149             }
4150           else
4151             bitmap_set_bit (&generic_head, DECL_UID (t));
4152           break;
4153
4154         case OMP_CLAUSE_FIRSTPRIVATE:
4155           t = OMP_CLAUSE_DECL (c);
4156           if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL)
4157             {
4158               if (processing_template_decl)
4159                 break;
4160               if (DECL_P (t))
4161                 error ("%qD is not a variable in clause %<firstprivate%>", t);
4162               else
4163                 error ("%qE is not a variable in clause %<firstprivate%>", t);
4164               remove = true;
4165             }
4166           else if (bitmap_bit_p (&generic_head, DECL_UID (t))
4167                    || bitmap_bit_p (&firstprivate_head, DECL_UID (t)))
4168             {
4169               error ("%qD appears more than once in data clauses", t);
4170               remove = true;
4171             }
4172           else
4173             bitmap_set_bit (&firstprivate_head, DECL_UID (t));
4174           break;
4175
4176         case OMP_CLAUSE_LASTPRIVATE:
4177           t = OMP_CLAUSE_DECL (c);
4178           if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL)
4179             {
4180               if (processing_template_decl)
4181                 break;
4182               if (DECL_P (t))
4183                 error ("%qD is not a variable in clause %<lastprivate%>", t);
4184               else
4185                 error ("%qE is not a variable in clause %<lastprivate%>", t);
4186               remove = true;
4187             }
4188           else if (bitmap_bit_p (&generic_head, DECL_UID (t))
4189                    || bitmap_bit_p (&lastprivate_head, DECL_UID (t)))
4190             {
4191               error ("%qD appears more than once in data clauses", t);
4192               remove = true;
4193             }
4194           else
4195             bitmap_set_bit (&lastprivate_head, DECL_UID (t));
4196           break;
4197
4198         case OMP_CLAUSE_IF:
4199           t = OMP_CLAUSE_IF_EXPR (c);
4200           t = maybe_convert_cond (t);
4201           if (t == error_mark_node)
4202             remove = true;
4203           else if (!processing_template_decl)
4204             t = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4205           OMP_CLAUSE_IF_EXPR (c) = t;
4206           break;
4207
4208         case OMP_CLAUSE_FINAL:
4209           t = OMP_CLAUSE_FINAL_EXPR (c);
4210           t = maybe_convert_cond (t);
4211           if (t == error_mark_node)
4212             remove = true;
4213           else if (!processing_template_decl)
4214             t = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4215           OMP_CLAUSE_FINAL_EXPR (c) = t;
4216           break;
4217
4218         case OMP_CLAUSE_NUM_THREADS:
4219           t = OMP_CLAUSE_NUM_THREADS_EXPR (c);
4220           if (t == error_mark_node)
4221             remove = true;
4222           else if (!type_dependent_expression_p (t)
4223                    && !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4224             {
4225               error ("num_threads expression must be integral");
4226               remove = true;
4227             }
4228           else
4229             {
4230               t = mark_rvalue_use (t);
4231               if (!processing_template_decl)
4232                 t = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4233               OMP_CLAUSE_NUM_THREADS_EXPR (c) = t;
4234             }
4235           break;
4236
4237         case OMP_CLAUSE_SCHEDULE:
4238           t = OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c);
4239           if (t == NULL)
4240             ;
4241           else if (t == error_mark_node)
4242             remove = true;
4243           else if (!type_dependent_expression_p (t)
4244                    && !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4245             {
4246               error ("schedule chunk size expression must be integral");
4247               remove = true;
4248             }
4249           else
4250             {
4251               t = mark_rvalue_use (t);
4252               if (!processing_template_decl)
4253                 t = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4254               OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c) = t;
4255             }
4256           break;
4257
4258         case OMP_CLAUSE_NOWAIT:
4259         case OMP_CLAUSE_ORDERED:
4260         case OMP_CLAUSE_DEFAULT:
4261         case OMP_CLAUSE_UNTIED:
4262         case OMP_CLAUSE_COLLAPSE:
4263         case OMP_CLAUSE_MERGEABLE:
4264           break;
4265
4266         default:
4267           gcc_unreachable ();
4268         }
4269
4270       if (remove)
4271         *pc = OMP_CLAUSE_CHAIN (c);
4272       else
4273         pc = &OMP_CLAUSE_CHAIN (c);
4274     }
4275
4276   for (pc = &clauses, c = clauses; c ; c = *pc)
4277     {
4278       enum omp_clause_code c_kind = OMP_CLAUSE_CODE (c);
4279       bool remove = false;
4280       bool need_complete_non_reference = false;
4281       bool need_default_ctor = false;
4282       bool need_copy_ctor = false;
4283       bool need_copy_assignment = false;
4284       bool need_implicitly_determined = false;
4285       tree type, inner_type;
4286
4287       switch (c_kind)
4288         {
4289         case OMP_CLAUSE_SHARED:
4290           name = "shared";
4291           need_implicitly_determined = true;
4292           break;
4293         case OMP_CLAUSE_PRIVATE:
4294           name = "private";
4295           need_complete_non_reference = true;
4296           need_default_ctor = true;
4297           need_implicitly_determined = true;
4298           break;
4299         case OMP_CLAUSE_FIRSTPRIVATE:
4300           name = "firstprivate";
4301           need_complete_non_reference = true;
4302           need_copy_ctor = true;
4303           need_implicitly_determined = true;
4304           break;
4305         case OMP_CLAUSE_LASTPRIVATE:
4306           name = "lastprivate";
4307           need_complete_non_reference = true;
4308           need_copy_assignment = true;
4309           need_implicitly_determined = true;
4310           break;
4311         case OMP_CLAUSE_REDUCTION:
4312           name = "reduction";
4313           need_implicitly_determined = true;
4314           break;
4315         case OMP_CLAUSE_COPYPRIVATE:
4316           name = "copyprivate";
4317           need_copy_assignment = true;
4318           break;
4319         case OMP_CLAUSE_COPYIN:
4320           name = "copyin";
4321           need_copy_assignment = true;
4322           break;
4323         default:
4324           pc = &OMP_CLAUSE_CHAIN (c);
4325           continue;
4326         }
4327
4328       t = OMP_CLAUSE_DECL (c);
4329       if (processing_template_decl
4330           && !VAR_P (t) && TREE_CODE (t) != PARM_DECL)
4331         {
4332           pc = &OMP_CLAUSE_CHAIN (c);
4333           continue;
4334         }
4335
4336       switch (c_kind)
4337         {
4338         case OMP_CLAUSE_LASTPRIVATE:
4339           if (!bitmap_bit_p (&firstprivate_head, DECL_UID (t)))
4340             need_default_ctor = true;
4341           break;
4342
4343         case OMP_CLAUSE_REDUCTION:
4344           if (AGGREGATE_TYPE_P (TREE_TYPE (t))
4345               || POINTER_TYPE_P (TREE_TYPE (t)))
4346             {
4347               error ("%qE has invalid type for %<reduction%>", t);
4348               remove = true;
4349             }
4350           else if (FLOAT_TYPE_P (TREE_TYPE (t)))
4351             {
4352               enum tree_code r_code = OMP_CLAUSE_REDUCTION_CODE (c);
4353               switch (r_code)
4354                 {
4355                 case PLUS_EXPR:
4356                 case MULT_EXPR:
4357                 case MINUS_EXPR:
4358                 case MIN_EXPR:
4359                 case MAX_EXPR:
4360                   break;
4361                 default:
4362                   error ("%qE has invalid type for %<reduction(%s)%>",
4363                          t, operator_name_info[r_code].name);
4364                   remove = true;
4365                 }
4366             }
4367           break;
4368
4369         case OMP_CLAUSE_COPYIN:
4370           if (!VAR_P (t) || !DECL_THREAD_LOCAL_P (t))
4371             {
4372               error ("%qE must be %<threadprivate%> for %<copyin%>", t);
4373               remove = true;
4374             }
4375           break;
4376
4377         default:
4378           break;
4379         }
4380
4381       if (need_complete_non_reference || need_copy_assignment)
4382         {
4383           t = require_complete_type (t);
4384           if (t == error_mark_node)
4385             remove = true;
4386           else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
4387                    && need_complete_non_reference)
4388             {
4389               error ("%qE has reference type for %qs", t, name);
4390               remove = true;
4391             }
4392         }
4393       if (need_implicitly_determined)
4394         {
4395           const char *share_name = NULL;
4396
4397           if (VAR_P (t) && DECL_THREAD_LOCAL_P (t))
4398             share_name = "threadprivate";
4399           else switch (cxx_omp_predetermined_sharing (t))
4400             {
4401             case OMP_CLAUSE_DEFAULT_UNSPECIFIED:
4402               break;
4403             case OMP_CLAUSE_DEFAULT_SHARED:
4404               /* const vars may be specified in firstprivate clause.  */
4405               if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
4406                   && cxx_omp_const_qual_no_mutable (t))
4407                 break;
4408               share_name = "shared";
4409               break;
4410             case OMP_CLAUSE_DEFAULT_PRIVATE:
4411               share_name = "private";
4412               break;
4413             default:
4414               gcc_unreachable ();
4415             }
4416           if (share_name)
4417             {
4418               error ("%qE is predetermined %qs for %qs",
4419                      t, share_name, name);
4420               remove = true;
4421             }
4422         }
4423
4424       /* We're interested in the base element, not arrays.  */
4425       inner_type = type = TREE_TYPE (t);
4426       while (TREE_CODE (inner_type) == ARRAY_TYPE)
4427         inner_type = TREE_TYPE (inner_type);
4428
4429       /* Check for special function availability by building a call to one.
4430          Save the results, because later we won't be in the right context
4431          for making these queries.  */
4432       if (CLASS_TYPE_P (inner_type)
4433           && COMPLETE_TYPE_P (inner_type)
4434           && (need_default_ctor || need_copy_ctor || need_copy_assignment)
4435           && !type_dependent_expression_p (t)
4436           && cxx_omp_create_clause_info (c, inner_type, need_default_ctor,
4437                                          need_copy_ctor, need_copy_assignment))
4438         remove = true;
4439
4440       if (remove)
4441         *pc = OMP_CLAUSE_CHAIN (c);
4442       else
4443         pc = &OMP_CLAUSE_CHAIN (c);
4444     }
4445
4446   bitmap_obstack_release (NULL);
4447   return clauses;
4448 }
4449
4450 /* For all variables in the tree_list VARS, mark them as thread local.  */
4451
4452 void
4453 finish_omp_threadprivate (tree vars)
4454 {
4455   tree t;
4456
4457   /* Mark every variable in VARS to be assigned thread local storage.  */
4458   for (t = vars; t; t = TREE_CHAIN (t))
4459     {
4460       tree v = TREE_PURPOSE (t);
4461
4462       if (error_operand_p (v))
4463         ;
4464       else if (!VAR_P (v))
4465         error ("%<threadprivate%> %qD is not file, namespace "
4466                "or block scope variable", v);
4467       /* If V had already been marked threadprivate, it doesn't matter
4468          whether it had been used prior to this point.  */
4469       else if (TREE_USED (v)
4470           && (DECL_LANG_SPECIFIC (v) == NULL
4471               || !CP_DECL_THREADPRIVATE_P (v)))
4472         error ("%qE declared %<threadprivate%> after first use", v);
4473       else if (! TREE_STATIC (v) && ! DECL_EXTERNAL (v))
4474         error ("automatic variable %qE cannot be %<threadprivate%>", v);
4475       else if (! COMPLETE_TYPE_P (complete_type (TREE_TYPE (v))))
4476         error ("%<threadprivate%> %qE has incomplete type", v);
4477       else if (TREE_STATIC (v) && TYPE_P (CP_DECL_CONTEXT (v))
4478                && CP_DECL_CONTEXT (v) != current_class_type)
4479         error ("%<threadprivate%> %qE directive not "
4480                "in %qT definition", v, CP_DECL_CONTEXT (v));
4481       else
4482         {
4483           /* Allocate a LANG_SPECIFIC structure for V, if needed.  */
4484           if (DECL_LANG_SPECIFIC (v) == NULL)
4485             {
4486               retrofit_lang_decl (v);
4487
4488               /* Make sure that DECL_DISCRIMINATOR_P continues to be true
4489                  after the allocation of the lang_decl structure.  */
4490               if (DECL_DISCRIMINATOR_P (v))
4491                 DECL_LANG_SPECIFIC (v)->u.base.u2sel = 1;
4492             }
4493
4494           if (! DECL_THREAD_LOCAL_P (v))
4495             {
4496               DECL_TLS_MODEL (v) = decl_default_tls_model (v);
4497               /* If rtl has been already set for this var, call
4498                  make_decl_rtl once again, so that encode_section_info
4499                  has a chance to look at the new decl flags.  */
4500               if (DECL_RTL_SET_P (v))
4501                 make_decl_rtl (v);
4502             }
4503           CP_DECL_THREADPRIVATE_P (v) = 1;
4504         }
4505     }
4506 }
4507
4508 /* Build an OpenMP structured block.  */
4509
4510 tree
4511 begin_omp_structured_block (void)
4512 {
4513   return do_pushlevel (sk_omp);
4514 }
4515
4516 tree
4517 finish_omp_structured_block (tree block)
4518 {
4519   return do_poplevel (block);
4520 }
4521
4522 /* Similarly, except force the retention of the BLOCK.  */
4523
4524 tree
4525 begin_omp_parallel (void)
4526 {
4527   keep_next_level (true);
4528   return begin_omp_structured_block ();
4529 }
4530
4531 tree
4532 finish_omp_parallel (tree clauses, tree body)
4533 {
4534   tree stmt;
4535
4536   body = finish_omp_structured_block (body);
4537
4538   stmt = make_node (OMP_PARALLEL);
4539   TREE_TYPE (stmt) = void_type_node;
4540   OMP_PARALLEL_CLAUSES (stmt) = clauses;
4541   OMP_PARALLEL_BODY (stmt) = body;
4542
4543   return add_stmt (stmt);
4544 }
4545
4546 tree
4547 begin_omp_task (void)
4548 {
4549   keep_next_level (true);
4550   return begin_omp_structured_block ();
4551 }
4552
4553 tree
4554 finish_omp_task (tree clauses, tree body)
4555 {
4556   tree stmt;
4557
4558   body = finish_omp_structured_block (body);
4559
4560   stmt = make_node (OMP_TASK);
4561   TREE_TYPE (stmt) = void_type_node;
4562   OMP_TASK_CLAUSES (stmt) = clauses;
4563   OMP_TASK_BODY (stmt) = body;
4564
4565   return add_stmt (stmt);
4566 }
4567
4568 /* Helper function for finish_omp_for.  Convert Ith random access iterator
4569    into integral iterator.  Return FALSE if successful.  */
4570
4571 static bool
4572 handle_omp_for_class_iterator (int i, location_t locus, tree declv, tree initv,
4573                                tree condv, tree incrv, tree *body,
4574                                tree *pre_body, tree clauses)
4575 {
4576   tree diff, iter_init, iter_incr = NULL, last;
4577   tree incr_var = NULL, orig_pre_body, orig_body, c;
4578   tree decl = TREE_VEC_ELT (declv, i);
4579   tree init = TREE_VEC_ELT (initv, i);
4580   tree cond = TREE_VEC_ELT (condv, i);
4581   tree incr = TREE_VEC_ELT (incrv, i);
4582   tree iter = decl;
4583   location_t elocus = locus;
4584
4585   if (init && EXPR_HAS_LOCATION (init))
4586     elocus = EXPR_LOCATION (init);
4587
4588   switch (TREE_CODE (cond))
4589     {
4590     case GT_EXPR:
4591     case GE_EXPR:
4592     case LT_EXPR:
4593     case LE_EXPR:
4594       if (TREE_OPERAND (cond, 1) == iter)
4595         cond = build2 (swap_tree_comparison (TREE_CODE (cond)),
4596                        TREE_TYPE (cond), iter, TREE_OPERAND (cond, 0));
4597       if (TREE_OPERAND (cond, 0) != iter)
4598         cond = error_mark_node;
4599       else
4600         {
4601           tree tem = build_x_binary_op (EXPR_LOCATION (cond),
4602                                         TREE_CODE (cond),
4603                                         iter, ERROR_MARK,
4604                                         TREE_OPERAND (cond, 1), ERROR_MARK,
4605                                         NULL, tf_warning_or_error);
4606           if (error_operand_p (tem))
4607             return true;
4608         }
4609       break;
4610     default:
4611       cond = error_mark_node;
4612       break;
4613     }
4614   if (cond == error_mark_node)
4615     {
4616       error_at (elocus, "invalid controlling predicate");
4617       return true;
4618     }
4619   diff = build_x_binary_op (elocus, MINUS_EXPR, TREE_OPERAND (cond, 1),
4620                             ERROR_MARK, iter, ERROR_MARK, NULL,
4621                             tf_warning_or_error);
4622   if (error_operand_p (diff))
4623     return true;
4624   if (TREE_CODE (TREE_TYPE (diff)) != INTEGER_TYPE)
4625     {
4626       error_at (elocus, "difference between %qE and %qD does not have integer type",
4627                 TREE_OPERAND (cond, 1), iter);
4628       return true;
4629     }
4630
4631   switch (TREE_CODE (incr))
4632     {
4633     case PREINCREMENT_EXPR:
4634     case PREDECREMENT_EXPR:
4635     case POSTINCREMENT_EXPR:
4636     case POSTDECREMENT_EXPR:
4637       if (TREE_OPERAND (incr, 0) != iter)
4638         {
4639           incr = error_mark_node;
4640           break;
4641         }
4642       iter_incr = build_x_unary_op (EXPR_LOCATION (incr),
4643                                     TREE_CODE (incr), iter,
4644                                     tf_warning_or_error);
4645       if (error_operand_p (iter_incr))
4646         return true;
4647       else if (TREE_CODE (incr) == PREINCREMENT_EXPR
4648                || TREE_CODE (incr) == POSTINCREMENT_EXPR)
4649         incr = integer_one_node;
4650       else
4651         incr = integer_minus_one_node;
4652       break;
4653     case MODIFY_EXPR:
4654       if (TREE_OPERAND (incr, 0) != iter)
4655         incr = error_mark_node;
4656       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
4657                || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
4658         {
4659           tree rhs = TREE_OPERAND (incr, 1);
4660           if (TREE_OPERAND (rhs, 0) == iter)
4661             {
4662               if (TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs, 1)))
4663                   != INTEGER_TYPE)
4664                 incr = error_mark_node;
4665               else
4666                 {
4667                   iter_incr = build_x_modify_expr (EXPR_LOCATION (rhs),
4668                                                    iter, TREE_CODE (rhs),
4669                                                    TREE_OPERAND (rhs, 1),
4670                                                    tf_warning_or_error);
4671                   if (error_operand_p (iter_incr))
4672                     return true;
4673                   incr = TREE_OPERAND (rhs, 1);
4674                   incr = cp_convert (TREE_TYPE (diff), incr,
4675                                      tf_warning_or_error);
4676                   if (TREE_CODE (rhs) == MINUS_EXPR)
4677                     {
4678                       incr = build1 (NEGATE_EXPR, TREE_TYPE (diff), incr);
4679                       incr = fold_if_not_in_template (incr);
4680                     }
4681                   if (TREE_CODE (incr) != INTEGER_CST
4682                       && (TREE_CODE (incr) != NOP_EXPR
4683                           || (TREE_CODE (TREE_OPERAND (incr, 0))
4684                               != INTEGER_CST)))
4685                     iter_incr = NULL;
4686                 }
4687             }
4688           else if (TREE_OPERAND (rhs, 1) == iter)
4689             {
4690               if (TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs, 0))) != INTEGER_TYPE
4691                   || TREE_CODE (rhs) != PLUS_EXPR)
4692                 incr = error_mark_node;
4693               else
4694                 {
4695                   iter_incr = build_x_binary_op (EXPR_LOCATION (rhs),
4696                                                  PLUS_EXPR,
4697                                                  TREE_OPERAND (rhs, 0),
4698                                                  ERROR_MARK, iter,
4699                                                  ERROR_MARK, NULL,
4700                                                  tf_warning_or_error);
4701                   if (error_operand_p (iter_incr))
4702                     return true;
4703                   iter_incr = build_x_modify_expr (EXPR_LOCATION (rhs),
4704                                                    iter, NOP_EXPR,
4705                                                    iter_incr,
4706                                                    tf_warning_or_error);
4707                   if (error_operand_p (iter_incr))
4708                     return true;
4709                   incr = TREE_OPERAND (rhs, 0);
4710                   iter_incr = NULL;
4711                 }
4712             }
4713           else
4714             incr = error_mark_node;
4715         }
4716       else
4717         incr = error_mark_node;
4718       break;
4719     default:
4720       incr = error_mark_node;
4721       break;
4722     }
4723
4724   if (incr == error_mark_node)
4725     {
4726       error_at (elocus, "invalid increment expression");
4727       return true;
4728     }
4729
4730   incr = cp_convert (TREE_TYPE (diff), incr, tf_warning_or_error);
4731   for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c))
4732     if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE
4733         && OMP_CLAUSE_DECL (c) == iter)
4734       break;
4735
4736   decl = create_temporary_var (TREE_TYPE (diff));
4737   pushdecl (decl);
4738   add_decl_expr (decl);
4739   last = create_temporary_var (TREE_TYPE (diff));
4740   pushdecl (last);
4741   add_decl_expr (last);
4742   if (c && iter_incr == NULL)
4743     {
4744       incr_var = create_temporary_var (TREE_TYPE (diff));
4745       pushdecl (incr_var);
4746       add_decl_expr (incr_var);
4747     }
4748   gcc_assert (stmts_are_full_exprs_p ());
4749
4750   orig_pre_body = *pre_body;
4751   *pre_body = push_stmt_list ();
4752   if (orig_pre_body)
4753     add_stmt (orig_pre_body);
4754   if (init != NULL)
4755     finish_expr_stmt (build_x_modify_expr (elocus,
4756                                            iter, NOP_EXPR, init,
4757                                            tf_warning_or_error));
4758   init = build_int_cst (TREE_TYPE (diff), 0);
4759   if (c && iter_incr == NULL)
4760     {
4761       finish_expr_stmt (build_x_modify_expr (elocus,
4762                                              incr_var, NOP_EXPR,
4763                                              incr, tf_warning_or_error));
4764       incr = incr_var;
4765       iter_incr = build_x_modify_expr (elocus,
4766                                        iter, PLUS_EXPR, incr,
4767                                        tf_warning_or_error);
4768     }
4769   finish_expr_stmt (build_x_modify_expr (elocus,
4770                                          last, NOP_EXPR, init,
4771                                          tf_warning_or_error));
4772   *pre_body = pop_stmt_list (*pre_body);
4773
4774   cond = cp_build_binary_op (elocus,
4775                              TREE_CODE (cond), decl, diff,
4776                              tf_warning_or_error);
4777   incr = build_modify_expr (elocus, decl, NULL_TREE, PLUS_EXPR,
4778                             elocus, incr, NULL_TREE);
4779
4780   orig_body = *body;
4781   *body = push_stmt_list ();
4782   iter_init = build2 (MINUS_EXPR, TREE_TYPE (diff), decl, last);
4783   iter_init = build_x_modify_expr (elocus,
4784                                    iter, PLUS_EXPR, iter_init,
4785                                    tf_warning_or_error);
4786   iter_init = build1 (NOP_EXPR, void_type_node, iter_init);
4787   finish_expr_stmt (iter_init);
4788   finish_expr_stmt (build_x_modify_expr (elocus,
4789                                          last, NOP_EXPR, decl,
4790                                          tf_warning_or_error));
4791   add_stmt (orig_body);
4792   *body = pop_stmt_list (*body);
4793
4794   if (c)
4795     {
4796       OMP_CLAUSE_LASTPRIVATE_STMT (c) = push_stmt_list ();
4797       finish_expr_stmt (iter_incr);
4798       OMP_CLAUSE_LASTPRIVATE_STMT (c)
4799         = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (c));
4800     }
4801
4802   TREE_VEC_ELT (declv, i) = decl;
4803   TREE_VEC_ELT (initv, i) = init;
4804   TREE_VEC_ELT (condv, i) = cond;
4805   TREE_VEC_ELT (incrv, i) = incr;
4806
4807   return false;
4808 }
4809
4810 /* Build and validate an OMP_FOR statement.  CLAUSES, BODY, COND, INCR
4811    are directly for their associated operands in the statement.  DECL
4812    and INIT are a combo; if DECL is NULL then INIT ought to be a
4813    MODIFY_EXPR, and the DECL should be extracted.  PRE_BODY are
4814    optional statements that need to go before the loop into its
4815    sk_omp scope.  */
4816
4817 tree
4818 finish_omp_for (location_t locus, tree declv, tree initv, tree condv,
4819                 tree incrv, tree body, tree pre_body, tree clauses)
4820 {
4821   tree omp_for = NULL, orig_incr = NULL;
4822   tree decl, init, cond, incr;
4823   location_t elocus;
4824   int i;
4825
4826   gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (initv));
4827   gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (condv));
4828   gcc_assert (TREE_VEC_LENGTH (declv) == TREE_VEC_LENGTH (incrv));
4829   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
4830     {
4831       decl = TREE_VEC_ELT (declv, i);
4832       init = TREE_VEC_ELT (initv, i);
4833       cond = TREE_VEC_ELT (condv, i);
4834       incr = TREE_VEC_ELT (incrv, i);
4835       elocus = locus;
4836
4837       if (decl == NULL)
4838         {
4839           if (init != NULL)
4840             switch (TREE_CODE (init))
4841               {
4842               case MODIFY_EXPR:
4843                 decl = TREE_OPERAND (init, 0);
4844                 init = TREE_OPERAND (init, 1);
4845                 break;
4846               case MODOP_EXPR:
4847                 if (TREE_CODE (TREE_OPERAND (init, 1)) == NOP_EXPR)
4848                   {
4849                     decl = TREE_OPERAND (init, 0);
4850                     init = TREE_OPERAND (init, 2);
4851                   }
4852                 break;
4853               default:
4854                 break;
4855               }
4856
4857           if (decl == NULL)
4858             {
4859               error_at (locus,
4860                         "expected iteration declaration or initialization");
4861               return NULL;
4862             }
4863         }
4864
4865       if (init && EXPR_HAS_LOCATION (init))
4866         elocus = EXPR_LOCATION (init);
4867
4868       if (cond == NULL)
4869         {
4870           error_at (elocus, "missing controlling predicate");
4871           return NULL;
4872         }
4873
4874       if (incr == NULL)
4875         {
4876           error_at (elocus, "missing increment expression");
4877           return NULL;
4878         }
4879
4880       TREE_VEC_ELT (declv, i) = decl;
4881       TREE_VEC_ELT (initv, i) = init;
4882     }
4883
4884   if (dependent_omp_for_p (declv, initv, condv, incrv))
4885     {
4886       tree stmt;
4887
4888       stmt = make_node (OMP_FOR);
4889
4890       for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
4891         {
4892           /* This is really just a place-holder.  We'll be decomposing this
4893              again and going through the cp_build_modify_expr path below when
4894              we instantiate the thing.  */
4895           TREE_VEC_ELT (initv, i)
4896             = build2 (MODIFY_EXPR, void_type_node, TREE_VEC_ELT (declv, i),
4897                       TREE_VEC_ELT (initv, i));
4898         }
4899
4900       TREE_TYPE (stmt) = void_type_node;
4901       OMP_FOR_INIT (stmt) = initv;
4902       OMP_FOR_COND (stmt) = condv;
4903       OMP_FOR_INCR (stmt) = incrv;
4904       OMP_FOR_BODY (stmt) = body;
4905       OMP_FOR_PRE_BODY (stmt) = pre_body;
4906       OMP_FOR_CLAUSES (stmt) = clauses;
4907
4908       SET_EXPR_LOCATION (stmt, locus);
4909       return add_stmt (stmt);
4910     }
4911
4912   if (processing_template_decl)
4913     orig_incr = make_tree_vec (TREE_VEC_LENGTH (incrv));
4914
4915   for (i = 0; i < TREE_VEC_LENGTH (declv); )
4916     {
4917       decl = TREE_VEC_ELT (declv, i);
4918       init = TREE_VEC_ELT (initv, i);
4919       cond = TREE_VEC_ELT (condv, i);
4920       incr = TREE_VEC_ELT (incrv, i);
4921       if (orig_incr)
4922         TREE_VEC_ELT (orig_incr, i) = incr;
4923       elocus = locus;
4924
4925       if (init && EXPR_HAS_LOCATION (init))
4926         elocus = EXPR_LOCATION (init);
4927
4928       if (!DECL_P (decl))
4929         {
4930           error_at (elocus, "expected iteration declaration or initialization");
4931           return NULL;
4932         }
4933
4934       if (incr && TREE_CODE (incr) == MODOP_EXPR)
4935         {
4936           if (orig_incr)
4937             TREE_VEC_ELT (orig_incr, i) = incr;
4938           incr = cp_build_modify_expr (TREE_OPERAND (incr, 0),
4939                                        TREE_CODE (TREE_OPERAND (incr, 1)),
4940                                        TREE_OPERAND (incr, 2),
4941                                        tf_warning_or_error);
4942         }
4943
4944       if (CLASS_TYPE_P (TREE_TYPE (decl)))
4945         {
4946           if (handle_omp_for_class_iterator (i, locus, declv, initv, condv,
4947                                              incrv, &body, &pre_body, clauses))
4948             return NULL;
4949           continue;
4950         }
4951
4952       if (!INTEGRAL_TYPE_P (TREE_TYPE (decl))
4953           && !TYPE_PTR_P (TREE_TYPE (decl)))
4954         {
4955           error_at (elocus, "invalid type for iteration variable %qE", decl);
4956           return NULL;
4957         }
4958
4959       if (!processing_template_decl)
4960         {
4961           init = fold_build_cleanup_point_expr (TREE_TYPE (init), init);
4962           init = cp_build_modify_expr (decl, NOP_EXPR, init, tf_warning_or_error);
4963         }
4964       else
4965         init = build2 (MODIFY_EXPR, void_type_node, decl, init);
4966       if (cond
4967           && TREE_SIDE_EFFECTS (cond)
4968           && COMPARISON_CLASS_P (cond)
4969           && !processing_template_decl)
4970         {
4971           tree t = TREE_OPERAND (cond, 0);
4972           if (TREE_SIDE_EFFECTS (t)
4973               && t != decl
4974               && (TREE_CODE (t) != NOP_EXPR
4975                   || TREE_OPERAND (t, 0) != decl))
4976             TREE_OPERAND (cond, 0)
4977               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4978
4979           t = TREE_OPERAND (cond, 1);
4980           if (TREE_SIDE_EFFECTS (t)
4981               && t != decl
4982               && (TREE_CODE (t) != NOP_EXPR
4983                   || TREE_OPERAND (t, 0) != decl))
4984             TREE_OPERAND (cond, 1)
4985               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
4986         }
4987       if (decl == error_mark_node || init == error_mark_node)
4988         return NULL;
4989
4990       TREE_VEC_ELT (declv, i) = decl;
4991       TREE_VEC_ELT (initv, i) = init;
4992       TREE_VEC_ELT (condv, i) = cond;
4993       TREE_VEC_ELT (incrv, i) = incr;
4994       i++;
4995     }
4996
4997   if (IS_EMPTY_STMT (pre_body))
4998     pre_body = NULL;
4999
5000   omp_for = c_finish_omp_for (locus, declv, initv, condv, incrv,
5001                               body, pre_body);
5002
5003   if (omp_for == NULL)
5004     return NULL;
5005
5006   for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INCR (omp_for)); i++)
5007     {
5008       decl = TREE_OPERAND (TREE_VEC_ELT (OMP_FOR_INIT (omp_for), i), 0);
5009       incr = TREE_VEC_ELT (OMP_FOR_INCR (omp_for), i);
5010
5011       if (TREE_CODE (incr) != MODIFY_EXPR)
5012         continue;
5013
5014       if (TREE_SIDE_EFFECTS (TREE_OPERAND (incr, 1))
5015           && BINARY_CLASS_P (TREE_OPERAND (incr, 1))
5016           && !processing_template_decl)
5017         {
5018           tree t = TREE_OPERAND (TREE_OPERAND (incr, 1), 0);
5019           if (TREE_SIDE_EFFECTS (t)
5020               && t != decl
5021               && (TREE_CODE (t) != NOP_EXPR
5022                   || TREE_OPERAND (t, 0) != decl))
5023             TREE_OPERAND (TREE_OPERAND (incr, 1), 0)
5024               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
5025
5026           t = TREE_OPERAND (TREE_OPERAND (incr, 1), 1);
5027           if (TREE_SIDE_EFFECTS (t)
5028               && t != decl
5029               && (TREE_CODE (t) != NOP_EXPR
5030                   || TREE_OPERAND (t, 0) != decl))
5031             TREE_OPERAND (TREE_OPERAND (incr, 1), 1)
5032               = fold_build_cleanup_point_expr (TREE_TYPE (t), t);
5033         }
5034
5035       if (orig_incr)
5036         TREE_VEC_ELT (OMP_FOR_INCR (omp_for), i) = TREE_VEC_ELT (orig_incr, i);
5037     }
5038   if (omp_for != NULL)
5039     OMP_FOR_CLAUSES (omp_for) = clauses;
5040   return omp_for;
5041 }
5042
5043 void
5044 finish_omp_atomic (enum tree_code code, enum tree_code opcode, tree lhs,
5045                    tree rhs, tree v, tree lhs1, tree rhs1)
5046 {
5047   tree orig_lhs;
5048   tree orig_rhs;
5049   tree orig_v;
5050   tree orig_lhs1;
5051   tree orig_rhs1;
5052   bool dependent_p;
5053   tree stmt;
5054
5055   orig_lhs = lhs;
5056   orig_rhs = rhs;
5057   orig_v = v;
5058   orig_lhs1 = lhs1;
5059   orig_rhs1 = rhs1;
5060   dependent_p = false;
5061   stmt = NULL_TREE;
5062
5063   /* Even in a template, we can detect invalid uses of the atomic
5064      pragma if neither LHS nor RHS is type-dependent.  */
5065   if (processing_template_decl)
5066     {
5067       dependent_p = (type_dependent_expression_p (lhs)
5068                      || (rhs && type_dependent_expression_p (rhs))
5069                      || (v && type_dependent_expression_p (v))
5070                      || (lhs1 && type_dependent_expression_p (lhs1))
5071                      || (rhs1 && type_dependent_expression_p (rhs1)));
5072       if (!dependent_p)
5073         {
5074           lhs = build_non_dependent_expr (lhs);
5075           if (rhs)
5076             rhs = build_non_dependent_expr (rhs);
5077           if (v)
5078             v = build_non_dependent_expr (v);
5079           if (lhs1)
5080             lhs1 = build_non_dependent_expr (lhs1);
5081           if (rhs1)
5082             rhs1 = build_non_dependent_expr (rhs1);
5083         }
5084     }
5085   if (!dependent_p)
5086     {
5087       stmt = c_finish_omp_atomic (input_location, code, opcode, lhs, rhs,
5088                                   v, lhs1, rhs1);
5089       if (stmt == error_mark_node)
5090         return;
5091     }
5092   if (processing_template_decl)
5093     {
5094       if (code == OMP_ATOMIC_READ)
5095         {
5096           stmt = build_min_nt_loc (EXPR_LOCATION (orig_lhs),
5097                                    OMP_ATOMIC_READ, orig_lhs);
5098           stmt = build2 (MODIFY_EXPR, void_type_node, orig_v, stmt);
5099         }
5100       else
5101         {
5102           if (opcode == NOP_EXPR)
5103             stmt = build2 (MODIFY_EXPR, void_type_node, orig_lhs, orig_rhs);
5104           else 
5105             stmt = build2 (opcode, void_type_node, orig_lhs, orig_rhs);
5106           if (orig_rhs1)
5107             stmt = build_min_nt_loc (EXPR_LOCATION (orig_rhs1),
5108                                      COMPOUND_EXPR, orig_rhs1, stmt);
5109           if (code != OMP_ATOMIC)
5110             {
5111               stmt = build_min_nt_loc (EXPR_LOCATION (orig_lhs1),
5112                                        code, orig_lhs1, stmt);
5113               stmt = build2 (MODIFY_EXPR, void_type_node, orig_v, stmt);
5114             }
5115         }
5116       stmt = build2 (OMP_ATOMIC, void_type_node, integer_zero_node, stmt);
5117     }
5118   add_stmt (stmt);
5119 }
5120
5121 void
5122 finish_omp_barrier (void)
5123 {
5124   tree fn = builtin_decl_explicit (BUILT_IN_GOMP_BARRIER);
5125   vec<tree, va_gc> *vec = make_tree_vector ();
5126   tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error);
5127   release_tree_vector (vec);
5128   finish_expr_stmt (stmt);
5129 }
5130
5131 void
5132 finish_omp_flush (void)
5133 {
5134   tree fn = builtin_decl_explicit (BUILT_IN_SYNC_SYNCHRONIZE);
5135   vec<tree, va_gc> *vec = make_tree_vector ();
5136   tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error);
5137   release_tree_vector (vec);
5138   finish_expr_stmt (stmt);
5139 }
5140
5141 void
5142 finish_omp_taskwait (void)
5143 {
5144   tree fn = builtin_decl_explicit (BUILT_IN_GOMP_TASKWAIT);
5145   vec<tree, va_gc> *vec = make_tree_vector ();
5146   tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error);
5147   release_tree_vector (vec);
5148   finish_expr_stmt (stmt);
5149 }
5150
5151 void
5152 finish_omp_taskyield (void)
5153 {
5154   tree fn = builtin_decl_explicit (BUILT_IN_GOMP_TASKYIELD);
5155   vec<tree, va_gc> *vec = make_tree_vector ();
5156   tree stmt = finish_call_expr (fn, &vec, false, false, tf_warning_or_error);
5157   release_tree_vector (vec);
5158   finish_expr_stmt (stmt);
5159 }
5160 \f
5161 /* Begin a __transaction_atomic or __transaction_relaxed statement.
5162    If PCOMPOUND is non-null, this is for a function-transaction-block, and we
5163    should create an extra compound stmt.  */
5164
5165 tree
5166 begin_transaction_stmt (location_t loc, tree *pcompound, int flags)
5167 {
5168   tree r;
5169
5170   if (pcompound)
5171     *pcompound = begin_compound_stmt (0);
5172
5173   r = build_stmt (loc, TRANSACTION_EXPR, NULL_TREE);
5174
5175   /* Only add the statement to the function if support enabled.  */
5176   if (flag_tm)
5177     add_stmt (r);
5178   else
5179     error_at (loc, ((flags & TM_STMT_ATTR_RELAXED) != 0
5180                     ? G_("%<__transaction_relaxed%> without "
5181                          "transactional memory support enabled")
5182                     : G_("%<__transaction_atomic%> without "
5183                          "transactional memory support enabled")));
5184
5185   TRANSACTION_EXPR_BODY (r) = push_stmt_list ();
5186   TREE_SIDE_EFFECTS (r) = 1;
5187   return r;
5188 }
5189
5190 /* End a __transaction_atomic or __transaction_relaxed statement.
5191    If COMPOUND_STMT is non-null, this is for a function-transaction-block,
5192    and we should end the compound.  If NOEX is non-NULL, we wrap the body in
5193    a MUST_NOT_THROW_EXPR with NOEX as condition.  */
5194
5195 void
5196 finish_transaction_stmt (tree stmt, tree compound_stmt, int flags, tree noex)
5197 {
5198   TRANSACTION_EXPR_BODY (stmt) = pop_stmt_list (TRANSACTION_EXPR_BODY (stmt));
5199   TRANSACTION_EXPR_OUTER (stmt) = (flags & TM_STMT_ATTR_OUTER) != 0;
5200   TRANSACTION_EXPR_RELAXED (stmt) = (flags & TM_STMT_ATTR_RELAXED) != 0;
5201   TRANSACTION_EXPR_IS_STMT (stmt) = 1;
5202
5203   /* noexcept specifications are not allowed for function transactions.  */
5204   gcc_assert (!(noex && compound_stmt));
5205   if (noex)
5206     {
5207       tree body = build_must_not_throw_expr (TRANSACTION_EXPR_BODY (stmt),
5208                                              noex);
5209       SET_EXPR_LOCATION (body, EXPR_LOCATION (TRANSACTION_EXPR_BODY (stmt)));
5210       TREE_SIDE_EFFECTS (body) = 1;
5211       TRANSACTION_EXPR_BODY (stmt) = body;
5212     }
5213
5214   if (compound_stmt)
5215     finish_compound_stmt (compound_stmt);
5216   finish_stmt ();
5217 }
5218
5219 /* Build a __transaction_atomic or __transaction_relaxed expression.  If
5220    NOEX is non-NULL, we wrap the body in a MUST_NOT_THROW_EXPR with NOEX as
5221    condition.  */
5222
5223 tree
5224 build_transaction_expr (location_t loc, tree expr, int flags, tree noex)
5225 {
5226   tree ret;
5227   if (noex)
5228     {
5229       expr = build_must_not_throw_expr (expr, noex);
5230       SET_EXPR_LOCATION (expr, loc);
5231       TREE_SIDE_EFFECTS (expr) = 1;
5232     }
5233   ret = build1 (TRANSACTION_EXPR, TREE_TYPE (expr), expr);
5234   if (flags & TM_STMT_ATTR_RELAXED)
5235         TRANSACTION_EXPR_RELAXED (ret) = 1;
5236   TREE_SIDE_EFFECTS (ret) = 1;
5237   SET_EXPR_LOCATION (ret, loc);
5238   return ret;
5239 }
5240 \f
5241 void
5242 init_cp_semantics (void)
5243 {
5244 }
5245 \f
5246 /* Build a STATIC_ASSERT for a static assertion with the condition
5247    CONDITION and the message text MESSAGE.  LOCATION is the location
5248    of the static assertion in the source code.  When MEMBER_P, this
5249    static assertion is a member of a class.  */
5250 void 
5251 finish_static_assert (tree condition, tree message, location_t location, 
5252                       bool member_p)
5253 {
5254   if (message == NULL_TREE
5255       || message == error_mark_node
5256       || condition == NULL_TREE
5257       || condition == error_mark_node)
5258     return;
5259
5260   if (check_for_bare_parameter_packs (condition))
5261     condition = error_mark_node;
5262
5263   if (type_dependent_expression_p (condition) 
5264       || value_dependent_expression_p (condition))
5265     {
5266       /* We're in a template; build a STATIC_ASSERT and put it in
5267          the right place. */
5268       tree assertion;
5269
5270       assertion = make_node (STATIC_ASSERT);
5271       STATIC_ASSERT_CONDITION (assertion) = condition;
5272       STATIC_ASSERT_MESSAGE (assertion) = message;
5273       STATIC_ASSERT_SOURCE_LOCATION (assertion) = location;
5274
5275       if (member_p)
5276         maybe_add_class_template_decl_list (current_class_type, 
5277                                             assertion,
5278                                             /*friend_p=*/0);
5279       else
5280         add_stmt (assertion);
5281
5282       return;
5283     }
5284
5285   /* Fold the expression and convert it to a boolean value. */
5286   condition = fold_non_dependent_expr (condition);
5287   condition = cp_convert (boolean_type_node, condition, tf_warning_or_error);
5288   condition = maybe_constant_value (condition);
5289
5290   if (TREE_CODE (condition) == INTEGER_CST && !integer_zerop (condition))
5291     /* Do nothing; the condition is satisfied. */
5292     ;
5293   else 
5294     {
5295       location_t saved_loc = input_location;
5296
5297       input_location = location;
5298       if (TREE_CODE (condition) == INTEGER_CST 
5299           && integer_zerop (condition))
5300         /* Report the error. */
5301         error ("static assertion failed: %s", TREE_STRING_POINTER (message));
5302       else if (condition && condition != error_mark_node)
5303         {
5304           error ("non-constant condition for static assertion");
5305           cxx_constant_value (condition);
5306         }
5307       input_location = saved_loc;
5308     }
5309 }
5310 \f
5311 /* Implements the C++0x decltype keyword. Returns the type of EXPR,
5312    suitable for use as a type-specifier.
5313
5314    ID_EXPRESSION_OR_MEMBER_ACCESS_P is true when EXPR was parsed as an
5315    id-expression or a class member access, FALSE when it was parsed as
5316    a full expression.  */
5317
5318 tree
5319 finish_decltype_type (tree expr, bool id_expression_or_member_access_p,
5320                       tsubst_flags_t complain)
5321 {
5322   tree type = NULL_TREE;
5323
5324   if (!expr || error_operand_p (expr))
5325     return error_mark_node;
5326
5327   if (TYPE_P (expr)
5328       || TREE_CODE (expr) == TYPE_DECL
5329       || (TREE_CODE (expr) == BIT_NOT_EXPR
5330           && TYPE_P (TREE_OPERAND (expr, 0))))
5331     {
5332       if (complain & tf_error)
5333         error ("argument to decltype must be an expression");
5334       return error_mark_node;
5335     }
5336
5337   /* Depending on the resolution of DR 1172, we may later need to distinguish
5338      instantiation-dependent but not type-dependent expressions so that, say,
5339      A<decltype(sizeof(T))>::U doesn't require 'typename'.  */
5340   if (instantiation_dependent_expression_p (expr))
5341     {
5342       type = cxx_make_type (DECLTYPE_TYPE);
5343       DECLTYPE_TYPE_EXPR (type) = expr;
5344       DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (type)
5345         = id_expression_or_member_access_p;
5346       SET_TYPE_STRUCTURAL_EQUALITY (type);
5347
5348       return type;
5349     }
5350
5351   /* The type denoted by decltype(e) is defined as follows:  */
5352
5353   expr = resolve_nondeduced_context (expr);
5354
5355   if (invalid_nonstatic_memfn_p (expr, complain))
5356     return error_mark_node;
5357
5358   if (type_unknown_p (expr))
5359     {
5360       if (complain & tf_error)
5361         error ("decltype cannot resolve address of overloaded function");
5362       return error_mark_node;
5363     }
5364
5365   /* To get the size of a static data member declared as an array of
5366      unknown bound, we need to instantiate it.  */
5367   if (VAR_P (expr)
5368       && VAR_HAD_UNKNOWN_BOUND (expr)
5369       && DECL_TEMPLATE_INSTANTIATION (expr))
5370     instantiate_decl (expr, /*defer_ok*/true, /*expl_inst_mem*/false);
5371
5372   if (id_expression_or_member_access_p)
5373     {
5374       /* If e is an id-expression or a class member access (5.2.5
5375          [expr.ref]), decltype(e) is defined as the type of the entity
5376          named by e. If there is no such entity, or e names a set of
5377          overloaded functions, the program is ill-formed.  */
5378       if (identifier_p (expr))
5379         expr = lookup_name (expr);
5380
5381       if (INDIRECT_REF_P (expr))
5382         /* This can happen when the expression is, e.g., "a.b". Just
5383            look at the underlying operand.  */
5384         expr = TREE_OPERAND (expr, 0);
5385
5386       if (TREE_CODE (expr) == OFFSET_REF
5387           || TREE_CODE (expr) == MEMBER_REF
5388           || TREE_CODE (expr) == SCOPE_REF)
5389         /* We're only interested in the field itself. If it is a
5390            BASELINK, we will need to see through it in the next
5391            step.  */
5392         expr = TREE_OPERAND (expr, 1);
5393
5394       if (BASELINK_P (expr))
5395         /* See through BASELINK nodes to the underlying function.  */
5396         expr = BASELINK_FUNCTIONS (expr);
5397
5398       switch (TREE_CODE (expr))
5399         {
5400         case FIELD_DECL:
5401           if (DECL_BIT_FIELD_TYPE (expr))
5402             {
5403               type = DECL_BIT_FIELD_TYPE (expr);
5404               break;
5405             }
5406           /* Fall through for fields that aren't bitfields.  */
5407
5408         case FUNCTION_DECL:
5409         case VAR_DECL:
5410         case CONST_DECL:
5411         case PARM_DECL:
5412         case RESULT_DECL:
5413         case TEMPLATE_PARM_INDEX:
5414           expr = mark_type_use (expr);
5415           type = TREE_TYPE (expr);
5416           break;
5417
5418         case ERROR_MARK:
5419           type = error_mark_node;
5420           break;
5421
5422         case COMPONENT_REF:
5423         case COMPOUND_EXPR:
5424           mark_type_use (expr);
5425           type = is_bitfield_expr_with_lowered_type (expr);
5426           if (!type)
5427             type = TREE_TYPE (TREE_OPERAND (expr, 1));
5428           break;
5429
5430         case BIT_FIELD_REF:
5431           gcc_unreachable ();
5432
5433         case INTEGER_CST:
5434         case PTRMEM_CST:
5435           /* We can get here when the id-expression refers to an
5436              enumerator or non-type template parameter.  */
5437           type = TREE_TYPE (expr);
5438           break;
5439
5440         default:
5441           /* Handle instantiated template non-type arguments.  */
5442           type = TREE_TYPE (expr);
5443           break;
5444         }
5445     }
5446   else
5447     {
5448       /* Within a lambda-expression:
5449
5450          Every occurrence of decltype((x)) where x is a possibly
5451          parenthesized id-expression that names an entity of
5452          automatic storage duration is treated as if x were
5453          transformed into an access to a corresponding data member
5454          of the closure type that would have been declared if x
5455          were a use of the denoted entity.  */
5456       if (outer_automatic_var_p (expr)
5457           && current_function_decl
5458           && LAMBDA_FUNCTION_P (current_function_decl))
5459         type = capture_decltype (expr);
5460       else if (error_operand_p (expr))
5461         type = error_mark_node;
5462       else if (expr == current_class_ptr)
5463         /* If the expression is just "this", we want the
5464            cv-unqualified pointer for the "this" type.  */
5465         type = TYPE_MAIN_VARIANT (TREE_TYPE (expr));
5466       else
5467         {
5468           /* Otherwise, where T is the type of e, if e is an lvalue,
5469              decltype(e) is defined as T&; if an xvalue, T&&; otherwise, T. */
5470           cp_lvalue_kind clk = lvalue_kind (expr);
5471           type = unlowered_expr_type (expr);
5472           gcc_assert (TREE_CODE (type) != REFERENCE_TYPE);
5473
5474           /* For vector types, pick a non-opaque variant.  */
5475           if (TREE_CODE (type) == VECTOR_TYPE)
5476             type = strip_typedefs (type);
5477
5478           if (clk != clk_none && !(clk & clk_class))
5479             type = cp_build_reference_type (type, (clk & clk_rvalueref));
5480         }
5481     }
5482
5483   if (cxx_dialect >= cxx1y && array_of_runtime_bound_p (type))
5484     {
5485       if (complain & tf_warning_or_error)
5486         pedwarn (input_location, OPT_Wvla,
5487                  "taking decltype of array of runtime bound");
5488       else
5489         return error_mark_node;
5490     }
5491
5492   return type;
5493 }
5494
5495 /* Called from trait_expr_value to evaluate either __has_nothrow_assign or 
5496    __has_nothrow_copy, depending on assign_p.  */
5497
5498 static bool
5499 classtype_has_nothrow_assign_or_copy_p (tree type, bool assign_p)
5500 {
5501   tree fns;
5502
5503   if (assign_p)
5504     {
5505       int ix;
5506       ix = lookup_fnfields_1 (type, ansi_assopname (NOP_EXPR));
5507       if (ix < 0)
5508         return false;
5509       fns = (*CLASSTYPE_METHOD_VEC (type))[ix];
5510     } 
5511   else if (TYPE_HAS_COPY_CTOR (type))
5512     {
5513       /* If construction of the copy constructor was postponed, create
5514          it now.  */
5515       if (CLASSTYPE_LAZY_COPY_CTOR (type))
5516         lazily_declare_fn (sfk_copy_constructor, type);
5517       if (CLASSTYPE_LAZY_MOVE_CTOR (type))
5518         lazily_declare_fn (sfk_move_constructor, type);
5519       fns = CLASSTYPE_CONSTRUCTORS (type);
5520     }
5521   else
5522     return false;
5523
5524   for (; fns; fns = OVL_NEXT (fns))
5525     {
5526       tree fn = OVL_CURRENT (fns);
5527  
5528       if (assign_p)
5529         {
5530           if (copy_fn_p (fn) == 0)
5531             continue;
5532         }
5533       else if (copy_fn_p (fn) <= 0)
5534         continue;
5535
5536       maybe_instantiate_noexcept (fn);
5537       if (!TYPE_NOTHROW_P (TREE_TYPE (fn)))
5538         return false;
5539     }
5540
5541   return true;
5542 }
5543
5544 /* Actually evaluates the trait.  */
5545
5546 static bool
5547 trait_expr_value (cp_trait_kind kind, tree type1, tree type2)
5548 {
5549   enum tree_code type_code1;
5550   tree t;
5551
5552   type_code1 = TREE_CODE (type1);
5553
5554   switch (kind)
5555     {
5556     case CPTK_HAS_NOTHROW_ASSIGN:
5557       type1 = strip_array_types (type1);
5558       return (!CP_TYPE_CONST_P (type1) && type_code1 != REFERENCE_TYPE
5559               && (trait_expr_value (CPTK_HAS_TRIVIAL_ASSIGN, type1, type2)
5560                   || (CLASS_TYPE_P (type1)
5561                       && classtype_has_nothrow_assign_or_copy_p (type1,
5562                                                                  true))));
5563
5564     case CPTK_HAS_TRIVIAL_ASSIGN:
5565       /* ??? The standard seems to be missing the "or array of such a class
5566          type" wording for this trait.  */
5567       type1 = strip_array_types (type1);
5568       return (!CP_TYPE_CONST_P (type1) && type_code1 != REFERENCE_TYPE
5569               && (trivial_type_p (type1)
5570                     || (CLASS_TYPE_P (type1)
5571                         && TYPE_HAS_TRIVIAL_COPY_ASSIGN (type1))));
5572
5573     case CPTK_HAS_NOTHROW_CONSTRUCTOR:
5574       type1 = strip_array_types (type1);
5575       return (trait_expr_value (CPTK_HAS_TRIVIAL_CONSTRUCTOR, type1, type2) 
5576               || (CLASS_TYPE_P (type1)
5577                   && (t = locate_ctor (type1))
5578                   && (maybe_instantiate_noexcept (t),
5579                       TYPE_NOTHROW_P (TREE_TYPE (t)))));
5580
5581     case CPTK_HAS_TRIVIAL_CONSTRUCTOR:
5582       type1 = strip_array_types (type1);
5583       return (trivial_type_p (type1)
5584               || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_DFLT (type1)));
5585
5586     case CPTK_HAS_NOTHROW_COPY:
5587       type1 = strip_array_types (type1);
5588       return (trait_expr_value (CPTK_HAS_TRIVIAL_COPY, type1, type2)
5589               || (CLASS_TYPE_P (type1)
5590                   && classtype_has_nothrow_assign_or_copy_p (type1, false)));
5591
5592     case CPTK_HAS_TRIVIAL_COPY:
5593       /* ??? The standard seems to be missing the "or array of such a class
5594          type" wording for this trait.  */
5595       type1 = strip_array_types (type1);
5596       return (trivial_type_p (type1) || type_code1 == REFERENCE_TYPE
5597               || (CLASS_TYPE_P (type1) && TYPE_HAS_TRIVIAL_COPY_CTOR (type1)));
5598
5599     case CPTK_HAS_TRIVIAL_DESTRUCTOR:
5600       type1 = strip_array_types (type1);
5601       return (trivial_type_p (type1) || type_code1 == REFERENCE_TYPE
5602               || (CLASS_TYPE_P (type1)
5603                   && TYPE_HAS_TRIVIAL_DESTRUCTOR (type1)));
5604
5605     case CPTK_HAS_VIRTUAL_DESTRUCTOR:
5606       return type_has_virtual_destructor (type1);
5607
5608     case CPTK_IS_ABSTRACT:
5609       return (ABSTRACT_CLASS_TYPE_P (type1));
5610
5611     case CPTK_IS_BASE_OF:
5612       return (NON_UNION_CLASS_TYPE_P (type1) && NON_UNION_CLASS_TYPE_P (type2)
5613               && DERIVED_FROM_P (type1, type2));
5614
5615     case CPTK_IS_CLASS:
5616       return (NON_UNION_CLASS_TYPE_P (type1));
5617
5618     case CPTK_IS_CONVERTIBLE_TO:
5619       /* TODO  */
5620       return false;
5621
5622     case CPTK_IS_EMPTY:
5623       return (NON_UNION_CLASS_TYPE_P (type1) && CLASSTYPE_EMPTY_P (type1));
5624
5625     case CPTK_IS_ENUM:
5626       return (type_code1 == ENUMERAL_TYPE);
5627
5628     case CPTK_IS_FINAL:
5629       return (CLASS_TYPE_P (type1) && CLASSTYPE_FINAL (type1));
5630
5631     case CPTK_IS_LITERAL_TYPE:
5632       return (literal_type_p (type1));
5633
5634     case CPTK_IS_POD:
5635       return (pod_type_p (type1));
5636
5637     case CPTK_IS_POLYMORPHIC:
5638       return (CLASS_TYPE_P (type1) && TYPE_POLYMORPHIC_P (type1));
5639
5640     case CPTK_IS_STD_LAYOUT:
5641       return (std_layout_type_p (type1));
5642
5643     case CPTK_IS_TRIVIAL:
5644       return (trivial_type_p (type1));
5645
5646     case CPTK_IS_UNION:
5647       return (type_code1 == UNION_TYPE);
5648
5649     default:
5650       gcc_unreachable ();
5651       return false;
5652     }
5653 }
5654
5655 /* If TYPE is an array of unknown bound, or (possibly cv-qualified)
5656    void, or a complete type, returns it, otherwise NULL_TREE.  */
5657
5658 static tree
5659 check_trait_type (tree type)
5660 {
5661   if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
5662       && COMPLETE_TYPE_P (TREE_TYPE (type)))
5663     return type;
5664
5665   if (VOID_TYPE_P (type))
5666     return type;
5667
5668   return complete_type_or_else (strip_array_types (type), NULL_TREE);
5669 }
5670
5671 /* Process a trait expression.  */
5672
5673 tree
5674 finish_trait_expr (cp_trait_kind kind, tree type1, tree type2)
5675 {
5676   gcc_assert (kind == CPTK_HAS_NOTHROW_ASSIGN
5677               || kind == CPTK_HAS_NOTHROW_CONSTRUCTOR
5678               || kind == CPTK_HAS_NOTHROW_COPY
5679               || kind == CPTK_HAS_TRIVIAL_ASSIGN
5680               || kind == CPTK_HAS_TRIVIAL_CONSTRUCTOR
5681               || kind == CPTK_HAS_TRIVIAL_COPY
5682               || kind == CPTK_HAS_TRIVIAL_DESTRUCTOR
5683               || kind == CPTK_HAS_VIRTUAL_DESTRUCTOR          
5684               || kind == CPTK_IS_ABSTRACT
5685               || kind == CPTK_IS_BASE_OF
5686               || kind == CPTK_IS_CLASS
5687               || kind == CPTK_IS_CONVERTIBLE_TO
5688               || kind == CPTK_IS_EMPTY
5689               || kind == CPTK_IS_ENUM
5690               || kind == CPTK_IS_FINAL
5691               || kind == CPTK_IS_LITERAL_TYPE
5692               || kind == CPTK_IS_POD
5693               || kind == CPTK_IS_POLYMORPHIC
5694               || kind == CPTK_IS_STD_LAYOUT
5695               || kind == CPTK_IS_TRIVIAL
5696               || kind == CPTK_IS_UNION);
5697
5698   if (kind == CPTK_IS_CONVERTIBLE_TO)
5699     {
5700       sorry ("__is_convertible_to");
5701       return error_mark_node;
5702     }
5703
5704   if (type1 == error_mark_node
5705       || ((kind == CPTK_IS_BASE_OF || kind == CPTK_IS_CONVERTIBLE_TO)
5706           && type2 == error_mark_node))
5707     return error_mark_node;
5708
5709   if (processing_template_decl)
5710     {
5711       tree trait_expr = make_node (TRAIT_EXPR);
5712       TREE_TYPE (trait_expr) = boolean_type_node;
5713       TRAIT_EXPR_TYPE1 (trait_expr) = type1;
5714       TRAIT_EXPR_TYPE2 (trait_expr) = type2;
5715       TRAIT_EXPR_KIND (trait_expr) = kind;
5716       return trait_expr;
5717     }
5718
5719   switch (kind)
5720     {
5721     case CPTK_HAS_NOTHROW_ASSIGN:
5722     case CPTK_HAS_TRIVIAL_ASSIGN:
5723     case CPTK_HAS_NOTHROW_CONSTRUCTOR:
5724     case CPTK_HAS_TRIVIAL_CONSTRUCTOR:
5725     case CPTK_HAS_NOTHROW_COPY:
5726     case CPTK_HAS_TRIVIAL_COPY:
5727     case CPTK_HAS_TRIVIAL_DESTRUCTOR:
5728     case CPTK_HAS_VIRTUAL_DESTRUCTOR:
5729     case CPTK_IS_ABSTRACT:
5730     case CPTK_IS_EMPTY:
5731     case CPTK_IS_FINAL:
5732     case CPTK_IS_LITERAL_TYPE:
5733     case CPTK_IS_POD:
5734     case CPTK_IS_POLYMORPHIC:
5735     case CPTK_IS_STD_LAYOUT:
5736     case CPTK_IS_TRIVIAL:
5737       if (!check_trait_type (type1))
5738         return error_mark_node;
5739       break;
5740
5741     case CPTK_IS_BASE_OF:
5742       if (NON_UNION_CLASS_TYPE_P (type1) && NON_UNION_CLASS_TYPE_P (type2)
5743           && !same_type_ignoring_top_level_qualifiers_p (type1, type2)
5744           && !complete_type_or_else (type2, NULL_TREE))
5745         /* We already issued an error.  */
5746         return error_mark_node;
5747       break;
5748
5749     case CPTK_IS_CLASS:
5750     case CPTK_IS_ENUM:
5751     case CPTK_IS_UNION:
5752       break;
5753     
5754     case CPTK_IS_CONVERTIBLE_TO:
5755     default:
5756       gcc_unreachable ();
5757     }
5758
5759   return (trait_expr_value (kind, type1, type2)
5760           ? boolean_true_node : boolean_false_node);
5761 }
5762
5763 /* Do-nothing variants of functions to handle pragma FLOAT_CONST_DECIMAL64,
5764    which is ignored for C++.  */
5765
5766 void
5767 set_float_const_decimal64 (void)
5768 {
5769 }
5770
5771 void
5772 clear_float_const_decimal64 (void)
5773 {
5774 }
5775
5776 bool
5777 float_const_decimal64_p (void)
5778 {
5779   return 0;
5780 }
5781
5782 \f
5783 /* Return true if T is a literal type.   */
5784
5785 bool
5786 literal_type_p (tree t)
5787 {
5788   if (SCALAR_TYPE_P (t)
5789       || TREE_CODE (t) == VECTOR_TYPE
5790       || TREE_CODE (t) == REFERENCE_TYPE)
5791     return true;
5792   if (CLASS_TYPE_P (t))
5793     {
5794       t = complete_type (t);
5795       gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
5796       return CLASSTYPE_LITERAL_P (t);
5797     }
5798   if (TREE_CODE (t) == ARRAY_TYPE)
5799     return literal_type_p (strip_array_types (t));
5800   return false;
5801 }
5802
5803 /* If DECL is a variable declared `constexpr', require its type
5804    be literal.  Return the DECL if OK, otherwise NULL.  */
5805
5806 tree
5807 ensure_literal_type_for_constexpr_object (tree decl)
5808 {
5809   tree type = TREE_TYPE (decl);
5810   if (VAR_P (decl) && DECL_DECLARED_CONSTEXPR_P (decl)
5811       && !processing_template_decl)
5812     {
5813       if (CLASS_TYPE_P (type) && !COMPLETE_TYPE_P (complete_type (type)))
5814         /* Don't complain here, we'll complain about incompleteness
5815            when we try to initialize the variable.  */;
5816       else if (!literal_type_p (type))
5817         {
5818           error ("the type %qT of constexpr variable %qD is not literal",
5819                  type, decl);
5820           explain_non_literal_class (type);
5821           return NULL;
5822         }
5823     }
5824   return decl;
5825 }
5826
5827 /* Representation of entries in the constexpr function definition table.  */
5828
5829 typedef struct GTY(()) constexpr_fundef {
5830   tree decl;
5831   tree body;
5832 } constexpr_fundef;
5833
5834 /* This table holds all constexpr function definitions seen in
5835    the current translation unit.  */
5836
5837 static GTY ((param_is (constexpr_fundef))) htab_t constexpr_fundef_table;
5838
5839 /* Utility function used for managing the constexpr function table.
5840    Return true if the entries pointed to by P and Q are for the
5841    same constexpr function.  */
5842
5843 static inline int
5844 constexpr_fundef_equal (const void *p, const void *q)
5845 {
5846   const constexpr_fundef *lhs = (const constexpr_fundef *) p;
5847   const constexpr_fundef *rhs = (const constexpr_fundef *) q;
5848   return lhs->decl == rhs->decl;
5849 }
5850
5851 /* Utility function used for managing the constexpr function table.
5852    Return a hash value for the entry pointed to by Q.  */
5853
5854 static inline hashval_t
5855 constexpr_fundef_hash (const void *p)
5856 {
5857   const constexpr_fundef *fundef = (const constexpr_fundef *) p;
5858   return DECL_UID (fundef->decl);
5859 }
5860
5861 /* Return a previously saved definition of function FUN.   */
5862
5863 static constexpr_fundef *
5864 retrieve_constexpr_fundef (tree fun)
5865 {
5866   constexpr_fundef fundef = { NULL, NULL };
5867   if (constexpr_fundef_table == NULL)
5868     return NULL;
5869
5870   fundef.decl = fun;
5871   return (constexpr_fundef *) htab_find (constexpr_fundef_table, &fundef);
5872 }
5873
5874 /* Check whether the parameter and return types of FUN are valid for a
5875    constexpr function, and complain if COMPLAIN.  */
5876
5877 static bool
5878 is_valid_constexpr_fn (tree fun, bool complain)
5879 {
5880   tree parm = FUNCTION_FIRST_USER_PARM (fun);
5881   bool ret = true;
5882   for (; parm != NULL; parm = TREE_CHAIN (parm))
5883     if (!literal_type_p (TREE_TYPE (parm)))
5884       {
5885         ret = false;
5886         if (complain)
5887           {
5888             error ("invalid type for parameter %d of constexpr "
5889                    "function %q+#D", DECL_PARM_INDEX (parm), fun);
5890             explain_non_literal_class (TREE_TYPE (parm));
5891           }
5892       }
5893
5894   if (!DECL_CONSTRUCTOR_P (fun))
5895     {
5896       tree rettype = TREE_TYPE (TREE_TYPE (fun));
5897       if (!literal_type_p (rettype))
5898         {
5899           ret = false;
5900           if (complain)
5901             {
5902               error ("invalid return type %qT of constexpr function %q+D",
5903                      rettype, fun);
5904               explain_non_literal_class (rettype);
5905             }
5906         }
5907
5908       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
5909           && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
5910         {
5911           ret = false;
5912           if (complain)
5913             {
5914               error ("enclosing class of constexpr non-static member "
5915                      "function %q+#D is not a literal type", fun);
5916               explain_non_literal_class (DECL_CONTEXT (fun));
5917             }
5918         }
5919     }
5920   else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
5921     {
5922       ret = false;
5923       if (complain)
5924         error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
5925     }
5926
5927   return ret;
5928 }
5929
5930 /* Subroutine of build_data_member_initialization.  MEMBER is a COMPONENT_REF
5931    for a member of an anonymous aggregate, INIT is the initializer for that
5932    member, and VEC_OUTER is the vector of constructor elements for the class
5933    whose constructor we are processing.  Add the initializer to the vector
5934    and return true to indicate success.  */
5935
5936 static bool
5937 build_anon_member_initialization (tree member, tree init,
5938                                   vec<constructor_elt, va_gc> **vec_outer)
5939 {
5940   /* MEMBER presents the relevant fields from the inside out, but we need
5941      to build up the initializer from the outside in so that we can reuse
5942      previously built CONSTRUCTORs if this is, say, the second field in an
5943      anonymous struct.  So we use a vec as a stack.  */
5944   vec<tree> fields;
5945   fields.create (2);
5946   do
5947     {
5948       fields.safe_push (TREE_OPERAND (member, 1));
5949       member = TREE_OPERAND (member, 0);
5950     }
5951   while (ANON_AGGR_TYPE_P (TREE_TYPE (member)));
5952
5953   /* VEC has the constructor elements vector for the context of FIELD.
5954      If FIELD is an anonymous aggregate, we will push inside it.  */
5955   vec<constructor_elt, va_gc> **vec = vec_outer;
5956   tree field;
5957   while (field = fields.pop(),
5958          ANON_AGGR_TYPE_P (TREE_TYPE (field)))
5959     {
5960       tree ctor;
5961       /* If there is already an outer constructor entry for the anonymous
5962          aggregate FIELD, use it; otherwise, insert one.  */
5963       if (vec_safe_is_empty (*vec)
5964           || (*vec)->last().index != field)
5965         {
5966           ctor = build_constructor (TREE_TYPE (field), NULL);
5967           CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
5968         }
5969       else
5970         ctor = (*vec)->last().value;
5971       vec = &CONSTRUCTOR_ELTS (ctor);
5972     }
5973
5974   /* Now we're at the innermost field, the one that isn't an anonymous
5975      aggregate.  Add its initializer to the CONSTRUCTOR and we're done.  */
5976   gcc_assert (fields.is_empty());
5977   fields.release ();
5978   CONSTRUCTOR_APPEND_ELT (*vec, field, init);
5979
5980   return true;
5981 }
5982
5983 /* Subroutine of  build_constexpr_constructor_member_initializers.
5984    The expression tree T represents a data member initialization
5985    in a (constexpr) constructor definition.  Build a pairing of
5986    the data member with its initializer, and prepend that pair
5987    to the existing initialization pair INITS.  */
5988
5989 static bool
5990 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
5991 {
5992   tree member, init;
5993   if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
5994     t = TREE_OPERAND (t, 0);
5995   if (TREE_CODE (t) == EXPR_STMT)
5996     t = TREE_OPERAND (t, 0);
5997   if (t == error_mark_node)
5998     return false;
5999   if (TREE_CODE (t) == STATEMENT_LIST)
6000     {
6001       tree_stmt_iterator i;
6002       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
6003         {
6004           if (! build_data_member_initialization (tsi_stmt (i), vec))
6005             return false;
6006         }
6007       return true;
6008     }
6009   if (TREE_CODE (t) == CLEANUP_STMT)
6010     {
6011       /* We can't see a CLEANUP_STMT in a constructor for a literal class,
6012          but we can in a constexpr constructor for a non-literal class.  Just
6013          ignore it; either all the initialization will be constant, in which
6014          case the cleanup can't run, or it can't be constexpr.
6015          Still recurse into CLEANUP_BODY.  */
6016       return build_data_member_initialization (CLEANUP_BODY (t), vec);
6017     }
6018   if (TREE_CODE (t) == CONVERT_EXPR)
6019     t = TREE_OPERAND (t, 0);
6020   if (TREE_CODE (t) == INIT_EXPR
6021       || TREE_CODE (t) == MODIFY_EXPR)
6022     {
6023       member = TREE_OPERAND (t, 0);
6024       init = unshare_expr (TREE_OPERAND (t, 1));
6025     }
6026   else if (TREE_CODE (t) == CALL_EXPR)
6027     {
6028       member = CALL_EXPR_ARG (t, 0);
6029       /* We don't use build_cplus_new here because it complains about
6030          abstract bases.  Leaving the call unwrapped means that it has the
6031          wrong type, but cxx_eval_constant_expression doesn't care.  */
6032       init = unshare_expr (t);
6033     }
6034   else if (TREE_CODE (t) == DECL_EXPR)
6035     /* Declaring a temporary, don't add it to the CONSTRUCTOR.  */
6036     return true;
6037   else
6038     gcc_unreachable ();
6039   if (INDIRECT_REF_P (member))
6040     member = TREE_OPERAND (member, 0);
6041   if (TREE_CODE (member) == NOP_EXPR)
6042     {
6043       tree op = member;
6044       STRIP_NOPS (op);
6045       if (TREE_CODE (op) == ADDR_EXPR)
6046         {
6047           gcc_assert (same_type_ignoring_top_level_qualifiers_p
6048                       (TREE_TYPE (TREE_TYPE (op)),
6049                        TREE_TYPE (TREE_TYPE (member))));
6050           /* Initializing a cv-qualified member; we need to look through
6051              the const_cast.  */
6052           member = op;
6053         }
6054       else if (op == current_class_ptr
6055                && (same_type_ignoring_top_level_qualifiers_p
6056                    (TREE_TYPE (TREE_TYPE (member)),
6057                     current_class_type)))
6058         /* Delegating constructor.  */
6059         member = op;
6060       else
6061         {
6062           /* This is an initializer for an empty base; keep it for now so
6063              we can check it in cxx_eval_bare_aggregate.  */
6064           gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
6065         }
6066     }
6067   if (TREE_CODE (member) == ADDR_EXPR)
6068     member = TREE_OPERAND (member, 0);
6069   if (TREE_CODE (member) == COMPONENT_REF)
6070     {
6071       tree aggr = TREE_OPERAND (member, 0);
6072       if (TREE_CODE (aggr) != COMPONENT_REF)
6073         /* Normal member initialization.  */
6074         member = TREE_OPERAND (member, 1);
6075       else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
6076         /* Initializing a member of an anonymous union.  */
6077         return build_anon_member_initialization (member, init, vec);
6078       else
6079         /* We're initializing a vtable pointer in a base.  Leave it as
6080            COMPONENT_REF so we remember the path to get to the vfield.  */
6081         gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
6082     }
6083
6084   CONSTRUCTOR_APPEND_ELT (*vec, member, init);
6085   return true;
6086 }
6087
6088 /* Make sure that there are no statements after LAST in the constructor
6089    body represented by LIST.  */
6090
6091 bool
6092 check_constexpr_ctor_body (tree last, tree list)
6093 {
6094   bool ok = true;
6095   if (TREE_CODE (list) == STATEMENT_LIST)
6096     {
6097       tree_stmt_iterator i = tsi_last (list);
6098       for (; !tsi_end_p (i); tsi_prev (&i))
6099         {
6100           tree t = tsi_stmt (i);
6101           if (t == last)
6102             break;
6103           if (TREE_CODE (t) == BIND_EXPR)
6104             {
6105               if (!check_constexpr_ctor_body (last, BIND_EXPR_BODY (t)))
6106                 return false;
6107               else
6108                 continue;
6109             }
6110           /* We currently allow typedefs and static_assert.
6111              FIXME allow them in the standard, too.  */
6112           if (TREE_CODE (t) != STATIC_ASSERT)
6113             {
6114               ok = false;
6115               break;
6116             }
6117         }
6118     }
6119   else if (list != last
6120            && TREE_CODE (list) != STATIC_ASSERT)
6121     ok = false;
6122   if (!ok)
6123     {
6124       error ("constexpr constructor does not have empty body");
6125       DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
6126     }
6127   return ok;
6128 }
6129
6130 /* V is a vector of constructor elements built up for the base and member
6131    initializers of a constructor for TYPE.  They need to be in increasing
6132    offset order, which they might not be yet if TYPE has a primary base
6133    which is not first in the base-clause or a vptr and at least one base
6134    all of which are non-primary.  */
6135
6136 static vec<constructor_elt, va_gc> *
6137 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
6138 {
6139   tree pri = CLASSTYPE_PRIMARY_BINFO (type);
6140   tree field_type;
6141   constructor_elt elt;
6142   int i;
6143
6144   if (pri)
6145     field_type = BINFO_TYPE (pri);
6146   else if (TYPE_CONTAINS_VPTR_P (type))
6147     field_type = vtbl_ptr_type_node;
6148   else
6149     return v;
6150
6151   /* Find the element for the primary base or vptr and move it to the
6152      beginning of the vec.  */
6153   vec<constructor_elt, va_gc> &vref = *v;
6154   for (i = 0; ; ++i)
6155     if (TREE_TYPE (vref[i].index) == field_type)
6156       break;
6157
6158   if (i > 0)
6159     {
6160       elt = vref[i];
6161       for (; i > 0; --i)
6162         vref[i] = vref[i-1];
6163       vref[0] = elt;
6164     }
6165
6166   return v;
6167 }
6168
6169 /* Build compile-time evalable representations of member-initializer list
6170    for a constexpr constructor.  */
6171
6172 static tree
6173 build_constexpr_constructor_member_initializers (tree type, tree body)
6174 {
6175   vec<constructor_elt, va_gc> *vec = NULL;
6176   bool ok = true;
6177   if (TREE_CODE (body) == MUST_NOT_THROW_EXPR
6178       || TREE_CODE (body) == EH_SPEC_BLOCK)
6179     body = TREE_OPERAND (body, 0);
6180   if (TREE_CODE (body) == STATEMENT_LIST)
6181     body = STATEMENT_LIST_HEAD (body)->stmt;
6182   body = BIND_EXPR_BODY (body);
6183   if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
6184     {
6185       body = TREE_OPERAND (body, 0);
6186       if (TREE_CODE (body) == EXPR_STMT)
6187         body = TREE_OPERAND (body, 0);
6188       if (TREE_CODE (body) == INIT_EXPR
6189           && (same_type_ignoring_top_level_qualifiers_p
6190               (TREE_TYPE (TREE_OPERAND (body, 0)),
6191                current_class_type)))
6192         {
6193           /* Trivial copy.  */
6194           return TREE_OPERAND (body, 1);
6195         }
6196       ok = build_data_member_initialization (body, &vec);
6197     }
6198   else if (TREE_CODE (body) == STATEMENT_LIST)
6199     {
6200       tree_stmt_iterator i;
6201       for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
6202         {
6203           ok = build_data_member_initialization (tsi_stmt (i), &vec);
6204           if (!ok)
6205             break;
6206         }
6207     }
6208   else if (TREE_CODE (body) == TRY_BLOCK)
6209     {
6210       error ("body of %<constexpr%> constructor cannot be "
6211              "a function-try-block");
6212       return error_mark_node;
6213     }
6214   else if (EXPR_P (body))
6215     ok = build_data_member_initialization (body, &vec);
6216   else
6217     gcc_assert (errorcount > 0);
6218   if (ok)
6219     {
6220       if (vec_safe_length (vec) > 0)
6221         {
6222           /* In a delegating constructor, return the target.  */
6223           constructor_elt *ce = &(*vec)[0];
6224           if (ce->index == current_class_ptr)
6225             {
6226               body = ce->value;
6227               vec_free (vec);
6228               return body;
6229             }
6230         }
6231       vec = sort_constexpr_mem_initializers (type, vec);
6232       return build_constructor (type, vec);
6233     }
6234   else
6235     return error_mark_node;
6236 }
6237
6238 /* Subroutine of register_constexpr_fundef.  BODY is the body of a function
6239    declared to be constexpr, or a sub-statement thereof.  Returns the
6240    return value if suitable, error_mark_node for a statement not allowed in
6241    a constexpr function, or NULL_TREE if no return value was found.  */
6242
6243 static tree
6244 constexpr_fn_retval (tree body)
6245 {
6246   switch (TREE_CODE (body))
6247     {
6248     case STATEMENT_LIST:
6249       {
6250         tree_stmt_iterator i;
6251         tree expr = NULL_TREE;
6252         for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
6253           {
6254             tree s = constexpr_fn_retval (tsi_stmt (i));
6255             if (s == error_mark_node)
6256               return error_mark_node;
6257             else if (s == NULL_TREE)
6258               /* Keep iterating.  */;
6259             else if (expr)
6260               /* Multiple return statements.  */
6261               return error_mark_node;
6262             else
6263               expr = s;
6264           }
6265         return expr;
6266       }
6267
6268     case RETURN_EXPR:
6269       return unshare_expr (TREE_OPERAND (body, 0));
6270
6271     case DECL_EXPR:
6272       if (TREE_CODE (DECL_EXPR_DECL (body)) == USING_DECL)
6273         return NULL_TREE;
6274       return error_mark_node;
6275
6276     case CLEANUP_POINT_EXPR:
6277       return constexpr_fn_retval (TREE_OPERAND (body, 0));
6278
6279     case USING_STMT:
6280       return NULL_TREE;
6281
6282     default:
6283       return error_mark_node;
6284     }
6285 }
6286
6287 /* Subroutine of register_constexpr_fundef.  BODY is the DECL_SAVED_TREE of
6288    FUN; do the necessary transformations to turn it into a single expression
6289    that we can store in the hash table.  */
6290
6291 static tree
6292 massage_constexpr_body (tree fun, tree body)
6293 {
6294   if (DECL_CONSTRUCTOR_P (fun))
6295     body = build_constexpr_constructor_member_initializers
6296       (DECL_CONTEXT (fun), body);
6297   else
6298     {
6299       if (TREE_CODE (body) == EH_SPEC_BLOCK)
6300         body = EH_SPEC_STMTS (body);
6301       if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
6302         body = TREE_OPERAND (body, 0);
6303       if (TREE_CODE (body) == BIND_EXPR)
6304         body = BIND_EXPR_BODY (body);
6305       body = constexpr_fn_retval (body);
6306     }
6307   return body;
6308 }
6309
6310 /* FUN is a constexpr constructor with massaged body BODY.  Return true
6311    if some bases/fields are uninitialized, and complain if COMPLAIN.  */
6312
6313 static bool
6314 cx_check_missing_mem_inits (tree fun, tree body, bool complain)
6315 {
6316   bool bad;
6317   tree field;
6318   unsigned i, nelts;
6319   tree ctype;
6320
6321   if (TREE_CODE (body) != CONSTRUCTOR)
6322     return false;
6323
6324   nelts = CONSTRUCTOR_NELTS (body);
6325   ctype = DECL_CONTEXT (fun);
6326   field = TYPE_FIELDS (ctype);
6327
6328   if (TREE_CODE (ctype) == UNION_TYPE)
6329     {
6330       if (nelts == 0 && next_initializable_field (field))
6331         {
6332           if (complain)
6333             error ("%<constexpr%> constructor for union %qT must "
6334                    "initialize exactly one non-static data member", ctype);
6335           return true;
6336         }
6337       return false;
6338     }
6339
6340   bad = false;
6341   for (i = 0; i <= nelts; ++i)
6342     {
6343       tree index;
6344       if (i == nelts)
6345         index = NULL_TREE;
6346       else
6347         {
6348           index = CONSTRUCTOR_ELT (body, i)->index;
6349           /* Skip base and vtable inits.  */
6350           if (TREE_CODE (index) != FIELD_DECL
6351               || DECL_ARTIFICIAL (index))
6352             continue;
6353         }
6354       for (; field != index; field = DECL_CHAIN (field))
6355         {
6356           tree ftype;
6357           if (TREE_CODE (field) != FIELD_DECL
6358               || (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
6359               || DECL_ARTIFICIAL (field))
6360             continue;
6361           ftype = strip_array_types (TREE_TYPE (field));
6362           if (type_has_constexpr_default_constructor (ftype))
6363             {
6364               /* It's OK to skip a member with a trivial constexpr ctor.
6365                  A constexpr ctor that isn't trivial should have been
6366                  added in by now.  */
6367               gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
6368                                    || errorcount != 0);
6369               continue;
6370             }
6371           if (!complain)
6372             return true;
6373           error ("uninitialized member %qD in %<constexpr%> constructor",
6374                  field);
6375           bad = true;
6376         }
6377       if (field == NULL_TREE)
6378         break;
6379       field = DECL_CHAIN (field);
6380     }
6381
6382   return bad;
6383 }
6384
6385 /* We are processing the definition of the constexpr function FUN.
6386    Check that its BODY fulfills the propriate requirements and
6387    enter it in the constexpr function definition table.
6388    For constructor BODY is actually the TREE_LIST of the
6389    member-initializer list.  */
6390
6391 tree
6392 register_constexpr_fundef (tree fun, tree body)
6393 {
6394   constexpr_fundef entry;
6395   constexpr_fundef **slot;
6396
6397   if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
6398     return NULL;
6399
6400   body = massage_constexpr_body (fun, body);
6401   if (body == NULL_TREE || body == error_mark_node)
6402     {
6403       if (!DECL_CONSTRUCTOR_P (fun))
6404         error ("body of constexpr function %qD not a return-statement", fun);
6405       return NULL;
6406     }
6407
6408   if (!potential_rvalue_constant_expression (body))
6409     {
6410       if (!DECL_GENERATED_P (fun))
6411         require_potential_rvalue_constant_expression (body);
6412       return NULL;
6413     }
6414
6415   if (DECL_CONSTRUCTOR_P (fun)
6416       && cx_check_missing_mem_inits (fun, body, !DECL_GENERATED_P (fun)))
6417     return NULL;
6418
6419   /* Create the constexpr function table if necessary.  */
6420   if (constexpr_fundef_table == NULL)
6421     constexpr_fundef_table = htab_create_ggc (101,
6422                                               constexpr_fundef_hash,
6423                                               constexpr_fundef_equal,
6424                                               ggc_free);
6425   entry.decl = fun;
6426   entry.body = body;
6427   slot = (constexpr_fundef **)
6428     htab_find_slot (constexpr_fundef_table, &entry, INSERT);
6429
6430   gcc_assert (*slot == NULL);
6431   *slot = ggc_alloc_constexpr_fundef ();
6432   **slot = entry;
6433
6434   return fun;
6435 }
6436
6437 /* FUN is a non-constexpr function called in a context that requires a
6438    constant expression.  If it comes from a constexpr template, explain why
6439    the instantiation isn't constexpr.  */
6440
6441 void
6442 explain_invalid_constexpr_fn (tree fun)
6443 {
6444   static struct pointer_set_t *diagnosed;
6445   tree body;
6446   location_t save_loc;
6447   /* Only diagnose defaulted functions or instantiations.  */
6448   if (!DECL_DEFAULTED_FN (fun)
6449       && !is_instantiation_of_constexpr (fun))
6450     return;
6451   if (diagnosed == NULL)
6452     diagnosed = pointer_set_create ();
6453   if (pointer_set_insert (diagnosed, fun) != 0)
6454     /* Already explained.  */
6455     return;
6456
6457   save_loc = input_location;
6458   input_location = DECL_SOURCE_LOCATION (fun);
6459   inform (0, "%q+D is not usable as a constexpr function because:", fun);
6460   /* First check the declaration.  */
6461   if (is_valid_constexpr_fn (fun, true))
6462     {
6463       /* Then if it's OK, the body.  */
6464       if (DECL_DEFAULTED_FN (fun))
6465         explain_implicit_non_constexpr (fun);
6466       else
6467         {
6468           body = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
6469           require_potential_rvalue_constant_expression (body);
6470           if (DECL_CONSTRUCTOR_P (fun))
6471             cx_check_missing_mem_inits (fun, body, true);
6472         }
6473     }
6474   input_location = save_loc;
6475 }
6476
6477 /* Objects of this type represent calls to constexpr functions
6478    along with the bindings of parameters to their arguments, for
6479    the purpose of compile time evaluation.  */
6480
6481 typedef struct GTY(()) constexpr_call {
6482   /* Description of the constexpr function definition.  */
6483   constexpr_fundef *fundef;
6484   /* Parameter bindings environment.  A TREE_LIST where each TREE_PURPOSE
6485      is a parameter _DECL and the TREE_VALUE is the value of the parameter.
6486      Note: This arrangement is made to accomodate the use of
6487      iterative_hash_template_arg (see pt.c).  If you change this
6488      representation, also change the hash calculation in
6489      cxx_eval_call_expression.  */
6490   tree bindings;
6491   /* Result of the call.
6492        NULL means the call is being evaluated.
6493        error_mark_node means that the evaluation was erroneous;
6494        otherwise, the actuall value of the call.  */
6495   tree result;
6496   /* The hash of this call; we remember it here to avoid having to
6497      recalculate it when expanding the hash table.  */
6498   hashval_t hash;
6499 } constexpr_call;
6500
6501 /* A table of all constexpr calls that have been evaluated by the
6502    compiler in this translation unit.  */
6503
6504 static GTY ((param_is (constexpr_call))) htab_t constexpr_call_table;
6505
6506 static tree cxx_eval_constant_expression (const constexpr_call *, tree,
6507                                           bool, bool, bool *, bool *);
6508
6509 /* Compute a hash value for a constexpr call representation.  */
6510
6511 static hashval_t
6512 constexpr_call_hash (const void *p)
6513 {
6514   const constexpr_call *info = (const constexpr_call *) p;
6515   return info->hash;
6516 }
6517
6518 /* Return 1 if the objects pointed to by P and Q represent calls
6519    to the same constexpr function with the same arguments.
6520    Otherwise, return 0.  */
6521
6522 static int
6523 constexpr_call_equal (const void *p, const void *q)
6524 {
6525   const constexpr_call *lhs = (const constexpr_call *) p;
6526   const constexpr_call *rhs = (const constexpr_call *) q;
6527   tree lhs_bindings;
6528   tree rhs_bindings;
6529   if (lhs == rhs)
6530     return 1;
6531   if (!constexpr_fundef_equal (lhs->fundef, rhs->fundef))
6532     return 0;
6533   lhs_bindings = lhs->bindings;
6534   rhs_bindings = rhs->bindings;
6535   while (lhs_bindings != NULL && rhs_bindings != NULL)
6536     {
6537       tree lhs_arg = TREE_VALUE (lhs_bindings);
6538       tree rhs_arg = TREE_VALUE (rhs_bindings);
6539       gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
6540       if (!cp_tree_equal (lhs_arg, rhs_arg))
6541         return 0;
6542       lhs_bindings = TREE_CHAIN (lhs_bindings);
6543       rhs_bindings = TREE_CHAIN (rhs_bindings);
6544     }
6545   return lhs_bindings == rhs_bindings;
6546 }
6547
6548 /* Initialize the constexpr call table, if needed.  */
6549
6550 static void
6551 maybe_initialize_constexpr_call_table (void)
6552 {
6553   if (constexpr_call_table == NULL)
6554     constexpr_call_table = htab_create_ggc (101,
6555                                             constexpr_call_hash,
6556                                             constexpr_call_equal,
6557                                             ggc_free);
6558 }
6559
6560 /* Return true if T designates the implied `this' parameter.  */
6561
6562 static inline bool
6563 is_this_parameter (tree t)
6564 {
6565   return t == current_class_ptr;
6566 }
6567
6568 /* We have an expression tree T that represents a call, either CALL_EXPR
6569    or AGGR_INIT_EXPR.  If the call is lexically to a named function,
6570    retrun the _DECL for that function.  */
6571
6572 static tree
6573 get_function_named_in_call (tree t)
6574 {
6575   tree fun = NULL;
6576   switch (TREE_CODE (t))
6577     {
6578     case CALL_EXPR:
6579       fun = CALL_EXPR_FN (t);
6580       break;
6581
6582     case AGGR_INIT_EXPR:
6583       fun = AGGR_INIT_EXPR_FN (t);
6584       break;
6585
6586     default:
6587       gcc_unreachable();
6588       break;
6589     }
6590   if (TREE_CODE (fun) == ADDR_EXPR
6591       && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
6592     fun = TREE_OPERAND (fun, 0);
6593   return fun;
6594 }
6595
6596 /* We have an expression tree T that represents a call, either CALL_EXPR
6597    or AGGR_INIT_EXPR.  Return the Nth argument.  */
6598
6599 static inline tree
6600 get_nth_callarg (tree t, int n)
6601 {
6602   switch (TREE_CODE (t))
6603     {
6604     case CALL_EXPR:
6605       return CALL_EXPR_ARG (t, n);
6606
6607     case AGGR_INIT_EXPR:
6608       return AGGR_INIT_EXPR_ARG (t, n);
6609
6610     default:
6611       gcc_unreachable ();
6612       return NULL;
6613     }
6614 }
6615
6616 /* Look up the binding of the function parameter T in a constexpr
6617    function call context CALL.  */
6618
6619 static tree
6620 lookup_parameter_binding (const constexpr_call *call, tree t)
6621 {
6622   tree b = purpose_member (t, call->bindings);
6623   return TREE_VALUE (b);
6624 }
6625
6626 /* Attempt to evaluate T which represents a call to a builtin function.
6627    We assume here that all builtin functions evaluate to scalar types
6628    represented by _CST nodes.  */
6629
6630 static tree
6631 cxx_eval_builtin_function_call (const constexpr_call *call, tree t,
6632                                 bool allow_non_constant, bool addr,
6633                                 bool *non_constant_p, bool *overflow_p)
6634 {
6635   const int nargs = call_expr_nargs (t);
6636   tree *args = (tree *) alloca (nargs * sizeof (tree));
6637   tree new_call;
6638   int i;
6639   for (i = 0; i < nargs; ++i)
6640     {
6641       args[i] = cxx_eval_constant_expression (call, CALL_EXPR_ARG (t, i),
6642                                               allow_non_constant, addr,
6643                                               non_constant_p, overflow_p);
6644       if (allow_non_constant && *non_constant_p)
6645         return t;
6646     }
6647   if (*non_constant_p)
6648     return t;
6649   new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
6650                                    CALL_EXPR_FN (t), nargs, args);
6651   new_call = fold (new_call);
6652   VERIFY_CONSTANT (new_call);
6653   return new_call;
6654 }
6655
6656 /* TEMP is the constant value of a temporary object of type TYPE.  Adjust
6657    the type of the value to match.  */
6658
6659 static tree
6660 adjust_temp_type (tree type, tree temp)
6661 {
6662   if (TREE_TYPE (temp) == type)
6663     return temp;
6664   /* Avoid wrapping an aggregate value in a NOP_EXPR.  */
6665   if (TREE_CODE (temp) == CONSTRUCTOR)
6666     return build_constructor (type, CONSTRUCTOR_ELTS (temp));
6667   gcc_assert (scalarish_type_p (type));
6668   return cp_fold_convert (type, temp);
6669 }
6670
6671 /* Subroutine of cxx_eval_call_expression.
6672    We are processing a call expression (either CALL_EXPR or
6673    AGGR_INIT_EXPR) in the call context of OLD_CALL.  Evaluate
6674    all arguments and bind their values to correspondings
6675    parameters, making up the NEW_CALL context.  */
6676
6677 static void
6678 cxx_bind_parameters_in_call (const constexpr_call *old_call, tree t,
6679                              constexpr_call *new_call,
6680                              bool allow_non_constant,
6681                              bool *non_constant_p, bool *overflow_p)
6682 {
6683   const int nargs = call_expr_nargs (t);
6684   tree fun = new_call->fundef->decl;
6685   tree parms = DECL_ARGUMENTS (fun);
6686   int i;
6687   for (i = 0; i < nargs; ++i)
6688     {
6689       tree x, arg;
6690       tree type = parms ? TREE_TYPE (parms) : void_type_node;
6691       /* For member function, the first argument is a pointer to the implied
6692          object.  And for an object contruction, don't bind `this' before
6693          it is fully constructed.  */
6694       if (i == 0 && DECL_CONSTRUCTOR_P (fun))
6695         goto next;
6696       x = get_nth_callarg (t, i);
6697       if (parms && DECL_BY_REFERENCE (parms))
6698         {
6699           /* cp_genericize made this a reference for argument passing, but
6700              we don't want to treat it like one for constexpr evaluation.  */
6701           gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
6702           gcc_assert (TREE_CODE (TREE_TYPE (x)) == REFERENCE_TYPE);
6703           type = TREE_TYPE (type);
6704           x = convert_from_reference (x);
6705         }
6706       arg = cxx_eval_constant_expression (old_call, x, allow_non_constant,
6707                                           TREE_CODE (type) == REFERENCE_TYPE,
6708                                           non_constant_p, overflow_p);
6709       /* Don't VERIFY_CONSTANT here.  */
6710       if (*non_constant_p && allow_non_constant)
6711         return;
6712       /* Just discard ellipsis args after checking their constantitude.  */
6713       if (!parms)
6714         continue;
6715       if (*non_constant_p)
6716         /* Don't try to adjust the type of non-constant args.  */
6717         goto next;
6718
6719       /* Make sure the binding has the same type as the parm.  */
6720       if (TREE_CODE (type) != REFERENCE_TYPE)
6721         arg = adjust_temp_type (type, arg);
6722       new_call->bindings = tree_cons (parms, arg, new_call->bindings);
6723     next:
6724       parms = TREE_CHAIN (parms);
6725     }
6726 }
6727
6728 /* Variables and functions to manage constexpr call expansion context.
6729    These do not need to be marked for PCH or GC.  */
6730
6731 /* FIXME remember and print actual constant arguments.  */
6732 static vec<tree> call_stack = vNULL;
6733 static int call_stack_tick;
6734 static int last_cx_error_tick;
6735
6736 static bool
6737 push_cx_call_context (tree call)
6738 {
6739   ++call_stack_tick;
6740   if (!EXPR_HAS_LOCATION (call))
6741     SET_EXPR_LOCATION (call, input_location);
6742   call_stack.safe_push (call);
6743   if (call_stack.length () > (unsigned) max_constexpr_depth)
6744     return false;
6745   return true;
6746 }
6747
6748 static void
6749 pop_cx_call_context (void)
6750 {
6751   ++call_stack_tick;
6752   call_stack.pop ();
6753 }
6754
6755 vec<tree> 
6756 cx_error_context (void)
6757 {
6758   vec<tree> r = vNULL;
6759   if (call_stack_tick != last_cx_error_tick
6760       && !call_stack.is_empty ())
6761     r = call_stack;
6762   last_cx_error_tick = call_stack_tick;
6763   return r;
6764 }
6765
6766 /* Subroutine of cxx_eval_constant_expression.
6767    Evaluate the call expression tree T in the context of OLD_CALL expression
6768    evaluation.  */
6769
6770 static tree
6771 cxx_eval_call_expression (const constexpr_call *old_call, tree t,
6772                           bool allow_non_constant, bool addr,
6773                           bool *non_constant_p, bool *overflow_p)
6774 {
6775   location_t loc = EXPR_LOC_OR_HERE (t);
6776   tree fun = get_function_named_in_call (t);
6777   tree result;
6778   constexpr_call new_call = { NULL, NULL, NULL, 0 };
6779   constexpr_call **slot;
6780   constexpr_call *entry;
6781   bool depth_ok;
6782
6783   if (TREE_CODE (fun) != FUNCTION_DECL)
6784     {
6785       /* Might be a constexpr function pointer.  */
6786       fun = cxx_eval_constant_expression (old_call, fun, allow_non_constant,
6787                                           /*addr*/false, non_constant_p, overflow_p);
6788       if (TREE_CODE (fun) == ADDR_EXPR)
6789         fun = TREE_OPERAND (fun, 0);
6790     }
6791   if (TREE_CODE (fun) != FUNCTION_DECL)
6792     {
6793       if (!allow_non_constant && !*non_constant_p)
6794         error_at (loc, "expression %qE does not designate a constexpr "
6795                   "function", fun);
6796       *non_constant_p = true;
6797       return t;
6798     }
6799   if (DECL_CLONED_FUNCTION_P (fun))
6800     fun = DECL_CLONED_FUNCTION (fun);
6801   if (is_builtin_fn (fun))
6802     return cxx_eval_builtin_function_call (old_call, t, allow_non_constant,
6803                                            addr, non_constant_p, overflow_p);
6804   if (!DECL_DECLARED_CONSTEXPR_P (fun))
6805     {
6806       if (!allow_non_constant)
6807         {
6808           error_at (loc, "call to non-constexpr function %qD", fun);
6809           explain_invalid_constexpr_fn (fun);
6810         }
6811       *non_constant_p = true;
6812       return t;
6813     }
6814
6815   /* Shortcut trivial copy constructor/op=.  */
6816   if (call_expr_nargs (t) == 2 && trivial_fn_p (fun))
6817     {
6818       tree arg = convert_from_reference (get_nth_callarg (t, 1));
6819       return cxx_eval_constant_expression (old_call, arg, allow_non_constant,
6820                                            addr, non_constant_p, overflow_p);
6821     }
6822
6823   /* If in direct recursive call, optimize definition search.  */
6824   if (old_call != NULL && old_call->fundef->decl == fun)
6825     new_call.fundef = old_call->fundef;
6826   else
6827     {
6828       new_call.fundef = retrieve_constexpr_fundef (fun);
6829       if (new_call.fundef == NULL || new_call.fundef->body == NULL)
6830         {
6831           if (!allow_non_constant)
6832             {
6833               if (DECL_INITIAL (fun))
6834                 {
6835                   /* The definition of fun was somehow unsuitable.  */
6836                   error_at (loc, "%qD called in a constant expression", fun);
6837                   explain_invalid_constexpr_fn (fun);
6838                 }
6839               else
6840                 error_at (loc, "%qD used before its definition", fun);
6841             }
6842           *non_constant_p = true;
6843           return t;
6844         }
6845     }
6846   cxx_bind_parameters_in_call (old_call, t, &new_call,
6847                                allow_non_constant, non_constant_p, overflow_p);
6848   if (*non_constant_p)
6849     return t;
6850
6851   depth_ok = push_cx_call_context (t);
6852
6853   new_call.hash
6854     = iterative_hash_template_arg (new_call.bindings,
6855                                    constexpr_fundef_hash (new_call.fundef));
6856
6857   /* If we have seen this call before, we are done.  */
6858   maybe_initialize_constexpr_call_table ();
6859   slot = (constexpr_call **)
6860     htab_find_slot (constexpr_call_table, &new_call, INSERT);
6861   entry = *slot;
6862   if (entry == NULL)
6863     {
6864       /* We need to keep a pointer to the entry, not just the slot, as the
6865          slot can move in the call to cxx_eval_builtin_function_call.  */
6866       *slot = entry = ggc_alloc_constexpr_call ();
6867       *entry = new_call;
6868     }
6869   /* Calls which are in progress have their result set to NULL
6870      so that we can detect circular dependencies.  */
6871   else if (entry->result == NULL)
6872     {
6873       if (!allow_non_constant)
6874         error ("call has circular dependency");
6875       *non_constant_p = true;
6876       entry->result = result = error_mark_node;
6877     }
6878
6879   if (!depth_ok)
6880     {
6881       if (!allow_non_constant)
6882         error ("constexpr evaluation depth exceeds maximum of %d (use "
6883                "-fconstexpr-depth= to increase the maximum)",
6884                max_constexpr_depth);
6885       *non_constant_p = true;
6886       entry->result = result = error_mark_node;
6887     }
6888   else
6889     {
6890       result = entry->result;
6891       if (!result || result == error_mark_node)
6892         result = (cxx_eval_constant_expression
6893                   (&new_call, new_call.fundef->body,
6894                    allow_non_constant, addr,
6895                    non_constant_p, overflow_p));
6896       if (result == error_mark_node)
6897         *non_constant_p = true;
6898       if (*non_constant_p)
6899         entry->result = result = error_mark_node;
6900       else
6901         {
6902           /* If this was a call to initialize an object, set the type of
6903              the CONSTRUCTOR to the type of that object.  */
6904           if (DECL_CONSTRUCTOR_P (fun))
6905             {
6906               tree ob_arg = get_nth_callarg (t, 0);
6907               STRIP_NOPS (ob_arg);
6908               gcc_assert (TYPE_PTR_P (TREE_TYPE (ob_arg))
6909                           && CLASS_TYPE_P (TREE_TYPE (TREE_TYPE (ob_arg))));
6910               result = adjust_temp_type (TREE_TYPE (TREE_TYPE (ob_arg)),
6911                                          result);
6912             }
6913           entry->result = result;
6914         }
6915     }
6916
6917   pop_cx_call_context ();
6918   return unshare_expr (result);
6919 }
6920
6921 /* FIXME speed this up, it's taking 16% of compile time on sieve testcase.  */
6922
6923 bool
6924 reduced_constant_expression_p (tree t)
6925 {
6926   if (TREE_CODE (t) == PTRMEM_CST)
6927     /* Even if we can't lower this yet, it's constant.  */
6928     return true;
6929   /* FIXME are we calling this too much?  */
6930   return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
6931 }
6932
6933 /* Some expressions may have constant operands but are not constant
6934    themselves, such as 1/0.  Call this function (or rather, the macro
6935    following it) to check for that condition.
6936
6937    We only call this in places that require an arithmetic constant, not in
6938    places where we might have a non-constant expression that can be a
6939    component of a constant expression, such as the address of a constexpr
6940    variable that might be dereferenced later.  */
6941
6942 static bool
6943 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
6944                  bool *overflow_p)
6945 {
6946   if (!*non_constant_p && !reduced_constant_expression_p (t))
6947     {
6948       if (!allow_non_constant)
6949         error ("%q+E is not a constant expression", t);
6950       *non_constant_p = true;
6951     }
6952   if (TREE_OVERFLOW_P (t))
6953     {
6954       if (!allow_non_constant)
6955         {
6956           permerror (input_location, "overflow in constant expression");
6957           /* If we're being permissive (and are in an enforcing
6958              context), ignore the overflow.  */
6959           if (flag_permissive)
6960             return *non_constant_p;
6961         }
6962       *overflow_p = true;
6963     }
6964   return *non_constant_p;
6965 }
6966
6967 /* Subroutine of cxx_eval_constant_expression.
6968    Attempt to reduce the unary expression tree T to a compile time value.
6969    If successful, return the value.  Otherwise issue a diagnostic
6970    and return error_mark_node.  */
6971
6972 static tree
6973 cxx_eval_unary_expression (const constexpr_call *call, tree t,
6974                            bool allow_non_constant, bool addr,
6975                            bool *non_constant_p, bool *overflow_p)
6976 {
6977   tree r;
6978   tree orig_arg = TREE_OPERAND (t, 0);
6979   tree arg = cxx_eval_constant_expression (call, orig_arg, allow_non_constant,
6980                                            addr, non_constant_p, overflow_p);
6981   VERIFY_CONSTANT (arg);
6982   if (arg == orig_arg)
6983     return t;
6984   r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), arg);
6985   VERIFY_CONSTANT (r);
6986   return r;
6987 }
6988
6989 /* Subroutine of cxx_eval_constant_expression.
6990    Like cxx_eval_unary_expression, except for binary expressions.  */
6991
6992 static tree
6993 cxx_eval_binary_expression (const constexpr_call *call, tree t,
6994                             bool allow_non_constant, bool addr,
6995                             bool *non_constant_p, bool *overflow_p)
6996 {
6997   tree r;
6998   tree orig_lhs = TREE_OPERAND (t, 0);
6999   tree orig_rhs = TREE_OPERAND (t, 1);
7000   tree lhs, rhs;
7001   lhs = cxx_eval_constant_expression (call, orig_lhs,
7002                                       allow_non_constant, addr,
7003                                       non_constant_p, overflow_p);
7004   VERIFY_CONSTANT (lhs);
7005   rhs = cxx_eval_constant_expression (call, orig_rhs,
7006                                       allow_non_constant, addr,
7007                                       non_constant_p, overflow_p);
7008   VERIFY_CONSTANT (rhs);
7009   if (lhs == orig_lhs && rhs == orig_rhs)
7010     return t;
7011   r = fold_build2 (TREE_CODE (t), TREE_TYPE (t), lhs, rhs);
7012   VERIFY_CONSTANT (r);
7013   return r;
7014 }
7015
7016 /* Subroutine of cxx_eval_constant_expression.
7017    Attempt to evaluate condition expressions.  Dead branches are not
7018    looked into.  */
7019
7020 static tree
7021 cxx_eval_conditional_expression (const constexpr_call *call, tree t,
7022                                  bool allow_non_constant, bool addr,
7023                                  bool *non_constant_p, bool *overflow_p)
7024 {
7025   tree val = cxx_eval_constant_expression (call, TREE_OPERAND (t, 0),
7026                                            allow_non_constant, addr,
7027                                            non_constant_p, overflow_p);
7028   VERIFY_CONSTANT (val);
7029   /* Don't VERIFY_CONSTANT the other operands.  */
7030   if (integer_zerop (val))
7031     return cxx_eval_constant_expression (call, TREE_OPERAND (t, 2),
7032                                          allow_non_constant, addr,
7033                                          non_constant_p, overflow_p);
7034   return cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
7035                                        allow_non_constant, addr,
7036                                        non_constant_p, overflow_p);
7037 }
7038
7039 /* Subroutine of cxx_eval_constant_expression.
7040    Attempt to reduce a reference to an array slot.  */
7041
7042 static tree
7043 cxx_eval_array_reference (const constexpr_call *call, tree t,
7044                           bool allow_non_constant, bool addr,
7045                           bool *non_constant_p, bool *overflow_p)
7046 {
7047   tree oldary = TREE_OPERAND (t, 0);
7048   tree ary = cxx_eval_constant_expression (call, oldary,
7049                                            allow_non_constant, addr,
7050                                            non_constant_p, overflow_p);
7051   tree index, oldidx;
7052   HOST_WIDE_INT i;
7053   tree elem_type;
7054   unsigned len, elem_nchars = 1;
7055   if (*non_constant_p)
7056     return t;
7057   oldidx = TREE_OPERAND (t, 1);
7058   index = cxx_eval_constant_expression (call, oldidx,
7059                                         allow_non_constant, false,
7060                                         non_constant_p, overflow_p);
7061   VERIFY_CONSTANT (index);
7062   if (addr && ary == oldary && index == oldidx)
7063     return t;
7064   else if (addr)
7065     return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
7066   elem_type = TREE_TYPE (TREE_TYPE (ary));
7067   if (TREE_CODE (ary) == CONSTRUCTOR)
7068     len = CONSTRUCTOR_NELTS (ary);
7069   else if (TREE_CODE (ary) == STRING_CST)
7070     {
7071       elem_nchars = (TYPE_PRECISION (elem_type)
7072                      / TYPE_PRECISION (char_type_node));
7073       len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
7074     }
7075   else
7076     {
7077       /* We can't do anything with other tree codes, so use
7078          VERIFY_CONSTANT to complain and fail.  */
7079       VERIFY_CONSTANT (ary);
7080       gcc_unreachable ();
7081     }
7082   if (compare_tree_int (index, len) >= 0)
7083     {
7084       if (tree_int_cst_lt (index, array_type_nelts_top (TREE_TYPE (ary))))
7085         {
7086           /* If it's within the array bounds but doesn't have an explicit
7087              initializer, it's value-initialized.  */
7088           tree val = build_value_init (elem_type, tf_warning_or_error);
7089           return cxx_eval_constant_expression (call, val,
7090                                                allow_non_constant, addr,
7091                                                non_constant_p, overflow_p);
7092         }
7093
7094       if (!allow_non_constant)
7095         error ("array subscript out of bound");
7096       *non_constant_p = true;
7097       return t;
7098     }
7099   else if (tree_int_cst_lt (index, integer_zero_node))
7100     {
7101       if (!allow_non_constant)
7102         error ("negative array subscript");
7103       *non_constant_p = true;
7104       return t;
7105     }
7106   i = tree_low_cst (index, 0);
7107   if (TREE_CODE (ary) == CONSTRUCTOR)
7108     return (*CONSTRUCTOR_ELTS (ary))[i].value;
7109   else if (elem_nchars == 1)
7110     return build_int_cst (cv_unqualified (TREE_TYPE (TREE_TYPE (ary))),
7111                           TREE_STRING_POINTER (ary)[i]);
7112   else
7113     {
7114       tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (ary)));
7115       return native_interpret_expr (type, (const unsigned char *)
7116                                           TREE_STRING_POINTER (ary)
7117                                           + i * elem_nchars, elem_nchars);
7118     }
7119   /* Don't VERIFY_CONSTANT here.  */
7120 }
7121
7122 /* Subroutine of cxx_eval_constant_expression.
7123    Attempt to reduce a field access of a value of class type.  */
7124
7125 static tree
7126 cxx_eval_component_reference (const constexpr_call *call, tree t,
7127                               bool allow_non_constant, bool addr,
7128                               bool *non_constant_p, bool *overflow_p)
7129 {
7130   unsigned HOST_WIDE_INT i;
7131   tree field;
7132   tree value;
7133   tree part = TREE_OPERAND (t, 1);
7134   tree orig_whole = TREE_OPERAND (t, 0);
7135   tree whole = cxx_eval_constant_expression (call, orig_whole,
7136                                              allow_non_constant, addr,
7137                                              non_constant_p, overflow_p);
7138   if (whole == orig_whole)
7139     return t;
7140   if (addr)
7141     return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
7142                         whole, part, NULL_TREE);
7143   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
7144      CONSTRUCTOR.  */
7145   if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
7146     {
7147       if (!allow_non_constant)
7148         error ("%qE is not a constant expression", orig_whole);
7149       *non_constant_p = true;
7150     }
7151   if (DECL_MUTABLE_P (part))
7152     {
7153       if (!allow_non_constant)
7154         error ("mutable %qD is not usable in a constant expression", part);
7155       *non_constant_p = true;
7156     }
7157   if (*non_constant_p)
7158     return t;
7159   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
7160     {
7161       if (field == part)
7162         return value;
7163     }
7164   if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
7165       && CONSTRUCTOR_NELTS (whole) > 0)
7166     {
7167       /* DR 1188 says we don't have to deal with this.  */
7168       if (!allow_non_constant)
7169         error ("accessing %qD member instead of initialized %qD member in "
7170                "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
7171       *non_constant_p = true;
7172       return t;
7173     }
7174
7175   /* If there's no explicit init for this field, it's value-initialized.  */
7176   value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
7177   return cxx_eval_constant_expression (call, value,
7178                                        allow_non_constant, addr,
7179                                        non_constant_p, overflow_p);
7180 }
7181
7182 /* Subroutine of cxx_eval_constant_expression.
7183    Attempt to reduce a field access of a value of class type that is
7184    expressed as a BIT_FIELD_REF.  */
7185
7186 static tree
7187 cxx_eval_bit_field_ref (const constexpr_call *call, tree t,
7188                         bool allow_non_constant, bool addr,
7189                         bool *non_constant_p, bool *overflow_p)
7190 {
7191   tree orig_whole = TREE_OPERAND (t, 0);
7192   tree retval, fldval, utype, mask;
7193   bool fld_seen = false;
7194   HOST_WIDE_INT istart, isize;
7195   tree whole = cxx_eval_constant_expression (call, orig_whole,
7196                                              allow_non_constant, addr,
7197                                              non_constant_p, overflow_p);
7198   tree start, field, value;
7199   unsigned HOST_WIDE_INT i;
7200
7201   if (whole == orig_whole)
7202     return t;
7203   /* Don't VERIFY_CONSTANT here; we only want to check that we got a
7204      CONSTRUCTOR.  */
7205   if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
7206     {
7207       if (!allow_non_constant)
7208         error ("%qE is not a constant expression", orig_whole);
7209       *non_constant_p = true;
7210     }
7211   if (*non_constant_p)
7212     return t;
7213
7214   start = TREE_OPERAND (t, 2);
7215   istart = tree_low_cst (start, 0);
7216   isize = tree_low_cst (TREE_OPERAND (t, 1), 0);
7217   utype = TREE_TYPE (t);
7218   if (!TYPE_UNSIGNED (utype))
7219     utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
7220   retval = build_int_cst (utype, 0);
7221   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
7222     {
7223       tree bitpos = bit_position (field);
7224       if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
7225         return value;
7226       if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
7227           && TREE_CODE (value) == INTEGER_CST
7228           && host_integerp (bitpos, 0)
7229           && host_integerp (DECL_SIZE (field), 0))
7230         {
7231           HOST_WIDE_INT bit = tree_low_cst (bitpos, 0);
7232           HOST_WIDE_INT sz = tree_low_cst (DECL_SIZE (field), 0);
7233           HOST_WIDE_INT shift;
7234           if (bit >= istart && bit + sz <= istart + isize)
7235             {
7236               fldval = fold_convert (utype, value);
7237               mask = build_int_cst_type (utype, -1);
7238               mask = fold_build2 (LSHIFT_EXPR, utype, mask,
7239                                   size_int (TYPE_PRECISION (utype) - sz));
7240               mask = fold_build2 (RSHIFT_EXPR, utype, mask,
7241                                   size_int (TYPE_PRECISION (utype) - sz));
7242               fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
7243               shift = bit - istart;
7244               if (BYTES_BIG_ENDIAN)
7245                 shift = TYPE_PRECISION (utype) - shift - sz;
7246               fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
7247                                     size_int (shift));
7248               retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
7249               fld_seen = true;
7250             }
7251         }
7252     }
7253   if (fld_seen)
7254     return fold_convert (TREE_TYPE (t), retval);
7255   gcc_unreachable ();
7256   return error_mark_node;
7257 }
7258
7259 /* Subroutine of cxx_eval_constant_expression.
7260    Evaluate a short-circuited logical expression T in the context
7261    of a given constexpr CALL.  BAILOUT_VALUE is the value for
7262    early return.  CONTINUE_VALUE is used here purely for
7263    sanity check purposes.  */
7264
7265 static tree
7266 cxx_eval_logical_expression (const constexpr_call *call, tree t,
7267                              tree bailout_value, tree continue_value,
7268                              bool allow_non_constant, bool addr,
7269                              bool *non_constant_p, bool *overflow_p)
7270 {
7271   tree r;
7272   tree lhs = cxx_eval_constant_expression (call, TREE_OPERAND (t, 0),
7273                                            allow_non_constant, addr,
7274                                            non_constant_p, overflow_p);
7275   VERIFY_CONSTANT (lhs);
7276   if (tree_int_cst_equal (lhs, bailout_value))
7277     return lhs;
7278   gcc_assert (tree_int_cst_equal (lhs, continue_value));
7279   r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
7280                                     allow_non_constant, addr, non_constant_p, overflow_p);
7281   VERIFY_CONSTANT (r);
7282   return r;
7283 }
7284
7285 /* REF is a COMPONENT_REF designating a particular field.  V is a vector of
7286    CONSTRUCTOR elements to initialize (part of) an object containing that
7287    field.  Return a pointer to the constructor_elt corresponding to the
7288    initialization of the field.  */
7289
7290 static constructor_elt *
7291 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
7292 {
7293   tree aggr = TREE_OPERAND (ref, 0);
7294   tree field = TREE_OPERAND (ref, 1);
7295   HOST_WIDE_INT i;
7296   constructor_elt *ce;
7297
7298   gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
7299
7300   if (TREE_CODE (aggr) == COMPONENT_REF)
7301     {
7302       constructor_elt *base_ce
7303         = base_field_constructor_elt (v, aggr);
7304       v = CONSTRUCTOR_ELTS (base_ce->value);
7305     }
7306
7307   for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
7308     if (ce->index == field)
7309       return ce;
7310
7311   gcc_unreachable ();
7312   return NULL;
7313 }
7314
7315 /* Subroutine of cxx_eval_constant_expression.
7316    The expression tree T denotes a C-style array or a C-style
7317    aggregate.  Reduce it to a constant expression.  */
7318
7319 static tree
7320 cxx_eval_bare_aggregate (const constexpr_call *call, tree t,
7321                          bool allow_non_constant, bool addr,
7322                          bool *non_constant_p, bool *overflow_p)
7323 {
7324   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
7325   vec<constructor_elt, va_gc> *n;
7326   vec_alloc (n, vec_safe_length (v));
7327   constructor_elt *ce;
7328   HOST_WIDE_INT i;
7329   bool changed = false;
7330   gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
7331   for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
7332     {
7333       tree elt = cxx_eval_constant_expression (call, ce->value,
7334                                                allow_non_constant, addr,
7335                                                non_constant_p, overflow_p);
7336       /* Don't VERIFY_CONSTANT here.  */
7337       if (allow_non_constant && *non_constant_p)
7338         goto fail;
7339       if (elt != ce->value)
7340         changed = true;
7341       if (ce->index && TREE_CODE (ce->index) == COMPONENT_REF)
7342         {
7343           /* This is an initialization of a vfield inside a base
7344              subaggregate that we already initialized; push this
7345              initialization into the previous initialization.  */
7346           constructor_elt *inner = base_field_constructor_elt (n, ce->index);
7347           inner->value = elt;
7348         }
7349       else if (ce->index && TREE_CODE (ce->index) == NOP_EXPR)
7350         {
7351           /* This is an initializer for an empty base; now that we've
7352              checked that it's constant, we can ignore it.  */
7353           gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (ce->index))));
7354         }
7355       else
7356         CONSTRUCTOR_APPEND_ELT (n, ce->index, elt);
7357     }
7358   if (*non_constant_p || !changed)
7359     {
7360     fail:
7361       vec_free (n);
7362       return t;
7363     }
7364   t = build_constructor (TREE_TYPE (t), n);
7365   TREE_CONSTANT (t) = true;
7366   if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
7367     t = fold (t);
7368   return t;
7369 }
7370
7371 /* Subroutine of cxx_eval_constant_expression.
7372    The expression tree T is a VEC_INIT_EXPR which denotes the desired
7373    initialization of a non-static data member of array type.  Reduce it to a
7374    CONSTRUCTOR.
7375
7376    Note that apart from value-initialization (when VALUE_INIT is true),
7377    this is only intended to support value-initialization and the
7378    initializations done by defaulted constructors for classes with
7379    non-static data members of array type.  In this case, VEC_INIT_EXPR_INIT
7380    will either be NULL_TREE for the default constructor, or a COMPONENT_REF
7381    for the copy/move constructor.  */
7382
7383 static tree
7384 cxx_eval_vec_init_1 (const constexpr_call *call, tree atype, tree init,
7385                      bool value_init, bool allow_non_constant, bool addr,
7386                      bool *non_constant_p, bool *overflow_p)
7387 {
7388   tree elttype = TREE_TYPE (atype);
7389   int max = tree_low_cst (array_type_nelts (atype), 0);
7390   vec<constructor_elt, va_gc> *n;
7391   vec_alloc (n, max + 1);
7392   bool pre_init = false;
7393   int i;
7394
7395   /* For the default constructor, build up a call to the default
7396      constructor of the element type.  We only need to handle class types
7397      here, as for a constructor to be constexpr, all members must be
7398      initialized, which for a defaulted default constructor means they must
7399      be of a class type with a constexpr default constructor.  */
7400   if (TREE_CODE (elttype) == ARRAY_TYPE)
7401     /* We only do this at the lowest level.  */;
7402   else if (value_init)
7403     {
7404       init = build_value_init (elttype, tf_warning_or_error);
7405       init = cxx_eval_constant_expression
7406             (call, init, allow_non_constant, addr, non_constant_p, overflow_p);
7407       pre_init = true;
7408     }
7409   else if (!init)
7410     {
7411       vec<tree, va_gc> *argvec = make_tree_vector ();
7412       init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
7413                                         &argvec, elttype, LOOKUP_NORMAL,
7414                                         tf_warning_or_error);
7415       release_tree_vector (argvec);
7416       init = cxx_eval_constant_expression (call, init, allow_non_constant,
7417                                            addr, non_constant_p, overflow_p);
7418       pre_init = true;
7419     }
7420
7421   if (*non_constant_p && !allow_non_constant)
7422     goto fail;
7423
7424   for (i = 0; i <= max; ++i)
7425     {
7426       tree idx = build_int_cst (size_type_node, i);
7427       tree eltinit;
7428       if (TREE_CODE (elttype) == ARRAY_TYPE)
7429         {
7430           /* A multidimensional array; recurse.  */
7431           if (value_init || init == NULL_TREE)
7432             eltinit = NULL_TREE;
7433           else
7434             eltinit = cp_build_array_ref (input_location, init, idx,
7435                                           tf_warning_or_error);
7436           eltinit = cxx_eval_vec_init_1 (call, elttype, eltinit, value_init,
7437                                          allow_non_constant, addr,
7438                                          non_constant_p, overflow_p);
7439         }
7440       else if (pre_init)
7441         {
7442           /* Initializing an element using value or default initialization
7443              we just pre-built above.  */
7444           if (i == 0)
7445             eltinit = init;
7446           else
7447             eltinit = unshare_expr (init);
7448         }
7449       else
7450         {
7451           /* Copying an element.  */
7452           vec<tree, va_gc> *argvec;
7453           gcc_assert (same_type_ignoring_top_level_qualifiers_p
7454                       (atype, TREE_TYPE (init)));
7455           eltinit = cp_build_array_ref (input_location, init, idx,
7456                                         tf_warning_or_error);
7457           if (!real_lvalue_p (init))
7458             eltinit = move (eltinit);
7459           argvec = make_tree_vector ();
7460           argvec->quick_push (eltinit);
7461           eltinit = (build_special_member_call
7462                      (NULL_TREE, complete_ctor_identifier, &argvec,
7463                       elttype, LOOKUP_NORMAL, tf_warning_or_error));
7464           release_tree_vector (argvec);
7465           eltinit = cxx_eval_constant_expression
7466             (call, eltinit, allow_non_constant, addr, non_constant_p, overflow_p);
7467         }
7468       if (*non_constant_p && !allow_non_constant)
7469         goto fail;
7470       CONSTRUCTOR_APPEND_ELT (n, idx, eltinit);
7471     }
7472
7473   if (!*non_constant_p)
7474     {
7475       init = build_constructor (atype, n);
7476       TREE_CONSTANT (init) = true;
7477       return init;
7478     }
7479
7480  fail:
7481   vec_free (n);
7482   return init;
7483 }
7484
7485 static tree
7486 cxx_eval_vec_init (const constexpr_call *call, tree t,
7487                    bool allow_non_constant, bool addr,
7488                    bool *non_constant_p, bool *overflow_p)
7489 {
7490   tree atype = TREE_TYPE (t);
7491   tree init = VEC_INIT_EXPR_INIT (t);
7492   tree r = cxx_eval_vec_init_1 (call, atype, init,
7493                                 VEC_INIT_EXPR_VALUE_INIT (t),
7494                                 allow_non_constant, addr, non_constant_p, overflow_p);
7495   if (*non_constant_p)
7496     return t;
7497   else
7498     return r;
7499 }
7500
7501 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
7502    match.  We want to be less strict for simple *& folding; if we have a
7503    non-const temporary that we access through a const pointer, that should
7504    work.  We handle this here rather than change fold_indirect_ref_1
7505    because we're dealing with things like ADDR_EXPR of INTEGER_CST which
7506    don't really make sense outside of constant expression evaluation.  Also
7507    we want to allow folding to COMPONENT_REF, which could cause trouble
7508    with TBAA in fold_indirect_ref_1.
7509
7510    Try to keep this function synced with fold_indirect_ref_1.  */
7511
7512 static tree
7513 cxx_fold_indirect_ref (location_t loc, tree type, tree op0, bool *empty_base)
7514 {
7515   tree sub, subtype;
7516
7517   sub = op0;
7518   STRIP_NOPS (sub);
7519   subtype = TREE_TYPE (sub);
7520   if (!POINTER_TYPE_P (subtype))
7521     return NULL_TREE;
7522
7523   if (TREE_CODE (sub) == ADDR_EXPR)
7524     {
7525       tree op = TREE_OPERAND (sub, 0);
7526       tree optype = TREE_TYPE (op);
7527
7528       /* *&CONST_DECL -> to the value of the const decl.  */
7529       if (TREE_CODE (op) == CONST_DECL)
7530         return DECL_INITIAL (op);
7531       /* *&p => p;  make sure to handle *&"str"[cst] here.  */
7532       if (same_type_ignoring_top_level_qualifiers_p (optype, type))
7533         {
7534           tree fop = fold_read_from_constant_string (op);
7535           if (fop)
7536             return fop;
7537           else
7538             return op;
7539         }
7540       /* *(foo *)&fooarray => fooarray[0] */
7541       else if (TREE_CODE (optype) == ARRAY_TYPE
7542                && (same_type_ignoring_top_level_qualifiers_p
7543                    (type, TREE_TYPE (optype))))
7544         {
7545           tree type_domain = TYPE_DOMAIN (optype);
7546           tree min_val = size_zero_node;
7547           if (type_domain && TYPE_MIN_VALUE (type_domain))
7548             min_val = TYPE_MIN_VALUE (type_domain);
7549           return build4_loc (loc, ARRAY_REF, type, op, min_val,
7550                              NULL_TREE, NULL_TREE);
7551         }
7552       /* *(foo *)&complexfoo => __real__ complexfoo */
7553       else if (TREE_CODE (optype) == COMPLEX_TYPE
7554                && (same_type_ignoring_top_level_qualifiers_p
7555                    (type, TREE_TYPE (optype))))
7556         return fold_build1_loc (loc, REALPART_EXPR, type, op);
7557       /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
7558       else if (TREE_CODE (optype) == VECTOR_TYPE
7559                && (same_type_ignoring_top_level_qualifiers_p
7560                    (type, TREE_TYPE (optype))))
7561         {
7562           tree part_width = TYPE_SIZE (type);
7563           tree index = bitsize_int (0);
7564           return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
7565         }
7566       /* Also handle conversion to an empty base class, which
7567          is represented with a NOP_EXPR.  */
7568       else if (is_empty_class (type)
7569                && CLASS_TYPE_P (optype)
7570                && DERIVED_FROM_P (type, optype))
7571         {
7572           *empty_base = true;
7573           return op;
7574         }
7575       /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
7576       else if (RECORD_OR_UNION_TYPE_P (optype))
7577         {
7578           tree field = TYPE_FIELDS (optype);
7579           for (; field; field = DECL_CHAIN (field))
7580             if (TREE_CODE (field) == FIELD_DECL
7581                 && integer_zerop (byte_position (field))
7582                 && (same_type_ignoring_top_level_qualifiers_p
7583                     (TREE_TYPE (field), type)))
7584               {
7585                 return fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
7586                 break;
7587               }
7588         }
7589     }
7590   else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
7591            && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
7592     {
7593       tree op00 = TREE_OPERAND (sub, 0);
7594       tree op01 = TREE_OPERAND (sub, 1);
7595
7596       STRIP_NOPS (op00);
7597       if (TREE_CODE (op00) == ADDR_EXPR)
7598         {
7599           tree op00type;
7600           op00 = TREE_OPERAND (op00, 0);
7601           op00type = TREE_TYPE (op00);
7602
7603           /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
7604           if (TREE_CODE (op00type) == VECTOR_TYPE
7605               && (same_type_ignoring_top_level_qualifiers_p
7606                   (type, TREE_TYPE (op00type))))
7607             {
7608               HOST_WIDE_INT offset = tree_low_cst (op01, 0);
7609               tree part_width = TYPE_SIZE (type);
7610               unsigned HOST_WIDE_INT part_widthi = tree_low_cst (part_width, 0)/BITS_PER_UNIT;
7611               unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
7612               tree index = bitsize_int (indexi);
7613
7614               if (offset/part_widthi <= TYPE_VECTOR_SUBPARTS (op00type))
7615                 return fold_build3_loc (loc,
7616                                         BIT_FIELD_REF, type, op00,
7617                                         part_width, index);
7618
7619             }
7620           /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
7621           else if (TREE_CODE (op00type) == COMPLEX_TYPE
7622                    && (same_type_ignoring_top_level_qualifiers_p
7623                        (type, TREE_TYPE (op00type))))
7624             {
7625               tree size = TYPE_SIZE_UNIT (type);
7626               if (tree_int_cst_equal (size, op01))
7627                 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
7628             }
7629           /* ((foo *)&fooarray)[1] => fooarray[1] */
7630           else if (TREE_CODE (op00type) == ARRAY_TYPE
7631                    && (same_type_ignoring_top_level_qualifiers_p
7632                        (type, TREE_TYPE (op00type))))
7633             {
7634               tree type_domain = TYPE_DOMAIN (op00type);
7635               tree min_val = size_zero_node;
7636               if (type_domain && TYPE_MIN_VALUE (type_domain))
7637                 min_val = TYPE_MIN_VALUE (type_domain);
7638               op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
7639                                      TYPE_SIZE_UNIT (type));
7640               op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
7641               return build4_loc (loc, ARRAY_REF, type, op00, op01,
7642                                  NULL_TREE, NULL_TREE);
7643             }
7644           /* Also handle conversion to an empty base class, which
7645              is represented with a NOP_EXPR.  */
7646           else if (is_empty_class (type)
7647                    && CLASS_TYPE_P (op00type)
7648                    && DERIVED_FROM_P (type, op00type))
7649             {
7650               *empty_base = true;
7651               return op00;
7652             }
7653           /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
7654           else if (RECORD_OR_UNION_TYPE_P (op00type))
7655             {
7656               tree field = TYPE_FIELDS (op00type);
7657               for (; field; field = DECL_CHAIN (field))
7658                 if (TREE_CODE (field) == FIELD_DECL
7659                     && tree_int_cst_equal (byte_position (field), op01)
7660                     && (same_type_ignoring_top_level_qualifiers_p
7661                         (TREE_TYPE (field), type)))
7662                   {
7663                     return fold_build3 (COMPONENT_REF, type, op00,
7664                                      field, NULL_TREE);
7665                     break;
7666                   }
7667             }
7668         }
7669     }
7670   /* *(foo *)fooarrptr => (*fooarrptr)[0] */
7671   else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
7672            && (same_type_ignoring_top_level_qualifiers_p
7673                (type, TREE_TYPE (TREE_TYPE (subtype)))))
7674     {
7675       tree type_domain;
7676       tree min_val = size_zero_node;
7677       tree newsub = cxx_fold_indirect_ref (loc, TREE_TYPE (subtype), sub, NULL);
7678       if (newsub)
7679         sub = newsub;
7680       else
7681         sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
7682       type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
7683       if (type_domain && TYPE_MIN_VALUE (type_domain))
7684         min_val = TYPE_MIN_VALUE (type_domain);
7685       return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
7686                          NULL_TREE);
7687     }
7688
7689   return NULL_TREE;
7690 }
7691
7692 static tree
7693 cxx_eval_indirect_ref (const constexpr_call *call, tree t,
7694                        bool allow_non_constant, bool addr,
7695                        bool *non_constant_p, bool *overflow_p)
7696 {
7697   tree orig_op0 = TREE_OPERAND (t, 0);
7698   tree op0 = cxx_eval_constant_expression (call, orig_op0, allow_non_constant,
7699                                            /*addr*/false, non_constant_p, overflow_p);
7700   bool empty_base = false;
7701   tree r;
7702
7703   /* Don't VERIFY_CONSTANT here.  */
7704   if (*non_constant_p)
7705     return t;
7706
7707   r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), op0,
7708                              &empty_base);
7709
7710   if (r)
7711     r = cxx_eval_constant_expression (call, r, allow_non_constant,
7712                                       addr, non_constant_p, overflow_p);
7713   else
7714     {
7715       tree sub = op0;
7716       STRIP_NOPS (sub);
7717       if (TREE_CODE (sub) == POINTER_PLUS_EXPR)
7718         {
7719           sub = TREE_OPERAND (sub, 0);
7720           STRIP_NOPS (sub);
7721         }
7722       if (TREE_CODE (sub) == ADDR_EXPR)
7723         {
7724           /* We couldn't fold to a constant value.  Make sure it's not
7725              something we should have been able to fold.  */
7726           gcc_assert (!same_type_ignoring_top_level_qualifiers_p
7727                       (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
7728           /* DR 1188 says we don't have to deal with this.  */
7729           if (!allow_non_constant)
7730             error ("accessing value of %qE through a %qT glvalue in a "
7731                    "constant expression", build_fold_indirect_ref (sub),
7732                    TREE_TYPE (t));
7733           *non_constant_p = true;
7734           return t;
7735         }
7736     }
7737
7738   /* If we're pulling out the value of an empty base, make sure
7739      that the whole object is constant and then return an empty
7740      CONSTRUCTOR.  */
7741   if (empty_base)
7742     {
7743       VERIFY_CONSTANT (r);
7744       r = build_constructor (TREE_TYPE (t), NULL);
7745       TREE_CONSTANT (r) = true;
7746     }
7747
7748   if (r == NULL_TREE)
7749     {
7750       if (addr && op0 != orig_op0)
7751         return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
7752       if (!addr)
7753         VERIFY_CONSTANT (t);
7754       return t;
7755     }
7756   return r;
7757 }
7758
7759 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
7760    Shared between potential_constant_expression and
7761    cxx_eval_constant_expression.  */
7762
7763 static void
7764 non_const_var_error (tree r)
7765 {
7766   tree type = TREE_TYPE (r);
7767   error ("the value of %qD is not usable in a constant "
7768          "expression", r);
7769   /* Avoid error cascade.  */
7770   if (DECL_INITIAL (r) == error_mark_node)
7771     return;
7772   if (DECL_DECLARED_CONSTEXPR_P (r))
7773     inform (DECL_SOURCE_LOCATION (r),
7774             "%qD used in its own initializer", r);
7775   else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7776     {
7777       if (!CP_TYPE_CONST_P (type))
7778         inform (DECL_SOURCE_LOCATION (r),
7779                 "%q#D is not const", r);
7780       else if (CP_TYPE_VOLATILE_P (type))
7781         inform (DECL_SOURCE_LOCATION (r),
7782                 "%q#D is volatile", r);
7783       else if (!DECL_INITIAL (r)
7784                || !TREE_CONSTANT (DECL_INITIAL (r)))
7785         inform (DECL_SOURCE_LOCATION (r),
7786                 "%qD was not initialized with a constant "
7787                 "expression", r);
7788       else
7789         gcc_unreachable ();
7790     }
7791   else
7792     {
7793       if (cxx_dialect >= cxx0x && !DECL_DECLARED_CONSTEXPR_P (r))
7794         inform (DECL_SOURCE_LOCATION (r),
7795                 "%qD was not declared %<constexpr%>", r);
7796       else
7797         inform (DECL_SOURCE_LOCATION (r),
7798                 "%qD does not have integral or enumeration type",
7799                 r);
7800     }
7801 }
7802
7803 /* Subroutine of cxx_eval_constant_expression.
7804    Like cxx_eval_unary_expression, except for trinary expressions.  */
7805
7806 static tree
7807 cxx_eval_trinary_expression (const constexpr_call *call, tree t,
7808                              bool allow_non_constant, bool addr,
7809                              bool *non_constant_p, bool *overflow_p)
7810 {
7811   int i;
7812   tree args[3];
7813   tree val;
7814
7815   for (i = 0; i < 3; i++)
7816     {
7817       args[i] = cxx_eval_constant_expression (call, TREE_OPERAND (t, i),
7818                                               allow_non_constant, addr,
7819                                               non_constant_p, overflow_p);
7820       VERIFY_CONSTANT (args[i]);
7821     }
7822
7823   val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
7824                           args[0], args[1], args[2]);
7825   if (val == NULL_TREE)
7826     return t;
7827   VERIFY_CONSTANT (val);
7828   return val;
7829 }
7830
7831 /* Attempt to reduce the expression T to a constant value.
7832    On failure, issue diagnostic and return error_mark_node.  */
7833 /* FIXME unify with c_fully_fold */
7834
7835 static tree
7836 cxx_eval_constant_expression (const constexpr_call *call, tree t,
7837                               bool allow_non_constant, bool addr,
7838                               bool *non_constant_p, bool *overflow_p)
7839 {
7840   tree r = t;
7841
7842   if (t == error_mark_node)
7843     {
7844       *non_constant_p = true;
7845       return t;
7846     }
7847   if (CONSTANT_CLASS_P (t))
7848     {
7849       if (TREE_CODE (t) == PTRMEM_CST)
7850         t = cplus_expand_constant (t);
7851       else if (TREE_OVERFLOW (t) && (!flag_permissive || allow_non_constant))
7852         *overflow_p = true;
7853       return t;
7854     }
7855   if (TREE_CODE (t) != NOP_EXPR
7856       && reduced_constant_expression_p (t))
7857     return fold (t);
7858
7859   switch (TREE_CODE (t))
7860     {
7861     case VAR_DECL:
7862       if (addr)
7863         return t;
7864       /* else fall through. */
7865     case CONST_DECL:
7866       r = integral_constant_value (t);
7867       if (TREE_CODE (r) == TARGET_EXPR
7868           && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
7869         r = TARGET_EXPR_INITIAL (r);
7870       if (DECL_P (r))
7871         {
7872           if (!allow_non_constant)
7873             non_const_var_error (r);
7874           *non_constant_p = true;
7875         }
7876       break;
7877
7878     case FUNCTION_DECL:
7879     case TEMPLATE_DECL:
7880     case LABEL_DECL:
7881       return t;
7882
7883     case PARM_DECL:
7884       if (call && DECL_CONTEXT (t) == call->fundef->decl)
7885         {
7886           if (DECL_ARTIFICIAL (t) && DECL_CONSTRUCTOR_P (DECL_CONTEXT (t)))
7887             {
7888               if (!allow_non_constant)
7889                 sorry ("use of the value of the object being constructed "
7890                        "in a constant expression");
7891               *non_constant_p = true;
7892             }
7893           else
7894             r = lookup_parameter_binding (call, t);
7895         }
7896       else if (addr)
7897         /* Defer in case this is only used for its type.  */;
7898       else
7899         {
7900           if (!allow_non_constant)
7901             error ("%qE is not a constant expression", t);
7902           *non_constant_p = true;
7903         }
7904       break;
7905
7906     case CALL_EXPR:
7907     case AGGR_INIT_EXPR:
7908       r = cxx_eval_call_expression (call, t, allow_non_constant, addr,
7909                                     non_constant_p, overflow_p);
7910       break;
7911
7912     case TARGET_EXPR:
7913       if (!literal_type_p (TREE_TYPE (t)))
7914         {
7915           if (!allow_non_constant)
7916             {
7917               error ("temporary of non-literal type %qT in a "
7918                      "constant expression", TREE_TYPE (t));
7919               explain_non_literal_class (TREE_TYPE (t));
7920             }
7921           *non_constant_p = true;
7922           break;
7923         }
7924       /* else fall through.  */
7925     case INIT_EXPR:
7926       /* Pass false for 'addr' because these codes indicate
7927          initialization of a temporary.  */
7928       r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
7929                                         allow_non_constant, false,
7930                                         non_constant_p, overflow_p);
7931       if (!*non_constant_p)
7932         /* Adjust the type of the result to the type of the temporary.  */
7933         r = adjust_temp_type (TREE_TYPE (t), r);
7934       break;
7935
7936     case SCOPE_REF:
7937       r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 1),
7938                                         allow_non_constant, addr,
7939                                         non_constant_p, overflow_p);
7940       break;
7941
7942     case RETURN_EXPR:
7943     case NON_LVALUE_EXPR:
7944     case TRY_CATCH_EXPR:
7945     case CLEANUP_POINT_EXPR:
7946     case MUST_NOT_THROW_EXPR:
7947     case SAVE_EXPR:
7948       r = cxx_eval_constant_expression (call, TREE_OPERAND (t, 0),
7949                                         allow_non_constant, addr,
7950                                         non_constant_p, overflow_p);
7951       break;
7952
7953       /* These differ from cxx_eval_unary_expression in that this doesn't
7954          check for a constant operand or result; an address can be
7955          constant without its operand being, and vice versa.  */
7956     case INDIRECT_REF:
7957       r = cxx_eval_indirect_ref (call, t, allow_non_constant, addr,
7958                                  non_constant_p, overflow_p);
7959       break;
7960
7961     case ADDR_EXPR:
7962       {
7963         tree oldop = TREE_OPERAND (t, 0);
7964         tree op = cxx_eval_constant_expression (call, oldop,
7965                                                 allow_non_constant,
7966                                                 /*addr*/true,
7967                                                 non_constant_p, overflow_p);
7968         /* Don't VERIFY_CONSTANT here.  */
7969         if (*non_constant_p)
7970           return t;
7971         /* This function does more aggressive folding than fold itself.  */
7972         r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
7973         if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
7974           return t;
7975         break;
7976       }
7977
7978     case REALPART_EXPR:
7979     case IMAGPART_EXPR:
7980     case CONJ_EXPR:
7981     case FIX_TRUNC_EXPR:
7982     case FLOAT_EXPR:
7983     case NEGATE_EXPR:
7984     case ABS_EXPR:
7985     case BIT_NOT_EXPR:
7986     case TRUTH_NOT_EXPR:
7987     case FIXED_CONVERT_EXPR:
7988       r = cxx_eval_unary_expression (call, t, allow_non_constant, addr,
7989                                      non_constant_p, overflow_p);
7990       break;
7991
7992     case SIZEOF_EXPR:
7993       if (SIZEOF_EXPR_TYPE_P (t))
7994         r = cxx_sizeof_or_alignof_type (TREE_TYPE (TREE_OPERAND (t, 0)),
7995                                         SIZEOF_EXPR, false);
7996       else if (TYPE_P (TREE_OPERAND (t, 0)))
7997         r = cxx_sizeof_or_alignof_type (TREE_OPERAND (t, 0), SIZEOF_EXPR,
7998                                         false);
7999       else
8000         r = cxx_sizeof_or_alignof_expr (TREE_OPERAND (t, 0), SIZEOF_EXPR,
8001                                         false);
8002       if (r == error_mark_node)
8003         r = size_one_node;
8004       VERIFY_CONSTANT (r);
8005       break;
8006
8007     case COMPOUND_EXPR:
8008       {
8009         /* check_return_expr sometimes wraps a TARGET_EXPR in a
8010            COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
8011            introduced by build_call_a.  */
8012         tree op0 = TREE_OPERAND (t, 0);
8013         tree op1 = TREE_OPERAND (t, 1);
8014         STRIP_NOPS (op1);
8015         if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
8016             || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
8017           r = cxx_eval_constant_expression (call, op0, allow_non_constant,
8018                                             addr, non_constant_p, overflow_p);
8019         else
8020           {
8021             /* Check that the LHS is constant and then discard it.  */
8022             cxx_eval_constant_expression (call, op0, allow_non_constant,
8023                                           false, non_constant_p, overflow_p);
8024             op1 = TREE_OPERAND (t, 1);
8025             r = cxx_eval_constant_expression (call, op1, allow_non_constant,
8026                                               addr, non_constant_p, overflow_p);
8027           }
8028       }
8029       break;
8030
8031     case POINTER_PLUS_EXPR:
8032     case PLUS_EXPR:
8033     case MINUS_EXPR:
8034     case MULT_EXPR:
8035     case TRUNC_DIV_EXPR:
8036     case CEIL_DIV_EXPR:
8037     case FLOOR_DIV_EXPR:
8038     case ROUND_DIV_EXPR:
8039     case TRUNC_MOD_EXPR:
8040     case CEIL_MOD_EXPR:
8041     case ROUND_MOD_EXPR:
8042     case RDIV_EXPR:
8043     case EXACT_DIV_EXPR:
8044     case MIN_EXPR:
8045     case MAX_EXPR:
8046     case LSHIFT_EXPR:
8047     case RSHIFT_EXPR:
8048     case LROTATE_EXPR:
8049     case RROTATE_EXPR:
8050     case BIT_IOR_EXPR:
8051     case BIT_XOR_EXPR:
8052     case BIT_AND_EXPR:
8053     case TRUTH_XOR_EXPR:
8054     case LT_EXPR:
8055     case LE_EXPR:
8056     case GT_EXPR:
8057     case GE_EXPR:
8058     case EQ_EXPR:
8059     case NE_EXPR:
8060     case UNORDERED_EXPR:
8061     case ORDERED_EXPR:
8062     case UNLT_EXPR:
8063     case UNLE_EXPR:
8064     case UNGT_EXPR:
8065     case UNGE_EXPR:
8066     case UNEQ_EXPR:
8067     case LTGT_EXPR:
8068     case RANGE_EXPR:
8069     case COMPLEX_EXPR:
8070       r = cxx_eval_binary_expression (call, t, allow_non_constant, addr,
8071                                       non_constant_p, overflow_p);
8072       break;
8073
8074       /* fold can introduce non-IF versions of these; still treat them as
8075          short-circuiting.  */
8076     case TRUTH_AND_EXPR:
8077     case TRUTH_ANDIF_EXPR:
8078       r = cxx_eval_logical_expression (call, t, boolean_false_node,
8079                                        boolean_true_node,
8080                                        allow_non_constant, addr,
8081                                        non_constant_p, overflow_p);
8082       break;
8083
8084     case TRUTH_OR_EXPR:
8085     case TRUTH_ORIF_EXPR:
8086       r = cxx_eval_logical_expression (call, t, boolean_true_node,
8087                                        boolean_false_node,
8088                                        allow_non_constant, addr,
8089                                        non_constant_p, overflow_p);
8090       break;
8091
8092     case ARRAY_NOTATION_REF:
8093     case ARRAY_REF:
8094       r = cxx_eval_array_reference (call, t, allow_non_constant, addr,
8095                                     non_constant_p, overflow_p);
8096       break;
8097
8098     case COMPONENT_REF:
8099       r = cxx_eval_component_reference (call, t, allow_non_constant, addr,
8100                                         non_constant_p, overflow_p);
8101       break;
8102
8103     case BIT_FIELD_REF:
8104       r = cxx_eval_bit_field_ref (call, t, allow_non_constant, addr,
8105                                   non_constant_p, overflow_p);
8106       break;
8107
8108     case COND_EXPR:
8109     case VEC_COND_EXPR:
8110       r = cxx_eval_conditional_expression (call, t, allow_non_constant, addr,
8111                                            non_constant_p, overflow_p);
8112       break;
8113
8114     case CONSTRUCTOR:
8115       r = cxx_eval_bare_aggregate (call, t, allow_non_constant, addr,
8116                                    non_constant_p, overflow_p);
8117       break;
8118
8119     case VEC_INIT_EXPR:
8120       /* We can get this in a defaulted constructor for a class with a
8121          non-static data member of array type.  Either the initializer will
8122          be NULL, meaning default-initialization, or it will be an lvalue
8123          or xvalue of the same type, meaning direct-initialization from the
8124          corresponding member.  */
8125       r = cxx_eval_vec_init (call, t, allow_non_constant, addr,
8126                              non_constant_p, overflow_p);
8127       break;
8128
8129     case FMA_EXPR:
8130     case VEC_PERM_EXPR:
8131       r = cxx_eval_trinary_expression (call, t, allow_non_constant, addr,
8132                                        non_constant_p, overflow_p);
8133       break;
8134
8135     case CONVERT_EXPR:
8136     case VIEW_CONVERT_EXPR:
8137     case NOP_EXPR:
8138       {
8139         tree oldop = TREE_OPERAND (t, 0);
8140         tree op = cxx_eval_constant_expression (call, oldop,
8141                                                 allow_non_constant, addr,
8142                                                 non_constant_p, overflow_p);
8143         if (*non_constant_p)
8144           return t;
8145         if (POINTER_TYPE_P (TREE_TYPE (t))
8146             && TREE_CODE (op) == INTEGER_CST
8147             && !integer_zerop (op))
8148           {
8149             if (!allow_non_constant)
8150               error_at (EXPR_LOC_OR_HERE (t),
8151                         "reinterpret_cast from integer to pointer");
8152             *non_constant_p = true;
8153             return t;
8154           }
8155         if (op == oldop)
8156           /* We didn't fold at the top so we could check for ptr-int
8157              conversion.  */
8158           return fold (t);
8159         r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), op);
8160         /* Conversion of an out-of-range value has implementation-defined
8161            behavior; the language considers it different from arithmetic
8162            overflow, which is undefined.  */
8163         if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
8164           TREE_OVERFLOW (r) = false;
8165       }
8166       break;
8167
8168     case EMPTY_CLASS_EXPR:
8169       /* This is good enough for a function argument that might not get
8170          used, and they can't do anything with it, so just return it.  */
8171       return t;
8172
8173     case LAMBDA_EXPR:
8174     case PREINCREMENT_EXPR:
8175     case POSTINCREMENT_EXPR:
8176     case PREDECREMENT_EXPR:
8177     case POSTDECREMENT_EXPR:
8178     case NEW_EXPR:
8179     case VEC_NEW_EXPR:
8180     case DELETE_EXPR:
8181     case VEC_DELETE_EXPR:
8182     case THROW_EXPR:
8183     case MODIFY_EXPR:
8184     case MODOP_EXPR:
8185       /* GCC internal stuff.  */
8186     case VA_ARG_EXPR:
8187     case OBJ_TYPE_REF:
8188     case WITH_CLEANUP_EXPR:
8189     case STATEMENT_LIST:
8190     case BIND_EXPR:
8191     case NON_DEPENDENT_EXPR:
8192     case BASELINK:
8193     case EXPR_STMT:
8194     case OFFSET_REF:
8195       if (!allow_non_constant)
8196         error_at (EXPR_LOC_OR_HERE (t),
8197                   "expression %qE is not a constant-expression", t);
8198       *non_constant_p = true;
8199       break;
8200
8201     default:
8202       internal_error ("unexpected expression %qE of kind %s", t,
8203                       tree_code_name[TREE_CODE (t)]);
8204       *non_constant_p = true;
8205       break;
8206     }
8207
8208   if (r == error_mark_node)
8209     *non_constant_p = true;
8210
8211   if (*non_constant_p)
8212     return t;
8213   else
8214     return r;
8215 }
8216
8217 static tree
8218 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant)
8219 {
8220   bool non_constant_p = false;
8221   bool overflow_p = false;
8222   tree r = cxx_eval_constant_expression (NULL, t, allow_non_constant,
8223                                          false, &non_constant_p, &overflow_p);
8224
8225   verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
8226
8227   if (TREE_CODE (t) != CONSTRUCTOR
8228       && cp_has_mutable_p (TREE_TYPE (t)))
8229     {
8230       /* We allow a mutable type if the original expression was a
8231          CONSTRUCTOR so that we can do aggregate initialization of
8232          constexpr variables.  */
8233       if (!allow_non_constant)
8234         error ("%qT cannot be the type of a complete constant expression "
8235                "because it has mutable sub-objects", TREE_TYPE (t));
8236       non_constant_p = true;
8237     }
8238
8239   /* Technically we should check this for all subexpressions, but that
8240      runs into problems with our internal representation of pointer
8241      subtraction and the 5.19 rules are still in flux.  */
8242   if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
8243       && ARITHMETIC_TYPE_P (TREE_TYPE (r))
8244       && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
8245     {
8246       if (!allow_non_constant)
8247         error ("conversion from pointer type %qT "
8248                "to arithmetic type %qT in a constant-expression",
8249                TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
8250       non_constant_p = true;
8251     }
8252
8253   if (!non_constant_p && overflow_p)
8254     non_constant_p = true;
8255
8256   if (non_constant_p && !allow_non_constant)
8257     return error_mark_node;
8258   else if (non_constant_p && TREE_CONSTANT (r))
8259     {
8260       /* This isn't actually constant, so unset TREE_CONSTANT.  */
8261       if (EXPR_P (r))
8262         r = copy_node (r);
8263       else if (TREE_CODE (r) == CONSTRUCTOR)
8264         r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
8265       else
8266         r = build_nop (TREE_TYPE (r), r);
8267       TREE_CONSTANT (r) = false;
8268     }
8269   else if (non_constant_p || r == t)
8270     return t;
8271
8272   if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
8273     {
8274       if (TREE_CODE (t) == TARGET_EXPR
8275           && TARGET_EXPR_INITIAL (t) == r)
8276         return t;
8277       else
8278         {
8279           r = get_target_expr (r);
8280           TREE_CONSTANT (r) = true;
8281           return r;
8282         }
8283     }
8284   else
8285     return r;
8286 }
8287
8288 /* Returns true if T is a valid subexpression of a constant expression,
8289    even if it isn't itself a constant expression.  */
8290
8291 bool
8292 is_sub_constant_expr (tree t)
8293 {
8294   bool non_constant_p = false;
8295   bool overflow_p = false;
8296   cxx_eval_constant_expression (NULL, t, true, false, &non_constant_p,
8297                                 &overflow_p);
8298   return !non_constant_p && !overflow_p;
8299 }
8300
8301 /* If T represents a constant expression returns its reduced value.
8302    Otherwise return error_mark_node.  If T is dependent, then
8303    return NULL.  */
8304
8305 tree
8306 cxx_constant_value (tree t)
8307 {
8308   return cxx_eval_outermost_constant_expr (t, false);
8309 }
8310
8311 /* If T is a constant expression, returns its reduced value.
8312    Otherwise, if T does not have TREE_CONSTANT set, returns T.
8313    Otherwise, returns a version of T without TREE_CONSTANT.  */
8314
8315 tree
8316 maybe_constant_value (tree t)
8317 {
8318   tree r;
8319
8320   if (instantiation_dependent_expression_p (t)
8321       || type_unknown_p (t)
8322       || BRACE_ENCLOSED_INITIALIZER_P (t)
8323       || !potential_constant_expression (t))
8324     {
8325       if (TREE_OVERFLOW_P (t))
8326         {
8327           t = build_nop (TREE_TYPE (t), t);
8328           TREE_CONSTANT (t) = false;
8329         }
8330       return t;
8331     }
8332
8333   r = cxx_eval_outermost_constant_expr (t, true);
8334 #ifdef ENABLE_CHECKING
8335   /* cp_tree_equal looks through NOPs, so allow them.  */
8336   gcc_assert (r == t
8337               || CONVERT_EXPR_P (t)
8338               || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8339               || !cp_tree_equal (r, t));
8340 #endif
8341   return r;
8342 }
8343
8344 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
8345    than wrapped in a TARGET_EXPR.  */
8346
8347 tree
8348 maybe_constant_init (tree t)
8349 {
8350   t = maybe_constant_value (t);
8351   if (TREE_CODE (t) == TARGET_EXPR)
8352     {
8353       tree init = TARGET_EXPR_INITIAL (t);
8354       if (TREE_CODE (init) == CONSTRUCTOR)
8355         t = init;
8356     }
8357   return t;
8358 }
8359
8360 #if 0
8361 /* FIXME see ADDR_EXPR section in potential_constant_expression_1.  */
8362 /* Return true if the object referred to by REF has automatic or thread
8363    local storage.  */
8364
8365 enum { ck_ok, ck_bad, ck_unknown };
8366 static int
8367 check_automatic_or_tls (tree ref)
8368 {
8369   enum machine_mode mode;
8370   HOST_WIDE_INT bitsize, bitpos;
8371   tree offset;
8372   int volatilep = 0, unsignedp = 0;
8373   tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
8374                                    &mode, &unsignedp, &volatilep, false);
8375   duration_kind dk;
8376
8377   /* If there isn't a decl in the middle, we don't know the linkage here,
8378      and this isn't a constant expression anyway.  */
8379   if (!DECL_P (decl))
8380     return ck_unknown;
8381   dk = decl_storage_duration (decl);
8382   return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
8383 }
8384 #endif
8385
8386 /* Return true if T denotes a potentially constant expression.  Issue
8387    diagnostic as appropriate under control of FLAGS.  If WANT_RVAL is true,
8388    an lvalue-rvalue conversion is implied.
8389
8390    C++0x [expr.const] used to say
8391
8392    6 An expression is a potential constant expression if it is
8393      a constant expression where all occurences of function
8394      parameters are replaced by arbitrary constant expressions
8395      of the appropriate type.
8396
8397    2  A conditional expression is a constant expression unless it
8398       involves one of the following as a potentially evaluated
8399       subexpression (3.2), but subexpressions of logical AND (5.14),
8400       logical OR (5.15), and conditional (5.16) operations that are
8401       not evaluated are not considered.   */
8402
8403 static bool
8404 potential_constant_expression_1 (tree t, bool want_rval, tsubst_flags_t flags)
8405 {
8406   enum { any = false, rval = true };
8407   int i;
8408   tree tmp;
8409
8410   if (t == error_mark_node)
8411     return false;
8412   if (t == NULL_TREE)
8413     return true;
8414   if (TREE_THIS_VOLATILE (t))
8415     {
8416       if (flags & tf_error)
8417         error ("expression %qE has side-effects", t);
8418       return false;
8419     }
8420   if (CONSTANT_CLASS_P (t))
8421     return true;
8422
8423   switch (TREE_CODE (t))
8424     {
8425     case FUNCTION_DECL:
8426     case BASELINK:
8427     case TEMPLATE_DECL:
8428     case OVERLOAD:
8429     case TEMPLATE_ID_EXPR:
8430     case LABEL_DECL:
8431     case CONST_DECL:
8432     case SIZEOF_EXPR:
8433     case ALIGNOF_EXPR:
8434     case OFFSETOF_EXPR:
8435     case NOEXCEPT_EXPR:
8436     case TEMPLATE_PARM_INDEX:
8437     case TRAIT_EXPR:
8438     case IDENTIFIER_NODE:
8439     case USERDEF_LITERAL:
8440       /* We can see a FIELD_DECL in a pointer-to-member expression.  */
8441     case FIELD_DECL:
8442     case PARM_DECL:
8443     case USING_DECL:
8444       return true;
8445
8446     case AGGR_INIT_EXPR:
8447     case CALL_EXPR:
8448       /* -- an invocation of a function other than a constexpr function
8449             or a constexpr constructor.  */
8450       {
8451         tree fun = get_function_named_in_call (t);
8452         const int nargs = call_expr_nargs (t);
8453         i = 0;
8454
8455         if (is_overloaded_fn (fun))
8456           {
8457             if (TREE_CODE (fun) == FUNCTION_DECL)
8458               {
8459                 if (builtin_valid_in_constant_expr_p (fun))
8460                   return true;
8461                 if (!DECL_DECLARED_CONSTEXPR_P (fun)
8462                     /* Allow any built-in function; if the expansion
8463                        isn't constant, we'll deal with that then.  */
8464                     && !is_builtin_fn (fun))
8465                   {
8466                     if (flags & tf_error)
8467                       {
8468                         error_at (EXPR_LOC_OR_HERE (t),
8469                                   "call to non-constexpr function %qD", fun);
8470                         explain_invalid_constexpr_fn (fun);
8471                       }
8472                     return false;
8473                   }
8474                 /* A call to a non-static member function takes the address
8475                    of the object as the first argument.  But in a constant
8476                    expression the address will be folded away, so look
8477                    through it now.  */
8478                 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
8479                     && !DECL_CONSTRUCTOR_P (fun))
8480                   {
8481                     tree x = get_nth_callarg (t, 0);
8482                     if (is_this_parameter (x))
8483                       {
8484                         if (DECL_CONTEXT (x) == NULL_TREE
8485                             || DECL_CONSTRUCTOR_P (DECL_CONTEXT (x)))
8486                           {
8487                             if (flags & tf_error)
8488                               sorry ("calling a member function of the "
8489                                      "object being constructed in a constant "
8490                                      "expression");
8491                             return false;
8492                           }
8493                         /* Otherwise OK.  */;
8494                       }
8495                     else if (!potential_constant_expression_1 (x, rval, flags))
8496                       return false;
8497                     i = 1;
8498                   }
8499               }
8500             else
8501               {
8502                 if (!potential_constant_expression_1 (fun, true, flags))
8503                   return false;
8504                 fun = get_first_fn (fun);
8505               }
8506             /* Skip initial arguments to base constructors.  */
8507             if (DECL_BASE_CONSTRUCTOR_P (fun))
8508               i = num_artificial_parms_for (fun);
8509             fun = DECL_ORIGIN (fun);
8510           }
8511         else
8512           {
8513             if (potential_constant_expression_1 (fun, rval, flags))
8514               /* Might end up being a constant function pointer.  */;
8515             else
8516               return false;
8517           }
8518         for (; i < nargs; ++i)
8519           {
8520             tree x = get_nth_callarg (t, i);
8521             if (!potential_constant_expression_1 (x, rval, flags))
8522               return false;
8523           }
8524         return true;
8525       }
8526
8527     case NON_LVALUE_EXPR:
8528       /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
8529             -- an lvalue of integral type that refers to a non-volatile
8530                const variable or static data member initialized with
8531                constant expressions, or
8532
8533             -- an lvalue of literal type that refers to non-volatile
8534                object defined with constexpr, or that refers to a
8535                sub-object of such an object;  */
8536       return potential_constant_expression_1 (TREE_OPERAND (t, 0), rval, flags);
8537
8538     case VAR_DECL:
8539       if (want_rval && !decl_constant_var_p (t)
8540           && !dependent_type_p (TREE_TYPE (t)))
8541         {
8542           if (flags & tf_error)
8543             non_const_var_error (t);
8544           return false;
8545         }
8546       return true;
8547
8548     case NOP_EXPR:
8549     case CONVERT_EXPR:
8550     case VIEW_CONVERT_EXPR:
8551       /* -- a reinterpret_cast.  FIXME not implemented, and this rule
8552          may change to something more specific to type-punning (DR 1312).  */
8553       {
8554         tree from = TREE_OPERAND (t, 0);
8555         if (POINTER_TYPE_P (TREE_TYPE (t))
8556             && TREE_CODE (from) == INTEGER_CST
8557             && !integer_zerop (from))
8558           {
8559             if (flags & tf_error)
8560               error_at (EXPR_LOC_OR_HERE (t),
8561                         "reinterpret_cast from integer to pointer");
8562             return false;
8563           }
8564         return (potential_constant_expression_1
8565                 (from, TREE_CODE (t) != VIEW_CONVERT_EXPR, flags));
8566       }
8567
8568     case ADDR_EXPR:
8569       /* -- a unary operator & that is applied to an lvalue that
8570             designates an object with thread or automatic storage
8571             duration;  */
8572       t = TREE_OPERAND (t, 0);
8573 #if 0
8574       /* FIXME adjust when issue 1197 is fully resolved.  For now don't do
8575          any checking here, as we might dereference the pointer later.  If
8576          we remove this code, also remove check_automatic_or_tls.  */
8577       i = check_automatic_or_tls (t);
8578       if (i == ck_ok)
8579         return true;
8580       if (i == ck_bad)
8581         {
8582           if (flags & tf_error)
8583             error ("address-of an object %qE with thread local or "
8584                    "automatic storage is not a constant expression", t);
8585           return false;
8586         }
8587 #endif
8588       return potential_constant_expression_1 (t, any, flags);
8589
8590     case COMPONENT_REF:
8591     case BIT_FIELD_REF:
8592     case ARROW_EXPR:
8593     case OFFSET_REF:
8594       /* -- a class member access unless its postfix-expression is
8595             of literal type or of pointer to literal type.  */
8596       /* This test would be redundant, as it follows from the
8597          postfix-expression being a potential constant expression.  */
8598       return potential_constant_expression_1 (TREE_OPERAND (t, 0),
8599                                               want_rval, flags);
8600
8601     case EXPR_PACK_EXPANSION:
8602       return potential_constant_expression_1 (PACK_EXPANSION_PATTERN (t),
8603                                               want_rval, flags);
8604
8605     case INDIRECT_REF:
8606       {
8607         tree x = TREE_OPERAND (t, 0);
8608         STRIP_NOPS (x);
8609         if (is_this_parameter (x))
8610           {
8611             if (DECL_CONTEXT (x)
8612                 && !DECL_DECLARED_CONSTEXPR_P (DECL_CONTEXT (x)))
8613               {
8614                 if (flags & tf_error)
8615                   error ("use of %<this%> in a constant expression");
8616                 return false;
8617               }
8618             if (want_rval && DECL_CONTEXT (x)
8619                 && DECL_CONSTRUCTOR_P (DECL_CONTEXT (x)))
8620               {
8621                 if (flags & tf_error)
8622                   sorry ("use of the value of the object being constructed "
8623                          "in a constant expression");
8624                 return false;
8625               }
8626             return true;
8627           }
8628         return potential_constant_expression_1 (x, rval, flags);
8629       }
8630
8631     case LAMBDA_EXPR:
8632     case DYNAMIC_CAST_EXPR:
8633     case PSEUDO_DTOR_EXPR:
8634     case PREINCREMENT_EXPR:
8635     case POSTINCREMENT_EXPR:
8636     case PREDECREMENT_EXPR:
8637     case POSTDECREMENT_EXPR:
8638     case NEW_EXPR:
8639     case VEC_NEW_EXPR:
8640     case DELETE_EXPR:
8641     case VEC_DELETE_EXPR:
8642     case THROW_EXPR:
8643     case MODIFY_EXPR:
8644     case MODOP_EXPR:
8645     case OMP_ATOMIC:
8646     case OMP_ATOMIC_READ:
8647     case OMP_ATOMIC_CAPTURE_OLD:
8648     case OMP_ATOMIC_CAPTURE_NEW:
8649       /* GCC internal stuff.  */
8650     case VA_ARG_EXPR:
8651     case OBJ_TYPE_REF:
8652     case WITH_CLEANUP_EXPR:
8653     case CLEANUP_POINT_EXPR:
8654     case MUST_NOT_THROW_EXPR:
8655     case TRY_CATCH_EXPR:
8656     case STATEMENT_LIST:
8657       /* Don't bother trying to define a subset of statement-expressions to
8658          be constant-expressions, at least for now.  */
8659     case STMT_EXPR:
8660     case EXPR_STMT:
8661     case BIND_EXPR:
8662     case TRANSACTION_EXPR:
8663     case IF_STMT:
8664     case DO_STMT:
8665     case FOR_STMT:
8666     case WHILE_STMT:
8667       if (flags & tf_error)
8668         error ("expression %qE is not a constant-expression", t);
8669       return false;
8670
8671     case TYPEID_EXPR:
8672       /* -- a typeid expression whose operand is of polymorphic
8673             class type;  */
8674       {
8675         tree e = TREE_OPERAND (t, 0);
8676         if (!TYPE_P (e) && !type_dependent_expression_p (e)
8677             && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
8678           {
8679             if (flags & tf_error)
8680               error ("typeid-expression is not a constant expression "
8681                      "because %qE is of polymorphic type", e);
8682             return false;
8683           }
8684         return true;
8685       }
8686
8687     case MINUS_EXPR:
8688       /* -- a subtraction where both operands are pointers.   */
8689       if (TYPE_PTR_P (TREE_OPERAND (t, 0))
8690           && TYPE_PTR_P (TREE_OPERAND (t, 1)))
8691         {
8692           if (flags & tf_error)
8693             error ("difference of two pointer expressions is not "
8694                    "a constant expression");
8695           return false;
8696         }
8697       want_rval = true;
8698       goto binary;
8699
8700     case LT_EXPR:
8701     case LE_EXPR:
8702     case GT_EXPR:
8703     case GE_EXPR:
8704     case EQ_EXPR:
8705     case NE_EXPR:
8706       /* -- a relational or equality operator where at least
8707             one of the operands is a pointer.  */
8708       if (TYPE_PTR_P (TREE_OPERAND (t, 0))
8709           || TYPE_PTR_P (TREE_OPERAND (t, 1)))
8710         {
8711           if (flags & tf_error)
8712             error ("pointer comparison expression is not a "
8713                    "constant expression");
8714           return false;
8715         }
8716       want_rval = true;
8717       goto binary;
8718
8719     case BIT_NOT_EXPR:
8720       /* A destructor.  */
8721       if (TYPE_P (TREE_OPERAND (t, 0)))
8722         return true;
8723       /* else fall through.  */
8724
8725     case REALPART_EXPR:
8726     case IMAGPART_EXPR:
8727     case CONJ_EXPR:
8728     case SAVE_EXPR:
8729     case FIX_TRUNC_EXPR:
8730     case FLOAT_EXPR:
8731     case NEGATE_EXPR:
8732     case ABS_EXPR:
8733     case TRUTH_NOT_EXPR:
8734     case FIXED_CONVERT_EXPR:
8735     case UNARY_PLUS_EXPR:
8736       return potential_constant_expression_1 (TREE_OPERAND (t, 0), rval,
8737                                               flags);
8738
8739     case CAST_EXPR:
8740     case CONST_CAST_EXPR:
8741     case STATIC_CAST_EXPR:
8742     case REINTERPRET_CAST_EXPR:
8743     case IMPLICIT_CONV_EXPR:
8744       if (cxx_dialect < cxx0x
8745           && !dependent_type_p (TREE_TYPE (t))
8746           && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
8747         /* In C++98, a conversion to non-integral type can't be part of a
8748            constant expression.  */
8749         {
8750           if (flags & tf_error)
8751             error ("cast to non-integral type %qT in a constant expression",
8752                    TREE_TYPE (t));
8753           return false;
8754         }
8755
8756       return (potential_constant_expression_1
8757               (TREE_OPERAND (t, 0),
8758                TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE, flags));
8759
8760     case PAREN_EXPR:
8761     case NON_DEPENDENT_EXPR:
8762       /* For convenience.  */
8763     case RETURN_EXPR:
8764       return potential_constant_expression_1 (TREE_OPERAND (t, 0),
8765                                               want_rval, flags);
8766
8767     case SCOPE_REF:
8768       return potential_constant_expression_1 (TREE_OPERAND (t, 1),
8769                                               want_rval, flags);
8770
8771     case TARGET_EXPR:
8772       if (!literal_type_p (TREE_TYPE (t)))
8773         {
8774           if (flags & tf_error)
8775             {
8776               error ("temporary of non-literal type %qT in a "
8777                      "constant expression", TREE_TYPE (t));
8778               explain_non_literal_class (TREE_TYPE (t));
8779             }
8780           return false;
8781         }
8782     case INIT_EXPR:
8783       return potential_constant_expression_1 (TREE_OPERAND (t, 1),
8784                                               rval, flags);
8785
8786     case CONSTRUCTOR:
8787       {
8788         vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
8789         constructor_elt *ce;
8790         for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
8791           if (!potential_constant_expression_1 (ce->value, want_rval, flags))
8792             return false;
8793         return true;
8794       }
8795
8796     case TREE_LIST:
8797       {
8798         gcc_assert (TREE_PURPOSE (t) == NULL_TREE
8799                     || DECL_P (TREE_PURPOSE (t)));
8800         if (!potential_constant_expression_1 (TREE_VALUE (t), want_rval,
8801                                               flags))
8802           return false;
8803         if (TREE_CHAIN (t) == NULL_TREE)
8804           return true;
8805         return potential_constant_expression_1 (TREE_CHAIN (t), want_rval,
8806                                                 flags);
8807       }
8808
8809     case TRUNC_DIV_EXPR:
8810     case CEIL_DIV_EXPR:
8811     case FLOOR_DIV_EXPR:
8812     case ROUND_DIV_EXPR:
8813     case TRUNC_MOD_EXPR:
8814     case CEIL_MOD_EXPR:
8815     case ROUND_MOD_EXPR:
8816       {
8817         tree denom = TREE_OPERAND (t, 1);
8818         if (!potential_constant_expression_1 (denom, rval, flags))
8819           return false;
8820         /* We can't call cxx_eval_outermost_constant_expr on an expression
8821            that hasn't been through fold_non_dependent_expr yet.  */
8822         if (!processing_template_decl)
8823           denom = cxx_eval_outermost_constant_expr (denom, true);
8824         if (integer_zerop (denom))
8825           {
8826             if (flags & tf_error)
8827               error ("division by zero is not a constant-expression");
8828             return false;
8829           }
8830         else
8831           {
8832             want_rval = true;
8833             return potential_constant_expression_1 (TREE_OPERAND (t, 0),
8834                                                     want_rval, flags);
8835           }
8836       }
8837
8838     case COMPOUND_EXPR:
8839       {
8840         /* check_return_expr sometimes wraps a TARGET_EXPR in a
8841            COMPOUND_EXPR; don't get confused.  Also handle EMPTY_CLASS_EXPR
8842            introduced by build_call_a.  */
8843         tree op0 = TREE_OPERAND (t, 0);
8844         tree op1 = TREE_OPERAND (t, 1);
8845         STRIP_NOPS (op1);
8846         if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
8847             || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
8848           return potential_constant_expression_1 (op0, want_rval, flags);
8849         else
8850           goto binary;
8851       }
8852
8853       /* If the first operand is the non-short-circuit constant, look at
8854          the second operand; otherwise we only care about the first one for
8855          potentiality.  */
8856     case TRUTH_AND_EXPR:
8857     case TRUTH_ANDIF_EXPR:
8858       tmp = boolean_true_node;
8859       goto truth;
8860     case TRUTH_OR_EXPR:
8861     case TRUTH_ORIF_EXPR:
8862       tmp = boolean_false_node;
8863     truth:
8864       {
8865         tree op = TREE_OPERAND (t, 0);
8866         if (!potential_constant_expression_1 (op, rval, flags))
8867           return false;
8868         if (!processing_template_decl)
8869           op = cxx_eval_outermost_constant_expr (op, true);
8870         if (tree_int_cst_equal (op, tmp))
8871           return potential_constant_expression_1 (TREE_OPERAND (t, 1), rval, flags);
8872         else
8873           return true;
8874       }
8875
8876     case PLUS_EXPR:
8877     case MULT_EXPR:
8878     case POINTER_PLUS_EXPR:
8879     case RDIV_EXPR:
8880     case EXACT_DIV_EXPR:
8881     case MIN_EXPR:
8882     case MAX_EXPR:
8883     case LSHIFT_EXPR:
8884     case RSHIFT_EXPR:
8885     case LROTATE_EXPR:
8886     case RROTATE_EXPR:
8887     case BIT_IOR_EXPR:
8888     case BIT_XOR_EXPR:
8889     case BIT_AND_EXPR:
8890     case TRUTH_XOR_EXPR:
8891     case UNORDERED_EXPR:
8892     case ORDERED_EXPR:
8893     case UNLT_EXPR:
8894     case UNLE_EXPR:
8895     case UNGT_EXPR:
8896     case UNGE_EXPR:
8897     case UNEQ_EXPR:
8898     case LTGT_EXPR:
8899     case RANGE_EXPR:
8900     case COMPLEX_EXPR:
8901       want_rval = true;
8902       /* Fall through.  */
8903     case ARRAY_REF:
8904     case ARRAY_NOTATION_REF:
8905     case ARRAY_RANGE_REF:
8906     case MEMBER_REF:
8907     case DOTSTAR_EXPR:
8908     binary:
8909       for (i = 0; i < 2; ++i)
8910         if (!potential_constant_expression_1 (TREE_OPERAND (t, i),
8911                                               want_rval, flags))
8912           return false;
8913       return true;
8914
8915     case FMA_EXPR:
8916     case VEC_PERM_EXPR:
8917      for (i = 0; i < 3; ++i)
8918       if (!potential_constant_expression_1 (TREE_OPERAND (t, i),
8919                                             true, flags))
8920         return false;
8921      return true;
8922
8923     case COND_EXPR:
8924     case VEC_COND_EXPR:
8925       /* If the condition is a known constant, we know which of the legs we
8926          care about; otherwise we only require that the condition and
8927          either of the legs be potentially constant.  */
8928       tmp = TREE_OPERAND (t, 0);
8929       if (!potential_constant_expression_1 (tmp, rval, flags))
8930         return false;
8931       if (!processing_template_decl)
8932         tmp = cxx_eval_outermost_constant_expr (tmp, true);
8933       if (integer_zerop (tmp))
8934         return potential_constant_expression_1 (TREE_OPERAND (t, 2),
8935                                                 want_rval, flags);
8936       else if (TREE_CODE (tmp) == INTEGER_CST)
8937         return potential_constant_expression_1 (TREE_OPERAND (t, 1),
8938                                                 want_rval, flags);
8939       for (i = 1; i < 3; ++i)
8940         if (potential_constant_expression_1 (TREE_OPERAND (t, i),
8941                                              want_rval, tf_none))
8942           return true;
8943       if (flags & tf_error)
8944         error ("expression %qE is not a constant-expression", t);
8945       return false;
8946
8947     case VEC_INIT_EXPR:
8948       if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
8949         return true;
8950       if (flags & tf_error)
8951         {
8952           error ("non-constant array initialization");
8953           diagnose_non_constexpr_vec_init (t);
8954         }
8955       return false;
8956
8957     default:
8958       if (objc_is_property_ref (t))
8959         return false;
8960
8961       sorry ("unexpected AST of kind %s", tree_code_name[TREE_CODE (t)]);
8962       gcc_unreachable();
8963       return false;
8964     }
8965 }
8966
8967 /* The main entry point to the above.  */
8968
8969 bool
8970 potential_constant_expression (tree t)
8971 {
8972   return potential_constant_expression_1 (t, false, tf_none);
8973 }
8974
8975 /* As above, but require a constant rvalue.  */
8976
8977 bool
8978 potential_rvalue_constant_expression (tree t)
8979 {
8980   return potential_constant_expression_1 (t, true, tf_none);
8981 }
8982
8983 /* Like above, but complain about non-constant expressions.  */
8984
8985 bool
8986 require_potential_constant_expression (tree t)
8987 {
8988   return potential_constant_expression_1 (t, false, tf_warning_or_error);
8989 }
8990
8991 /* Cross product of the above.  */
8992
8993 bool
8994 require_potential_rvalue_constant_expression (tree t)
8995 {
8996   return potential_constant_expression_1 (t, true, tf_warning_or_error);
8997 }
8998 \f
8999 /* Constructor for a lambda expression.  */
9000
9001 tree
9002 build_lambda_expr (void)
9003 {
9004   tree lambda = make_node (LAMBDA_EXPR);
9005   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda) = CPLD_NONE;
9006   LAMBDA_EXPR_CAPTURE_LIST         (lambda) = NULL_TREE;
9007   LAMBDA_EXPR_THIS_CAPTURE         (lambda) = NULL_TREE;
9008   LAMBDA_EXPR_PENDING_PROXIES      (lambda) = NULL;
9009   LAMBDA_EXPR_RETURN_TYPE          (lambda) = NULL_TREE;
9010   LAMBDA_EXPR_MUTABLE_P            (lambda) = false;
9011   return lambda;
9012 }
9013
9014 /* Create the closure object for a LAMBDA_EXPR.  */
9015
9016 tree
9017 build_lambda_object (tree lambda_expr)
9018 {
9019   /* Build aggregate constructor call.
9020      - cp_parser_braced_list
9021      - cp_parser_functional_cast  */
9022   vec<constructor_elt, va_gc> *elts = NULL;
9023   tree node, expr, type;
9024   location_t saved_loc;
9025
9026   if (processing_template_decl)
9027     return lambda_expr;
9028
9029   /* Make sure any error messages refer to the lambda-introducer.  */
9030   saved_loc = input_location;
9031   input_location = LAMBDA_EXPR_LOCATION (lambda_expr);
9032
9033   for (node = LAMBDA_EXPR_CAPTURE_LIST (lambda_expr);
9034        node;
9035        node = TREE_CHAIN (node))
9036     {
9037       tree field = TREE_PURPOSE (node);
9038       tree val = TREE_VALUE (node);
9039
9040       if (field == error_mark_node)
9041         {
9042           expr = error_mark_node;
9043           goto out;
9044         }
9045
9046       if (DECL_P (val))
9047         mark_used (val);
9048
9049       /* Mere mortals can't copy arrays with aggregate initialization, so
9050          do some magic to make it work here.  */
9051       if (TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE)
9052         val = build_array_copy (val);
9053       else if (DECL_NORMAL_CAPTURE_P (field)
9054                && !DECL_VLA_CAPTURE_P (field)
9055                && TREE_CODE (TREE_TYPE (field)) != REFERENCE_TYPE)
9056         {
9057           /* "the entities that are captured by copy are used to
9058              direct-initialize each corresponding non-static data
9059              member of the resulting closure object."
9060
9061              There's normally no way to express direct-initialization
9062              from an element of a CONSTRUCTOR, so we build up a special
9063              TARGET_EXPR to bypass the usual copy-initialization.  */
9064           val = force_rvalue (val, tf_warning_or_error);
9065           if (TREE_CODE (val) == TARGET_EXPR)
9066             TARGET_EXPR_DIRECT_INIT_P (val) = true;
9067         }
9068
9069       CONSTRUCTOR_APPEND_ELT (elts, DECL_NAME (field), val);
9070     }
9071
9072   expr = build_constructor (init_list_type_node, elts);
9073   CONSTRUCTOR_IS_DIRECT_INIT (expr) = 1;
9074
9075   /* N2927: "[The closure] class type is not an aggregate."
9076      But we briefly treat it as an aggregate to make this simpler.  */
9077   type = LAMBDA_EXPR_CLOSURE (lambda_expr);
9078   CLASSTYPE_NON_AGGREGATE (type) = 0;
9079   expr = finish_compound_literal (type, expr, tf_warning_or_error);
9080   CLASSTYPE_NON_AGGREGATE (type) = 1;
9081
9082  out:
9083   input_location = saved_loc;
9084   return expr;
9085 }
9086
9087 /* Return an initialized RECORD_TYPE for LAMBDA.
9088    LAMBDA must have its explicit captures already.  */
9089
9090 tree
9091 begin_lambda_type (tree lambda)
9092 {
9093   tree type;
9094
9095   {
9096     /* Unique name.  This is just like an unnamed class, but we cannot use
9097        make_anon_name because of certain checks against TYPE_ANONYMOUS_P.  */
9098     tree name;
9099     name = make_lambda_name ();
9100
9101     /* Create the new RECORD_TYPE for this lambda.  */
9102     type = xref_tag (/*tag_code=*/record_type,
9103                      name,
9104                      /*scope=*/ts_lambda,
9105                      /*template_header_p=*/false);
9106   }
9107
9108   /* Designate it as a struct so that we can use aggregate initialization.  */
9109   CLASSTYPE_DECLARED_CLASS (type) = false;
9110
9111   /* Cross-reference the expression and the type.  */
9112   LAMBDA_EXPR_CLOSURE (lambda) = type;
9113   CLASSTYPE_LAMBDA_EXPR (type) = lambda;
9114
9115   /* Clear base types.  */
9116   xref_basetypes (type, /*bases=*/NULL_TREE);
9117
9118   /* Start the class.  */
9119   type = begin_class_definition (type);
9120   if (type == error_mark_node)
9121     return error_mark_node;
9122
9123   return type;
9124 }
9125
9126 /* Returns the type to use for the return type of the operator() of a
9127    closure class.  */
9128
9129 tree
9130 lambda_return_type (tree expr)
9131 {
9132   if (expr == NULL_TREE)
9133     return void_type_node;
9134   if (type_unknown_p (expr)
9135       || BRACE_ENCLOSED_INITIALIZER_P (expr))
9136     {
9137       cxx_incomplete_type_error (expr, TREE_TYPE (expr));
9138       return void_type_node;
9139     }
9140   gcc_checking_assert (!type_dependent_expression_p (expr));
9141   return cv_unqualified (type_decays_to (unlowered_expr_type (expr)));
9142 }
9143
9144 /* Given a LAMBDA_EXPR or closure type LAMBDA, return the op() of the
9145    closure type.  */
9146
9147 tree
9148 lambda_function (tree lambda)
9149 {
9150   tree type;
9151   if (TREE_CODE (lambda) == LAMBDA_EXPR)
9152     type = LAMBDA_EXPR_CLOSURE (lambda);
9153   else
9154     type = lambda;
9155   gcc_assert (LAMBDA_TYPE_P (type));
9156   /* Don't let debug_tree cause instantiation.  */
9157   if (CLASSTYPE_TEMPLATE_INSTANTIATION (type)
9158       && !COMPLETE_OR_OPEN_TYPE_P (type))
9159     return NULL_TREE;
9160   lambda = lookup_member (type, ansi_opname (CALL_EXPR),
9161                           /*protect=*/0, /*want_type=*/false,
9162                           tf_warning_or_error);
9163   if (lambda)
9164     lambda = BASELINK_FUNCTIONS (lambda);
9165   return lambda;
9166 }
9167
9168 /* Returns the type to use for the FIELD_DECL corresponding to the
9169    capture of EXPR.
9170    The caller should add REFERENCE_TYPE for capture by reference.  */
9171
9172 tree
9173 lambda_capture_field_type (tree expr, bool explicit_init_p)
9174 {
9175   tree type;
9176   if (explicit_init_p)
9177     {
9178       type = make_auto ();
9179       type = do_auto_deduction (type, expr, type);
9180     }
9181   else
9182     type = non_reference (unlowered_expr_type (expr));
9183   if (!type || WILDCARD_TYPE_P (type))
9184     {
9185       type = cxx_make_type (DECLTYPE_TYPE);
9186       DECLTYPE_TYPE_EXPR (type) = expr;
9187       DECLTYPE_FOR_LAMBDA_CAPTURE (type) = true;
9188       DECLTYPE_FOR_INIT_CAPTURE (type) = explicit_init_p;
9189       SET_TYPE_STRUCTURAL_EQUALITY (type);
9190     }
9191   return type;
9192 }
9193
9194 /* Insert the deduced return type for an auto function.  */
9195
9196 void
9197 apply_deduced_return_type (tree fco, tree return_type)
9198 {
9199   tree result;
9200
9201   if (return_type == error_mark_node)
9202     return;
9203
9204   if (LAMBDA_FUNCTION_P (fco))
9205     {
9206       tree lambda = CLASSTYPE_LAMBDA_EXPR (current_class_type);
9207       LAMBDA_EXPR_RETURN_TYPE (lambda) = return_type;
9208     }
9209
9210   if (DECL_CONV_FN_P (fco))
9211     DECL_NAME (fco) = mangle_conv_op_name_for_type (return_type);
9212
9213   TREE_TYPE (fco) = change_return_type (return_type, TREE_TYPE (fco));
9214
9215   result = DECL_RESULT (fco);
9216   if (result == NULL_TREE)
9217     return;
9218   if (TREE_TYPE (result) == return_type)
9219     return;
9220
9221   /* We already have a DECL_RESULT from start_preparsed_function.
9222      Now we need to redo the work it and allocate_struct_function
9223      did to reflect the new type.  */
9224   gcc_assert (current_function_decl == fco);
9225   result = build_decl (input_location, RESULT_DECL, NULL_TREE,
9226                        TYPE_MAIN_VARIANT (return_type));
9227   DECL_ARTIFICIAL (result) = 1;
9228   DECL_IGNORED_P (result) = 1;
9229   cp_apply_type_quals_to_decl (cp_type_quals (return_type),
9230                                result);
9231
9232   DECL_RESULT (fco) = result;
9233
9234   if (!processing_template_decl)
9235     {
9236       bool aggr = aggregate_value_p (result, fco);
9237 #ifdef PCC_STATIC_STRUCT_RETURN
9238       cfun->returns_pcc_struct = aggr;
9239 #endif
9240       cfun->returns_struct = aggr;
9241     }
9242
9243 }
9244
9245 /* DECL is a local variable or parameter from the surrounding scope of a
9246    lambda-expression.  Returns the decltype for a use of the capture field
9247    for DECL even if it hasn't been captured yet.  */
9248
9249 static tree
9250 capture_decltype (tree decl)
9251 {
9252   tree lam = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (current_function_decl));
9253   /* FIXME do lookup instead of list walk? */
9254   tree cap = value_member (decl, LAMBDA_EXPR_CAPTURE_LIST (lam));
9255   tree type;
9256
9257   if (cap)
9258     type = TREE_TYPE (TREE_PURPOSE (cap));
9259   else
9260     switch (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lam))
9261       {
9262       case CPLD_NONE:
9263         error ("%qD is not captured", decl);
9264         return error_mark_node;
9265
9266       case CPLD_COPY:
9267         type = TREE_TYPE (decl);
9268         if (TREE_CODE (type) == REFERENCE_TYPE
9269             && TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE)
9270           type = TREE_TYPE (type);
9271         break;
9272
9273       case CPLD_REFERENCE:
9274         type = TREE_TYPE (decl);
9275         if (TREE_CODE (type) != REFERENCE_TYPE)
9276           type = build_reference_type (TREE_TYPE (decl));
9277         break;
9278
9279       default:
9280         gcc_unreachable ();
9281       }
9282
9283   if (TREE_CODE (type) != REFERENCE_TYPE)
9284     {
9285       if (!LAMBDA_EXPR_MUTABLE_P (lam))
9286         type = cp_build_qualified_type (type, (cp_type_quals (type)
9287                                                |TYPE_QUAL_CONST));
9288       type = build_reference_type (type);
9289     }
9290   return type;
9291 }
9292
9293 /* Returns true iff DECL is a lambda capture proxy variable created by
9294    build_capture_proxy.  */
9295
9296 bool
9297 is_capture_proxy (tree decl)
9298 {
9299   return (VAR_P (decl)
9300           && DECL_HAS_VALUE_EXPR_P (decl)
9301           && !DECL_ANON_UNION_VAR_P (decl)
9302           && LAMBDA_FUNCTION_P (DECL_CONTEXT (decl)));
9303 }
9304
9305 /* Returns true iff DECL is a capture proxy for a normal capture
9306    (i.e. without explicit initializer).  */
9307
9308 bool
9309 is_normal_capture_proxy (tree decl)
9310 {
9311   if (!is_capture_proxy (decl))
9312     /* It's not a capture proxy.  */
9313     return false;
9314
9315   /* It is a capture proxy, is it a normal capture?  */
9316   tree val = DECL_VALUE_EXPR (decl);
9317   if (val == error_mark_node)
9318     return true;
9319
9320   gcc_assert (TREE_CODE (val) == COMPONENT_REF);
9321   val = TREE_OPERAND (val, 1);
9322   return DECL_NORMAL_CAPTURE_P (val);
9323 }
9324
9325 /* VAR is a capture proxy created by build_capture_proxy; add it to the
9326    current function, which is the operator() for the appropriate lambda.  */
9327
9328 void
9329 insert_capture_proxy (tree var)
9330 {
9331   cp_binding_level *b;
9332   tree stmt_list;
9333
9334   /* Put the capture proxy in the extra body block so that it won't clash
9335      with a later local variable.  */
9336   b = current_binding_level;
9337   for (;;)
9338     {
9339       cp_binding_level *n = b->level_chain;
9340       if (n->kind == sk_function_parms)
9341         break;
9342       b = n;
9343     }
9344   pushdecl_with_scope (var, b, false);
9345
9346   /* And put a DECL_EXPR in the STATEMENT_LIST for the same block.  */
9347   var = build_stmt (DECL_SOURCE_LOCATION (var), DECL_EXPR, var);
9348   stmt_list = (*stmt_list_stack)[1];
9349   gcc_assert (stmt_list);
9350   append_to_statement_list_force (var, &stmt_list);
9351 }
9352
9353 /* We've just finished processing a lambda; if the containing scope is also
9354    a lambda, insert any capture proxies that were created while processing
9355    the nested lambda.  */
9356
9357 void
9358 insert_pending_capture_proxies (void)
9359 {
9360   tree lam;
9361   vec<tree, va_gc> *proxies;
9362   unsigned i;
9363
9364   if (!current_function_decl || !LAMBDA_FUNCTION_P (current_function_decl))
9365     return;
9366
9367   lam = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (current_function_decl));
9368   proxies = LAMBDA_EXPR_PENDING_PROXIES (lam);
9369   for (i = 0; i < vec_safe_length (proxies); ++i)
9370     {
9371       tree var = (*proxies)[i];
9372       insert_capture_proxy (var);
9373     }
9374   release_tree_vector (LAMBDA_EXPR_PENDING_PROXIES (lam));
9375   LAMBDA_EXPR_PENDING_PROXIES (lam) = NULL;
9376 }
9377
9378 /* Given REF, a COMPONENT_REF designating a field in the lambda closure,
9379    return the type we want the proxy to have: the type of the field itself,
9380    with added const-qualification if the lambda isn't mutable and the
9381    capture is by value.  */
9382
9383 tree
9384 lambda_proxy_type (tree ref)
9385 {
9386   tree type;
9387   if (REFERENCE_REF_P (ref))
9388     ref = TREE_OPERAND (ref, 0);
9389   type = TREE_TYPE (ref);
9390   if (type && !WILDCARD_TYPE_P (non_reference (type)))
9391     return type;
9392   type = cxx_make_type (DECLTYPE_TYPE);
9393   DECLTYPE_TYPE_EXPR (type) = ref;
9394   DECLTYPE_FOR_LAMBDA_PROXY (type) = true;
9395   SET_TYPE_STRUCTURAL_EQUALITY (type);
9396   return type;
9397 }
9398
9399 /* MEMBER is a capture field in a lambda closure class.  Now that we're
9400    inside the operator(), build a placeholder var for future lookups and
9401    debugging.  */
9402
9403 tree
9404 build_capture_proxy (tree member)
9405 {
9406   tree var, object, fn, closure, name, lam, type;
9407
9408   closure = DECL_CONTEXT (member);
9409   fn = lambda_function (closure);
9410   lam = CLASSTYPE_LAMBDA_EXPR (closure);
9411
9412   /* The proxy variable forwards to the capture field.  */
9413   object = build_fold_indirect_ref (DECL_ARGUMENTS (fn));
9414   object = finish_non_static_data_member (member, object, NULL_TREE);
9415   if (REFERENCE_REF_P (object))
9416     object = TREE_OPERAND (object, 0);
9417
9418   /* Remove the __ inserted by add_capture.  */
9419   if (DECL_NORMAL_CAPTURE_P (member))
9420     name = get_identifier (IDENTIFIER_POINTER (DECL_NAME (member)) + 2);
9421   else
9422     name = DECL_NAME (member);
9423
9424   type = lambda_proxy_type (object);
9425
9426   if (DECL_VLA_CAPTURE_P (member))
9427     {
9428       /* Rebuild the VLA type from the pointer and maxindex.  */
9429       tree field = next_initializable_field (TYPE_FIELDS (type));
9430       tree ptr = build_simple_component_ref (object, field);
9431       field = next_initializable_field (DECL_CHAIN (field));
9432       tree max = build_simple_component_ref (object, field);
9433       type = build_array_type (TREE_TYPE (TREE_TYPE (ptr)),
9434                                build_index_type (max));
9435       type = build_reference_type (type);
9436       REFERENCE_VLA_OK (type) = true;
9437       object = convert (type, ptr);
9438     }
9439
9440   var = build_decl (input_location, VAR_DECL, name, type);
9441   SET_DECL_VALUE_EXPR (var, object);
9442   DECL_HAS_VALUE_EXPR_P (var) = 1;
9443   DECL_ARTIFICIAL (var) = 1;
9444   TREE_USED (var) = 1;
9445   DECL_CONTEXT (var) = fn;
9446
9447   if (name == this_identifier)
9448     {
9449       gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (lam) == member);
9450       LAMBDA_EXPR_THIS_CAPTURE (lam) = var;
9451     }
9452
9453   if (fn == current_function_decl)
9454     insert_capture_proxy (var);
9455   else
9456     vec_safe_push (LAMBDA_EXPR_PENDING_PROXIES (lam), var);
9457
9458   return var;
9459 }
9460
9461 /* Return a struct containing a pointer and a length for lambda capture of
9462    an array of runtime length.  */
9463
9464 static tree
9465 vla_capture_type (tree array_type)
9466 {
9467   static tree ptr_id, max_id;
9468   tree type = xref_tag (record_type, make_anon_name (), ts_current, false);
9469   xref_basetypes (type, NULL_TREE);
9470   type = begin_class_definition (type);
9471   if (!ptr_id)
9472     {
9473       ptr_id = get_identifier ("ptr");
9474       max_id = get_identifier ("max");
9475     }
9476   tree ptrtype = build_pointer_type (TREE_TYPE (array_type));
9477   tree field = build_decl (input_location, FIELD_DECL, ptr_id, ptrtype);
9478   finish_member_declaration (field);
9479   field = build_decl (input_location, FIELD_DECL, max_id, sizetype);
9480   finish_member_declaration (field);
9481   return finish_struct (type, NULL_TREE);
9482 }
9483
9484 /* From an ID and INITIALIZER, create a capture (by reference if
9485    BY_REFERENCE_P is true), add it to the capture-list for LAMBDA,
9486    and return it.  */
9487
9488 tree
9489 add_capture (tree lambda, tree id, tree initializer, bool by_reference_p,
9490              bool explicit_init_p)
9491 {
9492   char *buf;
9493   tree type, member, name;
9494   bool vla = false;
9495
9496   if (TREE_CODE (initializer) == TREE_LIST)
9497     initializer = build_x_compound_expr_from_list (initializer, ELK_INIT,
9498                                                    tf_warning_or_error);
9499   type = lambda_capture_field_type (initializer, explicit_init_p);
9500   if (array_of_runtime_bound_p (type))
9501     {
9502       vla = true;
9503       if (!by_reference_p)
9504         error ("array of runtime bound cannot be captured by copy, "
9505                "only by reference");
9506
9507       /* For a VLA, we capture the address of the first element and the
9508          maximum index, and then reconstruct the VLA for the proxy.  */
9509       tree elt = cp_build_array_ref (input_location, initializer,
9510                                      integer_zero_node, tf_warning_or_error);
9511       initializer = build_constructor_va (init_list_type_node, 2,
9512                                           NULL_TREE, build_address (elt),
9513                                           NULL_TREE, array_type_nelts (type));
9514       type = vla_capture_type (type);
9515     }
9516   else if (variably_modified_type_p (type, NULL_TREE))
9517     {
9518       error ("capture of variable-size type %qT that is not a C++1y array "
9519              "of runtime bound", type);
9520       if (TREE_CODE (type) == ARRAY_TYPE
9521           && variably_modified_type_p (TREE_TYPE (type), NULL_TREE))
9522         inform (input_location, "because the array element type %qT has "
9523                 "variable size", TREE_TYPE (type));
9524     }
9525   else if (by_reference_p)
9526     {
9527       type = build_reference_type (type);
9528       if (!real_lvalue_p (initializer))
9529         error ("cannot capture %qE by reference", initializer);
9530     }
9531   else
9532     /* Capture by copy requires a complete type.  */
9533     type = complete_type (type);
9534
9535   /* Add __ to the beginning of the field name so that user code
9536      won't find the field with name lookup.  We can't just leave the name
9537      unset because template instantiation uses the name to find
9538      instantiated fields.  */
9539   if (!explicit_init_p)
9540     {
9541       buf = (char *) alloca (IDENTIFIER_LENGTH (id) + 3);
9542       buf[1] = buf[0] = '_';
9543       memcpy (buf + 2, IDENTIFIER_POINTER (id),
9544               IDENTIFIER_LENGTH (id) + 1);
9545       name = get_identifier (buf);
9546     }
9547   else
9548     /* But captures with explicit initializers are named.  */
9549     name = id;
9550
9551   /* If TREE_TYPE isn't set, we're still in the introducer, so check
9552      for duplicates.  */
9553   if (!LAMBDA_EXPR_CLOSURE (lambda))
9554     {
9555       if (IDENTIFIER_MARKED (name))
9556         {
9557           pedwarn (input_location, 0,
9558                    "already captured %qD in lambda expression", id);
9559           return NULL_TREE;
9560         }
9561       IDENTIFIER_MARKED (name) = true;
9562     }
9563
9564   /* Make member variable.  */
9565   member = build_lang_decl (FIELD_DECL, name, type);
9566   DECL_VLA_CAPTURE_P (member) = vla;
9567
9568   if (!explicit_init_p)
9569     /* Normal captures are invisible to name lookup but uses are replaced
9570        with references to the capture field; we implement this by only
9571        really making them invisible in unevaluated context; see
9572        qualify_lookup.  For now, let's make explicitly initialized captures
9573        always visible.  */
9574     DECL_NORMAL_CAPTURE_P (member) = true;
9575
9576   if (id == this_identifier)
9577     LAMBDA_EXPR_THIS_CAPTURE (lambda) = member;
9578
9579   /* Add it to the appropriate closure class if we've started it.  */
9580   if (current_class_type
9581       && current_class_type == LAMBDA_EXPR_CLOSURE (lambda))
9582     finish_member_declaration (member);
9583
9584   LAMBDA_EXPR_CAPTURE_LIST (lambda)
9585     = tree_cons (member, initializer, LAMBDA_EXPR_CAPTURE_LIST (lambda));
9586
9587   if (LAMBDA_EXPR_CLOSURE (lambda))
9588     return build_capture_proxy (member);
9589   /* For explicit captures we haven't started the function yet, so we wait
9590      and build the proxy from cp_parser_lambda_body.  */
9591   return NULL_TREE;
9592 }
9593
9594 /* Register all the capture members on the list CAPTURES, which is the
9595    LAMBDA_EXPR_CAPTURE_LIST for the lambda after the introducer.  */
9596
9597 void
9598 register_capture_members (tree captures)
9599 {
9600   if (captures == NULL_TREE)
9601     return;
9602
9603   register_capture_members (TREE_CHAIN (captures));
9604   /* We set this in add_capture to avoid duplicates.  */
9605   IDENTIFIER_MARKED (DECL_NAME (TREE_PURPOSE (captures))) = false;
9606   finish_member_declaration (TREE_PURPOSE (captures));
9607 }
9608
9609 /* Similar to add_capture, except this works on a stack of nested lambdas.
9610    BY_REFERENCE_P in this case is derived from the default capture mode.
9611    Returns the capture for the lambda at the bottom of the stack.  */
9612
9613 tree
9614 add_default_capture (tree lambda_stack, tree id, tree initializer)
9615 {
9616   bool this_capture_p = (id == this_identifier);
9617
9618   tree var = NULL_TREE;
9619
9620   tree saved_class_type = current_class_type;
9621
9622   tree node;
9623
9624   for (node = lambda_stack;
9625        node;
9626        node = TREE_CHAIN (node))
9627     {
9628       tree lambda = TREE_VALUE (node);
9629
9630       current_class_type = LAMBDA_EXPR_CLOSURE (lambda);
9631       var = add_capture (lambda,
9632                             id,
9633                             initializer,
9634                             /*by_reference_p=*/
9635                             (!this_capture_p
9636                              && (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda)
9637                                  == CPLD_REFERENCE)),
9638                             /*explicit_init_p=*/false);
9639       initializer = convert_from_reference (var);
9640     }
9641
9642   current_class_type = saved_class_type;
9643
9644   return var;
9645 }
9646
9647 /* Return the capture pertaining to a use of 'this' in LAMBDA, in the form of an
9648    INDIRECT_REF, possibly adding it through default capturing.  */
9649
9650 tree
9651 lambda_expr_this_capture (tree lambda)
9652 {
9653   tree result;
9654
9655   tree this_capture = LAMBDA_EXPR_THIS_CAPTURE (lambda);
9656
9657   /* In unevaluated context this isn't an odr-use, so just return the
9658      nearest 'this'.  */
9659   if (cp_unevaluated_operand)
9660     return lookup_name (this_identifier);
9661
9662   /* Try to default capture 'this' if we can.  */
9663   if (!this_capture
9664       && LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda) != CPLD_NONE)
9665     {
9666       tree lambda_stack = NULL_TREE;
9667       tree init = NULL_TREE;
9668
9669       /* If we are in a lambda function, we can move out until we hit:
9670            1. a non-lambda function or NSDMI,
9671            2. a lambda function capturing 'this', or
9672            3. a non-default capturing lambda function.  */
9673       for (tree tlambda = lambda; ;)
9674         {
9675           lambda_stack = tree_cons (NULL_TREE,
9676                                     tlambda,
9677                                     lambda_stack);
9678
9679           if (LAMBDA_EXPR_EXTRA_SCOPE (tlambda)
9680               && TREE_CODE (LAMBDA_EXPR_EXTRA_SCOPE (tlambda)) == FIELD_DECL)
9681             {
9682               /* In an NSDMI, we don't have a function to look up the decl in,
9683                  but the fake 'this' pointer that we're using for parsing is
9684                  in scope_chain.  */
9685               init = scope_chain->x_current_class_ptr;
9686               gcc_checking_assert
9687                 (init && (TREE_TYPE (TREE_TYPE (init))
9688                           == current_nonlambda_class_type ()));
9689               break;
9690             }
9691
9692           tree closure_decl = TYPE_NAME (LAMBDA_EXPR_CLOSURE (tlambda));
9693           tree containing_function = decl_function_context (closure_decl);
9694
9695           if (containing_function == NULL_TREE)
9696             /* We ran out of scopes; there's no 'this' to capture.  */
9697             break;
9698
9699           if (!LAMBDA_FUNCTION_P (containing_function))
9700             {
9701               /* We found a non-lambda function.  */
9702               if (DECL_NONSTATIC_MEMBER_FUNCTION_P (containing_function))
9703                 /* First parameter is 'this'.  */
9704                 init = DECL_ARGUMENTS (containing_function);
9705               break;
9706             }
9707
9708           tlambda
9709             = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (containing_function));
9710
9711           if (LAMBDA_EXPR_THIS_CAPTURE (tlambda))
9712             {
9713               /* An outer lambda has already captured 'this'.  */
9714               init = LAMBDA_EXPR_THIS_CAPTURE (tlambda);
9715               break;
9716             }
9717
9718           if (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (tlambda) == CPLD_NONE)
9719             /* An outer lambda won't let us capture 'this'.  */
9720             break;
9721         }
9722
9723       if (init)
9724         this_capture = add_default_capture (lambda_stack,
9725                                             /*id=*/this_identifier,
9726                                             init);
9727     }
9728
9729   if (!this_capture)
9730     {
9731       error ("%<this%> was not captured for this lambda function");
9732       result = error_mark_node;
9733     }
9734   else
9735     {
9736       /* To make sure that current_class_ref is for the lambda.  */
9737       gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (current_class_ref))
9738                   == LAMBDA_EXPR_CLOSURE (lambda));
9739
9740       result = this_capture;
9741
9742       /* If 'this' is captured, each use of 'this' is transformed into an
9743          access to the corresponding unnamed data member of the closure
9744          type cast (_expr.cast_ 5.4) to the type of 'this'. [ The cast
9745          ensures that the transformed expression is an rvalue. ] */
9746       result = rvalue (result);
9747     }
9748
9749   return result;
9750 }
9751
9752 /* We don't want to capture 'this' until we know we need it, i.e. after
9753    overload resolution has chosen a non-static member function.  At that
9754    point we call this function to turn a dummy object into a use of the
9755    'this' capture.  */
9756
9757 tree
9758 maybe_resolve_dummy (tree object)
9759 {
9760   if (!is_dummy_object (object))
9761     return object;
9762
9763   tree type = TYPE_MAIN_VARIANT (TREE_TYPE (object));
9764   gcc_assert (!TYPE_PTR_P (type));
9765
9766   if (type != current_class_type
9767       && current_class_type
9768       && LAMBDA_TYPE_P (current_class_type)
9769       && DERIVED_FROM_P (type, current_nonlambda_class_type ()))
9770     {
9771       /* In a lambda, need to go through 'this' capture.  */
9772       tree lam = CLASSTYPE_LAMBDA_EXPR (current_class_type);
9773       tree cap = lambda_expr_this_capture (lam);
9774       object = build_x_indirect_ref (EXPR_LOCATION (object), cap,
9775                                      RO_NULL, tf_warning_or_error);
9776     }
9777
9778   return object;
9779 }
9780
9781 /* Returns the method basetype of the innermost non-lambda function, or
9782    NULL_TREE if none.  */
9783
9784 tree
9785 nonlambda_method_basetype (void)
9786 {
9787   tree fn, type;
9788   if (!current_class_ref)
9789     return NULL_TREE;
9790
9791   type = current_class_type;
9792   if (!LAMBDA_TYPE_P (type))
9793     return type;
9794
9795   /* Find the nearest enclosing non-lambda function.  */
9796   fn = TYPE_NAME (type);
9797   do
9798     fn = decl_function_context (fn);
9799   while (fn && LAMBDA_FUNCTION_P (fn));
9800
9801   if (!fn || !DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
9802     return NULL_TREE;
9803
9804   return TYPE_METHOD_BASETYPE (TREE_TYPE (fn));
9805 }
9806
9807 /* If the closure TYPE has a static op(), also add a conversion to function
9808    pointer.  */
9809
9810 void
9811 maybe_add_lambda_conv_op (tree type)
9812 {
9813   bool nested = (current_function_decl != NULL_TREE);
9814   tree callop = lambda_function (type);
9815   tree rettype, name, fntype, fn, body, compound_stmt;
9816   tree thistype, stattype, statfn, convfn, call, arg;
9817   vec<tree, va_gc> *argvec;
9818
9819   if (LAMBDA_EXPR_CAPTURE_LIST (CLASSTYPE_LAMBDA_EXPR (type)) != NULL_TREE)
9820     return;
9821
9822   if (processing_template_decl)
9823     return;
9824
9825   if (DECL_INITIAL (callop) == NULL_TREE)
9826     {
9827       /* If the op() wasn't instantiated due to errors, give up.  */
9828       gcc_assert (errorcount || sorrycount);
9829       return;
9830     }
9831
9832   stattype = build_function_type (TREE_TYPE (TREE_TYPE (callop)),
9833                                   FUNCTION_ARG_CHAIN (callop));
9834
9835   /* First build up the conversion op.  */
9836
9837   rettype = build_pointer_type (stattype);
9838   name = mangle_conv_op_name_for_type (rettype);
9839   thistype = cp_build_qualified_type (type, TYPE_QUAL_CONST);
9840   fntype = build_method_type_directly (thistype, rettype, void_list_node);
9841   fn = convfn = build_lang_decl (FUNCTION_DECL, name, fntype);
9842   DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (callop);
9843
9844   if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn
9845       && DECL_ALIGN (fn) < 2 * BITS_PER_UNIT)
9846     DECL_ALIGN (fn) = 2 * BITS_PER_UNIT;
9847
9848   SET_OVERLOADED_OPERATOR_CODE (fn, TYPE_EXPR);
9849   grokclassfn (type, fn, NO_SPECIAL);
9850   set_linkage_according_to_type (type, fn);
9851   rest_of_decl_compilation (fn, toplevel_bindings_p (), at_eof);
9852   DECL_IN_AGGR_P (fn) = 1;
9853   DECL_ARTIFICIAL (fn) = 1;
9854   DECL_NOT_REALLY_EXTERN (fn) = 1;
9855   DECL_DECLARED_INLINE_P (fn) = 1;
9856   DECL_ARGUMENTS (fn) = build_this_parm (fntype, TYPE_QUAL_CONST);
9857   if (nested)
9858     DECL_INTERFACE_KNOWN (fn) = 1;
9859
9860   add_method (type, fn, NULL_TREE);
9861
9862   /* Generic thunk code fails for varargs; we'll complain in mark_used if
9863      the conversion op is used.  */
9864   if (varargs_function_p (callop))
9865     {
9866       DECL_DELETED_FN (fn) = 1;
9867       return;
9868     }
9869
9870   /* Now build up the thunk to be returned.  */
9871
9872   name = get_identifier ("_FUN");
9873   fn = statfn = build_lang_decl (FUNCTION_DECL, name, stattype);
9874   DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (callop);
9875   if (TARGET_PTRMEMFUNC_VBIT_LOCATION == ptrmemfunc_vbit_in_pfn
9876       && DECL_ALIGN (fn) < 2 * BITS_PER_UNIT)
9877     DECL_ALIGN (fn) = 2 * BITS_PER_UNIT;
9878   grokclassfn (type, fn, NO_SPECIAL);
9879   set_linkage_according_to_type (type, fn);
9880   rest_of_decl_compilation (fn, toplevel_bindings_p (), at_eof);
9881   DECL_IN_AGGR_P (fn) = 1;
9882   DECL_ARTIFICIAL (fn) = 1;
9883   DECL_NOT_REALLY_EXTERN (fn) = 1;
9884   DECL_DECLARED_INLINE_P (fn) = 1;
9885   DECL_STATIC_FUNCTION_P (fn) = 1;
9886   DECL_ARGUMENTS (fn) = copy_list (DECL_CHAIN (DECL_ARGUMENTS (callop)));
9887   for (arg = DECL_ARGUMENTS (fn); arg; arg = DECL_CHAIN (arg))
9888     {
9889       /* Avoid duplicate -Wshadow warnings.  */
9890       DECL_NAME (arg) = NULL_TREE;
9891       DECL_CONTEXT (arg) = fn;
9892     }
9893   if (nested)
9894     DECL_INTERFACE_KNOWN (fn) = 1;
9895
9896   add_method (type, fn, NULL_TREE);
9897
9898   if (nested)
9899     push_function_context ();
9900   else
9901     /* Still increment function_depth so that we don't GC in the
9902        middle of an expression.  */
9903     ++function_depth;
9904
9905   /* Generate the body of the thunk.  */
9906
9907   start_preparsed_function (statfn, NULL_TREE,
9908                             SF_PRE_PARSED | SF_INCLASS_INLINE);
9909   if (DECL_ONE_ONLY (statfn))
9910     {
9911       /* Put the thunk in the same comdat group as the call op.  */
9912       symtab_add_to_same_comdat_group
9913          ((symtab_node) cgraph_get_create_node (statfn),
9914           (symtab_node) cgraph_get_create_node (callop));
9915     }
9916   body = begin_function_body ();
9917   compound_stmt = begin_compound_stmt (0);
9918
9919   arg = build1 (NOP_EXPR, TREE_TYPE (DECL_ARGUMENTS (callop)),
9920                 null_pointer_node);
9921   argvec = make_tree_vector ();
9922   argvec->quick_push (arg);
9923   for (arg = DECL_ARGUMENTS (statfn); arg; arg = DECL_CHAIN (arg))
9924     {
9925       mark_exp_read (arg);
9926       vec_safe_push (argvec, arg);
9927     }
9928   call = build_call_a (callop, argvec->length (), argvec->address ());
9929   CALL_FROM_THUNK_P (call) = 1;
9930   if (MAYBE_CLASS_TYPE_P (TREE_TYPE (call)))
9931     call = build_cplus_new (TREE_TYPE (call), call, tf_warning_or_error);
9932   call = convert_from_reference (call);
9933   finish_return_stmt (call);
9934
9935   finish_compound_stmt (compound_stmt);
9936   finish_function_body (body);
9937
9938   expand_or_defer_fn (finish_function (2));
9939
9940   /* Generate the body of the conversion op.  */
9941
9942   start_preparsed_function (convfn, NULL_TREE,
9943                             SF_PRE_PARSED | SF_INCLASS_INLINE);
9944   body = begin_function_body ();
9945   compound_stmt = begin_compound_stmt (0);
9946
9947   /* decl_needed_p needs to see that it's used.  */
9948   TREE_USED (statfn) = 1;
9949   finish_return_stmt (decay_conversion (statfn, tf_warning_or_error));
9950
9951   finish_compound_stmt (compound_stmt);
9952   finish_function_body (body);
9953
9954   expand_or_defer_fn (finish_function (2));
9955
9956   if (nested)
9957     pop_function_context ();
9958   else
9959     --function_depth;
9960 }
9961
9962 /* Returns true iff VAL is a lambda-related declaration which should
9963    be ignored by unqualified lookup.  */
9964
9965 bool
9966 is_lambda_ignored_entity (tree val)
9967 {
9968   /* In unevaluated context, look past normal capture proxies.  */
9969   if (cp_unevaluated_operand && is_normal_capture_proxy (val))
9970     return true;
9971
9972   /* Always ignore lambda fields, their names are only for debugging.  */
9973   if (TREE_CODE (val) == FIELD_DECL
9974       && CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (val)))
9975     return true;
9976
9977   /* None of the lookups that use qualify_lookup want the op() from the
9978      lambda; they want the one from the enclosing class.  */
9979   if (TREE_CODE (val) == FUNCTION_DECL && LAMBDA_FUNCTION_P (val))
9980     return true;
9981
9982   return false;
9983 }
9984
9985 #include "gt-cp-semantics.h"