PR c++/60336
[official-gcc.git] / gcc / cp / lambda.c
blob76a839ce73046caf8b7f7a06f0e51541942fd34c
1 /* Perform the semantic phase of lambda 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.
6 Copyright (C) 1998-2017 Free Software Foundation, Inc.
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it
11 under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
15 GCC is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3. If not see
22 <http://www.gnu.org/licenses/>. */
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "cp-tree.h"
28 #include "stringpool.h"
29 #include "cgraph.h"
30 #include "tree-iterator.h"
31 #include "toplev.h"
32 #include "gimplify.h"
33 #include "cp-cilkplus.h"
35 /* Constructor for a lambda expression. */
37 tree
38 build_lambda_expr (void)
40 tree lambda = make_node (LAMBDA_EXPR);
41 LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda) = CPLD_NONE;
42 LAMBDA_EXPR_CAPTURE_LIST (lambda) = NULL_TREE;
43 LAMBDA_EXPR_THIS_CAPTURE (lambda) = NULL_TREE;
44 LAMBDA_EXPR_PENDING_PROXIES (lambda) = NULL;
45 LAMBDA_EXPR_MUTABLE_P (lambda) = false;
46 return lambda;
49 /* Create the closure object for a LAMBDA_EXPR. */
51 tree
52 build_lambda_object (tree lambda_expr)
54 /* Build aggregate constructor call.
55 - cp_parser_braced_list
56 - cp_parser_functional_cast */
57 vec<constructor_elt, va_gc> *elts = NULL;
58 tree node, expr, type;
59 location_t saved_loc;
61 if (processing_template_decl || lambda_expr == error_mark_node)
62 return lambda_expr;
64 /* Make sure any error messages refer to the lambda-introducer. */
65 saved_loc = input_location;
66 input_location = LAMBDA_EXPR_LOCATION (lambda_expr);
68 for (node = LAMBDA_EXPR_CAPTURE_LIST (lambda_expr);
69 node;
70 node = TREE_CHAIN (node))
72 tree field = TREE_PURPOSE (node);
73 tree val = TREE_VALUE (node);
75 if (field == error_mark_node)
77 expr = error_mark_node;
78 goto out;
81 if (TREE_CODE (val) == TREE_LIST)
82 val = build_x_compound_expr_from_list (val, ELK_INIT,
83 tf_warning_or_error);
85 if (DECL_P (val))
86 mark_used (val);
88 /* Mere mortals can't copy arrays with aggregate initialization, so
89 do some magic to make it work here. */
90 if (TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE)
91 val = build_array_copy (val);
92 else if (DECL_NORMAL_CAPTURE_P (field)
93 && !DECL_VLA_CAPTURE_P (field)
94 && TREE_CODE (TREE_TYPE (field)) != REFERENCE_TYPE)
96 /* "the entities that are captured by copy are used to
97 direct-initialize each corresponding non-static data
98 member of the resulting closure object."
100 There's normally no way to express direct-initialization
101 from an element of a CONSTRUCTOR, so we build up a special
102 TARGET_EXPR to bypass the usual copy-initialization. */
103 val = force_rvalue (val, tf_warning_or_error);
104 if (TREE_CODE (val) == TARGET_EXPR)
105 TARGET_EXPR_DIRECT_INIT_P (val) = true;
108 CONSTRUCTOR_APPEND_ELT (elts, DECL_NAME (field), val);
111 expr = build_constructor (init_list_type_node, elts);
112 CONSTRUCTOR_IS_DIRECT_INIT (expr) = 1;
114 /* N2927: "[The closure] class type is not an aggregate."
115 But we briefly treat it as an aggregate to make this simpler. */
116 type = LAMBDA_EXPR_CLOSURE (lambda_expr);
117 CLASSTYPE_NON_AGGREGATE (type) = 0;
118 expr = finish_compound_literal (type, expr, tf_warning_or_error);
119 CLASSTYPE_NON_AGGREGATE (type) = 1;
121 out:
122 input_location = saved_loc;
123 return expr;
126 /* Return an initialized RECORD_TYPE for LAMBDA.
127 LAMBDA must have its explicit captures already. */
129 tree
130 begin_lambda_type (tree lambda)
132 tree type;
135 /* Unique name. This is just like an unnamed class, but we cannot use
136 make_anon_name because of certain checks against TYPE_UNNAMED_P. */
137 tree name;
138 name = make_lambda_name ();
140 /* Create the new RECORD_TYPE for this lambda. */
141 type = xref_tag (/*tag_code=*/record_type,
142 name,
143 /*scope=*/ts_lambda,
144 /*template_header_p=*/false);
145 if (type == error_mark_node)
146 return error_mark_node;
149 /* Designate it as a struct so that we can use aggregate initialization. */
150 CLASSTYPE_DECLARED_CLASS (type) = false;
152 /* Cross-reference the expression and the type. */
153 LAMBDA_EXPR_CLOSURE (lambda) = type;
154 CLASSTYPE_LAMBDA_EXPR (type) = lambda;
156 /* In C++17, assume the closure is literal; we'll clear the flag later if
157 necessary. */
158 if (cxx_dialect >= cxx17)
159 CLASSTYPE_LITERAL_P (type) = true;
161 /* Clear base types. */
162 xref_basetypes (type, /*bases=*/NULL_TREE);
164 /* Start the class. */
165 type = begin_class_definition (type);
167 return type;
170 /* Returns the type to use for the return type of the operator() of a
171 closure class. */
173 tree
174 lambda_return_type (tree expr)
176 if (expr == NULL_TREE)
177 return void_type_node;
178 if (type_unknown_p (expr)
179 || BRACE_ENCLOSED_INITIALIZER_P (expr))
181 cxx_incomplete_type_error (expr, TREE_TYPE (expr));
182 return error_mark_node;
184 gcc_checking_assert (!type_dependent_expression_p (expr));
185 return cv_unqualified (type_decays_to (unlowered_expr_type (expr)));
188 /* Given a LAMBDA_EXPR or closure type LAMBDA, return the op() of the
189 closure type. */
191 tree
192 lambda_function (tree lambda)
194 tree type;
195 if (TREE_CODE (lambda) == LAMBDA_EXPR)
196 type = LAMBDA_EXPR_CLOSURE (lambda);
197 else
198 type = lambda;
199 gcc_assert (LAMBDA_TYPE_P (type));
200 /* Don't let debug_tree cause instantiation. */
201 if (CLASSTYPE_TEMPLATE_INSTANTIATION (type)
202 && !COMPLETE_OR_OPEN_TYPE_P (type))
203 return NULL_TREE;
204 lambda = lookup_member (type, call_op_identifier,
205 /*protect=*/0, /*want_type=*/false,
206 tf_warning_or_error);
207 if (lambda)
208 lambda = STRIP_TEMPLATE (get_first_fn (lambda));
209 return lambda;
212 /* Returns the type to use for the FIELD_DECL corresponding to the
213 capture of EXPR. EXPLICIT_INIT_P indicates whether this is a
214 C++14 init capture, and BY_REFERENCE_P indicates whether we're
215 capturing by reference. */
217 tree
218 lambda_capture_field_type (tree expr, bool explicit_init_p,
219 bool by_reference_p)
221 tree type;
222 bool is_this = is_this_parameter (tree_strip_nop_conversions (expr));
224 if (!is_this && type_dependent_expression_p (expr))
226 type = cxx_make_type (DECLTYPE_TYPE);
227 DECLTYPE_TYPE_EXPR (type) = expr;
228 DECLTYPE_FOR_LAMBDA_CAPTURE (type) = true;
229 DECLTYPE_FOR_INIT_CAPTURE (type) = explicit_init_p;
230 DECLTYPE_FOR_REF_CAPTURE (type) = by_reference_p;
231 SET_TYPE_STRUCTURAL_EQUALITY (type);
233 else if (!is_this && explicit_init_p)
235 tree auto_node = make_auto ();
237 type = auto_node;
238 if (by_reference_p)
239 /* Add the reference now, so deduction doesn't lose
240 outermost CV qualifiers of EXPR. */
241 type = build_reference_type (type);
242 type = do_auto_deduction (type, expr, auto_node);
244 else
246 type = non_reference (unlowered_expr_type (expr));
248 if (!is_this
249 && (by_reference_p || TREE_CODE (type) == FUNCTION_TYPE))
250 type = build_reference_type (type);
253 return type;
256 /* Returns true iff DECL is a lambda capture proxy variable created by
257 build_capture_proxy. */
259 bool
260 is_capture_proxy (tree decl)
262 return (VAR_P (decl)
263 && DECL_HAS_VALUE_EXPR_P (decl)
264 && !DECL_ANON_UNION_VAR_P (decl)
265 && LAMBDA_FUNCTION_P (DECL_CONTEXT (decl)));
268 /* Returns true iff DECL is a capture proxy for a normal capture
269 (i.e. without explicit initializer). */
271 bool
272 is_normal_capture_proxy (tree decl)
274 if (!is_capture_proxy (decl))
275 /* It's not a capture proxy. */
276 return false;
278 if (variably_modified_type_p (TREE_TYPE (decl), NULL_TREE))
279 /* VLA capture. */
280 return true;
282 /* It is a capture proxy, is it a normal capture? */
283 tree val = DECL_VALUE_EXPR (decl);
284 if (val == error_mark_node)
285 return true;
287 if (TREE_CODE (val) == ADDR_EXPR)
288 val = TREE_OPERAND (val, 0);
289 gcc_assert (TREE_CODE (val) == COMPONENT_REF);
290 val = TREE_OPERAND (val, 1);
291 return DECL_NORMAL_CAPTURE_P (val);
294 /* VAR is a capture proxy created by build_capture_proxy; add it to the
295 current function, which is the operator() for the appropriate lambda. */
297 void
298 insert_capture_proxy (tree var)
300 if (is_normal_capture_proxy (var))
302 tree cap = DECL_CAPTURED_VARIABLE (var);
303 if (CHECKING_P)
305 gcc_assert (!is_normal_capture_proxy (cap));
306 tree old = retrieve_local_specialization (cap);
307 if (old)
308 gcc_assert (DECL_CONTEXT (old) != DECL_CONTEXT (var));
310 register_local_specialization (var, cap);
313 /* Put the capture proxy in the extra body block so that it won't clash
314 with a later local variable. */
315 pushdecl_outermost_localscope (var);
317 /* And put a DECL_EXPR in the STATEMENT_LIST for the same block. */
318 var = build_stmt (DECL_SOURCE_LOCATION (var), DECL_EXPR, var);
319 tree stmt_list = (*stmt_list_stack)[1];
320 gcc_assert (stmt_list);
321 append_to_statement_list_force (var, &stmt_list);
324 /* We've just finished processing a lambda; if the containing scope is also
325 a lambda, insert any capture proxies that were created while processing
326 the nested lambda. */
328 void
329 insert_pending_capture_proxies (void)
331 tree lam;
332 vec<tree, va_gc> *proxies;
333 unsigned i;
335 if (!current_function_decl || !LAMBDA_FUNCTION_P (current_function_decl))
336 return;
338 lam = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (current_function_decl));
339 proxies = LAMBDA_EXPR_PENDING_PROXIES (lam);
340 for (i = 0; i < vec_safe_length (proxies); ++i)
342 tree var = (*proxies)[i];
343 insert_capture_proxy (var);
345 release_tree_vector (LAMBDA_EXPR_PENDING_PROXIES (lam));
346 LAMBDA_EXPR_PENDING_PROXIES (lam) = NULL;
349 /* Given REF, a COMPONENT_REF designating a field in the lambda closure,
350 return the type we want the proxy to have: the type of the field itself,
351 with added const-qualification if the lambda isn't mutable and the
352 capture is by value. */
354 tree
355 lambda_proxy_type (tree ref)
357 tree type;
358 if (ref == error_mark_node)
359 return error_mark_node;
360 if (REFERENCE_REF_P (ref))
361 ref = TREE_OPERAND (ref, 0);
362 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
363 type = TREE_TYPE (ref);
364 if (!type || WILDCARD_TYPE_P (non_reference (type)))
366 type = cxx_make_type (DECLTYPE_TYPE);
367 DECLTYPE_TYPE_EXPR (type) = ref;
368 DECLTYPE_FOR_LAMBDA_PROXY (type) = true;
369 SET_TYPE_STRUCTURAL_EQUALITY (type);
371 if (DECL_PACK_P (TREE_OPERAND (ref, 1)))
372 type = make_pack_expansion (type);
373 return type;
376 /* MEMBER is a capture field in a lambda closure class. Now that we're
377 inside the operator(), build a placeholder var for future lookups and
378 debugging. */
380 tree
381 build_capture_proxy (tree member, tree init)
383 tree var, object, fn, closure, name, lam, type;
385 if (PACK_EXPANSION_P (member))
386 member = PACK_EXPANSION_PATTERN (member);
388 closure = DECL_CONTEXT (member);
389 fn = lambda_function (closure);
390 lam = CLASSTYPE_LAMBDA_EXPR (closure);
392 /* The proxy variable forwards to the capture field. */
393 object = build_fold_indirect_ref (DECL_ARGUMENTS (fn));
394 object = finish_non_static_data_member (member, object, NULL_TREE);
395 if (REFERENCE_REF_P (object))
396 object = TREE_OPERAND (object, 0);
398 /* Remove the __ inserted by add_capture. */
399 name = get_identifier (IDENTIFIER_POINTER (DECL_NAME (member)) + 2);
401 type = lambda_proxy_type (object);
403 if (name == this_identifier && !POINTER_TYPE_P (type))
405 type = build_pointer_type (type);
406 type = cp_build_qualified_type (type, TYPE_QUAL_CONST);
407 object = build_fold_addr_expr_with_type (object, type);
410 if (DECL_VLA_CAPTURE_P (member))
412 /* Rebuild the VLA type from the pointer and maxindex. */
413 tree field = next_initializable_field (TYPE_FIELDS (type));
414 tree ptr = build_simple_component_ref (object, field);
415 field = next_initializable_field (DECL_CHAIN (field));
416 tree max = build_simple_component_ref (object, field);
417 type = build_cplus_array_type (TREE_TYPE (TREE_TYPE (ptr)),
418 build_index_type (max));
419 type = build_reference_type (type);
420 REFERENCE_VLA_OK (type) = true;
421 object = convert (type, ptr);
424 var = build_decl (input_location, VAR_DECL, name, type);
425 SET_DECL_VALUE_EXPR (var, object);
426 DECL_HAS_VALUE_EXPR_P (var) = 1;
427 DECL_ARTIFICIAL (var) = 1;
428 TREE_USED (var) = 1;
429 DECL_CONTEXT (var) = fn;
431 if (DECL_NORMAL_CAPTURE_P (member))
433 if (DECL_VLA_CAPTURE_P (member))
435 init = CONSTRUCTOR_ELT (init, 0)->value;
436 init = TREE_OPERAND (init, 0); // Strip ADDR_EXPR.
437 init = TREE_OPERAND (init, 0); // Strip ARRAY_REF.
439 else
441 if (PACK_EXPANSION_P (init))
442 init = PACK_EXPANSION_PATTERN (init);
443 if (TREE_CODE (init) == INDIRECT_REF)
444 init = TREE_OPERAND (init, 0);
445 STRIP_NOPS (init);
447 gcc_assert (VAR_P (init) || TREE_CODE (init) == PARM_DECL);
448 while (is_normal_capture_proxy (init))
449 init = DECL_CAPTURED_VARIABLE (init);
450 retrofit_lang_decl (var);
451 DECL_CAPTURED_VARIABLE (var) = init;
454 if (name == this_identifier)
456 gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (lam) == member);
457 LAMBDA_EXPR_THIS_CAPTURE (lam) = var;
460 if (fn == current_function_decl)
461 insert_capture_proxy (var);
462 else
463 vec_safe_push (LAMBDA_EXPR_PENDING_PROXIES (lam), var);
465 return var;
468 static GTY(()) tree ptr_id;
469 static GTY(()) tree max_id;
471 /* Return a struct containing a pointer and a length for lambda capture of
472 an array of runtime length. */
474 static tree
475 vla_capture_type (tree array_type)
477 tree type = xref_tag (record_type, make_anon_name (), ts_current, false);
478 xref_basetypes (type, NULL_TREE);
479 type = begin_class_definition (type);
480 if (!ptr_id)
482 ptr_id = get_identifier ("ptr");
483 max_id = get_identifier ("max");
485 tree ptrtype = build_pointer_type (TREE_TYPE (array_type));
486 tree field = build_decl (input_location, FIELD_DECL, ptr_id, ptrtype);
487 finish_member_declaration (field);
488 field = build_decl (input_location, FIELD_DECL, max_id, sizetype);
489 finish_member_declaration (field);
490 return finish_struct (type, NULL_TREE);
493 /* From an ID and INITIALIZER, create a capture (by reference if
494 BY_REFERENCE_P is true), add it to the capture-list for LAMBDA,
495 and return it. If ID is `this', BY_REFERENCE_P says whether
496 `*this' is captured by reference. */
498 tree
499 add_capture (tree lambda, tree id, tree orig_init, bool by_reference_p,
500 bool explicit_init_p)
502 char *buf;
503 tree type, member, name;
504 bool vla = false;
505 bool variadic = false;
506 tree initializer = orig_init;
508 if (PACK_EXPANSION_P (initializer))
510 initializer = PACK_EXPANSION_PATTERN (initializer);
511 variadic = true;
514 if (TREE_CODE (initializer) == TREE_LIST
515 /* A pack expansion might end up with multiple elements. */
516 && !PACK_EXPANSION_P (TREE_VALUE (initializer)))
517 initializer = build_x_compound_expr_from_list (initializer, ELK_INIT,
518 tf_warning_or_error);
519 type = TREE_TYPE (initializer);
520 if (type == error_mark_node)
521 return error_mark_node;
523 if (array_of_runtime_bound_p (type))
525 vla = true;
526 if (!by_reference_p)
527 error ("array of runtime bound cannot be captured by copy, "
528 "only by reference");
530 /* For a VLA, we capture the address of the first element and the
531 maximum index, and then reconstruct the VLA for the proxy. */
532 tree elt = cp_build_array_ref (input_location, initializer,
533 integer_zero_node, tf_warning_or_error);
534 initializer = build_constructor_va (init_list_type_node, 2,
535 NULL_TREE, build_address (elt),
536 NULL_TREE, array_type_nelts (type));
537 type = vla_capture_type (type);
539 else if (!dependent_type_p (type)
540 && variably_modified_type_p (type, NULL_TREE))
542 error ("capture of variable-size type %qT that is not an N3639 array "
543 "of runtime bound", type);
544 if (TREE_CODE (type) == ARRAY_TYPE
545 && variably_modified_type_p (TREE_TYPE (type), NULL_TREE))
546 inform (input_location, "because the array element type %qT has "
547 "variable size", TREE_TYPE (type));
548 type = error_mark_node;
550 else
552 type = lambda_capture_field_type (initializer, explicit_init_p,
553 by_reference_p);
554 if (type == error_mark_node)
555 return error_mark_node;
557 if (id == this_identifier && !by_reference_p)
559 gcc_assert (POINTER_TYPE_P (type));
560 type = TREE_TYPE (type);
561 initializer = cp_build_fold_indirect_ref (initializer);
564 if (dependent_type_p (type))
566 else if (id != this_identifier && by_reference_p)
568 if (!lvalue_p (initializer))
570 error ("cannot capture %qE by reference", initializer);
571 return error_mark_node;
574 else
576 /* Capture by copy requires a complete type. */
577 type = complete_type (type);
578 if (!COMPLETE_TYPE_P (type))
580 error ("capture by copy of incomplete type %qT", type);
581 cxx_incomplete_type_inform (type);
582 return error_mark_node;
587 /* Add __ to the beginning of the field name so that user code
588 won't find the field with name lookup. We can't just leave the name
589 unset because template instantiation uses the name to find
590 instantiated fields. */
591 buf = (char *) alloca (IDENTIFIER_LENGTH (id) + 3);
592 buf[1] = buf[0] = '_';
593 memcpy (buf + 2, IDENTIFIER_POINTER (id),
594 IDENTIFIER_LENGTH (id) + 1);
595 name = get_identifier (buf);
597 /* If TREE_TYPE isn't set, we're still in the introducer, so check
598 for duplicates. */
599 if (!LAMBDA_EXPR_CLOSURE (lambda))
601 if (IDENTIFIER_MARKED (name))
603 pedwarn (input_location, 0,
604 "already captured %qD in lambda expression", id);
605 return NULL_TREE;
607 IDENTIFIER_MARKED (name) = true;
610 if (variadic)
611 type = make_pack_expansion (type);
613 /* Make member variable. */
614 member = build_decl (input_location, FIELD_DECL, name, type);
615 DECL_VLA_CAPTURE_P (member) = vla;
617 if (!explicit_init_p)
618 /* Normal captures are invisible to name lookup but uses are replaced
619 with references to the capture field; we implement this by only
620 really making them invisible in unevaluated context; see
621 qualify_lookup. For now, let's make explicitly initialized captures
622 always visible. */
623 DECL_NORMAL_CAPTURE_P (member) = true;
625 if (id == this_identifier)
626 LAMBDA_EXPR_THIS_CAPTURE (lambda) = member;
628 /* Add it to the appropriate closure class if we've started it. */
629 if (current_class_type
630 && current_class_type == LAMBDA_EXPR_CLOSURE (lambda))
632 if (COMPLETE_TYPE_P (current_class_type))
633 internal_error ("trying to capture %qD in instantiation of "
634 "generic lambda", id);
635 finish_member_declaration (member);
638 tree listmem = member;
639 if (variadic)
641 listmem = make_pack_expansion (member);
642 initializer = orig_init;
644 LAMBDA_EXPR_CAPTURE_LIST (lambda)
645 = tree_cons (listmem, initializer, LAMBDA_EXPR_CAPTURE_LIST (lambda));
647 if (LAMBDA_EXPR_CLOSURE (lambda))
648 return build_capture_proxy (member, initializer);
649 /* For explicit captures we haven't started the function yet, so we wait
650 and build the proxy from cp_parser_lambda_body. */
651 return NULL_TREE;
654 /* Register all the capture members on the list CAPTURES, which is the
655 LAMBDA_EXPR_CAPTURE_LIST for the lambda after the introducer. */
657 void
658 register_capture_members (tree captures)
660 if (captures == NULL_TREE)
661 return;
663 register_capture_members (TREE_CHAIN (captures));
665 tree field = TREE_PURPOSE (captures);
666 if (PACK_EXPANSION_P (field))
667 field = PACK_EXPANSION_PATTERN (field);
669 /* We set this in add_capture to avoid duplicates. */
670 IDENTIFIER_MARKED (DECL_NAME (field)) = false;
671 finish_member_declaration (field);
674 /* Similar to add_capture, except this works on a stack of nested lambdas.
675 BY_REFERENCE_P in this case is derived from the default capture mode.
676 Returns the capture for the lambda at the bottom of the stack. */
678 tree
679 add_default_capture (tree lambda_stack, tree id, tree initializer)
681 bool this_capture_p = (id == this_identifier);
683 tree var = NULL_TREE;
685 tree saved_class_type = current_class_type;
687 tree node;
689 for (node = lambda_stack;
690 node;
691 node = TREE_CHAIN (node))
693 tree lambda = TREE_VALUE (node);
695 current_class_type = LAMBDA_EXPR_CLOSURE (lambda);
696 if (DECL_PACK_P (initializer))
697 initializer = make_pack_expansion (initializer);
698 var = add_capture (lambda,
700 initializer,
701 /*by_reference_p=*/
702 (this_capture_p
703 || (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda)
704 == CPLD_REFERENCE)),
705 /*explicit_init_p=*/false);
706 initializer = convert_from_reference (var);
709 current_class_type = saved_class_type;
711 return var;
714 /* Return the capture pertaining to a use of 'this' in LAMBDA, in the
715 form of an INDIRECT_REF, possibly adding it through default
716 capturing, if ADD_CAPTURE_P is true. */
718 tree
719 lambda_expr_this_capture (tree lambda, bool add_capture_p)
721 tree result;
723 tree this_capture = LAMBDA_EXPR_THIS_CAPTURE (lambda);
725 /* In unevaluated context this isn't an odr-use, so don't capture. */
726 if (cp_unevaluated_operand)
727 add_capture_p = false;
729 /* Try to default capture 'this' if we can. */
730 if (!this_capture
731 && (!add_capture_p
732 || LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda) != CPLD_NONE))
734 tree lambda_stack = NULL_TREE;
735 tree init = NULL_TREE;
737 /* If we are in a lambda function, we can move out until we hit:
738 1. a non-lambda function or NSDMI,
739 2. a lambda function capturing 'this', or
740 3. a non-default capturing lambda function. */
741 for (tree tlambda = lambda; ;)
743 lambda_stack = tree_cons (NULL_TREE,
744 tlambda,
745 lambda_stack);
747 if (LAMBDA_EXPR_EXTRA_SCOPE (tlambda)
748 && TREE_CODE (LAMBDA_EXPR_EXTRA_SCOPE (tlambda)) == FIELD_DECL)
750 /* In an NSDMI, we don't have a function to look up the decl in,
751 but the fake 'this' pointer that we're using for parsing is
752 in scope_chain. */
753 init = scope_chain->x_current_class_ptr;
754 gcc_checking_assert
755 (init && (TREE_TYPE (TREE_TYPE (init))
756 == current_nonlambda_class_type ()));
757 break;
760 tree closure_decl = TYPE_NAME (LAMBDA_EXPR_CLOSURE (tlambda));
761 tree containing_function = decl_function_context (closure_decl);
763 if (containing_function == NULL_TREE)
764 /* We ran out of scopes; there's no 'this' to capture. */
765 break;
767 if (!LAMBDA_FUNCTION_P (containing_function))
769 /* We found a non-lambda function. */
770 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (containing_function))
771 /* First parameter is 'this'. */
772 init = DECL_ARGUMENTS (containing_function);
773 break;
776 tlambda
777 = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (containing_function));
779 if (LAMBDA_EXPR_THIS_CAPTURE (tlambda))
781 /* An outer lambda has already captured 'this'. */
782 init = LAMBDA_EXPR_THIS_CAPTURE (tlambda);
783 break;
786 if (LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (tlambda) == CPLD_NONE)
787 /* An outer lambda won't let us capture 'this'. */
788 break;
791 if (init)
793 if (add_capture_p)
794 this_capture = add_default_capture (lambda_stack,
795 /*id=*/this_identifier,
796 init);
797 else
798 this_capture = init;
802 if (cp_unevaluated_operand)
803 result = this_capture;
804 else if (!this_capture)
806 if (add_capture_p)
808 error ("%<this%> was not captured for this lambda function");
809 result = error_mark_node;
811 else
812 result = NULL_TREE;
814 else
816 /* To make sure that current_class_ref is for the lambda. */
817 gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (current_class_ref))
818 == LAMBDA_EXPR_CLOSURE (lambda));
820 result = this_capture;
822 /* If 'this' is captured, each use of 'this' is transformed into an
823 access to the corresponding unnamed data member of the closure
824 type cast (_expr.cast_ 5.4) to the type of 'this'. [ The cast
825 ensures that the transformed expression is an rvalue. ] */
826 result = rvalue (result);
829 return result;
832 /* Return the current LAMBDA_EXPR, if this is a resolvable dummy
833 object. NULL otherwise.. */
835 static tree
836 resolvable_dummy_lambda (tree object)
838 if (!is_dummy_object (object))
839 return NULL_TREE;
841 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (object));
842 gcc_assert (!TYPE_PTR_P (type));
844 if (type != current_class_type
845 && current_class_type
846 && LAMBDA_TYPE_P (current_class_type)
847 && lambda_function (current_class_type)
848 && DERIVED_FROM_P (type, current_nonlambda_class_type ()))
849 return CLASSTYPE_LAMBDA_EXPR (current_class_type);
851 return NULL_TREE;
854 /* We don't want to capture 'this' until we know we need it, i.e. after
855 overload resolution has chosen a non-static member function. At that
856 point we call this function to turn a dummy object into a use of the
857 'this' capture. */
859 tree
860 maybe_resolve_dummy (tree object, bool add_capture_p)
862 if (tree lam = resolvable_dummy_lambda (object))
863 if (tree cap = lambda_expr_this_capture (lam, add_capture_p))
864 if (cap != error_mark_node)
865 object = build_fold_indirect_ref (cap);
867 return object;
870 /* When parsing a generic lambda containing an argument-dependent
871 member function call we defer overload resolution to instantiation
872 time. But we have to know now whether to capture this or not.
873 Do that if FNS contains any non-static fns.
874 The std doesn't anticipate this case, but I expect this to be the
875 outcome of discussion. */
877 void
878 maybe_generic_this_capture (tree object, tree fns)
880 if (tree lam = resolvable_dummy_lambda (object))
881 if (!LAMBDA_EXPR_THIS_CAPTURE (lam))
883 /* We've not yet captured, so look at the function set of
884 interest. */
885 if (BASELINK_P (fns))
886 fns = BASELINK_FUNCTIONS (fns);
887 bool id_expr = TREE_CODE (fns) == TEMPLATE_ID_EXPR;
888 if (id_expr)
889 fns = TREE_OPERAND (fns, 0);
891 for (lkp_iterator iter (fns); iter; ++iter)
892 if ((!id_expr || TREE_CODE (*iter) == TEMPLATE_DECL)
893 && DECL_NONSTATIC_MEMBER_FUNCTION_P (*iter))
895 /* Found a non-static member. Capture this. */
896 lambda_expr_this_capture (lam, true);
897 break;
902 /* Returns the innermost non-lambda function. */
904 tree
905 current_nonlambda_function (void)
907 tree fn = current_function_decl;
908 while (fn && LAMBDA_FUNCTION_P (fn))
909 fn = decl_function_context (fn);
910 return fn;
913 /* Returns the method basetype of the innermost non-lambda function, or
914 NULL_TREE if none. */
916 tree
917 nonlambda_method_basetype (void)
919 tree fn, type;
920 if (!current_class_ref)
921 return NULL_TREE;
923 type = current_class_type;
924 if (!LAMBDA_TYPE_P (type))
925 return type;
927 /* Find the nearest enclosing non-lambda function. */
928 fn = TYPE_NAME (type);
930 fn = decl_function_context (fn);
931 while (fn && LAMBDA_FUNCTION_P (fn));
933 if (!fn || !DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
934 return NULL_TREE;
936 return TYPE_METHOD_BASETYPE (TREE_TYPE (fn));
939 /* Like current_scope, but looking through lambdas. */
941 tree
942 current_nonlambda_scope (void)
944 tree scope = current_scope ();
945 for (;;)
947 if (TREE_CODE (scope) == FUNCTION_DECL
948 && LAMBDA_FUNCTION_P (scope))
950 scope = CP_TYPE_CONTEXT (DECL_CONTEXT (scope));
951 continue;
953 else if (LAMBDA_TYPE_P (scope))
955 scope = CP_TYPE_CONTEXT (scope);
956 continue;
958 break;
960 return scope;
963 /* Helper function for maybe_add_lambda_conv_op; build a CALL_EXPR with
964 indicated FN and NARGS, but do not initialize the return type or any of the
965 argument slots. */
967 static tree
968 prepare_op_call (tree fn, int nargs)
970 tree t;
972 t = build_vl_exp (CALL_EXPR, nargs + 3);
973 CALL_EXPR_FN (t) = fn;
974 CALL_EXPR_STATIC_CHAIN (t) = NULL;
976 return t;
979 /* Return true iff CALLOP is the op() for a generic lambda. */
981 bool
982 generic_lambda_fn_p (tree callop)
984 return (LAMBDA_FUNCTION_P (callop)
985 && DECL_TEMPLATE_INFO (callop)
986 && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (callop)));
989 /* If the closure TYPE has a static op(), also add a conversion to function
990 pointer. */
992 void
993 maybe_add_lambda_conv_op (tree type)
995 bool nested = (cfun != NULL);
996 bool nested_def = decl_function_context (TYPE_MAIN_DECL (type));
997 tree callop = lambda_function (type);
998 tree lam = CLASSTYPE_LAMBDA_EXPR (type);
1000 if (LAMBDA_EXPR_CAPTURE_LIST (lam) != NULL_TREE
1001 || LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lam) != CPLD_NONE)
1002 return;
1004 if (processing_template_decl)
1005 return;
1007 bool const generic_lambda_p = generic_lambda_fn_p (callop);
1009 if (!generic_lambda_p && DECL_INITIAL (callop) == NULL_TREE)
1011 /* If the op() wasn't instantiated due to errors, give up. */
1012 gcc_assert (errorcount || sorrycount);
1013 return;
1016 /* Non-template conversion operators are defined directly with build_call_a
1017 and using DIRECT_ARGVEC for arguments (including 'this'). Templates are
1018 deferred and the CALL is built in-place. In the case of a deduced return
1019 call op, the decltype expression, DECLTYPE_CALL, used as a substitute for
1020 the return type is also built in-place. The arguments of DECLTYPE_CALL in
1021 the return expression may differ in flags from those in the body CALL. In
1022 particular, parameter pack expansions are marked PACK_EXPANSION_LOCAL_P in
1023 the body CALL, but not in DECLTYPE_CALL. */
1025 vec<tree, va_gc> *direct_argvec = 0;
1026 tree decltype_call = 0, call = 0;
1027 tree optype = TREE_TYPE (callop);
1028 tree fn_result = TREE_TYPE (optype);
1030 tree thisarg = build_nop (TREE_TYPE (DECL_ARGUMENTS (callop)),
1031 null_pointer_node);
1032 if (generic_lambda_p)
1034 ++processing_template_decl;
1036 /* Prepare the dependent member call for the static member function
1037 '_FUN' and, potentially, prepare another call to be used in a decltype
1038 return expression for a deduced return call op to allow for simple
1039 implementation of the conversion operator. */
1041 tree instance = cp_build_fold_indirect_ref (thisarg);
1042 tree objfn = build_min (COMPONENT_REF, NULL_TREE,
1043 instance, DECL_NAME (callop), NULL_TREE);
1044 int nargs = list_length (DECL_ARGUMENTS (callop)) - 1;
1046 call = prepare_op_call (objfn, nargs);
1047 if (type_uses_auto (fn_result))
1048 decltype_call = prepare_op_call (objfn, nargs);
1050 else
1052 direct_argvec = make_tree_vector ();
1053 direct_argvec->quick_push (thisarg);
1056 /* Copy CALLOP's argument list (as per 'copy_list') as FN_ARGS in order to
1057 declare the static member function "_FUN" below. For each arg append to
1058 DIRECT_ARGVEC (for the non-template case) or populate the pre-allocated
1059 call args (for the template case). If a parameter pack is found, expand
1060 it, flagging it as PACK_EXPANSION_LOCAL_P for the body call. */
1062 tree fn_args = NULL_TREE;
1064 int ix = 0;
1065 tree src = DECL_CHAIN (DECL_ARGUMENTS (callop));
1066 tree tgt = NULL;
1068 while (src)
1070 tree new_node = copy_node (src);
1072 if (!fn_args)
1073 fn_args = tgt = new_node;
1074 else
1076 TREE_CHAIN (tgt) = new_node;
1077 tgt = new_node;
1080 mark_exp_read (tgt);
1082 if (generic_lambda_p)
1084 /* Avoid capturing variables in this context. */
1085 ++cp_unevaluated_operand;
1086 tree a = forward_parm (tgt);
1087 --cp_unevaluated_operand;
1089 CALL_EXPR_ARG (call, ix) = a;
1090 if (decltype_call)
1091 CALL_EXPR_ARG (decltype_call, ix) = unshare_expr (a);
1093 if (PACK_EXPANSION_P (a))
1094 /* Set this after unsharing so it's not in decltype_call. */
1095 PACK_EXPANSION_LOCAL_P (a) = true;
1097 ++ix;
1099 else
1100 vec_safe_push (direct_argvec, tgt);
1102 src = TREE_CHAIN (src);
1106 if (generic_lambda_p)
1108 if (decltype_call)
1110 fn_result = finish_decltype_type
1111 (decltype_call, /*id_expression_or_member_access_p=*/false,
1112 tf_warning_or_error);
1115 else
1116 call = build_call_a (callop,
1117 direct_argvec->length (),
1118 direct_argvec->address ());
1120 CALL_FROM_THUNK_P (call) = 1;
1121 SET_EXPR_LOCATION (call, UNKNOWN_LOCATION);
1123 tree stattype = build_function_type (fn_result, FUNCTION_ARG_CHAIN (callop));
1124 stattype = (cp_build_type_attribute_variant
1125 (stattype, TYPE_ATTRIBUTES (optype)));
1126 if (flag_noexcept_type
1127 && TYPE_NOTHROW_P (TREE_TYPE (callop)))
1128 stattype = build_exception_variant (stattype, noexcept_true_spec);
1130 if (generic_lambda_p)
1131 --processing_template_decl;
1133 /* First build up the conversion op. */
1135 tree rettype = build_pointer_type (stattype);
1136 tree name = make_conv_op_name (rettype);
1137 tree thistype = cp_build_qualified_type (type, TYPE_QUAL_CONST);
1138 tree fntype = build_method_type_directly (thistype, rettype, void_list_node);
1139 tree convfn = build_lang_decl (FUNCTION_DECL, name, fntype);
1140 tree fn = convfn;
1141 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (callop);
1142 SET_DECL_ALIGN (fn, MINIMUM_METHOD_BOUNDARY);
1143 grokclassfn (type, fn, NO_SPECIAL);
1144 set_linkage_according_to_type (type, fn);
1145 rest_of_decl_compilation (fn, namespace_bindings_p (), at_eof);
1146 DECL_IN_AGGR_P (fn) = 1;
1147 DECL_ARTIFICIAL (fn) = 1;
1148 DECL_NOT_REALLY_EXTERN (fn) = 1;
1149 DECL_DECLARED_INLINE_P (fn) = 1;
1150 DECL_ARGUMENTS (fn) = build_this_parm (fn, fntype, TYPE_QUAL_CONST);
1152 if (nested_def)
1153 DECL_INTERFACE_KNOWN (fn) = 1;
1155 if (generic_lambda_p)
1156 fn = add_inherited_template_parms (fn, DECL_TI_TEMPLATE (callop));
1158 add_method (type, fn, false);
1160 /* Generic thunk code fails for varargs; we'll complain in mark_used if
1161 the conversion op is used. */
1162 if (varargs_function_p (callop))
1164 DECL_DELETED_FN (fn) = 1;
1165 return;
1168 /* Now build up the thunk to be returned. */
1170 name = get_identifier ("_FUN");
1171 tree statfn = build_lang_decl (FUNCTION_DECL, name, stattype);
1172 fn = statfn;
1173 DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (callop);
1174 grokclassfn (type, fn, NO_SPECIAL);
1175 set_linkage_according_to_type (type, fn);
1176 rest_of_decl_compilation (fn, namespace_bindings_p (), at_eof);
1177 DECL_IN_AGGR_P (fn) = 1;
1178 DECL_ARTIFICIAL (fn) = 1;
1179 DECL_NOT_REALLY_EXTERN (fn) = 1;
1180 DECL_DECLARED_INLINE_P (fn) = 1;
1181 DECL_STATIC_FUNCTION_P (fn) = 1;
1182 DECL_ARGUMENTS (fn) = fn_args;
1183 for (tree arg = fn_args; arg; arg = DECL_CHAIN (arg))
1185 /* Avoid duplicate -Wshadow warnings. */
1186 DECL_NAME (arg) = NULL_TREE;
1187 DECL_CONTEXT (arg) = fn;
1189 if (nested_def)
1190 DECL_INTERFACE_KNOWN (fn) = 1;
1192 if (generic_lambda_p)
1193 fn = add_inherited_template_parms (fn, DECL_TI_TEMPLATE (callop));
1195 if (flag_sanitize & SANITIZE_NULL)
1196 /* Don't UBsan this function; we're deliberately calling op() with a null
1197 object argument. */
1198 add_no_sanitize_value (fn, SANITIZE_UNDEFINED);
1200 add_method (type, fn, false);
1202 if (nested)
1203 push_function_context ();
1204 else
1205 /* Still increment function_depth so that we don't GC in the
1206 middle of an expression. */
1207 ++function_depth;
1209 /* Generate the body of the thunk. */
1211 start_preparsed_function (statfn, NULL_TREE,
1212 SF_PRE_PARSED | SF_INCLASS_INLINE);
1213 if (DECL_ONE_ONLY (statfn))
1215 /* Put the thunk in the same comdat group as the call op. */
1216 cgraph_node::get_create (statfn)->add_to_same_comdat_group
1217 (cgraph_node::get_create (callop));
1219 tree body = begin_function_body ();
1220 tree compound_stmt = begin_compound_stmt (0);
1221 if (!generic_lambda_p)
1223 set_flags_from_callee (call);
1224 if (MAYBE_CLASS_TYPE_P (TREE_TYPE (call)))
1225 call = build_cplus_new (TREE_TYPE (call), call, tf_warning_or_error);
1227 call = convert_from_reference (call);
1228 finish_return_stmt (call);
1230 finish_compound_stmt (compound_stmt);
1231 finish_function_body (body);
1233 fn = finish_function (/*inline_p=*/true);
1234 if (!generic_lambda_p)
1235 expand_or_defer_fn (fn);
1237 /* Generate the body of the conversion op. */
1239 start_preparsed_function (convfn, NULL_TREE,
1240 SF_PRE_PARSED | SF_INCLASS_INLINE);
1241 body = begin_function_body ();
1242 compound_stmt = begin_compound_stmt (0);
1244 /* decl_needed_p needs to see that it's used. */
1245 TREE_USED (statfn) = 1;
1246 finish_return_stmt (decay_conversion (statfn, tf_warning_or_error));
1248 finish_compound_stmt (compound_stmt);
1249 finish_function_body (body);
1251 fn = finish_function (/*inline_p=*/true);
1252 if (!generic_lambda_p)
1253 expand_or_defer_fn (fn);
1255 if (nested)
1256 pop_function_context ();
1257 else
1258 --function_depth;
1261 /* True if FN is the static function "_FUN" that gets returned from the lambda
1262 conversion operator. */
1264 bool
1265 lambda_static_thunk_p (tree fn)
1267 return (fn && TREE_CODE (fn) == FUNCTION_DECL
1268 && DECL_ARTIFICIAL (fn)
1269 && DECL_STATIC_FUNCTION_P (fn)
1270 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fn)));
1273 /* Returns true iff VAL is a lambda-related declaration which should
1274 be ignored by unqualified lookup. */
1276 bool
1277 is_lambda_ignored_entity (tree val)
1279 /* Look past normal capture proxies. */
1280 if (is_normal_capture_proxy (val))
1281 return true;
1283 /* Always ignore lambda fields, their names are only for debugging. */
1284 if (TREE_CODE (val) == FIELD_DECL
1285 && CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (val)))
1286 return true;
1288 /* None of the lookups that use qualify_lookup want the op() from the
1289 lambda; they want the one from the enclosing class. */
1290 if (TREE_CODE (val) == FUNCTION_DECL && LAMBDA_FUNCTION_P (val))
1291 return true;
1293 return false;
1296 /* Lambdas that appear in variable initializer or default argument scope
1297 get that in their mangling, so we need to record it. We might as well
1298 use the count for function and namespace scopes as well. */
1299 static GTY(()) tree lambda_scope;
1300 static GTY(()) int lambda_count;
1301 struct GTY(()) tree_int
1303 tree t;
1304 int i;
1306 static GTY(()) vec<tree_int, va_gc> *lambda_scope_stack;
1308 void
1309 start_lambda_scope (tree decl)
1311 tree_int ti;
1312 gcc_assert (decl);
1313 /* Once we're inside a function, we ignore variable scope and just push
1314 the function again so that popping works properly. */
1315 if (current_function_decl && TREE_CODE (decl) == VAR_DECL)
1316 decl = current_function_decl;
1317 ti.t = lambda_scope;
1318 ti.i = lambda_count;
1319 vec_safe_push (lambda_scope_stack, ti);
1320 if (lambda_scope != decl)
1322 /* Don't reset the count if we're still in the same function. */
1323 lambda_scope = decl;
1324 lambda_count = 0;
1328 void
1329 record_lambda_scope (tree lambda)
1331 LAMBDA_EXPR_EXTRA_SCOPE (lambda) = lambda_scope;
1332 LAMBDA_EXPR_DISCRIMINATOR (lambda) = lambda_count++;
1335 void
1336 finish_lambda_scope (void)
1338 tree_int *p = &lambda_scope_stack->last ();
1339 if (lambda_scope != p->t)
1341 lambda_scope = p->t;
1342 lambda_count = p->i;
1344 lambda_scope_stack->pop ();
1347 tree
1348 start_lambda_function (tree fco, tree lambda_expr)
1350 /* Let the front end know that we are going to be defining this
1351 function. */
1352 start_preparsed_function (fco,
1353 NULL_TREE,
1354 SF_PRE_PARSED | SF_INCLASS_INLINE);
1356 tree body = begin_function_body ();
1358 /* Push the proxies for any explicit captures. */
1359 for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (lambda_expr); cap;
1360 cap = TREE_CHAIN (cap))
1361 build_capture_proxy (TREE_PURPOSE (cap), TREE_VALUE (cap));
1363 return body;
1366 void
1367 finish_lambda_function (tree body)
1369 finish_function_body (body);
1371 /* Finish the function and generate code for it if necessary. */
1372 tree fn = finish_function (/*inline_p=*/true);
1374 /* Only expand if the call op is not a template. */
1375 if (!DECL_TEMPLATE_INFO (fn))
1376 expand_or_defer_fn (fn);
1379 #include "gt-cp-lambda.h"