1 // expressions.cc -- Go frontend expression handling.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #ifndef ENABLE_BUILD_WITH_CXX
20 #include "tree-iterator.h"
25 #ifndef ENABLE_BUILD_WITH_CXX
34 #include "statements.h"
38 #include "expressions.h"
43 Expression::Expression(Expression_classification classification,
45 : classification_(classification), location_(location)
49 Expression::~Expression()
53 // Traverse the expressions.
56 Expression::traverse(Expression** pexpr, Traverse* traverse)
58 Expression* expr = *pexpr;
59 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
61 int t = traverse->expression(pexpr);
62 if (t == TRAVERSE_EXIT)
64 else if (t == TRAVERSE_SKIP_COMPONENTS)
65 return TRAVERSE_CONTINUE;
67 return expr->do_traverse(traverse);
70 // Traverse subexpressions of this expression.
73 Expression::traverse_subexpressions(Traverse* traverse)
75 return this->do_traverse(traverse);
78 // Default implementation for do_traverse for child classes.
81 Expression::do_traverse(Traverse*)
83 return TRAVERSE_CONTINUE;
86 // This virtual function is called by the parser if the value of this
87 // expression is being discarded. By default, we give an error.
88 // Expressions with side effects override.
91 Expression::do_discarding_value()
93 this->unused_value_error();
96 // This virtual function is called to export expressions. This will
97 // only be used by expressions which may be constant.
100 Expression::do_export(Export*) const
105 // Give an error saying that the value of the expression is not used.
108 Expression::unused_value_error()
110 error_at(this->location(), "value computed is not used");
113 // Note that this expression is an error. This is called by children
114 // when they discover an error.
117 Expression::set_is_error()
119 this->classification_ = EXPRESSION_ERROR;
122 // For children to call to report an error conveniently.
125 Expression::report_error(const char* msg)
127 error_at(this->location_, "%s", msg);
128 this->set_is_error();
131 // Set types of variables and constants. This is implemented by the
135 Expression::determine_type(const Type_context* context)
137 this->do_determine_type(context);
140 // Set types when there is no context.
143 Expression::determine_type_no_context()
145 Type_context context;
146 this->do_determine_type(&context);
149 // Return a tree handling any conversions which must be done during
153 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
154 Type* rhs_type, tree rhs_tree,
157 if (lhs_type->is_error() || rhs_type->is_error())
158 return error_mark_node;
160 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
161 return error_mark_node;
163 Gogo* gogo = context->gogo();
165 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
166 if (lhs_type_tree == error_mark_node)
167 return error_mark_node;
169 if (lhs_type != rhs_type && lhs_type->interface_type() != NULL)
171 if (rhs_type->interface_type() == NULL)
172 return Expression::convert_type_to_interface(context, lhs_type,
176 return Expression::convert_interface_to_interface(context, lhs_type,
180 else if (lhs_type != rhs_type && rhs_type->interface_type() != NULL)
181 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
183 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
185 // Assigning nil to an open array.
186 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
188 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
190 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
191 tree field = TYPE_FIELDS(lhs_type_tree);
192 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
195 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
197 elt = VEC_quick_push(constructor_elt, init, NULL);
198 field = DECL_CHAIN(field);
199 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
202 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
204 elt = VEC_quick_push(constructor_elt, init, NULL);
205 field = DECL_CHAIN(field);
206 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
209 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
211 tree val = build_constructor(lhs_type_tree, init);
212 TREE_CONSTANT(val) = 1;
216 else if (rhs_type->is_nil_type())
218 // The left hand side should be a pointer type at the tree
220 go_assert(POINTER_TYPE_P(lhs_type_tree));
221 return fold_convert(lhs_type_tree, null_pointer_node);
223 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
225 // No conversion is needed.
228 else if (POINTER_TYPE_P(lhs_type_tree)
229 || INTEGRAL_TYPE_P(lhs_type_tree)
230 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
231 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
232 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
233 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
234 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
235 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
236 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
238 // Avoid confusion from zero sized variables which may be
239 // represented as non-zero-sized.
240 if (int_size_in_bytes(lhs_type_tree) == 0
241 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
244 // This conversion must be permitted by Go, or we wouldn't have
246 go_assert(int_size_in_bytes(lhs_type_tree)
247 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
248 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
249 lhs_type_tree, rhs_tree);
253 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
258 // Return a tree for a conversion from a non-interface type to an
262 Expression::convert_type_to_interface(Translate_context* context,
263 Type* lhs_type, Type* rhs_type,
264 tree rhs_tree, Location location)
266 Gogo* gogo = context->gogo();
267 Interface_type* lhs_interface_type = lhs_type->interface_type();
268 bool lhs_is_empty = lhs_interface_type->is_empty();
270 // Since RHS_TYPE is a static type, we can create the interface
271 // method table at compile time.
273 // When setting an interface to nil, we just set both fields to
275 if (rhs_type->is_nil_type())
277 Btype* lhs_btype = lhs_type->get_backend(gogo);
278 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
281 // This should have been checked already.
282 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
284 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
285 if (lhs_type_tree == error_mark_node)
286 return error_mark_node;
288 // An interface is a tuple. If LHS_TYPE is an empty interface type,
289 // then the first field is the type descriptor for RHS_TYPE.
290 // Otherwise it is the interface method table for RHS_TYPE.
291 tree first_field_value;
293 first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
296 // Build the interface method table for this interface and this
297 // object type: a list of function pointers for each interface
299 Named_type* rhs_named_type = rhs_type->named_type();
300 bool is_pointer = false;
301 if (rhs_named_type == NULL)
303 rhs_named_type = rhs_type->deref()->named_type();
307 if (rhs_named_type == NULL)
308 method_table = null_pointer_node;
311 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
313 first_field_value = fold_convert_loc(location.gcc_location(),
314 const_ptr_type_node, method_table);
316 if (first_field_value == error_mark_node)
317 return error_mark_node;
319 // Start building a constructor for the value we will return.
321 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
323 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
324 tree field = TYPE_FIELDS(lhs_type_tree);
325 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
326 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
328 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
331 elt = VEC_quick_push(constructor_elt, init, NULL);
332 field = DECL_CHAIN(field);
333 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
336 if (rhs_type->points_to() != NULL)
338 // We are assigning a pointer to the interface; the interface
339 // holds the pointer itself.
340 elt->value = rhs_tree;
341 return build_constructor(lhs_type_tree, init);
344 // We are assigning a non-pointer value to the interface; the
345 // interface gets a copy of the value in the heap.
347 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
349 tree space = gogo->allocate_memory(rhs_type, object_size, location);
350 space = fold_convert_loc(location.gcc_location(),
351 build_pointer_type(TREE_TYPE(rhs_tree)), space);
352 space = save_expr(space);
354 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
355 TREE_THIS_NOTRAP(ref) = 1;
356 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
357 void_type_node, ref, rhs_tree);
359 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
362 return build2(COMPOUND_EXPR, lhs_type_tree, set,
363 build_constructor(lhs_type_tree, init));
366 // Return a tree for the type descriptor of RHS_TREE, which has
367 // interface type RHS_TYPE. If RHS_TREE is nil the result will be
371 Expression::get_interface_type_descriptor(Translate_context*,
372 Type* rhs_type, tree rhs_tree,
375 tree rhs_type_tree = TREE_TYPE(rhs_tree);
376 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
377 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
378 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
380 if (rhs_type->interface_type()->is_empty())
382 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
383 "__type_descriptor") == 0);
387 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
389 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
391 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
392 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
393 tree f = TYPE_FIELDS(TREE_TYPE(v1));
394 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
396 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
398 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
399 v, fold_convert_loc(location.gcc_location(),
402 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
404 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
408 // Return a tree for the conversion of an interface type to an
412 Expression::convert_interface_to_interface(Translate_context* context,
413 Type *lhs_type, Type *rhs_type,
414 tree rhs_tree, bool for_type_guard,
417 Gogo* gogo = context->gogo();
418 Interface_type* lhs_interface_type = lhs_type->interface_type();
419 bool lhs_is_empty = lhs_interface_type->is_empty();
421 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
422 if (lhs_type_tree == error_mark_node)
423 return error_mark_node;
425 // In the general case this requires runtime examination of the type
426 // method table to match it up with the interface methods.
428 // FIXME: If all of the methods in the right hand side interface
429 // also appear in the left hand side interface, then we don't need
430 // to do a runtime check, although we still need to build a new
433 // Get the type descriptor for the right hand side. This will be
434 // NULL for a nil interface.
436 if (!DECL_P(rhs_tree))
437 rhs_tree = save_expr(rhs_tree);
439 tree rhs_type_descriptor =
440 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
443 // The result is going to be a two element constructor.
445 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
447 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
448 tree field = TYPE_FIELDS(lhs_type_tree);
453 // A type assertion fails when converting a nil interface.
454 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
456 static tree assert_interface_decl;
457 tree call = Gogo::call_builtin(&assert_interface_decl,
459 "__go_assert_interface",
462 TREE_TYPE(lhs_type_descriptor),
464 TREE_TYPE(rhs_type_descriptor),
465 rhs_type_descriptor);
466 if (call == error_mark_node)
467 return error_mark_node;
468 // This will panic if the interface conversion fails.
469 TREE_NOTHROW(assert_interface_decl) = 0;
470 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
473 else if (lhs_is_empty)
475 // A convertion to an empty interface always succeeds, and the
476 // first field is just the type descriptor of the object.
477 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
478 "__type_descriptor") == 0);
479 elt->value = fold_convert_loc(location.gcc_location(),
480 TREE_TYPE(field), rhs_type_descriptor);
484 // A conversion to a non-empty interface may fail, but unlike a
485 // type assertion converting nil will always succeed.
486 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
488 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
490 static tree convert_interface_decl;
491 tree call = Gogo::call_builtin(&convert_interface_decl,
493 "__go_convert_interface",
496 TREE_TYPE(lhs_type_descriptor),
498 TREE_TYPE(rhs_type_descriptor),
499 rhs_type_descriptor);
500 if (call == error_mark_node)
501 return error_mark_node;
502 // This will panic if the interface conversion fails.
503 TREE_NOTHROW(convert_interface_decl) = 0;
504 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
508 // The second field is simply the object pointer.
510 elt = VEC_quick_push(constructor_elt, init, NULL);
511 field = DECL_CHAIN(field);
512 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
515 tree rhs_type_tree = TREE_TYPE(rhs_tree);
516 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
517 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
518 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
519 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
522 return build_constructor(lhs_type_tree, init);
525 // Return a tree for the conversion of an interface type to a
526 // non-interface type.
529 Expression::convert_interface_to_type(Translate_context* context,
530 Type *lhs_type, Type* rhs_type,
531 tree rhs_tree, Location location)
533 Gogo* gogo = context->gogo();
534 tree rhs_type_tree = TREE_TYPE(rhs_tree);
536 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
537 if (lhs_type_tree == error_mark_node)
538 return error_mark_node;
540 // Call a function to check that the type is valid. The function
541 // will panic with an appropriate runtime type error if the type is
544 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
546 if (!DECL_P(rhs_tree))
547 rhs_tree = save_expr(rhs_tree);
549 tree rhs_type_descriptor =
550 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
553 tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
556 static tree check_interface_type_decl;
557 tree call = Gogo::call_builtin(&check_interface_type_decl,
559 "__go_check_interface_type",
562 TREE_TYPE(lhs_type_descriptor),
564 TREE_TYPE(rhs_type_descriptor),
566 TREE_TYPE(rhs_inter_descriptor),
567 rhs_inter_descriptor);
568 if (call == error_mark_node)
569 return error_mark_node;
570 // This call will panic if the conversion is invalid.
571 TREE_NOTHROW(check_interface_type_decl) = 0;
573 // If the call succeeds, pull out the value.
574 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
575 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
576 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
577 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
580 // If the value is a pointer, then it is the value we want.
581 // Otherwise it points to the value.
582 if (lhs_type->points_to() == NULL)
584 val = fold_convert_loc(location.gcc_location(),
585 build_pointer_type(lhs_type_tree), val);
586 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
589 return build2(COMPOUND_EXPR, lhs_type_tree, call,
590 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
593 // Convert an expression to a tree. This is implemented by the child
594 // class. Not that it is not in general safe to call this multiple
595 // times for a single expression, but that we don't catch such errors.
598 Expression::get_tree(Translate_context* context)
600 // The child may have marked this expression as having an error.
601 if (this->classification_ == EXPRESSION_ERROR)
602 return error_mark_node;
604 return this->do_get_tree(context);
607 // Return a tree for VAL in TYPE.
610 Expression::integer_constant_tree(mpz_t val, tree type)
612 if (type == error_mark_node)
613 return error_mark_node;
614 else if (TREE_CODE(type) == INTEGER_TYPE)
615 return double_int_to_tree(type,
616 mpz_get_double_int(type, val, true));
617 else if (TREE_CODE(type) == REAL_TYPE)
620 mpfr_init_set_z(fval, val, GMP_RNDN);
621 tree ret = Expression::float_constant_tree(fval, type);
625 else if (TREE_CODE(type) == COMPLEX_TYPE)
628 mpfr_init_set_z(fval, val, GMP_RNDN);
629 tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
631 tree imag = build_real_from_int_cst(TREE_TYPE(type),
633 return build_complex(type, real, imag);
639 // Return a tree for VAL in TYPE.
642 Expression::float_constant_tree(mpfr_t val, tree type)
644 if (type == error_mark_node)
645 return error_mark_node;
646 else if (TREE_CODE(type) == INTEGER_TYPE)
650 mpfr_get_z(ival, val, GMP_RNDN);
651 tree ret = Expression::integer_constant_tree(ival, type);
655 else if (TREE_CODE(type) == REAL_TYPE)
658 real_from_mpfr(&r1, val, type, GMP_RNDN);
660 real_convert(&r2, TYPE_MODE(type), &r1);
661 return build_real(type, r2);
663 else if (TREE_CODE(type) == COMPLEX_TYPE)
666 real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
668 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
669 tree imag = build_real_from_int_cst(TREE_TYPE(type),
671 return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
677 // Return a tree for REAL/IMAG in TYPE.
680 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
682 if (type == error_mark_node)
683 return error_mark_node;
684 else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
685 return Expression::float_constant_tree(real, type);
686 else if (TREE_CODE(type) == COMPLEX_TYPE)
689 real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
691 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
694 real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
696 real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
698 return build_complex(type, build_real(TREE_TYPE(type), r2),
699 build_real(TREE_TYPE(type), r4));
705 // Return a tree which evaluates to true if VAL, of arbitrary integer
706 // type, is negative or is more than the maximum value of BOUND_TYPE.
707 // If SOFAR is not NULL, it is or'red into the result. The return
708 // value may be NULL if SOFAR is NULL.
711 Expression::check_bounds(tree val, tree bound_type, tree sofar,
714 tree val_type = TREE_TYPE(val);
715 tree ret = NULL_TREE;
717 if (!TYPE_UNSIGNED(val_type))
719 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
720 build_int_cst(val_type, 0));
721 if (ret == boolean_false_node)
725 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
726 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
727 go_assert(val_type_size != -1 && bound_type_size != -1);
728 if (val_type_size > bound_type_size
729 || (val_type_size == bound_type_size
730 && TYPE_UNSIGNED(val_type)
731 && !TYPE_UNSIGNED(bound_type)))
733 tree max = TYPE_MAX_VALUE(bound_type);
734 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
735 val, fold_convert_loc(loc.gcc_location(),
737 if (big == boolean_false_node)
739 else if (ret == NULL_TREE)
742 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
743 boolean_type_node, ret, big);
746 if (ret == NULL_TREE)
748 else if (sofar == NULL_TREE)
751 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
756 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
758 this->do_dump_expression(ast_dump_context);
761 // Error expressions. This are used to avoid cascading errors.
763 class Error_expression : public Expression
766 Error_expression(Location location)
767 : Expression(EXPRESSION_ERROR, location)
772 do_is_constant() const
776 do_numeric_constant_value(Numeric_constant* nc) const
778 nc->set_unsigned_long(NULL, 0);
783 do_discarding_value()
788 { return Type::make_error_type(); }
791 do_determine_type(const Type_context*)
799 do_is_addressable() const
803 do_get_tree(Translate_context*)
804 { return error_mark_node; }
807 do_dump_expression(Ast_dump_context*) const;
810 // Dump the ast representation for an error expression to a dump context.
813 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
815 ast_dump_context->ostream() << "_Error_" ;
819 Expression::make_error(Location location)
821 return new Error_expression(location);
824 // An expression which is really a type. This is used during parsing.
825 // It is an error if these survive after lowering.
828 Type_expression : public Expression
831 Type_expression(Type* type, Location location)
832 : Expression(EXPRESSION_TYPE, location),
838 do_traverse(Traverse* traverse)
839 { return Type::traverse(this->type_, traverse); }
843 { return this->type_; }
846 do_determine_type(const Type_context*)
850 do_check_types(Gogo*)
851 { this->report_error(_("invalid use of type")); }
858 do_get_tree(Translate_context*)
859 { go_unreachable(); }
861 void do_dump_expression(Ast_dump_context*) const;
864 // The type which we are representing as an expression.
869 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
871 ast_dump_context->dump_type(this->type_);
875 Expression::make_type(Type* type, Location location)
877 return new Type_expression(type, location);
880 // Class Parser_expression.
883 Parser_expression::do_type()
885 // We should never really ask for the type of a Parser_expression.
886 // However, it can happen, at least when we have an invalid const
887 // whose initializer refers to the const itself. In that case we
888 // may ask for the type when lowering the const itself.
889 go_assert(saw_errors());
890 return Type::make_error_type();
893 // Class Var_expression.
895 // Lower a variable expression. Here we just make sure that the
896 // initialization expression of the variable has been lowered. This
897 // ensures that we will be able to determine the type of the variable
901 Var_expression::do_lower(Gogo* gogo, Named_object* function,
902 Statement_inserter* inserter, int)
904 if (this->variable_->is_variable())
906 Variable* var = this->variable_->var_value();
907 // This is either a local variable or a global variable. A
908 // reference to a variable which is local to an enclosing
909 // function will be a reference to a field in a closure.
910 if (var->is_global())
915 var->lower_init_expression(gogo, function, inserter);
920 // Return the type of a reference to a variable.
923 Var_expression::do_type()
925 if (this->variable_->is_variable())
926 return this->variable_->var_value()->type();
927 else if (this->variable_->is_result_variable())
928 return this->variable_->result_var_value()->type();
933 // Determine the type of a reference to a variable.
936 Var_expression::do_determine_type(const Type_context*)
938 if (this->variable_->is_variable())
939 this->variable_->var_value()->determine_type();
942 // Something takes the address of this variable. This means that we
943 // may want to move the variable onto the heap.
946 Var_expression::do_address_taken(bool escapes)
950 if (this->variable_->is_variable())
951 this->variable_->var_value()->set_non_escaping_address_taken();
952 else if (this->variable_->is_result_variable())
953 this->variable_->result_var_value()->set_non_escaping_address_taken();
959 if (this->variable_->is_variable())
960 this->variable_->var_value()->set_address_taken();
961 else if (this->variable_->is_result_variable())
962 this->variable_->result_var_value()->set_address_taken();
968 // Get the tree for a reference to a variable.
971 Var_expression::do_get_tree(Translate_context* context)
973 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
974 context->function());
975 tree ret = var_to_tree(bvar);
976 if (ret == error_mark_node)
977 return error_mark_node;
979 if (this->variable_->is_variable())
980 is_in_heap = this->variable_->var_value()->is_in_heap();
981 else if (this->variable_->is_result_variable())
982 is_in_heap = this->variable_->result_var_value()->is_in_heap();
987 ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
988 TREE_THIS_NOTRAP(ret) = 1;
993 // Ast dump for variable expression.
996 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
998 ast_dump_context->ostream() << this->variable_->name() ;
1001 // Make a reference to a variable in an expression.
1004 Expression::make_var_reference(Named_object* var, Location location)
1007 return Expression::make_sink(location);
1009 // FIXME: Creating a new object for each reference to a variable is
1011 return new Var_expression(var, location);
1014 // Class Temporary_reference_expression.
1019 Temporary_reference_expression::do_type()
1021 return this->statement_->type();
1024 // Called if something takes the address of this temporary variable.
1025 // We never have to move temporary variables to the heap, but we do
1026 // need to know that they must live in the stack rather than in a
1030 Temporary_reference_expression::do_address_taken(bool)
1032 this->statement_->set_is_address_taken();
1035 // Get a tree referring to the variable.
1038 Temporary_reference_expression::do_get_tree(Translate_context* context)
1040 Bvariable* bvar = this->statement_->get_backend_variable(context);
1042 // The gcc backend can't represent the same set of recursive types
1043 // that the Go frontend can. In some cases this means that a
1044 // temporary variable won't have the right backend type. Correct
1045 // that here by adding a type cast. We need to use base() to push
1046 // the circularity down one level.
1047 tree ret = var_to_tree(bvar);
1048 if (!this->is_lvalue_
1049 && POINTER_TYPE_P(TREE_TYPE(ret))
1050 && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1052 Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1053 tree type_tree = type_to_tree(type_btype);
1054 ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1059 // Ast dump for temporary reference.
1062 Temporary_reference_expression::do_dump_expression(
1063 Ast_dump_context* ast_dump_context) const
1065 ast_dump_context->dump_temp_variable_name(this->statement_);
1068 // Make a reference to a temporary variable.
1070 Temporary_reference_expression*
1071 Expression::make_temporary_reference(Temporary_statement* statement,
1074 return new Temporary_reference_expression(statement, location);
1077 // Class Set_and_use_temporary_expression.
1082 Set_and_use_temporary_expression::do_type()
1084 return this->statement_->type();
1087 // Take the address.
1090 Set_and_use_temporary_expression::do_address_taken(bool)
1092 this->statement_->set_is_address_taken();
1095 // Return the backend representation.
1098 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1100 Bvariable* bvar = this->statement_->get_backend_variable(context);
1101 tree var_tree = var_to_tree(bvar);
1102 tree expr_tree = this->expr_->get_tree(context);
1103 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1104 return error_mark_node;
1105 Location loc = this->location();
1106 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1107 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1108 var_tree, expr_tree),
1115 Set_and_use_temporary_expression::do_dump_expression(
1116 Ast_dump_context* ast_dump_context) const
1118 ast_dump_context->ostream() << '(';
1119 ast_dump_context->dump_temp_variable_name(this->statement_);
1120 ast_dump_context->ostream() << " = ";
1121 this->expr_->dump_expression(ast_dump_context);
1122 ast_dump_context->ostream() << ')';
1125 // Make a set-and-use temporary.
1127 Set_and_use_temporary_expression*
1128 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1129 Expression* expr, Location location)
1131 return new Set_and_use_temporary_expression(statement, expr, location);
1134 // A sink expression--a use of the blank identifier _.
1136 class Sink_expression : public Expression
1139 Sink_expression(Location location)
1140 : Expression(EXPRESSION_SINK, location),
1141 type_(NULL), var_(NULL_TREE)
1146 do_discarding_value()
1153 do_determine_type(const Type_context*);
1157 { return new Sink_expression(this->location()); }
1160 do_get_tree(Translate_context*);
1163 do_dump_expression(Ast_dump_context*) const;
1166 // The type of this sink variable.
1168 // The temporary variable we generate.
1172 // Return the type of a sink expression.
1175 Sink_expression::do_type()
1177 if (this->type_ == NULL)
1178 return Type::make_sink_type();
1182 // Determine the type of a sink expression.
1185 Sink_expression::do_determine_type(const Type_context* context)
1187 if (context->type != NULL)
1188 this->type_ = context->type;
1191 // Return a temporary variable for a sink expression. This will
1192 // presumably be a write-only variable which the middle-end will drop.
1195 Sink_expression::do_get_tree(Translate_context* context)
1197 if (this->var_ == NULL_TREE)
1199 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1200 Btype* bt = this->type_->get_backend(context->gogo());
1201 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1206 // Ast dump for sink expression.
1209 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1211 ast_dump_context->ostream() << "_" ;
1214 // Make a sink expression.
1217 Expression::make_sink(Location location)
1219 return new Sink_expression(location);
1222 // Class Func_expression.
1224 // FIXME: Can a function expression appear in a constant expression?
1225 // The value is unchanging. Initializing a constant to the address of
1226 // a function seems like it could work, though there might be little
1232 Func_expression::do_traverse(Traverse* traverse)
1234 return (this->closure_ == NULL
1236 : Expression::traverse(&this->closure_, traverse));
1239 // Return the type of a function expression.
1242 Func_expression::do_type()
1244 if (this->function_->is_function())
1245 return this->function_->func_value()->type();
1246 else if (this->function_->is_function_declaration())
1247 return this->function_->func_declaration_value()->type();
1252 // Get the tree for a function expression without evaluating the
1256 Func_expression::get_tree_without_closure(Gogo* gogo)
1258 Function_type* fntype;
1259 if (this->function_->is_function())
1260 fntype = this->function_->func_value()->type();
1261 else if (this->function_->is_function_declaration())
1262 fntype = this->function_->func_declaration_value()->type();
1266 // Builtin functions are handled specially by Call_expression. We
1267 // can't take their address.
1268 if (fntype->is_builtin())
1270 error_at(this->location(),
1271 "invalid use of special builtin function %qs; must be called",
1272 this->function_->name().c_str());
1273 return error_mark_node;
1276 Named_object* no = this->function_;
1278 tree id = no->get_id(gogo);
1279 if (id == error_mark_node)
1280 return error_mark_node;
1283 if (no->is_function())
1284 fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1285 else if (no->is_function_declaration())
1286 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1290 if (fndecl == error_mark_node)
1291 return error_mark_node;
1293 return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1296 // Get the tree for a function expression. This is used when we take
1297 // the address of a function rather than simply calling it. If the
1298 // function has a closure, we must use a trampoline.
1301 Func_expression::do_get_tree(Translate_context* context)
1303 Gogo* gogo = context->gogo();
1305 tree fnaddr = this->get_tree_without_closure(gogo);
1306 if (fnaddr == error_mark_node)
1307 return error_mark_node;
1309 go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1310 && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1311 TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1313 // For a normal non-nested function call, that is all we have to do.
1314 if (!this->function_->is_function()
1315 || this->function_->func_value()->enclosing() == NULL)
1317 go_assert(this->closure_ == NULL);
1321 // For a nested function call, we have to always allocate a
1322 // trampoline. If we don't always allocate, then closures will not
1323 // be reliably distinct.
1324 Expression* closure = this->closure_;
1326 if (closure == NULL)
1327 closure_tree = null_pointer_node;
1330 // Get the value of the closure. This will be a pointer to
1331 // space allocated on the heap.
1332 closure_tree = closure->get_tree(context);
1333 if (closure_tree == error_mark_node)
1334 return error_mark_node;
1335 go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1338 // Now we need to build some code on the heap. This code will load
1339 // the static chain pointer with the closure and then jump to the
1340 // body of the function. The normal gcc approach is to build the
1341 // code on the stack. Unfortunately we can not do that, as Go
1342 // permits us to return the function pointer.
1344 return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1347 // Ast dump for function.
1350 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1352 ast_dump_context->ostream() << this->function_->name();
1353 if (this->closure_ != NULL)
1355 ast_dump_context->ostream() << " {closure = ";
1356 this->closure_->dump_expression(ast_dump_context);
1357 ast_dump_context->ostream() << "}";
1361 // Make a reference to a function in an expression.
1364 Expression::make_func_reference(Named_object* function, Expression* closure,
1367 return new Func_expression(function, closure, location);
1370 // Class Unknown_expression.
1372 // Return the name of an unknown expression.
1375 Unknown_expression::name() const
1377 return this->named_object_->name();
1380 // Lower a reference to an unknown name.
1383 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1385 Location location = this->location();
1386 Named_object* no = this->named_object_;
1388 if (!no->is_unknown())
1392 real = no->unknown_value()->real_named_object();
1395 if (this->is_composite_literal_key_)
1397 if (!this->no_error_message_)
1398 error_at(location, "reference to undefined name %qs",
1399 this->named_object_->message_name().c_str());
1400 return Expression::make_error(location);
1403 switch (real->classification())
1405 case Named_object::NAMED_OBJECT_CONST:
1406 return Expression::make_const_reference(real, location);
1407 case Named_object::NAMED_OBJECT_TYPE:
1408 return Expression::make_type(real->type_value(), location);
1409 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1410 if (this->is_composite_literal_key_)
1412 if (!this->no_error_message_)
1413 error_at(location, "reference to undefined type %qs",
1414 real->message_name().c_str());
1415 return Expression::make_error(location);
1416 case Named_object::NAMED_OBJECT_VAR:
1417 real->var_value()->set_is_used();
1418 return Expression::make_var_reference(real, location);
1419 case Named_object::NAMED_OBJECT_FUNC:
1420 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1421 return Expression::make_func_reference(real, NULL, location);
1422 case Named_object::NAMED_OBJECT_PACKAGE:
1423 if (this->is_composite_literal_key_)
1425 if (!this->no_error_message_)
1426 error_at(location, "unexpected reference to package");
1427 return Expression::make_error(location);
1433 // Dump the ast representation for an unknown expression to a dump context.
1436 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1438 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1442 // Make a reference to an unknown name.
1445 Expression::make_unknown_reference(Named_object* no, Location location)
1447 return new Unknown_expression(no, location);
1450 // A boolean expression.
1452 class Boolean_expression : public Expression
1455 Boolean_expression(bool val, Location location)
1456 : Expression(EXPRESSION_BOOLEAN, location),
1457 val_(val), type_(NULL)
1465 do_is_constant() const
1472 do_determine_type(const Type_context*);
1479 do_get_tree(Translate_context*)
1480 { return this->val_ ? boolean_true_node : boolean_false_node; }
1483 do_export(Export* exp) const
1484 { exp->write_c_string(this->val_ ? "true" : "false"); }
1487 do_dump_expression(Ast_dump_context* ast_dump_context) const
1488 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1493 // The type as determined by context.
1500 Boolean_expression::do_type()
1502 if (this->type_ == NULL)
1503 this->type_ = Type::make_boolean_type();
1507 // Set the type from the context.
1510 Boolean_expression::do_determine_type(const Type_context* context)
1512 if (this->type_ != NULL && !this->type_->is_abstract())
1514 else if (context->type != NULL && context->type->is_boolean_type())
1515 this->type_ = context->type;
1516 else if (!context->may_be_abstract)
1517 this->type_ = Type::lookup_bool_type();
1520 // Import a boolean constant.
1523 Boolean_expression::do_import(Import* imp)
1525 if (imp->peek_char() == 't')
1527 imp->require_c_string("true");
1528 return Expression::make_boolean(true, imp->location());
1532 imp->require_c_string("false");
1533 return Expression::make_boolean(false, imp->location());
1537 // Make a boolean expression.
1540 Expression::make_boolean(bool val, Location location)
1542 return new Boolean_expression(val, location);
1545 // Class String_expression.
1550 String_expression::do_type()
1552 if (this->type_ == NULL)
1553 this->type_ = Type::make_string_type();
1557 // Set the type from the context.
1560 String_expression::do_determine_type(const Type_context* context)
1562 if (this->type_ != NULL && !this->type_->is_abstract())
1564 else if (context->type != NULL && context->type->is_string_type())
1565 this->type_ = context->type;
1566 else if (!context->may_be_abstract)
1567 this->type_ = Type::lookup_string_type();
1570 // Build a string constant.
1573 String_expression::do_get_tree(Translate_context* context)
1575 return context->gogo()->go_string_constant_tree(this->val_);
1578 // Write string literal to string dump.
1581 String_expression::export_string(String_dump* exp,
1582 const String_expression* str)
1585 s.reserve(str->val_.length() * 4 + 2);
1587 for (std::string::const_iterator p = str->val_.begin();
1588 p != str->val_.end();
1591 if (*p == '\\' || *p == '"')
1596 else if (*p >= 0x20 && *p < 0x7f)
1598 else if (*p == '\n')
1600 else if (*p == '\t')
1605 unsigned char c = *p;
1606 unsigned int dig = c >> 4;
1607 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1609 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1613 exp->write_string(s);
1616 // Export a string expression.
1619 String_expression::do_export(Export* exp) const
1621 String_expression::export_string(exp, this);
1624 // Import a string expression.
1627 String_expression::do_import(Import* imp)
1629 imp->require_c_string("\"");
1633 int c = imp->get_char();
1634 if (c == '"' || c == -1)
1637 val += static_cast<char>(c);
1640 c = imp->get_char();
1641 if (c == '\\' || c == '"')
1642 val += static_cast<char>(c);
1649 c = imp->get_char();
1650 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1651 c = imp->get_char();
1652 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1653 char v = (vh << 4) | vl;
1658 error_at(imp->location(), "bad string constant");
1659 return Expression::make_error(imp->location());
1663 return Expression::make_string(val, imp->location());
1666 // Ast dump for string expression.
1669 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1671 String_expression::export_string(ast_dump_context, this);
1674 // Make a string expression.
1677 Expression::make_string(const std::string& val, Location location)
1679 return new String_expression(val, location);
1682 // Make an integer expression.
1684 class Integer_expression : public Expression
1687 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1689 : Expression(EXPRESSION_INTEGER, location),
1690 type_(type), is_character_constant_(is_character_constant)
1691 { mpz_init_set(this->val_, *val); }
1696 // Write VAL to string dump.
1698 export_integer(String_dump* exp, const mpz_t val);
1700 // Write VAL to dump context.
1702 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1706 do_is_constant() const
1710 do_numeric_constant_value(Numeric_constant* nc) const;
1716 do_determine_type(const Type_context* context);
1719 do_check_types(Gogo*);
1722 do_get_tree(Translate_context*);
1727 if (this->is_character_constant_)
1728 return Expression::make_character(&this->val_, this->type_,
1731 return Expression::make_integer(&this->val_, this->type_,
1736 do_export(Export*) const;
1739 do_dump_expression(Ast_dump_context*) const;
1742 // The integer value.
1746 // Whether this is a character constant.
1747 bool is_character_constant_;
1750 // Return a numeric constant for this expression. We have to mark
1751 // this as a character when appropriate.
1754 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1756 if (this->is_character_constant_)
1757 nc->set_rune(this->type_, this->val_);
1759 nc->set_int(this->type_, this->val_);
1763 // Return the current type. If we haven't set the type yet, we return
1764 // an abstract integer type.
1767 Integer_expression::do_type()
1769 if (this->type_ == NULL)
1771 if (this->is_character_constant_)
1772 this->type_ = Type::make_abstract_character_type();
1774 this->type_ = Type::make_abstract_integer_type();
1779 // Set the type of the integer value. Here we may switch from an
1780 // abstract type to a real type.
1783 Integer_expression::do_determine_type(const Type_context* context)
1785 if (this->type_ != NULL && !this->type_->is_abstract())
1787 else if (context->type != NULL && context->type->is_numeric_type())
1788 this->type_ = context->type;
1789 else if (!context->may_be_abstract)
1791 if (this->is_character_constant_)
1792 this->type_ = Type::lookup_integer_type("int32");
1794 this->type_ = Type::lookup_integer_type("int");
1798 // Check the type of an integer constant.
1801 Integer_expression::do_check_types(Gogo*)
1803 Type* type = this->type_;
1806 Numeric_constant nc;
1807 if (this->is_character_constant_)
1808 nc.set_rune(NULL, this->val_);
1810 nc.set_int(NULL, this->val_);
1811 if (!nc.set_type(type, true, this->location()))
1812 this->set_is_error();
1815 // Get a tree for an integer constant.
1818 Integer_expression::do_get_tree(Translate_context* context)
1820 Gogo* gogo = context->gogo();
1822 if (this->type_ != NULL && !this->type_->is_abstract())
1823 type = type_to_tree(this->type_->get_backend(gogo));
1824 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1826 // We are converting to an abstract floating point type.
1827 Type* ftype = Type::lookup_float_type("float64");
1828 type = type_to_tree(ftype->get_backend(gogo));
1830 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1832 // We are converting to an abstract complex type.
1833 Type* ctype = Type::lookup_complex_type("complex128");
1834 type = type_to_tree(ctype->get_backend(gogo));
1838 // If we still have an abstract type here, then this is being
1839 // used in a constant expression which didn't get reduced for
1840 // some reason. Use a type which will fit the value. We use <,
1841 // not <=, because we need an extra bit for the sign bit.
1842 int bits = mpz_sizeinbase(this->val_, 2);
1843 if (bits < INT_TYPE_SIZE)
1845 Type* t = Type::lookup_integer_type("int");
1846 type = type_to_tree(t->get_backend(gogo));
1850 Type* t = Type::lookup_integer_type("int64");
1851 type = type_to_tree(t->get_backend(gogo));
1854 type = long_long_integer_type_node;
1856 return Expression::integer_constant_tree(this->val_, type);
1859 // Write VAL to export data.
1862 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1864 char* s = mpz_get_str(NULL, 10, val);
1865 exp->write_c_string(s);
1869 // Export an integer in a constant expression.
1872 Integer_expression::do_export(Export* exp) const
1874 Integer_expression::export_integer(exp, this->val_);
1875 if (this->is_character_constant_)
1876 exp->write_c_string("'");
1877 // A trailing space lets us reliably identify the end of the number.
1878 exp->write_c_string(" ");
1881 // Import an integer, floating point, or complex value. This handles
1882 // all these types because they all start with digits.
1885 Integer_expression::do_import(Import* imp)
1887 std::string num = imp->read_identifier();
1888 imp->require_c_string(" ");
1889 if (!num.empty() && num[num.length() - 1] == 'i')
1892 size_t plus_pos = num.find('+', 1);
1893 size_t minus_pos = num.find('-', 1);
1895 if (plus_pos == std::string::npos)
1897 else if (minus_pos == std::string::npos)
1901 error_at(imp->location(), "bad number in import data: %qs",
1903 return Expression::make_error(imp->location());
1905 if (pos == std::string::npos)
1906 mpfr_set_ui(real, 0, GMP_RNDN);
1909 std::string real_str = num.substr(0, pos);
1910 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1912 error_at(imp->location(), "bad number in import data: %qs",
1914 return Expression::make_error(imp->location());
1918 std::string imag_str;
1919 if (pos == std::string::npos)
1922 imag_str = num.substr(pos);
1923 imag_str = imag_str.substr(0, imag_str.size() - 1);
1925 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1927 error_at(imp->location(), "bad number in import data: %qs",
1929 return Expression::make_error(imp->location());
1931 Expression* ret = Expression::make_complex(&real, &imag, NULL,
1937 else if (num.find('.') == std::string::npos
1938 && num.find('E') == std::string::npos)
1940 bool is_character_constant = (!num.empty()
1941 && num[num.length() - 1] == '\'');
1942 if (is_character_constant)
1943 num = num.substr(0, num.length() - 1);
1945 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1947 error_at(imp->location(), "bad number in import data: %qs",
1949 return Expression::make_error(imp->location());
1952 if (is_character_constant)
1953 ret = Expression::make_character(&val, NULL, imp->location());
1955 ret = Expression::make_integer(&val, NULL, imp->location());
1962 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1964 error_at(imp->location(), "bad number in import data: %qs",
1966 return Expression::make_error(imp->location());
1968 Expression* ret = Expression::make_float(&val, NULL, imp->location());
1973 // Ast dump for integer expression.
1976 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1978 if (this->is_character_constant_)
1979 ast_dump_context->ostream() << '\'';
1980 Integer_expression::export_integer(ast_dump_context, this->val_);
1981 if (this->is_character_constant_)
1982 ast_dump_context->ostream() << '\'';
1985 // Build a new integer value.
1988 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1990 return new Integer_expression(val, type, false, location);
1993 // Build a new character constant value.
1996 Expression::make_character(const mpz_t* val, Type* type, Location location)
1998 return new Integer_expression(val, type, true, location);
2003 class Float_expression : public Expression
2006 Float_expression(const mpfr_t* val, Type* type, Location location)
2007 : Expression(EXPRESSION_FLOAT, location),
2010 mpfr_init_set(this->val_, *val, GMP_RNDN);
2013 // Write VAL to export data.
2015 export_float(String_dump* exp, const mpfr_t val);
2017 // Write VAL to dump file.
2019 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2023 do_is_constant() const
2027 do_numeric_constant_value(Numeric_constant* nc) const
2029 nc->set_float(this->type_, this->val_);
2037 do_determine_type(const Type_context*);
2040 do_check_types(Gogo*);
2044 { return Expression::make_float(&this->val_, this->type_,
2045 this->location()); }
2048 do_get_tree(Translate_context*);
2051 do_export(Export*) const;
2054 do_dump_expression(Ast_dump_context*) const;
2057 // The floating point value.
2063 // Return the current type. If we haven't set the type yet, we return
2064 // an abstract float type.
2067 Float_expression::do_type()
2069 if (this->type_ == NULL)
2070 this->type_ = Type::make_abstract_float_type();
2074 // Set the type of the float value. Here we may switch from an
2075 // abstract type to a real type.
2078 Float_expression::do_determine_type(const Type_context* context)
2080 if (this->type_ != NULL && !this->type_->is_abstract())
2082 else if (context->type != NULL
2083 && (context->type->integer_type() != NULL
2084 || context->type->float_type() != NULL
2085 || context->type->complex_type() != NULL))
2086 this->type_ = context->type;
2087 else if (!context->may_be_abstract)
2088 this->type_ = Type::lookup_float_type("float64");
2091 // Check the type of a float value.
2094 Float_expression::do_check_types(Gogo*)
2096 Type* type = this->type_;
2099 Numeric_constant nc;
2100 nc.set_float(NULL, this->val_);
2101 if (!nc.set_type(this->type_, true, this->location()))
2102 this->set_is_error();
2105 // Get a tree for a float constant.
2108 Float_expression::do_get_tree(Translate_context* context)
2110 Gogo* gogo = context->gogo();
2112 if (this->type_ != NULL && !this->type_->is_abstract())
2113 type = type_to_tree(this->type_->get_backend(gogo));
2114 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2116 // We have an abstract integer type. We just hope for the best.
2117 type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2121 // If we still have an abstract type here, then this is being
2122 // used in a constant expression which didn't get reduced. We
2123 // just use float64 and hope for the best.
2124 Type* ft = Type::lookup_float_type("float64");
2125 type = type_to_tree(ft->get_backend(gogo));
2127 return Expression::float_constant_tree(this->val_, type);
2130 // Write a floating point number to a string dump.
2133 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2136 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2138 exp->write_c_string("-");
2139 exp->write_c_string("0.");
2140 exp->write_c_string(*s == '-' ? s + 1 : s);
2143 snprintf(buf, sizeof buf, "E%ld", exponent);
2144 exp->write_c_string(buf);
2147 // Export a floating point number in a constant expression.
2150 Float_expression::do_export(Export* exp) const
2152 Float_expression::export_float(exp, this->val_);
2153 // A trailing space lets us reliably identify the end of the number.
2154 exp->write_c_string(" ");
2157 // Dump a floating point number to the dump file.
2160 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2162 Float_expression::export_float(ast_dump_context, this->val_);
2165 // Make a float expression.
2168 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2170 return new Float_expression(val, type, location);
2175 class Complex_expression : public Expression
2178 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2180 : Expression(EXPRESSION_COMPLEX, location),
2183 mpfr_init_set(this->real_, *real, GMP_RNDN);
2184 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2187 // Write REAL/IMAG to string dump.
2189 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2191 // Write REAL/IMAG to dump context.
2193 dump_complex(Ast_dump_context* ast_dump_context,
2194 const mpfr_t real, const mpfr_t val);
2198 do_is_constant() const
2202 do_numeric_constant_value(Numeric_constant* nc) const
2204 nc->set_complex(this->type_, this->real_, this->imag_);
2212 do_determine_type(const Type_context*);
2215 do_check_types(Gogo*);
2220 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2225 do_get_tree(Translate_context*);
2228 do_export(Export*) const;
2231 do_dump_expression(Ast_dump_context*) const;
2236 // The imaginary part;
2238 // The type if known.
2242 // Return the current type. If we haven't set the type yet, we return
2243 // an abstract complex type.
2246 Complex_expression::do_type()
2248 if (this->type_ == NULL)
2249 this->type_ = Type::make_abstract_complex_type();
2253 // Set the type of the complex value. Here we may switch from an
2254 // abstract type to a real type.
2257 Complex_expression::do_determine_type(const Type_context* context)
2259 if (this->type_ != NULL && !this->type_->is_abstract())
2261 else if (context->type != NULL
2262 && context->type->complex_type() != NULL)
2263 this->type_ = context->type;
2264 else if (!context->may_be_abstract)
2265 this->type_ = Type::lookup_complex_type("complex128");
2268 // Check the type of a complex value.
2271 Complex_expression::do_check_types(Gogo*)
2273 Type* type = this->type_;
2276 Numeric_constant nc;
2277 nc.set_complex(NULL, this->real_, this->imag_);
2278 if (!nc.set_type(this->type_, true, this->location()))
2279 this->set_is_error();
2282 // Get a tree for a complex constant.
2285 Complex_expression::do_get_tree(Translate_context* context)
2287 Gogo* gogo = context->gogo();
2289 if (this->type_ != NULL && !this->type_->is_abstract())
2290 type = type_to_tree(this->type_->get_backend(gogo));
2293 // If we still have an abstract type here, this this is being
2294 // used in a constant expression which didn't get reduced. We
2295 // just use complex128 and hope for the best.
2296 Type* ct = Type::lookup_complex_type("complex128");
2297 type = type_to_tree(ct->get_backend(gogo));
2299 return Expression::complex_constant_tree(this->real_, this->imag_, type);
2302 // Write REAL/IMAG to export data.
2305 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2308 if (!mpfr_zero_p(real))
2310 Float_expression::export_float(exp, real);
2311 if (mpfr_sgn(imag) > 0)
2312 exp->write_c_string("+");
2314 Float_expression::export_float(exp, imag);
2315 exp->write_c_string("i");
2318 // Export a complex number in a constant expression.
2321 Complex_expression::do_export(Export* exp) const
2323 Complex_expression::export_complex(exp, this->real_, this->imag_);
2324 // A trailing space lets us reliably identify the end of the number.
2325 exp->write_c_string(" ");
2328 // Dump a complex expression to the dump file.
2331 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2333 Complex_expression::export_complex(ast_dump_context,
2338 // Make a complex expression.
2341 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2344 return new Complex_expression(real, imag, type, location);
2347 // Find a named object in an expression.
2349 class Find_named_object : public Traverse
2352 Find_named_object(Named_object* no)
2353 : Traverse(traverse_expressions),
2354 no_(no), found_(false)
2357 // Whether we found the object.
2360 { return this->found_; }
2364 expression(Expression**);
2367 // The object we are looking for.
2369 // Whether we found it.
2373 // A reference to a const in an expression.
2375 class Const_expression : public Expression
2378 Const_expression(Named_object* constant, Location location)
2379 : Expression(EXPRESSION_CONST_REFERENCE, location),
2380 constant_(constant), type_(NULL), seen_(false)
2385 { return this->constant_; }
2387 // Check that the initializer does not refer to the constant itself.
2389 check_for_init_loop();
2393 do_traverse(Traverse*);
2396 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2399 do_is_constant() const
2403 do_numeric_constant_value(Numeric_constant* nc) const;
2406 do_string_constant_value(std::string* val) const
2407 { return this->constant_->const_value()->expr()->string_constant_value(val); }
2412 // The type of a const is set by the declaration, not the use.
2414 do_determine_type(const Type_context*);
2417 do_check_types(Gogo*);
2424 do_get_tree(Translate_context* context);
2426 // When exporting a reference to a const as part of a const
2427 // expression, we export the value. We ignore the fact that it has
2430 do_export(Export* exp) const
2431 { this->constant_->const_value()->expr()->export_expression(exp); }
2434 do_dump_expression(Ast_dump_context*) const;
2438 Named_object* constant_;
2439 // The type of this reference. This is used if the constant has an
2442 // Used to prevent infinite recursion when a constant incorrectly
2443 // refers to itself.
2450 Const_expression::do_traverse(Traverse* traverse)
2452 if (this->type_ != NULL)
2453 return Type::traverse(this->type_, traverse);
2454 return TRAVERSE_CONTINUE;
2457 // Lower a constant expression. This is where we convert the
2458 // predeclared constant iota into an integer value.
2461 Const_expression::do_lower(Gogo* gogo, Named_object*,
2462 Statement_inserter*, int iota_value)
2464 if (this->constant_->const_value()->expr()->classification()
2467 if (iota_value == -1)
2469 error_at(this->location(),
2470 "iota is only defined in const declarations");
2474 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2475 Expression* ret = Expression::make_integer(&val, NULL,
2481 // Make sure that the constant itself has been lowered.
2482 gogo->lower_constant(this->constant_);
2487 // Return a numeric constant value.
2490 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2495 Expression* e = this->constant_->const_value()->expr();
2499 bool r = e->numeric_constant_value(nc);
2501 this->seen_ = false;
2504 if (this->type_ != NULL)
2505 ctype = this->type_;
2507 ctype = this->constant_->const_value()->type();
2508 if (r && ctype != NULL)
2510 if (!nc->set_type(ctype, false, this->location()))
2517 // Return the type of the const reference.
2520 Const_expression::do_type()
2522 if (this->type_ != NULL)
2525 Named_constant* nc = this->constant_->const_value();
2527 if (this->seen_ || nc->lowering())
2529 this->report_error(_("constant refers to itself"));
2530 this->type_ = Type::make_error_type();
2536 Type* ret = nc->type();
2540 this->seen_ = false;
2544 // During parsing, a named constant may have a NULL type, but we
2545 // must not return a NULL type here.
2546 ret = nc->expr()->type();
2548 this->seen_ = false;
2553 // Set the type of the const reference.
2556 Const_expression::do_determine_type(const Type_context* context)
2558 Type* ctype = this->constant_->const_value()->type();
2559 Type* cetype = (ctype != NULL
2561 : this->constant_->const_value()->expr()->type());
2562 if (ctype != NULL && !ctype->is_abstract())
2564 else if (context->type != NULL
2565 && context->type->is_numeric_type()
2566 && cetype->is_numeric_type())
2567 this->type_ = context->type;
2568 else if (context->type != NULL
2569 && context->type->is_string_type()
2570 && cetype->is_string_type())
2571 this->type_ = context->type;
2572 else if (context->type != NULL
2573 && context->type->is_boolean_type()
2574 && cetype->is_boolean_type())
2575 this->type_ = context->type;
2576 else if (!context->may_be_abstract)
2578 if (cetype->is_abstract())
2579 cetype = cetype->make_non_abstract_type();
2580 this->type_ = cetype;
2584 // Check for a loop in which the initializer of a constant refers to
2585 // the constant itself.
2588 Const_expression::check_for_init_loop()
2590 if (this->type_ != NULL && this->type_->is_error())
2595 this->report_error(_("constant refers to itself"));
2596 this->type_ = Type::make_error_type();
2600 Expression* init = this->constant_->const_value()->expr();
2601 Find_named_object find_named_object(this->constant_);
2604 Expression::traverse(&init, &find_named_object);
2605 this->seen_ = false;
2607 if (find_named_object.found())
2609 if (this->type_ == NULL || !this->type_->is_error())
2611 this->report_error(_("constant refers to itself"));
2612 this->type_ = Type::make_error_type();
2618 // Check types of a const reference.
2621 Const_expression::do_check_types(Gogo*)
2623 if (this->type_ != NULL && this->type_->is_error())
2626 this->check_for_init_loop();
2628 // Check that numeric constant fits in type.
2629 if (this->type_ != NULL && this->type_->is_numeric_type())
2631 Numeric_constant nc;
2632 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2634 if (!nc.set_type(this->type_, true, this->location()))
2635 this->set_is_error();
2640 // Return a tree for the const reference.
2643 Const_expression::do_get_tree(Translate_context* context)
2645 Gogo* gogo = context->gogo();
2647 if (this->type_ == NULL)
2648 type_tree = NULL_TREE;
2651 type_tree = type_to_tree(this->type_->get_backend(gogo));
2652 if (type_tree == error_mark_node)
2653 return error_mark_node;
2656 // If the type has been set for this expression, but the underlying
2657 // object is an abstract int or float, we try to get the abstract
2658 // value. Otherwise we may lose something in the conversion.
2659 if (this->type_ != NULL
2660 && this->type_->is_numeric_type()
2661 && (this->constant_->const_value()->type() == NULL
2662 || this->constant_->const_value()->type()->is_abstract()))
2664 Expression* expr = this->constant_->const_value()->expr();
2665 Numeric_constant nc;
2666 if (expr->numeric_constant_value(&nc)
2667 && nc.set_type(this->type_, false, this->location()))
2669 Expression* e = nc.expression(this->location());
2670 return e->get_tree(context);
2674 tree const_tree = this->constant_->get_tree(gogo, context->function());
2675 if (this->type_ == NULL
2676 || const_tree == error_mark_node
2677 || TREE_TYPE(const_tree) == error_mark_node)
2681 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2682 ret = fold_convert(type_tree, const_tree);
2683 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2684 ret = fold(convert_to_integer(type_tree, const_tree));
2685 else if (TREE_CODE(type_tree) == REAL_TYPE)
2686 ret = fold(convert_to_real(type_tree, const_tree));
2687 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2688 ret = fold(convert_to_complex(type_tree, const_tree));
2694 // Dump ast representation for constant expression.
2697 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2699 ast_dump_context->ostream() << this->constant_->name();
2702 // Make a reference to a constant in an expression.
2705 Expression::make_const_reference(Named_object* constant,
2708 return new Const_expression(constant, location);
2711 // Find a named object in an expression.
2714 Find_named_object::expression(Expression** pexpr)
2716 switch ((*pexpr)->classification())
2718 case Expression::EXPRESSION_CONST_REFERENCE:
2720 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2721 if (ce->named_object() == this->no_)
2724 // We need to check a constant initializer explicitly, as
2725 // loops here will not be caught by the loop checking for
2726 // variable initializers.
2727 ce->check_for_init_loop();
2729 return TRAVERSE_CONTINUE;
2732 case Expression::EXPRESSION_VAR_REFERENCE:
2733 if ((*pexpr)->var_expression()->named_object() == this->no_)
2735 return TRAVERSE_CONTINUE;
2736 case Expression::EXPRESSION_FUNC_REFERENCE:
2737 if ((*pexpr)->func_expression()->named_object() == this->no_)
2739 return TRAVERSE_CONTINUE;
2741 return TRAVERSE_CONTINUE;
2743 this->found_ = true;
2744 return TRAVERSE_EXIT;
2749 class Nil_expression : public Expression
2752 Nil_expression(Location location)
2753 : Expression(EXPRESSION_NIL, location)
2761 do_is_constant() const
2766 { return Type::make_nil_type(); }
2769 do_determine_type(const Type_context*)
2777 do_get_tree(Translate_context*)
2778 { return null_pointer_node; }
2781 do_export(Export* exp) const
2782 { exp->write_c_string("nil"); }
2785 do_dump_expression(Ast_dump_context* ast_dump_context) const
2786 { ast_dump_context->ostream() << "nil"; }
2789 // Import a nil expression.
2792 Nil_expression::do_import(Import* imp)
2794 imp->require_c_string("nil");
2795 return Expression::make_nil(imp->location());
2798 // Make a nil expression.
2801 Expression::make_nil(Location location)
2803 return new Nil_expression(location);
2806 // The value of the predeclared constant iota. This is little more
2807 // than a marker. This will be lowered to an integer in
2808 // Const_expression::do_lower, which is where we know the value that
2811 class Iota_expression : public Parser_expression
2814 Iota_expression(Location location)
2815 : Parser_expression(EXPRESSION_IOTA, location)
2820 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2821 { go_unreachable(); }
2823 // There should only ever be one of these.
2826 { go_unreachable(); }
2829 do_dump_expression(Ast_dump_context* ast_dump_context) const
2830 { ast_dump_context->ostream() << "iota"; }
2833 // Make an iota expression. This is only called for one case: the
2834 // value of the predeclared constant iota.
2837 Expression::make_iota()
2839 static Iota_expression iota_expression(Linemap::unknown_location());
2840 return &iota_expression;
2843 // A type conversion expression.
2845 class Type_conversion_expression : public Expression
2848 Type_conversion_expression(Type* type, Expression* expr,
2850 : Expression(EXPRESSION_CONVERSION, location),
2851 type_(type), expr_(expr), may_convert_function_types_(false)
2854 // Return the type to which we are converting.
2857 { return this->type_; }
2859 // Return the expression which we are converting.
2862 { return this->expr_; }
2864 // Permit converting from one function type to another. This is
2865 // used internally for method expressions.
2867 set_may_convert_function_types()
2869 this->may_convert_function_types_ = true;
2872 // Import a type conversion expression.
2878 do_traverse(Traverse* traverse);
2881 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2884 do_is_constant() const
2885 { return this->expr_->is_constant(); }
2888 do_numeric_constant_value(Numeric_constant*) const;
2891 do_string_constant_value(std::string*) const;
2895 { return this->type_; }
2898 do_determine_type(const Type_context*)
2900 Type_context subcontext(this->type_, false);
2901 this->expr_->determine_type(&subcontext);
2905 do_check_types(Gogo*);
2910 return new Type_conversion_expression(this->type_, this->expr_->copy(),
2915 do_get_tree(Translate_context* context);
2918 do_export(Export*) const;
2921 do_dump_expression(Ast_dump_context*) const;
2924 // The type to convert to.
2926 // The expression to convert.
2928 // True if this is permitted to convert function types. This is
2929 // used internally for method expressions.
2930 bool may_convert_function_types_;
2936 Type_conversion_expression::do_traverse(Traverse* traverse)
2938 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2939 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2940 return TRAVERSE_EXIT;
2941 return TRAVERSE_CONTINUE;
2944 // Convert to a constant at lowering time.
2947 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2948 Statement_inserter*, int)
2950 Type* type = this->type_;
2951 Expression* val = this->expr_;
2952 Location location = this->location();
2954 if (type->is_numeric_type())
2956 Numeric_constant nc;
2957 if (val->numeric_constant_value(&nc))
2959 if (!nc.set_type(type, true, location))
2960 return Expression::make_error(location);
2961 return nc.expression(location);
2965 if (type->is_slice_type())
2967 Type* element_type = type->array_type()->element_type()->forwarded();
2968 bool is_byte = (element_type->integer_type() != NULL
2969 && element_type->integer_type()->is_byte());
2970 bool is_rune = (element_type->integer_type() != NULL
2971 && element_type->integer_type()->is_rune());
2972 if (is_byte || is_rune)
2975 if (val->string_constant_value(&s))
2977 Expression_list* vals = new Expression_list();
2980 for (std::string::const_iterator p = s.begin();
2985 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
2986 Expression* v = Expression::make_integer(&val,
2995 const char *p = s.data();
2996 const char *pend = s.data() + s.length();
3000 int adv = Lex::fetch_char(p, &c);
3003 warning_at(this->location(), 0,
3004 "invalid UTF-8 encoding");
3009 mpz_init_set_ui(val, c);
3010 Expression* v = Expression::make_integer(&val,
3018 return Expression::make_slice_composite_literal(type, vals,
3027 // Return the constant numeric value if there is one.
3030 Type_conversion_expression::do_numeric_constant_value(
3031 Numeric_constant* nc) const
3033 if (!this->type_->is_numeric_type())
3035 if (!this->expr_->numeric_constant_value(nc))
3037 return nc->set_type(this->type_, false, this->location());
3040 // Return the constant string value if there is one.
3043 Type_conversion_expression::do_string_constant_value(std::string* val) const
3045 if (this->type_->is_string_type()
3046 && this->expr_->type()->integer_type() != NULL)
3048 Numeric_constant nc;
3049 if (this->expr_->numeric_constant_value(&nc))
3052 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3055 Lex::append_char(ival, true, val, this->location());
3061 // FIXME: Could handle conversion from const []int here.
3066 // Check that types are convertible.
3069 Type_conversion_expression::do_check_types(Gogo*)
3071 Type* type = this->type_;
3072 Type* expr_type = this->expr_->type();
3075 if (type->is_error() || expr_type->is_error())
3077 this->set_is_error();
3081 if (this->may_convert_function_types_
3082 && type->function_type() != NULL
3083 && expr_type->function_type() != NULL)
3086 if (Type::are_convertible(type, expr_type, &reason))
3089 error_at(this->location(), "%s", reason.c_str());
3090 this->set_is_error();
3093 // Get a tree for a type conversion.
3096 Type_conversion_expression::do_get_tree(Translate_context* context)
3098 Gogo* gogo = context->gogo();
3099 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3100 tree expr_tree = this->expr_->get_tree(context);
3102 if (type_tree == error_mark_node
3103 || expr_tree == error_mark_node
3104 || TREE_TYPE(expr_tree) == error_mark_node)
3105 return error_mark_node;
3107 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3108 return fold_convert(type_tree, expr_tree);
3110 Type* type = this->type_;
3111 Type* expr_type = this->expr_->type();
3113 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3114 ret = Expression::convert_for_assignment(context, type, expr_type,
3115 expr_tree, this->location());
3116 else if (type->integer_type() != NULL)
3118 if (expr_type->integer_type() != NULL
3119 || expr_type->float_type() != NULL
3120 || expr_type->is_unsafe_pointer_type())
3121 ret = fold(convert_to_integer(type_tree, expr_tree));
3125 else if (type->float_type() != NULL)
3127 if (expr_type->integer_type() != NULL
3128 || expr_type->float_type() != NULL)
3129 ret = fold(convert_to_real(type_tree, expr_tree));
3133 else if (type->complex_type() != NULL)
3135 if (expr_type->complex_type() != NULL)
3136 ret = fold(convert_to_complex(type_tree, expr_tree));
3140 else if (type->is_string_type()
3141 && expr_type->integer_type() != NULL)
3143 expr_tree = fold_convert(integer_type_node, expr_tree);
3144 if (host_integerp(expr_tree, 0))
3146 HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3148 Lex::append_char(intval, true, &s, this->location());
3149 Expression* se = Expression::make_string(s, this->location());
3150 return se->get_tree(context);
3153 static tree int_to_string_fndecl;
3154 ret = Gogo::call_builtin(&int_to_string_fndecl,
3156 "__go_int_to_string",
3160 fold_convert(integer_type_node, expr_tree));
3162 else if (type->is_string_type() && expr_type->is_slice_type())
3164 if (!DECL_P(expr_tree))
3165 expr_tree = save_expr(expr_tree);
3166 Array_type* a = expr_type->array_type();
3167 Type* e = a->element_type()->forwarded();
3168 go_assert(e->integer_type() != NULL);
3169 tree valptr = fold_convert(const_ptr_type_node,
3170 a->value_pointer_tree(gogo, expr_tree));
3171 tree len = a->length_tree(gogo, expr_tree);
3172 len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3174 if (e->integer_type()->is_byte())
3176 static tree byte_array_to_string_fndecl;
3177 ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3179 "__go_byte_array_to_string",
3182 const_ptr_type_node,
3189 go_assert(e->integer_type()->is_rune());
3190 static tree int_array_to_string_fndecl;
3191 ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3193 "__go_int_array_to_string",
3196 const_ptr_type_node,
3202 else if (type->is_slice_type() && expr_type->is_string_type())
3204 Type* e = type->array_type()->element_type()->forwarded();
3205 go_assert(e->integer_type() != NULL);
3206 if (e->integer_type()->is_byte())
3208 tree string_to_byte_array_fndecl = NULL_TREE;
3209 ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3211 "__go_string_to_byte_array",
3214 TREE_TYPE(expr_tree),
3219 go_assert(e->integer_type()->is_rune());
3220 tree string_to_int_array_fndecl = NULL_TREE;
3221 ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3223 "__go_string_to_int_array",
3226 TREE_TYPE(expr_tree),
3230 else if ((type->is_unsafe_pointer_type()
3231 && expr_type->points_to() != NULL)
3232 || (expr_type->is_unsafe_pointer_type()
3233 && type->points_to() != NULL))
3234 ret = fold_convert(type_tree, expr_tree);
3235 else if (type->is_unsafe_pointer_type()
3236 && expr_type->integer_type() != NULL)
3237 ret = convert_to_pointer(type_tree, expr_tree);
3238 else if (this->may_convert_function_types_
3239 && type->function_type() != NULL
3240 && expr_type->function_type() != NULL)
3241 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3244 ret = Expression::convert_for_assignment(context, type, expr_type,
3245 expr_tree, this->location());
3250 // Output a type conversion in a constant expression.
3253 Type_conversion_expression::do_export(Export* exp) const
3255 exp->write_c_string("convert(");
3256 exp->write_type(this->type_);
3257 exp->write_c_string(", ");
3258 this->expr_->export_expression(exp);
3259 exp->write_c_string(")");
3262 // Import a type conversion or a struct construction.
3265 Type_conversion_expression::do_import(Import* imp)
3267 imp->require_c_string("convert(");
3268 Type* type = imp->read_type();
3269 imp->require_c_string(", ");
3270 Expression* val = Expression::import_expression(imp);
3271 imp->require_c_string(")");
3272 return Expression::make_cast(type, val, imp->location());
3275 // Dump ast representation for a type conversion expression.
3278 Type_conversion_expression::do_dump_expression(
3279 Ast_dump_context* ast_dump_context) const
3281 ast_dump_context->dump_type(this->type_);
3282 ast_dump_context->ostream() << "(";
3283 ast_dump_context->dump_expression(this->expr_);
3284 ast_dump_context->ostream() << ") ";
3287 // Make a type cast expression.
3290 Expression::make_cast(Type* type, Expression* val, Location location)
3292 if (type->is_error_type() || val->is_error_expression())
3293 return Expression::make_error(location);
3294 return new Type_conversion_expression(type, val, location);
3297 // An unsafe type conversion, used to pass values to builtin functions.
3299 class Unsafe_type_conversion_expression : public Expression
3302 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3304 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3305 type_(type), expr_(expr)
3310 do_traverse(Traverse* traverse);
3314 { return this->type_; }
3317 do_determine_type(const Type_context*)
3318 { this->expr_->determine_type_no_context(); }
3323 return new Unsafe_type_conversion_expression(this->type_,
3324 this->expr_->copy(),
3329 do_get_tree(Translate_context*);
3332 do_dump_expression(Ast_dump_context*) const;
3335 // The type to convert to.
3337 // The expression to convert.
3344 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3346 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3347 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3348 return TRAVERSE_EXIT;
3349 return TRAVERSE_CONTINUE;
3352 // Convert to backend representation.
3355 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3357 // We are only called for a limited number of cases.
3359 Type* t = this->type_;
3360 Type* et = this->expr_->type();
3362 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3363 tree expr_tree = this->expr_->get_tree(context);
3364 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3365 return error_mark_node;
3367 Location loc = this->location();
3369 bool use_view_convert = false;
3370 if (t->is_slice_type())
3372 go_assert(et->is_slice_type());
3373 use_view_convert = true;
3375 else if (t->map_type() != NULL)
3376 go_assert(et->map_type() != NULL);
3377 else if (t->channel_type() != NULL)
3378 go_assert(et->channel_type() != NULL);
3379 else if (t->points_to() != NULL)
3380 go_assert(et->points_to() != NULL || et->is_nil_type());
3381 else if (et->is_unsafe_pointer_type())
3382 go_assert(t->points_to() != NULL);
3383 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3385 go_assert(et->interface_type() != NULL
3386 && !et->interface_type()->is_empty());
3387 use_view_convert = true;
3389 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3391 go_assert(et->interface_type() != NULL
3392 && et->interface_type()->is_empty());
3393 use_view_convert = true;
3395 else if (t->integer_type() != NULL)
3397 go_assert(et->is_boolean_type()
3398 || et->integer_type() != NULL
3399 || et->function_type() != NULL
3400 || et->points_to() != NULL
3401 || et->map_type() != NULL
3402 || et->channel_type() != NULL);
3403 return convert_to_integer(type_tree, expr_tree);
3408 if (use_view_convert)
3409 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3412 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3415 // Dump ast representation for an unsafe type conversion expression.
3418 Unsafe_type_conversion_expression::do_dump_expression(
3419 Ast_dump_context* ast_dump_context) const
3421 ast_dump_context->dump_type(this->type_);
3422 ast_dump_context->ostream() << "(";
3423 ast_dump_context->dump_expression(this->expr_);
3424 ast_dump_context->ostream() << ") ";
3427 // Make an unsafe type conversion expression.
3430 Expression::make_unsafe_cast(Type* type, Expression* expr,
3433 return new Unsafe_type_conversion_expression(type, expr, location);
3436 // Unary expressions.
3438 class Unary_expression : public Expression
3441 Unary_expression(Operator op, Expression* expr, Location location)
3442 : Expression(EXPRESSION_UNARY, location),
3443 op_(op), escapes_(true), create_temp_(false), expr_(expr)
3446 // Return the operator.
3449 { return this->op_; }
3451 // Return the operand.
3454 { return this->expr_; }
3456 // Record that an address expression does not escape.
3458 set_does_not_escape()
3460 go_assert(this->op_ == OPERATOR_AND);
3461 this->escapes_ = false;
3464 // Record that this is an address expression which should create a
3465 // temporary variable if necessary. This is used for method calls.
3469 go_assert(this->op_ == OPERATOR_AND);
3470 this->create_temp_ = true;
3473 // Apply unary opcode OP to UNC, setting NC. Return true if this
3474 // could be done, false if not. Issue errors for overflow.
3476 eval_constant(Operator op, const Numeric_constant* unc,
3477 Location, Numeric_constant* nc);
3484 do_traverse(Traverse* traverse)
3485 { return Expression::traverse(&this->expr_, traverse); }
3488 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3491 do_is_constant() const;
3494 do_numeric_constant_value(Numeric_constant*) const;
3500 do_determine_type(const Type_context*);
3503 do_check_types(Gogo*);
3508 return Expression::make_unary(this->op_, this->expr_->copy(),
3513 do_must_eval_subexpressions_in_order(int*) const
3514 { return this->op_ == OPERATOR_MULT; }
3517 do_is_addressable() const
3518 { return this->op_ == OPERATOR_MULT; }
3521 do_get_tree(Translate_context*);
3524 do_export(Export*) const;
3527 do_dump_expression(Ast_dump_context*) const;
3530 // The unary operator to apply.
3532 // Normally true. False if this is an address expression which does
3533 // not escape the current function.
3535 // True if this is an address expression which should create a
3536 // temporary variable if necessary.
3542 // If we are taking the address of a composite literal, and the
3543 // contents are not constant, then we want to make a heap composite
3547 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3549 Location loc = this->location();
3550 Operator op = this->op_;
3551 Expression* expr = this->expr_;
3553 if (op == OPERATOR_MULT && expr->is_type_expression())
3554 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3556 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3557 // moving x to the heap. FIXME: Is it worth doing a real escape
3558 // analysis here? This case is found in math/unsafe.go and is
3559 // therefore worth special casing.
3560 if (op == OPERATOR_MULT)
3562 Expression* e = expr;
3563 while (e->classification() == EXPRESSION_CONVERSION)
3565 Type_conversion_expression* te
3566 = static_cast<Type_conversion_expression*>(e);
3570 if (e->classification() == EXPRESSION_UNARY)
3572 Unary_expression* ue = static_cast<Unary_expression*>(e);
3573 if (ue->op_ == OPERATOR_AND)
3580 ue->set_does_not_escape();
3585 // Catching an invalid indirection of unsafe.Pointer here avoid
3586 // having to deal with TYPE_VOID in other places.
3587 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3589 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3590 return Expression::make_error(this->location());
3593 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS
3594 || op == OPERATOR_NOT || op == OPERATOR_XOR)
3596 Numeric_constant nc;
3597 if (expr->numeric_constant_value(&nc))
3599 Numeric_constant result;
3600 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3601 return result.expression(loc);
3608 // Return whether a unary expression is a constant.
3611 Unary_expression::do_is_constant() const
3613 if (this->op_ == OPERATOR_MULT)
3615 // Indirecting through a pointer is only constant if the object
3616 // to which the expression points is constant, but we currently
3617 // have no way to determine that.
3620 else if (this->op_ == OPERATOR_AND)
3622 // Taking the address of a variable is constant if it is a
3623 // global variable, not constant otherwise. In other cases
3624 // taking the address is probably not a constant.
3625 Var_expression* ve = this->expr_->var_expression();
3628 Named_object* no = ve->named_object();
3629 return no->is_variable() && no->var_value()->is_global();
3634 return this->expr_->is_constant();
3637 // Apply unary opcode OP to UNC, setting NC. Return true if this
3638 // could be done, false if not. Issue errors for overflow.
3641 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3642 Location location, Numeric_constant* nc)
3650 case OPERATOR_MINUS:
3651 if (unc->is_int() || unc->is_rune())
3653 else if (unc->is_float())
3656 unc->get_float(&uval);
3659 mpfr_neg(val, uval, GMP_RNDN);
3660 nc->set_float(unc->type(), val);
3665 else if (unc->is_complex())
3667 mpfr_t ureal, uimag;
3668 unc->get_complex(&ureal, &uimag);
3672 mpfr_neg(real, ureal, GMP_RNDN);
3673 mpfr_neg(imag, uimag, GMP_RNDN);
3674 nc->set_complex(unc->type(), real, imag);
3696 if (!unc->is_int() && !unc->is_rune())
3700 unc->get_int(&uval);
3706 case OPERATOR_MINUS:
3711 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3716 Type* utype = unc->type();
3717 if (utype->integer_type() == NULL
3718 || utype->integer_type()->is_abstract())
3722 // The number of HOST_WIDE_INTs that it takes to represent
3724 size_t count = ((mpz_sizeinbase(uval, 2)
3725 + HOST_BITS_PER_WIDE_INT
3727 / HOST_BITS_PER_WIDE_INT);
3729 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3730 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3732 size_t obits = utype->integer_type()->bits();
3734 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3737 mpz_init_set_ui(adj, 1);
3738 mpz_mul_2exp(adj, adj, obits);
3739 mpz_add(uval, uval, adj);
3744 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3745 go_assert(ecount <= count);
3747 // Trim down to the number of words required by the type.
3748 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3749 / HOST_BITS_PER_WIDE_INT);
3750 go_assert(ocount <= count);
3752 for (size_t i = 0; i < ocount; ++i)
3755 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3757 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3760 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3762 if (!utype->integer_type()->is_unsigned()
3763 && mpz_tstbit(val, obits - 1))
3766 mpz_init_set_ui(adj, 1);
3767 mpz_mul_2exp(adj, adj, obits);
3768 mpz_sub(val, val, adj);
3782 nc->set_rune(NULL, val);
3784 nc->set_int(NULL, val);
3789 return nc->set_type(unc->type(), true, location);
3792 // Return the integral constant value of a unary expression, if it has one.
3795 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3797 Numeric_constant unc;
3798 if (!this->expr_->numeric_constant_value(&unc))
3800 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3804 // Return the type of a unary expression.
3807 Unary_expression::do_type()
3812 case OPERATOR_MINUS:
3815 return this->expr_->type();
3818 return Type::make_pointer_type(this->expr_->type());
3822 Type* subtype = this->expr_->type();
3823 Type* points_to = subtype->points_to();
3824 if (points_to == NULL)
3825 return Type::make_error_type();
3834 // Determine abstract types for a unary expression.
3837 Unary_expression::do_determine_type(const Type_context* context)
3842 case OPERATOR_MINUS:
3845 this->expr_->determine_type(context);
3849 // Taking the address of something.
3851 Type* subtype = (context->type == NULL
3853 : context->type->points_to());
3854 Type_context subcontext(subtype, false);
3855 this->expr_->determine_type(&subcontext);
3860 // Indirecting through a pointer.
3862 Type* subtype = (context->type == NULL
3864 : Type::make_pointer_type(context->type));
3865 Type_context subcontext(subtype, false);
3866 this->expr_->determine_type(&subcontext);
3875 // Check types for a unary expression.
3878 Unary_expression::do_check_types(Gogo*)
3880 Type* type = this->expr_->type();
3881 if (type->is_error())
3883 this->set_is_error();
3890 case OPERATOR_MINUS:
3891 if (type->integer_type() == NULL
3892 && type->float_type() == NULL
3893 && type->complex_type() == NULL)
3894 this->report_error(_("expected numeric type"));
3899 if (type->integer_type() == NULL
3900 && !type->is_boolean_type())
3901 this->report_error(_("expected integer or boolean type"));
3905 if (!this->expr_->is_addressable())
3907 if (!this->create_temp_)
3908 this->report_error(_("invalid operand for unary %<&%>"));
3911 this->expr_->address_taken(this->escapes_);
3915 // Indirecting through a pointer.
3916 if (type->points_to() == NULL)
3917 this->report_error(_("expected pointer"));
3925 // Get a tree for a unary expression.
3928 Unary_expression::do_get_tree(Translate_context* context)
3930 Location loc = this->location();
3932 // Taking the address of a set-and-use-temporary expression requires
3933 // setting the temporary and then taking the address.
3934 if (this->op_ == OPERATOR_AND)
3936 Set_and_use_temporary_expression* sut =
3937 this->expr_->set_and_use_temporary_expression();
3940 Temporary_statement* temp = sut->temporary();
3941 Bvariable* bvar = temp->get_backend_variable(context);
3942 tree var_tree = var_to_tree(bvar);
3943 Expression* val = sut->expression();
3944 tree val_tree = val->get_tree(context);
3945 if (var_tree == error_mark_node || val_tree == error_mark_node)
3946 return error_mark_node;
3947 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3949 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3950 TREE_TYPE(addr_tree),
3951 build2_loc(sut->location().gcc_location(),
3952 MODIFY_EXPR, void_type_node,
3953 var_tree, val_tree),
3958 tree expr = this->expr_->get_tree(context);
3959 if (expr == error_mark_node)
3960 return error_mark_node;
3967 case OPERATOR_MINUS:
3969 tree type = TREE_TYPE(expr);
3970 tree compute_type = excess_precision_type(type);
3971 if (compute_type != NULL_TREE)
3972 expr = ::convert(compute_type, expr);
3973 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3974 (compute_type != NULL_TREE
3978 if (compute_type != NULL_TREE)
3979 ret = ::convert(type, ret);
3984 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
3985 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
3986 TREE_TYPE(expr), expr);
3988 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
3989 expr, build_int_cst(TREE_TYPE(expr), 0));
3992 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
3996 if (!this->create_temp_)
3998 // We should not see a non-constant constructor here; cases
3999 // where we would see one should have been moved onto the
4000 // heap at parse time. Taking the address of a nonconstant
4001 // constructor will not do what the programmer expects.
4002 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4003 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4006 // Build a decl for a constant constructor.
4007 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4009 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4010 create_tmp_var_name("C"), TREE_TYPE(expr));
4011 DECL_EXTERNAL(decl) = 0;
4012 TREE_PUBLIC(decl) = 0;
4013 TREE_READONLY(decl) = 1;
4014 TREE_CONSTANT(decl) = 1;
4015 TREE_STATIC(decl) = 1;
4016 TREE_ADDRESSABLE(decl) = 1;
4017 DECL_ARTIFICIAL(decl) = 1;
4018 DECL_INITIAL(decl) = expr;
4019 rest_of_decl_compilation(decl, 1, 0);
4023 if (this->create_temp_
4024 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4026 && TREE_CODE(expr) != INDIRECT_REF
4027 && TREE_CODE(expr) != COMPONENT_REF)
4029 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4030 DECL_IGNORED_P(tmp) = 1;
4031 DECL_INITIAL(tmp) = expr;
4032 TREE_ADDRESSABLE(tmp) = 1;
4033 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4034 build_pointer_type(TREE_TYPE(expr)),
4035 build1_loc(loc.gcc_location(), DECL_EXPR,
4036 void_type_node, tmp),
4037 build_fold_addr_expr_loc(loc.gcc_location(), tmp));
4040 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4044 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4046 // If we are dereferencing the pointer to a large struct, we
4047 // need to check for nil. We don't bother to check for small
4048 // structs because we expect the system to crash on a nil
4049 // pointer dereference.
4050 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4051 if (!VOID_TYPE_P(target_type_tree))
4053 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4054 if (s == -1 || s >= 4096)
4057 expr = save_expr(expr);
4058 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4061 fold_convert(TREE_TYPE(expr),
4062 null_pointer_node));
4063 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4065 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4066 TREE_TYPE(expr), build3(COND_EXPR,
4074 // If the type of EXPR is a recursive pointer type, then we
4075 // need to insert a cast before indirecting.
4076 if (VOID_TYPE_P(target_type_tree))
4078 Type* pt = this->expr_->type()->points_to();
4079 tree ind = type_to_tree(pt->get_backend(context->gogo()));
4080 expr = fold_convert_loc(loc.gcc_location(),
4081 build_pointer_type(ind), expr);
4084 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4092 // Export a unary expression.
4095 Unary_expression::do_export(Export* exp) const
4100 exp->write_c_string("+ ");
4102 case OPERATOR_MINUS:
4103 exp->write_c_string("- ");
4106 exp->write_c_string("! ");
4109 exp->write_c_string("^ ");
4116 this->expr_->export_expression(exp);
4119 // Import a unary expression.
4122 Unary_expression::do_import(Import* imp)
4125 switch (imp->get_char())
4131 op = OPERATOR_MINUS;
4142 imp->require_c_string(" ");
4143 Expression* expr = Expression::import_expression(imp);
4144 return Expression::make_unary(op, expr, imp->location());
4147 // Dump ast representation of an unary expression.
4150 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4152 ast_dump_context->dump_operator(this->op_);
4153 ast_dump_context->ostream() << "(";
4154 ast_dump_context->dump_expression(this->expr_);
4155 ast_dump_context->ostream() << ") ";
4158 // Make a unary expression.
4161 Expression::make_unary(Operator op, Expression* expr, Location location)
4163 return new Unary_expression(op, expr, location);
4166 // If this is an indirection through a pointer, return the expression
4167 // being pointed through. Otherwise return this.
4172 if (this->classification_ == EXPRESSION_UNARY)
4174 Unary_expression* ue = static_cast<Unary_expression*>(this);
4175 if (ue->op() == OPERATOR_MULT)
4176 return ue->operand();
4181 // Class Binary_expression.
4186 Binary_expression::do_traverse(Traverse* traverse)
4188 int t = Expression::traverse(&this->left_, traverse);
4189 if (t == TRAVERSE_EXIT)
4190 return TRAVERSE_EXIT;
4191 return Expression::traverse(&this->right_, traverse);
4194 // Return the type to use for a binary operation on operands of
4195 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4196 // such may be NULL or abstract.
4199 Binary_expression::operation_type(Operator op, Type* left_type,
4200 Type* right_type, Type** result_type)
4202 if (left_type != right_type
4203 && !left_type->is_abstract()
4204 && !right_type->is_abstract()
4205 && left_type->base() != right_type->base()
4206 && op != OPERATOR_LSHIFT
4207 && op != OPERATOR_RSHIFT)
4209 // May be a type error--let it be diagnosed elsewhere.
4213 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4215 if (left_type->integer_type() != NULL)
4216 *result_type = left_type;
4218 *result_type = Type::make_abstract_integer_type();
4220 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4221 *result_type = left_type;
4222 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4223 *result_type = right_type;
4224 else if (!left_type->is_abstract())
4225 *result_type = left_type;
4226 else if (!right_type->is_abstract())
4227 *result_type = right_type;
4228 else if (left_type->complex_type() != NULL)
4229 *result_type = left_type;
4230 else if (right_type->complex_type() != NULL)
4231 *result_type = right_type;
4232 else if (left_type->float_type() != NULL)
4233 *result_type = left_type;
4234 else if (right_type->float_type() != NULL)
4235 *result_type = right_type;
4236 else if (left_type->integer_type() != NULL
4237 && left_type->integer_type()->is_rune())
4238 *result_type = left_type;
4239 else if (right_type->integer_type() != NULL
4240 && right_type->integer_type()->is_rune())
4241 *result_type = right_type;
4243 *result_type = left_type;
4248 // Convert an integer comparison code and an operator to a boolean
4252 Binary_expression::cmp_to_bool(Operator op, int cmp)
4259 case OPERATOR_NOTEQ:
4276 // Compare constants according to OP.
4279 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4280 Numeric_constant* right_nc,
4281 Location location, bool* result)
4283 Type* left_type = left_nc->type();
4284 Type* right_type = right_nc->type();
4287 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4290 // When comparing an untyped operand to a typed operand, we are
4291 // effectively coercing the untyped operand to the other operand's
4292 // type, so make sure that is valid.
4293 if (!left_nc->set_type(type, true, location)
4294 || !right_nc->set_type(type, true, location))
4299 if (type->complex_type() != NULL)
4301 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4303 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4305 else if (type->float_type() != NULL)
4306 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4308 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4311 *result = Binary_expression::cmp_to_bool(op, cmp);
4316 // Compare integer constants.
4319 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4320 const Numeric_constant* right_nc,
4324 if (!left_nc->to_int(&left_val))
4327 if (!right_nc->to_int(&right_val))
4329 mpz_clear(left_val);
4333 *cmp = mpz_cmp(left_val, right_val);
4335 mpz_clear(left_val);
4336 mpz_clear(right_val);
4341 // Compare floating point constants.
4344 Binary_expression::compare_float(const Numeric_constant* left_nc,
4345 const Numeric_constant* right_nc,
4349 if (!left_nc->to_float(&left_val))
4352 if (!right_nc->to_float(&right_val))
4354 mpfr_clear(left_val);
4358 // We already coerced both operands to the same type. If that type
4359 // is not an abstract type, we need to round the values accordingly.
4360 Type* type = left_nc->type();
4361 if (!type->is_abstract() && type->float_type() != NULL)
4363 int bits = type->float_type()->bits();
4364 mpfr_prec_round(left_val, bits, GMP_RNDN);
4365 mpfr_prec_round(right_val, bits, GMP_RNDN);
4368 *cmp = mpfr_cmp(left_val, right_val);
4370 mpfr_clear(left_val);
4371 mpfr_clear(right_val);
4376 // Compare complex constants. Complex numbers may only be compared
4380 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4381 const Numeric_constant* right_nc,
4384 mpfr_t left_real, left_imag;
4385 if (!left_nc->to_complex(&left_real, &left_imag))
4387 mpfr_t right_real, right_imag;
4388 if (!right_nc->to_complex(&right_real, &right_imag))
4390 mpfr_clear(left_real);
4391 mpfr_clear(left_imag);
4395 // We already coerced both operands to the same type. If that type
4396 // is not an abstract type, we need to round the values accordingly.
4397 Type* type = left_nc->type();
4398 if (!type->is_abstract() && type->complex_type() != NULL)
4400 int bits = type->complex_type()->bits();
4401 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4402 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4403 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4404 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4407 *cmp = (mpfr_cmp(left_real, right_real) != 0
4408 || mpfr_cmp(left_imag, right_imag) != 0);
4410 mpfr_clear(left_real);
4411 mpfr_clear(left_imag);
4412 mpfr_clear(right_real);
4413 mpfr_clear(right_imag);
4418 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4419 // true if this could be done, false if not. Issue errors at LOCATION
4423 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4424 Numeric_constant* right_nc,
4425 Location location, Numeric_constant* nc)
4430 case OPERATOR_ANDAND:
4432 case OPERATOR_NOTEQ:
4437 // These return boolean values and as such must be handled
4444 Type* left_type = left_nc->type();
4445 Type* right_type = right_nc->type();
4448 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4451 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4453 // When combining an untyped operand with a typed operand, we are
4454 // effectively coercing the untyped operand to the other operand's
4455 // type, so make sure that is valid.
4456 if (!left_nc->set_type(type, true, location))
4458 if (!is_shift && !right_nc->set_type(type, true, location))
4462 if (type->complex_type() != NULL)
4463 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4464 else if (type->float_type() != NULL)
4465 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4467 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4470 r = nc->set_type(type, true, location);
4475 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4476 // integer operations. Return true if this could be done, false if
4480 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4481 const Numeric_constant* right_nc,
4482 Location location, Numeric_constant* nc)
4485 if (!left_nc->to_int(&left_val))
4488 if (!right_nc->to_int(&right_val))
4490 mpz_clear(left_val);
4500 mpz_add(val, left_val, right_val);
4502 case OPERATOR_MINUS:
4503 mpz_sub(val, left_val, right_val);
4506 mpz_ior(val, left_val, right_val);
4509 mpz_xor(val, left_val, right_val);
4512 mpz_mul(val, left_val, right_val);
4515 if (mpz_sgn(right_val) != 0)
4516 mpz_tdiv_q(val, left_val, right_val);
4519 error_at(location, "division by zero");
4524 if (mpz_sgn(right_val) != 0)
4525 mpz_tdiv_r(val, left_val, right_val);
4528 error_at(location, "division by zero");
4532 case OPERATOR_LSHIFT:
4534 unsigned long shift = mpz_get_ui(right_val);
4535 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4536 mpz_mul_2exp(val, left_val, shift);
4539 error_at(location, "shift count overflow");
4545 case OPERATOR_RSHIFT:
4547 unsigned long shift = mpz_get_ui(right_val);
4548 if (mpz_cmp_ui(right_val, shift) != 0)
4550 error_at(location, "shift count overflow");
4555 if (mpz_cmp_ui(left_val, 0) >= 0)
4556 mpz_tdiv_q_2exp(val, left_val, shift);
4558 mpz_fdiv_q_2exp(val, left_val, shift);
4564 mpz_and(val, left_val, right_val);
4566 case OPERATOR_BITCLEAR:
4570 mpz_com(tval, right_val);
4571 mpz_and(val, left_val, tval);
4579 mpz_clear(left_val);
4580 mpz_clear(right_val);
4582 if (left_nc->is_rune()
4583 || (op != OPERATOR_LSHIFT
4584 && op != OPERATOR_RSHIFT
4585 && right_nc->is_rune()))
4586 nc->set_rune(NULL, val);
4588 nc->set_int(NULL, val);
4595 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4596 // floating point operations. Return true if this could be done,
4600 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4601 const Numeric_constant* right_nc,
4602 Location location, Numeric_constant* nc)
4605 if (!left_nc->to_float(&left_val))
4608 if (!right_nc->to_float(&right_val))
4610 mpfr_clear(left_val);
4621 mpfr_add(val, left_val, right_val, GMP_RNDN);
4623 case OPERATOR_MINUS:
4624 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4629 case OPERATOR_BITCLEAR:
4631 case OPERATOR_LSHIFT:
4632 case OPERATOR_RSHIFT:
4633 mpfr_set_ui(val, 0, GMP_RNDN);
4637 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4640 if (!mpfr_zero_p(right_val))
4641 mpfr_div(val, left_val, right_val, GMP_RNDN);
4644 error_at(location, "division by zero");
4645 mpfr_set_ui(val, 0, GMP_RNDN);
4652 mpfr_clear(left_val);
4653 mpfr_clear(right_val);
4655 nc->set_float(NULL, val);
4661 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4662 // complex operations. Return true if this could be done, false if
4666 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4667 const Numeric_constant* right_nc,
4668 Location location, Numeric_constant* nc)
4670 mpfr_t left_real, left_imag;
4671 if (!left_nc->to_complex(&left_real, &left_imag))
4673 mpfr_t right_real, right_imag;
4674 if (!right_nc->to_complex(&right_real, &right_imag))
4676 mpfr_clear(left_real);
4677 mpfr_clear(left_imag);
4689 mpfr_add(real, left_real, right_real, GMP_RNDN);
4690 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4692 case OPERATOR_MINUS:
4693 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4694 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4699 case OPERATOR_BITCLEAR:
4701 case OPERATOR_LSHIFT:
4702 case OPERATOR_RSHIFT:
4703 mpfr_set_ui(real, 0, GMP_RNDN);
4704 mpfr_set_ui(imag, 0, GMP_RNDN);
4709 // You might think that multiplying two complex numbers would
4710 // be simple, and you would be right, until you start to think
4711 // about getting the right answer for infinity. If one
4712 // operand here is infinity and the other is anything other
4713 // than zero or NaN, then we are going to wind up subtracting
4714 // two infinity values. That will give us a NaN, but the
4715 // correct answer is infinity.
4719 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4723 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4727 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4731 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4733 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4734 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4736 // If we get NaN on both sides, check whether it should really
4737 // be infinity. The rule is that if either side of the
4738 // complex number is infinity, then the whole value is
4739 // infinity, even if the other side is NaN. So the only case
4740 // we have to fix is the one in which both sides are NaN.
4741 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4742 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4743 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4745 bool is_infinity = false;
4749 mpfr_init_set(lr, left_real, GMP_RNDN);
4750 mpfr_init_set(li, left_imag, GMP_RNDN);
4754 mpfr_init_set(rr, right_real, GMP_RNDN);
4755 mpfr_init_set(ri, right_imag, GMP_RNDN);
4757 // If the left side is infinity, then the result is
4759 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4761 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4762 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4763 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4764 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4767 mpfr_set_ui(rr, 0, GMP_RNDN);
4768 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4772 mpfr_set_ui(ri, 0, GMP_RNDN);
4773 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4778 // If the right side is infinity, then the result is
4780 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4782 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4783 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4784 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4785 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4788 mpfr_set_ui(lr, 0, GMP_RNDN);
4789 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4793 mpfr_set_ui(li, 0, GMP_RNDN);
4794 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4799 // If we got an overflow in the intermediate computations,
4800 // then the result is infinity.
4802 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4803 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4807 mpfr_set_ui(lr, 0, GMP_RNDN);
4808 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4812 mpfr_set_ui(li, 0, GMP_RNDN);
4813 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4817 mpfr_set_ui(rr, 0, GMP_RNDN);
4818 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4822 mpfr_set_ui(ri, 0, GMP_RNDN);
4823 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4830 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4831 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4832 mpfr_mul(lirr, li, rr, GMP_RNDN);
4833 mpfr_mul(liri, li, ri, GMP_RNDN);
4834 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4835 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4836 mpfr_set_inf(real, mpfr_sgn(real));
4837 mpfr_set_inf(imag, mpfr_sgn(imag));
4854 // For complex division we want to avoid having an
4855 // intermediate overflow turn the whole result in a NaN. We
4856 // scale the values to try to avoid this.
4858 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4860 error_at(location, "division by zero");
4861 mpfr_set_ui(real, 0, GMP_RNDN);
4862 mpfr_set_ui(imag, 0, GMP_RNDN);
4870 mpfr_abs(rra, right_real, GMP_RNDN);
4871 mpfr_abs(ria, right_imag, GMP_RNDN);
4874 mpfr_max(t, rra, ria, GMP_RNDN);
4878 mpfr_init_set(rr, right_real, GMP_RNDN);
4879 mpfr_init_set(ri, right_imag, GMP_RNDN);
4881 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4883 ilogbw = mpfr_get_exp(t);
4884 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4885 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4890 mpfr_mul(denom, rr, rr, GMP_RNDN);
4891 mpfr_mul(t, ri, ri, GMP_RNDN);
4892 mpfr_add(denom, denom, t, GMP_RNDN);
4894 mpfr_mul(real, left_real, rr, GMP_RNDN);
4895 mpfr_mul(t, left_imag, ri, GMP_RNDN);
4896 mpfr_add(real, real, t, GMP_RNDN);
4897 mpfr_div(real, real, denom, GMP_RNDN);
4898 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4900 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4901 mpfr_mul(t, left_real, ri, GMP_RNDN);
4902 mpfr_sub(imag, imag, t, GMP_RNDN);
4903 mpfr_div(imag, imag, denom, GMP_RNDN);
4904 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
4906 // If we wind up with NaN on both sides, check whether we
4907 // should really have infinity. The rule is that if either
4908 // side of the complex number is infinity, then the whole
4909 // value is infinity, even if the other side is NaN. So the
4910 // only case we have to fix is the one in which both sides are
4912 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4913 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4914 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4916 if (mpfr_zero_p(denom))
4918 mpfr_set_inf(real, mpfr_sgn(rr));
4919 mpfr_mul(real, real, left_real, GMP_RNDN);
4920 mpfr_set_inf(imag, mpfr_sgn(rr));
4921 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
4923 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
4924 && mpfr_number_p(rr) && mpfr_number_p(ri))
4926 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
4927 mpfr_copysign(t, t, left_real, GMP_RNDN);
4930 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
4931 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
4935 mpfr_mul(t3, t, rr, GMP_RNDN);
4939 mpfr_mul(t4, t2, ri, GMP_RNDN);
4941 mpfr_add(t3, t3, t4, GMP_RNDN);
4942 mpfr_set_inf(real, mpfr_sgn(t3));
4944 mpfr_mul(t3, t2, rr, GMP_RNDN);
4945 mpfr_mul(t4, t, ri, GMP_RNDN);
4946 mpfr_sub(t3, t3, t4, GMP_RNDN);
4947 mpfr_set_inf(imag, mpfr_sgn(t3));
4953 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
4954 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
4956 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4957 mpfr_copysign(t, t, rr, GMP_RNDN);
4960 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4961 mpfr_copysign(t2, t2, ri, GMP_RNDN);
4965 mpfr_mul(t3, left_real, t, GMP_RNDN);
4969 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
4971 mpfr_add(t3, t3, t4, GMP_RNDN);
4972 mpfr_set_ui(real, 0, GMP_RNDN);
4973 mpfr_mul(real, real, t3, GMP_RNDN);
4975 mpfr_mul(t3, left_imag, t, GMP_RNDN);
4976 mpfr_mul(t4, left_real, t2, GMP_RNDN);
4977 mpfr_sub(t3, t3, t4, GMP_RNDN);
4978 mpfr_set_ui(imag, 0, GMP_RNDN);
4979 mpfr_mul(imag, imag, t3, GMP_RNDN);
4999 mpfr_clear(left_real);
5000 mpfr_clear(left_imag);
5001 mpfr_clear(right_real);
5002 mpfr_clear(right_imag);
5004 nc->set_complex(NULL, real, imag);
5011 // Lower a binary expression. We have to evaluate constant
5012 // expressions now, in order to implement Go's unlimited precision
5016 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5017 Statement_inserter* inserter, int)
5019 Location location = this->location();
5020 Operator op = this->op_;
5021 Expression* left = this->left_;
5022 Expression* right = this->right_;
5024 const bool is_comparison = (op == OPERATOR_EQEQ
5025 || op == OPERATOR_NOTEQ
5026 || op == OPERATOR_LT
5027 || op == OPERATOR_LE
5028 || op == OPERATOR_GT
5029 || op == OPERATOR_GE);
5031 // Numeric constant expressions.
5033 Numeric_constant left_nc;
5034 Numeric_constant right_nc;
5035 if (left->numeric_constant_value(&left_nc)
5036 && right->numeric_constant_value(&right_nc))
5041 if (!Binary_expression::compare_constant(op, &left_nc,
5042 &right_nc, location,
5045 return Expression::make_cast(Type::lookup_bool_type(),
5046 Expression::make_boolean(result,
5052 Numeric_constant nc;
5053 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5056 return nc.expression(location);
5061 // String constant expressions.
5062 if (left->type()->is_string_type() && right->type()->is_string_type())
5064 std::string left_string;
5065 std::string right_string;
5066 if (left->string_constant_value(&left_string)
5067 && right->string_constant_value(&right_string))
5069 if (op == OPERATOR_PLUS)
5070 return Expression::make_string(left_string + right_string,
5072 else if (is_comparison)
5074 int cmp = left_string.compare(right_string);
5075 bool r = Binary_expression::cmp_to_bool(op, cmp);
5076 return Expression::make_cast(Type::lookup_bool_type(),
5077 Expression::make_boolean(r,
5084 // Lower struct and array comparisons.
5085 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5087 if (left->type()->struct_type() != NULL)
5088 return this->lower_struct_comparison(gogo, inserter);
5089 else if (left->type()->array_type() != NULL
5090 && !left->type()->is_slice_type())
5091 return this->lower_array_comparison(gogo, inserter);
5097 // Lower a struct comparison.
5100 Binary_expression::lower_struct_comparison(Gogo* gogo,
5101 Statement_inserter* inserter)
5103 Struct_type* st = this->left_->type()->struct_type();
5104 Struct_type* st2 = this->right_->type()->struct_type();
5107 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5109 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5110 this->right_->type(), NULL))
5113 // See if we can compare using memcmp. As a heuristic, we use
5114 // memcmp rather than field references and comparisons if there are
5115 // more than two fields.
5116 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5117 return this->lower_compare_to_memcmp(gogo, inserter);
5119 Location loc = this->location();
5121 Expression* left = this->left_;
5122 Temporary_statement* left_temp = NULL;
5123 if (left->var_expression() == NULL
5124 && left->temporary_reference_expression() == NULL)
5126 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5127 inserter->insert(left_temp);
5128 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5131 Expression* right = this->right_;
5132 Temporary_statement* right_temp = NULL;
5133 if (right->var_expression() == NULL
5134 && right->temporary_reference_expression() == NULL)
5136 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5137 inserter->insert(right_temp);
5138 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5141 Expression* ret = Expression::make_boolean(true, loc);
5142 const Struct_field_list* fields = st->fields();
5143 unsigned int field_index = 0;
5144 for (Struct_field_list::const_iterator pf = fields->begin();
5145 pf != fields->end();
5146 ++pf, ++field_index)
5148 if (field_index > 0)
5150 if (left_temp == NULL)
5151 left = left->copy();
5153 left = Expression::make_temporary_reference(left_temp, loc);
5154 if (right_temp == NULL)
5155 right = right->copy();
5157 right = Expression::make_temporary_reference(right_temp, loc);
5159 Expression* f1 = Expression::make_field_reference(left, field_index,
5161 Expression* f2 = Expression::make_field_reference(right, field_index,
5163 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5164 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5167 if (this->op_ == OPERATOR_NOTEQ)
5168 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5173 // Lower an array comparison.
5176 Binary_expression::lower_array_comparison(Gogo* gogo,
5177 Statement_inserter* inserter)
5179 Array_type* at = this->left_->type()->array_type();
5180 Array_type* at2 = this->right_->type()->array_type();
5183 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5185 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5186 this->right_->type(), NULL))
5189 // Call memcmp directly if possible. This may let the middle-end
5190 // optimize the call.
5191 if (at->compare_is_identity(gogo))
5192 return this->lower_compare_to_memcmp(gogo, inserter);
5194 // Call the array comparison function.
5195 Named_object* hash_fn;
5196 Named_object* equal_fn;
5197 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5198 &hash_fn, &equal_fn);
5200 Location loc = this->location();
5202 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5204 Expression_list* args = new Expression_list();
5205 args->push_back(this->operand_address(inserter, this->left_));
5206 args->push_back(this->operand_address(inserter, this->right_));
5207 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5209 Expression* ret = Expression::make_call(func, args, false, loc);
5211 if (this->op_ == OPERATOR_NOTEQ)
5212 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5217 // Lower a struct or array comparison to a call to memcmp.
5220 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5222 Location loc = this->location();
5224 Expression* a1 = this->operand_address(inserter, this->left_);
5225 Expression* a2 = this->operand_address(inserter, this->right_);
5226 Expression* len = Expression::make_type_info(this->left_->type(),
5229 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5232 mpz_init_set_ui(zval, 0);
5233 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5236 return Expression::make_binary(this->op_, call, zero, loc);
5239 // Return the address of EXPR, cast to unsafe.Pointer.
5242 Binary_expression::operand_address(Statement_inserter* inserter,
5245 Location loc = this->location();
5247 if (!expr->is_addressable())
5249 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5251 inserter->insert(temp);
5252 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5254 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5255 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5256 Type* void_type = Type::make_void_type();
5257 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5258 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5261 // Return the numeric constant value, if it has one.
5264 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5266 Operator op = this->op_;
5268 if (op == OPERATOR_EQEQ
5269 || op == OPERATOR_NOTEQ
5270 || op == OPERATOR_LT
5271 || op == OPERATOR_LE
5272 || op == OPERATOR_GT
5273 || op == OPERATOR_GE)
5276 Numeric_constant left_nc;
5277 if (!this->left_->numeric_constant_value(&left_nc))
5279 Numeric_constant right_nc;
5280 if (!this->right_->numeric_constant_value(&right_nc))
5283 return Binary_expression::eval_constant(op, &left_nc, &right_nc,
5284 this->location(), nc);
5287 // Note that the value is being discarded.
5290 Binary_expression::do_discarding_value()
5292 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5293 this->right_->discarding_value();
5295 this->unused_value_error();
5301 Binary_expression::do_type()
5303 if (this->classification() == EXPRESSION_ERROR)
5304 return Type::make_error_type();
5309 case OPERATOR_ANDAND:
5311 case OPERATOR_NOTEQ:
5316 return Type::lookup_bool_type();
5319 case OPERATOR_MINUS:
5326 case OPERATOR_BITCLEAR:
5329 if (!Binary_expression::operation_type(this->op_,
5330 this->left_->type(),
5331 this->right_->type(),
5333 return Type::make_error_type();
5337 case OPERATOR_LSHIFT:
5338 case OPERATOR_RSHIFT:
5339 return this->left_->type();
5346 // Set type for a binary expression.
5349 Binary_expression::do_determine_type(const Type_context* context)
5351 Type* tleft = this->left_->type();
5352 Type* tright = this->right_->type();
5354 // Both sides should have the same type, except for the shift
5355 // operations. For a comparison, we should ignore the incoming
5358 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5359 || this->op_ == OPERATOR_RSHIFT);
5361 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5362 || this->op_ == OPERATOR_NOTEQ
5363 || this->op_ == OPERATOR_LT
5364 || this->op_ == OPERATOR_LE
5365 || this->op_ == OPERATOR_GT
5366 || this->op_ == OPERATOR_GE);
5368 Type_context subcontext(*context);
5372 // In a comparison, the context does not determine the types of
5374 subcontext.type = NULL;
5377 // Set the context for the left hand operand.
5380 // The right hand operand of a shift plays no role in
5381 // determining the type of the left hand operand.
5383 else if (!tleft->is_abstract())
5384 subcontext.type = tleft;
5385 else if (!tright->is_abstract())
5386 subcontext.type = tright;
5387 else if (subcontext.type == NULL)
5389 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5390 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5391 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5393 // Both sides have an abstract integer, abstract float, or
5394 // abstract complex type. Just let CONTEXT determine
5395 // whether they may remain abstract or not.
5397 else if (tleft->complex_type() != NULL)
5398 subcontext.type = tleft;
5399 else if (tright->complex_type() != NULL)
5400 subcontext.type = tright;
5401 else if (tleft->float_type() != NULL)
5402 subcontext.type = tleft;
5403 else if (tright->float_type() != NULL)
5404 subcontext.type = tright;
5406 subcontext.type = tleft;
5408 if (subcontext.type != NULL && !context->may_be_abstract)
5409 subcontext.type = subcontext.type->make_non_abstract_type();
5412 this->left_->determine_type(&subcontext);
5416 // We may have inherited an unusable type for the shift operand.
5417 // Give a useful error if that happened.
5418 if (tleft->is_abstract()
5419 && subcontext.type != NULL
5420 && (this->left_->type()->integer_type() == NULL
5421 || (subcontext.type->integer_type() == NULL
5422 && subcontext.type->float_type() == NULL
5423 && subcontext.type->complex_type() == NULL)))
5424 this->report_error(("invalid context-determined non-integer type "
5425 "for shift operand"));
5427 // The context for the right hand operand is the same as for the
5428 // left hand operand, except for a shift operator.
5429 subcontext.type = Type::lookup_integer_type("uint");
5430 subcontext.may_be_abstract = false;
5433 this->right_->determine_type(&subcontext);
5436 // Report an error if the binary operator OP does not support TYPE.
5437 // OTYPE is the type of the other operand. Return whether the
5438 // operation is OK. This should not be used for shift.
5441 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5447 case OPERATOR_ANDAND:
5448 if (!type->is_boolean_type())
5450 error_at(location, "expected boolean type");
5456 case OPERATOR_NOTEQ:
5459 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5461 error_at(location, "%s", reason.c_str());
5473 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5475 error_at(location, "%s", reason.c_str());
5482 case OPERATOR_PLUSEQ:
5483 if (type->integer_type() == NULL
5484 && type->float_type() == NULL
5485 && type->complex_type() == NULL
5486 && !type->is_string_type())
5489 "expected integer, floating, complex, or string type");
5494 case OPERATOR_MINUS:
5495 case OPERATOR_MINUSEQ:
5497 case OPERATOR_MULTEQ:
5499 case OPERATOR_DIVEQ:
5500 if (type->integer_type() == NULL
5501 && type->float_type() == NULL
5502 && type->complex_type() == NULL)
5504 error_at(location, "expected integer, floating, or complex type");
5510 case OPERATOR_MODEQ:
5514 case OPERATOR_ANDEQ:
5516 case OPERATOR_XOREQ:
5517 case OPERATOR_BITCLEAR:
5518 case OPERATOR_BITCLEAREQ:
5519 if (type->integer_type() == NULL)
5521 error_at(location, "expected integer type");
5536 Binary_expression::do_check_types(Gogo*)
5538 if (this->classification() == EXPRESSION_ERROR)
5541 Type* left_type = this->left_->type();
5542 Type* right_type = this->right_->type();
5543 if (left_type->is_error() || right_type->is_error())
5545 this->set_is_error();
5549 if (this->op_ == OPERATOR_EQEQ
5550 || this->op_ == OPERATOR_NOTEQ
5551 || this->op_ == OPERATOR_LT
5552 || this->op_ == OPERATOR_LE
5553 || this->op_ == OPERATOR_GT
5554 || this->op_ == OPERATOR_GE)
5556 if (!Type::are_assignable(left_type, right_type, NULL)
5557 && !Type::are_assignable(right_type, left_type, NULL))
5559 this->report_error(_("incompatible types in binary expression"));
5562 if (!Binary_expression::check_operator_type(this->op_, left_type,
5565 || !Binary_expression::check_operator_type(this->op_, right_type,
5569 this->set_is_error();
5573 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5575 if (!Type::are_compatible_for_binop(left_type, right_type))
5577 this->report_error(_("incompatible types in binary expression"));
5580 if (!Binary_expression::check_operator_type(this->op_, left_type,
5584 this->set_is_error();
5590 if (left_type->integer_type() == NULL)
5591 this->report_error(_("shift of non-integer operand"));
5593 if (!right_type->is_abstract()
5594 && (right_type->integer_type() == NULL
5595 || !right_type->integer_type()->is_unsigned()))
5596 this->report_error(_("shift count not unsigned integer"));
5599 Numeric_constant nc;
5600 if (this->right_->numeric_constant_value(&nc))
5603 if (!nc.to_int(&val))
5604 this->report_error(_("shift count not unsigned integer"));
5607 if (mpz_sgn(val) < 0)
5609 this->report_error(_("negative shift count"));
5611 Location rloc = this->right_->location();
5612 this->right_ = Expression::make_integer(&val, right_type,
5622 // Get a tree for a binary expression.
5625 Binary_expression::do_get_tree(Translate_context* context)
5627 tree left = this->left_->get_tree(context);
5628 tree right = this->right_->get_tree(context);
5630 if (left == error_mark_node || right == error_mark_node)
5631 return error_mark_node;
5633 enum tree_code code;
5634 bool use_left_type = true;
5635 bool is_shift_op = false;
5639 case OPERATOR_NOTEQ:
5644 return Expression::comparison_tree(context, this->op_,
5645 this->left_->type(), left,
5646 this->right_->type(), right,
5650 code = TRUTH_ORIF_EXPR;
5651 use_left_type = false;
5653 case OPERATOR_ANDAND:
5654 code = TRUTH_ANDIF_EXPR;
5655 use_left_type = false;
5660 case OPERATOR_MINUS:
5664 code = BIT_IOR_EXPR;
5667 code = BIT_XOR_EXPR;
5674 Type *t = this->left_->type();
5675 if (t->float_type() != NULL || t->complex_type() != NULL)
5678 code = TRUNC_DIV_EXPR;
5682 code = TRUNC_MOD_EXPR;
5684 case OPERATOR_LSHIFT:
5688 case OPERATOR_RSHIFT:
5693 code = BIT_AND_EXPR;
5695 case OPERATOR_BITCLEAR:
5696 right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5697 code = BIT_AND_EXPR;
5703 tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5705 if (this->left_->type()->is_string_type())
5707 go_assert(this->op_ == OPERATOR_PLUS);
5708 Type* st = Type::make_string_type();
5709 tree string_type = type_to_tree(st->get_backend(context->gogo()));
5710 static tree string_plus_decl;
5711 return Gogo::call_builtin(&string_plus_decl,
5722 tree compute_type = excess_precision_type(type);
5723 if (compute_type != NULL_TREE)
5725 left = ::convert(compute_type, left);
5726 right = ::convert(compute_type, right);
5729 tree eval_saved = NULL_TREE;
5732 // Make sure the values are evaluated.
5733 if (!DECL_P(left) && TREE_SIDE_EFFECTS(left))
5735 left = save_expr(left);
5738 if (!DECL_P(right) && TREE_SIDE_EFFECTS(right))
5740 right = save_expr(right);
5741 if (eval_saved == NULL_TREE)
5744 eval_saved = fold_build2_loc(this->location().gcc_location(),
5746 void_type_node, eval_saved, right);
5750 tree ret = fold_build2_loc(this->location().gcc_location(),
5752 compute_type != NULL_TREE ? compute_type : type,
5755 if (compute_type != NULL_TREE)
5756 ret = ::convert(type, ret);
5758 // In Go, a shift larger than the size of the type is well-defined.
5759 // This is not true in GENERIC, so we need to insert a conditional.
5762 go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
5763 go_assert(this->left_->type()->integer_type() != NULL);
5764 int bits = TYPE_PRECISION(TREE_TYPE(left));
5766 tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
5767 build_int_cst_type(TREE_TYPE(right), bits));
5769 tree overflow_result = fold_convert_loc(this->location().gcc_location(),
5772 if (this->op_ == OPERATOR_RSHIFT
5773 && !this->left_->type()->integer_type()->is_unsigned())
5776 fold_build2_loc(this->location().gcc_location(), LT_EXPR,
5777 boolean_type_node, left,
5778 fold_convert_loc(this->location().gcc_location(),
5780 integer_zero_node));
5782 fold_build2_loc(this->location().gcc_location(),
5783 MINUS_EXPR, TREE_TYPE(left),
5784 fold_convert_loc(this->location().gcc_location(),
5787 fold_convert_loc(this->location().gcc_location(),
5791 fold_build3_loc(this->location().gcc_location(), COND_EXPR,
5792 TREE_TYPE(left), neg, neg_one,
5796 ret = fold_build3_loc(this->location().gcc_location(), COND_EXPR,
5797 TREE_TYPE(left), compare, ret, overflow_result);
5799 if (eval_saved != NULL_TREE)
5800 ret = fold_build2_loc(this->location().gcc_location(), COMPOUND_EXPR,
5801 TREE_TYPE(ret), eval_saved, ret);
5807 // Export a binary expression.
5810 Binary_expression::do_export(Export* exp) const
5812 exp->write_c_string("(");
5813 this->left_->export_expression(exp);
5817 exp->write_c_string(" || ");
5819 case OPERATOR_ANDAND:
5820 exp->write_c_string(" && ");
5823 exp->write_c_string(" == ");
5825 case OPERATOR_NOTEQ:
5826 exp->write_c_string(" != ");
5829 exp->write_c_string(" < ");
5832 exp->write_c_string(" <= ");
5835 exp->write_c_string(" > ");
5838 exp->write_c_string(" >= ");
5841 exp->write_c_string(" + ");
5843 case OPERATOR_MINUS:
5844 exp->write_c_string(" - ");
5847 exp->write_c_string(" | ");
5850 exp->write_c_string(" ^ ");
5853 exp->write_c_string(" * ");
5856 exp->write_c_string(" / ");
5859 exp->write_c_string(" % ");
5861 case OPERATOR_LSHIFT:
5862 exp->write_c_string(" << ");
5864 case OPERATOR_RSHIFT:
5865 exp->write_c_string(" >> ");
5868 exp->write_c_string(" & ");
5870 case OPERATOR_BITCLEAR:
5871 exp->write_c_string(" &^ ");
5876 this->right_->export_expression(exp);
5877 exp->write_c_string(")");
5880 // Import a binary expression.
5883 Binary_expression::do_import(Import* imp)
5885 imp->require_c_string("(");
5887 Expression* left = Expression::import_expression(imp);
5890 if (imp->match_c_string(" || "))
5895 else if (imp->match_c_string(" && "))
5897 op = OPERATOR_ANDAND;
5900 else if (imp->match_c_string(" == "))
5905 else if (imp->match_c_string(" != "))
5907 op = OPERATOR_NOTEQ;
5910 else if (imp->match_c_string(" < "))
5915 else if (imp->match_c_string(" <= "))
5920 else if (imp->match_c_string(" > "))
5925 else if (imp->match_c_string(" >= "))
5930 else if (imp->match_c_string(" + "))
5935 else if (imp->match_c_string(" - "))
5937 op = OPERATOR_MINUS;
5940 else if (imp->match_c_string(" | "))
5945 else if (imp->match_c_string(" ^ "))
5950 else if (imp->match_c_string(" * "))
5955 else if (imp->match_c_string(" / "))
5960 else if (imp->match_c_string(" % "))
5965 else if (imp->match_c_string(" << "))
5967 op = OPERATOR_LSHIFT;
5970 else if (imp->match_c_string(" >> "))
5972 op = OPERATOR_RSHIFT;
5975 else if (imp->match_c_string(" & "))
5980 else if (imp->match_c_string(" &^ "))
5982 op = OPERATOR_BITCLEAR;
5987 error_at(imp->location(), "unrecognized binary operator");
5988 return Expression::make_error(imp->location());
5991 Expression* right = Expression::import_expression(imp);
5993 imp->require_c_string(")");
5995 return Expression::make_binary(op, left, right, imp->location());
5998 // Dump ast representation of a binary expression.
6001 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6003 ast_dump_context->ostream() << "(";
6004 ast_dump_context->dump_expression(this->left_);
6005 ast_dump_context->ostream() << " ";
6006 ast_dump_context->dump_operator(this->op_);
6007 ast_dump_context->ostream() << " ";
6008 ast_dump_context->dump_expression(this->right_);
6009 ast_dump_context->ostream() << ") ";
6012 // Make a binary expression.
6015 Expression::make_binary(Operator op, Expression* left, Expression* right,
6018 return new Binary_expression(op, left, right, location);
6021 // Implement a comparison.
6024 Expression::comparison_tree(Translate_context* context, Operator op,
6025 Type* left_type, tree left_tree,
6026 Type* right_type, tree right_tree,
6029 enum tree_code code;
6035 case OPERATOR_NOTEQ:
6054 if (left_type->is_string_type() && right_type->is_string_type())
6056 Type* st = Type::make_string_type();
6057 tree string_type = type_to_tree(st->get_backend(context->gogo()));
6058 static tree string_compare_decl;
6059 left_tree = Gogo::call_builtin(&string_compare_decl,
6068 right_tree = build_int_cst_type(integer_type_node, 0);
6070 else if ((left_type->interface_type() != NULL
6071 && right_type->interface_type() == NULL
6072 && !right_type->is_nil_type())
6073 || (left_type->interface_type() == NULL
6074 && !left_type->is_nil_type()
6075 && right_type->interface_type() != NULL))
6077 // Comparing an interface value to a non-interface value.
6078 if (left_type->interface_type() == NULL)
6080 std::swap(left_type, right_type);
6081 std::swap(left_tree, right_tree);
6084 // The right operand is not an interface. We need to take its
6085 // address if it is not a pointer.
6088 if (right_type->points_to() != NULL)
6090 make_tmp = NULL_TREE;
6093 else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree)) || DECL_P(right_tree))
6095 make_tmp = NULL_TREE;
6096 arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6097 if (DECL_P(right_tree))
6098 TREE_ADDRESSABLE(right_tree) = 1;
6102 tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6103 get_name(right_tree));
6104 DECL_IGNORED_P(tmp) = 0;
6105 DECL_INITIAL(tmp) = right_tree;
6106 TREE_ADDRESSABLE(tmp) = 1;
6107 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6108 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6109 arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6111 arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6113 tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
6116 if (left_type->interface_type()->is_empty())
6118 static tree empty_interface_value_compare_decl;
6119 left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6121 "__go_empty_interface_value_compare",
6124 TREE_TYPE(left_tree),
6126 TREE_TYPE(descriptor),
6130 if (left_tree == error_mark_node)
6131 return error_mark_node;
6132 // This can panic if the type is not comparable.
6133 TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6137 static tree interface_value_compare_decl;
6138 left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6140 "__go_interface_value_compare",
6143 TREE_TYPE(left_tree),
6145 TREE_TYPE(descriptor),
6149 if (left_tree == error_mark_node)
6150 return error_mark_node;
6151 // This can panic if the type is not comparable.
6152 TREE_NOTHROW(interface_value_compare_decl) = 0;
6154 right_tree = build_int_cst_type(integer_type_node, 0);
6156 if (make_tmp != NULL_TREE)
6157 left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6160 else if (left_type->interface_type() != NULL
6161 && right_type->interface_type() != NULL)
6163 if (left_type->interface_type()->is_empty()
6164 && right_type->interface_type()->is_empty())
6166 static tree empty_interface_compare_decl;
6167 left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6169 "__go_empty_interface_compare",
6172 TREE_TYPE(left_tree),
6174 TREE_TYPE(right_tree),
6176 if (left_tree == error_mark_node)
6177 return error_mark_node;
6178 // This can panic if the type is uncomparable.
6179 TREE_NOTHROW(empty_interface_compare_decl) = 0;
6181 else if (!left_type->interface_type()->is_empty()
6182 && !right_type->interface_type()->is_empty())
6184 static tree interface_compare_decl;
6185 left_tree = Gogo::call_builtin(&interface_compare_decl,
6187 "__go_interface_compare",
6190 TREE_TYPE(left_tree),
6192 TREE_TYPE(right_tree),
6194 if (left_tree == error_mark_node)
6195 return error_mark_node;
6196 // This can panic if the type is uncomparable.
6197 TREE_NOTHROW(interface_compare_decl) = 0;
6201 if (left_type->interface_type()->is_empty())
6203 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6204 std::swap(left_type, right_type);
6205 std::swap(left_tree, right_tree);
6207 go_assert(!left_type->interface_type()->is_empty());
6208 go_assert(right_type->interface_type()->is_empty());
6209 static tree interface_empty_compare_decl;
6210 left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6212 "__go_interface_empty_compare",
6215 TREE_TYPE(left_tree),
6217 TREE_TYPE(right_tree),
6219 if (left_tree == error_mark_node)
6220 return error_mark_node;
6221 // This can panic if the type is uncomparable.
6222 TREE_NOTHROW(interface_empty_compare_decl) = 0;
6225 right_tree = build_int_cst_type(integer_type_node, 0);
6228 if (left_type->is_nil_type()
6229 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6231 std::swap(left_type, right_type);
6232 std::swap(left_tree, right_tree);
6235 if (right_type->is_nil_type())
6237 if (left_type->array_type() != NULL
6238 && left_type->array_type()->length() == NULL)
6240 Array_type* at = left_type->array_type();
6241 left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6242 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6244 else if (left_type->interface_type() != NULL)
6246 // An interface is nil if the first field is nil.
6247 tree left_type_tree = TREE_TYPE(left_tree);
6248 go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6249 tree field = TYPE_FIELDS(left_type_tree);
6250 left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6252 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6256 go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6257 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6261 if (left_tree == error_mark_node || right_tree == error_mark_node)
6262 return error_mark_node;
6264 tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
6265 if (CAN_HAVE_LOCATION_P(ret))
6266 SET_EXPR_LOCATION(ret, location.gcc_location());
6270 // Class Bound_method_expression.
6275 Bound_method_expression::do_traverse(Traverse* traverse)
6277 return Expression::traverse(&this->expr_, traverse);
6280 // Return the type of a bound method expression. The type of this
6281 // object is really the type of the method with no receiver. We
6282 // should be able to get away with just returning the type of the
6286 Bound_method_expression::do_type()
6288 if (this->method_->is_function())
6289 return this->method_->func_value()->type();
6290 else if (this->method_->is_function_declaration())
6291 return this->method_->func_declaration_value()->type();
6293 return Type::make_error_type();
6296 // Determine the types of a method expression.
6299 Bound_method_expression::do_determine_type(const Type_context*)
6301 Function_type* fntype = this->type()->function_type();
6302 if (fntype == NULL || !fntype->is_method())
6303 this->expr_->determine_type_no_context();
6306 Type_context subcontext(fntype->receiver()->type(), false);
6307 this->expr_->determine_type(&subcontext);
6311 // Check the types of a method expression.
6314 Bound_method_expression::do_check_types(Gogo*)
6316 if (!this->method_->is_function()
6317 && !this->method_->is_function_declaration())
6318 this->report_error(_("object is not a method"));
6321 Type* rtype = this->type()->function_type()->receiver()->type()->deref();
6322 Type* etype = (this->expr_type_ != NULL
6324 : this->expr_->type());
6325 etype = etype->deref();
6326 if (!Type::are_identical(rtype, etype, true, NULL))
6327 this->report_error(_("method type does not match object type"));
6331 // Get the tree for a method expression. There is no standard tree
6332 // representation for this. The only places it may currently be used
6333 // are in a Call_expression or a Go_statement, which will take it
6334 // apart directly. So this has nothing to do at present.
6337 Bound_method_expression::do_get_tree(Translate_context*)
6339 error_at(this->location(), "reference to method other than calling it");
6340 return error_mark_node;
6343 // Dump ast representation of a bound method expression.
6346 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6349 if (this->expr_type_ != NULL)
6350 ast_dump_context->ostream() << "(";
6351 ast_dump_context->dump_expression(this->expr_);
6352 if (this->expr_type_ != NULL)
6354 ast_dump_context->ostream() << ":";
6355 ast_dump_context->dump_type(this->expr_type_);
6356 ast_dump_context->ostream() << ")";
6359 ast_dump_context->ostream() << "." << this->method_->name();
6362 // Make a method expression.
6364 Bound_method_expression*
6365 Expression::make_bound_method(Expression* expr, Named_object* method,
6368 return new Bound_method_expression(expr, method, location);
6371 // Class Builtin_call_expression. This is used for a call to a
6372 // builtin function.
6374 class Builtin_call_expression : public Call_expression
6377 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6378 bool is_varargs, Location location);
6381 // This overrides Call_expression::do_lower.
6383 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6386 do_is_constant() const;
6389 do_numeric_constant_value(Numeric_constant*) const;
6392 do_discarding_value();
6398 do_determine_type(const Type_context*);
6401 do_check_types(Gogo*);
6406 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6407 this->args()->copy(),
6413 do_get_tree(Translate_context*);
6416 do_export(Export*) const;
6419 do_is_recover_call() const;
6422 do_set_recover_arg(Expression*);
6425 // The builtin functions.
6426 enum Builtin_function_code
6430 // Predeclared builtin functions.
6447 // Builtin functions from the unsafe package.
6460 real_imag_type(Type*);
6463 complex_type(Type*);
6469 check_int_value(Expression*);
6471 // A pointer back to the general IR structure. This avoids a global
6472 // variable, or passing it around everywhere.
6474 // The builtin function being called.
6475 Builtin_function_code code_;
6476 // Used to stop endless loops when the length of an array uses len
6477 // or cap of the array itself.
6481 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6483 Expression_list* args,
6486 : Call_expression(fn, args, is_varargs, location),
6487 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6489 Func_expression* fnexp = this->fn()->func_expression();
6490 go_assert(fnexp != NULL);
6491 const std::string& name(fnexp->named_object()->name());
6492 if (name == "append")
6493 this->code_ = BUILTIN_APPEND;
6494 else if (name == "cap")
6495 this->code_ = BUILTIN_CAP;
6496 else if (name == "close")
6497 this->code_ = BUILTIN_CLOSE;
6498 else if (name == "complex")
6499 this->code_ = BUILTIN_COMPLEX;
6500 else if (name == "copy")
6501 this->code_ = BUILTIN_COPY;
6502 else if (name == "delete")
6503 this->code_ = BUILTIN_DELETE;
6504 else if (name == "imag")
6505 this->code_ = BUILTIN_IMAG;
6506 else if (name == "len")
6507 this->code_ = BUILTIN_LEN;
6508 else if (name == "make")
6509 this->code_ = BUILTIN_MAKE;
6510 else if (name == "new")
6511 this->code_ = BUILTIN_NEW;
6512 else if (name == "panic")
6513 this->code_ = BUILTIN_PANIC;
6514 else if (name == "print")
6515 this->code_ = BUILTIN_PRINT;
6516 else if (name == "println")
6517 this->code_ = BUILTIN_PRINTLN;
6518 else if (name == "real")
6519 this->code_ = BUILTIN_REAL;
6520 else if (name == "recover")
6521 this->code_ = BUILTIN_RECOVER;
6522 else if (name == "Alignof")
6523 this->code_ = BUILTIN_ALIGNOF;
6524 else if (name == "Offsetof")
6525 this->code_ = BUILTIN_OFFSETOF;
6526 else if (name == "Sizeof")
6527 this->code_ = BUILTIN_SIZEOF;
6532 // Return whether this is a call to recover. This is a virtual
6533 // function called from the parent class.
6536 Builtin_call_expression::do_is_recover_call() const
6538 if (this->classification() == EXPRESSION_ERROR)
6540 return this->code_ == BUILTIN_RECOVER;
6543 // Set the argument for a call to recover.
6546 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6548 const Expression_list* args = this->args();
6549 go_assert(args == NULL || args->empty());
6550 Expression_list* new_args = new Expression_list();
6551 new_args->push_back(arg);
6552 this->set_args(new_args);
6555 // A traversal class which looks for a call expression.
6557 class Find_call_expression : public Traverse
6560 Find_call_expression()
6561 : Traverse(traverse_expressions),
6566 expression(Expression**);
6570 { return this->found_; }
6577 Find_call_expression::expression(Expression** pexpr)
6579 if ((*pexpr)->call_expression() != NULL)
6581 this->found_ = true;
6582 return TRAVERSE_EXIT;
6584 return TRAVERSE_CONTINUE;
6587 // Lower a builtin call expression. This turns new and make into
6588 // specific expressions. We also convert to a constant if we can.
6591 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6592 Statement_inserter* inserter, int)
6594 if (this->classification() == EXPRESSION_ERROR)
6597 Location loc = this->location();
6599 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6601 this->report_error(_("invalid use of %<...%> with builtin function"));
6602 return Expression::make_error(loc);
6605 if (this->is_constant())
6607 // We can only lower len and cap if there are no function calls
6608 // in the arguments. Otherwise we have to make the call.
6609 if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
6611 Expression* arg = this->one_arg();
6612 if (arg != NULL && !arg->is_constant())
6614 Find_call_expression find_call;
6615 Expression::traverse(&arg, &find_call);
6616 if (find_call.found())
6621 Numeric_constant nc;
6622 if (this->numeric_constant_value(&nc))
6623 return nc.expression(loc);
6626 switch (this->code_)
6633 const Expression_list* args = this->args();
6634 if (args == NULL || args->size() < 1)
6635 this->report_error(_("not enough arguments"));
6636 else if (args->size() > 1)
6637 this->report_error(_("too many arguments"));
6640 Expression* arg = args->front();
6641 if (!arg->is_type_expression())
6643 error_at(arg->location(), "expected type");
6644 this->set_is_error();
6647 return Expression::make_allocation(arg->type(), loc);
6653 return this->lower_make();
6655 case BUILTIN_RECOVER:
6656 if (function != NULL)
6657 function->func_value()->set_calls_recover();
6660 // Calling recover outside of a function always returns the
6661 // nil empty interface.
6662 Type* eface = Type::make_empty_interface_type(loc);
6663 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6667 case BUILTIN_APPEND:
6669 // Lower the varargs.
6670 const Expression_list* args = this->args();
6671 if (args == NULL || args->empty())
6673 Type* slice_type = args->front()->type();
6674 if (!slice_type->is_slice_type())
6676 error_at(args->front()->location(), "argument 1 must be a slice");
6677 this->set_is_error();
6680 Type* element_type = slice_type->array_type()->element_type();
6681 this->lower_varargs(gogo, function, inserter,
6682 Type::make_array_type(element_type, NULL),
6687 case BUILTIN_DELETE:
6689 // Lower to a runtime function call.
6690 const Expression_list* args = this->args();
6691 if (args == NULL || args->size() < 2)
6692 this->report_error(_("not enough arguments"));
6693 else if (args->size() > 2)
6694 this->report_error(_("too many arguments"));
6695 else if (args->front()->type()->map_type() == NULL)
6696 this->report_error(_("argument 1 must be a map"));
6699 // Since this function returns no value it must appear in
6700 // a statement by itself, so we don't have to worry about
6701 // order of evaluation of values around it. Evaluate the
6702 // map first to get order of evaluation right.
6703 Map_type* mt = args->front()->type()->map_type();
6704 Temporary_statement* map_temp =
6705 Statement::make_temporary(mt, args->front(), loc);
6706 inserter->insert(map_temp);
6708 Temporary_statement* key_temp =
6709 Statement::make_temporary(mt->key_type(), args->back(), loc);
6710 inserter->insert(key_temp);
6712 Expression* e1 = Expression::make_temporary_reference(map_temp,
6714 Expression* e2 = Expression::make_temporary_reference(key_temp,
6716 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6717 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6727 // Lower a make expression.
6730 Builtin_call_expression::lower_make()
6732 Location loc = this->location();
6734 const Expression_list* args = this->args();
6735 if (args == NULL || args->size() < 1)
6737 this->report_error(_("not enough arguments"));
6738 return Expression::make_error(this->location());
6741 Expression_list::const_iterator parg = args->begin();
6743 Expression* first_arg = *parg;
6744 if (!first_arg->is_type_expression())
6746 error_at(first_arg->location(), "expected type");
6747 this->set_is_error();
6748 return Expression::make_error(this->location());
6750 Type* type = first_arg->type();
6752 bool is_slice = false;
6753 bool is_map = false;
6754 bool is_chan = false;
6755 if (type->is_slice_type())
6757 else if (type->map_type() != NULL)
6759 else if (type->channel_type() != NULL)
6763 this->report_error(_("invalid type for make function"));
6764 return Expression::make_error(this->location());
6767 bool have_big_args = false;
6768 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6769 int uintptr_bits = uintptr_type->integer_type()->bits();
6772 Expression* len_arg;
6773 if (parg == args->end())
6777 this->report_error(_("length required when allocating a slice"));
6778 return Expression::make_error(this->location());
6782 mpz_init_set_ui(zval, 0);
6783 len_arg = Expression::make_integer(&zval, NULL, loc);
6789 if (!this->check_int_value(len_arg))
6791 this->report_error(_("bad size for make"));
6792 return Expression::make_error(this->location());
6794 if (len_arg->type()->integer_type() != NULL
6795 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6796 have_big_args = true;
6800 Expression* cap_arg = NULL;
6801 if (is_slice && parg != args->end())
6804 if (!this->check_int_value(cap_arg))
6806 this->report_error(_("bad capacity when making slice"));
6807 return Expression::make_error(this->location());
6809 if (cap_arg->type()->integer_type() != NULL
6810 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6811 have_big_args = true;
6815 if (parg != args->end())
6817 this->report_error(_("too many arguments to make"));
6818 return Expression::make_error(this->location());
6821 Location type_loc = first_arg->location();
6822 Expression* type_arg;
6823 if (is_slice || is_chan)
6824 type_arg = Expression::make_type_descriptor(type, type_loc);
6826 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6833 if (cap_arg == NULL)
6834 call = Runtime::make_call((have_big_args
6835 ? Runtime::MAKESLICE1BIG
6836 : Runtime::MAKESLICE1),
6837 loc, 2, type_arg, len_arg);
6839 call = Runtime::make_call((have_big_args
6840 ? Runtime::MAKESLICE2BIG
6841 : Runtime::MAKESLICE2),
6842 loc, 3, type_arg, len_arg, cap_arg);
6845 call = Runtime::make_call((have_big_args
6846 ? Runtime::MAKEMAPBIG
6847 : Runtime::MAKEMAP),
6848 loc, 2, type_arg, len_arg);
6850 call = Runtime::make_call((have_big_args
6851 ? Runtime::MAKECHANBIG
6852 : Runtime::MAKECHAN),
6853 loc, 2, type_arg, len_arg);
6857 return Expression::make_unsafe_cast(type, call, loc);
6860 // Return whether an expression has an integer value. Report an error
6861 // if not. This is used when handling calls to the predeclared make
6865 Builtin_call_expression::check_int_value(Expression* e)
6867 if (e->type()->integer_type() != NULL)
6870 // Check for a floating point constant with integer value.
6871 Numeric_constant nc;
6873 if (e->numeric_constant_value(&nc) && nc.to_int(&ival))
6882 // Return the type of the real or imag functions, given the type of
6883 // the argument. We need to map complex to float, complex64 to
6884 // float32, and complex128 to float64, so it has to be done by name.
6885 // This returns NULL if it can't figure out the type.
6888 Builtin_call_expression::real_imag_type(Type* arg_type)
6890 if (arg_type == NULL || arg_type->is_abstract())
6892 Named_type* nt = arg_type->named_type();
6895 while (nt->real_type()->named_type() != NULL)
6896 nt = nt->real_type()->named_type();
6897 if (nt->name() == "complex64")
6898 return Type::lookup_float_type("float32");
6899 else if (nt->name() == "complex128")
6900 return Type::lookup_float_type("float64");
6905 // Return the type of the complex function, given the type of one of the
6906 // argments. Like real_imag_type, we have to map by name.
6909 Builtin_call_expression::complex_type(Type* arg_type)
6911 if (arg_type == NULL || arg_type->is_abstract())
6913 Named_type* nt = arg_type->named_type();
6916 while (nt->real_type()->named_type() != NULL)
6917 nt = nt->real_type()->named_type();
6918 if (nt->name() == "float32")
6919 return Type::lookup_complex_type("complex64");
6920 else if (nt->name() == "float64")
6921 return Type::lookup_complex_type("complex128");
6926 // Return a single argument, or NULL if there isn't one.
6929 Builtin_call_expression::one_arg() const
6931 const Expression_list* args = this->args();
6932 if (args == NULL || args->size() != 1)
6934 return args->front();
6937 // Return whether this is constant: len of a string, or len or cap of
6938 // a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
6941 Builtin_call_expression::do_is_constant() const
6943 switch (this->code_)
6951 Expression* arg = this->one_arg();
6954 Type* arg_type = arg->type();
6956 if (arg_type->points_to() != NULL
6957 && arg_type->points_to()->array_type() != NULL
6958 && !arg_type->points_to()->is_slice_type())
6959 arg_type = arg_type->points_to();
6961 if (arg_type->array_type() != NULL
6962 && arg_type->array_type()->length() != NULL)
6965 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
6968 bool ret = arg->is_constant();
6969 this->seen_ = false;
6975 case BUILTIN_SIZEOF:
6976 case BUILTIN_ALIGNOF:
6977 return this->one_arg() != NULL;
6979 case BUILTIN_OFFSETOF:
6981 Expression* arg = this->one_arg();
6984 return arg->field_reference_expression() != NULL;
6987 case BUILTIN_COMPLEX:
6989 const Expression_list* args = this->args();
6990 if (args != NULL && args->size() == 2)
6991 return args->front()->is_constant() && args->back()->is_constant();
6998 Expression* arg = this->one_arg();
6999 return arg != NULL && arg->is_constant();
7009 // Return a numeric constant if possible.
7012 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7014 if (this->code_ == BUILTIN_LEN
7015 || this->code_ == BUILTIN_CAP)
7017 Expression* arg = this->one_arg();
7020 Type* arg_type = arg->type();
7022 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7025 if (arg->string_constant_value(&sval))
7027 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7033 if (arg_type->points_to() != NULL
7034 && arg_type->points_to()->array_type() != NULL
7035 && !arg_type->points_to()->is_slice_type())
7036 arg_type = arg_type->points_to();
7038 if (arg_type->array_type() != NULL
7039 && arg_type->array_type()->length() != NULL)
7043 Expression* e = arg_type->array_type()->length();
7045 bool r = e->numeric_constant_value(nc);
7046 this->seen_ = false;
7049 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7056 else if (this->code_ == BUILTIN_SIZEOF
7057 || this->code_ == BUILTIN_ALIGNOF)
7059 Expression* arg = this->one_arg();
7062 Type* arg_type = arg->type();
7063 if (arg_type->is_error())
7065 if (arg_type->is_abstract())
7067 if (arg_type->named_type() != NULL)
7068 arg_type->named_type()->convert(this->gogo_);
7071 if (this->code_ == BUILTIN_SIZEOF)
7073 if (!arg_type->backend_type_size(this->gogo_, &ret))
7076 else if (this->code_ == BUILTIN_ALIGNOF)
7078 if (arg->field_reference_expression() == NULL)
7080 if (!arg_type->backend_type_align(this->gogo_, &ret))
7085 // Calling unsafe.Alignof(s.f) returns the alignment of
7086 // the type of f when it is used as a field in a struct.
7087 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7094 nc->set_unsigned_long(NULL, static_cast<unsigned long>(ret));
7097 else if (this->code_ == BUILTIN_OFFSETOF)
7099 Expression* arg = this->one_arg();
7102 Field_reference_expression* farg = arg->field_reference_expression();
7105 Expression* struct_expr = farg->expr();
7106 Type* st = struct_expr->type();
7107 if (st->struct_type() == NULL)
7109 if (st->named_type() != NULL)
7110 st->named_type()->convert(this->gogo_);
7111 unsigned int offset;
7112 if (!st->struct_type()->backend_field_offset(this->gogo_,
7113 farg->field_index(),
7116 nc->set_unsigned_long(NULL, static_cast<unsigned long>(offset));
7119 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7121 Expression* arg = this->one_arg();
7125 Numeric_constant argnc;
7126 if (!arg->numeric_constant_value(&argnc))
7131 if (!argnc.to_complex(&real, &imag))
7134 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7135 if (this->code_ == BUILTIN_REAL)
7136 nc->set_float(type, real);
7138 nc->set_float(type, imag);
7141 else if (this->code_ == BUILTIN_COMPLEX)
7143 const Expression_list* args = this->args();
7144 if (args == NULL || args->size() != 2)
7147 Numeric_constant rnc;
7148 if (!args->front()->numeric_constant_value(&rnc))
7150 Numeric_constant inc;
7151 if (!args->back()->numeric_constant_value(&inc))
7154 if (rnc.type() != NULL
7155 && !rnc.type()->is_abstract()
7156 && inc.type() != NULL
7157 && !inc.type()->is_abstract()
7158 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7162 if (!rnc.to_float(&r))
7165 if (!inc.to_float(&i))
7171 Type* arg_type = rnc.type();
7172 if (arg_type == NULL || arg_type->is_abstract())
7173 arg_type = inc.type();
7175 Type* type = Builtin_call_expression::complex_type(arg_type);
7176 nc->set_complex(type, r, i);
7187 // Give an error if we are discarding the value of an expression which
7188 // should not normally be discarded. We don't give an error for
7189 // discarding the value of an ordinary function call, but we do for
7190 // builtin functions, purely for consistency with the gc compiler.
7193 Builtin_call_expression::do_discarding_value()
7195 switch (this->code_)
7197 case BUILTIN_INVALID:
7201 case BUILTIN_APPEND:
7203 case BUILTIN_COMPLEX:
7209 case BUILTIN_ALIGNOF:
7210 case BUILTIN_OFFSETOF:
7211 case BUILTIN_SIZEOF:
7212 this->unused_value_error();
7217 case BUILTIN_DELETE:
7220 case BUILTIN_PRINTLN:
7221 case BUILTIN_RECOVER:
7229 Builtin_call_expression::do_type()
7231 switch (this->code_)
7233 case BUILTIN_INVALID:
7240 const Expression_list* args = this->args();
7241 if (args == NULL || args->empty())
7242 return Type::make_error_type();
7243 return Type::make_pointer_type(args->front()->type());
7249 case BUILTIN_ALIGNOF:
7250 case BUILTIN_OFFSETOF:
7251 case BUILTIN_SIZEOF:
7252 return Type::lookup_integer_type("int");
7255 case BUILTIN_DELETE:
7258 case BUILTIN_PRINTLN:
7259 return Type::make_void_type();
7261 case BUILTIN_RECOVER:
7262 return Type::make_empty_interface_type(Linemap::predeclared_location());
7264 case BUILTIN_APPEND:
7266 const Expression_list* args = this->args();
7267 if (args == NULL || args->empty())
7268 return Type::make_error_type();
7269 return args->front()->type();
7275 Expression* arg = this->one_arg();
7277 return Type::make_error_type();
7278 Type* t = arg->type();
7279 if (t->is_abstract())
7280 t = t->make_non_abstract_type();
7281 t = Builtin_call_expression::real_imag_type(t);
7283 t = Type::make_error_type();
7287 case BUILTIN_COMPLEX:
7289 const Expression_list* args = this->args();
7290 if (args == NULL || args->size() != 2)
7291 return Type::make_error_type();
7292 Type* t = args->front()->type();
7293 if (t->is_abstract())
7295 t = args->back()->type();
7296 if (t->is_abstract())
7297 t = t->make_non_abstract_type();
7299 t = Builtin_call_expression::complex_type(t);
7301 t = Type::make_error_type();
7307 // Determine the type.
7310 Builtin_call_expression::do_determine_type(const Type_context* context)
7312 if (!this->determining_types())
7315 this->fn()->determine_type_no_context();
7317 const Expression_list* args = this->args();
7320 Type* arg_type = NULL;
7321 switch (this->code_)
7324 case BUILTIN_PRINTLN:
7325 // Do not force a large integer constant to "int".
7331 arg_type = Builtin_call_expression::complex_type(context->type);
7335 case BUILTIN_COMPLEX:
7337 // For the complex function the type of one operand can
7338 // determine the type of the other, as in a binary expression.
7339 arg_type = Builtin_call_expression::real_imag_type(context->type);
7340 if (args != NULL && args->size() == 2)
7342 Type* t1 = args->front()->type();
7343 Type* t2 = args->front()->type();
7344 if (!t1->is_abstract())
7346 else if (!t2->is_abstract())
7360 for (Expression_list::const_iterator pa = args->begin();
7364 Type_context subcontext;
7365 subcontext.type = arg_type;
7369 // We want to print large constants, we so can't just
7370 // use the appropriate nonabstract type. Use uint64 for
7371 // an integer if we know it is nonnegative, otherwise
7372 // use int64 for a integer, otherwise use float64 for a
7373 // float or complex128 for a complex.
7374 Type* want_type = NULL;
7375 Type* atype = (*pa)->type();
7376 if (atype->is_abstract())
7378 if (atype->integer_type() != NULL)
7380 Numeric_constant nc;
7381 if (this->numeric_constant_value(&nc))
7384 if (nc.to_int(&val))
7386 if (mpz_sgn(val) >= 0)
7387 want_type = Type::lookup_integer_type("uint64");
7391 if (want_type == NULL)
7392 want_type = Type::lookup_integer_type("int64");
7394 else if (atype->float_type() != NULL)
7395 want_type = Type::lookup_float_type("float64");
7396 else if (atype->complex_type() != NULL)
7397 want_type = Type::lookup_complex_type("complex128");
7398 else if (atype->is_abstract_string_type())
7399 want_type = Type::lookup_string_type();
7400 else if (atype->is_abstract_boolean_type())
7401 want_type = Type::lookup_bool_type();
7404 subcontext.type = want_type;
7408 (*pa)->determine_type(&subcontext);
7413 // If there is exactly one argument, return true. Otherwise give an
7414 // error message and return false.
7417 Builtin_call_expression::check_one_arg()
7419 const Expression_list* args = this->args();
7420 if (args == NULL || args->size() < 1)
7422 this->report_error(_("not enough arguments"));
7425 else if (args->size() > 1)
7427 this->report_error(_("too many arguments"));
7430 if (args->front()->is_error_expression()
7431 || args->front()->type()->is_error())
7433 this->set_is_error();
7439 // Check argument types for a builtin function.
7442 Builtin_call_expression::do_check_types(Gogo*)
7444 if (this->is_error_expression())
7446 switch (this->code_)
7448 case BUILTIN_INVALID:
7451 case BUILTIN_DELETE:
7457 // The single argument may be either a string or an array or a
7458 // map or a channel, or a pointer to a closed array.
7459 if (this->check_one_arg())
7461 Type* arg_type = this->one_arg()->type();
7462 if (arg_type->points_to() != NULL
7463 && arg_type->points_to()->array_type() != NULL
7464 && !arg_type->points_to()->is_slice_type())
7465 arg_type = arg_type->points_to();
7466 if (this->code_ == BUILTIN_CAP)
7468 if (!arg_type->is_error()
7469 && arg_type->array_type() == NULL
7470 && arg_type->channel_type() == NULL)
7471 this->report_error(_("argument must be array or slice "
7476 if (!arg_type->is_error()
7477 && !arg_type->is_string_type()
7478 && arg_type->array_type() == NULL
7479 && arg_type->map_type() == NULL
7480 && arg_type->channel_type() == NULL)
7481 this->report_error(_("argument must be string or "
7482 "array or slice or map or channel"));
7489 case BUILTIN_PRINTLN:
7491 const Expression_list* args = this->args();
7494 if (this->code_ == BUILTIN_PRINT)
7495 warning_at(this->location(), 0,
7496 "no arguments for builtin function %<%s%>",
7497 (this->code_ == BUILTIN_PRINT
7503 for (Expression_list::const_iterator p = args->begin();
7507 Type* type = (*p)->type();
7508 if (type->is_error()
7509 || type->is_string_type()
7510 || type->integer_type() != NULL
7511 || type->float_type() != NULL
7512 || type->complex_type() != NULL
7513 || type->is_boolean_type()
7514 || type->points_to() != NULL
7515 || type->interface_type() != NULL
7516 || type->channel_type() != NULL
7517 || type->map_type() != NULL
7518 || type->function_type() != NULL
7519 || type->is_slice_type())
7521 else if ((*p)->is_type_expression())
7523 // If this is a type expression it's going to give
7524 // an error anyhow, so we don't need one here.
7527 this->report_error(_("unsupported argument type to "
7528 "builtin function"));
7535 if (this->check_one_arg())
7537 if (this->one_arg()->type()->channel_type() == NULL)
7538 this->report_error(_("argument must be channel"));
7539 else if (!this->one_arg()->type()->channel_type()->may_send())
7540 this->report_error(_("cannot close receive-only channel"));
7545 case BUILTIN_SIZEOF:
7546 case BUILTIN_ALIGNOF:
7547 this->check_one_arg();
7550 case BUILTIN_RECOVER:
7551 if (this->args() != NULL && !this->args()->empty())
7552 this->report_error(_("too many arguments"));
7555 case BUILTIN_OFFSETOF:
7556 if (this->check_one_arg())
7558 Expression* arg = this->one_arg();
7559 if (arg->field_reference_expression() == NULL)
7560 this->report_error(_("argument must be a field reference"));
7566 const Expression_list* args = this->args();
7567 if (args == NULL || args->size() < 2)
7569 this->report_error(_("not enough arguments"));
7572 else if (args->size() > 2)
7574 this->report_error(_("too many arguments"));
7577 Type* arg1_type = args->front()->type();
7578 Type* arg2_type = args->back()->type();
7579 if (arg1_type->is_error() || arg2_type->is_error())
7583 if (arg1_type->is_slice_type())
7584 e1 = arg1_type->array_type()->element_type();
7587 this->report_error(_("left argument must be a slice"));
7591 if (arg2_type->is_slice_type())
7593 Type* e2 = arg2_type->array_type()->element_type();
7594 if (!Type::are_identical(e1, e2, true, NULL))
7595 this->report_error(_("element types must be the same"));
7597 else if (arg2_type->is_string_type())
7599 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7600 this->report_error(_("first argument must be []byte"));
7603 this->report_error(_("second argument must be slice or string"));
7607 case BUILTIN_APPEND:
7609 const Expression_list* args = this->args();
7610 if (args == NULL || args->size() < 2)
7612 this->report_error(_("not enough arguments"));
7615 if (args->size() > 2)
7617 this->report_error(_("too many arguments"));
7620 if (args->front()->type()->is_error()
7621 || args->back()->type()->is_error())
7624 Array_type* at = args->front()->type()->array_type();
7625 Type* e = at->element_type();
7627 // The language permits appending a string to a []byte, as a
7629 if (args->back()->type()->is_string_type())
7631 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7635 // The language says that the second argument must be
7636 // assignable to a slice of the element type of the first
7637 // argument. We already know the first argument is a slice
7639 Type* arg2_type = Type::make_array_type(e, NULL);
7641 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7644 this->report_error(_("argument 2 has invalid type"));
7647 error_at(this->location(), "argument 2 has invalid type (%s)",
7649 this->set_is_error();
7657 if (this->check_one_arg())
7659 if (this->one_arg()->type()->complex_type() == NULL)
7660 this->report_error(_("argument must have complex type"));
7664 case BUILTIN_COMPLEX:
7666 const Expression_list* args = this->args();
7667 if (args == NULL || args->size() < 2)
7668 this->report_error(_("not enough arguments"));
7669 else if (args->size() > 2)
7670 this->report_error(_("too many arguments"));
7671 else if (args->front()->is_error_expression()
7672 || args->front()->type()->is_error()
7673 || args->back()->is_error_expression()
7674 || args->back()->type()->is_error())
7675 this->set_is_error();
7676 else if (!Type::are_identical(args->front()->type(),
7677 args->back()->type(), true, NULL))
7678 this->report_error(_("complex arguments must have identical types"));
7679 else if (args->front()->type()->float_type() == NULL)
7680 this->report_error(_("complex arguments must have "
7681 "floating-point type"));
7690 // Return the tree for a builtin function.
7693 Builtin_call_expression::do_get_tree(Translate_context* context)
7695 Gogo* gogo = context->gogo();
7696 Location location = this->location();
7697 switch (this->code_)
7699 case BUILTIN_INVALID:
7707 const Expression_list* args = this->args();
7708 go_assert(args != NULL && args->size() == 1);
7709 Expression* arg = *args->begin();
7710 Type* arg_type = arg->type();
7714 go_assert(saw_errors());
7715 return error_mark_node;
7719 tree arg_tree = arg->get_tree(context);
7721 this->seen_ = false;
7723 if (arg_tree == error_mark_node)
7724 return error_mark_node;
7726 if (arg_type->points_to() != NULL)
7728 arg_type = arg_type->points_to();
7729 go_assert(arg_type->array_type() != NULL
7730 && !arg_type->is_slice_type());
7731 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
7732 arg_tree = build_fold_indirect_ref(arg_tree);
7736 if (this->code_ == BUILTIN_LEN)
7738 if (arg_type->is_string_type())
7739 val_tree = String_type::length_tree(gogo, arg_tree);
7740 else if (arg_type->array_type() != NULL)
7744 go_assert(saw_errors());
7745 return error_mark_node;
7748 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
7749 this->seen_ = false;
7751 else if (arg_type->map_type() != NULL)
7753 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7754 static tree map_len_fndecl;
7755 val_tree = Gogo::call_builtin(&map_len_fndecl,
7763 else if (arg_type->channel_type() != NULL)
7765 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7766 static tree chan_len_fndecl;
7767 val_tree = Gogo::call_builtin(&chan_len_fndecl,
7780 if (arg_type->array_type() != NULL)
7784 go_assert(saw_errors());
7785 return error_mark_node;
7788 val_tree = arg_type->array_type()->capacity_tree(gogo,
7790 this->seen_ = false;
7792 else if (arg_type->channel_type() != NULL)
7794 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7795 static tree chan_cap_fndecl;
7796 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
7808 if (val_tree == error_mark_node)
7809 return error_mark_node;
7811 Type* int_type = Type::lookup_integer_type("int");
7812 tree type_tree = type_to_tree(int_type->get_backend(gogo));
7813 if (type_tree == TREE_TYPE(val_tree))
7816 return fold(convert_to_integer(type_tree, val_tree));
7820 case BUILTIN_PRINTLN:
7822 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7823 tree stmt_list = NULL_TREE;
7825 const Expression_list* call_args = this->args();
7826 if (call_args != NULL)
7828 for (Expression_list::const_iterator p = call_args->begin();
7829 p != call_args->end();
7832 if (is_ln && p != call_args->begin())
7834 static tree print_space_fndecl;
7835 tree call = Gogo::call_builtin(&print_space_fndecl,
7840 if (call == error_mark_node)
7841 return error_mark_node;
7842 append_to_statement_list(call, &stmt_list);
7845 Type* type = (*p)->type();
7847 tree arg = (*p)->get_tree(context);
7848 if (arg == error_mark_node)
7849 return error_mark_node;
7853 if (type->is_string_type())
7855 static tree print_string_fndecl;
7856 pfndecl = &print_string_fndecl;
7857 fnname = "__go_print_string";
7859 else if (type->integer_type() != NULL
7860 && type->integer_type()->is_unsigned())
7862 static tree print_uint64_fndecl;
7863 pfndecl = &print_uint64_fndecl;
7864 fnname = "__go_print_uint64";
7865 Type* itype = Type::lookup_integer_type("uint64");
7866 Btype* bitype = itype->get_backend(gogo);
7867 arg = fold_convert_loc(location.gcc_location(),
7868 type_to_tree(bitype), arg);
7870 else if (type->integer_type() != NULL)
7872 static tree print_int64_fndecl;
7873 pfndecl = &print_int64_fndecl;
7874 fnname = "__go_print_int64";
7875 Type* itype = Type::lookup_integer_type("int64");
7876 Btype* bitype = itype->get_backend(gogo);
7877 arg = fold_convert_loc(location.gcc_location(),
7878 type_to_tree(bitype), arg);
7880 else if (type->float_type() != NULL)
7882 static tree print_double_fndecl;
7883 pfndecl = &print_double_fndecl;
7884 fnname = "__go_print_double";
7885 arg = fold_convert_loc(location.gcc_location(),
7886 double_type_node, arg);
7888 else if (type->complex_type() != NULL)
7890 static tree print_complex_fndecl;
7891 pfndecl = &print_complex_fndecl;
7892 fnname = "__go_print_complex";
7893 arg = fold_convert_loc(location.gcc_location(),
7894 complex_double_type_node, arg);
7896 else if (type->is_boolean_type())
7898 static tree print_bool_fndecl;
7899 pfndecl = &print_bool_fndecl;
7900 fnname = "__go_print_bool";
7902 else if (type->points_to() != NULL
7903 || type->channel_type() != NULL
7904 || type->map_type() != NULL
7905 || type->function_type() != NULL)
7907 static tree print_pointer_fndecl;
7908 pfndecl = &print_pointer_fndecl;
7909 fnname = "__go_print_pointer";
7910 arg = fold_convert_loc(location.gcc_location(),
7911 ptr_type_node, arg);
7913 else if (type->interface_type() != NULL)
7915 if (type->interface_type()->is_empty())
7917 static tree print_empty_interface_fndecl;
7918 pfndecl = &print_empty_interface_fndecl;
7919 fnname = "__go_print_empty_interface";
7923 static tree print_interface_fndecl;
7924 pfndecl = &print_interface_fndecl;
7925 fnname = "__go_print_interface";
7928 else if (type->is_slice_type())
7930 static tree print_slice_fndecl;
7931 pfndecl = &print_slice_fndecl;
7932 fnname = "__go_print_slice";
7936 go_assert(saw_errors());
7937 return error_mark_node;
7940 tree call = Gogo::call_builtin(pfndecl,
7947 if (call == error_mark_node)
7948 return error_mark_node;
7949 append_to_statement_list(call, &stmt_list);
7955 static tree print_nl_fndecl;
7956 tree call = Gogo::call_builtin(&print_nl_fndecl,
7961 if (call == error_mark_node)
7962 return error_mark_node;
7963 append_to_statement_list(call, &stmt_list);
7971 const Expression_list* args = this->args();
7972 go_assert(args != NULL && args->size() == 1);
7973 Expression* arg = args->front();
7974 tree arg_tree = arg->get_tree(context);
7975 if (arg_tree == error_mark_node)
7976 return error_mark_node;
7978 Type::make_empty_interface_type(Linemap::predeclared_location());
7979 arg_tree = Expression::convert_for_assignment(context, empty,
7981 arg_tree, location);
7982 static tree panic_fndecl;
7983 tree call = Gogo::call_builtin(&panic_fndecl,
7988 TREE_TYPE(arg_tree),
7990 if (call == error_mark_node)
7991 return error_mark_node;
7992 // This function will throw an exception.
7993 TREE_NOTHROW(panic_fndecl) = 0;
7994 // This function will not return.
7995 TREE_THIS_VOLATILE(panic_fndecl) = 1;
7999 case BUILTIN_RECOVER:
8001 // The argument is set when building recover thunks. It's a
8002 // boolean value which is true if we can recover a value now.
8003 const Expression_list* args = this->args();
8004 go_assert(args != NULL && args->size() == 1);
8005 Expression* arg = args->front();
8006 tree arg_tree = arg->get_tree(context);
8007 if (arg_tree == error_mark_node)
8008 return error_mark_node;
8011 Type::make_empty_interface_type(Linemap::predeclared_location());
8012 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8014 Type* nil_type = Type::make_nil_type();
8015 Expression* nil = Expression::make_nil(location);
8016 tree nil_tree = nil->get_tree(context);
8017 tree empty_nil_tree = Expression::convert_for_assignment(context,
8023 // We need to handle a deferred call to recover specially,
8024 // because it changes whether it can recover a panic or not.
8025 // See test7 in test/recover1.go.
8027 if (this->is_deferred())
8029 static tree deferred_recover_fndecl;
8030 call = Gogo::call_builtin(&deferred_recover_fndecl,
8032 "__go_deferred_recover",
8038 static tree recover_fndecl;
8039 call = Gogo::call_builtin(&recover_fndecl,
8045 if (call == error_mark_node)
8046 return error_mark_node;
8047 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8048 arg_tree, call, empty_nil_tree);
8053 const Expression_list* args = this->args();
8054 go_assert(args != NULL && args->size() == 1);
8055 Expression* arg = args->front();
8056 tree arg_tree = arg->get_tree(context);
8057 if (arg_tree == error_mark_node)
8058 return error_mark_node;
8059 static tree close_fndecl;
8060 return Gogo::call_builtin(&close_fndecl,
8062 "__go_builtin_close",
8065 TREE_TYPE(arg_tree),
8069 case BUILTIN_SIZEOF:
8070 case BUILTIN_OFFSETOF:
8071 case BUILTIN_ALIGNOF:
8073 Numeric_constant nc;
8075 if (!this->numeric_constant_value(&nc)
8076 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8078 go_assert(saw_errors());
8079 return error_mark_node;
8081 Type* int_type = Type::lookup_integer_type("int");
8082 tree type = type_to_tree(int_type->get_backend(gogo));
8083 return build_int_cst(type, val);
8088 const Expression_list* args = this->args();
8089 go_assert(args != NULL && args->size() == 2);
8090 Expression* arg1 = args->front();
8091 Expression* arg2 = args->back();
8093 tree arg1_tree = arg1->get_tree(context);
8094 tree arg2_tree = arg2->get_tree(context);
8095 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8096 return error_mark_node;
8098 Type* arg1_type = arg1->type();
8099 Array_type* at = arg1_type->array_type();
8100 arg1_tree = save_expr(arg1_tree);
8101 tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8102 tree arg1_len = at->length_tree(gogo, arg1_tree);
8103 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8104 return error_mark_node;
8106 Type* arg2_type = arg2->type();
8109 if (arg2_type->is_slice_type())
8111 at = arg2_type->array_type();
8112 arg2_tree = save_expr(arg2_tree);
8113 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8114 arg2_len = at->length_tree(gogo, arg2_tree);
8118 arg2_tree = save_expr(arg2_tree);
8119 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8120 arg2_len = String_type::length_tree(gogo, arg2_tree);
8122 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8123 return error_mark_node;
8125 arg1_len = save_expr(arg1_len);
8126 arg2_len = save_expr(arg2_len);
8127 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8128 TREE_TYPE(arg1_len),
8129 fold_build2_loc(location.gcc_location(),
8130 LT_EXPR, boolean_type_node,
8131 arg1_len, arg2_len),
8132 arg1_len, arg2_len);
8133 len = save_expr(len);
8135 Type* element_type = at->element_type();
8136 Btype* element_btype = element_type->get_backend(gogo);
8137 tree element_type_tree = type_to_tree(element_btype);
8138 if (element_type_tree == error_mark_node)
8139 return error_mark_node;
8140 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8141 tree bytecount = fold_convert_loc(location.gcc_location(),
8142 TREE_TYPE(element_size), len);
8143 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8144 TREE_TYPE(element_size),
8145 bytecount, element_size);
8146 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8149 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8151 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8154 static tree copy_fndecl;
8155 tree call = Gogo::call_builtin(©_fndecl,
8166 if (call == error_mark_node)
8167 return error_mark_node;
8169 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8170 TREE_TYPE(len), call, len);
8173 case BUILTIN_APPEND:
8175 const Expression_list* args = this->args();
8176 go_assert(args != NULL && args->size() == 2);
8177 Expression* arg1 = args->front();
8178 Expression* arg2 = args->back();
8180 tree arg1_tree = arg1->get_tree(context);
8181 tree arg2_tree = arg2->get_tree(context);
8182 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8183 return error_mark_node;
8185 Array_type* at = arg1->type()->array_type();
8186 Type* element_type = at->element_type()->forwarded();
8191 if (arg2->type()->is_string_type()
8192 && element_type->integer_type() != NULL
8193 && element_type->integer_type()->is_byte())
8195 arg2_tree = save_expr(arg2_tree);
8196 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8197 arg2_len = String_type::length_tree(gogo, arg2_tree);
8198 element_size = size_int(1);
8202 arg2_tree = Expression::convert_for_assignment(context, at,
8206 if (arg2_tree == error_mark_node)
8207 return error_mark_node;
8209 arg2_tree = save_expr(arg2_tree);
8211 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8212 arg2_len = at->length_tree(gogo, arg2_tree);
8214 Btype* element_btype = element_type->get_backend(gogo);
8215 tree element_type_tree = type_to_tree(element_btype);
8216 if (element_type_tree == error_mark_node)
8217 return error_mark_node;
8218 element_size = TYPE_SIZE_UNIT(element_type_tree);
8221 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8223 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8225 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8228 if (arg2_val == error_mark_node
8229 || arg2_len == error_mark_node
8230 || element_size == error_mark_node)
8231 return error_mark_node;
8233 // We rebuild the decl each time since the slice types may
8235 tree append_fndecl = NULL_TREE;
8236 return Gogo::call_builtin(&append_fndecl,
8240 TREE_TYPE(arg1_tree),
8241 TREE_TYPE(arg1_tree),
8254 const Expression_list* args = this->args();
8255 go_assert(args != NULL && args->size() == 1);
8256 Expression* arg = args->front();
8257 tree arg_tree = arg->get_tree(context);
8258 if (arg_tree == error_mark_node)
8259 return error_mark_node;
8260 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
8261 if (this->code_ == BUILTIN_REAL)
8262 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
8263 TREE_TYPE(TREE_TYPE(arg_tree)),
8266 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
8267 TREE_TYPE(TREE_TYPE(arg_tree)),
8271 case BUILTIN_COMPLEX:
8273 const Expression_list* args = this->args();
8274 go_assert(args != NULL && args->size() == 2);
8275 tree r = args->front()->get_tree(context);
8276 tree i = args->back()->get_tree(context);
8277 if (r == error_mark_node || i == error_mark_node)
8278 return error_mark_node;
8279 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
8280 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
8281 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
8282 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
8283 build_complex_type(TREE_TYPE(r)),
8292 // We have to support exporting a builtin call expression, because
8293 // code can set a constant to the result of a builtin expression.
8296 Builtin_call_expression::do_export(Export* exp) const
8298 Numeric_constant nc;
8299 if (!this->numeric_constant_value(&nc))
8301 error_at(this->location(), "value is not constant");
8309 Integer_expression::export_integer(exp, val);
8312 else if (nc.is_float())
8315 nc.get_float(&fval);
8316 Float_expression::export_float(exp, fval);
8319 else if (nc.is_complex())
8323 Complex_expression::export_complex(exp, real, imag);
8330 // A trailing space lets us reliably identify the end of the number.
8331 exp->write_c_string(" ");
8334 // Class Call_expression.
8339 Call_expression::do_traverse(Traverse* traverse)
8341 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8342 return TRAVERSE_EXIT;
8343 if (this->args_ != NULL)
8345 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8346 return TRAVERSE_EXIT;
8348 return TRAVERSE_CONTINUE;
8351 // Lower a call statement.
8354 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8355 Statement_inserter* inserter, int)
8357 Location loc = this->location();
8359 // A type cast can look like a function call.
8360 if (this->fn_->is_type_expression()
8361 && this->args_ != NULL
8362 && this->args_->size() == 1)
8363 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8366 // Recognize a call to a builtin function.
8367 Func_expression* fne = this->fn_->func_expression();
8369 && fne->named_object()->is_function_declaration()
8370 && fne->named_object()->func_declaration_value()->type()->is_builtin())
8371 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8372 this->is_varargs_, loc);
8374 // Handle an argument which is a call to a function which returns
8375 // multiple results.
8376 if (this->args_ != NULL
8377 && this->args_->size() == 1
8378 && this->args_->front()->call_expression() != NULL
8379 && this->fn_->type()->function_type() != NULL)
8381 Function_type* fntype = this->fn_->type()->function_type();
8382 size_t rc = this->args_->front()->call_expression()->result_count();
8384 && fntype->parameters() != NULL
8385 && (fntype->parameters()->size() == rc
8386 || (fntype->is_varargs()
8387 && fntype->parameters()->size() - 1 <= rc)))
8389 Call_expression* call = this->args_->front()->call_expression();
8390 Expression_list* args = new Expression_list;
8391 for (size_t i = 0; i < rc; ++i)
8392 args->push_back(Expression::make_call_result(call, i));
8393 // We can't return a new call expression here, because this
8394 // one may be referenced by Call_result expressions. We
8395 // also can't delete the old arguments, because we may still
8396 // traverse them somewhere up the call stack. FIXME.
8401 // If this call returns multiple results, create a temporary
8402 // variable for each result.
8403 size_t rc = this->result_count();
8404 if (rc > 1 && this->results_ == NULL)
8406 std::vector<Temporary_statement*>* temps =
8407 new std::vector<Temporary_statement*>;
8409 const Typed_identifier_list* results =
8410 this->fn_->type()->function_type()->results();
8411 for (Typed_identifier_list::const_iterator p = results->begin();
8412 p != results->end();
8415 Temporary_statement* temp = Statement::make_temporary(p->type(),
8417 inserter->insert(temp);
8418 temps->push_back(temp);
8420 this->results_ = temps;
8423 // Handle a call to a varargs function by packaging up the extra
8425 if (this->fn_->type()->function_type() != NULL
8426 && this->fn_->type()->function_type()->is_varargs())
8428 Function_type* fntype = this->fn_->type()->function_type();
8429 const Typed_identifier_list* parameters = fntype->parameters();
8430 go_assert(parameters != NULL && !parameters->empty());
8431 Type* varargs_type = parameters->back().type();
8432 this->lower_varargs(gogo, function, inserter, varargs_type,
8433 parameters->size());
8436 // If this is call to a method, call the method directly passing the
8437 // object as the first parameter.
8438 Bound_method_expression* bme = this->fn_->bound_method_expression();
8441 Named_object* method = bme->method();
8442 Expression* first_arg = bme->first_argument();
8444 // We always pass a pointer when calling a method.
8445 if (first_arg->type()->points_to() == NULL
8446 && !first_arg->type()->is_error())
8448 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8449 // We may need to create a temporary variable so that we can
8450 // take the address. We can't do that here because it will
8451 // mess up the order of evaluation.
8452 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8453 ue->set_create_temp();
8456 // If we are calling a method which was inherited from an
8457 // embedded struct, and the method did not get a stub, then the
8458 // first type may be wrong.
8459 Type* fatype = bme->first_argument_type();
8462 if (fatype->points_to() == NULL)
8463 fatype = Type::make_pointer_type(fatype);
8464 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8467 Expression_list* new_args = new Expression_list();
8468 new_args->push_back(first_arg);
8469 if (this->args_ != NULL)
8471 for (Expression_list::const_iterator p = this->args_->begin();
8472 p != this->args_->end();
8474 new_args->push_back(*p);
8477 // We have to change in place because this structure may be
8478 // referenced by Call_result_expressions. We can't delete the
8479 // old arguments, because we may be traversing them up in some
8481 this->args_ = new_args;
8482 this->fn_ = Expression::make_func_reference(method, NULL,
8489 // Lower a call to a varargs function. FUNCTION is the function in
8490 // which the call occurs--it's not the function we are calling.
8491 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8492 // PARAM_COUNT is the number of parameters of the function we are
8493 // calling; the last of these parameters will be the varargs
8497 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8498 Statement_inserter* inserter,
8499 Type* varargs_type, size_t param_count)
8501 if (this->varargs_are_lowered_)
8504 Location loc = this->location();
8506 go_assert(param_count > 0);
8507 go_assert(varargs_type->is_slice_type());
8509 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8510 if (arg_count < param_count - 1)
8512 // Not enough arguments; will be caught in check_types.
8516 Expression_list* old_args = this->args_;
8517 Expression_list* new_args = new Expression_list();
8518 bool push_empty_arg = false;
8519 if (old_args == NULL || old_args->empty())
8521 go_assert(param_count == 1);
8522 push_empty_arg = true;
8526 Expression_list::const_iterator pa;
8528 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8530 if (static_cast<size_t>(i) == param_count)
8532 new_args->push_back(*pa);
8535 // We have reached the varargs parameter.
8537 bool issued_error = false;
8538 if (pa == old_args->end())
8539 push_empty_arg = true;
8540 else if (pa + 1 == old_args->end() && this->is_varargs_)
8541 new_args->push_back(*pa);
8542 else if (this->is_varargs_)
8544 this->report_error(_("too many arguments"));
8549 Type* element_type = varargs_type->array_type()->element_type();
8550 Expression_list* vals = new Expression_list;
8551 for (; pa != old_args->end(); ++pa, ++i)
8553 // Check types here so that we get a better message.
8554 Type* patype = (*pa)->type();
8555 Location paloc = (*pa)->location();
8556 if (!this->check_argument_type(i, element_type, patype,
8557 paloc, issued_error))
8559 vals->push_back(*pa);
8562 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8563 gogo->lower_expression(function, inserter, &val);
8564 new_args->push_back(val);
8569 new_args->push_back(Expression::make_nil(loc));
8571 // We can't return a new call expression here, because this one may
8572 // be referenced by Call_result expressions. FIXME. We can't
8573 // delete OLD_ARGS because we may have both a Call_expression and a
8574 // Builtin_call_expression which refer to them. FIXME.
8575 this->args_ = new_args;
8576 this->varargs_are_lowered_ = true;
8579 // Get the function type. This can return NULL in error cases.
8582 Call_expression::get_function_type() const
8584 return this->fn_->type()->function_type();
8587 // Return the number of values which this call will return.
8590 Call_expression::result_count() const
8592 const Function_type* fntype = this->get_function_type();
8595 if (fntype->results() == NULL)
8597 return fntype->results()->size();
8600 // Return the temporary which holds a result.
8602 Temporary_statement*
8603 Call_expression::result(size_t i) const
8605 if (this->results_ == NULL || this->results_->size() <= i)
8607 go_assert(saw_errors());
8610 return (*this->results_)[i];
8613 // Return whether this is a call to the predeclared function recover.
8616 Call_expression::is_recover_call() const
8618 return this->do_is_recover_call();
8621 // Set the argument to the recover function.
8624 Call_expression::set_recover_arg(Expression* arg)
8626 this->do_set_recover_arg(arg);
8629 // Virtual functions also implemented by Builtin_call_expression.
8632 Call_expression::do_is_recover_call() const
8638 Call_expression::do_set_recover_arg(Expression*)
8643 // We have found an error with this call expression; return true if
8644 // we should report it.
8647 Call_expression::issue_error()
8649 if (this->issued_error_)
8653 this->issued_error_ = true;
8661 Call_expression::do_type()
8663 if (this->type_ != NULL)
8667 Function_type* fntype = this->get_function_type();
8669 return Type::make_error_type();
8671 const Typed_identifier_list* results = fntype->results();
8672 if (results == NULL)
8673 ret = Type::make_void_type();
8674 else if (results->size() == 1)
8675 ret = results->begin()->type();
8677 ret = Type::make_call_multiple_result_type(this);
8684 // Determine types for a call expression. We can use the function
8685 // parameter types to set the types of the arguments.
8688 Call_expression::do_determine_type(const Type_context*)
8690 if (!this->determining_types())
8693 this->fn_->determine_type_no_context();
8694 Function_type* fntype = this->get_function_type();
8695 const Typed_identifier_list* parameters = NULL;
8697 parameters = fntype->parameters();
8698 if (this->args_ != NULL)
8700 Typed_identifier_list::const_iterator pt;
8701 if (parameters != NULL)
8702 pt = parameters->begin();
8704 for (Expression_list::const_iterator pa = this->args_->begin();
8705 pa != this->args_->end();
8711 // If this is a method, the first argument is the
8713 if (fntype != NULL && fntype->is_method())
8715 Type* rtype = fntype->receiver()->type();
8716 // The receiver is always passed as a pointer.
8717 if (rtype->points_to() == NULL)
8718 rtype = Type::make_pointer_type(rtype);
8719 Type_context subcontext(rtype, false);
8720 (*pa)->determine_type(&subcontext);
8725 if (parameters != NULL && pt != parameters->end())
8727 Type_context subcontext(pt->type(), false);
8728 (*pa)->determine_type(&subcontext);
8732 (*pa)->determine_type_no_context();
8737 // Called when determining types for a Call_expression. Return true
8738 // if we should go ahead, false if they have already been determined.
8741 Call_expression::determining_types()
8743 if (this->types_are_determined_)
8747 this->types_are_determined_ = true;
8752 // Check types for parameter I.
8755 Call_expression::check_argument_type(int i, const Type* parameter_type,
8756 const Type* argument_type,
8757 Location argument_location,
8762 if (this->are_hidden_fields_ok_)
8763 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
8766 ok = Type::are_assignable(parameter_type, argument_type, &reason);
8772 error_at(argument_location, "argument %d has incompatible type", i);
8774 error_at(argument_location,
8775 "argument %d has incompatible type (%s)",
8778 this->set_is_error();
8787 Call_expression::do_check_types(Gogo*)
8789 Function_type* fntype = this->get_function_type();
8792 if (!this->fn_->type()->is_error())
8793 this->report_error(_("expected function"));
8797 bool is_method = fntype->is_method();
8800 go_assert(this->args_ != NULL && !this->args_->empty());
8801 Type* rtype = fntype->receiver()->type();
8802 Expression* first_arg = this->args_->front();
8803 // The language permits copying hidden fields for a method
8804 // receiver. We dereference the values since receivers are
8805 // always passed as pointers.
8807 if (!Type::are_assignable_hidden_ok(rtype->deref(),
8808 first_arg->type()->deref(),
8812 this->report_error(_("incompatible type for receiver"));
8815 error_at(this->location(),
8816 "incompatible type for receiver (%s)",
8818 this->set_is_error();
8823 // Note that varargs was handled by the lower_varargs() method, so
8824 // we don't have to worry about it here.
8826 const Typed_identifier_list* parameters = fntype->parameters();
8827 if (this->args_ == NULL)
8829 if (parameters != NULL && !parameters->empty())
8830 this->report_error(_("not enough arguments"));
8832 else if (parameters == NULL)
8834 if (!is_method || this->args_->size() > 1)
8835 this->report_error(_("too many arguments"));
8840 Expression_list::const_iterator pa = this->args_->begin();
8843 for (Typed_identifier_list::const_iterator pt = parameters->begin();
8844 pt != parameters->end();
8847 if (pa == this->args_->end())
8849 this->report_error(_("not enough arguments"));
8852 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
8853 (*pa)->location(), false);
8855 if (pa != this->args_->end())
8856 this->report_error(_("too many arguments"));
8860 // Return whether we have to use a temporary variable to ensure that
8861 // we evaluate this call expression in order. If the call returns no
8862 // results then it will inevitably be executed last.
8865 Call_expression::do_must_eval_in_order() const
8867 return this->result_count() > 0;
8870 // Get the function and the first argument to use when calling an
8871 // interface method.
8874 Call_expression::interface_method_function(
8875 Translate_context* context,
8876 Interface_field_reference_expression* interface_method,
8877 tree* first_arg_ptr)
8879 tree expr = interface_method->expr()->get_tree(context);
8880 if (expr == error_mark_node)
8881 return error_mark_node;
8882 expr = save_expr(expr);
8883 tree first_arg = interface_method->get_underlying_object_tree(context, expr);
8884 if (first_arg == error_mark_node)
8885 return error_mark_node;
8886 *first_arg_ptr = first_arg;
8887 return interface_method->get_function_tree(context, expr);
8890 // Build the call expression.
8893 Call_expression::do_get_tree(Translate_context* context)
8895 if (this->tree_ != NULL_TREE)
8898 Function_type* fntype = this->get_function_type();
8900 return error_mark_node;
8902 if (this->fn_->is_error_expression())
8903 return error_mark_node;
8905 Gogo* gogo = context->gogo();
8906 Location location = this->location();
8908 Func_expression* func = this->fn_->func_expression();
8909 Interface_field_reference_expression* interface_method =
8910 this->fn_->interface_field_reference_expression();
8911 const bool has_closure = func != NULL && func->closure() != NULL;
8912 const bool is_interface_method = interface_method != NULL;
8916 if (this->args_ == NULL || this->args_->empty())
8918 nargs = is_interface_method ? 1 : 0;
8919 args = nargs == 0 ? NULL : new tree[nargs];
8921 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
8923 // Passing a receiver parameter.
8924 go_assert(!is_interface_method
8925 && fntype->is_method()
8926 && this->args_->size() == 1);
8928 args = new tree[nargs];
8929 args[0] = this->args_->front()->get_tree(context);
8933 const Typed_identifier_list* params = fntype->parameters();
8935 nargs = this->args_->size();
8936 int i = is_interface_method ? 1 : 0;
8938 args = new tree[nargs];
8940 Typed_identifier_list::const_iterator pp = params->begin();
8941 Expression_list::const_iterator pe = this->args_->begin();
8942 if (!is_interface_method && fntype->is_method())
8944 args[i] = (*pe)->get_tree(context);
8948 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
8950 go_assert(pp != params->end());
8951 tree arg_val = (*pe)->get_tree(context);
8952 args[i] = Expression::convert_for_assignment(context,
8957 if (args[i] == error_mark_node)
8960 return error_mark_node;
8963 go_assert(pp == params->end());
8964 go_assert(i == nargs);
8967 tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
8968 if (rettype == error_mark_node)
8971 return error_mark_node;
8976 fn = func->get_tree_without_closure(gogo);
8977 else if (!is_interface_method)
8978 fn = this->fn_->get_tree(context);
8980 fn = this->interface_method_function(context, interface_method, &args[0]);
8982 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
8985 return error_mark_node;
8989 if (TREE_CODE(fndecl) == ADDR_EXPR)
8990 fndecl = TREE_OPERAND(fndecl, 0);
8992 // Add a type cast in case the type of the function is a recursive
8993 // type which refers to itself.
8994 if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
8996 tree fnt = type_to_tree(fntype->get_backend(gogo));
8997 if (fnt == error_mark_node)
8998 return error_mark_node;
8999 fn = fold_convert_loc(location.gcc_location(), fnt, fn);
9002 // This is to support builtin math functions when using 80387 math.
9003 tree excess_type = NULL_TREE;
9005 && TREE_CODE(fndecl) == FUNCTION_DECL
9006 && DECL_IS_BUILTIN(fndecl)
9007 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9009 && ((SCALAR_FLOAT_TYPE_P(rettype)
9010 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9011 || (COMPLEX_FLOAT_TYPE_P(rettype)
9012 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9014 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9015 if (excess_type != NULL_TREE)
9017 tree excess_fndecl = mathfn_built_in(excess_type,
9018 DECL_FUNCTION_CODE(fndecl));
9019 if (excess_fndecl == NULL_TREE)
9020 excess_type = NULL_TREE;
9023 fn = build_fold_addr_expr_loc(location.gcc_location(),
9025 for (int i = 0; i < nargs; ++i)
9027 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9028 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9029 args[i] = ::convert(excess_type, args[i]);
9035 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9039 SET_EXPR_LOCATION(ret, location.gcc_location());
9043 tree closure_tree = func->closure()->get_tree(context);
9044 if (closure_tree != error_mark_node)
9045 CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
9048 // If this is a recursive function type which returns itself, as in
9050 // we have used ptr_type_node for the return type. Add a cast here
9051 // to the correct type.
9052 if (TREE_TYPE(ret) == ptr_type_node)
9054 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9055 ret = fold_convert_loc(location.gcc_location(), t, ret);
9058 if (excess_type != NULL_TREE)
9060 // Calling convert here can undo our excess precision change.
9061 // That may or may not be a bug in convert_to_real.
9062 ret = build1(NOP_EXPR, rettype, ret);
9065 if (this->results_ != NULL)
9066 ret = this->set_results(context, ret);
9073 // Set the result variables if this call returns multiple results.
9076 Call_expression::set_results(Translate_context* context, tree call_tree)
9078 tree stmt_list = NULL_TREE;
9080 call_tree = save_expr(call_tree);
9082 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9084 go_assert(saw_errors());
9088 Location loc = this->location();
9089 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9090 size_t rc = this->result_count();
9091 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9093 go_assert(field != NULL_TREE);
9095 Temporary_statement* temp = this->result(i);
9098 go_assert(saw_errors());
9099 return error_mark_node;
9101 Temporary_reference_expression* ref =
9102 Expression::make_temporary_reference(temp, loc);
9103 ref->set_is_lvalue();
9104 tree temp_tree = ref->get_tree(context);
9105 if (temp_tree == error_mark_node)
9108 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9109 TREE_TYPE(field), call_tree, field, NULL_TREE);
9110 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9111 void_type_node, temp_tree, val_tree);
9113 append_to_statement_list(set_tree, &stmt_list);
9115 go_assert(field == NULL_TREE);
9117 return save_expr(stmt_list);
9120 // Dump ast representation for a call expressin.
9123 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9125 this->fn_->dump_expression(ast_dump_context);
9126 ast_dump_context->ostream() << "(";
9128 ast_dump_context->dump_expression_list(this->args_);
9130 ast_dump_context->ostream() << ") ";
9133 // Make a call expression.
9136 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9139 return new Call_expression(fn, args, is_varargs, location);
9142 // A single result from a call which returns multiple results.
9144 class Call_result_expression : public Expression
9147 Call_result_expression(Call_expression* call, unsigned int index)
9148 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9149 call_(call), index_(index)
9154 do_traverse(Traverse*);
9160 do_determine_type(const Type_context*);
9163 do_check_types(Gogo*);
9168 return new Call_result_expression(this->call_->call_expression(),
9173 do_must_eval_in_order() const
9177 do_get_tree(Translate_context*);
9180 do_dump_expression(Ast_dump_context*) const;
9183 // The underlying call expression.
9185 // Which result we want.
9186 unsigned int index_;
9189 // Traverse a call result.
9192 Call_result_expression::do_traverse(Traverse* traverse)
9194 if (traverse->remember_expression(this->call_))
9196 // We have already traversed the call expression.
9197 return TRAVERSE_CONTINUE;
9199 return Expression::traverse(&this->call_, traverse);
9205 Call_result_expression::do_type()
9207 if (this->classification() == EXPRESSION_ERROR)
9208 return Type::make_error_type();
9210 // THIS->CALL_ can be replaced with a temporary reference due to
9211 // Call_expression::do_must_eval_in_order when there is an error.
9212 Call_expression* ce = this->call_->call_expression();
9215 this->set_is_error();
9216 return Type::make_error_type();
9218 Function_type* fntype = ce->get_function_type();
9221 if (ce->issue_error())
9223 if (!ce->fn()->type()->is_error())
9224 this->report_error(_("expected function"));
9226 this->set_is_error();
9227 return Type::make_error_type();
9229 const Typed_identifier_list* results = fntype->results();
9230 if (results == NULL || results->size() < 2)
9232 if (ce->issue_error())
9233 this->report_error(_("number of results does not match "
9234 "number of values"));
9235 return Type::make_error_type();
9237 Typed_identifier_list::const_iterator pr = results->begin();
9238 for (unsigned int i = 0; i < this->index_; ++i)
9240 if (pr == results->end())
9244 if (pr == results->end())
9246 if (ce->issue_error())
9247 this->report_error(_("number of results does not match "
9248 "number of values"));
9249 return Type::make_error_type();
9254 // Check the type. Just make sure that we trigger the warning in
9258 Call_result_expression::do_check_types(Gogo*)
9263 // Determine the type. We have nothing to do here, but the 0 result
9264 // needs to pass down to the caller.
9267 Call_result_expression::do_determine_type(const Type_context*)
9269 this->call_->determine_type_no_context();
9272 // Return the tree. We just refer to the temporary set by the call
9273 // expression. We don't do this at lowering time because it makes it
9274 // hard to evaluate the call at the right time.
9277 Call_result_expression::do_get_tree(Translate_context* context)
9279 Call_expression* ce = this->call_->call_expression();
9282 go_assert(this->call_->is_error_expression());
9283 return error_mark_node;
9285 Temporary_statement* ts = ce->result(this->index_);
9288 go_assert(saw_errors());
9289 return error_mark_node;
9291 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9292 return ref->get_tree(context);
9295 // Dump ast representation for a call result expression.
9298 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9301 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9302 // (struct) and the fields are referenced instead.
9303 ast_dump_context->ostream() << this->index_ << "@(";
9304 ast_dump_context->dump_expression(this->call_);
9305 ast_dump_context->ostream() << ")";
9308 // Make a reference to a single result of a call which returns
9309 // multiple results.
9312 Expression::make_call_result(Call_expression* call, unsigned int index)
9314 return new Call_result_expression(call, index);
9317 // Class Index_expression.
9322 Index_expression::do_traverse(Traverse* traverse)
9324 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9325 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9326 || (this->end_ != NULL
9327 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
9328 return TRAVERSE_EXIT;
9329 return TRAVERSE_CONTINUE;
9332 // Lower an index expression. This converts the generic index
9333 // expression into an array index, a string index, or a map index.
9336 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9338 Location location = this->location();
9339 Expression* left = this->left_;
9340 Expression* start = this->start_;
9341 Expression* end = this->end_;
9343 Type* type = left->type();
9344 if (type->is_error())
9345 return Expression::make_error(location);
9346 else if (left->is_type_expression())
9348 error_at(location, "attempt to index type expression");
9349 return Expression::make_error(location);
9351 else if (type->array_type() != NULL)
9352 return Expression::make_array_index(left, start, end, location);
9353 else if (type->points_to() != NULL
9354 && type->points_to()->array_type() != NULL
9355 && !type->points_to()->is_slice_type())
9357 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9359 return Expression::make_array_index(deref, start, end, location);
9361 else if (type->is_string_type())
9362 return Expression::make_string_index(left, start, end, location);
9363 else if (type->map_type() != NULL)
9367 error_at(location, "invalid slice of map");
9368 return Expression::make_error(location);
9370 Map_index_expression* ret = Expression::make_map_index(left, start,
9372 if (this->is_lvalue_)
9373 ret->set_is_lvalue();
9379 "attempt to index object which is not array, string, or map");
9380 return Expression::make_error(location);
9384 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
9388 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9389 const Expression* expr,
9390 const Expression* start,
9391 const Expression* end)
9393 expr->dump_expression(ast_dump_context);
9394 ast_dump_context->ostream() << "[";
9395 start->dump_expression(ast_dump_context);
9398 ast_dump_context->ostream() << ":";
9399 end->dump_expression(ast_dump_context);
9401 ast_dump_context->ostream() << "]";
9404 // Dump ast representation for an index expression.
9407 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9410 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9411 this->start_, this->end_);
9414 // Make an index expression.
9417 Expression::make_index(Expression* left, Expression* start, Expression* end,
9420 return new Index_expression(left, start, end, location);
9423 // An array index. This is used for both indexing and slicing.
9425 class Array_index_expression : public Expression
9428 Array_index_expression(Expression* array, Expression* start,
9429 Expression* end, Location location)
9430 : Expression(EXPRESSION_ARRAY_INDEX, location),
9431 array_(array), start_(start), end_(end), type_(NULL)
9436 do_traverse(Traverse*);
9442 do_determine_type(const Type_context*);
9445 do_check_types(Gogo*);
9450 return Expression::make_array_index(this->array_->copy(),
9451 this->start_->copy(),
9454 : this->end_->copy()),
9459 do_must_eval_subexpressions_in_order(int* skip) const
9466 do_is_addressable() const;
9469 do_address_taken(bool escapes)
9470 { this->array_->address_taken(escapes); }
9473 do_get_tree(Translate_context*);
9476 do_dump_expression(Ast_dump_context*) const;
9479 // The array we are getting a value from.
9481 // The start or only index.
9483 // The end index of a slice. This may be NULL for a simple array
9484 // index, or it may be a nil expression for the length of the array.
9486 // The type of the expression.
9490 // Array index traversal.
9493 Array_index_expression::do_traverse(Traverse* traverse)
9495 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9496 return TRAVERSE_EXIT;
9497 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9498 return TRAVERSE_EXIT;
9499 if (this->end_ != NULL)
9501 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9502 return TRAVERSE_EXIT;
9504 return TRAVERSE_CONTINUE;
9507 // Return the type of an array index.
9510 Array_index_expression::do_type()
9512 if (this->type_ == NULL)
9514 Array_type* type = this->array_->type()->array_type();
9516 this->type_ = Type::make_error_type();
9517 else if (this->end_ == NULL)
9518 this->type_ = type->element_type();
9519 else if (type->is_slice_type())
9521 // A slice of a slice has the same type as the original
9523 this->type_ = this->array_->type()->deref();
9527 // A slice of an array is a slice.
9528 this->type_ = Type::make_array_type(type->element_type(), NULL);
9534 // Set the type of an array index.
9537 Array_index_expression::do_determine_type(const Type_context*)
9539 this->array_->determine_type_no_context();
9540 this->start_->determine_type_no_context();
9541 if (this->end_ != NULL)
9542 this->end_->determine_type_no_context();
9545 // Check types of an array index.
9548 Array_index_expression::do_check_types(Gogo*)
9550 if (this->start_->type()->integer_type() == NULL)
9551 this->report_error(_("index must be integer"));
9552 if (this->end_ != NULL
9553 && this->end_->type()->integer_type() == NULL
9554 && !this->end_->type()->is_error()
9555 && !this->end_->is_nil_expression()
9556 && !this->end_->is_error_expression())
9557 this->report_error(_("slice end must be integer"));
9559 Array_type* array_type = this->array_->type()->array_type();
9560 if (array_type == NULL)
9562 go_assert(this->array_->type()->is_error());
9566 unsigned int int_bits =
9567 Type::lookup_integer_type("int")->integer_type()->bits();
9569 Numeric_constant lvalnc;
9571 bool lval_valid = (array_type->length() != NULL
9572 && array_type->length()->numeric_constant_value(&lvalnc)
9573 && lvalnc.to_int(&lval));
9574 Numeric_constant inc;
9576 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9578 if (mpz_sgn(ival) < 0
9579 || mpz_sizeinbase(ival, 2) >= int_bits
9581 && (this->end_ == NULL
9582 ? mpz_cmp(ival, lval) >= 0
9583 : mpz_cmp(ival, lval) > 0)))
9585 error_at(this->start_->location(), "array index out of bounds");
9586 this->set_is_error();
9590 if (this->end_ != NULL && !this->end_->is_nil_expression())
9592 Numeric_constant enc;
9594 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9596 if (mpz_sgn(eval) < 0
9597 || mpz_sizeinbase(eval, 2) >= int_bits
9598 || (lval_valid && mpz_cmp(eval, lval) > 0))
9600 error_at(this->end_->location(), "array index out of bounds");
9601 this->set_is_error();
9609 // A slice of an array requires an addressable array. A slice of a
9610 // slice is always possible.
9611 if (this->end_ != NULL && !array_type->is_slice_type())
9613 if (!this->array_->is_addressable())
9614 this->report_error(_("slice of unaddressable value"));
9616 this->array_->address_taken(true);
9620 // Return whether this expression is addressable.
9623 Array_index_expression::do_is_addressable() const
9625 // A slice expression is not addressable.
9626 if (this->end_ != NULL)
9629 // An index into a slice is addressable.
9630 if (this->array_->type()->is_slice_type())
9633 // An index into an array is addressable if the array is
9635 return this->array_->is_addressable();
9638 // Get a tree for an array index.
9641 Array_index_expression::do_get_tree(Translate_context* context)
9643 Gogo* gogo = context->gogo();
9644 Location loc = this->location();
9646 Array_type* array_type = this->array_->type()->array_type();
9647 if (array_type == NULL)
9649 go_assert(this->array_->type()->is_error());
9650 return error_mark_node;
9653 tree type_tree = type_to_tree(array_type->get_backend(gogo));
9654 if (type_tree == error_mark_node)
9655 return error_mark_node;
9657 tree array_tree = this->array_->get_tree(context);
9658 if (array_tree == error_mark_node)
9659 return error_mark_node;
9661 if (array_type->length() == NULL && !DECL_P(array_tree))
9662 array_tree = save_expr(array_tree);
9664 tree length_tree = NULL_TREE;
9665 if (this->end_ == NULL || this->end_->is_nil_expression())
9667 length_tree = array_type->length_tree(gogo, array_tree);
9668 if (length_tree == error_mark_node)
9669 return error_mark_node;
9670 length_tree = save_expr(length_tree);
9673 tree capacity_tree = NULL_TREE;
9674 if (this->end_ != NULL)
9676 capacity_tree = array_type->capacity_tree(gogo, array_tree);
9677 if (capacity_tree == error_mark_node)
9678 return error_mark_node;
9679 capacity_tree = save_expr(capacity_tree);
9682 tree length_type = (length_tree != NULL_TREE
9683 ? TREE_TYPE(length_tree)
9684 : TREE_TYPE(capacity_tree));
9686 tree bad_index = boolean_false_node;
9688 tree start_tree = this->start_->get_tree(context);
9689 if (start_tree == error_mark_node)
9690 return error_mark_node;
9691 if (!DECL_P(start_tree))
9692 start_tree = save_expr(start_tree);
9693 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
9694 start_tree = convert_to_integer(length_type, start_tree);
9696 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
9699 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
9700 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9701 boolean_type_node, bad_index,
9702 fold_build2_loc(loc.gcc_location(),
9706 boolean_type_node, start_tree,
9711 int code = (array_type->length() != NULL
9712 ? (this->end_ == NULL
9713 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9714 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9715 : (this->end_ == NULL
9716 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9717 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9718 tree crash = Gogo::runtime_error(code, loc);
9720 if (this->end_ == NULL)
9722 // Simple array indexing. This has to return an l-value, so
9723 // wrap the index check into START_TREE.
9724 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
9725 build3(COND_EXPR, void_type_node,
9726 bad_index, crash, NULL_TREE),
9728 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
9730 if (array_type->length() != NULL)
9733 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
9734 start_tree, NULL_TREE, NULL_TREE);
9739 tree values = array_type->value_pointer_tree(gogo, array_tree);
9740 Type* element_type = array_type->element_type();
9741 Btype* belement_type = element_type->get_backend(gogo);
9742 tree element_type_tree = type_to_tree(belement_type);
9743 if (element_type_tree == error_mark_node)
9744 return error_mark_node;
9745 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9746 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9747 start_tree, element_size);
9748 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9749 TREE_TYPE(values), values, offset);
9750 return build_fold_indirect_ref(ptr);
9757 if (this->end_->is_nil_expression())
9758 end_tree = length_tree;
9761 end_tree = this->end_->get_tree(context);
9762 if (end_tree == error_mark_node)
9763 return error_mark_node;
9764 if (!DECL_P(end_tree))
9765 end_tree = save_expr(end_tree);
9766 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
9767 end_tree = convert_to_integer(length_type, end_tree);
9769 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
9772 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
9774 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9776 fold_build2_loc(loc.gcc_location(),
9777 LT_EXPR, boolean_type_node,
9778 end_tree, start_tree),
9779 fold_build2_loc(loc.gcc_location(),
9780 GT_EXPR, boolean_type_node,
9781 end_tree, capacity_tree));
9782 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9783 boolean_type_node, bad_index, bad_end);
9786 Type* element_type = array_type->element_type();
9787 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
9788 if (element_type_tree == error_mark_node)
9789 return error_mark_node;
9790 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9792 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9793 fold_convert_loc(loc.gcc_location(), sizetype,
9797 tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
9798 if (value_pointer == error_mark_node)
9799 return error_mark_node;
9801 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9802 TREE_TYPE(value_pointer),
9803 value_pointer, offset);
9805 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9806 length_type, end_tree, start_tree);
9808 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9809 length_type, capacity_tree,
9812 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
9813 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
9815 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
9817 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
9818 tree field = TYPE_FIELDS(struct_tree);
9819 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
9821 elt->value = value_pointer;
9823 elt = VEC_quick_push(constructor_elt, init, NULL);
9824 field = DECL_CHAIN(field);
9825 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
9827 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9828 result_length_tree);
9830 elt = VEC_quick_push(constructor_elt, init, NULL);
9831 field = DECL_CHAIN(field);
9832 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
9834 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9835 result_capacity_tree);
9837 tree constructor = build_constructor(struct_tree, init);
9839 if (TREE_CONSTANT(value_pointer)
9840 && TREE_CONSTANT(result_length_tree)
9841 && TREE_CONSTANT(result_capacity_tree))
9842 TREE_CONSTANT(constructor) = 1;
9844 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
9845 TREE_TYPE(constructor),
9846 build3(COND_EXPR, void_type_node,
9847 bad_index, crash, NULL_TREE),
9851 // Dump ast representation for an array index expression.
9854 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9857 Index_expression::dump_index_expression(ast_dump_context, this->array_,
9858 this->start_, this->end_);
9861 // Make an array index expression. END may be NULL.
9864 Expression::make_array_index(Expression* array, Expression* start,
9865 Expression* end, Location location)
9867 return new Array_index_expression(array, start, end, location);
9870 // A string index. This is used for both indexing and slicing.
9872 class String_index_expression : public Expression
9875 String_index_expression(Expression* string, Expression* start,
9876 Expression* end, Location location)
9877 : Expression(EXPRESSION_STRING_INDEX, location),
9878 string_(string), start_(start), end_(end)
9883 do_traverse(Traverse*);
9889 do_determine_type(const Type_context*);
9892 do_check_types(Gogo*);
9897 return Expression::make_string_index(this->string_->copy(),
9898 this->start_->copy(),
9901 : this->end_->copy()),
9906 do_must_eval_subexpressions_in_order(int* skip) const
9913 do_get_tree(Translate_context*);
9916 do_dump_expression(Ast_dump_context*) const;
9919 // The string we are getting a value from.
9920 Expression* string_;
9921 // The start or only index.
9923 // The end index of a slice. This may be NULL for a single index,
9924 // or it may be a nil expression for the length of the string.
9928 // String index traversal.
9931 String_index_expression::do_traverse(Traverse* traverse)
9933 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
9934 return TRAVERSE_EXIT;
9935 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9936 return TRAVERSE_EXIT;
9937 if (this->end_ != NULL)
9939 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9940 return TRAVERSE_EXIT;
9942 return TRAVERSE_CONTINUE;
9945 // Return the type of a string index.
9948 String_index_expression::do_type()
9950 if (this->end_ == NULL)
9951 return Type::lookup_integer_type("uint8");
9953 return this->string_->type();
9956 // Determine the type of a string index.
9959 String_index_expression::do_determine_type(const Type_context*)
9961 this->string_->determine_type_no_context();
9962 this->start_->determine_type_no_context();
9963 if (this->end_ != NULL)
9964 this->end_->determine_type_no_context();
9967 // Check types of a string index.
9970 String_index_expression::do_check_types(Gogo*)
9972 if (this->start_->type()->integer_type() == NULL)
9973 this->report_error(_("index must be integer"));
9974 if (this->end_ != NULL
9975 && this->end_->type()->integer_type() == NULL
9976 && !this->end_->is_nil_expression())
9977 this->report_error(_("slice end must be integer"));
9980 bool sval_valid = this->string_->string_constant_value(&sval);
9982 Numeric_constant inc;
9984 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9986 if (mpz_sgn(ival) < 0
9987 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
9989 error_at(this->start_->location(), "string index out of bounds");
9990 this->set_is_error();
9994 if (this->end_ != NULL && !this->end_->is_nil_expression())
9996 Numeric_constant enc;
9998 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10000 if (mpz_sgn(eval) < 0
10001 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10003 error_at(this->end_->location(), "string index out of bounds");
10004 this->set_is_error();
10011 // Get a tree for a string index.
10014 String_index_expression::do_get_tree(Translate_context* context)
10016 Location loc = this->location();
10018 tree string_tree = this->string_->get_tree(context);
10019 if (string_tree == error_mark_node)
10020 return error_mark_node;
10022 if (this->string_->type()->points_to() != NULL)
10023 string_tree = build_fold_indirect_ref(string_tree);
10024 if (!DECL_P(string_tree))
10025 string_tree = save_expr(string_tree);
10026 tree string_type = TREE_TYPE(string_tree);
10028 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
10029 length_tree = save_expr(length_tree);
10030 tree length_type = TREE_TYPE(length_tree);
10032 tree bad_index = boolean_false_node;
10034 tree start_tree = this->start_->get_tree(context);
10035 if (start_tree == error_mark_node)
10036 return error_mark_node;
10037 if (!DECL_P(start_tree))
10038 start_tree = save_expr(start_tree);
10039 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10040 start_tree = convert_to_integer(length_type, start_tree);
10042 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10045 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10047 int code = (this->end_ == NULL
10048 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10049 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10050 tree crash = Gogo::runtime_error(code, loc);
10052 if (this->end_ == NULL)
10054 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10055 boolean_type_node, bad_index,
10056 fold_build2_loc(loc.gcc_location(), GE_EXPR,
10058 start_tree, length_tree));
10060 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
10061 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10062 TREE_TYPE(bytes_tree),
10064 fold_convert_loc(loc.gcc_location(), sizetype,
10066 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
10068 return build2(COMPOUND_EXPR, TREE_TYPE(index),
10069 build3(COND_EXPR, void_type_node,
10070 bad_index, crash, NULL_TREE),
10076 if (this->end_->is_nil_expression())
10077 end_tree = build_int_cst(length_type, -1);
10080 end_tree = this->end_->get_tree(context);
10081 if (end_tree == error_mark_node)
10082 return error_mark_node;
10083 if (!DECL_P(end_tree))
10084 end_tree = save_expr(end_tree);
10085 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10086 end_tree = convert_to_integer(length_type, end_tree);
10088 bad_index = Expression::check_bounds(end_tree, length_type,
10091 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
10095 static tree strslice_fndecl;
10096 tree ret = Gogo::call_builtin(&strslice_fndecl,
10098 "__go_string_slice",
10107 if (ret == error_mark_node)
10108 return error_mark_node;
10109 // This will panic if the bounds are out of range for the
10111 TREE_NOTHROW(strslice_fndecl) = 0;
10113 if (bad_index == boolean_false_node)
10116 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
10117 build3(COND_EXPR, void_type_node,
10118 bad_index, crash, NULL_TREE),
10123 // Dump ast representation for a string index expression.
10126 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10129 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10130 this->start_, this->end_);
10133 // Make a string index expression. END may be NULL.
10136 Expression::make_string_index(Expression* string, Expression* start,
10137 Expression* end, Location location)
10139 return new String_index_expression(string, start, end, location);
10142 // Class Map_index.
10144 // Get the type of the map.
10147 Map_index_expression::get_map_type() const
10149 Map_type* mt = this->map_->type()->deref()->map_type();
10151 go_assert(saw_errors());
10155 // Map index traversal.
10158 Map_index_expression::do_traverse(Traverse* traverse)
10160 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10161 return TRAVERSE_EXIT;
10162 return Expression::traverse(&this->index_, traverse);
10165 // Return the type of a map index.
10168 Map_index_expression::do_type()
10170 Map_type* mt = this->get_map_type();
10172 return Type::make_error_type();
10173 Type* type = mt->val_type();
10174 // If this map index is in a tuple assignment, we actually return a
10175 // pointer to the value type. Tuple_map_assignment_statement is
10176 // responsible for handling this correctly. We need to get the type
10177 // right in case this gets assigned to a temporary variable.
10178 if (this->is_in_tuple_assignment_)
10179 type = Type::make_pointer_type(type);
10183 // Fix the type of a map index.
10186 Map_index_expression::do_determine_type(const Type_context*)
10188 this->map_->determine_type_no_context();
10189 Map_type* mt = this->get_map_type();
10190 Type* key_type = mt == NULL ? NULL : mt->key_type();
10191 Type_context subcontext(key_type, false);
10192 this->index_->determine_type(&subcontext);
10195 // Check types of a map index.
10198 Map_index_expression::do_check_types(Gogo*)
10200 std::string reason;
10201 Map_type* mt = this->get_map_type();
10204 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10206 if (reason.empty())
10207 this->report_error(_("incompatible type for map index"));
10210 error_at(this->location(), "incompatible type for map index (%s)",
10212 this->set_is_error();
10217 // Get a tree for a map index.
10220 Map_index_expression::do_get_tree(Translate_context* context)
10222 Map_type* type = this->get_map_type();
10224 return error_mark_node;
10226 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
10227 if (valptr == error_mark_node)
10228 return error_mark_node;
10229 valptr = save_expr(valptr);
10231 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
10233 if (this->is_lvalue_)
10234 return build_fold_indirect_ref(valptr);
10235 else if (this->is_in_tuple_assignment_)
10237 // Tuple_map_assignment_statement is responsible for using this
10243 Gogo* gogo = context->gogo();
10244 Btype* val_btype = type->val_type()->get_backend(gogo);
10245 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10246 return fold_build3(COND_EXPR, val_type_tree,
10247 fold_build2(EQ_EXPR, boolean_type_node, valptr,
10248 fold_convert(TREE_TYPE(valptr),
10249 null_pointer_node)),
10250 expr_to_tree(val_zero),
10251 build_fold_indirect_ref(valptr));
10255 // Get a tree for the map index. This returns a tree which evaluates
10256 // to a pointer to a value. The pointer will be NULL if the key is
10260 Map_index_expression::get_value_pointer(Translate_context* context,
10263 Map_type* type = this->get_map_type();
10265 return error_mark_node;
10267 tree map_tree = this->map_->get_tree(context);
10268 tree index_tree = this->index_->get_tree(context);
10269 index_tree = Expression::convert_for_assignment(context, type->key_type(),
10270 this->index_->type(),
10273 if (map_tree == error_mark_node || index_tree == error_mark_node)
10274 return error_mark_node;
10276 if (this->map_->type()->points_to() != NULL)
10277 map_tree = build_fold_indirect_ref(map_tree);
10279 // We need to pass in a pointer to the key, so stuff it into a
10283 if (current_function_decl != NULL)
10285 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
10286 DECL_IGNORED_P(tmp) = 0;
10287 DECL_INITIAL(tmp) = index_tree;
10288 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
10289 TREE_ADDRESSABLE(tmp) = 1;
10293 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
10294 create_tmp_var_name("M"),
10295 TREE_TYPE(index_tree));
10296 DECL_EXTERNAL(tmp) = 0;
10297 TREE_PUBLIC(tmp) = 0;
10298 TREE_STATIC(tmp) = 1;
10299 DECL_ARTIFICIAL(tmp) = 1;
10300 if (!TREE_CONSTANT(index_tree))
10301 make_tmp = fold_build2_loc(this->location().gcc_location(),
10302 INIT_EXPR, void_type_node,
10306 TREE_READONLY(tmp) = 1;
10307 TREE_CONSTANT(tmp) = 1;
10308 DECL_INITIAL(tmp) = index_tree;
10309 make_tmp = NULL_TREE;
10311 rest_of_decl_compilation(tmp, 1, 0);
10314 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
10315 build_fold_addr_expr_loc(this->location().gcc_location(),
10318 static tree map_index_fndecl;
10319 tree call = Gogo::call_builtin(&map_index_fndecl,
10323 const_ptr_type_node,
10324 TREE_TYPE(map_tree),
10326 const_ptr_type_node,
10330 ? boolean_true_node
10331 : boolean_false_node));
10332 if (call == error_mark_node)
10333 return error_mark_node;
10334 // This can panic on a map of interface type if the interface holds
10335 // an uncomparable or unhashable type.
10336 TREE_NOTHROW(map_index_fndecl) = 0;
10338 Type* val_type = type->val_type();
10339 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
10340 if (val_type_tree == error_mark_node)
10341 return error_mark_node;
10342 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
10344 tree ret = fold_convert_loc(this->location().gcc_location(),
10345 ptr_val_type_tree, call);
10346 if (make_tmp != NULL_TREE)
10347 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
10351 // Dump ast representation for a map index expression
10354 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10357 Index_expression::dump_index_expression(ast_dump_context,
10358 this->map_, this->index_, NULL);
10361 // Make a map index expression.
10363 Map_index_expression*
10364 Expression::make_map_index(Expression* map, Expression* index,
10367 return new Map_index_expression(map, index, location);
10370 // Class Field_reference_expression.
10372 // Return the type of a field reference.
10375 Field_reference_expression::do_type()
10377 Type* type = this->expr_->type();
10378 if (type->is_error())
10380 Struct_type* struct_type = type->struct_type();
10381 go_assert(struct_type != NULL);
10382 return struct_type->field(this->field_index_)->type();
10385 // Check the types for a field reference.
10388 Field_reference_expression::do_check_types(Gogo*)
10390 Type* type = this->expr_->type();
10391 if (type->is_error())
10393 Struct_type* struct_type = type->struct_type();
10394 go_assert(struct_type != NULL);
10395 go_assert(struct_type->field(this->field_index_) != NULL);
10398 // Get a tree for a field reference.
10401 Field_reference_expression::do_get_tree(Translate_context* context)
10403 tree struct_tree = this->expr_->get_tree(context);
10404 if (struct_tree == error_mark_node
10405 || TREE_TYPE(struct_tree) == error_mark_node)
10406 return error_mark_node;
10407 go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
10408 tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
10409 if (field == NULL_TREE)
10411 // This can happen for a type which refers to itself indirectly
10412 // and then turns out to be erroneous.
10413 go_assert(saw_errors());
10414 return error_mark_node;
10416 for (unsigned int i = this->field_index_; i > 0; --i)
10418 field = DECL_CHAIN(field);
10419 go_assert(field != NULL_TREE);
10421 if (TREE_TYPE(field) == error_mark_node)
10422 return error_mark_node;
10423 return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
10427 // Dump ast representation for a field reference expression.
10430 Field_reference_expression::do_dump_expression(
10431 Ast_dump_context* ast_dump_context) const
10433 this->expr_->dump_expression(ast_dump_context);
10434 ast_dump_context->ostream() << "." << this->field_index_;
10437 // Make a reference to a qualified identifier in an expression.
10439 Field_reference_expression*
10440 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10443 return new Field_reference_expression(expr, field_index, location);
10446 // Class Interface_field_reference_expression.
10448 // Return a tree for the pointer to the function to call.
10451 Interface_field_reference_expression::get_function_tree(Translate_context*,
10454 if (this->expr_->type()->points_to() != NULL)
10455 expr = build_fold_indirect_ref(expr);
10457 tree expr_type = TREE_TYPE(expr);
10458 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10460 tree field = TYPE_FIELDS(expr_type);
10461 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
10463 tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10464 go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
10466 table = build_fold_indirect_ref(table);
10467 go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
10469 std::string name = Gogo::unpack_hidden_name(this->name_);
10470 for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
10471 field != NULL_TREE;
10472 field = DECL_CHAIN(field))
10474 if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
10477 go_assert(field != NULL_TREE);
10479 return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
10482 // Return a tree for the first argument to pass to the interface
10486 Interface_field_reference_expression::get_underlying_object_tree(
10487 Translate_context*,
10490 if (this->expr_->type()->points_to() != NULL)
10491 expr = build_fold_indirect_ref(expr);
10493 tree expr_type = TREE_TYPE(expr);
10494 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10496 tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
10497 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
10499 return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10505 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10507 return Expression::traverse(&this->expr_, traverse);
10510 // Return the type of an interface field reference.
10513 Interface_field_reference_expression::do_type()
10515 Type* expr_type = this->expr_->type();
10517 Type* points_to = expr_type->points_to();
10518 if (points_to != NULL)
10519 expr_type = points_to;
10521 Interface_type* interface_type = expr_type->interface_type();
10522 if (interface_type == NULL)
10523 return Type::make_error_type();
10525 const Typed_identifier* method = interface_type->find_method(this->name_);
10526 if (method == NULL)
10527 return Type::make_error_type();
10529 return method->type();
10532 // Determine types.
10535 Interface_field_reference_expression::do_determine_type(const Type_context*)
10537 this->expr_->determine_type_no_context();
10540 // Check the types for an interface field reference.
10543 Interface_field_reference_expression::do_check_types(Gogo*)
10545 Type* type = this->expr_->type();
10547 Type* points_to = type->points_to();
10548 if (points_to != NULL)
10551 Interface_type* interface_type = type->interface_type();
10552 if (interface_type == NULL)
10554 if (!type->is_error_type())
10555 this->report_error(_("expected interface or pointer to interface"));
10559 const Typed_identifier* method =
10560 interface_type->find_method(this->name_);
10561 if (method == NULL)
10563 error_at(this->location(), "method %qs not in interface",
10564 Gogo::message_name(this->name_).c_str());
10565 this->set_is_error();
10570 // Get a tree for a reference to a field in an interface. There is no
10571 // standard tree type representation for this: it's a function
10572 // attached to its first argument, like a Bound_method_expression.
10573 // The only places it may currently be used are in a Call_expression
10574 // or a Go_statement, which will take it apart directly. So this has
10575 // nothing to do at present.
10578 Interface_field_reference_expression::do_get_tree(Translate_context*)
10580 error_at(this->location(), "reference to method other than calling it");
10581 return error_mark_node;
10584 // Dump ast representation for an interface field reference.
10587 Interface_field_reference_expression::do_dump_expression(
10588 Ast_dump_context* ast_dump_context) const
10590 this->expr_->dump_expression(ast_dump_context);
10591 ast_dump_context->ostream() << "." << this->name_;
10594 // Make a reference to a field in an interface.
10597 Expression::make_interface_field_reference(Expression* expr,
10598 const std::string& field,
10601 return new Interface_field_reference_expression(expr, field, location);
10604 // A general selector. This is a Parser_expression for LEFT.NAME. It
10605 // is lowered after we know the type of the left hand side.
10607 class Selector_expression : public Parser_expression
10610 Selector_expression(Expression* left, const std::string& name,
10612 : Parser_expression(EXPRESSION_SELECTOR, location),
10613 left_(left), name_(name)
10618 do_traverse(Traverse* traverse)
10619 { return Expression::traverse(&this->left_, traverse); }
10622 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
10627 return new Selector_expression(this->left_->copy(), this->name_,
10632 do_dump_expression(Ast_dump_context* ast_dump_context) const;
10636 lower_method_expression(Gogo*);
10638 // The expression on the left hand side.
10640 // The name on the right hand side.
10644 // Lower a selector expression once we know the real type of the left
10648 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
10651 Expression* left = this->left_;
10652 if (left->is_type_expression())
10653 return this->lower_method_expression(gogo);
10654 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
10658 // Lower a method expression T.M or (*T).M. We turn this into a
10659 // function literal.
10662 Selector_expression::lower_method_expression(Gogo* gogo)
10664 Location location = this->location();
10665 Type* type = this->left_->type();
10666 const std::string& name(this->name_);
10669 if (type->points_to() == NULL)
10670 is_pointer = false;
10674 type = type->points_to();
10676 Named_type* nt = type->named_type();
10680 ("method expression requires named type or "
10681 "pointer to named type"));
10682 return Expression::make_error(location);
10686 Method* method = nt->method_function(name, &is_ambiguous);
10687 const Typed_identifier* imethod = NULL;
10688 if (method == NULL && !is_pointer)
10690 Interface_type* it = nt->interface_type();
10692 imethod = it->find_method(name);
10695 if (method == NULL && imethod == NULL)
10698 error_at(location, "type %<%s%s%> has no method %<%s%>",
10699 is_pointer ? "*" : "",
10700 nt->message_name().c_str(),
10701 Gogo::message_name(name).c_str());
10703 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
10704 Gogo::message_name(name).c_str(),
10705 is_pointer ? "*" : "",
10706 nt->message_name().c_str());
10707 return Expression::make_error(location);
10710 if (method != NULL && !is_pointer && !method->is_value_method())
10712 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
10713 nt->message_name().c_str(),
10714 Gogo::message_name(name).c_str());
10715 return Expression::make_error(location);
10718 // Build a new function type in which the receiver becomes the first
10720 Function_type* method_type;
10721 if (method != NULL)
10723 method_type = method->type();
10724 go_assert(method_type->is_method());
10728 method_type = imethod->type()->function_type();
10729 go_assert(method_type != NULL && !method_type->is_method());
10732 const char* const receiver_name = "$this";
10733 Typed_identifier_list* parameters = new Typed_identifier_list();
10734 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
10737 const Typed_identifier_list* method_parameters = method_type->parameters();
10738 if (method_parameters != NULL)
10741 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
10742 p != method_parameters->end();
10745 if (!p->name().empty())
10746 parameters->push_back(*p);
10750 snprintf(buf, sizeof buf, "$param%d", i);
10751 parameters->push_back(Typed_identifier(buf, p->type(),
10757 const Typed_identifier_list* method_results = method_type->results();
10758 Typed_identifier_list* results;
10759 if (method_results == NULL)
10763 results = new Typed_identifier_list();
10764 for (Typed_identifier_list::const_iterator p = method_results->begin();
10765 p != method_results->end();
10767 results->push_back(*p);
10770 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
10772 if (method_type->is_varargs())
10773 fntype->set_is_varargs();
10775 // We generate methods which always takes a pointer to the receiver
10776 // as their first argument. If this is for a pointer type, we can
10777 // simply reuse the existing function. We use an internal hack to
10778 // get the right type.
10780 if (method != NULL && is_pointer)
10782 Named_object* mno = (method->needs_stub_method()
10783 ? method->stub_object()
10784 : method->named_object());
10785 Expression* f = Expression::make_func_reference(mno, NULL, location);
10786 f = Expression::make_cast(fntype, f, location);
10787 Type_conversion_expression* tce =
10788 static_cast<Type_conversion_expression*>(f);
10789 tce->set_may_convert_function_types();
10793 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
10796 Named_object* vno = gogo->lookup(receiver_name, NULL);
10797 go_assert(vno != NULL);
10798 Expression* ve = Expression::make_var_reference(vno, location);
10800 if (method != NULL)
10801 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
10803 bm = Expression::make_interface_field_reference(ve, name, location);
10805 // Even though we found the method above, if it has an error type we
10806 // may see an error here.
10807 if (bm->is_error_expression())
10809 gogo->finish_function(location);
10813 Expression_list* args;
10814 if (parameters->size() <= 1)
10818 args = new Expression_list();
10819 Typed_identifier_list::const_iterator p = parameters->begin();
10821 for (; p != parameters->end(); ++p)
10823 vno = gogo->lookup(p->name(), NULL);
10824 go_assert(vno != NULL);
10825 args->push_back(Expression::make_var_reference(vno, location));
10829 gogo->start_block(location);
10831 Call_expression* call = Expression::make_call(bm, args,
10832 method_type->is_varargs(),
10835 size_t count = call->result_count();
10838 s = Statement::make_statement(call, true);
10841 Expression_list* retvals = new Expression_list();
10843 retvals->push_back(call);
10846 for (size_t i = 0; i < count; ++i)
10847 retvals->push_back(Expression::make_call_result(call, i));
10849 s = Statement::make_return_statement(retvals, location);
10851 gogo->add_statement(s);
10853 Block* b = gogo->finish_block(location);
10855 gogo->add_block(b, location);
10857 // Lower the call in case there are multiple results.
10858 gogo->lower_block(no, b);
10860 gogo->finish_function(location);
10862 return Expression::make_func_reference(no, NULL, location);
10865 // Dump the ast for a selector expression.
10868 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10871 ast_dump_context->dump_expression(this->left_);
10872 ast_dump_context->ostream() << ".";
10873 ast_dump_context->ostream() << this->name_;
10876 // Make a selector expression.
10879 Expression::make_selector(Expression* left, const std::string& name,
10882 return new Selector_expression(left, name, location);
10885 // Implement the builtin function new.
10887 class Allocation_expression : public Expression
10890 Allocation_expression(Type* type, Location location)
10891 : Expression(EXPRESSION_ALLOCATION, location),
10897 do_traverse(Traverse* traverse)
10898 { return Type::traverse(this->type_, traverse); }
10902 { return Type::make_pointer_type(this->type_); }
10905 do_determine_type(const Type_context*)
10910 { return new Allocation_expression(this->type_, this->location()); }
10913 do_get_tree(Translate_context*);
10916 do_dump_expression(Ast_dump_context*) const;
10919 // The type we are allocating.
10923 // Return a tree for an allocation expression.
10926 Allocation_expression::do_get_tree(Translate_context* context)
10928 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
10929 if (type_tree == error_mark_node)
10930 return error_mark_node;
10931 tree size_tree = TYPE_SIZE_UNIT(type_tree);
10932 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
10934 if (space == error_mark_node)
10935 return error_mark_node;
10936 return fold_convert(build_pointer_type(type_tree), space);
10939 // Dump ast representation for an allocation expression.
10942 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10945 ast_dump_context->ostream() << "new(";
10946 ast_dump_context->dump_type(this->type_);
10947 ast_dump_context->ostream() << ")";
10950 // Make an allocation expression.
10953 Expression::make_allocation(Type* type, Location location)
10955 return new Allocation_expression(type, location);
10958 // Construct a struct.
10960 class Struct_construction_expression : public Expression
10963 Struct_construction_expression(Type* type, Expression_list* vals,
10965 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
10966 type_(type), vals_(vals)
10969 // Return whether this is a constant initializer.
10971 is_constant_struct() const;
10975 do_traverse(Traverse* traverse);
10979 { return this->type_; }
10982 do_determine_type(const Type_context*);
10985 do_check_types(Gogo*);
10990 return new Struct_construction_expression(this->type_, this->vals_->copy(),
10995 do_get_tree(Translate_context*);
10998 do_export(Export*) const;
11001 do_dump_expression(Ast_dump_context*) const;
11004 // The type of the struct to construct.
11006 // The list of values, in order of the fields in the struct. A NULL
11007 // entry means that the field should be zero-initialized.
11008 Expression_list* vals_;
11014 Struct_construction_expression::do_traverse(Traverse* traverse)
11016 if (this->vals_ != NULL
11017 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11018 return TRAVERSE_EXIT;
11019 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11020 return TRAVERSE_EXIT;
11021 return TRAVERSE_CONTINUE;
11024 // Return whether this is a constant initializer.
11027 Struct_construction_expression::is_constant_struct() const
11029 if (this->vals_ == NULL)
11031 for (Expression_list::const_iterator pv = this->vals_->begin();
11032 pv != this->vals_->end();
11036 && !(*pv)->is_constant()
11037 && (!(*pv)->is_composite_literal()
11038 || (*pv)->is_nonconstant_composite_literal()))
11042 const Struct_field_list* fields = this->type_->struct_type()->fields();
11043 for (Struct_field_list::const_iterator pf = fields->begin();
11044 pf != fields->end();
11047 // There are no constant constructors for interfaces.
11048 if (pf->type()->interface_type() != NULL)
11055 // Final type determination.
11058 Struct_construction_expression::do_determine_type(const Type_context*)
11060 if (this->vals_ == NULL)
11062 const Struct_field_list* fields = this->type_->struct_type()->fields();
11063 Expression_list::const_iterator pv = this->vals_->begin();
11064 for (Struct_field_list::const_iterator pf = fields->begin();
11065 pf != fields->end();
11068 if (pv == this->vals_->end())
11072 Type_context subcontext(pf->type(), false);
11073 (*pv)->determine_type(&subcontext);
11076 // Extra values are an error we will report elsewhere; we still want
11077 // to determine the type to avoid knockon errors.
11078 for (; pv != this->vals_->end(); ++pv)
11079 (*pv)->determine_type_no_context();
11085 Struct_construction_expression::do_check_types(Gogo*)
11087 if (this->vals_ == NULL)
11090 Struct_type* st = this->type_->struct_type();
11091 if (this->vals_->size() > st->field_count())
11093 this->report_error(_("too many expressions for struct"));
11097 const Struct_field_list* fields = st->fields();
11098 Expression_list::const_iterator pv = this->vals_->begin();
11100 for (Struct_field_list::const_iterator pf = fields->begin();
11101 pf != fields->end();
11104 if (pv == this->vals_->end())
11106 this->report_error(_("too few expressions for struct"));
11113 std::string reason;
11114 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11116 if (reason.empty())
11117 error_at((*pv)->location(),
11118 "incompatible type for field %d in struct construction",
11121 error_at((*pv)->location(),
11122 ("incompatible type for field %d in "
11123 "struct construction (%s)"),
11124 i + 1, reason.c_str());
11125 this->set_is_error();
11128 go_assert(pv == this->vals_->end());
11131 // Return a tree for constructing a struct.
11134 Struct_construction_expression::do_get_tree(Translate_context* context)
11136 Gogo* gogo = context->gogo();
11138 if (this->vals_ == NULL)
11140 Btype* btype = this->type_->get_backend(gogo);
11141 return expr_to_tree(gogo->backend()->zero_expression(btype));
11144 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11145 if (type_tree == error_mark_node)
11146 return error_mark_node;
11147 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11149 bool is_constant = true;
11150 const Struct_field_list* fields = this->type_->struct_type()->fields();
11151 VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
11153 Struct_field_list::const_iterator pf = fields->begin();
11154 Expression_list::const_iterator pv = this->vals_->begin();
11155 for (tree field = TYPE_FIELDS(type_tree);
11156 field != NULL_TREE;
11157 field = DECL_CHAIN(field), ++pf)
11159 go_assert(pf != fields->end());
11161 Btype* fbtype = pf->type()->get_backend(gogo);
11164 if (pv == this->vals_->end())
11165 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11166 else if (*pv == NULL)
11168 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11173 val = Expression::convert_for_assignment(context, pf->type(),
11175 (*pv)->get_tree(context),
11180 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
11181 return error_mark_node;
11183 constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
11184 elt->index = field;
11186 if (!TREE_CONSTANT(val))
11187 is_constant = false;
11189 go_assert(pf == fields->end());
11191 tree ret = build_constructor(type_tree, elts);
11193 TREE_CONSTANT(ret) = 1;
11197 // Export a struct construction.
11200 Struct_construction_expression::do_export(Export* exp) const
11202 exp->write_c_string("convert(");
11203 exp->write_type(this->type_);
11204 for (Expression_list::const_iterator pv = this->vals_->begin();
11205 pv != this->vals_->end();
11208 exp->write_c_string(", ");
11210 (*pv)->export_expression(exp);
11212 exp->write_c_string(")");
11215 // Dump ast representation of a struct construction expression.
11218 Struct_construction_expression::do_dump_expression(
11219 Ast_dump_context* ast_dump_context) const
11221 ast_dump_context->dump_type(this->type_);
11222 ast_dump_context->ostream() << "{";
11223 ast_dump_context->dump_expression_list(this->vals_);
11224 ast_dump_context->ostream() << "}";
11227 // Make a struct composite literal. This used by the thunk code.
11230 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11233 go_assert(type->struct_type() != NULL);
11234 return new Struct_construction_expression(type, vals, location);
11237 // Construct an array. This class is not used directly; instead we
11238 // use the child classes, Fixed_array_construction_expression and
11239 // Open_array_construction_expression.
11241 class Array_construction_expression : public Expression
11244 Array_construction_expression(Expression_classification classification,
11245 Type* type, Expression_list* vals,
11247 : Expression(classification, location),
11248 type_(type), vals_(vals)
11252 // Return whether this is a constant initializer.
11254 is_constant_array() const;
11256 // Return the number of elements.
11258 element_count() const
11259 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11263 do_traverse(Traverse* traverse);
11267 { return this->type_; }
11270 do_determine_type(const Type_context*);
11273 do_check_types(Gogo*);
11276 do_export(Export*) const;
11278 // The list of values.
11281 { return this->vals_; }
11283 // Get a constructor tree for the array values.
11285 get_constructor_tree(Translate_context* context, tree type_tree);
11288 do_dump_expression(Ast_dump_context*) const;
11291 // The type of the array to construct.
11293 // The list of values.
11294 Expression_list* vals_;
11300 Array_construction_expression::do_traverse(Traverse* traverse)
11302 if (this->vals_ != NULL
11303 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11304 return TRAVERSE_EXIT;
11305 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11306 return TRAVERSE_EXIT;
11307 return TRAVERSE_CONTINUE;
11310 // Return whether this is a constant initializer.
11313 Array_construction_expression::is_constant_array() const
11315 if (this->vals_ == NULL)
11318 // There are no constant constructors for interfaces.
11319 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11322 for (Expression_list::const_iterator pv = this->vals_->begin();
11323 pv != this->vals_->end();
11327 && !(*pv)->is_constant()
11328 && (!(*pv)->is_composite_literal()
11329 || (*pv)->is_nonconstant_composite_literal()))
11335 // Final type determination.
11338 Array_construction_expression::do_determine_type(const Type_context*)
11340 if (this->vals_ == NULL)
11342 Type_context subcontext(this->type_->array_type()->element_type(), false);
11343 for (Expression_list::const_iterator pv = this->vals_->begin();
11344 pv != this->vals_->end();
11348 (*pv)->determine_type(&subcontext);
11355 Array_construction_expression::do_check_types(Gogo*)
11357 if (this->vals_ == NULL)
11360 Array_type* at = this->type_->array_type();
11362 Type* element_type = at->element_type();
11363 for (Expression_list::const_iterator pv = this->vals_->begin();
11364 pv != this->vals_->end();
11368 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11370 error_at((*pv)->location(),
11371 "incompatible type for element %d in composite literal",
11373 this->set_is_error();
11377 Expression* length = at->length();
11378 Numeric_constant nc;
11381 && !length->is_error_expression()
11382 && length->numeric_constant_value(&nc)
11383 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
11385 if (this->vals_->size() > val)
11386 this->report_error(_("too many elements in composite literal"));
11390 // Get a constructor tree for the array values.
11393 Array_construction_expression::get_constructor_tree(Translate_context* context,
11396 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11397 (this->vals_ == NULL
11399 : this->vals_->size()));
11400 Type* element_type = this->type_->array_type()->element_type();
11401 bool is_constant = true;
11402 if (this->vals_ != NULL)
11405 for (Expression_list::const_iterator pv = this->vals_->begin();
11406 pv != this->vals_->end();
11409 constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
11410 elt->index = size_int(i);
11413 Gogo* gogo = context->gogo();
11414 Btype* ebtype = element_type->get_backend(gogo);
11415 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11416 elt->value = expr_to_tree(zv);
11420 tree value_tree = (*pv)->get_tree(context);
11421 elt->value = Expression::convert_for_assignment(context,
11427 if (elt->value == error_mark_node)
11428 return error_mark_node;
11429 if (!TREE_CONSTANT(elt->value))
11430 is_constant = false;
11434 tree ret = build_constructor(type_tree, values);
11436 TREE_CONSTANT(ret) = 1;
11440 // Export an array construction.
11443 Array_construction_expression::do_export(Export* exp) const
11445 exp->write_c_string("convert(");
11446 exp->write_type(this->type_);
11447 if (this->vals_ != NULL)
11449 for (Expression_list::const_iterator pv = this->vals_->begin();
11450 pv != this->vals_->end();
11453 exp->write_c_string(", ");
11455 (*pv)->export_expression(exp);
11458 exp->write_c_string(")");
11461 // Dump ast representation of an array construction expressin.
11464 Array_construction_expression::do_dump_expression(
11465 Ast_dump_context* ast_dump_context) const
11467 Expression* length = this->type_->array_type() != NULL ?
11468 this->type_->array_type()->length() : NULL;
11470 ast_dump_context->ostream() << "[" ;
11471 if (length != NULL)
11473 ast_dump_context->dump_expression(length);
11475 ast_dump_context->ostream() << "]" ;
11476 ast_dump_context->dump_type(this->type_);
11477 ast_dump_context->ostream() << "{" ;
11478 ast_dump_context->dump_expression_list(this->vals_);
11479 ast_dump_context->ostream() << "}" ;
11483 // Construct a fixed array.
11485 class Fixed_array_construction_expression :
11486 public Array_construction_expression
11489 Fixed_array_construction_expression(Type* type, Expression_list* vals,
11491 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11492 type, vals, location)
11494 go_assert(type->array_type() != NULL
11495 && type->array_type()->length() != NULL);
11502 return new Fixed_array_construction_expression(this->type(),
11503 (this->vals() == NULL
11505 : this->vals()->copy()),
11510 do_get_tree(Translate_context*);
11513 do_dump_expression(Ast_dump_context*);
11516 // Return a tree for constructing a fixed array.
11519 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
11521 Type* type = this->type();
11522 Btype* btype = type->get_backend(context->gogo());
11523 return this->get_constructor_tree(context, type_to_tree(btype));
11526 // Dump ast representation of an array construction expressin.
11529 Fixed_array_construction_expression::do_dump_expression(
11530 Ast_dump_context* ast_dump_context)
11533 ast_dump_context->ostream() << "[";
11534 ast_dump_context->dump_expression (this->type()->array_type()->length());
11535 ast_dump_context->ostream() << "]";
11536 ast_dump_context->dump_type(this->type());
11537 ast_dump_context->ostream() << "{";
11538 ast_dump_context->dump_expression_list(this->vals());
11539 ast_dump_context->ostream() << "}";
11542 // Construct an open array.
11544 class Open_array_construction_expression : public Array_construction_expression
11547 Open_array_construction_expression(Type* type, Expression_list* vals,
11549 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
11550 type, vals, location)
11552 go_assert(type->array_type() != NULL
11553 && type->array_type()->length() == NULL);
11557 // Note that taking the address of an open array literal is invalid.
11562 return new Open_array_construction_expression(this->type(),
11563 (this->vals() == NULL
11565 : this->vals()->copy()),
11570 do_get_tree(Translate_context*);
11573 // Return a tree for constructing an open array.
11576 Open_array_construction_expression::do_get_tree(Translate_context* context)
11578 Array_type* array_type = this->type()->array_type();
11579 if (array_type == NULL)
11581 go_assert(this->type()->is_error());
11582 return error_mark_node;
11585 Type* element_type = array_type->element_type();
11586 Btype* belement_type = element_type->get_backend(context->gogo());
11587 tree element_type_tree = type_to_tree(belement_type);
11588 if (element_type_tree == error_mark_node)
11589 return error_mark_node;
11593 if (this->vals() == NULL || this->vals()->empty())
11595 // We need to create a unique value.
11596 tree max = size_int(0);
11597 tree constructor_type = build_array_type(element_type_tree,
11598 build_index_type(max));
11599 if (constructor_type == error_mark_node)
11600 return error_mark_node;
11601 VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
11602 constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
11603 elt->index = size_int(0);
11604 Gogo* gogo = context->gogo();
11605 Btype* btype = element_type->get_backend(gogo);
11606 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
11607 values = build_constructor(constructor_type, vec);
11608 if (TREE_CONSTANT(elt->value))
11609 TREE_CONSTANT(values) = 1;
11610 length_tree = size_int(0);
11614 tree max = size_int(this->vals()->size() - 1);
11615 tree constructor_type = build_array_type(element_type_tree,
11616 build_index_type(max));
11617 if (constructor_type == error_mark_node)
11618 return error_mark_node;
11619 values = this->get_constructor_tree(context, constructor_type);
11620 length_tree = size_int(this->vals()->size());
11623 if (values == error_mark_node)
11624 return error_mark_node;
11626 bool is_constant_initializer = TREE_CONSTANT(values);
11628 // We have to copy the initial values into heap memory if we are in
11629 // a function or if the values are not constants. We also have to
11630 // copy them if they may contain pointers in a non-constant context,
11631 // as otherwise the garbage collector won't see them.
11632 bool copy_to_heap = (context->function() != NULL
11633 || !is_constant_initializer
11634 || (element_type->has_pointer()
11635 && !context->is_const()));
11637 if (is_constant_initializer)
11639 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11640 create_tmp_var_name("C"), TREE_TYPE(values));
11641 DECL_EXTERNAL(tmp) = 0;
11642 TREE_PUBLIC(tmp) = 0;
11643 TREE_STATIC(tmp) = 1;
11644 DECL_ARTIFICIAL(tmp) = 1;
11647 // If we are not copying the value to the heap, we will only
11648 // initialize the value once, so we can use this directly
11649 // rather than copying it. In that case we can't make it
11650 // read-only, because the program is permitted to change it.
11651 TREE_READONLY(tmp) = 1;
11652 TREE_CONSTANT(tmp) = 1;
11654 DECL_INITIAL(tmp) = values;
11655 rest_of_decl_compilation(tmp, 1, 0);
11663 // the initializer will only run once.
11664 space = build_fold_addr_expr(values);
11669 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
11670 space = context->gogo()->allocate_memory(element_type, memsize,
11672 space = save_expr(space);
11674 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
11675 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
11677 TREE_THIS_NOTRAP(ref) = 1;
11678 set = build2(MODIFY_EXPR, void_type_node, ref, values);
11681 // Build a constructor for the open array.
11683 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
11684 if (type_tree == error_mark_node)
11685 return error_mark_node;
11686 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11688 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
11690 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
11691 tree field = TYPE_FIELDS(type_tree);
11692 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
11693 elt->index = field;
11694 elt->value = fold_convert(TREE_TYPE(field), space);
11696 elt = VEC_quick_push(constructor_elt, init, NULL);
11697 field = DECL_CHAIN(field);
11698 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
11699 elt->index = field;
11700 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11702 elt = VEC_quick_push(constructor_elt, init, NULL);
11703 field = DECL_CHAIN(field);
11704 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
11705 elt->index = field;
11706 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11708 tree constructor = build_constructor(type_tree, init);
11709 if (constructor == error_mark_node)
11710 return error_mark_node;
11712 TREE_CONSTANT(constructor) = 1;
11714 if (set == NULL_TREE)
11715 return constructor;
11717 return build2(COMPOUND_EXPR, type_tree, set, constructor);
11720 // Make a slice composite literal. This is used by the type
11721 // descriptor code.
11724 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
11727 go_assert(type->is_slice_type());
11728 return new Open_array_construction_expression(type, vals, location);
11731 // Construct a map.
11733 class Map_construction_expression : public Expression
11736 Map_construction_expression(Type* type, Expression_list* vals,
11738 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
11739 type_(type), vals_(vals)
11740 { go_assert(vals == NULL || vals->size() % 2 == 0); }
11744 do_traverse(Traverse* traverse);
11748 { return this->type_; }
11751 do_determine_type(const Type_context*);
11754 do_check_types(Gogo*);
11759 return new Map_construction_expression(this->type_, this->vals_->copy(),
11764 do_get_tree(Translate_context*);
11767 do_export(Export*) const;
11770 do_dump_expression(Ast_dump_context*) const;
11773 // The type of the map to construct.
11775 // The list of values.
11776 Expression_list* vals_;
11782 Map_construction_expression::do_traverse(Traverse* traverse)
11784 if (this->vals_ != NULL
11785 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11786 return TRAVERSE_EXIT;
11787 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11788 return TRAVERSE_EXIT;
11789 return TRAVERSE_CONTINUE;
11792 // Final type determination.
11795 Map_construction_expression::do_determine_type(const Type_context*)
11797 if (this->vals_ == NULL)
11800 Map_type* mt = this->type_->map_type();
11801 Type_context key_context(mt->key_type(), false);
11802 Type_context val_context(mt->val_type(), false);
11803 for (Expression_list::const_iterator pv = this->vals_->begin();
11804 pv != this->vals_->end();
11807 (*pv)->determine_type(&key_context);
11809 (*pv)->determine_type(&val_context);
11816 Map_construction_expression::do_check_types(Gogo*)
11818 if (this->vals_ == NULL)
11821 Map_type* mt = this->type_->map_type();
11823 Type* key_type = mt->key_type();
11824 Type* val_type = mt->val_type();
11825 for (Expression_list::const_iterator pv = this->vals_->begin();
11826 pv != this->vals_->end();
11829 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
11831 error_at((*pv)->location(),
11832 "incompatible type for element %d key in map construction",
11834 this->set_is_error();
11837 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
11839 error_at((*pv)->location(),
11840 ("incompatible type for element %d value "
11841 "in map construction"),
11843 this->set_is_error();
11848 // Return a tree for constructing a map.
11851 Map_construction_expression::do_get_tree(Translate_context* context)
11853 Gogo* gogo = context->gogo();
11854 Location loc = this->location();
11856 Map_type* mt = this->type_->map_type();
11858 // Build a struct to hold the key and value.
11859 tree struct_type = make_node(RECORD_TYPE);
11861 Type* key_type = mt->key_type();
11862 tree id = get_identifier("__key");
11863 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
11864 if (key_type_tree == error_mark_node)
11865 return error_mark_node;
11866 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
11868 DECL_CONTEXT(key_field) = struct_type;
11869 TYPE_FIELDS(struct_type) = key_field;
11871 Type* val_type = mt->val_type();
11872 id = get_identifier("__val");
11873 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
11874 if (val_type_tree == error_mark_node)
11875 return error_mark_node;
11876 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
11878 DECL_CONTEXT(val_field) = struct_type;
11879 DECL_CHAIN(key_field) = val_field;
11881 layout_type(struct_type);
11883 bool is_constant = true;
11888 if (this->vals_ == NULL || this->vals_->empty())
11890 valaddr = null_pointer_node;
11891 make_tmp = NULL_TREE;
11895 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11896 this->vals_->size() / 2);
11898 for (Expression_list::const_iterator pv = this->vals_->begin();
11899 pv != this->vals_->end();
11902 bool one_is_constant = true;
11904 VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
11906 constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
11907 elt->index = key_field;
11908 tree val_tree = (*pv)->get_tree(context);
11909 elt->value = Expression::convert_for_assignment(context, key_type,
11912 if (elt->value == error_mark_node)
11913 return error_mark_node;
11914 if (!TREE_CONSTANT(elt->value))
11915 one_is_constant = false;
11919 elt = VEC_quick_push(constructor_elt, one, NULL);
11920 elt->index = val_field;
11921 val_tree = (*pv)->get_tree(context);
11922 elt->value = Expression::convert_for_assignment(context, val_type,
11925 if (elt->value == error_mark_node)
11926 return error_mark_node;
11927 if (!TREE_CONSTANT(elt->value))
11928 one_is_constant = false;
11930 elt = VEC_quick_push(constructor_elt, values, NULL);
11931 elt->index = size_int(i);
11932 elt->value = build_constructor(struct_type, one);
11933 if (one_is_constant)
11934 TREE_CONSTANT(elt->value) = 1;
11936 is_constant = false;
11939 tree index_type = build_index_type(size_int(i - 1));
11940 tree array_type = build_array_type(struct_type, index_type);
11941 tree init = build_constructor(array_type, values);
11943 TREE_CONSTANT(init) = 1;
11945 if (current_function_decl != NULL)
11947 tmp = create_tmp_var(array_type, get_name(array_type));
11948 DECL_INITIAL(tmp) = init;
11949 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
11950 void_type_node, tmp);
11951 TREE_ADDRESSABLE(tmp) = 1;
11955 tmp = build_decl(loc.gcc_location(), VAR_DECL,
11956 create_tmp_var_name("M"), array_type);
11957 DECL_EXTERNAL(tmp) = 0;
11958 TREE_PUBLIC(tmp) = 0;
11959 TREE_STATIC(tmp) = 1;
11960 DECL_ARTIFICIAL(tmp) = 1;
11961 if (!TREE_CONSTANT(init))
11962 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
11963 void_type_node, tmp, init);
11966 TREE_READONLY(tmp) = 1;
11967 TREE_CONSTANT(tmp) = 1;
11968 DECL_INITIAL(tmp) = init;
11969 make_tmp = NULL_TREE;
11971 rest_of_decl_compilation(tmp, 1, 0);
11974 valaddr = build_fold_addr_expr(tmp);
11977 tree descriptor = mt->map_descriptor_pointer(gogo, loc);
11979 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11980 if (type_tree == error_mark_node)
11981 return error_mark_node;
11983 static tree construct_map_fndecl;
11984 tree call = Gogo::call_builtin(&construct_map_fndecl,
11986 "__go_construct_map",
11989 TREE_TYPE(descriptor),
11994 TYPE_SIZE_UNIT(struct_type),
11996 byte_position(val_field),
11998 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
11999 const_ptr_type_node,
12000 fold_convert(const_ptr_type_node, valaddr));
12001 if (call == error_mark_node)
12002 return error_mark_node;
12005 if (make_tmp == NULL)
12008 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
12013 // Export an array construction.
12016 Map_construction_expression::do_export(Export* exp) const
12018 exp->write_c_string("convert(");
12019 exp->write_type(this->type_);
12020 for (Expression_list::const_iterator pv = this->vals_->begin();
12021 pv != this->vals_->end();
12024 exp->write_c_string(", ");
12025 (*pv)->export_expression(exp);
12027 exp->write_c_string(")");
12030 // Dump ast representation for a map construction expression.
12033 Map_construction_expression::do_dump_expression(
12034 Ast_dump_context* ast_dump_context) const
12036 ast_dump_context->ostream() << "{" ;
12037 ast_dump_context->dump_expression_list(this->vals_, true);
12038 ast_dump_context->ostream() << "}";
12041 // A general composite literal. This is lowered to a type specific
12044 class Composite_literal_expression : public Parser_expression
12047 Composite_literal_expression(Type* type, int depth, bool has_keys,
12048 Expression_list* vals, Location location)
12049 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12050 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
12055 do_traverse(Traverse* traverse);
12058 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12063 return new Composite_literal_expression(this->type_, this->depth_,
12065 (this->vals_ == NULL
12067 : this->vals_->copy()),
12072 do_dump_expression(Ast_dump_context*) const;
12076 lower_struct(Gogo*, Type*);
12079 lower_array(Type*);
12082 make_array(Type*, Expression_list*);
12085 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12087 // The type of the composite literal.
12089 // The depth within a list of composite literals within a composite
12090 // literal, when the type is omitted.
12092 // The values to put in the composite literal.
12093 Expression_list* vals_;
12094 // If this is true, then VALS_ is a list of pairs: a key and a
12095 // value. In an array initializer, a missing key will be NULL.
12102 Composite_literal_expression::do_traverse(Traverse* traverse)
12104 if (this->vals_ != NULL
12105 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12106 return TRAVERSE_EXIT;
12107 return Type::traverse(this->type_, traverse);
12110 // Lower a generic composite literal into a specific version based on
12114 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12115 Statement_inserter* inserter, int)
12117 Type* type = this->type_;
12119 for (int depth = this->depth_; depth > 0; --depth)
12121 if (type->array_type() != NULL)
12122 type = type->array_type()->element_type();
12123 else if (type->map_type() != NULL)
12124 type = type->map_type()->val_type();
12127 if (!type->is_error())
12128 error_at(this->location(),
12129 ("may only omit types within composite literals "
12130 "of slice, array, or map type"));
12131 return Expression::make_error(this->location());
12135 Type *pt = type->points_to();
12136 bool is_pointer = false;
12144 if (type->is_error())
12145 return Expression::make_error(this->location());
12146 else if (type->struct_type() != NULL)
12147 ret = this->lower_struct(gogo, type);
12148 else if (type->array_type() != NULL)
12149 ret = this->lower_array(type);
12150 else if (type->map_type() != NULL)
12151 ret = this->lower_map(gogo, function, inserter, type);
12154 error_at(this->location(),
12155 ("expected struct, slice, array, or map type "
12156 "for composite literal"));
12157 return Expression::make_error(this->location());
12161 ret = Expression::make_heap_composite(ret, this->location());
12166 // Lower a struct composite literal.
12169 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12171 Location location = this->location();
12172 Struct_type* st = type->struct_type();
12173 if (this->vals_ == NULL || !this->has_keys_)
12175 if (this->vals_ != NULL
12176 && !this->vals_->empty()
12177 && type->named_type() != NULL
12178 && type->named_type()->named_object()->package() != NULL)
12180 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12181 pf != st->fields()->end();
12184 if (Gogo::is_hidden_name(pf->field_name()))
12185 error_at(this->location(),
12186 "assignment of unexported field %qs in %qs literal",
12187 Gogo::message_name(pf->field_name()).c_str(),
12188 type->named_type()->message_name().c_str());
12192 return new Struct_construction_expression(type, this->vals_, location);
12195 size_t field_count = st->field_count();
12196 std::vector<Expression*> vals(field_count);
12197 Expression_list::const_iterator p = this->vals_->begin();
12198 while (p != this->vals_->end())
12200 Expression* name_expr = *p;
12203 go_assert(p != this->vals_->end());
12204 Expression* val = *p;
12208 if (name_expr == NULL)
12210 error_at(val->location(), "mixture of field and value initializers");
12211 return Expression::make_error(location);
12214 bool bad_key = false;
12216 const Named_object* no = NULL;
12217 switch (name_expr->classification())
12219 case EXPRESSION_UNKNOWN_REFERENCE:
12220 name = name_expr->unknown_expression()->name();
12223 case EXPRESSION_CONST_REFERENCE:
12224 no = static_cast<Const_expression*>(name_expr)->named_object();
12227 case EXPRESSION_TYPE:
12229 Type* t = name_expr->type();
12230 Named_type* nt = t->named_type();
12234 no = nt->named_object();
12238 case EXPRESSION_VAR_REFERENCE:
12239 no = name_expr->var_expression()->named_object();
12242 case EXPRESSION_FUNC_REFERENCE:
12243 no = name_expr->func_expression()->named_object();
12246 case EXPRESSION_UNARY:
12247 // If there is a local variable around with the same name as
12248 // the field, and this occurs in the closure, then the
12249 // parser may turn the field reference into an indirection
12250 // through the closure. FIXME: This is a mess.
12253 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12254 if (ue->op() == OPERATOR_MULT)
12256 Field_reference_expression* fre =
12257 ue->operand()->field_reference_expression();
12261 fre->expr()->type()->deref()->struct_type();
12264 const Struct_field* sf = st->field(fre->field_index());
12265 name = sf->field_name();
12267 // See below. FIXME.
12268 if (!Gogo::is_hidden_name(name)
12272 if (gogo->lookup_global(name.c_str()) != NULL)
12273 name = gogo->pack_hidden_name(name, false);
12277 snprintf(buf, sizeof buf, "%u", fre->field_index());
12278 size_t buflen = strlen(buf);
12279 if (name.compare(name.length() - buflen, buflen, buf)
12282 name = name.substr(0, name.length() - buflen);
12297 error_at(name_expr->location(), "expected struct field name");
12298 return Expression::make_error(location);
12305 // A predefined name won't be packed. If it starts with a
12306 // lower case letter we need to check for that case, because
12307 // the field name will be packed. FIXME.
12308 if (!Gogo::is_hidden_name(name)
12312 Named_object* gno = gogo->lookup_global(name.c_str());
12314 name = gogo->pack_hidden_name(name, false);
12318 unsigned int index;
12319 const Struct_field* sf = st->find_local_field(name, &index);
12322 error_at(name_expr->location(), "unknown field %qs in %qs",
12323 Gogo::message_name(name).c_str(),
12324 (type->named_type() != NULL
12325 ? type->named_type()->message_name().c_str()
12326 : "unnamed struct"));
12327 return Expression::make_error(location);
12329 if (vals[index] != NULL)
12331 error_at(name_expr->location(),
12332 "duplicate value for field %qs in %qs",
12333 Gogo::message_name(name).c_str(),
12334 (type->named_type() != NULL
12335 ? type->named_type()->message_name().c_str()
12336 : "unnamed struct"));
12337 return Expression::make_error(location);
12340 if (type->named_type() != NULL
12341 && type->named_type()->named_object()->package() != NULL
12342 && Gogo::is_hidden_name(sf->field_name()))
12343 error_at(name_expr->location(),
12344 "assignment of unexported field %qs in %qs literal",
12345 Gogo::message_name(sf->field_name()).c_str(),
12346 type->named_type()->message_name().c_str());
12351 Expression_list* list = new Expression_list;
12352 list->reserve(field_count);
12353 for (size_t i = 0; i < field_count; ++i)
12354 list->push_back(vals[i]);
12356 return new Struct_construction_expression(type, list, location);
12359 // Lower an array composite literal.
12362 Composite_literal_expression::lower_array(Type* type)
12364 Location location = this->location();
12365 if (this->vals_ == NULL || !this->has_keys_)
12366 return this->make_array(type, this->vals_);
12368 std::vector<Expression*> vals;
12369 vals.reserve(this->vals_->size());
12370 unsigned long index = 0;
12371 Expression_list::const_iterator p = this->vals_->begin();
12372 while (p != this->vals_->end())
12374 Expression* index_expr = *p;
12377 go_assert(p != this->vals_->end());
12378 Expression* val = *p;
12382 if (index_expr != NULL)
12384 Numeric_constant nc;
12385 if (!index_expr->numeric_constant_value(&nc))
12387 error_at(index_expr->location(),
12388 "index expression is not integer constant");
12389 return Expression::make_error(location);
12392 switch (nc.to_unsigned_long(&index))
12394 case Numeric_constant::NC_UL_VALID:
12396 case Numeric_constant::NC_UL_NOTINT:
12397 error_at(index_expr->location(),
12398 "index expression is not integer constant");
12399 return Expression::make_error(location);
12400 case Numeric_constant::NC_UL_NEGATIVE:
12401 error_at(index_expr->location(), "index expression is negative");
12402 return Expression::make_error(location);
12403 case Numeric_constant::NC_UL_BIG:
12404 error_at(index_expr->location(), "index value overflow");
12405 return Expression::make_error(location);
12410 Named_type* ntype = Type::lookup_integer_type("int");
12411 Integer_type* inttype = ntype->integer_type();
12412 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12413 && index >> (inttype->bits() - 1) != 0)
12415 error_at(index_expr->location(), "index value overflow");
12416 return Expression::make_error(location);
12419 // FIXME: Our representation isn't very good; this avoids
12421 if (index > 0x1000000)
12423 error_at(index_expr->location(), "index too large for compiler");
12424 return Expression::make_error(location);
12428 if (index == vals.size())
12429 vals.push_back(val);
12432 if (index > vals.size())
12434 vals.reserve(index + 32);
12435 vals.resize(index + 1, static_cast<Expression*>(NULL));
12437 if (vals[index] != NULL)
12439 error_at((index_expr != NULL
12440 ? index_expr->location()
12441 : val->location()),
12442 "duplicate value for index %lu",
12444 return Expression::make_error(location);
12452 size_t size = vals.size();
12453 Expression_list* list = new Expression_list;
12454 list->reserve(size);
12455 for (size_t i = 0; i < size; ++i)
12456 list->push_back(vals[i]);
12458 return this->make_array(type, list);
12461 // Actually build the array composite literal. This handles
12465 Composite_literal_expression::make_array(Type* type, Expression_list* vals)
12467 Location location = this->location();
12468 Array_type* at = type->array_type();
12469 if (at->length() != NULL && at->length()->is_nil_expression())
12471 size_t size = vals == NULL ? 0 : vals->size();
12473 mpz_init_set_ui(vlen, size);
12474 Expression* elen = Expression::make_integer(&vlen, NULL, location);
12476 at = Type::make_array_type(at->element_type(), elen);
12479 if (at->length() != NULL)
12480 return new Fixed_array_construction_expression(type, vals, location);
12482 return new Open_array_construction_expression(type, vals, location);
12485 // Lower a map composite literal.
12488 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12489 Statement_inserter* inserter,
12492 Location location = this->location();
12493 if (this->vals_ != NULL)
12495 if (!this->has_keys_)
12497 error_at(location, "map composite literal must have keys");
12498 return Expression::make_error(location);
12501 for (Expression_list::iterator p = this->vals_->begin();
12502 p != this->vals_->end();
12508 error_at((*p)->location(),
12509 "map composite literal must have keys for every value");
12510 return Expression::make_error(location);
12512 // Make sure we have lowered the key; it may not have been
12513 // lowered in order to handle keys for struct composite
12514 // literals. Lower it now to get the right error message.
12515 if ((*p)->unknown_expression() != NULL)
12517 (*p)->unknown_expression()->clear_is_composite_literal_key();
12518 gogo->lower_expression(function, inserter, &*p);
12519 go_assert((*p)->is_error_expression());
12520 return Expression::make_error(location);
12525 return new Map_construction_expression(type, this->vals_, location);
12528 // Dump ast representation for a composite literal expression.
12531 Composite_literal_expression::do_dump_expression(
12532 Ast_dump_context* ast_dump_context) const
12534 ast_dump_context->ostream() << "composite(";
12535 ast_dump_context->dump_type(this->type_);
12536 ast_dump_context->ostream() << ", {";
12537 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12538 ast_dump_context->ostream() << "})";
12541 // Make a composite literal expression.
12544 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
12545 Expression_list* vals,
12548 return new Composite_literal_expression(type, depth, has_keys, vals,
12552 // Return whether this expression is a composite literal.
12555 Expression::is_composite_literal() const
12557 switch (this->classification_)
12559 case EXPRESSION_COMPOSITE_LITERAL:
12560 case EXPRESSION_STRUCT_CONSTRUCTION:
12561 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12562 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12563 case EXPRESSION_MAP_CONSTRUCTION:
12570 // Return whether this expression is a composite literal which is not
12574 Expression::is_nonconstant_composite_literal() const
12576 switch (this->classification_)
12578 case EXPRESSION_STRUCT_CONSTRUCTION:
12580 const Struct_construction_expression *psce =
12581 static_cast<const Struct_construction_expression*>(this);
12582 return !psce->is_constant_struct();
12584 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12586 const Fixed_array_construction_expression *pace =
12587 static_cast<const Fixed_array_construction_expression*>(this);
12588 return !pace->is_constant_array();
12590 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12592 const Open_array_construction_expression *pace =
12593 static_cast<const Open_array_construction_expression*>(this);
12594 return !pace->is_constant_array();
12596 case EXPRESSION_MAP_CONSTRUCTION:
12603 // Return true if this is a reference to a local variable.
12606 Expression::is_local_variable() const
12608 const Var_expression* ve = this->var_expression();
12611 const Named_object* no = ve->named_object();
12612 return (no->is_result_variable()
12613 || (no->is_variable() && !no->var_value()->is_global()));
12616 // Class Type_guard_expression.
12621 Type_guard_expression::do_traverse(Traverse* traverse)
12623 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
12624 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12625 return TRAVERSE_EXIT;
12626 return TRAVERSE_CONTINUE;
12629 // Check types of a type guard expression. The expression must have
12630 // an interface type, but the actual type conversion is checked at run
12634 Type_guard_expression::do_check_types(Gogo*)
12636 // 6g permits using a type guard with unsafe.pointer; we are
12638 Type* expr_type = this->expr_->type();
12639 if (expr_type->is_unsafe_pointer_type())
12641 if (this->type_->points_to() == NULL
12642 && (this->type_->integer_type() == NULL
12643 || (this->type_->forwarded()
12644 != Type::lookup_integer_type("uintptr"))))
12645 this->report_error(_("invalid unsafe.Pointer conversion"));
12647 else if (this->type_->is_unsafe_pointer_type())
12649 if (expr_type->points_to() == NULL
12650 && (expr_type->integer_type() == NULL
12651 || (expr_type->forwarded()
12652 != Type::lookup_integer_type("uintptr"))))
12653 this->report_error(_("invalid unsafe.Pointer conversion"));
12655 else if (expr_type->interface_type() == NULL)
12657 if (!expr_type->is_error() && !this->type_->is_error())
12658 this->report_error(_("type assertion only valid for interface types"));
12659 this->set_is_error();
12661 else if (this->type_->interface_type() == NULL)
12663 std::string reason;
12664 if (!expr_type->interface_type()->implements_interface(this->type_,
12667 if (!this->type_->is_error())
12669 if (reason.empty())
12670 this->report_error(_("impossible type assertion: "
12671 "type does not implement interface"));
12673 error_at(this->location(),
12674 ("impossible type assertion: "
12675 "type does not implement interface (%s)"),
12678 this->set_is_error();
12683 // Return a tree for a type guard expression.
12686 Type_guard_expression::do_get_tree(Translate_context* context)
12688 Gogo* gogo = context->gogo();
12689 tree expr_tree = this->expr_->get_tree(context);
12690 if (expr_tree == error_mark_node)
12691 return error_mark_node;
12692 Type* expr_type = this->expr_->type();
12693 if ((this->type_->is_unsafe_pointer_type()
12694 && (expr_type->points_to() != NULL
12695 || expr_type->integer_type() != NULL))
12696 || (expr_type->is_unsafe_pointer_type()
12697 && this->type_->points_to() != NULL))
12698 return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
12700 else if (expr_type->is_unsafe_pointer_type()
12701 && this->type_->integer_type() != NULL)
12702 return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
12704 else if (this->type_->interface_type() != NULL)
12705 return Expression::convert_interface_to_interface(context, this->type_,
12706 this->expr_->type(),
12710 return Expression::convert_for_assignment(context, this->type_,
12711 this->expr_->type(), expr_tree,
12715 // Dump ast representation for a type guard expression.
12718 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12721 this->expr_->dump_expression(ast_dump_context);
12722 ast_dump_context->ostream() << ".";
12723 ast_dump_context->dump_type(this->type_);
12726 // Make a type guard expression.
12729 Expression::make_type_guard(Expression* expr, Type* type,
12732 return new Type_guard_expression(expr, type, location);
12735 // Class Heap_composite_expression.
12737 // When you take the address of a composite literal, it is allocated
12738 // on the heap. This class implements that.
12740 class Heap_composite_expression : public Expression
12743 Heap_composite_expression(Expression* expr, Location location)
12744 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
12750 do_traverse(Traverse* traverse)
12751 { return Expression::traverse(&this->expr_, traverse); }
12755 { return Type::make_pointer_type(this->expr_->type()); }
12758 do_determine_type(const Type_context*)
12759 { this->expr_->determine_type_no_context(); }
12764 return Expression::make_heap_composite(this->expr_->copy(),
12769 do_get_tree(Translate_context*);
12771 // We only export global objects, and the parser does not generate
12772 // this in global scope.
12774 do_export(Export*) const
12775 { go_unreachable(); }
12778 do_dump_expression(Ast_dump_context*) const;
12781 // The composite literal which is being put on the heap.
12785 // Return a tree which allocates a composite literal on the heap.
12788 Heap_composite_expression::do_get_tree(Translate_context* context)
12790 tree expr_tree = this->expr_->get_tree(context);
12791 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
12792 return error_mark_node;
12793 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
12794 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
12795 tree space = context->gogo()->allocate_memory(this->expr_->type(),
12796 expr_size, this->location());
12797 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
12798 space = save_expr(space);
12799 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12801 TREE_THIS_NOTRAP(ref) = 1;
12802 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
12803 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
12805 SET_EXPR_LOCATION(ret, this->location().gcc_location());
12809 // Dump ast representation for a heap composite expression.
12812 Heap_composite_expression::do_dump_expression(
12813 Ast_dump_context* ast_dump_context) const
12815 ast_dump_context->ostream() << "&(";
12816 ast_dump_context->dump_expression(this->expr_);
12817 ast_dump_context->ostream() << ")";
12820 // Allocate a composite literal on the heap.
12823 Expression::make_heap_composite(Expression* expr, Location location)
12825 return new Heap_composite_expression(expr, location);
12828 // Class Receive_expression.
12830 // Return the type of a receive expression.
12833 Receive_expression::do_type()
12835 Channel_type* channel_type = this->channel_->type()->channel_type();
12836 if (channel_type == NULL)
12837 return Type::make_error_type();
12838 return channel_type->element_type();
12841 // Check types for a receive expression.
12844 Receive_expression::do_check_types(Gogo*)
12846 Type* type = this->channel_->type();
12847 if (type->is_error())
12849 this->set_is_error();
12852 if (type->channel_type() == NULL)
12854 this->report_error(_("expected channel"));
12857 if (!type->channel_type()->may_receive())
12859 this->report_error(_("invalid receive on send-only channel"));
12864 // Get a tree for a receive expression.
12867 Receive_expression::do_get_tree(Translate_context* context)
12869 Location loc = this->location();
12871 Channel_type* channel_type = this->channel_->type()->channel_type();
12872 if (channel_type == NULL)
12874 go_assert(this->channel_->type()->is_error());
12875 return error_mark_node;
12878 Expression* td = Expression::make_type_descriptor(channel_type, loc);
12879 tree td_tree = td->get_tree(context);
12881 Type* element_type = channel_type->element_type();
12882 Btype* element_type_btype = element_type->get_backend(context->gogo());
12883 tree element_type_tree = type_to_tree(element_type_btype);
12885 tree channel = this->channel_->get_tree(context);
12886 if (element_type_tree == error_mark_node || channel == error_mark_node)
12887 return error_mark_node;
12889 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
12892 // Dump ast representation for a receive expression.
12895 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
12897 ast_dump_context->ostream() << " <- " ;
12898 ast_dump_context->dump_expression(channel_);
12901 // Make a receive expression.
12903 Receive_expression*
12904 Expression::make_receive(Expression* channel, Location location)
12906 return new Receive_expression(channel, location);
12909 // An expression which evaluates to a pointer to the type descriptor
12912 class Type_descriptor_expression : public Expression
12915 Type_descriptor_expression(Type* type, Location location)
12916 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
12923 { return Type::make_type_descriptor_ptr_type(); }
12926 do_determine_type(const Type_context*)
12934 do_get_tree(Translate_context* context)
12936 return this->type_->type_descriptor_pointer(context->gogo(),
12941 do_dump_expression(Ast_dump_context*) const;
12944 // The type for which this is the descriptor.
12948 // Dump ast representation for a type descriptor expression.
12951 Type_descriptor_expression::do_dump_expression(
12952 Ast_dump_context* ast_dump_context) const
12954 ast_dump_context->dump_type(this->type_);
12957 // Make a type descriptor expression.
12960 Expression::make_type_descriptor(Type* type, Location location)
12962 return new Type_descriptor_expression(type, location);
12965 // An expression which evaluates to some characteristic of a type.
12966 // This is only used to initialize fields of a type descriptor. Using
12967 // a new expression class is slightly inefficient but gives us a good
12968 // separation between the frontend and the middle-end with regard to
12969 // how types are laid out.
12971 class Type_info_expression : public Expression
12974 Type_info_expression(Type* type, Type_info type_info)
12975 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
12976 type_(type), type_info_(type_info)
12984 do_determine_type(const Type_context*)
12992 do_get_tree(Translate_context* context);
12995 do_dump_expression(Ast_dump_context*) const;
12998 // The type for which we are getting information.
13000 // What information we want.
13001 Type_info type_info_;
13004 // The type is chosen to match what the type descriptor struct
13008 Type_info_expression::do_type()
13010 switch (this->type_info_)
13012 case TYPE_INFO_SIZE:
13013 return Type::lookup_integer_type("uintptr");
13014 case TYPE_INFO_ALIGNMENT:
13015 case TYPE_INFO_FIELD_ALIGNMENT:
13016 return Type::lookup_integer_type("uint8");
13022 // Return type information in GENERIC.
13025 Type_info_expression::do_get_tree(Translate_context* context)
13027 Btype* btype = this->type_->get_backend(context->gogo());
13028 Gogo* gogo = context->gogo();
13030 switch (this->type_info_)
13032 case TYPE_INFO_SIZE:
13033 val = gogo->backend()->type_size(btype);
13035 case TYPE_INFO_ALIGNMENT:
13036 val = gogo->backend()->type_alignment(btype);
13038 case TYPE_INFO_FIELD_ALIGNMENT:
13039 val = gogo->backend()->type_field_alignment(btype);
13044 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
13045 go_assert(val_type_tree != error_mark_node);
13046 return build_int_cstu(val_type_tree, val);
13049 // Dump ast representation for a type info expression.
13052 Type_info_expression::do_dump_expression(
13053 Ast_dump_context* ast_dump_context) const
13055 ast_dump_context->ostream() << "typeinfo(";
13056 ast_dump_context->dump_type(this->type_);
13057 ast_dump_context->ostream() << ",";
13058 ast_dump_context->ostream() <<
13059 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13060 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13061 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13063 ast_dump_context->ostream() << ")";
13066 // Make a type info expression.
13069 Expression::make_type_info(Type* type, Type_info type_info)
13071 return new Type_info_expression(type, type_info);
13074 // An expression which evaluates to the offset of a field within a
13075 // struct. This, like Type_info_expression, q.v., is only used to
13076 // initialize fields of a type descriptor.
13078 class Struct_field_offset_expression : public Expression
13081 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
13082 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
13083 Linemap::predeclared_location()),
13084 type_(type), field_(field)
13090 { return Type::lookup_integer_type("uintptr"); }
13093 do_determine_type(const Type_context*)
13101 do_get_tree(Translate_context* context);
13104 do_dump_expression(Ast_dump_context*) const;
13107 // The type of the struct.
13108 Struct_type* type_;
13110 const Struct_field* field_;
13113 // Return a struct field offset in GENERIC.
13116 Struct_field_offset_expression::do_get_tree(Translate_context* context)
13118 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
13119 if (type_tree == error_mark_node)
13120 return error_mark_node;
13122 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13123 go_assert(val_type_tree != error_mark_node);
13125 const Struct_field_list* fields = this->type_->fields();
13126 tree struct_field_tree = TYPE_FIELDS(type_tree);
13127 Struct_field_list::const_iterator p;
13128 for (p = fields->begin();
13129 p != fields->end();
13130 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
13132 go_assert(struct_field_tree != NULL_TREE);
13133 if (&*p == this->field_)
13136 go_assert(&*p == this->field_);
13138 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
13139 byte_position(struct_field_tree));
13142 // Dump ast representation for a struct field offset expression.
13145 Struct_field_offset_expression::do_dump_expression(
13146 Ast_dump_context* ast_dump_context) const
13148 ast_dump_context->ostream() << "unsafe.Offsetof(";
13149 ast_dump_context->dump_type(this->type_);
13150 ast_dump_context->ostream() << '.';
13151 ast_dump_context->ostream() <<
13152 Gogo::message_name(this->field_->field_name());
13153 ast_dump_context->ostream() << ")";
13156 // Make an expression for a struct field offset.
13159 Expression::make_struct_field_offset(Struct_type* type,
13160 const Struct_field* field)
13162 return new Struct_field_offset_expression(type, field);
13165 // An expression which evaluates to a pointer to the map descriptor of
13168 class Map_descriptor_expression : public Expression
13171 Map_descriptor_expression(Map_type* type, Location location)
13172 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
13179 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
13182 do_determine_type(const Type_context*)
13190 do_get_tree(Translate_context* context)
13192 return this->type_->map_descriptor_pointer(context->gogo(),
13197 do_dump_expression(Ast_dump_context*) const;
13200 // The type for which this is the descriptor.
13204 // Dump ast representation for a map descriptor expression.
13207 Map_descriptor_expression::do_dump_expression(
13208 Ast_dump_context* ast_dump_context) const
13210 ast_dump_context->ostream() << "map_descriptor(";
13211 ast_dump_context->dump_type(this->type_);
13212 ast_dump_context->ostream() << ")";
13215 // Make a map descriptor expression.
13218 Expression::make_map_descriptor(Map_type* type, Location location)
13220 return new Map_descriptor_expression(type, location);
13223 // An expression which evaluates to the address of an unnamed label.
13225 class Label_addr_expression : public Expression
13228 Label_addr_expression(Label* label, Location location)
13229 : Expression(EXPRESSION_LABEL_ADDR, location),
13236 { return Type::make_pointer_type(Type::make_void_type()); }
13239 do_determine_type(const Type_context*)
13244 { return new Label_addr_expression(this->label_, this->location()); }
13247 do_get_tree(Translate_context* context)
13249 return expr_to_tree(this->label_->get_addr(context, this->location()));
13253 do_dump_expression(Ast_dump_context* ast_dump_context) const
13254 { ast_dump_context->ostream() << this->label_->name(); }
13257 // The label whose address we are taking.
13261 // Make an expression for the address of an unnamed label.
13264 Expression::make_label_addr(Label* label, Location location)
13266 return new Label_addr_expression(label, location);
13269 // Import an expression. This comes at the end in order to see the
13270 // various class definitions.
13273 Expression::import_expression(Import* imp)
13275 int c = imp->peek_char();
13276 if (imp->match_c_string("- ")
13277 || imp->match_c_string("! ")
13278 || imp->match_c_string("^ "))
13279 return Unary_expression::do_import(imp);
13281 return Binary_expression::do_import(imp);
13282 else if (imp->match_c_string("true")
13283 || imp->match_c_string("false"))
13284 return Boolean_expression::do_import(imp);
13286 return String_expression::do_import(imp);
13287 else if (c == '-' || (c >= '0' && c <= '9'))
13289 // This handles integers, floats and complex constants.
13290 return Integer_expression::do_import(imp);
13292 else if (imp->match_c_string("nil"))
13293 return Nil_expression::do_import(imp);
13294 else if (imp->match_c_string("convert"))
13295 return Type_conversion_expression::do_import(imp);
13298 error_at(imp->location(), "import error: expected expression");
13299 return Expression::make_error(imp->location());
13303 // Class Expression_list.
13305 // Traverse the list.
13308 Expression_list::traverse(Traverse* traverse)
13310 for (Expression_list::iterator p = this->begin();
13316 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13317 return TRAVERSE_EXIT;
13320 return TRAVERSE_CONTINUE;
13326 Expression_list::copy()
13328 Expression_list* ret = new Expression_list();
13329 for (Expression_list::iterator p = this->begin();
13334 ret->push_back(NULL);
13336 ret->push_back((*p)->copy());
13341 // Return whether an expression list has an error expression.
13344 Expression_list::contains_error() const
13346 for (Expression_list::const_iterator p = this->begin();
13349 if (*p != NULL && (*p)->is_error_expression())
13354 // Class Numeric_constant.
13358 Numeric_constant::~Numeric_constant()
13363 // Copy constructor.
13365 Numeric_constant::Numeric_constant(const Numeric_constant& a)
13366 : classification_(a.classification_), type_(a.type_)
13368 switch (a.classification_)
13374 mpz_init_set(this->u_.int_val, a.u_.int_val);
13377 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13380 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13382 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13390 // Assignment operator.
13393 Numeric_constant::operator=(const Numeric_constant& a)
13396 this->classification_ = a.classification_;
13397 this->type_ = a.type_;
13398 switch (a.classification_)
13404 mpz_init_set(this->u_.int_val, a.u_.int_val);
13407 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13410 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13412 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13421 // Clear the contents.
13424 Numeric_constant::clear()
13426 switch (this->classification_)
13432 mpz_clear(this->u_.int_val);
13435 mpfr_clear(this->u_.float_val);
13438 mpfr_clear(this->u_.complex_val.real);
13439 mpfr_clear(this->u_.complex_val.imag);
13444 this->classification_ = NC_INVALID;
13447 // Set to an unsigned long value.
13450 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
13453 this->classification_ = NC_INT;
13454 this->type_ = type;
13455 mpz_init_set_ui(this->u_.int_val, val);
13458 // Set to an integer value.
13461 Numeric_constant::set_int(Type* type, const mpz_t val)
13464 this->classification_ = NC_INT;
13465 this->type_ = type;
13466 mpz_init_set(this->u_.int_val, val);
13469 // Set to a rune value.
13472 Numeric_constant::set_rune(Type* type, const mpz_t val)
13475 this->classification_ = NC_RUNE;
13476 this->type_ = type;
13477 mpz_init_set(this->u_.int_val, val);
13480 // Set to a floating point value.
13483 Numeric_constant::set_float(Type* type, const mpfr_t val)
13486 this->classification_ = NC_FLOAT;
13487 this->type_ = type;
13488 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
13491 // Set to a complex value.
13494 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
13497 this->classification_ = NC_COMPLEX;
13498 this->type_ = type;
13499 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
13500 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
13503 // Get an int value.
13506 Numeric_constant::get_int(mpz_t* val) const
13508 go_assert(this->is_int());
13509 mpz_init_set(*val, this->u_.int_val);
13512 // Get a rune value.
13515 Numeric_constant::get_rune(mpz_t* val) const
13517 go_assert(this->is_rune());
13518 mpz_init_set(*val, this->u_.int_val);
13521 // Get a floating point value.
13524 Numeric_constant::get_float(mpfr_t* val) const
13526 go_assert(this->is_float());
13527 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13530 // Get a complex value.
13533 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
13535 go_assert(this->is_complex());
13536 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
13537 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
13540 // Express value as unsigned long if possible.
13542 Numeric_constant::To_unsigned_long
13543 Numeric_constant::to_unsigned_long(unsigned long* val) const
13545 switch (this->classification_)
13549 return this->mpz_to_unsigned_long(this->u_.int_val, val);
13551 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
13553 if (!mpfr_zero_p(this->u_.complex_val.imag))
13554 return NC_UL_NOTINT;
13555 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
13561 // Express integer value as unsigned long if possible.
13563 Numeric_constant::To_unsigned_long
13564 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
13565 unsigned long *val) const
13567 if (mpz_sgn(ival) < 0)
13568 return NC_UL_NEGATIVE;
13569 unsigned long ui = mpz_get_ui(ival);
13570 if (mpz_cmp_ui(ival, ui) != 0)
13573 return NC_UL_VALID;
13576 // Express floating point value as unsigned long if possible.
13578 Numeric_constant::To_unsigned_long
13579 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
13580 unsigned long *val) const
13582 if (!mpfr_integer_p(fval))
13583 return NC_UL_NOTINT;
13586 mpfr_get_z(ival, fval, GMP_RNDN);
13587 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
13592 // Convert value to integer if possible.
13595 Numeric_constant::to_int(mpz_t* val) const
13597 switch (this->classification_)
13601 mpz_init_set(*val, this->u_.int_val);
13604 if (!mpfr_integer_p(this->u_.float_val))
13607 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
13610 if (!mpfr_zero_p(this->u_.complex_val.imag)
13611 || !mpfr_integer_p(this->u_.complex_val.real))
13614 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
13621 // Convert value to floating point if possible.
13624 Numeric_constant::to_float(mpfr_t* val) const
13626 switch (this->classification_)
13630 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
13633 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13636 if (!mpfr_zero_p(this->u_.complex_val.imag))
13638 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
13645 // Convert value to complex.
13648 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
13650 switch (this->classification_)
13654 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
13655 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13658 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
13659 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13662 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
13663 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
13673 Numeric_constant::type() const
13675 if (this->type_ != NULL)
13676 return this->type_;
13677 switch (this->classification_)
13680 return Type::make_abstract_integer_type();
13682 return Type::make_abstract_character_type();
13684 return Type::make_abstract_float_type();
13686 return Type::make_abstract_complex_type();
13692 // If the constant can be expressed in TYPE, then set the type of the
13693 // constant to TYPE and return true. Otherwise return false, and, if
13694 // ISSUE_ERROR is true, report an appropriate error message.
13697 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
13702 else if (type->integer_type() != NULL)
13703 ret = this->check_int_type(type->integer_type(), issue_error, loc);
13704 else if (type->float_type() != NULL)
13705 ret = this->check_float_type(type->float_type(), issue_error, loc);
13706 else if (type->complex_type() != NULL)
13707 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
13711 this->type_ = type;
13715 // Check whether the constant can be expressed in an integer type.
13718 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
13719 Location location) const
13722 switch (this->classification_)
13726 mpz_init_set(val, this->u_.int_val);
13730 if (!mpfr_integer_p(this->u_.float_val))
13733 error_at(location, "floating point constant truncated to integer");
13737 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
13741 if (!mpfr_integer_p(this->u_.complex_val.real)
13742 || !mpfr_zero_p(this->u_.complex_val.imag))
13745 error_at(location, "complex constant truncated to integer");
13749 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
13757 if (type->is_abstract())
13761 int bits = mpz_sizeinbase(val, 2);
13762 if (type->is_unsigned())
13764 // For an unsigned type we can only accept a nonnegative
13765 // number, and we must be able to represents at least BITS.
13766 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
13770 // For a signed type we need an extra bit to indicate the
13771 // sign. We have to handle the most negative integer
13773 ret = (bits + 1 <= type->bits()
13774 || (bits <= type->bits()
13775 && mpz_sgn(val) < 0
13776 && (mpz_scan1(val, 0)
13777 == static_cast<unsigned long>(type->bits() - 1))
13778 && mpz_scan0(val, type->bits()) == ULONG_MAX));
13782 if (!ret && issue_error)
13783 error_at(location, "integer constant overflow");
13788 // Check whether the constant can be expressed in a floating point
13792 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
13793 Location location) const
13796 switch (this->classification_)
13800 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
13804 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
13808 if (!mpfr_zero_p(this->u_.complex_val.imag))
13811 error_at(location, "complex constant truncated to float");
13814 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
13822 if (type->is_abstract())
13824 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
13826 // A NaN or Infinity always fits in the range of the type.
13831 mp_exp_t exp = mpfr_get_exp(val);
13833 switch (type->bits())
13845 ret = exp <= max_exp;
13850 if (!ret && issue_error)
13851 error_at(location, "floating point constant overflow");
13856 // Check whether the constant can be expressed in a complex type.
13859 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
13860 Location location) const
13862 if (type->is_abstract())
13866 switch (type->bits())
13879 switch (this->classification_)
13883 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
13887 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
13891 if (!mpfr_nan_p(this->u_.complex_val.imag)
13892 && !mpfr_inf_p(this->u_.complex_val.imag)
13893 && !mpfr_zero_p(this->u_.complex_val.imag))
13895 if (mpfr_get_exp(this->u_.complex_val.imag) > max_exp)
13898 error_at(location, "complex imaginary part overflow");
13902 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
13910 if (mpfr_nan_p(real) || mpfr_inf_p(real) || mpfr_zero_p(real))
13913 ret = mpfr_get_exp(real) <= max_exp;
13917 if (!ret && issue_error)
13918 error_at(location, "complex real part overflow");
13923 // Return an Expression for this value.
13926 Numeric_constant::expression(Location loc) const
13928 switch (this->classification_)
13931 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
13933 return Expression::make_character(&this->u_.int_val, this->type_, loc);
13935 return Expression::make_float(&this->u_.float_val, this->type_, loc);
13937 return Expression::make_complex(&this->u_.complex_val.real,
13938 &this->u_.complex_val.imag,