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.
13 #ifndef ENABLE_BUILD_WITH_CXX
22 #include "tree-iterator.h"
27 #ifndef ENABLE_BUILD_WITH_CXX
36 #include "statements.h"
40 #include "expressions.h"
45 Expression::Expression(Expression_classification classification,
47 : classification_(classification), location_(location)
51 Expression::~Expression()
55 // Traverse the expressions.
58 Expression::traverse(Expression** pexpr, Traverse* traverse)
60 Expression* expr = *pexpr;
61 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
63 int t = traverse->expression(pexpr);
64 if (t == TRAVERSE_EXIT)
66 else if (t == TRAVERSE_SKIP_COMPONENTS)
67 return TRAVERSE_CONTINUE;
69 return expr->do_traverse(traverse);
72 // Traverse subexpressions of this expression.
75 Expression::traverse_subexpressions(Traverse* traverse)
77 return this->do_traverse(traverse);
80 // Default implementation for do_traverse for child classes.
83 Expression::do_traverse(Traverse*)
85 return TRAVERSE_CONTINUE;
88 // This virtual function is called by the parser if the value of this
89 // expression is being discarded. By default, we give an error.
90 // Expressions with side effects override.
93 Expression::do_discarding_value()
95 this->unused_value_error();
98 // This virtual function is called to export expressions. This will
99 // only be used by expressions which may be constant.
102 Expression::do_export(Export*) const
107 // Give an error saying that the value of the expression is not used.
110 Expression::unused_value_error()
112 error_at(this->location(), "value computed is not used");
115 // Note that this expression is an error. This is called by children
116 // when they discover an error.
119 Expression::set_is_error()
121 this->classification_ = EXPRESSION_ERROR;
124 // For children to call to report an error conveniently.
127 Expression::report_error(const char* msg)
129 error_at(this->location_, "%s", msg);
130 this->set_is_error();
133 // Set types of variables and constants. This is implemented by the
137 Expression::determine_type(const Type_context* context)
139 this->do_determine_type(context);
142 // Set types when there is no context.
145 Expression::determine_type_no_context()
147 Type_context context;
148 this->do_determine_type(&context);
151 // Return a tree handling any conversions which must be done during
155 Expression::convert_for_assignment(Translate_context* context, Type* lhs_type,
156 Type* rhs_type, tree rhs_tree,
159 if (lhs_type->is_error() || rhs_type->is_error())
160 return error_mark_node;
162 if (rhs_tree == error_mark_node || TREE_TYPE(rhs_tree) == error_mark_node)
163 return error_mark_node;
165 Gogo* gogo = context->gogo();
167 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
168 if (lhs_type_tree == error_mark_node)
169 return error_mark_node;
171 if (lhs_type != rhs_type && lhs_type->interface_type() != NULL)
173 if (rhs_type->interface_type() == NULL)
174 return Expression::convert_type_to_interface(context, lhs_type,
178 return Expression::convert_interface_to_interface(context, lhs_type,
182 else if (lhs_type != rhs_type && rhs_type->interface_type() != NULL)
183 return Expression::convert_interface_to_type(context, lhs_type, rhs_type,
185 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
187 // Assigning nil to an open array.
188 go_assert(TREE_CODE(lhs_type_tree) == RECORD_TYPE);
190 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
192 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
193 tree field = TYPE_FIELDS(lhs_type_tree);
194 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
197 elt->value = fold_convert(TREE_TYPE(field), null_pointer_node);
199 elt = VEC_quick_push(constructor_elt, init, NULL);
200 field = DECL_CHAIN(field);
201 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
204 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
206 elt = VEC_quick_push(constructor_elt, init, NULL);
207 field = DECL_CHAIN(field);
208 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
211 elt->value = fold_convert(TREE_TYPE(field), integer_zero_node);
213 tree val = build_constructor(lhs_type_tree, init);
214 TREE_CONSTANT(val) = 1;
218 else if (rhs_type->is_nil_type())
220 // The left hand side should be a pointer type at the tree
222 go_assert(POINTER_TYPE_P(lhs_type_tree));
223 return fold_convert(lhs_type_tree, null_pointer_node);
225 else if (lhs_type_tree == TREE_TYPE(rhs_tree))
227 // No conversion is needed.
230 else if (POINTER_TYPE_P(lhs_type_tree)
231 || INTEGRAL_TYPE_P(lhs_type_tree)
232 || SCALAR_FLOAT_TYPE_P(lhs_type_tree)
233 || COMPLEX_FLOAT_TYPE_P(lhs_type_tree))
234 return fold_convert_loc(location.gcc_location(), lhs_type_tree, rhs_tree);
235 else if ((TREE_CODE(lhs_type_tree) == RECORD_TYPE
236 && TREE_CODE(TREE_TYPE(rhs_tree)) == RECORD_TYPE)
237 || (TREE_CODE(lhs_type_tree) == ARRAY_TYPE
238 && TREE_CODE(TREE_TYPE(rhs_tree)) == ARRAY_TYPE))
240 // Avoid confusion from zero sized variables which may be
241 // represented as non-zero-sized.
242 if (int_size_in_bytes(lhs_type_tree) == 0
243 || int_size_in_bytes(TREE_TYPE(rhs_tree)) == 0)
246 // This conversion must be permitted by Go, or we wouldn't have
248 go_assert(int_size_in_bytes(lhs_type_tree)
249 == int_size_in_bytes(TREE_TYPE(rhs_tree)));
250 return fold_build1_loc(location.gcc_location(), VIEW_CONVERT_EXPR,
251 lhs_type_tree, rhs_tree);
255 go_assert(useless_type_conversion_p(lhs_type_tree, TREE_TYPE(rhs_tree)));
260 // Return a tree for a conversion from a non-interface type to an
264 Expression::convert_type_to_interface(Translate_context* context,
265 Type* lhs_type, Type* rhs_type,
266 tree rhs_tree, Location location)
268 Gogo* gogo = context->gogo();
269 Interface_type* lhs_interface_type = lhs_type->interface_type();
270 bool lhs_is_empty = lhs_interface_type->is_empty();
272 // Since RHS_TYPE is a static type, we can create the interface
273 // method table at compile time.
275 // When setting an interface to nil, we just set both fields to
277 if (rhs_type->is_nil_type())
279 Btype* lhs_btype = lhs_type->get_backend(gogo);
280 return expr_to_tree(gogo->backend()->zero_expression(lhs_btype));
283 // This should have been checked already.
284 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
286 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
287 if (lhs_type_tree == error_mark_node)
288 return error_mark_node;
290 // An interface is a tuple. If LHS_TYPE is an empty interface type,
291 // then the first field is the type descriptor for RHS_TYPE.
292 // Otherwise it is the interface method table for RHS_TYPE.
293 tree first_field_value;
295 first_field_value = rhs_type->type_descriptor_pointer(gogo, location);
298 // Build the interface method table for this interface and this
299 // object type: a list of function pointers for each interface
301 Named_type* rhs_named_type = rhs_type->named_type();
302 bool is_pointer = false;
303 if (rhs_named_type == NULL)
305 rhs_named_type = rhs_type->deref()->named_type();
309 if (rhs_named_type == NULL)
310 method_table = null_pointer_node;
313 rhs_named_type->interface_method_table(gogo, lhs_interface_type,
315 first_field_value = fold_convert_loc(location.gcc_location(),
316 const_ptr_type_node, method_table);
318 if (first_field_value == error_mark_node)
319 return error_mark_node;
321 // Start building a constructor for the value we will return.
323 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
325 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
326 tree field = TYPE_FIELDS(lhs_type_tree);
327 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
328 (lhs_is_empty ? "__type_descriptor" : "__methods")) == 0);
330 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
333 elt = VEC_quick_push(constructor_elt, init, NULL);
334 field = DECL_CHAIN(field);
335 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
338 if (rhs_type->points_to() != NULL)
340 // We are assigning a pointer to the interface; the interface
341 // holds the pointer itself.
342 elt->value = rhs_tree;
343 return build_constructor(lhs_type_tree, init);
346 // We are assigning a non-pointer value to the interface; the
347 // interface gets a copy of the value in the heap.
349 tree object_size = TYPE_SIZE_UNIT(TREE_TYPE(rhs_tree));
351 tree space = gogo->allocate_memory(rhs_type, object_size, location);
352 space = fold_convert_loc(location.gcc_location(),
353 build_pointer_type(TREE_TYPE(rhs_tree)), space);
354 space = save_expr(space);
356 tree ref = build_fold_indirect_ref_loc(location.gcc_location(), space);
357 TREE_THIS_NOTRAP(ref) = 1;
358 tree set = fold_build2_loc(location.gcc_location(), MODIFY_EXPR,
359 void_type_node, ref, rhs_tree);
361 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
364 return build2(COMPOUND_EXPR, lhs_type_tree, set,
365 build_constructor(lhs_type_tree, init));
368 // Return a tree for the type descriptor of RHS_TREE, which has
369 // interface type RHS_TYPE. If RHS_TREE is nil the result will be
373 Expression::get_interface_type_descriptor(Translate_context*,
374 Type* rhs_type, tree rhs_tree,
377 tree rhs_type_tree = TREE_TYPE(rhs_tree);
378 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
379 tree rhs_field = TYPE_FIELDS(rhs_type_tree);
380 tree v = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
382 if (rhs_type->interface_type()->is_empty())
384 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)),
385 "__type_descriptor") == 0);
389 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__methods")
391 go_assert(POINTER_TYPE_P(TREE_TYPE(v)));
393 tree v1 = build_fold_indirect_ref_loc(location.gcc_location(), v);
394 go_assert(TREE_CODE(TREE_TYPE(v1)) == RECORD_TYPE);
395 tree f = TYPE_FIELDS(TREE_TYPE(v1));
396 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(f)), "__type_descriptor")
398 v1 = build3(COMPONENT_REF, TREE_TYPE(f), v1, f, NULL_TREE);
400 tree eq = fold_build2_loc(location.gcc_location(), EQ_EXPR, boolean_type_node,
401 v, fold_convert_loc(location.gcc_location(),
404 tree n = fold_convert_loc(location.gcc_location(), TREE_TYPE(v1),
406 return fold_build3_loc(location.gcc_location(), COND_EXPR, TREE_TYPE(v1),
410 // Return a tree for the conversion of an interface type to an
414 Expression::convert_interface_to_interface(Translate_context* context,
415 Type *lhs_type, Type *rhs_type,
416 tree rhs_tree, bool for_type_guard,
419 Gogo* gogo = context->gogo();
420 Interface_type* lhs_interface_type = lhs_type->interface_type();
421 bool lhs_is_empty = lhs_interface_type->is_empty();
423 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
424 if (lhs_type_tree == error_mark_node)
425 return error_mark_node;
427 // In the general case this requires runtime examination of the type
428 // method table to match it up with the interface methods.
430 // FIXME: If all of the methods in the right hand side interface
431 // also appear in the left hand side interface, then we don't need
432 // to do a runtime check, although we still need to build a new
435 // Get the type descriptor for the right hand side. This will be
436 // NULL for a nil interface.
438 if (!DECL_P(rhs_tree))
439 rhs_tree = save_expr(rhs_tree);
441 tree rhs_type_descriptor =
442 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
445 // The result is going to be a two element constructor.
447 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 2);
449 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
450 tree field = TYPE_FIELDS(lhs_type_tree);
455 // A type assertion fails when converting a nil interface.
456 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
458 static tree assert_interface_decl;
459 tree call = Gogo::call_builtin(&assert_interface_decl,
461 "__go_assert_interface",
464 TREE_TYPE(lhs_type_descriptor),
466 TREE_TYPE(rhs_type_descriptor),
467 rhs_type_descriptor);
468 if (call == error_mark_node)
469 return error_mark_node;
470 // This will panic if the interface conversion fails.
471 TREE_NOTHROW(assert_interface_decl) = 0;
472 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
475 else if (lhs_is_empty)
477 // A convertion to an empty interface always succeeds, and the
478 // first field is just the type descriptor of the object.
479 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),
480 "__type_descriptor") == 0);
481 elt->value = fold_convert_loc(location.gcc_location(),
482 TREE_TYPE(field), rhs_type_descriptor);
486 // A conversion to a non-empty interface may fail, but unlike a
487 // type assertion converting nil will always succeed.
488 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods")
490 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo,
492 static tree convert_interface_decl;
493 tree call = Gogo::call_builtin(&convert_interface_decl,
495 "__go_convert_interface",
498 TREE_TYPE(lhs_type_descriptor),
500 TREE_TYPE(rhs_type_descriptor),
501 rhs_type_descriptor);
502 if (call == error_mark_node)
503 return error_mark_node;
504 // This will panic if the interface conversion fails.
505 TREE_NOTHROW(convert_interface_decl) = 0;
506 elt->value = fold_convert_loc(location.gcc_location(), TREE_TYPE(field),
510 // The second field is simply the object pointer.
512 elt = VEC_quick_push(constructor_elt, init, NULL);
513 field = DECL_CHAIN(field);
514 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
517 tree rhs_type_tree = TREE_TYPE(rhs_tree);
518 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
519 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
520 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
521 elt->value = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
524 return build_constructor(lhs_type_tree, init);
527 // Return a tree for the conversion of an interface type to a
528 // non-interface type.
531 Expression::convert_interface_to_type(Translate_context* context,
532 Type *lhs_type, Type* rhs_type,
533 tree rhs_tree, Location location)
535 Gogo* gogo = context->gogo();
536 tree rhs_type_tree = TREE_TYPE(rhs_tree);
538 tree lhs_type_tree = type_to_tree(lhs_type->get_backend(gogo));
539 if (lhs_type_tree == error_mark_node)
540 return error_mark_node;
542 // Call a function to check that the type is valid. The function
543 // will panic with an appropriate runtime type error if the type is
546 tree lhs_type_descriptor = lhs_type->type_descriptor_pointer(gogo, location);
548 if (!DECL_P(rhs_tree))
549 rhs_tree = save_expr(rhs_tree);
551 tree rhs_type_descriptor =
552 Expression::get_interface_type_descriptor(context, rhs_type, rhs_tree,
555 tree rhs_inter_descriptor = rhs_type->type_descriptor_pointer(gogo,
558 static tree check_interface_type_decl;
559 tree call = Gogo::call_builtin(&check_interface_type_decl,
561 "__go_check_interface_type",
564 TREE_TYPE(lhs_type_descriptor),
566 TREE_TYPE(rhs_type_descriptor),
568 TREE_TYPE(rhs_inter_descriptor),
569 rhs_inter_descriptor);
570 if (call == error_mark_node)
571 return error_mark_node;
572 // This call will panic if the conversion is invalid.
573 TREE_NOTHROW(check_interface_type_decl) = 0;
575 // If the call succeeds, pull out the value.
576 go_assert(TREE_CODE(rhs_type_tree) == RECORD_TYPE);
577 tree rhs_field = DECL_CHAIN(TYPE_FIELDS(rhs_type_tree));
578 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(rhs_field)), "__object") == 0);
579 tree val = build3(COMPONENT_REF, TREE_TYPE(rhs_field), rhs_tree, rhs_field,
582 // If the value is a pointer, then it is the value we want.
583 // Otherwise it points to the value.
584 if (lhs_type->points_to() == NULL)
586 val = fold_convert_loc(location.gcc_location(),
587 build_pointer_type(lhs_type_tree), val);
588 val = build_fold_indirect_ref_loc(location.gcc_location(), val);
591 return build2(COMPOUND_EXPR, lhs_type_tree, call,
592 fold_convert_loc(location.gcc_location(), lhs_type_tree, val));
595 // Convert an expression to a tree. This is implemented by the child
596 // class. Not that it is not in general safe to call this multiple
597 // times for a single expression, but that we don't catch such errors.
600 Expression::get_tree(Translate_context* context)
602 // The child may have marked this expression as having an error.
603 if (this->classification_ == EXPRESSION_ERROR)
604 return error_mark_node;
606 return this->do_get_tree(context);
609 // Return a tree for VAL in TYPE.
612 Expression::integer_constant_tree(mpz_t val, tree type)
614 if (type == error_mark_node)
615 return error_mark_node;
616 else if (TREE_CODE(type) == INTEGER_TYPE)
617 return double_int_to_tree(type,
618 mpz_get_double_int(type, val, true));
619 else if (TREE_CODE(type) == REAL_TYPE)
622 mpfr_init_set_z(fval, val, GMP_RNDN);
623 tree ret = Expression::float_constant_tree(fval, type);
627 else if (TREE_CODE(type) == COMPLEX_TYPE)
630 mpfr_init_set_z(fval, val, GMP_RNDN);
631 tree real = Expression::float_constant_tree(fval, TREE_TYPE(type));
633 tree imag = build_real_from_int_cst(TREE_TYPE(type),
635 return build_complex(type, real, imag);
641 // Return a tree for VAL in TYPE.
644 Expression::float_constant_tree(mpfr_t val, tree type)
646 if (type == error_mark_node)
647 return error_mark_node;
648 else if (TREE_CODE(type) == INTEGER_TYPE)
652 mpfr_get_z(ival, val, GMP_RNDN);
653 tree ret = Expression::integer_constant_tree(ival, type);
657 else if (TREE_CODE(type) == REAL_TYPE)
660 real_from_mpfr(&r1, val, type, GMP_RNDN);
662 real_convert(&r2, TYPE_MODE(type), &r1);
663 return build_real(type, r2);
665 else if (TREE_CODE(type) == COMPLEX_TYPE)
668 real_from_mpfr(&r1, val, TREE_TYPE(type), GMP_RNDN);
670 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
671 tree imag = build_real_from_int_cst(TREE_TYPE(type),
673 return build_complex(type, build_real(TREE_TYPE(type), r2), imag);
679 // Return a tree for REAL/IMAG in TYPE.
682 Expression::complex_constant_tree(mpfr_t real, mpfr_t imag, tree type)
684 if (type == error_mark_node)
685 return error_mark_node;
686 else if (TREE_CODE(type) == INTEGER_TYPE || TREE_CODE(type) == REAL_TYPE)
687 return Expression::float_constant_tree(real, type);
688 else if (TREE_CODE(type) == COMPLEX_TYPE)
691 real_from_mpfr(&r1, real, TREE_TYPE(type), GMP_RNDN);
693 real_convert(&r2, TYPE_MODE(TREE_TYPE(type)), &r1);
696 real_from_mpfr(&r3, imag, TREE_TYPE(type), GMP_RNDN);
698 real_convert(&r4, TYPE_MODE(TREE_TYPE(type)), &r3);
700 return build_complex(type, build_real(TREE_TYPE(type), r2),
701 build_real(TREE_TYPE(type), r4));
707 // Return a tree which evaluates to true if VAL, of arbitrary integer
708 // type, is negative or is more than the maximum value of BOUND_TYPE.
709 // If SOFAR is not NULL, it is or'red into the result. The return
710 // value may be NULL if SOFAR is NULL.
713 Expression::check_bounds(tree val, tree bound_type, tree sofar,
716 tree val_type = TREE_TYPE(val);
717 tree ret = NULL_TREE;
719 if (!TYPE_UNSIGNED(val_type))
721 ret = fold_build2_loc(loc.gcc_location(), LT_EXPR, boolean_type_node, val,
722 build_int_cst(val_type, 0));
723 if (ret == boolean_false_node)
727 HOST_WIDE_INT val_type_size = int_size_in_bytes(val_type);
728 HOST_WIDE_INT bound_type_size = int_size_in_bytes(bound_type);
729 go_assert(val_type_size != -1 && bound_type_size != -1);
730 if (val_type_size > bound_type_size
731 || (val_type_size == bound_type_size
732 && TYPE_UNSIGNED(val_type)
733 && !TYPE_UNSIGNED(bound_type)))
735 tree max = TYPE_MAX_VALUE(bound_type);
736 tree big = fold_build2_loc(loc.gcc_location(), GT_EXPR, boolean_type_node,
737 val, fold_convert_loc(loc.gcc_location(),
739 if (big == boolean_false_node)
741 else if (ret == NULL_TREE)
744 ret = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
745 boolean_type_node, ret, big);
748 if (ret == NULL_TREE)
750 else if (sofar == NULL_TREE)
753 return fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR, boolean_type_node,
758 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
760 this->do_dump_expression(ast_dump_context);
763 // Error expressions. This are used to avoid cascading errors.
765 class Error_expression : public Expression
768 Error_expression(Location location)
769 : Expression(EXPRESSION_ERROR, location)
774 do_is_constant() const
778 do_numeric_constant_value(Numeric_constant* nc) const
780 nc->set_unsigned_long(NULL, 0);
785 do_discarding_value()
790 { return Type::make_error_type(); }
793 do_determine_type(const Type_context*)
801 do_is_addressable() const
805 do_get_tree(Translate_context*)
806 { return error_mark_node; }
809 do_dump_expression(Ast_dump_context*) const;
812 // Dump the ast representation for an error expression to a dump context.
815 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
817 ast_dump_context->ostream() << "_Error_" ;
821 Expression::make_error(Location location)
823 return new Error_expression(location);
826 // An expression which is really a type. This is used during parsing.
827 // It is an error if these survive after lowering.
830 Type_expression : public Expression
833 Type_expression(Type* type, Location location)
834 : Expression(EXPRESSION_TYPE, location),
840 do_traverse(Traverse* traverse)
841 { return Type::traverse(this->type_, traverse); }
845 { return this->type_; }
848 do_determine_type(const Type_context*)
852 do_check_types(Gogo*)
853 { this->report_error(_("invalid use of type")); }
860 do_get_tree(Translate_context*)
861 { go_unreachable(); }
863 void do_dump_expression(Ast_dump_context*) const;
866 // The type which we are representing as an expression.
871 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
873 ast_dump_context->dump_type(this->type_);
877 Expression::make_type(Type* type, Location location)
879 return new Type_expression(type, location);
882 // Class Parser_expression.
885 Parser_expression::do_type()
887 // We should never really ask for the type of a Parser_expression.
888 // However, it can happen, at least when we have an invalid const
889 // whose initializer refers to the const itself. In that case we
890 // may ask for the type when lowering the const itself.
891 go_assert(saw_errors());
892 return Type::make_error_type();
895 // Class Var_expression.
897 // Lower a variable expression. Here we just make sure that the
898 // initialization expression of the variable has been lowered. This
899 // ensures that we will be able to determine the type of the variable
903 Var_expression::do_lower(Gogo* gogo, Named_object* function,
904 Statement_inserter* inserter, int)
906 if (this->variable_->is_variable())
908 Variable* var = this->variable_->var_value();
909 // This is either a local variable or a global variable. A
910 // reference to a variable which is local to an enclosing
911 // function will be a reference to a field in a closure.
912 if (var->is_global())
917 var->lower_init_expression(gogo, function, inserter);
922 // Return the type of a reference to a variable.
925 Var_expression::do_type()
927 if (this->variable_->is_variable())
928 return this->variable_->var_value()->type();
929 else if (this->variable_->is_result_variable())
930 return this->variable_->result_var_value()->type();
935 // Determine the type of a reference to a variable.
938 Var_expression::do_determine_type(const Type_context*)
940 if (this->variable_->is_variable())
941 this->variable_->var_value()->determine_type();
944 // Something takes the address of this variable. This means that we
945 // may want to move the variable onto the heap.
948 Var_expression::do_address_taken(bool escapes)
952 if (this->variable_->is_variable())
953 this->variable_->var_value()->set_non_escaping_address_taken();
954 else if (this->variable_->is_result_variable())
955 this->variable_->result_var_value()->set_non_escaping_address_taken();
961 if (this->variable_->is_variable())
962 this->variable_->var_value()->set_address_taken();
963 else if (this->variable_->is_result_variable())
964 this->variable_->result_var_value()->set_address_taken();
970 // Get the tree for a reference to a variable.
973 Var_expression::do_get_tree(Translate_context* context)
975 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
976 context->function());
977 tree ret = var_to_tree(bvar);
978 if (ret == error_mark_node)
979 return error_mark_node;
981 if (this->variable_->is_variable())
982 is_in_heap = this->variable_->var_value()->is_in_heap();
983 else if (this->variable_->is_result_variable())
984 is_in_heap = this->variable_->result_var_value()->is_in_heap();
989 ret = build_fold_indirect_ref_loc(this->location().gcc_location(), ret);
990 TREE_THIS_NOTRAP(ret) = 1;
995 // Ast dump for variable expression.
998 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1000 ast_dump_context->ostream() << this->variable_->name() ;
1003 // Make a reference to a variable in an expression.
1006 Expression::make_var_reference(Named_object* var, Location location)
1009 return Expression::make_sink(location);
1011 // FIXME: Creating a new object for each reference to a variable is
1013 return new Var_expression(var, location);
1016 // Class Temporary_reference_expression.
1021 Temporary_reference_expression::do_type()
1023 return this->statement_->type();
1026 // Called if something takes the address of this temporary variable.
1027 // We never have to move temporary variables to the heap, but we do
1028 // need to know that they must live in the stack rather than in a
1032 Temporary_reference_expression::do_address_taken(bool)
1034 this->statement_->set_is_address_taken();
1037 // Get a tree referring to the variable.
1040 Temporary_reference_expression::do_get_tree(Translate_context* context)
1042 Bvariable* bvar = this->statement_->get_backend_variable(context);
1044 // The gcc backend can't represent the same set of recursive types
1045 // that the Go frontend can. In some cases this means that a
1046 // temporary variable won't have the right backend type. Correct
1047 // that here by adding a type cast. We need to use base() to push
1048 // the circularity down one level.
1049 tree ret = var_to_tree(bvar);
1050 if (!this->is_lvalue_
1051 && POINTER_TYPE_P(TREE_TYPE(ret))
1052 && VOID_TYPE_P(TREE_TYPE(TREE_TYPE(ret))))
1054 Btype* type_btype = this->type()->base()->get_backend(context->gogo());
1055 tree type_tree = type_to_tree(type_btype);
1056 ret = fold_convert_loc(this->location().gcc_location(), type_tree, ret);
1061 // Ast dump for temporary reference.
1064 Temporary_reference_expression::do_dump_expression(
1065 Ast_dump_context* ast_dump_context) const
1067 ast_dump_context->dump_temp_variable_name(this->statement_);
1070 // Make a reference to a temporary variable.
1072 Temporary_reference_expression*
1073 Expression::make_temporary_reference(Temporary_statement* statement,
1076 return new Temporary_reference_expression(statement, location);
1079 // Class Set_and_use_temporary_expression.
1084 Set_and_use_temporary_expression::do_type()
1086 return this->statement_->type();
1089 // Take the address.
1092 Set_and_use_temporary_expression::do_address_taken(bool)
1094 this->statement_->set_is_address_taken();
1097 // Return the backend representation.
1100 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
1102 Bvariable* bvar = this->statement_->get_backend_variable(context);
1103 tree var_tree = var_to_tree(bvar);
1104 tree expr_tree = this->expr_->get_tree(context);
1105 if (var_tree == error_mark_node || expr_tree == error_mark_node)
1106 return error_mark_node;
1107 Location loc = this->location();
1108 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
1109 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
1110 var_tree, expr_tree),
1117 Set_and_use_temporary_expression::do_dump_expression(
1118 Ast_dump_context* ast_dump_context) const
1120 ast_dump_context->ostream() << '(';
1121 ast_dump_context->dump_temp_variable_name(this->statement_);
1122 ast_dump_context->ostream() << " = ";
1123 this->expr_->dump_expression(ast_dump_context);
1124 ast_dump_context->ostream() << ')';
1127 // Make a set-and-use temporary.
1129 Set_and_use_temporary_expression*
1130 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1131 Expression* expr, Location location)
1133 return new Set_and_use_temporary_expression(statement, expr, location);
1136 // A sink expression--a use of the blank identifier _.
1138 class Sink_expression : public Expression
1141 Sink_expression(Location location)
1142 : Expression(EXPRESSION_SINK, location),
1143 type_(NULL), var_(NULL_TREE)
1148 do_discarding_value()
1155 do_determine_type(const Type_context*);
1159 { return new Sink_expression(this->location()); }
1162 do_get_tree(Translate_context*);
1165 do_dump_expression(Ast_dump_context*) const;
1168 // The type of this sink variable.
1170 // The temporary variable we generate.
1174 // Return the type of a sink expression.
1177 Sink_expression::do_type()
1179 if (this->type_ == NULL)
1180 return Type::make_sink_type();
1184 // Determine the type of a sink expression.
1187 Sink_expression::do_determine_type(const Type_context* context)
1189 if (context->type != NULL)
1190 this->type_ = context->type;
1193 // Return a temporary variable for a sink expression. This will
1194 // presumably be a write-only variable which the middle-end will drop.
1197 Sink_expression::do_get_tree(Translate_context* context)
1199 if (this->var_ == NULL_TREE)
1201 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1202 Btype* bt = this->type_->get_backend(context->gogo());
1203 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
1208 // Ast dump for sink expression.
1211 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1213 ast_dump_context->ostream() << "_" ;
1216 // Make a sink expression.
1219 Expression::make_sink(Location location)
1221 return new Sink_expression(location);
1224 // Class Func_expression.
1226 // FIXME: Can a function expression appear in a constant expression?
1227 // The value is unchanging. Initializing a constant to the address of
1228 // a function seems like it could work, though there might be little
1234 Func_expression::do_traverse(Traverse* traverse)
1236 return (this->closure_ == NULL
1238 : Expression::traverse(&this->closure_, traverse));
1241 // Return the type of a function expression.
1244 Func_expression::do_type()
1246 if (this->function_->is_function())
1247 return this->function_->func_value()->type();
1248 else if (this->function_->is_function_declaration())
1249 return this->function_->func_declaration_value()->type();
1254 // Get the tree for a function expression without evaluating the
1258 Func_expression::get_tree_without_closure(Gogo* gogo)
1260 Function_type* fntype;
1261 if (this->function_->is_function())
1262 fntype = this->function_->func_value()->type();
1263 else if (this->function_->is_function_declaration())
1264 fntype = this->function_->func_declaration_value()->type();
1268 // Builtin functions are handled specially by Call_expression. We
1269 // can't take their address.
1270 if (fntype->is_builtin())
1272 error_at(this->location(),
1273 "invalid use of special builtin function %qs; must be called",
1274 this->function_->name().c_str());
1275 return error_mark_node;
1278 Named_object* no = this->function_;
1280 tree id = no->get_id(gogo);
1281 if (id == error_mark_node)
1282 return error_mark_node;
1285 if (no->is_function())
1286 fndecl = no->func_value()->get_or_make_decl(gogo, no, id);
1287 else if (no->is_function_declaration())
1288 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no, id);
1292 if (fndecl == error_mark_node)
1293 return error_mark_node;
1295 return build_fold_addr_expr_loc(this->location().gcc_location(), fndecl);
1298 // Get the tree for a function expression. This is used when we take
1299 // the address of a function rather than simply calling it. If the
1300 // function has a closure, we must use a trampoline.
1303 Func_expression::do_get_tree(Translate_context* context)
1305 Gogo* gogo = context->gogo();
1307 tree fnaddr = this->get_tree_without_closure(gogo);
1308 if (fnaddr == error_mark_node)
1309 return error_mark_node;
1311 go_assert(TREE_CODE(fnaddr) == ADDR_EXPR
1312 && TREE_CODE(TREE_OPERAND(fnaddr, 0)) == FUNCTION_DECL);
1313 TREE_ADDRESSABLE(TREE_OPERAND(fnaddr, 0)) = 1;
1315 // If there is no closure, that is all have to do.
1316 if (this->closure_ == NULL)
1319 go_assert(this->function_->func_value()->enclosing() != NULL);
1321 // Get the value of the closure. This will be a pointer to space
1322 // allocated on the heap.
1323 tree closure_tree = this->closure_->get_tree(context);
1324 if (closure_tree == error_mark_node)
1325 return error_mark_node;
1326 go_assert(POINTER_TYPE_P(TREE_TYPE(closure_tree)));
1328 // Now we need to build some code on the heap. This code will load
1329 // the static chain pointer with the closure and then jump to the
1330 // body of the function. The normal gcc approach is to build the
1331 // code on the stack. Unfortunately we can not do that, as Go
1332 // permits us to return the function pointer.
1334 return gogo->make_trampoline(fnaddr, closure_tree, this->location());
1337 // Ast dump for function.
1340 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1342 ast_dump_context->ostream() << this->function_->name();
1343 if (this->closure_ != NULL)
1345 ast_dump_context->ostream() << " {closure = ";
1346 this->closure_->dump_expression(ast_dump_context);
1347 ast_dump_context->ostream() << "}";
1351 // Make a reference to a function in an expression.
1354 Expression::make_func_reference(Named_object* function, Expression* closure,
1357 return new Func_expression(function, closure, location);
1360 // Class Unknown_expression.
1362 // Return the name of an unknown expression.
1365 Unknown_expression::name() const
1367 return this->named_object_->name();
1370 // Lower a reference to an unknown name.
1373 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1375 Location location = this->location();
1376 Named_object* no = this->named_object_;
1378 if (!no->is_unknown())
1382 real = no->unknown_value()->real_named_object();
1385 if (this->is_composite_literal_key_)
1387 if (!this->no_error_message_)
1388 error_at(location, "reference to undefined name %qs",
1389 this->named_object_->message_name().c_str());
1390 return Expression::make_error(location);
1393 switch (real->classification())
1395 case Named_object::NAMED_OBJECT_CONST:
1396 return Expression::make_const_reference(real, location);
1397 case Named_object::NAMED_OBJECT_TYPE:
1398 return Expression::make_type(real->type_value(), location);
1399 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1400 if (this->is_composite_literal_key_)
1402 if (!this->no_error_message_)
1403 error_at(location, "reference to undefined type %qs",
1404 real->message_name().c_str());
1405 return Expression::make_error(location);
1406 case Named_object::NAMED_OBJECT_VAR:
1407 real->var_value()->set_is_used();
1408 return Expression::make_var_reference(real, location);
1409 case Named_object::NAMED_OBJECT_FUNC:
1410 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1411 return Expression::make_func_reference(real, NULL, location);
1412 case Named_object::NAMED_OBJECT_PACKAGE:
1413 if (this->is_composite_literal_key_)
1415 if (!this->no_error_message_)
1416 error_at(location, "unexpected reference to package");
1417 return Expression::make_error(location);
1423 // Dump the ast representation for an unknown expression to a dump context.
1426 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1428 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1432 // Make a reference to an unknown name.
1435 Expression::make_unknown_reference(Named_object* no, Location location)
1437 return new Unknown_expression(no, location);
1440 // A boolean expression.
1442 class Boolean_expression : public Expression
1445 Boolean_expression(bool val, Location location)
1446 : Expression(EXPRESSION_BOOLEAN, location),
1447 val_(val), type_(NULL)
1455 do_is_constant() const
1462 do_determine_type(const Type_context*);
1469 do_get_tree(Translate_context*)
1470 { return this->val_ ? boolean_true_node : boolean_false_node; }
1473 do_export(Export* exp) const
1474 { exp->write_c_string(this->val_ ? "true" : "false"); }
1477 do_dump_expression(Ast_dump_context* ast_dump_context) const
1478 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1483 // The type as determined by context.
1490 Boolean_expression::do_type()
1492 if (this->type_ == NULL)
1493 this->type_ = Type::make_boolean_type();
1497 // Set the type from the context.
1500 Boolean_expression::do_determine_type(const Type_context* context)
1502 if (this->type_ != NULL && !this->type_->is_abstract())
1504 else if (context->type != NULL && context->type->is_boolean_type())
1505 this->type_ = context->type;
1506 else if (!context->may_be_abstract)
1507 this->type_ = Type::lookup_bool_type();
1510 // Import a boolean constant.
1513 Boolean_expression::do_import(Import* imp)
1515 if (imp->peek_char() == 't')
1517 imp->require_c_string("true");
1518 return Expression::make_boolean(true, imp->location());
1522 imp->require_c_string("false");
1523 return Expression::make_boolean(false, imp->location());
1527 // Make a boolean expression.
1530 Expression::make_boolean(bool val, Location location)
1532 return new Boolean_expression(val, location);
1535 // Class String_expression.
1540 String_expression::do_type()
1542 if (this->type_ == NULL)
1543 this->type_ = Type::make_string_type();
1547 // Set the type from the context.
1550 String_expression::do_determine_type(const Type_context* context)
1552 if (this->type_ != NULL && !this->type_->is_abstract())
1554 else if (context->type != NULL && context->type->is_string_type())
1555 this->type_ = context->type;
1556 else if (!context->may_be_abstract)
1557 this->type_ = Type::lookup_string_type();
1560 // Build a string constant.
1563 String_expression::do_get_tree(Translate_context* context)
1565 return context->gogo()->go_string_constant_tree(this->val_);
1568 // Write string literal to string dump.
1571 String_expression::export_string(String_dump* exp,
1572 const String_expression* str)
1575 s.reserve(str->val_.length() * 4 + 2);
1577 for (std::string::const_iterator p = str->val_.begin();
1578 p != str->val_.end();
1581 if (*p == '\\' || *p == '"')
1586 else if (*p >= 0x20 && *p < 0x7f)
1588 else if (*p == '\n')
1590 else if (*p == '\t')
1595 unsigned char c = *p;
1596 unsigned int dig = c >> 4;
1597 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1599 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1603 exp->write_string(s);
1606 // Export a string expression.
1609 String_expression::do_export(Export* exp) const
1611 String_expression::export_string(exp, this);
1614 // Import a string expression.
1617 String_expression::do_import(Import* imp)
1619 imp->require_c_string("\"");
1623 int c = imp->get_char();
1624 if (c == '"' || c == -1)
1627 val += static_cast<char>(c);
1630 c = imp->get_char();
1631 if (c == '\\' || c == '"')
1632 val += static_cast<char>(c);
1639 c = imp->get_char();
1640 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1641 c = imp->get_char();
1642 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1643 char v = (vh << 4) | vl;
1648 error_at(imp->location(), "bad string constant");
1649 return Expression::make_error(imp->location());
1653 return Expression::make_string(val, imp->location());
1656 // Ast dump for string expression.
1659 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1661 String_expression::export_string(ast_dump_context, this);
1664 // Make a string expression.
1667 Expression::make_string(const std::string& val, Location location)
1669 return new String_expression(val, location);
1672 // Make an integer expression.
1674 class Integer_expression : public Expression
1677 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1679 : Expression(EXPRESSION_INTEGER, location),
1680 type_(type), is_character_constant_(is_character_constant)
1681 { mpz_init_set(this->val_, *val); }
1686 // Write VAL to string dump.
1688 export_integer(String_dump* exp, const mpz_t val);
1690 // Write VAL to dump context.
1692 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1696 do_is_constant() const
1700 do_numeric_constant_value(Numeric_constant* nc) const;
1706 do_determine_type(const Type_context* context);
1709 do_check_types(Gogo*);
1712 do_get_tree(Translate_context*);
1717 if (this->is_character_constant_)
1718 return Expression::make_character(&this->val_, this->type_,
1721 return Expression::make_integer(&this->val_, this->type_,
1726 do_export(Export*) const;
1729 do_dump_expression(Ast_dump_context*) const;
1732 // The integer value.
1736 // Whether this is a character constant.
1737 bool is_character_constant_;
1740 // Return a numeric constant for this expression. We have to mark
1741 // this as a character when appropriate.
1744 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1746 if (this->is_character_constant_)
1747 nc->set_rune(this->type_, this->val_);
1749 nc->set_int(this->type_, this->val_);
1753 // Return the current type. If we haven't set the type yet, we return
1754 // an abstract integer type.
1757 Integer_expression::do_type()
1759 if (this->type_ == NULL)
1761 if (this->is_character_constant_)
1762 this->type_ = Type::make_abstract_character_type();
1764 this->type_ = Type::make_abstract_integer_type();
1769 // Set the type of the integer value. Here we may switch from an
1770 // abstract type to a real type.
1773 Integer_expression::do_determine_type(const Type_context* context)
1775 if (this->type_ != NULL && !this->type_->is_abstract())
1777 else if (context->type != NULL && context->type->is_numeric_type())
1778 this->type_ = context->type;
1779 else if (!context->may_be_abstract)
1781 if (this->is_character_constant_)
1782 this->type_ = Type::lookup_integer_type("int32");
1784 this->type_ = Type::lookup_integer_type("int");
1788 // Check the type of an integer constant.
1791 Integer_expression::do_check_types(Gogo*)
1793 Type* type = this->type_;
1796 Numeric_constant nc;
1797 if (this->is_character_constant_)
1798 nc.set_rune(NULL, this->val_);
1800 nc.set_int(NULL, this->val_);
1801 if (!nc.set_type(type, true, this->location()))
1802 this->set_is_error();
1805 // Get a tree for an integer constant.
1808 Integer_expression::do_get_tree(Translate_context* context)
1810 Gogo* gogo = context->gogo();
1812 if (this->type_ != NULL && !this->type_->is_abstract())
1813 type = type_to_tree(this->type_->get_backend(gogo));
1814 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1816 // We are converting to an abstract floating point type.
1817 Type* ftype = Type::lookup_float_type("float64");
1818 type = type_to_tree(ftype->get_backend(gogo));
1820 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1822 // We are converting to an abstract complex type.
1823 Type* ctype = Type::lookup_complex_type("complex128");
1824 type = type_to_tree(ctype->get_backend(gogo));
1828 // If we still have an abstract type here, then this is being
1829 // used in a constant expression which didn't get reduced for
1830 // some reason. Use a type which will fit the value. We use <,
1831 // not <=, because we need an extra bit for the sign bit.
1832 int bits = mpz_sizeinbase(this->val_, 2);
1833 if (bits < INT_TYPE_SIZE)
1835 Type* t = Type::lookup_integer_type("int");
1836 type = type_to_tree(t->get_backend(gogo));
1840 Type* t = Type::lookup_integer_type("int64");
1841 type = type_to_tree(t->get_backend(gogo));
1844 type = long_long_integer_type_node;
1846 return Expression::integer_constant_tree(this->val_, type);
1849 // Write VAL to export data.
1852 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1854 char* s = mpz_get_str(NULL, 10, val);
1855 exp->write_c_string(s);
1859 // Export an integer in a constant expression.
1862 Integer_expression::do_export(Export* exp) const
1864 Integer_expression::export_integer(exp, this->val_);
1865 if (this->is_character_constant_)
1866 exp->write_c_string("'");
1867 // A trailing space lets us reliably identify the end of the number.
1868 exp->write_c_string(" ");
1871 // Import an integer, floating point, or complex value. This handles
1872 // all these types because they all start with digits.
1875 Integer_expression::do_import(Import* imp)
1877 std::string num = imp->read_identifier();
1878 imp->require_c_string(" ");
1879 if (!num.empty() && num[num.length() - 1] == 'i')
1882 size_t plus_pos = num.find('+', 1);
1883 size_t minus_pos = num.find('-', 1);
1885 if (plus_pos == std::string::npos)
1887 else if (minus_pos == std::string::npos)
1891 error_at(imp->location(), "bad number in import data: %qs",
1893 return Expression::make_error(imp->location());
1895 if (pos == std::string::npos)
1896 mpfr_set_ui(real, 0, GMP_RNDN);
1899 std::string real_str = num.substr(0, pos);
1900 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1902 error_at(imp->location(), "bad number in import data: %qs",
1904 return Expression::make_error(imp->location());
1908 std::string imag_str;
1909 if (pos == std::string::npos)
1912 imag_str = num.substr(pos);
1913 imag_str = imag_str.substr(0, imag_str.size() - 1);
1915 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
1917 error_at(imp->location(), "bad number in import data: %qs",
1919 return Expression::make_error(imp->location());
1921 Expression* ret = Expression::make_complex(&real, &imag, NULL,
1927 else if (num.find('.') == std::string::npos
1928 && num.find('E') == std::string::npos)
1930 bool is_character_constant = (!num.empty()
1931 && num[num.length() - 1] == '\'');
1932 if (is_character_constant)
1933 num = num.substr(0, num.length() - 1);
1935 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
1937 error_at(imp->location(), "bad number in import data: %qs",
1939 return Expression::make_error(imp->location());
1942 if (is_character_constant)
1943 ret = Expression::make_character(&val, NULL, imp->location());
1945 ret = Expression::make_integer(&val, NULL, imp->location());
1952 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
1954 error_at(imp->location(), "bad number in import data: %qs",
1956 return Expression::make_error(imp->location());
1958 Expression* ret = Expression::make_float(&val, NULL, imp->location());
1963 // Ast dump for integer expression.
1966 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1968 if (this->is_character_constant_)
1969 ast_dump_context->ostream() << '\'';
1970 Integer_expression::export_integer(ast_dump_context, this->val_);
1971 if (this->is_character_constant_)
1972 ast_dump_context->ostream() << '\'';
1975 // Build a new integer value.
1978 Expression::make_integer(const mpz_t* val, Type* type, Location location)
1980 return new Integer_expression(val, type, false, location);
1983 // Build a new character constant value.
1986 Expression::make_character(const mpz_t* val, Type* type, Location location)
1988 return new Integer_expression(val, type, true, location);
1993 class Float_expression : public Expression
1996 Float_expression(const mpfr_t* val, Type* type, Location location)
1997 : Expression(EXPRESSION_FLOAT, location),
2000 mpfr_init_set(this->val_, *val, GMP_RNDN);
2003 // Write VAL to export data.
2005 export_float(String_dump* exp, const mpfr_t val);
2007 // Write VAL to dump file.
2009 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2013 do_is_constant() const
2017 do_numeric_constant_value(Numeric_constant* nc) const
2019 nc->set_float(this->type_, this->val_);
2027 do_determine_type(const Type_context*);
2030 do_check_types(Gogo*);
2034 { return Expression::make_float(&this->val_, this->type_,
2035 this->location()); }
2038 do_get_tree(Translate_context*);
2041 do_export(Export*) const;
2044 do_dump_expression(Ast_dump_context*) const;
2047 // The floating point value.
2053 // Return the current type. If we haven't set the type yet, we return
2054 // an abstract float type.
2057 Float_expression::do_type()
2059 if (this->type_ == NULL)
2060 this->type_ = Type::make_abstract_float_type();
2064 // Set the type of the float value. Here we may switch from an
2065 // abstract type to a real type.
2068 Float_expression::do_determine_type(const Type_context* context)
2070 if (this->type_ != NULL && !this->type_->is_abstract())
2072 else if (context->type != NULL
2073 && (context->type->integer_type() != NULL
2074 || context->type->float_type() != NULL
2075 || context->type->complex_type() != NULL))
2076 this->type_ = context->type;
2077 else if (!context->may_be_abstract)
2078 this->type_ = Type::lookup_float_type("float64");
2081 // Check the type of a float value.
2084 Float_expression::do_check_types(Gogo*)
2086 Type* type = this->type_;
2089 Numeric_constant nc;
2090 nc.set_float(NULL, this->val_);
2091 if (!nc.set_type(this->type_, true, this->location()))
2092 this->set_is_error();
2095 // Get a tree for a float constant.
2098 Float_expression::do_get_tree(Translate_context* context)
2100 Gogo* gogo = context->gogo();
2102 if (this->type_ != NULL && !this->type_->is_abstract())
2103 type = type_to_tree(this->type_->get_backend(gogo));
2104 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2106 // We have an abstract integer type. We just hope for the best.
2107 type = type_to_tree(Type::lookup_integer_type("int")->get_backend(gogo));
2111 // If we still have an abstract type here, then this is being
2112 // used in a constant expression which didn't get reduced. We
2113 // just use float64 and hope for the best.
2114 Type* ft = Type::lookup_float_type("float64");
2115 type = type_to_tree(ft->get_backend(gogo));
2117 return Expression::float_constant_tree(this->val_, type);
2120 // Write a floating point number to a string dump.
2123 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2126 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2128 exp->write_c_string("-");
2129 exp->write_c_string("0.");
2130 exp->write_c_string(*s == '-' ? s + 1 : s);
2133 snprintf(buf, sizeof buf, "E%ld", exponent);
2134 exp->write_c_string(buf);
2137 // Export a floating point number in a constant expression.
2140 Float_expression::do_export(Export* exp) const
2142 Float_expression::export_float(exp, this->val_);
2143 // A trailing space lets us reliably identify the end of the number.
2144 exp->write_c_string(" ");
2147 // Dump a floating point number to the dump file.
2150 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2152 Float_expression::export_float(ast_dump_context, this->val_);
2155 // Make a float expression.
2158 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2160 return new Float_expression(val, type, location);
2165 class Complex_expression : public Expression
2168 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2170 : Expression(EXPRESSION_COMPLEX, location),
2173 mpfr_init_set(this->real_, *real, GMP_RNDN);
2174 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2177 // Write REAL/IMAG to string dump.
2179 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2181 // Write REAL/IMAG to dump context.
2183 dump_complex(Ast_dump_context* ast_dump_context,
2184 const mpfr_t real, const mpfr_t val);
2188 do_is_constant() const
2192 do_numeric_constant_value(Numeric_constant* nc) const
2194 nc->set_complex(this->type_, this->real_, this->imag_);
2202 do_determine_type(const Type_context*);
2205 do_check_types(Gogo*);
2210 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2215 do_get_tree(Translate_context*);
2218 do_export(Export*) const;
2221 do_dump_expression(Ast_dump_context*) const;
2226 // The imaginary part;
2228 // The type if known.
2232 // Return the current type. If we haven't set the type yet, we return
2233 // an abstract complex type.
2236 Complex_expression::do_type()
2238 if (this->type_ == NULL)
2239 this->type_ = Type::make_abstract_complex_type();
2243 // Set the type of the complex value. Here we may switch from an
2244 // abstract type to a real type.
2247 Complex_expression::do_determine_type(const Type_context* context)
2249 if (this->type_ != NULL && !this->type_->is_abstract())
2251 else if (context->type != NULL
2252 && context->type->complex_type() != NULL)
2253 this->type_ = context->type;
2254 else if (!context->may_be_abstract)
2255 this->type_ = Type::lookup_complex_type("complex128");
2258 // Check the type of a complex value.
2261 Complex_expression::do_check_types(Gogo*)
2263 Type* type = this->type_;
2266 Numeric_constant nc;
2267 nc.set_complex(NULL, this->real_, this->imag_);
2268 if (!nc.set_type(this->type_, true, this->location()))
2269 this->set_is_error();
2272 // Get a tree for a complex constant.
2275 Complex_expression::do_get_tree(Translate_context* context)
2277 Gogo* gogo = context->gogo();
2279 if (this->type_ != NULL && !this->type_->is_abstract())
2280 type = type_to_tree(this->type_->get_backend(gogo));
2283 // If we still have an abstract type here, this this is being
2284 // used in a constant expression which didn't get reduced. We
2285 // just use complex128 and hope for the best.
2286 Type* ct = Type::lookup_complex_type("complex128");
2287 type = type_to_tree(ct->get_backend(gogo));
2289 return Expression::complex_constant_tree(this->real_, this->imag_, type);
2292 // Write REAL/IMAG to export data.
2295 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2298 if (!mpfr_zero_p(real))
2300 Float_expression::export_float(exp, real);
2301 if (mpfr_sgn(imag) > 0)
2302 exp->write_c_string("+");
2304 Float_expression::export_float(exp, imag);
2305 exp->write_c_string("i");
2308 // Export a complex number in a constant expression.
2311 Complex_expression::do_export(Export* exp) const
2313 Complex_expression::export_complex(exp, this->real_, this->imag_);
2314 // A trailing space lets us reliably identify the end of the number.
2315 exp->write_c_string(" ");
2318 // Dump a complex expression to the dump file.
2321 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2323 Complex_expression::export_complex(ast_dump_context,
2328 // Make a complex expression.
2331 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2334 return new Complex_expression(real, imag, type, location);
2337 // Find a named object in an expression.
2339 class Find_named_object : public Traverse
2342 Find_named_object(Named_object* no)
2343 : Traverse(traverse_expressions),
2344 no_(no), found_(false)
2347 // Whether we found the object.
2350 { return this->found_; }
2354 expression(Expression**);
2357 // The object we are looking for.
2359 // Whether we found it.
2363 // A reference to a const in an expression.
2365 class Const_expression : public Expression
2368 Const_expression(Named_object* constant, Location location)
2369 : Expression(EXPRESSION_CONST_REFERENCE, location),
2370 constant_(constant), type_(NULL), seen_(false)
2375 { return this->constant_; }
2377 // Check that the initializer does not refer to the constant itself.
2379 check_for_init_loop();
2383 do_traverse(Traverse*);
2386 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2389 do_is_constant() const
2393 do_numeric_constant_value(Numeric_constant* nc) const;
2396 do_string_constant_value(std::string* val) const;
2401 // The type of a const is set by the declaration, not the use.
2403 do_determine_type(const Type_context*);
2406 do_check_types(Gogo*);
2413 do_get_tree(Translate_context* context);
2415 // When exporting a reference to a const as part of a const
2416 // expression, we export the value. We ignore the fact that it has
2419 do_export(Export* exp) const
2420 { this->constant_->const_value()->expr()->export_expression(exp); }
2423 do_dump_expression(Ast_dump_context*) const;
2427 Named_object* constant_;
2428 // The type of this reference. This is used if the constant has an
2431 // Used to prevent infinite recursion when a constant incorrectly
2432 // refers to itself.
2439 Const_expression::do_traverse(Traverse* traverse)
2441 if (this->type_ != NULL)
2442 return Type::traverse(this->type_, traverse);
2443 return TRAVERSE_CONTINUE;
2446 // Lower a constant expression. This is where we convert the
2447 // predeclared constant iota into an integer value.
2450 Const_expression::do_lower(Gogo* gogo, Named_object*,
2451 Statement_inserter*, int iota_value)
2453 if (this->constant_->const_value()->expr()->classification()
2456 if (iota_value == -1)
2458 error_at(this->location(),
2459 "iota is only defined in const declarations");
2463 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2464 Expression* ret = Expression::make_integer(&val, NULL,
2470 // Make sure that the constant itself has been lowered.
2471 gogo->lower_constant(this->constant_);
2476 // Return a numeric constant value.
2479 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2484 Expression* e = this->constant_->const_value()->expr();
2488 bool r = e->numeric_constant_value(nc);
2490 this->seen_ = false;
2493 if (this->type_ != NULL)
2494 ctype = this->type_;
2496 ctype = this->constant_->const_value()->type();
2497 if (r && ctype != NULL)
2499 if (!nc->set_type(ctype, false, this->location()))
2507 Const_expression::do_string_constant_value(std::string* val) const
2512 Expression* e = this->constant_->const_value()->expr();
2515 bool ok = e->string_constant_value(val);
2516 this->seen_ = false;
2521 // Return the type of the const reference.
2524 Const_expression::do_type()
2526 if (this->type_ != NULL)
2529 Named_constant* nc = this->constant_->const_value();
2531 if (this->seen_ || nc->lowering())
2533 this->report_error(_("constant refers to itself"));
2534 this->type_ = Type::make_error_type();
2540 Type* ret = nc->type();
2544 this->seen_ = false;
2548 // During parsing, a named constant may have a NULL type, but we
2549 // must not return a NULL type here.
2550 ret = nc->expr()->type();
2552 this->seen_ = false;
2557 // Set the type of the const reference.
2560 Const_expression::do_determine_type(const Type_context* context)
2562 Type* ctype = this->constant_->const_value()->type();
2563 Type* cetype = (ctype != NULL
2565 : this->constant_->const_value()->expr()->type());
2566 if (ctype != NULL && !ctype->is_abstract())
2568 else if (context->type != NULL
2569 && context->type->is_numeric_type()
2570 && cetype->is_numeric_type())
2571 this->type_ = context->type;
2572 else if (context->type != NULL
2573 && context->type->is_string_type()
2574 && cetype->is_string_type())
2575 this->type_ = context->type;
2576 else if (context->type != NULL
2577 && context->type->is_boolean_type()
2578 && cetype->is_boolean_type())
2579 this->type_ = context->type;
2580 else if (!context->may_be_abstract)
2582 if (cetype->is_abstract())
2583 cetype = cetype->make_non_abstract_type();
2584 this->type_ = cetype;
2588 // Check for a loop in which the initializer of a constant refers to
2589 // the constant itself.
2592 Const_expression::check_for_init_loop()
2594 if (this->type_ != NULL && this->type_->is_error())
2599 this->report_error(_("constant refers to itself"));
2600 this->type_ = Type::make_error_type();
2604 Expression* init = this->constant_->const_value()->expr();
2605 Find_named_object find_named_object(this->constant_);
2608 Expression::traverse(&init, &find_named_object);
2609 this->seen_ = false;
2611 if (find_named_object.found())
2613 if (this->type_ == NULL || !this->type_->is_error())
2615 this->report_error(_("constant refers to itself"));
2616 this->type_ = Type::make_error_type();
2622 // Check types of a const reference.
2625 Const_expression::do_check_types(Gogo*)
2627 if (this->type_ != NULL && this->type_->is_error())
2630 this->check_for_init_loop();
2632 // Check that numeric constant fits in type.
2633 if (this->type_ != NULL && this->type_->is_numeric_type())
2635 Numeric_constant nc;
2636 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2638 if (!nc.set_type(this->type_, true, this->location()))
2639 this->set_is_error();
2644 // Return a tree for the const reference.
2647 Const_expression::do_get_tree(Translate_context* context)
2649 Gogo* gogo = context->gogo();
2651 if (this->type_ == NULL)
2652 type_tree = NULL_TREE;
2655 type_tree = type_to_tree(this->type_->get_backend(gogo));
2656 if (type_tree == error_mark_node)
2657 return error_mark_node;
2660 // If the type has been set for this expression, but the underlying
2661 // object is an abstract int or float, we try to get the abstract
2662 // value. Otherwise we may lose something in the conversion.
2663 if (this->type_ != NULL
2664 && this->type_->is_numeric_type()
2665 && (this->constant_->const_value()->type() == NULL
2666 || this->constant_->const_value()->type()->is_abstract()))
2668 Expression* expr = this->constant_->const_value()->expr();
2669 Numeric_constant nc;
2670 if (expr->numeric_constant_value(&nc)
2671 && nc.set_type(this->type_, false, this->location()))
2673 Expression* e = nc.expression(this->location());
2674 return e->get_tree(context);
2678 tree const_tree = this->constant_->get_tree(gogo, context->function());
2679 if (this->type_ == NULL
2680 || const_tree == error_mark_node
2681 || TREE_TYPE(const_tree) == error_mark_node)
2685 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(const_tree)))
2686 ret = fold_convert(type_tree, const_tree);
2687 else if (TREE_CODE(type_tree) == INTEGER_TYPE)
2688 ret = fold(convert_to_integer(type_tree, const_tree));
2689 else if (TREE_CODE(type_tree) == REAL_TYPE)
2690 ret = fold(convert_to_real(type_tree, const_tree));
2691 else if (TREE_CODE(type_tree) == COMPLEX_TYPE)
2692 ret = fold(convert_to_complex(type_tree, const_tree));
2698 // Dump ast representation for constant expression.
2701 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2703 ast_dump_context->ostream() << this->constant_->name();
2706 // Make a reference to a constant in an expression.
2709 Expression::make_const_reference(Named_object* constant,
2712 return new Const_expression(constant, location);
2715 // Find a named object in an expression.
2718 Find_named_object::expression(Expression** pexpr)
2720 switch ((*pexpr)->classification())
2722 case Expression::EXPRESSION_CONST_REFERENCE:
2724 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2725 if (ce->named_object() == this->no_)
2728 // We need to check a constant initializer explicitly, as
2729 // loops here will not be caught by the loop checking for
2730 // variable initializers.
2731 ce->check_for_init_loop();
2733 return TRAVERSE_CONTINUE;
2736 case Expression::EXPRESSION_VAR_REFERENCE:
2737 if ((*pexpr)->var_expression()->named_object() == this->no_)
2739 return TRAVERSE_CONTINUE;
2740 case Expression::EXPRESSION_FUNC_REFERENCE:
2741 if ((*pexpr)->func_expression()->named_object() == this->no_)
2743 return TRAVERSE_CONTINUE;
2745 return TRAVERSE_CONTINUE;
2747 this->found_ = true;
2748 return TRAVERSE_EXIT;
2753 class Nil_expression : public Expression
2756 Nil_expression(Location location)
2757 : Expression(EXPRESSION_NIL, location)
2765 do_is_constant() const
2770 { return Type::make_nil_type(); }
2773 do_determine_type(const Type_context*)
2781 do_get_tree(Translate_context*)
2782 { return null_pointer_node; }
2785 do_export(Export* exp) const
2786 { exp->write_c_string("nil"); }
2789 do_dump_expression(Ast_dump_context* ast_dump_context) const
2790 { ast_dump_context->ostream() << "nil"; }
2793 // Import a nil expression.
2796 Nil_expression::do_import(Import* imp)
2798 imp->require_c_string("nil");
2799 return Expression::make_nil(imp->location());
2802 // Make a nil expression.
2805 Expression::make_nil(Location location)
2807 return new Nil_expression(location);
2810 // The value of the predeclared constant iota. This is little more
2811 // than a marker. This will be lowered to an integer in
2812 // Const_expression::do_lower, which is where we know the value that
2815 class Iota_expression : public Parser_expression
2818 Iota_expression(Location location)
2819 : Parser_expression(EXPRESSION_IOTA, location)
2824 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2825 { go_unreachable(); }
2827 // There should only ever be one of these.
2830 { go_unreachable(); }
2833 do_dump_expression(Ast_dump_context* ast_dump_context) const
2834 { ast_dump_context->ostream() << "iota"; }
2837 // Make an iota expression. This is only called for one case: the
2838 // value of the predeclared constant iota.
2841 Expression::make_iota()
2843 static Iota_expression iota_expression(Linemap::unknown_location());
2844 return &iota_expression;
2847 // A type conversion expression.
2849 class Type_conversion_expression : public Expression
2852 Type_conversion_expression(Type* type, Expression* expr,
2854 : Expression(EXPRESSION_CONVERSION, location),
2855 type_(type), expr_(expr), may_convert_function_types_(false)
2858 // Return the type to which we are converting.
2861 { return this->type_; }
2863 // Return the expression which we are converting.
2866 { return this->expr_; }
2868 // Permit converting from one function type to another. This is
2869 // used internally for method expressions.
2871 set_may_convert_function_types()
2873 this->may_convert_function_types_ = true;
2876 // Import a type conversion expression.
2882 do_traverse(Traverse* traverse);
2885 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2888 do_is_constant() const
2889 { return this->expr_->is_constant(); }
2892 do_numeric_constant_value(Numeric_constant*) const;
2895 do_string_constant_value(std::string*) const;
2899 { return this->type_; }
2902 do_determine_type(const Type_context*)
2904 Type_context subcontext(this->type_, false);
2905 this->expr_->determine_type(&subcontext);
2909 do_check_types(Gogo*);
2914 return new Type_conversion_expression(this->type_, this->expr_->copy(),
2919 do_get_tree(Translate_context* context);
2922 do_export(Export*) const;
2925 do_dump_expression(Ast_dump_context*) const;
2928 // The type to convert to.
2930 // The expression to convert.
2932 // True if this is permitted to convert function types. This is
2933 // used internally for method expressions.
2934 bool may_convert_function_types_;
2940 Type_conversion_expression::do_traverse(Traverse* traverse)
2942 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
2943 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2944 return TRAVERSE_EXIT;
2945 return TRAVERSE_CONTINUE;
2948 // Convert to a constant at lowering time.
2951 Type_conversion_expression::do_lower(Gogo*, Named_object*,
2952 Statement_inserter*, int)
2954 Type* type = this->type_;
2955 Expression* val = this->expr_;
2956 Location location = this->location();
2958 if (type->is_numeric_type())
2960 Numeric_constant nc;
2961 if (val->numeric_constant_value(&nc))
2963 if (!nc.set_type(type, true, location))
2964 return Expression::make_error(location);
2965 return nc.expression(location);
2969 if (type->is_slice_type())
2971 Type* element_type = type->array_type()->element_type()->forwarded();
2972 bool is_byte = (element_type->integer_type() != NULL
2973 && element_type->integer_type()->is_byte());
2974 bool is_rune = (element_type->integer_type() != NULL
2975 && element_type->integer_type()->is_rune());
2976 if (is_byte || is_rune)
2979 if (val->string_constant_value(&s))
2981 Expression_list* vals = new Expression_list();
2984 for (std::string::const_iterator p = s.begin();
2989 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
2990 Expression* v = Expression::make_integer(&val,
2999 const char *p = s.data();
3000 const char *pend = s.data() + s.length();
3004 int adv = Lex::fetch_char(p, &c);
3007 warning_at(this->location(), 0,
3008 "invalid UTF-8 encoding");
3013 mpz_init_set_ui(val, c);
3014 Expression* v = Expression::make_integer(&val,
3022 return Expression::make_slice_composite_literal(type, vals,
3031 // Return the constant numeric value if there is one.
3034 Type_conversion_expression::do_numeric_constant_value(
3035 Numeric_constant* nc) const
3037 if (!this->type_->is_numeric_type())
3039 if (!this->expr_->numeric_constant_value(nc))
3041 return nc->set_type(this->type_, false, this->location());
3044 // Return the constant string value if there is one.
3047 Type_conversion_expression::do_string_constant_value(std::string* val) const
3049 if (this->type_->is_string_type()
3050 && this->expr_->type()->integer_type() != NULL)
3052 Numeric_constant nc;
3053 if (this->expr_->numeric_constant_value(&nc))
3056 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3059 Lex::append_char(ival, true, val, this->location());
3065 // FIXME: Could handle conversion from const []int here.
3070 // Check that types are convertible.
3073 Type_conversion_expression::do_check_types(Gogo*)
3075 Type* type = this->type_;
3076 Type* expr_type = this->expr_->type();
3079 if (type->is_error() || expr_type->is_error())
3081 this->set_is_error();
3085 if (this->may_convert_function_types_
3086 && type->function_type() != NULL
3087 && expr_type->function_type() != NULL)
3090 if (Type::are_convertible(type, expr_type, &reason))
3093 error_at(this->location(), "%s", reason.c_str());
3094 this->set_is_error();
3097 // Get a tree for a type conversion.
3100 Type_conversion_expression::do_get_tree(Translate_context* context)
3102 Gogo* gogo = context->gogo();
3103 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
3104 tree expr_tree = this->expr_->get_tree(context);
3106 if (type_tree == error_mark_node
3107 || expr_tree == error_mark_node
3108 || TREE_TYPE(expr_tree) == error_mark_node)
3109 return error_mark_node;
3111 if (TYPE_MAIN_VARIANT(type_tree) == TYPE_MAIN_VARIANT(TREE_TYPE(expr_tree)))
3112 return fold_convert(type_tree, expr_tree);
3114 Type* type = this->type_;
3115 Type* expr_type = this->expr_->type();
3117 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3118 ret = Expression::convert_for_assignment(context, type, expr_type,
3119 expr_tree, this->location());
3120 else if (type->integer_type() != NULL)
3122 if (expr_type->integer_type() != NULL
3123 || expr_type->float_type() != NULL
3124 || expr_type->is_unsafe_pointer_type())
3125 ret = fold(convert_to_integer(type_tree, expr_tree));
3129 else if (type->float_type() != NULL)
3131 if (expr_type->integer_type() != NULL
3132 || expr_type->float_type() != NULL)
3133 ret = fold(convert_to_real(type_tree, expr_tree));
3137 else if (type->complex_type() != NULL)
3139 if (expr_type->complex_type() != NULL)
3140 ret = fold(convert_to_complex(type_tree, expr_tree));
3144 else if (type->is_string_type()
3145 && expr_type->integer_type() != NULL)
3147 expr_tree = fold_convert(integer_type_node, expr_tree);
3148 if (host_integerp(expr_tree, 0))
3150 HOST_WIDE_INT intval = tree_low_cst(expr_tree, 0);
3152 Lex::append_char(intval, true, &s, this->location());
3153 Expression* se = Expression::make_string(s, this->location());
3154 return se->get_tree(context);
3157 static tree int_to_string_fndecl;
3158 ret = Gogo::call_builtin(&int_to_string_fndecl,
3160 "__go_int_to_string",
3164 fold_convert(integer_type_node, expr_tree));
3166 else if (type->is_string_type() && expr_type->is_slice_type())
3168 if (!DECL_P(expr_tree))
3169 expr_tree = save_expr(expr_tree);
3170 Array_type* a = expr_type->array_type();
3171 Type* e = a->element_type()->forwarded();
3172 go_assert(e->integer_type() != NULL);
3173 tree valptr = fold_convert(const_ptr_type_node,
3174 a->value_pointer_tree(gogo, expr_tree));
3175 tree len = a->length_tree(gogo, expr_tree);
3176 len = fold_convert_loc(this->location().gcc_location(), integer_type_node,
3178 if (e->integer_type()->is_byte())
3180 static tree byte_array_to_string_fndecl;
3181 ret = Gogo::call_builtin(&byte_array_to_string_fndecl,
3183 "__go_byte_array_to_string",
3186 const_ptr_type_node,
3193 go_assert(e->integer_type()->is_rune());
3194 static tree int_array_to_string_fndecl;
3195 ret = Gogo::call_builtin(&int_array_to_string_fndecl,
3197 "__go_int_array_to_string",
3200 const_ptr_type_node,
3206 else if (type->is_slice_type() && expr_type->is_string_type())
3208 Type* e = type->array_type()->element_type()->forwarded();
3209 go_assert(e->integer_type() != NULL);
3210 if (e->integer_type()->is_byte())
3212 tree string_to_byte_array_fndecl = NULL_TREE;
3213 ret = Gogo::call_builtin(&string_to_byte_array_fndecl,
3215 "__go_string_to_byte_array",
3218 TREE_TYPE(expr_tree),
3223 go_assert(e->integer_type()->is_rune());
3224 tree string_to_int_array_fndecl = NULL_TREE;
3225 ret = Gogo::call_builtin(&string_to_int_array_fndecl,
3227 "__go_string_to_int_array",
3230 TREE_TYPE(expr_tree),
3234 else if ((type->is_unsafe_pointer_type()
3235 && expr_type->points_to() != NULL)
3236 || (expr_type->is_unsafe_pointer_type()
3237 && type->points_to() != NULL))
3238 ret = fold_convert(type_tree, expr_tree);
3239 else if (type->is_unsafe_pointer_type()
3240 && expr_type->integer_type() != NULL)
3241 ret = convert_to_pointer(type_tree, expr_tree);
3242 else if (this->may_convert_function_types_
3243 && type->function_type() != NULL
3244 && expr_type->function_type() != NULL)
3245 ret = fold_convert_loc(this->location().gcc_location(), type_tree,
3248 ret = Expression::convert_for_assignment(context, type, expr_type,
3249 expr_tree, this->location());
3254 // Output a type conversion in a constant expression.
3257 Type_conversion_expression::do_export(Export* exp) const
3259 exp->write_c_string("convert(");
3260 exp->write_type(this->type_);
3261 exp->write_c_string(", ");
3262 this->expr_->export_expression(exp);
3263 exp->write_c_string(")");
3266 // Import a type conversion or a struct construction.
3269 Type_conversion_expression::do_import(Import* imp)
3271 imp->require_c_string("convert(");
3272 Type* type = imp->read_type();
3273 imp->require_c_string(", ");
3274 Expression* val = Expression::import_expression(imp);
3275 imp->require_c_string(")");
3276 return Expression::make_cast(type, val, imp->location());
3279 // Dump ast representation for a type conversion expression.
3282 Type_conversion_expression::do_dump_expression(
3283 Ast_dump_context* ast_dump_context) const
3285 ast_dump_context->dump_type(this->type_);
3286 ast_dump_context->ostream() << "(";
3287 ast_dump_context->dump_expression(this->expr_);
3288 ast_dump_context->ostream() << ") ";
3291 // Make a type cast expression.
3294 Expression::make_cast(Type* type, Expression* val, Location location)
3296 if (type->is_error_type() || val->is_error_expression())
3297 return Expression::make_error(location);
3298 return new Type_conversion_expression(type, val, location);
3301 // An unsafe type conversion, used to pass values to builtin functions.
3303 class Unsafe_type_conversion_expression : public Expression
3306 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3308 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3309 type_(type), expr_(expr)
3314 do_traverse(Traverse* traverse);
3318 { return this->type_; }
3321 do_determine_type(const Type_context*)
3322 { this->expr_->determine_type_no_context(); }
3327 return new Unsafe_type_conversion_expression(this->type_,
3328 this->expr_->copy(),
3333 do_get_tree(Translate_context*);
3336 do_dump_expression(Ast_dump_context*) const;
3339 // The type to convert to.
3341 // The expression to convert.
3348 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3350 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3351 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3352 return TRAVERSE_EXIT;
3353 return TRAVERSE_CONTINUE;
3356 // Convert to backend representation.
3359 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3361 // We are only called for a limited number of cases.
3363 Type* t = this->type_;
3364 Type* et = this->expr_->type();
3366 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
3367 tree expr_tree = this->expr_->get_tree(context);
3368 if (type_tree == error_mark_node || expr_tree == error_mark_node)
3369 return error_mark_node;
3371 Location loc = this->location();
3373 bool use_view_convert = false;
3374 if (t->is_slice_type())
3376 go_assert(et->is_slice_type());
3377 use_view_convert = true;
3379 else if (t->map_type() != NULL)
3380 go_assert(et->map_type() != NULL);
3381 else if (t->channel_type() != NULL)
3382 go_assert(et->channel_type() != NULL);
3383 else if (t->points_to() != NULL)
3384 go_assert(et->points_to() != NULL || et->is_nil_type());
3385 else if (et->is_unsafe_pointer_type())
3386 go_assert(t->points_to() != NULL);
3387 else if (t->interface_type() != NULL && !t->interface_type()->is_empty())
3389 go_assert(et->interface_type() != NULL
3390 && !et->interface_type()->is_empty());
3391 use_view_convert = true;
3393 else if (t->interface_type() != NULL && t->interface_type()->is_empty())
3395 go_assert(et->interface_type() != NULL
3396 && et->interface_type()->is_empty());
3397 use_view_convert = true;
3399 else if (t->integer_type() != NULL)
3401 go_assert(et->is_boolean_type()
3402 || et->integer_type() != NULL
3403 || et->function_type() != NULL
3404 || et->points_to() != NULL
3405 || et->map_type() != NULL
3406 || et->channel_type() != NULL);
3407 return convert_to_integer(type_tree, expr_tree);
3412 if (use_view_convert)
3413 return fold_build1_loc(loc.gcc_location(), VIEW_CONVERT_EXPR, type_tree,
3416 return fold_convert_loc(loc.gcc_location(), type_tree, expr_tree);
3419 // Dump ast representation for an unsafe type conversion expression.
3422 Unsafe_type_conversion_expression::do_dump_expression(
3423 Ast_dump_context* ast_dump_context) const
3425 ast_dump_context->dump_type(this->type_);
3426 ast_dump_context->ostream() << "(";
3427 ast_dump_context->dump_expression(this->expr_);
3428 ast_dump_context->ostream() << ") ";
3431 // Make an unsafe type conversion expression.
3434 Expression::make_unsafe_cast(Type* type, Expression* expr,
3437 return new Unsafe_type_conversion_expression(type, expr, location);
3440 // Unary expressions.
3442 class Unary_expression : public Expression
3445 Unary_expression(Operator op, Expression* expr, Location location)
3446 : Expression(EXPRESSION_UNARY, location),
3447 op_(op), escapes_(true), create_temp_(false), expr_(expr)
3450 // Return the operator.
3453 { return this->op_; }
3455 // Return the operand.
3458 { return this->expr_; }
3460 // Record that an address expression does not escape.
3462 set_does_not_escape()
3464 go_assert(this->op_ == OPERATOR_AND);
3465 this->escapes_ = false;
3468 // Record that this is an address expression which should create a
3469 // temporary variable if necessary. This is used for method calls.
3473 go_assert(this->op_ == OPERATOR_AND);
3474 this->create_temp_ = true;
3477 // Apply unary opcode OP to UNC, setting NC. Return true if this
3478 // could be done, false if not. Issue errors for overflow.
3480 eval_constant(Operator op, const Numeric_constant* unc,
3481 Location, Numeric_constant* nc);
3488 do_traverse(Traverse* traverse)
3489 { return Expression::traverse(&this->expr_, traverse); }
3492 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3495 do_is_constant() const;
3498 do_numeric_constant_value(Numeric_constant*) const;
3504 do_determine_type(const Type_context*);
3507 do_check_types(Gogo*);
3512 return Expression::make_unary(this->op_, this->expr_->copy(),
3517 do_must_eval_subexpressions_in_order(int*) const
3518 { return this->op_ == OPERATOR_MULT; }
3521 do_is_addressable() const
3522 { return this->op_ == OPERATOR_MULT; }
3525 do_get_tree(Translate_context*);
3528 do_export(Export*) const;
3531 do_dump_expression(Ast_dump_context*) const;
3534 // The unary operator to apply.
3536 // Normally true. False if this is an address expression which does
3537 // not escape the current function.
3539 // True if this is an address expression which should create a
3540 // temporary variable if necessary.
3546 // If we are taking the address of a composite literal, and the
3547 // contents are not constant, then we want to make a heap composite
3551 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3553 Location loc = this->location();
3554 Operator op = this->op_;
3555 Expression* expr = this->expr_;
3557 if (op == OPERATOR_MULT && expr->is_type_expression())
3558 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3560 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3561 // moving x to the heap. FIXME: Is it worth doing a real escape
3562 // analysis here? This case is found in math/unsafe.go and is
3563 // therefore worth special casing.
3564 if (op == OPERATOR_MULT)
3566 Expression* e = expr;
3567 while (e->classification() == EXPRESSION_CONVERSION)
3569 Type_conversion_expression* te
3570 = static_cast<Type_conversion_expression*>(e);
3574 if (e->classification() == EXPRESSION_UNARY)
3576 Unary_expression* ue = static_cast<Unary_expression*>(e);
3577 if (ue->op_ == OPERATOR_AND)
3584 ue->set_does_not_escape();
3589 // Catching an invalid indirection of unsafe.Pointer here avoid
3590 // having to deal with TYPE_VOID in other places.
3591 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3593 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3594 return Expression::make_error(this->location());
3597 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3599 Numeric_constant nc;
3600 if (expr->numeric_constant_value(&nc))
3602 Numeric_constant result;
3603 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3604 return result.expression(loc);
3611 // Return whether a unary expression is a constant.
3614 Unary_expression::do_is_constant() const
3616 if (this->op_ == OPERATOR_MULT)
3618 // Indirecting through a pointer is only constant if the object
3619 // to which the expression points is constant, but we currently
3620 // have no way to determine that.
3623 else if (this->op_ == OPERATOR_AND)
3625 // Taking the address of a variable is constant if it is a
3626 // global variable, not constant otherwise. In other cases
3627 // taking the address is probably not a constant.
3628 Var_expression* ve = this->expr_->var_expression();
3631 Named_object* no = ve->named_object();
3632 return no->is_variable() && no->var_value()->is_global();
3637 return this->expr_->is_constant();
3640 // Apply unary opcode OP to UNC, setting NC. Return true if this
3641 // could be done, false if not. Issue errors for overflow.
3644 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3645 Location location, Numeric_constant* nc)
3653 case OPERATOR_MINUS:
3654 if (unc->is_int() || unc->is_rune())
3656 else if (unc->is_float())
3659 unc->get_float(&uval);
3662 mpfr_neg(val, uval, GMP_RNDN);
3663 nc->set_float(unc->type(), val);
3668 else if (unc->is_complex())
3670 mpfr_t ureal, uimag;
3671 unc->get_complex(&ureal, &uimag);
3675 mpfr_neg(real, ureal, GMP_RNDN);
3676 mpfr_neg(imag, uimag, GMP_RNDN);
3677 nc->set_complex(unc->type(), real, imag);
3699 if (!unc->is_int() && !unc->is_rune())
3704 unc->get_rune(&uval);
3706 unc->get_int(&uval);
3712 case OPERATOR_MINUS:
3717 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3722 Type* utype = unc->type();
3723 if (utype->integer_type() == NULL
3724 || utype->integer_type()->is_abstract())
3728 // The number of HOST_WIDE_INTs that it takes to represent
3730 size_t count = ((mpz_sizeinbase(uval, 2)
3731 + HOST_BITS_PER_WIDE_INT
3733 / HOST_BITS_PER_WIDE_INT);
3735 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3736 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3738 size_t obits = utype->integer_type()->bits();
3740 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3743 mpz_init_set_ui(adj, 1);
3744 mpz_mul_2exp(adj, adj, obits);
3745 mpz_add(uval, uval, adj);
3750 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3751 go_assert(ecount <= count);
3753 // Trim down to the number of words required by the type.
3754 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3755 / HOST_BITS_PER_WIDE_INT);
3756 go_assert(ocount <= count);
3758 for (size_t i = 0; i < ocount; ++i)
3761 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3763 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3766 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3768 if (!utype->integer_type()->is_unsigned()
3769 && mpz_tstbit(val, obits - 1))
3772 mpz_init_set_ui(adj, 1);
3773 mpz_mul_2exp(adj, adj, obits);
3774 mpz_sub(val, val, adj);
3788 nc->set_rune(NULL, val);
3790 nc->set_int(NULL, val);
3795 return nc->set_type(unc->type(), true, location);
3798 // Return the integral constant value of a unary expression, if it has one.
3801 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3803 Numeric_constant unc;
3804 if (!this->expr_->numeric_constant_value(&unc))
3806 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3810 // Return the type of a unary expression.
3813 Unary_expression::do_type()
3818 case OPERATOR_MINUS:
3821 return this->expr_->type();
3824 return Type::make_pointer_type(this->expr_->type());
3828 Type* subtype = this->expr_->type();
3829 Type* points_to = subtype->points_to();
3830 if (points_to == NULL)
3831 return Type::make_error_type();
3840 // Determine abstract types for a unary expression.
3843 Unary_expression::do_determine_type(const Type_context* context)
3848 case OPERATOR_MINUS:
3851 this->expr_->determine_type(context);
3855 // Taking the address of something.
3857 Type* subtype = (context->type == NULL
3859 : context->type->points_to());
3860 Type_context subcontext(subtype, false);
3861 this->expr_->determine_type(&subcontext);
3866 // Indirecting through a pointer.
3868 Type* subtype = (context->type == NULL
3870 : Type::make_pointer_type(context->type));
3871 Type_context subcontext(subtype, false);
3872 this->expr_->determine_type(&subcontext);
3881 // Check types for a unary expression.
3884 Unary_expression::do_check_types(Gogo*)
3886 Type* type = this->expr_->type();
3887 if (type->is_error())
3889 this->set_is_error();
3896 case OPERATOR_MINUS:
3897 if (type->integer_type() == NULL
3898 && type->float_type() == NULL
3899 && type->complex_type() == NULL)
3900 this->report_error(_("expected numeric type"));
3904 if (!type->is_boolean_type())
3905 this->report_error(_("expected boolean type"));
3909 if (type->integer_type() == NULL
3910 && !type->is_boolean_type())
3911 this->report_error(_("expected integer or boolean type"));
3915 if (!this->expr_->is_addressable())
3917 if (!this->create_temp_)
3918 this->report_error(_("invalid operand for unary %<&%>"));
3921 this->expr_->address_taken(this->escapes_);
3925 // Indirecting through a pointer.
3926 if (type->points_to() == NULL)
3927 this->report_error(_("expected pointer"));
3935 // Get a tree for a unary expression.
3938 Unary_expression::do_get_tree(Translate_context* context)
3940 Location loc = this->location();
3942 // Taking the address of a set-and-use-temporary expression requires
3943 // setting the temporary and then taking the address.
3944 if (this->op_ == OPERATOR_AND)
3946 Set_and_use_temporary_expression* sut =
3947 this->expr_->set_and_use_temporary_expression();
3950 Temporary_statement* temp = sut->temporary();
3951 Bvariable* bvar = temp->get_backend_variable(context);
3952 tree var_tree = var_to_tree(bvar);
3953 Expression* val = sut->expression();
3954 tree val_tree = val->get_tree(context);
3955 if (var_tree == error_mark_node || val_tree == error_mark_node)
3956 return error_mark_node;
3957 tree addr_tree = build_fold_addr_expr_loc(loc.gcc_location(),
3959 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
3960 TREE_TYPE(addr_tree),
3961 build2_loc(sut->location().gcc_location(),
3962 MODIFY_EXPR, void_type_node,
3963 var_tree, val_tree),
3968 tree expr = this->expr_->get_tree(context);
3969 if (expr == error_mark_node)
3970 return error_mark_node;
3977 case OPERATOR_MINUS:
3979 tree type = TREE_TYPE(expr);
3980 tree compute_type = excess_precision_type(type);
3981 if (compute_type != NULL_TREE)
3982 expr = ::convert(compute_type, expr);
3983 tree ret = fold_build1_loc(loc.gcc_location(), NEGATE_EXPR,
3984 (compute_type != NULL_TREE
3988 if (compute_type != NULL_TREE)
3989 ret = ::convert(type, ret);
3994 if (TREE_CODE(TREE_TYPE(expr)) == BOOLEAN_TYPE)
3995 return fold_build1_loc(loc.gcc_location(), TRUTH_NOT_EXPR,
3996 TREE_TYPE(expr), expr);
3998 return fold_build2_loc(loc.gcc_location(), NE_EXPR, boolean_type_node,
3999 expr, build_int_cst(TREE_TYPE(expr), 0));
4002 return fold_build1_loc(loc.gcc_location(), BIT_NOT_EXPR, TREE_TYPE(expr),
4006 if (!this->create_temp_)
4008 // We should not see a non-constant constructor here; cases
4009 // where we would see one should have been moved onto the
4010 // heap at parse time. Taking the address of a nonconstant
4011 // constructor will not do what the programmer expects.
4012 go_assert(TREE_CODE(expr) != CONSTRUCTOR || TREE_CONSTANT(expr));
4013 go_assert(TREE_CODE(expr) != ADDR_EXPR);
4016 // Build a decl for a constant constructor.
4017 if (TREE_CODE(expr) == CONSTRUCTOR && TREE_CONSTANT(expr))
4019 tree decl = build_decl(this->location().gcc_location(), VAR_DECL,
4020 create_tmp_var_name("C"), TREE_TYPE(expr));
4021 DECL_EXTERNAL(decl) = 0;
4022 TREE_PUBLIC(decl) = 0;
4023 TREE_READONLY(decl) = 1;
4024 TREE_CONSTANT(decl) = 1;
4025 TREE_STATIC(decl) = 1;
4026 TREE_ADDRESSABLE(decl) = 1;
4027 DECL_ARTIFICIAL(decl) = 1;
4028 DECL_INITIAL(decl) = expr;
4029 rest_of_decl_compilation(decl, 1, 0);
4033 if (this->create_temp_
4034 && !TREE_ADDRESSABLE(TREE_TYPE(expr))
4035 && (TREE_CODE(expr) == CONST_DECL || !DECL_P(expr))
4036 && TREE_CODE(expr) != INDIRECT_REF
4037 && TREE_CODE(expr) != COMPONENT_REF)
4039 if (current_function_decl != NULL)
4041 tree tmp = create_tmp_var(TREE_TYPE(expr), get_name(expr));
4042 DECL_IGNORED_P(tmp) = 1;
4043 DECL_INITIAL(tmp) = expr;
4044 TREE_ADDRESSABLE(tmp) = 1;
4045 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4046 build_pointer_type(TREE_TYPE(expr)),
4047 build1_loc(loc.gcc_location(), DECL_EXPR,
4048 void_type_node, tmp),
4049 build_fold_addr_expr_loc(loc.gcc_location(),
4054 tree tmp = build_decl(loc.gcc_location(), VAR_DECL,
4055 create_tmp_var_name("A"), TREE_TYPE(expr));
4056 DECL_EXTERNAL(tmp) = 0;
4057 TREE_PUBLIC(tmp) = 0;
4058 TREE_STATIC(tmp) = 1;
4059 DECL_ARTIFICIAL(tmp) = 1;
4060 TREE_ADDRESSABLE(tmp) = 1;
4062 if (!TREE_CONSTANT(expr))
4063 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
4064 void_type_node, tmp, expr);
4067 TREE_READONLY(tmp) = 1;
4068 TREE_CONSTANT(tmp) = 1;
4069 DECL_INITIAL(tmp) = expr;
4070 make_tmp = NULL_TREE;
4072 rest_of_decl_compilation(tmp, 1, 0);
4073 tree addr = build_fold_addr_expr_loc(loc.gcc_location(), tmp);
4074 if (make_tmp == NULL_TREE)
4076 return build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4077 TREE_TYPE(addr), make_tmp, addr);
4081 return build_fold_addr_expr_loc(loc.gcc_location(), expr);
4085 go_assert(POINTER_TYPE_P(TREE_TYPE(expr)));
4087 // If we are dereferencing the pointer to a large struct, we
4088 // need to check for nil. We don't bother to check for small
4089 // structs because we expect the system to crash on a nil
4090 // pointer dereference.
4091 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4092 if (!VOID_TYPE_P(target_type_tree))
4094 HOST_WIDE_INT s = int_size_in_bytes(target_type_tree);
4095 if (s == -1 || s >= 4096)
4098 expr = save_expr(expr);
4099 tree compare = fold_build2_loc(loc.gcc_location(), EQ_EXPR,
4102 fold_convert(TREE_TYPE(expr),
4103 null_pointer_node));
4104 tree crash = Gogo::runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4106 expr = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
4107 TREE_TYPE(expr), build3(COND_EXPR,
4115 // If the type of EXPR is a recursive pointer type, then we
4116 // need to insert a cast before indirecting.
4117 if (VOID_TYPE_P(target_type_tree))
4119 Type* pt = this->expr_->type()->points_to();
4120 tree ind = type_to_tree(pt->get_backend(context->gogo()));
4121 expr = fold_convert_loc(loc.gcc_location(),
4122 build_pointer_type(ind), expr);
4125 return build_fold_indirect_ref_loc(loc.gcc_location(), expr);
4133 // Export a unary expression.
4136 Unary_expression::do_export(Export* exp) const
4141 exp->write_c_string("+ ");
4143 case OPERATOR_MINUS:
4144 exp->write_c_string("- ");
4147 exp->write_c_string("! ");
4150 exp->write_c_string("^ ");
4157 this->expr_->export_expression(exp);
4160 // Import a unary expression.
4163 Unary_expression::do_import(Import* imp)
4166 switch (imp->get_char())
4172 op = OPERATOR_MINUS;
4183 imp->require_c_string(" ");
4184 Expression* expr = Expression::import_expression(imp);
4185 return Expression::make_unary(op, expr, imp->location());
4188 // Dump ast representation of an unary expression.
4191 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4193 ast_dump_context->dump_operator(this->op_);
4194 ast_dump_context->ostream() << "(";
4195 ast_dump_context->dump_expression(this->expr_);
4196 ast_dump_context->ostream() << ") ";
4199 // Make a unary expression.
4202 Expression::make_unary(Operator op, Expression* expr, Location location)
4204 return new Unary_expression(op, expr, location);
4207 // If this is an indirection through a pointer, return the expression
4208 // being pointed through. Otherwise return this.
4213 if (this->classification_ == EXPRESSION_UNARY)
4215 Unary_expression* ue = static_cast<Unary_expression*>(this);
4216 if (ue->op() == OPERATOR_MULT)
4217 return ue->operand();
4222 // Class Binary_expression.
4227 Binary_expression::do_traverse(Traverse* traverse)
4229 int t = Expression::traverse(&this->left_, traverse);
4230 if (t == TRAVERSE_EXIT)
4231 return TRAVERSE_EXIT;
4232 return Expression::traverse(&this->right_, traverse);
4235 // Return the type to use for a binary operation on operands of
4236 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4237 // such may be NULL or abstract.
4240 Binary_expression::operation_type(Operator op, Type* left_type,
4241 Type* right_type, Type** result_type)
4243 if (left_type != right_type
4244 && !left_type->is_abstract()
4245 && !right_type->is_abstract()
4246 && left_type->base() != right_type->base()
4247 && op != OPERATOR_LSHIFT
4248 && op != OPERATOR_RSHIFT)
4250 // May be a type error--let it be diagnosed elsewhere.
4254 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4256 if (left_type->integer_type() != NULL)
4257 *result_type = left_type;
4259 *result_type = Type::make_abstract_integer_type();
4261 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4262 *result_type = left_type;
4263 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4264 *result_type = right_type;
4265 else if (!left_type->is_abstract())
4266 *result_type = left_type;
4267 else if (!right_type->is_abstract())
4268 *result_type = right_type;
4269 else if (left_type->complex_type() != NULL)
4270 *result_type = left_type;
4271 else if (right_type->complex_type() != NULL)
4272 *result_type = right_type;
4273 else if (left_type->float_type() != NULL)
4274 *result_type = left_type;
4275 else if (right_type->float_type() != NULL)
4276 *result_type = right_type;
4277 else if (left_type->integer_type() != NULL
4278 && left_type->integer_type()->is_rune())
4279 *result_type = left_type;
4280 else if (right_type->integer_type() != NULL
4281 && right_type->integer_type()->is_rune())
4282 *result_type = right_type;
4284 *result_type = left_type;
4289 // Convert an integer comparison code and an operator to a boolean
4293 Binary_expression::cmp_to_bool(Operator op, int cmp)
4300 case OPERATOR_NOTEQ:
4317 // Compare constants according to OP.
4320 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4321 Numeric_constant* right_nc,
4322 Location location, bool* result)
4324 Type* left_type = left_nc->type();
4325 Type* right_type = right_nc->type();
4328 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4331 // When comparing an untyped operand to a typed operand, we are
4332 // effectively coercing the untyped operand to the other operand's
4333 // type, so make sure that is valid.
4334 if (!left_nc->set_type(type, true, location)
4335 || !right_nc->set_type(type, true, location))
4340 if (type->complex_type() != NULL)
4342 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4344 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4346 else if (type->float_type() != NULL)
4347 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4349 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4352 *result = Binary_expression::cmp_to_bool(op, cmp);
4357 // Compare integer constants.
4360 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4361 const Numeric_constant* right_nc,
4365 if (!left_nc->to_int(&left_val))
4368 if (!right_nc->to_int(&right_val))
4370 mpz_clear(left_val);
4374 *cmp = mpz_cmp(left_val, right_val);
4376 mpz_clear(left_val);
4377 mpz_clear(right_val);
4382 // Compare floating point constants.
4385 Binary_expression::compare_float(const Numeric_constant* left_nc,
4386 const Numeric_constant* right_nc,
4390 if (!left_nc->to_float(&left_val))
4393 if (!right_nc->to_float(&right_val))
4395 mpfr_clear(left_val);
4399 // We already coerced both operands to the same type. If that type
4400 // is not an abstract type, we need to round the values accordingly.
4401 Type* type = left_nc->type();
4402 if (!type->is_abstract() && type->float_type() != NULL)
4404 int bits = type->float_type()->bits();
4405 mpfr_prec_round(left_val, bits, GMP_RNDN);
4406 mpfr_prec_round(right_val, bits, GMP_RNDN);
4409 *cmp = mpfr_cmp(left_val, right_val);
4411 mpfr_clear(left_val);
4412 mpfr_clear(right_val);
4417 // Compare complex constants. Complex numbers may only be compared
4421 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4422 const Numeric_constant* right_nc,
4425 mpfr_t left_real, left_imag;
4426 if (!left_nc->to_complex(&left_real, &left_imag))
4428 mpfr_t right_real, right_imag;
4429 if (!right_nc->to_complex(&right_real, &right_imag))
4431 mpfr_clear(left_real);
4432 mpfr_clear(left_imag);
4436 // We already coerced both operands to the same type. If that type
4437 // is not an abstract type, we need to round the values accordingly.
4438 Type* type = left_nc->type();
4439 if (!type->is_abstract() && type->complex_type() != NULL)
4441 int bits = type->complex_type()->bits();
4442 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4443 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4444 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4445 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4448 *cmp = (mpfr_cmp(left_real, right_real) != 0
4449 || mpfr_cmp(left_imag, right_imag) != 0);
4451 mpfr_clear(left_real);
4452 mpfr_clear(left_imag);
4453 mpfr_clear(right_real);
4454 mpfr_clear(right_imag);
4459 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4460 // true if this could be done, false if not. Issue errors at LOCATION
4464 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4465 Numeric_constant* right_nc,
4466 Location location, Numeric_constant* nc)
4471 case OPERATOR_ANDAND:
4473 case OPERATOR_NOTEQ:
4478 // These return boolean values, not numeric.
4484 Type* left_type = left_nc->type();
4485 Type* right_type = right_nc->type();
4488 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4491 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4493 // When combining an untyped operand with a typed operand, we are
4494 // effectively coercing the untyped operand to the other operand's
4495 // type, so make sure that is valid.
4496 if (!left_nc->set_type(type, true, location))
4498 if (!is_shift && !right_nc->set_type(type, true, location))
4502 if (type->complex_type() != NULL)
4503 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4504 else if (type->float_type() != NULL)
4505 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4507 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4510 r = nc->set_type(type, true, location);
4515 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4516 // integer operations. Return true if this could be done, false if
4520 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4521 const Numeric_constant* right_nc,
4522 Location location, Numeric_constant* nc)
4525 if (!left_nc->to_int(&left_val))
4528 if (!right_nc->to_int(&right_val))
4530 mpz_clear(left_val);
4540 mpz_add(val, left_val, right_val);
4542 case OPERATOR_MINUS:
4543 mpz_sub(val, left_val, right_val);
4546 mpz_ior(val, left_val, right_val);
4549 mpz_xor(val, left_val, right_val);
4552 mpz_mul(val, left_val, right_val);
4555 if (mpz_sgn(right_val) != 0)
4556 mpz_tdiv_q(val, left_val, right_val);
4559 error_at(location, "division by zero");
4564 if (mpz_sgn(right_val) != 0)
4565 mpz_tdiv_r(val, left_val, right_val);
4568 error_at(location, "division by zero");
4572 case OPERATOR_LSHIFT:
4574 unsigned long shift = mpz_get_ui(right_val);
4575 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4576 mpz_mul_2exp(val, left_val, shift);
4579 error_at(location, "shift count overflow");
4585 case OPERATOR_RSHIFT:
4587 unsigned long shift = mpz_get_ui(right_val);
4588 if (mpz_cmp_ui(right_val, shift) != 0)
4590 error_at(location, "shift count overflow");
4595 if (mpz_cmp_ui(left_val, 0) >= 0)
4596 mpz_tdiv_q_2exp(val, left_val, shift);
4598 mpz_fdiv_q_2exp(val, left_val, shift);
4604 mpz_and(val, left_val, right_val);
4606 case OPERATOR_BITCLEAR:
4610 mpz_com(tval, right_val);
4611 mpz_and(val, left_val, tval);
4619 mpz_clear(left_val);
4620 mpz_clear(right_val);
4622 if (left_nc->is_rune()
4623 || (op != OPERATOR_LSHIFT
4624 && op != OPERATOR_RSHIFT
4625 && right_nc->is_rune()))
4626 nc->set_rune(NULL, val);
4628 nc->set_int(NULL, val);
4635 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4636 // floating point operations. Return true if this could be done,
4640 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4641 const Numeric_constant* right_nc,
4642 Location location, Numeric_constant* nc)
4645 if (!left_nc->to_float(&left_val))
4648 if (!right_nc->to_float(&right_val))
4650 mpfr_clear(left_val);
4661 mpfr_add(val, left_val, right_val, GMP_RNDN);
4663 case OPERATOR_MINUS:
4664 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4669 case OPERATOR_BITCLEAR:
4671 case OPERATOR_LSHIFT:
4672 case OPERATOR_RSHIFT:
4673 mpfr_set_ui(val, 0, GMP_RNDN);
4677 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4680 if (!mpfr_zero_p(right_val))
4681 mpfr_div(val, left_val, right_val, GMP_RNDN);
4684 error_at(location, "division by zero");
4685 mpfr_set_ui(val, 0, GMP_RNDN);
4692 mpfr_clear(left_val);
4693 mpfr_clear(right_val);
4695 nc->set_float(NULL, val);
4701 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4702 // complex operations. Return true if this could be done, false if
4706 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4707 const Numeric_constant* right_nc,
4708 Location location, Numeric_constant* nc)
4710 mpfr_t left_real, left_imag;
4711 if (!left_nc->to_complex(&left_real, &left_imag))
4713 mpfr_t right_real, right_imag;
4714 if (!right_nc->to_complex(&right_real, &right_imag))
4716 mpfr_clear(left_real);
4717 mpfr_clear(left_imag);
4729 mpfr_add(real, left_real, right_real, GMP_RNDN);
4730 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4732 case OPERATOR_MINUS:
4733 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4734 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4739 case OPERATOR_BITCLEAR:
4741 case OPERATOR_LSHIFT:
4742 case OPERATOR_RSHIFT:
4743 mpfr_set_ui(real, 0, GMP_RNDN);
4744 mpfr_set_ui(imag, 0, GMP_RNDN);
4749 // You might think that multiplying two complex numbers would
4750 // be simple, and you would be right, until you start to think
4751 // about getting the right answer for infinity. If one
4752 // operand here is infinity and the other is anything other
4753 // than zero or NaN, then we are going to wind up subtracting
4754 // two infinity values. That will give us a NaN, but the
4755 // correct answer is infinity.
4759 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4763 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4767 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4771 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4773 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4774 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4776 // If we get NaN on both sides, check whether it should really
4777 // be infinity. The rule is that if either side of the
4778 // complex number is infinity, then the whole value is
4779 // infinity, even if the other side is NaN. So the only case
4780 // we have to fix is the one in which both sides are NaN.
4781 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4782 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4783 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4785 bool is_infinity = false;
4789 mpfr_init_set(lr, left_real, GMP_RNDN);
4790 mpfr_init_set(li, left_imag, GMP_RNDN);
4794 mpfr_init_set(rr, right_real, GMP_RNDN);
4795 mpfr_init_set(ri, right_imag, GMP_RNDN);
4797 // If the left side is infinity, then the result is
4799 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4801 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4802 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4803 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4804 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4807 mpfr_set_ui(rr, 0, GMP_RNDN);
4808 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4812 mpfr_set_ui(ri, 0, GMP_RNDN);
4813 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4818 // If the right side is infinity, then the result is
4820 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4822 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4823 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4824 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4825 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4828 mpfr_set_ui(lr, 0, GMP_RNDN);
4829 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4833 mpfr_set_ui(li, 0, GMP_RNDN);
4834 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4839 // If we got an overflow in the intermediate computations,
4840 // then the result is infinity.
4842 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4843 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4847 mpfr_set_ui(lr, 0, GMP_RNDN);
4848 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4852 mpfr_set_ui(li, 0, GMP_RNDN);
4853 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4857 mpfr_set_ui(rr, 0, GMP_RNDN);
4858 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4862 mpfr_set_ui(ri, 0, GMP_RNDN);
4863 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4870 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4871 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4872 mpfr_mul(lirr, li, rr, GMP_RNDN);
4873 mpfr_mul(liri, li, ri, GMP_RNDN);
4874 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4875 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4876 mpfr_set_inf(real, mpfr_sgn(real));
4877 mpfr_set_inf(imag, mpfr_sgn(imag));
4894 // For complex division we want to avoid having an
4895 // intermediate overflow turn the whole result in a NaN. We
4896 // scale the values to try to avoid this.
4898 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4900 error_at(location, "division by zero");
4901 mpfr_set_ui(real, 0, GMP_RNDN);
4902 mpfr_set_ui(imag, 0, GMP_RNDN);
4910 mpfr_abs(rra, right_real, GMP_RNDN);
4911 mpfr_abs(ria, right_imag, GMP_RNDN);
4914 mpfr_max(t, rra, ria, GMP_RNDN);
4918 mpfr_init_set(rr, right_real, GMP_RNDN);
4919 mpfr_init_set(ri, right_imag, GMP_RNDN);
4921 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4923 ilogbw = mpfr_get_exp(t);
4924 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4925 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4930 mpfr_mul(denom, rr, rr, GMP_RNDN);
4931 mpfr_mul(t, ri, ri, GMP_RNDN);
4932 mpfr_add(denom, denom, t, GMP_RNDN);
4934 mpfr_mul(real, left_real, rr, GMP_RNDN);
4935 mpfr_mul(t, left_imag, ri, GMP_RNDN);
4936 mpfr_add(real, real, t, GMP_RNDN);
4937 mpfr_div(real, real, denom, GMP_RNDN);
4938 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4940 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4941 mpfr_mul(t, left_real, ri, GMP_RNDN);
4942 mpfr_sub(imag, imag, t, GMP_RNDN);
4943 mpfr_div(imag, imag, denom, GMP_RNDN);
4944 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
4946 // If we wind up with NaN on both sides, check whether we
4947 // should really have infinity. The rule is that if either
4948 // side of the complex number is infinity, then the whole
4949 // value is infinity, even if the other side is NaN. So the
4950 // only case we have to fix is the one in which both sides are
4952 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4953 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4954 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4956 if (mpfr_zero_p(denom))
4958 mpfr_set_inf(real, mpfr_sgn(rr));
4959 mpfr_mul(real, real, left_real, GMP_RNDN);
4960 mpfr_set_inf(imag, mpfr_sgn(rr));
4961 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
4963 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
4964 && mpfr_number_p(rr) && mpfr_number_p(ri))
4966 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
4967 mpfr_copysign(t, t, left_real, GMP_RNDN);
4970 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
4971 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
4975 mpfr_mul(t3, t, rr, GMP_RNDN);
4979 mpfr_mul(t4, t2, ri, GMP_RNDN);
4981 mpfr_add(t3, t3, t4, GMP_RNDN);
4982 mpfr_set_inf(real, mpfr_sgn(t3));
4984 mpfr_mul(t3, t2, rr, GMP_RNDN);
4985 mpfr_mul(t4, t, ri, GMP_RNDN);
4986 mpfr_sub(t3, t3, t4, GMP_RNDN);
4987 mpfr_set_inf(imag, mpfr_sgn(t3));
4993 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
4994 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
4996 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4997 mpfr_copysign(t, t, rr, GMP_RNDN);
5000 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5001 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5005 mpfr_mul(t3, left_real, t, GMP_RNDN);
5009 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5011 mpfr_add(t3, t3, t4, GMP_RNDN);
5012 mpfr_set_ui(real, 0, GMP_RNDN);
5013 mpfr_mul(real, real, t3, GMP_RNDN);
5015 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5016 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5017 mpfr_sub(t3, t3, t4, GMP_RNDN);
5018 mpfr_set_ui(imag, 0, GMP_RNDN);
5019 mpfr_mul(imag, imag, t3, GMP_RNDN);
5039 mpfr_clear(left_real);
5040 mpfr_clear(left_imag);
5041 mpfr_clear(right_real);
5042 mpfr_clear(right_imag);
5044 nc->set_complex(NULL, real, imag);
5051 // Lower a binary expression. We have to evaluate constant
5052 // expressions now, in order to implement Go's unlimited precision
5056 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5057 Statement_inserter* inserter, int)
5059 Location location = this->location();
5060 Operator op = this->op_;
5061 Expression* left = this->left_;
5062 Expression* right = this->right_;
5064 const bool is_comparison = (op == OPERATOR_EQEQ
5065 || op == OPERATOR_NOTEQ
5066 || op == OPERATOR_LT
5067 || op == OPERATOR_LE
5068 || op == OPERATOR_GT
5069 || op == OPERATOR_GE);
5071 // Numeric constant expressions.
5073 Numeric_constant left_nc;
5074 Numeric_constant right_nc;
5075 if (left->numeric_constant_value(&left_nc)
5076 && right->numeric_constant_value(&right_nc))
5081 if (!Binary_expression::compare_constant(op, &left_nc,
5082 &right_nc, location,
5085 return Expression::make_cast(Type::lookup_bool_type(),
5086 Expression::make_boolean(result,
5092 Numeric_constant nc;
5093 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5096 return nc.expression(location);
5101 // String constant expressions.
5102 if (left->type()->is_string_type() && right->type()->is_string_type())
5104 std::string left_string;
5105 std::string right_string;
5106 if (left->string_constant_value(&left_string)
5107 && right->string_constant_value(&right_string))
5109 if (op == OPERATOR_PLUS)
5110 return Expression::make_string(left_string + right_string,
5112 else if (is_comparison)
5114 int cmp = left_string.compare(right_string);
5115 bool r = Binary_expression::cmp_to_bool(op, cmp);
5116 return Expression::make_cast(Type::lookup_bool_type(),
5117 Expression::make_boolean(r,
5124 // Lower struct and array comparisons.
5125 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5127 if (left->type()->struct_type() != NULL)
5128 return this->lower_struct_comparison(gogo, inserter);
5129 else if (left->type()->array_type() != NULL
5130 && !left->type()->is_slice_type())
5131 return this->lower_array_comparison(gogo, inserter);
5137 // Lower a struct comparison.
5140 Binary_expression::lower_struct_comparison(Gogo* gogo,
5141 Statement_inserter* inserter)
5143 Struct_type* st = this->left_->type()->struct_type();
5144 Struct_type* st2 = this->right_->type()->struct_type();
5147 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5149 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5150 this->right_->type(), NULL))
5153 // See if we can compare using memcmp. As a heuristic, we use
5154 // memcmp rather than field references and comparisons if there are
5155 // more than two fields.
5156 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5157 return this->lower_compare_to_memcmp(gogo, inserter);
5159 Location loc = this->location();
5161 Expression* left = this->left_;
5162 Temporary_statement* left_temp = NULL;
5163 if (left->var_expression() == NULL
5164 && left->temporary_reference_expression() == NULL)
5166 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5167 inserter->insert(left_temp);
5168 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5171 Expression* right = this->right_;
5172 Temporary_statement* right_temp = NULL;
5173 if (right->var_expression() == NULL
5174 && right->temporary_reference_expression() == NULL)
5176 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5177 inserter->insert(right_temp);
5178 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5181 Expression* ret = Expression::make_boolean(true, loc);
5182 const Struct_field_list* fields = st->fields();
5183 unsigned int field_index = 0;
5184 for (Struct_field_list::const_iterator pf = fields->begin();
5185 pf != fields->end();
5186 ++pf, ++field_index)
5188 if (field_index > 0)
5190 if (left_temp == NULL)
5191 left = left->copy();
5193 left = Expression::make_temporary_reference(left_temp, loc);
5194 if (right_temp == NULL)
5195 right = right->copy();
5197 right = Expression::make_temporary_reference(right_temp, loc);
5199 Expression* f1 = Expression::make_field_reference(left, field_index,
5201 Expression* f2 = Expression::make_field_reference(right, field_index,
5203 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5204 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5207 if (this->op_ == OPERATOR_NOTEQ)
5208 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5213 // Lower an array comparison.
5216 Binary_expression::lower_array_comparison(Gogo* gogo,
5217 Statement_inserter* inserter)
5219 Array_type* at = this->left_->type()->array_type();
5220 Array_type* at2 = this->right_->type()->array_type();
5223 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5225 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5226 this->right_->type(), NULL))
5229 // Call memcmp directly if possible. This may let the middle-end
5230 // optimize the call.
5231 if (at->compare_is_identity(gogo))
5232 return this->lower_compare_to_memcmp(gogo, inserter);
5234 // Call the array comparison function.
5235 Named_object* hash_fn;
5236 Named_object* equal_fn;
5237 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5238 &hash_fn, &equal_fn);
5240 Location loc = this->location();
5242 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5244 Expression_list* args = new Expression_list();
5245 args->push_back(this->operand_address(inserter, this->left_));
5246 args->push_back(this->operand_address(inserter, this->right_));
5247 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5249 Expression* ret = Expression::make_call(func, args, false, loc);
5251 if (this->op_ == OPERATOR_NOTEQ)
5252 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5257 // Lower a struct or array comparison to a call to memcmp.
5260 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5262 Location loc = this->location();
5264 Expression* a1 = this->operand_address(inserter, this->left_);
5265 Expression* a2 = this->operand_address(inserter, this->right_);
5266 Expression* len = Expression::make_type_info(this->left_->type(),
5269 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5272 mpz_init_set_ui(zval, 0);
5273 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5276 return Expression::make_binary(this->op_, call, zero, loc);
5279 // Return the address of EXPR, cast to unsafe.Pointer.
5282 Binary_expression::operand_address(Statement_inserter* inserter,
5285 Location loc = this->location();
5287 if (!expr->is_addressable())
5289 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5291 inserter->insert(temp);
5292 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5294 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5295 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5296 Type* void_type = Type::make_void_type();
5297 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5298 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5301 // Return the numeric constant value, if it has one.
5304 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5306 Numeric_constant left_nc;
5307 if (!this->left_->numeric_constant_value(&left_nc))
5309 Numeric_constant right_nc;
5310 if (!this->right_->numeric_constant_value(&right_nc))
5312 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5313 this->location(), nc);
5316 // Note that the value is being discarded.
5319 Binary_expression::do_discarding_value()
5321 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5322 this->right_->discarding_value();
5324 this->unused_value_error();
5330 Binary_expression::do_type()
5332 if (this->classification() == EXPRESSION_ERROR)
5333 return Type::make_error_type();
5338 case OPERATOR_ANDAND:
5340 case OPERATOR_NOTEQ:
5345 return Type::lookup_bool_type();
5348 case OPERATOR_MINUS:
5355 case OPERATOR_BITCLEAR:
5358 if (!Binary_expression::operation_type(this->op_,
5359 this->left_->type(),
5360 this->right_->type(),
5362 return Type::make_error_type();
5366 case OPERATOR_LSHIFT:
5367 case OPERATOR_RSHIFT:
5368 return this->left_->type();
5375 // Set type for a binary expression.
5378 Binary_expression::do_determine_type(const Type_context* context)
5380 Type* tleft = this->left_->type();
5381 Type* tright = this->right_->type();
5383 // Both sides should have the same type, except for the shift
5384 // operations. For a comparison, we should ignore the incoming
5387 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5388 || this->op_ == OPERATOR_RSHIFT);
5390 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5391 || this->op_ == OPERATOR_NOTEQ
5392 || this->op_ == OPERATOR_LT
5393 || this->op_ == OPERATOR_LE
5394 || this->op_ == OPERATOR_GT
5395 || this->op_ == OPERATOR_GE);
5397 Type_context subcontext(*context);
5401 // In a comparison, the context does not determine the types of
5403 subcontext.type = NULL;
5406 // Set the context for the left hand operand.
5409 // The right hand operand of a shift plays no role in
5410 // determining the type of the left hand operand.
5412 else if (!tleft->is_abstract())
5413 subcontext.type = tleft;
5414 else if (!tright->is_abstract())
5415 subcontext.type = tright;
5416 else if (subcontext.type == NULL)
5418 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5419 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5420 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5422 // Both sides have an abstract integer, abstract float, or
5423 // abstract complex type. Just let CONTEXT determine
5424 // whether they may remain abstract or not.
5426 else if (tleft->complex_type() != NULL)
5427 subcontext.type = tleft;
5428 else if (tright->complex_type() != NULL)
5429 subcontext.type = tright;
5430 else if (tleft->float_type() != NULL)
5431 subcontext.type = tleft;
5432 else if (tright->float_type() != NULL)
5433 subcontext.type = tright;
5435 subcontext.type = tleft;
5437 if (subcontext.type != NULL && !context->may_be_abstract)
5438 subcontext.type = subcontext.type->make_non_abstract_type();
5441 this->left_->determine_type(&subcontext);
5445 // We may have inherited an unusable type for the shift operand.
5446 // Give a useful error if that happened.
5447 if (tleft->is_abstract()
5448 && subcontext.type != NULL
5449 && (this->left_->type()->integer_type() == NULL
5450 || (subcontext.type->integer_type() == NULL
5451 && subcontext.type->float_type() == NULL
5452 && subcontext.type->complex_type() == NULL)))
5453 this->report_error(("invalid context-determined non-integer type "
5454 "for shift operand"));
5456 // The context for the right hand operand is the same as for the
5457 // left hand operand, except for a shift operator.
5458 subcontext.type = Type::lookup_integer_type("uint");
5459 subcontext.may_be_abstract = false;
5462 this->right_->determine_type(&subcontext);
5465 // Report an error if the binary operator OP does not support TYPE.
5466 // OTYPE is the type of the other operand. Return whether the
5467 // operation is OK. This should not be used for shift.
5470 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5476 case OPERATOR_ANDAND:
5477 if (!type->is_boolean_type())
5479 error_at(location, "expected boolean type");
5485 case OPERATOR_NOTEQ:
5488 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5490 error_at(location, "%s", reason.c_str());
5502 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5504 error_at(location, "%s", reason.c_str());
5511 case OPERATOR_PLUSEQ:
5512 if (type->integer_type() == NULL
5513 && type->float_type() == NULL
5514 && type->complex_type() == NULL
5515 && !type->is_string_type())
5518 "expected integer, floating, complex, or string type");
5523 case OPERATOR_MINUS:
5524 case OPERATOR_MINUSEQ:
5526 case OPERATOR_MULTEQ:
5528 case OPERATOR_DIVEQ:
5529 if (type->integer_type() == NULL
5530 && type->float_type() == NULL
5531 && type->complex_type() == NULL)
5533 error_at(location, "expected integer, floating, or complex type");
5539 case OPERATOR_MODEQ:
5543 case OPERATOR_ANDEQ:
5545 case OPERATOR_XOREQ:
5546 case OPERATOR_BITCLEAR:
5547 case OPERATOR_BITCLEAREQ:
5548 if (type->integer_type() == NULL)
5550 error_at(location, "expected integer type");
5565 Binary_expression::do_check_types(Gogo*)
5567 if (this->classification() == EXPRESSION_ERROR)
5570 Type* left_type = this->left_->type();
5571 Type* right_type = this->right_->type();
5572 if (left_type->is_error() || right_type->is_error())
5574 this->set_is_error();
5578 if (this->op_ == OPERATOR_EQEQ
5579 || this->op_ == OPERATOR_NOTEQ
5580 || this->op_ == OPERATOR_LT
5581 || this->op_ == OPERATOR_LE
5582 || this->op_ == OPERATOR_GT
5583 || this->op_ == OPERATOR_GE)
5585 if (!Type::are_assignable(left_type, right_type, NULL)
5586 && !Type::are_assignable(right_type, left_type, NULL))
5588 this->report_error(_("incompatible types in binary expression"));
5591 if (!Binary_expression::check_operator_type(this->op_, left_type,
5594 || !Binary_expression::check_operator_type(this->op_, right_type,
5598 this->set_is_error();
5602 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5604 if (!Type::are_compatible_for_binop(left_type, right_type))
5606 this->report_error(_("incompatible types in binary expression"));
5609 if (!Binary_expression::check_operator_type(this->op_, left_type,
5613 this->set_is_error();
5619 if (left_type->integer_type() == NULL)
5620 this->report_error(_("shift of non-integer operand"));
5622 if (!right_type->is_abstract()
5623 && (right_type->integer_type() == NULL
5624 || !right_type->integer_type()->is_unsigned()))
5625 this->report_error(_("shift count not unsigned integer"));
5628 Numeric_constant nc;
5629 if (this->right_->numeric_constant_value(&nc))
5632 if (!nc.to_int(&val))
5633 this->report_error(_("shift count not unsigned integer"));
5636 if (mpz_sgn(val) < 0)
5638 this->report_error(_("negative shift count"));
5640 Location rloc = this->right_->location();
5641 this->right_ = Expression::make_integer(&val, right_type,
5651 // Get a tree for a binary expression.
5654 Binary_expression::do_get_tree(Translate_context* context)
5656 tree left = this->left_->get_tree(context);
5657 tree right = this->right_->get_tree(context);
5659 if (left == error_mark_node || right == error_mark_node)
5660 return error_mark_node;
5662 enum tree_code code;
5663 bool use_left_type = true;
5664 bool is_shift_op = false;
5665 bool is_idiv_op = false;
5669 case OPERATOR_NOTEQ:
5674 return Expression::comparison_tree(context, this->op_,
5675 this->left_->type(), left,
5676 this->right_->type(), right,
5680 code = TRUTH_ORIF_EXPR;
5681 use_left_type = false;
5683 case OPERATOR_ANDAND:
5684 code = TRUTH_ANDIF_EXPR;
5685 use_left_type = false;
5690 case OPERATOR_MINUS:
5694 code = BIT_IOR_EXPR;
5697 code = BIT_XOR_EXPR;
5704 Type *t = this->left_->type();
5705 if (t->float_type() != NULL || t->complex_type() != NULL)
5709 code = TRUNC_DIV_EXPR;
5715 code = TRUNC_MOD_EXPR;
5718 case OPERATOR_LSHIFT:
5722 case OPERATOR_RSHIFT:
5727 code = BIT_AND_EXPR;
5729 case OPERATOR_BITCLEAR:
5730 right = fold_build1(BIT_NOT_EXPR, TREE_TYPE(right), right);
5731 code = BIT_AND_EXPR;
5737 location_t gccloc = this->location().gcc_location();
5738 tree type = use_left_type ? TREE_TYPE(left) : TREE_TYPE(right);
5740 if (this->left_->type()->is_string_type())
5742 go_assert(this->op_ == OPERATOR_PLUS);
5743 Type* st = Type::make_string_type();
5744 tree string_type = type_to_tree(st->get_backend(context->gogo()));
5745 static tree string_plus_decl;
5746 return Gogo::call_builtin(&string_plus_decl,
5757 tree compute_type = excess_precision_type(type);
5758 if (compute_type != NULL_TREE)
5760 left = ::convert(compute_type, left);
5761 right = ::convert(compute_type, right);
5764 tree eval_saved = NULL_TREE;
5766 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5768 // Make sure the values are evaluated.
5771 left = save_expr(left);
5776 right = save_expr(right);
5777 if (eval_saved == NULL_TREE)
5780 eval_saved = fold_build2_loc(gccloc, COMPOUND_EXPR,
5781 void_type_node, eval_saved, right);
5785 tree ret = fold_build2_loc(gccloc, code,
5786 compute_type != NULL_TREE ? compute_type : type,
5789 if (compute_type != NULL_TREE)
5790 ret = ::convert(type, ret);
5792 // In Go, a shift larger than the size of the type is well-defined.
5793 // This is not true in GENERIC, so we need to insert a conditional.
5796 go_assert(INTEGRAL_TYPE_P(TREE_TYPE(left)));
5797 go_assert(this->left_->type()->integer_type() != NULL);
5798 int bits = TYPE_PRECISION(TREE_TYPE(left));
5800 tree compare = fold_build2(LT_EXPR, boolean_type_node, right,
5801 build_int_cst_type(TREE_TYPE(right), bits));
5803 tree overflow_result = fold_convert_loc(gccloc, TREE_TYPE(left),
5805 if (this->op_ == OPERATOR_RSHIFT
5806 && !this->left_->type()->integer_type()->is_unsigned())
5809 fold_build2_loc(gccloc, LT_EXPR, boolean_type_node,
5811 fold_convert_loc(gccloc, TREE_TYPE(left),
5812 integer_zero_node));
5814 fold_build2_loc(gccloc, MINUS_EXPR, TREE_TYPE(left),
5815 fold_convert_loc(gccloc, TREE_TYPE(left),
5817 fold_convert_loc(gccloc, TREE_TYPE(left),
5820 fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5821 neg, neg_one, overflow_result);
5824 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(left),
5825 compare, ret, overflow_result);
5827 if (eval_saved != NULL_TREE)
5828 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5832 // Add checks for division by zero and division overflow as needed.
5835 if (go_check_divide_zero)
5838 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5840 fold_convert_loc(gccloc,
5842 integer_zero_node));
5844 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO), 0
5845 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5846 tree panic = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5847 Gogo::runtime_error(errcode,
5849 fold_convert_loc(gccloc, TREE_TYPE(ret),
5850 integer_zero_node));
5852 // right == 0 ? (__go_runtime_error(...), 0) : ret
5853 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5857 if (go_check_divide_overflow)
5860 // FIXME: It would be nice to say that this test is expected
5862 tree m1 = integer_minus_one_node;
5863 tree check = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5865 fold_convert_loc(gccloc,
5870 if (TYPE_UNSIGNED(TREE_TYPE(ret)))
5872 // An unsigned -1 is the largest possible number, so
5873 // dividing is always 1 or 0.
5874 tree cmp = fold_build2_loc(gccloc, EQ_EXPR, boolean_type_node,
5876 if (this->op_ == OPERATOR_DIV)
5877 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5879 fold_convert_loc(gccloc,
5882 fold_convert_loc(gccloc,
5884 integer_zero_node));
5886 overflow = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5888 fold_convert_loc(gccloc,
5895 // Computing left / -1 is the same as computing - left,
5896 // which does not overflow since Go sets -fwrapv.
5897 if (this->op_ == OPERATOR_DIV)
5898 overflow = fold_build1_loc(gccloc, NEGATE_EXPR, TREE_TYPE(left),
5901 overflow = integer_zero_node;
5903 overflow = fold_convert_loc(gccloc, TREE_TYPE(ret), overflow);
5905 // right == -1 ? - left : ret
5906 ret = fold_build3_loc(gccloc, COND_EXPR, TREE_TYPE(ret),
5907 check, overflow, ret);
5910 if (eval_saved != NULL_TREE)
5911 ret = fold_build2_loc(gccloc, COMPOUND_EXPR, TREE_TYPE(ret),
5918 // Export a binary expression.
5921 Binary_expression::do_export(Export* exp) const
5923 exp->write_c_string("(");
5924 this->left_->export_expression(exp);
5928 exp->write_c_string(" || ");
5930 case OPERATOR_ANDAND:
5931 exp->write_c_string(" && ");
5934 exp->write_c_string(" == ");
5936 case OPERATOR_NOTEQ:
5937 exp->write_c_string(" != ");
5940 exp->write_c_string(" < ");
5943 exp->write_c_string(" <= ");
5946 exp->write_c_string(" > ");
5949 exp->write_c_string(" >= ");
5952 exp->write_c_string(" + ");
5954 case OPERATOR_MINUS:
5955 exp->write_c_string(" - ");
5958 exp->write_c_string(" | ");
5961 exp->write_c_string(" ^ ");
5964 exp->write_c_string(" * ");
5967 exp->write_c_string(" / ");
5970 exp->write_c_string(" % ");
5972 case OPERATOR_LSHIFT:
5973 exp->write_c_string(" << ");
5975 case OPERATOR_RSHIFT:
5976 exp->write_c_string(" >> ");
5979 exp->write_c_string(" & ");
5981 case OPERATOR_BITCLEAR:
5982 exp->write_c_string(" &^ ");
5987 this->right_->export_expression(exp);
5988 exp->write_c_string(")");
5991 // Import a binary expression.
5994 Binary_expression::do_import(Import* imp)
5996 imp->require_c_string("(");
5998 Expression* left = Expression::import_expression(imp);
6001 if (imp->match_c_string(" || "))
6006 else if (imp->match_c_string(" && "))
6008 op = OPERATOR_ANDAND;
6011 else if (imp->match_c_string(" == "))
6016 else if (imp->match_c_string(" != "))
6018 op = OPERATOR_NOTEQ;
6021 else if (imp->match_c_string(" < "))
6026 else if (imp->match_c_string(" <= "))
6031 else if (imp->match_c_string(" > "))
6036 else if (imp->match_c_string(" >= "))
6041 else if (imp->match_c_string(" + "))
6046 else if (imp->match_c_string(" - "))
6048 op = OPERATOR_MINUS;
6051 else if (imp->match_c_string(" | "))
6056 else if (imp->match_c_string(" ^ "))
6061 else if (imp->match_c_string(" * "))
6066 else if (imp->match_c_string(" / "))
6071 else if (imp->match_c_string(" % "))
6076 else if (imp->match_c_string(" << "))
6078 op = OPERATOR_LSHIFT;
6081 else if (imp->match_c_string(" >> "))
6083 op = OPERATOR_RSHIFT;
6086 else if (imp->match_c_string(" & "))
6091 else if (imp->match_c_string(" &^ "))
6093 op = OPERATOR_BITCLEAR;
6098 error_at(imp->location(), "unrecognized binary operator");
6099 return Expression::make_error(imp->location());
6102 Expression* right = Expression::import_expression(imp);
6104 imp->require_c_string(")");
6106 return Expression::make_binary(op, left, right, imp->location());
6109 // Dump ast representation of a binary expression.
6112 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6114 ast_dump_context->ostream() << "(";
6115 ast_dump_context->dump_expression(this->left_);
6116 ast_dump_context->ostream() << " ";
6117 ast_dump_context->dump_operator(this->op_);
6118 ast_dump_context->ostream() << " ";
6119 ast_dump_context->dump_expression(this->right_);
6120 ast_dump_context->ostream() << ") ";
6123 // Make a binary expression.
6126 Expression::make_binary(Operator op, Expression* left, Expression* right,
6129 return new Binary_expression(op, left, right, location);
6132 // Implement a comparison.
6135 Expression::comparison_tree(Translate_context* context, Operator op,
6136 Type* left_type, tree left_tree,
6137 Type* right_type, tree right_tree,
6140 enum tree_code code;
6146 case OPERATOR_NOTEQ:
6165 if (left_type->is_string_type() && right_type->is_string_type())
6167 Type* st = Type::make_string_type();
6168 tree string_type = type_to_tree(st->get_backend(context->gogo()));
6169 static tree string_compare_decl;
6170 left_tree = Gogo::call_builtin(&string_compare_decl,
6179 right_tree = build_int_cst_type(integer_type_node, 0);
6181 else if ((left_type->interface_type() != NULL
6182 && right_type->interface_type() == NULL
6183 && !right_type->is_nil_type())
6184 || (left_type->interface_type() == NULL
6185 && !left_type->is_nil_type()
6186 && right_type->interface_type() != NULL))
6188 // Comparing an interface value to a non-interface value.
6189 if (left_type->interface_type() == NULL)
6191 std::swap(left_type, right_type);
6192 std::swap(left_tree, right_tree);
6195 // The right operand is not an interface. We need to take its
6196 // address if it is not a pointer.
6199 if (right_type->points_to() != NULL)
6201 make_tmp = NULL_TREE;
6204 else if (TREE_ADDRESSABLE(TREE_TYPE(right_tree))
6205 || (TREE_CODE(right_tree) != CONST_DECL
6206 && DECL_P(right_tree)))
6208 make_tmp = NULL_TREE;
6209 arg = build_fold_addr_expr_loc(location.gcc_location(), right_tree);
6210 if (DECL_P(right_tree))
6211 TREE_ADDRESSABLE(right_tree) = 1;
6215 tree tmp = create_tmp_var(TREE_TYPE(right_tree),
6216 get_name(right_tree));
6217 DECL_IGNORED_P(tmp) = 0;
6218 DECL_INITIAL(tmp) = right_tree;
6219 TREE_ADDRESSABLE(tmp) = 1;
6220 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
6221 SET_EXPR_LOCATION(make_tmp, location.gcc_location());
6222 arg = build_fold_addr_expr_loc(location.gcc_location(), tmp);
6224 arg = fold_convert_loc(location.gcc_location(), ptr_type_node, arg);
6226 tree descriptor = right_type->type_descriptor_pointer(context->gogo(),
6229 if (left_type->interface_type()->is_empty())
6231 static tree empty_interface_value_compare_decl;
6232 left_tree = Gogo::call_builtin(&empty_interface_value_compare_decl,
6234 "__go_empty_interface_value_compare",
6237 TREE_TYPE(left_tree),
6239 TREE_TYPE(descriptor),
6243 if (left_tree == error_mark_node)
6244 return error_mark_node;
6245 // This can panic if the type is not comparable.
6246 TREE_NOTHROW(empty_interface_value_compare_decl) = 0;
6250 static tree interface_value_compare_decl;
6251 left_tree = Gogo::call_builtin(&interface_value_compare_decl,
6253 "__go_interface_value_compare",
6256 TREE_TYPE(left_tree),
6258 TREE_TYPE(descriptor),
6262 if (left_tree == error_mark_node)
6263 return error_mark_node;
6264 // This can panic if the type is not comparable.
6265 TREE_NOTHROW(interface_value_compare_decl) = 0;
6267 right_tree = build_int_cst_type(integer_type_node, 0);
6269 if (make_tmp != NULL_TREE)
6270 left_tree = build2(COMPOUND_EXPR, TREE_TYPE(left_tree), make_tmp,
6273 else if (left_type->interface_type() != NULL
6274 && right_type->interface_type() != NULL)
6276 if (left_type->interface_type()->is_empty()
6277 && right_type->interface_type()->is_empty())
6279 static tree empty_interface_compare_decl;
6280 left_tree = Gogo::call_builtin(&empty_interface_compare_decl,
6282 "__go_empty_interface_compare",
6285 TREE_TYPE(left_tree),
6287 TREE_TYPE(right_tree),
6289 if (left_tree == error_mark_node)
6290 return error_mark_node;
6291 // This can panic if the type is uncomparable.
6292 TREE_NOTHROW(empty_interface_compare_decl) = 0;
6294 else if (!left_type->interface_type()->is_empty()
6295 && !right_type->interface_type()->is_empty())
6297 static tree interface_compare_decl;
6298 left_tree = Gogo::call_builtin(&interface_compare_decl,
6300 "__go_interface_compare",
6303 TREE_TYPE(left_tree),
6305 TREE_TYPE(right_tree),
6307 if (left_tree == error_mark_node)
6308 return error_mark_node;
6309 // This can panic if the type is uncomparable.
6310 TREE_NOTHROW(interface_compare_decl) = 0;
6314 if (left_type->interface_type()->is_empty())
6316 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6317 std::swap(left_type, right_type);
6318 std::swap(left_tree, right_tree);
6320 go_assert(!left_type->interface_type()->is_empty());
6321 go_assert(right_type->interface_type()->is_empty());
6322 static tree interface_empty_compare_decl;
6323 left_tree = Gogo::call_builtin(&interface_empty_compare_decl,
6325 "__go_interface_empty_compare",
6328 TREE_TYPE(left_tree),
6330 TREE_TYPE(right_tree),
6332 if (left_tree == error_mark_node)
6333 return error_mark_node;
6334 // This can panic if the type is uncomparable.
6335 TREE_NOTHROW(interface_empty_compare_decl) = 0;
6338 right_tree = build_int_cst_type(integer_type_node, 0);
6341 if (left_type->is_nil_type()
6342 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6344 std::swap(left_type, right_type);
6345 std::swap(left_tree, right_tree);
6348 if (right_type->is_nil_type())
6350 if (left_type->array_type() != NULL
6351 && left_type->array_type()->length() == NULL)
6353 Array_type* at = left_type->array_type();
6354 left_tree = at->value_pointer_tree(context->gogo(), left_tree);
6355 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6357 else if (left_type->interface_type() != NULL)
6359 // An interface is nil if the first field is nil.
6360 tree left_type_tree = TREE_TYPE(left_tree);
6361 go_assert(TREE_CODE(left_type_tree) == RECORD_TYPE);
6362 tree field = TYPE_FIELDS(left_type_tree);
6363 left_tree = build3(COMPONENT_REF, TREE_TYPE(field), left_tree,
6365 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6369 go_assert(POINTER_TYPE_P(TREE_TYPE(left_tree)));
6370 right_tree = fold_convert(TREE_TYPE(left_tree), null_pointer_node);
6374 if (left_tree == error_mark_node || right_tree == error_mark_node)
6375 return error_mark_node;
6377 tree ret = fold_build2(code, boolean_type_node, left_tree, right_tree);
6378 if (CAN_HAVE_LOCATION_P(ret))
6379 SET_EXPR_LOCATION(ret, location.gcc_location());
6383 // Class Bound_method_expression.
6388 Bound_method_expression::do_traverse(Traverse* traverse)
6390 return Expression::traverse(&this->expr_, traverse);
6393 // Return the type of a bound method expression. The type of this
6394 // object is really the type of the method with no receiver. We
6395 // should be able to get away with just returning the type of the
6399 Bound_method_expression::do_type()
6401 if (this->method_->is_function())
6402 return this->method_->func_value()->type();
6403 else if (this->method_->is_function_declaration())
6404 return this->method_->func_declaration_value()->type();
6406 return Type::make_error_type();
6409 // Determine the types of a method expression.
6412 Bound_method_expression::do_determine_type(const Type_context*)
6414 Function_type* fntype = this->type()->function_type();
6415 if (fntype == NULL || !fntype->is_method())
6416 this->expr_->determine_type_no_context();
6419 Type_context subcontext(fntype->receiver()->type(), false);
6420 this->expr_->determine_type(&subcontext);
6424 // Check the types of a method expression.
6427 Bound_method_expression::do_check_types(Gogo*)
6429 if (!this->method_->is_function()
6430 && !this->method_->is_function_declaration())
6431 this->report_error(_("object is not a method"));
6434 Type* rtype = this->type()->function_type()->receiver()->type()->deref();
6435 Type* etype = (this->expr_type_ != NULL
6437 : this->expr_->type());
6438 etype = etype->deref();
6439 if (!Type::are_identical(rtype, etype, true, NULL))
6440 this->report_error(_("method type does not match object type"));
6444 // Get the tree for a method expression. There is no standard tree
6445 // representation for this. The only places it may currently be used
6446 // are in a Call_expression or a Go_statement, which will take it
6447 // apart directly. So this has nothing to do at present.
6450 Bound_method_expression::do_get_tree(Translate_context*)
6452 error_at(this->location(), "reference to method other than calling it");
6453 return error_mark_node;
6456 // Dump ast representation of a bound method expression.
6459 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6462 if (this->expr_type_ != NULL)
6463 ast_dump_context->ostream() << "(";
6464 ast_dump_context->dump_expression(this->expr_);
6465 if (this->expr_type_ != NULL)
6467 ast_dump_context->ostream() << ":";
6468 ast_dump_context->dump_type(this->expr_type_);
6469 ast_dump_context->ostream() << ")";
6472 ast_dump_context->ostream() << "." << this->method_->name();
6475 // Make a method expression.
6477 Bound_method_expression*
6478 Expression::make_bound_method(Expression* expr, Named_object* method,
6481 return new Bound_method_expression(expr, method, location);
6484 // Class Builtin_call_expression. This is used for a call to a
6485 // builtin function.
6487 class Builtin_call_expression : public Call_expression
6490 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6491 bool is_varargs, Location location);
6494 // This overrides Call_expression::do_lower.
6496 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6499 do_is_constant() const;
6502 do_numeric_constant_value(Numeric_constant*) const;
6505 do_discarding_value();
6511 do_determine_type(const Type_context*);
6514 do_check_types(Gogo*);
6519 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6520 this->args()->copy(),
6526 do_get_tree(Translate_context*);
6529 do_export(Export*) const;
6532 do_is_recover_call() const;
6535 do_set_recover_arg(Expression*);
6538 // The builtin functions.
6539 enum Builtin_function_code
6543 // Predeclared builtin functions.
6560 // Builtin functions from the unsafe package.
6573 real_imag_type(Type*);
6576 complex_type(Type*);
6582 check_int_value(Expression*);
6584 // A pointer back to the general IR structure. This avoids a global
6585 // variable, or passing it around everywhere.
6587 // The builtin function being called.
6588 Builtin_function_code code_;
6589 // Used to stop endless loops when the length of an array uses len
6590 // or cap of the array itself.
6594 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6596 Expression_list* args,
6599 : Call_expression(fn, args, is_varargs, location),
6600 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6602 Func_expression* fnexp = this->fn()->func_expression();
6603 go_assert(fnexp != NULL);
6604 const std::string& name(fnexp->named_object()->name());
6605 if (name == "append")
6606 this->code_ = BUILTIN_APPEND;
6607 else if (name == "cap")
6608 this->code_ = BUILTIN_CAP;
6609 else if (name == "close")
6610 this->code_ = BUILTIN_CLOSE;
6611 else if (name == "complex")
6612 this->code_ = BUILTIN_COMPLEX;
6613 else if (name == "copy")
6614 this->code_ = BUILTIN_COPY;
6615 else if (name == "delete")
6616 this->code_ = BUILTIN_DELETE;
6617 else if (name == "imag")
6618 this->code_ = BUILTIN_IMAG;
6619 else if (name == "len")
6620 this->code_ = BUILTIN_LEN;
6621 else if (name == "make")
6622 this->code_ = BUILTIN_MAKE;
6623 else if (name == "new")
6624 this->code_ = BUILTIN_NEW;
6625 else if (name == "panic")
6626 this->code_ = BUILTIN_PANIC;
6627 else if (name == "print")
6628 this->code_ = BUILTIN_PRINT;
6629 else if (name == "println")
6630 this->code_ = BUILTIN_PRINTLN;
6631 else if (name == "real")
6632 this->code_ = BUILTIN_REAL;
6633 else if (name == "recover")
6634 this->code_ = BUILTIN_RECOVER;
6635 else if (name == "Alignof")
6636 this->code_ = BUILTIN_ALIGNOF;
6637 else if (name == "Offsetof")
6638 this->code_ = BUILTIN_OFFSETOF;
6639 else if (name == "Sizeof")
6640 this->code_ = BUILTIN_SIZEOF;
6645 // Return whether this is a call to recover. This is a virtual
6646 // function called from the parent class.
6649 Builtin_call_expression::do_is_recover_call() const
6651 if (this->classification() == EXPRESSION_ERROR)
6653 return this->code_ == BUILTIN_RECOVER;
6656 // Set the argument for a call to recover.
6659 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6661 const Expression_list* args = this->args();
6662 go_assert(args == NULL || args->empty());
6663 Expression_list* new_args = new Expression_list();
6664 new_args->push_back(arg);
6665 this->set_args(new_args);
6668 // A traversal class which looks for a call expression.
6670 class Find_call_expression : public Traverse
6673 Find_call_expression()
6674 : Traverse(traverse_expressions),
6679 expression(Expression**);
6683 { return this->found_; }
6690 Find_call_expression::expression(Expression** pexpr)
6692 if ((*pexpr)->call_expression() != NULL)
6694 this->found_ = true;
6695 return TRAVERSE_EXIT;
6697 return TRAVERSE_CONTINUE;
6700 // Lower a builtin call expression. This turns new and make into
6701 // specific expressions. We also convert to a constant if we can.
6704 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6705 Statement_inserter* inserter, int)
6707 if (this->classification() == EXPRESSION_ERROR)
6710 Location loc = this->location();
6712 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6714 this->report_error(_("invalid use of %<...%> with builtin function"));
6715 return Expression::make_error(loc);
6718 if (this->is_constant())
6720 // We can only lower len and cap if there are no function calls
6721 // in the arguments. Otherwise we have to make the call.
6722 if (this->code_ == BUILTIN_LEN || this->code_ == BUILTIN_CAP)
6724 Expression* arg = this->one_arg();
6725 if (arg != NULL && !arg->is_constant())
6727 Find_call_expression find_call;
6728 Expression::traverse(&arg, &find_call);
6729 if (find_call.found())
6734 Numeric_constant nc;
6735 if (this->numeric_constant_value(&nc))
6736 return nc.expression(loc);
6739 switch (this->code_)
6746 const Expression_list* args = this->args();
6747 if (args == NULL || args->size() < 1)
6748 this->report_error(_("not enough arguments"));
6749 else if (args->size() > 1)
6750 this->report_error(_("too many arguments"));
6753 Expression* arg = args->front();
6754 if (!arg->is_type_expression())
6756 error_at(arg->location(), "expected type");
6757 this->set_is_error();
6760 return Expression::make_allocation(arg->type(), loc);
6766 return this->lower_make();
6768 case BUILTIN_RECOVER:
6769 if (function != NULL)
6770 function->func_value()->set_calls_recover();
6773 // Calling recover outside of a function always returns the
6774 // nil empty interface.
6775 Type* eface = Type::make_empty_interface_type(loc);
6776 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6780 case BUILTIN_APPEND:
6782 // Lower the varargs.
6783 const Expression_list* args = this->args();
6784 if (args == NULL || args->empty())
6786 Type* slice_type = args->front()->type();
6787 if (!slice_type->is_slice_type())
6789 error_at(args->front()->location(), "argument 1 must be a slice");
6790 this->set_is_error();
6793 Type* element_type = slice_type->array_type()->element_type();
6794 this->lower_varargs(gogo, function, inserter,
6795 Type::make_array_type(element_type, NULL),
6800 case BUILTIN_DELETE:
6802 // Lower to a runtime function call.
6803 const Expression_list* args = this->args();
6804 if (args == NULL || args->size() < 2)
6805 this->report_error(_("not enough arguments"));
6806 else if (args->size() > 2)
6807 this->report_error(_("too many arguments"));
6808 else if (args->front()->type()->map_type() == NULL)
6809 this->report_error(_("argument 1 must be a map"));
6812 // Since this function returns no value it must appear in
6813 // a statement by itself, so we don't have to worry about
6814 // order of evaluation of values around it. Evaluate the
6815 // map first to get order of evaluation right.
6816 Map_type* mt = args->front()->type()->map_type();
6817 Temporary_statement* map_temp =
6818 Statement::make_temporary(mt, args->front(), loc);
6819 inserter->insert(map_temp);
6821 Temporary_statement* key_temp =
6822 Statement::make_temporary(mt->key_type(), args->back(), loc);
6823 inserter->insert(key_temp);
6825 Expression* e1 = Expression::make_temporary_reference(map_temp,
6827 Expression* e2 = Expression::make_temporary_reference(key_temp,
6829 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6830 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6840 // Lower a make expression.
6843 Builtin_call_expression::lower_make()
6845 Location loc = this->location();
6847 const Expression_list* args = this->args();
6848 if (args == NULL || args->size() < 1)
6850 this->report_error(_("not enough arguments"));
6851 return Expression::make_error(this->location());
6854 Expression_list::const_iterator parg = args->begin();
6856 Expression* first_arg = *parg;
6857 if (!first_arg->is_type_expression())
6859 error_at(first_arg->location(), "expected type");
6860 this->set_is_error();
6861 return Expression::make_error(this->location());
6863 Type* type = first_arg->type();
6865 bool is_slice = false;
6866 bool is_map = false;
6867 bool is_chan = false;
6868 if (type->is_slice_type())
6870 else if (type->map_type() != NULL)
6872 else if (type->channel_type() != NULL)
6876 this->report_error(_("invalid type for make function"));
6877 return Expression::make_error(this->location());
6880 bool have_big_args = false;
6881 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6882 int uintptr_bits = uintptr_type->integer_type()->bits();
6885 Expression* len_arg;
6886 if (parg == args->end())
6890 this->report_error(_("length required when allocating a slice"));
6891 return Expression::make_error(this->location());
6895 mpz_init_set_ui(zval, 0);
6896 len_arg = Expression::make_integer(&zval, NULL, loc);
6902 if (!this->check_int_value(len_arg))
6904 this->report_error(_("bad size for make"));
6905 return Expression::make_error(this->location());
6907 if (len_arg->type()->integer_type() != NULL
6908 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6909 have_big_args = true;
6913 Expression* cap_arg = NULL;
6914 if (is_slice && parg != args->end())
6917 if (!this->check_int_value(cap_arg))
6919 this->report_error(_("bad capacity when making slice"));
6920 return Expression::make_error(this->location());
6922 if (cap_arg->type()->integer_type() != NULL
6923 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6924 have_big_args = true;
6928 if (parg != args->end())
6930 this->report_error(_("too many arguments to make"));
6931 return Expression::make_error(this->location());
6934 Location type_loc = first_arg->location();
6935 Expression* type_arg;
6936 if (is_slice || is_chan)
6937 type_arg = Expression::make_type_descriptor(type, type_loc);
6939 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6946 if (cap_arg == NULL)
6947 call = Runtime::make_call((have_big_args
6948 ? Runtime::MAKESLICE1BIG
6949 : Runtime::MAKESLICE1),
6950 loc, 2, type_arg, len_arg);
6952 call = Runtime::make_call((have_big_args
6953 ? Runtime::MAKESLICE2BIG
6954 : Runtime::MAKESLICE2),
6955 loc, 3, type_arg, len_arg, cap_arg);
6958 call = Runtime::make_call((have_big_args
6959 ? Runtime::MAKEMAPBIG
6960 : Runtime::MAKEMAP),
6961 loc, 2, type_arg, len_arg);
6963 call = Runtime::make_call((have_big_args
6964 ? Runtime::MAKECHANBIG
6965 : Runtime::MAKECHAN),
6966 loc, 2, type_arg, len_arg);
6970 return Expression::make_unsafe_cast(type, call, loc);
6973 // Return whether an expression has an integer value. Report an error
6974 // if not. This is used when handling calls to the predeclared make
6978 Builtin_call_expression::check_int_value(Expression* e)
6980 if (e->type()->integer_type() != NULL)
6983 // Check for a floating point constant with integer value.
6984 Numeric_constant nc;
6986 if (e->numeric_constant_value(&nc) && nc.to_int(&ival))
6995 // Return the type of the real or imag functions, given the type of
6996 // the argument. We need to map complex to float, complex64 to
6997 // float32, and complex128 to float64, so it has to be done by name.
6998 // This returns NULL if it can't figure out the type.
7001 Builtin_call_expression::real_imag_type(Type* arg_type)
7003 if (arg_type == NULL || arg_type->is_abstract())
7005 Named_type* nt = arg_type->named_type();
7008 while (nt->real_type()->named_type() != NULL)
7009 nt = nt->real_type()->named_type();
7010 if (nt->name() == "complex64")
7011 return Type::lookup_float_type("float32");
7012 else if (nt->name() == "complex128")
7013 return Type::lookup_float_type("float64");
7018 // Return the type of the complex function, given the type of one of the
7019 // argments. Like real_imag_type, we have to map by name.
7022 Builtin_call_expression::complex_type(Type* arg_type)
7024 if (arg_type == NULL || arg_type->is_abstract())
7026 Named_type* nt = arg_type->named_type();
7029 while (nt->real_type()->named_type() != NULL)
7030 nt = nt->real_type()->named_type();
7031 if (nt->name() == "float32")
7032 return Type::lookup_complex_type("complex64");
7033 else if (nt->name() == "float64")
7034 return Type::lookup_complex_type("complex128");
7039 // Return a single argument, or NULL if there isn't one.
7042 Builtin_call_expression::one_arg() const
7044 const Expression_list* args = this->args();
7045 if (args == NULL || args->size() != 1)
7047 return args->front();
7050 // Return whether this is constant: len of a string, or len or cap of
7051 // a fixed array, or unsafe.Sizeof, unsafe.Offsetof, unsafe.Alignof.
7054 Builtin_call_expression::do_is_constant() const
7056 switch (this->code_)
7064 Expression* arg = this->one_arg();
7067 Type* arg_type = arg->type();
7069 if (arg_type->points_to() != NULL
7070 && arg_type->points_to()->array_type() != NULL
7071 && !arg_type->points_to()->is_slice_type())
7072 arg_type = arg_type->points_to();
7074 if (arg_type->array_type() != NULL
7075 && arg_type->array_type()->length() != NULL)
7078 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7081 bool ret = arg->is_constant();
7082 this->seen_ = false;
7088 case BUILTIN_SIZEOF:
7089 case BUILTIN_ALIGNOF:
7090 return this->one_arg() != NULL;
7092 case BUILTIN_OFFSETOF:
7094 Expression* arg = this->one_arg();
7097 return arg->field_reference_expression() != NULL;
7100 case BUILTIN_COMPLEX:
7102 const Expression_list* args = this->args();
7103 if (args != NULL && args->size() == 2)
7104 return args->front()->is_constant() && args->back()->is_constant();
7111 Expression* arg = this->one_arg();
7112 return arg != NULL && arg->is_constant();
7122 // Return a numeric constant if possible.
7125 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7127 if (this->code_ == BUILTIN_LEN
7128 || this->code_ == BUILTIN_CAP)
7130 Expression* arg = this->one_arg();
7133 Type* arg_type = arg->type();
7135 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7138 if (arg->string_constant_value(&sval))
7140 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7146 if (arg_type->points_to() != NULL
7147 && arg_type->points_to()->array_type() != NULL
7148 && !arg_type->points_to()->is_slice_type())
7149 arg_type = arg_type->points_to();
7151 if (arg_type->array_type() != NULL
7152 && arg_type->array_type()->length() != NULL)
7156 Expression* e = arg_type->array_type()->length();
7158 bool r = e->numeric_constant_value(nc);
7159 this->seen_ = false;
7162 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7169 else if (this->code_ == BUILTIN_SIZEOF
7170 || this->code_ == BUILTIN_ALIGNOF)
7172 Expression* arg = this->one_arg();
7175 Type* arg_type = arg->type();
7176 if (arg_type->is_error())
7178 if (arg_type->is_abstract())
7180 if (arg_type->named_type() != NULL)
7181 arg_type->named_type()->convert(this->gogo_);
7184 if (this->code_ == BUILTIN_SIZEOF)
7186 if (!arg_type->backend_type_size(this->gogo_, &ret))
7189 else if (this->code_ == BUILTIN_ALIGNOF)
7191 if (arg->field_reference_expression() == NULL)
7193 if (!arg_type->backend_type_align(this->gogo_, &ret))
7198 // Calling unsafe.Alignof(s.f) returns the alignment of
7199 // the type of f when it is used as a field in a struct.
7200 if (!arg_type->backend_type_field_align(this->gogo_, &ret))
7207 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7208 static_cast<unsigned long>(ret));
7211 else if (this->code_ == BUILTIN_OFFSETOF)
7213 Expression* arg = this->one_arg();
7216 Field_reference_expression* farg = arg->field_reference_expression();
7219 Expression* struct_expr = farg->expr();
7220 Type* st = struct_expr->type();
7221 if (st->struct_type() == NULL)
7223 if (st->named_type() != NULL)
7224 st->named_type()->convert(this->gogo_);
7225 unsigned int offset;
7226 if (!st->struct_type()->backend_field_offset(this->gogo_,
7227 farg->field_index(),
7230 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7231 static_cast<unsigned long>(offset));
7234 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7236 Expression* arg = this->one_arg();
7240 Numeric_constant argnc;
7241 if (!arg->numeric_constant_value(&argnc))
7246 if (!argnc.to_complex(&real, &imag))
7249 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7250 if (this->code_ == BUILTIN_REAL)
7251 nc->set_float(type, real);
7253 nc->set_float(type, imag);
7256 else if (this->code_ == BUILTIN_COMPLEX)
7258 const Expression_list* args = this->args();
7259 if (args == NULL || args->size() != 2)
7262 Numeric_constant rnc;
7263 if (!args->front()->numeric_constant_value(&rnc))
7265 Numeric_constant inc;
7266 if (!args->back()->numeric_constant_value(&inc))
7269 if (rnc.type() != NULL
7270 && !rnc.type()->is_abstract()
7271 && inc.type() != NULL
7272 && !inc.type()->is_abstract()
7273 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7277 if (!rnc.to_float(&r))
7280 if (!inc.to_float(&i))
7286 Type* arg_type = rnc.type();
7287 if (arg_type == NULL || arg_type->is_abstract())
7288 arg_type = inc.type();
7290 Type* type = Builtin_call_expression::complex_type(arg_type);
7291 nc->set_complex(type, r, i);
7302 // Give an error if we are discarding the value of an expression which
7303 // should not normally be discarded. We don't give an error for
7304 // discarding the value of an ordinary function call, but we do for
7305 // builtin functions, purely for consistency with the gc compiler.
7308 Builtin_call_expression::do_discarding_value()
7310 switch (this->code_)
7312 case BUILTIN_INVALID:
7316 case BUILTIN_APPEND:
7318 case BUILTIN_COMPLEX:
7324 case BUILTIN_ALIGNOF:
7325 case BUILTIN_OFFSETOF:
7326 case BUILTIN_SIZEOF:
7327 this->unused_value_error();
7332 case BUILTIN_DELETE:
7335 case BUILTIN_PRINTLN:
7336 case BUILTIN_RECOVER:
7344 Builtin_call_expression::do_type()
7346 switch (this->code_)
7348 case BUILTIN_INVALID:
7355 const Expression_list* args = this->args();
7356 if (args == NULL || args->empty())
7357 return Type::make_error_type();
7358 return Type::make_pointer_type(args->front()->type());
7364 return Type::lookup_integer_type("int");
7366 case BUILTIN_ALIGNOF:
7367 case BUILTIN_OFFSETOF:
7368 case BUILTIN_SIZEOF:
7369 return Type::lookup_integer_type("uintptr");
7372 case BUILTIN_DELETE:
7375 case BUILTIN_PRINTLN:
7376 return Type::make_void_type();
7378 case BUILTIN_RECOVER:
7379 return Type::make_empty_interface_type(Linemap::predeclared_location());
7381 case BUILTIN_APPEND:
7383 const Expression_list* args = this->args();
7384 if (args == NULL || args->empty())
7385 return Type::make_error_type();
7386 return args->front()->type();
7392 Expression* arg = this->one_arg();
7394 return Type::make_error_type();
7395 Type* t = arg->type();
7396 if (t->is_abstract())
7397 t = t->make_non_abstract_type();
7398 t = Builtin_call_expression::real_imag_type(t);
7400 t = Type::make_error_type();
7404 case BUILTIN_COMPLEX:
7406 const Expression_list* args = this->args();
7407 if (args == NULL || args->size() != 2)
7408 return Type::make_error_type();
7409 Type* t = args->front()->type();
7410 if (t->is_abstract())
7412 t = args->back()->type();
7413 if (t->is_abstract())
7414 t = t->make_non_abstract_type();
7416 t = Builtin_call_expression::complex_type(t);
7418 t = Type::make_error_type();
7424 // Determine the type.
7427 Builtin_call_expression::do_determine_type(const Type_context* context)
7429 if (!this->determining_types())
7432 this->fn()->determine_type_no_context();
7434 const Expression_list* args = this->args();
7437 Type* arg_type = NULL;
7438 switch (this->code_)
7441 case BUILTIN_PRINTLN:
7442 // Do not force a large integer constant to "int".
7448 arg_type = Builtin_call_expression::complex_type(context->type);
7452 case BUILTIN_COMPLEX:
7454 // For the complex function the type of one operand can
7455 // determine the type of the other, as in a binary expression.
7456 arg_type = Builtin_call_expression::real_imag_type(context->type);
7457 if (args != NULL && args->size() == 2)
7459 Type* t1 = args->front()->type();
7460 Type* t2 = args->front()->type();
7461 if (!t1->is_abstract())
7463 else if (!t2->is_abstract())
7477 for (Expression_list::const_iterator pa = args->begin();
7481 Type_context subcontext;
7482 subcontext.type = arg_type;
7486 // We want to print large constants, we so can't just
7487 // use the appropriate nonabstract type. Use uint64 for
7488 // an integer if we know it is nonnegative, otherwise
7489 // use int64 for a integer, otherwise use float64 for a
7490 // float or complex128 for a complex.
7491 Type* want_type = NULL;
7492 Type* atype = (*pa)->type();
7493 if (atype->is_abstract())
7495 if (atype->integer_type() != NULL)
7497 Numeric_constant nc;
7498 if (this->numeric_constant_value(&nc))
7501 if (nc.to_int(&val))
7503 if (mpz_sgn(val) >= 0)
7504 want_type = Type::lookup_integer_type("uint64");
7508 if (want_type == NULL)
7509 want_type = Type::lookup_integer_type("int64");
7511 else if (atype->float_type() != NULL)
7512 want_type = Type::lookup_float_type("float64");
7513 else if (atype->complex_type() != NULL)
7514 want_type = Type::lookup_complex_type("complex128");
7515 else if (atype->is_abstract_string_type())
7516 want_type = Type::lookup_string_type();
7517 else if (atype->is_abstract_boolean_type())
7518 want_type = Type::lookup_bool_type();
7521 subcontext.type = want_type;
7525 (*pa)->determine_type(&subcontext);
7530 // If there is exactly one argument, return true. Otherwise give an
7531 // error message and return false.
7534 Builtin_call_expression::check_one_arg()
7536 const Expression_list* args = this->args();
7537 if (args == NULL || args->size() < 1)
7539 this->report_error(_("not enough arguments"));
7542 else if (args->size() > 1)
7544 this->report_error(_("too many arguments"));
7547 if (args->front()->is_error_expression()
7548 || args->front()->type()->is_error())
7550 this->set_is_error();
7556 // Check argument types for a builtin function.
7559 Builtin_call_expression::do_check_types(Gogo*)
7561 if (this->is_error_expression())
7563 switch (this->code_)
7565 case BUILTIN_INVALID:
7568 case BUILTIN_DELETE:
7574 // The single argument may be either a string or an array or a
7575 // map or a channel, or a pointer to a closed array.
7576 if (this->check_one_arg())
7578 Type* arg_type = this->one_arg()->type();
7579 if (arg_type->points_to() != NULL
7580 && arg_type->points_to()->array_type() != NULL
7581 && !arg_type->points_to()->is_slice_type())
7582 arg_type = arg_type->points_to();
7583 if (this->code_ == BUILTIN_CAP)
7585 if (!arg_type->is_error()
7586 && arg_type->array_type() == NULL
7587 && arg_type->channel_type() == NULL)
7588 this->report_error(_("argument must be array or slice "
7593 if (!arg_type->is_error()
7594 && !arg_type->is_string_type()
7595 && arg_type->array_type() == NULL
7596 && arg_type->map_type() == NULL
7597 && arg_type->channel_type() == NULL)
7598 this->report_error(_("argument must be string or "
7599 "array or slice or map or channel"));
7606 case BUILTIN_PRINTLN:
7608 const Expression_list* args = this->args();
7611 if (this->code_ == BUILTIN_PRINT)
7612 warning_at(this->location(), 0,
7613 "no arguments for builtin function %<%s%>",
7614 (this->code_ == BUILTIN_PRINT
7620 for (Expression_list::const_iterator p = args->begin();
7624 Type* type = (*p)->type();
7625 if (type->is_error()
7626 || type->is_string_type()
7627 || type->integer_type() != NULL
7628 || type->float_type() != NULL
7629 || type->complex_type() != NULL
7630 || type->is_boolean_type()
7631 || type->points_to() != NULL
7632 || type->interface_type() != NULL
7633 || type->channel_type() != NULL
7634 || type->map_type() != NULL
7635 || type->function_type() != NULL
7636 || type->is_slice_type())
7638 else if ((*p)->is_type_expression())
7640 // If this is a type expression it's going to give
7641 // an error anyhow, so we don't need one here.
7644 this->report_error(_("unsupported argument type to "
7645 "builtin function"));
7652 if (this->check_one_arg())
7654 if (this->one_arg()->type()->channel_type() == NULL)
7655 this->report_error(_("argument must be channel"));
7656 else if (!this->one_arg()->type()->channel_type()->may_send())
7657 this->report_error(_("cannot close receive-only channel"));
7662 case BUILTIN_SIZEOF:
7663 case BUILTIN_ALIGNOF:
7664 this->check_one_arg();
7667 case BUILTIN_RECOVER:
7668 if (this->args() != NULL && !this->args()->empty())
7669 this->report_error(_("too many arguments"));
7672 case BUILTIN_OFFSETOF:
7673 if (this->check_one_arg())
7675 Expression* arg = this->one_arg();
7676 if (arg->field_reference_expression() == NULL)
7677 this->report_error(_("argument must be a field reference"));
7683 const Expression_list* args = this->args();
7684 if (args == NULL || args->size() < 2)
7686 this->report_error(_("not enough arguments"));
7689 else if (args->size() > 2)
7691 this->report_error(_("too many arguments"));
7694 Type* arg1_type = args->front()->type();
7695 Type* arg2_type = args->back()->type();
7696 if (arg1_type->is_error() || arg2_type->is_error())
7700 if (arg1_type->is_slice_type())
7701 e1 = arg1_type->array_type()->element_type();
7704 this->report_error(_("left argument must be a slice"));
7708 if (arg2_type->is_slice_type())
7710 Type* e2 = arg2_type->array_type()->element_type();
7711 if (!Type::are_identical(e1, e2, true, NULL))
7712 this->report_error(_("element types must be the same"));
7714 else if (arg2_type->is_string_type())
7716 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7717 this->report_error(_("first argument must be []byte"));
7720 this->report_error(_("second argument must be slice or string"));
7724 case BUILTIN_APPEND:
7726 const Expression_list* args = this->args();
7727 if (args == NULL || args->size() < 2)
7729 this->report_error(_("not enough arguments"));
7732 if (args->size() > 2)
7734 this->report_error(_("too many arguments"));
7737 if (args->front()->type()->is_error()
7738 || args->back()->type()->is_error())
7741 Array_type* at = args->front()->type()->array_type();
7742 Type* e = at->element_type();
7744 // The language permits appending a string to a []byte, as a
7746 if (args->back()->type()->is_string_type())
7748 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7752 // The language says that the second argument must be
7753 // assignable to a slice of the element type of the first
7754 // argument. We already know the first argument is a slice
7756 Type* arg2_type = Type::make_array_type(e, NULL);
7758 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7761 this->report_error(_("argument 2 has invalid type"));
7764 error_at(this->location(), "argument 2 has invalid type (%s)",
7766 this->set_is_error();
7774 if (this->check_one_arg())
7776 if (this->one_arg()->type()->complex_type() == NULL)
7777 this->report_error(_("argument must have complex type"));
7781 case BUILTIN_COMPLEX:
7783 const Expression_list* args = this->args();
7784 if (args == NULL || args->size() < 2)
7785 this->report_error(_("not enough arguments"));
7786 else if (args->size() > 2)
7787 this->report_error(_("too many arguments"));
7788 else if (args->front()->is_error_expression()
7789 || args->front()->type()->is_error()
7790 || args->back()->is_error_expression()
7791 || args->back()->type()->is_error())
7792 this->set_is_error();
7793 else if (!Type::are_identical(args->front()->type(),
7794 args->back()->type(), true, NULL))
7795 this->report_error(_("complex arguments must have identical types"));
7796 else if (args->front()->type()->float_type() == NULL)
7797 this->report_error(_("complex arguments must have "
7798 "floating-point type"));
7807 // Return the tree for a builtin function.
7810 Builtin_call_expression::do_get_tree(Translate_context* context)
7812 Gogo* gogo = context->gogo();
7813 Location location = this->location();
7814 switch (this->code_)
7816 case BUILTIN_INVALID:
7824 const Expression_list* args = this->args();
7825 go_assert(args != NULL && args->size() == 1);
7826 Expression* arg = *args->begin();
7827 Type* arg_type = arg->type();
7831 go_assert(saw_errors());
7832 return error_mark_node;
7836 tree arg_tree = arg->get_tree(context);
7838 this->seen_ = false;
7840 if (arg_tree == error_mark_node)
7841 return error_mark_node;
7843 if (arg_type->points_to() != NULL)
7845 arg_type = arg_type->points_to();
7846 go_assert(arg_type->array_type() != NULL
7847 && !arg_type->is_slice_type());
7848 go_assert(POINTER_TYPE_P(TREE_TYPE(arg_tree)));
7849 arg_tree = build_fold_indirect_ref(arg_tree);
7853 if (this->code_ == BUILTIN_LEN)
7855 if (arg_type->is_string_type())
7856 val_tree = String_type::length_tree(gogo, arg_tree);
7857 else if (arg_type->array_type() != NULL)
7861 go_assert(saw_errors());
7862 return error_mark_node;
7865 val_tree = arg_type->array_type()->length_tree(gogo, arg_tree);
7866 this->seen_ = false;
7868 else if (arg_type->map_type() != NULL)
7870 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7871 static tree map_len_fndecl;
7872 val_tree = Gogo::call_builtin(&map_len_fndecl,
7880 else if (arg_type->channel_type() != NULL)
7882 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7883 static tree chan_len_fndecl;
7884 val_tree = Gogo::call_builtin(&chan_len_fndecl,
7897 if (arg_type->array_type() != NULL)
7901 go_assert(saw_errors());
7902 return error_mark_node;
7905 val_tree = arg_type->array_type()->capacity_tree(gogo,
7907 this->seen_ = false;
7909 else if (arg_type->channel_type() != NULL)
7911 tree arg_type_tree = type_to_tree(arg_type->get_backend(gogo));
7912 static tree chan_cap_fndecl;
7913 val_tree = Gogo::call_builtin(&chan_cap_fndecl,
7925 if (val_tree == error_mark_node)
7926 return error_mark_node;
7928 Type* int_type = Type::lookup_integer_type("int");
7929 tree type_tree = type_to_tree(int_type->get_backend(gogo));
7930 if (type_tree == TREE_TYPE(val_tree))
7933 return fold(convert_to_integer(type_tree, val_tree));
7937 case BUILTIN_PRINTLN:
7939 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
7940 tree stmt_list = NULL_TREE;
7942 const Expression_list* call_args = this->args();
7943 if (call_args != NULL)
7945 for (Expression_list::const_iterator p = call_args->begin();
7946 p != call_args->end();
7949 if (is_ln && p != call_args->begin())
7951 static tree print_space_fndecl;
7952 tree call = Gogo::call_builtin(&print_space_fndecl,
7957 if (call == error_mark_node)
7958 return error_mark_node;
7959 append_to_statement_list(call, &stmt_list);
7962 Type* type = (*p)->type();
7964 tree arg = (*p)->get_tree(context);
7965 if (arg == error_mark_node)
7966 return error_mark_node;
7970 if (type->is_string_type())
7972 static tree print_string_fndecl;
7973 pfndecl = &print_string_fndecl;
7974 fnname = "__go_print_string";
7976 else if (type->integer_type() != NULL
7977 && type->integer_type()->is_unsigned())
7979 static tree print_uint64_fndecl;
7980 pfndecl = &print_uint64_fndecl;
7981 fnname = "__go_print_uint64";
7982 Type* itype = Type::lookup_integer_type("uint64");
7983 Btype* bitype = itype->get_backend(gogo);
7984 arg = fold_convert_loc(location.gcc_location(),
7985 type_to_tree(bitype), arg);
7987 else if (type->integer_type() != NULL)
7989 static tree print_int64_fndecl;
7990 pfndecl = &print_int64_fndecl;
7991 fnname = "__go_print_int64";
7992 Type* itype = Type::lookup_integer_type("int64");
7993 Btype* bitype = itype->get_backend(gogo);
7994 arg = fold_convert_loc(location.gcc_location(),
7995 type_to_tree(bitype), arg);
7997 else if (type->float_type() != NULL)
7999 static tree print_double_fndecl;
8000 pfndecl = &print_double_fndecl;
8001 fnname = "__go_print_double";
8002 arg = fold_convert_loc(location.gcc_location(),
8003 double_type_node, arg);
8005 else if (type->complex_type() != NULL)
8007 static tree print_complex_fndecl;
8008 pfndecl = &print_complex_fndecl;
8009 fnname = "__go_print_complex";
8010 arg = fold_convert_loc(location.gcc_location(),
8011 complex_double_type_node, arg);
8013 else if (type->is_boolean_type())
8015 static tree print_bool_fndecl;
8016 pfndecl = &print_bool_fndecl;
8017 fnname = "__go_print_bool";
8019 else if (type->points_to() != NULL
8020 || type->channel_type() != NULL
8021 || type->map_type() != NULL
8022 || type->function_type() != NULL)
8024 static tree print_pointer_fndecl;
8025 pfndecl = &print_pointer_fndecl;
8026 fnname = "__go_print_pointer";
8027 arg = fold_convert_loc(location.gcc_location(),
8028 ptr_type_node, arg);
8030 else if (type->interface_type() != NULL)
8032 if (type->interface_type()->is_empty())
8034 static tree print_empty_interface_fndecl;
8035 pfndecl = &print_empty_interface_fndecl;
8036 fnname = "__go_print_empty_interface";
8040 static tree print_interface_fndecl;
8041 pfndecl = &print_interface_fndecl;
8042 fnname = "__go_print_interface";
8045 else if (type->is_slice_type())
8047 static tree print_slice_fndecl;
8048 pfndecl = &print_slice_fndecl;
8049 fnname = "__go_print_slice";
8053 go_assert(saw_errors());
8054 return error_mark_node;
8057 tree call = Gogo::call_builtin(pfndecl,
8064 if (call == error_mark_node)
8065 return error_mark_node;
8066 append_to_statement_list(call, &stmt_list);
8072 static tree print_nl_fndecl;
8073 tree call = Gogo::call_builtin(&print_nl_fndecl,
8078 if (call == error_mark_node)
8079 return error_mark_node;
8080 append_to_statement_list(call, &stmt_list);
8088 const Expression_list* args = this->args();
8089 go_assert(args != NULL && args->size() == 1);
8090 Expression* arg = args->front();
8091 tree arg_tree = arg->get_tree(context);
8092 if (arg_tree == error_mark_node)
8093 return error_mark_node;
8095 Type::make_empty_interface_type(Linemap::predeclared_location());
8096 arg_tree = Expression::convert_for_assignment(context, empty,
8098 arg_tree, location);
8099 static tree panic_fndecl;
8100 tree call = Gogo::call_builtin(&panic_fndecl,
8105 TREE_TYPE(arg_tree),
8107 if (call == error_mark_node)
8108 return error_mark_node;
8109 // This function will throw an exception.
8110 TREE_NOTHROW(panic_fndecl) = 0;
8111 // This function will not return.
8112 TREE_THIS_VOLATILE(panic_fndecl) = 1;
8116 case BUILTIN_RECOVER:
8118 // The argument is set when building recover thunks. It's a
8119 // boolean value which is true if we can recover a value now.
8120 const Expression_list* args = this->args();
8121 go_assert(args != NULL && args->size() == 1);
8122 Expression* arg = args->front();
8123 tree arg_tree = arg->get_tree(context);
8124 if (arg_tree == error_mark_node)
8125 return error_mark_node;
8128 Type::make_empty_interface_type(Linemap::predeclared_location());
8129 tree empty_tree = type_to_tree(empty->get_backend(context->gogo()));
8131 Type* nil_type = Type::make_nil_type();
8132 Expression* nil = Expression::make_nil(location);
8133 tree nil_tree = nil->get_tree(context);
8134 tree empty_nil_tree = Expression::convert_for_assignment(context,
8140 // We need to handle a deferred call to recover specially,
8141 // because it changes whether it can recover a panic or not.
8142 // See test7 in test/recover1.go.
8144 if (this->is_deferred())
8146 static tree deferred_recover_fndecl;
8147 call = Gogo::call_builtin(&deferred_recover_fndecl,
8149 "__go_deferred_recover",
8155 static tree recover_fndecl;
8156 call = Gogo::call_builtin(&recover_fndecl,
8162 if (call == error_mark_node)
8163 return error_mark_node;
8164 return fold_build3_loc(location.gcc_location(), COND_EXPR, empty_tree,
8165 arg_tree, call, empty_nil_tree);
8170 const Expression_list* args = this->args();
8171 go_assert(args != NULL && args->size() == 1);
8172 Expression* arg = args->front();
8173 tree arg_tree = arg->get_tree(context);
8174 if (arg_tree == error_mark_node)
8175 return error_mark_node;
8176 static tree close_fndecl;
8177 return Gogo::call_builtin(&close_fndecl,
8179 "__go_builtin_close",
8182 TREE_TYPE(arg_tree),
8186 case BUILTIN_SIZEOF:
8187 case BUILTIN_OFFSETOF:
8188 case BUILTIN_ALIGNOF:
8190 Numeric_constant nc;
8192 if (!this->numeric_constant_value(&nc)
8193 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8195 go_assert(saw_errors());
8196 return error_mark_node;
8198 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8199 tree type = type_to_tree(uintptr_type->get_backend(gogo));
8200 return build_int_cst(type, val);
8205 const Expression_list* args = this->args();
8206 go_assert(args != NULL && args->size() == 2);
8207 Expression* arg1 = args->front();
8208 Expression* arg2 = args->back();
8210 tree arg1_tree = arg1->get_tree(context);
8211 tree arg2_tree = arg2->get_tree(context);
8212 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8213 return error_mark_node;
8215 Type* arg1_type = arg1->type();
8216 Array_type* at = arg1_type->array_type();
8217 arg1_tree = save_expr(arg1_tree);
8218 tree arg1_val = at->value_pointer_tree(gogo, arg1_tree);
8219 tree arg1_len = at->length_tree(gogo, arg1_tree);
8220 if (arg1_val == error_mark_node || arg1_len == error_mark_node)
8221 return error_mark_node;
8223 Type* arg2_type = arg2->type();
8226 if (arg2_type->is_slice_type())
8228 at = arg2_type->array_type();
8229 arg2_tree = save_expr(arg2_tree);
8230 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8231 arg2_len = at->length_tree(gogo, arg2_tree);
8235 arg2_tree = save_expr(arg2_tree);
8236 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8237 arg2_len = String_type::length_tree(gogo, arg2_tree);
8239 if (arg2_val == error_mark_node || arg2_len == error_mark_node)
8240 return error_mark_node;
8242 arg1_len = save_expr(arg1_len);
8243 arg2_len = save_expr(arg2_len);
8244 tree len = fold_build3_loc(location.gcc_location(), COND_EXPR,
8245 TREE_TYPE(arg1_len),
8246 fold_build2_loc(location.gcc_location(),
8247 LT_EXPR, boolean_type_node,
8248 arg1_len, arg2_len),
8249 arg1_len, arg2_len);
8250 len = save_expr(len);
8252 Type* element_type = at->element_type();
8253 Btype* element_btype = element_type->get_backend(gogo);
8254 tree element_type_tree = type_to_tree(element_btype);
8255 if (element_type_tree == error_mark_node)
8256 return error_mark_node;
8257 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
8258 tree bytecount = fold_convert_loc(location.gcc_location(),
8259 TREE_TYPE(element_size), len);
8260 bytecount = fold_build2_loc(location.gcc_location(), MULT_EXPR,
8261 TREE_TYPE(element_size),
8262 bytecount, element_size);
8263 bytecount = fold_convert_loc(location.gcc_location(), size_type_node,
8266 arg1_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8268 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8271 static tree copy_fndecl;
8272 tree call = Gogo::call_builtin(©_fndecl,
8283 if (call == error_mark_node)
8284 return error_mark_node;
8286 return fold_build2_loc(location.gcc_location(), COMPOUND_EXPR,
8287 TREE_TYPE(len), call, len);
8290 case BUILTIN_APPEND:
8292 const Expression_list* args = this->args();
8293 go_assert(args != NULL && args->size() == 2);
8294 Expression* arg1 = args->front();
8295 Expression* arg2 = args->back();
8297 tree arg1_tree = arg1->get_tree(context);
8298 tree arg2_tree = arg2->get_tree(context);
8299 if (arg1_tree == error_mark_node || arg2_tree == error_mark_node)
8300 return error_mark_node;
8302 Array_type* at = arg1->type()->array_type();
8303 Type* element_type = at->element_type()->forwarded();
8308 if (arg2->type()->is_string_type()
8309 && element_type->integer_type() != NULL
8310 && element_type->integer_type()->is_byte())
8312 arg2_tree = save_expr(arg2_tree);
8313 arg2_val = String_type::bytes_tree(gogo, arg2_tree);
8314 arg2_len = String_type::length_tree(gogo, arg2_tree);
8315 element_size = size_int(1);
8319 arg2_tree = Expression::convert_for_assignment(context, at,
8323 if (arg2_tree == error_mark_node)
8324 return error_mark_node;
8326 arg2_tree = save_expr(arg2_tree);
8328 arg2_val = at->value_pointer_tree(gogo, arg2_tree);
8329 arg2_len = at->length_tree(gogo, arg2_tree);
8331 Btype* element_btype = element_type->get_backend(gogo);
8332 tree element_type_tree = type_to_tree(element_btype);
8333 if (element_type_tree == error_mark_node)
8334 return error_mark_node;
8335 element_size = TYPE_SIZE_UNIT(element_type_tree);
8338 arg2_val = fold_convert_loc(location.gcc_location(), ptr_type_node,
8340 arg2_len = fold_convert_loc(location.gcc_location(), size_type_node,
8342 element_size = fold_convert_loc(location.gcc_location(), size_type_node,
8345 if (arg2_val == error_mark_node
8346 || arg2_len == error_mark_node
8347 || element_size == error_mark_node)
8348 return error_mark_node;
8350 // We rebuild the decl each time since the slice types may
8352 tree append_fndecl = NULL_TREE;
8353 return Gogo::call_builtin(&append_fndecl,
8357 TREE_TYPE(arg1_tree),
8358 TREE_TYPE(arg1_tree),
8371 const Expression_list* args = this->args();
8372 go_assert(args != NULL && args->size() == 1);
8373 Expression* arg = args->front();
8374 tree arg_tree = arg->get_tree(context);
8375 if (arg_tree == error_mark_node)
8376 return error_mark_node;
8377 go_assert(COMPLEX_FLOAT_TYPE_P(TREE_TYPE(arg_tree)));
8378 if (this->code_ == BUILTIN_REAL)
8379 return fold_build1_loc(location.gcc_location(), REALPART_EXPR,
8380 TREE_TYPE(TREE_TYPE(arg_tree)),
8383 return fold_build1_loc(location.gcc_location(), IMAGPART_EXPR,
8384 TREE_TYPE(TREE_TYPE(arg_tree)),
8388 case BUILTIN_COMPLEX:
8390 const Expression_list* args = this->args();
8391 go_assert(args != NULL && args->size() == 2);
8392 tree r = args->front()->get_tree(context);
8393 tree i = args->back()->get_tree(context);
8394 if (r == error_mark_node || i == error_mark_node)
8395 return error_mark_node;
8396 go_assert(TYPE_MAIN_VARIANT(TREE_TYPE(r))
8397 == TYPE_MAIN_VARIANT(TREE_TYPE(i)));
8398 go_assert(SCALAR_FLOAT_TYPE_P(TREE_TYPE(r)));
8399 return fold_build2_loc(location.gcc_location(), COMPLEX_EXPR,
8400 build_complex_type(TREE_TYPE(r)),
8409 // We have to support exporting a builtin call expression, because
8410 // code can set a constant to the result of a builtin expression.
8413 Builtin_call_expression::do_export(Export* exp) const
8415 Numeric_constant nc;
8416 if (!this->numeric_constant_value(&nc))
8418 error_at(this->location(), "value is not constant");
8426 Integer_expression::export_integer(exp, val);
8429 else if (nc.is_float())
8432 nc.get_float(&fval);
8433 Float_expression::export_float(exp, fval);
8436 else if (nc.is_complex())
8440 Complex_expression::export_complex(exp, real, imag);
8447 // A trailing space lets us reliably identify the end of the number.
8448 exp->write_c_string(" ");
8451 // Class Call_expression.
8456 Call_expression::do_traverse(Traverse* traverse)
8458 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8459 return TRAVERSE_EXIT;
8460 if (this->args_ != NULL)
8462 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8463 return TRAVERSE_EXIT;
8465 return TRAVERSE_CONTINUE;
8468 // Lower a call statement.
8471 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8472 Statement_inserter* inserter, int)
8474 Location loc = this->location();
8476 // A type cast can look like a function call.
8477 if (this->fn_->is_type_expression()
8478 && this->args_ != NULL
8479 && this->args_->size() == 1)
8480 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8483 // Recognize a call to a builtin function.
8484 Func_expression* fne = this->fn_->func_expression();
8486 && fne->named_object()->is_function_declaration()
8487 && fne->named_object()->func_declaration_value()->type()->is_builtin())
8488 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8489 this->is_varargs_, loc);
8491 // Handle an argument which is a call to a function which returns
8492 // multiple results.
8493 if (this->args_ != NULL
8494 && this->args_->size() == 1
8495 && this->args_->front()->call_expression() != NULL
8496 && this->fn_->type()->function_type() != NULL)
8498 Function_type* fntype = this->fn_->type()->function_type();
8499 size_t rc = this->args_->front()->call_expression()->result_count();
8501 && fntype->parameters() != NULL
8502 && (fntype->parameters()->size() == rc
8503 || (fntype->is_varargs()
8504 && fntype->parameters()->size() - 1 <= rc)))
8506 Call_expression* call = this->args_->front()->call_expression();
8507 Expression_list* args = new Expression_list;
8508 for (size_t i = 0; i < rc; ++i)
8509 args->push_back(Expression::make_call_result(call, i));
8510 // We can't return a new call expression here, because this
8511 // one may be referenced by Call_result expressions. We
8512 // also can't delete the old arguments, because we may still
8513 // traverse them somewhere up the call stack. FIXME.
8518 // If this call returns multiple results, create a temporary
8519 // variable for each result.
8520 size_t rc = this->result_count();
8521 if (rc > 1 && this->results_ == NULL)
8523 std::vector<Temporary_statement*>* temps =
8524 new std::vector<Temporary_statement*>;
8526 const Typed_identifier_list* results =
8527 this->fn_->type()->function_type()->results();
8528 for (Typed_identifier_list::const_iterator p = results->begin();
8529 p != results->end();
8532 Temporary_statement* temp = Statement::make_temporary(p->type(),
8534 inserter->insert(temp);
8535 temps->push_back(temp);
8537 this->results_ = temps;
8540 // Handle a call to a varargs function by packaging up the extra
8542 if (this->fn_->type()->function_type() != NULL
8543 && this->fn_->type()->function_type()->is_varargs())
8545 Function_type* fntype = this->fn_->type()->function_type();
8546 const Typed_identifier_list* parameters = fntype->parameters();
8547 go_assert(parameters != NULL && !parameters->empty());
8548 Type* varargs_type = parameters->back().type();
8549 this->lower_varargs(gogo, function, inserter, varargs_type,
8550 parameters->size());
8553 // If this is call to a method, call the method directly passing the
8554 // object as the first parameter.
8555 Bound_method_expression* bme = this->fn_->bound_method_expression();
8558 Named_object* method = bme->method();
8559 Expression* first_arg = bme->first_argument();
8561 // We always pass a pointer when calling a method.
8562 if (first_arg->type()->points_to() == NULL
8563 && !first_arg->type()->is_error())
8565 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8566 // We may need to create a temporary variable so that we can
8567 // take the address. We can't do that here because it will
8568 // mess up the order of evaluation.
8569 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8570 ue->set_create_temp();
8573 // If we are calling a method which was inherited from an
8574 // embedded struct, and the method did not get a stub, then the
8575 // first type may be wrong.
8576 Type* fatype = bme->first_argument_type();
8579 if (fatype->points_to() == NULL)
8580 fatype = Type::make_pointer_type(fatype);
8581 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8584 Expression_list* new_args = new Expression_list();
8585 new_args->push_back(first_arg);
8586 if (this->args_ != NULL)
8588 for (Expression_list::const_iterator p = this->args_->begin();
8589 p != this->args_->end();
8591 new_args->push_back(*p);
8594 // We have to change in place because this structure may be
8595 // referenced by Call_result_expressions. We can't delete the
8596 // old arguments, because we may be traversing them up in some
8598 this->args_ = new_args;
8599 this->fn_ = Expression::make_func_reference(method, NULL,
8606 // Lower a call to a varargs function. FUNCTION is the function in
8607 // which the call occurs--it's not the function we are calling.
8608 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8609 // PARAM_COUNT is the number of parameters of the function we are
8610 // calling; the last of these parameters will be the varargs
8614 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8615 Statement_inserter* inserter,
8616 Type* varargs_type, size_t param_count)
8618 if (this->varargs_are_lowered_)
8621 Location loc = this->location();
8623 go_assert(param_count > 0);
8624 go_assert(varargs_type->is_slice_type());
8626 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8627 if (arg_count < param_count - 1)
8629 // Not enough arguments; will be caught in check_types.
8633 Expression_list* old_args = this->args_;
8634 Expression_list* new_args = new Expression_list();
8635 bool push_empty_arg = false;
8636 if (old_args == NULL || old_args->empty())
8638 go_assert(param_count == 1);
8639 push_empty_arg = true;
8643 Expression_list::const_iterator pa;
8645 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8647 if (static_cast<size_t>(i) == param_count)
8649 new_args->push_back(*pa);
8652 // We have reached the varargs parameter.
8654 bool issued_error = false;
8655 if (pa == old_args->end())
8656 push_empty_arg = true;
8657 else if (pa + 1 == old_args->end() && this->is_varargs_)
8658 new_args->push_back(*pa);
8659 else if (this->is_varargs_)
8661 if ((*pa)->type()->is_slice_type())
8662 this->report_error(_("too many arguments"));
8665 error_at(this->location(),
8666 _("invalid use of %<...%> with non-slice"));
8667 this->set_is_error();
8673 Type* element_type = varargs_type->array_type()->element_type();
8674 Expression_list* vals = new Expression_list;
8675 for (; pa != old_args->end(); ++pa, ++i)
8677 // Check types here so that we get a better message.
8678 Type* patype = (*pa)->type();
8679 Location paloc = (*pa)->location();
8680 if (!this->check_argument_type(i, element_type, patype,
8681 paloc, issued_error))
8683 vals->push_back(*pa);
8686 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8687 gogo->lower_expression(function, inserter, &val);
8688 new_args->push_back(val);
8693 new_args->push_back(Expression::make_nil(loc));
8695 // We can't return a new call expression here, because this one may
8696 // be referenced by Call_result expressions. FIXME. We can't
8697 // delete OLD_ARGS because we may have both a Call_expression and a
8698 // Builtin_call_expression which refer to them. FIXME.
8699 this->args_ = new_args;
8700 this->varargs_are_lowered_ = true;
8703 // Get the function type. This can return NULL in error cases.
8706 Call_expression::get_function_type() const
8708 return this->fn_->type()->function_type();
8711 // Return the number of values which this call will return.
8714 Call_expression::result_count() const
8716 const Function_type* fntype = this->get_function_type();
8719 if (fntype->results() == NULL)
8721 return fntype->results()->size();
8724 // Return the temporary which holds a result.
8726 Temporary_statement*
8727 Call_expression::result(size_t i) const
8729 if (this->results_ == NULL || this->results_->size() <= i)
8731 go_assert(saw_errors());
8734 return (*this->results_)[i];
8737 // Return whether this is a call to the predeclared function recover.
8740 Call_expression::is_recover_call() const
8742 return this->do_is_recover_call();
8745 // Set the argument to the recover function.
8748 Call_expression::set_recover_arg(Expression* arg)
8750 this->do_set_recover_arg(arg);
8753 // Virtual functions also implemented by Builtin_call_expression.
8756 Call_expression::do_is_recover_call() const
8762 Call_expression::do_set_recover_arg(Expression*)
8767 // We have found an error with this call expression; return true if
8768 // we should report it.
8771 Call_expression::issue_error()
8773 if (this->issued_error_)
8777 this->issued_error_ = true;
8785 Call_expression::do_type()
8787 if (this->type_ != NULL)
8791 Function_type* fntype = this->get_function_type();
8793 return Type::make_error_type();
8795 const Typed_identifier_list* results = fntype->results();
8796 if (results == NULL)
8797 ret = Type::make_void_type();
8798 else if (results->size() == 1)
8799 ret = results->begin()->type();
8801 ret = Type::make_call_multiple_result_type(this);
8808 // Determine types for a call expression. We can use the function
8809 // parameter types to set the types of the arguments.
8812 Call_expression::do_determine_type(const Type_context*)
8814 if (!this->determining_types())
8817 this->fn_->determine_type_no_context();
8818 Function_type* fntype = this->get_function_type();
8819 const Typed_identifier_list* parameters = NULL;
8821 parameters = fntype->parameters();
8822 if (this->args_ != NULL)
8824 Typed_identifier_list::const_iterator pt;
8825 if (parameters != NULL)
8826 pt = parameters->begin();
8828 for (Expression_list::const_iterator pa = this->args_->begin();
8829 pa != this->args_->end();
8835 // If this is a method, the first argument is the
8837 if (fntype != NULL && fntype->is_method())
8839 Type* rtype = fntype->receiver()->type();
8840 // The receiver is always passed as a pointer.
8841 if (rtype->points_to() == NULL)
8842 rtype = Type::make_pointer_type(rtype);
8843 Type_context subcontext(rtype, false);
8844 (*pa)->determine_type(&subcontext);
8849 if (parameters != NULL && pt != parameters->end())
8851 Type_context subcontext(pt->type(), false);
8852 (*pa)->determine_type(&subcontext);
8856 (*pa)->determine_type_no_context();
8861 // Called when determining types for a Call_expression. Return true
8862 // if we should go ahead, false if they have already been determined.
8865 Call_expression::determining_types()
8867 if (this->types_are_determined_)
8871 this->types_are_determined_ = true;
8876 // Check types for parameter I.
8879 Call_expression::check_argument_type(int i, const Type* parameter_type,
8880 const Type* argument_type,
8881 Location argument_location,
8886 if (this->are_hidden_fields_ok_)
8887 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
8890 ok = Type::are_assignable(parameter_type, argument_type, &reason);
8896 error_at(argument_location, "argument %d has incompatible type", i);
8898 error_at(argument_location,
8899 "argument %d has incompatible type (%s)",
8902 this->set_is_error();
8911 Call_expression::do_check_types(Gogo*)
8913 if (this->classification() == EXPRESSION_ERROR)
8916 Function_type* fntype = this->get_function_type();
8919 if (!this->fn_->type()->is_error())
8920 this->report_error(_("expected function"));
8924 bool is_method = fntype->is_method();
8927 go_assert(this->args_ != NULL && !this->args_->empty());
8928 Type* rtype = fntype->receiver()->type();
8929 Expression* first_arg = this->args_->front();
8930 // The language permits copying hidden fields for a method
8931 // receiver. We dereference the values since receivers are
8932 // always passed as pointers.
8934 if (!Type::are_assignable_hidden_ok(rtype->deref(),
8935 first_arg->type()->deref(),
8939 this->report_error(_("incompatible type for receiver"));
8942 error_at(this->location(),
8943 "incompatible type for receiver (%s)",
8945 this->set_is_error();
8950 // Note that varargs was handled by the lower_varargs() method, so
8951 // we don't have to worry about it here unless something is wrong.
8952 if (this->is_varargs_ && !this->varargs_are_lowered_)
8954 if (!fntype->is_varargs())
8956 error_at(this->location(),
8957 _("invalid use of %<...%> calling non-variadic function"));
8958 this->set_is_error();
8963 const Typed_identifier_list* parameters = fntype->parameters();
8964 if (this->args_ == NULL)
8966 if (parameters != NULL && !parameters->empty())
8967 this->report_error(_("not enough arguments"));
8969 else if (parameters == NULL)
8971 if (!is_method || this->args_->size() > 1)
8972 this->report_error(_("too many arguments"));
8977 Expression_list::const_iterator pa = this->args_->begin();
8980 for (Typed_identifier_list::const_iterator pt = parameters->begin();
8981 pt != parameters->end();
8984 if (pa == this->args_->end())
8986 this->report_error(_("not enough arguments"));
8989 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
8990 (*pa)->location(), false);
8992 if (pa != this->args_->end())
8993 this->report_error(_("too many arguments"));
8997 // Return whether we have to use a temporary variable to ensure that
8998 // we evaluate this call expression in order. If the call returns no
8999 // results then it will inevitably be executed last.
9002 Call_expression::do_must_eval_in_order() const
9004 return this->result_count() > 0;
9007 // Get the function and the first argument to use when calling an
9008 // interface method.
9011 Call_expression::interface_method_function(
9012 Translate_context* context,
9013 Interface_field_reference_expression* interface_method,
9014 tree* first_arg_ptr)
9016 tree expr = interface_method->expr()->get_tree(context);
9017 if (expr == error_mark_node)
9018 return error_mark_node;
9019 expr = save_expr(expr);
9020 tree first_arg = interface_method->get_underlying_object_tree(context, expr);
9021 if (first_arg == error_mark_node)
9022 return error_mark_node;
9023 *first_arg_ptr = first_arg;
9024 return interface_method->get_function_tree(context, expr);
9027 // Build the call expression.
9030 Call_expression::do_get_tree(Translate_context* context)
9032 if (this->tree_ != NULL_TREE)
9035 Function_type* fntype = this->get_function_type();
9037 return error_mark_node;
9039 if (this->fn_->is_error_expression())
9040 return error_mark_node;
9042 Gogo* gogo = context->gogo();
9043 Location location = this->location();
9045 Func_expression* func = this->fn_->func_expression();
9046 Interface_field_reference_expression* interface_method =
9047 this->fn_->interface_field_reference_expression();
9048 const bool has_closure = func != NULL && func->closure() != NULL;
9049 const bool is_interface_method = interface_method != NULL;
9053 if (this->args_ == NULL || this->args_->empty())
9055 nargs = is_interface_method ? 1 : 0;
9056 args = nargs == 0 ? NULL : new tree[nargs];
9058 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9060 // Passing a receiver parameter.
9061 go_assert(!is_interface_method
9062 && fntype->is_method()
9063 && this->args_->size() == 1);
9065 args = new tree[nargs];
9066 args[0] = this->args_->front()->get_tree(context);
9070 const Typed_identifier_list* params = fntype->parameters();
9072 nargs = this->args_->size();
9073 int i = is_interface_method ? 1 : 0;
9075 args = new tree[nargs];
9077 Typed_identifier_list::const_iterator pp = params->begin();
9078 Expression_list::const_iterator pe = this->args_->begin();
9079 if (!is_interface_method && fntype->is_method())
9081 args[i] = (*pe)->get_tree(context);
9085 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9087 go_assert(pp != params->end());
9088 tree arg_val = (*pe)->get_tree(context);
9089 args[i] = Expression::convert_for_assignment(context,
9094 if (args[i] == error_mark_node)
9097 return error_mark_node;
9100 go_assert(pp == params->end());
9101 go_assert(i == nargs);
9104 tree rettype = TREE_TYPE(TREE_TYPE(type_to_tree(fntype->get_backend(gogo))));
9105 if (rettype == error_mark_node)
9108 return error_mark_node;
9113 fn = func->get_tree_without_closure(gogo);
9114 else if (!is_interface_method)
9115 fn = this->fn_->get_tree(context);
9117 fn = this->interface_method_function(context, interface_method, &args[0]);
9119 if (fn == error_mark_node || TREE_TYPE(fn) == error_mark_node)
9122 return error_mark_node;
9126 if (TREE_CODE(fndecl) == ADDR_EXPR)
9127 fndecl = TREE_OPERAND(fndecl, 0);
9129 // Add a type cast in case the type of the function is a recursive
9130 // type which refers to itself.
9131 if (!DECL_P(fndecl) || !DECL_IS_BUILTIN(fndecl))
9133 tree fnt = type_to_tree(fntype->get_backend(gogo));
9134 if (fnt == error_mark_node)
9135 return error_mark_node;
9136 fn = fold_convert_loc(location.gcc_location(), fnt, fn);
9139 // This is to support builtin math functions when using 80387 math.
9140 tree excess_type = NULL_TREE;
9142 && TREE_CODE(fndecl) == FUNCTION_DECL
9143 && DECL_IS_BUILTIN(fndecl)
9144 && DECL_BUILT_IN_CLASS(fndecl) == BUILT_IN_NORMAL
9146 && ((SCALAR_FLOAT_TYPE_P(rettype)
9147 && SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[0])))
9148 || (COMPLEX_FLOAT_TYPE_P(rettype)
9149 && COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[0])))))
9151 excess_type = excess_precision_type(TREE_TYPE(args[0]));
9152 if (excess_type != NULL_TREE)
9154 tree excess_fndecl = mathfn_built_in(excess_type,
9155 DECL_FUNCTION_CODE(fndecl));
9156 if (excess_fndecl == NULL_TREE)
9157 excess_type = NULL_TREE;
9160 fn = build_fold_addr_expr_loc(location.gcc_location(),
9162 for (int i = 0; i < nargs; ++i)
9164 if (SCALAR_FLOAT_TYPE_P(TREE_TYPE(args[i]))
9165 || COMPLEX_FLOAT_TYPE_P(TREE_TYPE(args[i])))
9166 args[i] = ::convert(excess_type, args[i]);
9172 tree ret = build_call_array(excess_type != NULL_TREE ? excess_type : rettype,
9176 SET_EXPR_LOCATION(ret, location.gcc_location());
9180 tree closure_tree = func->closure()->get_tree(context);
9181 if (closure_tree != error_mark_node)
9182 CALL_EXPR_STATIC_CHAIN(ret) = closure_tree;
9185 // If this is a recursive function type which returns itself, as in
9187 // we have used ptr_type_node for the return type. Add a cast here
9188 // to the correct type.
9189 if (TREE_TYPE(ret) == ptr_type_node)
9191 tree t = type_to_tree(this->type()->base()->get_backend(gogo));
9192 ret = fold_convert_loc(location.gcc_location(), t, ret);
9195 if (excess_type != NULL_TREE)
9197 // Calling convert here can undo our excess precision change.
9198 // That may or may not be a bug in convert_to_real.
9199 ret = build1(NOP_EXPR, rettype, ret);
9202 if (this->results_ != NULL)
9203 ret = this->set_results(context, ret);
9210 // Set the result variables if this call returns multiple results.
9213 Call_expression::set_results(Translate_context* context, tree call_tree)
9215 tree stmt_list = NULL_TREE;
9217 call_tree = save_expr(call_tree);
9219 if (TREE_CODE(TREE_TYPE(call_tree)) != RECORD_TYPE)
9221 go_assert(saw_errors());
9225 Location loc = this->location();
9226 tree field = TYPE_FIELDS(TREE_TYPE(call_tree));
9227 size_t rc = this->result_count();
9228 for (size_t i = 0; i < rc; ++i, field = DECL_CHAIN(field))
9230 go_assert(field != NULL_TREE);
9232 Temporary_statement* temp = this->result(i);
9235 go_assert(saw_errors());
9236 return error_mark_node;
9238 Temporary_reference_expression* ref =
9239 Expression::make_temporary_reference(temp, loc);
9240 ref->set_is_lvalue();
9241 tree temp_tree = ref->get_tree(context);
9242 if (temp_tree == error_mark_node)
9243 return error_mark_node;
9245 tree val_tree = build3_loc(loc.gcc_location(), COMPONENT_REF,
9246 TREE_TYPE(field), call_tree, field, NULL_TREE);
9247 tree set_tree = build2_loc(loc.gcc_location(), MODIFY_EXPR,
9248 void_type_node, temp_tree, val_tree);
9250 append_to_statement_list(set_tree, &stmt_list);
9252 go_assert(field == NULL_TREE);
9254 return save_expr(stmt_list);
9257 // Dump ast representation for a call expressin.
9260 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9262 this->fn_->dump_expression(ast_dump_context);
9263 ast_dump_context->ostream() << "(";
9265 ast_dump_context->dump_expression_list(this->args_);
9267 ast_dump_context->ostream() << ") ";
9270 // Make a call expression.
9273 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9276 return new Call_expression(fn, args, is_varargs, location);
9279 // A single result from a call which returns multiple results.
9281 class Call_result_expression : public Expression
9284 Call_result_expression(Call_expression* call, unsigned int index)
9285 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9286 call_(call), index_(index)
9291 do_traverse(Traverse*);
9297 do_determine_type(const Type_context*);
9300 do_check_types(Gogo*);
9305 return new Call_result_expression(this->call_->call_expression(),
9310 do_must_eval_in_order() const
9314 do_get_tree(Translate_context*);
9317 do_dump_expression(Ast_dump_context*) const;
9320 // The underlying call expression.
9322 // Which result we want.
9323 unsigned int index_;
9326 // Traverse a call result.
9329 Call_result_expression::do_traverse(Traverse* traverse)
9331 if (traverse->remember_expression(this->call_))
9333 // We have already traversed the call expression.
9334 return TRAVERSE_CONTINUE;
9336 return Expression::traverse(&this->call_, traverse);
9342 Call_result_expression::do_type()
9344 if (this->classification() == EXPRESSION_ERROR)
9345 return Type::make_error_type();
9347 // THIS->CALL_ can be replaced with a temporary reference due to
9348 // Call_expression::do_must_eval_in_order when there is an error.
9349 Call_expression* ce = this->call_->call_expression();
9352 this->set_is_error();
9353 return Type::make_error_type();
9355 Function_type* fntype = ce->get_function_type();
9358 if (ce->issue_error())
9360 if (!ce->fn()->type()->is_error())
9361 this->report_error(_("expected function"));
9363 this->set_is_error();
9364 return Type::make_error_type();
9366 const Typed_identifier_list* results = fntype->results();
9367 if (results == NULL || results->size() < 2)
9369 if (ce->issue_error())
9370 this->report_error(_("number of results does not match "
9371 "number of values"));
9372 return Type::make_error_type();
9374 Typed_identifier_list::const_iterator pr = results->begin();
9375 for (unsigned int i = 0; i < this->index_; ++i)
9377 if (pr == results->end())
9381 if (pr == results->end())
9383 if (ce->issue_error())
9384 this->report_error(_("number of results does not match "
9385 "number of values"));
9386 return Type::make_error_type();
9391 // Check the type. Just make sure that we trigger the warning in
9395 Call_result_expression::do_check_types(Gogo*)
9400 // Determine the type. We have nothing to do here, but the 0 result
9401 // needs to pass down to the caller.
9404 Call_result_expression::do_determine_type(const Type_context*)
9406 this->call_->determine_type_no_context();
9409 // Return the tree. We just refer to the temporary set by the call
9410 // expression. We don't do this at lowering time because it makes it
9411 // hard to evaluate the call at the right time.
9414 Call_result_expression::do_get_tree(Translate_context* context)
9416 Call_expression* ce = this->call_->call_expression();
9419 go_assert(this->call_->is_error_expression());
9420 return error_mark_node;
9422 Temporary_statement* ts = ce->result(this->index_);
9425 go_assert(saw_errors());
9426 return error_mark_node;
9428 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9429 return ref->get_tree(context);
9432 // Dump ast representation for a call result expression.
9435 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9438 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9439 // (struct) and the fields are referenced instead.
9440 ast_dump_context->ostream() << this->index_ << "@(";
9441 ast_dump_context->dump_expression(this->call_);
9442 ast_dump_context->ostream() << ")";
9445 // Make a reference to a single result of a call which returns
9446 // multiple results.
9449 Expression::make_call_result(Call_expression* call, unsigned int index)
9451 return new Call_result_expression(call, index);
9454 // Class Index_expression.
9459 Index_expression::do_traverse(Traverse* traverse)
9461 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9462 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9463 || (this->end_ != NULL
9464 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT))
9465 return TRAVERSE_EXIT;
9466 return TRAVERSE_CONTINUE;
9469 // Lower an index expression. This converts the generic index
9470 // expression into an array index, a string index, or a map index.
9473 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9475 Location location = this->location();
9476 Expression* left = this->left_;
9477 Expression* start = this->start_;
9478 Expression* end = this->end_;
9480 Type* type = left->type();
9481 if (type->is_error())
9482 return Expression::make_error(location);
9483 else if (left->is_type_expression())
9485 error_at(location, "attempt to index type expression");
9486 return Expression::make_error(location);
9488 else if (type->array_type() != NULL)
9489 return Expression::make_array_index(left, start, end, location);
9490 else if (type->points_to() != NULL
9491 && type->points_to()->array_type() != NULL
9492 && !type->points_to()->is_slice_type())
9494 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9496 return Expression::make_array_index(deref, start, end, location);
9498 else if (type->is_string_type())
9499 return Expression::make_string_index(left, start, end, location);
9500 else if (type->map_type() != NULL)
9504 error_at(location, "invalid slice of map");
9505 return Expression::make_error(location);
9507 Map_index_expression* ret = Expression::make_map_index(left, start,
9509 if (this->is_lvalue_)
9510 ret->set_is_lvalue();
9516 "attempt to index object which is not array, string, or map");
9517 return Expression::make_error(location);
9521 // Write an indexed expression (expr[expr:expr] or expr[expr]) to a
9525 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9526 const Expression* expr,
9527 const Expression* start,
9528 const Expression* end)
9530 expr->dump_expression(ast_dump_context);
9531 ast_dump_context->ostream() << "[";
9532 start->dump_expression(ast_dump_context);
9535 ast_dump_context->ostream() << ":";
9536 end->dump_expression(ast_dump_context);
9538 ast_dump_context->ostream() << "]";
9541 // Dump ast representation for an index expression.
9544 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9547 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9548 this->start_, this->end_);
9551 // Make an index expression.
9554 Expression::make_index(Expression* left, Expression* start, Expression* end,
9557 return new Index_expression(left, start, end, location);
9560 // An array index. This is used for both indexing and slicing.
9562 class Array_index_expression : public Expression
9565 Array_index_expression(Expression* array, Expression* start,
9566 Expression* end, Location location)
9567 : Expression(EXPRESSION_ARRAY_INDEX, location),
9568 array_(array), start_(start), end_(end), type_(NULL)
9573 do_traverse(Traverse*);
9579 do_determine_type(const Type_context*);
9582 do_check_types(Gogo*);
9587 return Expression::make_array_index(this->array_->copy(),
9588 this->start_->copy(),
9591 : this->end_->copy()),
9596 do_must_eval_subexpressions_in_order(int* skip) const
9603 do_is_addressable() const;
9606 do_address_taken(bool escapes)
9607 { this->array_->address_taken(escapes); }
9610 do_get_tree(Translate_context*);
9613 do_dump_expression(Ast_dump_context*) const;
9616 // The array we are getting a value from.
9618 // The start or only index.
9620 // The end index of a slice. This may be NULL for a simple array
9621 // index, or it may be a nil expression for the length of the array.
9623 // The type of the expression.
9627 // Array index traversal.
9630 Array_index_expression::do_traverse(Traverse* traverse)
9632 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9633 return TRAVERSE_EXIT;
9634 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9635 return TRAVERSE_EXIT;
9636 if (this->end_ != NULL)
9638 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9639 return TRAVERSE_EXIT;
9641 return TRAVERSE_CONTINUE;
9644 // Return the type of an array index.
9647 Array_index_expression::do_type()
9649 if (this->type_ == NULL)
9651 Array_type* type = this->array_->type()->array_type();
9653 this->type_ = Type::make_error_type();
9654 else if (this->end_ == NULL)
9655 this->type_ = type->element_type();
9656 else if (type->is_slice_type())
9658 // A slice of a slice has the same type as the original
9660 this->type_ = this->array_->type()->deref();
9664 // A slice of an array is a slice.
9665 this->type_ = Type::make_array_type(type->element_type(), NULL);
9671 // Set the type of an array index.
9674 Array_index_expression::do_determine_type(const Type_context*)
9676 this->array_->determine_type_no_context();
9677 this->start_->determine_type_no_context();
9678 if (this->end_ != NULL)
9679 this->end_->determine_type_no_context();
9682 // Check types of an array index.
9685 Array_index_expression::do_check_types(Gogo*)
9687 if (this->start_->type()->integer_type() == NULL)
9688 this->report_error(_("index must be integer"));
9689 if (this->end_ != NULL
9690 && this->end_->type()->integer_type() == NULL
9691 && !this->end_->type()->is_error()
9692 && !this->end_->is_nil_expression()
9693 && !this->end_->is_error_expression())
9694 this->report_error(_("slice end must be integer"));
9696 Array_type* array_type = this->array_->type()->array_type();
9697 if (array_type == NULL)
9699 go_assert(this->array_->type()->is_error());
9703 unsigned int int_bits =
9704 Type::lookup_integer_type("int")->integer_type()->bits();
9706 Numeric_constant lvalnc;
9708 bool lval_valid = (array_type->length() != NULL
9709 && array_type->length()->numeric_constant_value(&lvalnc)
9710 && lvalnc.to_int(&lval));
9711 Numeric_constant inc;
9713 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9715 if (mpz_sgn(ival) < 0
9716 || mpz_sizeinbase(ival, 2) >= int_bits
9718 && (this->end_ == NULL
9719 ? mpz_cmp(ival, lval) >= 0
9720 : mpz_cmp(ival, lval) > 0)))
9722 error_at(this->start_->location(), "array index out of bounds");
9723 this->set_is_error();
9727 if (this->end_ != NULL && !this->end_->is_nil_expression())
9729 Numeric_constant enc;
9731 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9733 if (mpz_sgn(eval) < 0
9734 || mpz_sizeinbase(eval, 2) >= int_bits
9735 || (lval_valid && mpz_cmp(eval, lval) > 0))
9737 error_at(this->end_->location(), "array index out of bounds");
9738 this->set_is_error();
9746 // A slice of an array requires an addressable array. A slice of a
9747 // slice is always possible.
9748 if (this->end_ != NULL && !array_type->is_slice_type())
9750 if (!this->array_->is_addressable())
9751 this->report_error(_("slice of unaddressable value"));
9753 this->array_->address_taken(true);
9757 // Return whether this expression is addressable.
9760 Array_index_expression::do_is_addressable() const
9762 // A slice expression is not addressable.
9763 if (this->end_ != NULL)
9766 // An index into a slice is addressable.
9767 if (this->array_->type()->is_slice_type())
9770 // An index into an array is addressable if the array is
9772 return this->array_->is_addressable();
9775 // Get a tree for an array index.
9778 Array_index_expression::do_get_tree(Translate_context* context)
9780 Gogo* gogo = context->gogo();
9781 Location loc = this->location();
9783 Array_type* array_type = this->array_->type()->array_type();
9784 if (array_type == NULL)
9786 go_assert(this->array_->type()->is_error());
9787 return error_mark_node;
9790 tree type_tree = type_to_tree(array_type->get_backend(gogo));
9791 if (type_tree == error_mark_node)
9792 return error_mark_node;
9794 tree array_tree = this->array_->get_tree(context);
9795 if (array_tree == error_mark_node)
9796 return error_mark_node;
9798 if (array_type->length() == NULL && !DECL_P(array_tree))
9799 array_tree = save_expr(array_tree);
9801 tree length_tree = NULL_TREE;
9802 if (this->end_ == NULL || this->end_->is_nil_expression())
9804 length_tree = array_type->length_tree(gogo, array_tree);
9805 if (length_tree == error_mark_node)
9806 return error_mark_node;
9807 length_tree = save_expr(length_tree);
9810 tree capacity_tree = NULL_TREE;
9811 if (this->end_ != NULL)
9813 capacity_tree = array_type->capacity_tree(gogo, array_tree);
9814 if (capacity_tree == error_mark_node)
9815 return error_mark_node;
9816 capacity_tree = save_expr(capacity_tree);
9819 tree length_type = (length_tree != NULL_TREE
9820 ? TREE_TYPE(length_tree)
9821 : TREE_TYPE(capacity_tree));
9823 tree bad_index = boolean_false_node;
9825 tree start_tree = this->start_->get_tree(context);
9826 if (start_tree == error_mark_node)
9827 return error_mark_node;
9828 if (!DECL_P(start_tree))
9829 start_tree = save_expr(start_tree);
9830 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
9831 start_tree = convert_to_integer(length_type, start_tree);
9833 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
9836 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
9837 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9838 boolean_type_node, bad_index,
9839 fold_build2_loc(loc.gcc_location(),
9843 boolean_type_node, start_tree,
9848 int code = (array_type->length() != NULL
9849 ? (this->end_ == NULL
9850 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9851 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9852 : (this->end_ == NULL
9853 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9854 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9855 tree crash = Gogo::runtime_error(code, loc);
9857 if (this->end_ == NULL)
9859 // Simple array indexing. This has to return an l-value, so
9860 // wrap the index check into START_TREE.
9861 start_tree = build2(COMPOUND_EXPR, TREE_TYPE(start_tree),
9862 build3(COND_EXPR, void_type_node,
9863 bad_index, crash, NULL_TREE),
9865 start_tree = fold_convert_loc(loc.gcc_location(), sizetype, start_tree);
9867 if (array_type->length() != NULL)
9870 return build4(ARRAY_REF, TREE_TYPE(type_tree), array_tree,
9871 start_tree, NULL_TREE, NULL_TREE);
9876 tree values = array_type->value_pointer_tree(gogo, array_tree);
9877 Type* element_type = array_type->element_type();
9878 Btype* belement_type = element_type->get_backend(gogo);
9879 tree element_type_tree = type_to_tree(belement_type);
9880 if (element_type_tree == error_mark_node)
9881 return error_mark_node;
9882 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9883 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9884 start_tree, element_size);
9885 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9886 TREE_TYPE(values), values, offset);
9887 return build_fold_indirect_ref(ptr);
9894 if (this->end_->is_nil_expression())
9895 end_tree = length_tree;
9898 end_tree = this->end_->get_tree(context);
9899 if (end_tree == error_mark_node)
9900 return error_mark_node;
9901 if (!DECL_P(end_tree))
9902 end_tree = save_expr(end_tree);
9903 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
9904 end_tree = convert_to_integer(length_type, end_tree);
9906 bad_index = Expression::check_bounds(end_tree, length_type, bad_index,
9909 end_tree = fold_convert_loc(loc.gcc_location(), length_type, end_tree);
9911 tree bad_end = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9913 fold_build2_loc(loc.gcc_location(),
9914 LT_EXPR, boolean_type_node,
9915 end_tree, start_tree),
9916 fold_build2_loc(loc.gcc_location(),
9917 GT_EXPR, boolean_type_node,
9918 end_tree, capacity_tree));
9919 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
9920 boolean_type_node, bad_index, bad_end);
9923 Type* element_type = array_type->element_type();
9924 tree element_type_tree = type_to_tree(element_type->get_backend(gogo));
9925 if (element_type_tree == error_mark_node)
9926 return error_mark_node;
9927 tree element_size = TYPE_SIZE_UNIT(element_type_tree);
9929 tree offset = fold_build2_loc(loc.gcc_location(), MULT_EXPR, sizetype,
9930 fold_convert_loc(loc.gcc_location(), sizetype,
9934 tree value_pointer = array_type->value_pointer_tree(gogo, array_tree);
9935 if (value_pointer == error_mark_node)
9936 return error_mark_node;
9938 value_pointer = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
9939 TREE_TYPE(value_pointer),
9940 value_pointer, offset);
9942 tree result_length_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9943 length_type, end_tree, start_tree);
9945 tree result_capacity_tree = fold_build2_loc(loc.gcc_location(), MINUS_EXPR,
9946 length_type, capacity_tree,
9949 tree struct_tree = type_to_tree(this->type()->get_backend(gogo));
9950 go_assert(TREE_CODE(struct_tree) == RECORD_TYPE);
9952 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
9954 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
9955 tree field = TYPE_FIELDS(struct_tree);
9956 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
9958 elt->value = value_pointer;
9960 elt = VEC_quick_push(constructor_elt, init, NULL);
9961 field = DECL_CHAIN(field);
9962 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
9964 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9965 result_length_tree);
9967 elt = VEC_quick_push(constructor_elt, init, NULL);
9968 field = DECL_CHAIN(field);
9969 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__capacity") == 0);
9971 elt->value = fold_convert_loc(loc.gcc_location(), TREE_TYPE(field),
9972 result_capacity_tree);
9974 tree constructor = build_constructor(struct_tree, init);
9976 if (TREE_CONSTANT(value_pointer)
9977 && TREE_CONSTANT(result_length_tree)
9978 && TREE_CONSTANT(result_capacity_tree))
9979 TREE_CONSTANT(constructor) = 1;
9981 return fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
9982 TREE_TYPE(constructor),
9983 build3(COND_EXPR, void_type_node,
9984 bad_index, crash, NULL_TREE),
9988 // Dump ast representation for an array index expression.
9991 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9994 Index_expression::dump_index_expression(ast_dump_context, this->array_,
9995 this->start_, this->end_);
9998 // Make an array index expression. END may be NULL.
10001 Expression::make_array_index(Expression* array, Expression* start,
10002 Expression* end, Location location)
10004 return new Array_index_expression(array, start, end, location);
10007 // A string index. This is used for both indexing and slicing.
10009 class String_index_expression : public Expression
10012 String_index_expression(Expression* string, Expression* start,
10013 Expression* end, Location location)
10014 : Expression(EXPRESSION_STRING_INDEX, location),
10015 string_(string), start_(start), end_(end)
10020 do_traverse(Traverse*);
10026 do_determine_type(const Type_context*);
10029 do_check_types(Gogo*);
10034 return Expression::make_string_index(this->string_->copy(),
10035 this->start_->copy(),
10036 (this->end_ == NULL
10038 : this->end_->copy()),
10043 do_must_eval_subexpressions_in_order(int* skip) const
10050 do_get_tree(Translate_context*);
10053 do_dump_expression(Ast_dump_context*) const;
10056 // The string we are getting a value from.
10057 Expression* string_;
10058 // The start or only index.
10059 Expression* start_;
10060 // The end index of a slice. This may be NULL for a single index,
10061 // or it may be a nil expression for the length of the string.
10065 // String index traversal.
10068 String_index_expression::do_traverse(Traverse* traverse)
10070 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10071 return TRAVERSE_EXIT;
10072 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10073 return TRAVERSE_EXIT;
10074 if (this->end_ != NULL)
10076 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10077 return TRAVERSE_EXIT;
10079 return TRAVERSE_CONTINUE;
10082 // Return the type of a string index.
10085 String_index_expression::do_type()
10087 if (this->end_ == NULL)
10088 return Type::lookup_integer_type("uint8");
10090 return this->string_->type();
10093 // Determine the type of a string index.
10096 String_index_expression::do_determine_type(const Type_context*)
10098 this->string_->determine_type_no_context();
10099 this->start_->determine_type_no_context();
10100 if (this->end_ != NULL)
10101 this->end_->determine_type_no_context();
10104 // Check types of a string index.
10107 String_index_expression::do_check_types(Gogo*)
10109 if (this->start_->type()->integer_type() == NULL)
10110 this->report_error(_("index must be integer"));
10111 if (this->end_ != NULL
10112 && this->end_->type()->integer_type() == NULL
10113 && !this->end_->is_nil_expression())
10114 this->report_error(_("slice end must be integer"));
10117 bool sval_valid = this->string_->string_constant_value(&sval);
10119 Numeric_constant inc;
10121 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10123 if (mpz_sgn(ival) < 0
10124 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10126 error_at(this->start_->location(), "string index out of bounds");
10127 this->set_is_error();
10131 if (this->end_ != NULL && !this->end_->is_nil_expression())
10133 Numeric_constant enc;
10135 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10137 if (mpz_sgn(eval) < 0
10138 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10140 error_at(this->end_->location(), "string index out of bounds");
10141 this->set_is_error();
10148 // Get a tree for a string index.
10151 String_index_expression::do_get_tree(Translate_context* context)
10153 Location loc = this->location();
10155 tree string_tree = this->string_->get_tree(context);
10156 if (string_tree == error_mark_node)
10157 return error_mark_node;
10159 if (this->string_->type()->points_to() != NULL)
10160 string_tree = build_fold_indirect_ref(string_tree);
10161 if (!DECL_P(string_tree))
10162 string_tree = save_expr(string_tree);
10163 tree string_type = TREE_TYPE(string_tree);
10165 tree length_tree = String_type::length_tree(context->gogo(), string_tree);
10166 length_tree = save_expr(length_tree);
10167 tree length_type = TREE_TYPE(length_tree);
10169 tree bad_index = boolean_false_node;
10171 tree start_tree = this->start_->get_tree(context);
10172 if (start_tree == error_mark_node)
10173 return error_mark_node;
10174 if (!DECL_P(start_tree))
10175 start_tree = save_expr(start_tree);
10176 if (!INTEGRAL_TYPE_P(TREE_TYPE(start_tree)))
10177 start_tree = convert_to_integer(length_type, start_tree);
10179 bad_index = Expression::check_bounds(start_tree, length_type, bad_index,
10182 start_tree = fold_convert_loc(loc.gcc_location(), length_type, start_tree);
10184 int code = (this->end_ == NULL
10185 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10186 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10187 tree crash = Gogo::runtime_error(code, loc);
10189 if (this->end_ == NULL)
10191 bad_index = fold_build2_loc(loc.gcc_location(), TRUTH_OR_EXPR,
10192 boolean_type_node, bad_index,
10193 fold_build2_loc(loc.gcc_location(), GE_EXPR,
10195 start_tree, length_tree));
10197 tree bytes_tree = String_type::bytes_tree(context->gogo(), string_tree);
10198 tree ptr = fold_build2_loc(loc.gcc_location(), POINTER_PLUS_EXPR,
10199 TREE_TYPE(bytes_tree),
10201 fold_convert_loc(loc.gcc_location(), sizetype,
10203 tree index = build_fold_indirect_ref_loc(loc.gcc_location(), ptr);
10205 return build2(COMPOUND_EXPR, TREE_TYPE(index),
10206 build3(COND_EXPR, void_type_node,
10207 bad_index, crash, NULL_TREE),
10213 if (this->end_->is_nil_expression())
10214 end_tree = build_int_cst(length_type, -1);
10217 end_tree = this->end_->get_tree(context);
10218 if (end_tree == error_mark_node)
10219 return error_mark_node;
10220 if (!DECL_P(end_tree))
10221 end_tree = save_expr(end_tree);
10222 if (!INTEGRAL_TYPE_P(TREE_TYPE(end_tree)))
10223 end_tree = convert_to_integer(length_type, end_tree);
10225 bad_index = Expression::check_bounds(end_tree, length_type,
10228 end_tree = fold_convert_loc(loc.gcc_location(), length_type,
10232 static tree strslice_fndecl;
10233 tree ret = Gogo::call_builtin(&strslice_fndecl,
10235 "__go_string_slice",
10244 if (ret == error_mark_node)
10245 return error_mark_node;
10246 // This will panic if the bounds are out of range for the
10248 TREE_NOTHROW(strslice_fndecl) = 0;
10250 if (bad_index == boolean_false_node)
10253 return build2(COMPOUND_EXPR, TREE_TYPE(ret),
10254 build3(COND_EXPR, void_type_node,
10255 bad_index, crash, NULL_TREE),
10260 // Dump ast representation for a string index expression.
10263 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10266 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10267 this->start_, this->end_);
10270 // Make a string index expression. END may be NULL.
10273 Expression::make_string_index(Expression* string, Expression* start,
10274 Expression* end, Location location)
10276 return new String_index_expression(string, start, end, location);
10279 // Class Map_index.
10281 // Get the type of the map.
10284 Map_index_expression::get_map_type() const
10286 Map_type* mt = this->map_->type()->deref()->map_type();
10288 go_assert(saw_errors());
10292 // Map index traversal.
10295 Map_index_expression::do_traverse(Traverse* traverse)
10297 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10298 return TRAVERSE_EXIT;
10299 return Expression::traverse(&this->index_, traverse);
10302 // Return the type of a map index.
10305 Map_index_expression::do_type()
10307 Map_type* mt = this->get_map_type();
10309 return Type::make_error_type();
10310 Type* type = mt->val_type();
10311 // If this map index is in a tuple assignment, we actually return a
10312 // pointer to the value type. Tuple_map_assignment_statement is
10313 // responsible for handling this correctly. We need to get the type
10314 // right in case this gets assigned to a temporary variable.
10315 if (this->is_in_tuple_assignment_)
10316 type = Type::make_pointer_type(type);
10320 // Fix the type of a map index.
10323 Map_index_expression::do_determine_type(const Type_context*)
10325 this->map_->determine_type_no_context();
10326 Map_type* mt = this->get_map_type();
10327 Type* key_type = mt == NULL ? NULL : mt->key_type();
10328 Type_context subcontext(key_type, false);
10329 this->index_->determine_type(&subcontext);
10332 // Check types of a map index.
10335 Map_index_expression::do_check_types(Gogo*)
10337 std::string reason;
10338 Map_type* mt = this->get_map_type();
10341 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10343 if (reason.empty())
10344 this->report_error(_("incompatible type for map index"));
10347 error_at(this->location(), "incompatible type for map index (%s)",
10349 this->set_is_error();
10354 // Get a tree for a map index.
10357 Map_index_expression::do_get_tree(Translate_context* context)
10359 Map_type* type = this->get_map_type();
10361 return error_mark_node;
10363 tree valptr = this->get_value_pointer(context, this->is_lvalue_);
10364 if (valptr == error_mark_node)
10365 return error_mark_node;
10366 valptr = save_expr(valptr);
10368 tree val_type_tree = TREE_TYPE(TREE_TYPE(valptr));
10370 if (this->is_lvalue_)
10371 return build_fold_indirect_ref(valptr);
10372 else if (this->is_in_tuple_assignment_)
10374 // Tuple_map_assignment_statement is responsible for using this
10380 Gogo* gogo = context->gogo();
10381 Btype* val_btype = type->val_type()->get_backend(gogo);
10382 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10383 return fold_build3(COND_EXPR, val_type_tree,
10384 fold_build2(EQ_EXPR, boolean_type_node, valptr,
10385 fold_convert(TREE_TYPE(valptr),
10386 null_pointer_node)),
10387 expr_to_tree(val_zero),
10388 build_fold_indirect_ref(valptr));
10392 // Get a tree for the map index. This returns a tree which evaluates
10393 // to a pointer to a value. The pointer will be NULL if the key is
10397 Map_index_expression::get_value_pointer(Translate_context* context,
10400 Map_type* type = this->get_map_type();
10402 return error_mark_node;
10404 tree map_tree = this->map_->get_tree(context);
10405 tree index_tree = this->index_->get_tree(context);
10406 index_tree = Expression::convert_for_assignment(context, type->key_type(),
10407 this->index_->type(),
10410 if (map_tree == error_mark_node || index_tree == error_mark_node)
10411 return error_mark_node;
10413 if (this->map_->type()->points_to() != NULL)
10414 map_tree = build_fold_indirect_ref(map_tree);
10416 // We need to pass in a pointer to the key, so stuff it into a
10420 if (current_function_decl != NULL)
10422 tmp = create_tmp_var(TREE_TYPE(index_tree), get_name(index_tree));
10423 DECL_IGNORED_P(tmp) = 0;
10424 DECL_INITIAL(tmp) = index_tree;
10425 make_tmp = build1(DECL_EXPR, void_type_node, tmp);
10426 TREE_ADDRESSABLE(tmp) = 1;
10430 tmp = build_decl(this->location().gcc_location(), VAR_DECL,
10431 create_tmp_var_name("M"),
10432 TREE_TYPE(index_tree));
10433 DECL_EXTERNAL(tmp) = 0;
10434 TREE_PUBLIC(tmp) = 0;
10435 TREE_STATIC(tmp) = 1;
10436 DECL_ARTIFICIAL(tmp) = 1;
10437 if (!TREE_CONSTANT(index_tree))
10438 make_tmp = fold_build2_loc(this->location().gcc_location(),
10439 INIT_EXPR, void_type_node,
10443 TREE_READONLY(tmp) = 1;
10444 TREE_CONSTANT(tmp) = 1;
10445 DECL_INITIAL(tmp) = index_tree;
10446 make_tmp = NULL_TREE;
10448 rest_of_decl_compilation(tmp, 1, 0);
10451 fold_convert_loc(this->location().gcc_location(), const_ptr_type_node,
10452 build_fold_addr_expr_loc(this->location().gcc_location(),
10455 static tree map_index_fndecl;
10456 tree call = Gogo::call_builtin(&map_index_fndecl,
10460 const_ptr_type_node,
10461 TREE_TYPE(map_tree),
10463 const_ptr_type_node,
10467 ? boolean_true_node
10468 : boolean_false_node));
10469 if (call == error_mark_node)
10470 return error_mark_node;
10471 // This can panic on a map of interface type if the interface holds
10472 // an uncomparable or unhashable type.
10473 TREE_NOTHROW(map_index_fndecl) = 0;
10475 Type* val_type = type->val_type();
10476 tree val_type_tree = type_to_tree(val_type->get_backend(context->gogo()));
10477 if (val_type_tree == error_mark_node)
10478 return error_mark_node;
10479 tree ptr_val_type_tree = build_pointer_type(val_type_tree);
10481 tree ret = fold_convert_loc(this->location().gcc_location(),
10482 ptr_val_type_tree, call);
10483 if (make_tmp != NULL_TREE)
10484 ret = build2(COMPOUND_EXPR, ptr_val_type_tree, make_tmp, ret);
10488 // Dump ast representation for a map index expression
10491 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10494 Index_expression::dump_index_expression(ast_dump_context,
10495 this->map_, this->index_, NULL);
10498 // Make a map index expression.
10500 Map_index_expression*
10501 Expression::make_map_index(Expression* map, Expression* index,
10504 return new Map_index_expression(map, index, location);
10507 // Class Field_reference_expression.
10509 // Return the type of a field reference.
10512 Field_reference_expression::do_type()
10514 Type* type = this->expr_->type();
10515 if (type->is_error())
10517 Struct_type* struct_type = type->struct_type();
10518 go_assert(struct_type != NULL);
10519 return struct_type->field(this->field_index_)->type();
10522 // Check the types for a field reference.
10525 Field_reference_expression::do_check_types(Gogo*)
10527 Type* type = this->expr_->type();
10528 if (type->is_error())
10530 Struct_type* struct_type = type->struct_type();
10531 go_assert(struct_type != NULL);
10532 go_assert(struct_type->field(this->field_index_) != NULL);
10535 // Get a tree for a field reference.
10538 Field_reference_expression::do_get_tree(Translate_context* context)
10540 tree struct_tree = this->expr_->get_tree(context);
10541 if (struct_tree == error_mark_node
10542 || TREE_TYPE(struct_tree) == error_mark_node)
10543 return error_mark_node;
10544 go_assert(TREE_CODE(TREE_TYPE(struct_tree)) == RECORD_TYPE);
10545 tree field = TYPE_FIELDS(TREE_TYPE(struct_tree));
10546 if (field == NULL_TREE)
10548 // This can happen for a type which refers to itself indirectly
10549 // and then turns out to be erroneous.
10550 go_assert(saw_errors());
10551 return error_mark_node;
10553 for (unsigned int i = this->field_index_; i > 0; --i)
10555 field = DECL_CHAIN(field);
10556 go_assert(field != NULL_TREE);
10558 if (TREE_TYPE(field) == error_mark_node)
10559 return error_mark_node;
10560 return build3(COMPONENT_REF, TREE_TYPE(field), struct_tree, field,
10564 // Dump ast representation for a field reference expression.
10567 Field_reference_expression::do_dump_expression(
10568 Ast_dump_context* ast_dump_context) const
10570 this->expr_->dump_expression(ast_dump_context);
10571 ast_dump_context->ostream() << "." << this->field_index_;
10574 // Make a reference to a qualified identifier in an expression.
10576 Field_reference_expression*
10577 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10580 return new Field_reference_expression(expr, field_index, location);
10583 // Class Interface_field_reference_expression.
10585 // Return a tree for the pointer to the function to call.
10588 Interface_field_reference_expression::get_function_tree(Translate_context*,
10591 if (this->expr_->type()->points_to() != NULL)
10592 expr = build_fold_indirect_ref(expr);
10594 tree expr_type = TREE_TYPE(expr);
10595 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10597 tree field = TYPE_FIELDS(expr_type);
10598 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__methods") == 0);
10600 tree table = build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10601 go_assert(POINTER_TYPE_P(TREE_TYPE(table)));
10603 table = build_fold_indirect_ref(table);
10604 go_assert(TREE_CODE(TREE_TYPE(table)) == RECORD_TYPE);
10606 std::string name = Gogo::unpack_hidden_name(this->name_);
10607 for (field = DECL_CHAIN(TYPE_FIELDS(TREE_TYPE(table)));
10608 field != NULL_TREE;
10609 field = DECL_CHAIN(field))
10611 if (name == IDENTIFIER_POINTER(DECL_NAME(field)))
10614 go_assert(field != NULL_TREE);
10616 return build3(COMPONENT_REF, TREE_TYPE(field), table, field, NULL_TREE);
10619 // Return a tree for the first argument to pass to the interface
10623 Interface_field_reference_expression::get_underlying_object_tree(
10624 Translate_context*,
10627 if (this->expr_->type()->points_to() != NULL)
10628 expr = build_fold_indirect_ref(expr);
10630 tree expr_type = TREE_TYPE(expr);
10631 go_assert(TREE_CODE(expr_type) == RECORD_TYPE);
10633 tree field = DECL_CHAIN(TYPE_FIELDS(expr_type));
10634 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__object") == 0);
10636 return build3(COMPONENT_REF, TREE_TYPE(field), expr, field, NULL_TREE);
10642 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10644 return Expression::traverse(&this->expr_, traverse);
10647 // Return the type of an interface field reference.
10650 Interface_field_reference_expression::do_type()
10652 Type* expr_type = this->expr_->type();
10654 Type* points_to = expr_type->points_to();
10655 if (points_to != NULL)
10656 expr_type = points_to;
10658 Interface_type* interface_type = expr_type->interface_type();
10659 if (interface_type == NULL)
10660 return Type::make_error_type();
10662 const Typed_identifier* method = interface_type->find_method(this->name_);
10663 if (method == NULL)
10664 return Type::make_error_type();
10666 return method->type();
10669 // Determine types.
10672 Interface_field_reference_expression::do_determine_type(const Type_context*)
10674 this->expr_->determine_type_no_context();
10677 // Check the types for an interface field reference.
10680 Interface_field_reference_expression::do_check_types(Gogo*)
10682 Type* type = this->expr_->type();
10684 Type* points_to = type->points_to();
10685 if (points_to != NULL)
10688 Interface_type* interface_type = type->interface_type();
10689 if (interface_type == NULL)
10691 if (!type->is_error_type())
10692 this->report_error(_("expected interface or pointer to interface"));
10696 const Typed_identifier* method =
10697 interface_type->find_method(this->name_);
10698 if (method == NULL)
10700 error_at(this->location(), "method %qs not in interface",
10701 Gogo::message_name(this->name_).c_str());
10702 this->set_is_error();
10707 // Get a tree for a reference to a field in an interface. There is no
10708 // standard tree type representation for this: it's a function
10709 // attached to its first argument, like a Bound_method_expression.
10710 // The only places it may currently be used are in a Call_expression
10711 // or a Go_statement, which will take it apart directly. So this has
10712 // nothing to do at present.
10715 Interface_field_reference_expression::do_get_tree(Translate_context*)
10717 error_at(this->location(), "reference to method other than calling it");
10718 return error_mark_node;
10721 // Dump ast representation for an interface field reference.
10724 Interface_field_reference_expression::do_dump_expression(
10725 Ast_dump_context* ast_dump_context) const
10727 this->expr_->dump_expression(ast_dump_context);
10728 ast_dump_context->ostream() << "." << this->name_;
10731 // Make a reference to a field in an interface.
10734 Expression::make_interface_field_reference(Expression* expr,
10735 const std::string& field,
10738 return new Interface_field_reference_expression(expr, field, location);
10741 // A general selector. This is a Parser_expression for LEFT.NAME. It
10742 // is lowered after we know the type of the left hand side.
10744 class Selector_expression : public Parser_expression
10747 Selector_expression(Expression* left, const std::string& name,
10749 : Parser_expression(EXPRESSION_SELECTOR, location),
10750 left_(left), name_(name)
10755 do_traverse(Traverse* traverse)
10756 { return Expression::traverse(&this->left_, traverse); }
10759 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
10764 return new Selector_expression(this->left_->copy(), this->name_,
10769 do_dump_expression(Ast_dump_context* ast_dump_context) const;
10773 lower_method_expression(Gogo*);
10775 // The expression on the left hand side.
10777 // The name on the right hand side.
10781 // Lower a selector expression once we know the real type of the left
10785 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
10788 Expression* left = this->left_;
10789 if (left->is_type_expression())
10790 return this->lower_method_expression(gogo);
10791 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
10795 // Lower a method expression T.M or (*T).M. We turn this into a
10796 // function literal.
10799 Selector_expression::lower_method_expression(Gogo* gogo)
10801 Location location = this->location();
10802 Type* type = this->left_->type();
10803 const std::string& name(this->name_);
10806 if (type->points_to() == NULL)
10807 is_pointer = false;
10811 type = type->points_to();
10813 Named_type* nt = type->named_type();
10817 ("method expression requires named type or "
10818 "pointer to named type"));
10819 return Expression::make_error(location);
10823 Method* method = nt->method_function(name, &is_ambiguous);
10824 const Typed_identifier* imethod = NULL;
10825 if (method == NULL && !is_pointer)
10827 Interface_type* it = nt->interface_type();
10829 imethod = it->find_method(name);
10832 if (method == NULL && imethod == NULL)
10835 error_at(location, "type %<%s%s%> has no method %<%s%>",
10836 is_pointer ? "*" : "",
10837 nt->message_name().c_str(),
10838 Gogo::message_name(name).c_str());
10840 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
10841 Gogo::message_name(name).c_str(),
10842 is_pointer ? "*" : "",
10843 nt->message_name().c_str());
10844 return Expression::make_error(location);
10847 if (method != NULL && !is_pointer && !method->is_value_method())
10849 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
10850 nt->message_name().c_str(),
10851 Gogo::message_name(name).c_str());
10852 return Expression::make_error(location);
10855 // Build a new function type in which the receiver becomes the first
10857 Function_type* method_type;
10858 if (method != NULL)
10860 method_type = method->type();
10861 go_assert(method_type->is_method());
10865 method_type = imethod->type()->function_type();
10866 go_assert(method_type != NULL && !method_type->is_method());
10869 const char* const receiver_name = "$this";
10870 Typed_identifier_list* parameters = new Typed_identifier_list();
10871 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
10874 const Typed_identifier_list* method_parameters = method_type->parameters();
10875 if (method_parameters != NULL)
10878 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
10879 p != method_parameters->end();
10882 if (!p->name().empty())
10883 parameters->push_back(*p);
10887 snprintf(buf, sizeof buf, "$param%d", i);
10888 parameters->push_back(Typed_identifier(buf, p->type(),
10894 const Typed_identifier_list* method_results = method_type->results();
10895 Typed_identifier_list* results;
10896 if (method_results == NULL)
10900 results = new Typed_identifier_list();
10901 for (Typed_identifier_list::const_iterator p = method_results->begin();
10902 p != method_results->end();
10904 results->push_back(*p);
10907 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
10909 if (method_type->is_varargs())
10910 fntype->set_is_varargs();
10912 // We generate methods which always takes a pointer to the receiver
10913 // as their first argument. If this is for a pointer type, we can
10914 // simply reuse the existing function. We use an internal hack to
10915 // get the right type.
10917 if (method != NULL && is_pointer)
10919 Named_object* mno = (method->needs_stub_method()
10920 ? method->stub_object()
10921 : method->named_object());
10922 Expression* f = Expression::make_func_reference(mno, NULL, location);
10923 f = Expression::make_cast(fntype, f, location);
10924 Type_conversion_expression* tce =
10925 static_cast<Type_conversion_expression*>(f);
10926 tce->set_may_convert_function_types();
10930 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
10933 Named_object* vno = gogo->lookup(receiver_name, NULL);
10934 go_assert(vno != NULL);
10935 Expression* ve = Expression::make_var_reference(vno, location);
10937 if (method != NULL)
10938 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
10940 bm = Expression::make_interface_field_reference(ve, name, location);
10942 // Even though we found the method above, if it has an error type we
10943 // may see an error here.
10944 if (bm->is_error_expression())
10946 gogo->finish_function(location);
10950 Expression_list* args;
10951 if (parameters->size() <= 1)
10955 args = new Expression_list();
10956 Typed_identifier_list::const_iterator p = parameters->begin();
10958 for (; p != parameters->end(); ++p)
10960 vno = gogo->lookup(p->name(), NULL);
10961 go_assert(vno != NULL);
10962 args->push_back(Expression::make_var_reference(vno, location));
10966 gogo->start_block(location);
10968 Call_expression* call = Expression::make_call(bm, args,
10969 method_type->is_varargs(),
10972 size_t count = call->result_count();
10975 s = Statement::make_statement(call, true);
10978 Expression_list* retvals = new Expression_list();
10980 retvals->push_back(call);
10983 for (size_t i = 0; i < count; ++i)
10984 retvals->push_back(Expression::make_call_result(call, i));
10986 s = Statement::make_return_statement(retvals, location);
10988 gogo->add_statement(s);
10990 Block* b = gogo->finish_block(location);
10992 gogo->add_block(b, location);
10994 // Lower the call in case there are multiple results.
10995 gogo->lower_block(no, b);
10997 gogo->finish_function(location);
10999 return Expression::make_func_reference(no, NULL, location);
11002 // Dump the ast for a selector expression.
11005 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11008 ast_dump_context->dump_expression(this->left_);
11009 ast_dump_context->ostream() << ".";
11010 ast_dump_context->ostream() << this->name_;
11013 // Make a selector expression.
11016 Expression::make_selector(Expression* left, const std::string& name,
11019 return new Selector_expression(left, name, location);
11022 // Implement the builtin function new.
11024 class Allocation_expression : public Expression
11027 Allocation_expression(Type* type, Location location)
11028 : Expression(EXPRESSION_ALLOCATION, location),
11034 do_traverse(Traverse* traverse)
11035 { return Type::traverse(this->type_, traverse); }
11039 { return Type::make_pointer_type(this->type_); }
11042 do_determine_type(const Type_context*)
11047 { return new Allocation_expression(this->type_, this->location()); }
11050 do_get_tree(Translate_context*);
11053 do_dump_expression(Ast_dump_context*) const;
11056 // The type we are allocating.
11060 // Return a tree for an allocation expression.
11063 Allocation_expression::do_get_tree(Translate_context* context)
11065 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
11066 if (type_tree == error_mark_node)
11067 return error_mark_node;
11068 tree size_tree = TYPE_SIZE_UNIT(type_tree);
11069 tree space = context->gogo()->allocate_memory(this->type_, size_tree,
11071 if (space == error_mark_node)
11072 return error_mark_node;
11073 return fold_convert(build_pointer_type(type_tree), space);
11076 // Dump ast representation for an allocation expression.
11079 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11082 ast_dump_context->ostream() << "new(";
11083 ast_dump_context->dump_type(this->type_);
11084 ast_dump_context->ostream() << ")";
11087 // Make an allocation expression.
11090 Expression::make_allocation(Type* type, Location location)
11092 return new Allocation_expression(type, location);
11095 // Construct a struct.
11097 class Struct_construction_expression : public Expression
11100 Struct_construction_expression(Type* type, Expression_list* vals,
11102 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11103 type_(type), vals_(vals), traverse_order_(NULL)
11106 // Set the traversal order, used to ensure that we implement the
11107 // order of evaluation rules. Takes ownership of the argument.
11109 set_traverse_order(std::vector<int>* traverse_order)
11110 { this->traverse_order_ = traverse_order; }
11112 // Return whether this is a constant initializer.
11114 is_constant_struct() const;
11118 do_traverse(Traverse* traverse);
11122 { return this->type_; }
11125 do_determine_type(const Type_context*);
11128 do_check_types(Gogo*);
11133 Struct_construction_expression* ret =
11134 new Struct_construction_expression(this->type_, this->vals_->copy(),
11136 if (this->traverse_order_ != NULL)
11137 ret->set_traverse_order(this->traverse_order_);
11142 do_get_tree(Translate_context*);
11145 do_export(Export*) const;
11148 do_dump_expression(Ast_dump_context*) const;
11151 // The type of the struct to construct.
11153 // The list of values, in order of the fields in the struct. A NULL
11154 // entry means that the field should be zero-initialized.
11155 Expression_list* vals_;
11156 // If not NULL, the order in which to traverse vals_. This is used
11157 // so that we implement the order of evaluation rules correctly.
11158 std::vector<int>* traverse_order_;
11164 Struct_construction_expression::do_traverse(Traverse* traverse)
11166 if (this->vals_ != NULL)
11168 if (this->traverse_order_ == NULL)
11170 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11171 return TRAVERSE_EXIT;
11175 for (std::vector<int>::const_iterator p =
11176 this->traverse_order_->begin();
11177 p != this->traverse_order_->end();
11180 if (Expression::traverse(&this->vals_->at(*p), traverse)
11182 return TRAVERSE_EXIT;
11186 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11187 return TRAVERSE_EXIT;
11188 return TRAVERSE_CONTINUE;
11191 // Return whether this is a constant initializer.
11194 Struct_construction_expression::is_constant_struct() const
11196 if (this->vals_ == NULL)
11198 for (Expression_list::const_iterator pv = this->vals_->begin();
11199 pv != this->vals_->end();
11203 && !(*pv)->is_constant()
11204 && (!(*pv)->is_composite_literal()
11205 || (*pv)->is_nonconstant_composite_literal()))
11209 const Struct_field_list* fields = this->type_->struct_type()->fields();
11210 for (Struct_field_list::const_iterator pf = fields->begin();
11211 pf != fields->end();
11214 // There are no constant constructors for interfaces.
11215 if (pf->type()->interface_type() != NULL)
11222 // Final type determination.
11225 Struct_construction_expression::do_determine_type(const Type_context*)
11227 if (this->vals_ == NULL)
11229 const Struct_field_list* fields = this->type_->struct_type()->fields();
11230 Expression_list::const_iterator pv = this->vals_->begin();
11231 for (Struct_field_list::const_iterator pf = fields->begin();
11232 pf != fields->end();
11235 if (pv == this->vals_->end())
11239 Type_context subcontext(pf->type(), false);
11240 (*pv)->determine_type(&subcontext);
11243 // Extra values are an error we will report elsewhere; we still want
11244 // to determine the type to avoid knockon errors.
11245 for (; pv != this->vals_->end(); ++pv)
11246 (*pv)->determine_type_no_context();
11252 Struct_construction_expression::do_check_types(Gogo*)
11254 if (this->vals_ == NULL)
11257 Struct_type* st = this->type_->struct_type();
11258 if (this->vals_->size() > st->field_count())
11260 this->report_error(_("too many expressions for struct"));
11264 const Struct_field_list* fields = st->fields();
11265 Expression_list::const_iterator pv = this->vals_->begin();
11267 for (Struct_field_list::const_iterator pf = fields->begin();
11268 pf != fields->end();
11271 if (pv == this->vals_->end())
11273 this->report_error(_("too few expressions for struct"));
11280 std::string reason;
11281 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11283 if (reason.empty())
11284 error_at((*pv)->location(),
11285 "incompatible type for field %d in struct construction",
11288 error_at((*pv)->location(),
11289 ("incompatible type for field %d in "
11290 "struct construction (%s)"),
11291 i + 1, reason.c_str());
11292 this->set_is_error();
11295 go_assert(pv == this->vals_->end());
11298 // Return a tree for constructing a struct.
11301 Struct_construction_expression::do_get_tree(Translate_context* context)
11303 Gogo* gogo = context->gogo();
11305 if (this->vals_ == NULL)
11307 Btype* btype = this->type_->get_backend(gogo);
11308 return expr_to_tree(gogo->backend()->zero_expression(btype));
11311 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
11312 if (type_tree == error_mark_node)
11313 return error_mark_node;
11314 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11316 bool is_constant = true;
11317 const Struct_field_list* fields = this->type_->struct_type()->fields();
11318 VEC(constructor_elt,gc)* elts = VEC_alloc(constructor_elt, gc,
11320 Struct_field_list::const_iterator pf = fields->begin();
11321 Expression_list::const_iterator pv = this->vals_->begin();
11322 for (tree field = TYPE_FIELDS(type_tree);
11323 field != NULL_TREE;
11324 field = DECL_CHAIN(field), ++pf)
11326 go_assert(pf != fields->end());
11328 Btype* fbtype = pf->type()->get_backend(gogo);
11331 if (pv == this->vals_->end())
11332 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11333 else if (*pv == NULL)
11335 val = expr_to_tree(gogo->backend()->zero_expression(fbtype));
11340 val = Expression::convert_for_assignment(context, pf->type(),
11342 (*pv)->get_tree(context),
11347 if (val == error_mark_node || TREE_TYPE(val) == error_mark_node)
11348 return error_mark_node;
11350 constructor_elt* elt = VEC_quick_push(constructor_elt, elts, NULL);
11351 elt->index = field;
11353 if (!TREE_CONSTANT(val))
11354 is_constant = false;
11356 go_assert(pf == fields->end());
11358 tree ret = build_constructor(type_tree, elts);
11360 TREE_CONSTANT(ret) = 1;
11364 // Export a struct construction.
11367 Struct_construction_expression::do_export(Export* exp) const
11369 exp->write_c_string("convert(");
11370 exp->write_type(this->type_);
11371 for (Expression_list::const_iterator pv = this->vals_->begin();
11372 pv != this->vals_->end();
11375 exp->write_c_string(", ");
11377 (*pv)->export_expression(exp);
11379 exp->write_c_string(")");
11382 // Dump ast representation of a struct construction expression.
11385 Struct_construction_expression::do_dump_expression(
11386 Ast_dump_context* ast_dump_context) const
11388 ast_dump_context->dump_type(this->type_);
11389 ast_dump_context->ostream() << "{";
11390 ast_dump_context->dump_expression_list(this->vals_);
11391 ast_dump_context->ostream() << "}";
11394 // Make a struct composite literal. This used by the thunk code.
11397 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11400 go_assert(type->struct_type() != NULL);
11401 return new Struct_construction_expression(type, vals, location);
11404 // Construct an array. This class is not used directly; instead we
11405 // use the child classes, Fixed_array_construction_expression and
11406 // Open_array_construction_expression.
11408 class Array_construction_expression : public Expression
11411 Array_construction_expression(Expression_classification classification,
11413 const std::vector<unsigned long>* indexes,
11414 Expression_list* vals, Location location)
11415 : Expression(classification, location),
11416 type_(type), indexes_(indexes), vals_(vals)
11417 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
11420 // Return whether this is a constant initializer.
11422 is_constant_array() const;
11424 // Return the number of elements.
11426 element_count() const
11427 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
11431 do_traverse(Traverse* traverse);
11435 { return this->type_; }
11438 do_determine_type(const Type_context*);
11441 do_check_types(Gogo*);
11444 do_export(Export*) const;
11447 const std::vector<unsigned long>*
11449 { return this->indexes_; }
11451 // The list of values.
11454 { return this->vals_; }
11456 // Get a constructor tree for the array values.
11458 get_constructor_tree(Translate_context* context, tree type_tree);
11461 do_dump_expression(Ast_dump_context*) const;
11464 // The type of the array to construct.
11466 // The list of indexes into the array, one for each value. This may
11467 // be NULL, in which case the indexes start at zero and increment.
11468 const std::vector<unsigned long>* indexes_;
11469 // The list of values. This may be NULL if there are no values.
11470 Expression_list* vals_;
11476 Array_construction_expression::do_traverse(Traverse* traverse)
11478 if (this->vals_ != NULL
11479 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11480 return TRAVERSE_EXIT;
11481 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11482 return TRAVERSE_EXIT;
11483 return TRAVERSE_CONTINUE;
11486 // Return whether this is a constant initializer.
11489 Array_construction_expression::is_constant_array() const
11491 if (this->vals_ == NULL)
11494 // There are no constant constructors for interfaces.
11495 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11498 for (Expression_list::const_iterator pv = this->vals_->begin();
11499 pv != this->vals_->end();
11503 && !(*pv)->is_constant()
11504 && (!(*pv)->is_composite_literal()
11505 || (*pv)->is_nonconstant_composite_literal()))
11511 // Final type determination.
11514 Array_construction_expression::do_determine_type(const Type_context*)
11516 if (this->vals_ == NULL)
11518 Type_context subcontext(this->type_->array_type()->element_type(), false);
11519 for (Expression_list::const_iterator pv = this->vals_->begin();
11520 pv != this->vals_->end();
11524 (*pv)->determine_type(&subcontext);
11531 Array_construction_expression::do_check_types(Gogo*)
11533 if (this->vals_ == NULL)
11536 Array_type* at = this->type_->array_type();
11538 Type* element_type = at->element_type();
11539 for (Expression_list::const_iterator pv = this->vals_->begin();
11540 pv != this->vals_->end();
11544 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11546 error_at((*pv)->location(),
11547 "incompatible type for element %d in composite literal",
11549 this->set_is_error();
11554 // Get a constructor tree for the array values.
11557 Array_construction_expression::get_constructor_tree(Translate_context* context,
11560 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
11561 (this->vals_ == NULL
11563 : this->vals_->size()));
11564 Type* element_type = this->type_->array_type()->element_type();
11565 bool is_constant = true;
11566 if (this->vals_ != NULL)
11569 std::vector<unsigned long>::const_iterator pi;
11570 if (this->indexes_ != NULL)
11571 pi = this->indexes_->begin();
11572 for (Expression_list::const_iterator pv = this->vals_->begin();
11573 pv != this->vals_->end();
11576 if (this->indexes_ != NULL)
11577 go_assert(pi != this->indexes_->end());
11578 constructor_elt* elt = VEC_quick_push(constructor_elt, values, NULL);
11580 if (this->indexes_ == NULL)
11581 elt->index = size_int(i);
11583 elt->index = size_int(*pi);
11587 Gogo* gogo = context->gogo();
11588 Btype* ebtype = element_type->get_backend(gogo);
11589 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11590 elt->value = expr_to_tree(zv);
11594 tree value_tree = (*pv)->get_tree(context);
11595 elt->value = Expression::convert_for_assignment(context,
11601 if (elt->value == error_mark_node)
11602 return error_mark_node;
11603 if (!TREE_CONSTANT(elt->value))
11604 is_constant = false;
11605 if (this->indexes_ != NULL)
11608 if (this->indexes_ != NULL)
11609 go_assert(pi == this->indexes_->end());
11612 tree ret = build_constructor(type_tree, values);
11614 TREE_CONSTANT(ret) = 1;
11618 // Export an array construction.
11621 Array_construction_expression::do_export(Export* exp) const
11623 exp->write_c_string("convert(");
11624 exp->write_type(this->type_);
11625 if (this->vals_ != NULL)
11627 std::vector<unsigned long>::const_iterator pi;
11628 if (this->indexes_ != NULL)
11629 pi = this->indexes_->begin();
11630 for (Expression_list::const_iterator pv = this->vals_->begin();
11631 pv != this->vals_->end();
11634 exp->write_c_string(", ");
11636 if (this->indexes_ != NULL)
11639 snprintf(buf, sizeof buf, "%lu", *pi);
11640 exp->write_c_string(buf);
11641 exp->write_c_string(":");
11645 (*pv)->export_expression(exp);
11647 if (this->indexes_ != NULL)
11651 exp->write_c_string(")");
11654 // Dump ast representation of an array construction expressin.
11657 Array_construction_expression::do_dump_expression(
11658 Ast_dump_context* ast_dump_context) const
11660 Expression* length = this->type_->array_type()->length();
11662 ast_dump_context->ostream() << "[" ;
11663 if (length != NULL)
11665 ast_dump_context->dump_expression(length);
11667 ast_dump_context->ostream() << "]" ;
11668 ast_dump_context->dump_type(this->type_);
11669 ast_dump_context->ostream() << "{" ;
11670 if (this->indexes_ == NULL)
11671 ast_dump_context->dump_expression_list(this->vals_);
11674 Expression_list::const_iterator pv = this->vals_->begin();
11675 for (std::vector<unsigned long>::const_iterator pi =
11676 this->indexes_->begin();
11677 pi != this->indexes_->end();
11680 if (pi != this->indexes_->begin())
11681 ast_dump_context->ostream() << ", ";
11682 ast_dump_context->ostream() << *pi << ':';
11683 ast_dump_context->dump_expression(*pv);
11686 ast_dump_context->ostream() << "}" ;
11690 // Construct a fixed array.
11692 class Fixed_array_construction_expression :
11693 public Array_construction_expression
11696 Fixed_array_construction_expression(Type* type,
11697 const std::vector<unsigned long>* indexes,
11698 Expression_list* vals, Location location)
11699 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11700 type, indexes, vals, location)
11701 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
11707 return new Fixed_array_construction_expression(this->type(),
11709 (this->vals() == NULL
11711 : this->vals()->copy()),
11716 do_get_tree(Translate_context*);
11719 // Return a tree for constructing a fixed array.
11722 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
11724 Type* type = this->type();
11725 Btype* btype = type->get_backend(context->gogo());
11726 return this->get_constructor_tree(context, type_to_tree(btype));
11729 // Construct an open array.
11731 class Open_array_construction_expression : public Array_construction_expression
11734 Open_array_construction_expression(Type* type,
11735 const std::vector<unsigned long>* indexes,
11736 Expression_list* vals, Location location)
11737 : Array_construction_expression(EXPRESSION_OPEN_ARRAY_CONSTRUCTION,
11738 type, indexes, vals, location)
11739 { go_assert(type->is_slice_type()); }
11742 // Note that taking the address of an open array literal is invalid.
11747 return new Open_array_construction_expression(this->type(),
11749 (this->vals() == NULL
11751 : this->vals()->copy()),
11756 do_get_tree(Translate_context*);
11759 // Return a tree for constructing an open array.
11762 Open_array_construction_expression::do_get_tree(Translate_context* context)
11764 Array_type* array_type = this->type()->array_type();
11765 if (array_type == NULL)
11767 go_assert(this->type()->is_error());
11768 return error_mark_node;
11771 Type* element_type = array_type->element_type();
11772 Btype* belement_type = element_type->get_backend(context->gogo());
11773 tree element_type_tree = type_to_tree(belement_type);
11774 if (element_type_tree == error_mark_node)
11775 return error_mark_node;
11779 if (this->vals() == NULL || this->vals()->empty())
11781 // We need to create a unique value.
11782 tree max = size_int(0);
11783 tree constructor_type = build_array_type(element_type_tree,
11784 build_index_type(max));
11785 if (constructor_type == error_mark_node)
11786 return error_mark_node;
11787 VEC(constructor_elt,gc)* vec = VEC_alloc(constructor_elt, gc, 1);
11788 constructor_elt* elt = VEC_quick_push(constructor_elt, vec, NULL);
11789 elt->index = size_int(0);
11790 Gogo* gogo = context->gogo();
11791 Btype* btype = element_type->get_backend(gogo);
11792 elt->value = expr_to_tree(gogo->backend()->zero_expression(btype));
11793 values = build_constructor(constructor_type, vec);
11794 if (TREE_CONSTANT(elt->value))
11795 TREE_CONSTANT(values) = 1;
11796 length_tree = size_int(0);
11800 unsigned long max_index;
11801 if (this->indexes() == NULL)
11802 max_index = this->vals()->size() - 1;
11804 max_index = this->indexes()->back();
11805 tree max_tree = size_int(max_index);
11806 tree constructor_type = build_array_type(element_type_tree,
11807 build_index_type(max_tree));
11808 if (constructor_type == error_mark_node)
11809 return error_mark_node;
11810 values = this->get_constructor_tree(context, constructor_type);
11811 length_tree = size_int(max_index + 1);
11814 if (values == error_mark_node)
11815 return error_mark_node;
11817 bool is_constant_initializer = TREE_CONSTANT(values);
11819 // We have to copy the initial values into heap memory if we are in
11820 // a function or if the values are not constants. We also have to
11821 // copy them if they may contain pointers in a non-constant context,
11822 // as otherwise the garbage collector won't see them.
11823 bool copy_to_heap = (context->function() != NULL
11824 || !is_constant_initializer
11825 || (element_type->has_pointer()
11826 && !context->is_const()));
11828 if (is_constant_initializer)
11830 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
11831 create_tmp_var_name("C"), TREE_TYPE(values));
11832 DECL_EXTERNAL(tmp) = 0;
11833 TREE_PUBLIC(tmp) = 0;
11834 TREE_STATIC(tmp) = 1;
11835 DECL_ARTIFICIAL(tmp) = 1;
11838 // If we are not copying the value to the heap, we will only
11839 // initialize the value once, so we can use this directly
11840 // rather than copying it. In that case we can't make it
11841 // read-only, because the program is permitted to change it.
11842 TREE_READONLY(tmp) = 1;
11843 TREE_CONSTANT(tmp) = 1;
11845 DECL_INITIAL(tmp) = values;
11846 rest_of_decl_compilation(tmp, 1, 0);
11854 // the initializer will only run once.
11855 space = build_fold_addr_expr(values);
11860 tree memsize = TYPE_SIZE_UNIT(TREE_TYPE(values));
11861 space = context->gogo()->allocate_memory(element_type, memsize,
11863 space = save_expr(space);
11865 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
11866 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
11868 TREE_THIS_NOTRAP(ref) = 1;
11869 set = build2(MODIFY_EXPR, void_type_node, ref, values);
11872 // Build a constructor for the open array.
11874 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
11875 if (type_tree == error_mark_node)
11876 return error_mark_node;
11877 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
11879 VEC(constructor_elt,gc)* init = VEC_alloc(constructor_elt, gc, 3);
11881 constructor_elt* elt = VEC_quick_push(constructor_elt, init, NULL);
11882 tree field = TYPE_FIELDS(type_tree);
11883 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
11884 elt->index = field;
11885 elt->value = fold_convert(TREE_TYPE(field), space);
11887 elt = VEC_quick_push(constructor_elt, init, NULL);
11888 field = DECL_CHAIN(field);
11889 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
11890 elt->index = field;
11891 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11893 elt = VEC_quick_push(constructor_elt, init, NULL);
11894 field = DECL_CHAIN(field);
11895 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
11896 elt->index = field;
11897 elt->value = fold_convert(TREE_TYPE(field), length_tree);
11899 tree constructor = build_constructor(type_tree, init);
11900 if (constructor == error_mark_node)
11901 return error_mark_node;
11903 TREE_CONSTANT(constructor) = 1;
11905 if (set == NULL_TREE)
11906 return constructor;
11908 return build2(COMPOUND_EXPR, type_tree, set, constructor);
11911 // Make a slice composite literal. This is used by the type
11912 // descriptor code.
11915 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
11918 go_assert(type->is_slice_type());
11919 return new Open_array_construction_expression(type, NULL, vals, location);
11922 // Construct a map.
11924 class Map_construction_expression : public Expression
11927 Map_construction_expression(Type* type, Expression_list* vals,
11929 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
11930 type_(type), vals_(vals)
11931 { go_assert(vals == NULL || vals->size() % 2 == 0); }
11935 do_traverse(Traverse* traverse);
11939 { return this->type_; }
11942 do_determine_type(const Type_context*);
11945 do_check_types(Gogo*);
11950 return new Map_construction_expression(this->type_, this->vals_->copy(),
11955 do_get_tree(Translate_context*);
11958 do_export(Export*) const;
11961 do_dump_expression(Ast_dump_context*) const;
11964 // The type of the map to construct.
11966 // The list of values.
11967 Expression_list* vals_;
11973 Map_construction_expression::do_traverse(Traverse* traverse)
11975 if (this->vals_ != NULL
11976 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11977 return TRAVERSE_EXIT;
11978 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11979 return TRAVERSE_EXIT;
11980 return TRAVERSE_CONTINUE;
11983 // Final type determination.
11986 Map_construction_expression::do_determine_type(const Type_context*)
11988 if (this->vals_ == NULL)
11991 Map_type* mt = this->type_->map_type();
11992 Type_context key_context(mt->key_type(), false);
11993 Type_context val_context(mt->val_type(), false);
11994 for (Expression_list::const_iterator pv = this->vals_->begin();
11995 pv != this->vals_->end();
11998 (*pv)->determine_type(&key_context);
12000 (*pv)->determine_type(&val_context);
12007 Map_construction_expression::do_check_types(Gogo*)
12009 if (this->vals_ == NULL)
12012 Map_type* mt = this->type_->map_type();
12014 Type* key_type = mt->key_type();
12015 Type* val_type = mt->val_type();
12016 for (Expression_list::const_iterator pv = this->vals_->begin();
12017 pv != this->vals_->end();
12020 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12022 error_at((*pv)->location(),
12023 "incompatible type for element %d key in map construction",
12025 this->set_is_error();
12028 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12030 error_at((*pv)->location(),
12031 ("incompatible type for element %d value "
12032 "in map construction"),
12034 this->set_is_error();
12039 // Return a tree for constructing a map.
12042 Map_construction_expression::do_get_tree(Translate_context* context)
12044 Gogo* gogo = context->gogo();
12045 Location loc = this->location();
12047 Map_type* mt = this->type_->map_type();
12049 // Build a struct to hold the key and value.
12050 tree struct_type = make_node(RECORD_TYPE);
12052 Type* key_type = mt->key_type();
12053 tree id = get_identifier("__key");
12054 tree key_type_tree = type_to_tree(key_type->get_backend(gogo));
12055 if (key_type_tree == error_mark_node)
12056 return error_mark_node;
12057 tree key_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12059 DECL_CONTEXT(key_field) = struct_type;
12060 TYPE_FIELDS(struct_type) = key_field;
12062 Type* val_type = mt->val_type();
12063 id = get_identifier("__val");
12064 tree val_type_tree = type_to_tree(val_type->get_backend(gogo));
12065 if (val_type_tree == error_mark_node)
12066 return error_mark_node;
12067 tree val_field = build_decl(loc.gcc_location(), FIELD_DECL, id,
12069 DECL_CONTEXT(val_field) = struct_type;
12070 DECL_CHAIN(key_field) = val_field;
12072 layout_type(struct_type);
12074 bool is_constant = true;
12079 if (this->vals_ == NULL || this->vals_->empty())
12081 valaddr = null_pointer_node;
12082 make_tmp = NULL_TREE;
12086 VEC(constructor_elt,gc)* values = VEC_alloc(constructor_elt, gc,
12087 this->vals_->size() / 2);
12089 for (Expression_list::const_iterator pv = this->vals_->begin();
12090 pv != this->vals_->end();
12093 bool one_is_constant = true;
12095 VEC(constructor_elt,gc)* one = VEC_alloc(constructor_elt, gc, 2);
12097 constructor_elt* elt = VEC_quick_push(constructor_elt, one, NULL);
12098 elt->index = key_field;
12099 tree val_tree = (*pv)->get_tree(context);
12100 elt->value = Expression::convert_for_assignment(context, key_type,
12103 if (elt->value == error_mark_node)
12104 return error_mark_node;
12105 if (!TREE_CONSTANT(elt->value))
12106 one_is_constant = false;
12110 elt = VEC_quick_push(constructor_elt, one, NULL);
12111 elt->index = val_field;
12112 val_tree = (*pv)->get_tree(context);
12113 elt->value = Expression::convert_for_assignment(context, val_type,
12116 if (elt->value == error_mark_node)
12117 return error_mark_node;
12118 if (!TREE_CONSTANT(elt->value))
12119 one_is_constant = false;
12121 elt = VEC_quick_push(constructor_elt, values, NULL);
12122 elt->index = size_int(i);
12123 elt->value = build_constructor(struct_type, one);
12124 if (one_is_constant)
12125 TREE_CONSTANT(elt->value) = 1;
12127 is_constant = false;
12130 tree index_type = build_index_type(size_int(i - 1));
12131 tree array_type = build_array_type(struct_type, index_type);
12132 tree init = build_constructor(array_type, values);
12134 TREE_CONSTANT(init) = 1;
12136 if (current_function_decl != NULL)
12138 tmp = create_tmp_var(array_type, get_name(array_type));
12139 DECL_INITIAL(tmp) = init;
12140 make_tmp = fold_build1_loc(loc.gcc_location(), DECL_EXPR,
12141 void_type_node, tmp);
12142 TREE_ADDRESSABLE(tmp) = 1;
12146 tmp = build_decl(loc.gcc_location(), VAR_DECL,
12147 create_tmp_var_name("M"), array_type);
12148 DECL_EXTERNAL(tmp) = 0;
12149 TREE_PUBLIC(tmp) = 0;
12150 TREE_STATIC(tmp) = 1;
12151 DECL_ARTIFICIAL(tmp) = 1;
12152 if (!TREE_CONSTANT(init))
12153 make_tmp = fold_build2_loc(loc.gcc_location(), INIT_EXPR,
12154 void_type_node, tmp, init);
12157 TREE_READONLY(tmp) = 1;
12158 TREE_CONSTANT(tmp) = 1;
12159 DECL_INITIAL(tmp) = init;
12160 make_tmp = NULL_TREE;
12162 rest_of_decl_compilation(tmp, 1, 0);
12165 valaddr = build_fold_addr_expr(tmp);
12168 tree descriptor = mt->map_descriptor_pointer(gogo, loc);
12170 tree type_tree = type_to_tree(this->type_->get_backend(gogo));
12171 if (type_tree == error_mark_node)
12172 return error_mark_node;
12174 static tree construct_map_fndecl;
12175 tree call = Gogo::call_builtin(&construct_map_fndecl,
12177 "__go_construct_map",
12180 TREE_TYPE(descriptor),
12185 TYPE_SIZE_UNIT(struct_type),
12187 byte_position(val_field),
12189 TYPE_SIZE_UNIT(TREE_TYPE(val_field)),
12190 const_ptr_type_node,
12191 fold_convert(const_ptr_type_node, valaddr));
12192 if (call == error_mark_node)
12193 return error_mark_node;
12196 if (make_tmp == NULL)
12199 ret = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR, type_tree,
12204 // Export an array construction.
12207 Map_construction_expression::do_export(Export* exp) const
12209 exp->write_c_string("convert(");
12210 exp->write_type(this->type_);
12211 for (Expression_list::const_iterator pv = this->vals_->begin();
12212 pv != this->vals_->end();
12215 exp->write_c_string(", ");
12216 (*pv)->export_expression(exp);
12218 exp->write_c_string(")");
12221 // Dump ast representation for a map construction expression.
12224 Map_construction_expression::do_dump_expression(
12225 Ast_dump_context* ast_dump_context) const
12227 ast_dump_context->ostream() << "{" ;
12228 ast_dump_context->dump_expression_list(this->vals_, true);
12229 ast_dump_context->ostream() << "}";
12232 // A general composite literal. This is lowered to a type specific
12235 class Composite_literal_expression : public Parser_expression
12238 Composite_literal_expression(Type* type, int depth, bool has_keys,
12239 Expression_list* vals, Location location)
12240 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12241 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys)
12246 do_traverse(Traverse* traverse);
12249 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12254 return new Composite_literal_expression(this->type_, this->depth_,
12256 (this->vals_ == NULL
12258 : this->vals_->copy()),
12263 do_dump_expression(Ast_dump_context*) const;
12267 lower_struct(Gogo*, Type*);
12270 lower_array(Type*);
12273 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12276 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12278 // The type of the composite literal.
12280 // The depth within a list of composite literals within a composite
12281 // literal, when the type is omitted.
12283 // The values to put in the composite literal.
12284 Expression_list* vals_;
12285 // If this is true, then VALS_ is a list of pairs: a key and a
12286 // value. In an array initializer, a missing key will be NULL.
12293 Composite_literal_expression::do_traverse(Traverse* traverse)
12295 if (this->vals_ != NULL
12296 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12297 return TRAVERSE_EXIT;
12298 return Type::traverse(this->type_, traverse);
12301 // Lower a generic composite literal into a specific version based on
12305 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12306 Statement_inserter* inserter, int)
12308 Type* type = this->type_;
12310 for (int depth = this->depth_; depth > 0; --depth)
12312 if (type->array_type() != NULL)
12313 type = type->array_type()->element_type();
12314 else if (type->map_type() != NULL)
12315 type = type->map_type()->val_type();
12318 if (!type->is_error())
12319 error_at(this->location(),
12320 ("may only omit types within composite literals "
12321 "of slice, array, or map type"));
12322 return Expression::make_error(this->location());
12326 Type *pt = type->points_to();
12327 bool is_pointer = false;
12335 if (type->is_error())
12336 return Expression::make_error(this->location());
12337 else if (type->struct_type() != NULL)
12338 ret = this->lower_struct(gogo, type);
12339 else if (type->array_type() != NULL)
12340 ret = this->lower_array(type);
12341 else if (type->map_type() != NULL)
12342 ret = this->lower_map(gogo, function, inserter, type);
12345 error_at(this->location(),
12346 ("expected struct, slice, array, or map type "
12347 "for composite literal"));
12348 return Expression::make_error(this->location());
12352 ret = Expression::make_heap_composite(ret, this->location());
12357 // Lower a struct composite literal.
12360 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12362 Location location = this->location();
12363 Struct_type* st = type->struct_type();
12364 if (this->vals_ == NULL || !this->has_keys_)
12366 if (this->vals_ != NULL
12367 && !this->vals_->empty()
12368 && type->named_type() != NULL
12369 && type->named_type()->named_object()->package() != NULL)
12371 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12372 pf != st->fields()->end();
12375 if (Gogo::is_hidden_name(pf->field_name()))
12376 error_at(this->location(),
12377 "assignment of unexported field %qs in %qs literal",
12378 Gogo::message_name(pf->field_name()).c_str(),
12379 type->named_type()->message_name().c_str());
12383 return new Struct_construction_expression(type, this->vals_, location);
12386 size_t field_count = st->field_count();
12387 std::vector<Expression*> vals(field_count);
12388 std::vector<int>* traverse_order = new(std::vector<int>);
12389 Expression_list::const_iterator p = this->vals_->begin();
12390 while (p != this->vals_->end())
12392 Expression* name_expr = *p;
12395 go_assert(p != this->vals_->end());
12396 Expression* val = *p;
12400 if (name_expr == NULL)
12402 error_at(val->location(), "mixture of field and value initializers");
12403 return Expression::make_error(location);
12406 bool bad_key = false;
12408 const Named_object* no = NULL;
12409 switch (name_expr->classification())
12411 case EXPRESSION_UNKNOWN_REFERENCE:
12412 name = name_expr->unknown_expression()->name();
12415 case EXPRESSION_CONST_REFERENCE:
12416 no = static_cast<Const_expression*>(name_expr)->named_object();
12419 case EXPRESSION_TYPE:
12421 Type* t = name_expr->type();
12422 Named_type* nt = t->named_type();
12426 no = nt->named_object();
12430 case EXPRESSION_VAR_REFERENCE:
12431 no = name_expr->var_expression()->named_object();
12434 case EXPRESSION_FUNC_REFERENCE:
12435 no = name_expr->func_expression()->named_object();
12438 case EXPRESSION_UNARY:
12439 // If there is a local variable around with the same name as
12440 // the field, and this occurs in the closure, then the
12441 // parser may turn the field reference into an indirection
12442 // through the closure. FIXME: This is a mess.
12445 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12446 if (ue->op() == OPERATOR_MULT)
12448 Field_reference_expression* fre =
12449 ue->operand()->field_reference_expression();
12453 fre->expr()->type()->deref()->struct_type();
12456 const Struct_field* sf = st->field(fre->field_index());
12457 name = sf->field_name();
12459 // See below. FIXME.
12460 if (!Gogo::is_hidden_name(name)
12464 if (gogo->lookup_global(name.c_str()) != NULL)
12465 name = gogo->pack_hidden_name(name, false);
12469 snprintf(buf, sizeof buf, "%u", fre->field_index());
12470 size_t buflen = strlen(buf);
12471 if (name.compare(name.length() - buflen, buflen, buf)
12474 name = name.substr(0, name.length() - buflen);
12489 error_at(name_expr->location(), "expected struct field name");
12490 return Expression::make_error(location);
12497 // A predefined name won't be packed. If it starts with a
12498 // lower case letter we need to check for that case, because
12499 // the field name will be packed. FIXME.
12500 if (!Gogo::is_hidden_name(name)
12504 Named_object* gno = gogo->lookup_global(name.c_str());
12506 name = gogo->pack_hidden_name(name, false);
12510 unsigned int index;
12511 const Struct_field* sf = st->find_local_field(name, &index);
12514 error_at(name_expr->location(), "unknown field %qs in %qs",
12515 Gogo::message_name(name).c_str(),
12516 (type->named_type() != NULL
12517 ? type->named_type()->message_name().c_str()
12518 : "unnamed struct"));
12519 return Expression::make_error(location);
12521 if (vals[index] != NULL)
12523 error_at(name_expr->location(),
12524 "duplicate value for field %qs in %qs",
12525 Gogo::message_name(name).c_str(),
12526 (type->named_type() != NULL
12527 ? type->named_type()->message_name().c_str()
12528 : "unnamed struct"));
12529 return Expression::make_error(location);
12532 if (type->named_type() != NULL
12533 && type->named_type()->named_object()->package() != NULL
12534 && Gogo::is_hidden_name(sf->field_name()))
12535 error_at(name_expr->location(),
12536 "assignment of unexported field %qs in %qs literal",
12537 Gogo::message_name(sf->field_name()).c_str(),
12538 type->named_type()->message_name().c_str());
12541 traverse_order->push_back(index);
12544 Expression_list* list = new Expression_list;
12545 list->reserve(field_count);
12546 for (size_t i = 0; i < field_count; ++i)
12547 list->push_back(vals[i]);
12549 Struct_construction_expression* ret =
12550 new Struct_construction_expression(type, list, location);
12551 ret->set_traverse_order(traverse_order);
12555 // Used to sort an index/value array.
12557 class Index_value_compare
12561 operator()(const std::pair<unsigned long, Expression*>& a,
12562 const std::pair<unsigned long, Expression*>& b)
12563 { return a.first < b.first; }
12566 // Lower an array composite literal.
12569 Composite_literal_expression::lower_array(Type* type)
12571 Location location = this->location();
12572 if (this->vals_ == NULL || !this->has_keys_)
12573 return this->make_array(type, NULL, this->vals_);
12575 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
12576 indexes->reserve(this->vals_->size());
12577 bool indexes_out_of_order = false;
12578 Expression_list* vals = new Expression_list();
12579 vals->reserve(this->vals_->size());
12580 unsigned long index = 0;
12581 Expression_list::const_iterator p = this->vals_->begin();
12582 while (p != this->vals_->end())
12584 Expression* index_expr = *p;
12587 go_assert(p != this->vals_->end());
12588 Expression* val = *p;
12592 if (index_expr == NULL)
12594 if (!indexes->empty())
12595 indexes->push_back(index);
12599 if (indexes->empty() && !vals->empty())
12601 for (size_t i = 0; i < vals->size(); ++i)
12602 indexes->push_back(i);
12605 Numeric_constant nc;
12606 if (!index_expr->numeric_constant_value(&nc))
12608 error_at(index_expr->location(),
12609 "index expression is not integer constant");
12610 return Expression::make_error(location);
12613 switch (nc.to_unsigned_long(&index))
12615 case Numeric_constant::NC_UL_VALID:
12617 case Numeric_constant::NC_UL_NOTINT:
12618 error_at(index_expr->location(),
12619 "index expression is not integer constant");
12620 return Expression::make_error(location);
12621 case Numeric_constant::NC_UL_NEGATIVE:
12622 error_at(index_expr->location(), "index expression is negative");
12623 return Expression::make_error(location);
12624 case Numeric_constant::NC_UL_BIG:
12625 error_at(index_expr->location(), "index value overflow");
12626 return Expression::make_error(location);
12631 Named_type* ntype = Type::lookup_integer_type("int");
12632 Integer_type* inttype = ntype->integer_type();
12633 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12634 && index >> (inttype->bits() - 1) != 0)
12636 error_at(index_expr->location(), "index value overflow");
12637 return Expression::make_error(location);
12640 if (std::find(indexes->begin(), indexes->end(), index)
12643 error_at(index_expr->location(), "duplicate value for index %lu",
12645 return Expression::make_error(location);
12648 if (!indexes->empty() && index < indexes->back())
12649 indexes_out_of_order = true;
12651 indexes->push_back(index);
12654 vals->push_back(val);
12659 if (indexes->empty())
12665 if (indexes_out_of_order)
12667 typedef std::vector<std::pair<unsigned long, Expression*> > V;
12670 v.reserve(indexes->size());
12671 std::vector<unsigned long>::const_iterator pi = indexes->begin();
12672 for (Expression_list::const_iterator pe = vals->begin();
12675 v.push_back(std::make_pair(*pi, *pe));
12677 std::sort(v.begin(), v.end(), Index_value_compare());
12681 indexes = new std::vector<unsigned long>();
12682 indexes->reserve(v.size());
12683 vals = new Expression_list();
12684 vals->reserve(v.size());
12686 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
12688 indexes->push_back(p->first);
12689 vals->push_back(p->second);
12693 return this->make_array(type, indexes, vals);
12696 // Actually build the array composite literal. This handles
12700 Composite_literal_expression::make_array(
12702 const std::vector<unsigned long>* indexes,
12703 Expression_list* vals)
12705 Location location = this->location();
12706 Array_type* at = type->array_type();
12708 if (at->length() != NULL && at->length()->is_nil_expression())
12713 else if (indexes != NULL)
12714 size = indexes->back() + 1;
12717 size = vals->size();
12718 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
12719 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
12720 && size >> (it->bits() - 1) != 0)
12722 error_at(location, "too many elements in composite literal");
12723 return Expression::make_error(location);
12728 mpz_init_set_ui(vlen, size);
12729 Expression* elen = Expression::make_integer(&vlen, NULL, location);
12731 at = Type::make_array_type(at->element_type(), elen);
12734 else if (at->length() != NULL
12735 && !at->length()->is_error_expression()
12736 && this->vals_ != NULL)
12738 Numeric_constant nc;
12740 if (at->length()->numeric_constant_value(&nc)
12741 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
12743 if (indexes == NULL)
12745 if (this->vals_->size() > val)
12747 error_at(location, "too many elements in composite literal");
12748 return Expression::make_error(location);
12753 unsigned long max = indexes->back();
12757 ("some element keys in composite literal "
12758 "are out of range"));
12759 return Expression::make_error(location);
12765 if (at->length() != NULL)
12766 return new Fixed_array_construction_expression(type, indexes, vals,
12769 return new Open_array_construction_expression(type, indexes, vals,
12773 // Lower a map composite literal.
12776 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12777 Statement_inserter* inserter,
12780 Location location = this->location();
12781 if (this->vals_ != NULL)
12783 if (!this->has_keys_)
12785 error_at(location, "map composite literal must have keys");
12786 return Expression::make_error(location);
12789 for (Expression_list::iterator p = this->vals_->begin();
12790 p != this->vals_->end();
12796 error_at((*p)->location(),
12797 "map composite literal must have keys for every value");
12798 return Expression::make_error(location);
12800 // Make sure we have lowered the key; it may not have been
12801 // lowered in order to handle keys for struct composite
12802 // literals. Lower it now to get the right error message.
12803 if ((*p)->unknown_expression() != NULL)
12805 (*p)->unknown_expression()->clear_is_composite_literal_key();
12806 gogo->lower_expression(function, inserter, &*p);
12807 go_assert((*p)->is_error_expression());
12808 return Expression::make_error(location);
12813 return new Map_construction_expression(type, this->vals_, location);
12816 // Dump ast representation for a composite literal expression.
12819 Composite_literal_expression::do_dump_expression(
12820 Ast_dump_context* ast_dump_context) const
12822 ast_dump_context->ostream() << "composite(";
12823 ast_dump_context->dump_type(this->type_);
12824 ast_dump_context->ostream() << ", {";
12825 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12826 ast_dump_context->ostream() << "})";
12829 // Make a composite literal expression.
12832 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
12833 Expression_list* vals,
12836 return new Composite_literal_expression(type, depth, has_keys, vals,
12840 // Return whether this expression is a composite literal.
12843 Expression::is_composite_literal() const
12845 switch (this->classification_)
12847 case EXPRESSION_COMPOSITE_LITERAL:
12848 case EXPRESSION_STRUCT_CONSTRUCTION:
12849 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12850 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12851 case EXPRESSION_MAP_CONSTRUCTION:
12858 // Return whether this expression is a composite literal which is not
12862 Expression::is_nonconstant_composite_literal() const
12864 switch (this->classification_)
12866 case EXPRESSION_STRUCT_CONSTRUCTION:
12868 const Struct_construction_expression *psce =
12869 static_cast<const Struct_construction_expression*>(this);
12870 return !psce->is_constant_struct();
12872 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
12874 const Fixed_array_construction_expression *pace =
12875 static_cast<const Fixed_array_construction_expression*>(this);
12876 return !pace->is_constant_array();
12878 case EXPRESSION_OPEN_ARRAY_CONSTRUCTION:
12880 const Open_array_construction_expression *pace =
12881 static_cast<const Open_array_construction_expression*>(this);
12882 return !pace->is_constant_array();
12884 case EXPRESSION_MAP_CONSTRUCTION:
12891 // Return true if this is a reference to a local variable.
12894 Expression::is_local_variable() const
12896 const Var_expression* ve = this->var_expression();
12899 const Named_object* no = ve->named_object();
12900 return (no->is_result_variable()
12901 || (no->is_variable() && !no->var_value()->is_global()));
12904 // Class Type_guard_expression.
12909 Type_guard_expression::do_traverse(Traverse* traverse)
12911 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
12912 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12913 return TRAVERSE_EXIT;
12914 return TRAVERSE_CONTINUE;
12917 // Check types of a type guard expression. The expression must have
12918 // an interface type, but the actual type conversion is checked at run
12922 Type_guard_expression::do_check_types(Gogo*)
12924 // 6g permits using a type guard with unsafe.pointer; we are
12926 Type* expr_type = this->expr_->type();
12927 if (expr_type->is_unsafe_pointer_type())
12929 if (this->type_->points_to() == NULL
12930 && (this->type_->integer_type() == NULL
12931 || (this->type_->forwarded()
12932 != Type::lookup_integer_type("uintptr"))))
12933 this->report_error(_("invalid unsafe.Pointer conversion"));
12935 else if (this->type_->is_unsafe_pointer_type())
12937 if (expr_type->points_to() == NULL
12938 && (expr_type->integer_type() == NULL
12939 || (expr_type->forwarded()
12940 != Type::lookup_integer_type("uintptr"))))
12941 this->report_error(_("invalid unsafe.Pointer conversion"));
12943 else if (expr_type->interface_type() == NULL)
12945 if (!expr_type->is_error() && !this->type_->is_error())
12946 this->report_error(_("type assertion only valid for interface types"));
12947 this->set_is_error();
12949 else if (this->type_->interface_type() == NULL)
12951 std::string reason;
12952 if (!expr_type->interface_type()->implements_interface(this->type_,
12955 if (!this->type_->is_error())
12957 if (reason.empty())
12958 this->report_error(_("impossible type assertion: "
12959 "type does not implement interface"));
12961 error_at(this->location(),
12962 ("impossible type assertion: "
12963 "type does not implement interface (%s)"),
12966 this->set_is_error();
12971 // Return a tree for a type guard expression.
12974 Type_guard_expression::do_get_tree(Translate_context* context)
12976 Gogo* gogo = context->gogo();
12977 tree expr_tree = this->expr_->get_tree(context);
12978 if (expr_tree == error_mark_node)
12979 return error_mark_node;
12980 Type* expr_type = this->expr_->type();
12981 if ((this->type_->is_unsafe_pointer_type()
12982 && (expr_type->points_to() != NULL
12983 || expr_type->integer_type() != NULL))
12984 || (expr_type->is_unsafe_pointer_type()
12985 && this->type_->points_to() != NULL))
12986 return convert_to_pointer(type_to_tree(this->type_->get_backend(gogo)),
12988 else if (expr_type->is_unsafe_pointer_type()
12989 && this->type_->integer_type() != NULL)
12990 return convert_to_integer(type_to_tree(this->type_->get_backend(gogo)),
12992 else if (this->type_->interface_type() != NULL)
12993 return Expression::convert_interface_to_interface(context, this->type_,
12994 this->expr_->type(),
12998 return Expression::convert_for_assignment(context, this->type_,
12999 this->expr_->type(), expr_tree,
13003 // Dump ast representation for a type guard expression.
13006 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13009 this->expr_->dump_expression(ast_dump_context);
13010 ast_dump_context->ostream() << ".";
13011 ast_dump_context->dump_type(this->type_);
13014 // Make a type guard expression.
13017 Expression::make_type_guard(Expression* expr, Type* type,
13020 return new Type_guard_expression(expr, type, location);
13023 // Class Heap_composite_expression.
13025 // When you take the address of a composite literal, it is allocated
13026 // on the heap. This class implements that.
13028 class Heap_composite_expression : public Expression
13031 Heap_composite_expression(Expression* expr, Location location)
13032 : Expression(EXPRESSION_HEAP_COMPOSITE, location),
13038 do_traverse(Traverse* traverse)
13039 { return Expression::traverse(&this->expr_, traverse); }
13043 { return Type::make_pointer_type(this->expr_->type()); }
13046 do_determine_type(const Type_context*)
13047 { this->expr_->determine_type_no_context(); }
13052 return Expression::make_heap_composite(this->expr_->copy(),
13057 do_get_tree(Translate_context*);
13059 // We only export global objects, and the parser does not generate
13060 // this in global scope.
13062 do_export(Export*) const
13063 { go_unreachable(); }
13066 do_dump_expression(Ast_dump_context*) const;
13069 // The composite literal which is being put on the heap.
13073 // Return a tree which allocates a composite literal on the heap.
13076 Heap_composite_expression::do_get_tree(Translate_context* context)
13078 tree expr_tree = this->expr_->get_tree(context);
13079 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
13080 return error_mark_node;
13081 tree expr_size = TYPE_SIZE_UNIT(TREE_TYPE(expr_tree));
13082 go_assert(TREE_CODE(expr_size) == INTEGER_CST);
13083 tree space = context->gogo()->allocate_memory(this->expr_->type(),
13084 expr_size, this->location());
13085 space = fold_convert(build_pointer_type(TREE_TYPE(expr_tree)), space);
13086 space = save_expr(space);
13087 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13089 TREE_THIS_NOTRAP(ref) = 1;
13090 tree ret = build2(COMPOUND_EXPR, TREE_TYPE(space),
13091 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13093 SET_EXPR_LOCATION(ret, this->location().gcc_location());
13097 // Dump ast representation for a heap composite expression.
13100 Heap_composite_expression::do_dump_expression(
13101 Ast_dump_context* ast_dump_context) const
13103 ast_dump_context->ostream() << "&(";
13104 ast_dump_context->dump_expression(this->expr_);
13105 ast_dump_context->ostream() << ")";
13108 // Allocate a composite literal on the heap.
13111 Expression::make_heap_composite(Expression* expr, Location location)
13113 return new Heap_composite_expression(expr, location);
13116 // Class Receive_expression.
13118 // Return the type of a receive expression.
13121 Receive_expression::do_type()
13123 Channel_type* channel_type = this->channel_->type()->channel_type();
13124 if (channel_type == NULL)
13125 return Type::make_error_type();
13126 return channel_type->element_type();
13129 // Check types for a receive expression.
13132 Receive_expression::do_check_types(Gogo*)
13134 Type* type = this->channel_->type();
13135 if (type->is_error())
13137 this->set_is_error();
13140 if (type->channel_type() == NULL)
13142 this->report_error(_("expected channel"));
13145 if (!type->channel_type()->may_receive())
13147 this->report_error(_("invalid receive on send-only channel"));
13152 // Get a tree for a receive expression.
13155 Receive_expression::do_get_tree(Translate_context* context)
13157 Location loc = this->location();
13159 Channel_type* channel_type = this->channel_->type()->channel_type();
13160 if (channel_type == NULL)
13162 go_assert(this->channel_->type()->is_error());
13163 return error_mark_node;
13166 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13167 tree td_tree = td->get_tree(context);
13169 Type* element_type = channel_type->element_type();
13170 Btype* element_type_btype = element_type->get_backend(context->gogo());
13171 tree element_type_tree = type_to_tree(element_type_btype);
13173 tree channel = this->channel_->get_tree(context);
13174 if (element_type_tree == error_mark_node || channel == error_mark_node)
13175 return error_mark_node;
13177 return Gogo::receive_from_channel(element_type_tree, td_tree, channel, loc);
13180 // Dump ast representation for a receive expression.
13183 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13185 ast_dump_context->ostream() << " <- " ;
13186 ast_dump_context->dump_expression(channel_);
13189 // Make a receive expression.
13191 Receive_expression*
13192 Expression::make_receive(Expression* channel, Location location)
13194 return new Receive_expression(channel, location);
13197 // An expression which evaluates to a pointer to the type descriptor
13200 class Type_descriptor_expression : public Expression
13203 Type_descriptor_expression(Type* type, Location location)
13204 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13211 { return Type::make_type_descriptor_ptr_type(); }
13214 do_determine_type(const Type_context*)
13222 do_get_tree(Translate_context* context)
13224 return this->type_->type_descriptor_pointer(context->gogo(),
13229 do_dump_expression(Ast_dump_context*) const;
13232 // The type for which this is the descriptor.
13236 // Dump ast representation for a type descriptor expression.
13239 Type_descriptor_expression::do_dump_expression(
13240 Ast_dump_context* ast_dump_context) const
13242 ast_dump_context->dump_type(this->type_);
13245 // Make a type descriptor expression.
13248 Expression::make_type_descriptor(Type* type, Location location)
13250 return new Type_descriptor_expression(type, location);
13253 // An expression which evaluates to some characteristic of a type.
13254 // This is only used to initialize fields of a type descriptor. Using
13255 // a new expression class is slightly inefficient but gives us a good
13256 // separation between the frontend and the middle-end with regard to
13257 // how types are laid out.
13259 class Type_info_expression : public Expression
13262 Type_info_expression(Type* type, Type_info type_info)
13263 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13264 type_(type), type_info_(type_info)
13272 do_determine_type(const Type_context*)
13280 do_get_tree(Translate_context* context);
13283 do_dump_expression(Ast_dump_context*) const;
13286 // The type for which we are getting information.
13288 // What information we want.
13289 Type_info type_info_;
13292 // The type is chosen to match what the type descriptor struct
13296 Type_info_expression::do_type()
13298 switch (this->type_info_)
13300 case TYPE_INFO_SIZE:
13301 return Type::lookup_integer_type("uintptr");
13302 case TYPE_INFO_ALIGNMENT:
13303 case TYPE_INFO_FIELD_ALIGNMENT:
13304 return Type::lookup_integer_type("uint8");
13310 // Return type information in GENERIC.
13313 Type_info_expression::do_get_tree(Translate_context* context)
13315 Btype* btype = this->type_->get_backend(context->gogo());
13316 Gogo* gogo = context->gogo();
13318 switch (this->type_info_)
13320 case TYPE_INFO_SIZE:
13321 val = gogo->backend()->type_size(btype);
13323 case TYPE_INFO_ALIGNMENT:
13324 val = gogo->backend()->type_alignment(btype);
13326 case TYPE_INFO_FIELD_ALIGNMENT:
13327 val = gogo->backend()->type_field_alignment(btype);
13332 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
13333 go_assert(val_type_tree != error_mark_node);
13334 return build_int_cstu(val_type_tree, val);
13337 // Dump ast representation for a type info expression.
13340 Type_info_expression::do_dump_expression(
13341 Ast_dump_context* ast_dump_context) const
13343 ast_dump_context->ostream() << "typeinfo(";
13344 ast_dump_context->dump_type(this->type_);
13345 ast_dump_context->ostream() << ",";
13346 ast_dump_context->ostream() <<
13347 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13348 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13349 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13351 ast_dump_context->ostream() << ")";
13354 // Make a type info expression.
13357 Expression::make_type_info(Type* type, Type_info type_info)
13359 return new Type_info_expression(type, type_info);
13362 // An expression which evaluates to the offset of a field within a
13363 // struct. This, like Type_info_expression, q.v., is only used to
13364 // initialize fields of a type descriptor.
13366 class Struct_field_offset_expression : public Expression
13369 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
13370 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
13371 Linemap::predeclared_location()),
13372 type_(type), field_(field)
13378 { return Type::lookup_integer_type("uintptr"); }
13381 do_determine_type(const Type_context*)
13389 do_get_tree(Translate_context* context);
13392 do_dump_expression(Ast_dump_context*) const;
13395 // The type of the struct.
13396 Struct_type* type_;
13398 const Struct_field* field_;
13401 // Return a struct field offset in GENERIC.
13404 Struct_field_offset_expression::do_get_tree(Translate_context* context)
13406 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
13407 if (type_tree == error_mark_node)
13408 return error_mark_node;
13410 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
13411 go_assert(val_type_tree != error_mark_node);
13413 const Struct_field_list* fields = this->type_->fields();
13414 tree struct_field_tree = TYPE_FIELDS(type_tree);
13415 Struct_field_list::const_iterator p;
13416 for (p = fields->begin();
13417 p != fields->end();
13418 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
13420 go_assert(struct_field_tree != NULL_TREE);
13421 if (&*p == this->field_)
13424 go_assert(&*p == this->field_);
13426 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
13427 byte_position(struct_field_tree));
13430 // Dump ast representation for a struct field offset expression.
13433 Struct_field_offset_expression::do_dump_expression(
13434 Ast_dump_context* ast_dump_context) const
13436 ast_dump_context->ostream() << "unsafe.Offsetof(";
13437 ast_dump_context->dump_type(this->type_);
13438 ast_dump_context->ostream() << '.';
13439 ast_dump_context->ostream() <<
13440 Gogo::message_name(this->field_->field_name());
13441 ast_dump_context->ostream() << ")";
13444 // Make an expression for a struct field offset.
13447 Expression::make_struct_field_offset(Struct_type* type,
13448 const Struct_field* field)
13450 return new Struct_field_offset_expression(type, field);
13453 // An expression which evaluates to a pointer to the map descriptor of
13456 class Map_descriptor_expression : public Expression
13459 Map_descriptor_expression(Map_type* type, Location location)
13460 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
13467 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
13470 do_determine_type(const Type_context*)
13478 do_get_tree(Translate_context* context)
13480 return this->type_->map_descriptor_pointer(context->gogo(),
13485 do_dump_expression(Ast_dump_context*) const;
13488 // The type for which this is the descriptor.
13492 // Dump ast representation for a map descriptor expression.
13495 Map_descriptor_expression::do_dump_expression(
13496 Ast_dump_context* ast_dump_context) const
13498 ast_dump_context->ostream() << "map_descriptor(";
13499 ast_dump_context->dump_type(this->type_);
13500 ast_dump_context->ostream() << ")";
13503 // Make a map descriptor expression.
13506 Expression::make_map_descriptor(Map_type* type, Location location)
13508 return new Map_descriptor_expression(type, location);
13511 // An expression which evaluates to the address of an unnamed label.
13513 class Label_addr_expression : public Expression
13516 Label_addr_expression(Label* label, Location location)
13517 : Expression(EXPRESSION_LABEL_ADDR, location),
13524 { return Type::make_pointer_type(Type::make_void_type()); }
13527 do_determine_type(const Type_context*)
13532 { return new Label_addr_expression(this->label_, this->location()); }
13535 do_get_tree(Translate_context* context)
13537 return expr_to_tree(this->label_->get_addr(context, this->location()));
13541 do_dump_expression(Ast_dump_context* ast_dump_context) const
13542 { ast_dump_context->ostream() << this->label_->name(); }
13545 // The label whose address we are taking.
13549 // Make an expression for the address of an unnamed label.
13552 Expression::make_label_addr(Label* label, Location location)
13554 return new Label_addr_expression(label, location);
13557 // Import an expression. This comes at the end in order to see the
13558 // various class definitions.
13561 Expression::import_expression(Import* imp)
13563 int c = imp->peek_char();
13564 if (imp->match_c_string("- ")
13565 || imp->match_c_string("! ")
13566 || imp->match_c_string("^ "))
13567 return Unary_expression::do_import(imp);
13569 return Binary_expression::do_import(imp);
13570 else if (imp->match_c_string("true")
13571 || imp->match_c_string("false"))
13572 return Boolean_expression::do_import(imp);
13574 return String_expression::do_import(imp);
13575 else if (c == '-' || (c >= '0' && c <= '9'))
13577 // This handles integers, floats and complex constants.
13578 return Integer_expression::do_import(imp);
13580 else if (imp->match_c_string("nil"))
13581 return Nil_expression::do_import(imp);
13582 else if (imp->match_c_string("convert"))
13583 return Type_conversion_expression::do_import(imp);
13586 error_at(imp->location(), "import error: expected expression");
13587 return Expression::make_error(imp->location());
13591 // Class Expression_list.
13593 // Traverse the list.
13596 Expression_list::traverse(Traverse* traverse)
13598 for (Expression_list::iterator p = this->begin();
13604 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13605 return TRAVERSE_EXIT;
13608 return TRAVERSE_CONTINUE;
13614 Expression_list::copy()
13616 Expression_list* ret = new Expression_list();
13617 for (Expression_list::iterator p = this->begin();
13622 ret->push_back(NULL);
13624 ret->push_back((*p)->copy());
13629 // Return whether an expression list has an error expression.
13632 Expression_list::contains_error() const
13634 for (Expression_list::const_iterator p = this->begin();
13637 if (*p != NULL && (*p)->is_error_expression())
13642 // Class Numeric_constant.
13646 Numeric_constant::~Numeric_constant()
13651 // Copy constructor.
13653 Numeric_constant::Numeric_constant(const Numeric_constant& a)
13654 : classification_(a.classification_), type_(a.type_)
13656 switch (a.classification_)
13662 mpz_init_set(this->u_.int_val, a.u_.int_val);
13665 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13668 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13670 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13678 // Assignment operator.
13681 Numeric_constant::operator=(const Numeric_constant& a)
13684 this->classification_ = a.classification_;
13685 this->type_ = a.type_;
13686 switch (a.classification_)
13692 mpz_init_set(this->u_.int_val, a.u_.int_val);
13695 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
13698 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
13700 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
13709 // Clear the contents.
13712 Numeric_constant::clear()
13714 switch (this->classification_)
13720 mpz_clear(this->u_.int_val);
13723 mpfr_clear(this->u_.float_val);
13726 mpfr_clear(this->u_.complex_val.real);
13727 mpfr_clear(this->u_.complex_val.imag);
13732 this->classification_ = NC_INVALID;
13735 // Set to an unsigned long value.
13738 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
13741 this->classification_ = NC_INT;
13742 this->type_ = type;
13743 mpz_init_set_ui(this->u_.int_val, val);
13746 // Set to an integer value.
13749 Numeric_constant::set_int(Type* type, const mpz_t val)
13752 this->classification_ = NC_INT;
13753 this->type_ = type;
13754 mpz_init_set(this->u_.int_val, val);
13757 // Set to a rune value.
13760 Numeric_constant::set_rune(Type* type, const mpz_t val)
13763 this->classification_ = NC_RUNE;
13764 this->type_ = type;
13765 mpz_init_set(this->u_.int_val, val);
13768 // Set to a floating point value.
13771 Numeric_constant::set_float(Type* type, const mpfr_t val)
13774 this->classification_ = NC_FLOAT;
13775 this->type_ = type;
13776 // Numeric constants do not have negative zero values, so remove
13777 // them here. They also don't have infinity or NaN values, but we
13778 // should never see them here.
13779 if (mpfr_zero_p(val))
13780 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
13782 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
13785 // Set to a complex value.
13788 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
13791 this->classification_ = NC_COMPLEX;
13792 this->type_ = type;
13793 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
13794 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
13797 // Get an int value.
13800 Numeric_constant::get_int(mpz_t* val) const
13802 go_assert(this->is_int());
13803 mpz_init_set(*val, this->u_.int_val);
13806 // Get a rune value.
13809 Numeric_constant::get_rune(mpz_t* val) const
13811 go_assert(this->is_rune());
13812 mpz_init_set(*val, this->u_.int_val);
13815 // Get a floating point value.
13818 Numeric_constant::get_float(mpfr_t* val) const
13820 go_assert(this->is_float());
13821 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13824 // Get a complex value.
13827 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
13829 go_assert(this->is_complex());
13830 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
13831 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
13834 // Express value as unsigned long if possible.
13836 Numeric_constant::To_unsigned_long
13837 Numeric_constant::to_unsigned_long(unsigned long* val) const
13839 switch (this->classification_)
13843 return this->mpz_to_unsigned_long(this->u_.int_val, val);
13845 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
13847 if (!mpfr_zero_p(this->u_.complex_val.imag))
13848 return NC_UL_NOTINT;
13849 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
13855 // Express integer value as unsigned long if possible.
13857 Numeric_constant::To_unsigned_long
13858 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
13859 unsigned long *val) const
13861 if (mpz_sgn(ival) < 0)
13862 return NC_UL_NEGATIVE;
13863 unsigned long ui = mpz_get_ui(ival);
13864 if (mpz_cmp_ui(ival, ui) != 0)
13867 return NC_UL_VALID;
13870 // Express floating point value as unsigned long if possible.
13872 Numeric_constant::To_unsigned_long
13873 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
13874 unsigned long *val) const
13876 if (!mpfr_integer_p(fval))
13877 return NC_UL_NOTINT;
13880 mpfr_get_z(ival, fval, GMP_RNDN);
13881 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
13886 // Convert value to integer if possible.
13889 Numeric_constant::to_int(mpz_t* val) const
13891 switch (this->classification_)
13895 mpz_init_set(*val, this->u_.int_val);
13898 if (!mpfr_integer_p(this->u_.float_val))
13901 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
13904 if (!mpfr_zero_p(this->u_.complex_val.imag)
13905 || !mpfr_integer_p(this->u_.complex_val.real))
13908 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
13915 // Convert value to floating point if possible.
13918 Numeric_constant::to_float(mpfr_t* val) const
13920 switch (this->classification_)
13924 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
13927 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
13930 if (!mpfr_zero_p(this->u_.complex_val.imag))
13932 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
13939 // Convert value to complex.
13942 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
13944 switch (this->classification_)
13948 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
13949 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13952 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
13953 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
13956 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
13957 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
13967 Numeric_constant::type() const
13969 if (this->type_ != NULL)
13970 return this->type_;
13971 switch (this->classification_)
13974 return Type::make_abstract_integer_type();
13976 return Type::make_abstract_character_type();
13978 return Type::make_abstract_float_type();
13980 return Type::make_abstract_complex_type();
13986 // If the constant can be expressed in TYPE, then set the type of the
13987 // constant to TYPE and return true. Otherwise return false, and, if
13988 // ISSUE_ERROR is true, report an appropriate error message.
13991 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
13996 else if (type->integer_type() != NULL)
13997 ret = this->check_int_type(type->integer_type(), issue_error, loc);
13998 else if (type->float_type() != NULL)
13999 ret = this->check_float_type(type->float_type(), issue_error, loc);
14000 else if (type->complex_type() != NULL)
14001 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
14005 this->type_ = type;
14009 // Check whether the constant can be expressed in an integer type.
14012 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
14013 Location location) const
14016 switch (this->classification_)
14020 mpz_init_set(val, this->u_.int_val);
14024 if (!mpfr_integer_p(this->u_.float_val))
14027 error_at(location, "floating point constant truncated to integer");
14031 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
14035 if (!mpfr_integer_p(this->u_.complex_val.real)
14036 || !mpfr_zero_p(this->u_.complex_val.imag))
14039 error_at(location, "complex constant truncated to integer");
14043 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
14051 if (type->is_abstract())
14055 int bits = mpz_sizeinbase(val, 2);
14056 if (type->is_unsigned())
14058 // For an unsigned type we can only accept a nonnegative
14059 // number, and we must be able to represents at least BITS.
14060 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
14064 // For a signed type we need an extra bit to indicate the
14065 // sign. We have to handle the most negative integer
14067 ret = (bits + 1 <= type->bits()
14068 || (bits <= type->bits()
14069 && mpz_sgn(val) < 0
14070 && (mpz_scan1(val, 0)
14071 == static_cast<unsigned long>(type->bits() - 1))
14072 && mpz_scan0(val, type->bits()) == ULONG_MAX));
14076 if (!ret && issue_error)
14077 error_at(location, "integer constant overflow");
14082 // Check whether the constant can be expressed in a floating point
14086 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
14087 Location location) const
14090 switch (this->classification_)
14094 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
14098 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
14102 if (!mpfr_zero_p(this->u_.complex_val.imag))
14105 error_at(location, "complex constant truncated to float");
14108 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
14116 if (type->is_abstract())
14118 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
14120 // A NaN or Infinity always fits in the range of the type.
14125 mp_exp_t exp = mpfr_get_exp(val);
14127 switch (type->bits())
14139 ret = exp <= max_exp;
14144 if (!ret && issue_error)
14145 error_at(location, "floating point constant overflow");
14150 // Check whether the constant can be expressed in a complex type.
14153 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
14154 Location location) const
14156 if (type->is_abstract())
14160 switch (type->bits())
14173 switch (this->classification_)
14177 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
14181 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
14185 if (!mpfr_nan_p(this->u_.complex_val.imag)
14186 && !mpfr_inf_p(this->u_.complex_val.imag)
14187 && !mpfr_zero_p(this->u_.complex_val.imag))
14189 if (mpfr_get_exp(this->u_.complex_val.imag) > max_exp)
14192 error_at(location, "complex imaginary part overflow");
14196 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
14204 if (mpfr_nan_p(real) || mpfr_inf_p(real) || mpfr_zero_p(real))
14207 ret = mpfr_get_exp(real) <= max_exp;
14211 if (!ret && issue_error)
14212 error_at(location, "complex real part overflow");
14217 // Return an Expression for this value.
14220 Numeric_constant::expression(Location loc) const
14222 switch (this->classification_)
14225 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
14227 return Expression::make_character(&this->u_.int_val, this->type_, loc);
14229 return Expression::make_float(&this->u_.float_val, this->type_, loc);
14231 return Expression::make_complex(&this->u_.complex_val.real,
14232 &this->u_.complex_val.imag,