Sync to current external repository.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blobbd2e3183bfe9aa01c4886ce897ca94157fbc5038
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.
7 #include "go-system.h"
9 #include <algorithm>
11 #include "toplev.h"
12 #include "intl.h"
13 #include "tree.h"
14 #include "stringpool.h"
15 #include "stor-layout.h"
16 #include "gimple-expr.h"
17 #include "tree-iterator.h"
18 #include "convert.h"
19 #include "real.h"
20 #include "realmpfr.h"
22 #include "go-c.h"
23 #include "gogo.h"
24 #include "types.h"
25 #include "export.h"
26 #include "import.h"
27 #include "statements.h"
28 #include "lex.h"
29 #include "runtime.h"
30 #include "backend.h"
31 #include "expressions.h"
32 #include "ast-dump.h"
34 // Class Expression.
36 Expression::Expression(Expression_classification classification,
37 Location location)
38 : classification_(classification), location_(location)
42 Expression::~Expression()
46 // Traverse the expressions.
48 int
49 Expression::traverse(Expression** pexpr, Traverse* traverse)
51 Expression* expr = *pexpr;
52 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
54 int t = traverse->expression(pexpr);
55 if (t == TRAVERSE_EXIT)
56 return TRAVERSE_EXIT;
57 else if (t == TRAVERSE_SKIP_COMPONENTS)
58 return TRAVERSE_CONTINUE;
60 return expr->do_traverse(traverse);
63 // Traverse subexpressions of this expression.
65 int
66 Expression::traverse_subexpressions(Traverse* traverse)
68 return this->do_traverse(traverse);
71 // Default implementation for do_traverse for child classes.
73 int
74 Expression::do_traverse(Traverse*)
76 return TRAVERSE_CONTINUE;
79 // This virtual function is called by the parser if the value of this
80 // expression is being discarded. By default, we give an error.
81 // Expressions with side effects override.
83 bool
84 Expression::do_discarding_value()
86 this->unused_value_error();
87 return false;
90 // This virtual function is called to export expressions. This will
91 // only be used by expressions which may be constant.
93 void
94 Expression::do_export(Export*) const
96 go_unreachable();
99 // Give an error saying that the value of the expression is not used.
101 void
102 Expression::unused_value_error()
104 this->report_error(_("value computed is not used"));
107 // Note that this expression is an error. This is called by children
108 // when they discover an error.
110 void
111 Expression::set_is_error()
113 this->classification_ = EXPRESSION_ERROR;
116 // For children to call to report an error conveniently.
118 void
119 Expression::report_error(const char* msg)
121 error_at(this->location_, "%s", msg);
122 this->set_is_error();
125 // Set types of variables and constants. This is implemented by the
126 // child class.
128 void
129 Expression::determine_type(const Type_context* context)
131 this->do_determine_type(context);
134 // Set types when there is no context.
136 void
137 Expression::determine_type_no_context()
139 Type_context context;
140 this->do_determine_type(&context);
143 // Return an expression handling any conversions which must be done during
144 // assignment.
146 Expression*
147 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
148 Expression* rhs, Location location)
150 Type* rhs_type = rhs->type();
151 if (lhs_type->is_error()
152 || rhs_type->is_error()
153 || rhs->is_error_expression())
154 return Expression::make_error(location);
156 if (lhs_type->forwarded() != rhs_type->forwarded()
157 && lhs_type->interface_type() != NULL)
159 if (rhs_type->interface_type() == NULL)
160 return Expression::convert_type_to_interface(lhs_type, rhs, location);
161 else
162 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
163 location);
165 else if (lhs_type->forwarded() != rhs_type->forwarded()
166 && rhs_type->interface_type() != NULL)
167 return Expression::convert_interface_to_type(lhs_type, rhs, location);
168 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
170 // Assigning nil to a slice.
171 mpz_t zval;
172 mpz_init_set_ui(zval, 0UL);
173 Expression* zero = Expression::make_integer(&zval, NULL, location);
174 mpz_clear(zval);
175 Expression* nil = Expression::make_nil(location);
176 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
178 else if (rhs_type->is_nil_type())
179 return Expression::make_nil(location);
180 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
182 // No conversion is needed.
183 return rhs;
185 else if (lhs_type->points_to() != NULL)
186 return Expression::make_unsafe_cast(lhs_type, rhs, location);
187 else if (lhs_type->is_numeric_type())
188 return Expression::make_cast(lhs_type, rhs, location);
189 else if ((lhs_type->struct_type() != NULL
190 && rhs_type->struct_type() != NULL)
191 || (lhs_type->array_type() != NULL
192 && rhs_type->array_type() != NULL))
194 // Avoid confusion from zero sized variables which may be
195 // represented as non-zero-sized.
196 // TODO(cmang): This check is for a GCC-specific issue, and should be
197 // removed from the frontend. FIXME.
198 size_t lhs_size = gogo->backend()->type_size(lhs_type->get_backend(gogo));
199 size_t rhs_size = gogo->backend()->type_size(rhs_type->get_backend(gogo));
200 if (rhs_size == 0 || lhs_size == 0)
201 return rhs;
203 // This conversion must be permitted by Go, or we wouldn't have
204 // gotten here.
205 return Expression::make_unsafe_cast(lhs_type, rhs, location);
207 else
208 return rhs;
211 // Return an expression for a conversion from a non-interface type to an
212 // interface type.
214 Expression*
215 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
216 Location location)
218 Interface_type* lhs_interface_type = lhs_type->interface_type();
219 bool lhs_is_empty = lhs_interface_type->is_empty();
221 // Since RHS_TYPE is a static type, we can create the interface
222 // method table at compile time.
224 // When setting an interface to nil, we just set both fields to
225 // NULL.
226 Type* rhs_type = rhs->type();
227 if (rhs_type->is_nil_type())
229 Expression* nil = Expression::make_nil(location);
230 return Expression::make_interface_value(lhs_type, nil, nil, location);
233 // This should have been checked already.
234 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
236 // An interface is a tuple. If LHS_TYPE is an empty interface type,
237 // then the first field is the type descriptor for RHS_TYPE.
238 // Otherwise it is the interface method table for RHS_TYPE.
239 Expression* first_field;
240 if (lhs_is_empty)
241 first_field = Expression::make_type_descriptor(rhs_type, location);
242 else
244 // Build the interface method table for this interface and this
245 // object type: a list of function pointers for each interface
246 // method.
247 Named_type* rhs_named_type = rhs_type->named_type();
248 Struct_type* rhs_struct_type = rhs_type->struct_type();
249 bool is_pointer = false;
250 if (rhs_named_type == NULL && rhs_struct_type == NULL)
252 rhs_named_type = rhs_type->deref()->named_type();
253 rhs_struct_type = rhs_type->deref()->struct_type();
254 is_pointer = true;
256 if (rhs_named_type != NULL)
257 first_field =
258 rhs_named_type->interface_method_table(lhs_interface_type,
259 is_pointer);
260 else if (rhs_struct_type != NULL)
261 first_field =
262 rhs_struct_type->interface_method_table(lhs_interface_type,
263 is_pointer);
264 else
265 first_field = Expression::make_nil(location);
268 Expression* obj;
269 if (rhs_type->points_to() != NULL)
271 // We are assigning a pointer to the interface; the interface
272 // holds the pointer itself.
273 obj = rhs;
275 else
277 // We are assigning a non-pointer value to the interface; the
278 // interface gets a copy of the value in the heap.
279 obj = Expression::make_heap_expression(rhs, location);
282 return Expression::make_interface_value(lhs_type, first_field, obj, location);
285 // Return an expression for the type descriptor of RHS.
287 Expression*
288 Expression::get_interface_type_descriptor(Expression* rhs)
290 go_assert(rhs->type()->interface_type() != NULL);
291 Location location = rhs->location();
293 // The type descriptor is the first field of an empty interface.
294 if (rhs->type()->interface_type()->is_empty())
295 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
296 location);
298 Expression* mtable =
299 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
301 Expression* descriptor =
302 Expression::make_unary(OPERATOR_MULT, mtable, location);
303 descriptor = Expression::make_field_reference(descriptor, 0, location);
304 Expression* nil = Expression::make_nil(location);
306 Expression* eq =
307 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
308 return Expression::make_conditional(eq, nil, descriptor, location);
311 // Return an expression for the conversion of an interface type to an
312 // interface type.
314 Expression*
315 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
316 bool for_type_guard,
317 Location location)
319 Interface_type* lhs_interface_type = lhs_type->interface_type();
320 bool lhs_is_empty = lhs_interface_type->is_empty();
322 // In the general case this requires runtime examination of the type
323 // method table to match it up with the interface methods.
325 // FIXME: If all of the methods in the right hand side interface
326 // also appear in the left hand side interface, then we don't need
327 // to do a runtime check, although we still need to build a new
328 // method table.
330 // Get the type descriptor for the right hand side. This will be
331 // NULL for a nil interface.
332 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
333 Expression* lhs_type_expr =
334 Expression::make_type_descriptor(lhs_type, location);
336 Expression* first_field;
337 if (for_type_guard)
339 // A type assertion fails when converting a nil interface.
340 first_field =
341 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
342 lhs_type_expr, rhs_type_expr);
344 else if (lhs_is_empty)
346 // A conversion to an empty interface always succeeds, and the
347 // first field is just the type descriptor of the object.
348 first_field = rhs_type_expr;
350 else
352 // A conversion to a non-empty interface may fail, but unlike a
353 // type assertion converting nil will always succeed.
354 first_field =
355 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
356 lhs_type_expr, rhs_type_expr);
359 // The second field is simply the object pointer.
360 Expression* obj =
361 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
362 return Expression::make_interface_value(lhs_type, first_field, obj, location);
365 // Return an expression for the conversion of an interface type to a
366 // non-interface type.
368 Expression*
369 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
370 Location location)
372 // Call a function to check that the type is valid. The function
373 // will panic with an appropriate runtime type error if the type is
374 // not valid.
375 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
376 location);
377 Expression* rhs_descriptor =
378 Expression::get_interface_type_descriptor(rhs);
380 Type* rhs_type = rhs->type();
381 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
382 location);
384 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
385 location, 3, lhs_type_expr,
386 rhs_descriptor, rhs_inter_expr);
388 // If the call succeeds, pull out the value.
389 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
390 location);
392 // If the value is a pointer, then it is the value we want.
393 // Otherwise it points to the value.
394 if (lhs_type->points_to() == NULL)
396 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
397 location);
398 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
400 return Expression::make_compound(check_iface, obj, location);
403 // Convert an expression to a tree. This is implemented by the child
404 // class. Not that it is not in general safe to call this multiple
405 // times for a single expression, but that we don't catch such errors.
407 tree
408 Expression::get_tree(Translate_context* context)
410 // The child may have marked this expression as having an error.
411 if (this->classification_ == EXPRESSION_ERROR)
412 return error_mark_node;
414 return this->do_get_tree(context);
417 // Return a backend expression for VAL.
418 Bexpression*
419 Expression::backend_numeric_constant_expression(Translate_context* context,
420 Numeric_constant* val)
422 Gogo* gogo = context->gogo();
423 Type* type = val->type();
424 if (type == NULL)
425 return gogo->backend()->error_expression();
427 Btype* btype = type->get_backend(gogo);
428 Bexpression* ret;
429 if (type->integer_type() != NULL)
431 mpz_t ival;
432 if (!val->to_int(&ival))
434 go_assert(saw_errors());
435 return gogo->backend()->error_expression();
437 ret = gogo->backend()->integer_constant_expression(btype, ival);
438 mpz_clear(ival);
440 else if (type->float_type() != NULL)
442 mpfr_t fval;
443 if (!val->to_float(&fval))
445 go_assert(saw_errors());
446 return gogo->backend()->error_expression();
448 ret = gogo->backend()->float_constant_expression(btype, fval);
449 mpfr_clear(fval);
451 else if (type->complex_type() != NULL)
453 mpfr_t real;
454 mpfr_t imag;
455 if (!val->to_complex(&real, &imag))
457 go_assert(saw_errors());
458 return gogo->backend()->error_expression();
460 ret = gogo->backend()->complex_constant_expression(btype, real, imag);
461 mpfr_clear(real);
462 mpfr_clear(imag);
464 else
465 go_unreachable();
467 return ret;
470 // Return an expression which evaluates to true if VAL, of arbitrary integer
471 // type, is negative or is more than the maximum value of the Go type "int".
473 Expression*
474 Expression::check_bounds(Expression* val, Location loc)
476 Type* val_type = val->type();
477 Type* bound_type = Type::lookup_integer_type("int");
479 int val_type_size;
480 bool val_is_unsigned = false;
481 if (val_type->integer_type() != NULL)
483 val_type_size = val_type->integer_type()->bits();
484 val_is_unsigned = val_type->integer_type()->is_unsigned();
486 else
488 if (!val_type->is_numeric_type()
489 || !Type::are_convertible(bound_type, val_type, NULL))
491 go_assert(saw_errors());
492 return Expression::make_boolean(true, loc);
495 if (val_type->complex_type() != NULL)
496 val_type_size = val_type->complex_type()->bits();
497 else
498 val_type_size = val_type->float_type()->bits();
501 Expression* negative_index = Expression::make_boolean(false, loc);
502 Expression* index_overflows = Expression::make_boolean(false, loc);
503 if (!val_is_unsigned)
505 mpz_t zval;
506 mpz_init_set_ui(zval, 0UL);
507 Expression* zero = Expression::make_integer(&zval, val_type, loc);
508 mpz_clear(zval);
510 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
513 int bound_type_size = bound_type->integer_type()->bits();
514 if (val_type_size > bound_type_size
515 || (val_type_size == bound_type_size
516 && val_is_unsigned))
518 mpz_t one;
519 mpz_init_set_ui(one, 1UL);
521 // maxval = 2^(bound_type_size - 1) - 1
522 mpz_t maxval;
523 mpz_init(maxval);
524 mpz_mul_2exp(maxval, one, bound_type_size - 1);
525 mpz_sub_ui(maxval, maxval, 1);
526 Expression* max = Expression::make_integer(&maxval, val_type, loc);
527 mpz_clear(one);
528 mpz_clear(maxval);
530 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
533 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
534 loc);
537 void
538 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
540 this->do_dump_expression(ast_dump_context);
543 // Error expressions. This are used to avoid cascading errors.
545 class Error_expression : public Expression
547 public:
548 Error_expression(Location location)
549 : Expression(EXPRESSION_ERROR, location)
552 protected:
553 bool
554 do_is_constant() const
555 { return true; }
557 bool
558 do_numeric_constant_value(Numeric_constant* nc) const
560 nc->set_unsigned_long(NULL, 0);
561 return true;
564 bool
565 do_discarding_value()
566 { return true; }
568 Type*
569 do_type()
570 { return Type::make_error_type(); }
572 void
573 do_determine_type(const Type_context*)
576 Expression*
577 do_copy()
578 { return this; }
580 bool
581 do_is_addressable() const
582 { return true; }
584 tree
585 do_get_tree(Translate_context*)
586 { return error_mark_node; }
588 void
589 do_dump_expression(Ast_dump_context*) const;
592 // Dump the ast representation for an error expression to a dump context.
594 void
595 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
597 ast_dump_context->ostream() << "_Error_" ;
600 Expression*
601 Expression::make_error(Location location)
603 return new Error_expression(location);
606 // An expression which is really a type. This is used during parsing.
607 // It is an error if these survive after lowering.
609 class
610 Type_expression : public Expression
612 public:
613 Type_expression(Type* type, Location location)
614 : Expression(EXPRESSION_TYPE, location),
615 type_(type)
618 protected:
620 do_traverse(Traverse* traverse)
621 { return Type::traverse(this->type_, traverse); }
623 Type*
624 do_type()
625 { return this->type_; }
627 void
628 do_determine_type(const Type_context*)
631 void
632 do_check_types(Gogo*)
633 { this->report_error(_("invalid use of type")); }
635 Expression*
636 do_copy()
637 { return this; }
639 tree
640 do_get_tree(Translate_context*)
641 { go_unreachable(); }
643 void do_dump_expression(Ast_dump_context*) const;
645 private:
646 // The type which we are representing as an expression.
647 Type* type_;
650 void
651 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
653 ast_dump_context->dump_type(this->type_);
656 Expression*
657 Expression::make_type(Type* type, Location location)
659 return new Type_expression(type, location);
662 // Class Parser_expression.
664 Type*
665 Parser_expression::do_type()
667 // We should never really ask for the type of a Parser_expression.
668 // However, it can happen, at least when we have an invalid const
669 // whose initializer refers to the const itself. In that case we
670 // may ask for the type when lowering the const itself.
671 go_assert(saw_errors());
672 return Type::make_error_type();
675 // Class Var_expression.
677 // Lower a variable expression. Here we just make sure that the
678 // initialization expression of the variable has been lowered. This
679 // ensures that we will be able to determine the type of the variable
680 // if necessary.
682 Expression*
683 Var_expression::do_lower(Gogo* gogo, Named_object* function,
684 Statement_inserter* inserter, int)
686 if (this->variable_->is_variable())
688 Variable* var = this->variable_->var_value();
689 // This is either a local variable or a global variable. A
690 // reference to a variable which is local to an enclosing
691 // function will be a reference to a field in a closure.
692 if (var->is_global())
694 function = NULL;
695 inserter = NULL;
697 var->lower_init_expression(gogo, function, inserter);
699 return this;
702 // Return the type of a reference to a variable.
704 Type*
705 Var_expression::do_type()
707 if (this->variable_->is_variable())
708 return this->variable_->var_value()->type();
709 else if (this->variable_->is_result_variable())
710 return this->variable_->result_var_value()->type();
711 else
712 go_unreachable();
715 // Determine the type of a reference to a variable.
717 void
718 Var_expression::do_determine_type(const Type_context*)
720 if (this->variable_->is_variable())
721 this->variable_->var_value()->determine_type();
724 // Something takes the address of this variable. This means that we
725 // may want to move the variable onto the heap.
727 void
728 Var_expression::do_address_taken(bool escapes)
730 if (!escapes)
732 if (this->variable_->is_variable())
733 this->variable_->var_value()->set_non_escaping_address_taken();
734 else if (this->variable_->is_result_variable())
735 this->variable_->result_var_value()->set_non_escaping_address_taken();
736 else
737 go_unreachable();
739 else
741 if (this->variable_->is_variable())
742 this->variable_->var_value()->set_address_taken();
743 else if (this->variable_->is_result_variable())
744 this->variable_->result_var_value()->set_address_taken();
745 else
746 go_unreachable();
750 // Get the tree for a reference to a variable.
752 tree
753 Var_expression::do_get_tree(Translate_context* context)
755 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
756 context->function());
757 bool is_in_heap;
758 Location loc = this->location();
759 if (this->variable_->is_variable())
760 is_in_heap = this->variable_->var_value()->is_in_heap();
761 else if (this->variable_->is_result_variable())
762 is_in_heap = this->variable_->result_var_value()->is_in_heap();
763 else
764 go_unreachable();
766 Bexpression* ret = context->backend()->var_expression(bvar, loc);
767 if (is_in_heap)
768 ret = context->backend()->indirect_expression(ret, true, loc);
769 return expr_to_tree(ret);
772 // Ast dump for variable expression.
774 void
775 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
777 ast_dump_context->ostream() << this->variable_->name() ;
780 // Make a reference to a variable in an expression.
782 Expression*
783 Expression::make_var_reference(Named_object* var, Location location)
785 if (var->is_sink())
786 return Expression::make_sink(location);
788 // FIXME: Creating a new object for each reference to a variable is
789 // wasteful.
790 return new Var_expression(var, location);
793 // Class Temporary_reference_expression.
795 // The type.
797 Type*
798 Temporary_reference_expression::do_type()
800 return this->statement_->type();
803 // Called if something takes the address of this temporary variable.
804 // We never have to move temporary variables to the heap, but we do
805 // need to know that they must live in the stack rather than in a
806 // register.
808 void
809 Temporary_reference_expression::do_address_taken(bool)
811 this->statement_->set_is_address_taken();
814 // Get a tree referring to the variable.
816 tree
817 Temporary_reference_expression::do_get_tree(Translate_context* context)
819 Gogo* gogo = context->gogo();
820 Bvariable* bvar = this->statement_->get_backend_variable(context);
821 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
823 // The backend can't always represent the same set of recursive types
824 // that the Go frontend can. In some cases this means that a
825 // temporary variable won't have the right backend type. Correct
826 // that here by adding a type cast. We need to use base() to push
827 // the circularity down one level.
828 Type* stype = this->statement_->type();
829 if (!this->is_lvalue_
830 && stype->has_pointer()
831 && stype->deref()->is_void_type())
833 Btype* btype = this->type()->base()->get_backend(gogo);
834 ret = gogo->backend()->convert_expression(btype, ret, this->location());
836 return expr_to_tree(ret);
839 // Ast dump for temporary reference.
841 void
842 Temporary_reference_expression::do_dump_expression(
843 Ast_dump_context* ast_dump_context) const
845 ast_dump_context->dump_temp_variable_name(this->statement_);
848 // Make a reference to a temporary variable.
850 Temporary_reference_expression*
851 Expression::make_temporary_reference(Temporary_statement* statement,
852 Location location)
854 return new Temporary_reference_expression(statement, location);
857 // Class Set_and_use_temporary_expression.
859 // Return the type.
861 Type*
862 Set_and_use_temporary_expression::do_type()
864 return this->statement_->type();
867 // Determine the type of the expression.
869 void
870 Set_and_use_temporary_expression::do_determine_type(
871 const Type_context* context)
873 this->expr_->determine_type(context);
876 // Take the address.
878 void
879 Set_and_use_temporary_expression::do_address_taken(bool)
881 this->statement_->set_is_address_taken();
884 // Return the backend representation.
886 tree
887 Set_and_use_temporary_expression::do_get_tree(Translate_context* context)
889 Bvariable* bvar = this->statement_->get_backend_variable(context);
890 tree var_tree = var_to_tree(bvar);
891 tree expr_tree = this->expr_->get_tree(context);
892 if (var_tree == error_mark_node || expr_tree == error_mark_node)
893 return error_mark_node;
894 Location loc = this->location();
895 return build2_loc(loc.gcc_location(), COMPOUND_EXPR, TREE_TYPE(var_tree),
896 build2_loc(loc.gcc_location(), MODIFY_EXPR, void_type_node,
897 var_tree, expr_tree),
898 var_tree);
901 // Dump.
903 void
904 Set_and_use_temporary_expression::do_dump_expression(
905 Ast_dump_context* ast_dump_context) const
907 ast_dump_context->ostream() << '(';
908 ast_dump_context->dump_temp_variable_name(this->statement_);
909 ast_dump_context->ostream() << " = ";
910 this->expr_->dump_expression(ast_dump_context);
911 ast_dump_context->ostream() << ')';
914 // Make a set-and-use temporary.
916 Set_and_use_temporary_expression*
917 Expression::make_set_and_use_temporary(Temporary_statement* statement,
918 Expression* expr, Location location)
920 return new Set_and_use_temporary_expression(statement, expr, location);
923 // A sink expression--a use of the blank identifier _.
925 class Sink_expression : public Expression
927 public:
928 Sink_expression(Location location)
929 : Expression(EXPRESSION_SINK, location),
930 type_(NULL), var_(NULL_TREE)
933 protected:
934 bool
935 do_discarding_value()
936 { return true; }
938 Type*
939 do_type();
941 void
942 do_determine_type(const Type_context*);
944 Expression*
945 do_copy()
946 { return new Sink_expression(this->location()); }
948 tree
949 do_get_tree(Translate_context*);
951 void
952 do_dump_expression(Ast_dump_context*) const;
954 private:
955 // The type of this sink variable.
956 Type* type_;
957 // The temporary variable we generate.
958 tree var_;
961 // Return the type of a sink expression.
963 Type*
964 Sink_expression::do_type()
966 if (this->type_ == NULL)
967 return Type::make_sink_type();
968 return this->type_;
971 // Determine the type of a sink expression.
973 void
974 Sink_expression::do_determine_type(const Type_context* context)
976 if (context->type != NULL)
977 this->type_ = context->type;
980 // Return a temporary variable for a sink expression. This will
981 // presumably be a write-only variable which the middle-end will drop.
983 tree
984 Sink_expression::do_get_tree(Translate_context* context)
986 if (this->var_ == NULL_TREE)
988 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
989 Btype* bt = this->type_->get_backend(context->gogo());
990 this->var_ = create_tmp_var(type_to_tree(bt), "blank");
992 return this->var_;
995 // Ast dump for sink expression.
997 void
998 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1000 ast_dump_context->ostream() << "_" ;
1003 // Make a sink expression.
1005 Expression*
1006 Expression::make_sink(Location location)
1008 return new Sink_expression(location);
1011 // Class Func_expression.
1013 // FIXME: Can a function expression appear in a constant expression?
1014 // The value is unchanging. Initializing a constant to the address of
1015 // a function seems like it could work, though there might be little
1016 // point to it.
1018 // Traversal.
1021 Func_expression::do_traverse(Traverse* traverse)
1023 return (this->closure_ == NULL
1024 ? TRAVERSE_CONTINUE
1025 : Expression::traverse(&this->closure_, traverse));
1028 // Return the type of a function expression.
1030 Type*
1031 Func_expression::do_type()
1033 if (this->function_->is_function())
1034 return this->function_->func_value()->type();
1035 else if (this->function_->is_function_declaration())
1036 return this->function_->func_declaration_value()->type();
1037 else
1038 go_unreachable();
1041 // Get the tree for the code of a function expression.
1043 Bexpression*
1044 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1046 Function_type* fntype;
1047 if (no->is_function())
1048 fntype = no->func_value()->type();
1049 else if (no->is_function_declaration())
1050 fntype = no->func_declaration_value()->type();
1051 else
1052 go_unreachable();
1054 // Builtin functions are handled specially by Call_expression. We
1055 // can't take their address.
1056 if (fntype->is_builtin())
1058 error_at(loc,
1059 "invalid use of special builtin function %qs; must be called",
1060 no->message_name().c_str());
1061 return gogo->backend()->error_expression();
1064 Bfunction* fndecl;
1065 if (no->is_function())
1066 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1067 else if (no->is_function_declaration())
1068 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1069 else
1070 go_unreachable();
1072 return gogo->backend()->function_code_expression(fndecl, loc);
1075 // Get the tree for a function expression. This is used when we take
1076 // the address of a function rather than simply calling it. A func
1077 // value is represented as a pointer to a block of memory. The first
1078 // word of that memory is a pointer to the function code. The
1079 // remaining parts of that memory are the addresses of variables that
1080 // the function closes over.
1082 tree
1083 Func_expression::do_get_tree(Translate_context* context)
1085 // If there is no closure, just use the function descriptor.
1086 if (this->closure_ == NULL)
1088 Gogo* gogo = context->gogo();
1089 Named_object* no = this->function_;
1090 Expression* descriptor;
1091 if (no->is_function())
1092 descriptor = no->func_value()->descriptor(gogo, no);
1093 else if (no->is_function_declaration())
1095 if (no->func_declaration_value()->type()->is_builtin())
1097 error_at(this->location(),
1098 ("invalid use of special builtin function %qs; "
1099 "must be called"),
1100 no->message_name().c_str());
1101 return error_mark_node;
1103 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1105 else
1106 go_unreachable();
1108 tree dtree = descriptor->get_tree(context);
1109 if (dtree == error_mark_node)
1110 return error_mark_node;
1111 return build_fold_addr_expr_loc(this->location().gcc_location(), dtree);
1114 go_assert(this->function_->func_value()->enclosing() != NULL);
1116 // If there is a closure, then the closure is itself the function
1117 // expression. It is a pointer to a struct whose first field points
1118 // to the function code and whose remaining fields are the addresses
1119 // of the closed-over variables.
1120 return this->closure_->get_tree(context);
1123 // Ast dump for function.
1125 void
1126 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1128 ast_dump_context->ostream() << this->function_->name();
1129 if (this->closure_ != NULL)
1131 ast_dump_context->ostream() << " {closure = ";
1132 this->closure_->dump_expression(ast_dump_context);
1133 ast_dump_context->ostream() << "}";
1137 // Make a reference to a function in an expression.
1139 Expression*
1140 Expression::make_func_reference(Named_object* function, Expression* closure,
1141 Location location)
1143 return new Func_expression(function, closure, location);
1146 // Class Func_descriptor_expression.
1148 // Constructor.
1150 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1151 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1152 fn_(fn), dvar_(NULL)
1154 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1157 // Traversal.
1160 Func_descriptor_expression::do_traverse(Traverse*)
1162 return TRAVERSE_CONTINUE;
1165 // All function descriptors have the same type.
1167 Type* Func_descriptor_expression::descriptor_type;
1169 void
1170 Func_descriptor_expression::make_func_descriptor_type()
1172 if (Func_descriptor_expression::descriptor_type != NULL)
1173 return;
1174 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1175 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1176 Func_descriptor_expression::descriptor_type =
1177 Type::make_builtin_named_type("functionDescriptor", struct_type);
1180 Type*
1181 Func_descriptor_expression::do_type()
1183 Func_descriptor_expression::make_func_descriptor_type();
1184 return Func_descriptor_expression::descriptor_type;
1187 // The tree for a function descriptor.
1189 tree
1190 Func_descriptor_expression::do_get_tree(Translate_context* context)
1192 if (this->dvar_ != NULL)
1193 return var_to_tree(this->dvar_);
1195 Gogo* gogo = context->gogo();
1196 Named_object* no = this->fn_;
1197 Location loc = no->location();
1199 std::string var_name;
1200 if (no->package() == NULL)
1201 var_name = gogo->pkgpath_symbol();
1202 else
1203 var_name = no->package()->pkgpath_symbol();
1204 var_name.push_back('.');
1205 var_name.append(Gogo::unpack_hidden_name(no->name()));
1206 var_name.append("$descriptor");
1208 Btype* btype = this->type()->get_backend(gogo);
1210 Bvariable* bvar;
1211 if (no->package() != NULL
1212 || Linemap::is_predeclared_location(no->location()))
1213 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1214 loc);
1215 else
1217 Location bloc = Linemap::predeclared_location();
1218 bool is_hidden = ((no->is_function()
1219 && no->func_value()->enclosing() != NULL)
1220 || Gogo::is_thunk(no));
1221 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1222 btype, bloc);
1223 Expression_list* vals = new Expression_list();
1224 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1225 Expression* init =
1226 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1227 Translate_context bcontext(gogo, NULL, NULL, NULL);
1228 bcontext.set_is_const();
1229 Bexpression* binit = tree_to_expr(init->get_tree(&bcontext));
1230 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1231 false, btype, bloc, binit);
1234 this->dvar_ = bvar;
1235 return var_to_tree(bvar);
1238 // Print a function descriptor expression.
1240 void
1241 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1243 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1246 // Make a function descriptor expression.
1248 Func_descriptor_expression*
1249 Expression::make_func_descriptor(Named_object* fn)
1251 return new Func_descriptor_expression(fn);
1254 // Make the function descriptor type, so that it can be converted.
1256 void
1257 Expression::make_func_descriptor_type()
1259 Func_descriptor_expression::make_func_descriptor_type();
1262 // A reference to just the code of a function.
1264 class Func_code_reference_expression : public Expression
1266 public:
1267 Func_code_reference_expression(Named_object* function, Location location)
1268 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1269 function_(function)
1272 protected:
1274 do_traverse(Traverse*)
1275 { return TRAVERSE_CONTINUE; }
1277 bool
1278 do_is_immutable() const
1279 { return true; }
1281 Type*
1282 do_type()
1283 { return Type::make_pointer_type(Type::make_void_type()); }
1285 void
1286 do_determine_type(const Type_context*)
1289 Expression*
1290 do_copy()
1292 return Expression::make_func_code_reference(this->function_,
1293 this->location());
1296 tree
1297 do_get_tree(Translate_context*);
1299 void
1300 do_dump_expression(Ast_dump_context* context) const
1301 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1303 private:
1304 // The function.
1305 Named_object* function_;
1308 // Get the tree for a reference to function code.
1310 tree
1311 Func_code_reference_expression::do_get_tree(Translate_context* context)
1313 Bexpression* ret =
1314 Func_expression::get_code_pointer(context->gogo(), this->function_,
1315 this->location());
1316 return expr_to_tree(ret);
1319 // Make a reference to the code of a function.
1321 Expression*
1322 Expression::make_func_code_reference(Named_object* function, Location location)
1324 return new Func_code_reference_expression(function, location);
1327 // Class Unknown_expression.
1329 // Return the name of an unknown expression.
1331 const std::string&
1332 Unknown_expression::name() const
1334 return this->named_object_->name();
1337 // Lower a reference to an unknown name.
1339 Expression*
1340 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1342 Location location = this->location();
1343 Named_object* no = this->named_object_;
1344 Named_object* real;
1345 if (!no->is_unknown())
1346 real = no;
1347 else
1349 real = no->unknown_value()->real_named_object();
1350 if (real == NULL)
1352 if (this->is_composite_literal_key_)
1353 return this;
1354 if (!this->no_error_message_)
1355 error_at(location, "reference to undefined name %qs",
1356 this->named_object_->message_name().c_str());
1357 return Expression::make_error(location);
1360 switch (real->classification())
1362 case Named_object::NAMED_OBJECT_CONST:
1363 return Expression::make_const_reference(real, location);
1364 case Named_object::NAMED_OBJECT_TYPE:
1365 return Expression::make_type(real->type_value(), location);
1366 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1367 if (this->is_composite_literal_key_)
1368 return this;
1369 if (!this->no_error_message_)
1370 error_at(location, "reference to undefined type %qs",
1371 real->message_name().c_str());
1372 return Expression::make_error(location);
1373 case Named_object::NAMED_OBJECT_VAR:
1374 real->var_value()->set_is_used();
1375 return Expression::make_var_reference(real, location);
1376 case Named_object::NAMED_OBJECT_FUNC:
1377 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1378 return Expression::make_func_reference(real, NULL, location);
1379 case Named_object::NAMED_OBJECT_PACKAGE:
1380 if (this->is_composite_literal_key_)
1381 return this;
1382 if (!this->no_error_message_)
1383 error_at(location, "unexpected reference to package");
1384 return Expression::make_error(location);
1385 default:
1386 go_unreachable();
1390 // Dump the ast representation for an unknown expression to a dump context.
1392 void
1393 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1395 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1396 << ")";
1399 // Make a reference to an unknown name.
1401 Unknown_expression*
1402 Expression::make_unknown_reference(Named_object* no, Location location)
1404 return new Unknown_expression(no, location);
1407 // A boolean expression.
1409 class Boolean_expression : public Expression
1411 public:
1412 Boolean_expression(bool val, Location location)
1413 : Expression(EXPRESSION_BOOLEAN, location),
1414 val_(val), type_(NULL)
1417 static Expression*
1418 do_import(Import*);
1420 protected:
1421 bool
1422 do_is_constant() const
1423 { return true; }
1425 Type*
1426 do_type();
1428 void
1429 do_determine_type(const Type_context*);
1431 Expression*
1432 do_copy()
1433 { return this; }
1435 tree
1436 do_get_tree(Translate_context*)
1437 { return this->val_ ? boolean_true_node : boolean_false_node; }
1439 void
1440 do_export(Export* exp) const
1441 { exp->write_c_string(this->val_ ? "true" : "false"); }
1443 void
1444 do_dump_expression(Ast_dump_context* ast_dump_context) const
1445 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1447 private:
1448 // The constant.
1449 bool val_;
1450 // The type as determined by context.
1451 Type* type_;
1454 // Get the type.
1456 Type*
1457 Boolean_expression::do_type()
1459 if (this->type_ == NULL)
1460 this->type_ = Type::make_boolean_type();
1461 return this->type_;
1464 // Set the type from the context.
1466 void
1467 Boolean_expression::do_determine_type(const Type_context* context)
1469 if (this->type_ != NULL && !this->type_->is_abstract())
1471 else if (context->type != NULL && context->type->is_boolean_type())
1472 this->type_ = context->type;
1473 else if (!context->may_be_abstract)
1474 this->type_ = Type::lookup_bool_type();
1477 // Import a boolean constant.
1479 Expression*
1480 Boolean_expression::do_import(Import* imp)
1482 if (imp->peek_char() == 't')
1484 imp->require_c_string("true");
1485 return Expression::make_boolean(true, imp->location());
1487 else
1489 imp->require_c_string("false");
1490 return Expression::make_boolean(false, imp->location());
1494 // Make a boolean expression.
1496 Expression*
1497 Expression::make_boolean(bool val, Location location)
1499 return new Boolean_expression(val, location);
1502 // Class String_expression.
1504 // Get the type.
1506 Type*
1507 String_expression::do_type()
1509 if (this->type_ == NULL)
1510 this->type_ = Type::make_string_type();
1511 return this->type_;
1514 // Set the type from the context.
1516 void
1517 String_expression::do_determine_type(const Type_context* context)
1519 if (this->type_ != NULL && !this->type_->is_abstract())
1521 else if (context->type != NULL && context->type->is_string_type())
1522 this->type_ = context->type;
1523 else if (!context->may_be_abstract)
1524 this->type_ = Type::lookup_string_type();
1527 // Build a string constant.
1529 tree
1530 String_expression::do_get_tree(Translate_context* context)
1532 Gogo* gogo = context->gogo();
1533 Btype* btype = Type::make_string_type()->get_backend(gogo);
1535 Location loc = this->location();
1536 std::vector<Bexpression*> init(2);
1537 Bexpression* str_cst =
1538 gogo->backend()->string_constant_expression(this->val_);
1539 init[0] = gogo->backend()->address_expression(str_cst, loc);
1541 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1542 mpz_t lenval;
1543 mpz_init_set_ui(lenval, this->val_.length());
1544 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1545 mpz_clear(lenval);
1547 Bexpression* ret = gogo->backend()->constructor_expression(btype, init, loc);
1548 return expr_to_tree(ret);
1551 // Write string literal to string dump.
1553 void
1554 String_expression::export_string(String_dump* exp,
1555 const String_expression* str)
1557 std::string s;
1558 s.reserve(str->val_.length() * 4 + 2);
1559 s += '"';
1560 for (std::string::const_iterator p = str->val_.begin();
1561 p != str->val_.end();
1562 ++p)
1564 if (*p == '\\' || *p == '"')
1566 s += '\\';
1567 s += *p;
1569 else if (*p >= 0x20 && *p < 0x7f)
1570 s += *p;
1571 else if (*p == '\n')
1572 s += "\\n";
1573 else if (*p == '\t')
1574 s += "\\t";
1575 else
1577 s += "\\x";
1578 unsigned char c = *p;
1579 unsigned int dig = c >> 4;
1580 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1581 dig = c & 0xf;
1582 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1585 s += '"';
1586 exp->write_string(s);
1589 // Export a string expression.
1591 void
1592 String_expression::do_export(Export* exp) const
1594 String_expression::export_string(exp, this);
1597 // Import a string expression.
1599 Expression*
1600 String_expression::do_import(Import* imp)
1602 imp->require_c_string("\"");
1603 std::string val;
1604 while (true)
1606 int c = imp->get_char();
1607 if (c == '"' || c == -1)
1608 break;
1609 if (c != '\\')
1610 val += static_cast<char>(c);
1611 else
1613 c = imp->get_char();
1614 if (c == '\\' || c == '"')
1615 val += static_cast<char>(c);
1616 else if (c == 'n')
1617 val += '\n';
1618 else if (c == 't')
1619 val += '\t';
1620 else if (c == 'x')
1622 c = imp->get_char();
1623 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1624 c = imp->get_char();
1625 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1626 char v = (vh << 4) | vl;
1627 val += v;
1629 else
1631 error_at(imp->location(), "bad string constant");
1632 return Expression::make_error(imp->location());
1636 return Expression::make_string(val, imp->location());
1639 // Ast dump for string expression.
1641 void
1642 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1644 String_expression::export_string(ast_dump_context, this);
1647 // Make a string expression.
1649 Expression*
1650 Expression::make_string(const std::string& val, Location location)
1652 return new String_expression(val, location);
1655 // An expression that evaluates to some characteristic of a string.
1656 // This is used when indexing, bound-checking, or nil checking a string.
1658 class String_info_expression : public Expression
1660 public:
1661 String_info_expression(Expression* string, String_info string_info,
1662 Location location)
1663 : Expression(EXPRESSION_STRING_INFO, location),
1664 string_(string), string_info_(string_info)
1667 protected:
1668 Type*
1669 do_type();
1671 void
1672 do_determine_type(const Type_context*)
1673 { go_unreachable(); }
1675 Expression*
1676 do_copy()
1678 return new String_info_expression(this->string_->copy(), this->string_info_,
1679 this->location());
1682 tree
1683 do_get_tree(Translate_context* context);
1685 void
1686 do_dump_expression(Ast_dump_context*) const;
1688 void
1689 do_issue_nil_check()
1690 { this->string_->issue_nil_check(); }
1692 private:
1693 // The string for which we are getting information.
1694 Expression* string_;
1695 // What information we want.
1696 String_info string_info_;
1699 // Return the type of the string info.
1701 Type*
1702 String_info_expression::do_type()
1704 switch (this->string_info_)
1706 case STRING_INFO_DATA:
1708 Type* byte_type = Type::lookup_integer_type("uint8");
1709 return Type::make_pointer_type(byte_type);
1711 case STRING_INFO_LENGTH:
1712 return Type::lookup_integer_type("int");
1713 default:
1714 go_unreachable();
1718 // Return string information in GENERIC.
1720 tree
1721 String_info_expression::do_get_tree(Translate_context* context)
1723 Gogo* gogo = context->gogo();
1725 Bexpression* bstring = tree_to_expr(this->string_->get_tree(context));
1726 Bexpression* ret;
1727 switch (this->string_info_)
1729 case STRING_INFO_DATA:
1730 case STRING_INFO_LENGTH:
1731 ret = gogo->backend()->struct_field_expression(bstring, this->string_info_,
1732 this->location());
1733 break;
1734 default:
1735 go_unreachable();
1737 return expr_to_tree(ret);
1740 // Dump ast representation for a type info expression.
1742 void
1743 String_info_expression::do_dump_expression(
1744 Ast_dump_context* ast_dump_context) const
1746 ast_dump_context->ostream() << "stringinfo(";
1747 this->string_->dump_expression(ast_dump_context);
1748 ast_dump_context->ostream() << ",";
1749 ast_dump_context->ostream() <<
1750 (this->string_info_ == STRING_INFO_DATA ? "data"
1751 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1752 : "unknown");
1753 ast_dump_context->ostream() << ")";
1756 // Make a string info expression.
1758 Expression*
1759 Expression::make_string_info(Expression* string, String_info string_info,
1760 Location location)
1762 return new String_info_expression(string, string_info, location);
1765 // Make an integer expression.
1767 class Integer_expression : public Expression
1769 public:
1770 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1771 Location location)
1772 : Expression(EXPRESSION_INTEGER, location),
1773 type_(type), is_character_constant_(is_character_constant)
1774 { mpz_init_set(this->val_, *val); }
1776 static Expression*
1777 do_import(Import*);
1779 // Write VAL to string dump.
1780 static void
1781 export_integer(String_dump* exp, const mpz_t val);
1783 // Write VAL to dump context.
1784 static void
1785 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1787 protected:
1788 bool
1789 do_is_constant() const
1790 { return true; }
1792 bool
1793 do_numeric_constant_value(Numeric_constant* nc) const;
1795 Type*
1796 do_type();
1798 void
1799 do_determine_type(const Type_context* context);
1801 void
1802 do_check_types(Gogo*);
1804 tree
1805 do_get_tree(Translate_context*);
1807 Expression*
1808 do_copy()
1810 if (this->is_character_constant_)
1811 return Expression::make_character(&this->val_, this->type_,
1812 this->location());
1813 else
1814 return Expression::make_integer(&this->val_, this->type_,
1815 this->location());
1818 void
1819 do_export(Export*) const;
1821 void
1822 do_dump_expression(Ast_dump_context*) const;
1824 private:
1825 // The integer value.
1826 mpz_t val_;
1827 // The type so far.
1828 Type* type_;
1829 // Whether this is a character constant.
1830 bool is_character_constant_;
1833 // Return a numeric constant for this expression. We have to mark
1834 // this as a character when appropriate.
1836 bool
1837 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1839 if (this->is_character_constant_)
1840 nc->set_rune(this->type_, this->val_);
1841 else
1842 nc->set_int(this->type_, this->val_);
1843 return true;
1846 // Return the current type. If we haven't set the type yet, we return
1847 // an abstract integer type.
1849 Type*
1850 Integer_expression::do_type()
1852 if (this->type_ == NULL)
1854 if (this->is_character_constant_)
1855 this->type_ = Type::make_abstract_character_type();
1856 else
1857 this->type_ = Type::make_abstract_integer_type();
1859 return this->type_;
1862 // Set the type of the integer value. Here we may switch from an
1863 // abstract type to a real type.
1865 void
1866 Integer_expression::do_determine_type(const Type_context* context)
1868 if (this->type_ != NULL && !this->type_->is_abstract())
1870 else if (context->type != NULL && context->type->is_numeric_type())
1871 this->type_ = context->type;
1872 else if (!context->may_be_abstract)
1874 if (this->is_character_constant_)
1875 this->type_ = Type::lookup_integer_type("int32");
1876 else
1877 this->type_ = Type::lookup_integer_type("int");
1881 // Check the type of an integer constant.
1883 void
1884 Integer_expression::do_check_types(Gogo*)
1886 Type* type = this->type_;
1887 if (type == NULL)
1888 return;
1889 Numeric_constant nc;
1890 if (this->is_character_constant_)
1891 nc.set_rune(NULL, this->val_);
1892 else
1893 nc.set_int(NULL, this->val_);
1894 if (!nc.set_type(type, true, this->location()))
1895 this->set_is_error();
1898 // Get a tree for an integer constant.
1900 tree
1901 Integer_expression::do_get_tree(Translate_context* context)
1903 Type* resolved_type = NULL;
1904 if (this->type_ != NULL && !this->type_->is_abstract())
1905 resolved_type = this->type_;
1906 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1908 // We are converting to an abstract floating point type.
1909 resolved_type = Type::lookup_float_type("float64");
1911 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1913 // We are converting to an abstract complex type.
1914 resolved_type = Type::lookup_complex_type("complex128");
1916 else
1918 // If we still have an abstract type here, then this is being
1919 // used in a constant expression which didn't get reduced for
1920 // some reason. Use a type which will fit the value. We use <,
1921 // not <=, because we need an extra bit for the sign bit.
1922 int bits = mpz_sizeinbase(this->val_, 2);
1923 Type* int_type = Type::lookup_integer_type("int");
1924 if (bits < int_type->integer_type()->bits())
1925 resolved_type = int_type;
1926 else if (bits < 64)
1927 resolved_type = Type::lookup_integer_type("int64");
1928 else
1930 if (!saw_errors())
1931 error_at(this->location(),
1932 "unknown type for large integer constant");
1933 Bexpression* ret = context->gogo()->backend()->error_expression();
1934 return expr_to_tree(ret);
1937 Numeric_constant nc;
1938 nc.set_int(resolved_type, this->val_);
1939 Bexpression* ret =
1940 Expression::backend_numeric_constant_expression(context, &nc);
1941 return expr_to_tree(ret);
1944 // Write VAL to export data.
1946 void
1947 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1949 char* s = mpz_get_str(NULL, 10, val);
1950 exp->write_c_string(s);
1951 free(s);
1954 // Export an integer in a constant expression.
1956 void
1957 Integer_expression::do_export(Export* exp) const
1959 Integer_expression::export_integer(exp, this->val_);
1960 if (this->is_character_constant_)
1961 exp->write_c_string("'");
1962 // A trailing space lets us reliably identify the end of the number.
1963 exp->write_c_string(" ");
1966 // Import an integer, floating point, or complex value. This handles
1967 // all these types because they all start with digits.
1969 Expression*
1970 Integer_expression::do_import(Import* imp)
1972 std::string num = imp->read_identifier();
1973 imp->require_c_string(" ");
1974 if (!num.empty() && num[num.length() - 1] == 'i')
1976 mpfr_t real;
1977 size_t plus_pos = num.find('+', 1);
1978 size_t minus_pos = num.find('-', 1);
1979 size_t pos;
1980 if (plus_pos == std::string::npos)
1981 pos = minus_pos;
1982 else if (minus_pos == std::string::npos)
1983 pos = plus_pos;
1984 else
1986 error_at(imp->location(), "bad number in import data: %qs",
1987 num.c_str());
1988 return Expression::make_error(imp->location());
1990 if (pos == std::string::npos)
1991 mpfr_set_ui(real, 0, GMP_RNDN);
1992 else
1994 std::string real_str = num.substr(0, pos);
1995 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1997 error_at(imp->location(), "bad number in import data: %qs",
1998 real_str.c_str());
1999 return Expression::make_error(imp->location());
2003 std::string imag_str;
2004 if (pos == std::string::npos)
2005 imag_str = num;
2006 else
2007 imag_str = num.substr(pos);
2008 imag_str = imag_str.substr(0, imag_str.size() - 1);
2009 mpfr_t imag;
2010 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2012 error_at(imp->location(), "bad number in import data: %qs",
2013 imag_str.c_str());
2014 return Expression::make_error(imp->location());
2016 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2017 imp->location());
2018 mpfr_clear(real);
2019 mpfr_clear(imag);
2020 return ret;
2022 else if (num.find('.') == std::string::npos
2023 && num.find('E') == std::string::npos)
2025 bool is_character_constant = (!num.empty()
2026 && num[num.length() - 1] == '\'');
2027 if (is_character_constant)
2028 num = num.substr(0, num.length() - 1);
2029 mpz_t val;
2030 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2032 error_at(imp->location(), "bad number in import data: %qs",
2033 num.c_str());
2034 return Expression::make_error(imp->location());
2036 Expression* ret;
2037 if (is_character_constant)
2038 ret = Expression::make_character(&val, NULL, imp->location());
2039 else
2040 ret = Expression::make_integer(&val, NULL, imp->location());
2041 mpz_clear(val);
2042 return ret;
2044 else
2046 mpfr_t val;
2047 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2049 error_at(imp->location(), "bad number in import data: %qs",
2050 num.c_str());
2051 return Expression::make_error(imp->location());
2053 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2054 mpfr_clear(val);
2055 return ret;
2058 // Ast dump for integer expression.
2060 void
2061 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2063 if (this->is_character_constant_)
2064 ast_dump_context->ostream() << '\'';
2065 Integer_expression::export_integer(ast_dump_context, this->val_);
2066 if (this->is_character_constant_)
2067 ast_dump_context->ostream() << '\'';
2070 // Build a new integer value.
2072 Expression*
2073 Expression::make_integer(const mpz_t* val, Type* type, Location location)
2075 return new Integer_expression(val, type, false, location);
2078 // Build a new character constant value.
2080 Expression*
2081 Expression::make_character(const mpz_t* val, Type* type, Location location)
2083 return new Integer_expression(val, type, true, location);
2086 // Floats.
2088 class Float_expression : public Expression
2090 public:
2091 Float_expression(const mpfr_t* val, Type* type, Location location)
2092 : Expression(EXPRESSION_FLOAT, location),
2093 type_(type)
2095 mpfr_init_set(this->val_, *val, GMP_RNDN);
2098 // Write VAL to export data.
2099 static void
2100 export_float(String_dump* exp, const mpfr_t val);
2102 // Write VAL to dump file.
2103 static void
2104 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2106 protected:
2107 bool
2108 do_is_constant() const
2109 { return true; }
2111 bool
2112 do_numeric_constant_value(Numeric_constant* nc) const
2114 nc->set_float(this->type_, this->val_);
2115 return true;
2118 Type*
2119 do_type();
2121 void
2122 do_determine_type(const Type_context*);
2124 void
2125 do_check_types(Gogo*);
2127 Expression*
2128 do_copy()
2129 { return Expression::make_float(&this->val_, this->type_,
2130 this->location()); }
2132 tree
2133 do_get_tree(Translate_context*);
2135 void
2136 do_export(Export*) const;
2138 void
2139 do_dump_expression(Ast_dump_context*) const;
2141 private:
2142 // The floating point value.
2143 mpfr_t val_;
2144 // The type so far.
2145 Type* type_;
2148 // Return the current type. If we haven't set the type yet, we return
2149 // an abstract float type.
2151 Type*
2152 Float_expression::do_type()
2154 if (this->type_ == NULL)
2155 this->type_ = Type::make_abstract_float_type();
2156 return this->type_;
2159 // Set the type of the float value. Here we may switch from an
2160 // abstract type to a real type.
2162 void
2163 Float_expression::do_determine_type(const Type_context* context)
2165 if (this->type_ != NULL && !this->type_->is_abstract())
2167 else if (context->type != NULL
2168 && (context->type->integer_type() != NULL
2169 || context->type->float_type() != NULL
2170 || context->type->complex_type() != NULL))
2171 this->type_ = context->type;
2172 else if (!context->may_be_abstract)
2173 this->type_ = Type::lookup_float_type("float64");
2176 // Check the type of a float value.
2178 void
2179 Float_expression::do_check_types(Gogo*)
2181 Type* type = this->type_;
2182 if (type == NULL)
2183 return;
2184 Numeric_constant nc;
2185 nc.set_float(NULL, this->val_);
2186 if (!nc.set_type(this->type_, true, this->location()))
2187 this->set_is_error();
2190 // Get a tree for a float constant.
2192 tree
2193 Float_expression::do_get_tree(Translate_context* context)
2195 Type* resolved_type;
2196 if (this->type_ != NULL && !this->type_->is_abstract())
2197 resolved_type = this->type_;
2198 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2200 // We have an abstract integer type. We just hope for the best.
2201 resolved_type = Type::lookup_integer_type("int");
2203 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2205 // We are converting to an abstract complex type.
2206 resolved_type = Type::lookup_complex_type("complex128");
2208 else
2210 // If we still have an abstract type here, then this is being
2211 // used in a constant expression which didn't get reduced. We
2212 // just use float64 and hope for the best.
2213 resolved_type = Type::lookup_float_type("float64");
2216 Numeric_constant nc;
2217 nc.set_float(resolved_type, this->val_);
2218 Bexpression* ret =
2219 Expression::backend_numeric_constant_expression(context, &nc);
2220 return expr_to_tree(ret);
2223 // Write a floating point number to a string dump.
2225 void
2226 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2228 mp_exp_t exponent;
2229 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2230 if (*s == '-')
2231 exp->write_c_string("-");
2232 exp->write_c_string("0.");
2233 exp->write_c_string(*s == '-' ? s + 1 : s);
2234 mpfr_free_str(s);
2235 char buf[30];
2236 snprintf(buf, sizeof buf, "E%ld", exponent);
2237 exp->write_c_string(buf);
2240 // Export a floating point number in a constant expression.
2242 void
2243 Float_expression::do_export(Export* exp) const
2245 Float_expression::export_float(exp, this->val_);
2246 // A trailing space lets us reliably identify the end of the number.
2247 exp->write_c_string(" ");
2250 // Dump a floating point number to the dump file.
2252 void
2253 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2255 Float_expression::export_float(ast_dump_context, this->val_);
2258 // Make a float expression.
2260 Expression*
2261 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2263 return new Float_expression(val, type, location);
2266 // Complex numbers.
2268 class Complex_expression : public Expression
2270 public:
2271 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2272 Location location)
2273 : Expression(EXPRESSION_COMPLEX, location),
2274 type_(type)
2276 mpfr_init_set(this->real_, *real, GMP_RNDN);
2277 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2280 // Write REAL/IMAG to string dump.
2281 static void
2282 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2284 // Write REAL/IMAG to dump context.
2285 static void
2286 dump_complex(Ast_dump_context* ast_dump_context,
2287 const mpfr_t real, const mpfr_t val);
2289 protected:
2290 bool
2291 do_is_constant() const
2292 { return true; }
2294 bool
2295 do_numeric_constant_value(Numeric_constant* nc) const
2297 nc->set_complex(this->type_, this->real_, this->imag_);
2298 return true;
2301 Type*
2302 do_type();
2304 void
2305 do_determine_type(const Type_context*);
2307 void
2308 do_check_types(Gogo*);
2310 Expression*
2311 do_copy()
2313 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2314 this->location());
2317 tree
2318 do_get_tree(Translate_context*);
2320 void
2321 do_export(Export*) const;
2323 void
2324 do_dump_expression(Ast_dump_context*) const;
2326 private:
2327 // The real part.
2328 mpfr_t real_;
2329 // The imaginary part;
2330 mpfr_t imag_;
2331 // The type if known.
2332 Type* type_;
2335 // Return the current type. If we haven't set the type yet, we return
2336 // an abstract complex type.
2338 Type*
2339 Complex_expression::do_type()
2341 if (this->type_ == NULL)
2342 this->type_ = Type::make_abstract_complex_type();
2343 return this->type_;
2346 // Set the type of the complex value. Here we may switch from an
2347 // abstract type to a real type.
2349 void
2350 Complex_expression::do_determine_type(const Type_context* context)
2352 if (this->type_ != NULL && !this->type_->is_abstract())
2354 else if (context->type != NULL
2355 && context->type->complex_type() != NULL)
2356 this->type_ = context->type;
2357 else if (!context->may_be_abstract)
2358 this->type_ = Type::lookup_complex_type("complex128");
2361 // Check the type of a complex value.
2363 void
2364 Complex_expression::do_check_types(Gogo*)
2366 Type* type = this->type_;
2367 if (type == NULL)
2368 return;
2369 Numeric_constant nc;
2370 nc.set_complex(NULL, this->real_, this->imag_);
2371 if (!nc.set_type(this->type_, true, this->location()))
2372 this->set_is_error();
2375 // Get a tree for a complex constant.
2377 tree
2378 Complex_expression::do_get_tree(Translate_context* context)
2380 Type* resolved_type;
2381 if (this->type_ != NULL && !this->type_->is_abstract())
2382 resolved_type = this->type_;
2383 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2385 // We are converting to an abstract integer type.
2386 resolved_type = Type::lookup_integer_type("int");
2388 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2390 // We are converting to an abstract float type.
2391 resolved_type = Type::lookup_float_type("float64");
2393 else
2395 // If we still have an abstract type here, this this is being
2396 // used in a constant expression which didn't get reduced. We
2397 // just use complex128 and hope for the best.
2398 resolved_type = Type::lookup_complex_type("complex128");
2401 Numeric_constant nc;
2402 nc.set_complex(resolved_type, this->real_, this->imag_);
2403 Bexpression* ret =
2404 Expression::backend_numeric_constant_expression(context, &nc);
2405 return expr_to_tree(ret);
2408 // Write REAL/IMAG to export data.
2410 void
2411 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2412 const mpfr_t imag)
2414 if (!mpfr_zero_p(real))
2416 Float_expression::export_float(exp, real);
2417 if (mpfr_sgn(imag) > 0)
2418 exp->write_c_string("+");
2420 Float_expression::export_float(exp, imag);
2421 exp->write_c_string("i");
2424 // Export a complex number in a constant expression.
2426 void
2427 Complex_expression::do_export(Export* exp) const
2429 Complex_expression::export_complex(exp, this->real_, this->imag_);
2430 // A trailing space lets us reliably identify the end of the number.
2431 exp->write_c_string(" ");
2434 // Dump a complex expression to the dump file.
2436 void
2437 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2439 Complex_expression::export_complex(ast_dump_context,
2440 this->real_,
2441 this->imag_);
2444 // Make a complex expression.
2446 Expression*
2447 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2448 Location location)
2450 return new Complex_expression(real, imag, type, location);
2453 // Find a named object in an expression.
2455 class Find_named_object : public Traverse
2457 public:
2458 Find_named_object(Named_object* no)
2459 : Traverse(traverse_expressions),
2460 no_(no), found_(false)
2463 // Whether we found the object.
2464 bool
2465 found() const
2466 { return this->found_; }
2468 protected:
2470 expression(Expression**);
2472 private:
2473 // The object we are looking for.
2474 Named_object* no_;
2475 // Whether we found it.
2476 bool found_;
2479 // A reference to a const in an expression.
2481 class Const_expression : public Expression
2483 public:
2484 Const_expression(Named_object* constant, Location location)
2485 : Expression(EXPRESSION_CONST_REFERENCE, location),
2486 constant_(constant), type_(NULL), seen_(false)
2489 Named_object*
2490 named_object()
2491 { return this->constant_; }
2493 // Check that the initializer does not refer to the constant itself.
2494 void
2495 check_for_init_loop();
2497 protected:
2499 do_traverse(Traverse*);
2501 Expression*
2502 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2504 bool
2505 do_is_constant() const
2506 { return true; }
2508 bool
2509 do_numeric_constant_value(Numeric_constant* nc) const;
2511 bool
2512 do_string_constant_value(std::string* val) const;
2514 Type*
2515 do_type();
2517 // The type of a const is set by the declaration, not the use.
2518 void
2519 do_determine_type(const Type_context*);
2521 void
2522 do_check_types(Gogo*);
2524 Expression*
2525 do_copy()
2526 { return this; }
2528 tree
2529 do_get_tree(Translate_context* context);
2531 // When exporting a reference to a const as part of a const
2532 // expression, we export the value. We ignore the fact that it has
2533 // a name.
2534 void
2535 do_export(Export* exp) const
2536 { this->constant_->const_value()->expr()->export_expression(exp); }
2538 void
2539 do_dump_expression(Ast_dump_context*) const;
2541 private:
2542 // The constant.
2543 Named_object* constant_;
2544 // The type of this reference. This is used if the constant has an
2545 // abstract type.
2546 Type* type_;
2547 // Used to prevent infinite recursion when a constant incorrectly
2548 // refers to itself.
2549 mutable bool seen_;
2552 // Traversal.
2555 Const_expression::do_traverse(Traverse* traverse)
2557 if (this->type_ != NULL)
2558 return Type::traverse(this->type_, traverse);
2559 return TRAVERSE_CONTINUE;
2562 // Lower a constant expression. This is where we convert the
2563 // predeclared constant iota into an integer value.
2565 Expression*
2566 Const_expression::do_lower(Gogo* gogo, Named_object*,
2567 Statement_inserter*, int iota_value)
2569 if (this->constant_->const_value()->expr()->classification()
2570 == EXPRESSION_IOTA)
2572 if (iota_value == -1)
2574 error_at(this->location(),
2575 "iota is only defined in const declarations");
2576 iota_value = 0;
2578 mpz_t val;
2579 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2580 Expression* ret = Expression::make_integer(&val, NULL,
2581 this->location());
2582 mpz_clear(val);
2583 return ret;
2586 // Make sure that the constant itself has been lowered.
2587 gogo->lower_constant(this->constant_);
2589 return this;
2592 // Return a numeric constant value.
2594 bool
2595 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2597 if (this->seen_)
2598 return false;
2600 Expression* e = this->constant_->const_value()->expr();
2602 this->seen_ = true;
2604 bool r = e->numeric_constant_value(nc);
2606 this->seen_ = false;
2608 Type* ctype;
2609 if (this->type_ != NULL)
2610 ctype = this->type_;
2611 else
2612 ctype = this->constant_->const_value()->type();
2613 if (r && ctype != NULL)
2615 if (!nc->set_type(ctype, false, this->location()))
2616 return false;
2619 return r;
2622 bool
2623 Const_expression::do_string_constant_value(std::string* val) const
2625 if (this->seen_)
2626 return false;
2628 Expression* e = this->constant_->const_value()->expr();
2630 this->seen_ = true;
2631 bool ok = e->string_constant_value(val);
2632 this->seen_ = false;
2634 return ok;
2637 // Return the type of the const reference.
2639 Type*
2640 Const_expression::do_type()
2642 if (this->type_ != NULL)
2643 return this->type_;
2645 Named_constant* nc = this->constant_->const_value();
2647 if (this->seen_ || nc->lowering())
2649 this->report_error(_("constant refers to itself"));
2650 this->type_ = Type::make_error_type();
2651 return this->type_;
2654 this->seen_ = true;
2656 Type* ret = nc->type();
2658 if (ret != NULL)
2660 this->seen_ = false;
2661 return ret;
2664 // During parsing, a named constant may have a NULL type, but we
2665 // must not return a NULL type here.
2666 ret = nc->expr()->type();
2668 this->seen_ = false;
2670 return ret;
2673 // Set the type of the const reference.
2675 void
2676 Const_expression::do_determine_type(const Type_context* context)
2678 Type* ctype = this->constant_->const_value()->type();
2679 Type* cetype = (ctype != NULL
2680 ? ctype
2681 : this->constant_->const_value()->expr()->type());
2682 if (ctype != NULL && !ctype->is_abstract())
2684 else if (context->type != NULL
2685 && context->type->is_numeric_type()
2686 && cetype->is_numeric_type())
2687 this->type_ = context->type;
2688 else if (context->type != NULL
2689 && context->type->is_string_type()
2690 && cetype->is_string_type())
2691 this->type_ = context->type;
2692 else if (context->type != NULL
2693 && context->type->is_boolean_type()
2694 && cetype->is_boolean_type())
2695 this->type_ = context->type;
2696 else if (!context->may_be_abstract)
2698 if (cetype->is_abstract())
2699 cetype = cetype->make_non_abstract_type();
2700 this->type_ = cetype;
2704 // Check for a loop in which the initializer of a constant refers to
2705 // the constant itself.
2707 void
2708 Const_expression::check_for_init_loop()
2710 if (this->type_ != NULL && this->type_->is_error())
2711 return;
2713 if (this->seen_)
2715 this->report_error(_("constant refers to itself"));
2716 this->type_ = Type::make_error_type();
2717 return;
2720 Expression* init = this->constant_->const_value()->expr();
2721 Find_named_object find_named_object(this->constant_);
2723 this->seen_ = true;
2724 Expression::traverse(&init, &find_named_object);
2725 this->seen_ = false;
2727 if (find_named_object.found())
2729 if (this->type_ == NULL || !this->type_->is_error())
2731 this->report_error(_("constant refers to itself"));
2732 this->type_ = Type::make_error_type();
2734 return;
2738 // Check types of a const reference.
2740 void
2741 Const_expression::do_check_types(Gogo*)
2743 if (this->type_ != NULL && this->type_->is_error())
2744 return;
2746 this->check_for_init_loop();
2748 // Check that numeric constant fits in type.
2749 if (this->type_ != NULL && this->type_->is_numeric_type())
2751 Numeric_constant nc;
2752 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2754 if (!nc.set_type(this->type_, true, this->location()))
2755 this->set_is_error();
2760 // Return a tree for the const reference.
2762 tree
2763 Const_expression::do_get_tree(Translate_context* context)
2765 if (this->type_ != NULL && this->type_->is_error())
2766 return error_mark_node;
2768 // If the type has been set for this expression, but the underlying
2769 // object is an abstract int or float, we try to get the abstract
2770 // value. Otherwise we may lose something in the conversion.
2771 if (this->type_ != NULL
2772 && this->type_->is_numeric_type()
2773 && (this->constant_->const_value()->type() == NULL
2774 || this->constant_->const_value()->type()->is_abstract()))
2776 Expression* expr = this->constant_->const_value()->expr();
2777 Numeric_constant nc;
2778 if (expr->numeric_constant_value(&nc)
2779 && nc.set_type(this->type_, false, this->location()))
2781 Expression* e = nc.expression(this->location());
2782 return e->get_tree(context);
2786 Gogo* gogo = context->gogo();
2787 Bexpression* ret =
2788 tree_to_expr(this->constant_->get_tree(gogo, context->function()));
2789 if (this->type_ != NULL)
2791 Btype* btype = this->type_->get_backend(gogo);
2792 ret = gogo->backend()->convert_expression(btype, ret, this->location());
2794 return expr_to_tree(ret);
2797 // Dump ast representation for constant expression.
2799 void
2800 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2802 ast_dump_context->ostream() << this->constant_->name();
2805 // Make a reference to a constant in an expression.
2807 Expression*
2808 Expression::make_const_reference(Named_object* constant,
2809 Location location)
2811 return new Const_expression(constant, location);
2814 // Find a named object in an expression.
2817 Find_named_object::expression(Expression** pexpr)
2819 switch ((*pexpr)->classification())
2821 case Expression::EXPRESSION_CONST_REFERENCE:
2823 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2824 if (ce->named_object() == this->no_)
2825 break;
2827 // We need to check a constant initializer explicitly, as
2828 // loops here will not be caught by the loop checking for
2829 // variable initializers.
2830 ce->check_for_init_loop();
2832 return TRAVERSE_CONTINUE;
2835 case Expression::EXPRESSION_VAR_REFERENCE:
2836 if ((*pexpr)->var_expression()->named_object() == this->no_)
2837 break;
2838 return TRAVERSE_CONTINUE;
2839 case Expression::EXPRESSION_FUNC_REFERENCE:
2840 if ((*pexpr)->func_expression()->named_object() == this->no_)
2841 break;
2842 return TRAVERSE_CONTINUE;
2843 default:
2844 return TRAVERSE_CONTINUE;
2846 this->found_ = true;
2847 return TRAVERSE_EXIT;
2850 // The nil value.
2852 class Nil_expression : public Expression
2854 public:
2855 Nil_expression(Location location)
2856 : Expression(EXPRESSION_NIL, location)
2859 static Expression*
2860 do_import(Import*);
2862 protected:
2863 bool
2864 do_is_constant() const
2865 { return true; }
2867 bool
2868 do_is_immutable() const
2869 { return true; }
2871 Type*
2872 do_type()
2873 { return Type::make_nil_type(); }
2875 void
2876 do_determine_type(const Type_context*)
2879 Expression*
2880 do_copy()
2881 { return this; }
2883 tree
2884 do_get_tree(Translate_context*)
2885 { return null_pointer_node; }
2887 void
2888 do_export(Export* exp) const
2889 { exp->write_c_string("nil"); }
2891 void
2892 do_dump_expression(Ast_dump_context* ast_dump_context) const
2893 { ast_dump_context->ostream() << "nil"; }
2896 // Import a nil expression.
2898 Expression*
2899 Nil_expression::do_import(Import* imp)
2901 imp->require_c_string("nil");
2902 return Expression::make_nil(imp->location());
2905 // Make a nil expression.
2907 Expression*
2908 Expression::make_nil(Location location)
2910 return new Nil_expression(location);
2913 // The value of the predeclared constant iota. This is little more
2914 // than a marker. This will be lowered to an integer in
2915 // Const_expression::do_lower, which is where we know the value that
2916 // it should have.
2918 class Iota_expression : public Parser_expression
2920 public:
2921 Iota_expression(Location location)
2922 : Parser_expression(EXPRESSION_IOTA, location)
2925 protected:
2926 Expression*
2927 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2928 { go_unreachable(); }
2930 // There should only ever be one of these.
2931 Expression*
2932 do_copy()
2933 { go_unreachable(); }
2935 void
2936 do_dump_expression(Ast_dump_context* ast_dump_context) const
2937 { ast_dump_context->ostream() << "iota"; }
2940 // Make an iota expression. This is only called for one case: the
2941 // value of the predeclared constant iota.
2943 Expression*
2944 Expression::make_iota()
2946 static Iota_expression iota_expression(Linemap::unknown_location());
2947 return &iota_expression;
2950 // A type conversion expression.
2952 class Type_conversion_expression : public Expression
2954 public:
2955 Type_conversion_expression(Type* type, Expression* expr,
2956 Location location)
2957 : Expression(EXPRESSION_CONVERSION, location),
2958 type_(type), expr_(expr), may_convert_function_types_(false)
2961 // Return the type to which we are converting.
2962 Type*
2963 type() const
2964 { return this->type_; }
2966 // Return the expression which we are converting.
2967 Expression*
2968 expr() const
2969 { return this->expr_; }
2971 // Permit converting from one function type to another. This is
2972 // used internally for method expressions.
2973 void
2974 set_may_convert_function_types()
2976 this->may_convert_function_types_ = true;
2979 // Import a type conversion expression.
2980 static Expression*
2981 do_import(Import*);
2983 protected:
2985 do_traverse(Traverse* traverse);
2987 Expression*
2988 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2990 Expression*
2991 do_flatten(Gogo*, Named_object*, Statement_inserter*);
2993 bool
2994 do_is_constant() const;
2996 bool
2997 do_numeric_constant_value(Numeric_constant*) const;
2999 bool
3000 do_string_constant_value(std::string*) const;
3002 Type*
3003 do_type()
3004 { return this->type_; }
3006 void
3007 do_determine_type(const Type_context*)
3009 Type_context subcontext(this->type_, false);
3010 this->expr_->determine_type(&subcontext);
3013 void
3014 do_check_types(Gogo*);
3016 Expression*
3017 do_copy()
3019 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3020 this->location());
3023 tree
3024 do_get_tree(Translate_context* context);
3026 void
3027 do_export(Export*) const;
3029 void
3030 do_dump_expression(Ast_dump_context*) const;
3032 private:
3033 // The type to convert to.
3034 Type* type_;
3035 // The expression to convert.
3036 Expression* expr_;
3037 // True if this is permitted to convert function types. This is
3038 // used internally for method expressions.
3039 bool may_convert_function_types_;
3042 // Traversal.
3045 Type_conversion_expression::do_traverse(Traverse* traverse)
3047 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3048 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3049 return TRAVERSE_EXIT;
3050 return TRAVERSE_CONTINUE;
3053 // Convert to a constant at lowering time.
3055 Expression*
3056 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3057 Statement_inserter*, int)
3059 Type* type = this->type_;
3060 Expression* val = this->expr_;
3061 Location location = this->location();
3063 if (type->is_numeric_type())
3065 Numeric_constant nc;
3066 if (val->numeric_constant_value(&nc))
3068 if (!nc.set_type(type, true, location))
3069 return Expression::make_error(location);
3070 return nc.expression(location);
3074 if (type->is_slice_type())
3076 Type* element_type = type->array_type()->element_type()->forwarded();
3077 bool is_byte = (element_type->integer_type() != NULL
3078 && element_type->integer_type()->is_byte());
3079 bool is_rune = (element_type->integer_type() != NULL
3080 && element_type->integer_type()->is_rune());
3081 if (is_byte || is_rune)
3083 std::string s;
3084 if (val->string_constant_value(&s))
3086 Expression_list* vals = new Expression_list();
3087 if (is_byte)
3089 for (std::string::const_iterator p = s.begin();
3090 p != s.end();
3091 p++)
3093 mpz_t val;
3094 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3095 Expression* v = Expression::make_integer(&val,
3096 element_type,
3097 location);
3098 vals->push_back(v);
3099 mpz_clear(val);
3102 else
3104 const char *p = s.data();
3105 const char *pend = s.data() + s.length();
3106 while (p < pend)
3108 unsigned int c;
3109 int adv = Lex::fetch_char(p, &c);
3110 if (adv == 0)
3112 warning_at(this->location(), 0,
3113 "invalid UTF-8 encoding");
3114 adv = 1;
3116 p += adv;
3117 mpz_t val;
3118 mpz_init_set_ui(val, c);
3119 Expression* v = Expression::make_integer(&val,
3120 element_type,
3121 location);
3122 vals->push_back(v);
3123 mpz_clear(val);
3127 return Expression::make_slice_composite_literal(type, vals,
3128 location);
3133 return this;
3136 // Flatten a type conversion by using a temporary variable for the slice
3137 // in slice to string conversions.
3139 Expression*
3140 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3141 Statement_inserter* inserter)
3143 if (((this->type()->is_string_type()
3144 && this->expr_->type()->is_slice_type())
3145 || (this->type()->interface_type() != NULL
3146 && this->expr_->type()->interface_type() != NULL))
3147 && !this->expr_->is_variable())
3149 Temporary_statement* temp =
3150 Statement::make_temporary(NULL, this->expr_, this->location());
3151 inserter->insert(temp);
3152 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3154 return this;
3157 // Return whether a type conversion is a constant.
3159 bool
3160 Type_conversion_expression::do_is_constant() const
3162 if (!this->expr_->is_constant())
3163 return false;
3165 // A conversion to a type that may not be used as a constant is not
3166 // a constant. For example, []byte(nil).
3167 Type* type = this->type_;
3168 if (type->integer_type() == NULL
3169 && type->float_type() == NULL
3170 && type->complex_type() == NULL
3171 && !type->is_boolean_type()
3172 && !type->is_string_type())
3173 return false;
3175 return true;
3178 // Return the constant numeric value if there is one.
3180 bool
3181 Type_conversion_expression::do_numeric_constant_value(
3182 Numeric_constant* nc) const
3184 if (!this->type_->is_numeric_type())
3185 return false;
3186 if (!this->expr_->numeric_constant_value(nc))
3187 return false;
3188 return nc->set_type(this->type_, false, this->location());
3191 // Return the constant string value if there is one.
3193 bool
3194 Type_conversion_expression::do_string_constant_value(std::string* val) const
3196 if (this->type_->is_string_type()
3197 && this->expr_->type()->integer_type() != NULL)
3199 Numeric_constant nc;
3200 if (this->expr_->numeric_constant_value(&nc))
3202 unsigned long ival;
3203 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3205 val->clear();
3206 Lex::append_char(ival, true, val, this->location());
3207 return true;
3212 // FIXME: Could handle conversion from const []int here.
3214 return false;
3217 // Check that types are convertible.
3219 void
3220 Type_conversion_expression::do_check_types(Gogo*)
3222 Type* type = this->type_;
3223 Type* expr_type = this->expr_->type();
3224 std::string reason;
3226 if (type->is_error() || expr_type->is_error())
3228 this->set_is_error();
3229 return;
3232 if (this->may_convert_function_types_
3233 && type->function_type() != NULL
3234 && expr_type->function_type() != NULL)
3235 return;
3237 if (Type::are_convertible(type, expr_type, &reason))
3238 return;
3240 error_at(this->location(), "%s", reason.c_str());
3241 this->set_is_error();
3244 // Get a tree for a type conversion.
3246 tree
3247 Type_conversion_expression::do_get_tree(Translate_context* context)
3249 Type* type = this->type_;
3250 Type* expr_type = this->expr_->type();
3252 Gogo* gogo = context->gogo();
3253 Btype* btype = type->get_backend(gogo);
3254 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3255 Location loc = this->location();
3257 if (Type::are_identical(type, expr_type, false, NULL))
3259 Bexpression* bconvert =
3260 gogo->backend()->convert_expression(btype, bexpr, loc);
3261 return expr_to_tree(bconvert);
3263 else if (type->interface_type() != NULL
3264 || expr_type->interface_type() != NULL)
3266 Expression* conversion =
3267 Expression::convert_for_assignment(gogo, type, this->expr_,
3268 this->location());
3269 return conversion->get_tree(context);
3271 else if (type->is_string_type()
3272 && expr_type->integer_type() != NULL)
3274 mpz_t intval;
3275 Numeric_constant nc;
3276 if (this->expr_->numeric_constant_value(&nc)
3277 && nc.to_int(&intval)
3278 && mpz_fits_ushort_p(intval))
3280 std::string s;
3281 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3282 mpz_clear(intval);
3283 Expression* se = Expression::make_string(s, loc);
3284 return se->get_tree(context);
3287 Expression* i2s_expr =
3288 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3289 return Expression::make_cast(type, i2s_expr, loc)->get_tree(context);
3291 else if (type->is_string_type() && expr_type->is_slice_type())
3293 Array_type* a = expr_type->array_type();
3294 Type* e = a->element_type()->forwarded();
3295 go_assert(e->integer_type() != NULL);
3296 go_assert(this->expr_->is_variable());
3298 Runtime::Function code;
3299 if (e->integer_type()->is_byte())
3300 code = Runtime::BYTE_ARRAY_TO_STRING;
3301 else
3303 go_assert(e->integer_type()->is_rune());
3304 code = Runtime::INT_ARRAY_TO_STRING;
3306 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3307 Expression* len = a->get_length(gogo, this->expr_);
3308 return Runtime::make_call(code, loc, 2, valptr, len)->get_tree(context);
3310 else if (type->is_slice_type() && expr_type->is_string_type())
3312 Type* e = type->array_type()->element_type()->forwarded();
3313 go_assert(e->integer_type() != NULL);
3315 Runtime::Function code;
3316 if (e->integer_type()->is_byte())
3317 code = Runtime::STRING_TO_BYTE_ARRAY;
3318 else
3320 go_assert(e->integer_type()->is_rune());
3321 code = Runtime::STRING_TO_INT_ARRAY;
3323 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3324 return Expression::make_unsafe_cast(type, s2a, loc)->get_tree(context);
3326 else if (type->is_numeric_type())
3328 go_assert(Type::are_convertible(type, expr_type, NULL));
3329 Bexpression* bconvert =
3330 gogo->backend()->convert_expression(btype, bexpr, loc);
3331 return expr_to_tree(bconvert);
3333 else if ((type->is_unsafe_pointer_type()
3334 && (expr_type->points_to() != NULL
3335 || expr_type->integer_type()))
3336 || (expr_type->is_unsafe_pointer_type()
3337 && type->points_to() != NULL)
3338 || (this->may_convert_function_types_
3339 && type->function_type() != NULL
3340 && expr_type->function_type() != NULL))
3342 Bexpression* bconvert =
3343 gogo->backend()->convert_expression(btype, bexpr, loc);
3344 return expr_to_tree(bconvert);
3346 else
3348 Expression* conversion =
3349 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3350 return conversion->get_tree(context);
3354 // Output a type conversion in a constant expression.
3356 void
3357 Type_conversion_expression::do_export(Export* exp) const
3359 exp->write_c_string("convert(");
3360 exp->write_type(this->type_);
3361 exp->write_c_string(", ");
3362 this->expr_->export_expression(exp);
3363 exp->write_c_string(")");
3366 // Import a type conversion or a struct construction.
3368 Expression*
3369 Type_conversion_expression::do_import(Import* imp)
3371 imp->require_c_string("convert(");
3372 Type* type = imp->read_type();
3373 imp->require_c_string(", ");
3374 Expression* val = Expression::import_expression(imp);
3375 imp->require_c_string(")");
3376 return Expression::make_cast(type, val, imp->location());
3379 // Dump ast representation for a type conversion expression.
3381 void
3382 Type_conversion_expression::do_dump_expression(
3383 Ast_dump_context* ast_dump_context) const
3385 ast_dump_context->dump_type(this->type_);
3386 ast_dump_context->ostream() << "(";
3387 ast_dump_context->dump_expression(this->expr_);
3388 ast_dump_context->ostream() << ") ";
3391 // Make a type cast expression.
3393 Expression*
3394 Expression::make_cast(Type* type, Expression* val, Location location)
3396 if (type->is_error_type() || val->is_error_expression())
3397 return Expression::make_error(location);
3398 return new Type_conversion_expression(type, val, location);
3401 // An unsafe type conversion, used to pass values to builtin functions.
3403 class Unsafe_type_conversion_expression : public Expression
3405 public:
3406 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3407 Location location)
3408 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3409 type_(type), expr_(expr)
3412 protected:
3414 do_traverse(Traverse* traverse);
3416 Type*
3417 do_type()
3418 { return this->type_; }
3420 void
3421 do_determine_type(const Type_context*)
3422 { this->expr_->determine_type_no_context(); }
3424 Expression*
3425 do_copy()
3427 return new Unsafe_type_conversion_expression(this->type_,
3428 this->expr_->copy(),
3429 this->location());
3432 tree
3433 do_get_tree(Translate_context*);
3435 void
3436 do_dump_expression(Ast_dump_context*) const;
3438 private:
3439 // The type to convert to.
3440 Type* type_;
3441 // The expression to convert.
3442 Expression* expr_;
3445 // Traversal.
3448 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3450 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3451 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3452 return TRAVERSE_EXIT;
3453 return TRAVERSE_CONTINUE;
3456 // Convert to backend representation.
3458 tree
3459 Unsafe_type_conversion_expression::do_get_tree(Translate_context* context)
3461 // We are only called for a limited number of cases.
3463 Type* t = this->type_;
3464 Type* et = this->expr_->type();
3465 if (t->array_type() != NULL)
3466 go_assert(et->array_type() != NULL
3467 && t->is_slice_type() == et->is_slice_type());
3468 else if (t->struct_type() != NULL)
3470 if (t->named_type() != NULL
3471 && et->named_type() != NULL
3472 && !Type::are_convertible(t, et, NULL))
3474 go_assert(saw_errors());
3475 return error_mark_node;
3478 go_assert(et->struct_type() != NULL
3479 && Type::are_convertible(t, et, NULL));
3481 else if (t->map_type() != NULL)
3482 go_assert(et->map_type() != NULL);
3483 else if (t->channel_type() != NULL)
3484 go_assert(et->channel_type() != NULL);
3485 else if (t->points_to() != NULL)
3486 go_assert(et->points_to() != NULL
3487 || et->channel_type() != NULL
3488 || et->map_type() != NULL
3489 || et->function_type() != NULL
3490 || et->is_nil_type());
3491 else if (et->is_unsafe_pointer_type())
3492 go_assert(t->points_to() != NULL);
3493 else if (t->interface_type() != NULL)
3495 bool empty_iface = t->interface_type()->is_empty();
3496 go_assert(et->interface_type() != NULL
3497 && et->interface_type()->is_empty() == empty_iface);
3499 else if (t->integer_type() != NULL)
3500 go_assert(et->is_boolean_type()
3501 || et->integer_type() != NULL
3502 || et->function_type() != NULL
3503 || et->points_to() != NULL
3504 || et->map_type() != NULL
3505 || et->channel_type() != NULL);
3506 else
3507 go_unreachable();
3509 Gogo* gogo = context->gogo();
3510 Btype* btype = t->get_backend(gogo);
3511 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
3512 Location loc = this->location();
3513 Bexpression* ret =
3514 gogo->backend()->convert_expression(btype, bexpr, loc);
3515 return expr_to_tree(ret);
3518 // Dump ast representation for an unsafe type conversion expression.
3520 void
3521 Unsafe_type_conversion_expression::do_dump_expression(
3522 Ast_dump_context* ast_dump_context) const
3524 ast_dump_context->dump_type(this->type_);
3525 ast_dump_context->ostream() << "(";
3526 ast_dump_context->dump_expression(this->expr_);
3527 ast_dump_context->ostream() << ") ";
3530 // Make an unsafe type conversion expression.
3532 Expression*
3533 Expression::make_unsafe_cast(Type* type, Expression* expr,
3534 Location location)
3536 return new Unsafe_type_conversion_expression(type, expr, location);
3539 // Unary expressions.
3541 class Unary_expression : public Expression
3543 public:
3544 Unary_expression(Operator op, Expression* expr, Location location)
3545 : Expression(EXPRESSION_UNARY, location),
3546 op_(op), escapes_(true), create_temp_(false), expr_(expr),
3547 issue_nil_check_(false)
3550 // Return the operator.
3551 Operator
3552 op() const
3553 { return this->op_; }
3555 // Return the operand.
3556 Expression*
3557 operand() const
3558 { return this->expr_; }
3560 // Record that an address expression does not escape.
3561 void
3562 set_does_not_escape()
3564 go_assert(this->op_ == OPERATOR_AND);
3565 this->escapes_ = false;
3568 // Record that this is an address expression which should create a
3569 // temporary variable if necessary. This is used for method calls.
3570 void
3571 set_create_temp()
3573 go_assert(this->op_ == OPERATOR_AND);
3574 this->create_temp_ = true;
3577 // Apply unary opcode OP to UNC, setting NC. Return true if this
3578 // could be done, false if not. Issue errors for overflow.
3579 static bool
3580 eval_constant(Operator op, const Numeric_constant* unc,
3581 Location, Numeric_constant* nc);
3583 static Expression*
3584 do_import(Import*);
3586 protected:
3588 do_traverse(Traverse* traverse)
3589 { return Expression::traverse(&this->expr_, traverse); }
3591 Expression*
3592 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3594 Expression*
3595 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3597 bool
3598 do_is_constant() const;
3600 bool
3601 do_is_immutable() const
3602 { return this->expr_->is_immutable(); }
3604 bool
3605 do_numeric_constant_value(Numeric_constant*) const;
3607 Type*
3608 do_type();
3610 void
3611 do_determine_type(const Type_context*);
3613 void
3614 do_check_types(Gogo*);
3616 Expression*
3617 do_copy()
3619 return Expression::make_unary(this->op_, this->expr_->copy(),
3620 this->location());
3623 bool
3624 do_must_eval_subexpressions_in_order(int*) const
3625 { return this->op_ == OPERATOR_MULT; }
3627 bool
3628 do_is_addressable() const
3629 { return this->op_ == OPERATOR_MULT; }
3631 tree
3632 do_get_tree(Translate_context*);
3634 void
3635 do_export(Export*) const;
3637 void
3638 do_dump_expression(Ast_dump_context*) const;
3640 void
3641 do_issue_nil_check()
3642 { this->issue_nil_check_ = (this->op_ == OPERATOR_MULT); }
3644 private:
3645 // The unary operator to apply.
3646 Operator op_;
3647 // Normally true. False if this is an address expression which does
3648 // not escape the current function.
3649 bool escapes_;
3650 // True if this is an address expression which should create a
3651 // temporary variable if necessary.
3652 bool create_temp_;
3653 // The operand.
3654 Expression* expr_;
3655 // Whether or not to issue a nil check for this expression if its address
3656 // is being taken.
3657 bool issue_nil_check_;
3660 // If we are taking the address of a composite literal, and the
3661 // contents are not constant, then we want to make a heap expression
3662 // instead.
3664 Expression*
3665 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3667 Location loc = this->location();
3668 Operator op = this->op_;
3669 Expression* expr = this->expr_;
3671 if (op == OPERATOR_MULT && expr->is_type_expression())
3672 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3674 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3675 // moving x to the heap. FIXME: Is it worth doing a real escape
3676 // analysis here? This case is found in math/unsafe.go and is
3677 // therefore worth special casing.
3678 if (op == OPERATOR_MULT)
3680 Expression* e = expr;
3681 while (e->classification() == EXPRESSION_CONVERSION)
3683 Type_conversion_expression* te
3684 = static_cast<Type_conversion_expression*>(e);
3685 e = te->expr();
3688 if (e->classification() == EXPRESSION_UNARY)
3690 Unary_expression* ue = static_cast<Unary_expression*>(e);
3691 if (ue->op_ == OPERATOR_AND)
3693 if (e == expr)
3695 // *&x == x.
3696 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3698 error_at(ue->location(),
3699 "invalid operand for unary %<&%>");
3700 this->set_is_error();
3702 return ue->expr_;
3704 ue->set_does_not_escape();
3709 // Catching an invalid indirection of unsafe.Pointer here avoid
3710 // having to deal with TYPE_VOID in other places.
3711 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3713 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3714 return Expression::make_error(this->location());
3717 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3719 Numeric_constant nc;
3720 if (expr->numeric_constant_value(&nc))
3722 Numeric_constant result;
3723 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3724 return result.expression(loc);
3728 return this;
3731 // Flatten expression if a nil check must be performed and create temporary
3732 // variables if necessary.
3734 Expression*
3735 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3736 Statement_inserter* inserter)
3738 if (this->is_error_expression() || this->expr_->is_error_expression())
3739 return Expression::make_error(this->location());
3741 Location location = this->location();
3742 if (this->op_ == OPERATOR_MULT
3743 && !this->expr_->is_variable())
3745 go_assert(this->expr_->type()->points_to() != NULL);
3746 Type* ptype = this->expr_->type()->points_to();
3747 if (!ptype->is_void_type())
3749 Btype* pbtype = ptype->get_backend(gogo);
3750 size_t s = gogo->backend()->type_size(pbtype);
3751 if (s >= 4096 || this->issue_nil_check_)
3753 Temporary_statement* temp =
3754 Statement::make_temporary(NULL, this->expr_, location);
3755 inserter->insert(temp);
3756 this->expr_ =
3757 Expression::make_temporary_reference(temp, location);
3762 if (this->create_temp_ && !this->expr_->is_variable())
3764 Temporary_statement* temp =
3765 Statement::make_temporary(NULL, this->expr_, location);
3766 inserter->insert(temp);
3767 this->expr_ = Expression::make_temporary_reference(temp, location);
3770 return this;
3773 // Return whether a unary expression is a constant.
3775 bool
3776 Unary_expression::do_is_constant() const
3778 if (this->op_ == OPERATOR_MULT)
3780 // Indirecting through a pointer is only constant if the object
3781 // to which the expression points is constant, but we currently
3782 // have no way to determine that.
3783 return false;
3785 else if (this->op_ == OPERATOR_AND)
3787 // Taking the address of a variable is constant if it is a
3788 // global variable, not constant otherwise. In other cases taking the
3789 // address is probably not a constant.
3790 Var_expression* ve = this->expr_->var_expression();
3791 if (ve != NULL)
3793 Named_object* no = ve->named_object();
3794 return no->is_variable() && no->var_value()->is_global();
3796 return false;
3798 else
3799 return this->expr_->is_constant();
3802 // Apply unary opcode OP to UNC, setting NC. Return true if this
3803 // could be done, false if not. Issue errors for overflow.
3805 bool
3806 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3807 Location location, Numeric_constant* nc)
3809 switch (op)
3811 case OPERATOR_PLUS:
3812 *nc = *unc;
3813 return true;
3815 case OPERATOR_MINUS:
3816 if (unc->is_int() || unc->is_rune())
3817 break;
3818 else if (unc->is_float())
3820 mpfr_t uval;
3821 unc->get_float(&uval);
3822 mpfr_t val;
3823 mpfr_init(val);
3824 mpfr_neg(val, uval, GMP_RNDN);
3825 nc->set_float(unc->type(), val);
3826 mpfr_clear(uval);
3827 mpfr_clear(val);
3828 return true;
3830 else if (unc->is_complex())
3832 mpfr_t ureal, uimag;
3833 unc->get_complex(&ureal, &uimag);
3834 mpfr_t real, imag;
3835 mpfr_init(real);
3836 mpfr_init(imag);
3837 mpfr_neg(real, ureal, GMP_RNDN);
3838 mpfr_neg(imag, uimag, GMP_RNDN);
3839 nc->set_complex(unc->type(), real, imag);
3840 mpfr_clear(ureal);
3841 mpfr_clear(uimag);
3842 mpfr_clear(real);
3843 mpfr_clear(imag);
3844 return true;
3846 else
3847 go_unreachable();
3849 case OPERATOR_XOR:
3850 break;
3852 case OPERATOR_NOT:
3853 case OPERATOR_AND:
3854 case OPERATOR_MULT:
3855 return false;
3857 default:
3858 go_unreachable();
3861 if (!unc->is_int() && !unc->is_rune())
3862 return false;
3864 mpz_t uval;
3865 if (unc->is_rune())
3866 unc->get_rune(&uval);
3867 else
3868 unc->get_int(&uval);
3869 mpz_t val;
3870 mpz_init(val);
3872 switch (op)
3874 case OPERATOR_MINUS:
3875 mpz_neg(val, uval);
3876 break;
3878 case OPERATOR_NOT:
3879 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3880 break;
3882 case OPERATOR_XOR:
3884 Type* utype = unc->type();
3885 if (utype->integer_type() == NULL
3886 || utype->integer_type()->is_abstract())
3887 mpz_com(val, uval);
3888 else
3890 // The number of HOST_WIDE_INTs that it takes to represent
3891 // UVAL.
3892 size_t count = ((mpz_sizeinbase(uval, 2)
3893 + HOST_BITS_PER_WIDE_INT
3894 - 1)
3895 / HOST_BITS_PER_WIDE_INT);
3897 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3898 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3900 size_t obits = utype->integer_type()->bits();
3902 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3904 mpz_t adj;
3905 mpz_init_set_ui(adj, 1);
3906 mpz_mul_2exp(adj, adj, obits);
3907 mpz_add(uval, uval, adj);
3908 mpz_clear(adj);
3911 size_t ecount;
3912 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3913 go_assert(ecount <= count);
3915 // Trim down to the number of words required by the type.
3916 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3917 / HOST_BITS_PER_WIDE_INT);
3918 go_assert(ocount <= count);
3920 for (size_t i = 0; i < ocount; ++i)
3921 phwi[i] = ~phwi[i];
3923 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3924 if (clearbits != 0)
3925 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3926 >> clearbits);
3928 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3930 if (!utype->integer_type()->is_unsigned()
3931 && mpz_tstbit(val, obits - 1))
3933 mpz_t adj;
3934 mpz_init_set_ui(adj, 1);
3935 mpz_mul_2exp(adj, adj, obits);
3936 mpz_sub(val, val, adj);
3937 mpz_clear(adj);
3940 delete[] phwi;
3943 break;
3945 default:
3946 go_unreachable();
3949 if (unc->is_rune())
3950 nc->set_rune(NULL, val);
3951 else
3952 nc->set_int(NULL, val);
3954 mpz_clear(uval);
3955 mpz_clear(val);
3957 return nc->set_type(unc->type(), true, location);
3960 // Return the integral constant value of a unary expression, if it has one.
3962 bool
3963 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3965 Numeric_constant unc;
3966 if (!this->expr_->numeric_constant_value(&unc))
3967 return false;
3968 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3969 nc);
3972 // Return the type of a unary expression.
3974 Type*
3975 Unary_expression::do_type()
3977 switch (this->op_)
3979 case OPERATOR_PLUS:
3980 case OPERATOR_MINUS:
3981 case OPERATOR_NOT:
3982 case OPERATOR_XOR:
3983 return this->expr_->type();
3985 case OPERATOR_AND:
3986 return Type::make_pointer_type(this->expr_->type());
3988 case OPERATOR_MULT:
3990 Type* subtype = this->expr_->type();
3991 Type* points_to = subtype->points_to();
3992 if (points_to == NULL)
3993 return Type::make_error_type();
3994 return points_to;
3997 default:
3998 go_unreachable();
4002 // Determine abstract types for a unary expression.
4004 void
4005 Unary_expression::do_determine_type(const Type_context* context)
4007 switch (this->op_)
4009 case OPERATOR_PLUS:
4010 case OPERATOR_MINUS:
4011 case OPERATOR_NOT:
4012 case OPERATOR_XOR:
4013 this->expr_->determine_type(context);
4014 break;
4016 case OPERATOR_AND:
4017 // Taking the address of something.
4019 Type* subtype = (context->type == NULL
4020 ? NULL
4021 : context->type->points_to());
4022 Type_context subcontext(subtype, false);
4023 this->expr_->determine_type(&subcontext);
4025 break;
4027 case OPERATOR_MULT:
4028 // Indirecting through a pointer.
4030 Type* subtype = (context->type == NULL
4031 ? NULL
4032 : Type::make_pointer_type(context->type));
4033 Type_context subcontext(subtype, false);
4034 this->expr_->determine_type(&subcontext);
4036 break;
4038 default:
4039 go_unreachable();
4043 // Check types for a unary expression.
4045 void
4046 Unary_expression::do_check_types(Gogo*)
4048 Type* type = this->expr_->type();
4049 if (type->is_error())
4051 this->set_is_error();
4052 return;
4055 switch (this->op_)
4057 case OPERATOR_PLUS:
4058 case OPERATOR_MINUS:
4059 if (type->integer_type() == NULL
4060 && type->float_type() == NULL
4061 && type->complex_type() == NULL)
4062 this->report_error(_("expected numeric type"));
4063 break;
4065 case OPERATOR_NOT:
4066 if (!type->is_boolean_type())
4067 this->report_error(_("expected boolean type"));
4068 break;
4070 case OPERATOR_XOR:
4071 if (type->integer_type() == NULL
4072 && !type->is_boolean_type())
4073 this->report_error(_("expected integer or boolean type"));
4074 break;
4076 case OPERATOR_AND:
4077 if (!this->expr_->is_addressable())
4079 if (!this->create_temp_)
4081 error_at(this->location(), "invalid operand for unary %<&%>");
4082 this->set_is_error();
4085 else
4087 this->expr_->address_taken(this->escapes_);
4088 this->expr_->issue_nil_check();
4090 break;
4092 case OPERATOR_MULT:
4093 // Indirecting through a pointer.
4094 if (type->points_to() == NULL)
4095 this->report_error(_("expected pointer"));
4096 break;
4098 default:
4099 go_unreachable();
4103 // Get a tree for a unary expression.
4105 tree
4106 Unary_expression::do_get_tree(Translate_context* context)
4108 Gogo* gogo = context->gogo();
4109 Location loc = this->location();
4111 // Taking the address of a set-and-use-temporary expression requires
4112 // setting the temporary and then taking the address.
4113 if (this->op_ == OPERATOR_AND)
4115 Set_and_use_temporary_expression* sut =
4116 this->expr_->set_and_use_temporary_expression();
4117 if (sut != NULL)
4119 Temporary_statement* temp = sut->temporary();
4120 Bvariable* bvar = temp->get_backend_variable(context);
4121 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4123 Expression* val = sut->expression();
4124 Bexpression* bval = tree_to_expr(val->get_tree(context));
4126 Bstatement* bassign =
4127 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4128 Bexpression* bvar_addr =
4129 gogo->backend()->address_expression(bvar_expr, loc);
4130 Bexpression* ret =
4131 gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4132 return expr_to_tree(ret);
4136 Bexpression* ret;
4137 tree expr = this->expr_->get_tree(context);
4138 Bexpression* bexpr = tree_to_expr(expr);
4139 Btype* btype = this->expr_->type()->get_backend(gogo);
4140 switch (this->op_)
4142 case OPERATOR_PLUS:
4143 ret = bexpr;
4144 break;
4146 case OPERATOR_MINUS:
4147 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4148 ret = gogo->backend()->convert_expression(btype, ret, loc);
4149 break;
4151 case OPERATOR_NOT:
4152 case OPERATOR_XOR:
4153 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4154 break;
4156 case OPERATOR_AND:
4157 if (!this->create_temp_)
4159 // We should not see a non-constant constructor here; cases
4160 // where we would see one should have been moved onto the
4161 // heap at parse time. Taking the address of a nonconstant
4162 // constructor will not do what the programmer expects.
4164 go_assert(!this->expr_->is_composite_literal()
4165 || this->expr_->is_immutable());
4166 if (this->expr_->classification() == EXPRESSION_UNARY)
4168 Unary_expression* ue =
4169 static_cast<Unary_expression*>(this->expr_);
4170 go_assert(ue->op() != OPERATOR_AND);
4174 // Build a decl for a constant constructor.
4175 if ((this->expr_->is_composite_literal()
4176 || this->expr_->string_expression() != NULL)
4177 && this->expr_->is_immutable())
4179 static unsigned int counter;
4180 char buf[100];
4181 snprintf(buf, sizeof buf, "C%u", counter);
4182 ++counter;
4184 Bvariable* decl =
4185 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4186 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4187 btype, loc, bexpr);
4188 bexpr = gogo->backend()->var_expression(decl, loc);
4191 go_assert(!this->create_temp_ || this->expr_->is_variable());
4192 ret = gogo->backend()->address_expression(bexpr, loc);
4193 break;
4195 case OPERATOR_MULT:
4197 go_assert(this->expr_->type()->points_to() != NULL);
4199 // If we are dereferencing the pointer to a large struct, we
4200 // need to check for nil. We don't bother to check for small
4201 // structs because we expect the system to crash on a nil
4202 // pointer dereference. However, if we know the address of this
4203 // expression is being taken, we must always check for nil.
4205 Type* ptype = this->expr_->type()->points_to();
4206 Btype* pbtype = ptype->get_backend(gogo);
4207 if (!ptype->is_void_type())
4209 size_t s = gogo->backend()->type_size(pbtype);
4210 if (s >= 4096 || this->issue_nil_check_)
4212 go_assert(this->expr_->is_variable());
4214 Expression* nil_expr = Expression::make_nil(loc);
4215 Bexpression* nil = tree_to_expr(nil_expr->get_tree(context));
4216 Bexpression* compare =
4217 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4218 nil, loc);
4220 Expression* crash_expr =
4221 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
4222 Bexpression* crash =
4223 tree_to_expr(crash_expr->get_tree(context));
4224 bexpr = gogo->backend()->conditional_expression(btype, compare,
4225 crash, bexpr,
4226 loc);
4231 // If the type of EXPR is a recursive pointer type, then we
4232 // need to insert a cast before indirecting.
4233 tree expr = expr_to_tree(bexpr);
4234 tree target_type_tree = TREE_TYPE(TREE_TYPE(expr));
4235 if (VOID_TYPE_P(target_type_tree))
4237 tree ind = type_to_tree(pbtype);
4238 expr = fold_convert_loc(loc.gcc_location(),
4239 build_pointer_type(ind), expr);
4240 bexpr = tree_to_expr(expr);
4243 ret = gogo->backend()->indirect_expression(bexpr, false, loc);
4245 break;
4247 default:
4248 go_unreachable();
4251 return expr_to_tree(ret);
4254 // Export a unary expression.
4256 void
4257 Unary_expression::do_export(Export* exp) const
4259 switch (this->op_)
4261 case OPERATOR_PLUS:
4262 exp->write_c_string("+ ");
4263 break;
4264 case OPERATOR_MINUS:
4265 exp->write_c_string("- ");
4266 break;
4267 case OPERATOR_NOT:
4268 exp->write_c_string("! ");
4269 break;
4270 case OPERATOR_XOR:
4271 exp->write_c_string("^ ");
4272 break;
4273 case OPERATOR_AND:
4274 case OPERATOR_MULT:
4275 default:
4276 go_unreachable();
4278 this->expr_->export_expression(exp);
4281 // Import a unary expression.
4283 Expression*
4284 Unary_expression::do_import(Import* imp)
4286 Operator op;
4287 switch (imp->get_char())
4289 case '+':
4290 op = OPERATOR_PLUS;
4291 break;
4292 case '-':
4293 op = OPERATOR_MINUS;
4294 break;
4295 case '!':
4296 op = OPERATOR_NOT;
4297 break;
4298 case '^':
4299 op = OPERATOR_XOR;
4300 break;
4301 default:
4302 go_unreachable();
4304 imp->require_c_string(" ");
4305 Expression* expr = Expression::import_expression(imp);
4306 return Expression::make_unary(op, expr, imp->location());
4309 // Dump ast representation of an unary expression.
4311 void
4312 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4314 ast_dump_context->dump_operator(this->op_);
4315 ast_dump_context->ostream() << "(";
4316 ast_dump_context->dump_expression(this->expr_);
4317 ast_dump_context->ostream() << ") ";
4320 // Make a unary expression.
4322 Expression*
4323 Expression::make_unary(Operator op, Expression* expr, Location location)
4325 return new Unary_expression(op, expr, location);
4328 // If this is an indirection through a pointer, return the expression
4329 // being pointed through. Otherwise return this.
4331 Expression*
4332 Expression::deref()
4334 if (this->classification_ == EXPRESSION_UNARY)
4336 Unary_expression* ue = static_cast<Unary_expression*>(this);
4337 if (ue->op() == OPERATOR_MULT)
4338 return ue->operand();
4340 return this;
4343 // Class Binary_expression.
4345 // Traversal.
4348 Binary_expression::do_traverse(Traverse* traverse)
4350 int t = Expression::traverse(&this->left_, traverse);
4351 if (t == TRAVERSE_EXIT)
4352 return TRAVERSE_EXIT;
4353 return Expression::traverse(&this->right_, traverse);
4356 // Return the type to use for a binary operation on operands of
4357 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4358 // such may be NULL or abstract.
4360 bool
4361 Binary_expression::operation_type(Operator op, Type* left_type,
4362 Type* right_type, Type** result_type)
4364 if (left_type != right_type
4365 && !left_type->is_abstract()
4366 && !right_type->is_abstract()
4367 && left_type->base() != right_type->base()
4368 && op != OPERATOR_LSHIFT
4369 && op != OPERATOR_RSHIFT)
4371 // May be a type error--let it be diagnosed elsewhere.
4372 return false;
4375 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4377 if (left_type->integer_type() != NULL)
4378 *result_type = left_type;
4379 else
4380 *result_type = Type::make_abstract_integer_type();
4382 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4383 *result_type = left_type;
4384 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4385 *result_type = right_type;
4386 else if (!left_type->is_abstract())
4387 *result_type = left_type;
4388 else if (!right_type->is_abstract())
4389 *result_type = right_type;
4390 else if (left_type->complex_type() != NULL)
4391 *result_type = left_type;
4392 else if (right_type->complex_type() != NULL)
4393 *result_type = right_type;
4394 else if (left_type->float_type() != NULL)
4395 *result_type = left_type;
4396 else if (right_type->float_type() != NULL)
4397 *result_type = right_type;
4398 else if (left_type->integer_type() != NULL
4399 && left_type->integer_type()->is_rune())
4400 *result_type = left_type;
4401 else if (right_type->integer_type() != NULL
4402 && right_type->integer_type()->is_rune())
4403 *result_type = right_type;
4404 else
4405 *result_type = left_type;
4407 return true;
4410 // Convert an integer comparison code and an operator to a boolean
4411 // value.
4413 bool
4414 Binary_expression::cmp_to_bool(Operator op, int cmp)
4416 switch (op)
4418 case OPERATOR_EQEQ:
4419 return cmp == 0;
4420 break;
4421 case OPERATOR_NOTEQ:
4422 return cmp != 0;
4423 break;
4424 case OPERATOR_LT:
4425 return cmp < 0;
4426 break;
4427 case OPERATOR_LE:
4428 return cmp <= 0;
4429 case OPERATOR_GT:
4430 return cmp > 0;
4431 case OPERATOR_GE:
4432 return cmp >= 0;
4433 default:
4434 go_unreachable();
4438 // Compare constants according to OP.
4440 bool
4441 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4442 Numeric_constant* right_nc,
4443 Location location, bool* result)
4445 Type* left_type = left_nc->type();
4446 Type* right_type = right_nc->type();
4448 Type* type;
4449 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4450 return false;
4452 // When comparing an untyped operand to a typed operand, we are
4453 // effectively coercing the untyped operand to the other operand's
4454 // type, so make sure that is valid.
4455 if (!left_nc->set_type(type, true, location)
4456 || !right_nc->set_type(type, true, location))
4457 return false;
4459 bool ret;
4460 int cmp;
4461 if (type->complex_type() != NULL)
4463 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4464 return false;
4465 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4467 else if (type->float_type() != NULL)
4468 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4469 else
4470 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4472 if (ret)
4473 *result = Binary_expression::cmp_to_bool(op, cmp);
4475 return ret;
4478 // Compare integer constants.
4480 bool
4481 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4482 const Numeric_constant* right_nc,
4483 int* cmp)
4485 mpz_t left_val;
4486 if (!left_nc->to_int(&left_val))
4487 return false;
4488 mpz_t right_val;
4489 if (!right_nc->to_int(&right_val))
4491 mpz_clear(left_val);
4492 return false;
4495 *cmp = mpz_cmp(left_val, right_val);
4497 mpz_clear(left_val);
4498 mpz_clear(right_val);
4500 return true;
4503 // Compare floating point constants.
4505 bool
4506 Binary_expression::compare_float(const Numeric_constant* left_nc,
4507 const Numeric_constant* right_nc,
4508 int* cmp)
4510 mpfr_t left_val;
4511 if (!left_nc->to_float(&left_val))
4512 return false;
4513 mpfr_t right_val;
4514 if (!right_nc->to_float(&right_val))
4516 mpfr_clear(left_val);
4517 return false;
4520 // We already coerced both operands to the same type. If that type
4521 // is not an abstract type, we need to round the values accordingly.
4522 Type* type = left_nc->type();
4523 if (!type->is_abstract() && type->float_type() != NULL)
4525 int bits = type->float_type()->bits();
4526 mpfr_prec_round(left_val, bits, GMP_RNDN);
4527 mpfr_prec_round(right_val, bits, GMP_RNDN);
4530 *cmp = mpfr_cmp(left_val, right_val);
4532 mpfr_clear(left_val);
4533 mpfr_clear(right_val);
4535 return true;
4538 // Compare complex constants. Complex numbers may only be compared
4539 // for equality.
4541 bool
4542 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4543 const Numeric_constant* right_nc,
4544 int* cmp)
4546 mpfr_t left_real, left_imag;
4547 if (!left_nc->to_complex(&left_real, &left_imag))
4548 return false;
4549 mpfr_t right_real, right_imag;
4550 if (!right_nc->to_complex(&right_real, &right_imag))
4552 mpfr_clear(left_real);
4553 mpfr_clear(left_imag);
4554 return false;
4557 // We already coerced both operands to the same type. If that type
4558 // is not an abstract type, we need to round the values accordingly.
4559 Type* type = left_nc->type();
4560 if (!type->is_abstract() && type->complex_type() != NULL)
4562 int bits = type->complex_type()->bits();
4563 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4564 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4565 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4566 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4569 *cmp = (mpfr_cmp(left_real, right_real) != 0
4570 || mpfr_cmp(left_imag, right_imag) != 0);
4572 mpfr_clear(left_real);
4573 mpfr_clear(left_imag);
4574 mpfr_clear(right_real);
4575 mpfr_clear(right_imag);
4577 return true;
4580 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4581 // true if this could be done, false if not. Issue errors at LOCATION
4582 // as appropriate.
4584 bool
4585 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4586 Numeric_constant* right_nc,
4587 Location location, Numeric_constant* nc)
4589 switch (op)
4591 case OPERATOR_OROR:
4592 case OPERATOR_ANDAND:
4593 case OPERATOR_EQEQ:
4594 case OPERATOR_NOTEQ:
4595 case OPERATOR_LT:
4596 case OPERATOR_LE:
4597 case OPERATOR_GT:
4598 case OPERATOR_GE:
4599 // These return boolean values, not numeric.
4600 return false;
4601 default:
4602 break;
4605 Type* left_type = left_nc->type();
4606 Type* right_type = right_nc->type();
4608 Type* type;
4609 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4610 return false;
4612 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4614 // When combining an untyped operand with a typed operand, we are
4615 // effectively coercing the untyped operand to the other operand's
4616 // type, so make sure that is valid.
4617 if (!left_nc->set_type(type, true, location))
4618 return false;
4619 if (!is_shift && !right_nc->set_type(type, true, location))
4620 return false;
4622 bool r;
4623 if (type->complex_type() != NULL)
4624 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4625 else if (type->float_type() != NULL)
4626 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4627 else
4628 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4630 if (r)
4631 r = nc->set_type(type, true, location);
4633 return r;
4636 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4637 // integer operations. Return true if this could be done, false if
4638 // not.
4640 bool
4641 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4642 const Numeric_constant* right_nc,
4643 Location location, Numeric_constant* nc)
4645 mpz_t left_val;
4646 if (!left_nc->to_int(&left_val))
4647 return false;
4648 mpz_t right_val;
4649 if (!right_nc->to_int(&right_val))
4651 mpz_clear(left_val);
4652 return false;
4655 mpz_t val;
4656 mpz_init(val);
4658 switch (op)
4660 case OPERATOR_PLUS:
4661 mpz_add(val, left_val, right_val);
4662 if (mpz_sizeinbase(val, 2) > 0x100000)
4664 error_at(location, "constant addition overflow");
4665 mpz_set_ui(val, 1);
4667 break;
4668 case OPERATOR_MINUS:
4669 mpz_sub(val, left_val, right_val);
4670 if (mpz_sizeinbase(val, 2) > 0x100000)
4672 error_at(location, "constant subtraction overflow");
4673 mpz_set_ui(val, 1);
4675 break;
4676 case OPERATOR_OR:
4677 mpz_ior(val, left_val, right_val);
4678 break;
4679 case OPERATOR_XOR:
4680 mpz_xor(val, left_val, right_val);
4681 break;
4682 case OPERATOR_MULT:
4683 mpz_mul(val, left_val, right_val);
4684 if (mpz_sizeinbase(val, 2) > 0x100000)
4686 error_at(location, "constant multiplication overflow");
4687 mpz_set_ui(val, 1);
4689 break;
4690 case OPERATOR_DIV:
4691 if (mpz_sgn(right_val) != 0)
4692 mpz_tdiv_q(val, left_val, right_val);
4693 else
4695 error_at(location, "division by zero");
4696 mpz_set_ui(val, 0);
4698 break;
4699 case OPERATOR_MOD:
4700 if (mpz_sgn(right_val) != 0)
4701 mpz_tdiv_r(val, left_val, right_val);
4702 else
4704 error_at(location, "division by zero");
4705 mpz_set_ui(val, 0);
4707 break;
4708 case OPERATOR_LSHIFT:
4710 unsigned long shift = mpz_get_ui(right_val);
4711 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4712 mpz_mul_2exp(val, left_val, shift);
4713 else
4715 error_at(location, "shift count overflow");
4716 mpz_set_ui(val, 1);
4718 break;
4720 break;
4721 case OPERATOR_RSHIFT:
4723 unsigned long shift = mpz_get_ui(right_val);
4724 if (mpz_cmp_ui(right_val, shift) != 0)
4726 error_at(location, "shift count overflow");
4727 mpz_set_ui(val, 1);
4729 else
4731 if (mpz_cmp_ui(left_val, 0) >= 0)
4732 mpz_tdiv_q_2exp(val, left_val, shift);
4733 else
4734 mpz_fdiv_q_2exp(val, left_val, shift);
4736 break;
4738 break;
4739 case OPERATOR_AND:
4740 mpz_and(val, left_val, right_val);
4741 break;
4742 case OPERATOR_BITCLEAR:
4744 mpz_t tval;
4745 mpz_init(tval);
4746 mpz_com(tval, right_val);
4747 mpz_and(val, left_val, tval);
4748 mpz_clear(tval);
4750 break;
4751 default:
4752 go_unreachable();
4755 mpz_clear(left_val);
4756 mpz_clear(right_val);
4758 if (left_nc->is_rune()
4759 || (op != OPERATOR_LSHIFT
4760 && op != OPERATOR_RSHIFT
4761 && right_nc->is_rune()))
4762 nc->set_rune(NULL, val);
4763 else
4764 nc->set_int(NULL, val);
4766 mpz_clear(val);
4768 return true;
4771 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4772 // floating point operations. Return true if this could be done,
4773 // false if not.
4775 bool
4776 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4777 const Numeric_constant* right_nc,
4778 Location location, Numeric_constant* nc)
4780 mpfr_t left_val;
4781 if (!left_nc->to_float(&left_val))
4782 return false;
4783 mpfr_t right_val;
4784 if (!right_nc->to_float(&right_val))
4786 mpfr_clear(left_val);
4787 return false;
4790 mpfr_t val;
4791 mpfr_init(val);
4793 bool ret = true;
4794 switch (op)
4796 case OPERATOR_PLUS:
4797 mpfr_add(val, left_val, right_val, GMP_RNDN);
4798 break;
4799 case OPERATOR_MINUS:
4800 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4801 break;
4802 case OPERATOR_OR:
4803 case OPERATOR_XOR:
4804 case OPERATOR_AND:
4805 case OPERATOR_BITCLEAR:
4806 case OPERATOR_MOD:
4807 case OPERATOR_LSHIFT:
4808 case OPERATOR_RSHIFT:
4809 mpfr_set_ui(val, 0, GMP_RNDN);
4810 ret = false;
4811 break;
4812 case OPERATOR_MULT:
4813 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4814 break;
4815 case OPERATOR_DIV:
4816 if (!mpfr_zero_p(right_val))
4817 mpfr_div(val, left_val, right_val, GMP_RNDN);
4818 else
4820 error_at(location, "division by zero");
4821 mpfr_set_ui(val, 0, GMP_RNDN);
4823 break;
4824 default:
4825 go_unreachable();
4828 mpfr_clear(left_val);
4829 mpfr_clear(right_val);
4831 nc->set_float(NULL, val);
4832 mpfr_clear(val);
4834 return ret;
4837 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4838 // complex operations. Return true if this could be done, false if
4839 // not.
4841 bool
4842 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4843 const Numeric_constant* right_nc,
4844 Location location, Numeric_constant* nc)
4846 mpfr_t left_real, left_imag;
4847 if (!left_nc->to_complex(&left_real, &left_imag))
4848 return false;
4849 mpfr_t right_real, right_imag;
4850 if (!right_nc->to_complex(&right_real, &right_imag))
4852 mpfr_clear(left_real);
4853 mpfr_clear(left_imag);
4854 return false;
4857 mpfr_t real, imag;
4858 mpfr_init(real);
4859 mpfr_init(imag);
4861 bool ret = true;
4862 switch (op)
4864 case OPERATOR_PLUS:
4865 mpfr_add(real, left_real, right_real, GMP_RNDN);
4866 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4867 break;
4868 case OPERATOR_MINUS:
4869 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4870 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4871 break;
4872 case OPERATOR_OR:
4873 case OPERATOR_XOR:
4874 case OPERATOR_AND:
4875 case OPERATOR_BITCLEAR:
4876 case OPERATOR_MOD:
4877 case OPERATOR_LSHIFT:
4878 case OPERATOR_RSHIFT:
4879 mpfr_set_ui(real, 0, GMP_RNDN);
4880 mpfr_set_ui(imag, 0, GMP_RNDN);
4881 ret = false;
4882 break;
4883 case OPERATOR_MULT:
4885 // You might think that multiplying two complex numbers would
4886 // be simple, and you would be right, until you start to think
4887 // about getting the right answer for infinity. If one
4888 // operand here is infinity and the other is anything other
4889 // than zero or NaN, then we are going to wind up subtracting
4890 // two infinity values. That will give us a NaN, but the
4891 // correct answer is infinity.
4893 mpfr_t lrrr;
4894 mpfr_init(lrrr);
4895 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4897 mpfr_t lrri;
4898 mpfr_init(lrri);
4899 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4901 mpfr_t lirr;
4902 mpfr_init(lirr);
4903 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4905 mpfr_t liri;
4906 mpfr_init(liri);
4907 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4909 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4910 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4912 // If we get NaN on both sides, check whether it should really
4913 // be infinity. The rule is that if either side of the
4914 // complex number is infinity, then the whole value is
4915 // infinity, even if the other side is NaN. So the only case
4916 // we have to fix is the one in which both sides are NaN.
4917 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4918 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4919 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4921 bool is_infinity = false;
4923 mpfr_t lr;
4924 mpfr_t li;
4925 mpfr_init_set(lr, left_real, GMP_RNDN);
4926 mpfr_init_set(li, left_imag, GMP_RNDN);
4928 mpfr_t rr;
4929 mpfr_t ri;
4930 mpfr_init_set(rr, right_real, GMP_RNDN);
4931 mpfr_init_set(ri, right_imag, GMP_RNDN);
4933 // If the left side is infinity, then the result is
4934 // infinity.
4935 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4937 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4938 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4939 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4940 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4941 if (mpfr_nan_p(rr))
4943 mpfr_set_ui(rr, 0, GMP_RNDN);
4944 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4946 if (mpfr_nan_p(ri))
4948 mpfr_set_ui(ri, 0, GMP_RNDN);
4949 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4951 is_infinity = true;
4954 // If the right side is infinity, then the result is
4955 // infinity.
4956 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4958 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4959 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4960 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4961 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4962 if (mpfr_nan_p(lr))
4964 mpfr_set_ui(lr, 0, GMP_RNDN);
4965 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4967 if (mpfr_nan_p(li))
4969 mpfr_set_ui(li, 0, GMP_RNDN);
4970 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4972 is_infinity = true;
4975 // If we got an overflow in the intermediate computations,
4976 // then the result is infinity.
4977 if (!is_infinity
4978 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4979 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4981 if (mpfr_nan_p(lr))
4983 mpfr_set_ui(lr, 0, GMP_RNDN);
4984 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4986 if (mpfr_nan_p(li))
4988 mpfr_set_ui(li, 0, GMP_RNDN);
4989 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4991 if (mpfr_nan_p(rr))
4993 mpfr_set_ui(rr, 0, GMP_RNDN);
4994 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4996 if (mpfr_nan_p(ri))
4998 mpfr_set_ui(ri, 0, GMP_RNDN);
4999 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
5001 is_infinity = true;
5004 if (is_infinity)
5006 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
5007 mpfr_mul(lrri, lr, ri, GMP_RNDN);
5008 mpfr_mul(lirr, li, rr, GMP_RNDN);
5009 mpfr_mul(liri, li, ri, GMP_RNDN);
5010 mpfr_sub(real, lrrr, liri, GMP_RNDN);
5011 mpfr_add(imag, lrri, lirr, GMP_RNDN);
5012 mpfr_set_inf(real, mpfr_sgn(real));
5013 mpfr_set_inf(imag, mpfr_sgn(imag));
5016 mpfr_clear(lr);
5017 mpfr_clear(li);
5018 mpfr_clear(rr);
5019 mpfr_clear(ri);
5022 mpfr_clear(lrrr);
5023 mpfr_clear(lrri);
5024 mpfr_clear(lirr);
5025 mpfr_clear(liri);
5027 break;
5028 case OPERATOR_DIV:
5030 // For complex division we want to avoid having an
5031 // intermediate overflow turn the whole result in a NaN. We
5032 // scale the values to try to avoid this.
5034 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
5036 error_at(location, "division by zero");
5037 mpfr_set_ui(real, 0, GMP_RNDN);
5038 mpfr_set_ui(imag, 0, GMP_RNDN);
5039 break;
5042 mpfr_t rra;
5043 mpfr_t ria;
5044 mpfr_init(rra);
5045 mpfr_init(ria);
5046 mpfr_abs(rra, right_real, GMP_RNDN);
5047 mpfr_abs(ria, right_imag, GMP_RNDN);
5048 mpfr_t t;
5049 mpfr_init(t);
5050 mpfr_max(t, rra, ria, GMP_RNDN);
5052 mpfr_t rr;
5053 mpfr_t ri;
5054 mpfr_init_set(rr, right_real, GMP_RNDN);
5055 mpfr_init_set(ri, right_imag, GMP_RNDN);
5056 long ilogbw = 0;
5057 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5059 ilogbw = mpfr_get_exp(t);
5060 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5061 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5064 mpfr_t denom;
5065 mpfr_init(denom);
5066 mpfr_mul(denom, rr, rr, GMP_RNDN);
5067 mpfr_mul(t, ri, ri, GMP_RNDN);
5068 mpfr_add(denom, denom, t, GMP_RNDN);
5070 mpfr_mul(real, left_real, rr, GMP_RNDN);
5071 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5072 mpfr_add(real, real, t, GMP_RNDN);
5073 mpfr_div(real, real, denom, GMP_RNDN);
5074 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5076 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5077 mpfr_mul(t, left_real, ri, GMP_RNDN);
5078 mpfr_sub(imag, imag, t, GMP_RNDN);
5079 mpfr_div(imag, imag, denom, GMP_RNDN);
5080 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5082 // If we wind up with NaN on both sides, check whether we
5083 // should really have infinity. The rule is that if either
5084 // side of the complex number is infinity, then the whole
5085 // value is infinity, even if the other side is NaN. So the
5086 // only case we have to fix is the one in which both sides are
5087 // NaN.
5088 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5089 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5090 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5092 if (mpfr_zero_p(denom))
5094 mpfr_set_inf(real, mpfr_sgn(rr));
5095 mpfr_mul(real, real, left_real, GMP_RNDN);
5096 mpfr_set_inf(imag, mpfr_sgn(rr));
5097 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5099 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5100 && mpfr_number_p(rr) && mpfr_number_p(ri))
5102 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5103 mpfr_copysign(t, t, left_real, GMP_RNDN);
5105 mpfr_t t2;
5106 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5107 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5109 mpfr_t t3;
5110 mpfr_init(t3);
5111 mpfr_mul(t3, t, rr, GMP_RNDN);
5113 mpfr_t t4;
5114 mpfr_init(t4);
5115 mpfr_mul(t4, t2, ri, GMP_RNDN);
5117 mpfr_add(t3, t3, t4, GMP_RNDN);
5118 mpfr_set_inf(real, mpfr_sgn(t3));
5120 mpfr_mul(t3, t2, rr, GMP_RNDN);
5121 mpfr_mul(t4, t, ri, GMP_RNDN);
5122 mpfr_sub(t3, t3, t4, GMP_RNDN);
5123 mpfr_set_inf(imag, mpfr_sgn(t3));
5125 mpfr_clear(t2);
5126 mpfr_clear(t3);
5127 mpfr_clear(t4);
5129 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5130 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5132 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5133 mpfr_copysign(t, t, rr, GMP_RNDN);
5135 mpfr_t t2;
5136 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5137 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5139 mpfr_t t3;
5140 mpfr_init(t3);
5141 mpfr_mul(t3, left_real, t, GMP_RNDN);
5143 mpfr_t t4;
5144 mpfr_init(t4);
5145 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5147 mpfr_add(t3, t3, t4, GMP_RNDN);
5148 mpfr_set_ui(real, 0, GMP_RNDN);
5149 mpfr_mul(real, real, t3, GMP_RNDN);
5151 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5152 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5153 mpfr_sub(t3, t3, t4, GMP_RNDN);
5154 mpfr_set_ui(imag, 0, GMP_RNDN);
5155 mpfr_mul(imag, imag, t3, GMP_RNDN);
5157 mpfr_clear(t2);
5158 mpfr_clear(t3);
5159 mpfr_clear(t4);
5163 mpfr_clear(denom);
5164 mpfr_clear(rr);
5165 mpfr_clear(ri);
5166 mpfr_clear(t);
5167 mpfr_clear(rra);
5168 mpfr_clear(ria);
5170 break;
5171 default:
5172 go_unreachable();
5175 mpfr_clear(left_real);
5176 mpfr_clear(left_imag);
5177 mpfr_clear(right_real);
5178 mpfr_clear(right_imag);
5180 nc->set_complex(NULL, real, imag);
5181 mpfr_clear(real);
5182 mpfr_clear(imag);
5184 return ret;
5187 // Lower a binary expression. We have to evaluate constant
5188 // expressions now, in order to implement Go's unlimited precision
5189 // constants.
5191 Expression*
5192 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5193 Statement_inserter* inserter, int)
5195 Location location = this->location();
5196 Operator op = this->op_;
5197 Expression* left = this->left_;
5198 Expression* right = this->right_;
5200 const bool is_comparison = (op == OPERATOR_EQEQ
5201 || op == OPERATOR_NOTEQ
5202 || op == OPERATOR_LT
5203 || op == OPERATOR_LE
5204 || op == OPERATOR_GT
5205 || op == OPERATOR_GE);
5207 // Numeric constant expressions.
5209 Numeric_constant left_nc;
5210 Numeric_constant right_nc;
5211 if (left->numeric_constant_value(&left_nc)
5212 && right->numeric_constant_value(&right_nc))
5214 if (is_comparison)
5216 bool result;
5217 if (!Binary_expression::compare_constant(op, &left_nc,
5218 &right_nc, location,
5219 &result))
5220 return this;
5221 return Expression::make_cast(Type::make_boolean_type(),
5222 Expression::make_boolean(result,
5223 location),
5224 location);
5226 else
5228 Numeric_constant nc;
5229 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5230 location, &nc))
5231 return this;
5232 return nc.expression(location);
5237 // String constant expressions.
5238 if (left->type()->is_string_type() && right->type()->is_string_type())
5240 std::string left_string;
5241 std::string right_string;
5242 if (left->string_constant_value(&left_string)
5243 && right->string_constant_value(&right_string))
5245 if (op == OPERATOR_PLUS)
5246 return Expression::make_string(left_string + right_string,
5247 location);
5248 else if (is_comparison)
5250 int cmp = left_string.compare(right_string);
5251 bool r = Binary_expression::cmp_to_bool(op, cmp);
5252 return Expression::make_boolean(r, location);
5257 // Lower struct, array, and some interface comparisons.
5258 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5260 if (left->type()->struct_type() != NULL)
5261 return this->lower_struct_comparison(gogo, inserter);
5262 else if (left->type()->array_type() != NULL
5263 && !left->type()->is_slice_type())
5264 return this->lower_array_comparison(gogo, inserter);
5265 else if ((left->type()->interface_type() != NULL
5266 && right->type()->interface_type() == NULL)
5267 || (left->type()->interface_type() == NULL
5268 && right->type()->interface_type() != NULL))
5269 return this->lower_interface_value_comparison(gogo, inserter);
5272 return this;
5275 // Lower a struct comparison.
5277 Expression*
5278 Binary_expression::lower_struct_comparison(Gogo* gogo,
5279 Statement_inserter* inserter)
5281 Struct_type* st = this->left_->type()->struct_type();
5282 Struct_type* st2 = this->right_->type()->struct_type();
5283 if (st2 == NULL)
5284 return this;
5285 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5286 return this;
5287 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5288 this->right_->type(), NULL))
5289 return this;
5291 // See if we can compare using memcmp. As a heuristic, we use
5292 // memcmp rather than field references and comparisons if there are
5293 // more than two fields.
5294 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5295 return this->lower_compare_to_memcmp(gogo, inserter);
5297 Location loc = this->location();
5299 Expression* left = this->left_;
5300 Temporary_statement* left_temp = NULL;
5301 if (left->var_expression() == NULL
5302 && left->temporary_reference_expression() == NULL)
5304 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5305 inserter->insert(left_temp);
5306 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5309 Expression* right = this->right_;
5310 Temporary_statement* right_temp = NULL;
5311 if (right->var_expression() == NULL
5312 && right->temporary_reference_expression() == NULL)
5314 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5315 inserter->insert(right_temp);
5316 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5319 Expression* ret = Expression::make_boolean(true, loc);
5320 const Struct_field_list* fields = st->fields();
5321 unsigned int field_index = 0;
5322 for (Struct_field_list::const_iterator pf = fields->begin();
5323 pf != fields->end();
5324 ++pf, ++field_index)
5326 if (Gogo::is_sink_name(pf->field_name()))
5327 continue;
5329 if (field_index > 0)
5331 if (left_temp == NULL)
5332 left = left->copy();
5333 else
5334 left = Expression::make_temporary_reference(left_temp, loc);
5335 if (right_temp == NULL)
5336 right = right->copy();
5337 else
5338 right = Expression::make_temporary_reference(right_temp, loc);
5340 Expression* f1 = Expression::make_field_reference(left, field_index,
5341 loc);
5342 Expression* f2 = Expression::make_field_reference(right, field_index,
5343 loc);
5344 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5345 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5348 if (this->op_ == OPERATOR_NOTEQ)
5349 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5351 return ret;
5354 // Lower an array comparison.
5356 Expression*
5357 Binary_expression::lower_array_comparison(Gogo* gogo,
5358 Statement_inserter* inserter)
5360 Array_type* at = this->left_->type()->array_type();
5361 Array_type* at2 = this->right_->type()->array_type();
5362 if (at2 == NULL)
5363 return this;
5364 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5365 return this;
5366 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5367 this->right_->type(), NULL))
5368 return this;
5370 // Call memcmp directly if possible. This may let the middle-end
5371 // optimize the call.
5372 if (at->compare_is_identity(gogo))
5373 return this->lower_compare_to_memcmp(gogo, inserter);
5375 // Call the array comparison function.
5376 Named_object* hash_fn;
5377 Named_object* equal_fn;
5378 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5379 &hash_fn, &equal_fn);
5381 Location loc = this->location();
5383 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5385 Expression_list* args = new Expression_list();
5386 args->push_back(this->operand_address(inserter, this->left_));
5387 args->push_back(this->operand_address(inserter, this->right_));
5388 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5390 Expression* ret = Expression::make_call(func, args, false, loc);
5392 if (this->op_ == OPERATOR_NOTEQ)
5393 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5395 return ret;
5398 // Lower an interface to value comparison.
5400 Expression*
5401 Binary_expression::lower_interface_value_comparison(Gogo*,
5402 Statement_inserter* inserter)
5404 Type* left_type = this->left_->type();
5405 Type* right_type = this->right_->type();
5406 Interface_type* ift;
5407 if (left_type->interface_type() != NULL)
5409 ift = left_type->interface_type();
5410 if (!ift->implements_interface(right_type, NULL))
5411 return this;
5413 else
5415 ift = right_type->interface_type();
5416 if (!ift->implements_interface(left_type, NULL))
5417 return this;
5419 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5420 return this;
5422 Location loc = this->location();
5424 if (left_type->interface_type() == NULL
5425 && left_type->points_to() == NULL
5426 && !this->left_->is_addressable())
5428 Temporary_statement* temp =
5429 Statement::make_temporary(left_type, NULL, loc);
5430 inserter->insert(temp);
5431 this->left_ =
5432 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5435 if (right_type->interface_type() == NULL
5436 && right_type->points_to() == NULL
5437 && !this->right_->is_addressable())
5439 Temporary_statement* temp =
5440 Statement::make_temporary(right_type, NULL, loc);
5441 inserter->insert(temp);
5442 this->right_ =
5443 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5446 return this;
5449 // Lower a struct or array comparison to a call to memcmp.
5451 Expression*
5452 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5454 Location loc = this->location();
5456 Expression* a1 = this->operand_address(inserter, this->left_);
5457 Expression* a2 = this->operand_address(inserter, this->right_);
5458 Expression* len = Expression::make_type_info(this->left_->type(),
5459 TYPE_INFO_SIZE);
5461 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5463 mpz_t zval;
5464 mpz_init_set_ui(zval, 0);
5465 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5466 mpz_clear(zval);
5468 return Expression::make_binary(this->op_, call, zero, loc);
5471 Expression*
5472 Binary_expression::do_flatten(Gogo*, Named_object*,
5473 Statement_inserter* inserter)
5475 Location loc = this->location();
5476 Temporary_statement* temp;
5477 if (this->left_->type()->is_string_type()
5478 && this->op_ == OPERATOR_PLUS)
5480 if (!this->left_->is_variable())
5482 temp = Statement::make_temporary(NULL, this->left_, loc);
5483 inserter->insert(temp);
5484 this->left_ = Expression::make_temporary_reference(temp, loc);
5486 if (!this->right_->is_variable())
5488 temp =
5489 Statement::make_temporary(this->left_->type(), this->right_, loc);
5490 this->right_ = Expression::make_temporary_reference(temp, loc);
5491 inserter->insert(temp);
5495 Type* left_type = this->left_->type();
5496 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5497 || this->op_ == OPERATOR_RSHIFT);
5498 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5499 left_type->integer_type() != NULL)
5500 || this->op_ == OPERATOR_MOD);
5502 // FIXME: go_check_divide_zero and go_check_divide_overflow are globals
5503 // defined in gcc/go/lang.opt. These should be defined in go_create_gogo
5504 // and accessed from the Gogo* passed to do_flatten.
5505 if (is_shift_op
5506 || (is_idiv_op && (go_check_divide_zero || go_check_divide_overflow)))
5508 if (!this->left_->is_variable())
5510 temp = Statement::make_temporary(NULL, this->left_, loc);
5511 inserter->insert(temp);
5512 this->left_ = Expression::make_temporary_reference(temp, loc);
5514 if (!this->right_->is_variable())
5516 temp =
5517 Statement::make_temporary(NULL, this->right_, loc);
5518 this->right_ = Expression::make_temporary_reference(temp, loc);
5519 inserter->insert(temp);
5522 return this;
5526 // Return the address of EXPR, cast to unsafe.Pointer.
5528 Expression*
5529 Binary_expression::operand_address(Statement_inserter* inserter,
5530 Expression* expr)
5532 Location loc = this->location();
5534 if (!expr->is_addressable())
5536 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5537 loc);
5538 inserter->insert(temp);
5539 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5541 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5542 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5543 Type* void_type = Type::make_void_type();
5544 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5545 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5548 // Return the numeric constant value, if it has one.
5550 bool
5551 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5553 Numeric_constant left_nc;
5554 if (!this->left_->numeric_constant_value(&left_nc))
5555 return false;
5556 Numeric_constant right_nc;
5557 if (!this->right_->numeric_constant_value(&right_nc))
5558 return false;
5559 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5560 this->location(), nc);
5563 // Note that the value is being discarded.
5565 bool
5566 Binary_expression::do_discarding_value()
5568 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5569 return this->right_->discarding_value();
5570 else
5572 this->unused_value_error();
5573 return false;
5577 // Get type.
5579 Type*
5580 Binary_expression::do_type()
5582 if (this->classification() == EXPRESSION_ERROR)
5583 return Type::make_error_type();
5585 switch (this->op_)
5587 case OPERATOR_EQEQ:
5588 case OPERATOR_NOTEQ:
5589 case OPERATOR_LT:
5590 case OPERATOR_LE:
5591 case OPERATOR_GT:
5592 case OPERATOR_GE:
5593 if (this->type_ == NULL)
5594 this->type_ = Type::make_boolean_type();
5595 return this->type_;
5597 case OPERATOR_PLUS:
5598 case OPERATOR_MINUS:
5599 case OPERATOR_OR:
5600 case OPERATOR_XOR:
5601 case OPERATOR_MULT:
5602 case OPERATOR_DIV:
5603 case OPERATOR_MOD:
5604 case OPERATOR_AND:
5605 case OPERATOR_BITCLEAR:
5606 case OPERATOR_OROR:
5607 case OPERATOR_ANDAND:
5609 Type* type;
5610 if (!Binary_expression::operation_type(this->op_,
5611 this->left_->type(),
5612 this->right_->type(),
5613 &type))
5614 return Type::make_error_type();
5615 return type;
5618 case OPERATOR_LSHIFT:
5619 case OPERATOR_RSHIFT:
5620 return this->left_->type();
5622 default:
5623 go_unreachable();
5627 // Set type for a binary expression.
5629 void
5630 Binary_expression::do_determine_type(const Type_context* context)
5632 Type* tleft = this->left_->type();
5633 Type* tright = this->right_->type();
5635 // Both sides should have the same type, except for the shift
5636 // operations. For a comparison, we should ignore the incoming
5637 // type.
5639 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5640 || this->op_ == OPERATOR_RSHIFT);
5642 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5643 || this->op_ == OPERATOR_NOTEQ
5644 || this->op_ == OPERATOR_LT
5645 || this->op_ == OPERATOR_LE
5646 || this->op_ == OPERATOR_GT
5647 || this->op_ == OPERATOR_GE);
5649 Type_context subcontext(*context);
5651 if (is_comparison)
5653 // In a comparison, the context does not determine the types of
5654 // the operands.
5655 subcontext.type = NULL;
5658 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5660 // For a logical operation, the context does not determine the
5661 // types of the operands. The operands must be some boolean
5662 // type but if the context has a boolean type they do not
5663 // inherit it. See http://golang.org/issue/3924.
5664 subcontext.type = NULL;
5667 // Set the context for the left hand operand.
5668 if (is_shift_op)
5670 // The right hand operand of a shift plays no role in
5671 // determining the type of the left hand operand.
5673 else if (!tleft->is_abstract())
5674 subcontext.type = tleft;
5675 else if (!tright->is_abstract())
5676 subcontext.type = tright;
5677 else if (subcontext.type == NULL)
5679 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5680 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5681 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5683 // Both sides have an abstract integer, abstract float, or
5684 // abstract complex type. Just let CONTEXT determine
5685 // whether they may remain abstract or not.
5687 else if (tleft->complex_type() != NULL)
5688 subcontext.type = tleft;
5689 else if (tright->complex_type() != NULL)
5690 subcontext.type = tright;
5691 else if (tleft->float_type() != NULL)
5692 subcontext.type = tleft;
5693 else if (tright->float_type() != NULL)
5694 subcontext.type = tright;
5695 else
5696 subcontext.type = tleft;
5698 if (subcontext.type != NULL && !context->may_be_abstract)
5699 subcontext.type = subcontext.type->make_non_abstract_type();
5702 this->left_->determine_type(&subcontext);
5704 if (is_shift_op)
5706 // We may have inherited an unusable type for the shift operand.
5707 // Give a useful error if that happened.
5708 if (tleft->is_abstract()
5709 && subcontext.type != NULL
5710 && !subcontext.may_be_abstract
5711 && subcontext.type->interface_type() == NULL
5712 && subcontext.type->integer_type() == NULL)
5713 this->report_error(("invalid context-determined non-integer type "
5714 "for left operand of shift"));
5716 // The context for the right hand operand is the same as for the
5717 // left hand operand, except for a shift operator.
5718 subcontext.type = Type::lookup_integer_type("uint");
5719 subcontext.may_be_abstract = false;
5722 this->right_->determine_type(&subcontext);
5724 if (is_comparison)
5726 if (this->type_ != NULL && !this->type_->is_abstract())
5728 else if (context->type != NULL && context->type->is_boolean_type())
5729 this->type_ = context->type;
5730 else if (!context->may_be_abstract)
5731 this->type_ = Type::lookup_bool_type();
5735 // Report an error if the binary operator OP does not support TYPE.
5736 // OTYPE is the type of the other operand. Return whether the
5737 // operation is OK. This should not be used for shift.
5739 bool
5740 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5741 Location location)
5743 switch (op)
5745 case OPERATOR_OROR:
5746 case OPERATOR_ANDAND:
5747 if (!type->is_boolean_type())
5749 error_at(location, "expected boolean type");
5750 return false;
5752 break;
5754 case OPERATOR_EQEQ:
5755 case OPERATOR_NOTEQ:
5757 std::string reason;
5758 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5760 error_at(location, "%s", reason.c_str());
5761 return false;
5764 break;
5766 case OPERATOR_LT:
5767 case OPERATOR_LE:
5768 case OPERATOR_GT:
5769 case OPERATOR_GE:
5771 std::string reason;
5772 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5774 error_at(location, "%s", reason.c_str());
5775 return false;
5778 break;
5780 case OPERATOR_PLUS:
5781 case OPERATOR_PLUSEQ:
5782 if (type->integer_type() == NULL
5783 && type->float_type() == NULL
5784 && type->complex_type() == NULL
5785 && !type->is_string_type())
5787 error_at(location,
5788 "expected integer, floating, complex, or string type");
5789 return false;
5791 break;
5793 case OPERATOR_MINUS:
5794 case OPERATOR_MINUSEQ:
5795 case OPERATOR_MULT:
5796 case OPERATOR_MULTEQ:
5797 case OPERATOR_DIV:
5798 case OPERATOR_DIVEQ:
5799 if (type->integer_type() == NULL
5800 && type->float_type() == NULL
5801 && type->complex_type() == NULL)
5803 error_at(location, "expected integer, floating, or complex type");
5804 return false;
5806 break;
5808 case OPERATOR_MOD:
5809 case OPERATOR_MODEQ:
5810 case OPERATOR_OR:
5811 case OPERATOR_OREQ:
5812 case OPERATOR_AND:
5813 case OPERATOR_ANDEQ:
5814 case OPERATOR_XOR:
5815 case OPERATOR_XOREQ:
5816 case OPERATOR_BITCLEAR:
5817 case OPERATOR_BITCLEAREQ:
5818 if (type->integer_type() == NULL)
5820 error_at(location, "expected integer type");
5821 return false;
5823 break;
5825 default:
5826 go_unreachable();
5829 return true;
5832 // Check types.
5834 void
5835 Binary_expression::do_check_types(Gogo*)
5837 if (this->classification() == EXPRESSION_ERROR)
5838 return;
5840 Type* left_type = this->left_->type();
5841 Type* right_type = this->right_->type();
5842 if (left_type->is_error() || right_type->is_error())
5844 this->set_is_error();
5845 return;
5848 if (this->op_ == OPERATOR_EQEQ
5849 || this->op_ == OPERATOR_NOTEQ
5850 || this->op_ == OPERATOR_LT
5851 || this->op_ == OPERATOR_LE
5852 || this->op_ == OPERATOR_GT
5853 || this->op_ == OPERATOR_GE)
5855 if (left_type->is_nil_type() && right_type->is_nil_type())
5857 this->report_error(_("invalid comparison of nil with nil"));
5858 return;
5860 if (!Type::are_assignable(left_type, right_type, NULL)
5861 && !Type::are_assignable(right_type, left_type, NULL))
5863 this->report_error(_("incompatible types in binary expression"));
5864 return;
5866 if (!Binary_expression::check_operator_type(this->op_, left_type,
5867 right_type,
5868 this->location())
5869 || !Binary_expression::check_operator_type(this->op_, right_type,
5870 left_type,
5871 this->location()))
5873 this->set_is_error();
5874 return;
5877 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5879 if (!Type::are_compatible_for_binop(left_type, right_type))
5881 this->report_error(_("incompatible types in binary expression"));
5882 return;
5884 if (!Binary_expression::check_operator_type(this->op_, left_type,
5885 right_type,
5886 this->location()))
5888 this->set_is_error();
5889 return;
5891 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5893 // Division by a zero integer constant is an error.
5894 Numeric_constant rconst;
5895 unsigned long rval;
5896 if (left_type->integer_type() != NULL
5897 && this->right_->numeric_constant_value(&rconst)
5898 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5899 && rval == 0)
5901 this->report_error(_("integer division by zero"));
5902 return;
5906 else
5908 if (left_type->integer_type() == NULL)
5909 this->report_error(_("shift of non-integer operand"));
5911 if (!right_type->is_abstract()
5912 && (right_type->integer_type() == NULL
5913 || !right_type->integer_type()->is_unsigned()))
5914 this->report_error(_("shift count not unsigned integer"));
5915 else
5917 Numeric_constant nc;
5918 if (this->right_->numeric_constant_value(&nc))
5920 mpz_t val;
5921 if (!nc.to_int(&val))
5922 this->report_error(_("shift count not unsigned integer"));
5923 else
5925 if (mpz_sgn(val) < 0)
5927 this->report_error(_("negative shift count"));
5928 mpz_set_ui(val, 0);
5929 Location rloc = this->right_->location();
5930 this->right_ = Expression::make_integer(&val, right_type,
5931 rloc);
5933 mpz_clear(val);
5940 // Get a tree for a binary expression.
5942 tree
5943 Binary_expression::do_get_tree(Translate_context* context)
5945 Gogo* gogo = context->gogo();
5946 Location loc = this->location();
5947 Type* left_type = this->left_->type();
5948 Type* right_type = this->right_->type();
5950 bool use_left_type = true;
5951 bool is_shift_op = false;
5952 bool is_idiv_op = false;
5953 switch (this->op_)
5955 case OPERATOR_EQEQ:
5956 case OPERATOR_NOTEQ:
5957 case OPERATOR_LT:
5958 case OPERATOR_LE:
5959 case OPERATOR_GT:
5960 case OPERATOR_GE:
5962 Bexpression* ret =
5963 Expression::comparison(context, this->type_, this->op_,
5964 this->left_, this->right_, loc);
5965 return expr_to_tree(ret);
5968 case OPERATOR_OROR:
5969 case OPERATOR_ANDAND:
5970 use_left_type = false;
5971 break;
5972 case OPERATOR_PLUS:
5973 case OPERATOR_MINUS:
5974 case OPERATOR_OR:
5975 case OPERATOR_XOR:
5976 case OPERATOR_MULT:
5977 break;
5978 case OPERATOR_DIV:
5979 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5980 break;
5981 case OPERATOR_MOD:
5982 is_idiv_op = true;
5983 break;
5984 case OPERATOR_LSHIFT:
5985 case OPERATOR_RSHIFT:
5986 is_shift_op = true;
5987 break;
5988 case OPERATOR_BITCLEAR:
5989 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5990 case OPERATOR_AND:
5991 break;
5992 default:
5993 go_unreachable();
5996 if (left_type->is_string_type())
5998 go_assert(this->op_ == OPERATOR_PLUS);
5999 Expression* string_plus =
6000 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
6001 this->left_, this->right_);
6002 return string_plus->get_tree(context);
6005 // For complex division Go might want slightly different results than the
6006 // backend implementation provides, so we have our own runtime routine.
6007 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6009 Runtime::Function complex_code;
6010 switch (this->left_->type()->complex_type()->bits())
6012 case 64:
6013 complex_code = Runtime::COMPLEX64_DIV;
6014 break;
6015 case 128:
6016 complex_code = Runtime::COMPLEX128_DIV;
6017 break;
6018 default:
6019 go_unreachable();
6021 Expression* complex_div =
6022 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6023 return complex_div->get_tree(context);
6026 Bexpression* left = tree_to_expr(this->left_->get_tree(context));
6027 Bexpression* right = tree_to_expr(this->right_->get_tree(context));
6029 Type* type = use_left_type ? left_type : right_type;
6030 Btype* btype = type->get_backend(gogo);
6032 Bexpression* ret =
6033 gogo->backend()->binary_expression(this->op_, left, right, loc);
6034 ret = gogo->backend()->convert_expression(btype, ret, loc);
6036 // Initialize overflow constants.
6037 Bexpression* overflow;
6038 mpz_t zero;
6039 mpz_init_set_ui(zero, 0UL);
6040 mpz_t one;
6041 mpz_init_set_ui(one, 1UL);
6042 mpz_t neg_one;
6043 mpz_init_set_si(neg_one, -1);
6045 Btype* left_btype = left_type->get_backend(gogo);
6046 Btype* right_btype = right_type->get_backend(gogo);
6048 // In Go, a shift larger than the size of the type is well-defined.
6049 // This is not true in C, so we need to insert a conditional.
6050 if (is_shift_op)
6052 go_assert(left_type->integer_type() != NULL);
6054 mpz_t bitsval;
6055 int bits = left_type->integer_type()->bits();
6056 mpz_init_set_ui(bitsval, bits);
6057 Bexpression* bits_expr =
6058 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6059 Bexpression* compare =
6060 gogo->backend()->binary_expression(OPERATOR_LT,
6061 right, bits_expr, loc);
6063 Bexpression* zero_expr =
6064 gogo->backend()->integer_constant_expression(left_btype, zero);
6065 overflow = zero_expr;
6066 if (this->op_ == OPERATOR_RSHIFT
6067 && !left_type->integer_type()->is_unsigned())
6069 Bexpression* neg_expr =
6070 gogo->backend()->binary_expression(OPERATOR_LT, left,
6071 zero_expr, loc);
6072 Bexpression* neg_one_expr =
6073 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6074 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6075 neg_one_expr,
6076 zero_expr, loc);
6078 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6079 overflow, loc);
6080 mpz_clear(bitsval);
6083 // Add checks for division by zero and division overflow as needed.
6084 if (is_idiv_op)
6086 if (go_check_divide_zero)
6088 // right == 0
6089 Bexpression* zero_expr =
6090 gogo->backend()->integer_constant_expression(right_btype, zero);
6091 Bexpression* check =
6092 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6093 right, zero_expr, loc);
6095 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6096 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6097 Expression* crash = gogo->runtime_error(errcode, loc);
6098 Bexpression* crash_expr = tree_to_expr(crash->get_tree(context));
6100 // right == 0 ? (__go_runtime_error(...), 0) : ret
6101 ret = gogo->backend()->conditional_expression(btype, check,
6102 crash_expr, ret, loc);
6105 if (go_check_divide_overflow)
6107 // right == -1
6108 // FIXME: It would be nice to say that this test is expected
6109 // to return false.
6111 Bexpression* neg_one_expr =
6112 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6113 Bexpression* check =
6114 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6115 right, neg_one_expr, loc);
6117 Bexpression* zero_expr =
6118 gogo->backend()->integer_constant_expression(btype, zero);
6119 Bexpression* one_expr =
6120 gogo->backend()->integer_constant_expression(btype, one);
6122 if (type->integer_type()->is_unsigned())
6124 // An unsigned -1 is the largest possible number, so
6125 // dividing is always 1 or 0.
6127 Bexpression* cmp =
6128 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6129 left, right, loc);
6130 if (this->op_ == OPERATOR_DIV)
6131 overflow =
6132 gogo->backend()->conditional_expression(btype, cmp,
6133 one_expr, zero_expr,
6134 loc);
6135 else
6136 overflow =
6137 gogo->backend()->conditional_expression(btype, cmp,
6138 zero_expr, left,
6139 loc);
6141 else
6143 // Computing left / -1 is the same as computing - left,
6144 // which does not overflow since Go sets -fwrapv.
6145 if (this->op_ == OPERATOR_DIV)
6147 Expression* negate_expr =
6148 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6149 overflow = tree_to_expr(negate_expr->get_tree(context));
6151 else
6152 overflow = zero_expr;
6154 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6156 // right == -1 ? - left : ret
6157 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6158 ret, loc);
6162 mpz_clear(zero);
6163 mpz_clear(one);
6164 mpz_clear(neg_one);
6165 return expr_to_tree(ret);
6168 // Export a binary expression.
6170 void
6171 Binary_expression::do_export(Export* exp) const
6173 exp->write_c_string("(");
6174 this->left_->export_expression(exp);
6175 switch (this->op_)
6177 case OPERATOR_OROR:
6178 exp->write_c_string(" || ");
6179 break;
6180 case OPERATOR_ANDAND:
6181 exp->write_c_string(" && ");
6182 break;
6183 case OPERATOR_EQEQ:
6184 exp->write_c_string(" == ");
6185 break;
6186 case OPERATOR_NOTEQ:
6187 exp->write_c_string(" != ");
6188 break;
6189 case OPERATOR_LT:
6190 exp->write_c_string(" < ");
6191 break;
6192 case OPERATOR_LE:
6193 exp->write_c_string(" <= ");
6194 break;
6195 case OPERATOR_GT:
6196 exp->write_c_string(" > ");
6197 break;
6198 case OPERATOR_GE:
6199 exp->write_c_string(" >= ");
6200 break;
6201 case OPERATOR_PLUS:
6202 exp->write_c_string(" + ");
6203 break;
6204 case OPERATOR_MINUS:
6205 exp->write_c_string(" - ");
6206 break;
6207 case OPERATOR_OR:
6208 exp->write_c_string(" | ");
6209 break;
6210 case OPERATOR_XOR:
6211 exp->write_c_string(" ^ ");
6212 break;
6213 case OPERATOR_MULT:
6214 exp->write_c_string(" * ");
6215 break;
6216 case OPERATOR_DIV:
6217 exp->write_c_string(" / ");
6218 break;
6219 case OPERATOR_MOD:
6220 exp->write_c_string(" % ");
6221 break;
6222 case OPERATOR_LSHIFT:
6223 exp->write_c_string(" << ");
6224 break;
6225 case OPERATOR_RSHIFT:
6226 exp->write_c_string(" >> ");
6227 break;
6228 case OPERATOR_AND:
6229 exp->write_c_string(" & ");
6230 break;
6231 case OPERATOR_BITCLEAR:
6232 exp->write_c_string(" &^ ");
6233 break;
6234 default:
6235 go_unreachable();
6237 this->right_->export_expression(exp);
6238 exp->write_c_string(")");
6241 // Import a binary expression.
6243 Expression*
6244 Binary_expression::do_import(Import* imp)
6246 imp->require_c_string("(");
6248 Expression* left = Expression::import_expression(imp);
6250 Operator op;
6251 if (imp->match_c_string(" || "))
6253 op = OPERATOR_OROR;
6254 imp->advance(4);
6256 else if (imp->match_c_string(" && "))
6258 op = OPERATOR_ANDAND;
6259 imp->advance(4);
6261 else if (imp->match_c_string(" == "))
6263 op = OPERATOR_EQEQ;
6264 imp->advance(4);
6266 else if (imp->match_c_string(" != "))
6268 op = OPERATOR_NOTEQ;
6269 imp->advance(4);
6271 else if (imp->match_c_string(" < "))
6273 op = OPERATOR_LT;
6274 imp->advance(3);
6276 else if (imp->match_c_string(" <= "))
6278 op = OPERATOR_LE;
6279 imp->advance(4);
6281 else if (imp->match_c_string(" > "))
6283 op = OPERATOR_GT;
6284 imp->advance(3);
6286 else if (imp->match_c_string(" >= "))
6288 op = OPERATOR_GE;
6289 imp->advance(4);
6291 else if (imp->match_c_string(" + "))
6293 op = OPERATOR_PLUS;
6294 imp->advance(3);
6296 else if (imp->match_c_string(" - "))
6298 op = OPERATOR_MINUS;
6299 imp->advance(3);
6301 else if (imp->match_c_string(" | "))
6303 op = OPERATOR_OR;
6304 imp->advance(3);
6306 else if (imp->match_c_string(" ^ "))
6308 op = OPERATOR_XOR;
6309 imp->advance(3);
6311 else if (imp->match_c_string(" * "))
6313 op = OPERATOR_MULT;
6314 imp->advance(3);
6316 else if (imp->match_c_string(" / "))
6318 op = OPERATOR_DIV;
6319 imp->advance(3);
6321 else if (imp->match_c_string(" % "))
6323 op = OPERATOR_MOD;
6324 imp->advance(3);
6326 else if (imp->match_c_string(" << "))
6328 op = OPERATOR_LSHIFT;
6329 imp->advance(4);
6331 else if (imp->match_c_string(" >> "))
6333 op = OPERATOR_RSHIFT;
6334 imp->advance(4);
6336 else if (imp->match_c_string(" & "))
6338 op = OPERATOR_AND;
6339 imp->advance(3);
6341 else if (imp->match_c_string(" &^ "))
6343 op = OPERATOR_BITCLEAR;
6344 imp->advance(4);
6346 else
6348 error_at(imp->location(), "unrecognized binary operator");
6349 return Expression::make_error(imp->location());
6352 Expression* right = Expression::import_expression(imp);
6354 imp->require_c_string(")");
6356 return Expression::make_binary(op, left, right, imp->location());
6359 // Dump ast representation of a binary expression.
6361 void
6362 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6364 ast_dump_context->ostream() << "(";
6365 ast_dump_context->dump_expression(this->left_);
6366 ast_dump_context->ostream() << " ";
6367 ast_dump_context->dump_operator(this->op_);
6368 ast_dump_context->ostream() << " ";
6369 ast_dump_context->dump_expression(this->right_);
6370 ast_dump_context->ostream() << ") ";
6373 // Make a binary expression.
6375 Expression*
6376 Expression::make_binary(Operator op, Expression* left, Expression* right,
6377 Location location)
6379 return new Binary_expression(op, left, right, location);
6382 // Implement a comparison.
6384 Bexpression*
6385 Expression::comparison(Translate_context* context, Type* result_type,
6386 Operator op, Expression* left, Expression* right,
6387 Location location)
6389 Type* left_type = left->type();
6390 Type* right_type = right->type();
6392 mpz_t zval;
6393 mpz_init_set_ui(zval, 0UL);
6394 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6395 mpz_clear(zval);
6397 if (left_type->is_string_type() && right_type->is_string_type())
6399 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6400 left, right);
6401 right = zexpr;
6403 else if ((left_type->interface_type() != NULL
6404 && right_type->interface_type() == NULL
6405 && !right_type->is_nil_type())
6406 || (left_type->interface_type() == NULL
6407 && !left_type->is_nil_type()
6408 && right_type->interface_type() != NULL))
6410 // Comparing an interface value to a non-interface value.
6411 if (left_type->interface_type() == NULL)
6413 std::swap(left_type, right_type);
6414 std::swap(left, right);
6417 // The right operand is not an interface. We need to take its
6418 // address if it is not a pointer.
6419 Expression* pointer_arg = NULL;
6420 if (right_type->points_to() != NULL)
6421 pointer_arg = right;
6422 else
6424 go_assert(right->is_addressable());
6425 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6426 location);
6429 Expression* descriptor =
6430 Expression::make_type_descriptor(right_type, location);
6431 left =
6432 Runtime::make_call((left_type->interface_type()->is_empty()
6433 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6434 : Runtime::INTERFACE_VALUE_COMPARE),
6435 location, 3, left, descriptor,
6436 pointer_arg);
6437 right = zexpr;
6439 else if (left_type->interface_type() != NULL
6440 && right_type->interface_type() != NULL)
6442 Runtime::Function compare_function;
6443 if (left_type->interface_type()->is_empty()
6444 && right_type->interface_type()->is_empty())
6445 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6446 else if (!left_type->interface_type()->is_empty()
6447 && !right_type->interface_type()->is_empty())
6448 compare_function = Runtime::INTERFACE_COMPARE;
6449 else
6451 if (left_type->interface_type()->is_empty())
6453 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6454 std::swap(left_type, right_type);
6455 std::swap(left, right);
6457 go_assert(!left_type->interface_type()->is_empty());
6458 go_assert(right_type->interface_type()->is_empty());
6459 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6462 left = Runtime::make_call(compare_function, location, 2, left, right);
6463 right = zexpr;
6466 if (left_type->is_nil_type()
6467 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6469 std::swap(left_type, right_type);
6470 std::swap(left, right);
6473 if (right_type->is_nil_type())
6475 right = Expression::make_nil(location);
6476 if (left_type->array_type() != NULL
6477 && left_type->array_type()->length() == NULL)
6479 Array_type* at = left_type->array_type();
6480 left = at->get_value_pointer(context->gogo(), left);
6482 else if (left_type->interface_type() != NULL)
6484 // An interface is nil if the first field is nil.
6485 left = Expression::make_field_reference(left, 0, location);
6489 Bexpression* left_bexpr = tree_to_expr(left->get_tree(context));
6490 Bexpression* right_bexpr = tree_to_expr(right->get_tree(context));
6492 Gogo* gogo = context->gogo();
6493 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6494 right_bexpr, location);
6495 if (result_type != NULL)
6496 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6497 ret, location);
6498 return ret;
6501 // Class Bound_method_expression.
6503 // Traversal.
6506 Bound_method_expression::do_traverse(Traverse* traverse)
6508 return Expression::traverse(&this->expr_, traverse);
6511 // Lower the expression. If this is a method value rather than being
6512 // called, and the method is accessed via a pointer, we may need to
6513 // add nil checks. Introduce a temporary variable so that those nil
6514 // checks do not cause multiple evaluation.
6516 Expression*
6517 Bound_method_expression::do_lower(Gogo*, Named_object*,
6518 Statement_inserter* inserter, int)
6520 // For simplicity we use a temporary for every call to an embedded
6521 // method, even though some of them might be pure value methods and
6522 // not require a temporary.
6523 if (this->expr_->var_expression() == NULL
6524 && this->expr_->temporary_reference_expression() == NULL
6525 && this->expr_->set_and_use_temporary_expression() == NULL
6526 && (this->method_->field_indexes() != NULL
6527 || (this->method_->is_value_method()
6528 && this->expr_->type()->points_to() != NULL)))
6530 Temporary_statement* temp =
6531 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6532 inserter->insert(temp);
6533 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6534 this->location());
6536 return this;
6539 // Return the type of a bound method expression. The type of this
6540 // object is simply the type of the method with no receiver.
6542 Type*
6543 Bound_method_expression::do_type()
6545 Named_object* fn = this->method_->named_object();
6546 Function_type* fntype;
6547 if (fn->is_function())
6548 fntype = fn->func_value()->type();
6549 else if (fn->is_function_declaration())
6550 fntype = fn->func_declaration_value()->type();
6551 else
6552 return Type::make_error_type();
6553 return fntype->copy_without_receiver();
6556 // Determine the types of a method expression.
6558 void
6559 Bound_method_expression::do_determine_type(const Type_context*)
6561 Named_object* fn = this->method_->named_object();
6562 Function_type* fntype;
6563 if (fn->is_function())
6564 fntype = fn->func_value()->type();
6565 else if (fn->is_function_declaration())
6566 fntype = fn->func_declaration_value()->type();
6567 else
6568 fntype = NULL;
6569 if (fntype == NULL || !fntype->is_method())
6570 this->expr_->determine_type_no_context();
6571 else
6573 Type_context subcontext(fntype->receiver()->type(), false);
6574 this->expr_->determine_type(&subcontext);
6578 // Check the types of a method expression.
6580 void
6581 Bound_method_expression::do_check_types(Gogo*)
6583 Named_object* fn = this->method_->named_object();
6584 if (!fn->is_function() && !fn->is_function_declaration())
6586 this->report_error(_("object is not a method"));
6587 return;
6590 Function_type* fntype;
6591 if (fn->is_function())
6592 fntype = fn->func_value()->type();
6593 else if (fn->is_function_declaration())
6594 fntype = fn->func_declaration_value()->type();
6595 else
6596 go_unreachable();
6597 Type* rtype = fntype->receiver()->type()->deref();
6598 Type* etype = (this->expr_type_ != NULL
6599 ? this->expr_type_
6600 : this->expr_->type());
6601 etype = etype->deref();
6602 if (!Type::are_identical(rtype, etype, true, NULL))
6603 this->report_error(_("method type does not match object type"));
6606 // If a bound method expression is not simply called, then it is
6607 // represented as a closure. The closure will hold a single variable,
6608 // the receiver to pass to the method. The function will be a simple
6609 // thunk that pulls that value from the closure and calls the method
6610 // with the remaining arguments.
6612 // Because method values are not common, we don't build all thunks for
6613 // every methods, but instead only build them as we need them. In
6614 // particular, we even build them on demand for methods defined in
6615 // other packages.
6617 Bound_method_expression::Method_value_thunks
6618 Bound_method_expression::method_value_thunks;
6620 // Find or create the thunk for METHOD.
6622 Named_object*
6623 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6624 Named_object* fn)
6626 std::pair<Named_object*, Named_object*> val(fn, NULL);
6627 std::pair<Method_value_thunks::iterator, bool> ins =
6628 Bound_method_expression::method_value_thunks.insert(val);
6629 if (!ins.second)
6631 // We have seen this method before.
6632 go_assert(ins.first->second != NULL);
6633 return ins.first->second;
6636 Location loc = fn->location();
6638 Function_type* orig_fntype;
6639 if (fn->is_function())
6640 orig_fntype = fn->func_value()->type();
6641 else if (fn->is_function_declaration())
6642 orig_fntype = fn->func_declaration_value()->type();
6643 else
6644 orig_fntype = NULL;
6646 if (orig_fntype == NULL || !orig_fntype->is_method())
6648 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6649 return ins.first->second;
6652 Struct_field_list* sfl = new Struct_field_list();
6653 // The type here is wrong--it should be the C function type. But it
6654 // doesn't really matter.
6655 Type* vt = Type::make_pointer_type(Type::make_void_type());
6656 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6657 sfl->push_back(Struct_field(Typed_identifier("val.1",
6658 orig_fntype->receiver()->type(),
6659 loc)));
6660 Type* closure_type = Type::make_struct_type(sfl, loc);
6661 closure_type = Type::make_pointer_type(closure_type);
6663 Function_type* new_fntype = orig_fntype->copy_with_names();
6665 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6666 false, loc);
6668 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6669 cvar->set_is_used();
6670 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6671 new_no->func_value()->set_closure_var(cp);
6673 gogo->start_block(loc);
6675 // Field 0 of the closure is the function code pointer, field 1 is
6676 // the value on which to invoke the method.
6677 Expression* arg = Expression::make_var_reference(cp, loc);
6678 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6679 arg = Expression::make_field_reference(arg, 1, loc);
6681 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6683 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6684 Expression_list* args;
6685 if (orig_params == NULL || orig_params->empty())
6686 args = NULL;
6687 else
6689 const Typed_identifier_list* new_params = new_fntype->parameters();
6690 args = new Expression_list();
6691 for (Typed_identifier_list::const_iterator p = new_params->begin();
6692 p != new_params->end();
6693 ++p)
6695 Named_object* p_no = gogo->lookup(p->name(), NULL);
6696 go_assert(p_no != NULL
6697 && p_no->is_variable()
6698 && p_no->var_value()->is_parameter());
6699 args->push_back(Expression::make_var_reference(p_no, loc));
6703 Call_expression* call = Expression::make_call(bme, args,
6704 orig_fntype->is_varargs(),
6705 loc);
6706 call->set_varargs_are_lowered();
6708 Statement* s = Statement::make_return_from_call(call, loc);
6709 gogo->add_statement(s);
6710 Block* b = gogo->finish_block(loc);
6711 gogo->add_block(b, loc);
6712 gogo->lower_block(new_no, b);
6713 gogo->flatten_block(new_no, b);
6714 gogo->finish_function(loc);
6716 ins.first->second = new_no;
6717 return new_no;
6720 // Return an expression to check *REF for nil while dereferencing
6721 // according to FIELD_INDEXES. Update *REF to build up the field
6722 // reference. This is a static function so that we don't have to
6723 // worry about declaring Field_indexes in expressions.h.
6725 static Expression*
6726 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6727 Expression** ref)
6729 if (field_indexes == NULL)
6730 return Expression::make_boolean(false, loc);
6731 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6732 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6733 go_assert(stype != NULL
6734 && field_indexes->field_index < stype->field_count());
6735 if ((*ref)->type()->struct_type() == NULL)
6737 go_assert((*ref)->type()->points_to() != NULL);
6738 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6739 Expression::make_nil(loc),
6740 loc);
6741 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6742 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6743 go_assert((*ref)->type()->struct_type() == stype);
6745 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6746 loc);
6747 return cond;
6750 // Get the tree for a method value.
6752 tree
6753 Bound_method_expression::do_get_tree(Translate_context* context)
6755 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6756 this->method_,
6757 this->function_);
6758 if (thunk->is_erroneous())
6760 go_assert(saw_errors());
6761 return error_mark_node;
6764 // FIXME: We should lower this earlier, but we can't lower it in the
6765 // lowering pass because at that point we don't know whether we need
6766 // to create the thunk or not. If the expression is called, we
6767 // don't need the thunk.
6769 Location loc = this->location();
6771 // If the method expects a value, and we have a pointer, we need to
6772 // dereference the pointer.
6774 Named_object* fn = this->method_->named_object();
6775 Function_type* fntype;
6776 if (fn->is_function())
6777 fntype = fn->func_value()->type();
6778 else if (fn->is_function_declaration())
6779 fntype = fn->func_declaration_value()->type();
6780 else
6781 go_unreachable();
6783 Expression* val = this->expr_;
6784 if (fntype->receiver()->type()->points_to() == NULL
6785 && val->type()->points_to() != NULL)
6786 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6788 // Note that we are ignoring this->expr_type_ here. The thunk will
6789 // expect a closure whose second field has type this->expr_type_ (if
6790 // that is not NULL). We are going to pass it a closure whose
6791 // second field has type this->expr_->type(). Since
6792 // this->expr_type_ is only not-NULL for pointer types, we can get
6793 // away with this.
6795 Struct_field_list* fields = new Struct_field_list();
6796 fields->push_back(Struct_field(Typed_identifier("fn.0",
6797 thunk->func_value()->type(),
6798 loc)));
6799 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6800 Struct_type* st = Type::make_struct_type(fields, loc);
6802 Expression_list* vals = new Expression_list();
6803 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6804 vals->push_back(val);
6806 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6807 ret = Expression::make_heap_expression(ret, loc);
6809 tree ret_tree = ret->get_tree(context);
6811 Expression* nil_check = NULL;
6813 // See whether the expression or any embedded pointers are nil.
6815 Expression* expr = this->expr_;
6816 if (this->method_->field_indexes() != NULL)
6818 // Note that we are evaluating this->expr_ twice, but that is OK
6819 // because in the lowering pass we forced it into a temporary
6820 // variable.
6821 Expression* ref = expr;
6822 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6823 expr = ref;
6826 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6828 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6829 Expression::make_nil(loc),
6830 loc);
6831 if (nil_check == NULL)
6832 nil_check = n;
6833 else
6834 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6837 if (nil_check != NULL)
6839 tree nil_check_tree = nil_check->get_tree(context);
6840 Expression* crash_expr =
6841 context->gogo()->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
6842 tree crash = crash_expr->get_tree(context);
6843 if (ret_tree == error_mark_node
6844 || nil_check_tree == error_mark_node
6845 || crash == error_mark_node)
6846 return error_mark_node;
6848 ret_tree = fold_build2_loc(loc.gcc_location(), COMPOUND_EXPR,
6849 TREE_TYPE(ret_tree),
6850 build3_loc(loc.gcc_location(), COND_EXPR,
6851 void_type_node, nil_check_tree,
6852 crash, NULL_TREE),
6853 ret_tree);
6856 return ret_tree;
6859 // Dump ast representation of a bound method expression.
6861 void
6862 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6863 const
6865 if (this->expr_type_ != NULL)
6866 ast_dump_context->ostream() << "(";
6867 ast_dump_context->dump_expression(this->expr_);
6868 if (this->expr_type_ != NULL)
6870 ast_dump_context->ostream() << ":";
6871 ast_dump_context->dump_type(this->expr_type_);
6872 ast_dump_context->ostream() << ")";
6875 ast_dump_context->ostream() << "." << this->function_->name();
6878 // Make a method expression.
6880 Bound_method_expression*
6881 Expression::make_bound_method(Expression* expr, const Method* method,
6882 Named_object* function, Location location)
6884 return new Bound_method_expression(expr, method, function, location);
6887 // Class Builtin_call_expression. This is used for a call to a
6888 // builtin function.
6890 class Builtin_call_expression : public Call_expression
6892 public:
6893 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6894 bool is_varargs, Location location);
6896 protected:
6897 // This overrides Call_expression::do_lower.
6898 Expression*
6899 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6901 Expression*
6902 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6904 bool
6905 do_is_constant() const;
6907 bool
6908 do_numeric_constant_value(Numeric_constant*) const;
6910 bool
6911 do_discarding_value();
6913 Type*
6914 do_type();
6916 void
6917 do_determine_type(const Type_context*);
6919 void
6920 do_check_types(Gogo*);
6922 Expression*
6923 do_copy()
6925 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6926 this->args()->copy(),
6927 this->is_varargs(),
6928 this->location());
6931 tree
6932 do_get_tree(Translate_context*);
6934 void
6935 do_export(Export*) const;
6937 virtual bool
6938 do_is_recover_call() const;
6940 virtual void
6941 do_set_recover_arg(Expression*);
6943 private:
6944 // The builtin functions.
6945 enum Builtin_function_code
6947 BUILTIN_INVALID,
6949 // Predeclared builtin functions.
6950 BUILTIN_APPEND,
6951 BUILTIN_CAP,
6952 BUILTIN_CLOSE,
6953 BUILTIN_COMPLEX,
6954 BUILTIN_COPY,
6955 BUILTIN_DELETE,
6956 BUILTIN_IMAG,
6957 BUILTIN_LEN,
6958 BUILTIN_MAKE,
6959 BUILTIN_NEW,
6960 BUILTIN_PANIC,
6961 BUILTIN_PRINT,
6962 BUILTIN_PRINTLN,
6963 BUILTIN_REAL,
6964 BUILTIN_RECOVER,
6966 // Builtin functions from the unsafe package.
6967 BUILTIN_ALIGNOF,
6968 BUILTIN_OFFSETOF,
6969 BUILTIN_SIZEOF
6972 Expression*
6973 one_arg() const;
6975 bool
6976 check_one_arg();
6978 static Type*
6979 real_imag_type(Type*);
6981 static Type*
6982 complex_type(Type*);
6984 Expression*
6985 lower_make();
6987 bool
6988 check_int_value(Expression*, bool is_length);
6990 // A pointer back to the general IR structure. This avoids a global
6991 // variable, or passing it around everywhere.
6992 Gogo* gogo_;
6993 // The builtin function being called.
6994 Builtin_function_code code_;
6995 // Used to stop endless loops when the length of an array uses len
6996 // or cap of the array itself.
6997 mutable bool seen_;
7000 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7001 Expression* fn,
7002 Expression_list* args,
7003 bool is_varargs,
7004 Location location)
7005 : Call_expression(fn, args, is_varargs, location),
7006 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
7008 Func_expression* fnexp = this->fn()->func_expression();
7009 go_assert(fnexp != NULL);
7010 const std::string& name(fnexp->named_object()->name());
7011 if (name == "append")
7012 this->code_ = BUILTIN_APPEND;
7013 else if (name == "cap")
7014 this->code_ = BUILTIN_CAP;
7015 else if (name == "close")
7016 this->code_ = BUILTIN_CLOSE;
7017 else if (name == "complex")
7018 this->code_ = BUILTIN_COMPLEX;
7019 else if (name == "copy")
7020 this->code_ = BUILTIN_COPY;
7021 else if (name == "delete")
7022 this->code_ = BUILTIN_DELETE;
7023 else if (name == "imag")
7024 this->code_ = BUILTIN_IMAG;
7025 else if (name == "len")
7026 this->code_ = BUILTIN_LEN;
7027 else if (name == "make")
7028 this->code_ = BUILTIN_MAKE;
7029 else if (name == "new")
7030 this->code_ = BUILTIN_NEW;
7031 else if (name == "panic")
7032 this->code_ = BUILTIN_PANIC;
7033 else if (name == "print")
7034 this->code_ = BUILTIN_PRINT;
7035 else if (name == "println")
7036 this->code_ = BUILTIN_PRINTLN;
7037 else if (name == "real")
7038 this->code_ = BUILTIN_REAL;
7039 else if (name == "recover")
7040 this->code_ = BUILTIN_RECOVER;
7041 else if (name == "Alignof")
7042 this->code_ = BUILTIN_ALIGNOF;
7043 else if (name == "Offsetof")
7044 this->code_ = BUILTIN_OFFSETOF;
7045 else if (name == "Sizeof")
7046 this->code_ = BUILTIN_SIZEOF;
7047 else
7048 go_unreachable();
7051 // Return whether this is a call to recover. This is a virtual
7052 // function called from the parent class.
7054 bool
7055 Builtin_call_expression::do_is_recover_call() const
7057 if (this->classification() == EXPRESSION_ERROR)
7058 return false;
7059 return this->code_ == BUILTIN_RECOVER;
7062 // Set the argument for a call to recover.
7064 void
7065 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7067 const Expression_list* args = this->args();
7068 go_assert(args == NULL || args->empty());
7069 Expression_list* new_args = new Expression_list();
7070 new_args->push_back(arg);
7071 this->set_args(new_args);
7074 // Lower a builtin call expression. This turns new and make into
7075 // specific expressions. We also convert to a constant if we can.
7077 Expression*
7078 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7079 Statement_inserter* inserter, int)
7081 if (this->classification() == EXPRESSION_ERROR)
7082 return this;
7084 Location loc = this->location();
7086 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7088 this->report_error(_("invalid use of %<...%> with builtin function"));
7089 return Expression::make_error(loc);
7092 if (this->code_ == BUILTIN_OFFSETOF)
7094 Expression* arg = this->one_arg();
7096 if (arg->bound_method_expression() != NULL
7097 || arg->interface_field_reference_expression() != NULL)
7099 this->report_error(_("invalid use of method value as argument "
7100 "of Offsetof"));
7101 return this;
7104 Field_reference_expression* farg = arg->field_reference_expression();
7105 while (farg != NULL)
7107 if (!farg->implicit())
7108 break;
7109 // When the selector refers to an embedded field,
7110 // it must not be reached through pointer indirections.
7111 if (farg->expr()->deref() != farg->expr())
7113 this->report_error(_("argument of Offsetof implies "
7114 "indirection of an embedded field"));
7115 return this;
7117 // Go up until we reach the original base.
7118 farg = farg->expr()->field_reference_expression();
7122 if (this->is_constant())
7124 Numeric_constant nc;
7125 if (this->numeric_constant_value(&nc))
7126 return nc.expression(loc);
7129 switch (this->code_)
7131 default:
7132 break;
7134 case BUILTIN_NEW:
7136 const Expression_list* args = this->args();
7137 if (args == NULL || args->size() < 1)
7138 this->report_error(_("not enough arguments"));
7139 else if (args->size() > 1)
7140 this->report_error(_("too many arguments"));
7141 else
7143 Expression* arg = args->front();
7144 if (!arg->is_type_expression())
7146 error_at(arg->location(), "expected type");
7147 this->set_is_error();
7149 else
7150 return Expression::make_allocation(arg->type(), loc);
7153 break;
7155 case BUILTIN_MAKE:
7156 return this->lower_make();
7158 case BUILTIN_RECOVER:
7159 if (function != NULL)
7160 function->func_value()->set_calls_recover();
7161 else
7163 // Calling recover outside of a function always returns the
7164 // nil empty interface.
7165 Type* eface = Type::make_empty_interface_type(loc);
7166 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7168 break;
7170 case BUILTIN_APPEND:
7172 // Lower the varargs.
7173 const Expression_list* args = this->args();
7174 if (args == NULL || args->empty())
7175 return this;
7176 Type* slice_type = args->front()->type();
7177 if (!slice_type->is_slice_type())
7179 if (slice_type->is_nil_type())
7180 error_at(args->front()->location(), "use of untyped nil");
7181 else
7182 error_at(args->front()->location(),
7183 "argument 1 must be a slice");
7184 this->set_is_error();
7185 return this;
7187 Type* element_type = slice_type->array_type()->element_type();
7188 this->lower_varargs(gogo, function, inserter,
7189 Type::make_array_type(element_type, NULL),
7192 break;
7194 case BUILTIN_DELETE:
7196 // Lower to a runtime function call.
7197 const Expression_list* args = this->args();
7198 if (args == NULL || args->size() < 2)
7199 this->report_error(_("not enough arguments"));
7200 else if (args->size() > 2)
7201 this->report_error(_("too many arguments"));
7202 else if (args->front()->type()->map_type() == NULL)
7203 this->report_error(_("argument 1 must be a map"));
7204 else
7206 // Since this function returns no value it must appear in
7207 // a statement by itself, so we don't have to worry about
7208 // order of evaluation of values around it. Evaluate the
7209 // map first to get order of evaluation right.
7210 Map_type* mt = args->front()->type()->map_type();
7211 Temporary_statement* map_temp =
7212 Statement::make_temporary(mt, args->front(), loc);
7213 inserter->insert(map_temp);
7215 Temporary_statement* key_temp =
7216 Statement::make_temporary(mt->key_type(), args->back(), loc);
7217 inserter->insert(key_temp);
7219 Expression* e1 = Expression::make_temporary_reference(map_temp,
7220 loc);
7221 Expression* e2 = Expression::make_temporary_reference(key_temp,
7222 loc);
7223 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7224 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7225 2, e1, e2);
7228 break;
7231 return this;
7234 // Flatten a builtin call expression. This turns the arguments of copy and
7235 // append into temporary expressions.
7237 Expression*
7238 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7239 Statement_inserter* inserter)
7241 if (this->code_ == BUILTIN_APPEND
7242 || this->code_ == BUILTIN_COPY)
7244 Location loc = this->location();
7245 Type* at = this->args()->front()->type();
7246 for (Expression_list::iterator pa = this->args()->begin();
7247 pa != this->args()->end();
7248 ++pa)
7250 if ((*pa)->is_nil_expression())
7251 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7252 if (!(*pa)->is_variable())
7254 Temporary_statement* temp =
7255 Statement::make_temporary(NULL, *pa, loc);
7256 inserter->insert(temp);
7257 *pa = Expression::make_temporary_reference(temp, loc);
7261 return this;
7264 // Lower a make expression.
7266 Expression*
7267 Builtin_call_expression::lower_make()
7269 Location loc = this->location();
7271 const Expression_list* args = this->args();
7272 if (args == NULL || args->size() < 1)
7274 this->report_error(_("not enough arguments"));
7275 return Expression::make_error(this->location());
7278 Expression_list::const_iterator parg = args->begin();
7280 Expression* first_arg = *parg;
7281 if (!first_arg->is_type_expression())
7283 error_at(first_arg->location(), "expected type");
7284 this->set_is_error();
7285 return Expression::make_error(this->location());
7287 Type* type = first_arg->type();
7289 bool is_slice = false;
7290 bool is_map = false;
7291 bool is_chan = false;
7292 if (type->is_slice_type())
7293 is_slice = true;
7294 else if (type->map_type() != NULL)
7295 is_map = true;
7296 else if (type->channel_type() != NULL)
7297 is_chan = true;
7298 else
7300 this->report_error(_("invalid type for make function"));
7301 return Expression::make_error(this->location());
7304 bool have_big_args = false;
7305 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7306 int uintptr_bits = uintptr_type->integer_type()->bits();
7308 Type_context int_context(Type::lookup_integer_type("int"), false);
7310 ++parg;
7311 Expression* len_arg;
7312 if (parg == args->end())
7314 if (is_slice)
7316 this->report_error(_("length required when allocating a slice"));
7317 return Expression::make_error(this->location());
7320 mpz_t zval;
7321 mpz_init_set_ui(zval, 0);
7322 len_arg = Expression::make_integer(&zval, NULL, loc);
7323 mpz_clear(zval);
7325 else
7327 len_arg = *parg;
7328 len_arg->determine_type(&int_context);
7329 if (!this->check_int_value(len_arg, true))
7330 return Expression::make_error(this->location());
7331 if (len_arg->type()->integer_type() != NULL
7332 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7333 have_big_args = true;
7334 ++parg;
7337 Expression* cap_arg = NULL;
7338 if (is_slice && parg != args->end())
7340 cap_arg = *parg;
7341 cap_arg->determine_type(&int_context);
7342 if (!this->check_int_value(cap_arg, false))
7343 return Expression::make_error(this->location());
7345 Numeric_constant nclen;
7346 Numeric_constant nccap;
7347 unsigned long vlen;
7348 unsigned long vcap;
7349 if (len_arg->numeric_constant_value(&nclen)
7350 && cap_arg->numeric_constant_value(&nccap)
7351 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7352 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7353 && vlen > vcap)
7355 this->report_error(_("len larger than cap"));
7356 return Expression::make_error(this->location());
7359 if (cap_arg->type()->integer_type() != NULL
7360 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7361 have_big_args = true;
7362 ++parg;
7365 if (parg != args->end())
7367 this->report_error(_("too many arguments to make"));
7368 return Expression::make_error(this->location());
7371 Location type_loc = first_arg->location();
7372 Expression* type_arg;
7373 if (is_slice || is_chan)
7374 type_arg = Expression::make_type_descriptor(type, type_loc);
7375 else if (is_map)
7376 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7377 else
7378 go_unreachable();
7380 Expression* call;
7381 if (is_slice)
7383 if (cap_arg == NULL)
7384 call = Runtime::make_call((have_big_args
7385 ? Runtime::MAKESLICE1BIG
7386 : Runtime::MAKESLICE1),
7387 loc, 2, type_arg, len_arg);
7388 else
7389 call = Runtime::make_call((have_big_args
7390 ? Runtime::MAKESLICE2BIG
7391 : Runtime::MAKESLICE2),
7392 loc, 3, type_arg, len_arg, cap_arg);
7394 else if (is_map)
7395 call = Runtime::make_call((have_big_args
7396 ? Runtime::MAKEMAPBIG
7397 : Runtime::MAKEMAP),
7398 loc, 2, type_arg, len_arg);
7399 else if (is_chan)
7400 call = Runtime::make_call((have_big_args
7401 ? Runtime::MAKECHANBIG
7402 : Runtime::MAKECHAN),
7403 loc, 2, type_arg, len_arg);
7404 else
7405 go_unreachable();
7407 return Expression::make_unsafe_cast(type, call, loc);
7410 // Return whether an expression has an integer value. Report an error
7411 // if not. This is used when handling calls to the predeclared make
7412 // function.
7414 bool
7415 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7417 Numeric_constant nc;
7418 if (e->numeric_constant_value(&nc))
7420 unsigned long v;
7421 switch (nc.to_unsigned_long(&v))
7423 case Numeric_constant::NC_UL_VALID:
7424 break;
7425 case Numeric_constant::NC_UL_NOTINT:
7426 error_at(e->location(), "non-integer %s argument to make",
7427 is_length ? "len" : "cap");
7428 return false;
7429 case Numeric_constant::NC_UL_NEGATIVE:
7430 error_at(e->location(), "negative %s argument to make",
7431 is_length ? "len" : "cap");
7432 return false;
7433 case Numeric_constant::NC_UL_BIG:
7434 // We don't want to give a compile-time error for a 64-bit
7435 // value on a 32-bit target.
7436 break;
7439 mpz_t val;
7440 if (!nc.to_int(&val))
7441 go_unreachable();
7442 int bits = mpz_sizeinbase(val, 2);
7443 mpz_clear(val);
7444 Type* int_type = Type::lookup_integer_type("int");
7445 if (bits >= int_type->integer_type()->bits())
7447 error_at(e->location(), "%s argument too large for make",
7448 is_length ? "len" : "cap");
7449 return false;
7452 return true;
7455 if (e->type()->integer_type() != NULL)
7456 return true;
7458 error_at(e->location(), "non-integer %s argument to make",
7459 is_length ? "len" : "cap");
7460 return false;
7463 // Return the type of the real or imag functions, given the type of
7464 // the argument. We need to map complex to float, complex64 to
7465 // float32, and complex128 to float64, so it has to be done by name.
7466 // This returns NULL if it can't figure out the type.
7468 Type*
7469 Builtin_call_expression::real_imag_type(Type* arg_type)
7471 if (arg_type == NULL || arg_type->is_abstract())
7472 return NULL;
7473 Named_type* nt = arg_type->named_type();
7474 if (nt == NULL)
7475 return NULL;
7476 while (nt->real_type()->named_type() != NULL)
7477 nt = nt->real_type()->named_type();
7478 if (nt->name() == "complex64")
7479 return Type::lookup_float_type("float32");
7480 else if (nt->name() == "complex128")
7481 return Type::lookup_float_type("float64");
7482 else
7483 return NULL;
7486 // Return the type of the complex function, given the type of one of the
7487 // argments. Like real_imag_type, we have to map by name.
7489 Type*
7490 Builtin_call_expression::complex_type(Type* arg_type)
7492 if (arg_type == NULL || arg_type->is_abstract())
7493 return NULL;
7494 Named_type* nt = arg_type->named_type();
7495 if (nt == NULL)
7496 return NULL;
7497 while (nt->real_type()->named_type() != NULL)
7498 nt = nt->real_type()->named_type();
7499 if (nt->name() == "float32")
7500 return Type::lookup_complex_type("complex64");
7501 else if (nt->name() == "float64")
7502 return Type::lookup_complex_type("complex128");
7503 else
7504 return NULL;
7507 // Return a single argument, or NULL if there isn't one.
7509 Expression*
7510 Builtin_call_expression::one_arg() const
7512 const Expression_list* args = this->args();
7513 if (args == NULL || args->size() != 1)
7514 return NULL;
7515 return args->front();
7518 // A traversal class which looks for a call or receive expression.
7520 class Find_call_expression : public Traverse
7522 public:
7523 Find_call_expression()
7524 : Traverse(traverse_expressions),
7525 found_(false)
7529 expression(Expression**);
7531 bool
7532 found()
7533 { return this->found_; }
7535 private:
7536 bool found_;
7540 Find_call_expression::expression(Expression** pexpr)
7542 if ((*pexpr)->call_expression() != NULL
7543 || (*pexpr)->receive_expression() != NULL)
7545 this->found_ = true;
7546 return TRAVERSE_EXIT;
7548 return TRAVERSE_CONTINUE;
7551 // Return whether this is constant: len of a string constant, or len
7552 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7553 // unsafe.Alignof.
7555 bool
7556 Builtin_call_expression::do_is_constant() const
7558 if (this->is_error_expression())
7559 return true;
7560 switch (this->code_)
7562 case BUILTIN_LEN:
7563 case BUILTIN_CAP:
7565 if (this->seen_)
7566 return false;
7568 Expression* arg = this->one_arg();
7569 if (arg == NULL)
7570 return false;
7571 Type* arg_type = arg->type();
7573 if (arg_type->points_to() != NULL
7574 && arg_type->points_to()->array_type() != NULL
7575 && !arg_type->points_to()->is_slice_type())
7576 arg_type = arg_type->points_to();
7578 // The len and cap functions are only constant if there are no
7579 // function calls or channel operations in the arguments.
7580 // Otherwise we have to make the call.
7581 if (!arg->is_constant())
7583 Find_call_expression find_call;
7584 Expression::traverse(&arg, &find_call);
7585 if (find_call.found())
7586 return false;
7589 if (arg_type->array_type() != NULL
7590 && arg_type->array_type()->length() != NULL)
7591 return true;
7593 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7595 this->seen_ = true;
7596 bool ret = arg->is_constant();
7597 this->seen_ = false;
7598 return ret;
7601 break;
7603 case BUILTIN_SIZEOF:
7604 case BUILTIN_ALIGNOF:
7605 return this->one_arg() != NULL;
7607 case BUILTIN_OFFSETOF:
7609 Expression* arg = this->one_arg();
7610 if (arg == NULL)
7611 return false;
7612 return arg->field_reference_expression() != NULL;
7615 case BUILTIN_COMPLEX:
7617 const Expression_list* args = this->args();
7618 if (args != NULL && args->size() == 2)
7619 return args->front()->is_constant() && args->back()->is_constant();
7621 break;
7623 case BUILTIN_REAL:
7624 case BUILTIN_IMAG:
7626 Expression* arg = this->one_arg();
7627 return arg != NULL && arg->is_constant();
7630 default:
7631 break;
7634 return false;
7637 // Return a numeric constant if possible.
7639 bool
7640 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7642 if (this->code_ == BUILTIN_LEN
7643 || this->code_ == BUILTIN_CAP)
7645 Expression* arg = this->one_arg();
7646 if (arg == NULL)
7647 return false;
7648 Type* arg_type = arg->type();
7650 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7652 std::string sval;
7653 if (arg->string_constant_value(&sval))
7655 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7656 sval.length());
7657 return true;
7661 if (arg_type->points_to() != NULL
7662 && arg_type->points_to()->array_type() != NULL
7663 && !arg_type->points_to()->is_slice_type())
7664 arg_type = arg_type->points_to();
7666 if (arg_type->array_type() != NULL
7667 && arg_type->array_type()->length() != NULL)
7669 if (this->seen_)
7670 return false;
7671 Expression* e = arg_type->array_type()->length();
7672 this->seen_ = true;
7673 bool r = e->numeric_constant_value(nc);
7674 this->seen_ = false;
7675 if (r)
7677 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7678 this->location()))
7679 r = false;
7681 return r;
7684 else if (this->code_ == BUILTIN_SIZEOF
7685 || this->code_ == BUILTIN_ALIGNOF)
7687 Expression* arg = this->one_arg();
7688 if (arg == NULL)
7689 return false;
7690 Type* arg_type = arg->type();
7691 if (arg_type->is_error())
7692 return false;
7693 if (arg_type->is_abstract())
7694 return false;
7695 if (this->seen_)
7696 return false;
7698 unsigned int ret;
7699 if (this->code_ == BUILTIN_SIZEOF)
7701 this->seen_ = true;
7702 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7703 this->seen_ = false;
7704 if (!ok)
7705 return false;
7707 else if (this->code_ == BUILTIN_ALIGNOF)
7709 bool ok;
7710 this->seen_ = true;
7711 if (arg->field_reference_expression() == NULL)
7712 ok = arg_type->backend_type_align(this->gogo_, &ret);
7713 else
7715 // Calling unsafe.Alignof(s.f) returns the alignment of
7716 // the type of f when it is used as a field in a struct.
7717 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7719 this->seen_ = false;
7720 if (!ok)
7721 return false;
7723 else
7724 go_unreachable();
7726 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7727 static_cast<unsigned long>(ret));
7728 return true;
7730 else if (this->code_ == BUILTIN_OFFSETOF)
7732 Expression* arg = this->one_arg();
7733 if (arg == NULL)
7734 return false;
7735 Field_reference_expression* farg = arg->field_reference_expression();
7736 if (farg == NULL)
7737 return false;
7738 if (this->seen_)
7739 return false;
7741 unsigned int total_offset = 0;
7742 while (true)
7744 Expression* struct_expr = farg->expr();
7745 Type* st = struct_expr->type();
7746 if (st->struct_type() == NULL)
7747 return false;
7748 if (st->named_type() != NULL)
7749 st->named_type()->convert(this->gogo_);
7750 unsigned int offset;
7751 this->seen_ = true;
7752 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7753 farg->field_index(),
7754 &offset);
7755 this->seen_ = false;
7756 if (!ok)
7757 return false;
7758 total_offset += offset;
7759 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7761 // Go up until we reach the original base.
7762 farg = struct_expr->field_reference_expression();
7763 continue;
7765 break;
7767 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7768 static_cast<unsigned long>(total_offset));
7769 return true;
7771 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7773 Expression* arg = this->one_arg();
7774 if (arg == NULL)
7775 return false;
7777 Numeric_constant argnc;
7778 if (!arg->numeric_constant_value(&argnc))
7779 return false;
7781 mpfr_t real;
7782 mpfr_t imag;
7783 if (!argnc.to_complex(&real, &imag))
7784 return false;
7786 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7787 if (this->code_ == BUILTIN_REAL)
7788 nc->set_float(type, real);
7789 else
7790 nc->set_float(type, imag);
7791 return true;
7793 else if (this->code_ == BUILTIN_COMPLEX)
7795 const Expression_list* args = this->args();
7796 if (args == NULL || args->size() != 2)
7797 return false;
7799 Numeric_constant rnc;
7800 if (!args->front()->numeric_constant_value(&rnc))
7801 return false;
7802 Numeric_constant inc;
7803 if (!args->back()->numeric_constant_value(&inc))
7804 return false;
7806 if (rnc.type() != NULL
7807 && !rnc.type()->is_abstract()
7808 && inc.type() != NULL
7809 && !inc.type()->is_abstract()
7810 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7811 return false;
7813 mpfr_t r;
7814 if (!rnc.to_float(&r))
7815 return false;
7816 mpfr_t i;
7817 if (!inc.to_float(&i))
7819 mpfr_clear(r);
7820 return false;
7823 Type* arg_type = rnc.type();
7824 if (arg_type == NULL || arg_type->is_abstract())
7825 arg_type = inc.type();
7827 Type* type = Builtin_call_expression::complex_type(arg_type);
7828 nc->set_complex(type, r, i);
7830 mpfr_clear(r);
7831 mpfr_clear(i);
7833 return true;
7836 return false;
7839 // Give an error if we are discarding the value of an expression which
7840 // should not normally be discarded. We don't give an error for
7841 // discarding the value of an ordinary function call, but we do for
7842 // builtin functions, purely for consistency with the gc compiler.
7844 bool
7845 Builtin_call_expression::do_discarding_value()
7847 switch (this->code_)
7849 case BUILTIN_INVALID:
7850 default:
7851 go_unreachable();
7853 case BUILTIN_APPEND:
7854 case BUILTIN_CAP:
7855 case BUILTIN_COMPLEX:
7856 case BUILTIN_IMAG:
7857 case BUILTIN_LEN:
7858 case BUILTIN_MAKE:
7859 case BUILTIN_NEW:
7860 case BUILTIN_REAL:
7861 case BUILTIN_ALIGNOF:
7862 case BUILTIN_OFFSETOF:
7863 case BUILTIN_SIZEOF:
7864 this->unused_value_error();
7865 return false;
7867 case BUILTIN_CLOSE:
7868 case BUILTIN_COPY:
7869 case BUILTIN_DELETE:
7870 case BUILTIN_PANIC:
7871 case BUILTIN_PRINT:
7872 case BUILTIN_PRINTLN:
7873 case BUILTIN_RECOVER:
7874 return true;
7878 // Return the type.
7880 Type*
7881 Builtin_call_expression::do_type()
7883 switch (this->code_)
7885 case BUILTIN_INVALID:
7886 default:
7887 go_unreachable();
7889 case BUILTIN_NEW:
7890 case BUILTIN_MAKE:
7892 const Expression_list* args = this->args();
7893 if (args == NULL || args->empty())
7894 return Type::make_error_type();
7895 return Type::make_pointer_type(args->front()->type());
7898 case BUILTIN_CAP:
7899 case BUILTIN_COPY:
7900 case BUILTIN_LEN:
7901 return Type::lookup_integer_type("int");
7903 case BUILTIN_ALIGNOF:
7904 case BUILTIN_OFFSETOF:
7905 case BUILTIN_SIZEOF:
7906 return Type::lookup_integer_type("uintptr");
7908 case BUILTIN_CLOSE:
7909 case BUILTIN_DELETE:
7910 case BUILTIN_PANIC:
7911 case BUILTIN_PRINT:
7912 case BUILTIN_PRINTLN:
7913 return Type::make_void_type();
7915 case BUILTIN_RECOVER:
7916 return Type::make_empty_interface_type(Linemap::predeclared_location());
7918 case BUILTIN_APPEND:
7920 const Expression_list* args = this->args();
7921 if (args == NULL || args->empty())
7922 return Type::make_error_type();
7923 Type *ret = args->front()->type();
7924 if (!ret->is_slice_type())
7925 return Type::make_error_type();
7926 return ret;
7929 case BUILTIN_REAL:
7930 case BUILTIN_IMAG:
7932 Expression* arg = this->one_arg();
7933 if (arg == NULL)
7934 return Type::make_error_type();
7935 Type* t = arg->type();
7936 if (t->is_abstract())
7937 t = t->make_non_abstract_type();
7938 t = Builtin_call_expression::real_imag_type(t);
7939 if (t == NULL)
7940 t = Type::make_error_type();
7941 return t;
7944 case BUILTIN_COMPLEX:
7946 const Expression_list* args = this->args();
7947 if (args == NULL || args->size() != 2)
7948 return Type::make_error_type();
7949 Type* t = args->front()->type();
7950 if (t->is_abstract())
7952 t = args->back()->type();
7953 if (t->is_abstract())
7954 t = t->make_non_abstract_type();
7956 t = Builtin_call_expression::complex_type(t);
7957 if (t == NULL)
7958 t = Type::make_error_type();
7959 return t;
7964 // Determine the type.
7966 void
7967 Builtin_call_expression::do_determine_type(const Type_context* context)
7969 if (!this->determining_types())
7970 return;
7972 this->fn()->determine_type_no_context();
7974 const Expression_list* args = this->args();
7976 bool is_print;
7977 Type* arg_type = NULL;
7978 switch (this->code_)
7980 case BUILTIN_PRINT:
7981 case BUILTIN_PRINTLN:
7982 // Do not force a large integer constant to "int".
7983 is_print = true;
7984 break;
7986 case BUILTIN_REAL:
7987 case BUILTIN_IMAG:
7988 arg_type = Builtin_call_expression::complex_type(context->type);
7989 if (arg_type == NULL)
7990 arg_type = Type::lookup_complex_type("complex128");
7991 is_print = false;
7992 break;
7994 case BUILTIN_COMPLEX:
7996 // For the complex function the type of one operand can
7997 // determine the type of the other, as in a binary expression.
7998 arg_type = Builtin_call_expression::real_imag_type(context->type);
7999 if (arg_type == NULL)
8000 arg_type = Type::lookup_float_type("float64");
8001 if (args != NULL && args->size() == 2)
8003 Type* t1 = args->front()->type();
8004 Type* t2 = args->back()->type();
8005 if (!t1->is_abstract())
8006 arg_type = t1;
8007 else if (!t2->is_abstract())
8008 arg_type = t2;
8010 is_print = false;
8012 break;
8014 default:
8015 is_print = false;
8016 break;
8019 if (args != NULL)
8021 for (Expression_list::const_iterator pa = args->begin();
8022 pa != args->end();
8023 ++pa)
8025 Type_context subcontext;
8026 subcontext.type = arg_type;
8028 if (is_print)
8030 // We want to print large constants, we so can't just
8031 // use the appropriate nonabstract type. Use uint64 for
8032 // an integer if we know it is nonnegative, otherwise
8033 // use int64 for a integer, otherwise use float64 for a
8034 // float or complex128 for a complex.
8035 Type* want_type = NULL;
8036 Type* atype = (*pa)->type();
8037 if (atype->is_abstract())
8039 if (atype->integer_type() != NULL)
8041 Numeric_constant nc;
8042 if (this->numeric_constant_value(&nc))
8044 mpz_t val;
8045 if (nc.to_int(&val))
8047 if (mpz_sgn(val) >= 0)
8048 want_type = Type::lookup_integer_type("uint64");
8049 mpz_clear(val);
8052 if (want_type == NULL)
8053 want_type = Type::lookup_integer_type("int64");
8055 else if (atype->float_type() != NULL)
8056 want_type = Type::lookup_float_type("float64");
8057 else if (atype->complex_type() != NULL)
8058 want_type = Type::lookup_complex_type("complex128");
8059 else if (atype->is_abstract_string_type())
8060 want_type = Type::lookup_string_type();
8061 else if (atype->is_abstract_boolean_type())
8062 want_type = Type::lookup_bool_type();
8063 else
8064 go_unreachable();
8065 subcontext.type = want_type;
8069 (*pa)->determine_type(&subcontext);
8074 // If there is exactly one argument, return true. Otherwise give an
8075 // error message and return false.
8077 bool
8078 Builtin_call_expression::check_one_arg()
8080 const Expression_list* args = this->args();
8081 if (args == NULL || args->size() < 1)
8083 this->report_error(_("not enough arguments"));
8084 return false;
8086 else if (args->size() > 1)
8088 this->report_error(_("too many arguments"));
8089 return false;
8091 if (args->front()->is_error_expression()
8092 || args->front()->type()->is_error())
8094 this->set_is_error();
8095 return false;
8097 return true;
8100 // Check argument types for a builtin function.
8102 void
8103 Builtin_call_expression::do_check_types(Gogo*)
8105 if (this->is_error_expression())
8106 return;
8107 switch (this->code_)
8109 case BUILTIN_INVALID:
8110 case BUILTIN_NEW:
8111 case BUILTIN_MAKE:
8112 case BUILTIN_DELETE:
8113 return;
8115 case BUILTIN_LEN:
8116 case BUILTIN_CAP:
8118 // The single argument may be either a string or an array or a
8119 // map or a channel, or a pointer to a closed array.
8120 if (this->check_one_arg())
8122 Type* arg_type = this->one_arg()->type();
8123 if (arg_type->points_to() != NULL
8124 && arg_type->points_to()->array_type() != NULL
8125 && !arg_type->points_to()->is_slice_type())
8126 arg_type = arg_type->points_to();
8127 if (this->code_ == BUILTIN_CAP)
8129 if (!arg_type->is_error()
8130 && arg_type->array_type() == NULL
8131 && arg_type->channel_type() == NULL)
8132 this->report_error(_("argument must be array or slice "
8133 "or channel"));
8135 else
8137 if (!arg_type->is_error()
8138 && !arg_type->is_string_type()
8139 && arg_type->array_type() == NULL
8140 && arg_type->map_type() == NULL
8141 && arg_type->channel_type() == NULL)
8142 this->report_error(_("argument must be string or "
8143 "array or slice or map or channel"));
8147 break;
8149 case BUILTIN_PRINT:
8150 case BUILTIN_PRINTLN:
8152 const Expression_list* args = this->args();
8153 if (args == NULL)
8155 if (this->code_ == BUILTIN_PRINT)
8156 warning_at(this->location(), 0,
8157 "no arguments for builtin function %<%s%>",
8158 (this->code_ == BUILTIN_PRINT
8159 ? "print"
8160 : "println"));
8162 else
8164 for (Expression_list::const_iterator p = args->begin();
8165 p != args->end();
8166 ++p)
8168 Type* type = (*p)->type();
8169 if (type->is_error()
8170 || type->is_string_type()
8171 || type->integer_type() != NULL
8172 || type->float_type() != NULL
8173 || type->complex_type() != NULL
8174 || type->is_boolean_type()
8175 || type->points_to() != NULL
8176 || type->interface_type() != NULL
8177 || type->channel_type() != NULL
8178 || type->map_type() != NULL
8179 || type->function_type() != NULL
8180 || type->is_slice_type())
8182 else if ((*p)->is_type_expression())
8184 // If this is a type expression it's going to give
8185 // an error anyhow, so we don't need one here.
8187 else
8188 this->report_error(_("unsupported argument type to "
8189 "builtin function"));
8193 break;
8195 case BUILTIN_CLOSE:
8196 if (this->check_one_arg())
8198 if (this->one_arg()->type()->channel_type() == NULL)
8199 this->report_error(_("argument must be channel"));
8200 else if (!this->one_arg()->type()->channel_type()->may_send())
8201 this->report_error(_("cannot close receive-only channel"));
8203 break;
8205 case BUILTIN_PANIC:
8206 case BUILTIN_SIZEOF:
8207 case BUILTIN_ALIGNOF:
8208 this->check_one_arg();
8209 break;
8211 case BUILTIN_RECOVER:
8212 if (this->args() != NULL && !this->args()->empty())
8213 this->report_error(_("too many arguments"));
8214 break;
8216 case BUILTIN_OFFSETOF:
8217 if (this->check_one_arg())
8219 Expression* arg = this->one_arg();
8220 if (arg->field_reference_expression() == NULL)
8221 this->report_error(_("argument must be a field reference"));
8223 break;
8225 case BUILTIN_COPY:
8227 const Expression_list* args = this->args();
8228 if (args == NULL || args->size() < 2)
8230 this->report_error(_("not enough arguments"));
8231 break;
8233 else if (args->size() > 2)
8235 this->report_error(_("too many arguments"));
8236 break;
8238 Type* arg1_type = args->front()->type();
8239 Type* arg2_type = args->back()->type();
8240 if (arg1_type->is_error() || arg2_type->is_error())
8241 break;
8243 Type* e1;
8244 if (arg1_type->is_slice_type())
8245 e1 = arg1_type->array_type()->element_type();
8246 else
8248 this->report_error(_("left argument must be a slice"));
8249 break;
8252 if (arg2_type->is_slice_type())
8254 Type* e2 = arg2_type->array_type()->element_type();
8255 if (!Type::are_identical(e1, e2, true, NULL))
8256 this->report_error(_("element types must be the same"));
8258 else if (arg2_type->is_string_type())
8260 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8261 this->report_error(_("first argument must be []byte"));
8263 else
8264 this->report_error(_("second argument must be slice or string"));
8266 break;
8268 case BUILTIN_APPEND:
8270 const Expression_list* args = this->args();
8271 if (args == NULL || args->size() < 2)
8273 this->report_error(_("not enough arguments"));
8274 break;
8276 if (args->size() > 2)
8278 this->report_error(_("too many arguments"));
8279 break;
8281 if (args->front()->type()->is_error()
8282 || args->back()->type()->is_error())
8283 break;
8285 Array_type* at = args->front()->type()->array_type();
8286 Type* e = at->element_type();
8288 // The language permits appending a string to a []byte, as a
8289 // special case.
8290 if (args->back()->type()->is_string_type())
8292 if (e->integer_type() != NULL && e->integer_type()->is_byte())
8293 break;
8296 // The language says that the second argument must be
8297 // assignable to a slice of the element type of the first
8298 // argument. We already know the first argument is a slice
8299 // type.
8300 Type* arg2_type = Type::make_array_type(e, NULL);
8301 std::string reason;
8302 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8304 if (reason.empty())
8305 this->report_error(_("argument 2 has invalid type"));
8306 else
8308 error_at(this->location(), "argument 2 has invalid type (%s)",
8309 reason.c_str());
8310 this->set_is_error();
8313 break;
8316 case BUILTIN_REAL:
8317 case BUILTIN_IMAG:
8318 if (this->check_one_arg())
8320 if (this->one_arg()->type()->complex_type() == NULL)
8321 this->report_error(_("argument must have complex type"));
8323 break;
8325 case BUILTIN_COMPLEX:
8327 const Expression_list* args = this->args();
8328 if (args == NULL || args->size() < 2)
8329 this->report_error(_("not enough arguments"));
8330 else if (args->size() > 2)
8331 this->report_error(_("too many arguments"));
8332 else if (args->front()->is_error_expression()
8333 || args->front()->type()->is_error()
8334 || args->back()->is_error_expression()
8335 || args->back()->type()->is_error())
8336 this->set_is_error();
8337 else if (!Type::are_identical(args->front()->type(),
8338 args->back()->type(), true, NULL))
8339 this->report_error(_("complex arguments must have identical types"));
8340 else if (args->front()->type()->float_type() == NULL)
8341 this->report_error(_("complex arguments must have "
8342 "floating-point type"));
8344 break;
8346 default:
8347 go_unreachable();
8351 // Return the tree for a builtin function.
8353 tree
8354 Builtin_call_expression::do_get_tree(Translate_context* context)
8356 Gogo* gogo = context->gogo();
8357 Location location = this->location();
8358 switch (this->code_)
8360 case BUILTIN_INVALID:
8361 case BUILTIN_NEW:
8362 case BUILTIN_MAKE:
8363 go_unreachable();
8365 case BUILTIN_LEN:
8366 case BUILTIN_CAP:
8368 const Expression_list* args = this->args();
8369 go_assert(args != NULL && args->size() == 1);
8370 Expression* arg = args->front();
8371 Type* arg_type = arg->type();
8373 if (this->seen_)
8375 go_assert(saw_errors());
8376 return error_mark_node;
8378 this->seen_ = true;
8379 this->seen_ = false;
8380 if (arg_type->points_to() != NULL)
8382 arg_type = arg_type->points_to();
8383 go_assert(arg_type->array_type() != NULL
8384 && !arg_type->is_slice_type());
8385 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8388 Type* int_type = Type::lookup_integer_type("int");
8389 Expression* val;
8390 if (this->code_ == BUILTIN_LEN)
8392 if (arg_type->is_string_type())
8393 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8394 location);
8395 else if (arg_type->array_type() != NULL)
8397 if (this->seen_)
8399 go_assert(saw_errors());
8400 return error_mark_node;
8402 this->seen_ = true;
8403 val = arg_type->array_type()->get_length(gogo, arg);
8404 this->seen_ = false;
8406 else if (arg_type->map_type() != NULL)
8407 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8408 else if (arg_type->channel_type() != NULL)
8409 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8410 else
8411 go_unreachable();
8413 else
8415 if (arg_type->array_type() != NULL)
8417 if (this->seen_)
8419 go_assert(saw_errors());
8420 return error_mark_node;
8422 this->seen_ = true;
8423 val = arg_type->array_type()->get_capacity(gogo, arg);
8424 this->seen_ = false;
8426 else if (arg_type->channel_type() != NULL)
8427 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8428 else
8429 go_unreachable();
8432 return Expression::make_cast(int_type, val,
8433 location)->get_tree(context);
8436 case BUILTIN_PRINT:
8437 case BUILTIN_PRINTLN:
8439 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8440 Expression* print_stmts = NULL;
8442 const Expression_list* call_args = this->args();
8443 if (call_args != NULL)
8445 for (Expression_list::const_iterator p = call_args->begin();
8446 p != call_args->end();
8447 ++p)
8449 if (is_ln && p != call_args->begin())
8451 Expression* print_space =
8452 Runtime::make_call(Runtime::PRINT_SPACE,
8453 this->location(), 0);
8455 print_stmts =
8456 Expression::make_compound(print_stmts, print_space,
8457 location);
8460 Expression* arg = *p;
8461 Type* type = arg->type();
8462 Runtime::Function code;
8463 if (type->is_string_type())
8464 code = Runtime::PRINT_STRING;
8465 else if (type->integer_type() != NULL
8466 && type->integer_type()->is_unsigned())
8468 Type* itype = Type::lookup_integer_type("uint64");
8469 arg = Expression::make_cast(itype, arg, location);
8470 code = Runtime::PRINT_UINT64;
8472 else if (type->integer_type() != NULL)
8474 Type* itype = Type::lookup_integer_type("int64");
8475 arg = Expression::make_cast(itype, arg, location);
8476 code = Runtime::PRINT_INT64;
8478 else if (type->float_type() != NULL)
8480 Type* dtype = Type::lookup_float_type("float64");
8481 arg = Expression::make_cast(dtype, arg, location);
8482 code = Runtime::PRINT_DOUBLE;
8484 else if (type->complex_type() != NULL)
8486 Type* ctype = Type::lookup_complex_type("complex128");
8487 arg = Expression::make_cast(ctype, arg, location);
8488 code = Runtime::PRINT_COMPLEX;
8490 else if (type->is_boolean_type())
8491 code = Runtime::PRINT_BOOL;
8492 else if (type->points_to() != NULL
8493 || type->channel_type() != NULL
8494 || type->map_type() != NULL
8495 || type->function_type() != NULL)
8497 arg = Expression::make_cast(type, arg, location);
8498 code = Runtime::PRINT_POINTER;
8500 else if (type->interface_type() != NULL)
8502 if (type->interface_type()->is_empty())
8503 code = Runtime::PRINT_EMPTY_INTERFACE;
8504 else
8505 code = Runtime::PRINT_INTERFACE;
8507 else if (type->is_slice_type())
8508 code = Runtime::PRINT_SLICE;
8509 else
8511 go_assert(saw_errors());
8512 return error_mark_node;
8515 Expression* call = Runtime::make_call(code, location, 1, arg);
8516 if (print_stmts == NULL)
8517 print_stmts = call;
8518 else
8519 print_stmts = Expression::make_compound(print_stmts, call,
8520 location);
8524 if (is_ln)
8526 Expression* print_nl =
8527 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8528 if (print_stmts == NULL)
8529 print_stmts = print_nl;
8530 else
8531 print_stmts = Expression::make_compound(print_stmts, print_nl,
8532 location);
8535 return print_stmts->get_tree(context);
8538 case BUILTIN_PANIC:
8540 const Expression_list* args = this->args();
8541 go_assert(args != NULL && args->size() == 1);
8542 Expression* arg = args->front();
8543 Type *empty =
8544 Type::make_empty_interface_type(Linemap::predeclared_location());
8545 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8547 Expression* panic =
8548 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8549 return panic->get_tree(context);
8552 case BUILTIN_RECOVER:
8554 // The argument is set when building recover thunks. It's a
8555 // boolean value which is true if we can recover a value now.
8556 const Expression_list* args = this->args();
8557 go_assert(args != NULL && args->size() == 1);
8558 Expression* arg = args->front();
8559 Type *empty =
8560 Type::make_empty_interface_type(Linemap::predeclared_location());
8562 Expression* nil = Expression::make_nil(location);
8563 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8565 // We need to handle a deferred call to recover specially,
8566 // because it changes whether it can recover a panic or not.
8567 // See test7 in test/recover1.go.
8568 Expression* recover = Runtime::make_call((this->is_deferred()
8569 ? Runtime::DEFERRED_RECOVER
8570 : Runtime::RECOVER),
8571 location, 0);
8572 Expression* cond =
8573 Expression::make_conditional(arg, recover, nil, location);
8574 return cond->get_tree(context);
8577 case BUILTIN_CLOSE:
8579 const Expression_list* args = this->args();
8580 go_assert(args != NULL && args->size() == 1);
8581 Expression* arg = args->front();
8582 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8583 1, arg);
8584 return close->get_tree(context);
8587 case BUILTIN_SIZEOF:
8588 case BUILTIN_OFFSETOF:
8589 case BUILTIN_ALIGNOF:
8591 Numeric_constant nc;
8592 unsigned long val;
8593 if (!this->numeric_constant_value(&nc)
8594 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8596 go_assert(saw_errors());
8597 return error_mark_node;
8599 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8600 mpz_t ival;
8601 nc.get_int(&ival);
8602 Expression* int_cst =
8603 Expression::make_integer(&ival, uintptr_type, location);
8604 mpz_clear(ival);
8605 return int_cst->get_tree(context);
8608 case BUILTIN_COPY:
8610 const Expression_list* args = this->args();
8611 go_assert(args != NULL && args->size() == 2);
8612 Expression* arg1 = args->front();
8613 Expression* arg2 = args->back();
8615 Type* arg1_type = arg1->type();
8616 Array_type* at = arg1_type->array_type();
8617 go_assert(arg1->is_variable());
8618 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8619 Expression* arg1_len = at->get_length(gogo, arg1);
8621 Type* arg2_type = arg2->type();
8622 go_assert(arg2->is_variable());
8623 Expression* arg2_val;
8624 Expression* arg2_len;
8625 if (arg2_type->is_slice_type())
8627 at = arg2_type->array_type();
8628 arg2_val = at->get_value_pointer(gogo, arg2);
8629 arg2_len = at->get_length(gogo, arg2);
8631 else
8633 go_assert(arg2->is_variable());
8634 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8635 location);
8636 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8637 location);
8639 Expression* cond =
8640 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8641 Expression* length =
8642 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8644 Type* element_type = at->element_type();
8645 Btype* element_btype = element_type->get_backend(gogo);
8647 mpz_t size;
8648 size_t element_size = gogo->backend()->type_size(element_btype);
8649 mpz_init_set_ui(size, element_size);
8650 Expression* size_expr = Expression::make_integer(&size, length->type(), location);
8651 mpz_clear(size);
8653 Expression* bytecount =
8654 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8655 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8656 arg1_val, arg2_val, bytecount);
8658 Expression* compound = Expression::make_compound(copy, length, location);
8659 return compound->get_tree(context);
8662 case BUILTIN_APPEND:
8664 const Expression_list* args = this->args();
8665 go_assert(args != NULL && args->size() == 2);
8666 Expression* arg1 = args->front();
8667 Expression* arg2 = args->back();
8669 Array_type* at = arg1->type()->array_type();
8670 Type* element_type = at->element_type()->forwarded();
8672 go_assert(arg2->is_variable());
8673 Expression* arg2_val;
8674 Expression* arg2_len;
8675 mpz_t size;
8676 if (arg2->type()->is_string_type()
8677 && element_type->integer_type() != NULL
8678 && element_type->integer_type()->is_byte())
8680 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8681 location);
8682 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8683 location);
8684 mpz_init_set_ui(size, 1UL);
8686 else
8688 arg2_val = at->get_value_pointer(gogo, arg2);
8689 arg2_len = at->get_length(gogo, arg2);
8690 Btype* element_btype = element_type->get_backend(gogo);
8691 size_t element_size = gogo->backend()->type_size(element_btype);
8692 mpz_init_set_ui(size, element_size);
8694 Expression* element_size =
8695 Expression::make_integer(&size, NULL, location);
8696 mpz_clear(size);
8698 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8699 arg1, arg2_val, arg2_len,
8700 element_size);
8701 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8702 return append->get_tree(context);
8705 case BUILTIN_REAL:
8706 case BUILTIN_IMAG:
8708 const Expression_list* args = this->args();
8709 go_assert(args != NULL && args->size() == 1);
8710 Expression* arg = args->front();
8712 Bexpression* ret;
8713 Bexpression* bcomplex = tree_to_expr(arg->get_tree(context));
8714 if (this->code_ == BUILTIN_REAL)
8715 ret = gogo->backend()->real_part_expression(bcomplex, location);
8716 else
8717 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8718 return expr_to_tree(ret);
8721 case BUILTIN_COMPLEX:
8723 const Expression_list* args = this->args();
8724 go_assert(args != NULL && args->size() == 2);
8725 Bexpression* breal = tree_to_expr(args->front()->get_tree(context));
8726 Bexpression* bimag = tree_to_expr(args->back()->get_tree(context));
8727 Bexpression* ret =
8728 gogo->backend()->complex_expression(breal, bimag, location);
8729 return expr_to_tree(ret);
8732 default:
8733 go_unreachable();
8737 // We have to support exporting a builtin call expression, because
8738 // code can set a constant to the result of a builtin expression.
8740 void
8741 Builtin_call_expression::do_export(Export* exp) const
8743 Numeric_constant nc;
8744 if (!this->numeric_constant_value(&nc))
8746 error_at(this->location(), "value is not constant");
8747 return;
8750 if (nc.is_int())
8752 mpz_t val;
8753 nc.get_int(&val);
8754 Integer_expression::export_integer(exp, val);
8755 mpz_clear(val);
8757 else if (nc.is_float())
8759 mpfr_t fval;
8760 nc.get_float(&fval);
8761 Float_expression::export_float(exp, fval);
8762 mpfr_clear(fval);
8764 else if (nc.is_complex())
8766 mpfr_t real;
8767 mpfr_t imag;
8768 Complex_expression::export_complex(exp, real, imag);
8769 mpfr_clear(real);
8770 mpfr_clear(imag);
8772 else
8773 go_unreachable();
8775 // A trailing space lets us reliably identify the end of the number.
8776 exp->write_c_string(" ");
8779 // Class Call_expression.
8781 // A Go function can be viewed in a couple of different ways. The
8782 // code of a Go function becomes a backend function with parameters
8783 // whose types are simply the backend representation of the Go types.
8784 // If there are multiple results, they are returned as a backend
8785 // struct.
8787 // However, when Go code refers to a function other than simply
8788 // calling it, the backend type of that function is actually a struct.
8789 // The first field of the struct points to the Go function code
8790 // (sometimes a wrapper as described below). The remaining fields
8791 // hold addresses of closed-over variables. This struct is called a
8792 // closure.
8794 // There are a few cases to consider.
8796 // A direct function call of a known function in package scope. In
8797 // this case there are no closed-over variables, and we know the name
8798 // of the function code. We can simply produce a backend call to the
8799 // function directly, and not worry about the closure.
8801 // A direct function call of a known function literal. In this case
8802 // we know the function code and we know the closure. We generate the
8803 // function code such that it expects an additional final argument of
8804 // the closure type. We pass the closure as the last argument, after
8805 // the other arguments.
8807 // An indirect function call. In this case we have a closure. We
8808 // load the pointer to the function code from the first field of the
8809 // closure. We pass the address of the closure as the last argument.
8811 // A call to a method of an interface. Type methods are always at
8812 // package scope, so we call the function directly, and don't worry
8813 // about the closure.
8815 // This means that for a function at package scope we have two cases.
8816 // One is the direct call, which has no closure. The other is the
8817 // indirect call, which does have a closure. We can't simply ignore
8818 // the closure, even though it is the last argument, because that will
8819 // fail on targets where the function pops its arguments. So when
8820 // generating a closure for a package-scope function we set the
8821 // function code pointer in the closure to point to a wrapper
8822 // function. This wrapper function accepts a final argument that
8823 // points to the closure, ignores it, and calls the real function as a
8824 // direct function call. This wrapper will normally be efficient, and
8825 // can often simply be a tail call to the real function.
8827 // We don't use GCC's static chain pointer because 1) we don't need
8828 // it; 2) GCC only permits using a static chain to call a known
8829 // function, so we can't use it for an indirect call anyhow. Since we
8830 // can't use it for an indirect call, we may as well not worry about
8831 // using it for a direct call either.
8833 // We pass the closure last rather than first because it means that
8834 // the function wrapper we put into a closure for a package-scope
8835 // function can normally just be a tail call to the real function.
8837 // For method expressions we generate a wrapper that loads the
8838 // receiver from the closure and then calls the method. This
8839 // unfortunately forces reshuffling the arguments, since there is a
8840 // new first argument, but we can't avoid reshuffling either for
8841 // method expressions or for indirect calls of package-scope
8842 // functions, and since the latter are more common we reshuffle for
8843 // method expressions.
8845 // Note that the Go code retains the Go types. The extra final
8846 // argument only appears when we convert to the backend
8847 // representation.
8849 // Traversal.
8852 Call_expression::do_traverse(Traverse* traverse)
8854 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8855 return TRAVERSE_EXIT;
8856 if (this->args_ != NULL)
8858 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8859 return TRAVERSE_EXIT;
8861 return TRAVERSE_CONTINUE;
8864 // Lower a call statement.
8866 Expression*
8867 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8868 Statement_inserter* inserter, int)
8870 Location loc = this->location();
8872 // A type cast can look like a function call.
8873 if (this->fn_->is_type_expression()
8874 && this->args_ != NULL
8875 && this->args_->size() == 1)
8876 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8877 loc);
8879 // Because do_type will return an error type and thus prevent future
8880 // errors, check for that case now to ensure that the error gets
8881 // reported.
8882 Function_type* fntype = this->get_function_type();
8883 if (fntype == NULL)
8885 if (!this->fn_->type()->is_error())
8886 this->report_error(_("expected function"));
8887 return Expression::make_error(loc);
8890 // Handle an argument which is a call to a function which returns
8891 // multiple results.
8892 if (this->args_ != NULL
8893 && this->args_->size() == 1
8894 && this->args_->front()->call_expression() != NULL)
8896 size_t rc = this->args_->front()->call_expression()->result_count();
8897 if (rc > 1
8898 && ((fntype->parameters() != NULL
8899 && (fntype->parameters()->size() == rc
8900 || (fntype->is_varargs()
8901 && fntype->parameters()->size() - 1 <= rc)))
8902 || fntype->is_builtin()))
8904 Call_expression* call = this->args_->front()->call_expression();
8905 Expression_list* args = new Expression_list;
8906 for (size_t i = 0; i < rc; ++i)
8907 args->push_back(Expression::make_call_result(call, i));
8908 // We can't return a new call expression here, because this
8909 // one may be referenced by Call_result expressions. We
8910 // also can't delete the old arguments, because we may still
8911 // traverse them somewhere up the call stack. FIXME.
8912 this->args_ = args;
8916 // Recognize a call to a builtin function.
8917 if (fntype->is_builtin())
8918 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8919 this->is_varargs_, loc);
8921 // If this call returns multiple results, create a temporary
8922 // variable for each result.
8923 size_t rc = this->result_count();
8924 if (rc > 1 && this->results_ == NULL)
8926 std::vector<Temporary_statement*>* temps =
8927 new std::vector<Temporary_statement*>;
8928 temps->reserve(rc);
8929 const Typed_identifier_list* results = fntype->results();
8930 for (Typed_identifier_list::const_iterator p = results->begin();
8931 p != results->end();
8932 ++p)
8934 Temporary_statement* temp = Statement::make_temporary(p->type(),
8935 NULL, loc);
8936 inserter->insert(temp);
8937 temps->push_back(temp);
8939 this->results_ = temps;
8942 // Handle a call to a varargs function by packaging up the extra
8943 // parameters.
8944 if (fntype->is_varargs())
8946 const Typed_identifier_list* parameters = fntype->parameters();
8947 go_assert(parameters != NULL && !parameters->empty());
8948 Type* varargs_type = parameters->back().type();
8949 this->lower_varargs(gogo, function, inserter, varargs_type,
8950 parameters->size());
8953 // If this is call to a method, call the method directly passing the
8954 // object as the first parameter.
8955 Bound_method_expression* bme = this->fn_->bound_method_expression();
8956 if (bme != NULL)
8958 Named_object* methodfn = bme->function();
8959 Expression* first_arg = bme->first_argument();
8961 // We always pass a pointer when calling a method.
8962 if (first_arg->type()->points_to() == NULL
8963 && !first_arg->type()->is_error())
8965 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8966 // We may need to create a temporary variable so that we can
8967 // take the address. We can't do that here because it will
8968 // mess up the order of evaluation.
8969 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8970 ue->set_create_temp();
8973 // If we are calling a method which was inherited from an
8974 // embedded struct, and the method did not get a stub, then the
8975 // first type may be wrong.
8976 Type* fatype = bme->first_argument_type();
8977 if (fatype != NULL)
8979 if (fatype->points_to() == NULL)
8980 fatype = Type::make_pointer_type(fatype);
8981 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8984 Expression_list* new_args = new Expression_list();
8985 new_args->push_back(first_arg);
8986 if (this->args_ != NULL)
8988 for (Expression_list::const_iterator p = this->args_->begin();
8989 p != this->args_->end();
8990 ++p)
8991 new_args->push_back(*p);
8994 // We have to change in place because this structure may be
8995 // referenced by Call_result_expressions. We can't delete the
8996 // old arguments, because we may be traversing them up in some
8997 // caller. FIXME.
8998 this->args_ = new_args;
8999 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9000 bme->location());
9003 return this;
9006 // Lower a call to a varargs function. FUNCTION is the function in
9007 // which the call occurs--it's not the function we are calling.
9008 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9009 // PARAM_COUNT is the number of parameters of the function we are
9010 // calling; the last of these parameters will be the varargs
9011 // parameter.
9013 void
9014 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9015 Statement_inserter* inserter,
9016 Type* varargs_type, size_t param_count)
9018 if (this->varargs_are_lowered_)
9019 return;
9021 Location loc = this->location();
9023 go_assert(param_count > 0);
9024 go_assert(varargs_type->is_slice_type());
9026 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9027 if (arg_count < param_count - 1)
9029 // Not enough arguments; will be caught in check_types.
9030 return;
9033 Expression_list* old_args = this->args_;
9034 Expression_list* new_args = new Expression_list();
9035 bool push_empty_arg = false;
9036 if (old_args == NULL || old_args->empty())
9038 go_assert(param_count == 1);
9039 push_empty_arg = true;
9041 else
9043 Expression_list::const_iterator pa;
9044 int i = 1;
9045 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9047 if (static_cast<size_t>(i) == param_count)
9048 break;
9049 new_args->push_back(*pa);
9052 // We have reached the varargs parameter.
9054 bool issued_error = false;
9055 if (pa == old_args->end())
9056 push_empty_arg = true;
9057 else if (pa + 1 == old_args->end() && this->is_varargs_)
9058 new_args->push_back(*pa);
9059 else if (this->is_varargs_)
9061 if ((*pa)->type()->is_slice_type())
9062 this->report_error(_("too many arguments"));
9063 else
9065 error_at(this->location(),
9066 _("invalid use of %<...%> with non-slice"));
9067 this->set_is_error();
9069 return;
9071 else
9073 Type* element_type = varargs_type->array_type()->element_type();
9074 Expression_list* vals = new Expression_list;
9075 for (; pa != old_args->end(); ++pa, ++i)
9077 // Check types here so that we get a better message.
9078 Type* patype = (*pa)->type();
9079 Location paloc = (*pa)->location();
9080 if (!this->check_argument_type(i, element_type, patype,
9081 paloc, issued_error))
9082 continue;
9083 vals->push_back(*pa);
9085 Expression* val =
9086 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9087 gogo->lower_expression(function, inserter, &val);
9088 new_args->push_back(val);
9092 if (push_empty_arg)
9093 new_args->push_back(Expression::make_nil(loc));
9095 // We can't return a new call expression here, because this one may
9096 // be referenced by Call_result expressions. FIXME. We can't
9097 // delete OLD_ARGS because we may have both a Call_expression and a
9098 // Builtin_call_expression which refer to them. FIXME.
9099 this->args_ = new_args;
9100 this->varargs_are_lowered_ = true;
9103 // Flatten a call with multiple results into a temporary.
9105 Expression*
9106 Call_expression::do_flatten(Gogo*, Named_object*, Statement_inserter* inserter)
9108 size_t rc = this->result_count();
9109 if (rc > 1 && this->call_temp_ == NULL)
9111 Struct_field_list* sfl = new Struct_field_list();
9112 Function_type* fntype = this->get_function_type();
9113 const Typed_identifier_list* results = fntype->results();
9114 Location loc = this->location();
9116 int i = 0;
9117 char buf[10];
9118 for (Typed_identifier_list::const_iterator p = results->begin();
9119 p != results->end();
9120 ++p, ++i)
9122 snprintf(buf, sizeof buf, "res%d", i);
9123 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9126 Struct_type* st = Type::make_struct_type(sfl, loc);
9127 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9128 inserter->insert(this->call_temp_);
9131 return this;
9134 // Get the function type. This can return NULL in error cases.
9136 Function_type*
9137 Call_expression::get_function_type() const
9139 return this->fn_->type()->function_type();
9142 // Return the number of values which this call will return.
9144 size_t
9145 Call_expression::result_count() const
9147 const Function_type* fntype = this->get_function_type();
9148 if (fntype == NULL)
9149 return 0;
9150 if (fntype->results() == NULL)
9151 return 0;
9152 return fntype->results()->size();
9155 // Return the temporary which holds a result.
9157 Temporary_statement*
9158 Call_expression::result(size_t i) const
9160 if (this->results_ == NULL || this->results_->size() <= i)
9162 go_assert(saw_errors());
9163 return NULL;
9165 return (*this->results_)[i];
9168 // Return whether this is a call to the predeclared function recover.
9170 bool
9171 Call_expression::is_recover_call() const
9173 return this->do_is_recover_call();
9176 // Set the argument to the recover function.
9178 void
9179 Call_expression::set_recover_arg(Expression* arg)
9181 this->do_set_recover_arg(arg);
9184 // Virtual functions also implemented by Builtin_call_expression.
9186 bool
9187 Call_expression::do_is_recover_call() const
9189 return false;
9192 void
9193 Call_expression::do_set_recover_arg(Expression*)
9195 go_unreachable();
9198 // We have found an error with this call expression; return true if
9199 // we should report it.
9201 bool
9202 Call_expression::issue_error()
9204 if (this->issued_error_)
9205 return false;
9206 else
9208 this->issued_error_ = true;
9209 return true;
9213 // Get the type.
9215 Type*
9216 Call_expression::do_type()
9218 if (this->type_ != NULL)
9219 return this->type_;
9221 Type* ret;
9222 Function_type* fntype = this->get_function_type();
9223 if (fntype == NULL)
9224 return Type::make_error_type();
9226 const Typed_identifier_list* results = fntype->results();
9227 if (results == NULL)
9228 ret = Type::make_void_type();
9229 else if (results->size() == 1)
9230 ret = results->begin()->type();
9231 else
9232 ret = Type::make_call_multiple_result_type(this);
9234 this->type_ = ret;
9236 return this->type_;
9239 // Determine types for a call expression. We can use the function
9240 // parameter types to set the types of the arguments.
9242 void
9243 Call_expression::do_determine_type(const Type_context*)
9245 if (!this->determining_types())
9246 return;
9248 this->fn_->determine_type_no_context();
9249 Function_type* fntype = this->get_function_type();
9250 const Typed_identifier_list* parameters = NULL;
9251 if (fntype != NULL)
9252 parameters = fntype->parameters();
9253 if (this->args_ != NULL)
9255 Typed_identifier_list::const_iterator pt;
9256 if (parameters != NULL)
9257 pt = parameters->begin();
9258 bool first = true;
9259 for (Expression_list::const_iterator pa = this->args_->begin();
9260 pa != this->args_->end();
9261 ++pa)
9263 if (first)
9265 first = false;
9266 // If this is a method, the first argument is the
9267 // receiver.
9268 if (fntype != NULL && fntype->is_method())
9270 Type* rtype = fntype->receiver()->type();
9271 // The receiver is always passed as a pointer.
9272 if (rtype->points_to() == NULL)
9273 rtype = Type::make_pointer_type(rtype);
9274 Type_context subcontext(rtype, false);
9275 (*pa)->determine_type(&subcontext);
9276 continue;
9280 if (parameters != NULL && pt != parameters->end())
9282 Type_context subcontext(pt->type(), false);
9283 (*pa)->determine_type(&subcontext);
9284 ++pt;
9286 else
9287 (*pa)->determine_type_no_context();
9292 // Called when determining types for a Call_expression. Return true
9293 // if we should go ahead, false if they have already been determined.
9295 bool
9296 Call_expression::determining_types()
9298 if (this->types_are_determined_)
9299 return false;
9300 else
9302 this->types_are_determined_ = true;
9303 return true;
9307 // Check types for parameter I.
9309 bool
9310 Call_expression::check_argument_type(int i, const Type* parameter_type,
9311 const Type* argument_type,
9312 Location argument_location,
9313 bool issued_error)
9315 std::string reason;
9316 bool ok;
9317 if (this->are_hidden_fields_ok_)
9318 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9319 &reason);
9320 else
9321 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9322 if (!ok)
9324 if (!issued_error)
9326 if (reason.empty())
9327 error_at(argument_location, "argument %d has incompatible type", i);
9328 else
9329 error_at(argument_location,
9330 "argument %d has incompatible type (%s)",
9331 i, reason.c_str());
9333 this->set_is_error();
9334 return false;
9336 return true;
9339 // Check types.
9341 void
9342 Call_expression::do_check_types(Gogo*)
9344 if (this->classification() == EXPRESSION_ERROR)
9345 return;
9347 Function_type* fntype = this->get_function_type();
9348 if (fntype == NULL)
9350 if (!this->fn_->type()->is_error())
9351 this->report_error(_("expected function"));
9352 return;
9355 bool is_method = fntype->is_method();
9356 if (is_method)
9358 go_assert(this->args_ != NULL && !this->args_->empty());
9359 Type* rtype = fntype->receiver()->type();
9360 Expression* first_arg = this->args_->front();
9361 // The language permits copying hidden fields for a method
9362 // receiver. We dereference the values since receivers are
9363 // always passed as pointers.
9364 std::string reason;
9365 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9366 first_arg->type()->deref(),
9367 &reason))
9369 if (reason.empty())
9370 this->report_error(_("incompatible type for receiver"));
9371 else
9373 error_at(this->location(),
9374 "incompatible type for receiver (%s)",
9375 reason.c_str());
9376 this->set_is_error();
9381 // Note that varargs was handled by the lower_varargs() method, so
9382 // we don't have to worry about it here unless something is wrong.
9383 if (this->is_varargs_ && !this->varargs_are_lowered_)
9385 if (!fntype->is_varargs())
9387 error_at(this->location(),
9388 _("invalid use of %<...%> calling non-variadic function"));
9389 this->set_is_error();
9390 return;
9394 const Typed_identifier_list* parameters = fntype->parameters();
9395 if (this->args_ == NULL)
9397 if (parameters != NULL && !parameters->empty())
9398 this->report_error(_("not enough arguments"));
9400 else if (parameters == NULL)
9402 if (!is_method || this->args_->size() > 1)
9403 this->report_error(_("too many arguments"));
9405 else
9407 int i = 0;
9408 Expression_list::const_iterator pa = this->args_->begin();
9409 if (is_method)
9410 ++pa;
9411 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9412 pt != parameters->end();
9413 ++pt, ++pa, ++i)
9415 if (pa == this->args_->end())
9417 this->report_error(_("not enough arguments"));
9418 return;
9420 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9421 (*pa)->location(), false);
9423 if (pa != this->args_->end())
9424 this->report_error(_("too many arguments"));
9428 // Return whether we have to use a temporary variable to ensure that
9429 // we evaluate this call expression in order. If the call returns no
9430 // results then it will inevitably be executed last.
9432 bool
9433 Call_expression::do_must_eval_in_order() const
9435 return this->result_count() > 0;
9438 // Get the function and the first argument to use when calling an
9439 // interface method.
9441 Expression*
9442 Call_expression::interface_method_function(
9443 Interface_field_reference_expression* interface_method,
9444 Expression** first_arg_ptr)
9446 *first_arg_ptr = interface_method->get_underlying_object();
9447 return interface_method->get_function();
9450 // Build the call expression.
9452 tree
9453 Call_expression::do_get_tree(Translate_context* context)
9455 if (this->call_ != NULL)
9456 return expr_to_tree(this->call_);
9458 Function_type* fntype = this->get_function_type();
9459 if (fntype == NULL)
9460 return error_mark_node;
9462 if (this->fn_->is_error_expression())
9463 return error_mark_node;
9465 Gogo* gogo = context->gogo();
9466 Location location = this->location();
9468 Func_expression* func = this->fn_->func_expression();
9469 Interface_field_reference_expression* interface_method =
9470 this->fn_->interface_field_reference_expression();
9471 const bool has_closure = func != NULL && func->closure() != NULL;
9472 const bool is_interface_method = interface_method != NULL;
9474 bool has_closure_arg;
9475 if (has_closure)
9476 has_closure_arg = true;
9477 else if (func != NULL)
9478 has_closure_arg = false;
9479 else if (is_interface_method)
9480 has_closure_arg = false;
9481 else
9482 has_closure_arg = true;
9484 int nargs;
9485 std::vector<Bexpression*> fn_args;
9486 if (this->args_ == NULL || this->args_->empty())
9488 nargs = is_interface_method ? 1 : 0;
9489 if (nargs > 0)
9490 fn_args.resize(1);
9492 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9494 // Passing a receiver parameter.
9495 go_assert(!is_interface_method
9496 && fntype->is_method()
9497 && this->args_->size() == 1);
9498 nargs = 1;
9499 fn_args.resize(1);
9500 fn_args[0] = tree_to_expr(this->args_->front()->get_tree(context));
9502 else
9504 const Typed_identifier_list* params = fntype->parameters();
9506 nargs = this->args_->size();
9507 int i = is_interface_method ? 1 : 0;
9508 nargs += i;
9509 fn_args.resize(nargs);
9511 Typed_identifier_list::const_iterator pp = params->begin();
9512 Expression_list::const_iterator pe = this->args_->begin();
9513 if (!is_interface_method && fntype->is_method())
9515 fn_args[i] = tree_to_expr((*pe)->get_tree(context));
9516 ++pe;
9517 ++i;
9519 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9521 go_assert(pp != params->end());
9522 Expression* arg =
9523 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9524 location);
9525 fn_args[i] = tree_to_expr(arg->get_tree(context));
9527 go_assert(pp == params->end());
9528 go_assert(i == nargs);
9531 Expression* fn;
9532 Expression* closure = NULL;
9533 if (func != NULL)
9535 Named_object* no = func->named_object();
9536 fn = Expression::make_func_code_reference(no, location);
9537 if (has_closure)
9538 closure = func->closure();
9540 else if (!is_interface_method)
9542 closure = this->fn_;
9544 // The backend representation of this function type is a pointer
9545 // to a struct whose first field is the actual function to call.
9546 Type* pfntype =
9547 Type::make_pointer_type(
9548 Type::make_pointer_type(Type::make_void_type()));
9549 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9550 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9552 else
9554 Expression* first_arg;
9555 fn = this->interface_method_function(interface_method, &first_arg);
9556 fn_args[0] = tree_to_expr(first_arg->get_tree(context));
9559 if (!has_closure_arg)
9560 go_assert(closure == NULL);
9561 else
9563 // Pass the closure argument by calling the function function
9564 // __go_set_closure. In the order_evaluations pass we have
9565 // ensured that if any parameters contain call expressions, they
9566 // will have been moved out to temporary variables.
9567 go_assert(closure != NULL);
9568 Expression* set_closure =
9569 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9570 fn = Expression::make_compound(set_closure, fn, location);
9573 Btype* bft = fntype->get_backend_fntype(gogo);
9574 Bexpression* bfn = tree_to_expr(fn->get_tree(context));
9575 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9576 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
9578 if (this->results_ != NULL)
9580 go_assert(this->call_temp_ != NULL);
9581 Expression* call_ref =
9582 Expression::make_temporary_reference(this->call_temp_, location);
9583 Bexpression* bcall_ref = tree_to_expr(call_ref->get_tree(context));
9584 Bstatement* assn_stmt =
9585 gogo->backend()->assignment_statement(bcall_ref, call, location);
9587 this->call_ = this->set_results(context, bcall_ref);
9589 Bexpression* set_and_call =
9590 gogo->backend()->compound_expression(assn_stmt, this->call_,
9591 location);
9592 return expr_to_tree(set_and_call);
9595 this->call_ = call;
9596 return expr_to_tree(this->call_);
9599 // Set the result variables if this call returns multiple results.
9601 Bexpression*
9602 Call_expression::set_results(Translate_context* context, Bexpression* call)
9604 Gogo* gogo = context->gogo();
9606 Bexpression* results = NULL;
9607 Location loc = this->location();
9609 size_t rc = this->result_count();
9610 for (size_t i = 0; i < rc; ++i)
9612 Temporary_statement* temp = this->result(i);
9613 if (temp == NULL)
9615 go_assert(saw_errors());
9616 return gogo->backend()->error_expression();
9618 Temporary_reference_expression* ref =
9619 Expression::make_temporary_reference(temp, loc);
9620 ref->set_is_lvalue();
9622 Bexpression* result_ref = tree_to_expr(ref->get_tree(context));
9623 Bexpression* call_result =
9624 gogo->backend()->struct_field_expression(call, i, loc);
9625 Bstatement* assn_stmt =
9626 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9628 Bexpression* result =
9629 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9631 if (results == NULL)
9632 results = result;
9633 else
9635 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9636 results =
9637 gogo->backend()->compound_expression(expr_stmt, results, loc);
9640 return results;
9643 // Dump ast representation for a call expressin.
9645 void
9646 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9648 this->fn_->dump_expression(ast_dump_context);
9649 ast_dump_context->ostream() << "(";
9650 if (args_ != NULL)
9651 ast_dump_context->dump_expression_list(this->args_);
9653 ast_dump_context->ostream() << ") ";
9656 // Make a call expression.
9658 Call_expression*
9659 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9660 Location location)
9662 return new Call_expression(fn, args, is_varargs, location);
9665 // A single result from a call which returns multiple results.
9667 class Call_result_expression : public Expression
9669 public:
9670 Call_result_expression(Call_expression* call, unsigned int index)
9671 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9672 call_(call), index_(index)
9675 protected:
9677 do_traverse(Traverse*);
9679 Type*
9680 do_type();
9682 void
9683 do_determine_type(const Type_context*);
9685 void
9686 do_check_types(Gogo*);
9688 Expression*
9689 do_copy()
9691 return new Call_result_expression(this->call_->call_expression(),
9692 this->index_);
9695 bool
9696 do_must_eval_in_order() const
9697 { return true; }
9699 tree
9700 do_get_tree(Translate_context*);
9702 void
9703 do_dump_expression(Ast_dump_context*) const;
9705 private:
9706 // The underlying call expression.
9707 Expression* call_;
9708 // Which result we want.
9709 unsigned int index_;
9712 // Traverse a call result.
9715 Call_result_expression::do_traverse(Traverse* traverse)
9717 if (traverse->remember_expression(this->call_))
9719 // We have already traversed the call expression.
9720 return TRAVERSE_CONTINUE;
9722 return Expression::traverse(&this->call_, traverse);
9725 // Get the type.
9727 Type*
9728 Call_result_expression::do_type()
9730 if (this->classification() == EXPRESSION_ERROR)
9731 return Type::make_error_type();
9733 // THIS->CALL_ can be replaced with a temporary reference due to
9734 // Call_expression::do_must_eval_in_order when there is an error.
9735 Call_expression* ce = this->call_->call_expression();
9736 if (ce == NULL)
9738 this->set_is_error();
9739 return Type::make_error_type();
9741 Function_type* fntype = ce->get_function_type();
9742 if (fntype == NULL)
9744 if (ce->issue_error())
9746 if (!ce->fn()->type()->is_error())
9747 this->report_error(_("expected function"));
9749 this->set_is_error();
9750 return Type::make_error_type();
9752 const Typed_identifier_list* results = fntype->results();
9753 if (results == NULL || results->size() < 2)
9755 if (ce->issue_error())
9756 this->report_error(_("number of results does not match "
9757 "number of values"));
9758 return Type::make_error_type();
9760 Typed_identifier_list::const_iterator pr = results->begin();
9761 for (unsigned int i = 0; i < this->index_; ++i)
9763 if (pr == results->end())
9764 break;
9765 ++pr;
9767 if (pr == results->end())
9769 if (ce->issue_error())
9770 this->report_error(_("number of results does not match "
9771 "number of values"));
9772 return Type::make_error_type();
9774 return pr->type();
9777 // Check the type. Just make sure that we trigger the warning in
9778 // do_type.
9780 void
9781 Call_result_expression::do_check_types(Gogo*)
9783 this->type();
9786 // Determine the type. We have nothing to do here, but the 0 result
9787 // needs to pass down to the caller.
9789 void
9790 Call_result_expression::do_determine_type(const Type_context*)
9792 this->call_->determine_type_no_context();
9795 // Return the tree. We just refer to the temporary set by the call
9796 // expression. We don't do this at lowering time because it makes it
9797 // hard to evaluate the call at the right time.
9799 tree
9800 Call_result_expression::do_get_tree(Translate_context* context)
9802 Call_expression* ce = this->call_->call_expression();
9803 if (ce == NULL)
9805 go_assert(this->call_->is_error_expression());
9806 return error_mark_node;
9808 Temporary_statement* ts = ce->result(this->index_);
9809 if (ts == NULL)
9811 go_assert(saw_errors());
9812 return error_mark_node;
9814 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9815 return ref->get_tree(context);
9818 // Dump ast representation for a call result expression.
9820 void
9821 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9822 const
9824 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9825 // (struct) and the fields are referenced instead.
9826 ast_dump_context->ostream() << this->index_ << "@(";
9827 ast_dump_context->dump_expression(this->call_);
9828 ast_dump_context->ostream() << ")";
9831 // Make a reference to a single result of a call which returns
9832 // multiple results.
9834 Expression*
9835 Expression::make_call_result(Call_expression* call, unsigned int index)
9837 return new Call_result_expression(call, index);
9840 // Class Index_expression.
9842 // Traversal.
9845 Index_expression::do_traverse(Traverse* traverse)
9847 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9848 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9849 || (this->end_ != NULL
9850 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9851 || (this->cap_ != NULL
9852 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9853 return TRAVERSE_EXIT;
9854 return TRAVERSE_CONTINUE;
9857 // Lower an index expression. This converts the generic index
9858 // expression into an array index, a string index, or a map index.
9860 Expression*
9861 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9863 Location location = this->location();
9864 Expression* left = this->left_;
9865 Expression* start = this->start_;
9866 Expression* end = this->end_;
9867 Expression* cap = this->cap_;
9869 Type* type = left->type();
9870 if (type->is_error())
9871 return Expression::make_error(location);
9872 else if (left->is_type_expression())
9874 error_at(location, "attempt to index type expression");
9875 return Expression::make_error(location);
9877 else if (type->array_type() != NULL)
9878 return Expression::make_array_index(left, start, end, cap, location);
9879 else if (type->points_to() != NULL
9880 && type->points_to()->array_type() != NULL
9881 && !type->points_to()->is_slice_type())
9883 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9884 location);
9886 // For an ordinary index into the array, the pointer will be
9887 // dereferenced. For a slice it will not--the resulting slice
9888 // will simply reuse the pointer, which is incorrect if that
9889 // pointer is nil.
9890 if (end != NULL || cap != NULL)
9891 deref->issue_nil_check();
9893 return Expression::make_array_index(deref, start, end, cap, location);
9895 else if (type->is_string_type())
9897 if (cap != NULL)
9899 error_at(location, "invalid 3-index slice of string");
9900 return Expression::make_error(location);
9902 return Expression::make_string_index(left, start, end, location);
9904 else if (type->map_type() != NULL)
9906 if (end != NULL || cap != NULL)
9908 error_at(location, "invalid slice of map");
9909 return Expression::make_error(location);
9911 Map_index_expression* ret = Expression::make_map_index(left, start,
9912 location);
9913 if (this->is_lvalue_)
9914 ret->set_is_lvalue();
9915 return ret;
9917 else
9919 error_at(location,
9920 "attempt to index object which is not array, string, or map");
9921 return Expression::make_error(location);
9925 // Write an indexed expression
9926 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9928 void
9929 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9930 const Expression* expr,
9931 const Expression* start,
9932 const Expression* end,
9933 const Expression* cap)
9935 expr->dump_expression(ast_dump_context);
9936 ast_dump_context->ostream() << "[";
9937 start->dump_expression(ast_dump_context);
9938 if (end != NULL)
9940 ast_dump_context->ostream() << ":";
9941 end->dump_expression(ast_dump_context);
9943 if (cap != NULL)
9945 ast_dump_context->ostream() << ":";
9946 cap->dump_expression(ast_dump_context);
9948 ast_dump_context->ostream() << "]";
9951 // Dump ast representation for an index expression.
9953 void
9954 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9955 const
9957 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9958 this->start_, this->end_, this->cap_);
9961 // Make an index expression.
9963 Expression*
9964 Expression::make_index(Expression* left, Expression* start, Expression* end,
9965 Expression* cap, Location location)
9967 return new Index_expression(left, start, end, cap, location);
9970 // An array index. This is used for both indexing and slicing.
9972 class Array_index_expression : public Expression
9974 public:
9975 Array_index_expression(Expression* array, Expression* start,
9976 Expression* end, Expression* cap, Location location)
9977 : Expression(EXPRESSION_ARRAY_INDEX, location),
9978 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
9981 protected:
9983 do_traverse(Traverse*);
9985 Expression*
9986 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9988 Type*
9989 do_type();
9991 void
9992 do_determine_type(const Type_context*);
9994 void
9995 do_check_types(Gogo*);
9997 Expression*
9998 do_copy()
10000 return Expression::make_array_index(this->array_->copy(),
10001 this->start_->copy(),
10002 (this->end_ == NULL
10003 ? NULL
10004 : this->end_->copy()),
10005 (this->cap_ == NULL
10006 ? NULL
10007 : this->cap_->copy()),
10008 this->location());
10011 bool
10012 do_must_eval_subexpressions_in_order(int* skip) const
10014 *skip = 1;
10015 return true;
10018 bool
10019 do_is_addressable() const;
10021 void
10022 do_address_taken(bool escapes)
10023 { this->array_->address_taken(escapes); }
10025 void
10026 do_issue_nil_check()
10027 { this->array_->issue_nil_check(); }
10029 tree
10030 do_get_tree(Translate_context*);
10032 void
10033 do_dump_expression(Ast_dump_context*) const;
10035 private:
10036 // The array we are getting a value from.
10037 Expression* array_;
10038 // The start or only index.
10039 Expression* start_;
10040 // The end index of a slice. This may be NULL for a simple array
10041 // index, or it may be a nil expression for the length of the array.
10042 Expression* end_;
10043 // The capacity argument of a slice. This may be NULL for an array index or
10044 // slice.
10045 Expression* cap_;
10046 // The type of the expression.
10047 Type* type_;
10050 // Array index traversal.
10053 Array_index_expression::do_traverse(Traverse* traverse)
10055 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10056 return TRAVERSE_EXIT;
10057 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10058 return TRAVERSE_EXIT;
10059 if (this->end_ != NULL)
10061 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10062 return TRAVERSE_EXIT;
10064 if (this->cap_ != NULL)
10066 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10067 return TRAVERSE_EXIT;
10069 return TRAVERSE_CONTINUE;
10072 // Return the type of an array index.
10074 Type*
10075 Array_index_expression::do_type()
10077 if (this->type_ == NULL)
10079 Array_type* type = this->array_->type()->array_type();
10080 if (type == NULL)
10081 this->type_ = Type::make_error_type();
10082 else if (this->end_ == NULL)
10083 this->type_ = type->element_type();
10084 else if (type->is_slice_type())
10086 // A slice of a slice has the same type as the original
10087 // slice.
10088 this->type_ = this->array_->type()->deref();
10090 else
10092 // A slice of an array is a slice.
10093 this->type_ = Type::make_array_type(type->element_type(), NULL);
10096 return this->type_;
10099 // Set the type of an array index.
10101 void
10102 Array_index_expression::do_determine_type(const Type_context*)
10104 this->array_->determine_type_no_context();
10105 this->start_->determine_type_no_context();
10106 if (this->end_ != NULL)
10107 this->end_->determine_type_no_context();
10108 if (this->cap_ != NULL)
10109 this->cap_->determine_type_no_context();
10112 // Check types of an array index.
10114 void
10115 Array_index_expression::do_check_types(Gogo*)
10117 Numeric_constant nc;
10118 unsigned long v;
10119 if (this->start_->type()->integer_type() == NULL
10120 && !this->start_->type()->is_error()
10121 && (!this->start_->numeric_constant_value(&nc)
10122 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10123 this->report_error(_("index must be integer"));
10124 if (this->end_ != NULL
10125 && this->end_->type()->integer_type() == NULL
10126 && !this->end_->type()->is_error()
10127 && !this->end_->is_nil_expression()
10128 && !this->end_->is_error_expression()
10129 && (!this->end_->numeric_constant_value(&nc)
10130 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10131 this->report_error(_("slice end must be integer"));
10132 if (this->cap_ != NULL
10133 && this->cap_->type()->integer_type() == NULL
10134 && !this->cap_->type()->is_error()
10135 && !this->cap_->is_nil_expression()
10136 && !this->cap_->is_error_expression()
10137 && (!this->cap_->numeric_constant_value(&nc)
10138 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10139 this->report_error(_("slice capacity must be integer"));
10141 Array_type* array_type = this->array_->type()->array_type();
10142 if (array_type == NULL)
10144 go_assert(this->array_->type()->is_error());
10145 return;
10148 unsigned int int_bits =
10149 Type::lookup_integer_type("int")->integer_type()->bits();
10151 Numeric_constant lvalnc;
10152 mpz_t lval;
10153 bool lval_valid = (array_type->length() != NULL
10154 && array_type->length()->numeric_constant_value(&lvalnc)
10155 && lvalnc.to_int(&lval));
10156 Numeric_constant inc;
10157 mpz_t ival;
10158 bool ival_valid = false;
10159 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10161 ival_valid = true;
10162 if (mpz_sgn(ival) < 0
10163 || mpz_sizeinbase(ival, 2) >= int_bits
10164 || (lval_valid
10165 && (this->end_ == NULL
10166 ? mpz_cmp(ival, lval) >= 0
10167 : mpz_cmp(ival, lval) > 0)))
10169 error_at(this->start_->location(), "array index out of bounds");
10170 this->set_is_error();
10173 if (this->end_ != NULL && !this->end_->is_nil_expression())
10175 Numeric_constant enc;
10176 mpz_t eval;
10177 bool eval_valid = false;
10178 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10180 eval_valid = true;
10181 if (mpz_sgn(eval) < 0
10182 || mpz_sizeinbase(eval, 2) >= int_bits
10183 || (lval_valid && mpz_cmp(eval, lval) > 0))
10185 error_at(this->end_->location(), "array index out of bounds");
10186 this->set_is_error();
10188 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10189 this->report_error(_("inverted slice range"));
10192 Numeric_constant cnc;
10193 mpz_t cval;
10194 if (this->cap_ != NULL
10195 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10197 if (mpz_sgn(cval) < 0
10198 || mpz_sizeinbase(cval, 2) >= int_bits
10199 || (lval_valid && mpz_cmp(cval, lval) > 0))
10201 error_at(this->cap_->location(), "array index out of bounds");
10202 this->set_is_error();
10204 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10206 error_at(this->cap_->location(),
10207 "invalid slice index: capacity less than start");
10208 this->set_is_error();
10210 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10212 error_at(this->cap_->location(),
10213 "invalid slice index: capacity less than length");
10214 this->set_is_error();
10216 mpz_clear(cval);
10219 if (eval_valid)
10220 mpz_clear(eval);
10222 if (ival_valid)
10223 mpz_clear(ival);
10224 if (lval_valid)
10225 mpz_clear(lval);
10227 // A slice of an array requires an addressable array. A slice of a
10228 // slice is always possible.
10229 if (this->end_ != NULL && !array_type->is_slice_type())
10231 if (!this->array_->is_addressable())
10232 this->report_error(_("slice of unaddressable value"));
10233 else
10234 this->array_->address_taken(true);
10238 // Flatten array indexing by using temporary variables for slices and indexes.
10240 Expression*
10241 Array_index_expression::do_flatten(Gogo*, Named_object*,
10242 Statement_inserter* inserter)
10244 Location loc = this->location();
10245 Temporary_statement* temp;
10246 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10248 temp = Statement::make_temporary(NULL, this->array_, loc);
10249 inserter->insert(temp);
10250 this->array_ = Expression::make_temporary_reference(temp, loc);
10252 if (!this->start_->is_variable())
10254 temp = Statement::make_temporary(NULL, this->start_, loc);
10255 inserter->insert(temp);
10256 this->start_ = Expression::make_temporary_reference(temp, loc);
10258 if (this->end_ != NULL
10259 && !this->end_->is_nil_expression()
10260 && !this->end_->is_variable())
10262 temp = Statement::make_temporary(NULL, this->end_, loc);
10263 inserter->insert(temp);
10264 this->end_ = Expression::make_temporary_reference(temp, loc);
10266 if (this->cap_ != NULL && !this->cap_->is_variable())
10268 temp = Statement::make_temporary(NULL, this->cap_, loc);
10269 inserter->insert(temp);
10270 this->cap_ = Expression::make_temporary_reference(temp, loc);
10273 return this;
10276 // Return whether this expression is addressable.
10278 bool
10279 Array_index_expression::do_is_addressable() const
10281 // A slice expression is not addressable.
10282 if (this->end_ != NULL)
10283 return false;
10285 // An index into a slice is addressable.
10286 if (this->array_->type()->is_slice_type())
10287 return true;
10289 // An index into an array is addressable if the array is
10290 // addressable.
10291 return this->array_->is_addressable();
10294 // Get a tree for an array index.
10296 tree
10297 Array_index_expression::do_get_tree(Translate_context* context)
10299 Array_type* array_type = this->array_->type()->array_type();
10300 if (array_type == NULL)
10302 go_assert(this->array_->type()->is_error());
10303 return error_mark_node;
10305 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10307 Location loc = this->location();
10308 Gogo* gogo = context->gogo();
10310 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
10312 // We need to convert the length and capacity to the Go "int" type here
10313 // because the length of a fixed-length array could be of type "uintptr"
10314 // and gimple disallows binary operations between "uintptr" and other
10315 // integer types. FIXME.
10316 Bexpression* length = NULL;
10317 if (this->end_ == NULL || this->end_->is_nil_expression())
10319 Expression* len = array_type->get_length(gogo, this->array_);
10320 length = tree_to_expr(len->get_tree(context));
10321 length = gogo->backend()->convert_expression(int_btype, length, loc);
10324 Bexpression* capacity = NULL;
10325 if (this->end_ != NULL)
10327 Expression* cap = array_type->get_capacity(gogo, this->array_);
10328 capacity = tree_to_expr(cap->get_tree(context));
10329 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10332 Bexpression* cap_arg = capacity;
10333 if (this->cap_ != NULL)
10335 cap_arg = tree_to_expr(this->cap_->get_tree(context));
10336 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10339 if (length == NULL)
10340 length = cap_arg;
10342 int code = (array_type->length() != NULL
10343 ? (this->end_ == NULL
10344 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10345 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10346 : (this->end_ == NULL
10347 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10348 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10349 Bexpression* crash =
10350 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10352 Expression* bounds_check = Expression::check_bounds(this->start_, loc);
10353 Bexpression* bad_index = tree_to_expr(bounds_check->get_tree(context));
10355 Bexpression* start = tree_to_expr(this->start_->get_tree(context));
10356 start = gogo->backend()->convert_expression(int_btype, start, loc);
10357 Bexpression* start_too_large =
10358 gogo->backend()->binary_expression((this->end_ == NULL
10359 ? OPERATOR_GE
10360 : OPERATOR_GT),
10361 start,
10362 (this->end_ == NULL
10363 ? length
10364 : capacity),
10365 loc);
10366 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10367 bad_index, loc);
10369 if (this->end_ == NULL)
10371 // Simple array indexing. This has to return an l-value, so
10372 // wrap the index check into START.
10373 start =
10374 gogo->backend()->conditional_expression(int_btype, bad_index,
10375 crash, start, loc);
10377 Bexpression* ret;
10378 if (array_type->length() != NULL)
10380 Bexpression* array = tree_to_expr(this->array_->get_tree(context));
10381 ret = gogo->backend()->array_index_expression(array, start, loc);
10383 else
10385 // Slice.
10386 Expression* valptr =
10387 array_type->get_value_pointer(gogo, this->array_);
10388 Bexpression* ptr = tree_to_expr(valptr->get_tree(context));
10389 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10390 ret = gogo->backend()->indirect_expression(ptr, true, loc);
10392 return expr_to_tree(ret);
10395 // Array slice.
10397 if (this->cap_ != NULL)
10399 bounds_check = Expression::check_bounds(this->cap_, loc);
10400 Bexpression* bounds_bcheck =
10401 tree_to_expr(bounds_check->get_tree(context));
10402 bad_index =
10403 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10404 bad_index, loc);
10405 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10407 Bexpression* cap_too_small =
10408 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10409 Bexpression* cap_too_large =
10410 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10411 Bexpression* bad_cap =
10412 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10413 cap_too_large, loc);
10414 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10415 bad_index, loc);
10418 Bexpression* end;
10419 if (this->end_->is_nil_expression())
10420 end = length;
10421 else
10423 bounds_check = Expression::check_bounds(this->end_, loc);
10424 Bexpression* bounds_bcheck =
10425 tree_to_expr(bounds_check->get_tree(context));
10427 bad_index =
10428 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10429 bad_index, loc);
10431 end = tree_to_expr(this->end_->get_tree(context));
10432 end = gogo->backend()->convert_expression(int_btype, end, loc);
10433 Bexpression* end_too_small =
10434 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10435 Bexpression* end_too_large =
10436 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10437 Bexpression* bad_end =
10438 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10439 end_too_large, loc);
10440 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10441 bad_index, loc);
10444 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10445 Bexpression* val = tree_to_expr(valptr->get_tree(context));
10446 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10448 Bexpression* result_length =
10449 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10451 Bexpression* result_capacity =
10452 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10454 Btype* struct_btype = this->type()->get_backend(gogo);
10455 std::vector<Bexpression*> init;
10456 init.push_back(val);
10457 init.push_back(result_length);
10458 init.push_back(result_capacity);
10460 Bexpression* ctor =
10461 gogo->backend()->constructor_expression(struct_btype, init, loc);
10462 Bexpression* ret =
10463 gogo->backend()->conditional_expression(struct_btype, bad_index,
10464 crash, ctor, loc);
10466 return expr_to_tree(ret);
10469 // Dump ast representation for an array index expression.
10471 void
10472 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10473 const
10475 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10476 this->start_, this->end_, this->cap_);
10479 // Make an array index expression. END and CAP may be NULL.
10481 Expression*
10482 Expression::make_array_index(Expression* array, Expression* start,
10483 Expression* end, Expression* cap,
10484 Location location)
10486 return new Array_index_expression(array, start, end, cap, location);
10489 // A string index. This is used for both indexing and slicing.
10491 class String_index_expression : public Expression
10493 public:
10494 String_index_expression(Expression* string, Expression* start,
10495 Expression* end, Location location)
10496 : Expression(EXPRESSION_STRING_INDEX, location),
10497 string_(string), start_(start), end_(end)
10500 protected:
10502 do_traverse(Traverse*);
10504 Expression*
10505 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10507 Type*
10508 do_type();
10510 void
10511 do_determine_type(const Type_context*);
10513 void
10514 do_check_types(Gogo*);
10516 Expression*
10517 do_copy()
10519 return Expression::make_string_index(this->string_->copy(),
10520 this->start_->copy(),
10521 (this->end_ == NULL
10522 ? NULL
10523 : this->end_->copy()),
10524 this->location());
10527 bool
10528 do_must_eval_subexpressions_in_order(int* skip) const
10530 *skip = 1;
10531 return true;
10534 tree
10535 do_get_tree(Translate_context*);
10537 void
10538 do_dump_expression(Ast_dump_context*) const;
10540 private:
10541 // The string we are getting a value from.
10542 Expression* string_;
10543 // The start or only index.
10544 Expression* start_;
10545 // The end index of a slice. This may be NULL for a single index,
10546 // or it may be a nil expression for the length of the string.
10547 Expression* end_;
10550 // String index traversal.
10553 String_index_expression::do_traverse(Traverse* traverse)
10555 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10556 return TRAVERSE_EXIT;
10557 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10558 return TRAVERSE_EXIT;
10559 if (this->end_ != NULL)
10561 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10562 return TRAVERSE_EXIT;
10564 return TRAVERSE_CONTINUE;
10567 Expression*
10568 String_index_expression::do_flatten(Gogo*, Named_object*,
10569 Statement_inserter* inserter)
10571 Temporary_statement* temp;
10572 Location loc = this->location();
10573 if (!this->string_->is_variable())
10575 temp = Statement::make_temporary(NULL, this->string_, loc);
10576 inserter->insert(temp);
10577 this->string_ = Expression::make_temporary_reference(temp, loc);
10579 if (!this->start_->is_variable())
10581 temp = Statement::make_temporary(NULL, this->start_, loc);
10582 inserter->insert(temp);
10583 this->start_ = Expression::make_temporary_reference(temp, loc);
10585 if (this->end_ != NULL
10586 && !this->end_->is_nil_expression()
10587 && !this->end_->is_variable())
10589 temp = Statement::make_temporary(NULL, this->end_, loc);
10590 inserter->insert(temp);
10591 this->end_ = Expression::make_temporary_reference(temp, loc);
10594 return this;
10597 // Return the type of a string index.
10599 Type*
10600 String_index_expression::do_type()
10602 if (this->end_ == NULL)
10603 return Type::lookup_integer_type("uint8");
10604 else
10605 return this->string_->type();
10608 // Determine the type of a string index.
10610 void
10611 String_index_expression::do_determine_type(const Type_context*)
10613 this->string_->determine_type_no_context();
10614 this->start_->determine_type_no_context();
10615 if (this->end_ != NULL)
10616 this->end_->determine_type_no_context();
10619 // Check types of a string index.
10621 void
10622 String_index_expression::do_check_types(Gogo*)
10624 Numeric_constant nc;
10625 unsigned long v;
10626 if (this->start_->type()->integer_type() == NULL
10627 && !this->start_->type()->is_error()
10628 && (!this->start_->numeric_constant_value(&nc)
10629 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10630 this->report_error(_("index must be integer"));
10631 if (this->end_ != NULL
10632 && this->end_->type()->integer_type() == NULL
10633 && !this->end_->type()->is_error()
10634 && !this->end_->is_nil_expression()
10635 && !this->end_->is_error_expression()
10636 && (!this->end_->numeric_constant_value(&nc)
10637 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10638 this->report_error(_("slice end must be integer"));
10640 std::string sval;
10641 bool sval_valid = this->string_->string_constant_value(&sval);
10643 Numeric_constant inc;
10644 mpz_t ival;
10645 bool ival_valid = false;
10646 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10648 ival_valid = true;
10649 if (mpz_sgn(ival) < 0
10650 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10652 error_at(this->start_->location(), "string index out of bounds");
10653 this->set_is_error();
10656 if (this->end_ != NULL && !this->end_->is_nil_expression())
10658 Numeric_constant enc;
10659 mpz_t eval;
10660 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10662 if (mpz_sgn(eval) < 0
10663 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10665 error_at(this->end_->location(), "string index out of bounds");
10666 this->set_is_error();
10668 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10669 this->report_error(_("inverted slice range"));
10670 mpz_clear(eval);
10673 if (ival_valid)
10674 mpz_clear(ival);
10677 // Get a tree for a string index.
10679 tree
10680 String_index_expression::do_get_tree(Translate_context* context)
10682 Location loc = this->location();
10683 Expression* string_arg = this->string_;
10684 if (this->string_->type()->points_to() != NULL)
10685 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10687 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10689 int code = (this->end_ == NULL
10690 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10691 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10693 Gogo* gogo = context->gogo();
10694 Bexpression* crash =
10695 tree_to_expr(gogo->runtime_error(code, loc)->get_tree(context));
10697 Type* int_type = Type::lookup_integer_type("int");
10699 // It is possible that an error occurred earlier because the start index
10700 // cannot be represented as an integer type. In this case, we shouldn't
10701 // try casting the starting index into an integer since
10702 // Type_conversion_expression will fail to get the backend representation.
10703 // FIXME.
10704 if (this->start_->type()->integer_type() == NULL
10705 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10707 go_assert(saw_errors());
10708 return error_mark_node;
10711 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10713 if (this->end_ == NULL)
10715 Expression* length =
10716 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10718 Expression* start_too_large =
10719 Expression::make_binary(OPERATOR_GE, start, length, loc);
10720 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10721 bad_index, loc);
10722 Expression* bytes =
10723 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10725 Bexpression* bstart = tree_to_expr(start->get_tree(context));
10726 Bexpression* ptr = tree_to_expr(bytes->get_tree(context));
10727 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10728 Bexpression* index = gogo->backend()->indirect_expression(ptr, true, loc);
10730 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10731 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10732 Bexpression* ret =
10733 gogo->backend()->conditional_expression(byte_btype, index_error,
10734 crash, index, loc);
10735 return expr_to_tree(ret);
10738 Expression* end = NULL;
10739 if (this->end_->is_nil_expression())
10741 mpz_t neg_one;
10742 mpz_init_set_si(neg_one, -1);
10743 end = Expression::make_integer(&neg_one, int_type, loc);
10744 mpz_clear(neg_one);
10746 else
10748 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10749 bad_index =
10750 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10751 end = Expression::make_cast(int_type, this->end_, loc);
10754 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10755 string_arg, start, end);
10756 Bexpression* bstrslice = tree_to_expr(strslice->get_tree(context));
10758 Btype* str_btype = strslice->type()->get_backend(gogo);
10759 Bexpression* index_error = tree_to_expr(bad_index->get_tree(context));
10760 Bexpression* ret =
10761 gogo->backend()->conditional_expression(str_btype, index_error,
10762 crash, bstrslice, loc);
10763 return expr_to_tree(ret);
10766 // Dump ast representation for a string index expression.
10768 void
10769 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10770 const
10772 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10773 this->start_, this->end_, NULL);
10776 // Make a string index expression. END may be NULL.
10778 Expression*
10779 Expression::make_string_index(Expression* string, Expression* start,
10780 Expression* end, Location location)
10782 return new String_index_expression(string, start, end, location);
10785 // Class Map_index.
10787 // Get the type of the map.
10789 Map_type*
10790 Map_index_expression::get_map_type() const
10792 Map_type* mt = this->map_->type()->deref()->map_type();
10793 if (mt == NULL)
10794 go_assert(saw_errors());
10795 return mt;
10798 // Map index traversal.
10801 Map_index_expression::do_traverse(Traverse* traverse)
10803 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10804 return TRAVERSE_EXIT;
10805 return Expression::traverse(&this->index_, traverse);
10808 // We need to pass in a pointer to the key, so flatten the index into a
10809 // temporary variable if it isn't already. The value pointer will be
10810 // dereferenced and checked for nil, so flatten into a temporary to avoid
10811 // recomputation.
10813 Expression*
10814 Map_index_expression::do_flatten(Gogo*, Named_object*,
10815 Statement_inserter* inserter)
10817 Map_type* mt = this->get_map_type();
10818 if (this->index_->type() != mt->key_type())
10819 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10820 this->location());
10822 if (!this->index_->is_variable())
10824 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10825 this->location());
10826 inserter->insert(temp);
10827 this->index_ = Expression::make_temporary_reference(temp,
10828 this->location());
10831 if (this->value_pointer_ == NULL)
10832 this->get_value_pointer(this->is_lvalue_);
10833 if (!this->value_pointer_->is_variable())
10835 Temporary_statement* temp =
10836 Statement::make_temporary(NULL, this->value_pointer_,
10837 this->location());
10838 inserter->insert(temp);
10839 this->value_pointer_ =
10840 Expression::make_temporary_reference(temp, this->location());
10843 return this;
10846 // Return the type of a map index.
10848 Type*
10849 Map_index_expression::do_type()
10851 Map_type* mt = this->get_map_type();
10852 if (mt == NULL)
10853 return Type::make_error_type();
10854 Type* type = mt->val_type();
10855 // If this map index is in a tuple assignment, we actually return a
10856 // pointer to the value type. Tuple_map_assignment_statement is
10857 // responsible for handling this correctly. We need to get the type
10858 // right in case this gets assigned to a temporary variable.
10859 if (this->is_in_tuple_assignment_)
10860 type = Type::make_pointer_type(type);
10861 return type;
10864 // Fix the type of a map index.
10866 void
10867 Map_index_expression::do_determine_type(const Type_context*)
10869 this->map_->determine_type_no_context();
10870 Map_type* mt = this->get_map_type();
10871 Type* key_type = mt == NULL ? NULL : mt->key_type();
10872 Type_context subcontext(key_type, false);
10873 this->index_->determine_type(&subcontext);
10876 // Check types of a map index.
10878 void
10879 Map_index_expression::do_check_types(Gogo*)
10881 std::string reason;
10882 Map_type* mt = this->get_map_type();
10883 if (mt == NULL)
10884 return;
10885 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10887 if (reason.empty())
10888 this->report_error(_("incompatible type for map index"));
10889 else
10891 error_at(this->location(), "incompatible type for map index (%s)",
10892 reason.c_str());
10893 this->set_is_error();
10898 // Get a tree for a map index.
10900 tree
10901 Map_index_expression::do_get_tree(Translate_context* context)
10903 Map_type* type = this->get_map_type();
10904 if (type == NULL)
10906 go_assert(saw_errors());
10907 return error_mark_node;
10910 go_assert(this->value_pointer_ != NULL
10911 && this->value_pointer_->is_variable());
10913 Bexpression* ret;
10914 if (this->is_lvalue_)
10916 Expression* val =
10917 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10918 this->location());
10919 ret = tree_to_expr(val->get_tree(context));
10921 else if (this->is_in_tuple_assignment_)
10923 // Tuple_map_assignment_statement is responsible for using this
10924 // appropriately.
10925 ret = tree_to_expr(this->value_pointer_->get_tree(context));
10927 else
10929 Location loc = this->location();
10931 Expression* nil_check =
10932 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10933 Expression::make_nil(loc), loc);
10934 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
10935 Expression* val =
10936 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10937 Bexpression* bval = tree_to_expr(val->get_tree(context));
10939 Gogo* gogo = context->gogo();
10940 Btype* val_btype = type->val_type()->get_backend(gogo);
10941 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10942 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10943 val_zero, bval, loc);
10946 return expr_to_tree(ret);
10949 // Get an expression for the map index. This returns an expression which
10950 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10951 // not in the map.
10953 Expression*
10954 Map_index_expression::get_value_pointer(bool insert)
10956 if (this->value_pointer_ == NULL)
10958 Map_type* type = this->get_map_type();
10959 if (type == NULL)
10961 go_assert(saw_errors());
10962 return Expression::make_error(this->location());
10965 Location loc = this->location();
10966 Expression* map_ref = this->map_;
10967 if (this->map_->type()->points_to() != NULL)
10968 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10970 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10971 loc);
10972 Expression* map_index =
10973 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10974 map_ref, index_ptr,
10975 Expression::make_boolean(insert, loc));
10977 Type* val_type = type->val_type();
10978 this->value_pointer_ =
10979 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10980 map_index, this->location());
10982 return this->value_pointer_;
10985 // Dump ast representation for a map index expression
10987 void
10988 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10989 const
10991 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10992 this->index_, NULL, NULL);
10995 // Make a map index expression.
10997 Map_index_expression*
10998 Expression::make_map_index(Expression* map, Expression* index,
10999 Location location)
11001 return new Map_index_expression(map, index, location);
11004 // Class Field_reference_expression.
11006 // Lower a field reference expression. There is nothing to lower, but
11007 // this is where we generate the tracking information for fields with
11008 // the magic go:"track" tag.
11010 Expression*
11011 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11012 Statement_inserter* inserter, int)
11014 Struct_type* struct_type = this->expr_->type()->struct_type();
11015 if (struct_type == NULL)
11017 // Error will be reported elsewhere.
11018 return this;
11020 const Struct_field* field = struct_type->field(this->field_index_);
11021 if (field == NULL)
11022 return this;
11023 if (!field->has_tag())
11024 return this;
11025 if (field->tag().find("go:\"track\"") == std::string::npos)
11026 return this;
11028 // We have found a reference to a tracked field. Build a call to
11029 // the runtime function __go_fieldtrack with a string that describes
11030 // the field. FIXME: We should only call this once per referenced
11031 // field per function, not once for each reference to the field.
11033 if (this->called_fieldtrack_)
11034 return this;
11035 this->called_fieldtrack_ = true;
11037 Location loc = this->location();
11039 std::string s = "fieldtrack \"";
11040 Named_type* nt = this->expr_->type()->named_type();
11041 if (nt == NULL || nt->named_object()->package() == NULL)
11042 s.append(gogo->pkgpath());
11043 else
11044 s.append(nt->named_object()->package()->pkgpath());
11045 s.push_back('.');
11046 if (nt != NULL)
11047 s.append(Gogo::unpack_hidden_name(nt->name()));
11048 s.push_back('.');
11049 s.append(field->field_name());
11050 s.push_back('"');
11052 // We can't use a string here, because internally a string holds a
11053 // pointer to the actual bytes; when the linker garbage collects the
11054 // string, it won't garbage collect the bytes. So we use a
11055 // [...]byte.
11057 mpz_t val;
11058 mpz_init_set_ui(val, s.length());
11059 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
11060 mpz_clear(val);
11062 Type* byte_type = gogo->lookup_global("byte")->type_value();
11063 Type* array_type = Type::make_array_type(byte_type, length_expr);
11065 Expression_list* bytes = new Expression_list();
11066 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11068 mpz_init_set_ui(val, *p);
11069 Expression* byte = Expression::make_integer(&val, NULL, loc);
11070 mpz_clear(val);
11071 bytes->push_back(byte);
11074 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11075 bytes, false, loc);
11077 Variable* var = new Variable(array_type, e, true, false, false, loc);
11079 static int count;
11080 char buf[50];
11081 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11082 ++count;
11084 Named_object* no = gogo->add_variable(buf, var);
11085 e = Expression::make_var_reference(no, loc);
11086 e = Expression::make_unary(OPERATOR_AND, e, loc);
11088 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11089 inserter->insert(Statement::make_statement(call, false));
11091 // Put this function, and the global variable we just created, into
11092 // unique sections. This will permit the linker to garbage collect
11093 // them if they are not referenced. The effect is that the only
11094 // strings, indicating field references, that will wind up in the
11095 // executable will be those for functions that are actually needed.
11096 if (function != NULL)
11097 function->func_value()->set_in_unique_section();
11098 var->set_in_unique_section();
11100 return this;
11103 // Return the type of a field reference.
11105 Type*
11106 Field_reference_expression::do_type()
11108 Type* type = this->expr_->type();
11109 if (type->is_error())
11110 return type;
11111 Struct_type* struct_type = type->struct_type();
11112 go_assert(struct_type != NULL);
11113 return struct_type->field(this->field_index_)->type();
11116 // Check the types for a field reference.
11118 void
11119 Field_reference_expression::do_check_types(Gogo*)
11121 Type* type = this->expr_->type();
11122 if (type->is_error())
11123 return;
11124 Struct_type* struct_type = type->struct_type();
11125 go_assert(struct_type != NULL);
11126 go_assert(struct_type->field(this->field_index_) != NULL);
11129 // Get a tree for a field reference.
11131 tree
11132 Field_reference_expression::do_get_tree(Translate_context* context)
11134 Bexpression* bstruct = tree_to_expr(this->expr_->get_tree(context));
11135 Bexpression* ret =
11136 context->gogo()->backend()->struct_field_expression(bstruct,
11137 this->field_index_,
11138 this->location());
11139 return expr_to_tree(ret);
11142 // Dump ast representation for a field reference expression.
11144 void
11145 Field_reference_expression::do_dump_expression(
11146 Ast_dump_context* ast_dump_context) const
11148 this->expr_->dump_expression(ast_dump_context);
11149 ast_dump_context->ostream() << "." << this->field_index_;
11152 // Make a reference to a qualified identifier in an expression.
11154 Field_reference_expression*
11155 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11156 Location location)
11158 return new Field_reference_expression(expr, field_index, location);
11161 // Class Interface_field_reference_expression.
11163 // Return an expression for the pointer to the function to call.
11165 Expression*
11166 Interface_field_reference_expression::get_function()
11168 Expression* ref = this->expr_;
11169 Location loc = this->location();
11170 if (ref->type()->points_to() != NULL)
11171 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
11173 Expression* mtable =
11174 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11175 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11177 std::string name = Gogo::unpack_hidden_name(this->name_);
11178 unsigned int index;
11179 const Struct_field* field = mtable_type->find_local_field(name, &index);
11180 go_assert(field != NULL);
11181 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11182 return Expression::make_field_reference(mtable, index, loc);
11185 // Return an expression for the first argument to pass to the interface
11186 // function.
11188 Expression*
11189 Interface_field_reference_expression::get_underlying_object()
11191 Expression* expr = this->expr_;
11192 if (expr->type()->points_to() != NULL)
11193 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11194 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11195 this->location());
11198 // Traversal.
11201 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11203 return Expression::traverse(&this->expr_, traverse);
11206 // Lower the expression. If this expression is not called, we need to
11207 // evaluate the expression twice when converting to the backend
11208 // interface. So introduce a temporary variable if necessary.
11210 Expression*
11211 Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11212 Statement_inserter* inserter,
11213 int)
11215 if (!this->expr_->is_variable())
11217 Temporary_statement* temp =
11218 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11219 inserter->insert(temp);
11220 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11221 this->location());
11223 return this;
11226 // Return the type of an interface field reference.
11228 Type*
11229 Interface_field_reference_expression::do_type()
11231 Type* expr_type = this->expr_->type();
11233 Type* points_to = expr_type->points_to();
11234 if (points_to != NULL)
11235 expr_type = points_to;
11237 Interface_type* interface_type = expr_type->interface_type();
11238 if (interface_type == NULL)
11239 return Type::make_error_type();
11241 const Typed_identifier* method = interface_type->find_method(this->name_);
11242 if (method == NULL)
11243 return Type::make_error_type();
11245 return method->type();
11248 // Determine types.
11250 void
11251 Interface_field_reference_expression::do_determine_type(const Type_context*)
11253 this->expr_->determine_type_no_context();
11256 // Check the types for an interface field reference.
11258 void
11259 Interface_field_reference_expression::do_check_types(Gogo*)
11261 Type* type = this->expr_->type();
11263 Type* points_to = type->points_to();
11264 if (points_to != NULL)
11265 type = points_to;
11267 Interface_type* interface_type = type->interface_type();
11268 if (interface_type == NULL)
11270 if (!type->is_error_type())
11271 this->report_error(_("expected interface or pointer to interface"));
11273 else
11275 const Typed_identifier* method =
11276 interface_type->find_method(this->name_);
11277 if (method == NULL)
11279 error_at(this->location(), "method %qs not in interface",
11280 Gogo::message_name(this->name_).c_str());
11281 this->set_is_error();
11286 // If an interface field reference is not simply called, then it is
11287 // represented as a closure. The closure will hold a single variable,
11288 // the value of the interface on which the method should be called.
11289 // The function will be a simple thunk that pulls the value from the
11290 // closure and calls the method with the remaining arguments.
11292 // Because method values are not common, we don't build all thunks for
11293 // all possible interface methods, but instead only build them as we
11294 // need them. In particular, we even build them on demand for
11295 // interface methods defined in other packages.
11297 Interface_field_reference_expression::Interface_method_thunks
11298 Interface_field_reference_expression::interface_method_thunks;
11300 // Find or create the thunk to call method NAME on TYPE.
11302 Named_object*
11303 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11304 Interface_type* type,
11305 const std::string& name)
11307 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11308 std::pair<Interface_method_thunks::iterator, bool> ins =
11309 Interface_field_reference_expression::interface_method_thunks.insert(val);
11310 if (ins.second)
11312 // This is the first time we have seen this interface.
11313 ins.first->second = new Method_thunks();
11316 for (Method_thunks::const_iterator p = ins.first->second->begin();
11317 p != ins.first->second->end();
11318 p++)
11319 if (p->first == name)
11320 return p->second;
11322 Location loc = type->location();
11324 const Typed_identifier* method_id = type->find_method(name);
11325 if (method_id == NULL)
11326 return Named_object::make_erroneous_name(Gogo::thunk_name());
11328 Function_type* orig_fntype = method_id->type()->function_type();
11329 if (orig_fntype == NULL)
11330 return Named_object::make_erroneous_name(Gogo::thunk_name());
11332 Struct_field_list* sfl = new Struct_field_list();
11333 // The type here is wrong--it should be the C function type. But it
11334 // doesn't really matter.
11335 Type* vt = Type::make_pointer_type(Type::make_void_type());
11336 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11337 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11338 Type* closure_type = Type::make_struct_type(sfl, loc);
11339 closure_type = Type::make_pointer_type(closure_type);
11341 Function_type* new_fntype = orig_fntype->copy_with_names();
11343 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11344 false, loc);
11346 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11347 cvar->set_is_used();
11348 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11349 new_no->func_value()->set_closure_var(cp);
11351 gogo->start_block(loc);
11353 // Field 0 of the closure is the function code pointer, field 1 is
11354 // the value on which to invoke the method.
11355 Expression* arg = Expression::make_var_reference(cp, loc);
11356 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11357 arg = Expression::make_field_reference(arg, 1, loc);
11359 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11360 loc);
11362 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11363 Expression_list* args;
11364 if (orig_params == NULL || orig_params->empty())
11365 args = NULL;
11366 else
11368 const Typed_identifier_list* new_params = new_fntype->parameters();
11369 args = new Expression_list();
11370 for (Typed_identifier_list::const_iterator p = new_params->begin();
11371 p != new_params->end();
11372 ++p)
11374 Named_object* p_no = gogo->lookup(p->name(), NULL);
11375 go_assert(p_no != NULL
11376 && p_no->is_variable()
11377 && p_no->var_value()->is_parameter());
11378 args->push_back(Expression::make_var_reference(p_no, loc));
11382 Call_expression* call = Expression::make_call(ifre, args,
11383 orig_fntype->is_varargs(),
11384 loc);
11385 call->set_varargs_are_lowered();
11387 Statement* s = Statement::make_return_from_call(call, loc);
11388 gogo->add_statement(s);
11389 Block* b = gogo->finish_block(loc);
11390 gogo->add_block(b, loc);
11391 gogo->lower_block(new_no, b);
11392 gogo->flatten_block(new_no, b);
11393 gogo->finish_function(loc);
11395 ins.first->second->push_back(std::make_pair(name, new_no));
11396 return new_no;
11399 // Get a tree for a method value.
11401 tree
11402 Interface_field_reference_expression::do_get_tree(Translate_context* context)
11404 Interface_type* type = this->expr_->type()->interface_type();
11405 if (type == NULL)
11407 go_assert(saw_errors());
11408 return error_mark_node;
11411 Named_object* thunk =
11412 Interface_field_reference_expression::create_thunk(context->gogo(),
11413 type, this->name_);
11414 if (thunk->is_erroneous())
11416 go_assert(saw_errors());
11417 return error_mark_node;
11420 // FIXME: We should lower this earlier, but we can't it lower it in
11421 // the lowering pass because at that point we don't know whether we
11422 // need to create the thunk or not. If the expression is called, we
11423 // don't need the thunk.
11425 Location loc = this->location();
11427 Struct_field_list* fields = new Struct_field_list();
11428 fields->push_back(Struct_field(Typed_identifier("fn.0",
11429 thunk->func_value()->type(),
11430 loc)));
11431 fields->push_back(Struct_field(Typed_identifier("val.1",
11432 this->expr_->type(),
11433 loc)));
11434 Struct_type* st = Type::make_struct_type(fields, loc);
11436 Expression_list* vals = new Expression_list();
11437 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11438 vals->push_back(this->expr_);
11440 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11441 expr = Expression::make_heap_expression(expr, loc);
11443 Bexpression* bclosure = tree_to_expr(expr->get_tree(context));
11444 Expression* nil_check =
11445 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11446 Expression::make_nil(loc), loc);
11447 Bexpression* bnil_check = tree_to_expr(nil_check->get_tree(context));
11449 Gogo* gogo = context->gogo();
11450 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE, loc);
11451 Bexpression* bcrash = tree_to_expr(crash->get_tree(context));
11453 Bexpression* bcond =
11454 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11455 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11456 Bexpression* ret =
11457 gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11458 return expr_to_tree(ret);
11461 // Dump ast representation for an interface field reference.
11463 void
11464 Interface_field_reference_expression::do_dump_expression(
11465 Ast_dump_context* ast_dump_context) const
11467 this->expr_->dump_expression(ast_dump_context);
11468 ast_dump_context->ostream() << "." << this->name_;
11471 // Make a reference to a field in an interface.
11473 Expression*
11474 Expression::make_interface_field_reference(Expression* expr,
11475 const std::string& field,
11476 Location location)
11478 return new Interface_field_reference_expression(expr, field, location);
11481 // A general selector. This is a Parser_expression for LEFT.NAME. It
11482 // is lowered after we know the type of the left hand side.
11484 class Selector_expression : public Parser_expression
11486 public:
11487 Selector_expression(Expression* left, const std::string& name,
11488 Location location)
11489 : Parser_expression(EXPRESSION_SELECTOR, location),
11490 left_(left), name_(name)
11493 protected:
11495 do_traverse(Traverse* traverse)
11496 { return Expression::traverse(&this->left_, traverse); }
11498 Expression*
11499 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11501 Expression*
11502 do_copy()
11504 return new Selector_expression(this->left_->copy(), this->name_,
11505 this->location());
11508 void
11509 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11511 private:
11512 Expression*
11513 lower_method_expression(Gogo*);
11515 // The expression on the left hand side.
11516 Expression* left_;
11517 // The name on the right hand side.
11518 std::string name_;
11521 // Lower a selector expression once we know the real type of the left
11522 // hand side.
11524 Expression*
11525 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11526 int)
11528 Expression* left = this->left_;
11529 if (left->is_type_expression())
11530 return this->lower_method_expression(gogo);
11531 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11532 this->location());
11535 // Lower a method expression T.M or (*T).M. We turn this into a
11536 // function literal.
11538 Expression*
11539 Selector_expression::lower_method_expression(Gogo* gogo)
11541 Location location = this->location();
11542 Type* type = this->left_->type();
11543 const std::string& name(this->name_);
11545 bool is_pointer;
11546 if (type->points_to() == NULL)
11547 is_pointer = false;
11548 else
11550 is_pointer = true;
11551 type = type->points_to();
11553 Named_type* nt = type->named_type();
11554 if (nt == NULL)
11556 error_at(location,
11557 ("method expression requires named type or "
11558 "pointer to named type"));
11559 return Expression::make_error(location);
11562 bool is_ambiguous;
11563 Method* method = nt->method_function(name, &is_ambiguous);
11564 const Typed_identifier* imethod = NULL;
11565 if (method == NULL && !is_pointer)
11567 Interface_type* it = nt->interface_type();
11568 if (it != NULL)
11569 imethod = it->find_method(name);
11572 if (method == NULL && imethod == NULL)
11574 if (!is_ambiguous)
11575 error_at(location, "type %<%s%s%> has no method %<%s%>",
11576 is_pointer ? "*" : "",
11577 nt->message_name().c_str(),
11578 Gogo::message_name(name).c_str());
11579 else
11580 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11581 Gogo::message_name(name).c_str(),
11582 is_pointer ? "*" : "",
11583 nt->message_name().c_str());
11584 return Expression::make_error(location);
11587 if (method != NULL && !is_pointer && !method->is_value_method())
11589 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11590 nt->message_name().c_str(),
11591 Gogo::message_name(name).c_str());
11592 return Expression::make_error(location);
11595 // Build a new function type in which the receiver becomes the first
11596 // argument.
11597 Function_type* method_type;
11598 if (method != NULL)
11600 method_type = method->type();
11601 go_assert(method_type->is_method());
11603 else
11605 method_type = imethod->type()->function_type();
11606 go_assert(method_type != NULL && !method_type->is_method());
11609 const char* const receiver_name = "$this";
11610 Typed_identifier_list* parameters = new Typed_identifier_list();
11611 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11612 location));
11614 const Typed_identifier_list* method_parameters = method_type->parameters();
11615 if (method_parameters != NULL)
11617 int i = 0;
11618 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11619 p != method_parameters->end();
11620 ++p, ++i)
11622 if (!p->name().empty())
11623 parameters->push_back(*p);
11624 else
11626 char buf[20];
11627 snprintf(buf, sizeof buf, "$param%d", i);
11628 parameters->push_back(Typed_identifier(buf, p->type(),
11629 p->location()));
11634 const Typed_identifier_list* method_results = method_type->results();
11635 Typed_identifier_list* results;
11636 if (method_results == NULL)
11637 results = NULL;
11638 else
11640 results = new Typed_identifier_list();
11641 for (Typed_identifier_list::const_iterator p = method_results->begin();
11642 p != method_results->end();
11643 ++p)
11644 results->push_back(*p);
11647 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11648 location);
11649 if (method_type->is_varargs())
11650 fntype->set_is_varargs();
11652 // We generate methods which always takes a pointer to the receiver
11653 // as their first argument. If this is for a pointer type, we can
11654 // simply reuse the existing function. We use an internal hack to
11655 // get the right type.
11656 // FIXME: This optimization is disabled because it doesn't yet work
11657 // with function descriptors when the method expression is not
11658 // directly called.
11659 if (method != NULL && is_pointer && false)
11661 Named_object* mno = (method->needs_stub_method()
11662 ? method->stub_object()
11663 : method->named_object());
11664 Expression* f = Expression::make_func_reference(mno, NULL, location);
11665 f = Expression::make_cast(fntype, f, location);
11666 Type_conversion_expression* tce =
11667 static_cast<Type_conversion_expression*>(f);
11668 tce->set_may_convert_function_types();
11669 return f;
11672 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11673 location);
11675 Named_object* vno = gogo->lookup(receiver_name, NULL);
11676 go_assert(vno != NULL);
11677 Expression* ve = Expression::make_var_reference(vno, location);
11678 Expression* bm;
11679 if (method != NULL)
11680 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11681 else
11682 bm = Expression::make_interface_field_reference(ve, name, location);
11684 // Even though we found the method above, if it has an error type we
11685 // may see an error here.
11686 if (bm->is_error_expression())
11688 gogo->finish_function(location);
11689 return bm;
11692 Expression_list* args;
11693 if (parameters->size() <= 1)
11694 args = NULL;
11695 else
11697 args = new Expression_list();
11698 Typed_identifier_list::const_iterator p = parameters->begin();
11699 ++p;
11700 for (; p != parameters->end(); ++p)
11702 vno = gogo->lookup(p->name(), NULL);
11703 go_assert(vno != NULL);
11704 args->push_back(Expression::make_var_reference(vno, location));
11708 gogo->start_block(location);
11710 Call_expression* call = Expression::make_call(bm, args,
11711 method_type->is_varargs(),
11712 location);
11714 Statement* s = Statement::make_return_from_call(call, location);
11715 gogo->add_statement(s);
11717 Block* b = gogo->finish_block(location);
11719 gogo->add_block(b, location);
11721 // Lower the call in case there are multiple results.
11722 gogo->lower_block(no, b);
11723 gogo->flatten_block(no, b);
11725 gogo->finish_function(location);
11727 return Expression::make_func_reference(no, NULL, location);
11730 // Dump the ast for a selector expression.
11732 void
11733 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11734 const
11736 ast_dump_context->dump_expression(this->left_);
11737 ast_dump_context->ostream() << ".";
11738 ast_dump_context->ostream() << this->name_;
11741 // Make a selector expression.
11743 Expression*
11744 Expression::make_selector(Expression* left, const std::string& name,
11745 Location location)
11747 return new Selector_expression(left, name, location);
11750 // Implement the builtin function new.
11752 class Allocation_expression : public Expression
11754 public:
11755 Allocation_expression(Type* type, Location location)
11756 : Expression(EXPRESSION_ALLOCATION, location),
11757 type_(type)
11760 protected:
11762 do_traverse(Traverse* traverse)
11763 { return Type::traverse(this->type_, traverse); }
11765 Type*
11766 do_type()
11767 { return Type::make_pointer_type(this->type_); }
11769 void
11770 do_determine_type(const Type_context*)
11773 Expression*
11774 do_copy()
11775 { return new Allocation_expression(this->type_, this->location()); }
11777 tree
11778 do_get_tree(Translate_context*);
11780 void
11781 do_dump_expression(Ast_dump_context*) const;
11783 private:
11784 // The type we are allocating.
11785 Type* type_;
11788 // Return a tree for an allocation expression.
11790 tree
11791 Allocation_expression::do_get_tree(Translate_context* context)
11793 Gogo* gogo = context->gogo();
11794 Location loc = this->location();
11795 Expression* space = gogo->allocate_memory(this->type_, loc);
11796 Bexpression* bspace = tree_to_expr(space->get_tree(context));
11797 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11798 Bexpression* ret = gogo->backend()->convert_expression(pbtype, bspace, loc);
11799 return expr_to_tree(ret);
11802 // Dump ast representation for an allocation expression.
11804 void
11805 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11806 const
11808 ast_dump_context->ostream() << "new(";
11809 ast_dump_context->dump_type(this->type_);
11810 ast_dump_context->ostream() << ")";
11813 // Make an allocation expression.
11815 Expression*
11816 Expression::make_allocation(Type* type, Location location)
11818 return new Allocation_expression(type, location);
11821 // Construct a struct.
11823 class Struct_construction_expression : public Expression
11825 public:
11826 Struct_construction_expression(Type* type, Expression_list* vals,
11827 Location location)
11828 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11829 type_(type), vals_(vals), traverse_order_(NULL)
11832 // Set the traversal order, used to ensure that we implement the
11833 // order of evaluation rules. Takes ownership of the argument.
11834 void
11835 set_traverse_order(std::vector<int>* traverse_order)
11836 { this->traverse_order_ = traverse_order; }
11838 // Return whether this is a constant initializer.
11839 bool
11840 is_constant_struct() const;
11842 protected:
11844 do_traverse(Traverse* traverse);
11846 bool
11847 do_is_immutable() const;
11849 Type*
11850 do_type()
11851 { return this->type_; }
11853 void
11854 do_determine_type(const Type_context*);
11856 void
11857 do_check_types(Gogo*);
11859 Expression*
11860 do_copy()
11862 Struct_construction_expression* ret =
11863 new Struct_construction_expression(this->type_, this->vals_->copy(),
11864 this->location());
11865 if (this->traverse_order_ != NULL)
11866 ret->set_traverse_order(this->traverse_order_);
11867 return ret;
11870 tree
11871 do_get_tree(Translate_context*);
11873 void
11874 do_export(Export*) const;
11876 void
11877 do_dump_expression(Ast_dump_context*) const;
11879 private:
11880 // The type of the struct to construct.
11881 Type* type_;
11882 // The list of values, in order of the fields in the struct. A NULL
11883 // entry means that the field should be zero-initialized.
11884 Expression_list* vals_;
11885 // If not NULL, the order in which to traverse vals_. This is used
11886 // so that we implement the order of evaluation rules correctly.
11887 std::vector<int>* traverse_order_;
11890 // Traversal.
11893 Struct_construction_expression::do_traverse(Traverse* traverse)
11895 if (this->vals_ != NULL)
11897 if (this->traverse_order_ == NULL)
11899 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11900 return TRAVERSE_EXIT;
11902 else
11904 for (std::vector<int>::const_iterator p =
11905 this->traverse_order_->begin();
11906 p != this->traverse_order_->end();
11907 ++p)
11909 if (Expression::traverse(&this->vals_->at(*p), traverse)
11910 == TRAVERSE_EXIT)
11911 return TRAVERSE_EXIT;
11915 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11916 return TRAVERSE_EXIT;
11917 return TRAVERSE_CONTINUE;
11920 // Return whether this is a constant initializer.
11922 bool
11923 Struct_construction_expression::is_constant_struct() const
11925 if (this->vals_ == NULL)
11926 return true;
11927 for (Expression_list::const_iterator pv = this->vals_->begin();
11928 pv != this->vals_->end();
11929 ++pv)
11931 if (*pv != NULL
11932 && !(*pv)->is_constant()
11933 && (!(*pv)->is_composite_literal()
11934 || (*pv)->is_nonconstant_composite_literal()))
11935 return false;
11938 const Struct_field_list* fields = this->type_->struct_type()->fields();
11939 for (Struct_field_list::const_iterator pf = fields->begin();
11940 pf != fields->end();
11941 ++pf)
11943 // There are no constant constructors for interfaces.
11944 if (pf->type()->interface_type() != NULL)
11945 return false;
11948 return true;
11951 // Return whether this struct is immutable.
11953 bool
11954 Struct_construction_expression::do_is_immutable() const
11956 if (this->vals_ == NULL)
11957 return true;
11958 for (Expression_list::const_iterator pv = this->vals_->begin();
11959 pv != this->vals_->end();
11960 ++pv)
11962 if (*pv != NULL && !(*pv)->is_immutable())
11963 return false;
11965 return true;
11968 // Final type determination.
11970 void
11971 Struct_construction_expression::do_determine_type(const Type_context*)
11973 if (this->vals_ == NULL)
11974 return;
11975 const Struct_field_list* fields = this->type_->struct_type()->fields();
11976 Expression_list::const_iterator pv = this->vals_->begin();
11977 for (Struct_field_list::const_iterator pf = fields->begin();
11978 pf != fields->end();
11979 ++pf, ++pv)
11981 if (pv == this->vals_->end())
11982 return;
11983 if (*pv != NULL)
11985 Type_context subcontext(pf->type(), false);
11986 (*pv)->determine_type(&subcontext);
11989 // Extra values are an error we will report elsewhere; we still want
11990 // to determine the type to avoid knockon errors.
11991 for (; pv != this->vals_->end(); ++pv)
11992 (*pv)->determine_type_no_context();
11995 // Check types.
11997 void
11998 Struct_construction_expression::do_check_types(Gogo*)
12000 if (this->vals_ == NULL)
12001 return;
12003 Struct_type* st = this->type_->struct_type();
12004 if (this->vals_->size() > st->field_count())
12006 this->report_error(_("too many expressions for struct"));
12007 return;
12010 const Struct_field_list* fields = st->fields();
12011 Expression_list::const_iterator pv = this->vals_->begin();
12012 int i = 0;
12013 for (Struct_field_list::const_iterator pf = fields->begin();
12014 pf != fields->end();
12015 ++pf, ++pv, ++i)
12017 if (pv == this->vals_->end())
12019 this->report_error(_("too few expressions for struct"));
12020 break;
12023 if (*pv == NULL)
12024 continue;
12026 std::string reason;
12027 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12029 if (reason.empty())
12030 error_at((*pv)->location(),
12031 "incompatible type for field %d in struct construction",
12032 i + 1);
12033 else
12034 error_at((*pv)->location(),
12035 ("incompatible type for field %d in "
12036 "struct construction (%s)"),
12037 i + 1, reason.c_str());
12038 this->set_is_error();
12041 go_assert(pv == this->vals_->end());
12044 // Return a tree for constructing a struct.
12046 tree
12047 Struct_construction_expression::do_get_tree(Translate_context* context)
12049 Gogo* gogo = context->gogo();
12051 Btype* btype = this->type_->get_backend(gogo);
12052 if (this->vals_ == NULL)
12053 return expr_to_tree(gogo->backend()->zero_expression(btype));
12055 const Struct_field_list* fields = this->type_->struct_type()->fields();
12056 Expression_list::const_iterator pv = this->vals_->begin();
12057 std::vector<Bexpression*> init;
12058 for (Struct_field_list::const_iterator pf = fields->begin();
12059 pf != fields->end();
12060 ++pf)
12062 Btype* fbtype = pf->type()->get_backend(gogo);
12063 if (pv == this->vals_->end())
12064 init.push_back(gogo->backend()->zero_expression(fbtype));
12065 else if (*pv == NULL)
12067 init.push_back(gogo->backend()->zero_expression(fbtype));
12068 ++pv;
12070 else
12072 Expression* val =
12073 Expression::convert_for_assignment(gogo, pf->type(),
12074 *pv, this->location());
12075 init.push_back(tree_to_expr(val->get_tree(context)));
12076 ++pv;
12080 Bexpression* ret =
12081 gogo->backend()->constructor_expression(btype, init, this->location());
12082 return expr_to_tree(ret);
12085 // Export a struct construction.
12087 void
12088 Struct_construction_expression::do_export(Export* exp) const
12090 exp->write_c_string("convert(");
12091 exp->write_type(this->type_);
12092 for (Expression_list::const_iterator pv = this->vals_->begin();
12093 pv != this->vals_->end();
12094 ++pv)
12096 exp->write_c_string(", ");
12097 if (*pv != NULL)
12098 (*pv)->export_expression(exp);
12100 exp->write_c_string(")");
12103 // Dump ast representation of a struct construction expression.
12105 void
12106 Struct_construction_expression::do_dump_expression(
12107 Ast_dump_context* ast_dump_context) const
12109 ast_dump_context->dump_type(this->type_);
12110 ast_dump_context->ostream() << "{";
12111 ast_dump_context->dump_expression_list(this->vals_);
12112 ast_dump_context->ostream() << "}";
12115 // Make a struct composite literal. This used by the thunk code.
12117 Expression*
12118 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12119 Location location)
12121 go_assert(type->struct_type() != NULL);
12122 return new Struct_construction_expression(type, vals, location);
12125 // Construct an array. This class is not used directly; instead we
12126 // use the child classes, Fixed_array_construction_expression and
12127 // Slice_construction_expression.
12129 class Array_construction_expression : public Expression
12131 protected:
12132 Array_construction_expression(Expression_classification classification,
12133 Type* type,
12134 const std::vector<unsigned long>* indexes,
12135 Expression_list* vals, Location location)
12136 : Expression(classification, location),
12137 type_(type), indexes_(indexes), vals_(vals)
12138 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
12140 public:
12141 // Return whether this is a constant initializer.
12142 bool
12143 is_constant_array() const;
12145 // Return the number of elements.
12146 size_t
12147 element_count() const
12148 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12150 protected:
12152 do_traverse(Traverse* traverse);
12154 bool
12155 do_is_immutable() const;
12157 Type*
12158 do_type()
12159 { return this->type_; }
12161 void
12162 do_determine_type(const Type_context*);
12164 void
12165 do_check_types(Gogo*);
12167 void
12168 do_export(Export*) const;
12170 // The indexes.
12171 const std::vector<unsigned long>*
12172 indexes()
12173 { return this->indexes_; }
12175 // The list of values.
12176 Expression_list*
12177 vals()
12178 { return this->vals_; }
12180 // Get the backend constructor for the array values.
12181 Bexpression*
12182 get_constructor(Translate_context* context, Btype* btype);
12184 void
12185 do_dump_expression(Ast_dump_context*) const;
12187 private:
12188 // The type of the array to construct.
12189 Type* type_;
12190 // The list of indexes into the array, one for each value. This may
12191 // be NULL, in which case the indexes start at zero and increment.
12192 const std::vector<unsigned long>* indexes_;
12193 // The list of values. This may be NULL if there are no values.
12194 Expression_list* vals_;
12197 // Traversal.
12200 Array_construction_expression::do_traverse(Traverse* traverse)
12202 if (this->vals_ != NULL
12203 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12204 return TRAVERSE_EXIT;
12205 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12206 return TRAVERSE_EXIT;
12207 return TRAVERSE_CONTINUE;
12210 // Return whether this is a constant initializer.
12212 bool
12213 Array_construction_expression::is_constant_array() const
12215 if (this->vals_ == NULL)
12216 return true;
12218 // There are no constant constructors for interfaces.
12219 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12220 return false;
12222 for (Expression_list::const_iterator pv = this->vals_->begin();
12223 pv != this->vals_->end();
12224 ++pv)
12226 if (*pv != NULL
12227 && !(*pv)->is_constant()
12228 && (!(*pv)->is_composite_literal()
12229 || (*pv)->is_nonconstant_composite_literal()))
12230 return false;
12232 return true;
12235 // Return whether this is an immutable array initializer.
12237 bool
12238 Array_construction_expression::do_is_immutable() const
12240 if (this->vals_ == NULL)
12241 return true;
12242 for (Expression_list::const_iterator pv = this->vals_->begin();
12243 pv != this->vals_->end();
12244 ++pv)
12246 if (*pv != NULL && !(*pv)->is_immutable())
12247 return false;
12249 return true;
12252 // Final type determination.
12254 void
12255 Array_construction_expression::do_determine_type(const Type_context*)
12257 if (this->vals_ == NULL)
12258 return;
12259 Type_context subcontext(this->type_->array_type()->element_type(), false);
12260 for (Expression_list::const_iterator pv = this->vals_->begin();
12261 pv != this->vals_->end();
12262 ++pv)
12264 if (*pv != NULL)
12265 (*pv)->determine_type(&subcontext);
12269 // Check types.
12271 void
12272 Array_construction_expression::do_check_types(Gogo*)
12274 if (this->vals_ == NULL)
12275 return;
12277 Array_type* at = this->type_->array_type();
12278 int i = 0;
12279 Type* element_type = at->element_type();
12280 for (Expression_list::const_iterator pv = this->vals_->begin();
12281 pv != this->vals_->end();
12282 ++pv, ++i)
12284 if (*pv != NULL
12285 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12287 error_at((*pv)->location(),
12288 "incompatible type for element %d in composite literal",
12289 i + 1);
12290 this->set_is_error();
12295 // Get a constructor expression for the array values.
12297 Bexpression*
12298 Array_construction_expression::get_constructor(Translate_context* context,
12299 Btype* array_btype)
12301 Type* element_type = this->type_->array_type()->element_type();
12303 std::vector<unsigned long> indexes;
12304 std::vector<Bexpression*> vals;
12305 Gogo* gogo = context->gogo();
12306 if (this->vals_ != NULL)
12308 size_t i = 0;
12309 std::vector<unsigned long>::const_iterator pi;
12310 if (this->indexes_ != NULL)
12311 pi = this->indexes_->begin();
12312 for (Expression_list::const_iterator pv = this->vals_->begin();
12313 pv != this->vals_->end();
12314 ++pv, ++i)
12316 if (this->indexes_ != NULL)
12317 go_assert(pi != this->indexes_->end());
12319 if (this->indexes_ == NULL)
12320 indexes.push_back(i);
12321 else
12322 indexes.push_back(*pi);
12323 if (*pv == NULL)
12325 Btype* ebtype = element_type->get_backend(gogo);
12326 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12327 vals.push_back(zv);
12329 else
12331 Expression* val_expr =
12332 Expression::convert_for_assignment(gogo, element_type, *pv,
12333 this->location());
12334 vals.push_back(tree_to_expr(val_expr->get_tree(context)));
12336 if (this->indexes_ != NULL)
12337 ++pi;
12339 if (this->indexes_ != NULL)
12340 go_assert(pi == this->indexes_->end());
12342 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12343 vals, this->location());
12346 // Export an array construction.
12348 void
12349 Array_construction_expression::do_export(Export* exp) const
12351 exp->write_c_string("convert(");
12352 exp->write_type(this->type_);
12353 if (this->vals_ != NULL)
12355 std::vector<unsigned long>::const_iterator pi;
12356 if (this->indexes_ != NULL)
12357 pi = this->indexes_->begin();
12358 for (Expression_list::const_iterator pv = this->vals_->begin();
12359 pv != this->vals_->end();
12360 ++pv)
12362 exp->write_c_string(", ");
12364 if (this->indexes_ != NULL)
12366 char buf[100];
12367 snprintf(buf, sizeof buf, "%lu", *pi);
12368 exp->write_c_string(buf);
12369 exp->write_c_string(":");
12372 if (*pv != NULL)
12373 (*pv)->export_expression(exp);
12375 if (this->indexes_ != NULL)
12376 ++pi;
12379 exp->write_c_string(")");
12382 // Dump ast representation of an array construction expressin.
12384 void
12385 Array_construction_expression::do_dump_expression(
12386 Ast_dump_context* ast_dump_context) const
12388 Expression* length = this->type_->array_type()->length();
12390 ast_dump_context->ostream() << "[" ;
12391 if (length != NULL)
12393 ast_dump_context->dump_expression(length);
12395 ast_dump_context->ostream() << "]" ;
12396 ast_dump_context->dump_type(this->type_);
12397 ast_dump_context->ostream() << "{" ;
12398 if (this->indexes_ == NULL)
12399 ast_dump_context->dump_expression_list(this->vals_);
12400 else
12402 Expression_list::const_iterator pv = this->vals_->begin();
12403 for (std::vector<unsigned long>::const_iterator pi =
12404 this->indexes_->begin();
12405 pi != this->indexes_->end();
12406 ++pi, ++pv)
12408 if (pi != this->indexes_->begin())
12409 ast_dump_context->ostream() << ", ";
12410 ast_dump_context->ostream() << *pi << ':';
12411 ast_dump_context->dump_expression(*pv);
12414 ast_dump_context->ostream() << "}" ;
12418 // Construct a fixed array.
12420 class Fixed_array_construction_expression :
12421 public Array_construction_expression
12423 public:
12424 Fixed_array_construction_expression(Type* type,
12425 const std::vector<unsigned long>* indexes,
12426 Expression_list* vals, Location location)
12427 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12428 type, indexes, vals, location)
12429 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12431 protected:
12432 Expression*
12433 do_copy()
12435 return new Fixed_array_construction_expression(this->type(),
12436 this->indexes(),
12437 (this->vals() == NULL
12438 ? NULL
12439 : this->vals()->copy()),
12440 this->location());
12443 tree
12444 do_get_tree(Translate_context*);
12447 // Return a tree for constructing a fixed array.
12449 tree
12450 Fixed_array_construction_expression::do_get_tree(Translate_context* context)
12452 Type* type = this->type();
12453 Btype* btype = type->get_backend(context->gogo());
12454 return expr_to_tree(this->get_constructor(context, btype));
12457 // Construct a slice.
12459 class Slice_construction_expression : public Array_construction_expression
12461 public:
12462 Slice_construction_expression(Type* type,
12463 const std::vector<unsigned long>* indexes,
12464 Expression_list* vals, Location location)
12465 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12466 type, indexes, vals, location),
12467 valtype_(NULL)
12468 { go_assert(type->is_slice_type()); }
12470 protected:
12471 // Note that taking the address of a slice literal is invalid.
12473 Expression*
12474 do_copy()
12476 return new Slice_construction_expression(this->type(), this->indexes(),
12477 (this->vals() == NULL
12478 ? NULL
12479 : this->vals()->copy()),
12480 this->location());
12483 tree
12484 do_get_tree(Translate_context*);
12486 private:
12487 // The type of the values in this slice.
12488 Type* valtype_;
12491 // Return a tree for constructing a slice.
12493 tree
12494 Slice_construction_expression::do_get_tree(Translate_context* context)
12496 Array_type* array_type = this->type()->array_type();
12497 if (array_type == NULL)
12499 go_assert(this->type()->is_error());
12500 return error_mark_node;
12503 Type* element_type = array_type->element_type();
12504 if (this->valtype_ == NULL)
12506 mpz_t lenval;
12507 Expression* length;
12508 if (this->vals() == NULL || this->vals()->empty())
12509 mpz_init_set_ui(lenval, 0);
12510 else
12512 if (this->indexes() == NULL)
12513 mpz_init_set_ui(lenval, this->vals()->size());
12514 else
12515 mpz_init_set_ui(lenval, this->indexes()->back() + 1);
12517 Location loc = this->location();
12518 Type* int_type = Type::lookup_integer_type("int");
12519 length = Expression::make_integer(&lenval, int_type, loc);
12520 mpz_clear(lenval);
12521 this->valtype_ = Type::make_array_type(element_type, length);
12524 tree values;
12525 Gogo* gogo = context->gogo();
12526 Btype* val_btype = this->valtype_->get_backend(gogo);
12527 if (this->vals() == NULL || this->vals()->empty())
12529 // We need to create a unique value.
12530 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
12531 Bexpression* zero = gogo->backend()->zero_expression(int_btype);
12532 std::vector<unsigned long> index(1, 0);
12533 std::vector<Bexpression*> val(1, zero);
12534 Bexpression* ctor =
12535 gogo->backend()->array_constructor_expression(val_btype, index, val,
12536 this->location());
12537 values = expr_to_tree(ctor);
12539 else
12540 values = expr_to_tree(this->get_constructor(context, val_btype));
12542 if (values == error_mark_node)
12543 return error_mark_node;
12545 bool is_constant_initializer = TREE_CONSTANT(values);
12547 // We have to copy the initial values into heap memory if we are in
12548 // a function or if the values are not constants. We also have to
12549 // copy them if they may contain pointers in a non-constant context,
12550 // as otherwise the garbage collector won't see them.
12551 bool copy_to_heap = (context->function() != NULL
12552 || !is_constant_initializer
12553 || (element_type->has_pointer()
12554 && !context->is_const()));
12556 if (is_constant_initializer)
12558 tree tmp = build_decl(this->location().gcc_location(), VAR_DECL,
12559 create_tmp_var_name("C"), TREE_TYPE(values));
12560 DECL_EXTERNAL(tmp) = 0;
12561 TREE_PUBLIC(tmp) = 0;
12562 TREE_STATIC(tmp) = 1;
12563 DECL_ARTIFICIAL(tmp) = 1;
12564 if (copy_to_heap)
12566 // If we are not copying the value to the heap, we will only
12567 // initialize the value once, so we can use this directly
12568 // rather than copying it. In that case we can't make it
12569 // read-only, because the program is permitted to change it.
12570 TREE_READONLY(tmp) = 1;
12571 TREE_CONSTANT(tmp) = 1;
12573 DECL_INITIAL(tmp) = values;
12574 rest_of_decl_compilation(tmp, 1, 0);
12575 values = tmp;
12578 tree space;
12579 tree set;
12580 if (!copy_to_heap)
12582 // the initializer will only run once.
12583 space = build_fold_addr_expr(values);
12584 set = NULL_TREE;
12586 else
12588 Expression* alloc =
12589 context->gogo()->allocate_memory(this->valtype_, this->location());
12590 space = save_expr(alloc->get_tree(context));
12592 tree s = fold_convert(build_pointer_type(TREE_TYPE(values)), space);
12593 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
12595 TREE_THIS_NOTRAP(ref) = 1;
12596 set = build2(MODIFY_EXPR, void_type_node, ref, values);
12599 // Build a constructor for the slice.
12601 tree type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
12602 if (type_tree == error_mark_node)
12603 return error_mark_node;
12604 go_assert(TREE_CODE(type_tree) == RECORD_TYPE);
12606 vec<constructor_elt, va_gc> *init;
12607 vec_alloc(init, 3);
12609 constructor_elt empty = {NULL, NULL};
12610 constructor_elt* elt = init->quick_push(empty);
12611 tree field = TYPE_FIELDS(type_tree);
12612 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__values") == 0);
12613 elt->index = field;
12614 elt->value = fold_convert(TREE_TYPE(field), space);
12616 tree length_tree = this->valtype_->array_type()->length()->get_tree(context);
12617 elt = init->quick_push(empty);
12618 field = DECL_CHAIN(field);
12619 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)), "__count") == 0);
12620 elt->index = field;
12621 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12623 elt = init->quick_push(empty);
12624 field = DECL_CHAIN(field);
12625 go_assert(strcmp(IDENTIFIER_POINTER(DECL_NAME(field)),"__capacity") == 0);
12626 elt->index = field;
12627 elt->value = fold_convert(TREE_TYPE(field), length_tree);
12629 tree constructor = build_constructor(type_tree, init);
12630 if (constructor == error_mark_node)
12631 return error_mark_node;
12632 if (!copy_to_heap)
12633 TREE_CONSTANT(constructor) = 1;
12635 if (set == NULL_TREE)
12636 return constructor;
12637 else
12638 return build2(COMPOUND_EXPR, type_tree, set, constructor);
12641 // Make a slice composite literal. This is used by the type
12642 // descriptor code.
12644 Expression*
12645 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12646 Location location)
12648 go_assert(type->is_slice_type());
12649 return new Slice_construction_expression(type, NULL, vals, location);
12652 // Construct a map.
12654 class Map_construction_expression : public Expression
12656 public:
12657 Map_construction_expression(Type* type, Expression_list* vals,
12658 Location location)
12659 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
12660 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
12661 { go_assert(vals == NULL || vals->size() % 2 == 0); }
12663 protected:
12665 do_traverse(Traverse* traverse);
12667 Expression*
12668 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12670 Type*
12671 do_type()
12672 { return this->type_; }
12674 void
12675 do_determine_type(const Type_context*);
12677 void
12678 do_check_types(Gogo*);
12680 Expression*
12681 do_copy()
12683 return new Map_construction_expression(this->type_, this->vals_->copy(),
12684 this->location());
12687 tree
12688 do_get_tree(Translate_context*);
12690 void
12691 do_export(Export*) const;
12693 void
12694 do_dump_expression(Ast_dump_context*) const;
12696 private:
12697 // The type of the map to construct.
12698 Type* type_;
12699 // The list of values.
12700 Expression_list* vals_;
12701 // The type of the key-value pair struct for each map element.
12702 Struct_type* element_type_;
12703 // A temporary reference to the variable storing the constructor initializer.
12704 Temporary_statement* constructor_temp_;
12707 // Traversal.
12710 Map_construction_expression::do_traverse(Traverse* traverse)
12712 if (this->vals_ != NULL
12713 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12714 return TRAVERSE_EXIT;
12715 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12716 return TRAVERSE_EXIT;
12717 return TRAVERSE_CONTINUE;
12720 // Flatten constructor initializer into a temporary variable since
12721 // we need to take its address for __go_construct_map.
12723 Expression*
12724 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12725 Statement_inserter* inserter)
12727 if (!this->is_error_expression()
12728 && this->vals_ != NULL
12729 && !this->vals_->empty()
12730 && this->constructor_temp_ == NULL)
12732 Map_type* mt = this->type_->map_type();
12733 Type* key_type = mt->key_type();
12734 Type* val_type = mt->val_type();
12735 this->element_type_ = Type::make_builtin_struct_type(2,
12736 "__key", key_type,
12737 "__val", val_type);
12739 Expression_list* value_pairs = new Expression_list();
12740 Location loc = this->location();
12742 size_t i = 0;
12743 for (Expression_list::const_iterator pv = this->vals_->begin();
12744 pv != this->vals_->end();
12745 ++pv, ++i)
12747 Expression_list* key_value_pair = new Expression_list();
12748 Expression* key =
12749 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12751 ++pv;
12752 Expression* val =
12753 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12755 key_value_pair->push_back(key);
12756 key_value_pair->push_back(val);
12757 value_pairs->push_back(
12758 Expression::make_struct_composite_literal(this->element_type_,
12759 key_value_pair, loc));
12762 mpz_t lenval;
12763 mpz_init_set_ui(lenval, i);
12764 Expression* element_count = Expression::make_integer(&lenval, NULL, loc);
12765 mpz_clear(lenval);
12767 Type* ctor_type =
12768 Type::make_array_type(this->element_type_, element_count);
12769 Expression* constructor =
12770 new Fixed_array_construction_expression(ctor_type, NULL,
12771 value_pairs, loc);
12773 this->constructor_temp_ =
12774 Statement::make_temporary(NULL, constructor, loc);
12775 constructor->issue_nil_check();
12776 this->constructor_temp_->set_is_address_taken();
12777 inserter->insert(this->constructor_temp_);
12780 return this;
12783 // Final type determination.
12785 void
12786 Map_construction_expression::do_determine_type(const Type_context*)
12788 if (this->vals_ == NULL)
12789 return;
12791 Map_type* mt = this->type_->map_type();
12792 Type_context key_context(mt->key_type(), false);
12793 Type_context val_context(mt->val_type(), false);
12794 for (Expression_list::const_iterator pv = this->vals_->begin();
12795 pv != this->vals_->end();
12796 ++pv)
12798 (*pv)->determine_type(&key_context);
12799 ++pv;
12800 (*pv)->determine_type(&val_context);
12804 // Check types.
12806 void
12807 Map_construction_expression::do_check_types(Gogo*)
12809 if (this->vals_ == NULL)
12810 return;
12812 Map_type* mt = this->type_->map_type();
12813 int i = 0;
12814 Type* key_type = mt->key_type();
12815 Type* val_type = mt->val_type();
12816 for (Expression_list::const_iterator pv = this->vals_->begin();
12817 pv != this->vals_->end();
12818 ++pv, ++i)
12820 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12822 error_at((*pv)->location(),
12823 "incompatible type for element %d key in map construction",
12824 i + 1);
12825 this->set_is_error();
12827 ++pv;
12828 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12830 error_at((*pv)->location(),
12831 ("incompatible type for element %d value "
12832 "in map construction"),
12833 i + 1);
12834 this->set_is_error();
12839 // Return a tree for constructing a map.
12841 tree
12842 Map_construction_expression::do_get_tree(Translate_context* context)
12844 if (this->is_error_expression())
12845 return error_mark_node;
12846 Location loc = this->location();
12848 size_t i = 0;
12849 Expression* ventries;
12850 if (this->vals_ == NULL || this->vals_->empty())
12851 ventries = Expression::make_nil(loc);
12852 else
12854 go_assert(this->constructor_temp_ != NULL);
12855 i = this->vals_->size() / 2;
12857 Expression* ctor_ref =
12858 Expression::make_temporary_reference(this->constructor_temp_, loc);
12859 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12862 Map_type* mt = this->type_->map_type();
12863 if (this->element_type_ == NULL)
12864 this->element_type_ =
12865 Type::make_builtin_struct_type(2,
12866 "__key", mt->key_type(),
12867 "__val", mt->val_type());
12868 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12870 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12871 mpz_t countval;
12872 mpz_init_set_ui(countval, i);
12873 Expression* count = Expression::make_integer(&countval, uintptr_t, loc);
12874 mpz_clear(countval);
12876 Expression* entry_size =
12877 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12879 unsigned int field_index;
12880 const Struct_field* valfield =
12881 this->element_type_->find_local_field("__val", &field_index);
12882 Expression* val_offset =
12883 Expression::make_struct_field_offset(this->element_type_, valfield);
12884 Expression* val_size =
12885 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12887 Expression* map_ctor =
12888 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12889 entry_size, val_offset, val_size, ventries);
12890 return map_ctor->get_tree(context);
12893 // Export an array construction.
12895 void
12896 Map_construction_expression::do_export(Export* exp) const
12898 exp->write_c_string("convert(");
12899 exp->write_type(this->type_);
12900 for (Expression_list::const_iterator pv = this->vals_->begin();
12901 pv != this->vals_->end();
12902 ++pv)
12904 exp->write_c_string(", ");
12905 (*pv)->export_expression(exp);
12907 exp->write_c_string(")");
12910 // Dump ast representation for a map construction expression.
12912 void
12913 Map_construction_expression::do_dump_expression(
12914 Ast_dump_context* ast_dump_context) const
12916 ast_dump_context->ostream() << "{" ;
12917 ast_dump_context->dump_expression_list(this->vals_, true);
12918 ast_dump_context->ostream() << "}";
12921 // A general composite literal. This is lowered to a type specific
12922 // version.
12924 class Composite_literal_expression : public Parser_expression
12926 public:
12927 Composite_literal_expression(Type* type, int depth, bool has_keys,
12928 Expression_list* vals, bool all_are_names,
12929 Location location)
12930 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12931 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12932 all_are_names_(all_are_names)
12935 protected:
12937 do_traverse(Traverse* traverse);
12939 Expression*
12940 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12942 Expression*
12943 do_copy()
12945 return new Composite_literal_expression(this->type_, this->depth_,
12946 this->has_keys_,
12947 (this->vals_ == NULL
12948 ? NULL
12949 : this->vals_->copy()),
12950 this->all_are_names_,
12951 this->location());
12954 void
12955 do_dump_expression(Ast_dump_context*) const;
12957 private:
12958 Expression*
12959 lower_struct(Gogo*, Type*);
12961 Expression*
12962 lower_array(Type*);
12964 Expression*
12965 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12967 Expression*
12968 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12970 // The type of the composite literal.
12971 Type* type_;
12972 // The depth within a list of composite literals within a composite
12973 // literal, when the type is omitted.
12974 int depth_;
12975 // The values to put in the composite literal.
12976 Expression_list* vals_;
12977 // If this is true, then VALS_ is a list of pairs: a key and a
12978 // value. In an array initializer, a missing key will be NULL.
12979 bool has_keys_;
12980 // If this is true, then HAS_KEYS_ is true, and every key is a
12981 // simple identifier.
12982 bool all_are_names_;
12985 // Traversal.
12988 Composite_literal_expression::do_traverse(Traverse* traverse)
12990 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12991 return TRAVERSE_EXIT;
12993 // If this is a struct composite literal with keys, then the keys
12994 // are field names, not expressions. We don't want to traverse them
12995 // in that case. If we do, we can give an erroneous error "variable
12996 // initializer refers to itself." See bug482.go in the testsuite.
12997 if (this->has_keys_ && this->vals_ != NULL)
12999 // The type may not be resolvable at this point.
13000 Type* type = this->type_;
13002 for (int depth = this->depth_; depth > 0; --depth)
13004 if (type->array_type() != NULL)
13005 type = type->array_type()->element_type();
13006 else if (type->map_type() != NULL)
13007 type = type->map_type()->val_type();
13008 else
13010 // This error will be reported during lowering.
13011 return TRAVERSE_CONTINUE;
13015 while (true)
13017 if (type->classification() == Type::TYPE_NAMED)
13018 type = type->named_type()->real_type();
13019 else if (type->classification() == Type::TYPE_FORWARD)
13021 Type* t = type->forwarded();
13022 if (t == type)
13023 break;
13024 type = t;
13026 else
13027 break;
13030 if (type->classification() == Type::TYPE_STRUCT)
13032 Expression_list::iterator p = this->vals_->begin();
13033 while (p != this->vals_->end())
13035 // Skip key.
13036 ++p;
13037 go_assert(p != this->vals_->end());
13038 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13039 return TRAVERSE_EXIT;
13040 ++p;
13042 return TRAVERSE_CONTINUE;
13046 if (this->vals_ != NULL)
13047 return this->vals_->traverse(traverse);
13049 return TRAVERSE_CONTINUE;
13052 // Lower a generic composite literal into a specific version based on
13053 // the type.
13055 Expression*
13056 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13057 Statement_inserter* inserter, int)
13059 Type* type = this->type_;
13061 for (int depth = this->depth_; depth > 0; --depth)
13063 if (type->array_type() != NULL)
13064 type = type->array_type()->element_type();
13065 else if (type->map_type() != NULL)
13066 type = type->map_type()->val_type();
13067 else
13069 if (!type->is_error())
13070 error_at(this->location(),
13071 ("may only omit types within composite literals "
13072 "of slice, array, or map type"));
13073 return Expression::make_error(this->location());
13077 Type *pt = type->points_to();
13078 bool is_pointer = false;
13079 if (pt != NULL)
13081 is_pointer = true;
13082 type = pt;
13085 Expression* ret;
13086 if (type->is_error())
13087 return Expression::make_error(this->location());
13088 else if (type->struct_type() != NULL)
13089 ret = this->lower_struct(gogo, type);
13090 else if (type->array_type() != NULL)
13091 ret = this->lower_array(type);
13092 else if (type->map_type() != NULL)
13093 ret = this->lower_map(gogo, function, inserter, type);
13094 else
13096 error_at(this->location(),
13097 ("expected struct, slice, array, or map type "
13098 "for composite literal"));
13099 return Expression::make_error(this->location());
13102 if (is_pointer)
13103 ret = Expression::make_heap_expression(ret, this->location());
13105 return ret;
13108 // Lower a struct composite literal.
13110 Expression*
13111 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13113 Location location = this->location();
13114 Struct_type* st = type->struct_type();
13115 if (this->vals_ == NULL || !this->has_keys_)
13117 if (this->vals_ != NULL
13118 && !this->vals_->empty()
13119 && type->named_type() != NULL
13120 && type->named_type()->named_object()->package() != NULL)
13122 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13123 pf != st->fields()->end();
13124 ++pf)
13126 if (Gogo::is_hidden_name(pf->field_name()))
13127 error_at(this->location(),
13128 "assignment of unexported field %qs in %qs literal",
13129 Gogo::message_name(pf->field_name()).c_str(),
13130 type->named_type()->message_name().c_str());
13134 return new Struct_construction_expression(type, this->vals_, location);
13137 size_t field_count = st->field_count();
13138 std::vector<Expression*> vals(field_count);
13139 std::vector<int>* traverse_order = new(std::vector<int>);
13140 Expression_list::const_iterator p = this->vals_->begin();
13141 Expression* external_expr = NULL;
13142 const Named_object* external_no = NULL;
13143 while (p != this->vals_->end())
13145 Expression* name_expr = *p;
13147 ++p;
13148 go_assert(p != this->vals_->end());
13149 Expression* val = *p;
13151 ++p;
13153 if (name_expr == NULL)
13155 error_at(val->location(), "mixture of field and value initializers");
13156 return Expression::make_error(location);
13159 bool bad_key = false;
13160 std::string name;
13161 const Named_object* no = NULL;
13162 switch (name_expr->classification())
13164 case EXPRESSION_UNKNOWN_REFERENCE:
13165 name = name_expr->unknown_expression()->name();
13166 break;
13168 case EXPRESSION_CONST_REFERENCE:
13169 no = static_cast<Const_expression*>(name_expr)->named_object();
13170 break;
13172 case EXPRESSION_TYPE:
13174 Type* t = name_expr->type();
13175 Named_type* nt = t->named_type();
13176 if (nt == NULL)
13177 bad_key = true;
13178 else
13179 no = nt->named_object();
13181 break;
13183 case EXPRESSION_VAR_REFERENCE:
13184 no = name_expr->var_expression()->named_object();
13185 break;
13187 case EXPRESSION_FUNC_REFERENCE:
13188 no = name_expr->func_expression()->named_object();
13189 break;
13191 case EXPRESSION_UNARY:
13192 // If there is a local variable around with the same name as
13193 // the field, and this occurs in the closure, then the
13194 // parser may turn the field reference into an indirection
13195 // through the closure. FIXME: This is a mess.
13197 bad_key = true;
13198 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13199 if (ue->op() == OPERATOR_MULT)
13201 Field_reference_expression* fre =
13202 ue->operand()->field_reference_expression();
13203 if (fre != NULL)
13205 Struct_type* st =
13206 fre->expr()->type()->deref()->struct_type();
13207 if (st != NULL)
13209 const Struct_field* sf = st->field(fre->field_index());
13210 name = sf->field_name();
13212 // See below. FIXME.
13213 if (!Gogo::is_hidden_name(name)
13214 && name[0] >= 'a'
13215 && name[0] <= 'z')
13217 if (gogo->lookup_global(name.c_str()) != NULL)
13218 name = gogo->pack_hidden_name(name, false);
13221 char buf[20];
13222 snprintf(buf, sizeof buf, "%u", fre->field_index());
13223 size_t buflen = strlen(buf);
13224 if (name.compare(name.length() - buflen, buflen, buf)
13225 == 0)
13227 name = name.substr(0, name.length() - buflen);
13228 bad_key = false;
13234 break;
13236 default:
13237 bad_key = true;
13238 break;
13240 if (bad_key)
13242 error_at(name_expr->location(), "expected struct field name");
13243 return Expression::make_error(location);
13246 if (no != NULL)
13248 if (no->package() != NULL && external_expr == NULL)
13250 external_expr = name_expr;
13251 external_no = no;
13254 name = no->name();
13256 // A predefined name won't be packed. If it starts with a
13257 // lower case letter we need to check for that case, because
13258 // the field name will be packed. FIXME.
13259 if (!Gogo::is_hidden_name(name)
13260 && name[0] >= 'a'
13261 && name[0] <= 'z')
13263 Named_object* gno = gogo->lookup_global(name.c_str());
13264 if (gno == no)
13265 name = gogo->pack_hidden_name(name, false);
13269 unsigned int index;
13270 const Struct_field* sf = st->find_local_field(name, &index);
13271 if (sf == NULL)
13273 error_at(name_expr->location(), "unknown field %qs in %qs",
13274 Gogo::message_name(name).c_str(),
13275 (type->named_type() != NULL
13276 ? type->named_type()->message_name().c_str()
13277 : "unnamed struct"));
13278 return Expression::make_error(location);
13280 if (vals[index] != NULL)
13282 error_at(name_expr->location(),
13283 "duplicate value for field %qs in %qs",
13284 Gogo::message_name(name).c_str(),
13285 (type->named_type() != NULL
13286 ? type->named_type()->message_name().c_str()
13287 : "unnamed struct"));
13288 return Expression::make_error(location);
13291 if (type->named_type() != NULL
13292 && type->named_type()->named_object()->package() != NULL
13293 && Gogo::is_hidden_name(sf->field_name()))
13294 error_at(name_expr->location(),
13295 "assignment of unexported field %qs in %qs literal",
13296 Gogo::message_name(sf->field_name()).c_str(),
13297 type->named_type()->message_name().c_str());
13299 vals[index] = val;
13300 traverse_order->push_back(index);
13303 if (!this->all_are_names_)
13305 // This is a weird case like bug462 in the testsuite.
13306 if (external_expr == NULL)
13307 error_at(this->location(), "unknown field in %qs literal",
13308 (type->named_type() != NULL
13309 ? type->named_type()->message_name().c_str()
13310 : "unnamed struct"));
13311 else
13312 error_at(external_expr->location(), "unknown field %qs in %qs",
13313 external_no->message_name().c_str(),
13314 (type->named_type() != NULL
13315 ? type->named_type()->message_name().c_str()
13316 : "unnamed struct"));
13317 return Expression::make_error(location);
13320 Expression_list* list = new Expression_list;
13321 list->reserve(field_count);
13322 for (size_t i = 0; i < field_count; ++i)
13323 list->push_back(vals[i]);
13325 Struct_construction_expression* ret =
13326 new Struct_construction_expression(type, list, location);
13327 ret->set_traverse_order(traverse_order);
13328 return ret;
13331 // Used to sort an index/value array.
13333 class Index_value_compare
13335 public:
13336 bool
13337 operator()(const std::pair<unsigned long, Expression*>& a,
13338 const std::pair<unsigned long, Expression*>& b)
13339 { return a.first < b.first; }
13342 // Lower an array composite literal.
13344 Expression*
13345 Composite_literal_expression::lower_array(Type* type)
13347 Location location = this->location();
13348 if (this->vals_ == NULL || !this->has_keys_)
13349 return this->make_array(type, NULL, this->vals_);
13351 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13352 indexes->reserve(this->vals_->size());
13353 bool indexes_out_of_order = false;
13354 Expression_list* vals = new Expression_list();
13355 vals->reserve(this->vals_->size());
13356 unsigned long index = 0;
13357 Expression_list::const_iterator p = this->vals_->begin();
13358 while (p != this->vals_->end())
13360 Expression* index_expr = *p;
13362 ++p;
13363 go_assert(p != this->vals_->end());
13364 Expression* val = *p;
13366 ++p;
13368 if (index_expr == NULL)
13370 if (!indexes->empty())
13371 indexes->push_back(index);
13373 else
13375 if (indexes->empty() && !vals->empty())
13377 for (size_t i = 0; i < vals->size(); ++i)
13378 indexes->push_back(i);
13381 Numeric_constant nc;
13382 if (!index_expr->numeric_constant_value(&nc))
13384 error_at(index_expr->location(),
13385 "index expression is not integer constant");
13386 return Expression::make_error(location);
13389 switch (nc.to_unsigned_long(&index))
13391 case Numeric_constant::NC_UL_VALID:
13392 break;
13393 case Numeric_constant::NC_UL_NOTINT:
13394 error_at(index_expr->location(),
13395 "index expression is not integer constant");
13396 return Expression::make_error(location);
13397 case Numeric_constant::NC_UL_NEGATIVE:
13398 error_at(index_expr->location(), "index expression is negative");
13399 return Expression::make_error(location);
13400 case Numeric_constant::NC_UL_BIG:
13401 error_at(index_expr->location(), "index value overflow");
13402 return Expression::make_error(location);
13403 default:
13404 go_unreachable();
13407 Named_type* ntype = Type::lookup_integer_type("int");
13408 Integer_type* inttype = ntype->integer_type();
13409 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13410 && index >> (inttype->bits() - 1) != 0)
13412 error_at(index_expr->location(), "index value overflow");
13413 return Expression::make_error(location);
13416 if (std::find(indexes->begin(), indexes->end(), index)
13417 != indexes->end())
13419 error_at(index_expr->location(), "duplicate value for index %lu",
13420 index);
13421 return Expression::make_error(location);
13424 if (!indexes->empty() && index < indexes->back())
13425 indexes_out_of_order = true;
13427 indexes->push_back(index);
13430 vals->push_back(val);
13432 ++index;
13435 if (indexes->empty())
13437 delete indexes;
13438 indexes = NULL;
13441 if (indexes_out_of_order)
13443 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13445 V v;
13446 v.reserve(indexes->size());
13447 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13448 for (Expression_list::const_iterator pe = vals->begin();
13449 pe != vals->end();
13450 ++pe, ++pi)
13451 v.push_back(std::make_pair(*pi, *pe));
13453 std::sort(v.begin(), v.end(), Index_value_compare());
13455 delete indexes;
13456 delete vals;
13457 indexes = new std::vector<unsigned long>();
13458 indexes->reserve(v.size());
13459 vals = new Expression_list();
13460 vals->reserve(v.size());
13462 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13464 indexes->push_back(p->first);
13465 vals->push_back(p->second);
13469 return this->make_array(type, indexes, vals);
13472 // Actually build the array composite literal. This handles
13473 // [...]{...}.
13475 Expression*
13476 Composite_literal_expression::make_array(
13477 Type* type,
13478 const std::vector<unsigned long>* indexes,
13479 Expression_list* vals)
13481 Location location = this->location();
13482 Array_type* at = type->array_type();
13484 if (at->length() != NULL && at->length()->is_nil_expression())
13486 size_t size;
13487 if (vals == NULL)
13488 size = 0;
13489 else if (indexes != NULL)
13490 size = indexes->back() + 1;
13491 else
13493 size = vals->size();
13494 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13495 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13496 && size >> (it->bits() - 1) != 0)
13498 error_at(location, "too many elements in composite literal");
13499 return Expression::make_error(location);
13503 mpz_t vlen;
13504 mpz_init_set_ui(vlen, size);
13505 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13506 mpz_clear(vlen);
13507 at = Type::make_array_type(at->element_type(), elen);
13508 type = at;
13510 else if (at->length() != NULL
13511 && !at->length()->is_error_expression()
13512 && this->vals_ != NULL)
13514 Numeric_constant nc;
13515 unsigned long val;
13516 if (at->length()->numeric_constant_value(&nc)
13517 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13519 if (indexes == NULL)
13521 if (this->vals_->size() > val)
13523 error_at(location, "too many elements in composite literal");
13524 return Expression::make_error(location);
13527 else
13529 unsigned long max = indexes->back();
13530 if (max >= val)
13532 error_at(location,
13533 ("some element keys in composite literal "
13534 "are out of range"));
13535 return Expression::make_error(location);
13541 if (at->length() != NULL)
13542 return new Fixed_array_construction_expression(type, indexes, vals,
13543 location);
13544 else
13545 return new Slice_construction_expression(type, indexes, vals, location);
13548 // Lower a map composite literal.
13550 Expression*
13551 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13552 Statement_inserter* inserter,
13553 Type* type)
13555 Location location = this->location();
13556 if (this->vals_ != NULL)
13558 if (!this->has_keys_)
13560 error_at(location, "map composite literal must have keys");
13561 return Expression::make_error(location);
13564 for (Expression_list::iterator p = this->vals_->begin();
13565 p != this->vals_->end();
13566 p += 2)
13568 if (*p == NULL)
13570 ++p;
13571 error_at((*p)->location(),
13572 "map composite literal must have keys for every value");
13573 return Expression::make_error(location);
13575 // Make sure we have lowered the key; it may not have been
13576 // lowered in order to handle keys for struct composite
13577 // literals. Lower it now to get the right error message.
13578 if ((*p)->unknown_expression() != NULL)
13580 (*p)->unknown_expression()->clear_is_composite_literal_key();
13581 gogo->lower_expression(function, inserter, &*p);
13582 go_assert((*p)->is_error_expression());
13583 return Expression::make_error(location);
13588 return new Map_construction_expression(type, this->vals_, location);
13591 // Dump ast representation for a composite literal expression.
13593 void
13594 Composite_literal_expression::do_dump_expression(
13595 Ast_dump_context* ast_dump_context) const
13597 ast_dump_context->ostream() << "composite(";
13598 ast_dump_context->dump_type(this->type_);
13599 ast_dump_context->ostream() << ", {";
13600 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13601 ast_dump_context->ostream() << "})";
13604 // Make a composite literal expression.
13606 Expression*
13607 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13608 Expression_list* vals, bool all_are_names,
13609 Location location)
13611 return new Composite_literal_expression(type, depth, has_keys, vals,
13612 all_are_names, location);
13615 // Return whether this expression is a composite literal.
13617 bool
13618 Expression::is_composite_literal() const
13620 switch (this->classification_)
13622 case EXPRESSION_COMPOSITE_LITERAL:
13623 case EXPRESSION_STRUCT_CONSTRUCTION:
13624 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13625 case EXPRESSION_SLICE_CONSTRUCTION:
13626 case EXPRESSION_MAP_CONSTRUCTION:
13627 return true;
13628 default:
13629 return false;
13633 // Return whether this expression is a composite literal which is not
13634 // constant.
13636 bool
13637 Expression::is_nonconstant_composite_literal() const
13639 switch (this->classification_)
13641 case EXPRESSION_STRUCT_CONSTRUCTION:
13643 const Struct_construction_expression *psce =
13644 static_cast<const Struct_construction_expression*>(this);
13645 return !psce->is_constant_struct();
13647 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13649 const Fixed_array_construction_expression *pace =
13650 static_cast<const Fixed_array_construction_expression*>(this);
13651 return !pace->is_constant_array();
13653 case EXPRESSION_SLICE_CONSTRUCTION:
13655 const Slice_construction_expression *pace =
13656 static_cast<const Slice_construction_expression*>(this);
13657 return !pace->is_constant_array();
13659 case EXPRESSION_MAP_CONSTRUCTION:
13660 return true;
13661 default:
13662 return false;
13666 // Return true if this is a variable or temporary_variable.
13668 bool
13669 Expression::is_variable() const
13671 switch (this->classification_)
13673 case EXPRESSION_VAR_REFERENCE:
13674 case EXPRESSION_TEMPORARY_REFERENCE:
13675 case EXPRESSION_SET_AND_USE_TEMPORARY:
13676 return true;
13677 default:
13678 return false;
13682 // Return true if this is a reference to a local variable.
13684 bool
13685 Expression::is_local_variable() const
13687 const Var_expression* ve = this->var_expression();
13688 if (ve == NULL)
13689 return false;
13690 const Named_object* no = ve->named_object();
13691 return (no->is_result_variable()
13692 || (no->is_variable() && !no->var_value()->is_global()));
13695 // Class Type_guard_expression.
13697 // Traversal.
13700 Type_guard_expression::do_traverse(Traverse* traverse)
13702 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13703 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13704 return TRAVERSE_EXIT;
13705 return TRAVERSE_CONTINUE;
13708 Expression*
13709 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13710 Statement_inserter* inserter)
13712 if (!this->expr_->is_variable())
13714 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13715 this->location());
13716 inserter->insert(temp);
13717 this->expr_ =
13718 Expression::make_temporary_reference(temp, this->location());
13720 return this;
13723 // Check types of a type guard expression. The expression must have
13724 // an interface type, but the actual type conversion is checked at run
13725 // time.
13727 void
13728 Type_guard_expression::do_check_types(Gogo*)
13730 Type* expr_type = this->expr_->type();
13731 if (expr_type->interface_type() == NULL)
13733 if (!expr_type->is_error() && !this->type_->is_error())
13734 this->report_error(_("type assertion only valid for interface types"));
13735 this->set_is_error();
13737 else if (this->type_->interface_type() == NULL)
13739 std::string reason;
13740 if (!expr_type->interface_type()->implements_interface(this->type_,
13741 &reason))
13743 if (!this->type_->is_error())
13745 if (reason.empty())
13746 this->report_error(_("impossible type assertion: "
13747 "type does not implement interface"));
13748 else
13749 error_at(this->location(),
13750 ("impossible type assertion: "
13751 "type does not implement interface (%s)"),
13752 reason.c_str());
13754 this->set_is_error();
13759 // Return a tree for a type guard expression.
13761 tree
13762 Type_guard_expression::do_get_tree(Translate_context* context)
13764 Expression* conversion;
13765 if (this->type_->interface_type() != NULL)
13766 conversion =
13767 Expression::convert_interface_to_interface(this->type_, this->expr_,
13768 true, this->location());
13769 else
13770 conversion =
13771 Expression::convert_for_assignment(context->gogo(), this->type_,
13772 this->expr_, this->location());
13774 return conversion->get_tree(context);
13777 // Dump ast representation for a type guard expression.
13779 void
13780 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13781 const
13783 this->expr_->dump_expression(ast_dump_context);
13784 ast_dump_context->ostream() << ".";
13785 ast_dump_context->dump_type(this->type_);
13788 // Make a type guard expression.
13790 Expression*
13791 Expression::make_type_guard(Expression* expr, Type* type,
13792 Location location)
13794 return new Type_guard_expression(expr, type, location);
13797 // Class Heap_expression.
13799 // When you take the address of an escaping expression, it is allocated
13800 // on the heap. This class implements that.
13802 class Heap_expression : public Expression
13804 public:
13805 Heap_expression(Expression* expr, Location location)
13806 : Expression(EXPRESSION_HEAP, location),
13807 expr_(expr)
13810 protected:
13812 do_traverse(Traverse* traverse)
13813 { return Expression::traverse(&this->expr_, traverse); }
13815 Type*
13816 do_type()
13817 { return Type::make_pointer_type(this->expr_->type()); }
13819 void
13820 do_determine_type(const Type_context*)
13821 { this->expr_->determine_type_no_context(); }
13823 Expression*
13824 do_copy()
13826 return Expression::make_heap_expression(this->expr_->copy(),
13827 this->location());
13830 tree
13831 do_get_tree(Translate_context*);
13833 // We only export global objects, and the parser does not generate
13834 // this in global scope.
13835 void
13836 do_export(Export*) const
13837 { go_unreachable(); }
13839 void
13840 do_dump_expression(Ast_dump_context*) const;
13842 private:
13843 // The expression which is being put on the heap.
13844 Expression* expr_;
13847 // Return a tree which allocates an expression on the heap.
13849 tree
13850 Heap_expression::do_get_tree(Translate_context* context)
13852 tree expr_tree = this->expr_->get_tree(context);
13853 if (expr_tree == error_mark_node || TREE_TYPE(expr_tree) == error_mark_node)
13854 return error_mark_node;
13856 Expression* alloc =
13857 Expression::make_allocation(this->expr_->type(), this->location());
13859 Gogo* gogo = context->gogo();
13860 Btype* btype = this->expr_->type()->get_backend(gogo);
13861 size_t expr_size = gogo->backend()->type_size(btype);
13862 tree space = alloc->get_tree(context);
13863 if (expr_size == 0)
13864 return space;
13866 space = save_expr(space);
13867 tree ref = build_fold_indirect_ref_loc(this->location().gcc_location(),
13868 space);
13869 TREE_THIS_NOTRAP(ref) = 1;
13870 tree ret = build2(COMPOUND_EXPR,
13871 type_to_tree(this->type()->get_backend(gogo)),
13872 build2(MODIFY_EXPR, void_type_node, ref, expr_tree),
13873 space);
13874 SET_EXPR_LOCATION(ret, this->location().gcc_location());
13875 return ret;
13878 // Dump ast representation for a heap expression.
13880 void
13881 Heap_expression::do_dump_expression(
13882 Ast_dump_context* ast_dump_context) const
13884 ast_dump_context->ostream() << "&(";
13885 ast_dump_context->dump_expression(this->expr_);
13886 ast_dump_context->ostream() << ")";
13889 // Allocate an expression on the heap.
13891 Expression*
13892 Expression::make_heap_expression(Expression* expr, Location location)
13894 return new Heap_expression(expr, location);
13897 // Class Receive_expression.
13899 // Return the type of a receive expression.
13901 Type*
13902 Receive_expression::do_type()
13904 Channel_type* channel_type = this->channel_->type()->channel_type();
13905 if (channel_type == NULL)
13906 return Type::make_error_type();
13907 return channel_type->element_type();
13910 // Check types for a receive expression.
13912 void
13913 Receive_expression::do_check_types(Gogo*)
13915 Type* type = this->channel_->type();
13916 if (type->is_error())
13918 this->set_is_error();
13919 return;
13921 if (type->channel_type() == NULL)
13923 this->report_error(_("expected channel"));
13924 return;
13926 if (!type->channel_type()->may_receive())
13928 this->report_error(_("invalid receive on send-only channel"));
13929 return;
13933 // Flattening for receive expressions creates a temporary variable to store
13934 // received data in for receives.
13936 Expression*
13937 Receive_expression::do_flatten(Gogo*, Named_object*,
13938 Statement_inserter* inserter)
13940 Channel_type* channel_type = this->channel_->type()->channel_type();
13941 if (channel_type == NULL)
13943 go_assert(saw_errors());
13944 return this;
13947 Type* element_type = channel_type->element_type();
13948 if (this->temp_receiver_ == NULL)
13950 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13951 this->location());
13952 this->temp_receiver_->set_is_address_taken();
13953 inserter->insert(this->temp_receiver_);
13956 return this;
13959 // Get a tree for a receive expression.
13961 tree
13962 Receive_expression::do_get_tree(Translate_context* context)
13964 Location loc = this->location();
13966 Channel_type* channel_type = this->channel_->type()->channel_type();
13967 if (channel_type == NULL)
13969 go_assert(this->channel_->type()->is_error());
13970 return error_mark_node;
13972 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13974 Expression* recv_ref =
13975 Expression::make_temporary_reference(this->temp_receiver_, loc);
13976 Expression* recv_addr =
13977 Expression::make_temporary_reference(this->temp_receiver_, loc);
13978 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13979 Expression* recv =
13980 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13981 td, this->channel_, recv_addr);
13982 recv = Expression::make_compound(recv, recv_ref, loc);
13983 return recv->get_tree(context);
13986 // Dump ast representation for a receive expression.
13988 void
13989 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13991 ast_dump_context->ostream() << " <- " ;
13992 ast_dump_context->dump_expression(channel_);
13995 // Make a receive expression.
13997 Receive_expression*
13998 Expression::make_receive(Expression* channel, Location location)
14000 return new Receive_expression(channel, location);
14003 // An expression which evaluates to a pointer to the type descriptor
14004 // of a type.
14006 class Type_descriptor_expression : public Expression
14008 public:
14009 Type_descriptor_expression(Type* type, Location location)
14010 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14011 type_(type)
14014 protected:
14015 Type*
14016 do_type()
14017 { return Type::make_type_descriptor_ptr_type(); }
14019 bool
14020 do_is_immutable() const
14021 { return true; }
14023 void
14024 do_determine_type(const Type_context*)
14027 Expression*
14028 do_copy()
14029 { return this; }
14031 tree
14032 do_get_tree(Translate_context* context)
14034 Bexpression* ret = this->type_->type_descriptor_pointer(context->gogo(),
14035 this->location());
14036 return expr_to_tree(ret);
14039 void
14040 do_dump_expression(Ast_dump_context*) const;
14042 private:
14043 // The type for which this is the descriptor.
14044 Type* type_;
14047 // Dump ast representation for a type descriptor expression.
14049 void
14050 Type_descriptor_expression::do_dump_expression(
14051 Ast_dump_context* ast_dump_context) const
14053 ast_dump_context->dump_type(this->type_);
14056 // Make a type descriptor expression.
14058 Expression*
14059 Expression::make_type_descriptor(Type* type, Location location)
14061 return new Type_descriptor_expression(type, location);
14064 // An expression which evaluates to some characteristic of a type.
14065 // This is only used to initialize fields of a type descriptor. Using
14066 // a new expression class is slightly inefficient but gives us a good
14067 // separation between the frontend and the middle-end with regard to
14068 // how types are laid out.
14070 class Type_info_expression : public Expression
14072 public:
14073 Type_info_expression(Type* type, Type_info type_info)
14074 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14075 type_(type), type_info_(type_info)
14078 protected:
14079 Type*
14080 do_type();
14082 void
14083 do_determine_type(const Type_context*)
14086 Expression*
14087 do_copy()
14088 { return this; }
14090 tree
14091 do_get_tree(Translate_context* context);
14093 void
14094 do_dump_expression(Ast_dump_context*) const;
14096 private:
14097 // The type for which we are getting information.
14098 Type* type_;
14099 // What information we want.
14100 Type_info type_info_;
14103 // The type is chosen to match what the type descriptor struct
14104 // expects.
14106 Type*
14107 Type_info_expression::do_type()
14109 switch (this->type_info_)
14111 case TYPE_INFO_SIZE:
14112 return Type::lookup_integer_type("uintptr");
14113 case TYPE_INFO_ALIGNMENT:
14114 case TYPE_INFO_FIELD_ALIGNMENT:
14115 return Type::lookup_integer_type("uint8");
14116 default:
14117 go_unreachable();
14121 // Return type information in GENERIC.
14123 tree
14124 Type_info_expression::do_get_tree(Translate_context* context)
14126 Btype* btype = this->type_->get_backend(context->gogo());
14127 Gogo* gogo = context->gogo();
14128 size_t val;
14129 switch (this->type_info_)
14131 case TYPE_INFO_SIZE:
14132 val = gogo->backend()->type_size(btype);
14133 break;
14134 case TYPE_INFO_ALIGNMENT:
14135 val = gogo->backend()->type_alignment(btype);
14136 break;
14137 case TYPE_INFO_FIELD_ALIGNMENT:
14138 val = gogo->backend()->type_field_alignment(btype);
14139 break;
14140 default:
14141 go_unreachable();
14143 tree val_type_tree = type_to_tree(this->type()->get_backend(gogo));
14144 go_assert(val_type_tree != error_mark_node);
14145 return build_int_cstu(val_type_tree, val);
14148 // Dump ast representation for a type info expression.
14150 void
14151 Type_info_expression::do_dump_expression(
14152 Ast_dump_context* ast_dump_context) const
14154 ast_dump_context->ostream() << "typeinfo(";
14155 ast_dump_context->dump_type(this->type_);
14156 ast_dump_context->ostream() << ",";
14157 ast_dump_context->ostream() <<
14158 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14159 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14160 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14161 : "unknown");
14162 ast_dump_context->ostream() << ")";
14165 // Make a type info expression.
14167 Expression*
14168 Expression::make_type_info(Type* type, Type_info type_info)
14170 return new Type_info_expression(type, type_info);
14173 // An expression that evaluates to some characteristic of a slice.
14174 // This is used when indexing, bound-checking, or nil checking a slice.
14176 class Slice_info_expression : public Expression
14178 public:
14179 Slice_info_expression(Expression* slice, Slice_info slice_info,
14180 Location location)
14181 : Expression(EXPRESSION_SLICE_INFO, location),
14182 slice_(slice), slice_info_(slice_info)
14185 protected:
14186 Type*
14187 do_type();
14189 void
14190 do_determine_type(const Type_context*)
14193 Expression*
14194 do_copy()
14196 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14197 this->location());
14200 tree
14201 do_get_tree(Translate_context* context);
14203 void
14204 do_dump_expression(Ast_dump_context*) const;
14206 void
14207 do_issue_nil_check()
14208 { this->slice_->issue_nil_check(); }
14210 private:
14211 // The slice for which we are getting information.
14212 Expression* slice_;
14213 // What information we want.
14214 Slice_info slice_info_;
14217 // Return the type of the slice info.
14219 Type*
14220 Slice_info_expression::do_type()
14222 switch (this->slice_info_)
14224 case SLICE_INFO_VALUE_POINTER:
14225 return Type::make_pointer_type(
14226 this->slice_->type()->array_type()->element_type());
14227 case SLICE_INFO_LENGTH:
14228 case SLICE_INFO_CAPACITY:
14229 return Type::lookup_integer_type("int");
14230 default:
14231 go_unreachable();
14235 // Return slice information in GENERIC.
14237 tree
14238 Slice_info_expression::do_get_tree(Translate_context* context)
14240 Gogo* gogo = context->gogo();
14242 Bexpression* bslice = tree_to_expr(this->slice_->get_tree(context));
14243 Bexpression* ret;
14244 switch (this->slice_info_)
14246 case SLICE_INFO_VALUE_POINTER:
14247 case SLICE_INFO_LENGTH:
14248 case SLICE_INFO_CAPACITY:
14249 ret = gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14250 this->location());
14251 break;
14252 default:
14253 go_unreachable();
14255 return expr_to_tree(ret);
14258 // Dump ast representation for a type info expression.
14260 void
14261 Slice_info_expression::do_dump_expression(
14262 Ast_dump_context* ast_dump_context) const
14264 ast_dump_context->ostream() << "sliceinfo(";
14265 this->slice_->dump_expression(ast_dump_context);
14266 ast_dump_context->ostream() << ",";
14267 ast_dump_context->ostream() <<
14268 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14269 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14270 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14271 : "unknown");
14272 ast_dump_context->ostream() << ")";
14275 // Make a slice info expression.
14277 Expression*
14278 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14279 Location location)
14281 return new Slice_info_expression(slice, slice_info, location);
14284 // An expression that represents a slice value: a struct with value pointer,
14285 // length, and capacity fields.
14287 class Slice_value_expression : public Expression
14289 public:
14290 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14291 Expression* cap, Location location)
14292 : Expression(EXPRESSION_SLICE_VALUE, location),
14293 type_(type), valptr_(valptr), len_(len), cap_(cap)
14296 protected:
14298 do_traverse(Traverse*);
14300 Type*
14301 do_type()
14302 { return this->type_; }
14304 void
14305 do_determine_type(const Type_context*)
14306 { go_unreachable(); }
14308 Expression*
14309 do_copy()
14311 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14312 this->len_->copy(), this->cap_->copy(),
14313 this->location());
14316 tree
14317 do_get_tree(Translate_context* context);
14319 void
14320 do_dump_expression(Ast_dump_context*) const;
14322 private:
14323 // The type of the slice value.
14324 Type* type_;
14325 // The pointer to the values in the slice.
14326 Expression* valptr_;
14327 // The length of the slice.
14328 Expression* len_;
14329 // The capacity of the slice.
14330 Expression* cap_;
14334 Slice_value_expression::do_traverse(Traverse* traverse)
14336 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14337 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14338 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14339 return TRAVERSE_EXIT;
14340 return TRAVERSE_CONTINUE;
14343 tree
14344 Slice_value_expression::do_get_tree(Translate_context* context)
14346 std::vector<Bexpression*> vals(3);
14347 vals[0] = tree_to_expr(this->valptr_->get_tree(context));
14348 vals[1] = tree_to_expr(this->len_->get_tree(context));
14349 vals[2] = tree_to_expr(this->cap_->get_tree(context));
14351 Gogo* gogo = context->gogo();
14352 Btype* btype = this->type_->get_backend(gogo);
14353 Bexpression* ret =
14354 gogo->backend()->constructor_expression(btype, vals, this->location());
14355 return expr_to_tree(ret);
14358 void
14359 Slice_value_expression::do_dump_expression(
14360 Ast_dump_context* ast_dump_context) const
14362 ast_dump_context->ostream() << "slicevalue(";
14363 ast_dump_context->ostream() << "values: ";
14364 this->valptr_->dump_expression(ast_dump_context);
14365 ast_dump_context->ostream() << ", length: ";
14366 this->len_->dump_expression(ast_dump_context);
14367 ast_dump_context->ostream() << ", capacity: ";
14368 this->cap_->dump_expression(ast_dump_context);
14369 ast_dump_context->ostream() << ")";
14372 Expression*
14373 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14374 Expression* cap, Location location)
14376 go_assert(at->is_slice_type());
14377 return new Slice_value_expression(at, valptr, len, cap, location);
14380 // An expression that evaluates to some characteristic of a non-empty interface.
14381 // This is used to access the method table or underlying object of an interface.
14383 class Interface_info_expression : public Expression
14385 public:
14386 Interface_info_expression(Expression* iface, Interface_info iface_info,
14387 Location location)
14388 : Expression(EXPRESSION_INTERFACE_INFO, location),
14389 iface_(iface), iface_info_(iface_info)
14392 protected:
14393 Type*
14394 do_type();
14396 void
14397 do_determine_type(const Type_context*)
14400 Expression*
14401 do_copy()
14403 return new Interface_info_expression(this->iface_->copy(),
14404 this->iface_info_, this->location());
14407 tree
14408 do_get_tree(Translate_context* context);
14410 void
14411 do_dump_expression(Ast_dump_context*) const;
14413 void
14414 do_issue_nil_check()
14415 { this->iface_->issue_nil_check(); }
14417 private:
14418 // The interface for which we are getting information.
14419 Expression* iface_;
14420 // What information we want.
14421 Interface_info iface_info_;
14424 // Return the type of the interface info.
14426 Type*
14427 Interface_info_expression::do_type()
14429 switch (this->iface_info_)
14431 case INTERFACE_INFO_METHODS:
14433 Type* pdt = Type::make_type_descriptor_ptr_type();
14434 if (this->iface_->type()->interface_type()->is_empty())
14435 return pdt;
14437 Location loc = this->location();
14438 Struct_field_list* sfl = new Struct_field_list();
14439 sfl->push_back(
14440 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14442 Interface_type* itype = this->iface_->type()->interface_type();
14443 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14444 p != itype->methods()->end();
14445 ++p)
14447 Function_type* ft = p->type()->function_type();
14448 go_assert(ft->receiver() == NULL);
14450 const Typed_identifier_list* params = ft->parameters();
14451 Typed_identifier_list* mparams = new Typed_identifier_list();
14452 if (params != NULL)
14453 mparams->reserve(params->size() + 1);
14454 Type* vt = Type::make_pointer_type(Type::make_void_type());
14455 mparams->push_back(Typed_identifier("", vt, ft->location()));
14456 if (params != NULL)
14458 for (Typed_identifier_list::const_iterator pp = params->begin();
14459 pp != params->end();
14460 ++pp)
14461 mparams->push_back(*pp);
14464 Typed_identifier_list* mresults = (ft->results() == NULL
14465 ? NULL
14466 : ft->results()->copy());
14467 Backend_function_type* mft =
14468 Type::make_backend_function_type(NULL, mparams, mresults,
14469 ft->location());
14471 std::string fname = Gogo::unpack_hidden_name(p->name());
14472 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14475 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14477 case INTERFACE_INFO_OBJECT:
14478 return Type::make_pointer_type(Type::make_void_type());
14479 default:
14480 go_unreachable();
14484 // Return interface information in GENERIC.
14486 tree
14487 Interface_info_expression::do_get_tree(Translate_context* context)
14489 Gogo* gogo = context->gogo();
14491 Bexpression* biface = tree_to_expr(this->iface_->get_tree(context));
14492 Bexpression* ret;
14493 switch (this->iface_info_)
14495 case INTERFACE_INFO_METHODS:
14496 case INTERFACE_INFO_OBJECT:
14497 ret = gogo->backend()->struct_field_expression(biface, this->iface_info_,
14498 this->location());
14499 break;
14500 default:
14501 go_unreachable();
14503 return expr_to_tree(ret);
14506 // Dump ast representation for an interface info expression.
14508 void
14509 Interface_info_expression::do_dump_expression(
14510 Ast_dump_context* ast_dump_context) const
14512 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14513 ast_dump_context->ostream() << "interfaceinfo(";
14514 this->iface_->dump_expression(ast_dump_context);
14515 ast_dump_context->ostream() << ",";
14516 ast_dump_context->ostream() <<
14517 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14518 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14519 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14520 : "unknown");
14521 ast_dump_context->ostream() << ")";
14524 // Make an interface info expression.
14526 Expression*
14527 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14528 Location location)
14530 return new Interface_info_expression(iface, iface_info, location);
14533 // An expression that represents an interface value. The first field is either
14534 // a type descriptor for an empty interface or a pointer to the interface method
14535 // table for a non-empty interface. The second field is always the object.
14537 class Interface_value_expression : public Expression
14539 public:
14540 Interface_value_expression(Type* type, Expression* first_field,
14541 Expression* obj, Location location)
14542 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14543 type_(type), first_field_(first_field), obj_(obj)
14546 protected:
14548 do_traverse(Traverse*);
14550 Type*
14551 do_type()
14552 { return this->type_; }
14554 void
14555 do_determine_type(const Type_context*)
14556 { go_unreachable(); }
14558 Expression*
14559 do_copy()
14561 return new Interface_value_expression(this->type_,
14562 this->first_field_->copy(),
14563 this->obj_->copy(), this->location());
14566 tree
14567 do_get_tree(Translate_context* context);
14569 void
14570 do_dump_expression(Ast_dump_context*) const;
14572 private:
14573 // The type of the interface value.
14574 Type* type_;
14575 // The first field of the interface (either a type descriptor or a pointer
14576 // to the method table.
14577 Expression* first_field_;
14578 // The underlying object of the interface.
14579 Expression* obj_;
14583 Interface_value_expression::do_traverse(Traverse* traverse)
14585 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14586 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14587 return TRAVERSE_EXIT;
14588 return TRAVERSE_CONTINUE;
14591 tree
14592 Interface_value_expression::do_get_tree(Translate_context* context)
14594 std::vector<Bexpression*> vals(2);
14595 vals[0] = tree_to_expr(this->first_field_->get_tree(context));
14596 vals[1] = tree_to_expr(this->obj_->get_tree(context));
14598 Gogo* gogo = context->gogo();
14599 Btype* btype = this->type_->get_backend(gogo);
14600 Bexpression* ret =
14601 gogo->backend()->constructor_expression(btype, vals, this->location());
14602 return expr_to_tree(ret);
14605 void
14606 Interface_value_expression::do_dump_expression(
14607 Ast_dump_context* ast_dump_context) const
14609 ast_dump_context->ostream() << "interfacevalue(";
14610 ast_dump_context->ostream() <<
14611 (this->type_->interface_type()->is_empty()
14612 ? "type_descriptor: "
14613 : "methods: ");
14614 this->first_field_->dump_expression(ast_dump_context);
14615 ast_dump_context->ostream() << ", object: ";
14616 this->obj_->dump_expression(ast_dump_context);
14617 ast_dump_context->ostream() << ")";
14620 Expression*
14621 Expression::make_interface_value(Type* type, Expression* first_value,
14622 Expression* object, Location location)
14624 return new Interface_value_expression(type, first_value, object, location);
14627 // An interface method table for a pair of types: an interface type and a type
14628 // that implements that interface.
14630 class Interface_mtable_expression : public Expression
14632 public:
14633 Interface_mtable_expression(Interface_type* itype, Type* type,
14634 bool is_pointer, Location location)
14635 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14636 itype_(itype), type_(type), is_pointer_(is_pointer),
14637 method_table_type_(NULL), bvar_(NULL)
14640 protected:
14642 do_traverse(Traverse*);
14644 Type*
14645 do_type();
14647 bool
14648 is_immutable() const
14649 { return true; }
14651 void
14652 do_determine_type(const Type_context*)
14653 { go_unreachable(); }
14655 Expression*
14656 do_copy()
14658 return new Interface_mtable_expression(this->itype_, this->type_,
14659 this->is_pointer_, this->location());
14662 bool
14663 do_is_addressable() const
14664 { return true; }
14666 tree
14667 do_get_tree(Translate_context* context);
14669 void
14670 do_dump_expression(Ast_dump_context*) const;
14672 private:
14673 // The interface type for which the methods are defined.
14674 Interface_type* itype_;
14675 // The type to construct the interface method table for.
14676 Type* type_;
14677 // Whether this table contains the method set for the receiver type or the
14678 // pointer receiver type.
14679 bool is_pointer_;
14680 // The type of the method table.
14681 Type* method_table_type_;
14682 // The backend variable that refers to the interface method table.
14683 Bvariable* bvar_;
14687 Interface_mtable_expression::do_traverse(Traverse* traverse)
14689 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14690 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14691 return TRAVERSE_EXIT;
14692 return TRAVERSE_CONTINUE;
14695 Type*
14696 Interface_mtable_expression::do_type()
14698 if (this->method_table_type_ != NULL)
14699 return this->method_table_type_;
14701 const Typed_identifier_list* interface_methods = this->itype_->methods();
14702 go_assert(!interface_methods->empty());
14704 Struct_field_list* sfl = new Struct_field_list;
14705 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14706 this->location());
14707 sfl->push_back(Struct_field(tid));
14708 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14709 p != interface_methods->end();
14710 ++p)
14711 sfl->push_back(Struct_field(*p));
14712 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14713 return this->method_table_type_;
14716 tree
14717 Interface_mtable_expression::do_get_tree(Translate_context* context)
14719 Gogo* gogo = context->gogo();
14720 Bexpression* ret;
14721 Location loc = Linemap::predeclared_location();
14722 if (this->bvar_ != NULL)
14724 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14725 return expr_to_tree(ret);
14728 const Typed_identifier_list* interface_methods = this->itype_->methods();
14729 go_assert(!interface_methods->empty());
14731 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14732 + this->itype_->mangled_name(gogo)
14733 + "__"
14734 + this->type_->mangled_name(gogo));
14736 // See whether this interface has any hidden methods.
14737 bool has_hidden_methods = false;
14738 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14739 p != interface_methods->end();
14740 ++p)
14742 if (Gogo::is_hidden_name(p->name()))
14744 has_hidden_methods = true;
14745 break;
14749 // We already know that the named type is convertible to the
14750 // interface. If the interface has hidden methods, and the named
14751 // type is defined in a different package, then the interface
14752 // conversion table will be defined by that other package.
14753 if (has_hidden_methods
14754 && this->type_->named_type() != NULL
14755 && this->type_->named_type()->named_object()->package() != NULL)
14757 Btype* btype = this->type()->get_backend(gogo);
14758 this->bvar_ =
14759 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14760 ret = gogo->backend()->var_expression(this->bvar_, this->location());
14761 return expr_to_tree(ret);
14764 // The first element is the type descriptor.
14765 Type* td_type;
14766 if (!this->is_pointer_)
14767 td_type = this->type_;
14768 else
14769 td_type = Type::make_pointer_type(this->type_);
14771 // Build an interface method table for a type: a type descriptor followed by a
14772 // list of function pointers, one for each interface method. This is used for
14773 // interfaces.
14774 Expression_list* svals = new Expression_list();
14775 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14777 Named_type* nt = this->type_->named_type();
14778 Struct_type* st = this->type_->struct_type();
14779 go_assert(nt != NULL || st != NULL);
14781 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14782 p != interface_methods->end();
14783 ++p)
14785 bool is_ambiguous;
14786 Method* m;
14787 if (nt != NULL)
14788 m = nt->method_function(p->name(), &is_ambiguous);
14789 else
14790 m = st->method_function(p->name(), &is_ambiguous);
14791 go_assert(m != NULL);
14792 Named_object* no = m->named_object();
14794 go_assert(no->is_function() || no->is_function_declaration());
14795 svals->push_back(Expression::make_func_code_reference(no, loc));
14798 Btype* btype = this->type()->get_backend(gogo);
14799 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14800 svals, loc);
14801 Bexpression* ctor = tree_to_expr(mtable->get_tree(context));
14803 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14804 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14805 !is_public, btype, loc);
14806 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14807 !is_public, btype, loc, ctor);
14808 ret = gogo->backend()->var_expression(this->bvar_, loc);
14809 return expr_to_tree(ret);
14812 void
14813 Interface_mtable_expression::do_dump_expression(
14814 Ast_dump_context* ast_dump_context) const
14816 ast_dump_context->ostream() << "__go_"
14817 << (this->is_pointer_ ? "pimt__" : "imt_");
14818 ast_dump_context->dump_type(this->itype_);
14819 ast_dump_context->ostream() << "__";
14820 ast_dump_context->dump_type(this->type_);
14823 Expression*
14824 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14825 bool is_pointer, Location location)
14827 return new Interface_mtable_expression(itype, type, is_pointer, location);
14830 // An expression which evaluates to the offset of a field within a
14831 // struct. This, like Type_info_expression, q.v., is only used to
14832 // initialize fields of a type descriptor.
14834 class Struct_field_offset_expression : public Expression
14836 public:
14837 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14838 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14839 Linemap::predeclared_location()),
14840 type_(type), field_(field)
14843 protected:
14844 Type*
14845 do_type()
14846 { return Type::lookup_integer_type("uintptr"); }
14848 void
14849 do_determine_type(const Type_context*)
14852 Expression*
14853 do_copy()
14854 { return this; }
14856 tree
14857 do_get_tree(Translate_context* context);
14859 void
14860 do_dump_expression(Ast_dump_context*) const;
14862 private:
14863 // The type of the struct.
14864 Struct_type* type_;
14865 // The field.
14866 const Struct_field* field_;
14869 // Return a struct field offset in GENERIC.
14871 tree
14872 Struct_field_offset_expression::do_get_tree(Translate_context* context)
14874 tree type_tree = type_to_tree(this->type_->get_backend(context->gogo()));
14875 if (type_tree == error_mark_node)
14876 return error_mark_node;
14878 tree val_type_tree = type_to_tree(this->type()->get_backend(context->gogo()));
14879 go_assert(val_type_tree != error_mark_node);
14881 const Struct_field_list* fields = this->type_->fields();
14882 tree struct_field_tree = TYPE_FIELDS(type_tree);
14883 Struct_field_list::const_iterator p;
14884 for (p = fields->begin();
14885 p != fields->end();
14886 ++p, struct_field_tree = DECL_CHAIN(struct_field_tree))
14888 go_assert(struct_field_tree != NULL_TREE);
14889 if (&*p == this->field_)
14890 break;
14892 go_assert(&*p == this->field_);
14894 return fold_convert_loc(BUILTINS_LOCATION, val_type_tree,
14895 byte_position(struct_field_tree));
14898 // Dump ast representation for a struct field offset expression.
14900 void
14901 Struct_field_offset_expression::do_dump_expression(
14902 Ast_dump_context* ast_dump_context) const
14904 ast_dump_context->ostream() << "unsafe.Offsetof(";
14905 ast_dump_context->dump_type(this->type_);
14906 ast_dump_context->ostream() << '.';
14907 ast_dump_context->ostream() <<
14908 Gogo::message_name(this->field_->field_name());
14909 ast_dump_context->ostream() << ")";
14912 // Make an expression for a struct field offset.
14914 Expression*
14915 Expression::make_struct_field_offset(Struct_type* type,
14916 const Struct_field* field)
14918 return new Struct_field_offset_expression(type, field);
14921 // An expression which evaluates to a pointer to the map descriptor of
14922 // a map type.
14924 class Map_descriptor_expression : public Expression
14926 public:
14927 Map_descriptor_expression(Map_type* type, Location location)
14928 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14929 type_(type)
14932 protected:
14933 Type*
14934 do_type()
14935 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14937 void
14938 do_determine_type(const Type_context*)
14941 Expression*
14942 do_copy()
14943 { return this; }
14945 tree
14946 do_get_tree(Translate_context* context)
14948 Bexpression* ret = this->type_->map_descriptor_pointer(context->gogo(),
14949 this->location());
14950 return expr_to_tree(ret);
14953 void
14954 do_dump_expression(Ast_dump_context*) const;
14956 private:
14957 // The type for which this is the descriptor.
14958 Map_type* type_;
14961 // Dump ast representation for a map descriptor expression.
14963 void
14964 Map_descriptor_expression::do_dump_expression(
14965 Ast_dump_context* ast_dump_context) const
14967 ast_dump_context->ostream() << "map_descriptor(";
14968 ast_dump_context->dump_type(this->type_);
14969 ast_dump_context->ostream() << ")";
14972 // Make a map descriptor expression.
14974 Expression*
14975 Expression::make_map_descriptor(Map_type* type, Location location)
14977 return new Map_descriptor_expression(type, location);
14980 // An expression which evaluates to the address of an unnamed label.
14982 class Label_addr_expression : public Expression
14984 public:
14985 Label_addr_expression(Label* label, Location location)
14986 : Expression(EXPRESSION_LABEL_ADDR, location),
14987 label_(label)
14990 protected:
14991 Type*
14992 do_type()
14993 { return Type::make_pointer_type(Type::make_void_type()); }
14995 void
14996 do_determine_type(const Type_context*)
14999 Expression*
15000 do_copy()
15001 { return new Label_addr_expression(this->label_, this->location()); }
15003 tree
15004 do_get_tree(Translate_context* context)
15006 return expr_to_tree(this->label_->get_addr(context, this->location()));
15009 void
15010 do_dump_expression(Ast_dump_context* ast_dump_context) const
15011 { ast_dump_context->ostream() << this->label_->name(); }
15013 private:
15014 // The label whose address we are taking.
15015 Label* label_;
15018 // Make an expression for the address of an unnamed label.
15020 Expression*
15021 Expression::make_label_addr(Label* label, Location location)
15023 return new Label_addr_expression(label, location);
15026 // Conditional expressions.
15028 class Conditional_expression : public Expression
15030 public:
15031 Conditional_expression(Expression* cond, Expression* then_expr,
15032 Expression* else_expr, Location location)
15033 : Expression(EXPRESSION_CONDITIONAL, location),
15034 cond_(cond), then_(then_expr), else_(else_expr)
15037 protected:
15039 do_traverse(Traverse*);
15041 Type*
15042 do_type();
15044 void
15045 do_determine_type(const Type_context*);
15047 Expression*
15048 do_copy()
15050 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
15051 this->else_->copy(), this->location());
15054 tree
15055 do_get_tree(Translate_context* context);
15057 void
15058 do_dump_expression(Ast_dump_context*) const;
15060 private:
15061 // The condition to be checked.
15062 Expression* cond_;
15063 // The expression to execute if the condition is true.
15064 Expression* then_;
15065 // The expression to execute if the condition is false.
15066 Expression* else_;
15069 // Traversal.
15072 Conditional_expression::do_traverse(Traverse* traverse)
15074 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15075 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15076 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15077 return TRAVERSE_EXIT;
15078 return TRAVERSE_CONTINUE;
15081 // Return the type of the conditional expression.
15083 Type*
15084 Conditional_expression::do_type()
15086 Type* result_type = Type::make_void_type();
15087 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15088 NULL))
15089 result_type = this->then_->type();
15090 else if (this->then_->is_nil_expression()
15091 || this->else_->is_nil_expression())
15092 result_type = (!this->then_->is_nil_expression()
15093 ? this->then_->type()
15094 : this->else_->type());
15095 return result_type;
15098 // Determine type for a conditional expression.
15100 void
15101 Conditional_expression::do_determine_type(const Type_context* context)
15103 this->cond_->determine_type_no_context();
15104 this->then_->determine_type(context);
15105 this->else_->determine_type(context);
15108 // Get the backend representation of a conditional expression.
15110 tree
15111 Conditional_expression::do_get_tree(Translate_context* context)
15113 Gogo* gogo = context->gogo();
15114 Btype* result_btype = this->type()->get_backend(gogo);
15115 Bexpression* cond = tree_to_expr(this->cond_->get_tree(context));
15116 Bexpression* then = tree_to_expr(this->then_->get_tree(context));
15117 Bexpression* belse = tree_to_expr(this->else_->get_tree(context));
15118 Bexpression* ret =
15119 gogo->backend()->conditional_expression(result_btype, cond, then, belse,
15120 this->location());
15121 return expr_to_tree(ret);
15124 // Dump ast representation of a conditional expression.
15126 void
15127 Conditional_expression::do_dump_expression(
15128 Ast_dump_context* ast_dump_context) const
15130 ast_dump_context->ostream() << "(";
15131 ast_dump_context->dump_expression(this->cond_);
15132 ast_dump_context->ostream() << " ? ";
15133 ast_dump_context->dump_expression(this->then_);
15134 ast_dump_context->ostream() << " : ";
15135 ast_dump_context->dump_expression(this->else_);
15136 ast_dump_context->ostream() << ") ";
15139 // Make a conditional expression.
15141 Expression*
15142 Expression::make_conditional(Expression* cond, Expression* then,
15143 Expression* else_expr, Location location)
15145 return new Conditional_expression(cond, then, else_expr, location);
15148 // Compound expressions.
15150 class Compound_expression : public Expression
15152 public:
15153 Compound_expression(Expression* init, Expression* expr, Location location)
15154 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
15157 protected:
15159 do_traverse(Traverse*);
15161 Type*
15162 do_type();
15164 void
15165 do_determine_type(const Type_context*);
15167 Expression*
15168 do_copy()
15170 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
15171 this->location());
15174 tree
15175 do_get_tree(Translate_context* context);
15177 void
15178 do_dump_expression(Ast_dump_context*) const;
15180 private:
15181 // The expression that is evaluated first and discarded.
15182 Expression* init_;
15183 // The expression that is evaluated and returned.
15184 Expression* expr_;
15187 // Traversal.
15190 Compound_expression::do_traverse(Traverse* traverse)
15192 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15193 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15194 return TRAVERSE_EXIT;
15195 return TRAVERSE_CONTINUE;
15198 // Return the type of the compound expression.
15200 Type*
15201 Compound_expression::do_type()
15203 return this->expr_->type();
15206 // Determine type for a compound expression.
15208 void
15209 Compound_expression::do_determine_type(const Type_context* context)
15211 this->init_->determine_type_no_context();
15212 this->expr_->determine_type(context);
15215 // Get the backend representation of a compound expression.
15217 tree
15218 Compound_expression::do_get_tree(Translate_context* context)
15220 Gogo* gogo = context->gogo();
15221 Bexpression* binit = tree_to_expr(this->init_->get_tree(context));
15222 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15223 Bexpression* bexpr = tree_to_expr(this->expr_->get_tree(context));
15224 Bexpression* ret = gogo->backend()->compound_expression(init_stmt, bexpr,
15225 this->location());
15226 return expr_to_tree(ret);
15229 // Dump ast representation of a conditional expression.
15231 void
15232 Compound_expression::do_dump_expression(
15233 Ast_dump_context* ast_dump_context) const
15235 ast_dump_context->ostream() << "(";
15236 ast_dump_context->dump_expression(this->init_);
15237 ast_dump_context->ostream() << ",";
15238 ast_dump_context->dump_expression(this->expr_);
15239 ast_dump_context->ostream() << ") ";
15242 // Make a compound expression.
15244 Expression*
15245 Expression::make_compound(Expression* init, Expression* expr, Location location)
15247 return new Compound_expression(init, expr, location);
15250 // Import an expression. This comes at the end in order to see the
15251 // various class definitions.
15253 Expression*
15254 Expression::import_expression(Import* imp)
15256 int c = imp->peek_char();
15257 if (imp->match_c_string("- ")
15258 || imp->match_c_string("! ")
15259 || imp->match_c_string("^ "))
15260 return Unary_expression::do_import(imp);
15261 else if (c == '(')
15262 return Binary_expression::do_import(imp);
15263 else if (imp->match_c_string("true")
15264 || imp->match_c_string("false"))
15265 return Boolean_expression::do_import(imp);
15266 else if (c == '"')
15267 return String_expression::do_import(imp);
15268 else if (c == '-' || (c >= '0' && c <= '9'))
15270 // This handles integers, floats and complex constants.
15271 return Integer_expression::do_import(imp);
15273 else if (imp->match_c_string("nil"))
15274 return Nil_expression::do_import(imp);
15275 else if (imp->match_c_string("convert"))
15276 return Type_conversion_expression::do_import(imp);
15277 else
15279 error_at(imp->location(), "import error: expected expression");
15280 return Expression::make_error(imp->location());
15284 // Class Expression_list.
15286 // Traverse the list.
15289 Expression_list::traverse(Traverse* traverse)
15291 for (Expression_list::iterator p = this->begin();
15292 p != this->end();
15293 ++p)
15295 if (*p != NULL)
15297 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15298 return TRAVERSE_EXIT;
15301 return TRAVERSE_CONTINUE;
15304 // Copy the list.
15306 Expression_list*
15307 Expression_list::copy()
15309 Expression_list* ret = new Expression_list();
15310 for (Expression_list::iterator p = this->begin();
15311 p != this->end();
15312 ++p)
15314 if (*p == NULL)
15315 ret->push_back(NULL);
15316 else
15317 ret->push_back((*p)->copy());
15319 return ret;
15322 // Return whether an expression list has an error expression.
15324 bool
15325 Expression_list::contains_error() const
15327 for (Expression_list::const_iterator p = this->begin();
15328 p != this->end();
15329 ++p)
15330 if (*p != NULL && (*p)->is_error_expression())
15331 return true;
15332 return false;
15335 // Class Numeric_constant.
15337 // Destructor.
15339 Numeric_constant::~Numeric_constant()
15341 this->clear();
15344 // Copy constructor.
15346 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15347 : classification_(a.classification_), type_(a.type_)
15349 switch (a.classification_)
15351 case NC_INVALID:
15352 break;
15353 case NC_INT:
15354 case NC_RUNE:
15355 mpz_init_set(this->u_.int_val, a.u_.int_val);
15356 break;
15357 case NC_FLOAT:
15358 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15359 break;
15360 case NC_COMPLEX:
15361 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15362 GMP_RNDN);
15363 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15364 GMP_RNDN);
15365 break;
15366 default:
15367 go_unreachable();
15371 // Assignment operator.
15373 Numeric_constant&
15374 Numeric_constant::operator=(const Numeric_constant& a)
15376 this->clear();
15377 this->classification_ = a.classification_;
15378 this->type_ = a.type_;
15379 switch (a.classification_)
15381 case NC_INVALID:
15382 break;
15383 case NC_INT:
15384 case NC_RUNE:
15385 mpz_init_set(this->u_.int_val, a.u_.int_val);
15386 break;
15387 case NC_FLOAT:
15388 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15389 break;
15390 case NC_COMPLEX:
15391 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15392 GMP_RNDN);
15393 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15394 GMP_RNDN);
15395 break;
15396 default:
15397 go_unreachable();
15399 return *this;
15402 // Clear the contents.
15404 void
15405 Numeric_constant::clear()
15407 switch (this->classification_)
15409 case NC_INVALID:
15410 break;
15411 case NC_INT:
15412 case NC_RUNE:
15413 mpz_clear(this->u_.int_val);
15414 break;
15415 case NC_FLOAT:
15416 mpfr_clear(this->u_.float_val);
15417 break;
15418 case NC_COMPLEX:
15419 mpfr_clear(this->u_.complex_val.real);
15420 mpfr_clear(this->u_.complex_val.imag);
15421 break;
15422 default:
15423 go_unreachable();
15425 this->classification_ = NC_INVALID;
15428 // Set to an unsigned long value.
15430 void
15431 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15433 this->clear();
15434 this->classification_ = NC_INT;
15435 this->type_ = type;
15436 mpz_init_set_ui(this->u_.int_val, val);
15439 // Set to an integer value.
15441 void
15442 Numeric_constant::set_int(Type* type, const mpz_t val)
15444 this->clear();
15445 this->classification_ = NC_INT;
15446 this->type_ = type;
15447 mpz_init_set(this->u_.int_val, val);
15450 // Set to a rune value.
15452 void
15453 Numeric_constant::set_rune(Type* type, const mpz_t val)
15455 this->clear();
15456 this->classification_ = NC_RUNE;
15457 this->type_ = type;
15458 mpz_init_set(this->u_.int_val, val);
15461 // Set to a floating point value.
15463 void
15464 Numeric_constant::set_float(Type* type, const mpfr_t val)
15466 this->clear();
15467 this->classification_ = NC_FLOAT;
15468 this->type_ = type;
15469 // Numeric constants do not have negative zero values, so remove
15470 // them here. They also don't have infinity or NaN values, but we
15471 // should never see them here.
15472 if (mpfr_zero_p(val))
15473 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15474 else
15475 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
15478 // Set to a complex value.
15480 void
15481 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15483 this->clear();
15484 this->classification_ = NC_COMPLEX;
15485 this->type_ = type;
15486 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15487 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15490 // Get an int value.
15492 void
15493 Numeric_constant::get_int(mpz_t* val) const
15495 go_assert(this->is_int());
15496 mpz_init_set(*val, this->u_.int_val);
15499 // Get a rune value.
15501 void
15502 Numeric_constant::get_rune(mpz_t* val) const
15504 go_assert(this->is_rune());
15505 mpz_init_set(*val, this->u_.int_val);
15508 // Get a floating point value.
15510 void
15511 Numeric_constant::get_float(mpfr_t* val) const
15513 go_assert(this->is_float());
15514 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15517 // Get a complex value.
15519 void
15520 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15522 go_assert(this->is_complex());
15523 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15524 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15527 // Express value as unsigned long if possible.
15529 Numeric_constant::To_unsigned_long
15530 Numeric_constant::to_unsigned_long(unsigned long* val) const
15532 switch (this->classification_)
15534 case NC_INT:
15535 case NC_RUNE:
15536 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15537 case NC_FLOAT:
15538 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15539 case NC_COMPLEX:
15540 if (!mpfr_zero_p(this->u_.complex_val.imag))
15541 return NC_UL_NOTINT;
15542 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15543 default:
15544 go_unreachable();
15548 // Express integer value as unsigned long if possible.
15550 Numeric_constant::To_unsigned_long
15551 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15552 unsigned long *val) const
15554 if (mpz_sgn(ival) < 0)
15555 return NC_UL_NEGATIVE;
15556 unsigned long ui = mpz_get_ui(ival);
15557 if (mpz_cmp_ui(ival, ui) != 0)
15558 return NC_UL_BIG;
15559 *val = ui;
15560 return NC_UL_VALID;
15563 // Express floating point value as unsigned long if possible.
15565 Numeric_constant::To_unsigned_long
15566 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15567 unsigned long *val) const
15569 if (!mpfr_integer_p(fval))
15570 return NC_UL_NOTINT;
15571 mpz_t ival;
15572 mpz_init(ival);
15573 mpfr_get_z(ival, fval, GMP_RNDN);
15574 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15575 mpz_clear(ival);
15576 return ret;
15579 // Convert value to integer if possible.
15581 bool
15582 Numeric_constant::to_int(mpz_t* val) const
15584 switch (this->classification_)
15586 case NC_INT:
15587 case NC_RUNE:
15588 mpz_init_set(*val, this->u_.int_val);
15589 return true;
15590 case NC_FLOAT:
15591 if (!mpfr_integer_p(this->u_.float_val))
15592 return false;
15593 mpz_init(*val);
15594 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15595 return true;
15596 case NC_COMPLEX:
15597 if (!mpfr_zero_p(this->u_.complex_val.imag)
15598 || !mpfr_integer_p(this->u_.complex_val.real))
15599 return false;
15600 mpz_init(*val);
15601 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15602 return true;
15603 default:
15604 go_unreachable();
15608 // Convert value to floating point if possible.
15610 bool
15611 Numeric_constant::to_float(mpfr_t* val) const
15613 switch (this->classification_)
15615 case NC_INT:
15616 case NC_RUNE:
15617 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15618 return true;
15619 case NC_FLOAT:
15620 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15621 return true;
15622 case NC_COMPLEX:
15623 if (!mpfr_zero_p(this->u_.complex_val.imag))
15624 return false;
15625 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15626 return true;
15627 default:
15628 go_unreachable();
15632 // Convert value to complex.
15634 bool
15635 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15637 switch (this->classification_)
15639 case NC_INT:
15640 case NC_RUNE:
15641 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15642 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15643 return true;
15644 case NC_FLOAT:
15645 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15646 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15647 return true;
15648 case NC_COMPLEX:
15649 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15650 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15651 return true;
15652 default:
15653 go_unreachable();
15657 // Get the type.
15659 Type*
15660 Numeric_constant::type() const
15662 if (this->type_ != NULL)
15663 return this->type_;
15664 switch (this->classification_)
15666 case NC_INT:
15667 return Type::make_abstract_integer_type();
15668 case NC_RUNE:
15669 return Type::make_abstract_character_type();
15670 case NC_FLOAT:
15671 return Type::make_abstract_float_type();
15672 case NC_COMPLEX:
15673 return Type::make_abstract_complex_type();
15674 default:
15675 go_unreachable();
15679 // If the constant can be expressed in TYPE, then set the type of the
15680 // constant to TYPE and return true. Otherwise return false, and, if
15681 // ISSUE_ERROR is true, report an appropriate error message.
15683 bool
15684 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15686 bool ret;
15687 if (type == NULL)
15688 ret = true;
15689 else if (type->integer_type() != NULL)
15690 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15691 else if (type->float_type() != NULL)
15692 ret = this->check_float_type(type->float_type(), issue_error, loc);
15693 else if (type->complex_type() != NULL)
15694 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15695 else
15696 go_unreachable();
15697 if (ret)
15698 this->type_ = type;
15699 return ret;
15702 // Check whether the constant can be expressed in an integer type.
15704 bool
15705 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15706 Location location) const
15708 mpz_t val;
15709 switch (this->classification_)
15711 case NC_INT:
15712 case NC_RUNE:
15713 mpz_init_set(val, this->u_.int_val);
15714 break;
15716 case NC_FLOAT:
15717 if (!mpfr_integer_p(this->u_.float_val))
15719 if (issue_error)
15720 error_at(location, "floating point constant truncated to integer");
15721 return false;
15723 mpz_init(val);
15724 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15725 break;
15727 case NC_COMPLEX:
15728 if (!mpfr_integer_p(this->u_.complex_val.real)
15729 || !mpfr_zero_p(this->u_.complex_val.imag))
15731 if (issue_error)
15732 error_at(location, "complex constant truncated to integer");
15733 return false;
15735 mpz_init(val);
15736 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15737 break;
15739 default:
15740 go_unreachable();
15743 bool ret;
15744 if (type->is_abstract())
15745 ret = true;
15746 else
15748 int bits = mpz_sizeinbase(val, 2);
15749 if (type->is_unsigned())
15751 // For an unsigned type we can only accept a nonnegative
15752 // number, and we must be able to represents at least BITS.
15753 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15755 else
15757 // For a signed type we need an extra bit to indicate the
15758 // sign. We have to handle the most negative integer
15759 // specially.
15760 ret = (bits + 1 <= type->bits()
15761 || (bits <= type->bits()
15762 && mpz_sgn(val) < 0
15763 && (mpz_scan1(val, 0)
15764 == static_cast<unsigned long>(type->bits() - 1))
15765 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15769 if (!ret && issue_error)
15770 error_at(location, "integer constant overflow");
15772 return ret;
15775 // Check whether the constant can be expressed in a floating point
15776 // type.
15778 bool
15779 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15780 Location location)
15782 mpfr_t val;
15783 switch (this->classification_)
15785 case NC_INT:
15786 case NC_RUNE:
15787 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15788 break;
15790 case NC_FLOAT:
15791 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15792 break;
15794 case NC_COMPLEX:
15795 if (!mpfr_zero_p(this->u_.complex_val.imag))
15797 if (issue_error)
15798 error_at(location, "complex constant truncated to float");
15799 return false;
15801 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15802 break;
15804 default:
15805 go_unreachable();
15808 bool ret;
15809 if (type->is_abstract())
15810 ret = true;
15811 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15813 // A NaN or Infinity always fits in the range of the type.
15814 ret = true;
15816 else
15818 mp_exp_t exp = mpfr_get_exp(val);
15819 mp_exp_t max_exp;
15820 switch (type->bits())
15822 case 32:
15823 max_exp = 128;
15824 break;
15825 case 64:
15826 max_exp = 1024;
15827 break;
15828 default:
15829 go_unreachable();
15832 ret = exp <= max_exp;
15834 if (ret)
15836 // Round the constant to the desired type.
15837 mpfr_t t;
15838 mpfr_init(t);
15839 switch (type->bits())
15841 case 32:
15842 mpfr_set_prec(t, 24);
15843 break;
15844 case 64:
15845 mpfr_set_prec(t, 53);
15846 break;
15847 default:
15848 go_unreachable();
15850 mpfr_set(t, val, GMP_RNDN);
15851 mpfr_set(val, t, GMP_RNDN);
15852 mpfr_clear(t);
15854 this->set_float(type, val);
15858 mpfr_clear(val);
15860 if (!ret && issue_error)
15861 error_at(location, "floating point constant overflow");
15863 return ret;
15866 // Check whether the constant can be expressed in a complex type.
15868 bool
15869 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15870 Location location)
15872 if (type->is_abstract())
15873 return true;
15875 mp_exp_t max_exp;
15876 switch (type->bits())
15878 case 64:
15879 max_exp = 128;
15880 break;
15881 case 128:
15882 max_exp = 1024;
15883 break;
15884 default:
15885 go_unreachable();
15888 mpfr_t real;
15889 mpfr_t imag;
15890 switch (this->classification_)
15892 case NC_INT:
15893 case NC_RUNE:
15894 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
15895 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15896 break;
15898 case NC_FLOAT:
15899 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
15900 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15901 break;
15903 case NC_COMPLEX:
15904 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
15905 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
15906 break;
15908 default:
15909 go_unreachable();
15912 bool ret = true;
15913 if (!mpfr_nan_p(real)
15914 && !mpfr_inf_p(real)
15915 && !mpfr_zero_p(real)
15916 && mpfr_get_exp(real) > max_exp)
15918 if (issue_error)
15919 error_at(location, "complex real part overflow");
15920 ret = false;
15923 if (!mpfr_nan_p(imag)
15924 && !mpfr_inf_p(imag)
15925 && !mpfr_zero_p(imag)
15926 && mpfr_get_exp(imag) > max_exp)
15928 if (issue_error)
15929 error_at(location, "complex imaginary part overflow");
15930 ret = false;
15933 if (ret)
15935 // Round the constant to the desired type.
15936 mpfr_t t;
15937 mpfr_init(t);
15938 switch (type->bits())
15940 case 64:
15941 mpfr_set_prec(t, 24);
15942 break;
15943 case 128:
15944 mpfr_set_prec(t, 53);
15945 break;
15946 default:
15947 go_unreachable();
15949 mpfr_set(t, real, GMP_RNDN);
15950 mpfr_set(real, t, GMP_RNDN);
15951 mpfr_set(t, imag, GMP_RNDN);
15952 mpfr_set(imag, t, GMP_RNDN);
15953 mpfr_clear(t);
15955 this->set_complex(type, real, imag);
15958 mpfr_clear(real);
15959 mpfr_clear(imag);
15961 return ret;
15964 // Return an Expression for this value.
15966 Expression*
15967 Numeric_constant::expression(Location loc) const
15969 switch (this->classification_)
15971 case NC_INT:
15972 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15973 case NC_RUNE:
15974 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15975 case NC_FLOAT:
15976 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15977 case NC_COMPLEX:
15978 return Expression::make_complex(&this->u_.complex_val.real,
15979 &this->u_.complex_val.imag,
15980 this->type_, loc);
15981 default:
15982 go_unreachable();