compiler: relocate ID encoding utilities to gofrontend
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob0ab672608753e2b616f2ead6ccb5faa69fc891e2
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 "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "types.h"
16 #include "export.h"
17 #include "import.h"
18 #include "statements.h"
19 #include "lex.h"
20 #include "runtime.h"
21 #include "backend.h"
22 #include "expressions.h"
23 #include "ast-dump.h"
25 // Class Expression.
27 Expression::Expression(Expression_classification classification,
28 Location location)
29 : classification_(classification), location_(location)
33 Expression::~Expression()
37 // Traverse the expressions.
39 int
40 Expression::traverse(Expression** pexpr, Traverse* traverse)
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
45 int t = traverse->expression(pexpr);
46 if (t == TRAVERSE_EXIT)
47 return TRAVERSE_EXIT;
48 else if (t == TRAVERSE_SKIP_COMPONENTS)
49 return TRAVERSE_CONTINUE;
51 return expr->do_traverse(traverse);
54 // Traverse subexpressions of this expression.
56 int
57 Expression::traverse_subexpressions(Traverse* traverse)
59 return this->do_traverse(traverse);
62 // Default implementation for do_traverse for child classes.
64 int
65 Expression::do_traverse(Traverse*)
67 return TRAVERSE_CONTINUE;
70 // This virtual function is called by the parser if the value of this
71 // expression is being discarded. By default, we give an error.
72 // Expressions with side effects override.
74 bool
75 Expression::do_discarding_value()
77 this->unused_value_error();
78 return false;
81 // This virtual function is called to export expressions. This will
82 // only be used by expressions which may be constant.
84 void
85 Expression::do_export(Export*) const
87 go_unreachable();
90 // Give an error saying that the value of the expression is not used.
92 void
93 Expression::unused_value_error()
95 this->report_error(_("value computed is not used"));
98 // Note that this expression is an error. This is called by children
99 // when they discover an error.
101 void
102 Expression::set_is_error()
104 this->classification_ = EXPRESSION_ERROR;
107 // For children to call to report an error conveniently.
109 void
110 Expression::report_error(const char* msg)
112 go_error_at(this->location_, "%s", msg);
113 this->set_is_error();
116 // Set types of variables and constants. This is implemented by the
117 // child class.
119 void
120 Expression::determine_type(const Type_context* context)
122 this->do_determine_type(context);
125 // Set types when there is no context.
127 void
128 Expression::determine_type_no_context()
130 Type_context context;
131 this->do_determine_type(&context);
134 // Return an expression handling any conversions which must be done during
135 // assignment.
137 Expression*
138 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
139 Expression* rhs, Location location)
141 Type* rhs_type = rhs->type();
142 if (lhs_type->is_error()
143 || rhs_type->is_error()
144 || rhs->is_error_expression())
145 return Expression::make_error(location);
147 if (lhs_type->forwarded() != rhs_type->forwarded()
148 && lhs_type->interface_type() != NULL)
150 if (rhs_type->interface_type() == NULL)
151 return Expression::convert_type_to_interface(lhs_type, rhs, location);
152 else
153 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
154 location);
156 else if (lhs_type->forwarded() != rhs_type->forwarded()
157 && rhs_type->interface_type() != NULL)
158 return Expression::convert_interface_to_type(lhs_type, rhs, location);
159 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
161 // Assigning nil to a slice.
162 Expression* nil = Expression::make_nil(location);
163 Expression* zero = Expression::make_integer_ul(0, NULL, location);
164 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
166 else if (rhs_type->is_nil_type())
167 return Expression::make_nil(location);
168 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
170 // No conversion is needed.
171 return rhs;
173 else if (lhs_type->points_to() != NULL)
174 return Expression::make_unsafe_cast(lhs_type, rhs, location);
175 else if (lhs_type->is_numeric_type())
176 return Expression::make_cast(lhs_type, rhs, location);
177 else if ((lhs_type->struct_type() != NULL
178 && rhs_type->struct_type() != NULL)
179 || (lhs_type->array_type() != NULL
180 && rhs_type->array_type() != NULL))
182 // This conversion must be permitted by Go, or we wouldn't have
183 // gotten here.
184 return Expression::make_unsafe_cast(lhs_type, rhs, location);
186 else
187 return rhs;
190 // Return an expression for a conversion from a non-interface type to an
191 // interface type.
193 Expression*
194 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
195 Location location)
197 Interface_type* lhs_interface_type = lhs_type->interface_type();
198 bool lhs_is_empty = lhs_interface_type->is_empty();
200 // Since RHS_TYPE is a static type, we can create the interface
201 // method table at compile time.
203 // When setting an interface to nil, we just set both fields to
204 // NULL.
205 Type* rhs_type = rhs->type();
206 if (rhs_type->is_nil_type())
208 Expression* nil = Expression::make_nil(location);
209 return Expression::make_interface_value(lhs_type, nil, nil, location);
212 // This should have been checked already.
213 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
215 // An interface is a tuple. If LHS_TYPE is an empty interface type,
216 // then the first field is the type descriptor for RHS_TYPE.
217 // Otherwise it is the interface method table for RHS_TYPE.
218 Expression* first_field;
219 if (lhs_is_empty)
220 first_field = Expression::make_type_descriptor(rhs_type, location);
221 else
223 // Build the interface method table for this interface and this
224 // object type: a list of function pointers for each interface
225 // method.
226 Named_type* rhs_named_type = rhs_type->named_type();
227 Struct_type* rhs_struct_type = rhs_type->struct_type();
228 bool is_pointer = false;
229 if (rhs_named_type == NULL && rhs_struct_type == NULL)
231 rhs_named_type = rhs_type->deref()->named_type();
232 rhs_struct_type = rhs_type->deref()->struct_type();
233 is_pointer = true;
235 if (rhs_named_type != NULL)
236 first_field =
237 rhs_named_type->interface_method_table(lhs_interface_type,
238 is_pointer);
239 else if (rhs_struct_type != NULL)
240 first_field =
241 rhs_struct_type->interface_method_table(lhs_interface_type,
242 is_pointer);
243 else
244 first_field = Expression::make_nil(location);
247 Expression* obj;
248 if (rhs_type->points_to() != NULL)
250 // We are assigning a pointer to the interface; the interface
251 // holds the pointer itself.
252 obj = rhs;
254 else
256 // We are assigning a non-pointer value to the interface; the
257 // interface gets a copy of the value in the heap if it escapes.
258 // TODO(cmang): Associate escape state state of RHS with newly
259 // created OBJ.
260 obj = Expression::make_heap_expression(rhs, location);
263 return Expression::make_interface_value(lhs_type, first_field, obj, location);
266 // Return an expression for the type descriptor of RHS.
268 Expression*
269 Expression::get_interface_type_descriptor(Expression* rhs)
271 go_assert(rhs->type()->interface_type() != NULL);
272 Location location = rhs->location();
274 // The type descriptor is the first field of an empty interface.
275 if (rhs->type()->interface_type()->is_empty())
276 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
277 location);
279 Expression* mtable =
280 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
282 Expression* descriptor =
283 Expression::make_unary(OPERATOR_MULT, mtable, location);
284 descriptor = Expression::make_field_reference(descriptor, 0, location);
285 Expression* nil = Expression::make_nil(location);
287 Expression* eq =
288 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
289 return Expression::make_conditional(eq, nil, descriptor, location);
292 // Return an expression for the conversion of an interface type to an
293 // interface type.
295 Expression*
296 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
297 bool for_type_guard,
298 Location location)
300 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
301 return rhs;
303 Interface_type* lhs_interface_type = lhs_type->interface_type();
304 bool lhs_is_empty = lhs_interface_type->is_empty();
306 // In the general case this requires runtime examination of the type
307 // method table to match it up with the interface methods.
309 // FIXME: If all of the methods in the right hand side interface
310 // also appear in the left hand side interface, then we don't need
311 // to do a runtime check, although we still need to build a new
312 // method table.
314 // We are going to evaluate RHS multiple times.
315 go_assert(rhs->is_variable());
317 // Get the type descriptor for the right hand side. This will be
318 // NULL for a nil interface.
319 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
320 Expression* lhs_type_expr =
321 Expression::make_type_descriptor(lhs_type, location);
323 Expression* first_field;
324 if (for_type_guard)
326 // A type assertion fails when converting a nil interface.
327 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
328 lhs_type_expr, rhs_type_expr);
330 else if (lhs_is_empty)
332 // A conversion to an empty interface always succeeds, and the
333 // first field is just the type descriptor of the object.
334 first_field = rhs_type_expr;
336 else
338 // A conversion to a non-empty interface may fail, but unlike a
339 // type assertion converting nil will always succeed.
340 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
341 lhs_type_expr, rhs_type_expr);
344 // The second field is simply the object pointer.
345 Expression* obj =
346 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
347 return Expression::make_interface_value(lhs_type, first_field, obj, location);
350 // Return an expression for the conversion of an interface type to a
351 // non-interface type.
353 Expression*
354 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
355 Location location)
357 // We are going to evaluate RHS multiple times.
358 go_assert(rhs->is_variable());
360 // Call a function to check that the type is valid. The function
361 // will panic with an appropriate runtime type error if the type is
362 // not valid.
363 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
364 location);
365 Expression* rhs_descriptor =
366 Expression::get_interface_type_descriptor(rhs);
368 Type* rhs_type = rhs->type();
369 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
370 location);
372 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
373 location, 3, lhs_type_expr,
374 rhs_descriptor, rhs_inter_expr);
376 // If the call succeeds, pull out the value.
377 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
378 location);
380 // If the value is a pointer, then it is the value we want.
381 // Otherwise it points to the value.
382 if (lhs_type->points_to() == NULL)
384 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
385 location);
386 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
388 return Expression::make_compound(check_iface, obj, location);
391 // Convert an expression to its backend representation. This is implemented by
392 // the child class. Not that it is not in general safe to call this multiple
393 // times for a single expression, but that we don't catch such errors.
395 Bexpression*
396 Expression::get_backend(Translate_context* context)
398 // The child may have marked this expression as having an error.
399 if (this->classification_ == EXPRESSION_ERROR)
400 return context->backend()->error_expression();
402 return this->do_get_backend(context);
405 // Return a backend expression for VAL.
406 Bexpression*
407 Expression::backend_numeric_constant_expression(Translate_context* context,
408 Numeric_constant* val)
410 Gogo* gogo = context->gogo();
411 Type* type = val->type();
412 if (type == NULL)
413 return gogo->backend()->error_expression();
415 Btype* btype = type->get_backend(gogo);
416 Bexpression* ret;
417 if (type->integer_type() != NULL)
419 mpz_t ival;
420 if (!val->to_int(&ival))
422 go_assert(saw_errors());
423 return gogo->backend()->error_expression();
425 ret = gogo->backend()->integer_constant_expression(btype, ival);
426 mpz_clear(ival);
428 else if (type->float_type() != NULL)
430 mpfr_t fval;
431 if (!val->to_float(&fval))
433 go_assert(saw_errors());
434 return gogo->backend()->error_expression();
436 ret = gogo->backend()->float_constant_expression(btype, fval);
437 mpfr_clear(fval);
439 else if (type->complex_type() != NULL)
441 mpc_t cval;
442 if (!val->to_complex(&cval))
444 go_assert(saw_errors());
445 return gogo->backend()->error_expression();
447 ret = gogo->backend()->complex_constant_expression(btype, cval);
448 mpc_clear(cval);
450 else
451 go_unreachable();
453 return ret;
456 // Return an expression which evaluates to true if VAL, of arbitrary integer
457 // type, is negative or is more than the maximum value of the Go type "int".
459 Expression*
460 Expression::check_bounds(Expression* val, Location loc)
462 Type* val_type = val->type();
463 Type* bound_type = Type::lookup_integer_type("int");
465 int val_type_size;
466 bool val_is_unsigned = false;
467 if (val_type->integer_type() != NULL)
469 val_type_size = val_type->integer_type()->bits();
470 val_is_unsigned = val_type->integer_type()->is_unsigned();
472 else
474 if (!val_type->is_numeric_type()
475 || !Type::are_convertible(bound_type, val_type, NULL))
477 go_assert(saw_errors());
478 return Expression::make_boolean(true, loc);
481 if (val_type->complex_type() != NULL)
482 val_type_size = val_type->complex_type()->bits();
483 else
484 val_type_size = val_type->float_type()->bits();
487 Expression* negative_index = Expression::make_boolean(false, loc);
488 Expression* index_overflows = Expression::make_boolean(false, loc);
489 if (!val_is_unsigned)
491 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
492 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
495 int bound_type_size = bound_type->integer_type()->bits();
496 if (val_type_size > bound_type_size
497 || (val_type_size == bound_type_size
498 && val_is_unsigned))
500 mpz_t one;
501 mpz_init_set_ui(one, 1UL);
503 // maxval = 2^(bound_type_size - 1) - 1
504 mpz_t maxval;
505 mpz_init(maxval);
506 mpz_mul_2exp(maxval, one, bound_type_size - 1);
507 mpz_sub_ui(maxval, maxval, 1);
508 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
509 mpz_clear(one);
510 mpz_clear(maxval);
512 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
515 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
516 loc);
519 void
520 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
522 this->do_dump_expression(ast_dump_context);
525 // Error expressions. This are used to avoid cascading errors.
527 class Error_expression : public Expression
529 public:
530 Error_expression(Location location)
531 : Expression(EXPRESSION_ERROR, location)
534 protected:
535 bool
536 do_is_constant() const
537 { return true; }
539 bool
540 do_numeric_constant_value(Numeric_constant* nc) const
542 nc->set_unsigned_long(NULL, 0);
543 return true;
546 bool
547 do_discarding_value()
548 { return true; }
550 Type*
551 do_type()
552 { return Type::make_error_type(); }
554 void
555 do_determine_type(const Type_context*)
558 Expression*
559 do_copy()
560 { return this; }
562 bool
563 do_is_addressable() const
564 { return true; }
566 Bexpression*
567 do_get_backend(Translate_context* context)
568 { return context->backend()->error_expression(); }
570 void
571 do_dump_expression(Ast_dump_context*) const;
574 // Dump the ast representation for an error expression to a dump context.
576 void
577 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
579 ast_dump_context->ostream() << "_Error_" ;
582 Expression*
583 Expression::make_error(Location location)
585 return new Error_expression(location);
588 // An expression which is really a type. This is used during parsing.
589 // It is an error if these survive after lowering.
591 class
592 Type_expression : public Expression
594 public:
595 Type_expression(Type* type, Location location)
596 : Expression(EXPRESSION_TYPE, location),
597 type_(type)
600 protected:
602 do_traverse(Traverse* traverse)
603 { return Type::traverse(this->type_, traverse); }
605 Type*
606 do_type()
607 { return this->type_; }
609 void
610 do_determine_type(const Type_context*)
613 void
614 do_check_types(Gogo*)
615 { this->report_error(_("invalid use of type")); }
617 Expression*
618 do_copy()
619 { return this; }
621 Bexpression*
622 do_get_backend(Translate_context*)
623 { go_unreachable(); }
625 void do_dump_expression(Ast_dump_context*) const;
627 private:
628 // The type which we are representing as an expression.
629 Type* type_;
632 void
633 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
635 ast_dump_context->dump_type(this->type_);
638 Expression*
639 Expression::make_type(Type* type, Location location)
641 return new Type_expression(type, location);
644 // Class Parser_expression.
646 Type*
647 Parser_expression::do_type()
649 // We should never really ask for the type of a Parser_expression.
650 // However, it can happen, at least when we have an invalid const
651 // whose initializer refers to the const itself. In that case we
652 // may ask for the type when lowering the const itself.
653 go_assert(saw_errors());
654 return Type::make_error_type();
657 // Class Var_expression.
659 // Lower a variable expression. Here we just make sure that the
660 // initialization expression of the variable has been lowered. This
661 // ensures that we will be able to determine the type of the variable
662 // if necessary.
664 Expression*
665 Var_expression::do_lower(Gogo* gogo, Named_object* function,
666 Statement_inserter* inserter, int)
668 if (this->variable_->is_variable())
670 Variable* var = this->variable_->var_value();
671 // This is either a local variable or a global variable. A
672 // reference to a variable which is local to an enclosing
673 // function will be a reference to a field in a closure.
674 if (var->is_global())
676 function = NULL;
677 inserter = NULL;
679 var->lower_init_expression(gogo, function, inserter);
681 return this;
684 // Return the type of a reference to a variable.
686 Type*
687 Var_expression::do_type()
689 if (this->variable_->is_variable())
690 return this->variable_->var_value()->type();
691 else if (this->variable_->is_result_variable())
692 return this->variable_->result_var_value()->type();
693 else
694 go_unreachable();
697 // Determine the type of a reference to a variable.
699 void
700 Var_expression::do_determine_type(const Type_context*)
702 if (this->variable_->is_variable())
703 this->variable_->var_value()->determine_type();
706 // Something takes the address of this variable. This means that we
707 // may want to move the variable onto the heap.
709 void
710 Var_expression::do_address_taken(bool escapes)
712 if (!escapes)
714 if (this->variable_->is_variable())
715 this->variable_->var_value()->set_non_escaping_address_taken();
716 else if (this->variable_->is_result_variable())
717 this->variable_->result_var_value()->set_non_escaping_address_taken();
718 else
719 go_unreachable();
721 else
723 if (this->variable_->is_variable())
724 this->variable_->var_value()->set_address_taken();
725 else if (this->variable_->is_result_variable())
726 this->variable_->result_var_value()->set_address_taken();
727 else
728 go_unreachable();
731 if (this->variable_->is_variable()
732 && this->variable_->var_value()->is_in_heap())
734 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
735 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
739 // Get the backend representation for a reference to a variable.
741 Bexpression*
742 Var_expression::do_get_backend(Translate_context* context)
744 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
745 context->function());
746 bool is_in_heap;
747 Location loc = this->location();
748 Btype* btype;
749 Gogo* gogo = context->gogo();
750 if (this->variable_->is_variable())
752 is_in_heap = this->variable_->var_value()->is_in_heap();
753 btype = this->variable_->var_value()->type()->get_backend(gogo);
755 else if (this->variable_->is_result_variable())
757 is_in_heap = this->variable_->result_var_value()->is_in_heap();
758 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
760 else
761 go_unreachable();
763 Bexpression* ret = context->backend()->var_expression(bvar, loc);
764 if (is_in_heap)
765 ret = context->backend()->indirect_expression(btype, ret, true, loc);
766 return ret;
769 // Ast dump for variable expression.
771 void
772 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
774 ast_dump_context->ostream() << this->variable_->name() ;
777 // Make a reference to a variable in an expression.
779 Expression*
780 Expression::make_var_reference(Named_object* var, Location location)
782 if (var->is_sink())
783 return Expression::make_sink(location);
785 // FIXME: Creating a new object for each reference to a variable is
786 // wasteful.
787 return new Var_expression(var, location);
790 // Class Enclosed_var_expression.
793 Enclosed_var_expression::do_traverse(Traverse*)
795 return TRAVERSE_CONTINUE;
798 // Lower the reference to the enclosed variable.
800 Expression*
801 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
802 Statement_inserter* inserter, int)
804 gogo->lower_expression(function, inserter, &this->reference_);
805 return this;
808 // Flatten the reference to the enclosed variable.
810 Expression*
811 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
812 Statement_inserter* inserter)
814 gogo->flatten_expression(function, inserter, &this->reference_);
815 return this;
818 void
819 Enclosed_var_expression::do_address_taken(bool escapes)
821 if (!escapes)
823 if (this->variable_->is_variable())
824 this->variable_->var_value()->set_non_escaping_address_taken();
825 else if (this->variable_->is_result_variable())
826 this->variable_->result_var_value()->set_non_escaping_address_taken();
827 else
828 go_unreachable();
830 else
832 if (this->variable_->is_variable())
833 this->variable_->var_value()->set_address_taken();
834 else if (this->variable_->is_result_variable())
835 this->variable_->result_var_value()->set_address_taken();
836 else
837 go_unreachable();
840 if (this->variable_->is_variable()
841 && this->variable_->var_value()->is_in_heap())
842 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
845 // Ast dump for enclosed variable expression.
847 void
848 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
850 adc->ostream() << this->variable_->name();
853 // Make a reference to a variable within an enclosing function.
855 Expression*
856 Expression::make_enclosing_var_reference(Expression* reference,
857 Named_object* var, Location location)
859 return new Enclosed_var_expression(reference, var, location);
862 // Class Temporary_reference_expression.
864 // The type.
866 Type*
867 Temporary_reference_expression::do_type()
869 return this->statement_->type();
872 // Called if something takes the address of this temporary variable.
873 // We never have to move temporary variables to the heap, but we do
874 // need to know that they must live in the stack rather than in a
875 // register.
877 void
878 Temporary_reference_expression::do_address_taken(bool)
880 this->statement_->set_is_address_taken();
883 // Get a backend expression referring to the variable.
885 Bexpression*
886 Temporary_reference_expression::do_get_backend(Translate_context* context)
888 Gogo* gogo = context->gogo();
889 Bvariable* bvar = this->statement_->get_backend_variable(context);
890 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
892 // The backend can't always represent the same set of recursive types
893 // that the Go frontend can. In some cases this means that a
894 // temporary variable won't have the right backend type. Correct
895 // that here by adding a type cast. We need to use base() to push
896 // the circularity down one level.
897 Type* stype = this->statement_->type();
898 if (!this->is_lvalue_
899 && stype->has_pointer()
900 && stype->deref()->is_void_type())
902 Btype* btype = this->type()->base()->get_backend(gogo);
903 ret = gogo->backend()->convert_expression(btype, ret, this->location());
905 return ret;
908 // Ast dump for temporary reference.
910 void
911 Temporary_reference_expression::do_dump_expression(
912 Ast_dump_context* ast_dump_context) const
914 ast_dump_context->dump_temp_variable_name(this->statement_);
917 // Make a reference to a temporary variable.
919 Temporary_reference_expression*
920 Expression::make_temporary_reference(Temporary_statement* statement,
921 Location location)
923 return new Temporary_reference_expression(statement, location);
926 // Class Set_and_use_temporary_expression.
928 // Return the type.
930 Type*
931 Set_and_use_temporary_expression::do_type()
933 return this->statement_->type();
936 // Determine the type of the expression.
938 void
939 Set_and_use_temporary_expression::do_determine_type(
940 const Type_context* context)
942 this->expr_->determine_type(context);
945 // Take the address.
947 void
948 Set_and_use_temporary_expression::do_address_taken(bool)
950 this->statement_->set_is_address_taken();
953 // Return the backend representation.
955 Bexpression*
956 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
958 Location loc = this->location();
959 Gogo* gogo = context->gogo();
960 Bvariable* bvar = this->statement_->get_backend_variable(context);
961 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
963 Bexpression* bexpr = this->expr_->get_backend(context);
964 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
965 var_ref = gogo->backend()->var_expression(bvar, loc);
966 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
967 return ret;
970 // Dump.
972 void
973 Set_and_use_temporary_expression::do_dump_expression(
974 Ast_dump_context* ast_dump_context) const
976 ast_dump_context->ostream() << '(';
977 ast_dump_context->dump_temp_variable_name(this->statement_);
978 ast_dump_context->ostream() << " = ";
979 this->expr_->dump_expression(ast_dump_context);
980 ast_dump_context->ostream() << ')';
983 // Make a set-and-use temporary.
985 Set_and_use_temporary_expression*
986 Expression::make_set_and_use_temporary(Temporary_statement* statement,
987 Expression* expr, Location location)
989 return new Set_and_use_temporary_expression(statement, expr, location);
992 // A sink expression--a use of the blank identifier _.
994 class Sink_expression : public Expression
996 public:
997 Sink_expression(Location location)
998 : Expression(EXPRESSION_SINK, location),
999 type_(NULL), bvar_(NULL)
1002 protected:
1003 bool
1004 do_discarding_value()
1005 { return true; }
1007 Type*
1008 do_type();
1010 void
1011 do_determine_type(const Type_context*);
1013 Expression*
1014 do_copy()
1015 { return new Sink_expression(this->location()); }
1017 Bexpression*
1018 do_get_backend(Translate_context*);
1020 void
1021 do_dump_expression(Ast_dump_context*) const;
1023 private:
1024 // The type of this sink variable.
1025 Type* type_;
1026 // The temporary variable we generate.
1027 Bvariable* bvar_;
1030 // Return the type of a sink expression.
1032 Type*
1033 Sink_expression::do_type()
1035 if (this->type_ == NULL)
1036 return Type::make_sink_type();
1037 return this->type_;
1040 // Determine the type of a sink expression.
1042 void
1043 Sink_expression::do_determine_type(const Type_context* context)
1045 if (context->type != NULL)
1046 this->type_ = context->type;
1049 // Return a temporary variable for a sink expression. This will
1050 // presumably be a write-only variable which the middle-end will drop.
1052 Bexpression*
1053 Sink_expression::do_get_backend(Translate_context* context)
1055 Location loc = this->location();
1056 Gogo* gogo = context->gogo();
1057 if (this->bvar_ == NULL)
1059 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1060 Named_object* fn = context->function();
1061 go_assert(fn != NULL);
1062 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1063 Btype* bt = this->type_->get_backend(context->gogo());
1064 Bstatement* decl;
1065 this->bvar_ =
1066 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1067 false, loc, &decl);
1068 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
1069 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1070 return var_ref;
1072 return gogo->backend()->var_expression(this->bvar_, loc);
1075 // Ast dump for sink expression.
1077 void
1078 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1080 ast_dump_context->ostream() << "_" ;
1083 // Make a sink expression.
1085 Expression*
1086 Expression::make_sink(Location location)
1088 return new Sink_expression(location);
1091 // Class Func_expression.
1093 // FIXME: Can a function expression appear in a constant expression?
1094 // The value is unchanging. Initializing a constant to the address of
1095 // a function seems like it could work, though there might be little
1096 // point to it.
1098 // Traversal.
1101 Func_expression::do_traverse(Traverse* traverse)
1103 return (this->closure_ == NULL
1104 ? TRAVERSE_CONTINUE
1105 : Expression::traverse(&this->closure_, traverse));
1108 // Return the type of a function expression.
1110 Type*
1111 Func_expression::do_type()
1113 if (this->function_->is_function())
1114 return this->function_->func_value()->type();
1115 else if (this->function_->is_function_declaration())
1116 return this->function_->func_declaration_value()->type();
1117 else
1118 go_unreachable();
1121 // Get the backend representation for the code of a function expression.
1123 Bexpression*
1124 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1126 Function_type* fntype;
1127 if (no->is_function())
1128 fntype = no->func_value()->type();
1129 else if (no->is_function_declaration())
1130 fntype = no->func_declaration_value()->type();
1131 else
1132 go_unreachable();
1134 // Builtin functions are handled specially by Call_expression. We
1135 // can't take their address.
1136 if (fntype->is_builtin())
1138 go_error_at(loc,
1139 "invalid use of special builtin function %qs; must be called",
1140 no->message_name().c_str());
1141 return gogo->backend()->error_expression();
1144 Bfunction* fndecl;
1145 if (no->is_function())
1146 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1147 else if (no->is_function_declaration())
1148 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1149 else
1150 go_unreachable();
1152 return gogo->backend()->function_code_expression(fndecl, loc);
1155 // Get the backend representation for a function expression. This is used when
1156 // we take the address of a function rather than simply calling it. A func
1157 // value is represented as a pointer to a block of memory. The first
1158 // word of that memory is a pointer to the function code. The
1159 // remaining parts of that memory are the addresses of variables that
1160 // the function closes over.
1162 Bexpression*
1163 Func_expression::do_get_backend(Translate_context* context)
1165 // If there is no closure, just use the function descriptor.
1166 if (this->closure_ == NULL)
1168 Gogo* gogo = context->gogo();
1169 Named_object* no = this->function_;
1170 Expression* descriptor;
1171 if (no->is_function())
1172 descriptor = no->func_value()->descriptor(gogo, no);
1173 else if (no->is_function_declaration())
1175 if (no->func_declaration_value()->type()->is_builtin())
1177 go_error_at(this->location(),
1178 ("invalid use of special builtin function %qs; "
1179 "must be called"),
1180 no->message_name().c_str());
1181 return gogo->backend()->error_expression();
1183 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1185 else
1186 go_unreachable();
1188 Bexpression* bdesc = descriptor->get_backend(context);
1189 return gogo->backend()->address_expression(bdesc, this->location());
1192 go_assert(this->function_->func_value()->enclosing() != NULL);
1194 // If there is a closure, then the closure is itself the function
1195 // expression. It is a pointer to a struct whose first field points
1196 // to the function code and whose remaining fields are the addresses
1197 // of the closed-over variables.
1198 return this->closure_->get_backend(context);
1201 // Ast dump for function.
1203 void
1204 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1206 ast_dump_context->ostream() << this->function_->name();
1207 if (this->closure_ != NULL)
1209 ast_dump_context->ostream() << " {closure = ";
1210 this->closure_->dump_expression(ast_dump_context);
1211 ast_dump_context->ostream() << "}";
1215 // Make a reference to a function in an expression.
1217 Expression*
1218 Expression::make_func_reference(Named_object* function, Expression* closure,
1219 Location location)
1221 Func_expression* fe = new Func_expression(function, closure, location);
1223 // Detect references to builtin functions and set the runtime code if
1224 // appropriate.
1225 if (function->is_function_declaration())
1226 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1227 return fe;
1230 // Class Func_descriptor_expression.
1232 // Constructor.
1234 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1235 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1236 fn_(fn), dvar_(NULL)
1238 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1241 // Traversal.
1244 Func_descriptor_expression::do_traverse(Traverse*)
1246 return TRAVERSE_CONTINUE;
1249 // All function descriptors have the same type.
1251 Type* Func_descriptor_expression::descriptor_type;
1253 void
1254 Func_descriptor_expression::make_func_descriptor_type()
1256 if (Func_descriptor_expression::descriptor_type != NULL)
1257 return;
1258 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1259 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1260 Func_descriptor_expression::descriptor_type =
1261 Type::make_builtin_named_type("functionDescriptor", struct_type);
1264 Type*
1265 Func_descriptor_expression::do_type()
1267 Func_descriptor_expression::make_func_descriptor_type();
1268 return Func_descriptor_expression::descriptor_type;
1271 // The backend representation for a function descriptor.
1273 Bexpression*
1274 Func_descriptor_expression::do_get_backend(Translate_context* context)
1276 Named_object* no = this->fn_;
1277 Location loc = no->location();
1278 if (this->dvar_ != NULL)
1279 return context->backend()->var_expression(this->dvar_, loc);
1281 Gogo* gogo = context->gogo();
1282 std::string var_name;
1283 bool is_descriptor = false;
1284 if (no->is_function_declaration()
1285 && !no->func_declaration_value()->asm_name().empty()
1286 && Linemap::is_predeclared_location(no->location()))
1288 if (no->func_declaration_value()->asm_name().substr(0, 8) != "runtime.")
1289 var_name = no->func_declaration_value()->asm_name() + "_descriptor";
1290 else
1291 var_name = no->func_declaration_value()->asm_name() + "$descriptor";
1292 is_descriptor = true;
1294 else
1296 if (no->package() == NULL)
1297 var_name = gogo->pkgpath_symbol();
1298 else
1299 var_name = no->package()->pkgpath_symbol();
1300 var_name.push_back('.');
1301 var_name.append(Gogo::unpack_hidden_name(no->name()));
1302 var_name.append("$descriptor");
1305 Btype* btype = this->type()->get_backend(gogo);
1307 Bvariable* bvar;
1308 std::string asm_name(go_selectively_encode_id(var_name));
1309 if (no->package() != NULL || is_descriptor)
1310 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1311 btype, loc);
1312 else
1314 Location bloc = Linemap::predeclared_location();
1315 bool is_hidden = ((no->is_function()
1316 && no->func_value()->enclosing() != NULL)
1317 || Gogo::is_thunk(no));
1318 bvar = context->backend()->immutable_struct(var_name, asm_name,
1319 is_hidden, false,
1320 btype, bloc);
1321 Expression_list* vals = new Expression_list();
1322 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1323 Expression* init =
1324 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1325 Translate_context bcontext(gogo, NULL, NULL, NULL);
1326 bcontext.set_is_const();
1327 Bexpression* binit = init->get_backend(&bcontext);
1328 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1329 false, btype, bloc, binit);
1332 this->dvar_ = bvar;
1333 return gogo->backend()->var_expression(bvar, loc);
1336 // Print a function descriptor expression.
1338 void
1339 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1341 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1344 // Make a function descriptor expression.
1346 Func_descriptor_expression*
1347 Expression::make_func_descriptor(Named_object* fn)
1349 return new Func_descriptor_expression(fn);
1352 // Make the function descriptor type, so that it can be converted.
1354 void
1355 Expression::make_func_descriptor_type()
1357 Func_descriptor_expression::make_func_descriptor_type();
1360 // A reference to just the code of a function.
1362 class Func_code_reference_expression : public Expression
1364 public:
1365 Func_code_reference_expression(Named_object* function, Location location)
1366 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1367 function_(function)
1370 protected:
1372 do_traverse(Traverse*)
1373 { return TRAVERSE_CONTINUE; }
1375 bool
1376 do_is_static_initializer() const
1377 { return true; }
1379 Type*
1380 do_type()
1381 { return Type::make_pointer_type(Type::make_void_type()); }
1383 void
1384 do_determine_type(const Type_context*)
1387 Expression*
1388 do_copy()
1390 return Expression::make_func_code_reference(this->function_,
1391 this->location());
1394 Bexpression*
1395 do_get_backend(Translate_context*);
1397 void
1398 do_dump_expression(Ast_dump_context* context) const
1399 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1401 private:
1402 // The function.
1403 Named_object* function_;
1406 // Get the backend representation for a reference to function code.
1408 Bexpression*
1409 Func_code_reference_expression::do_get_backend(Translate_context* context)
1411 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1412 this->location());
1415 // Make a reference to the code of a function.
1417 Expression*
1418 Expression::make_func_code_reference(Named_object* function, Location location)
1420 return new Func_code_reference_expression(function, location);
1423 // Class Unknown_expression.
1425 // Return the name of an unknown expression.
1427 const std::string&
1428 Unknown_expression::name() const
1430 return this->named_object_->name();
1433 // Lower a reference to an unknown name.
1435 Expression*
1436 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1438 Location location = this->location();
1439 Named_object* no = this->named_object_;
1440 Named_object* real;
1441 if (!no->is_unknown())
1442 real = no;
1443 else
1445 real = no->unknown_value()->real_named_object();
1446 if (real == NULL)
1448 if (this->is_composite_literal_key_)
1449 return this;
1450 if (!this->no_error_message_)
1451 go_error_at(location, "reference to undefined name %qs",
1452 this->named_object_->message_name().c_str());
1453 return Expression::make_error(location);
1456 switch (real->classification())
1458 case Named_object::NAMED_OBJECT_CONST:
1459 return Expression::make_const_reference(real, location);
1460 case Named_object::NAMED_OBJECT_TYPE:
1461 return Expression::make_type(real->type_value(), location);
1462 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1463 if (this->is_composite_literal_key_)
1464 return this;
1465 if (!this->no_error_message_)
1466 go_error_at(location, "reference to undefined type %qs",
1467 real->message_name().c_str());
1468 return Expression::make_error(location);
1469 case Named_object::NAMED_OBJECT_VAR:
1470 real->var_value()->set_is_used();
1471 return Expression::make_var_reference(real, location);
1472 case Named_object::NAMED_OBJECT_FUNC:
1473 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1474 return Expression::make_func_reference(real, NULL, location);
1475 case Named_object::NAMED_OBJECT_PACKAGE:
1476 if (this->is_composite_literal_key_)
1477 return this;
1478 if (!this->no_error_message_)
1479 go_error_at(location, "unexpected reference to package");
1480 return Expression::make_error(location);
1481 default:
1482 go_unreachable();
1486 // Dump the ast representation for an unknown expression to a dump context.
1488 void
1489 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1491 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1492 << ")";
1495 // Make a reference to an unknown name.
1497 Unknown_expression*
1498 Expression::make_unknown_reference(Named_object* no, Location location)
1500 return new Unknown_expression(no, location);
1503 // A boolean expression.
1505 class Boolean_expression : public Expression
1507 public:
1508 Boolean_expression(bool val, Location location)
1509 : Expression(EXPRESSION_BOOLEAN, location),
1510 val_(val), type_(NULL)
1513 static Expression*
1514 do_import(Import*);
1516 protected:
1517 bool
1518 do_is_constant() const
1519 { return true; }
1521 bool
1522 do_is_static_initializer() const
1523 { return true; }
1525 Type*
1526 do_type();
1528 void
1529 do_determine_type(const Type_context*);
1531 Expression*
1532 do_copy()
1533 { return this; }
1535 Bexpression*
1536 do_get_backend(Translate_context* context)
1537 { return context->backend()->boolean_constant_expression(this->val_); }
1539 void
1540 do_export(Export* exp) const
1541 { exp->write_c_string(this->val_ ? "true" : "false"); }
1543 void
1544 do_dump_expression(Ast_dump_context* ast_dump_context) const
1545 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1547 private:
1548 // The constant.
1549 bool val_;
1550 // The type as determined by context.
1551 Type* type_;
1554 // Get the type.
1556 Type*
1557 Boolean_expression::do_type()
1559 if (this->type_ == NULL)
1560 this->type_ = Type::make_boolean_type();
1561 return this->type_;
1564 // Set the type from the context.
1566 void
1567 Boolean_expression::do_determine_type(const Type_context* context)
1569 if (this->type_ != NULL && !this->type_->is_abstract())
1571 else if (context->type != NULL && context->type->is_boolean_type())
1572 this->type_ = context->type;
1573 else if (!context->may_be_abstract)
1574 this->type_ = Type::lookup_bool_type();
1577 // Import a boolean constant.
1579 Expression*
1580 Boolean_expression::do_import(Import* imp)
1582 if (imp->peek_char() == 't')
1584 imp->require_c_string("true");
1585 return Expression::make_boolean(true, imp->location());
1587 else
1589 imp->require_c_string("false");
1590 return Expression::make_boolean(false, imp->location());
1594 // Make a boolean expression.
1596 Expression*
1597 Expression::make_boolean(bool val, Location location)
1599 return new Boolean_expression(val, location);
1602 // Class String_expression.
1604 // Get the type.
1606 Type*
1607 String_expression::do_type()
1609 if (this->type_ == NULL)
1610 this->type_ = Type::make_string_type();
1611 return this->type_;
1614 // Set the type from the context.
1616 void
1617 String_expression::do_determine_type(const Type_context* context)
1619 if (this->type_ != NULL && !this->type_->is_abstract())
1621 else if (context->type != NULL && context->type->is_string_type())
1622 this->type_ = context->type;
1623 else if (!context->may_be_abstract)
1624 this->type_ = Type::lookup_string_type();
1627 // Build a string constant.
1629 Bexpression*
1630 String_expression::do_get_backend(Translate_context* context)
1632 Gogo* gogo = context->gogo();
1633 Btype* btype = Type::make_string_type()->get_backend(gogo);
1635 Location loc = this->location();
1636 std::vector<Bexpression*> init(2);
1637 Bexpression* str_cst =
1638 gogo->backend()->string_constant_expression(this->val_);
1639 init[0] = gogo->backend()->address_expression(str_cst, loc);
1641 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1642 mpz_t lenval;
1643 mpz_init_set_ui(lenval, this->val_.length());
1644 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1645 mpz_clear(lenval);
1647 return gogo->backend()->constructor_expression(btype, init, loc);
1650 // Write string literal to string dump.
1652 void
1653 String_expression::export_string(String_dump* exp,
1654 const String_expression* str)
1656 std::string s;
1657 s.reserve(str->val_.length() * 4 + 2);
1658 s += '"';
1659 for (std::string::const_iterator p = str->val_.begin();
1660 p != str->val_.end();
1661 ++p)
1663 if (*p == '\\' || *p == '"')
1665 s += '\\';
1666 s += *p;
1668 else if (*p >= 0x20 && *p < 0x7f)
1669 s += *p;
1670 else if (*p == '\n')
1671 s += "\\n";
1672 else if (*p == '\t')
1673 s += "\\t";
1674 else
1676 s += "\\x";
1677 unsigned char c = *p;
1678 unsigned int dig = c >> 4;
1679 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1680 dig = c & 0xf;
1681 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1684 s += '"';
1685 exp->write_string(s);
1688 // Export a string expression.
1690 void
1691 String_expression::do_export(Export* exp) const
1693 String_expression::export_string(exp, this);
1696 // Import a string expression.
1698 Expression*
1699 String_expression::do_import(Import* imp)
1701 imp->require_c_string("\"");
1702 std::string val;
1703 while (true)
1705 int c = imp->get_char();
1706 if (c == '"' || c == -1)
1707 break;
1708 if (c != '\\')
1709 val += static_cast<char>(c);
1710 else
1712 c = imp->get_char();
1713 if (c == '\\' || c == '"')
1714 val += static_cast<char>(c);
1715 else if (c == 'n')
1716 val += '\n';
1717 else if (c == 't')
1718 val += '\t';
1719 else if (c == 'x')
1721 c = imp->get_char();
1722 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1723 c = imp->get_char();
1724 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1725 char v = (vh << 4) | vl;
1726 val += v;
1728 else
1730 go_error_at(imp->location(), "bad string constant");
1731 return Expression::make_error(imp->location());
1735 return Expression::make_string(val, imp->location());
1738 // Ast dump for string expression.
1740 void
1741 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1743 String_expression::export_string(ast_dump_context, this);
1746 // Make a string expression.
1748 Expression*
1749 Expression::make_string(const std::string& val, Location location)
1751 return new String_expression(val, location);
1754 // An expression that evaluates to some characteristic of a string.
1755 // This is used when indexing, bound-checking, or nil checking a string.
1757 class String_info_expression : public Expression
1759 public:
1760 String_info_expression(Expression* string, String_info string_info,
1761 Location location)
1762 : Expression(EXPRESSION_STRING_INFO, location),
1763 string_(string), string_info_(string_info)
1766 protected:
1767 Type*
1768 do_type();
1770 void
1771 do_determine_type(const Type_context*)
1772 { go_unreachable(); }
1774 Expression*
1775 do_copy()
1777 return new String_info_expression(this->string_->copy(), this->string_info_,
1778 this->location());
1781 Bexpression*
1782 do_get_backend(Translate_context* context);
1784 void
1785 do_dump_expression(Ast_dump_context*) const;
1787 void
1788 do_issue_nil_check()
1789 { this->string_->issue_nil_check(); }
1791 private:
1792 // The string for which we are getting information.
1793 Expression* string_;
1794 // What information we want.
1795 String_info string_info_;
1798 // Return the type of the string info.
1800 Type*
1801 String_info_expression::do_type()
1803 switch (this->string_info_)
1805 case STRING_INFO_DATA:
1807 Type* byte_type = Type::lookup_integer_type("uint8");
1808 return Type::make_pointer_type(byte_type);
1810 case STRING_INFO_LENGTH:
1811 return Type::lookup_integer_type("int");
1812 default:
1813 go_unreachable();
1817 // Return string information in GENERIC.
1819 Bexpression*
1820 String_info_expression::do_get_backend(Translate_context* context)
1822 Gogo* gogo = context->gogo();
1824 Bexpression* bstring = this->string_->get_backend(context);
1825 switch (this->string_info_)
1827 case STRING_INFO_DATA:
1828 case STRING_INFO_LENGTH:
1829 return gogo->backend()->struct_field_expression(bstring,
1830 this->string_info_,
1831 this->location());
1832 break;
1833 default:
1834 go_unreachable();
1838 // Dump ast representation for a type info expression.
1840 void
1841 String_info_expression::do_dump_expression(
1842 Ast_dump_context* ast_dump_context) const
1844 ast_dump_context->ostream() << "stringinfo(";
1845 this->string_->dump_expression(ast_dump_context);
1846 ast_dump_context->ostream() << ",";
1847 ast_dump_context->ostream() <<
1848 (this->string_info_ == STRING_INFO_DATA ? "data"
1849 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1850 : "unknown");
1851 ast_dump_context->ostream() << ")";
1854 // Make a string info expression.
1856 Expression*
1857 Expression::make_string_info(Expression* string, String_info string_info,
1858 Location location)
1860 return new String_info_expression(string, string_info, location);
1863 // Make an integer expression.
1865 class Integer_expression : public Expression
1867 public:
1868 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1869 Location location)
1870 : Expression(EXPRESSION_INTEGER, location),
1871 type_(type), is_character_constant_(is_character_constant)
1872 { mpz_init_set(this->val_, *val); }
1874 static Expression*
1875 do_import(Import*);
1877 // Write VAL to string dump.
1878 static void
1879 export_integer(String_dump* exp, const mpz_t val);
1881 // Write VAL to dump context.
1882 static void
1883 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1885 protected:
1886 bool
1887 do_is_constant() const
1888 { return true; }
1890 bool
1891 do_is_static_initializer() const
1892 { return true; }
1894 bool
1895 do_numeric_constant_value(Numeric_constant* nc) const;
1897 Type*
1898 do_type();
1900 void
1901 do_determine_type(const Type_context* context);
1903 void
1904 do_check_types(Gogo*);
1906 Bexpression*
1907 do_get_backend(Translate_context*);
1909 Expression*
1910 do_copy()
1912 if (this->is_character_constant_)
1913 return Expression::make_character(&this->val_, this->type_,
1914 this->location());
1915 else
1916 return Expression::make_integer_z(&this->val_, this->type_,
1917 this->location());
1920 void
1921 do_export(Export*) const;
1923 void
1924 do_dump_expression(Ast_dump_context*) const;
1926 private:
1927 // The integer value.
1928 mpz_t val_;
1929 // The type so far.
1930 Type* type_;
1931 // Whether this is a character constant.
1932 bool is_character_constant_;
1935 // Return a numeric constant for this expression. We have to mark
1936 // this as a character when appropriate.
1938 bool
1939 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1941 if (this->is_character_constant_)
1942 nc->set_rune(this->type_, this->val_);
1943 else
1944 nc->set_int(this->type_, this->val_);
1945 return true;
1948 // Return the current type. If we haven't set the type yet, we return
1949 // an abstract integer type.
1951 Type*
1952 Integer_expression::do_type()
1954 if (this->type_ == NULL)
1956 if (this->is_character_constant_)
1957 this->type_ = Type::make_abstract_character_type();
1958 else
1959 this->type_ = Type::make_abstract_integer_type();
1961 return this->type_;
1964 // Set the type of the integer value. Here we may switch from an
1965 // abstract type to a real type.
1967 void
1968 Integer_expression::do_determine_type(const Type_context* context)
1970 if (this->type_ != NULL && !this->type_->is_abstract())
1972 else if (context->type != NULL && context->type->is_numeric_type())
1973 this->type_ = context->type;
1974 else if (!context->may_be_abstract)
1976 if (this->is_character_constant_)
1977 this->type_ = Type::lookup_integer_type("int32");
1978 else
1979 this->type_ = Type::lookup_integer_type("int");
1983 // Check the type of an integer constant.
1985 void
1986 Integer_expression::do_check_types(Gogo*)
1988 Type* type = this->type_;
1989 if (type == NULL)
1990 return;
1991 Numeric_constant nc;
1992 if (this->is_character_constant_)
1993 nc.set_rune(NULL, this->val_);
1994 else
1995 nc.set_int(NULL, this->val_);
1996 if (!nc.set_type(type, true, this->location()))
1997 this->set_is_error();
2000 // Get the backend representation for an integer constant.
2002 Bexpression*
2003 Integer_expression::do_get_backend(Translate_context* context)
2005 if (this->is_error_expression()
2006 || (this->type_ != NULL && this->type_->is_error_type()))
2008 go_assert(saw_errors());
2009 return context->gogo()->backend()->error_expression();
2012 Type* resolved_type = NULL;
2013 if (this->type_ != NULL && !this->type_->is_abstract())
2014 resolved_type = this->type_;
2015 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2017 // We are converting to an abstract floating point type.
2018 resolved_type = Type::lookup_float_type("float64");
2020 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2022 // We are converting to an abstract complex type.
2023 resolved_type = Type::lookup_complex_type("complex128");
2025 else
2027 // If we still have an abstract type here, then this is being
2028 // used in a constant expression which didn't get reduced for
2029 // some reason. Use a type which will fit the value. We use <,
2030 // not <=, because we need an extra bit for the sign bit.
2031 int bits = mpz_sizeinbase(this->val_, 2);
2032 Type* int_type = Type::lookup_integer_type("int");
2033 if (bits < int_type->integer_type()->bits())
2034 resolved_type = int_type;
2035 else if (bits < 64)
2036 resolved_type = Type::lookup_integer_type("int64");
2037 else
2039 if (!saw_errors())
2040 go_error_at(this->location(),
2041 "unknown type for large integer constant");
2042 return context->gogo()->backend()->error_expression();
2045 Numeric_constant nc;
2046 nc.set_int(resolved_type, this->val_);
2047 return Expression::backend_numeric_constant_expression(context, &nc);
2050 // Write VAL to export data.
2052 void
2053 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2055 char* s = mpz_get_str(NULL, 10, val);
2056 exp->write_c_string(s);
2057 free(s);
2060 // Export an integer in a constant expression.
2062 void
2063 Integer_expression::do_export(Export* exp) const
2065 Integer_expression::export_integer(exp, this->val_);
2066 if (this->is_character_constant_)
2067 exp->write_c_string("'");
2068 // A trailing space lets us reliably identify the end of the number.
2069 exp->write_c_string(" ");
2072 // Import an integer, floating point, or complex value. This handles
2073 // all these types because they all start with digits.
2075 Expression*
2076 Integer_expression::do_import(Import* imp)
2078 std::string num = imp->read_identifier();
2079 imp->require_c_string(" ");
2080 if (!num.empty() && num[num.length() - 1] == 'i')
2082 mpfr_t real;
2083 size_t plus_pos = num.find('+', 1);
2084 size_t minus_pos = num.find('-', 1);
2085 size_t pos;
2086 if (plus_pos == std::string::npos)
2087 pos = minus_pos;
2088 else if (minus_pos == std::string::npos)
2089 pos = plus_pos;
2090 else
2092 go_error_at(imp->location(), "bad number in import data: %qs",
2093 num.c_str());
2094 return Expression::make_error(imp->location());
2096 if (pos == std::string::npos)
2097 mpfr_set_ui(real, 0, GMP_RNDN);
2098 else
2100 std::string real_str = num.substr(0, pos);
2101 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2103 go_error_at(imp->location(), "bad number in import data: %qs",
2104 real_str.c_str());
2105 return Expression::make_error(imp->location());
2109 std::string imag_str;
2110 if (pos == std::string::npos)
2111 imag_str = num;
2112 else
2113 imag_str = num.substr(pos);
2114 imag_str = imag_str.substr(0, imag_str.size() - 1);
2115 mpfr_t imag;
2116 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2118 go_error_at(imp->location(), "bad number in import data: %qs",
2119 imag_str.c_str());
2120 return Expression::make_error(imp->location());
2122 mpc_t cval;
2123 mpc_init2(cval, mpc_precision);
2124 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2125 mpfr_clear(real);
2126 mpfr_clear(imag);
2127 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2128 mpc_clear(cval);
2129 return ret;
2131 else if (num.find('.') == std::string::npos
2132 && num.find('E') == std::string::npos)
2134 bool is_character_constant = (!num.empty()
2135 && num[num.length() - 1] == '\'');
2136 if (is_character_constant)
2137 num = num.substr(0, num.length() - 1);
2138 mpz_t val;
2139 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2141 go_error_at(imp->location(), "bad number in import data: %qs",
2142 num.c_str());
2143 return Expression::make_error(imp->location());
2145 Expression* ret;
2146 if (is_character_constant)
2147 ret = Expression::make_character(&val, NULL, imp->location());
2148 else
2149 ret = Expression::make_integer_z(&val, NULL, imp->location());
2150 mpz_clear(val);
2151 return ret;
2153 else
2155 mpfr_t val;
2156 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2158 go_error_at(imp->location(), "bad number in import data: %qs",
2159 num.c_str());
2160 return Expression::make_error(imp->location());
2162 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2163 mpfr_clear(val);
2164 return ret;
2167 // Ast dump for integer expression.
2169 void
2170 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2172 if (this->is_character_constant_)
2173 ast_dump_context->ostream() << '\'';
2174 Integer_expression::export_integer(ast_dump_context, this->val_);
2175 if (this->is_character_constant_)
2176 ast_dump_context->ostream() << '\'';
2179 // Build a new integer value from a multi-precision integer.
2181 Expression*
2182 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2184 return new Integer_expression(val, type, false, location);
2187 // Build a new integer value from an unsigned long.
2189 Expression*
2190 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2192 mpz_t zval;
2193 mpz_init_set_ui(zval, val);
2194 Expression* ret = Expression::make_integer_z(&zval, type, location);
2195 mpz_clear(zval);
2196 return ret;
2199 // Build a new integer value from a signed long.
2201 Expression*
2202 Expression::make_integer_sl(long val, Type *type, Location location)
2204 mpz_t zval;
2205 mpz_init_set_si(zval, val);
2206 Expression* ret = Expression::make_integer_z(&zval, type, location);
2207 mpz_clear(zval);
2208 return ret;
2211 // Store an int64_t in an uninitialized mpz_t.
2213 static void
2214 set_mpz_from_int64(mpz_t* zval, int64_t val)
2216 if (val >= 0)
2218 unsigned long ul = static_cast<unsigned long>(val);
2219 if (static_cast<int64_t>(ul) == val)
2221 mpz_init_set_ui(*zval, ul);
2222 return;
2225 uint64_t uv;
2226 if (val >= 0)
2227 uv = static_cast<uint64_t>(val);
2228 else
2229 uv = static_cast<uint64_t>(- val);
2230 unsigned long ul = uv & 0xffffffffUL;
2231 mpz_init_set_ui(*zval, ul);
2232 mpz_t hval;
2233 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2234 mpz_mul_2exp(hval, hval, 32);
2235 mpz_add(*zval, *zval, hval);
2236 mpz_clear(hval);
2237 if (val < 0)
2238 mpz_neg(*zval, *zval);
2241 // Build a new integer value from an int64_t.
2243 Expression*
2244 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2246 mpz_t zval;
2247 set_mpz_from_int64(&zval, val);
2248 Expression* ret = Expression::make_integer_z(&zval, type, location);
2249 mpz_clear(zval);
2250 return ret;
2253 // Build a new character constant value.
2255 Expression*
2256 Expression::make_character(const mpz_t* val, Type* type, Location location)
2258 return new Integer_expression(val, type, true, location);
2261 // Floats.
2263 class Float_expression : public Expression
2265 public:
2266 Float_expression(const mpfr_t* val, Type* type, Location location)
2267 : Expression(EXPRESSION_FLOAT, location),
2268 type_(type)
2270 mpfr_init_set(this->val_, *val, GMP_RNDN);
2273 // Write VAL to export data.
2274 static void
2275 export_float(String_dump* exp, const mpfr_t val);
2277 // Write VAL to dump file.
2278 static void
2279 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2281 protected:
2282 bool
2283 do_is_constant() const
2284 { return true; }
2286 bool
2287 do_is_static_initializer() const
2288 { return true; }
2290 bool
2291 do_numeric_constant_value(Numeric_constant* nc) const
2293 nc->set_float(this->type_, this->val_);
2294 return true;
2297 Type*
2298 do_type();
2300 void
2301 do_determine_type(const Type_context*);
2303 void
2304 do_check_types(Gogo*);
2306 Expression*
2307 do_copy()
2308 { return Expression::make_float(&this->val_, this->type_,
2309 this->location()); }
2311 Bexpression*
2312 do_get_backend(Translate_context*);
2314 void
2315 do_export(Export*) const;
2317 void
2318 do_dump_expression(Ast_dump_context*) const;
2320 private:
2321 // The floating point value.
2322 mpfr_t val_;
2323 // The type so far.
2324 Type* type_;
2327 // Return the current type. If we haven't set the type yet, we return
2328 // an abstract float type.
2330 Type*
2331 Float_expression::do_type()
2333 if (this->type_ == NULL)
2334 this->type_ = Type::make_abstract_float_type();
2335 return this->type_;
2338 // Set the type of the float value. Here we may switch from an
2339 // abstract type to a real type.
2341 void
2342 Float_expression::do_determine_type(const Type_context* context)
2344 if (this->type_ != NULL && !this->type_->is_abstract())
2346 else if (context->type != NULL
2347 && (context->type->integer_type() != NULL
2348 || context->type->float_type() != NULL
2349 || context->type->complex_type() != NULL))
2350 this->type_ = context->type;
2351 else if (!context->may_be_abstract)
2352 this->type_ = Type::lookup_float_type("float64");
2355 // Check the type of a float value.
2357 void
2358 Float_expression::do_check_types(Gogo*)
2360 Type* type = this->type_;
2361 if (type == NULL)
2362 return;
2363 Numeric_constant nc;
2364 nc.set_float(NULL, this->val_);
2365 if (!nc.set_type(this->type_, true, this->location()))
2366 this->set_is_error();
2369 // Get the backend representation for a float constant.
2371 Bexpression*
2372 Float_expression::do_get_backend(Translate_context* context)
2374 if (this->is_error_expression()
2375 || (this->type_ != NULL && this->type_->is_error_type()))
2377 go_assert(saw_errors());
2378 return context->gogo()->backend()->error_expression();
2381 Type* resolved_type;
2382 if (this->type_ != NULL && !this->type_->is_abstract())
2383 resolved_type = this->type_;
2384 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2386 // We have an abstract integer type. We just hope for the best.
2387 resolved_type = Type::lookup_integer_type("int");
2389 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2391 // We are converting to an abstract complex type.
2392 resolved_type = Type::lookup_complex_type("complex128");
2394 else
2396 // If we still have an abstract type here, then this is being
2397 // used in a constant expression which didn't get reduced. We
2398 // just use float64 and hope for the best.
2399 resolved_type = Type::lookup_float_type("float64");
2402 Numeric_constant nc;
2403 nc.set_float(resolved_type, this->val_);
2404 return Expression::backend_numeric_constant_expression(context, &nc);
2407 // Write a floating point number to a string dump.
2409 void
2410 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2412 mp_exp_t exponent;
2413 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2414 if (*s == '-')
2415 exp->write_c_string("-");
2416 exp->write_c_string("0.");
2417 exp->write_c_string(*s == '-' ? s + 1 : s);
2418 mpfr_free_str(s);
2419 char buf[30];
2420 snprintf(buf, sizeof buf, "E%ld", exponent);
2421 exp->write_c_string(buf);
2424 // Export a floating point number in a constant expression.
2426 void
2427 Float_expression::do_export(Export* exp) const
2429 Float_expression::export_float(exp, this->val_);
2430 // A trailing space lets us reliably identify the end of the number.
2431 exp->write_c_string(" ");
2434 // Dump a floating point number to the dump file.
2436 void
2437 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2439 Float_expression::export_float(ast_dump_context, this->val_);
2442 // Make a float expression.
2444 Expression*
2445 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2447 return new Float_expression(val, type, location);
2450 // Complex numbers.
2452 class Complex_expression : public Expression
2454 public:
2455 Complex_expression(const mpc_t* val, Type* type, Location location)
2456 : Expression(EXPRESSION_COMPLEX, location),
2457 type_(type)
2459 mpc_init2(this->val_, mpc_precision);
2460 mpc_set(this->val_, *val, MPC_RNDNN);
2463 // Write VAL to string dump.
2464 static void
2465 export_complex(String_dump* exp, const mpc_t val);
2467 // Write REAL/IMAG to dump context.
2468 static void
2469 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2471 protected:
2472 bool
2473 do_is_constant() const
2474 { return true; }
2476 bool
2477 do_is_static_initializer() const
2478 { return true; }
2480 bool
2481 do_numeric_constant_value(Numeric_constant* nc) const
2483 nc->set_complex(this->type_, this->val_);
2484 return true;
2487 Type*
2488 do_type();
2490 void
2491 do_determine_type(const Type_context*);
2493 void
2494 do_check_types(Gogo*);
2496 Expression*
2497 do_copy()
2499 return Expression::make_complex(&this->val_, this->type_,
2500 this->location());
2503 Bexpression*
2504 do_get_backend(Translate_context*);
2506 void
2507 do_export(Export*) const;
2509 void
2510 do_dump_expression(Ast_dump_context*) const;
2512 private:
2513 // The complex value.
2514 mpc_t val_;
2515 // The type if known.
2516 Type* type_;
2519 // Return the current type. If we haven't set the type yet, we return
2520 // an abstract complex type.
2522 Type*
2523 Complex_expression::do_type()
2525 if (this->type_ == NULL)
2526 this->type_ = Type::make_abstract_complex_type();
2527 return this->type_;
2530 // Set the type of the complex value. Here we may switch from an
2531 // abstract type to a real type.
2533 void
2534 Complex_expression::do_determine_type(const Type_context* context)
2536 if (this->type_ != NULL && !this->type_->is_abstract())
2538 else if (context->type != NULL && context->type->is_numeric_type())
2539 this->type_ = context->type;
2540 else if (!context->may_be_abstract)
2541 this->type_ = Type::lookup_complex_type("complex128");
2544 // Check the type of a complex value.
2546 void
2547 Complex_expression::do_check_types(Gogo*)
2549 Type* type = this->type_;
2550 if (type == NULL)
2551 return;
2552 Numeric_constant nc;
2553 nc.set_complex(NULL, this->val_);
2554 if (!nc.set_type(this->type_, true, this->location()))
2555 this->set_is_error();
2558 // Get the backend representation for a complex constant.
2560 Bexpression*
2561 Complex_expression::do_get_backend(Translate_context* context)
2563 if (this->is_error_expression()
2564 || (this->type_ != NULL && this->type_->is_error_type()))
2566 go_assert(saw_errors());
2567 return context->gogo()->backend()->error_expression();
2570 Type* resolved_type;
2571 if (this->type_ != NULL && !this->type_->is_abstract())
2572 resolved_type = this->type_;
2573 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2575 // We are converting to an abstract integer type.
2576 resolved_type = Type::lookup_integer_type("int");
2578 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2580 // We are converting to an abstract float type.
2581 resolved_type = Type::lookup_float_type("float64");
2583 else
2585 // If we still have an abstract type here, this is being
2586 // used in a constant expression which didn't get reduced. We
2587 // just use complex128 and hope for the best.
2588 resolved_type = Type::lookup_complex_type("complex128");
2591 Numeric_constant nc;
2592 nc.set_complex(resolved_type, this->val_);
2593 return Expression::backend_numeric_constant_expression(context, &nc);
2596 // Write REAL/IMAG to export data.
2598 void
2599 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2601 if (!mpfr_zero_p(mpc_realref(val)))
2603 Float_expression::export_float(exp, mpc_realref(val));
2604 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2605 exp->write_c_string("+");
2607 Float_expression::export_float(exp, mpc_imagref(val));
2608 exp->write_c_string("i");
2611 // Export a complex number in a constant expression.
2613 void
2614 Complex_expression::do_export(Export* exp) const
2616 Complex_expression::export_complex(exp, this->val_);
2617 // A trailing space lets us reliably identify the end of the number.
2618 exp->write_c_string(" ");
2621 // Dump a complex expression to the dump file.
2623 void
2624 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2626 Complex_expression::export_complex(ast_dump_context, this->val_);
2629 // Make a complex expression.
2631 Expression*
2632 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2634 return new Complex_expression(val, type, location);
2637 // Find a named object in an expression.
2639 class Find_named_object : public Traverse
2641 public:
2642 Find_named_object(Named_object* no)
2643 : Traverse(traverse_expressions),
2644 no_(no), found_(false)
2647 // Whether we found the object.
2648 bool
2649 found() const
2650 { return this->found_; }
2652 protected:
2654 expression(Expression**);
2656 private:
2657 // The object we are looking for.
2658 Named_object* no_;
2659 // Whether we found it.
2660 bool found_;
2663 // A reference to a const in an expression.
2665 class Const_expression : public Expression
2667 public:
2668 Const_expression(Named_object* constant, Location location)
2669 : Expression(EXPRESSION_CONST_REFERENCE, location),
2670 constant_(constant), type_(NULL), seen_(false)
2673 Named_object*
2674 named_object()
2675 { return this->constant_; }
2677 // Check that the initializer does not refer to the constant itself.
2678 void
2679 check_for_init_loop();
2681 protected:
2683 do_traverse(Traverse*);
2685 Expression*
2686 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2688 bool
2689 do_is_constant() const
2690 { return true; }
2692 bool
2693 do_is_static_initializer() const
2694 { return true; }
2696 bool
2697 do_numeric_constant_value(Numeric_constant* nc) const;
2699 bool
2700 do_string_constant_value(std::string* val) const;
2702 Type*
2703 do_type();
2705 // The type of a const is set by the declaration, not the use.
2706 void
2707 do_determine_type(const Type_context*);
2709 void
2710 do_check_types(Gogo*);
2712 Expression*
2713 do_copy()
2714 { return this; }
2716 Bexpression*
2717 do_get_backend(Translate_context* context);
2719 // When exporting a reference to a const as part of a const
2720 // expression, we export the value. We ignore the fact that it has
2721 // a name.
2722 void
2723 do_export(Export* exp) const
2724 { this->constant_->const_value()->expr()->export_expression(exp); }
2726 void
2727 do_dump_expression(Ast_dump_context*) const;
2729 private:
2730 // The constant.
2731 Named_object* constant_;
2732 // The type of this reference. This is used if the constant has an
2733 // abstract type.
2734 Type* type_;
2735 // Used to prevent infinite recursion when a constant incorrectly
2736 // refers to itself.
2737 mutable bool seen_;
2740 // Traversal.
2743 Const_expression::do_traverse(Traverse* traverse)
2745 if (this->type_ != NULL)
2746 return Type::traverse(this->type_, traverse);
2747 return TRAVERSE_CONTINUE;
2750 // Lower a constant expression. This is where we convert the
2751 // predeclared constant iota into an integer value.
2753 Expression*
2754 Const_expression::do_lower(Gogo* gogo, Named_object*,
2755 Statement_inserter*, int iota_value)
2757 if (this->constant_->const_value()->expr()->classification()
2758 == EXPRESSION_IOTA)
2760 if (iota_value == -1)
2762 go_error_at(this->location(),
2763 "iota is only defined in const declarations");
2764 iota_value = 0;
2766 return Expression::make_integer_ul(iota_value, NULL, this->location());
2769 // Make sure that the constant itself has been lowered.
2770 gogo->lower_constant(this->constant_);
2772 return this;
2775 // Return a numeric constant value.
2777 bool
2778 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2780 if (this->seen_)
2781 return false;
2783 Expression* e = this->constant_->const_value()->expr();
2785 this->seen_ = true;
2787 bool r = e->numeric_constant_value(nc);
2789 this->seen_ = false;
2791 Type* ctype;
2792 if (this->type_ != NULL)
2793 ctype = this->type_;
2794 else
2795 ctype = this->constant_->const_value()->type();
2796 if (r && ctype != NULL)
2798 if (!nc->set_type(ctype, false, this->location()))
2799 return false;
2802 return r;
2805 bool
2806 Const_expression::do_string_constant_value(std::string* val) const
2808 if (this->seen_)
2809 return false;
2811 Expression* e = this->constant_->const_value()->expr();
2813 this->seen_ = true;
2814 bool ok = e->string_constant_value(val);
2815 this->seen_ = false;
2817 return ok;
2820 // Return the type of the const reference.
2822 Type*
2823 Const_expression::do_type()
2825 if (this->type_ != NULL)
2826 return this->type_;
2828 Named_constant* nc = this->constant_->const_value();
2830 if (this->seen_ || nc->lowering())
2832 this->report_error(_("constant refers to itself"));
2833 this->type_ = Type::make_error_type();
2834 return this->type_;
2837 this->seen_ = true;
2839 Type* ret = nc->type();
2841 if (ret != NULL)
2843 this->seen_ = false;
2844 return ret;
2847 // During parsing, a named constant may have a NULL type, but we
2848 // must not return a NULL type here.
2849 ret = nc->expr()->type();
2851 this->seen_ = false;
2853 return ret;
2856 // Set the type of the const reference.
2858 void
2859 Const_expression::do_determine_type(const Type_context* context)
2861 Type* ctype = this->constant_->const_value()->type();
2862 Type* cetype = (ctype != NULL
2863 ? ctype
2864 : this->constant_->const_value()->expr()->type());
2865 if (ctype != NULL && !ctype->is_abstract())
2867 else if (context->type != NULL
2868 && context->type->is_numeric_type()
2869 && cetype->is_numeric_type())
2870 this->type_ = context->type;
2871 else if (context->type != NULL
2872 && context->type->is_string_type()
2873 && cetype->is_string_type())
2874 this->type_ = context->type;
2875 else if (context->type != NULL
2876 && context->type->is_boolean_type()
2877 && cetype->is_boolean_type())
2878 this->type_ = context->type;
2879 else if (!context->may_be_abstract)
2881 if (cetype->is_abstract())
2882 cetype = cetype->make_non_abstract_type();
2883 this->type_ = cetype;
2887 // Check for a loop in which the initializer of a constant refers to
2888 // the constant itself.
2890 void
2891 Const_expression::check_for_init_loop()
2893 if (this->type_ != NULL && this->type_->is_error())
2894 return;
2896 if (this->seen_)
2898 this->report_error(_("constant refers to itself"));
2899 this->type_ = Type::make_error_type();
2900 return;
2903 Expression* init = this->constant_->const_value()->expr();
2904 Find_named_object find_named_object(this->constant_);
2906 this->seen_ = true;
2907 Expression::traverse(&init, &find_named_object);
2908 this->seen_ = false;
2910 if (find_named_object.found())
2912 if (this->type_ == NULL || !this->type_->is_error())
2914 this->report_error(_("constant refers to itself"));
2915 this->type_ = Type::make_error_type();
2917 return;
2921 // Check types of a const reference.
2923 void
2924 Const_expression::do_check_types(Gogo*)
2926 if (this->type_ != NULL && this->type_->is_error())
2927 return;
2929 this->check_for_init_loop();
2931 // Check that numeric constant fits in type.
2932 if (this->type_ != NULL && this->type_->is_numeric_type())
2934 Numeric_constant nc;
2935 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2937 if (!nc.set_type(this->type_, true, this->location()))
2938 this->set_is_error();
2943 // Return the backend representation for a const reference.
2945 Bexpression*
2946 Const_expression::do_get_backend(Translate_context* context)
2948 if (this->is_error_expression()
2949 || (this->type_ != NULL && this->type_->is_error()))
2951 go_assert(saw_errors());
2952 return context->backend()->error_expression();
2955 // If the type has been set for this expression, but the underlying
2956 // object is an abstract int or float, we try to get the abstract
2957 // value. Otherwise we may lose something in the conversion.
2958 Expression* expr = this->constant_->const_value()->expr();
2959 if (this->type_ != NULL
2960 && this->type_->is_numeric_type()
2961 && (this->constant_->const_value()->type() == NULL
2962 || this->constant_->const_value()->type()->is_abstract()))
2964 Numeric_constant nc;
2965 if (expr->numeric_constant_value(&nc)
2966 && nc.set_type(this->type_, false, this->location()))
2968 Expression* e = nc.expression(this->location());
2969 return e->get_backend(context);
2973 if (this->type_ != NULL)
2974 expr = Expression::make_cast(this->type_, expr, this->location());
2975 return expr->get_backend(context);
2978 // Dump ast representation for constant expression.
2980 void
2981 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2983 ast_dump_context->ostream() << this->constant_->name();
2986 // Make a reference to a constant in an expression.
2988 Expression*
2989 Expression::make_const_reference(Named_object* constant,
2990 Location location)
2992 return new Const_expression(constant, location);
2995 // Find a named object in an expression.
2998 Find_named_object::expression(Expression** pexpr)
3000 switch ((*pexpr)->classification())
3002 case Expression::EXPRESSION_CONST_REFERENCE:
3004 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3005 if (ce->named_object() == this->no_)
3006 break;
3008 // We need to check a constant initializer explicitly, as
3009 // loops here will not be caught by the loop checking for
3010 // variable initializers.
3011 ce->check_for_init_loop();
3013 return TRAVERSE_CONTINUE;
3016 case Expression::EXPRESSION_VAR_REFERENCE:
3017 if ((*pexpr)->var_expression()->named_object() == this->no_)
3018 break;
3019 return TRAVERSE_CONTINUE;
3020 case Expression::EXPRESSION_FUNC_REFERENCE:
3021 if ((*pexpr)->func_expression()->named_object() == this->no_)
3022 break;
3023 return TRAVERSE_CONTINUE;
3024 default:
3025 return TRAVERSE_CONTINUE;
3027 this->found_ = true;
3028 return TRAVERSE_EXIT;
3031 // The nil value.
3033 class Nil_expression : public Expression
3035 public:
3036 Nil_expression(Location location)
3037 : Expression(EXPRESSION_NIL, location)
3040 static Expression*
3041 do_import(Import*);
3043 protected:
3044 bool
3045 do_is_constant() const
3046 { return true; }
3048 bool
3049 do_is_static_initializer() const
3050 { return true; }
3052 Type*
3053 do_type()
3054 { return Type::make_nil_type(); }
3056 void
3057 do_determine_type(const Type_context*)
3060 Expression*
3061 do_copy()
3062 { return this; }
3064 Bexpression*
3065 do_get_backend(Translate_context* context)
3066 { return context->backend()->nil_pointer_expression(); }
3068 void
3069 do_export(Export* exp) const
3070 { exp->write_c_string("nil"); }
3072 void
3073 do_dump_expression(Ast_dump_context* ast_dump_context) const
3074 { ast_dump_context->ostream() << "nil"; }
3077 // Import a nil expression.
3079 Expression*
3080 Nil_expression::do_import(Import* imp)
3082 imp->require_c_string("nil");
3083 return Expression::make_nil(imp->location());
3086 // Make a nil expression.
3088 Expression*
3089 Expression::make_nil(Location location)
3091 return new Nil_expression(location);
3094 // The value of the predeclared constant iota. This is little more
3095 // than a marker. This will be lowered to an integer in
3096 // Const_expression::do_lower, which is where we know the value that
3097 // it should have.
3099 class Iota_expression : public Parser_expression
3101 public:
3102 Iota_expression(Location location)
3103 : Parser_expression(EXPRESSION_IOTA, location)
3106 protected:
3107 Expression*
3108 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3109 { go_unreachable(); }
3111 // There should only ever be one of these.
3112 Expression*
3113 do_copy()
3114 { go_unreachable(); }
3116 void
3117 do_dump_expression(Ast_dump_context* ast_dump_context) const
3118 { ast_dump_context->ostream() << "iota"; }
3121 // Make an iota expression. This is only called for one case: the
3122 // value of the predeclared constant iota.
3124 Expression*
3125 Expression::make_iota()
3127 static Iota_expression iota_expression(Linemap::unknown_location());
3128 return &iota_expression;
3131 // Class Type_conversion_expression.
3133 // Traversal.
3136 Type_conversion_expression::do_traverse(Traverse* traverse)
3138 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3139 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3140 return TRAVERSE_EXIT;
3141 return TRAVERSE_CONTINUE;
3144 // Convert to a constant at lowering time.
3146 Expression*
3147 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3148 Statement_inserter*, int)
3150 Type* type = this->type_;
3151 Expression* val = this->expr_;
3152 Location location = this->location();
3154 if (type->is_numeric_type())
3156 Numeric_constant nc;
3157 if (val->numeric_constant_value(&nc))
3159 if (!nc.set_type(type, true, location))
3160 return Expression::make_error(location);
3161 return nc.expression(location);
3165 // According to the language specification on string conversions
3166 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3167 // When converting an integer into a string, the string will be a UTF-8
3168 // representation of the integer and integers "outside the range of valid
3169 // Unicode code points are converted to '\uFFFD'."
3170 if (type->is_string_type())
3172 Numeric_constant nc;
3173 if (val->numeric_constant_value(&nc) && nc.is_int())
3175 // An integer value doesn't fit in the Unicode code point range if it
3176 // overflows the Go "int" type or is negative.
3177 unsigned long ul;
3178 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3179 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3180 return Expression::make_string("\ufffd", location);
3184 if (type->is_slice_type())
3186 Type* element_type = type->array_type()->element_type()->forwarded();
3187 bool is_byte = (element_type->integer_type() != NULL
3188 && element_type->integer_type()->is_byte());
3189 bool is_rune = (element_type->integer_type() != NULL
3190 && element_type->integer_type()->is_rune());
3191 if (is_byte || is_rune)
3193 std::string s;
3194 if (val->string_constant_value(&s))
3196 Expression_list* vals = new Expression_list();
3197 if (is_byte)
3199 for (std::string::const_iterator p = s.begin();
3200 p != s.end();
3201 p++)
3203 unsigned char c = static_cast<unsigned char>(*p);
3204 vals->push_back(Expression::make_integer_ul(c,
3205 element_type,
3206 location));
3209 else
3211 const char *p = s.data();
3212 const char *pend = s.data() + s.length();
3213 while (p < pend)
3215 unsigned int c;
3216 int adv = Lex::fetch_char(p, &c);
3217 if (adv == 0)
3219 go_warning_at(this->location(), 0,
3220 "invalid UTF-8 encoding");
3221 adv = 1;
3223 p += adv;
3224 vals->push_back(Expression::make_integer_ul(c,
3225 element_type,
3226 location));
3230 return Expression::make_slice_composite_literal(type, vals,
3231 location);
3236 return this;
3239 // Flatten a type conversion by using a temporary variable for the slice
3240 // in slice to string conversions.
3242 Expression*
3243 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3244 Statement_inserter* inserter)
3246 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3248 go_assert(saw_errors());
3249 return Expression::make_error(this->location());
3252 if (((this->type()->is_string_type()
3253 && this->expr_->type()->is_slice_type())
3254 || this->expr_->type()->interface_type() != NULL)
3255 && !this->expr_->is_variable())
3257 Temporary_statement* temp =
3258 Statement::make_temporary(NULL, this->expr_, this->location());
3259 inserter->insert(temp);
3260 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3262 return this;
3265 // Return whether a type conversion is a constant.
3267 bool
3268 Type_conversion_expression::do_is_constant() const
3270 if (!this->expr_->is_constant())
3271 return false;
3273 // A conversion to a type that may not be used as a constant is not
3274 // a constant. For example, []byte(nil).
3275 Type* type = this->type_;
3276 if (type->integer_type() == NULL
3277 && type->float_type() == NULL
3278 && type->complex_type() == NULL
3279 && !type->is_boolean_type()
3280 && !type->is_string_type())
3281 return false;
3283 return true;
3286 // Return whether a type conversion can be used in a constant
3287 // initializer.
3289 bool
3290 Type_conversion_expression::do_is_static_initializer() const
3292 Type* type = this->type_;
3293 Type* expr_type = this->expr_->type();
3295 if (type->interface_type() != NULL
3296 || expr_type->interface_type() != NULL)
3297 return false;
3299 if (!this->expr_->is_static_initializer())
3300 return false;
3302 if (Type::are_identical(type, expr_type, false, NULL))
3303 return true;
3305 return type->is_basic_type() && expr_type->is_basic_type();
3308 // Return the constant numeric value if there is one.
3310 bool
3311 Type_conversion_expression::do_numeric_constant_value(
3312 Numeric_constant* nc) const
3314 if (!this->type_->is_numeric_type())
3315 return false;
3316 if (!this->expr_->numeric_constant_value(nc))
3317 return false;
3318 return nc->set_type(this->type_, false, this->location());
3321 // Return the constant string value if there is one.
3323 bool
3324 Type_conversion_expression::do_string_constant_value(std::string* val) const
3326 if (this->type_->is_string_type()
3327 && this->expr_->type()->integer_type() != NULL)
3329 Numeric_constant nc;
3330 if (this->expr_->numeric_constant_value(&nc))
3332 unsigned long ival;
3333 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3335 val->clear();
3336 Lex::append_char(ival, true, val, this->location());
3337 return true;
3342 // FIXME: Could handle conversion from const []int here.
3344 return false;
3347 // Determine the resulting type of the conversion.
3349 void
3350 Type_conversion_expression::do_determine_type(const Type_context*)
3352 Type_context subcontext(this->type_, false);
3353 this->expr_->determine_type(&subcontext);
3356 // Check that types are convertible.
3358 void
3359 Type_conversion_expression::do_check_types(Gogo*)
3361 Type* type = this->type_;
3362 Type* expr_type = this->expr_->type();
3363 std::string reason;
3365 if (type->is_error() || expr_type->is_error())
3367 this->set_is_error();
3368 return;
3371 if (this->may_convert_function_types_
3372 && type->function_type() != NULL
3373 && expr_type->function_type() != NULL)
3374 return;
3376 if (Type::are_convertible(type, expr_type, &reason))
3377 return;
3379 go_error_at(this->location(), "%s", reason.c_str());
3380 this->set_is_error();
3383 // Get the backend representation for a type conversion.
3385 Bexpression*
3386 Type_conversion_expression::do_get_backend(Translate_context* context)
3388 Type* type = this->type_;
3389 Type* expr_type = this->expr_->type();
3391 Gogo* gogo = context->gogo();
3392 Btype* btype = type->get_backend(gogo);
3393 Bexpression* bexpr = this->expr_->get_backend(context);
3394 Location loc = this->location();
3396 if (Type::are_identical(type, expr_type, false, NULL))
3397 return gogo->backend()->convert_expression(btype, bexpr, loc);
3398 else if (type->interface_type() != NULL
3399 || expr_type->interface_type() != NULL)
3401 Expression* conversion =
3402 Expression::convert_for_assignment(gogo, type, this->expr_,
3403 this->location());
3404 return conversion->get_backend(context);
3406 else if (type->is_string_type()
3407 && expr_type->integer_type() != NULL)
3409 mpz_t intval;
3410 Numeric_constant nc;
3411 if (this->expr_->numeric_constant_value(&nc)
3412 && nc.to_int(&intval)
3413 && mpz_fits_ushort_p(intval))
3415 std::string s;
3416 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3417 mpz_clear(intval);
3418 Expression* se = Expression::make_string(s, loc);
3419 return se->get_backend(context);
3422 Expression* i2s_expr =
3423 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3424 Expression::make_nil(loc), this->expr_);
3425 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3427 else if (type->is_string_type() && expr_type->is_slice_type())
3429 Array_type* a = expr_type->array_type();
3430 Type* e = a->element_type()->forwarded();
3431 go_assert(e->integer_type() != NULL);
3432 go_assert(this->expr_->is_variable());
3434 Runtime::Function code;
3435 if (e->integer_type()->is_byte())
3436 code = Runtime::SLICEBYTETOSTRING;
3437 else
3439 go_assert(e->integer_type()->is_rune());
3440 code = Runtime::SLICERUNETOSTRING;
3442 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3443 this->expr_)->get_backend(context);
3445 else if (type->is_slice_type() && expr_type->is_string_type())
3447 Type* e = type->array_type()->element_type()->forwarded();
3448 go_assert(e->integer_type() != NULL);
3450 Runtime::Function code;
3451 if (e->integer_type()->is_byte())
3452 code = Runtime::STRINGTOSLICEBYTE;
3453 else
3455 go_assert(e->integer_type()->is_rune());
3456 code = Runtime::STRINGTOSLICERUNE;
3458 Expression* s2a = Runtime::make_call(code, loc, 2,
3459 Expression::make_nil(loc),
3460 this->expr_);
3461 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3463 else if (type->is_numeric_type())
3465 go_assert(Type::are_convertible(type, expr_type, NULL));
3466 return gogo->backend()->convert_expression(btype, bexpr, loc);
3468 else if ((type->is_unsafe_pointer_type()
3469 && (expr_type->points_to() != NULL
3470 || expr_type->integer_type()))
3471 || (expr_type->is_unsafe_pointer_type()
3472 && type->points_to() != NULL)
3473 || (this->may_convert_function_types_
3474 && type->function_type() != NULL
3475 && expr_type->function_type() != NULL))
3476 return gogo->backend()->convert_expression(btype, bexpr, loc);
3477 else
3479 Expression* conversion =
3480 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3481 return conversion->get_backend(context);
3485 // Output a type conversion in a constant expression.
3487 void
3488 Type_conversion_expression::do_export(Export* exp) const
3490 exp->write_c_string("convert(");
3491 exp->write_type(this->type_);
3492 exp->write_c_string(", ");
3493 this->expr_->export_expression(exp);
3494 exp->write_c_string(")");
3497 // Import a type conversion or a struct construction.
3499 Expression*
3500 Type_conversion_expression::do_import(Import* imp)
3502 imp->require_c_string("convert(");
3503 Type* type = imp->read_type();
3504 imp->require_c_string(", ");
3505 Expression* val = Expression::import_expression(imp);
3506 imp->require_c_string(")");
3507 return Expression::make_cast(type, val, imp->location());
3510 // Dump ast representation for a type conversion expression.
3512 void
3513 Type_conversion_expression::do_dump_expression(
3514 Ast_dump_context* ast_dump_context) const
3516 ast_dump_context->dump_type(this->type_);
3517 ast_dump_context->ostream() << "(";
3518 ast_dump_context->dump_expression(this->expr_);
3519 ast_dump_context->ostream() << ") ";
3522 // Make a type cast expression.
3524 Expression*
3525 Expression::make_cast(Type* type, Expression* val, Location location)
3527 if (type->is_error_type() || val->is_error_expression())
3528 return Expression::make_error(location);
3529 return new Type_conversion_expression(type, val, location);
3532 // Class Unsafe_type_conversion_expression.
3534 // Traversal.
3537 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3539 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3540 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3541 return TRAVERSE_EXIT;
3542 return TRAVERSE_CONTINUE;
3545 // Return whether an unsafe type conversion can be used as a constant
3546 // initializer.
3548 bool
3549 Unsafe_type_conversion_expression::do_is_static_initializer() const
3551 Type* type = this->type_;
3552 Type* expr_type = this->expr_->type();
3554 if (type->interface_type() != NULL
3555 || expr_type->interface_type() != NULL)
3556 return false;
3558 if (!this->expr_->is_static_initializer())
3559 return false;
3561 if (Type::are_convertible(type, expr_type, NULL))
3562 return true;
3564 return type->is_basic_type() && expr_type->is_basic_type();
3567 // Convert to backend representation.
3569 Bexpression*
3570 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3572 // We are only called for a limited number of cases.
3574 Type* t = this->type_;
3575 Type* et = this->expr_->type();
3577 if (t->is_error_type()
3578 || this->expr_->is_error_expression()
3579 || et->is_error_type())
3581 go_assert(saw_errors());
3582 return context->backend()->error_expression();
3585 if (t->array_type() != NULL)
3586 go_assert(et->array_type() != NULL
3587 && t->is_slice_type() == et->is_slice_type());
3588 else if (t->struct_type() != NULL)
3590 if (t->named_type() != NULL
3591 && et->named_type() != NULL
3592 && !Type::are_convertible(t, et, NULL))
3594 go_assert(saw_errors());
3595 return context->backend()->error_expression();
3598 go_assert(et->struct_type() != NULL
3599 && Type::are_convertible(t, et, NULL));
3601 else if (t->map_type() != NULL)
3602 go_assert(et->map_type() != NULL);
3603 else if (t->channel_type() != NULL)
3604 go_assert(et->channel_type() != NULL);
3605 else if (t->points_to() != NULL)
3606 go_assert(et->points_to() != NULL
3607 || et->channel_type() != NULL
3608 || et->map_type() != NULL
3609 || et->function_type() != NULL
3610 || et->integer_type() != NULL
3611 || et->is_nil_type());
3612 else if (et->is_unsafe_pointer_type())
3613 go_assert(t->points_to() != NULL);
3614 else if (t->interface_type() != NULL)
3616 bool empty_iface = t->interface_type()->is_empty();
3617 go_assert(et->interface_type() != NULL
3618 && et->interface_type()->is_empty() == empty_iface);
3620 else if (t->integer_type() != NULL)
3621 go_assert(et->is_boolean_type()
3622 || et->integer_type() != NULL
3623 || et->function_type() != NULL
3624 || et->points_to() != NULL
3625 || et->map_type() != NULL
3626 || et->channel_type() != NULL
3627 || et->is_nil_type());
3628 else if (t->function_type() != NULL)
3629 go_assert(et->points_to() != NULL);
3630 else
3631 go_unreachable();
3633 Gogo* gogo = context->gogo();
3634 Btype* btype = t->get_backend(gogo);
3635 Bexpression* bexpr = this->expr_->get_backend(context);
3636 Location loc = this->location();
3637 return gogo->backend()->convert_expression(btype, bexpr, loc);
3640 // Dump ast representation for an unsafe type conversion expression.
3642 void
3643 Unsafe_type_conversion_expression::do_dump_expression(
3644 Ast_dump_context* ast_dump_context) const
3646 ast_dump_context->dump_type(this->type_);
3647 ast_dump_context->ostream() << "(";
3648 ast_dump_context->dump_expression(this->expr_);
3649 ast_dump_context->ostream() << ") ";
3652 // Make an unsafe type conversion expression.
3654 Expression*
3655 Expression::make_unsafe_cast(Type* type, Expression* expr,
3656 Location location)
3658 return new Unsafe_type_conversion_expression(type, expr, location);
3661 // Class Unary_expression.
3663 // If we are taking the address of a composite literal, and the
3664 // contents are not constant, then we want to make a heap expression
3665 // instead.
3667 Expression*
3668 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3670 Location loc = this->location();
3671 Operator op = this->op_;
3672 Expression* expr = this->expr_;
3674 if (op == OPERATOR_MULT && expr->is_type_expression())
3675 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3677 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3678 // moving x to the heap. FIXME: Is it worth doing a real escape
3679 // analysis here? This case is found in math/unsafe.go and is
3680 // therefore worth special casing.
3681 if (op == OPERATOR_MULT)
3683 Expression* e = expr;
3684 while (e->classification() == EXPRESSION_CONVERSION)
3686 Type_conversion_expression* te
3687 = static_cast<Type_conversion_expression*>(e);
3688 e = te->expr();
3691 if (e->classification() == EXPRESSION_UNARY)
3693 Unary_expression* ue = static_cast<Unary_expression*>(e);
3694 if (ue->op_ == OPERATOR_AND)
3696 if (e == expr)
3698 // *&x == x.
3699 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3701 go_error_at(ue->location(),
3702 "invalid operand for unary %<&%>");
3703 this->set_is_error();
3705 return ue->expr_;
3707 ue->set_does_not_escape();
3712 // Catching an invalid indirection of unsafe.Pointer here avoid
3713 // having to deal with TYPE_VOID in other places.
3714 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3716 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3717 return Expression::make_error(this->location());
3720 // Check for an invalid pointer dereference. We need to do this
3721 // here because Unary_expression::do_type will return an error type
3722 // in this case. That can cause code to appear erroneous, and
3723 // therefore disappear at lowering time, without any error message.
3724 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3726 this->report_error(_("expected pointer"));
3727 return Expression::make_error(this->location());
3730 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3732 Numeric_constant nc;
3733 if (expr->numeric_constant_value(&nc))
3735 Numeric_constant result;
3736 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3737 return result.expression(loc);
3741 return this;
3744 // Flatten expression if a nil check must be performed and create temporary
3745 // variables if necessary.
3747 Expression*
3748 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3749 Statement_inserter* inserter)
3751 if (this->is_error_expression()
3752 || this->expr_->is_error_expression()
3753 || this->expr_->type()->is_error_type())
3755 go_assert(saw_errors());
3756 return Expression::make_error(this->location());
3759 Location location = this->location();
3760 if (this->op_ == OPERATOR_MULT
3761 && !this->expr_->is_variable())
3763 go_assert(this->expr_->type()->points_to() != NULL);
3764 Type* ptype = this->expr_->type()->points_to();
3765 if (!ptype->is_void_type())
3767 int64_t s;
3768 bool ok = ptype->backend_type_size(gogo, &s);
3769 if (!ok)
3771 go_assert(saw_errors());
3772 return Expression::make_error(this->location());
3774 if (s >= 4096 || this->issue_nil_check_)
3776 Temporary_statement* temp =
3777 Statement::make_temporary(NULL, this->expr_, location);
3778 inserter->insert(temp);
3779 this->expr_ =
3780 Expression::make_temporary_reference(temp, location);
3785 if (this->op_ == OPERATOR_AND)
3787 // If this->escapes_ is false at this point, then it was set to
3788 // false by an explicit call to set_does_not_escape, and the
3789 // value does not escape. If this->escapes_ is true, we may be
3790 // able to set it to false if taking the address of a variable
3791 // that does not escape.
3792 Node* n = Node::make_node(this);
3793 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3794 this->escapes_ = false;
3796 // When compiling the runtime, the address operator does not
3797 // cause local variables to escape. When escape analysis
3798 // becomes the default, this should be changed to make it an
3799 // error if we have an address operator that escapes.
3800 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
3801 this->escapes_ = false;
3803 Named_object* var = NULL;
3804 if (this->expr_->var_expression() != NULL)
3805 var = this->expr_->var_expression()->named_object();
3806 else if (this->expr_->enclosed_var_expression() != NULL)
3807 var = this->expr_->enclosed_var_expression()->variable();
3809 if (this->escapes_ && var != NULL)
3811 if (var->is_variable())
3812 this->escapes_ = var->var_value()->escapes();
3813 if (var->is_result_variable())
3814 this->escapes_ = var->result_var_value()->escapes();
3816 this->expr_->address_taken(this->escapes_);
3819 if (this->create_temp_ && !this->expr_->is_variable())
3821 Temporary_statement* temp =
3822 Statement::make_temporary(NULL, this->expr_, location);
3823 inserter->insert(temp);
3824 this->expr_ = Expression::make_temporary_reference(temp, location);
3827 return this;
3830 // Return whether a unary expression is a constant.
3832 bool
3833 Unary_expression::do_is_constant() const
3835 if (this->op_ == OPERATOR_MULT)
3837 // Indirecting through a pointer is only constant if the object
3838 // to which the expression points is constant, but we currently
3839 // have no way to determine that.
3840 return false;
3842 else if (this->op_ == OPERATOR_AND)
3844 // Taking the address of a variable is constant if it is a
3845 // global variable, not constant otherwise. In other cases taking the
3846 // address is probably not a constant.
3847 Var_expression* ve = this->expr_->var_expression();
3848 if (ve != NULL)
3850 Named_object* no = ve->named_object();
3851 return no->is_variable() && no->var_value()->is_global();
3853 return false;
3855 else
3856 return this->expr_->is_constant();
3859 // Return whether a unary expression can be used as a constant
3860 // initializer.
3862 bool
3863 Unary_expression::do_is_static_initializer() const
3865 if (this->op_ == OPERATOR_MULT)
3866 return false;
3867 else if (this->op_ == OPERATOR_AND)
3869 // The address of a global variable can used as a static
3870 // initializer.
3871 Var_expression* ve = this->expr_->var_expression();
3872 if (ve != NULL)
3874 Named_object* no = ve->named_object();
3875 return no->is_variable() && no->var_value()->is_global();
3878 // The address of a composite literal can be used as a static
3879 // initializer if the composite literal is itself usable as a
3880 // static initializer.
3881 if (this->expr_->is_composite_literal()
3882 && this->expr_->is_static_initializer())
3883 return true;
3885 // The address of a string constant can be used as a static
3886 // initializer. This can not be written in Go itself but this
3887 // is used when building a type descriptor.
3888 if (this->expr_->string_expression() != NULL)
3889 return true;
3891 return false;
3893 else
3894 return this->expr_->is_static_initializer();
3897 // Apply unary opcode OP to UNC, setting NC. Return true if this
3898 // could be done, false if not. Issue errors for overflow.
3900 bool
3901 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3902 Location location, Numeric_constant* nc)
3904 switch (op)
3906 case OPERATOR_PLUS:
3907 *nc = *unc;
3908 return true;
3910 case OPERATOR_MINUS:
3911 if (unc->is_int() || unc->is_rune())
3912 break;
3913 else if (unc->is_float())
3915 mpfr_t uval;
3916 unc->get_float(&uval);
3917 mpfr_t val;
3918 mpfr_init(val);
3919 mpfr_neg(val, uval, GMP_RNDN);
3920 nc->set_float(unc->type(), val);
3921 mpfr_clear(uval);
3922 mpfr_clear(val);
3923 return true;
3925 else if (unc->is_complex())
3927 mpc_t uval;
3928 unc->get_complex(&uval);
3929 mpc_t val;
3930 mpc_init2(val, mpc_precision);
3931 mpc_neg(val, uval, MPC_RNDNN);
3932 nc->set_complex(unc->type(), val);
3933 mpc_clear(uval);
3934 mpc_clear(val);
3935 return true;
3937 else
3938 go_unreachable();
3940 case OPERATOR_XOR:
3941 break;
3943 case OPERATOR_NOT:
3944 case OPERATOR_AND:
3945 case OPERATOR_MULT:
3946 return false;
3948 default:
3949 go_unreachable();
3952 if (!unc->is_int() && !unc->is_rune())
3953 return false;
3955 mpz_t uval;
3956 if (unc->is_rune())
3957 unc->get_rune(&uval);
3958 else
3959 unc->get_int(&uval);
3960 mpz_t val;
3961 mpz_init(val);
3963 switch (op)
3965 case OPERATOR_MINUS:
3966 mpz_neg(val, uval);
3967 break;
3969 case OPERATOR_NOT:
3970 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3971 break;
3973 case OPERATOR_XOR:
3975 Type* utype = unc->type();
3976 if (utype->integer_type() == NULL
3977 || utype->integer_type()->is_abstract())
3978 mpz_com(val, uval);
3979 else
3981 // The number of HOST_WIDE_INTs that it takes to represent
3982 // UVAL.
3983 size_t count = ((mpz_sizeinbase(uval, 2)
3984 + HOST_BITS_PER_WIDE_INT
3985 - 1)
3986 / HOST_BITS_PER_WIDE_INT);
3988 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3989 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3991 size_t obits = utype->integer_type()->bits();
3993 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3995 mpz_t adj;
3996 mpz_init_set_ui(adj, 1);
3997 mpz_mul_2exp(adj, adj, obits);
3998 mpz_add(uval, uval, adj);
3999 mpz_clear(adj);
4002 size_t ecount;
4003 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4004 go_assert(ecount <= count);
4006 // Trim down to the number of words required by the type.
4007 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4008 / HOST_BITS_PER_WIDE_INT);
4009 go_assert(ocount <= count);
4011 for (size_t i = 0; i < ocount; ++i)
4012 phwi[i] = ~phwi[i];
4014 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4015 if (clearbits != 0)
4016 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4017 >> clearbits);
4019 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4021 if (!utype->integer_type()->is_unsigned()
4022 && mpz_tstbit(val, obits - 1))
4024 mpz_t adj;
4025 mpz_init_set_ui(adj, 1);
4026 mpz_mul_2exp(adj, adj, obits);
4027 mpz_sub(val, val, adj);
4028 mpz_clear(adj);
4031 delete[] phwi;
4034 break;
4036 default:
4037 go_unreachable();
4040 if (unc->is_rune())
4041 nc->set_rune(NULL, val);
4042 else
4043 nc->set_int(NULL, val);
4045 mpz_clear(uval);
4046 mpz_clear(val);
4048 return nc->set_type(unc->type(), true, location);
4051 // Return the integral constant value of a unary expression, if it has one.
4053 bool
4054 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4056 Numeric_constant unc;
4057 if (!this->expr_->numeric_constant_value(&unc))
4058 return false;
4059 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4060 nc);
4063 // Return the type of a unary expression.
4065 Type*
4066 Unary_expression::do_type()
4068 switch (this->op_)
4070 case OPERATOR_PLUS:
4071 case OPERATOR_MINUS:
4072 case OPERATOR_NOT:
4073 case OPERATOR_XOR:
4074 return this->expr_->type();
4076 case OPERATOR_AND:
4077 return Type::make_pointer_type(this->expr_->type());
4079 case OPERATOR_MULT:
4081 Type* subtype = this->expr_->type();
4082 Type* points_to = subtype->points_to();
4083 if (points_to == NULL)
4084 return Type::make_error_type();
4085 return points_to;
4088 default:
4089 go_unreachable();
4093 // Determine abstract types for a unary expression.
4095 void
4096 Unary_expression::do_determine_type(const Type_context* context)
4098 switch (this->op_)
4100 case OPERATOR_PLUS:
4101 case OPERATOR_MINUS:
4102 case OPERATOR_NOT:
4103 case OPERATOR_XOR:
4104 this->expr_->determine_type(context);
4105 break;
4107 case OPERATOR_AND:
4108 // Taking the address of something.
4110 Type* subtype = (context->type == NULL
4111 ? NULL
4112 : context->type->points_to());
4113 Type_context subcontext(subtype, false);
4114 this->expr_->determine_type(&subcontext);
4116 break;
4118 case OPERATOR_MULT:
4119 // Indirecting through a pointer.
4121 Type* subtype = (context->type == NULL
4122 ? NULL
4123 : Type::make_pointer_type(context->type));
4124 Type_context subcontext(subtype, false);
4125 this->expr_->determine_type(&subcontext);
4127 break;
4129 default:
4130 go_unreachable();
4134 // Check types for a unary expression.
4136 void
4137 Unary_expression::do_check_types(Gogo*)
4139 Type* type = this->expr_->type();
4140 if (type->is_error())
4142 this->set_is_error();
4143 return;
4146 switch (this->op_)
4148 case OPERATOR_PLUS:
4149 case OPERATOR_MINUS:
4150 if (type->integer_type() == NULL
4151 && type->float_type() == NULL
4152 && type->complex_type() == NULL)
4153 this->report_error(_("expected numeric type"));
4154 break;
4156 case OPERATOR_NOT:
4157 if (!type->is_boolean_type())
4158 this->report_error(_("expected boolean type"));
4159 break;
4161 case OPERATOR_XOR:
4162 if (type->integer_type() == NULL)
4163 this->report_error(_("expected integer"));
4164 break;
4166 case OPERATOR_AND:
4167 if (!this->expr_->is_addressable())
4169 if (!this->create_temp_)
4171 go_error_at(this->location(), "invalid operand for unary %<&%>");
4172 this->set_is_error();
4175 else
4176 this->expr_->issue_nil_check();
4177 break;
4179 case OPERATOR_MULT:
4180 // Indirecting through a pointer.
4181 if (type->points_to() == NULL)
4182 this->report_error(_("expected pointer"));
4183 if (type->points_to()->is_error())
4184 this->set_is_error();
4185 break;
4187 default:
4188 go_unreachable();
4192 // Get the backend representation for a unary expression.
4194 Bexpression*
4195 Unary_expression::do_get_backend(Translate_context* context)
4197 Gogo* gogo = context->gogo();
4198 Location loc = this->location();
4200 // Taking the address of a set-and-use-temporary expression requires
4201 // setting the temporary and then taking the address.
4202 if (this->op_ == OPERATOR_AND)
4204 Set_and_use_temporary_expression* sut =
4205 this->expr_->set_and_use_temporary_expression();
4206 if (sut != NULL)
4208 Temporary_statement* temp = sut->temporary();
4209 Bvariable* bvar = temp->get_backend_variable(context);
4210 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4211 Bexpression* bval = sut->expression()->get_backend(context);
4213 Bstatement* bassign =
4214 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4215 Bexpression* bvar_addr =
4216 gogo->backend()->address_expression(bvar_expr, loc);
4217 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4221 Bexpression* ret;
4222 Bexpression* bexpr = this->expr_->get_backend(context);
4223 Btype* btype = this->expr_->type()->get_backend(gogo);
4224 switch (this->op_)
4226 case OPERATOR_PLUS:
4227 ret = bexpr;
4228 break;
4230 case OPERATOR_MINUS:
4231 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4232 ret = gogo->backend()->convert_expression(btype, ret, loc);
4233 break;
4235 case OPERATOR_NOT:
4236 case OPERATOR_XOR:
4237 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4238 break;
4240 case OPERATOR_AND:
4241 if (!this->create_temp_)
4243 // We should not see a non-constant constructor here; cases
4244 // where we would see one should have been moved onto the
4245 // heap at parse time. Taking the address of a nonconstant
4246 // constructor will not do what the programmer expects.
4248 go_assert(!this->expr_->is_composite_literal()
4249 || this->expr_->is_static_initializer());
4250 if (this->expr_->classification() == EXPRESSION_UNARY)
4252 Unary_expression* ue =
4253 static_cast<Unary_expression*>(this->expr_);
4254 go_assert(ue->op() != OPERATOR_AND);
4258 static unsigned int counter;
4259 char buf[100];
4260 if (this->is_gc_root_ || this->is_slice_init_)
4262 bool copy_to_heap = false;
4263 if (this->is_gc_root_)
4265 // Build a decl for a GC root variable. GC roots are mutable, so
4266 // they cannot be represented as an immutable_struct in the
4267 // backend.
4268 static unsigned int root_counter;
4269 snprintf(buf, sizeof buf, "gc%u", root_counter);
4270 ++root_counter;
4272 else
4274 // Build a decl for a slice value initializer. An immutable slice
4275 // value initializer may have to be copied to the heap if it
4276 // contains pointers in a non-constant context.
4277 snprintf(buf, sizeof buf, "C%u", counter);
4278 ++counter;
4280 Array_type* at = this->expr_->type()->array_type();
4281 go_assert(at != NULL);
4283 // If we are not copying the value to the heap, we will only
4284 // initialize the value once, so we can use this directly
4285 // rather than copying it. In that case we can't make it
4286 // read-only, because the program is permitted to change it.
4287 copy_to_heap = context->function() != NULL;
4289 std::string asm_name(go_selectively_encode_id(buf));
4290 Bvariable* implicit =
4291 gogo->backend()->implicit_variable(buf, asm_name,
4292 btype, true, copy_to_heap,
4293 false, 0);
4294 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4295 true, copy_to_heap, false,
4296 bexpr);
4297 bexpr = gogo->backend()->var_expression(implicit, loc);
4299 else if ((this->expr_->is_composite_literal()
4300 || this->expr_->string_expression() != NULL)
4301 && this->expr_->is_static_initializer())
4303 // Build a decl for a constant constructor.
4304 snprintf(buf, sizeof buf, "C%u", counter);
4305 ++counter;
4307 std::string asm_name(go_selectively_encode_id(buf));
4308 Bvariable* decl =
4309 gogo->backend()->immutable_struct(buf, asm_name,
4310 true, false, btype, loc);
4311 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4312 btype, loc, bexpr);
4313 bexpr = gogo->backend()->var_expression(decl, loc);
4316 go_assert(!this->create_temp_ || this->expr_->is_variable());
4317 ret = gogo->backend()->address_expression(bexpr, loc);
4318 break;
4320 case OPERATOR_MULT:
4322 go_assert(this->expr_->type()->points_to() != NULL);
4324 // If we are dereferencing the pointer to a large struct, we
4325 // need to check for nil. We don't bother to check for small
4326 // structs because we expect the system to crash on a nil
4327 // pointer dereference. However, if we know the address of this
4328 // expression is being taken, we must always check for nil.
4330 Type* ptype = this->expr_->type()->points_to();
4331 Btype* pbtype = ptype->get_backend(gogo);
4332 if (!ptype->is_void_type())
4334 int64_t s;
4335 bool ok = ptype->backend_type_size(gogo, &s);
4336 if (!ok)
4338 go_assert(saw_errors());
4339 return gogo->backend()->error_expression();
4341 if (s >= 4096 || this->issue_nil_check_)
4343 go_assert(this->expr_->is_variable());
4344 Bexpression* nil =
4345 Expression::make_nil(loc)->get_backend(context);
4346 Bexpression* compare =
4347 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4348 nil, loc);
4349 Bexpression* crash =
4350 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4351 loc)->get_backend(context);
4352 bexpr = gogo->backend()->conditional_expression(btype, compare,
4353 crash, bexpr,
4354 loc);
4358 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4360 break;
4362 default:
4363 go_unreachable();
4366 return ret;
4369 // Export a unary expression.
4371 void
4372 Unary_expression::do_export(Export* exp) const
4374 switch (this->op_)
4376 case OPERATOR_PLUS:
4377 exp->write_c_string("+ ");
4378 break;
4379 case OPERATOR_MINUS:
4380 exp->write_c_string("- ");
4381 break;
4382 case OPERATOR_NOT:
4383 exp->write_c_string("! ");
4384 break;
4385 case OPERATOR_XOR:
4386 exp->write_c_string("^ ");
4387 break;
4388 case OPERATOR_AND:
4389 case OPERATOR_MULT:
4390 default:
4391 go_unreachable();
4393 this->expr_->export_expression(exp);
4396 // Import a unary expression.
4398 Expression*
4399 Unary_expression::do_import(Import* imp)
4401 Operator op;
4402 switch (imp->get_char())
4404 case '+':
4405 op = OPERATOR_PLUS;
4406 break;
4407 case '-':
4408 op = OPERATOR_MINUS;
4409 break;
4410 case '!':
4411 op = OPERATOR_NOT;
4412 break;
4413 case '^':
4414 op = OPERATOR_XOR;
4415 break;
4416 default:
4417 go_unreachable();
4419 imp->require_c_string(" ");
4420 Expression* expr = Expression::import_expression(imp);
4421 return Expression::make_unary(op, expr, imp->location());
4424 // Dump ast representation of an unary expression.
4426 void
4427 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4429 ast_dump_context->dump_operator(this->op_);
4430 ast_dump_context->ostream() << "(";
4431 ast_dump_context->dump_expression(this->expr_);
4432 ast_dump_context->ostream() << ") ";
4435 // Make a unary expression.
4437 Expression*
4438 Expression::make_unary(Operator op, Expression* expr, Location location)
4440 return new Unary_expression(op, expr, location);
4443 // If this is an indirection through a pointer, return the expression
4444 // being pointed through. Otherwise return this.
4446 Expression*
4447 Expression::deref()
4449 if (this->classification_ == EXPRESSION_UNARY)
4451 Unary_expression* ue = static_cast<Unary_expression*>(this);
4452 if (ue->op() == OPERATOR_MULT)
4453 return ue->operand();
4455 return this;
4458 // Class Binary_expression.
4460 // Traversal.
4463 Binary_expression::do_traverse(Traverse* traverse)
4465 int t = Expression::traverse(&this->left_, traverse);
4466 if (t == TRAVERSE_EXIT)
4467 return TRAVERSE_EXIT;
4468 return Expression::traverse(&this->right_, traverse);
4471 // Return whether this expression may be used as a static initializer.
4473 bool
4474 Binary_expression::do_is_static_initializer() const
4476 if (!this->left_->is_static_initializer()
4477 || !this->right_->is_static_initializer())
4478 return false;
4480 // Addresses can be static initializers, but we can't implement
4481 // arbitray binary expressions of them.
4482 Unary_expression* lu = this->left_->unary_expression();
4483 Unary_expression* ru = this->right_->unary_expression();
4484 if (lu != NULL && lu->op() == OPERATOR_AND)
4486 if (ru != NULL && ru->op() == OPERATOR_AND)
4487 return this->op_ == OPERATOR_MINUS;
4488 else
4489 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4491 else if (ru != NULL && ru->op() == OPERATOR_AND)
4492 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4494 // Other cases should resolve in the backend.
4495 return true;
4498 // Return the type to use for a binary operation on operands of
4499 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4500 // such may be NULL or abstract.
4502 bool
4503 Binary_expression::operation_type(Operator op, Type* left_type,
4504 Type* right_type, Type** result_type)
4506 if (left_type != right_type
4507 && !left_type->is_abstract()
4508 && !right_type->is_abstract()
4509 && left_type->base() != right_type->base()
4510 && op != OPERATOR_LSHIFT
4511 && op != OPERATOR_RSHIFT)
4513 // May be a type error--let it be diagnosed elsewhere.
4514 return false;
4517 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4519 if (left_type->integer_type() != NULL)
4520 *result_type = left_type;
4521 else
4522 *result_type = Type::make_abstract_integer_type();
4524 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4525 *result_type = left_type;
4526 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4527 *result_type = right_type;
4528 else if (!left_type->is_abstract())
4529 *result_type = left_type;
4530 else if (!right_type->is_abstract())
4531 *result_type = right_type;
4532 else if (left_type->complex_type() != NULL)
4533 *result_type = left_type;
4534 else if (right_type->complex_type() != NULL)
4535 *result_type = right_type;
4536 else if (left_type->float_type() != NULL)
4537 *result_type = left_type;
4538 else if (right_type->float_type() != NULL)
4539 *result_type = right_type;
4540 else if (left_type->integer_type() != NULL
4541 && left_type->integer_type()->is_rune())
4542 *result_type = left_type;
4543 else if (right_type->integer_type() != NULL
4544 && right_type->integer_type()->is_rune())
4545 *result_type = right_type;
4546 else
4547 *result_type = left_type;
4549 return true;
4552 // Convert an integer comparison code and an operator to a boolean
4553 // value.
4555 bool
4556 Binary_expression::cmp_to_bool(Operator op, int cmp)
4558 switch (op)
4560 case OPERATOR_EQEQ:
4561 return cmp == 0;
4562 break;
4563 case OPERATOR_NOTEQ:
4564 return cmp != 0;
4565 break;
4566 case OPERATOR_LT:
4567 return cmp < 0;
4568 break;
4569 case OPERATOR_LE:
4570 return cmp <= 0;
4571 case OPERATOR_GT:
4572 return cmp > 0;
4573 case OPERATOR_GE:
4574 return cmp >= 0;
4575 default:
4576 go_unreachable();
4580 // Compare constants according to OP.
4582 bool
4583 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4584 Numeric_constant* right_nc,
4585 Location location, bool* result)
4587 Type* left_type = left_nc->type();
4588 Type* right_type = right_nc->type();
4590 Type* type;
4591 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4592 return false;
4594 // When comparing an untyped operand to a typed operand, we are
4595 // effectively coercing the untyped operand to the other operand's
4596 // type, so make sure that is valid.
4597 if (!left_nc->set_type(type, true, location)
4598 || !right_nc->set_type(type, true, location))
4599 return false;
4601 bool ret;
4602 int cmp;
4603 if (type->complex_type() != NULL)
4605 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4606 return false;
4607 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4609 else if (type->float_type() != NULL)
4610 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4611 else
4612 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4614 if (ret)
4615 *result = Binary_expression::cmp_to_bool(op, cmp);
4617 return ret;
4620 // Compare integer constants.
4622 bool
4623 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4624 const Numeric_constant* right_nc,
4625 int* cmp)
4627 mpz_t left_val;
4628 if (!left_nc->to_int(&left_val))
4629 return false;
4630 mpz_t right_val;
4631 if (!right_nc->to_int(&right_val))
4633 mpz_clear(left_val);
4634 return false;
4637 *cmp = mpz_cmp(left_val, right_val);
4639 mpz_clear(left_val);
4640 mpz_clear(right_val);
4642 return true;
4645 // Compare floating point constants.
4647 bool
4648 Binary_expression::compare_float(const Numeric_constant* left_nc,
4649 const Numeric_constant* right_nc,
4650 int* cmp)
4652 mpfr_t left_val;
4653 if (!left_nc->to_float(&left_val))
4654 return false;
4655 mpfr_t right_val;
4656 if (!right_nc->to_float(&right_val))
4658 mpfr_clear(left_val);
4659 return false;
4662 // We already coerced both operands to the same type. If that type
4663 // is not an abstract type, we need to round the values accordingly.
4664 Type* type = left_nc->type();
4665 if (!type->is_abstract() && type->float_type() != NULL)
4667 int bits = type->float_type()->bits();
4668 mpfr_prec_round(left_val, bits, GMP_RNDN);
4669 mpfr_prec_round(right_val, bits, GMP_RNDN);
4672 *cmp = mpfr_cmp(left_val, right_val);
4674 mpfr_clear(left_val);
4675 mpfr_clear(right_val);
4677 return true;
4680 // Compare complex constants. Complex numbers may only be compared
4681 // for equality.
4683 bool
4684 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4685 const Numeric_constant* right_nc,
4686 int* cmp)
4688 mpc_t left_val;
4689 if (!left_nc->to_complex(&left_val))
4690 return false;
4691 mpc_t right_val;
4692 if (!right_nc->to_complex(&right_val))
4694 mpc_clear(left_val);
4695 return false;
4698 // We already coerced both operands to the same type. If that type
4699 // is not an abstract type, we need to round the values accordingly.
4700 Type* type = left_nc->type();
4701 if (!type->is_abstract() && type->complex_type() != NULL)
4703 int bits = type->complex_type()->bits();
4704 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4705 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4706 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4707 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4710 *cmp = mpc_cmp(left_val, right_val) != 0;
4712 mpc_clear(left_val);
4713 mpc_clear(right_val);
4715 return true;
4718 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4719 // true if this could be done, false if not. Issue errors at LOCATION
4720 // as appropriate.
4722 bool
4723 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4724 Numeric_constant* right_nc,
4725 Location location, Numeric_constant* nc)
4727 switch (op)
4729 case OPERATOR_OROR:
4730 case OPERATOR_ANDAND:
4731 case OPERATOR_EQEQ:
4732 case OPERATOR_NOTEQ:
4733 case OPERATOR_LT:
4734 case OPERATOR_LE:
4735 case OPERATOR_GT:
4736 case OPERATOR_GE:
4737 // These return boolean values, not numeric.
4738 return false;
4739 default:
4740 break;
4743 Type* left_type = left_nc->type();
4744 Type* right_type = right_nc->type();
4746 Type* type;
4747 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4748 return false;
4750 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4752 // When combining an untyped operand with a typed operand, we are
4753 // effectively coercing the untyped operand to the other operand's
4754 // type, so make sure that is valid.
4755 if (!left_nc->set_type(type, true, location))
4756 return false;
4757 if (!is_shift && !right_nc->set_type(type, true, location))
4758 return false;
4759 if (is_shift
4760 && ((left_type->integer_type() == NULL
4761 && !left_type->is_abstract())
4762 || (right_type->integer_type() == NULL
4763 && !right_type->is_abstract())))
4764 return false;
4766 bool r;
4767 if (type->complex_type() != NULL)
4768 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4769 else if (type->float_type() != NULL)
4770 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4771 else
4772 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4774 if (r)
4775 r = nc->set_type(type, true, location);
4777 return r;
4780 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4781 // integer operations. Return true if this could be done, false if
4782 // not.
4784 bool
4785 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4786 const Numeric_constant* right_nc,
4787 Location location, Numeric_constant* nc)
4789 mpz_t left_val;
4790 if (!left_nc->to_int(&left_val))
4791 return false;
4792 mpz_t right_val;
4793 if (!right_nc->to_int(&right_val))
4795 mpz_clear(left_val);
4796 return false;
4799 mpz_t val;
4800 mpz_init(val);
4802 switch (op)
4804 case OPERATOR_PLUS:
4805 mpz_add(val, left_val, right_val);
4806 if (mpz_sizeinbase(val, 2) > 0x100000)
4808 go_error_at(location, "constant addition overflow");
4809 nc->set_invalid();
4810 mpz_set_ui(val, 1);
4812 break;
4813 case OPERATOR_MINUS:
4814 mpz_sub(val, left_val, right_val);
4815 if (mpz_sizeinbase(val, 2) > 0x100000)
4817 go_error_at(location, "constant subtraction overflow");
4818 nc->set_invalid();
4819 mpz_set_ui(val, 1);
4821 break;
4822 case OPERATOR_OR:
4823 mpz_ior(val, left_val, right_val);
4824 break;
4825 case OPERATOR_XOR:
4826 mpz_xor(val, left_val, right_val);
4827 break;
4828 case OPERATOR_MULT:
4829 mpz_mul(val, left_val, right_val);
4830 if (mpz_sizeinbase(val, 2) > 0x100000)
4832 go_error_at(location, "constant multiplication overflow");
4833 nc->set_invalid();
4834 mpz_set_ui(val, 1);
4836 break;
4837 case OPERATOR_DIV:
4838 if (mpz_sgn(right_val) != 0)
4839 mpz_tdiv_q(val, left_val, right_val);
4840 else
4842 go_error_at(location, "division by zero");
4843 nc->set_invalid();
4844 mpz_set_ui(val, 0);
4846 break;
4847 case OPERATOR_MOD:
4848 if (mpz_sgn(right_val) != 0)
4849 mpz_tdiv_r(val, left_val, right_val);
4850 else
4852 go_error_at(location, "division by zero");
4853 nc->set_invalid();
4854 mpz_set_ui(val, 0);
4856 break;
4857 case OPERATOR_LSHIFT:
4859 unsigned long shift = mpz_get_ui(right_val);
4860 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4861 mpz_mul_2exp(val, left_val, shift);
4862 else
4864 go_error_at(location, "shift count overflow");
4865 nc->set_invalid();
4866 mpz_set_ui(val, 1);
4868 break;
4870 break;
4871 case OPERATOR_RSHIFT:
4873 unsigned long shift = mpz_get_ui(right_val);
4874 if (mpz_cmp_ui(right_val, shift) != 0)
4876 go_error_at(location, "shift count overflow");
4877 nc->set_invalid();
4878 mpz_set_ui(val, 1);
4880 else
4882 if (mpz_cmp_ui(left_val, 0) >= 0)
4883 mpz_tdiv_q_2exp(val, left_val, shift);
4884 else
4885 mpz_fdiv_q_2exp(val, left_val, shift);
4887 break;
4889 break;
4890 case OPERATOR_AND:
4891 mpz_and(val, left_val, right_val);
4892 break;
4893 case OPERATOR_BITCLEAR:
4895 mpz_t tval;
4896 mpz_init(tval);
4897 mpz_com(tval, right_val);
4898 mpz_and(val, left_val, tval);
4899 mpz_clear(tval);
4901 break;
4902 default:
4903 go_unreachable();
4906 mpz_clear(left_val);
4907 mpz_clear(right_val);
4909 if (left_nc->is_rune()
4910 || (op != OPERATOR_LSHIFT
4911 && op != OPERATOR_RSHIFT
4912 && right_nc->is_rune()))
4913 nc->set_rune(NULL, val);
4914 else
4915 nc->set_int(NULL, val);
4917 mpz_clear(val);
4919 return true;
4922 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4923 // floating point operations. Return true if this could be done,
4924 // false if not.
4926 bool
4927 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4928 const Numeric_constant* right_nc,
4929 Location location, Numeric_constant* nc)
4931 mpfr_t left_val;
4932 if (!left_nc->to_float(&left_val))
4933 return false;
4934 mpfr_t right_val;
4935 if (!right_nc->to_float(&right_val))
4937 mpfr_clear(left_val);
4938 return false;
4941 mpfr_t val;
4942 mpfr_init(val);
4944 bool ret = true;
4945 switch (op)
4947 case OPERATOR_PLUS:
4948 mpfr_add(val, left_val, right_val, GMP_RNDN);
4949 break;
4950 case OPERATOR_MINUS:
4951 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4952 break;
4953 case OPERATOR_OR:
4954 case OPERATOR_XOR:
4955 case OPERATOR_AND:
4956 case OPERATOR_BITCLEAR:
4957 case OPERATOR_MOD:
4958 case OPERATOR_LSHIFT:
4959 case OPERATOR_RSHIFT:
4960 mpfr_set_ui(val, 0, GMP_RNDN);
4961 ret = false;
4962 break;
4963 case OPERATOR_MULT:
4964 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4965 break;
4966 case OPERATOR_DIV:
4967 if (!mpfr_zero_p(right_val))
4968 mpfr_div(val, left_val, right_val, GMP_RNDN);
4969 else
4971 go_error_at(location, "division by zero");
4972 nc->set_invalid();
4973 mpfr_set_ui(val, 0, GMP_RNDN);
4975 break;
4976 default:
4977 go_unreachable();
4980 mpfr_clear(left_val);
4981 mpfr_clear(right_val);
4983 nc->set_float(NULL, val);
4984 mpfr_clear(val);
4986 return ret;
4989 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4990 // complex operations. Return true if this could be done, false if
4991 // not.
4993 bool
4994 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4995 const Numeric_constant* right_nc,
4996 Location location, Numeric_constant* nc)
4998 mpc_t left_val;
4999 if (!left_nc->to_complex(&left_val))
5000 return false;
5001 mpc_t right_val;
5002 if (!right_nc->to_complex(&right_val))
5004 mpc_clear(left_val);
5005 return false;
5008 mpc_t val;
5009 mpc_init2(val, mpc_precision);
5011 bool ret = true;
5012 switch (op)
5014 case OPERATOR_PLUS:
5015 mpc_add(val, left_val, right_val, MPC_RNDNN);
5016 break;
5017 case OPERATOR_MINUS:
5018 mpc_sub(val, left_val, right_val, MPC_RNDNN);
5019 break;
5020 case OPERATOR_OR:
5021 case OPERATOR_XOR:
5022 case OPERATOR_AND:
5023 case OPERATOR_BITCLEAR:
5024 case OPERATOR_MOD:
5025 case OPERATOR_LSHIFT:
5026 case OPERATOR_RSHIFT:
5027 mpc_set_ui(val, 0, MPC_RNDNN);
5028 ret = false;
5029 break;
5030 case OPERATOR_MULT:
5031 mpc_mul(val, left_val, right_val, MPC_RNDNN);
5032 break;
5033 case OPERATOR_DIV:
5034 if (mpc_cmp_si(right_val, 0) == 0)
5036 go_error_at(location, "division by zero");
5037 nc->set_invalid();
5038 mpc_set_ui(val, 0, MPC_RNDNN);
5039 break;
5041 mpc_div(val, left_val, right_val, MPC_RNDNN);
5042 break;
5043 default:
5044 go_unreachable();
5047 mpc_clear(left_val);
5048 mpc_clear(right_val);
5050 nc->set_complex(NULL, val);
5051 mpc_clear(val);
5053 return ret;
5056 // Lower a binary expression. We have to evaluate constant
5057 // expressions now, in order to implement Go's unlimited precision
5058 // constants.
5060 Expression*
5061 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5062 Statement_inserter* inserter, int)
5064 Location location = this->location();
5065 Operator op = this->op_;
5066 Expression* left = this->left_;
5067 Expression* right = this->right_;
5069 const bool is_comparison = (op == OPERATOR_EQEQ
5070 || op == OPERATOR_NOTEQ
5071 || op == OPERATOR_LT
5072 || op == OPERATOR_LE
5073 || op == OPERATOR_GT
5074 || op == OPERATOR_GE);
5076 // Numeric constant expressions.
5078 Numeric_constant left_nc;
5079 Numeric_constant right_nc;
5080 if (left->numeric_constant_value(&left_nc)
5081 && right->numeric_constant_value(&right_nc))
5083 if (is_comparison)
5085 bool result;
5086 if (!Binary_expression::compare_constant(op, &left_nc,
5087 &right_nc, location,
5088 &result))
5089 return this;
5090 return Expression::make_cast(Type::make_boolean_type(),
5091 Expression::make_boolean(result,
5092 location),
5093 location);
5095 else
5097 Numeric_constant nc;
5098 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5099 location, &nc))
5100 return this;
5101 return nc.expression(location);
5106 // String constant expressions.
5107 if (left->type()->is_string_type() && right->type()->is_string_type())
5109 std::string left_string;
5110 std::string right_string;
5111 if (left->string_constant_value(&left_string)
5112 && right->string_constant_value(&right_string))
5114 if (op == OPERATOR_PLUS)
5115 return Expression::make_string(left_string + right_string,
5116 location);
5117 else if (is_comparison)
5119 int cmp = left_string.compare(right_string);
5120 bool r = Binary_expression::cmp_to_bool(op, cmp);
5121 return Expression::make_boolean(r, location);
5126 // Lower struct, array, and some interface comparisons.
5127 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5129 if (left->type()->struct_type() != NULL
5130 && right->type()->struct_type() != NULL)
5131 return this->lower_struct_comparison(gogo, inserter);
5132 else if (left->type()->array_type() != NULL
5133 && !left->type()->is_slice_type()
5134 && right->type()->array_type() != NULL
5135 && !right->type()->is_slice_type())
5136 return this->lower_array_comparison(gogo, inserter);
5137 else if ((left->type()->interface_type() != NULL
5138 && right->type()->interface_type() == NULL)
5139 || (left->type()->interface_type() == NULL
5140 && right->type()->interface_type() != NULL))
5141 return this->lower_interface_value_comparison(gogo, inserter);
5144 // Lower string concatenation to String_concat_expression, so that
5145 // we can group sequences of string additions.
5146 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5148 Expression_list* exprs;
5149 String_concat_expression* left_sce =
5150 this->left_->string_concat_expression();
5151 if (left_sce != NULL)
5152 exprs = left_sce->exprs();
5153 else
5155 exprs = new Expression_list();
5156 exprs->push_back(this->left_);
5159 String_concat_expression* right_sce =
5160 this->right_->string_concat_expression();
5161 if (right_sce != NULL)
5162 exprs->append(right_sce->exprs());
5163 else
5164 exprs->push_back(this->right_);
5166 return Expression::make_string_concat(exprs);
5169 return this;
5172 // Lower a struct comparison.
5174 Expression*
5175 Binary_expression::lower_struct_comparison(Gogo* gogo,
5176 Statement_inserter* inserter)
5178 Struct_type* st = this->left_->type()->struct_type();
5179 Struct_type* st2 = this->right_->type()->struct_type();
5180 if (st2 == NULL)
5181 return this;
5182 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5183 return this;
5184 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5185 this->right_->type(), NULL))
5186 return this;
5188 // See if we can compare using memcmp. As a heuristic, we use
5189 // memcmp rather than field references and comparisons if there are
5190 // more than two fields.
5191 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5192 return this->lower_compare_to_memcmp(gogo, inserter);
5194 Location loc = this->location();
5196 Expression* left = this->left_;
5197 Temporary_statement* left_temp = NULL;
5198 if (left->var_expression() == NULL
5199 && left->temporary_reference_expression() == NULL)
5201 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5202 inserter->insert(left_temp);
5203 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5206 Expression* right = this->right_;
5207 Temporary_statement* right_temp = NULL;
5208 if (right->var_expression() == NULL
5209 && right->temporary_reference_expression() == NULL)
5211 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5212 inserter->insert(right_temp);
5213 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5216 Expression* ret = Expression::make_boolean(true, loc);
5217 const Struct_field_list* fields = st->fields();
5218 unsigned int field_index = 0;
5219 for (Struct_field_list::const_iterator pf = fields->begin();
5220 pf != fields->end();
5221 ++pf, ++field_index)
5223 if (Gogo::is_sink_name(pf->field_name()))
5224 continue;
5226 if (field_index > 0)
5228 if (left_temp == NULL)
5229 left = left->copy();
5230 else
5231 left = Expression::make_temporary_reference(left_temp, loc);
5232 if (right_temp == NULL)
5233 right = right->copy();
5234 else
5235 right = Expression::make_temporary_reference(right_temp, loc);
5237 Expression* f1 = Expression::make_field_reference(left, field_index,
5238 loc);
5239 Expression* f2 = Expression::make_field_reference(right, field_index,
5240 loc);
5241 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5242 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5245 if (this->op_ == OPERATOR_NOTEQ)
5246 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5248 return ret;
5251 // Lower an array comparison.
5253 Expression*
5254 Binary_expression::lower_array_comparison(Gogo* gogo,
5255 Statement_inserter* inserter)
5257 Array_type* at = this->left_->type()->array_type();
5258 Array_type* at2 = this->right_->type()->array_type();
5259 if (at2 == NULL)
5260 return this;
5261 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5262 return this;
5263 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5264 this->right_->type(), NULL))
5265 return this;
5267 // Call memcmp directly if possible. This may let the middle-end
5268 // optimize the call.
5269 if (at->compare_is_identity(gogo))
5270 return this->lower_compare_to_memcmp(gogo, inserter);
5272 // Call the array comparison function.
5273 Named_object* hash_fn;
5274 Named_object* equal_fn;
5275 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5276 &hash_fn, &equal_fn);
5278 Location loc = this->location();
5280 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5282 Expression_list* args = new Expression_list();
5283 args->push_back(this->operand_address(inserter, this->left_));
5284 args->push_back(this->operand_address(inserter, this->right_));
5285 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5287 Expression* ret = Expression::make_call(func, args, false, loc);
5289 if (this->op_ == OPERATOR_NOTEQ)
5290 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5292 return ret;
5295 // Lower an interface to value comparison.
5297 Expression*
5298 Binary_expression::lower_interface_value_comparison(Gogo*,
5299 Statement_inserter* inserter)
5301 Type* left_type = this->left_->type();
5302 Type* right_type = this->right_->type();
5303 Interface_type* ift;
5304 if (left_type->interface_type() != NULL)
5306 ift = left_type->interface_type();
5307 if (!ift->implements_interface(right_type, NULL))
5308 return this;
5310 else
5312 ift = right_type->interface_type();
5313 if (!ift->implements_interface(left_type, NULL))
5314 return this;
5316 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5317 return this;
5319 Location loc = this->location();
5321 if (left_type->interface_type() == NULL
5322 && left_type->points_to() == NULL
5323 && !this->left_->is_addressable())
5325 Temporary_statement* temp =
5326 Statement::make_temporary(left_type, NULL, loc);
5327 inserter->insert(temp);
5328 this->left_ =
5329 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5332 if (right_type->interface_type() == NULL
5333 && right_type->points_to() == NULL
5334 && !this->right_->is_addressable())
5336 Temporary_statement* temp =
5337 Statement::make_temporary(right_type, NULL, loc);
5338 inserter->insert(temp);
5339 this->right_ =
5340 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5343 return this;
5346 // Lower a struct or array comparison to a call to memcmp.
5348 Expression*
5349 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5351 Location loc = this->location();
5353 Expression* a1 = this->operand_address(inserter, this->left_);
5354 Expression* a2 = this->operand_address(inserter, this->right_);
5355 Expression* len = Expression::make_type_info(this->left_->type(),
5356 TYPE_INFO_SIZE);
5358 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5359 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5360 return Expression::make_binary(this->op_, call, zero, loc);
5363 Expression*
5364 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5365 Statement_inserter* inserter)
5367 Location loc = this->location();
5368 if (this->left_->type()->is_error_type()
5369 || this->right_->type()->is_error_type()
5370 || this->left_->is_error_expression()
5371 || this->right_->is_error_expression())
5373 go_assert(saw_errors());
5374 return Expression::make_error(loc);
5377 Temporary_statement* temp;
5379 Type* left_type = this->left_->type();
5380 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5381 || this->op_ == OPERATOR_RSHIFT);
5382 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5383 left_type->integer_type() != NULL)
5384 || this->op_ == OPERATOR_MOD);
5386 if (is_shift_op
5387 || (is_idiv_op
5388 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5390 if (!this->left_->is_variable() && !this->left_->is_constant())
5392 temp = Statement::make_temporary(NULL, this->left_, loc);
5393 inserter->insert(temp);
5394 this->left_ = Expression::make_temporary_reference(temp, loc);
5396 if (!this->right_->is_variable() && !this->right_->is_constant())
5398 temp =
5399 Statement::make_temporary(NULL, this->right_, loc);
5400 this->right_ = Expression::make_temporary_reference(temp, loc);
5401 inserter->insert(temp);
5404 return this;
5408 // Return the address of EXPR, cast to unsafe.Pointer.
5410 Expression*
5411 Binary_expression::operand_address(Statement_inserter* inserter,
5412 Expression* expr)
5414 Location loc = this->location();
5416 if (!expr->is_addressable())
5418 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5419 loc);
5420 inserter->insert(temp);
5421 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5423 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5424 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5425 Type* void_type = Type::make_void_type();
5426 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5427 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5430 // Return the numeric constant value, if it has one.
5432 bool
5433 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5435 Numeric_constant left_nc;
5436 if (!this->left_->numeric_constant_value(&left_nc))
5437 return false;
5438 Numeric_constant right_nc;
5439 if (!this->right_->numeric_constant_value(&right_nc))
5440 return false;
5441 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5442 this->location(), nc);
5445 // Note that the value is being discarded.
5447 bool
5448 Binary_expression::do_discarding_value()
5450 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5451 return this->right_->discarding_value();
5452 else
5454 this->unused_value_error();
5455 return false;
5459 // Get type.
5461 Type*
5462 Binary_expression::do_type()
5464 if (this->classification() == EXPRESSION_ERROR)
5465 return Type::make_error_type();
5467 switch (this->op_)
5469 case OPERATOR_EQEQ:
5470 case OPERATOR_NOTEQ:
5471 case OPERATOR_LT:
5472 case OPERATOR_LE:
5473 case OPERATOR_GT:
5474 case OPERATOR_GE:
5475 if (this->type_ == NULL)
5476 this->type_ = Type::make_boolean_type();
5477 return this->type_;
5479 case OPERATOR_PLUS:
5480 case OPERATOR_MINUS:
5481 case OPERATOR_OR:
5482 case OPERATOR_XOR:
5483 case OPERATOR_MULT:
5484 case OPERATOR_DIV:
5485 case OPERATOR_MOD:
5486 case OPERATOR_AND:
5487 case OPERATOR_BITCLEAR:
5488 case OPERATOR_OROR:
5489 case OPERATOR_ANDAND:
5491 Type* type;
5492 if (!Binary_expression::operation_type(this->op_,
5493 this->left_->type(),
5494 this->right_->type(),
5495 &type))
5496 return Type::make_error_type();
5497 return type;
5500 case OPERATOR_LSHIFT:
5501 case OPERATOR_RSHIFT:
5502 return this->left_->type();
5504 default:
5505 go_unreachable();
5509 // Set type for a binary expression.
5511 void
5512 Binary_expression::do_determine_type(const Type_context* context)
5514 Type* tleft = this->left_->type();
5515 Type* tright = this->right_->type();
5517 // Both sides should have the same type, except for the shift
5518 // operations. For a comparison, we should ignore the incoming
5519 // type.
5521 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5522 || this->op_ == OPERATOR_RSHIFT);
5524 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5525 || this->op_ == OPERATOR_NOTEQ
5526 || this->op_ == OPERATOR_LT
5527 || this->op_ == OPERATOR_LE
5528 || this->op_ == OPERATOR_GT
5529 || this->op_ == OPERATOR_GE);
5531 // For constant expressions, the context of the result is not useful in
5532 // determining the types of the operands. It is only legal to use abstract
5533 // boolean, numeric, and string constants as operands where it is legal to
5534 // use non-abstract boolean, numeric, and string constants, respectively.
5535 // Any issues with the operation will be resolved in the check_types pass.
5536 bool is_constant_expr = (this->left_->is_constant()
5537 && this->right_->is_constant());
5539 Type_context subcontext(*context);
5541 if (is_comparison)
5543 // In a comparison, the context does not determine the types of
5544 // the operands.
5545 subcontext.type = NULL;
5548 // Set the context for the left hand operand.
5549 if (is_shift_op)
5551 // The right hand operand of a shift plays no role in
5552 // determining the type of the left hand operand.
5554 else if (!tleft->is_abstract())
5555 subcontext.type = tleft;
5556 else if (!tright->is_abstract())
5557 subcontext.type = tright;
5558 else if (subcontext.type == NULL)
5560 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5561 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5562 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5564 // Both sides have an abstract integer, abstract float, or
5565 // abstract complex type. Just let CONTEXT determine
5566 // whether they may remain abstract or not.
5568 else if (tleft->complex_type() != NULL)
5569 subcontext.type = tleft;
5570 else if (tright->complex_type() != NULL)
5571 subcontext.type = tright;
5572 else if (tleft->float_type() != NULL)
5573 subcontext.type = tleft;
5574 else if (tright->float_type() != NULL)
5575 subcontext.type = tright;
5576 else
5577 subcontext.type = tleft;
5579 if (subcontext.type != NULL && !context->may_be_abstract)
5580 subcontext.type = subcontext.type->make_non_abstract_type();
5583 if (!is_constant_expr)
5584 this->left_->determine_type(&subcontext);
5586 if (is_shift_op)
5588 // We may have inherited an unusable type for the shift operand.
5589 // Give a useful error if that happened.
5590 if (tleft->is_abstract()
5591 && subcontext.type != NULL
5592 && !subcontext.may_be_abstract
5593 && subcontext.type->interface_type() == NULL
5594 && subcontext.type->integer_type() == NULL)
5595 this->report_error(("invalid context-determined non-integer type "
5596 "for left operand of shift"));
5598 // The context for the right hand operand is the same as for the
5599 // left hand operand, except for a shift operator.
5600 subcontext.type = Type::lookup_integer_type("uint");
5601 subcontext.may_be_abstract = false;
5604 if (!is_constant_expr)
5605 this->right_->determine_type(&subcontext);
5607 if (is_comparison)
5609 if (this->type_ != NULL && !this->type_->is_abstract())
5611 else if (context->type != NULL && context->type->is_boolean_type())
5612 this->type_ = context->type;
5613 else if (!context->may_be_abstract)
5614 this->type_ = Type::lookup_bool_type();
5618 // Report an error if the binary operator OP does not support TYPE.
5619 // OTYPE is the type of the other operand. Return whether the
5620 // operation is OK. This should not be used for shift.
5622 bool
5623 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5624 Location location)
5626 switch (op)
5628 case OPERATOR_OROR:
5629 case OPERATOR_ANDAND:
5630 if (!type->is_boolean_type()
5631 || !otype->is_boolean_type())
5633 go_error_at(location, "expected boolean type");
5634 return false;
5636 break;
5638 case OPERATOR_EQEQ:
5639 case OPERATOR_NOTEQ:
5641 std::string reason;
5642 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5644 go_error_at(location, "%s", reason.c_str());
5645 return false;
5648 break;
5650 case OPERATOR_LT:
5651 case OPERATOR_LE:
5652 case OPERATOR_GT:
5653 case OPERATOR_GE:
5655 std::string reason;
5656 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5658 go_error_at(location, "%s", reason.c_str());
5659 return false;
5662 break;
5664 case OPERATOR_PLUS:
5665 case OPERATOR_PLUSEQ:
5666 if ((!type->is_numeric_type() && !type->is_string_type())
5667 || (!otype->is_numeric_type() && !otype->is_string_type()))
5669 go_error_at(location,
5670 "expected integer, floating, complex, or string type");
5671 return false;
5673 break;
5675 case OPERATOR_MINUS:
5676 case OPERATOR_MINUSEQ:
5677 case OPERATOR_MULT:
5678 case OPERATOR_MULTEQ:
5679 case OPERATOR_DIV:
5680 case OPERATOR_DIVEQ:
5681 if (!type->is_numeric_type() || !otype->is_numeric_type())
5683 go_error_at(location, "expected integer, floating, or complex type");
5684 return false;
5686 break;
5688 case OPERATOR_MOD:
5689 case OPERATOR_MODEQ:
5690 case OPERATOR_OR:
5691 case OPERATOR_OREQ:
5692 case OPERATOR_AND:
5693 case OPERATOR_ANDEQ:
5694 case OPERATOR_XOR:
5695 case OPERATOR_XOREQ:
5696 case OPERATOR_BITCLEAR:
5697 case OPERATOR_BITCLEAREQ:
5698 if (type->integer_type() == NULL || otype->integer_type() == NULL)
5700 go_error_at(location, "expected integer type");
5701 return false;
5703 break;
5705 default:
5706 go_unreachable();
5709 return true;
5712 // Check types.
5714 void
5715 Binary_expression::do_check_types(Gogo*)
5717 if (this->classification() == EXPRESSION_ERROR)
5718 return;
5720 Type* left_type = this->left_->type();
5721 Type* right_type = this->right_->type();
5722 if (left_type->is_error() || right_type->is_error())
5724 this->set_is_error();
5725 return;
5728 if (this->op_ == OPERATOR_EQEQ
5729 || this->op_ == OPERATOR_NOTEQ
5730 || this->op_ == OPERATOR_LT
5731 || this->op_ == OPERATOR_LE
5732 || this->op_ == OPERATOR_GT
5733 || this->op_ == OPERATOR_GE)
5735 if (left_type->is_nil_type() && right_type->is_nil_type())
5737 this->report_error(_("invalid comparison of nil with nil"));
5738 return;
5740 if (!Type::are_assignable(left_type, right_type, NULL)
5741 && !Type::are_assignable(right_type, left_type, NULL))
5743 this->report_error(_("incompatible types in binary expression"));
5744 return;
5746 if (!Binary_expression::check_operator_type(this->op_, left_type,
5747 right_type,
5748 this->location())
5749 || !Binary_expression::check_operator_type(this->op_, right_type,
5750 left_type,
5751 this->location()))
5753 this->set_is_error();
5754 return;
5757 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5759 if (!Type::are_compatible_for_binop(left_type, right_type))
5761 this->report_error(_("incompatible types in binary expression"));
5762 return;
5764 if (!Binary_expression::check_operator_type(this->op_, left_type,
5765 right_type,
5766 this->location()))
5768 this->set_is_error();
5769 return;
5771 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5773 // Division by a zero integer constant is an error.
5774 Numeric_constant rconst;
5775 unsigned long rval;
5776 if (left_type->integer_type() != NULL
5777 && this->right_->numeric_constant_value(&rconst)
5778 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5779 && rval == 0)
5781 this->report_error(_("integer division by zero"));
5782 return;
5786 else
5788 if (left_type->integer_type() == NULL)
5789 this->report_error(_("shift of non-integer operand"));
5791 if (right_type->is_string_type())
5792 this->report_error(_("shift count not unsigned integer"));
5793 else if (!right_type->is_abstract()
5794 && (right_type->integer_type() == NULL
5795 || !right_type->integer_type()->is_unsigned()))
5796 this->report_error(_("shift count not unsigned integer"));
5797 else
5799 Numeric_constant nc;
5800 if (this->right_->numeric_constant_value(&nc))
5802 mpz_t val;
5803 if (!nc.to_int(&val))
5804 this->report_error(_("shift count not unsigned integer"));
5805 else
5807 if (mpz_sgn(val) < 0)
5809 this->report_error(_("negative shift count"));
5810 Location rloc = this->right_->location();
5811 this->right_ = Expression::make_integer_ul(0, right_type,
5812 rloc);
5814 mpz_clear(val);
5821 // Get the backend representation for a binary expression.
5823 Bexpression*
5824 Binary_expression::do_get_backend(Translate_context* context)
5826 Gogo* gogo = context->gogo();
5827 Location loc = this->location();
5828 Type* left_type = this->left_->type();
5829 Type* right_type = this->right_->type();
5831 bool use_left_type = true;
5832 bool is_shift_op = false;
5833 bool is_idiv_op = false;
5834 switch (this->op_)
5836 case OPERATOR_EQEQ:
5837 case OPERATOR_NOTEQ:
5838 case OPERATOR_LT:
5839 case OPERATOR_LE:
5840 case OPERATOR_GT:
5841 case OPERATOR_GE:
5842 return Expression::comparison(context, this->type_, this->op_,
5843 this->left_, this->right_, loc);
5845 case OPERATOR_OROR:
5846 case OPERATOR_ANDAND:
5847 use_left_type = false;
5848 break;
5849 case OPERATOR_PLUS:
5850 case OPERATOR_MINUS:
5851 case OPERATOR_OR:
5852 case OPERATOR_XOR:
5853 case OPERATOR_MULT:
5854 break;
5855 case OPERATOR_DIV:
5856 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5857 break;
5858 // Fall through.
5859 case OPERATOR_MOD:
5860 is_idiv_op = true;
5861 break;
5862 case OPERATOR_LSHIFT:
5863 case OPERATOR_RSHIFT:
5864 is_shift_op = true;
5865 break;
5866 case OPERATOR_BITCLEAR:
5867 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5868 case OPERATOR_AND:
5869 break;
5870 default:
5871 go_unreachable();
5874 // The only binary operation for string is +, and that should have
5875 // been converted to a String_concat_expression in do_lower.
5876 go_assert(!left_type->is_string_type());
5878 // For complex division Go might want slightly different results than the
5879 // backend implementation provides, so we have our own runtime routine.
5880 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5882 Runtime::Function complex_code;
5883 switch (this->left_->type()->complex_type()->bits())
5885 case 64:
5886 complex_code = Runtime::COMPLEX64_DIV;
5887 break;
5888 case 128:
5889 complex_code = Runtime::COMPLEX128_DIV;
5890 break;
5891 default:
5892 go_unreachable();
5894 Expression* complex_div =
5895 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5896 return complex_div->get_backend(context);
5899 Bexpression* left = this->left_->get_backend(context);
5900 Bexpression* right = this->right_->get_backend(context);
5902 Type* type = use_left_type ? left_type : right_type;
5903 Btype* btype = type->get_backend(gogo);
5905 Bexpression* ret =
5906 gogo->backend()->binary_expression(this->op_, left, right, loc);
5907 ret = gogo->backend()->convert_expression(btype, ret, loc);
5909 // Initialize overflow constants.
5910 Bexpression* overflow;
5911 mpz_t zero;
5912 mpz_init_set_ui(zero, 0UL);
5913 mpz_t one;
5914 mpz_init_set_ui(one, 1UL);
5915 mpz_t neg_one;
5916 mpz_init_set_si(neg_one, -1);
5918 Btype* left_btype = left_type->get_backend(gogo);
5919 Btype* right_btype = right_type->get_backend(gogo);
5921 // In Go, a shift larger than the size of the type is well-defined.
5922 // This is not true in C, so we need to insert a conditional.
5923 if (is_shift_op)
5925 go_assert(left_type->integer_type() != NULL);
5927 mpz_t bitsval;
5928 int bits = left_type->integer_type()->bits();
5929 mpz_init_set_ui(bitsval, bits);
5930 Bexpression* bits_expr =
5931 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5932 Bexpression* compare =
5933 gogo->backend()->binary_expression(OPERATOR_LT,
5934 right, bits_expr, loc);
5936 Bexpression* zero_expr =
5937 gogo->backend()->integer_constant_expression(left_btype, zero);
5938 overflow = zero_expr;
5939 if (this->op_ == OPERATOR_RSHIFT
5940 && !left_type->integer_type()->is_unsigned())
5942 Bexpression* neg_expr =
5943 gogo->backend()->binary_expression(OPERATOR_LT, left,
5944 zero_expr, loc);
5945 Bexpression* neg_one_expr =
5946 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5947 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5948 neg_one_expr,
5949 zero_expr, loc);
5951 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5952 overflow, loc);
5953 mpz_clear(bitsval);
5956 // Add checks for division by zero and division overflow as needed.
5957 if (is_idiv_op)
5959 if (gogo->check_divide_by_zero())
5961 // right == 0
5962 Bexpression* zero_expr =
5963 gogo->backend()->integer_constant_expression(right_btype, zero);
5964 Bexpression* check =
5965 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5966 right, zero_expr, loc);
5968 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
5969 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5970 Bexpression* crash = gogo->runtime_error(errcode,
5971 loc)->get_backend(context);
5973 // right == 0 ? (__go_runtime_error(...), 0) : ret
5974 ret = gogo->backend()->conditional_expression(btype, check, crash,
5975 ret, loc);
5978 if (gogo->check_divide_overflow())
5980 // right == -1
5981 // FIXME: It would be nice to say that this test is expected
5982 // to return false.
5984 Bexpression* neg_one_expr =
5985 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5986 Bexpression* check =
5987 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5988 right, neg_one_expr, loc);
5990 Bexpression* zero_expr =
5991 gogo->backend()->integer_constant_expression(btype, zero);
5992 Bexpression* one_expr =
5993 gogo->backend()->integer_constant_expression(btype, one);
5995 if (type->integer_type()->is_unsigned())
5997 // An unsigned -1 is the largest possible number, so
5998 // dividing is always 1 or 0.
6000 Bexpression* cmp =
6001 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6002 left, right, loc);
6003 if (this->op_ == OPERATOR_DIV)
6004 overflow =
6005 gogo->backend()->conditional_expression(btype, cmp,
6006 one_expr, zero_expr,
6007 loc);
6008 else
6009 overflow =
6010 gogo->backend()->conditional_expression(btype, cmp,
6011 zero_expr, left,
6012 loc);
6014 else
6016 // Computing left / -1 is the same as computing - left,
6017 // which does not overflow since Go sets -fwrapv.
6018 if (this->op_ == OPERATOR_DIV)
6020 Expression* negate_expr =
6021 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6022 overflow = negate_expr->get_backend(context);
6024 else
6025 overflow = zero_expr;
6027 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6029 // right == -1 ? - left : ret
6030 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6031 ret, loc);
6035 mpz_clear(zero);
6036 mpz_clear(one);
6037 mpz_clear(neg_one);
6038 return ret;
6041 // Export a binary expression.
6043 void
6044 Binary_expression::do_export(Export* exp) const
6046 exp->write_c_string("(");
6047 this->left_->export_expression(exp);
6048 switch (this->op_)
6050 case OPERATOR_OROR:
6051 exp->write_c_string(" || ");
6052 break;
6053 case OPERATOR_ANDAND:
6054 exp->write_c_string(" && ");
6055 break;
6056 case OPERATOR_EQEQ:
6057 exp->write_c_string(" == ");
6058 break;
6059 case OPERATOR_NOTEQ:
6060 exp->write_c_string(" != ");
6061 break;
6062 case OPERATOR_LT:
6063 exp->write_c_string(" < ");
6064 break;
6065 case OPERATOR_LE:
6066 exp->write_c_string(" <= ");
6067 break;
6068 case OPERATOR_GT:
6069 exp->write_c_string(" > ");
6070 break;
6071 case OPERATOR_GE:
6072 exp->write_c_string(" >= ");
6073 break;
6074 case OPERATOR_PLUS:
6075 exp->write_c_string(" + ");
6076 break;
6077 case OPERATOR_MINUS:
6078 exp->write_c_string(" - ");
6079 break;
6080 case OPERATOR_OR:
6081 exp->write_c_string(" | ");
6082 break;
6083 case OPERATOR_XOR:
6084 exp->write_c_string(" ^ ");
6085 break;
6086 case OPERATOR_MULT:
6087 exp->write_c_string(" * ");
6088 break;
6089 case OPERATOR_DIV:
6090 exp->write_c_string(" / ");
6091 break;
6092 case OPERATOR_MOD:
6093 exp->write_c_string(" % ");
6094 break;
6095 case OPERATOR_LSHIFT:
6096 exp->write_c_string(" << ");
6097 break;
6098 case OPERATOR_RSHIFT:
6099 exp->write_c_string(" >> ");
6100 break;
6101 case OPERATOR_AND:
6102 exp->write_c_string(" & ");
6103 break;
6104 case OPERATOR_BITCLEAR:
6105 exp->write_c_string(" &^ ");
6106 break;
6107 default:
6108 go_unreachable();
6110 this->right_->export_expression(exp);
6111 exp->write_c_string(")");
6114 // Import a binary expression.
6116 Expression*
6117 Binary_expression::do_import(Import* imp)
6119 imp->require_c_string("(");
6121 Expression* left = Expression::import_expression(imp);
6123 Operator op;
6124 if (imp->match_c_string(" || "))
6126 op = OPERATOR_OROR;
6127 imp->advance(4);
6129 else if (imp->match_c_string(" && "))
6131 op = OPERATOR_ANDAND;
6132 imp->advance(4);
6134 else if (imp->match_c_string(" == "))
6136 op = OPERATOR_EQEQ;
6137 imp->advance(4);
6139 else if (imp->match_c_string(" != "))
6141 op = OPERATOR_NOTEQ;
6142 imp->advance(4);
6144 else if (imp->match_c_string(" < "))
6146 op = OPERATOR_LT;
6147 imp->advance(3);
6149 else if (imp->match_c_string(" <= "))
6151 op = OPERATOR_LE;
6152 imp->advance(4);
6154 else if (imp->match_c_string(" > "))
6156 op = OPERATOR_GT;
6157 imp->advance(3);
6159 else if (imp->match_c_string(" >= "))
6161 op = OPERATOR_GE;
6162 imp->advance(4);
6164 else if (imp->match_c_string(" + "))
6166 op = OPERATOR_PLUS;
6167 imp->advance(3);
6169 else if (imp->match_c_string(" - "))
6171 op = OPERATOR_MINUS;
6172 imp->advance(3);
6174 else if (imp->match_c_string(" | "))
6176 op = OPERATOR_OR;
6177 imp->advance(3);
6179 else if (imp->match_c_string(" ^ "))
6181 op = OPERATOR_XOR;
6182 imp->advance(3);
6184 else if (imp->match_c_string(" * "))
6186 op = OPERATOR_MULT;
6187 imp->advance(3);
6189 else if (imp->match_c_string(" / "))
6191 op = OPERATOR_DIV;
6192 imp->advance(3);
6194 else if (imp->match_c_string(" % "))
6196 op = OPERATOR_MOD;
6197 imp->advance(3);
6199 else if (imp->match_c_string(" << "))
6201 op = OPERATOR_LSHIFT;
6202 imp->advance(4);
6204 else if (imp->match_c_string(" >> "))
6206 op = OPERATOR_RSHIFT;
6207 imp->advance(4);
6209 else if (imp->match_c_string(" & "))
6211 op = OPERATOR_AND;
6212 imp->advance(3);
6214 else if (imp->match_c_string(" &^ "))
6216 op = OPERATOR_BITCLEAR;
6217 imp->advance(4);
6219 else
6221 go_error_at(imp->location(), "unrecognized binary operator");
6222 return Expression::make_error(imp->location());
6225 Expression* right = Expression::import_expression(imp);
6227 imp->require_c_string(")");
6229 return Expression::make_binary(op, left, right, imp->location());
6232 // Dump ast representation of a binary expression.
6234 void
6235 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6237 ast_dump_context->ostream() << "(";
6238 ast_dump_context->dump_expression(this->left_);
6239 ast_dump_context->ostream() << " ";
6240 ast_dump_context->dump_operator(this->op_);
6241 ast_dump_context->ostream() << " ";
6242 ast_dump_context->dump_expression(this->right_);
6243 ast_dump_context->ostream() << ") ";
6246 // Make a binary expression.
6248 Expression*
6249 Expression::make_binary(Operator op, Expression* left, Expression* right,
6250 Location location)
6252 return new Binary_expression(op, left, right, location);
6255 // Implement a comparison.
6257 Bexpression*
6258 Expression::comparison(Translate_context* context, Type* result_type,
6259 Operator op, Expression* left, Expression* right,
6260 Location location)
6262 Type* left_type = left->type();
6263 Type* right_type = right->type();
6265 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6267 if (left_type->is_string_type() && right_type->is_string_type())
6269 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6271 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6272 left, right);
6273 right = Expression::make_boolean(true, location);
6275 else
6277 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6278 left, right);
6279 right = zexpr;
6282 else if ((left_type->interface_type() != NULL
6283 && right_type->interface_type() == NULL
6284 && !right_type->is_nil_type())
6285 || (left_type->interface_type() == NULL
6286 && !left_type->is_nil_type()
6287 && right_type->interface_type() != NULL))
6289 // Comparing an interface value to a non-interface value.
6290 if (left_type->interface_type() == NULL)
6292 std::swap(left_type, right_type);
6293 std::swap(left, right);
6296 // The right operand is not an interface. We need to take its
6297 // address if it is not a pointer.
6298 Expression* pointer_arg = NULL;
6299 if (right_type->points_to() != NULL)
6300 pointer_arg = right;
6301 else
6303 go_assert(right->is_addressable());
6304 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6305 location);
6308 Expression* descriptor =
6309 Expression::make_type_descriptor(right_type, location);
6310 left =
6311 Runtime::make_call((left_type->interface_type()->is_empty()
6312 ? Runtime::EFACEVALEQ
6313 : Runtime::IFACEVALEQ),
6314 location, 3, left, descriptor,
6315 pointer_arg);
6316 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6317 right = Expression::make_boolean(true, location);
6319 else if (left_type->interface_type() != NULL
6320 && right_type->interface_type() != NULL)
6322 Runtime::Function compare_function;
6323 if (left_type->interface_type()->is_empty()
6324 && right_type->interface_type()->is_empty())
6325 compare_function = Runtime::EFACEEQ;
6326 else if (!left_type->interface_type()->is_empty()
6327 && !right_type->interface_type()->is_empty())
6328 compare_function = Runtime::IFACEEQ;
6329 else
6331 if (left_type->interface_type()->is_empty())
6333 std::swap(left_type, right_type);
6334 std::swap(left, right);
6336 go_assert(!left_type->interface_type()->is_empty());
6337 go_assert(right_type->interface_type()->is_empty());
6338 compare_function = Runtime::IFACEEFACEEQ;
6341 left = Runtime::make_call(compare_function, location, 2, left, right);
6342 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6343 right = Expression::make_boolean(true, location);
6346 if (left_type->is_nil_type()
6347 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6349 std::swap(left_type, right_type);
6350 std::swap(left, right);
6353 if (right_type->is_nil_type())
6355 right = Expression::make_nil(location);
6356 if (left_type->array_type() != NULL
6357 && left_type->array_type()->length() == NULL)
6359 Array_type* at = left_type->array_type();
6360 left = at->get_value_pointer(context->gogo(), left);
6362 else if (left_type->interface_type() != NULL)
6364 // An interface is nil if the first field is nil.
6365 left = Expression::make_field_reference(left, 0, location);
6369 Bexpression* left_bexpr = left->get_backend(context);
6370 Bexpression* right_bexpr = right->get_backend(context);
6372 Gogo* gogo = context->gogo();
6373 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6374 right_bexpr, location);
6375 if (result_type != NULL)
6376 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6377 ret, location);
6378 return ret;
6381 // Class String_concat_expression.
6383 bool
6384 String_concat_expression::do_is_constant() const
6386 for (Expression_list::const_iterator pe = this->exprs_->begin();
6387 pe != this->exprs_->end();
6388 ++pe)
6390 if (!(*pe)->is_constant())
6391 return false;
6393 return true;
6396 bool
6397 String_concat_expression::do_is_static_initializer() const
6399 for (Expression_list::const_iterator pe = this->exprs_->begin();
6400 pe != this->exprs_->end();
6401 ++pe)
6403 if (!(*pe)->is_static_initializer())
6404 return false;
6406 return true;
6409 Type*
6410 String_concat_expression::do_type()
6412 Type* t = this->exprs_->front()->type();
6413 Expression_list::iterator pe = this->exprs_->begin();
6414 ++pe;
6415 for (; pe != this->exprs_->end(); ++pe)
6417 Type* t1;
6418 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6419 (*pe)->type(),
6420 &t1))
6421 return Type::make_error_type();
6422 t = t1;
6424 return t;
6427 void
6428 String_concat_expression::do_determine_type(const Type_context* context)
6430 Type_context subcontext(*context);
6431 for (Expression_list::iterator pe = this->exprs_->begin();
6432 pe != this->exprs_->end();
6433 ++pe)
6435 Type* t = (*pe)->type();
6436 if (!t->is_abstract())
6438 subcontext.type = t;
6439 break;
6442 if (subcontext.type == NULL)
6443 subcontext.type = this->exprs_->front()->type();
6444 for (Expression_list::iterator pe = this->exprs_->begin();
6445 pe != this->exprs_->end();
6446 ++pe)
6447 (*pe)->determine_type(&subcontext);
6450 void
6451 String_concat_expression::do_check_types(Gogo*)
6453 if (this->is_error_expression())
6454 return;
6455 Type* t = this->exprs_->front()->type();
6456 if (t->is_error())
6458 this->set_is_error();
6459 return;
6461 Expression_list::iterator pe = this->exprs_->begin();
6462 ++pe;
6463 for (; pe != this->exprs_->end(); ++pe)
6465 Type* t1 = (*pe)->type();
6466 if (!Type::are_compatible_for_binop(t, t1))
6468 this->report_error("incompatible types in binary expression");
6469 return;
6471 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6472 this->location()))
6474 this->set_is_error();
6475 return;
6480 Expression*
6481 String_concat_expression::do_flatten(Gogo*, Named_object*,
6482 Statement_inserter*)
6484 if (this->is_error_expression())
6485 return this;
6486 Location loc = this->location();
6487 Type* type = this->type();
6488 Expression* nil_arg = Expression::make_nil(loc);
6489 Expression* call;
6490 switch (this->exprs_->size())
6492 case 0: case 1:
6493 go_unreachable();
6495 case 2: case 3: case 4: case 5:
6497 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6498 NULL, loc);
6499 Array_type* arg_type = Type::make_array_type(type, len);
6500 arg_type->set_is_array_incomparable();
6501 Expression* arg =
6502 Expression::make_array_composite_literal(arg_type, this->exprs_,
6503 loc);
6504 Runtime::Function code;
6505 switch (this->exprs_->size())
6507 default:
6508 go_unreachable();
6509 case 2:
6510 code = Runtime::CONCATSTRING2;
6511 break;
6512 case 3:
6513 code = Runtime::CONCATSTRING3;
6514 break;
6515 case 4:
6516 code = Runtime::CONCATSTRING4;
6517 break;
6518 case 5:
6519 code = Runtime::CONCATSTRING5;
6520 break;
6522 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6524 break;
6526 default:
6528 Type* arg_type = Type::make_array_type(type, NULL);
6529 Slice_construction_expression* sce =
6530 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6531 loc);
6532 sce->set_storage_does_not_escape();
6533 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6534 sce);
6536 break;
6539 return Expression::make_cast(type, call, loc);
6542 void
6543 String_concat_expression::do_dump_expression(
6544 Ast_dump_context* ast_dump_context) const
6546 ast_dump_context->ostream() << "concat(";
6547 ast_dump_context->dump_expression_list(this->exprs_, false);
6548 ast_dump_context->ostream() << ")";
6551 Expression*
6552 Expression::make_string_concat(Expression_list* exprs)
6554 return new String_concat_expression(exprs);
6557 // Class Bound_method_expression.
6559 // Traversal.
6562 Bound_method_expression::do_traverse(Traverse* traverse)
6564 return Expression::traverse(&this->expr_, traverse);
6567 // Return the type of a bound method expression. The type of this
6568 // object is simply the type of the method with no receiver.
6570 Type*
6571 Bound_method_expression::do_type()
6573 Named_object* fn = this->method_->named_object();
6574 Function_type* fntype;
6575 if (fn->is_function())
6576 fntype = fn->func_value()->type();
6577 else if (fn->is_function_declaration())
6578 fntype = fn->func_declaration_value()->type();
6579 else
6580 return Type::make_error_type();
6581 return fntype->copy_without_receiver();
6584 // Determine the types of a method expression.
6586 void
6587 Bound_method_expression::do_determine_type(const Type_context*)
6589 Named_object* fn = this->method_->named_object();
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 fntype = NULL;
6597 if (fntype == NULL || !fntype->is_method())
6598 this->expr_->determine_type_no_context();
6599 else
6601 Type_context subcontext(fntype->receiver()->type(), false);
6602 this->expr_->determine_type(&subcontext);
6606 // Check the types of a method expression.
6608 void
6609 Bound_method_expression::do_check_types(Gogo*)
6611 Named_object* fn = this->method_->named_object();
6612 if (!fn->is_function() && !fn->is_function_declaration())
6614 this->report_error(_("object is not a method"));
6615 return;
6618 Function_type* fntype;
6619 if (fn->is_function())
6620 fntype = fn->func_value()->type();
6621 else if (fn->is_function_declaration())
6622 fntype = fn->func_declaration_value()->type();
6623 else
6624 go_unreachable();
6625 Type* rtype = fntype->receiver()->type()->deref();
6626 Type* etype = (this->expr_type_ != NULL
6627 ? this->expr_type_
6628 : this->expr_->type());
6629 etype = etype->deref();
6630 if (!Type::are_identical(rtype, etype, true, NULL))
6631 this->report_error(_("method type does not match object type"));
6634 // If a bound method expression is not simply called, then it is
6635 // represented as a closure. The closure will hold a single variable,
6636 // the receiver to pass to the method. The function will be a simple
6637 // thunk that pulls that value from the closure and calls the method
6638 // with the remaining arguments.
6640 // Because method values are not common, we don't build all thunks for
6641 // every methods, but instead only build them as we need them. In
6642 // particular, we even build them on demand for methods defined in
6643 // other packages.
6645 Bound_method_expression::Method_value_thunks
6646 Bound_method_expression::method_value_thunks;
6648 // Find or create the thunk for METHOD.
6650 Named_object*
6651 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6652 Named_object* fn)
6654 std::pair<Named_object*, Named_object*> val(fn, NULL);
6655 std::pair<Method_value_thunks::iterator, bool> ins =
6656 Bound_method_expression::method_value_thunks.insert(val);
6657 if (!ins.second)
6659 // We have seen this method before.
6660 go_assert(ins.first->second != NULL);
6661 return ins.first->second;
6664 Location loc = fn->location();
6666 Function_type* orig_fntype;
6667 if (fn->is_function())
6668 orig_fntype = fn->func_value()->type();
6669 else if (fn->is_function_declaration())
6670 orig_fntype = fn->func_declaration_value()->type();
6671 else
6672 orig_fntype = NULL;
6674 if (orig_fntype == NULL || !orig_fntype->is_method())
6676 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6677 return ins.first->second;
6680 Struct_field_list* sfl = new Struct_field_list();
6681 // The type here is wrong--it should be the C function type. But it
6682 // doesn't really matter.
6683 Type* vt = Type::make_pointer_type(Type::make_void_type());
6684 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6685 sfl->push_back(Struct_field(Typed_identifier("val.1",
6686 orig_fntype->receiver()->type(),
6687 loc)));
6688 Type* closure_type = Type::make_struct_type(sfl, loc);
6689 closure_type = Type::make_pointer_type(closure_type);
6691 Function_type* new_fntype = orig_fntype->copy_with_names();
6693 std::string thunk_name = Gogo::thunk_name();
6694 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6695 false, loc);
6697 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6698 cvar->set_is_used();
6699 cvar->set_is_closure();
6700 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6701 NULL, cvar);
6702 new_no->func_value()->set_closure_var(cp);
6704 gogo->start_block(loc);
6706 // Field 0 of the closure is the function code pointer, field 1 is
6707 // the value on which to invoke the method.
6708 Expression* arg = Expression::make_var_reference(cp, loc);
6709 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6710 arg = Expression::make_field_reference(arg, 1, loc);
6712 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6714 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6715 Expression_list* args;
6716 if (orig_params == NULL || orig_params->empty())
6717 args = NULL;
6718 else
6720 const Typed_identifier_list* new_params = new_fntype->parameters();
6721 args = new Expression_list();
6722 for (Typed_identifier_list::const_iterator p = new_params->begin();
6723 p != new_params->end();
6724 ++p)
6726 Named_object* p_no = gogo->lookup(p->name(), NULL);
6727 go_assert(p_no != NULL
6728 && p_no->is_variable()
6729 && p_no->var_value()->is_parameter());
6730 args->push_back(Expression::make_var_reference(p_no, loc));
6734 Call_expression* call = Expression::make_call(bme, args,
6735 orig_fntype->is_varargs(),
6736 loc);
6737 call->set_varargs_are_lowered();
6739 Statement* s = Statement::make_return_from_call(call, loc);
6740 gogo->add_statement(s);
6741 Block* b = gogo->finish_block(loc);
6742 gogo->add_block(b, loc);
6743 gogo->lower_block(new_no, b);
6744 gogo->flatten_block(new_no, b);
6745 gogo->finish_function(loc);
6747 ins.first->second = new_no;
6748 return new_no;
6751 // Return an expression to check *REF for nil while dereferencing
6752 // according to FIELD_INDEXES. Update *REF to build up the field
6753 // reference. This is a static function so that we don't have to
6754 // worry about declaring Field_indexes in expressions.h.
6756 static Expression*
6757 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6758 Expression** ref)
6760 if (field_indexes == NULL)
6761 return Expression::make_boolean(false, loc);
6762 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6763 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6764 go_assert(stype != NULL
6765 && field_indexes->field_index < stype->field_count());
6766 if ((*ref)->type()->struct_type() == NULL)
6768 go_assert((*ref)->type()->points_to() != NULL);
6769 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6770 Expression::make_nil(loc),
6771 loc);
6772 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6773 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6774 go_assert((*ref)->type()->struct_type() == stype);
6776 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6777 loc);
6778 return cond;
6781 // Flatten a method value into a struct with nil checks. We can't do
6782 // this in the lowering phase, because if the method value is called
6783 // directly we don't need a thunk. That case will have been handled
6784 // by Call_expression::do_lower, so if we get here then we do need a
6785 // thunk.
6787 Expression*
6788 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
6789 Statement_inserter* inserter)
6791 Location loc = this->location();
6793 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
6794 this->method_,
6795 this->function_);
6796 if (thunk->is_erroneous())
6798 go_assert(saw_errors());
6799 return Expression::make_error(loc);
6802 // Force the expression into a variable. This is only necessary if
6803 // we are going to do nil checks below, but it's easy enough to
6804 // always do it.
6805 Expression* expr = this->expr_;
6806 if (!expr->is_variable())
6808 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
6809 inserter->insert(etemp);
6810 expr = Expression::make_temporary_reference(etemp, loc);
6813 // If the method expects a value, and we have a pointer, we need to
6814 // dereference the pointer.
6816 Named_object* fn = this->method_->named_object();
6817 Function_type *fntype;
6818 if (fn->is_function())
6819 fntype = fn->func_value()->type();
6820 else if (fn->is_function_declaration())
6821 fntype = fn->func_declaration_value()->type();
6822 else
6823 go_unreachable();
6825 Expression* val = expr;
6826 if (fntype->receiver()->type()->points_to() == NULL
6827 && val->type()->points_to() != NULL)
6828 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6830 // Note that we are ignoring this->expr_type_ here. The thunk will
6831 // expect a closure whose second field has type this->expr_type_ (if
6832 // that is not NULL). We are going to pass it a closure whose
6833 // second field has type this->expr_->type(). Since
6834 // this->expr_type_ is only not-NULL for pointer types, we can get
6835 // away with this.
6837 Struct_field_list* fields = new Struct_field_list();
6838 fields->push_back(Struct_field(Typed_identifier("fn.0",
6839 thunk->func_value()->type(),
6840 loc)));
6841 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6842 Struct_type* st = Type::make_struct_type(fields, loc);
6844 Expression_list* vals = new Expression_list();
6845 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6846 vals->push_back(val);
6848 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6850 if (!gogo->compiling_runtime() || gogo->package_name() != "runtime")
6851 ret = Expression::make_heap_expression(ret, loc);
6852 else
6854 // When compiling the runtime, method closures do not escape.
6855 // When escape analysis becomes the default, and applies to
6856 // method closures, this should be changed to make it an error
6857 // if a method closure escapes.
6858 Temporary_statement* ctemp = Statement::make_temporary(st, ret, loc);
6859 inserter->insert(ctemp);
6860 ret = Expression::make_temporary_reference(ctemp, loc);
6861 ret = Expression::make_unary(OPERATOR_AND, ret, loc);
6862 ret->unary_expression()->set_does_not_escape();
6865 // If necessary, check whether the expression or any embedded
6866 // pointers are nil.
6868 Expression* nil_check = NULL;
6869 if (this->method_->field_indexes() != NULL)
6871 Expression* ref = expr;
6872 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6873 expr = ref;
6876 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6878 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6879 Expression::make_nil(loc),
6880 loc);
6881 if (nil_check == NULL)
6882 nil_check = n;
6883 else
6884 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6887 if (nil_check != NULL)
6889 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6890 loc);
6891 // Fix the type of the conditional expression by pretending to
6892 // evaluate to RET either way through the conditional.
6893 crash = Expression::make_compound(crash, ret, loc);
6894 ret = Expression::make_conditional(nil_check, crash, ret, loc);
6897 // RET is a pointer to a struct, but we want a function type.
6898 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
6900 return ret;
6903 // Dump ast representation of a bound method expression.
6905 void
6906 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6907 const
6909 if (this->expr_type_ != NULL)
6910 ast_dump_context->ostream() << "(";
6911 ast_dump_context->dump_expression(this->expr_);
6912 if (this->expr_type_ != NULL)
6914 ast_dump_context->ostream() << ":";
6915 ast_dump_context->dump_type(this->expr_type_);
6916 ast_dump_context->ostream() << ")";
6919 ast_dump_context->ostream() << "." << this->function_->name();
6922 // Make a method expression.
6924 Bound_method_expression*
6925 Expression::make_bound_method(Expression* expr, const Method* method,
6926 Named_object* function, Location location)
6928 return new Bound_method_expression(expr, method, function, location);
6931 // Class Builtin_call_expression. This is used for a call to a
6932 // builtin function.
6934 class Builtin_call_expression : public Call_expression
6936 public:
6937 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6938 bool is_varargs, Location location);
6940 protected:
6941 // This overrides Call_expression::do_lower.
6942 Expression*
6943 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6945 Expression*
6946 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6948 bool
6949 do_is_constant() const;
6951 bool
6952 do_numeric_constant_value(Numeric_constant*) const;
6954 bool
6955 do_discarding_value();
6957 Type*
6958 do_type();
6960 void
6961 do_determine_type(const Type_context*);
6963 void
6964 do_check_types(Gogo*);
6966 Expression*
6967 do_copy();
6969 Bexpression*
6970 do_get_backend(Translate_context*);
6972 void
6973 do_export(Export*) const;
6975 virtual bool
6976 do_is_recover_call() const;
6978 virtual void
6979 do_set_recover_arg(Expression*);
6981 private:
6982 // The builtin functions.
6983 enum Builtin_function_code
6985 BUILTIN_INVALID,
6987 // Predeclared builtin functions.
6988 BUILTIN_APPEND,
6989 BUILTIN_CAP,
6990 BUILTIN_CLOSE,
6991 BUILTIN_COMPLEX,
6992 BUILTIN_COPY,
6993 BUILTIN_DELETE,
6994 BUILTIN_IMAG,
6995 BUILTIN_LEN,
6996 BUILTIN_MAKE,
6997 BUILTIN_NEW,
6998 BUILTIN_PANIC,
6999 BUILTIN_PRINT,
7000 BUILTIN_PRINTLN,
7001 BUILTIN_REAL,
7002 BUILTIN_RECOVER,
7004 // Builtin functions from the unsafe package.
7005 BUILTIN_ALIGNOF,
7006 BUILTIN_OFFSETOF,
7007 BUILTIN_SIZEOF
7010 Expression*
7011 one_arg() const;
7013 bool
7014 check_one_arg();
7016 static Type*
7017 real_imag_type(Type*);
7019 static Type*
7020 complex_type(Type*);
7022 Expression*
7023 lower_make(Statement_inserter*);
7025 Expression* flatten_append(Gogo*, Named_object*, Statement_inserter*);
7027 bool
7028 check_int_value(Expression*, bool is_length);
7030 // A pointer back to the general IR structure. This avoids a global
7031 // variable, or passing it around everywhere.
7032 Gogo* gogo_;
7033 // The builtin function being called.
7034 Builtin_function_code code_;
7035 // Used to stop endless loops when the length of an array uses len
7036 // or cap of the array itself.
7037 mutable bool seen_;
7038 // Whether the argument is set for calls to BUILTIN_RECOVER.
7039 bool recover_arg_is_set_;
7042 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7043 Expression* fn,
7044 Expression_list* args,
7045 bool is_varargs,
7046 Location location)
7047 : Call_expression(fn, args, is_varargs, location),
7048 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7049 recover_arg_is_set_(false)
7051 Func_expression* fnexp = this->fn()->func_expression();
7052 if (fnexp == NULL)
7054 this->code_ = BUILTIN_INVALID;
7055 return;
7057 const std::string& name(fnexp->named_object()->name());
7058 if (name == "append")
7059 this->code_ = BUILTIN_APPEND;
7060 else if (name == "cap")
7061 this->code_ = BUILTIN_CAP;
7062 else if (name == "close")
7063 this->code_ = BUILTIN_CLOSE;
7064 else if (name == "complex")
7065 this->code_ = BUILTIN_COMPLEX;
7066 else if (name == "copy")
7067 this->code_ = BUILTIN_COPY;
7068 else if (name == "delete")
7069 this->code_ = BUILTIN_DELETE;
7070 else if (name == "imag")
7071 this->code_ = BUILTIN_IMAG;
7072 else if (name == "len")
7073 this->code_ = BUILTIN_LEN;
7074 else if (name == "make")
7075 this->code_ = BUILTIN_MAKE;
7076 else if (name == "new")
7077 this->code_ = BUILTIN_NEW;
7078 else if (name == "panic")
7079 this->code_ = BUILTIN_PANIC;
7080 else if (name == "print")
7081 this->code_ = BUILTIN_PRINT;
7082 else if (name == "println")
7083 this->code_ = BUILTIN_PRINTLN;
7084 else if (name == "real")
7085 this->code_ = BUILTIN_REAL;
7086 else if (name == "recover")
7087 this->code_ = BUILTIN_RECOVER;
7088 else if (name == "Alignof")
7089 this->code_ = BUILTIN_ALIGNOF;
7090 else if (name == "Offsetof")
7091 this->code_ = BUILTIN_OFFSETOF;
7092 else if (name == "Sizeof")
7093 this->code_ = BUILTIN_SIZEOF;
7094 else
7095 go_unreachable();
7098 // Return whether this is a call to recover. This is a virtual
7099 // function called from the parent class.
7101 bool
7102 Builtin_call_expression::do_is_recover_call() const
7104 if (this->classification() == EXPRESSION_ERROR)
7105 return false;
7106 return this->code_ == BUILTIN_RECOVER;
7109 // Set the argument for a call to recover.
7111 void
7112 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7114 const Expression_list* args = this->args();
7115 go_assert(args == NULL || args->empty());
7116 Expression_list* new_args = new Expression_list();
7117 new_args->push_back(arg);
7118 this->set_args(new_args);
7119 this->recover_arg_is_set_ = true;
7122 // Lower a builtin call expression. This turns new and make into
7123 // specific expressions. We also convert to a constant if we can.
7125 Expression*
7126 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7127 Statement_inserter* inserter, int)
7129 if (this->is_error_expression())
7130 return this;
7132 Location loc = this->location();
7134 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7136 this->report_error(_("invalid use of %<...%> with builtin function"));
7137 return Expression::make_error(loc);
7140 if (this->code_ == BUILTIN_OFFSETOF)
7142 Expression* arg = this->one_arg();
7144 if (arg->bound_method_expression() != NULL
7145 || arg->interface_field_reference_expression() != NULL)
7147 this->report_error(_("invalid use of method value as argument "
7148 "of Offsetof"));
7149 return this;
7152 Field_reference_expression* farg = arg->field_reference_expression();
7153 while (farg != NULL)
7155 if (!farg->implicit())
7156 break;
7157 // When the selector refers to an embedded field,
7158 // it must not be reached through pointer indirections.
7159 if (farg->expr()->deref() != farg->expr())
7161 this->report_error(_("argument of Offsetof implies "
7162 "indirection of an embedded field"));
7163 return this;
7165 // Go up until we reach the original base.
7166 farg = farg->expr()->field_reference_expression();
7170 if (this->is_constant())
7172 Numeric_constant nc;
7173 if (this->numeric_constant_value(&nc))
7174 return nc.expression(loc);
7177 switch (this->code_)
7179 default:
7180 break;
7182 case BUILTIN_NEW:
7184 const Expression_list* args = this->args();
7185 if (args == NULL || args->size() < 1)
7186 this->report_error(_("not enough arguments"));
7187 else if (args->size() > 1)
7188 this->report_error(_("too many arguments"));
7189 else
7191 Expression* arg = args->front();
7192 if (!arg->is_type_expression())
7194 go_error_at(arg->location(), "expected type");
7195 this->set_is_error();
7197 else
7198 return Expression::make_allocation(arg->type(), loc);
7201 break;
7203 case BUILTIN_MAKE:
7204 return this->lower_make(inserter);
7206 case BUILTIN_RECOVER:
7207 if (function != NULL)
7208 function->func_value()->set_calls_recover();
7209 else
7211 // Calling recover outside of a function always returns the
7212 // nil empty interface.
7213 Type* eface = Type::make_empty_interface_type(loc);
7214 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7216 break;
7218 case BUILTIN_DELETE:
7220 // Lower to a runtime function call.
7221 const Expression_list* args = this->args();
7222 if (args == NULL || args->size() < 2)
7223 this->report_error(_("not enough arguments"));
7224 else if (args->size() > 2)
7225 this->report_error(_("too many arguments"));
7226 else if (args->front()->type()->map_type() == NULL)
7227 this->report_error(_("argument 1 must be a map"));
7228 else
7230 // Since this function returns no value it must appear in
7231 // a statement by itself, so we don't have to worry about
7232 // order of evaluation of values around it. Evaluate the
7233 // map first to get order of evaluation right.
7234 Map_type* mt = args->front()->type()->map_type();
7235 Temporary_statement* map_temp =
7236 Statement::make_temporary(mt, args->front(), loc);
7237 inserter->insert(map_temp);
7239 Temporary_statement* key_temp =
7240 Statement::make_temporary(mt->key_type(), args->back(), loc);
7241 inserter->insert(key_temp);
7243 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7244 Expression* e2 = Expression::make_temporary_reference(map_temp,
7245 loc);
7246 Expression* e3 = Expression::make_temporary_reference(key_temp,
7247 loc);
7248 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7249 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7250 3, e1, e2, e3);
7253 break;
7255 case BUILTIN_PRINT:
7256 case BUILTIN_PRINTLN:
7257 // Force all the arguments into temporary variables, so that we
7258 // don't try to evaluate something while holding the print lock.
7259 if (this->args() == NULL)
7260 break;
7261 for (Expression_list::iterator pa = this->args()->begin();
7262 pa != this->args()->end();
7263 ++pa)
7265 if (!(*pa)->is_variable() && !(*pa)->is_constant())
7267 Temporary_statement* temp =
7268 Statement::make_temporary(NULL, *pa, loc);
7269 inserter->insert(temp);
7270 *pa = Expression::make_temporary_reference(temp, loc);
7273 break;
7276 return this;
7279 // Flatten a builtin call expression. This turns the arguments of copy and
7280 // append into temporary expressions.
7282 Expression*
7283 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7284 Statement_inserter* inserter)
7286 Location loc = this->location();
7288 switch (this->code_)
7290 default:
7291 break;
7293 case BUILTIN_APPEND:
7294 return this->flatten_append(gogo, function, inserter);
7296 case BUILTIN_COPY:
7298 Type* at = this->args()->front()->type();
7299 for (Expression_list::iterator pa = this->args()->begin();
7300 pa != this->args()->end();
7301 ++pa)
7303 if ((*pa)->is_nil_expression())
7305 Expression* nil = Expression::make_nil(loc);
7306 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7307 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7309 if (!(*pa)->is_variable())
7311 Temporary_statement* temp =
7312 Statement::make_temporary(NULL, *pa, loc);
7313 inserter->insert(temp);
7314 *pa = Expression::make_temporary_reference(temp, loc);
7318 break;
7320 case BUILTIN_PANIC:
7321 for (Expression_list::iterator pa = this->args()->begin();
7322 pa != this->args()->end();
7323 ++pa)
7325 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7327 Temporary_statement* temp =
7328 Statement::make_temporary(NULL, *pa, loc);
7329 inserter->insert(temp);
7330 *pa = Expression::make_temporary_reference(temp, loc);
7333 break;
7335 case BUILTIN_LEN:
7336 case BUILTIN_CAP:
7338 Expression_list::iterator pa = this->args()->begin();
7339 if (!(*pa)->is_variable()
7340 && ((*pa)->type()->map_type() != NULL
7341 || (*pa)->type()->channel_type() != NULL))
7343 Temporary_statement* temp =
7344 Statement::make_temporary(NULL, *pa, loc);
7345 inserter->insert(temp);
7346 *pa = Expression::make_temporary_reference(temp, loc);
7349 break;
7352 return this;
7355 // Lower a make expression.
7357 Expression*
7358 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7360 Location loc = this->location();
7362 const Expression_list* args = this->args();
7363 if (args == NULL || args->size() < 1)
7365 this->report_error(_("not enough arguments"));
7366 return Expression::make_error(this->location());
7369 Expression_list::const_iterator parg = args->begin();
7371 Expression* first_arg = *parg;
7372 if (!first_arg->is_type_expression())
7374 go_error_at(first_arg->location(), "expected type");
7375 this->set_is_error();
7376 return Expression::make_error(this->location());
7378 Type* type = first_arg->type();
7380 bool is_slice = false;
7381 bool is_map = false;
7382 bool is_chan = false;
7383 if (type->is_slice_type())
7384 is_slice = true;
7385 else if (type->map_type() != NULL)
7386 is_map = true;
7387 else if (type->channel_type() != NULL)
7388 is_chan = true;
7389 else
7391 this->report_error(_("invalid type for make function"));
7392 return Expression::make_error(this->location());
7395 Type_context int_context(Type::lookup_integer_type("int"), false);
7397 ++parg;
7398 Expression* len_arg;
7399 if (parg == args->end())
7401 if (is_slice)
7403 this->report_error(_("length required when allocating a slice"));
7404 return Expression::make_error(this->location());
7406 len_arg = Expression::make_integer_ul(0, NULL, loc);
7408 else
7410 len_arg = *parg;
7411 len_arg->determine_type(&int_context);
7412 if (!this->check_int_value(len_arg, true))
7413 return Expression::make_error(this->location());
7414 ++parg;
7417 Expression* cap_arg = NULL;
7418 if (is_slice && parg != args->end())
7420 cap_arg = *parg;
7421 cap_arg->determine_type(&int_context);
7422 if (!this->check_int_value(cap_arg, false))
7423 return Expression::make_error(this->location());
7425 Numeric_constant nclen;
7426 Numeric_constant nccap;
7427 unsigned long vlen;
7428 unsigned long vcap;
7429 if (len_arg->numeric_constant_value(&nclen)
7430 && cap_arg->numeric_constant_value(&nccap)
7431 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7432 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7433 && vlen > vcap)
7435 this->report_error(_("len larger than cap"));
7436 return Expression::make_error(this->location());
7439 ++parg;
7442 if (parg != args->end())
7444 this->report_error(_("too many arguments to make"));
7445 return Expression::make_error(this->location());
7448 Location type_loc = first_arg->location();
7450 Expression* call;
7451 if (is_slice)
7453 Type* et = type->array_type()->element_type();
7454 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7455 if (cap_arg == NULL)
7457 Temporary_statement* temp = Statement::make_temporary(NULL,
7458 len_arg,
7459 loc);
7460 inserter->insert(temp);
7461 len_arg = Expression::make_temporary_reference(temp, loc);
7462 cap_arg = Expression::make_temporary_reference(temp, loc);
7464 call = Runtime::make_call(Runtime::MAKESLICE, loc, 3, type_arg,
7465 len_arg, cap_arg);
7467 else if (is_map)
7469 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7470 call = Runtime::make_call(Runtime::MAKEMAP, loc, 4, type_arg, len_arg,
7471 Expression::make_nil(loc),
7472 Expression::make_nil(loc));
7474 else if (is_chan)
7476 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7477 call = Runtime::make_call(Runtime::MAKECHAN, loc, 2, type_arg, len_arg);
7479 else
7480 go_unreachable();
7482 return Expression::make_unsafe_cast(type, call, loc);
7485 // Flatten a call to the predeclared append function. We do this in
7486 // the flatten phase, not the lowering phase, so that we run after
7487 // type checking and after order_evaluations.
7489 Expression*
7490 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7491 Statement_inserter* inserter)
7493 if (this->is_error_expression())
7494 return this;
7496 Location loc = this->location();
7498 const Expression_list* args = this->args();
7499 go_assert(args != NULL && !args->empty());
7501 Type* slice_type = args->front()->type();
7502 go_assert(slice_type->is_slice_type());
7503 Type* element_type = slice_type->array_type()->element_type();
7505 if (args->size() == 1)
7507 // append(s) evaluates to s.
7508 return args->front();
7511 Type* int_type = Type::lookup_integer_type("int");
7512 Type* uint_type = Type::lookup_integer_type("uint");
7514 // Implementing
7515 // append(s1, s2...)
7516 // or
7517 // append(s1, a1, a2, a3, ...)
7519 // s1tmp := s1
7520 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7521 loc);
7522 inserter->insert(s1tmp);
7524 // l1tmp := len(s1tmp)
7525 Named_object* lenfn = gogo->lookup_global("len");
7526 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7527 Expression_list* call_args = new Expression_list();
7528 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7529 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7530 gogo->lower_expression(function, inserter, &len);
7531 gogo->flatten_expression(function, inserter, &len);
7532 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7533 inserter->insert(l1tmp);
7535 Temporary_statement* s2tmp = NULL;
7536 Temporary_statement* l2tmp = NULL;
7537 Expression_list* add = NULL;
7538 Expression* len2;
7539 if (this->is_varargs())
7541 go_assert(args->size() == 2);
7543 // s2tmp := s2
7544 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7545 inserter->insert(s2tmp);
7547 // l2tmp := len(s2tmp)
7548 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7549 call_args = new Expression_list();
7550 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7551 len = Expression::make_call(lenref, call_args, false, loc);
7552 gogo->lower_expression(function, inserter, &len);
7553 gogo->flatten_expression(function, inserter, &len);
7554 l2tmp = Statement::make_temporary(int_type, len, loc);
7555 inserter->insert(l2tmp);
7557 // len2 = l2tmp
7558 len2 = Expression::make_temporary_reference(l2tmp, loc);
7560 else
7562 // We have to ensure that all the arguments are in variables
7563 // now, because otherwise if one of them is an index expression
7564 // into the current slice we could overwrite it before we fetch
7565 // it.
7566 add = new Expression_list();
7567 Expression_list::const_iterator pa = args->begin();
7568 for (++pa; pa != args->end(); ++pa)
7570 if ((*pa)->is_variable())
7571 add->push_back(*pa);
7572 else
7574 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7575 loc);
7576 inserter->insert(tmp);
7577 add->push_back(Expression::make_temporary_reference(tmp, loc));
7581 // len2 = len(add)
7582 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
7585 // ntmp := l1tmp + len2
7586 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
7587 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
7588 gogo->lower_expression(function, inserter, &sum);
7589 gogo->flatten_expression(function, inserter, &sum);
7590 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
7591 inserter->insert(ntmp);
7593 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
7594 // growslice(type, s1tmp, ntmp) :
7595 // s1tmp[:ntmp]
7596 // Using uint here means that if the computation of ntmp overflowed,
7597 // we will call growslice which will panic.
7599 Expression* left = Expression::make_temporary_reference(ntmp, loc);
7600 left = Expression::make_cast(uint_type, left, loc);
7602 Named_object* capfn = gogo->lookup_global("cap");
7603 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
7604 call_args = new Expression_list();
7605 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7606 Expression* right = Expression::make_call(capref, call_args, false, loc);
7607 right = Expression::make_cast(uint_type, right, loc);
7609 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
7611 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
7612 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
7613 Expression* a3 = Expression::make_temporary_reference(ntmp, loc);
7614 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 3,
7615 a1, a2, a3);
7616 call = Expression::make_unsafe_cast(slice_type, call, loc);
7618 ref = Expression::make_temporary_reference(s1tmp, loc);
7619 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
7620 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
7621 // FIXME: Mark this index as not requiring bounds checks.
7622 ref = Expression::make_index(ref, zero, ref2, NULL, loc);
7624 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
7626 gogo->lower_expression(function, inserter, &rhs);
7627 gogo->flatten_expression(function, inserter, &rhs);
7629 Expression* lhs = Expression::make_temporary_reference(s1tmp, loc);
7630 Statement* assign = Statement::make_assignment(lhs, rhs, loc);
7631 inserter->insert(assign);
7633 if (this->is_varargs())
7635 // copy(s1tmp[l1tmp:], s2tmp)
7636 a1 = Expression::make_temporary_reference(s1tmp, loc);
7637 ref = Expression::make_temporary_reference(l1tmp, loc);
7638 Expression* nil = Expression::make_nil(loc);
7639 // FIXME: Mark this index as not requiring bounds checks.
7640 a1 = Expression::make_index(a1, ref, nil, NULL, loc);
7642 a2 = Expression::make_temporary_reference(s2tmp, loc);
7644 Named_object* copyfn = gogo->lookup_global("copy");
7645 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
7646 call_args = new Expression_list();
7647 call_args->push_back(a1);
7648 call_args->push_back(a2);
7649 call = Expression::make_call(copyref, call_args, false, loc);
7650 gogo->lower_expression(function, inserter, &call);
7651 gogo->flatten_expression(function, inserter, &call);
7652 inserter->insert(Statement::make_statement(call, false));
7654 else
7656 // For each argument:
7657 // s1tmp[l1tmp+i] = a
7658 unsigned long i = 0;
7659 for (Expression_list::const_iterator pa = add->begin();
7660 pa != add->end();
7661 ++pa, ++i)
7663 ref = Expression::make_temporary_reference(s1tmp, loc);
7664 ref2 = Expression::make_temporary_reference(l1tmp, loc);
7665 Expression* off = Expression::make_integer_ul(i, int_type, loc);
7666 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
7667 // FIXME: Mark this index as not requiring bounds checks.
7668 lhs = Expression::make_index(ref, ref2, NULL, NULL, loc);
7669 gogo->lower_expression(function, inserter, &lhs);
7670 gogo->flatten_expression(function, inserter, &lhs);
7671 assign = Statement::make_assignment(lhs, *pa, loc);
7672 inserter->insert(assign);
7676 return Expression::make_temporary_reference(s1tmp, loc);
7679 // Return whether an expression has an integer value. Report an error
7680 // if not. This is used when handling calls to the predeclared make
7681 // function.
7683 bool
7684 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7686 Numeric_constant nc;
7687 if (e->numeric_constant_value(&nc))
7689 unsigned long v;
7690 switch (nc.to_unsigned_long(&v))
7692 case Numeric_constant::NC_UL_VALID:
7693 break;
7694 case Numeric_constant::NC_UL_NOTINT:
7695 go_error_at(e->location(), "non-integer %s argument to make",
7696 is_length ? "len" : "cap");
7697 return false;
7698 case Numeric_constant::NC_UL_NEGATIVE:
7699 go_error_at(e->location(), "negative %s argument to make",
7700 is_length ? "len" : "cap");
7701 return false;
7702 case Numeric_constant::NC_UL_BIG:
7703 // We don't want to give a compile-time error for a 64-bit
7704 // value on a 32-bit target.
7705 break;
7708 mpz_t val;
7709 if (!nc.to_int(&val))
7710 go_unreachable();
7711 int bits = mpz_sizeinbase(val, 2);
7712 mpz_clear(val);
7713 Type* int_type = Type::lookup_integer_type("int");
7714 if (bits >= int_type->integer_type()->bits())
7716 go_error_at(e->location(), "%s argument too large for make",
7717 is_length ? "len" : "cap");
7718 return false;
7721 return true;
7724 if (e->type()->integer_type() != NULL)
7725 return true;
7727 go_error_at(e->location(), "non-integer %s argument to make",
7728 is_length ? "len" : "cap");
7729 return false;
7732 // Return the type of the real or imag functions, given the type of
7733 // the argument. We need to map complex64 to float32 and complex128
7734 // to float64, so it has to be done by name. This returns NULL if it
7735 // can't figure out the type.
7737 Type*
7738 Builtin_call_expression::real_imag_type(Type* arg_type)
7740 if (arg_type == NULL || arg_type->is_abstract())
7741 return NULL;
7742 Named_type* nt = arg_type->named_type();
7743 if (nt == NULL)
7744 return NULL;
7745 while (nt->real_type()->named_type() != NULL)
7746 nt = nt->real_type()->named_type();
7747 if (nt->name() == "complex64")
7748 return Type::lookup_float_type("float32");
7749 else if (nt->name() == "complex128")
7750 return Type::lookup_float_type("float64");
7751 else
7752 return NULL;
7755 // Return the type of the complex function, given the type of one of the
7756 // argments. Like real_imag_type, we have to map by name.
7758 Type*
7759 Builtin_call_expression::complex_type(Type* arg_type)
7761 if (arg_type == NULL || arg_type->is_abstract())
7762 return NULL;
7763 Named_type* nt = arg_type->named_type();
7764 if (nt == NULL)
7765 return NULL;
7766 while (nt->real_type()->named_type() != NULL)
7767 nt = nt->real_type()->named_type();
7768 if (nt->name() == "float32")
7769 return Type::lookup_complex_type("complex64");
7770 else if (nt->name() == "float64")
7771 return Type::lookup_complex_type("complex128");
7772 else
7773 return NULL;
7776 // Return a single argument, or NULL if there isn't one.
7778 Expression*
7779 Builtin_call_expression::one_arg() const
7781 const Expression_list* args = this->args();
7782 if (args == NULL || args->size() != 1)
7783 return NULL;
7784 return args->front();
7787 // A traversal class which looks for a call or receive expression.
7789 class Find_call_expression : public Traverse
7791 public:
7792 Find_call_expression()
7793 : Traverse(traverse_expressions),
7794 found_(false)
7798 expression(Expression**);
7800 bool
7801 found()
7802 { return this->found_; }
7804 private:
7805 bool found_;
7809 Find_call_expression::expression(Expression** pexpr)
7811 if ((*pexpr)->call_expression() != NULL
7812 || (*pexpr)->receive_expression() != NULL)
7814 this->found_ = true;
7815 return TRAVERSE_EXIT;
7817 return TRAVERSE_CONTINUE;
7820 // Return whether this is constant: len of a string constant, or len
7821 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7822 // unsafe.Alignof.
7824 bool
7825 Builtin_call_expression::do_is_constant() const
7827 if (this->is_error_expression())
7828 return true;
7829 switch (this->code_)
7831 case BUILTIN_LEN:
7832 case BUILTIN_CAP:
7834 if (this->seen_)
7835 return false;
7837 Expression* arg = this->one_arg();
7838 if (arg == NULL)
7839 return false;
7840 Type* arg_type = arg->type();
7842 if (arg_type->points_to() != NULL
7843 && arg_type->points_to()->array_type() != NULL
7844 && !arg_type->points_to()->is_slice_type())
7845 arg_type = arg_type->points_to();
7847 // The len and cap functions are only constant if there are no
7848 // function calls or channel operations in the arguments.
7849 // Otherwise we have to make the call.
7850 if (!arg->is_constant())
7852 Find_call_expression find_call;
7853 Expression::traverse(&arg, &find_call);
7854 if (find_call.found())
7855 return false;
7858 if (arg_type->array_type() != NULL
7859 && arg_type->array_type()->length() != NULL)
7860 return true;
7862 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7864 this->seen_ = true;
7865 bool ret = arg->is_constant();
7866 this->seen_ = false;
7867 return ret;
7870 break;
7872 case BUILTIN_SIZEOF:
7873 case BUILTIN_ALIGNOF:
7874 return this->one_arg() != NULL;
7876 case BUILTIN_OFFSETOF:
7878 Expression* arg = this->one_arg();
7879 if (arg == NULL)
7880 return false;
7881 return arg->field_reference_expression() != NULL;
7884 case BUILTIN_COMPLEX:
7886 const Expression_list* args = this->args();
7887 if (args != NULL && args->size() == 2)
7888 return args->front()->is_constant() && args->back()->is_constant();
7890 break;
7892 case BUILTIN_REAL:
7893 case BUILTIN_IMAG:
7895 Expression* arg = this->one_arg();
7896 return arg != NULL && arg->is_constant();
7899 default:
7900 break;
7903 return false;
7906 // Return a numeric constant if possible.
7908 bool
7909 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7911 if (this->code_ == BUILTIN_LEN
7912 || this->code_ == BUILTIN_CAP)
7914 Expression* arg = this->one_arg();
7915 if (arg == NULL)
7916 return false;
7917 Type* arg_type = arg->type();
7919 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7921 std::string sval;
7922 if (arg->string_constant_value(&sval))
7924 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7925 sval.length());
7926 return true;
7930 if (arg_type->points_to() != NULL
7931 && arg_type->points_to()->array_type() != NULL
7932 && !arg_type->points_to()->is_slice_type())
7933 arg_type = arg_type->points_to();
7935 if (arg_type->array_type() != NULL
7936 && arg_type->array_type()->length() != NULL)
7938 if (this->seen_)
7939 return false;
7940 Expression* e = arg_type->array_type()->length();
7941 this->seen_ = true;
7942 bool r = e->numeric_constant_value(nc);
7943 this->seen_ = false;
7944 if (r)
7946 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7947 this->location()))
7948 r = false;
7950 return r;
7953 else if (this->code_ == BUILTIN_SIZEOF
7954 || this->code_ == BUILTIN_ALIGNOF)
7956 Expression* arg = this->one_arg();
7957 if (arg == NULL)
7958 return false;
7959 Type* arg_type = arg->type();
7960 if (arg_type->is_error())
7961 return false;
7962 if (arg_type->is_abstract())
7963 return false;
7964 if (this->seen_)
7965 return false;
7967 int64_t ret;
7968 if (this->code_ == BUILTIN_SIZEOF)
7970 this->seen_ = true;
7971 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7972 this->seen_ = false;
7973 if (!ok)
7974 return false;
7976 else if (this->code_ == BUILTIN_ALIGNOF)
7978 bool ok;
7979 this->seen_ = true;
7980 if (arg->field_reference_expression() == NULL)
7981 ok = arg_type->backend_type_align(this->gogo_, &ret);
7982 else
7984 // Calling unsafe.Alignof(s.f) returns the alignment of
7985 // the type of f when it is used as a field in a struct.
7986 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7988 this->seen_ = false;
7989 if (!ok)
7990 return false;
7992 else
7993 go_unreachable();
7995 mpz_t zval;
7996 set_mpz_from_int64(&zval, ret);
7997 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7998 mpz_clear(zval);
7999 return true;
8001 else if (this->code_ == BUILTIN_OFFSETOF)
8003 Expression* arg = this->one_arg();
8004 if (arg == NULL)
8005 return false;
8006 Field_reference_expression* farg = arg->field_reference_expression();
8007 if (farg == NULL)
8008 return false;
8009 if (this->seen_)
8010 return false;
8012 int64_t total_offset = 0;
8013 while (true)
8015 Expression* struct_expr = farg->expr();
8016 Type* st = struct_expr->type();
8017 if (st->struct_type() == NULL)
8018 return false;
8019 if (st->named_type() != NULL)
8020 st->named_type()->convert(this->gogo_);
8021 int64_t offset;
8022 this->seen_ = true;
8023 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8024 farg->field_index(),
8025 &offset);
8026 this->seen_ = false;
8027 if (!ok)
8028 return false;
8029 total_offset += offset;
8030 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8032 // Go up until we reach the original base.
8033 farg = struct_expr->field_reference_expression();
8034 continue;
8036 break;
8038 mpz_t zval;
8039 set_mpz_from_int64(&zval, total_offset);
8040 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8041 mpz_clear(zval);
8042 return true;
8044 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8046 Expression* arg = this->one_arg();
8047 if (arg == NULL)
8048 return false;
8050 Numeric_constant argnc;
8051 if (!arg->numeric_constant_value(&argnc))
8052 return false;
8054 mpc_t val;
8055 if (!argnc.to_complex(&val))
8056 return false;
8058 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8059 if (this->code_ == BUILTIN_REAL)
8060 nc->set_float(type, mpc_realref(val));
8061 else
8062 nc->set_float(type, mpc_imagref(val));
8063 mpc_clear(val);
8064 return true;
8066 else if (this->code_ == BUILTIN_COMPLEX)
8068 const Expression_list* args = this->args();
8069 if (args == NULL || args->size() != 2)
8070 return false;
8072 Numeric_constant rnc;
8073 if (!args->front()->numeric_constant_value(&rnc))
8074 return false;
8075 Numeric_constant inc;
8076 if (!args->back()->numeric_constant_value(&inc))
8077 return false;
8079 if (rnc.type() != NULL
8080 && !rnc.type()->is_abstract()
8081 && inc.type() != NULL
8082 && !inc.type()->is_abstract()
8083 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
8084 return false;
8086 mpfr_t r;
8087 if (!rnc.to_float(&r))
8088 return false;
8089 mpfr_t i;
8090 if (!inc.to_float(&i))
8092 mpfr_clear(r);
8093 return false;
8096 Type* arg_type = rnc.type();
8097 if (arg_type == NULL || arg_type->is_abstract())
8098 arg_type = inc.type();
8100 mpc_t val;
8101 mpc_init2(val, mpc_precision);
8102 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8103 mpfr_clear(r);
8104 mpfr_clear(i);
8106 Type* type = Builtin_call_expression::complex_type(arg_type);
8107 nc->set_complex(type, val);
8109 mpc_clear(val);
8111 return true;
8114 return false;
8117 // Give an error if we are discarding the value of an expression which
8118 // should not normally be discarded. We don't give an error for
8119 // discarding the value of an ordinary function call, but we do for
8120 // builtin functions, purely for consistency with the gc compiler.
8122 bool
8123 Builtin_call_expression::do_discarding_value()
8125 switch (this->code_)
8127 case BUILTIN_INVALID:
8128 default:
8129 go_unreachable();
8131 case BUILTIN_APPEND:
8132 case BUILTIN_CAP:
8133 case BUILTIN_COMPLEX:
8134 case BUILTIN_IMAG:
8135 case BUILTIN_LEN:
8136 case BUILTIN_MAKE:
8137 case BUILTIN_NEW:
8138 case BUILTIN_REAL:
8139 case BUILTIN_ALIGNOF:
8140 case BUILTIN_OFFSETOF:
8141 case BUILTIN_SIZEOF:
8142 this->unused_value_error();
8143 return false;
8145 case BUILTIN_CLOSE:
8146 case BUILTIN_COPY:
8147 case BUILTIN_DELETE:
8148 case BUILTIN_PANIC:
8149 case BUILTIN_PRINT:
8150 case BUILTIN_PRINTLN:
8151 case BUILTIN_RECOVER:
8152 return true;
8156 // Return the type.
8158 Type*
8159 Builtin_call_expression::do_type()
8161 if (this->is_error_expression())
8162 return Type::make_error_type();
8163 switch (this->code_)
8165 case BUILTIN_INVALID:
8166 default:
8167 return Type::make_error_type();
8169 case BUILTIN_NEW:
8170 case BUILTIN_MAKE:
8172 const Expression_list* args = this->args();
8173 if (args == NULL || args->empty())
8174 return Type::make_error_type();
8175 return Type::make_pointer_type(args->front()->type());
8178 case BUILTIN_CAP:
8179 case BUILTIN_COPY:
8180 case BUILTIN_LEN:
8181 return Type::lookup_integer_type("int");
8183 case BUILTIN_ALIGNOF:
8184 case BUILTIN_OFFSETOF:
8185 case BUILTIN_SIZEOF:
8186 return Type::lookup_integer_type("uintptr");
8188 case BUILTIN_CLOSE:
8189 case BUILTIN_DELETE:
8190 case BUILTIN_PANIC:
8191 case BUILTIN_PRINT:
8192 case BUILTIN_PRINTLN:
8193 return Type::make_void_type();
8195 case BUILTIN_RECOVER:
8196 return Type::make_empty_interface_type(Linemap::predeclared_location());
8198 case BUILTIN_APPEND:
8200 const Expression_list* args = this->args();
8201 if (args == NULL || args->empty())
8202 return Type::make_error_type();
8203 Type *ret = args->front()->type();
8204 if (!ret->is_slice_type())
8205 return Type::make_error_type();
8206 return ret;
8209 case BUILTIN_REAL:
8210 case BUILTIN_IMAG:
8212 Expression* arg = this->one_arg();
8213 if (arg == NULL)
8214 return Type::make_error_type();
8215 Type* t = arg->type();
8216 if (t->is_abstract())
8217 t = t->make_non_abstract_type();
8218 t = Builtin_call_expression::real_imag_type(t);
8219 if (t == NULL)
8220 t = Type::make_error_type();
8221 return t;
8224 case BUILTIN_COMPLEX:
8226 const Expression_list* args = this->args();
8227 if (args == NULL || args->size() != 2)
8228 return Type::make_error_type();
8229 Type* t = args->front()->type();
8230 if (t->is_abstract())
8232 t = args->back()->type();
8233 if (t->is_abstract())
8234 t = t->make_non_abstract_type();
8236 t = Builtin_call_expression::complex_type(t);
8237 if (t == NULL)
8238 t = Type::make_error_type();
8239 return t;
8244 // Determine the type.
8246 void
8247 Builtin_call_expression::do_determine_type(const Type_context* context)
8249 if (!this->determining_types())
8250 return;
8252 this->fn()->determine_type_no_context();
8254 const Expression_list* args = this->args();
8256 bool is_print;
8257 Type* arg_type = NULL;
8258 Type* trailing_arg_types = NULL;
8259 switch (this->code_)
8261 case BUILTIN_PRINT:
8262 case BUILTIN_PRINTLN:
8263 // Do not force a large integer constant to "int".
8264 is_print = true;
8265 break;
8267 case BUILTIN_REAL:
8268 case BUILTIN_IMAG:
8269 arg_type = Builtin_call_expression::complex_type(context->type);
8270 if (arg_type == NULL)
8271 arg_type = Type::lookup_complex_type("complex128");
8272 is_print = false;
8273 break;
8275 case BUILTIN_COMPLEX:
8277 // For the complex function the type of one operand can
8278 // determine the type of the other, as in a binary expression.
8279 arg_type = Builtin_call_expression::real_imag_type(context->type);
8280 if (arg_type == NULL)
8281 arg_type = Type::lookup_float_type("float64");
8282 if (args != NULL && args->size() == 2)
8284 Type* t1 = args->front()->type();
8285 Type* t2 = args->back()->type();
8286 if (!t1->is_abstract())
8287 arg_type = t1;
8288 else if (!t2->is_abstract())
8289 arg_type = t2;
8291 is_print = false;
8293 break;
8295 case BUILTIN_APPEND:
8296 if (!this->is_varargs()
8297 && args != NULL
8298 && !args->empty()
8299 && args->front()->type()->is_slice_type())
8300 trailing_arg_types =
8301 args->front()->type()->array_type()->element_type();
8302 is_print = false;
8303 break;
8305 default:
8306 is_print = false;
8307 break;
8310 if (args != NULL)
8312 for (Expression_list::const_iterator pa = args->begin();
8313 pa != args->end();
8314 ++pa)
8316 Type_context subcontext;
8317 subcontext.type = arg_type;
8319 if (is_print)
8321 // We want to print large constants, we so can't just
8322 // use the appropriate nonabstract type. Use uint64 for
8323 // an integer if we know it is nonnegative, otherwise
8324 // use int64 for a integer, otherwise use float64 for a
8325 // float or complex128 for a complex.
8326 Type* want_type = NULL;
8327 Type* atype = (*pa)->type();
8328 if (atype->is_abstract())
8330 if (atype->integer_type() != NULL)
8332 Numeric_constant nc;
8333 if (this->numeric_constant_value(&nc))
8335 mpz_t val;
8336 if (nc.to_int(&val))
8338 if (mpz_sgn(val) >= 0)
8339 want_type = Type::lookup_integer_type("uint64");
8340 mpz_clear(val);
8343 if (want_type == NULL)
8344 want_type = Type::lookup_integer_type("int64");
8346 else if (atype->float_type() != NULL)
8347 want_type = Type::lookup_float_type("float64");
8348 else if (atype->complex_type() != NULL)
8349 want_type = Type::lookup_complex_type("complex128");
8350 else if (atype->is_abstract_string_type())
8351 want_type = Type::lookup_string_type();
8352 else if (atype->is_abstract_boolean_type())
8353 want_type = Type::lookup_bool_type();
8354 else
8355 go_unreachable();
8356 subcontext.type = want_type;
8360 (*pa)->determine_type(&subcontext);
8362 if (trailing_arg_types != NULL)
8364 arg_type = trailing_arg_types;
8365 trailing_arg_types = NULL;
8371 // If there is exactly one argument, return true. Otherwise give an
8372 // error message and return false.
8374 bool
8375 Builtin_call_expression::check_one_arg()
8377 const Expression_list* args = this->args();
8378 if (args == NULL || args->size() < 1)
8380 this->report_error(_("not enough arguments"));
8381 return false;
8383 else if (args->size() > 1)
8385 this->report_error(_("too many arguments"));
8386 return false;
8388 if (args->front()->is_error_expression()
8389 || args->front()->type()->is_error())
8391 this->set_is_error();
8392 return false;
8394 return true;
8397 // Check argument types for a builtin function.
8399 void
8400 Builtin_call_expression::do_check_types(Gogo*)
8402 if (this->is_error_expression())
8403 return;
8404 switch (this->code_)
8406 case BUILTIN_INVALID:
8407 case BUILTIN_NEW:
8408 case BUILTIN_MAKE:
8409 case BUILTIN_DELETE:
8410 return;
8412 case BUILTIN_LEN:
8413 case BUILTIN_CAP:
8415 // The single argument may be either a string or an array or a
8416 // map or a channel, or a pointer to a closed array.
8417 if (this->check_one_arg())
8419 Type* arg_type = this->one_arg()->type();
8420 if (arg_type->points_to() != NULL
8421 && arg_type->points_to()->array_type() != NULL
8422 && !arg_type->points_to()->is_slice_type())
8423 arg_type = arg_type->points_to();
8424 if (this->code_ == BUILTIN_CAP)
8426 if (!arg_type->is_error()
8427 && arg_type->array_type() == NULL
8428 && arg_type->channel_type() == NULL)
8429 this->report_error(_("argument must be array or slice "
8430 "or channel"));
8432 else
8434 if (!arg_type->is_error()
8435 && !arg_type->is_string_type()
8436 && arg_type->array_type() == NULL
8437 && arg_type->map_type() == NULL
8438 && arg_type->channel_type() == NULL)
8439 this->report_error(_("argument must be string or "
8440 "array or slice or map or channel"));
8444 break;
8446 case BUILTIN_PRINT:
8447 case BUILTIN_PRINTLN:
8449 const Expression_list* args = this->args();
8450 if (args == NULL)
8452 if (this->code_ == BUILTIN_PRINT)
8453 go_warning_at(this->location(), 0,
8454 "no arguments for builtin function %<%s%>",
8455 (this->code_ == BUILTIN_PRINT
8456 ? "print"
8457 : "println"));
8459 else
8461 for (Expression_list::const_iterator p = args->begin();
8462 p != args->end();
8463 ++p)
8465 Type* type = (*p)->type();
8466 if (type->is_error()
8467 || type->is_string_type()
8468 || type->integer_type() != NULL
8469 || type->float_type() != NULL
8470 || type->complex_type() != NULL
8471 || type->is_boolean_type()
8472 || type->points_to() != NULL
8473 || type->interface_type() != NULL
8474 || type->channel_type() != NULL
8475 || type->map_type() != NULL
8476 || type->function_type() != NULL
8477 || type->is_slice_type())
8479 else if ((*p)->is_type_expression())
8481 // If this is a type expression it's going to give
8482 // an error anyhow, so we don't need one here.
8484 else
8485 this->report_error(_("unsupported argument type to "
8486 "builtin function"));
8490 break;
8492 case BUILTIN_CLOSE:
8493 if (this->check_one_arg())
8495 if (this->one_arg()->type()->channel_type() == NULL)
8496 this->report_error(_("argument must be channel"));
8497 else if (!this->one_arg()->type()->channel_type()->may_send())
8498 this->report_error(_("cannot close receive-only channel"));
8500 break;
8502 case BUILTIN_PANIC:
8503 case BUILTIN_SIZEOF:
8504 case BUILTIN_ALIGNOF:
8505 this->check_one_arg();
8506 break;
8508 case BUILTIN_RECOVER:
8509 if (this->args() != NULL
8510 && !this->args()->empty()
8511 && !this->recover_arg_is_set_)
8512 this->report_error(_("too many arguments"));
8513 break;
8515 case BUILTIN_OFFSETOF:
8516 if (this->check_one_arg())
8518 Expression* arg = this->one_arg();
8519 if (arg->field_reference_expression() == NULL)
8520 this->report_error(_("argument must be a field reference"));
8522 break;
8524 case BUILTIN_COPY:
8526 const Expression_list* args = this->args();
8527 if (args == NULL || args->size() < 2)
8529 this->report_error(_("not enough arguments"));
8530 break;
8532 else if (args->size() > 2)
8534 this->report_error(_("too many arguments"));
8535 break;
8537 Type* arg1_type = args->front()->type();
8538 Type* arg2_type = args->back()->type();
8539 if (arg1_type->is_error() || arg2_type->is_error())
8541 this->set_is_error();
8542 break;
8545 Type* e1;
8546 if (arg1_type->is_slice_type())
8547 e1 = arg1_type->array_type()->element_type();
8548 else
8550 this->report_error(_("left argument must be a slice"));
8551 break;
8554 if (arg2_type->is_slice_type())
8556 Type* e2 = arg2_type->array_type()->element_type();
8557 if (!Type::are_identical(e1, e2, true, NULL))
8558 this->report_error(_("element types must be the same"));
8560 else if (arg2_type->is_string_type())
8562 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8563 this->report_error(_("first argument must be []byte"));
8565 else
8566 this->report_error(_("second argument must be slice or string"));
8568 break;
8570 case BUILTIN_APPEND:
8572 const Expression_list* args = this->args();
8573 if (args == NULL || args->empty())
8575 this->report_error(_("not enough arguments"));
8576 break;
8579 Type* slice_type = args->front()->type();
8580 if (!slice_type->is_slice_type())
8582 if (slice_type->is_error_type())
8583 break;
8584 if (slice_type->is_nil_type())
8585 go_error_at(args->front()->location(), "use of untyped nil");
8586 else
8587 go_error_at(args->front()->location(),
8588 "argument 1 must be a slice");
8589 this->set_is_error();
8590 break;
8593 Type* element_type = slice_type->array_type()->element_type();
8594 if (this->is_varargs())
8596 if (!args->back()->type()->is_slice_type()
8597 && !args->back()->type()->is_string_type())
8599 go_error_at(args->back()->location(),
8600 "invalid use of %<...%> with non-slice/non-string");
8601 this->set_is_error();
8602 break;
8605 if (args->size() < 2)
8607 this->report_error(_("not enough arguments"));
8608 break;
8610 if (args->size() > 2)
8612 this->report_error(_("too many arguments"));
8613 break;
8616 if (args->back()->type()->is_string_type()
8617 && element_type->integer_type() != NULL
8618 && element_type->integer_type()->is_byte())
8620 // Permit append(s1, s2...) when s1 is a slice of
8621 // bytes and s2 is a string type.
8623 else
8625 // We have to test for assignment compatibility to a
8626 // slice of the element type, which is not necessarily
8627 // the same as the type of the first argument: the
8628 // first argument might have a named type.
8629 Type* check_type = Type::make_array_type(element_type, NULL);
8630 std::string reason;
8631 if (!Type::are_assignable(check_type, args->back()->type(),
8632 &reason))
8634 if (reason.empty())
8635 go_error_at(args->back()->location(),
8636 "argument 2 has invalid type");
8637 else
8638 go_error_at(args->back()->location(),
8639 "argument 2 has invalid type (%s)",
8640 reason.c_str());
8641 this->set_is_error();
8642 break;
8646 else
8648 Expression_list::const_iterator pa = args->begin();
8649 int i = 2;
8650 for (++pa; pa != args->end(); ++pa, ++i)
8652 std::string reason;
8653 if (!Type::are_assignable(element_type, (*pa)->type(),
8654 &reason))
8656 if (reason.empty())
8657 go_error_at((*pa)->location(),
8658 "argument %d has incompatible type", i);
8659 else
8660 go_error_at((*pa)->location(),
8661 "argument %d has incompatible type (%s)",
8662 i, reason.c_str());
8663 this->set_is_error();
8668 break;
8670 case BUILTIN_REAL:
8671 case BUILTIN_IMAG:
8672 if (this->check_one_arg())
8674 if (this->one_arg()->type()->complex_type() == NULL)
8675 this->report_error(_("argument must have complex type"));
8677 break;
8679 case BUILTIN_COMPLEX:
8681 const Expression_list* args = this->args();
8682 if (args == NULL || args->size() < 2)
8683 this->report_error(_("not enough arguments"));
8684 else if (args->size() > 2)
8685 this->report_error(_("too many arguments"));
8686 else if (args->front()->is_error_expression()
8687 || args->front()->type()->is_error()
8688 || args->back()->is_error_expression()
8689 || args->back()->type()->is_error())
8690 this->set_is_error();
8691 else if (!Type::are_identical(args->front()->type(),
8692 args->back()->type(), true, NULL))
8693 this->report_error(_("complex arguments must have identical types"));
8694 else if (args->front()->type()->float_type() == NULL)
8695 this->report_error(_("complex arguments must have "
8696 "floating-point type"));
8698 break;
8700 default:
8701 go_unreachable();
8705 Expression*
8706 Builtin_call_expression::do_copy()
8708 Call_expression* bce =
8709 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
8710 (this->args() == NULL
8711 ? NULL
8712 : this->args()->copy()),
8713 this->is_varargs(),
8714 this->location());
8716 if (this->varargs_are_lowered())
8717 bce->set_varargs_are_lowered();
8718 return bce;
8721 // Return the backend representation for a builtin function.
8723 Bexpression*
8724 Builtin_call_expression::do_get_backend(Translate_context* context)
8726 Gogo* gogo = context->gogo();
8727 Location location = this->location();
8729 if (this->is_erroneous_call())
8731 go_assert(saw_errors());
8732 return gogo->backend()->error_expression();
8735 switch (this->code_)
8737 case BUILTIN_INVALID:
8738 case BUILTIN_NEW:
8739 case BUILTIN_MAKE:
8740 go_unreachable();
8742 case BUILTIN_LEN:
8743 case BUILTIN_CAP:
8745 const Expression_list* args = this->args();
8746 go_assert(args != NULL && args->size() == 1);
8747 Expression* arg = args->front();
8748 Type* arg_type = arg->type();
8750 if (this->seen_)
8752 go_assert(saw_errors());
8753 return context->backend()->error_expression();
8755 this->seen_ = true;
8756 this->seen_ = false;
8757 if (arg_type->points_to() != NULL)
8759 arg_type = arg_type->points_to();
8760 go_assert(arg_type->array_type() != NULL
8761 && !arg_type->is_slice_type());
8762 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8765 Type* int_type = Type::lookup_integer_type("int");
8766 Expression* val;
8767 if (this->code_ == BUILTIN_LEN)
8769 if (arg_type->is_string_type())
8770 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8771 location);
8772 else if (arg_type->array_type() != NULL)
8774 if (this->seen_)
8776 go_assert(saw_errors());
8777 return context->backend()->error_expression();
8779 this->seen_ = true;
8780 val = arg_type->array_type()->get_length(gogo, arg);
8781 this->seen_ = false;
8783 else if (arg_type->map_type() != NULL
8784 || arg_type->channel_type() != NULL)
8786 // The first field is the length. If the pointer is
8787 // nil, the length is zero.
8788 Type* pint_type = Type::make_pointer_type(int_type);
8789 arg = Expression::make_unsafe_cast(pint_type, arg, location);
8790 Expression* nil = Expression::make_nil(location);
8791 nil = Expression::make_cast(pint_type, nil, location);
8792 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8793 arg, nil, location);
8794 Expression* zero = Expression::make_integer_ul(0, int_type,
8795 location);
8796 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8797 arg, location);
8798 val = Expression::make_conditional(cmp, zero, indir, location);
8800 else
8801 go_unreachable();
8803 else
8805 if (arg_type->array_type() != NULL)
8807 if (this->seen_)
8809 go_assert(saw_errors());
8810 return context->backend()->error_expression();
8812 this->seen_ = true;
8813 val = arg_type->array_type()->get_capacity(gogo, arg);
8814 this->seen_ = false;
8816 else if (arg_type->channel_type() != NULL)
8818 // The second field is the capacity. If the pointer
8819 // is nil, the capacity is zero.
8820 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8821 Type* pint_type = Type::make_pointer_type(int_type);
8822 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
8823 arg,
8824 location);
8825 int off = int_type->integer_type()->bits() / 8;
8826 Expression* eoff = Expression::make_integer_ul(off,
8827 uintptr_type,
8828 location);
8829 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
8830 location);
8831 parg = Expression::make_unsafe_cast(pint_type, parg, location);
8832 Expression* nil = Expression::make_nil(location);
8833 nil = Expression::make_cast(pint_type, nil, location);
8834 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
8835 arg, nil, location);
8836 Expression* zero = Expression::make_integer_ul(0, int_type,
8837 location);
8838 Expression* indir = Expression::make_unary(OPERATOR_MULT,
8839 parg, location);
8840 val = Expression::make_conditional(cmp, zero, indir, location);
8842 else
8843 go_unreachable();
8846 return Expression::make_cast(int_type, val,
8847 location)->get_backend(context);
8850 case BUILTIN_PRINT:
8851 case BUILTIN_PRINTLN:
8853 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8855 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
8856 location, 0);
8858 const Expression_list* call_args = this->args();
8859 if (call_args != NULL)
8861 for (Expression_list::const_iterator p = call_args->begin();
8862 p != call_args->end();
8863 ++p)
8865 if (is_ln && p != call_args->begin())
8867 Expression* print_space =
8868 Runtime::make_call(Runtime::PRINTSP, location, 0);
8870 print_stmts =
8871 Expression::make_compound(print_stmts, print_space,
8872 location);
8875 Expression* arg = *p;
8876 Type* type = arg->type();
8877 Runtime::Function code;
8878 if (type->is_string_type())
8879 code = Runtime::PRINTSTRING;
8880 else if (type->integer_type() != NULL
8881 && type->integer_type()->is_unsigned())
8883 Type* itype = Type::lookup_integer_type("uint64");
8884 arg = Expression::make_cast(itype, arg, location);
8885 code = Runtime::PRINTUINT;
8887 else if (type->integer_type() != NULL)
8889 Type* itype = Type::lookup_integer_type("int64");
8890 arg = Expression::make_cast(itype, arg, location);
8891 code = Runtime::PRINTINT;
8893 else if (type->float_type() != NULL)
8895 Type* dtype = Type::lookup_float_type("float64");
8896 arg = Expression::make_cast(dtype, arg, location);
8897 code = Runtime::PRINTFLOAT;
8899 else if (type->complex_type() != NULL)
8901 Type* ctype = Type::lookup_complex_type("complex128");
8902 arg = Expression::make_cast(ctype, arg, location);
8903 code = Runtime::PRINTCOMPLEX;
8905 else if (type->is_boolean_type())
8906 code = Runtime::PRINTBOOL;
8907 else if (type->points_to() != NULL
8908 || type->channel_type() != NULL
8909 || type->map_type() != NULL
8910 || type->function_type() != NULL)
8912 arg = Expression::make_cast(type, arg, location);
8913 code = Runtime::PRINTPOINTER;
8915 else if (type->interface_type() != NULL)
8917 if (type->interface_type()->is_empty())
8918 code = Runtime::PRINTEFACE;
8919 else
8920 code = Runtime::PRINTIFACE;
8922 else if (type->is_slice_type())
8923 code = Runtime::PRINTSLICE;
8924 else
8926 go_assert(saw_errors());
8927 return context->backend()->error_expression();
8930 Expression* call = Runtime::make_call(code, location, 1, arg);
8931 print_stmts = Expression::make_compound(print_stmts, call,
8932 location);
8936 if (is_ln)
8938 Expression* print_nl =
8939 Runtime::make_call(Runtime::PRINTNL, location, 0);
8940 print_stmts = Expression::make_compound(print_stmts, print_nl,
8941 location);
8944 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
8945 location, 0);
8946 print_stmts = Expression::make_compound(print_stmts, unlock, location);
8948 return print_stmts->get_backend(context);
8951 case BUILTIN_PANIC:
8953 const Expression_list* args = this->args();
8954 go_assert(args != NULL && args->size() == 1);
8955 Expression* arg = args->front();
8956 Type *empty =
8957 Type::make_empty_interface_type(Linemap::predeclared_location());
8958 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8960 Expression* panic =
8961 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
8962 return panic->get_backend(context);
8965 case BUILTIN_RECOVER:
8967 // The argument is set when building recover thunks. It's a
8968 // boolean value which is true if we can recover a value now.
8969 const Expression_list* args = this->args();
8970 go_assert(args != NULL && args->size() == 1);
8971 Expression* arg = args->front();
8972 Type *empty =
8973 Type::make_empty_interface_type(Linemap::predeclared_location());
8975 Expression* nil = Expression::make_nil(location);
8976 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8978 // We need to handle a deferred call to recover specially,
8979 // because it changes whether it can recover a panic or not.
8980 // See test7 in test/recover1.go.
8981 Expression* recover = Runtime::make_call((this->is_deferred()
8982 ? Runtime::DEFERREDRECOVER
8983 : Runtime::GORECOVER),
8984 location, 0);
8985 Expression* cond =
8986 Expression::make_conditional(arg, recover, nil, location);
8987 return cond->get_backend(context);
8990 case BUILTIN_CLOSE:
8992 const Expression_list* args = this->args();
8993 go_assert(args != NULL && args->size() == 1);
8994 Expression* arg = args->front();
8995 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8996 1, arg);
8997 return close->get_backend(context);
9000 case BUILTIN_SIZEOF:
9001 case BUILTIN_OFFSETOF:
9002 case BUILTIN_ALIGNOF:
9004 Numeric_constant nc;
9005 unsigned long val;
9006 if (!this->numeric_constant_value(&nc)
9007 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9009 go_assert(saw_errors());
9010 return context->backend()->error_expression();
9012 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9013 mpz_t ival;
9014 nc.get_int(&ival);
9015 Expression* int_cst =
9016 Expression::make_integer_z(&ival, uintptr_type, location);
9017 mpz_clear(ival);
9018 return int_cst->get_backend(context);
9021 case BUILTIN_COPY:
9023 const Expression_list* args = this->args();
9024 go_assert(args != NULL && args->size() == 2);
9025 Expression* arg1 = args->front();
9026 Expression* arg2 = args->back();
9028 Type* arg1_type = arg1->type();
9029 Array_type* at = arg1_type->array_type();
9030 go_assert(arg1->is_variable());
9032 Expression* call;
9034 Type* arg2_type = arg2->type();
9035 go_assert(arg2->is_variable());
9036 if (arg2_type->is_string_type())
9037 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9038 2, arg1, arg2);
9039 else
9041 Type* et = at->element_type();
9042 if (et->has_pointer())
9044 Expression* td = Expression::make_type_descriptor(et,
9045 location);
9046 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9047 3, td, arg1, arg2);
9049 else
9051 Expression* sz = Expression::make_type_info(et,
9052 TYPE_INFO_SIZE);
9053 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9054 arg1, arg2, sz);
9058 return call->get_backend(context);
9061 case BUILTIN_APPEND:
9062 // Handled in Builtin_call_expression::flatten_append.
9063 go_unreachable();
9065 case BUILTIN_REAL:
9066 case BUILTIN_IMAG:
9068 const Expression_list* args = this->args();
9069 go_assert(args != NULL && args->size() == 1);
9071 Bexpression* ret;
9072 Bexpression* bcomplex = args->front()->get_backend(context);
9073 if (this->code_ == BUILTIN_REAL)
9074 ret = gogo->backend()->real_part_expression(bcomplex, location);
9075 else
9076 ret = gogo->backend()->imag_part_expression(bcomplex, location);
9077 return ret;
9080 case BUILTIN_COMPLEX:
9082 const Expression_list* args = this->args();
9083 go_assert(args != NULL && args->size() == 2);
9084 Bexpression* breal = args->front()->get_backend(context);
9085 Bexpression* bimag = args->back()->get_backend(context);
9086 return gogo->backend()->complex_expression(breal, bimag, location);
9089 default:
9090 go_unreachable();
9094 // We have to support exporting a builtin call expression, because
9095 // code can set a constant to the result of a builtin expression.
9097 void
9098 Builtin_call_expression::do_export(Export* exp) const
9100 Numeric_constant nc;
9101 if (!this->numeric_constant_value(&nc))
9103 go_error_at(this->location(), "value is not constant");
9104 return;
9107 if (nc.is_int())
9109 mpz_t val;
9110 nc.get_int(&val);
9111 Integer_expression::export_integer(exp, val);
9112 mpz_clear(val);
9114 else if (nc.is_float())
9116 mpfr_t fval;
9117 nc.get_float(&fval);
9118 Float_expression::export_float(exp, fval);
9119 mpfr_clear(fval);
9121 else if (nc.is_complex())
9123 mpc_t cval;
9124 nc.get_complex(&cval);
9125 Complex_expression::export_complex(exp, cval);
9126 mpc_clear(cval);
9128 else
9129 go_unreachable();
9131 // A trailing space lets us reliably identify the end of the number.
9132 exp->write_c_string(" ");
9135 // Class Call_expression.
9137 // A Go function can be viewed in a couple of different ways. The
9138 // code of a Go function becomes a backend function with parameters
9139 // whose types are simply the backend representation of the Go types.
9140 // If there are multiple results, they are returned as a backend
9141 // struct.
9143 // However, when Go code refers to a function other than simply
9144 // calling it, the backend type of that function is actually a struct.
9145 // The first field of the struct points to the Go function code
9146 // (sometimes a wrapper as described below). The remaining fields
9147 // hold addresses of closed-over variables. This struct is called a
9148 // closure.
9150 // There are a few cases to consider.
9152 // A direct function call of a known function in package scope. In
9153 // this case there are no closed-over variables, and we know the name
9154 // of the function code. We can simply produce a backend call to the
9155 // function directly, and not worry about the closure.
9157 // A direct function call of a known function literal. In this case
9158 // we know the function code and we know the closure. We generate the
9159 // function code such that it expects an additional final argument of
9160 // the closure type. We pass the closure as the last argument, after
9161 // the other arguments.
9163 // An indirect function call. In this case we have a closure. We
9164 // load the pointer to the function code from the first field of the
9165 // closure. We pass the address of the closure as the last argument.
9167 // A call to a method of an interface. Type methods are always at
9168 // package scope, so we call the function directly, and don't worry
9169 // about the closure.
9171 // This means that for a function at package scope we have two cases.
9172 // One is the direct call, which has no closure. The other is the
9173 // indirect call, which does have a closure. We can't simply ignore
9174 // the closure, even though it is the last argument, because that will
9175 // fail on targets where the function pops its arguments. So when
9176 // generating a closure for a package-scope function we set the
9177 // function code pointer in the closure to point to a wrapper
9178 // function. This wrapper function accepts a final argument that
9179 // points to the closure, ignores it, and calls the real function as a
9180 // direct function call. This wrapper will normally be efficient, and
9181 // can often simply be a tail call to the real function.
9183 // We don't use GCC's static chain pointer because 1) we don't need
9184 // it; 2) GCC only permits using a static chain to call a known
9185 // function, so we can't use it for an indirect call anyhow. Since we
9186 // can't use it for an indirect call, we may as well not worry about
9187 // using it for a direct call either.
9189 // We pass the closure last rather than first because it means that
9190 // the function wrapper we put into a closure for a package-scope
9191 // function can normally just be a tail call to the real function.
9193 // For method expressions we generate a wrapper that loads the
9194 // receiver from the closure and then calls the method. This
9195 // unfortunately forces reshuffling the arguments, since there is a
9196 // new first argument, but we can't avoid reshuffling either for
9197 // method expressions or for indirect calls of package-scope
9198 // functions, and since the latter are more common we reshuffle for
9199 // method expressions.
9201 // Note that the Go code retains the Go types. The extra final
9202 // argument only appears when we convert to the backend
9203 // representation.
9205 // Traversal.
9208 Call_expression::do_traverse(Traverse* traverse)
9210 // If we are calling a function in a different package that returns
9211 // an unnamed type, this may be the only chance we get to traverse
9212 // that type. We don't traverse this->type_ because it may be a
9213 // Call_multiple_result_type that will just lead back here.
9214 if (this->type_ != NULL && !this->type_->is_error_type())
9216 Function_type *fntype = this->get_function_type();
9217 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9218 return TRAVERSE_EXIT;
9220 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9221 return TRAVERSE_EXIT;
9222 if (this->args_ != NULL)
9224 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9225 return TRAVERSE_EXIT;
9227 return TRAVERSE_CONTINUE;
9230 // Lower a call statement.
9232 Expression*
9233 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9234 Statement_inserter* inserter, int)
9236 Location loc = this->location();
9238 // A type cast can look like a function call.
9239 if (this->fn_->is_type_expression()
9240 && this->args_ != NULL
9241 && this->args_->size() == 1)
9242 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9243 loc);
9245 // Because do_type will return an error type and thus prevent future
9246 // errors, check for that case now to ensure that the error gets
9247 // reported.
9248 Function_type* fntype = this->get_function_type();
9249 if (fntype == NULL)
9251 if (!this->fn_->type()->is_error())
9252 this->report_error(_("expected function"));
9253 this->set_is_error();
9254 return this;
9257 // Handle an argument which is a call to a function which returns
9258 // multiple results.
9259 if (this->args_ != NULL
9260 && this->args_->size() == 1
9261 && this->args_->front()->call_expression() != NULL)
9263 size_t rc = this->args_->front()->call_expression()->result_count();
9264 if (rc > 1
9265 && ((fntype->parameters() != NULL
9266 && (fntype->parameters()->size() == rc
9267 || (fntype->is_varargs()
9268 && fntype->parameters()->size() - 1 <= rc)))
9269 || fntype->is_builtin()))
9271 Call_expression* call = this->args_->front()->call_expression();
9272 call->set_is_multi_value_arg();
9273 if (this->is_varargs_)
9275 // It is not clear which result of a multiple result call
9276 // the ellipsis operator should be applied to. If we unpack the
9277 // the call into its individual results here, the ellipsis will be
9278 // applied to the last result.
9279 go_error_at(call->location(),
9280 _("multiple-value argument in single-value context"));
9281 return Expression::make_error(call->location());
9284 Expression_list* args = new Expression_list;
9285 for (size_t i = 0; i < rc; ++i)
9286 args->push_back(Expression::make_call_result(call, i));
9287 // We can't return a new call expression here, because this
9288 // one may be referenced by Call_result expressions. We
9289 // also can't delete the old arguments, because we may still
9290 // traverse them somewhere up the call stack. FIXME.
9291 this->args_ = args;
9295 // Recognize a call to a builtin function.
9296 if (fntype->is_builtin())
9297 return new Builtin_call_expression(gogo, this->fn_, this->args_,
9298 this->is_varargs_, loc);
9300 // If this call returns multiple results, create a temporary
9301 // variable for each result.
9302 size_t rc = this->result_count();
9303 if (rc > 1 && this->results_ == NULL)
9305 std::vector<Temporary_statement*>* temps =
9306 new std::vector<Temporary_statement*>;
9307 temps->reserve(rc);
9308 const Typed_identifier_list* results = fntype->results();
9309 for (Typed_identifier_list::const_iterator p = results->begin();
9310 p != results->end();
9311 ++p)
9313 Temporary_statement* temp = Statement::make_temporary(p->type(),
9314 NULL, loc);
9315 inserter->insert(temp);
9316 temps->push_back(temp);
9318 this->results_ = temps;
9321 // Handle a call to a varargs function by packaging up the extra
9322 // parameters.
9323 if (fntype->is_varargs())
9325 const Typed_identifier_list* parameters = fntype->parameters();
9326 go_assert(parameters != NULL && !parameters->empty());
9327 Type* varargs_type = parameters->back().type();
9328 this->lower_varargs(gogo, function, inserter, varargs_type,
9329 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9332 // If this is call to a method, call the method directly passing the
9333 // object as the first parameter.
9334 Bound_method_expression* bme = this->fn_->bound_method_expression();
9335 if (bme != NULL)
9337 Named_object* methodfn = bme->function();
9338 Expression* first_arg = bme->first_argument();
9340 // We always pass a pointer when calling a method.
9341 if (first_arg->type()->points_to() == NULL
9342 && !first_arg->type()->is_error())
9344 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9345 // We may need to create a temporary variable so that we can
9346 // take the address. We can't do that here because it will
9347 // mess up the order of evaluation.
9348 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9349 ue->set_create_temp();
9352 // If we are calling a method which was inherited from an
9353 // embedded struct, and the method did not get a stub, then the
9354 // first type may be wrong.
9355 Type* fatype = bme->first_argument_type();
9356 if (fatype != NULL)
9358 if (fatype->points_to() == NULL)
9359 fatype = Type::make_pointer_type(fatype);
9360 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9363 Expression_list* new_args = new Expression_list();
9364 new_args->push_back(first_arg);
9365 if (this->args_ != NULL)
9367 for (Expression_list::const_iterator p = this->args_->begin();
9368 p != this->args_->end();
9369 ++p)
9370 new_args->push_back(*p);
9373 // We have to change in place because this structure may be
9374 // referenced by Call_result_expressions. We can't delete the
9375 // old arguments, because we may be traversing them up in some
9376 // caller. FIXME.
9377 this->args_ = new_args;
9378 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9379 bme->location());
9382 // Handle a couple of special runtime functions. In the runtime
9383 // package, getcallerpc returns the PC of the caller, and
9384 // getcallersp returns the frame pointer of the caller. Implement
9385 // these by turning them into calls to GCC builtin functions. We
9386 // could implement them in normal code, but then we would have to
9387 // explicitly unwind the stack. These functions are intended to be
9388 // efficient. Note that this technique obviously only works for
9389 // direct calls, but that is the only way they are used. The actual
9390 // argument to these functions is always the address of a parameter;
9391 // we don't need that for the GCC builtin functions, so we just
9392 // ignore it.
9393 if (gogo->compiling_runtime()
9394 && this->args_ != NULL
9395 && this->args_->size() == 1
9396 && gogo->package_name() == "runtime")
9398 Func_expression* fe = this->fn_->func_expression();
9399 if (fe != NULL
9400 && fe->named_object()->is_function_declaration()
9401 && fe->named_object()->package() == NULL)
9403 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9404 if (n == "getcallerpc")
9406 static Named_object* builtin_return_address;
9407 return this->lower_to_builtin(&builtin_return_address,
9408 "__builtin_return_address",
9411 else if (n == "getcallersp")
9413 static Named_object* builtin_frame_address;
9414 return this->lower_to_builtin(&builtin_frame_address,
9415 "__builtin_frame_address",
9421 return this;
9424 // Lower a call to a varargs function. FUNCTION is the function in
9425 // which the call occurs--it's not the function we are calling.
9426 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9427 // PARAM_COUNT is the number of parameters of the function we are
9428 // calling; the last of these parameters will be the varargs
9429 // parameter.
9431 void
9432 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9433 Statement_inserter* inserter,
9434 Type* varargs_type, size_t param_count,
9435 Slice_storage_escape_disp escape_disp)
9437 if (this->varargs_are_lowered_)
9438 return;
9440 Location loc = this->location();
9442 go_assert(param_count > 0);
9443 go_assert(varargs_type->is_slice_type());
9445 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
9446 if (arg_count < param_count - 1)
9448 // Not enough arguments; will be caught in check_types.
9449 return;
9452 Expression_list* old_args = this->args_;
9453 Expression_list* new_args = new Expression_list();
9454 bool push_empty_arg = false;
9455 if (old_args == NULL || old_args->empty())
9457 go_assert(param_count == 1);
9458 push_empty_arg = true;
9460 else
9462 Expression_list::const_iterator pa;
9463 int i = 1;
9464 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
9466 if (static_cast<size_t>(i) == param_count)
9467 break;
9468 new_args->push_back(*pa);
9471 // We have reached the varargs parameter.
9473 bool issued_error = false;
9474 if (pa == old_args->end())
9475 push_empty_arg = true;
9476 else if (pa + 1 == old_args->end() && this->is_varargs_)
9477 new_args->push_back(*pa);
9478 else if (this->is_varargs_)
9480 if ((*pa)->type()->is_slice_type())
9481 this->report_error(_("too many arguments"));
9482 else
9484 go_error_at(this->location(),
9485 _("invalid use of %<...%> with non-slice"));
9486 this->set_is_error();
9488 return;
9490 else
9492 Type* element_type = varargs_type->array_type()->element_type();
9493 Expression_list* vals = new Expression_list;
9494 for (; pa != old_args->end(); ++pa, ++i)
9496 // Check types here so that we get a better message.
9497 Type* patype = (*pa)->type();
9498 Location paloc = (*pa)->location();
9499 if (!this->check_argument_type(i, element_type, patype,
9500 paloc, issued_error))
9501 continue;
9502 vals->push_back(*pa);
9504 Slice_construction_expression* sce =
9505 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9506 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
9507 sce->set_storage_does_not_escape();
9508 Expression* val = sce;
9509 gogo->lower_expression(function, inserter, &val);
9510 new_args->push_back(val);
9514 if (push_empty_arg)
9515 new_args->push_back(Expression::make_nil(loc));
9517 // We can't return a new call expression here, because this one may
9518 // be referenced by Call_result expressions. FIXME. We can't
9519 // delete OLD_ARGS because we may have both a Call_expression and a
9520 // Builtin_call_expression which refer to them. FIXME.
9521 this->args_ = new_args;
9522 this->varargs_are_lowered_ = true;
9525 // Return a call to __builtin_return_address or __builtin_frame_address.
9527 Expression*
9528 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
9529 int arg)
9531 if (*pno == NULL)
9532 *pno = Gogo::declare_builtin_rf_address(name);
9534 Location loc = this->location();
9536 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
9537 Expression* a = Expression::make_integer_ul(arg, NULL, loc);
9538 Expression_list *args = new Expression_list();
9539 args->push_back(a);
9540 Expression* call = Expression::make_call(fn, args, false, loc);
9542 // The builtin functions return void*, but the Go functions return uintptr.
9543 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9544 return Expression::make_cast(uintptr_type, call, loc);
9547 // Flatten a call with multiple results into a temporary.
9549 Expression*
9550 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9551 Statement_inserter* inserter)
9553 if (this->is_erroneous_call())
9555 go_assert(saw_errors());
9556 return Expression::make_error(this->location());
9559 if (this->is_flattened_)
9560 return this;
9561 this->is_flattened_ = true;
9563 // Add temporary variables for all arguments that require type
9564 // conversion.
9565 Function_type* fntype = this->get_function_type();
9566 if (fntype == NULL)
9568 go_assert(saw_errors());
9569 return this;
9571 if (this->args_ != NULL && !this->args_->empty()
9572 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9574 bool is_interface_method =
9575 this->fn_->interface_field_reference_expression() != NULL;
9577 Expression_list *args = new Expression_list();
9578 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9579 Expression_list::const_iterator pa = this->args_->begin();
9580 if (!is_interface_method && fntype->is_method())
9582 // The receiver argument.
9583 args->push_back(*pa);
9584 ++pa;
9586 for (; pa != this->args_->end(); ++pa, ++pp)
9588 go_assert(pp != fntype->parameters()->end());
9589 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9590 args->push_back(*pa);
9591 else
9593 Location loc = (*pa)->location();
9594 Expression* arg = *pa;
9595 if (!arg->is_variable())
9597 Temporary_statement *temp =
9598 Statement::make_temporary(NULL, arg, loc);
9599 inserter->insert(temp);
9600 arg = Expression::make_temporary_reference(temp, loc);
9602 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
9603 loc);
9604 args->push_back(arg);
9607 delete this->args_;
9608 this->args_ = args;
9611 size_t rc = this->result_count();
9612 if (rc > 1 && this->call_temp_ == NULL)
9614 Struct_field_list* sfl = new Struct_field_list();
9615 Function_type* fntype = this->get_function_type();
9616 const Typed_identifier_list* results = fntype->results();
9617 Location loc = this->location();
9619 int i = 0;
9620 char buf[20];
9621 for (Typed_identifier_list::const_iterator p = results->begin();
9622 p != results->end();
9623 ++p, ++i)
9625 snprintf(buf, sizeof buf, "res%d", i);
9626 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9629 Struct_type* st = Type::make_struct_type(sfl, loc);
9630 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9631 inserter->insert(this->call_temp_);
9634 return this;
9637 // Get the function type. This can return NULL in error cases.
9639 Function_type*
9640 Call_expression::get_function_type() const
9642 return this->fn_->type()->function_type();
9645 // Return the number of values which this call will return.
9647 size_t
9648 Call_expression::result_count() const
9650 const Function_type* fntype = this->get_function_type();
9651 if (fntype == NULL)
9652 return 0;
9653 if (fntype->results() == NULL)
9654 return 0;
9655 return fntype->results()->size();
9658 // Return the temporary which holds a result.
9660 Temporary_statement*
9661 Call_expression::result(size_t i) const
9663 if (this->results_ == NULL || this->results_->size() <= i)
9665 go_assert(saw_errors());
9666 return NULL;
9668 return (*this->results_)[i];
9671 // Set the number of results expected from a call expression.
9673 void
9674 Call_expression::set_expected_result_count(size_t count)
9676 go_assert(this->expected_result_count_ == 0);
9677 this->expected_result_count_ = count;
9680 // Return whether this is a call to the predeclared function recover.
9682 bool
9683 Call_expression::is_recover_call() const
9685 return this->do_is_recover_call();
9688 // Set the argument to the recover function.
9690 void
9691 Call_expression::set_recover_arg(Expression* arg)
9693 this->do_set_recover_arg(arg);
9696 // Virtual functions also implemented by Builtin_call_expression.
9698 bool
9699 Call_expression::do_is_recover_call() const
9701 return false;
9704 void
9705 Call_expression::do_set_recover_arg(Expression*)
9707 go_unreachable();
9710 // We have found an error with this call expression; return true if
9711 // we should report it.
9713 bool
9714 Call_expression::issue_error()
9716 if (this->issued_error_)
9717 return false;
9718 else
9720 this->issued_error_ = true;
9721 return true;
9725 // Whether or not this call contains errors, either in the call or the
9726 // arguments to the call.
9728 bool
9729 Call_expression::is_erroneous_call()
9731 if (this->is_error_expression() || this->fn()->is_error_expression())
9732 return true;
9734 if (this->args() == NULL)
9735 return false;
9736 for (Expression_list::iterator pa = this->args()->begin();
9737 pa != this->args()->end();
9738 ++pa)
9740 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
9741 return true;
9743 return false;
9746 // Get the type.
9748 Type*
9749 Call_expression::do_type()
9751 if (this->type_ != NULL)
9752 return this->type_;
9754 Type* ret;
9755 Function_type* fntype = this->get_function_type();
9756 if (fntype == NULL)
9757 return Type::make_error_type();
9759 const Typed_identifier_list* results = fntype->results();
9760 if (results == NULL)
9761 ret = Type::make_void_type();
9762 else if (results->size() == 1)
9763 ret = results->begin()->type();
9764 else
9765 ret = Type::make_call_multiple_result_type(this);
9767 this->type_ = ret;
9769 return this->type_;
9772 // Determine types for a call expression. We can use the function
9773 // parameter types to set the types of the arguments.
9775 void
9776 Call_expression::do_determine_type(const Type_context*)
9778 if (!this->determining_types())
9779 return;
9781 this->fn_->determine_type_no_context();
9782 Function_type* fntype = this->get_function_type();
9783 const Typed_identifier_list* parameters = NULL;
9784 if (fntype != NULL)
9785 parameters = fntype->parameters();
9786 if (this->args_ != NULL)
9788 Typed_identifier_list::const_iterator pt;
9789 if (parameters != NULL)
9790 pt = parameters->begin();
9791 bool first = true;
9792 for (Expression_list::const_iterator pa = this->args_->begin();
9793 pa != this->args_->end();
9794 ++pa)
9796 if (first)
9798 first = false;
9799 // If this is a method, the first argument is the
9800 // receiver.
9801 if (fntype != NULL && fntype->is_method())
9803 Type* rtype = fntype->receiver()->type();
9804 // The receiver is always passed as a pointer.
9805 if (rtype->points_to() == NULL)
9806 rtype = Type::make_pointer_type(rtype);
9807 Type_context subcontext(rtype, false);
9808 (*pa)->determine_type(&subcontext);
9809 continue;
9813 if (parameters != NULL && pt != parameters->end())
9815 Type_context subcontext(pt->type(), false);
9816 (*pa)->determine_type(&subcontext);
9817 ++pt;
9819 else
9820 (*pa)->determine_type_no_context();
9825 // Called when determining types for a Call_expression. Return true
9826 // if we should go ahead, false if they have already been determined.
9828 bool
9829 Call_expression::determining_types()
9831 if (this->types_are_determined_)
9832 return false;
9833 else
9835 this->types_are_determined_ = true;
9836 return true;
9840 // Check types for parameter I.
9842 bool
9843 Call_expression::check_argument_type(int i, const Type* parameter_type,
9844 const Type* argument_type,
9845 Location argument_location,
9846 bool issued_error)
9848 std::string reason;
9849 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9851 if (!issued_error)
9853 if (reason.empty())
9854 go_error_at(argument_location, "argument %d has incompatible type", i);
9855 else
9856 go_error_at(argument_location,
9857 "argument %d has incompatible type (%s)",
9858 i, reason.c_str());
9860 this->set_is_error();
9861 return false;
9863 return true;
9866 // Check types.
9868 void
9869 Call_expression::do_check_types(Gogo*)
9871 if (this->classification() == EXPRESSION_ERROR)
9872 return;
9874 Function_type* fntype = this->get_function_type();
9875 if (fntype == NULL)
9877 if (!this->fn_->type()->is_error())
9878 this->report_error(_("expected function"));
9879 return;
9882 if (this->expected_result_count_ != 0
9883 && this->expected_result_count_ != this->result_count())
9885 if (this->issue_error())
9886 this->report_error(_("function result count mismatch"));
9887 this->set_is_error();
9888 return;
9891 bool is_method = fntype->is_method();
9892 if (is_method)
9894 go_assert(this->args_ != NULL && !this->args_->empty());
9895 Type* rtype = fntype->receiver()->type();
9896 Expression* first_arg = this->args_->front();
9897 // We dereference the values since receivers are always passed
9898 // as pointers.
9899 std::string reason;
9900 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9901 &reason))
9903 if (reason.empty())
9904 this->report_error(_("incompatible type for receiver"));
9905 else
9907 go_error_at(this->location(),
9908 "incompatible type for receiver (%s)",
9909 reason.c_str());
9910 this->set_is_error();
9915 // Note that varargs was handled by the lower_varargs() method, so
9916 // we don't have to worry about it here unless something is wrong.
9917 if (this->is_varargs_ && !this->varargs_are_lowered_)
9919 if (!fntype->is_varargs())
9921 go_error_at(this->location(),
9922 _("invalid use of %<...%> calling non-variadic function"));
9923 this->set_is_error();
9924 return;
9928 const Typed_identifier_list* parameters = fntype->parameters();
9929 if (this->args_ == NULL)
9931 if (parameters != NULL && !parameters->empty())
9932 this->report_error(_("not enough arguments"));
9934 else if (parameters == NULL)
9936 if (!is_method || this->args_->size() > 1)
9937 this->report_error(_("too many arguments"));
9939 else if (this->args_->size() == 1
9940 && this->args_->front()->call_expression() != NULL
9941 && this->args_->front()->call_expression()->result_count() > 1)
9943 // This is F(G()) when G returns more than one result. If the
9944 // results can be matched to parameters, it would have been
9945 // lowered in do_lower. If we get here we know there is a
9946 // mismatch.
9947 if (this->args_->front()->call_expression()->result_count()
9948 < parameters->size())
9949 this->report_error(_("not enough arguments"));
9950 else
9951 this->report_error(_("too many arguments"));
9953 else
9955 int i = 0;
9956 Expression_list::const_iterator pa = this->args_->begin();
9957 if (is_method)
9958 ++pa;
9959 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9960 pt != parameters->end();
9961 ++pt, ++pa, ++i)
9963 if (pa == this->args_->end())
9965 this->report_error(_("not enough arguments"));
9966 return;
9968 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9969 (*pa)->location(), false);
9971 if (pa != this->args_->end())
9972 this->report_error(_("too many arguments"));
9976 Expression*
9977 Call_expression::do_copy()
9979 Call_expression* call =
9980 Expression::make_call(this->fn_->copy(),
9981 (this->args_ == NULL
9982 ? NULL
9983 : this->args_->copy()),
9984 this->is_varargs_, this->location());
9986 if (this->varargs_are_lowered_)
9987 call->set_varargs_are_lowered();
9988 return call;
9991 // Return whether we have to use a temporary variable to ensure that
9992 // we evaluate this call expression in order. If the call returns no
9993 // results then it will inevitably be executed last.
9995 bool
9996 Call_expression::do_must_eval_in_order() const
9998 return this->result_count() > 0;
10001 // Get the function and the first argument to use when calling an
10002 // interface method.
10004 Expression*
10005 Call_expression::interface_method_function(
10006 Interface_field_reference_expression* interface_method,
10007 Expression** first_arg_ptr)
10009 *first_arg_ptr = interface_method->get_underlying_object();
10010 return interface_method->get_function();
10013 // Build the call expression.
10015 Bexpression*
10016 Call_expression::do_get_backend(Translate_context* context)
10018 if (this->call_ != NULL)
10019 return this->call_;
10021 Function_type* fntype = this->get_function_type();
10022 if (fntype == NULL)
10023 return context->backend()->error_expression();
10025 if (this->fn_->is_error_expression())
10026 return context->backend()->error_expression();
10028 Gogo* gogo = context->gogo();
10029 Location location = this->location();
10031 Func_expression* func = this->fn_->func_expression();
10032 Interface_field_reference_expression* interface_method =
10033 this->fn_->interface_field_reference_expression();
10034 const bool has_closure = func != NULL && func->closure() != NULL;
10035 const bool is_interface_method = interface_method != NULL;
10037 bool has_closure_arg;
10038 if (has_closure)
10039 has_closure_arg = true;
10040 else if (func != NULL)
10041 has_closure_arg = false;
10042 else if (is_interface_method)
10043 has_closure_arg = false;
10044 else
10045 has_closure_arg = true;
10047 int nargs;
10048 std::vector<Bexpression*> fn_args;
10049 if (this->args_ == NULL || this->args_->empty())
10051 nargs = is_interface_method ? 1 : 0;
10052 if (nargs > 0)
10053 fn_args.resize(1);
10055 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10057 // Passing a receiver parameter.
10058 go_assert(!is_interface_method
10059 && fntype->is_method()
10060 && this->args_->size() == 1);
10061 nargs = 1;
10062 fn_args.resize(1);
10063 fn_args[0] = this->args_->front()->get_backend(context);
10065 else
10067 const Typed_identifier_list* params = fntype->parameters();
10069 nargs = this->args_->size();
10070 int i = is_interface_method ? 1 : 0;
10071 nargs += i;
10072 fn_args.resize(nargs);
10074 Typed_identifier_list::const_iterator pp = params->begin();
10075 Expression_list::const_iterator pe = this->args_->begin();
10076 if (!is_interface_method && fntype->is_method())
10078 fn_args[i] = (*pe)->get_backend(context);
10079 ++pe;
10080 ++i;
10082 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10084 go_assert(pp != params->end());
10085 Expression* arg =
10086 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10087 location);
10088 fn_args[i] = arg->get_backend(context);
10090 go_assert(pp == params->end());
10091 go_assert(i == nargs);
10094 Expression* fn;
10095 Expression* closure = NULL;
10096 if (func != NULL)
10098 Named_object* no = func->named_object();
10099 fn = Expression::make_func_code_reference(no, location);
10100 if (has_closure)
10101 closure = func->closure();
10103 else if (!is_interface_method)
10105 closure = this->fn_;
10107 // The backend representation of this function type is a pointer
10108 // to a struct whose first field is the actual function to call.
10109 Type* pfntype =
10110 Type::make_pointer_type(
10111 Type::make_pointer_type(Type::make_void_type()));
10112 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10113 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
10115 else
10117 Expression* first_arg;
10118 fn = this->interface_method_function(interface_method, &first_arg);
10119 fn_args[0] = first_arg->get_backend(context);
10122 Bexpression* bclosure = NULL;
10123 if (has_closure_arg)
10124 bclosure = closure->get_backend(context);
10125 else
10126 go_assert(closure == NULL);
10128 Bexpression* bfn = fn->get_backend(context);
10130 // When not calling a named function directly, use a type conversion
10131 // in case the type of the function is a recursive type which refers
10132 // to itself. We don't do this for an interface method because 1)
10133 // an interface method never refers to itself, so we always have a
10134 // function type here; 2) we pass an extra first argument to an
10135 // interface method, so fntype is not correct.
10136 if (func == NULL && !is_interface_method)
10138 Btype* bft = fntype->get_backend_fntype(gogo);
10139 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10142 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args,
10143 bclosure, location);
10145 if (this->results_ != NULL)
10147 go_assert(this->call_temp_ != NULL);
10148 Expression* call_ref =
10149 Expression::make_temporary_reference(this->call_temp_, location);
10150 Bexpression* bcall_ref = call_ref->get_backend(context);
10151 Bstatement* assn_stmt =
10152 gogo->backend()->assignment_statement(bcall_ref, call, location);
10154 this->call_ = this->set_results(context, bcall_ref);
10156 Bexpression* set_and_call =
10157 gogo->backend()->compound_expression(assn_stmt, this->call_,
10158 location);
10159 return set_and_call;
10162 this->call_ = call;
10163 return this->call_;
10166 // Set the result variables if this call returns multiple results.
10168 Bexpression*
10169 Call_expression::set_results(Translate_context* context, Bexpression* call)
10171 Gogo* gogo = context->gogo();
10173 Bexpression* results = NULL;
10174 Location loc = this->location();
10176 size_t rc = this->result_count();
10177 for (size_t i = 0; i < rc; ++i)
10179 Temporary_statement* temp = this->result(i);
10180 if (temp == NULL)
10182 go_assert(saw_errors());
10183 return gogo->backend()->error_expression();
10185 Temporary_reference_expression* ref =
10186 Expression::make_temporary_reference(temp, loc);
10187 ref->set_is_lvalue();
10189 Bexpression* result_ref = ref->get_backend(context);
10190 Bexpression* call_result =
10191 gogo->backend()->struct_field_expression(call, i, loc);
10192 Bstatement* assn_stmt =
10193 gogo->backend()->assignment_statement(result_ref, call_result, loc);
10195 Bexpression* result =
10196 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
10198 if (results == NULL)
10199 results = result;
10200 else
10202 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
10203 results =
10204 gogo->backend()->compound_expression(expr_stmt, results, loc);
10207 return results;
10210 // Dump ast representation for a call expressin.
10212 void
10213 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10215 this->fn_->dump_expression(ast_dump_context);
10216 ast_dump_context->ostream() << "(";
10217 if (args_ != NULL)
10218 ast_dump_context->dump_expression_list(this->args_);
10220 ast_dump_context->ostream() << ") ";
10223 // Make a call expression.
10225 Call_expression*
10226 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10227 Location location)
10229 return new Call_expression(fn, args, is_varargs, location);
10232 // Class Call_result_expression.
10234 // Traverse a call result.
10237 Call_result_expression::do_traverse(Traverse* traverse)
10239 if (traverse->remember_expression(this->call_))
10241 // We have already traversed the call expression.
10242 return TRAVERSE_CONTINUE;
10244 return Expression::traverse(&this->call_, traverse);
10247 // Get the type.
10249 Type*
10250 Call_result_expression::do_type()
10252 if (this->classification() == EXPRESSION_ERROR)
10253 return Type::make_error_type();
10255 // THIS->CALL_ can be replaced with a temporary reference due to
10256 // Call_expression::do_must_eval_in_order when there is an error.
10257 Call_expression* ce = this->call_->call_expression();
10258 if (ce == NULL)
10260 this->set_is_error();
10261 return Type::make_error_type();
10263 Function_type* fntype = ce->get_function_type();
10264 if (fntype == NULL)
10266 if (ce->issue_error())
10268 if (!ce->fn()->type()->is_error())
10269 this->report_error(_("expected function"));
10271 this->set_is_error();
10272 return Type::make_error_type();
10274 const Typed_identifier_list* results = fntype->results();
10275 if (results == NULL || results->size() < 2)
10277 if (ce->issue_error())
10278 this->report_error(_("number of results does not match "
10279 "number of values"));
10280 return Type::make_error_type();
10282 Typed_identifier_list::const_iterator pr = results->begin();
10283 for (unsigned int i = 0; i < this->index_; ++i)
10285 if (pr == results->end())
10286 break;
10287 ++pr;
10289 if (pr == results->end())
10291 if (ce->issue_error())
10292 this->report_error(_("number of results does not match "
10293 "number of values"));
10294 return Type::make_error_type();
10296 return pr->type();
10299 // Check the type. Just make sure that we trigger the warning in
10300 // do_type.
10302 void
10303 Call_result_expression::do_check_types(Gogo*)
10305 this->type();
10308 // Determine the type. We have nothing to do here, but the 0 result
10309 // needs to pass down to the caller.
10311 void
10312 Call_result_expression::do_determine_type(const Type_context*)
10314 this->call_->determine_type_no_context();
10317 // Return the backend representation. We just refer to the temporary set by the
10318 // call expression. We don't do this at lowering time because it makes it
10319 // hard to evaluate the call at the right time.
10321 Bexpression*
10322 Call_result_expression::do_get_backend(Translate_context* context)
10324 Call_expression* ce = this->call_->call_expression();
10325 if (ce == NULL)
10327 go_assert(this->call_->is_error_expression());
10328 return context->backend()->error_expression();
10330 Temporary_statement* ts = ce->result(this->index_);
10331 if (ts == NULL)
10333 go_assert(saw_errors());
10334 return context->backend()->error_expression();
10336 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10337 return ref->get_backend(context);
10340 // Dump ast representation for a call result expression.
10342 void
10343 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10344 const
10346 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10347 // (struct) and the fields are referenced instead.
10348 ast_dump_context->ostream() << this->index_ << "@(";
10349 ast_dump_context->dump_expression(this->call_);
10350 ast_dump_context->ostream() << ")";
10353 // Make a reference to a single result of a call which returns
10354 // multiple results.
10356 Expression*
10357 Expression::make_call_result(Call_expression* call, unsigned int index)
10359 return new Call_result_expression(call, index);
10362 // Class Index_expression.
10364 // Traversal.
10367 Index_expression::do_traverse(Traverse* traverse)
10369 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10370 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10371 || (this->end_ != NULL
10372 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10373 || (this->cap_ != NULL
10374 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10375 return TRAVERSE_EXIT;
10376 return TRAVERSE_CONTINUE;
10379 // Lower an index expression. This converts the generic index
10380 // expression into an array index, a string index, or a map index.
10382 Expression*
10383 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10385 Location location = this->location();
10386 Expression* left = this->left_;
10387 Expression* start = this->start_;
10388 Expression* end = this->end_;
10389 Expression* cap = this->cap_;
10391 Type* type = left->type();
10392 if (type->is_error())
10394 go_assert(saw_errors());
10395 return Expression::make_error(location);
10397 else if (left->is_type_expression())
10399 go_error_at(location, "attempt to index type expression");
10400 return Expression::make_error(location);
10402 else if (type->array_type() != NULL)
10403 return Expression::make_array_index(left, start, end, cap, location);
10404 else if (type->points_to() != NULL
10405 && type->points_to()->array_type() != NULL
10406 && !type->points_to()->is_slice_type())
10408 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
10409 location);
10411 // For an ordinary index into the array, the pointer will be
10412 // dereferenced. For a slice it will not--the resulting slice
10413 // will simply reuse the pointer, which is incorrect if that
10414 // pointer is nil.
10415 if (end != NULL || cap != NULL)
10416 deref->issue_nil_check();
10418 return Expression::make_array_index(deref, start, end, cap, location);
10420 else if (type->is_string_type())
10422 if (cap != NULL)
10424 go_error_at(location, "invalid 3-index slice of string");
10425 return Expression::make_error(location);
10427 return Expression::make_string_index(left, start, end, location);
10429 else if (type->map_type() != NULL)
10431 if (end != NULL || cap != NULL)
10433 go_error_at(location, "invalid slice of map");
10434 return Expression::make_error(location);
10436 return Expression::make_map_index(left, start, location);
10438 else
10440 go_error_at(location,
10441 "attempt to index object which is not array, string, or map");
10442 return Expression::make_error(location);
10446 // Write an indexed expression
10447 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10449 void
10450 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10451 const Expression* expr,
10452 const Expression* start,
10453 const Expression* end,
10454 const Expression* cap)
10456 expr->dump_expression(ast_dump_context);
10457 ast_dump_context->ostream() << "[";
10458 start->dump_expression(ast_dump_context);
10459 if (end != NULL)
10461 ast_dump_context->ostream() << ":";
10462 end->dump_expression(ast_dump_context);
10464 if (cap != NULL)
10466 ast_dump_context->ostream() << ":";
10467 cap->dump_expression(ast_dump_context);
10469 ast_dump_context->ostream() << "]";
10472 // Dump ast representation for an index expression.
10474 void
10475 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10476 const
10478 Index_expression::dump_index_expression(ast_dump_context, this->left_,
10479 this->start_, this->end_, this->cap_);
10482 // Make an index expression.
10484 Expression*
10485 Expression::make_index(Expression* left, Expression* start, Expression* end,
10486 Expression* cap, Location location)
10488 return new Index_expression(left, start, end, cap, location);
10491 // Class Array_index_expression.
10493 // Array index traversal.
10496 Array_index_expression::do_traverse(Traverse* traverse)
10498 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10499 return TRAVERSE_EXIT;
10500 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10501 return TRAVERSE_EXIT;
10502 if (this->end_ != NULL)
10504 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10505 return TRAVERSE_EXIT;
10507 if (this->cap_ != NULL)
10509 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10510 return TRAVERSE_EXIT;
10512 return TRAVERSE_CONTINUE;
10515 // Return the type of an array index.
10517 Type*
10518 Array_index_expression::do_type()
10520 if (this->type_ == NULL)
10522 Array_type* type = this->array_->type()->array_type();
10523 if (type == NULL)
10524 this->type_ = Type::make_error_type();
10525 else if (this->end_ == NULL)
10526 this->type_ = type->element_type();
10527 else if (type->is_slice_type())
10529 // A slice of a slice has the same type as the original
10530 // slice.
10531 this->type_ = this->array_->type()->deref();
10533 else
10535 // A slice of an array is a slice.
10536 this->type_ = Type::make_array_type(type->element_type(), NULL);
10539 return this->type_;
10542 // Set the type of an array index.
10544 void
10545 Array_index_expression::do_determine_type(const Type_context*)
10547 this->array_->determine_type_no_context();
10549 Type_context index_context(Type::lookup_integer_type("int"), false);
10550 if (this->start_->is_constant())
10551 this->start_->determine_type(&index_context);
10552 else
10553 this->start_->determine_type_no_context();
10554 if (this->end_ != NULL)
10556 if (this->end_->is_constant())
10557 this->end_->determine_type(&index_context);
10558 else
10559 this->end_->determine_type_no_context();
10561 if (this->cap_ != NULL)
10563 if (this->cap_->is_constant())
10564 this->cap_->determine_type(&index_context);
10565 else
10566 this->cap_->determine_type_no_context();
10570 // Check types of an array index.
10572 void
10573 Array_index_expression::do_check_types(Gogo* gogo)
10575 Numeric_constant nc;
10576 unsigned long v;
10577 if (this->start_->type()->integer_type() == NULL
10578 && !this->start_->type()->is_error()
10579 && (!this->start_->numeric_constant_value(&nc)
10580 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10581 this->report_error(_("index must be integer"));
10582 if (this->end_ != NULL
10583 && this->end_->type()->integer_type() == NULL
10584 && !this->end_->type()->is_error()
10585 && !this->end_->is_nil_expression()
10586 && !this->end_->is_error_expression()
10587 && (!this->end_->numeric_constant_value(&nc)
10588 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10589 this->report_error(_("slice end must be integer"));
10590 if (this->cap_ != NULL
10591 && this->cap_->type()->integer_type() == NULL
10592 && !this->cap_->type()->is_error()
10593 && !this->cap_->is_nil_expression()
10594 && !this->cap_->is_error_expression()
10595 && (!this->cap_->numeric_constant_value(&nc)
10596 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10597 this->report_error(_("slice capacity must be integer"));
10599 Array_type* array_type = this->array_->type()->array_type();
10600 if (array_type == NULL)
10602 go_assert(this->array_->type()->is_error());
10603 return;
10606 unsigned int int_bits =
10607 Type::lookup_integer_type("int")->integer_type()->bits();
10609 Numeric_constant lvalnc;
10610 mpz_t lval;
10611 bool lval_valid = (array_type->length() != NULL
10612 && array_type->length()->numeric_constant_value(&lvalnc)
10613 && lvalnc.to_int(&lval));
10614 Numeric_constant inc;
10615 mpz_t ival;
10616 bool ival_valid = false;
10617 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10619 ival_valid = true;
10620 if (mpz_sgn(ival) < 0
10621 || mpz_sizeinbase(ival, 2) >= int_bits
10622 || (lval_valid
10623 && (this->end_ == NULL
10624 ? mpz_cmp(ival, lval) >= 0
10625 : mpz_cmp(ival, lval) > 0)))
10627 go_error_at(this->start_->location(), "array index out of bounds");
10628 this->set_is_error();
10631 if (this->end_ != NULL && !this->end_->is_nil_expression())
10633 Numeric_constant enc;
10634 mpz_t eval;
10635 bool eval_valid = false;
10636 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10638 eval_valid = true;
10639 if (mpz_sgn(eval) < 0
10640 || mpz_sizeinbase(eval, 2) >= int_bits
10641 || (lval_valid && mpz_cmp(eval, lval) > 0))
10643 go_error_at(this->end_->location(), "array index out of bounds");
10644 this->set_is_error();
10646 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10647 this->report_error(_("inverted slice range"));
10650 Numeric_constant cnc;
10651 mpz_t cval;
10652 if (this->cap_ != NULL
10653 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10655 if (mpz_sgn(cval) < 0
10656 || mpz_sizeinbase(cval, 2) >= int_bits
10657 || (lval_valid && mpz_cmp(cval, lval) > 0))
10659 go_error_at(this->cap_->location(), "array index out of bounds");
10660 this->set_is_error();
10662 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10664 go_error_at(this->cap_->location(),
10665 "invalid slice index: capacity less than start");
10666 this->set_is_error();
10668 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10670 go_error_at(this->cap_->location(),
10671 "invalid slice index: capacity less than length");
10672 this->set_is_error();
10674 mpz_clear(cval);
10677 if (eval_valid)
10678 mpz_clear(eval);
10680 if (ival_valid)
10681 mpz_clear(ival);
10682 if (lval_valid)
10683 mpz_clear(lval);
10685 // A slice of an array requires an addressable array. A slice of a
10686 // slice is always possible.
10687 if (this->end_ != NULL && !array_type->is_slice_type())
10689 if (!this->array_->is_addressable())
10690 this->report_error(_("slice of unaddressable value"));
10691 else
10693 bool escapes = true;
10695 // When compiling the runtime, a slice operation does not
10696 // cause local variables to escape. When escape analysis
10697 // becomes the default, this should be changed to make it an
10698 // error if we have a slice operation that escapes.
10699 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
10700 escapes = false;
10702 this->array_->address_taken(escapes);
10707 // Flatten array indexing by using temporary variables for slices and indexes.
10709 Expression*
10710 Array_index_expression::do_flatten(Gogo*, Named_object*,
10711 Statement_inserter* inserter)
10713 Location loc = this->location();
10714 Expression* array = this->array_;
10715 Expression* start = this->start_;
10716 Expression* end = this->end_;
10717 Expression* cap = this->cap_;
10718 if (array->is_error_expression()
10719 || array->type()->is_error_type()
10720 || start->is_error_expression()
10721 || start->type()->is_error_type()
10722 || (end != NULL
10723 && (end->is_error_expression() || end->type()->is_error_type()))
10724 || (cap != NULL
10725 && (cap->is_error_expression() || cap->type()->is_error_type())))
10727 go_assert(saw_errors());
10728 return Expression::make_error(loc);
10731 Temporary_statement* temp;
10732 if (array->type()->is_slice_type() && !array->is_variable())
10734 temp = Statement::make_temporary(NULL, array, loc);
10735 inserter->insert(temp);
10736 this->array_ = Expression::make_temporary_reference(temp, loc);
10738 if (!start->is_variable())
10740 temp = Statement::make_temporary(NULL, start, loc);
10741 inserter->insert(temp);
10742 this->start_ = Expression::make_temporary_reference(temp, loc);
10744 if (end != NULL
10745 && !end->is_nil_expression()
10746 && !end->is_variable())
10748 temp = Statement::make_temporary(NULL, end, loc);
10749 inserter->insert(temp);
10750 this->end_ = Expression::make_temporary_reference(temp, loc);
10752 if (cap!= NULL && !cap->is_variable())
10754 temp = Statement::make_temporary(NULL, cap, loc);
10755 inserter->insert(temp);
10756 this->cap_ = Expression::make_temporary_reference(temp, loc);
10759 return this;
10762 // Return whether this expression is addressable.
10764 bool
10765 Array_index_expression::do_is_addressable() const
10767 // A slice expression is not addressable.
10768 if (this->end_ != NULL)
10769 return false;
10771 // An index into a slice is addressable.
10772 if (this->array_->type()->is_slice_type())
10773 return true;
10775 // An index into an array is addressable if the array is
10776 // addressable.
10777 return this->array_->is_addressable();
10780 // Get the backend representation for an array index.
10782 Bexpression*
10783 Array_index_expression::do_get_backend(Translate_context* context)
10785 Array_type* array_type = this->array_->type()->array_type();
10786 if (array_type == NULL)
10788 go_assert(this->array_->type()->is_error());
10789 return context->backend()->error_expression();
10791 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10793 Location loc = this->location();
10794 Gogo* gogo = context->gogo();
10796 Type* int_type = Type::lookup_integer_type("int");
10797 Btype* int_btype = int_type->get_backend(gogo);
10799 // We need to convert the length and capacity to the Go "int" type here
10800 // because the length of a fixed-length array could be of type "uintptr"
10801 // and gimple disallows binary operations between "uintptr" and other
10802 // integer types. FIXME.
10803 Bexpression* length = NULL;
10804 if (this->end_ == NULL || this->end_->is_nil_expression())
10806 Expression* len = array_type->get_length(gogo, this->array_);
10807 length = len->get_backend(context);
10808 length = gogo->backend()->convert_expression(int_btype, length, loc);
10811 Bexpression* capacity = NULL;
10812 if (this->end_ != NULL)
10814 Expression* cap = array_type->get_capacity(gogo, this->array_);
10815 capacity = cap->get_backend(context);
10816 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10819 Bexpression* cap_arg = capacity;
10820 if (this->cap_ != NULL)
10822 cap_arg = this->cap_->get_backend(context);
10823 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10826 if (length == NULL)
10827 length = cap_arg;
10829 int code = (array_type->length() != NULL
10830 ? (this->end_ == NULL
10831 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10832 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10833 : (this->end_ == NULL
10834 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10835 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10836 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10838 if (this->start_->type()->integer_type() == NULL
10839 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10841 go_assert(saw_errors());
10842 return context->backend()->error_expression();
10845 Bexpression* bad_index =
10846 Expression::check_bounds(this->start_, loc)->get_backend(context);
10848 Bexpression* start = this->start_->get_backend(context);
10849 start = gogo->backend()->convert_expression(int_btype, start, loc);
10850 Bexpression* start_too_large =
10851 gogo->backend()->binary_expression((this->end_ == NULL
10852 ? OPERATOR_GE
10853 : OPERATOR_GT),
10854 start,
10855 (this->end_ == NULL
10856 ? length
10857 : capacity),
10858 loc);
10859 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10860 bad_index, loc);
10862 if (this->end_ == NULL)
10864 // Simple array indexing. This has to return an l-value, so
10865 // wrap the index check into START.
10866 start =
10867 gogo->backend()->conditional_expression(int_btype, bad_index,
10868 crash, start, loc);
10870 Bexpression* ret;
10871 if (array_type->length() != NULL)
10873 Bexpression* array = this->array_->get_backend(context);
10874 ret = gogo->backend()->array_index_expression(array, start, loc);
10876 else
10878 // Slice.
10879 Expression* valptr =
10880 array_type->get_value_pointer(gogo, this->array_);
10881 Bexpression* ptr = valptr->get_backend(context);
10882 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10884 Type* ele_type = this->array_->type()->array_type()->element_type();
10885 Btype* ele_btype = ele_type->get_backend(gogo);
10886 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
10888 return ret;
10891 // Array slice.
10893 if (this->cap_ != NULL)
10895 Bexpression* bounds_bcheck =
10896 Expression::check_bounds(this->cap_, loc)->get_backend(context);
10897 bad_index =
10898 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10899 bad_index, loc);
10900 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10902 Bexpression* cap_too_small =
10903 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10904 Bexpression* cap_too_large =
10905 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10906 Bexpression* bad_cap =
10907 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10908 cap_too_large, loc);
10909 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10910 bad_index, loc);
10913 Bexpression* end;
10914 if (this->end_->is_nil_expression())
10915 end = length;
10916 else
10918 Bexpression* bounds_bcheck =
10919 Expression::check_bounds(this->end_, loc)->get_backend(context);
10921 bad_index =
10922 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10923 bad_index, loc);
10925 end = this->end_->get_backend(context);
10926 end = gogo->backend()->convert_expression(int_btype, end, loc);
10927 Bexpression* end_too_small =
10928 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10929 Bexpression* end_too_large =
10930 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10931 Bexpression* bad_end =
10932 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10933 end_too_large, loc);
10934 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10935 bad_index, loc);
10938 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10939 Bexpression* val = valptr->get_backend(context);
10940 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10942 Bexpression* result_length =
10943 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10945 Bexpression* result_capacity =
10946 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10948 Btype* struct_btype = this->type()->get_backend(gogo);
10949 std::vector<Bexpression*> init;
10950 init.push_back(val);
10951 init.push_back(result_length);
10952 init.push_back(result_capacity);
10954 Bexpression* ctor =
10955 gogo->backend()->constructor_expression(struct_btype, init, loc);
10956 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10957 crash, ctor, loc);
10960 // Dump ast representation for an array index expression.
10962 void
10963 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10964 const
10966 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10967 this->start_, this->end_, this->cap_);
10970 // Make an array index expression. END and CAP may be NULL.
10972 Expression*
10973 Expression::make_array_index(Expression* array, Expression* start,
10974 Expression* end, Expression* cap,
10975 Location location)
10977 return new Array_index_expression(array, start, end, cap, location);
10980 // Class String_index_expression.
10982 // String index traversal.
10985 String_index_expression::do_traverse(Traverse* traverse)
10987 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10988 return TRAVERSE_EXIT;
10989 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10990 return TRAVERSE_EXIT;
10991 if (this->end_ != NULL)
10993 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10994 return TRAVERSE_EXIT;
10996 return TRAVERSE_CONTINUE;
10999 Expression*
11000 String_index_expression::do_flatten(Gogo*, Named_object*,
11001 Statement_inserter* inserter)
11003 Location loc = this->location();
11004 Expression* string = this->string_;
11005 Expression* start = this->start_;
11006 Expression* end = this->end_;
11007 if (string->is_error_expression()
11008 || string->type()->is_error_type()
11009 || start->is_error_expression()
11010 || start->type()->is_error_type()
11011 || (end != NULL
11012 && (end->is_error_expression() || end->type()->is_error_type())))
11014 go_assert(saw_errors());
11015 return Expression::make_error(loc);
11018 Temporary_statement* temp;
11019 if (!this->string_->is_variable())
11021 temp = Statement::make_temporary(NULL, this->string_, loc);
11022 inserter->insert(temp);
11023 this->string_ = Expression::make_temporary_reference(temp, loc);
11025 if (!this->start_->is_variable())
11027 temp = Statement::make_temporary(NULL, this->start_, loc);
11028 inserter->insert(temp);
11029 this->start_ = Expression::make_temporary_reference(temp, loc);
11031 if (this->end_ != NULL
11032 && !this->end_->is_nil_expression()
11033 && !this->end_->is_variable())
11035 temp = Statement::make_temporary(NULL, this->end_, loc);
11036 inserter->insert(temp);
11037 this->end_ = Expression::make_temporary_reference(temp, loc);
11040 return this;
11043 // Return the type of a string index.
11045 Type*
11046 String_index_expression::do_type()
11048 if (this->end_ == NULL)
11049 return Type::lookup_integer_type("uint8");
11050 else
11051 return this->string_->type();
11054 // Determine the type of a string index.
11056 void
11057 String_index_expression::do_determine_type(const Type_context*)
11059 this->string_->determine_type_no_context();
11061 Type_context index_context(Type::lookup_integer_type("int"), false);
11062 if (this->start_->is_constant())
11063 this->start_->determine_type(&index_context);
11064 else
11065 this->start_->determine_type_no_context();
11066 if (this->end_ != NULL)
11068 if (this->end_->is_constant())
11069 this->end_->determine_type(&index_context);
11070 else
11071 this->end_->determine_type_no_context();
11075 // Check types of a string index.
11077 void
11078 String_index_expression::do_check_types(Gogo*)
11080 Numeric_constant nc;
11081 unsigned long v;
11082 if (this->start_->type()->integer_type() == NULL
11083 && !this->start_->type()->is_error()
11084 && (!this->start_->numeric_constant_value(&nc)
11085 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11086 this->report_error(_("index must be integer"));
11087 if (this->end_ != NULL
11088 && this->end_->type()->integer_type() == NULL
11089 && !this->end_->type()->is_error()
11090 && !this->end_->is_nil_expression()
11091 && !this->end_->is_error_expression()
11092 && (!this->end_->numeric_constant_value(&nc)
11093 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11094 this->report_error(_("slice end must be integer"));
11096 std::string sval;
11097 bool sval_valid = this->string_->string_constant_value(&sval);
11099 Numeric_constant inc;
11100 mpz_t ival;
11101 bool ival_valid = false;
11102 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11104 ival_valid = true;
11105 if (mpz_sgn(ival) < 0
11106 || (sval_valid
11107 && (this->end_ == NULL
11108 ? mpz_cmp_ui(ival, sval.length()) >= 0
11109 : mpz_cmp_ui(ival, sval.length()) > 0)))
11111 go_error_at(this->start_->location(), "string index out of bounds");
11112 this->set_is_error();
11115 if (this->end_ != NULL && !this->end_->is_nil_expression())
11117 Numeric_constant enc;
11118 mpz_t eval;
11119 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11121 if (mpz_sgn(eval) < 0
11122 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11124 go_error_at(this->end_->location(), "string index out of bounds");
11125 this->set_is_error();
11127 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11128 this->report_error(_("inverted slice range"));
11129 mpz_clear(eval);
11132 if (ival_valid)
11133 mpz_clear(ival);
11136 // Get the backend representation for a string index.
11138 Bexpression*
11139 String_index_expression::do_get_backend(Translate_context* context)
11141 Location loc = this->location();
11142 Expression* string_arg = this->string_;
11143 if (this->string_->type()->points_to() != NULL)
11144 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
11146 Expression* bad_index = Expression::check_bounds(this->start_, loc);
11148 int code = (this->end_ == NULL
11149 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11150 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11152 Gogo* gogo = context->gogo();
11153 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11155 Type* int_type = Type::lookup_integer_type("int");
11157 // It is possible that an error occurred earlier because the start index
11158 // cannot be represented as an integer type. In this case, we shouldn't
11159 // try casting the starting index into an integer since
11160 // Type_conversion_expression will fail to get the backend representation.
11161 // FIXME.
11162 if (this->start_->type()->integer_type() == NULL
11163 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11165 go_assert(saw_errors());
11166 return context->backend()->error_expression();
11169 Expression* start = Expression::make_cast(int_type, this->start_, loc);
11171 if (this->end_ == NULL)
11173 Expression* length =
11174 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11176 Expression* start_too_large =
11177 Expression::make_binary(OPERATOR_GE, start, length, loc);
11178 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11179 bad_index, loc);
11180 Expression* bytes =
11181 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11183 Bexpression* bstart = start->get_backend(context);
11184 Bexpression* ptr = bytes->get_backend(context);
11185 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11186 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11187 Bexpression* index =
11188 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11190 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11191 Bexpression* index_error = bad_index->get_backend(context);
11192 return gogo->backend()->conditional_expression(byte_btype, index_error,
11193 crash, index, loc);
11196 Expression* end = NULL;
11197 if (this->end_->is_nil_expression())
11198 end = Expression::make_integer_sl(-1, int_type, loc);
11199 else
11201 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11202 bad_index =
11203 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11204 end = Expression::make_cast(int_type, this->end_, loc);
11207 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11208 string_arg, start, end);
11209 Bexpression* bstrslice = strslice->get_backend(context);
11211 Btype* str_btype = strslice->type()->get_backend(gogo);
11212 Bexpression* index_error = bad_index->get_backend(context);
11213 return gogo->backend()->conditional_expression(str_btype, index_error,
11214 crash, bstrslice, loc);
11217 // Dump ast representation for a string index expression.
11219 void
11220 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11221 const
11223 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11224 this->start_, this->end_, NULL);
11227 // Make a string index expression. END may be NULL.
11229 Expression*
11230 Expression::make_string_index(Expression* string, Expression* start,
11231 Expression* end, Location location)
11233 return new String_index_expression(string, start, end, location);
11236 // Class Map_index.
11238 // Get the type of the map.
11240 Map_type*
11241 Map_index_expression::get_map_type() const
11243 Map_type* mt = this->map_->type()->map_type();
11244 if (mt == NULL)
11245 go_assert(saw_errors());
11246 return mt;
11249 // Map index traversal.
11252 Map_index_expression::do_traverse(Traverse* traverse)
11254 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11255 return TRAVERSE_EXIT;
11256 return Expression::traverse(&this->index_, traverse);
11259 // We need to pass in a pointer to the key, so flatten the index into a
11260 // temporary variable if it isn't already. The value pointer will be
11261 // dereferenced and checked for nil, so flatten into a temporary to avoid
11262 // recomputation.
11264 Expression*
11265 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11266 Statement_inserter* inserter)
11268 Location loc = this->location();
11269 Map_type* mt = this->get_map_type();
11270 if (this->index()->is_error_expression()
11271 || this->index()->type()->is_error_type()
11272 || mt->is_error_type())
11274 go_assert(saw_errors());
11275 return Expression::make_error(loc);
11278 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
11280 if (this->index_->type()->interface_type() != NULL
11281 && !this->index_->is_variable())
11283 Temporary_statement* temp =
11284 Statement::make_temporary(NULL, this->index_, loc);
11285 inserter->insert(temp);
11286 this->index_ = Expression::make_temporary_reference(temp, loc);
11288 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11289 this->index_, loc);
11292 if (!this->index_->is_variable())
11294 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11295 loc);
11296 inserter->insert(temp);
11297 this->index_ = Expression::make_temporary_reference(temp, loc);
11300 if (this->value_pointer_ == NULL)
11301 this->get_value_pointer(gogo);
11302 if (this->value_pointer_->is_error_expression()
11303 || this->value_pointer_->type()->is_error_type())
11304 return Expression::make_error(loc);
11305 if (!this->value_pointer_->is_variable())
11307 Temporary_statement* temp =
11308 Statement::make_temporary(NULL, this->value_pointer_, loc);
11309 inserter->insert(temp);
11310 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11313 return this;
11316 // Return the type of a map index.
11318 Type*
11319 Map_index_expression::do_type()
11321 Map_type* mt = this->get_map_type();
11322 if (mt == NULL)
11323 return Type::make_error_type();
11324 return mt->val_type();
11327 // Fix the type of a map index.
11329 void
11330 Map_index_expression::do_determine_type(const Type_context*)
11332 this->map_->determine_type_no_context();
11333 Map_type* mt = this->get_map_type();
11334 Type* key_type = mt == NULL ? NULL : mt->key_type();
11335 Type_context subcontext(key_type, false);
11336 this->index_->determine_type(&subcontext);
11339 // Check types of a map index.
11341 void
11342 Map_index_expression::do_check_types(Gogo*)
11344 std::string reason;
11345 Map_type* mt = this->get_map_type();
11346 if (mt == NULL)
11347 return;
11348 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11350 if (reason.empty())
11351 this->report_error(_("incompatible type for map index"));
11352 else
11354 go_error_at(this->location(), "incompatible type for map index (%s)",
11355 reason.c_str());
11356 this->set_is_error();
11361 // Get the backend representation for a map index.
11363 Bexpression*
11364 Map_index_expression::do_get_backend(Translate_context* context)
11366 Map_type* type = this->get_map_type();
11367 if (type == NULL)
11369 go_assert(saw_errors());
11370 return context->backend()->error_expression();
11373 go_assert(this->value_pointer_ != NULL
11374 && this->value_pointer_->is_variable());
11376 Expression* val = Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
11377 this->location());
11378 return val->get_backend(context);
11381 // Get an expression for the map index. This returns an expression
11382 // that evaluates to a pointer to a value. If the key is not in the
11383 // map, the pointer will point to a zero value.
11385 Expression*
11386 Map_index_expression::get_value_pointer(Gogo* gogo)
11388 if (this->value_pointer_ == NULL)
11390 Map_type* type = this->get_map_type();
11391 if (type == NULL)
11393 go_assert(saw_errors());
11394 return Expression::make_error(this->location());
11397 Location loc = this->location();
11398 Expression* map_ref = this->map_;
11400 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11401 this->index_,
11402 loc);
11404 Expression* zero = type->fat_zero_value(gogo);
11406 Expression* map_index;
11408 if (zero == NULL)
11409 map_index =
11410 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11411 Expression::make_type_descriptor(type, loc),
11412 map_ref, index_ptr);
11413 else
11414 map_index =
11415 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11416 Expression::make_type_descriptor(type, loc),
11417 map_ref, index_ptr, zero);
11419 Type* val_type = type->val_type();
11420 this->value_pointer_ =
11421 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
11422 map_index, this->location());
11425 return this->value_pointer_;
11428 // Dump ast representation for a map index expression
11430 void
11431 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11432 const
11434 Index_expression::dump_index_expression(ast_dump_context, this->map_,
11435 this->index_, NULL, NULL);
11438 // Make a map index expression.
11440 Map_index_expression*
11441 Expression::make_map_index(Expression* map, Expression* index,
11442 Location location)
11444 return new Map_index_expression(map, index, location);
11447 // Class Field_reference_expression.
11449 // Lower a field reference expression. There is nothing to lower, but
11450 // this is where we generate the tracking information for fields with
11451 // the magic go:"track" tag.
11453 Expression*
11454 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11455 Statement_inserter* inserter, int)
11457 Struct_type* struct_type = this->expr_->type()->struct_type();
11458 if (struct_type == NULL)
11460 // Error will be reported elsewhere.
11461 return this;
11463 const Struct_field* field = struct_type->field(this->field_index_);
11464 if (field == NULL)
11465 return this;
11466 if (!field->has_tag())
11467 return this;
11468 if (field->tag().find("go:\"track\"") == std::string::npos)
11469 return this;
11471 // References from functions generated by the compiler don't count.
11472 if (function != NULL && function->func_value()->is_type_specific_function())
11473 return this;
11475 // We have found a reference to a tracked field. Build a call to
11476 // the runtime function __go_fieldtrack with a string that describes
11477 // the field. FIXME: We should only call this once per referenced
11478 // field per function, not once for each reference to the field.
11480 if (this->called_fieldtrack_)
11481 return this;
11482 this->called_fieldtrack_ = true;
11484 Location loc = this->location();
11486 std::string s = "fieldtrack \"";
11487 Named_type* nt = this->expr_->type()->named_type();
11488 if (nt == NULL || nt->named_object()->package() == NULL)
11489 s.append(gogo->pkgpath());
11490 else
11491 s.append(nt->named_object()->package()->pkgpath());
11492 s.push_back('.');
11493 if (nt != NULL)
11494 s.append(Gogo::unpack_hidden_name(nt->name()));
11495 s.push_back('.');
11496 s.append(field->field_name());
11497 s.push_back('"');
11499 // We can't use a string here, because internally a string holds a
11500 // pointer to the actual bytes; when the linker garbage collects the
11501 // string, it won't garbage collect the bytes. So we use a
11502 // [...]byte.
11504 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11506 Type* byte_type = gogo->lookup_global("byte")->type_value();
11507 Type* array_type = Type::make_array_type(byte_type, length_expr);
11509 Expression_list* bytes = new Expression_list();
11510 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11512 unsigned char c = static_cast<unsigned char>(*p);
11513 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11516 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11517 bytes, false, loc);
11519 Variable* var = new Variable(array_type, e, true, false, false, loc);
11521 static int count;
11522 char buf[50];
11523 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11524 ++count;
11526 Named_object* no = gogo->add_variable(buf, var);
11527 e = Expression::make_var_reference(no, loc);
11528 e = Expression::make_unary(OPERATOR_AND, e, loc);
11530 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11531 gogo->lower_expression(function, inserter, &call);
11532 inserter->insert(Statement::make_statement(call, false));
11534 // Put this function, and the global variable we just created, into
11535 // unique sections. This will permit the linker to garbage collect
11536 // them if they are not referenced. The effect is that the only
11537 // strings, indicating field references, that will wind up in the
11538 // executable will be those for functions that are actually needed.
11539 if (function != NULL)
11540 function->func_value()->set_in_unique_section();
11541 var->set_in_unique_section();
11543 return this;
11546 // Return the type of a field reference.
11548 Type*
11549 Field_reference_expression::do_type()
11551 Type* type = this->expr_->type();
11552 if (type->is_error())
11553 return type;
11554 Struct_type* struct_type = type->struct_type();
11555 go_assert(struct_type != NULL);
11556 return struct_type->field(this->field_index_)->type();
11559 // Check the types for a field reference.
11561 void
11562 Field_reference_expression::do_check_types(Gogo*)
11564 Type* type = this->expr_->type();
11565 if (type->is_error())
11566 return;
11567 Struct_type* struct_type = type->struct_type();
11568 go_assert(struct_type != NULL);
11569 go_assert(struct_type->field(this->field_index_) != NULL);
11572 // Get the backend representation for a field reference.
11574 Bexpression*
11575 Field_reference_expression::do_get_backend(Translate_context* context)
11577 Bexpression* bstruct = this->expr_->get_backend(context);
11578 return context->gogo()->backend()->struct_field_expression(bstruct,
11579 this->field_index_,
11580 this->location());
11583 // Dump ast representation for a field reference expression.
11585 void
11586 Field_reference_expression::do_dump_expression(
11587 Ast_dump_context* ast_dump_context) const
11589 this->expr_->dump_expression(ast_dump_context);
11590 ast_dump_context->ostream() << "." << this->field_index_;
11593 // Make a reference to a qualified identifier in an expression.
11595 Field_reference_expression*
11596 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11597 Location location)
11599 return new Field_reference_expression(expr, field_index, location);
11602 // Class Interface_field_reference_expression.
11604 // Return an expression for the pointer to the function to call.
11606 Expression*
11607 Interface_field_reference_expression::get_function()
11609 Expression* ref = this->expr_;
11610 Location loc = this->location();
11611 if (ref->type()->points_to() != NULL)
11612 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
11614 Expression* mtable =
11615 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11616 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11618 std::string name = Gogo::unpack_hidden_name(this->name_);
11619 unsigned int index;
11620 const Struct_field* field = mtable_type->find_local_field(name, &index);
11621 go_assert(field != NULL);
11622 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11623 return Expression::make_field_reference(mtable, index, loc);
11626 // Return an expression for the first argument to pass to the interface
11627 // function.
11629 Expression*
11630 Interface_field_reference_expression::get_underlying_object()
11632 Expression* expr = this->expr_;
11633 if (expr->type()->points_to() != NULL)
11634 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11635 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11636 this->location());
11639 // Traversal.
11642 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11644 return Expression::traverse(&this->expr_, traverse);
11647 // Lower the expression. If this expression is not called, we need to
11648 // evaluate the expression twice when converting to the backend
11649 // interface. So introduce a temporary variable if necessary.
11651 Expression*
11652 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
11653 Statement_inserter* inserter)
11655 if (this->expr_->is_error_expression()
11656 || this->expr_->type()->is_error_type())
11658 go_assert(saw_errors());
11659 return Expression::make_error(this->location());
11662 if (!this->expr_->is_variable())
11664 Temporary_statement* temp =
11665 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11666 inserter->insert(temp);
11667 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11668 this->location());
11670 return this;
11673 // Return the type of an interface field reference.
11675 Type*
11676 Interface_field_reference_expression::do_type()
11678 Type* expr_type = this->expr_->type();
11680 Type* points_to = expr_type->points_to();
11681 if (points_to != NULL)
11682 expr_type = points_to;
11684 Interface_type* interface_type = expr_type->interface_type();
11685 if (interface_type == NULL)
11686 return Type::make_error_type();
11688 const Typed_identifier* method = interface_type->find_method(this->name_);
11689 if (method == NULL)
11690 return Type::make_error_type();
11692 return method->type();
11695 // Determine types.
11697 void
11698 Interface_field_reference_expression::do_determine_type(const Type_context*)
11700 this->expr_->determine_type_no_context();
11703 // Check the types for an interface field reference.
11705 void
11706 Interface_field_reference_expression::do_check_types(Gogo*)
11708 Type* type = this->expr_->type();
11710 Type* points_to = type->points_to();
11711 if (points_to != NULL)
11712 type = points_to;
11714 Interface_type* interface_type = type->interface_type();
11715 if (interface_type == NULL)
11717 if (!type->is_error_type())
11718 this->report_error(_("expected interface or pointer to interface"));
11720 else
11722 const Typed_identifier* method =
11723 interface_type->find_method(this->name_);
11724 if (method == NULL)
11726 go_error_at(this->location(), "method %qs not in interface",
11727 Gogo::message_name(this->name_).c_str());
11728 this->set_is_error();
11733 // If an interface field reference is not simply called, then it is
11734 // represented as a closure. The closure will hold a single variable,
11735 // the value of the interface on which the method should be called.
11736 // The function will be a simple thunk that pulls the value from the
11737 // closure and calls the method with the remaining arguments.
11739 // Because method values are not common, we don't build all thunks for
11740 // all possible interface methods, but instead only build them as we
11741 // need them. In particular, we even build them on demand for
11742 // interface methods defined in other packages.
11744 Interface_field_reference_expression::Interface_method_thunks
11745 Interface_field_reference_expression::interface_method_thunks;
11747 // Find or create the thunk to call method NAME on TYPE.
11749 Named_object*
11750 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11751 Interface_type* type,
11752 const std::string& name)
11754 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11755 std::pair<Interface_method_thunks::iterator, bool> ins =
11756 Interface_field_reference_expression::interface_method_thunks.insert(val);
11757 if (ins.second)
11759 // This is the first time we have seen this interface.
11760 ins.first->second = new Method_thunks();
11763 for (Method_thunks::const_iterator p = ins.first->second->begin();
11764 p != ins.first->second->end();
11765 p++)
11766 if (p->first == name)
11767 return p->second;
11769 Location loc = type->location();
11771 const Typed_identifier* method_id = type->find_method(name);
11772 if (method_id == NULL)
11773 return Named_object::make_erroneous_name(Gogo::thunk_name());
11775 Function_type* orig_fntype = method_id->type()->function_type();
11776 if (orig_fntype == NULL)
11777 return Named_object::make_erroneous_name(Gogo::thunk_name());
11779 Struct_field_list* sfl = new Struct_field_list();
11780 // The type here is wrong--it should be the C function type. But it
11781 // doesn't really matter.
11782 Type* vt = Type::make_pointer_type(Type::make_void_type());
11783 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11784 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11785 Type* closure_type = Type::make_struct_type(sfl, loc);
11786 closure_type = Type::make_pointer_type(closure_type);
11788 Function_type* new_fntype = orig_fntype->copy_with_names();
11790 std::string thunk_name = Gogo::thunk_name();
11791 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
11792 false, loc);
11794 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11795 cvar->set_is_used();
11796 cvar->set_is_closure();
11797 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11798 NULL, cvar);
11799 new_no->func_value()->set_closure_var(cp);
11801 gogo->start_block(loc);
11803 // Field 0 of the closure is the function code pointer, field 1 is
11804 // the value on which to invoke the method.
11805 Expression* arg = Expression::make_var_reference(cp, loc);
11806 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11807 arg = Expression::make_field_reference(arg, 1, loc);
11809 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11810 loc);
11812 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11813 Expression_list* args;
11814 if (orig_params == NULL || orig_params->empty())
11815 args = NULL;
11816 else
11818 const Typed_identifier_list* new_params = new_fntype->parameters();
11819 args = new Expression_list();
11820 for (Typed_identifier_list::const_iterator p = new_params->begin();
11821 p != new_params->end();
11822 ++p)
11824 Named_object* p_no = gogo->lookup(p->name(), NULL);
11825 go_assert(p_no != NULL
11826 && p_no->is_variable()
11827 && p_no->var_value()->is_parameter());
11828 args->push_back(Expression::make_var_reference(p_no, loc));
11832 Call_expression* call = Expression::make_call(ifre, args,
11833 orig_fntype->is_varargs(),
11834 loc);
11835 call->set_varargs_are_lowered();
11837 Statement* s = Statement::make_return_from_call(call, loc);
11838 gogo->add_statement(s);
11839 Block* b = gogo->finish_block(loc);
11840 gogo->add_block(b, loc);
11841 gogo->lower_block(new_no, b);
11842 gogo->flatten_block(new_no, b);
11843 gogo->finish_function(loc);
11845 ins.first->second->push_back(std::make_pair(name, new_no));
11846 return new_no;
11849 // Get the backend representation for a method value.
11851 Bexpression*
11852 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11854 Interface_type* type = this->expr_->type()->interface_type();
11855 if (type == NULL)
11857 go_assert(saw_errors());
11858 return context->backend()->error_expression();
11861 Named_object* thunk =
11862 Interface_field_reference_expression::create_thunk(context->gogo(),
11863 type, this->name_);
11864 if (thunk->is_erroneous())
11866 go_assert(saw_errors());
11867 return context->backend()->error_expression();
11870 // FIXME: We should lower this earlier, but we can't it lower it in
11871 // the lowering pass because at that point we don't know whether we
11872 // need to create the thunk or not. If the expression is called, we
11873 // don't need the thunk.
11875 Location loc = this->location();
11877 Struct_field_list* fields = new Struct_field_list();
11878 fields->push_back(Struct_field(Typed_identifier("fn.0",
11879 thunk->func_value()->type(),
11880 loc)));
11881 fields->push_back(Struct_field(Typed_identifier("val.1",
11882 this->expr_->type(),
11883 loc)));
11884 Struct_type* st = Type::make_struct_type(fields, loc);
11886 Expression_list* vals = new Expression_list();
11887 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11888 vals->push_back(this->expr_);
11890 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11891 Bexpression* bclosure =
11892 Expression::make_heap_expression(expr, loc)->get_backend(context);
11894 Expression* nil_check =
11895 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11896 Expression::make_nil(loc), loc);
11897 Bexpression* bnil_check = nil_check->get_backend(context);
11899 Gogo* gogo = context->gogo();
11900 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11901 loc)->get_backend(context);
11903 Bexpression* bcond =
11904 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11905 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11906 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11909 // Dump ast representation for an interface field reference.
11911 void
11912 Interface_field_reference_expression::do_dump_expression(
11913 Ast_dump_context* ast_dump_context) const
11915 this->expr_->dump_expression(ast_dump_context);
11916 ast_dump_context->ostream() << "." << this->name_;
11919 // Make a reference to a field in an interface.
11921 Expression*
11922 Expression::make_interface_field_reference(Expression* expr,
11923 const std::string& field,
11924 Location location)
11926 return new Interface_field_reference_expression(expr, field, location);
11929 // A general selector. This is a Parser_expression for LEFT.NAME. It
11930 // is lowered after we know the type of the left hand side.
11932 class Selector_expression : public Parser_expression
11934 public:
11935 Selector_expression(Expression* left, const std::string& name,
11936 Location location)
11937 : Parser_expression(EXPRESSION_SELECTOR, location),
11938 left_(left), name_(name)
11941 protected:
11943 do_traverse(Traverse* traverse)
11944 { return Expression::traverse(&this->left_, traverse); }
11946 Expression*
11947 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11949 Expression*
11950 do_copy()
11952 return new Selector_expression(this->left_->copy(), this->name_,
11953 this->location());
11956 void
11957 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11959 private:
11960 Expression*
11961 lower_method_expression(Gogo*);
11963 // The expression on the left hand side.
11964 Expression* left_;
11965 // The name on the right hand side.
11966 std::string name_;
11969 // Lower a selector expression once we know the real type of the left
11970 // hand side.
11972 Expression*
11973 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11974 int)
11976 Expression* left = this->left_;
11977 if (left->is_type_expression())
11978 return this->lower_method_expression(gogo);
11979 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11980 this->location());
11983 // Lower a method expression T.M or (*T).M. We turn this into a
11984 // function literal.
11986 Expression*
11987 Selector_expression::lower_method_expression(Gogo* gogo)
11989 Location location = this->location();
11990 Type* left_type = this->left_->type();
11991 Type* type = left_type;
11992 const std::string& name(this->name_);
11994 bool is_pointer;
11995 if (type->points_to() == NULL)
11996 is_pointer = false;
11997 else
11999 is_pointer = true;
12000 type = type->points_to();
12002 Named_type* nt = type->named_type();
12003 if (nt == NULL)
12005 go_error_at(location,
12006 ("method expression requires named type or "
12007 "pointer to named type"));
12008 return Expression::make_error(location);
12011 bool is_ambiguous;
12012 Method* method = nt->method_function(name, &is_ambiguous);
12013 const Typed_identifier* imethod = NULL;
12014 if (method == NULL && !is_pointer)
12016 Interface_type* it = nt->interface_type();
12017 if (it != NULL)
12018 imethod = it->find_method(name);
12021 if ((method == NULL && imethod == NULL)
12022 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12024 if (!is_ambiguous)
12025 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12026 is_pointer ? "*" : "",
12027 nt->message_name().c_str(),
12028 Gogo::message_name(name).c_str());
12029 else
12030 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12031 Gogo::message_name(name).c_str(),
12032 is_pointer ? "*" : "",
12033 nt->message_name().c_str());
12034 return Expression::make_error(location);
12037 if (method != NULL && !is_pointer && !method->is_value_method())
12039 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12040 nt->message_name().c_str(),
12041 Gogo::message_name(name).c_str());
12042 return Expression::make_error(location);
12045 // Build a new function type in which the receiver becomes the first
12046 // argument.
12047 Function_type* method_type;
12048 if (method != NULL)
12050 method_type = method->type();
12051 go_assert(method_type->is_method());
12053 else
12055 method_type = imethod->type()->function_type();
12056 go_assert(method_type != NULL && !method_type->is_method());
12059 const char* const receiver_name = "$this";
12060 Typed_identifier_list* parameters = new Typed_identifier_list();
12061 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12062 location));
12064 const Typed_identifier_list* method_parameters = method_type->parameters();
12065 if (method_parameters != NULL)
12067 int i = 0;
12068 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12069 p != method_parameters->end();
12070 ++p, ++i)
12072 if (!p->name().empty())
12073 parameters->push_back(*p);
12074 else
12076 char buf[20];
12077 snprintf(buf, sizeof buf, "$param%d", i);
12078 parameters->push_back(Typed_identifier(buf, p->type(),
12079 p->location()));
12084 const Typed_identifier_list* method_results = method_type->results();
12085 Typed_identifier_list* results;
12086 if (method_results == NULL)
12087 results = NULL;
12088 else
12090 results = new Typed_identifier_list();
12091 for (Typed_identifier_list::const_iterator p = method_results->begin();
12092 p != method_results->end();
12093 ++p)
12094 results->push_back(*p);
12097 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12098 location);
12099 if (method_type->is_varargs())
12100 fntype->set_is_varargs();
12102 // We generate methods which always takes a pointer to the receiver
12103 // as their first argument. If this is for a pointer type, we can
12104 // simply reuse the existing function. We use an internal hack to
12105 // get the right type.
12106 // FIXME: This optimization is disabled because it doesn't yet work
12107 // with function descriptors when the method expression is not
12108 // directly called.
12109 if (method != NULL && is_pointer && false)
12111 Named_object* mno = (method->needs_stub_method()
12112 ? method->stub_object()
12113 : method->named_object());
12114 Expression* f = Expression::make_func_reference(mno, NULL, location);
12115 f = Expression::make_cast(fntype, f, location);
12116 Type_conversion_expression* tce =
12117 static_cast<Type_conversion_expression*>(f);
12118 tce->set_may_convert_function_types();
12119 return f;
12122 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
12123 location);
12125 Named_object* vno = gogo->lookup(receiver_name, NULL);
12126 go_assert(vno != NULL);
12127 Expression* ve = Expression::make_var_reference(vno, location);
12128 Expression* bm;
12129 if (method != NULL)
12130 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12131 else
12132 bm = Expression::make_interface_field_reference(ve, name, location);
12134 // Even though we found the method above, if it has an error type we
12135 // may see an error here.
12136 if (bm->is_error_expression())
12138 gogo->finish_function(location);
12139 return bm;
12142 Expression_list* args;
12143 if (parameters->size() <= 1)
12144 args = NULL;
12145 else
12147 args = new Expression_list();
12148 Typed_identifier_list::const_iterator p = parameters->begin();
12149 ++p;
12150 for (; p != parameters->end(); ++p)
12152 vno = gogo->lookup(p->name(), NULL);
12153 go_assert(vno != NULL);
12154 args->push_back(Expression::make_var_reference(vno, location));
12158 gogo->start_block(location);
12160 Call_expression* call = Expression::make_call(bm, args,
12161 method_type->is_varargs(),
12162 location);
12164 Statement* s = Statement::make_return_from_call(call, location);
12165 gogo->add_statement(s);
12167 Block* b = gogo->finish_block(location);
12169 gogo->add_block(b, location);
12171 // Lower the call in case there are multiple results.
12172 gogo->lower_block(no, b);
12173 gogo->flatten_block(no, b);
12175 gogo->finish_function(location);
12177 return Expression::make_func_reference(no, NULL, location);
12180 // Dump the ast for a selector expression.
12182 void
12183 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12184 const
12186 ast_dump_context->dump_expression(this->left_);
12187 ast_dump_context->ostream() << ".";
12188 ast_dump_context->ostream() << this->name_;
12191 // Make a selector expression.
12193 Expression*
12194 Expression::make_selector(Expression* left, const std::string& name,
12195 Location location)
12197 return new Selector_expression(left, name, location);
12200 // Class Allocation_expression.
12203 Allocation_expression::do_traverse(Traverse* traverse)
12205 return Type::traverse(this->type_, traverse);
12208 Type*
12209 Allocation_expression::do_type()
12211 return Type::make_pointer_type(this->type_);
12214 // Make a copy of an allocation expression.
12216 Expression*
12217 Allocation_expression::do_copy()
12219 Allocation_expression* alloc =
12220 new Allocation_expression(this->type_, this->location());
12221 if (this->allocate_on_stack_)
12222 alloc->set_allocate_on_stack();
12223 return alloc;
12226 // Return the backend representation for an allocation expression.
12228 Bexpression*
12229 Allocation_expression::do_get_backend(Translate_context* context)
12231 Gogo* gogo = context->gogo();
12232 Location loc = this->location();
12234 Node* n = Node::make_node(this);
12235 if (this->allocate_on_stack_
12236 || (n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
12238 int64_t size;
12239 bool ok = this->type_->backend_type_size(gogo, &size);
12240 if (!ok)
12242 go_assert(saw_errors());
12243 return gogo->backend()->error_expression();
12245 return gogo->backend()->stack_allocation_expression(size, loc);
12248 Btype* btype = this->type_->get_backend(gogo);
12249 Bexpression* space =
12250 gogo->allocate_memory(this->type_, loc)->get_backend(context);
12251 Btype* pbtype = gogo->backend()->pointer_type(btype);
12252 return gogo->backend()->convert_expression(pbtype, space, loc);
12255 // Dump ast representation for an allocation expression.
12257 void
12258 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12259 const
12261 ast_dump_context->ostream() << "new(";
12262 ast_dump_context->dump_type(this->type_);
12263 ast_dump_context->ostream() << ")";
12266 // Make an allocation expression.
12268 Expression*
12269 Expression::make_allocation(Type* type, Location location)
12271 return new Allocation_expression(type, location);
12274 // Class Ordered_value_list.
12277 Ordered_value_list::traverse_vals(Traverse* traverse)
12279 if (this->vals_ != NULL)
12281 if (this->traverse_order_ == NULL)
12283 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12284 return TRAVERSE_EXIT;
12286 else
12288 for (std::vector<unsigned long>::const_iterator p =
12289 this->traverse_order_->begin();
12290 p != this->traverse_order_->end();
12291 ++p)
12293 if (Expression::traverse(&this->vals_->at(*p), traverse)
12294 == TRAVERSE_EXIT)
12295 return TRAVERSE_EXIT;
12299 return TRAVERSE_CONTINUE;
12302 // Class Struct_construction_expression.
12304 // Traversal.
12307 Struct_construction_expression::do_traverse(Traverse* traverse)
12309 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12310 return TRAVERSE_EXIT;
12311 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12312 return TRAVERSE_EXIT;
12313 return TRAVERSE_CONTINUE;
12316 // Return whether this is a constant initializer.
12318 bool
12319 Struct_construction_expression::is_constant_struct() const
12321 if (this->vals() == NULL)
12322 return true;
12323 for (Expression_list::const_iterator pv = this->vals()->begin();
12324 pv != this->vals()->end();
12325 ++pv)
12327 if (*pv != NULL
12328 && !(*pv)->is_constant()
12329 && (!(*pv)->is_composite_literal()
12330 || (*pv)->is_nonconstant_composite_literal()))
12331 return false;
12334 const Struct_field_list* fields = this->type_->struct_type()->fields();
12335 for (Struct_field_list::const_iterator pf = fields->begin();
12336 pf != fields->end();
12337 ++pf)
12339 // There are no constant constructors for interfaces.
12340 if (pf->type()->interface_type() != NULL)
12341 return false;
12344 return true;
12347 // Return whether this struct can be used as a constant initializer.
12349 bool
12350 Struct_construction_expression::do_is_static_initializer() const
12352 if (this->vals() == NULL)
12353 return true;
12354 for (Expression_list::const_iterator pv = this->vals()->begin();
12355 pv != this->vals()->end();
12356 ++pv)
12358 if (*pv != NULL && !(*pv)->is_static_initializer())
12359 return false;
12361 return true;
12364 // Final type determination.
12366 void
12367 Struct_construction_expression::do_determine_type(const Type_context*)
12369 if (this->vals() == NULL)
12370 return;
12371 const Struct_field_list* fields = this->type_->struct_type()->fields();
12372 Expression_list::const_iterator pv = this->vals()->begin();
12373 for (Struct_field_list::const_iterator pf = fields->begin();
12374 pf != fields->end();
12375 ++pf, ++pv)
12377 if (pv == this->vals()->end())
12378 return;
12379 if (*pv != NULL)
12381 Type_context subcontext(pf->type(), false);
12382 (*pv)->determine_type(&subcontext);
12385 // Extra values are an error we will report elsewhere; we still want
12386 // to determine the type to avoid knockon errors.
12387 for (; pv != this->vals()->end(); ++pv)
12388 (*pv)->determine_type_no_context();
12391 // Check types.
12393 void
12394 Struct_construction_expression::do_check_types(Gogo*)
12396 if (this->vals() == NULL)
12397 return;
12399 Struct_type* st = this->type_->struct_type();
12400 if (this->vals()->size() > st->field_count())
12402 this->report_error(_("too many expressions for struct"));
12403 return;
12406 const Struct_field_list* fields = st->fields();
12407 Expression_list::const_iterator pv = this->vals()->begin();
12408 int i = 0;
12409 for (Struct_field_list::const_iterator pf = fields->begin();
12410 pf != fields->end();
12411 ++pf, ++pv, ++i)
12413 if (pv == this->vals()->end())
12415 this->report_error(_("too few expressions for struct"));
12416 break;
12419 if (*pv == NULL)
12420 continue;
12422 std::string reason;
12423 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12425 if (reason.empty())
12426 go_error_at((*pv)->location(),
12427 "incompatible type for field %d in struct construction",
12428 i + 1);
12429 else
12430 go_error_at((*pv)->location(),
12431 ("incompatible type for field %d in "
12432 "struct construction (%s)"),
12433 i + 1, reason.c_str());
12434 this->set_is_error();
12437 go_assert(pv == this->vals()->end());
12440 // Flatten a struct construction expression. Store the values into
12441 // temporaries in case they need interface conversion.
12443 Expression*
12444 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
12445 Statement_inserter* inserter)
12447 if (this->vals() == NULL)
12448 return this;
12450 // If this is a constant struct, we don't need temporaries.
12451 if (this->is_constant_struct())
12452 return this;
12454 Location loc = this->location();
12455 for (Expression_list::iterator pv = this->vals()->begin();
12456 pv != this->vals()->end();
12457 ++pv)
12459 if (*pv != NULL)
12461 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12463 go_assert(saw_errors());
12464 return Expression::make_error(loc);
12466 if (!(*pv)->is_variable())
12468 Temporary_statement* temp =
12469 Statement::make_temporary(NULL, *pv, loc);
12470 inserter->insert(temp);
12471 *pv = Expression::make_temporary_reference(temp, loc);
12475 return this;
12478 // Return the backend representation for constructing a struct.
12480 Bexpression*
12481 Struct_construction_expression::do_get_backend(Translate_context* context)
12483 Gogo* gogo = context->gogo();
12485 Btype* btype = this->type_->get_backend(gogo);
12486 if (this->vals() == NULL)
12487 return gogo->backend()->zero_expression(btype);
12489 const Struct_field_list* fields = this->type_->struct_type()->fields();
12490 Expression_list::const_iterator pv = this->vals()->begin();
12491 std::vector<Bexpression*> init;
12492 for (Struct_field_list::const_iterator pf = fields->begin();
12493 pf != fields->end();
12494 ++pf)
12496 Btype* fbtype = pf->type()->get_backend(gogo);
12497 if (pv == this->vals()->end())
12498 init.push_back(gogo->backend()->zero_expression(fbtype));
12499 else if (*pv == NULL)
12501 init.push_back(gogo->backend()->zero_expression(fbtype));
12502 ++pv;
12504 else
12506 Expression* val =
12507 Expression::convert_for_assignment(gogo, pf->type(),
12508 *pv, this->location());
12509 init.push_back(val->get_backend(context));
12510 ++pv;
12513 return gogo->backend()->constructor_expression(btype, init, this->location());
12516 // Export a struct construction.
12518 void
12519 Struct_construction_expression::do_export(Export* exp) const
12521 exp->write_c_string("convert(");
12522 exp->write_type(this->type_);
12523 for (Expression_list::const_iterator pv = this->vals()->begin();
12524 pv != this->vals()->end();
12525 ++pv)
12527 exp->write_c_string(", ");
12528 if (*pv != NULL)
12529 (*pv)->export_expression(exp);
12531 exp->write_c_string(")");
12534 // Dump ast representation of a struct construction expression.
12536 void
12537 Struct_construction_expression::do_dump_expression(
12538 Ast_dump_context* ast_dump_context) const
12540 ast_dump_context->dump_type(this->type_);
12541 ast_dump_context->ostream() << "{";
12542 ast_dump_context->dump_expression_list(this->vals());
12543 ast_dump_context->ostream() << "}";
12546 // Make a struct composite literal. This used by the thunk code.
12548 Expression*
12549 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12550 Location location)
12552 go_assert(type->struct_type() != NULL);
12553 return new Struct_construction_expression(type, vals, location);
12556 // Class Array_construction_expression.
12558 // Traversal.
12561 Array_construction_expression::do_traverse(Traverse* traverse)
12563 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12564 return TRAVERSE_EXIT;
12565 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12566 return TRAVERSE_EXIT;
12567 return TRAVERSE_CONTINUE;
12570 // Return whether this is a constant initializer.
12572 bool
12573 Array_construction_expression::is_constant_array() const
12575 if (this->vals() == NULL)
12576 return true;
12578 // There are no constant constructors for interfaces.
12579 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12580 return false;
12582 for (Expression_list::const_iterator pv = this->vals()->begin();
12583 pv != this->vals()->end();
12584 ++pv)
12586 if (*pv != NULL
12587 && !(*pv)->is_constant()
12588 && (!(*pv)->is_composite_literal()
12589 || (*pv)->is_nonconstant_composite_literal()))
12590 return false;
12592 return true;
12595 // Return whether this can be used a constant initializer.
12597 bool
12598 Array_construction_expression::do_is_static_initializer() const
12600 if (this->vals() == NULL)
12601 return true;
12602 for (Expression_list::const_iterator pv = this->vals()->begin();
12603 pv != this->vals()->end();
12604 ++pv)
12606 if (*pv != NULL && !(*pv)->is_static_initializer())
12607 return false;
12609 return true;
12612 // Final type determination.
12614 void
12615 Array_construction_expression::do_determine_type(const Type_context*)
12617 if (this->vals() == NULL)
12618 return;
12619 Type_context subcontext(this->type_->array_type()->element_type(), false);
12620 for (Expression_list::const_iterator pv = this->vals()->begin();
12621 pv != this->vals()->end();
12622 ++pv)
12624 if (*pv != NULL)
12625 (*pv)->determine_type(&subcontext);
12629 // Check types.
12631 void
12632 Array_construction_expression::do_check_types(Gogo*)
12634 if (this->vals() == NULL)
12635 return;
12637 Array_type* at = this->type_->array_type();
12638 int i = 0;
12639 Type* element_type = at->element_type();
12640 for (Expression_list::const_iterator pv = this->vals()->begin();
12641 pv != this->vals()->end();
12642 ++pv, ++i)
12644 if (*pv != NULL
12645 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12647 go_error_at((*pv)->location(),
12648 "incompatible type for element %d in composite literal",
12649 i + 1);
12650 this->set_is_error();
12655 // Flatten an array construction expression. Store the values into
12656 // temporaries in case they need interface conversion.
12658 Expression*
12659 Array_construction_expression::do_flatten(Gogo*, Named_object*,
12660 Statement_inserter* inserter)
12662 if (this->vals() == NULL)
12663 return this;
12665 // If this is a constant array, we don't need temporaries.
12666 if (this->is_constant_array())
12667 return this;
12669 Location loc = this->location();
12670 for (Expression_list::iterator pv = this->vals()->begin();
12671 pv != this->vals()->end();
12672 ++pv)
12674 if (*pv != NULL)
12676 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
12678 go_assert(saw_errors());
12679 return Expression::make_error(loc);
12681 if (!(*pv)->is_variable())
12683 Temporary_statement* temp =
12684 Statement::make_temporary(NULL, *pv, loc);
12685 inserter->insert(temp);
12686 *pv = Expression::make_temporary_reference(temp, loc);
12690 return this;
12693 // Get a constructor expression for the array values.
12695 Bexpression*
12696 Array_construction_expression::get_constructor(Translate_context* context,
12697 Btype* array_btype)
12699 Type* element_type = this->type_->array_type()->element_type();
12701 std::vector<unsigned long> indexes;
12702 std::vector<Bexpression*> vals;
12703 Gogo* gogo = context->gogo();
12704 if (this->vals() != NULL)
12706 size_t i = 0;
12707 std::vector<unsigned long>::const_iterator pi;
12708 if (this->indexes_ != NULL)
12709 pi = this->indexes_->begin();
12710 for (Expression_list::const_iterator pv = this->vals()->begin();
12711 pv != this->vals()->end();
12712 ++pv, ++i)
12714 if (this->indexes_ != NULL)
12715 go_assert(pi != this->indexes_->end());
12717 if (this->indexes_ == NULL)
12718 indexes.push_back(i);
12719 else
12720 indexes.push_back(*pi);
12721 if (*pv == NULL)
12723 Btype* ebtype = element_type->get_backend(gogo);
12724 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12725 vals.push_back(zv);
12727 else
12729 Expression* val_expr =
12730 Expression::convert_for_assignment(gogo, element_type, *pv,
12731 this->location());
12732 vals.push_back(val_expr->get_backend(context));
12734 if (this->indexes_ != NULL)
12735 ++pi;
12737 if (this->indexes_ != NULL)
12738 go_assert(pi == this->indexes_->end());
12740 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12741 vals, this->location());
12744 // Export an array construction.
12746 void
12747 Array_construction_expression::do_export(Export* exp) const
12749 exp->write_c_string("convert(");
12750 exp->write_type(this->type_);
12751 if (this->vals() != NULL)
12753 std::vector<unsigned long>::const_iterator pi;
12754 if (this->indexes_ != NULL)
12755 pi = this->indexes_->begin();
12756 for (Expression_list::const_iterator pv = this->vals()->begin();
12757 pv != this->vals()->end();
12758 ++pv)
12760 exp->write_c_string(", ");
12762 if (this->indexes_ != NULL)
12764 char buf[100];
12765 snprintf(buf, sizeof buf, "%lu", *pi);
12766 exp->write_c_string(buf);
12767 exp->write_c_string(":");
12770 if (*pv != NULL)
12771 (*pv)->export_expression(exp);
12773 if (this->indexes_ != NULL)
12774 ++pi;
12777 exp->write_c_string(")");
12780 // Dump ast representation of an array construction expression.
12782 void
12783 Array_construction_expression::do_dump_expression(
12784 Ast_dump_context* ast_dump_context) const
12786 Expression* length = this->type_->array_type()->length();
12788 ast_dump_context->ostream() << "[" ;
12789 if (length != NULL)
12791 ast_dump_context->dump_expression(length);
12793 ast_dump_context->ostream() << "]" ;
12794 ast_dump_context->dump_type(this->type_);
12795 this->dump_slice_storage_expression(ast_dump_context);
12796 ast_dump_context->ostream() << "{" ;
12797 if (this->indexes_ == NULL)
12798 ast_dump_context->dump_expression_list(this->vals());
12799 else
12801 Expression_list::const_iterator pv = this->vals()->begin();
12802 for (std::vector<unsigned long>::const_iterator pi =
12803 this->indexes_->begin();
12804 pi != this->indexes_->end();
12805 ++pi, ++pv)
12807 if (pi != this->indexes_->begin())
12808 ast_dump_context->ostream() << ", ";
12809 ast_dump_context->ostream() << *pi << ':';
12810 ast_dump_context->dump_expression(*pv);
12813 ast_dump_context->ostream() << "}" ;
12817 // Class Fixed_array_construction_expression.
12819 Fixed_array_construction_expression::Fixed_array_construction_expression(
12820 Type* type, const std::vector<unsigned long>* indexes,
12821 Expression_list* vals, Location location)
12822 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12823 type, indexes, vals, location)
12824 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12826 // Return the backend representation for constructing a fixed array.
12828 Bexpression*
12829 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
12831 Type* type = this->type();
12832 Btype* btype = type->get_backend(context->gogo());
12833 return this->get_constructor(context, btype);
12836 Expression*
12837 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12838 Location location)
12840 go_assert(type->array_type() != NULL && !type->is_slice_type());
12841 return new Fixed_array_construction_expression(type, NULL, vals, location);
12844 // Class Slice_construction_expression.
12846 Slice_construction_expression::Slice_construction_expression(
12847 Type* type, const std::vector<unsigned long>* indexes,
12848 Expression_list* vals, Location location)
12849 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12850 type, indexes, vals, location),
12851 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
12852 storage_escapes_(true)
12854 go_assert(type->is_slice_type());
12856 unsigned long lenval;
12857 Expression* length;
12858 if (vals == NULL || vals->empty())
12859 lenval = 0;
12860 else
12862 if (this->indexes() == NULL)
12863 lenval = vals->size();
12864 else
12865 lenval = indexes->back() + 1;
12867 Type* int_type = Type::lookup_integer_type("int");
12868 length = Expression::make_integer_ul(lenval, int_type, location);
12869 Type* element_type = type->array_type()->element_type();
12870 this->valtype_ = Type::make_array_type(element_type, length);
12873 // Traversal.
12876 Slice_construction_expression::do_traverse(Traverse* traverse)
12878 if (this->Array_construction_expression::do_traverse(traverse)
12879 == TRAVERSE_EXIT)
12880 return TRAVERSE_EXIT;
12881 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12882 return TRAVERSE_EXIT;
12883 if (this->array_val_ != NULL
12884 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
12885 return TRAVERSE_EXIT;
12886 if (this->slice_storage_ != NULL
12887 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
12888 return TRAVERSE_EXIT;
12889 return TRAVERSE_CONTINUE;
12892 // Helper routine to create fixed array value underlying the slice literal.
12893 // May be called during flattening, or later during do_get_backend().
12895 Expression*
12896 Slice_construction_expression::create_array_val()
12898 Array_type* array_type = this->type()->array_type();
12899 if (array_type == NULL)
12901 go_assert(this->type()->is_error());
12902 return NULL;
12905 Location loc = this->location();
12906 go_assert(this->valtype_ != NULL);
12908 Expression_list* vals = this->vals();
12909 if (this->vals() == NULL || this->vals()->empty())
12911 // We need to create a unique value for the empty array literal.
12912 vals = new Expression_list;
12913 vals->push_back(NULL);
12915 return new Fixed_array_construction_expression(
12916 this->valtype_, this->indexes(), vals, loc);
12919 // If we're previous established that the slice storage does not
12920 // escape, then create a separate array temp val here for it. We
12921 // need to do this as part of flattening so as to be able to insert
12922 // the new temp statement.
12924 Expression*
12925 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
12926 Statement_inserter* inserter)
12928 if (this->type()->array_type() == NULL)
12929 return NULL;
12931 // Base class flattening first
12932 this->Array_construction_expression::do_flatten(gogo, no, inserter);
12934 // Create an stack-allocated storage temp if storage won't escape
12935 if (!this->storage_escapes_)
12937 Location loc = this->location();
12938 this->array_val_ = create_array_val();
12939 go_assert(this->array_val_);
12940 Temporary_statement* temp =
12941 Statement::make_temporary(this->valtype_, this->array_val_, loc);
12942 inserter->insert(temp);
12943 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
12945 return this;
12948 // When dumping a slice construction expression that has an explicit
12949 // storeage temp, emit the temp here (if we don't do this the storage
12950 // temp appears unused in the AST dump).
12952 void
12953 Slice_construction_expression::
12954 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
12956 if (this->slice_storage_ == NULL)
12957 return;
12958 ast_dump_context->ostream() << "storage=" ;
12959 ast_dump_context->dump_expression(this->slice_storage_);
12962 // Return the backend representation for constructing a slice.
12964 Bexpression*
12965 Slice_construction_expression::do_get_backend(Translate_context* context)
12967 if (this->array_val_ == NULL)
12968 this->array_val_ = create_array_val();
12969 if (this->array_val_ == NULL)
12971 go_assert(this->type()->is_error());
12972 return context->backend()->error_expression();
12975 Location loc = this->location();
12977 bool is_static_initializer = this->array_val_->is_static_initializer();
12979 // We have to copy the initial values into heap memory if we are in
12980 // a function or if the values are not constants.
12981 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
12983 Expression* space;
12985 if (this->slice_storage_ != NULL)
12987 go_assert(!this->storage_escapes_);
12988 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
12990 else if (!copy_to_heap)
12992 // The initializer will only run once.
12993 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
12994 space->unary_expression()->set_is_slice_init();
12996 else
12998 space = Expression::make_heap_expression(this->array_val_, loc);
12999 Node* n = Node::make_node(this);
13000 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
13002 n = Node::make_node(space);
13003 n->set_encoding(Node::ESCAPE_NONE);
13007 // Build a constructor for the slice.
13008 Expression* len = this->valtype_->array_type()->length();
13009 Expression* slice_val =
13010 Expression::make_slice_value(this->type(), space, len, len, loc);
13011 return slice_val->get_backend(context);
13014 // Make a slice composite literal. This is used by the type
13015 // descriptor code.
13017 Slice_construction_expression*
13018 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13019 Location location)
13021 go_assert(type->is_slice_type());
13022 return new Slice_construction_expression(type, NULL, vals, location);
13025 // Class Map_construction_expression.
13027 // Traversal.
13030 Map_construction_expression::do_traverse(Traverse* traverse)
13032 if (this->vals_ != NULL
13033 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13034 return TRAVERSE_EXIT;
13035 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13036 return TRAVERSE_EXIT;
13037 return TRAVERSE_CONTINUE;
13040 // Flatten constructor initializer into a temporary variable since
13041 // we need to take its address for __go_construct_map.
13043 Expression*
13044 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13045 Statement_inserter* inserter)
13047 if (!this->is_error_expression()
13048 && this->vals_ != NULL
13049 && !this->vals_->empty()
13050 && this->constructor_temp_ == NULL)
13052 Map_type* mt = this->type_->map_type();
13053 Type* key_type = mt->key_type();
13054 Type* val_type = mt->val_type();
13055 this->element_type_ = Type::make_builtin_struct_type(2,
13056 "__key", key_type,
13057 "__val", val_type);
13059 Expression_list* value_pairs = new Expression_list();
13060 Location loc = this->location();
13062 size_t i = 0;
13063 for (Expression_list::const_iterator pv = this->vals_->begin();
13064 pv != this->vals_->end();
13065 ++pv, ++i)
13067 Expression_list* key_value_pair = new Expression_list();
13068 Expression* key = *pv;
13069 if (key->is_error_expression() || key->type()->is_error_type())
13071 go_assert(saw_errors());
13072 return Expression::make_error(loc);
13074 if (key->type()->interface_type() != NULL && !key->is_variable())
13076 Temporary_statement* temp =
13077 Statement::make_temporary(NULL, key, loc);
13078 inserter->insert(temp);
13079 key = Expression::make_temporary_reference(temp, loc);
13081 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13083 ++pv;
13084 Expression* val = *pv;
13085 if (val->is_error_expression() || val->type()->is_error_type())
13087 go_assert(saw_errors());
13088 return Expression::make_error(loc);
13090 if (val->type()->interface_type() != NULL && !val->is_variable())
13092 Temporary_statement* temp =
13093 Statement::make_temporary(NULL, val, loc);
13094 inserter->insert(temp);
13095 val = Expression::make_temporary_reference(temp, loc);
13097 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13099 key_value_pair->push_back(key);
13100 key_value_pair->push_back(val);
13101 value_pairs->push_back(
13102 Expression::make_struct_composite_literal(this->element_type_,
13103 key_value_pair, loc));
13106 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13107 Type* ctor_type =
13108 Type::make_array_type(this->element_type_, element_count);
13109 Expression* constructor =
13110 new Fixed_array_construction_expression(ctor_type, NULL,
13111 value_pairs, loc);
13113 this->constructor_temp_ =
13114 Statement::make_temporary(NULL, constructor, loc);
13115 constructor->issue_nil_check();
13116 this->constructor_temp_->set_is_address_taken();
13117 inserter->insert(this->constructor_temp_);
13120 return this;
13123 // Final type determination.
13125 void
13126 Map_construction_expression::do_determine_type(const Type_context*)
13128 if (this->vals_ == NULL)
13129 return;
13131 Map_type* mt = this->type_->map_type();
13132 Type_context key_context(mt->key_type(), false);
13133 Type_context val_context(mt->val_type(), false);
13134 for (Expression_list::const_iterator pv = this->vals_->begin();
13135 pv != this->vals_->end();
13136 ++pv)
13138 (*pv)->determine_type(&key_context);
13139 ++pv;
13140 (*pv)->determine_type(&val_context);
13144 // Check types.
13146 void
13147 Map_construction_expression::do_check_types(Gogo*)
13149 if (this->vals_ == NULL)
13150 return;
13152 Map_type* mt = this->type_->map_type();
13153 int i = 0;
13154 Type* key_type = mt->key_type();
13155 Type* val_type = mt->val_type();
13156 for (Expression_list::const_iterator pv = this->vals_->begin();
13157 pv != this->vals_->end();
13158 ++pv, ++i)
13160 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13162 go_error_at((*pv)->location(),
13163 "incompatible type for element %d key in map construction",
13164 i + 1);
13165 this->set_is_error();
13167 ++pv;
13168 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13170 go_error_at((*pv)->location(),
13171 ("incompatible type for element %d value "
13172 "in map construction"),
13173 i + 1);
13174 this->set_is_error();
13179 // Return the backend representation for constructing a map.
13181 Bexpression*
13182 Map_construction_expression::do_get_backend(Translate_context* context)
13184 if (this->is_error_expression())
13185 return context->backend()->error_expression();
13186 Location loc = this->location();
13188 size_t i = 0;
13189 Expression* ventries;
13190 if (this->vals_ == NULL || this->vals_->empty())
13191 ventries = Expression::make_nil(loc);
13192 else
13194 go_assert(this->constructor_temp_ != NULL);
13195 i = this->vals_->size() / 2;
13197 Expression* ctor_ref =
13198 Expression::make_temporary_reference(this->constructor_temp_, loc);
13199 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13202 Map_type* mt = this->type_->map_type();
13203 if (this->element_type_ == NULL)
13204 this->element_type_ =
13205 Type::make_builtin_struct_type(2,
13206 "__key", mt->key_type(),
13207 "__val", mt->val_type());
13208 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13210 Type* uintptr_t = Type::lookup_integer_type("uintptr");
13211 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13213 Expression* entry_size =
13214 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13216 unsigned int field_index;
13217 const Struct_field* valfield =
13218 this->element_type_->find_local_field("__val", &field_index);
13219 Expression* val_offset =
13220 Expression::make_struct_field_offset(this->element_type_, valfield);
13222 Expression* map_ctor =
13223 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13224 entry_size, val_offset, ventries);
13225 return map_ctor->get_backend(context);
13228 // Export an array construction.
13230 void
13231 Map_construction_expression::do_export(Export* exp) const
13233 exp->write_c_string("convert(");
13234 exp->write_type(this->type_);
13235 for (Expression_list::const_iterator pv = this->vals_->begin();
13236 pv != this->vals_->end();
13237 ++pv)
13239 exp->write_c_string(", ");
13240 (*pv)->export_expression(exp);
13242 exp->write_c_string(")");
13245 // Dump ast representation for a map construction expression.
13247 void
13248 Map_construction_expression::do_dump_expression(
13249 Ast_dump_context* ast_dump_context) const
13251 ast_dump_context->ostream() << "{" ;
13252 ast_dump_context->dump_expression_list(this->vals_, true);
13253 ast_dump_context->ostream() << "}";
13256 // Class Composite_literal_expression.
13258 // Traversal.
13261 Composite_literal_expression::do_traverse(Traverse* traverse)
13263 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13264 return TRAVERSE_EXIT;
13266 // If this is a struct composite literal with keys, then the keys
13267 // are field names, not expressions. We don't want to traverse them
13268 // in that case. If we do, we can give an erroneous error "variable
13269 // initializer refers to itself." See bug482.go in the testsuite.
13270 if (this->has_keys_ && this->vals_ != NULL)
13272 // The type may not be resolvable at this point.
13273 Type* type = this->type_;
13275 for (int depth = 0; depth < this->depth_; ++depth)
13277 if (type->array_type() != NULL)
13278 type = type->array_type()->element_type();
13279 else if (type->map_type() != NULL)
13281 if (this->key_path_[depth])
13282 type = type->map_type()->key_type();
13283 else
13284 type = type->map_type()->val_type();
13286 else
13288 // This error will be reported during lowering.
13289 return TRAVERSE_CONTINUE;
13293 while (true)
13295 if (type->classification() == Type::TYPE_NAMED)
13296 type = type->named_type()->real_type();
13297 else if (type->classification() == Type::TYPE_FORWARD)
13299 Type* t = type->forwarded();
13300 if (t == type)
13301 break;
13302 type = t;
13304 else
13305 break;
13308 if (type->classification() == Type::TYPE_STRUCT)
13310 Expression_list::iterator p = this->vals_->begin();
13311 while (p != this->vals_->end())
13313 // Skip key.
13314 ++p;
13315 go_assert(p != this->vals_->end());
13316 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
13317 return TRAVERSE_EXIT;
13318 ++p;
13320 return TRAVERSE_CONTINUE;
13324 if (this->vals_ != NULL)
13325 return this->vals_->traverse(traverse);
13327 return TRAVERSE_CONTINUE;
13330 // Lower a generic composite literal into a specific version based on
13331 // the type.
13333 Expression*
13334 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
13335 Statement_inserter* inserter, int)
13337 Type* type = this->type_;
13339 for (int depth = 0; depth < this->depth_; ++depth)
13341 if (type->array_type() != NULL)
13342 type = type->array_type()->element_type();
13343 else if (type->map_type() != NULL)
13345 if (this->key_path_[depth])
13346 type = type->map_type()->key_type();
13347 else
13348 type = type->map_type()->val_type();
13350 else
13352 if (!type->is_error())
13353 go_error_at(this->location(),
13354 ("may only omit types within composite literals "
13355 "of slice, array, or map type"));
13356 return Expression::make_error(this->location());
13360 Type *pt = type->points_to();
13361 bool is_pointer = false;
13362 if (pt != NULL)
13364 is_pointer = true;
13365 type = pt;
13368 Expression* ret;
13369 if (type->is_error())
13370 return Expression::make_error(this->location());
13371 else if (type->struct_type() != NULL)
13372 ret = this->lower_struct(gogo, type);
13373 else if (type->array_type() != NULL)
13374 ret = this->lower_array(type);
13375 else if (type->map_type() != NULL)
13376 ret = this->lower_map(gogo, function, inserter, type);
13377 else
13379 go_error_at(this->location(),
13380 ("expected struct, slice, array, or map type "
13381 "for composite literal"));
13382 return Expression::make_error(this->location());
13385 if (is_pointer)
13386 ret = Expression::make_heap_expression(ret, this->location());
13388 return ret;
13391 // Lower a struct composite literal.
13393 Expression*
13394 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13396 Location location = this->location();
13397 Struct_type* st = type->struct_type();
13398 if (this->vals_ == NULL || !this->has_keys_)
13400 if (this->vals_ != NULL
13401 && !this->vals_->empty()
13402 && type->named_type() != NULL
13403 && type->named_type()->named_object()->package() != NULL)
13405 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13406 pf != st->fields()->end();
13407 ++pf)
13409 if (Gogo::is_hidden_name(pf->field_name())
13410 || pf->is_embedded_builtin(gogo))
13411 go_error_at(this->location(),
13412 "assignment of unexported field %qs in %qs literal",
13413 Gogo::message_name(pf->field_name()).c_str(),
13414 type->named_type()->message_name().c_str());
13418 return new Struct_construction_expression(type, this->vals_, location);
13421 size_t field_count = st->field_count();
13422 std::vector<Expression*> vals(field_count);
13423 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
13424 Expression_list::const_iterator p = this->vals_->begin();
13425 Expression* external_expr = NULL;
13426 const Named_object* external_no = NULL;
13427 while (p != this->vals_->end())
13429 Expression* name_expr = *p;
13431 ++p;
13432 go_assert(p != this->vals_->end());
13433 Expression* val = *p;
13435 ++p;
13437 if (name_expr == NULL)
13439 go_error_at(val->location(),
13440 "mixture of field and value initializers");
13441 return Expression::make_error(location);
13444 bool bad_key = false;
13445 std::string name;
13446 const Named_object* no = NULL;
13447 switch (name_expr->classification())
13449 case EXPRESSION_UNKNOWN_REFERENCE:
13450 name = name_expr->unknown_expression()->name();
13451 if (type->named_type() != NULL)
13453 // If the named object found for this field name comes from a
13454 // different package than the struct it is a part of, do not count
13455 // this incorrect lookup as a usage of the object's package.
13456 no = name_expr->unknown_expression()->named_object();
13457 if (no->package() != NULL
13458 && no->package() != type->named_type()->named_object()->package())
13459 no->package()->forget_usage(name_expr);
13461 break;
13463 case EXPRESSION_CONST_REFERENCE:
13464 no = static_cast<Const_expression*>(name_expr)->named_object();
13465 break;
13467 case EXPRESSION_TYPE:
13469 Type* t = name_expr->type();
13470 Named_type* nt = t->named_type();
13471 if (nt == NULL)
13472 bad_key = true;
13473 else
13474 no = nt->named_object();
13476 break;
13478 case EXPRESSION_VAR_REFERENCE:
13479 no = name_expr->var_expression()->named_object();
13480 break;
13482 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13483 no = name_expr->enclosed_var_expression()->variable();
13484 break;
13486 case EXPRESSION_FUNC_REFERENCE:
13487 no = name_expr->func_expression()->named_object();
13488 break;
13490 default:
13491 bad_key = true;
13492 break;
13494 if (bad_key)
13496 go_error_at(name_expr->location(), "expected struct field name");
13497 return Expression::make_error(location);
13500 if (no != NULL)
13502 if (no->package() != NULL && external_expr == NULL)
13504 external_expr = name_expr;
13505 external_no = no;
13508 name = no->name();
13510 // A predefined name won't be packed. If it starts with a
13511 // lower case letter we need to check for that case, because
13512 // the field name will be packed. FIXME.
13513 if (!Gogo::is_hidden_name(name)
13514 && name[0] >= 'a'
13515 && name[0] <= 'z')
13517 Named_object* gno = gogo->lookup_global(name.c_str());
13518 if (gno == no)
13519 name = gogo->pack_hidden_name(name, false);
13523 unsigned int index;
13524 const Struct_field* sf = st->find_local_field(name, &index);
13525 if (sf == NULL)
13527 go_error_at(name_expr->location(), "unknown field %qs in %qs",
13528 Gogo::message_name(name).c_str(),
13529 (type->named_type() != NULL
13530 ? type->named_type()->message_name().c_str()
13531 : "unnamed struct"));
13532 return Expression::make_error(location);
13534 if (vals[index] != NULL)
13536 go_error_at(name_expr->location(),
13537 "duplicate value for field %qs in %qs",
13538 Gogo::message_name(name).c_str(),
13539 (type->named_type() != NULL
13540 ? type->named_type()->message_name().c_str()
13541 : "unnamed struct"));
13542 return Expression::make_error(location);
13545 if (type->named_type() != NULL
13546 && type->named_type()->named_object()->package() != NULL
13547 && (Gogo::is_hidden_name(sf->field_name())
13548 || sf->is_embedded_builtin(gogo)))
13549 go_error_at(name_expr->location(),
13550 "assignment of unexported field %qs in %qs literal",
13551 Gogo::message_name(sf->field_name()).c_str(),
13552 type->named_type()->message_name().c_str());
13554 vals[index] = val;
13555 traverse_order->push_back(static_cast<unsigned long>(index));
13558 if (!this->all_are_names_)
13560 // This is a weird case like bug462 in the testsuite.
13561 if (external_expr == NULL)
13562 go_error_at(this->location(), "unknown field in %qs literal",
13563 (type->named_type() != NULL
13564 ? type->named_type()->message_name().c_str()
13565 : "unnamed struct"));
13566 else
13567 go_error_at(external_expr->location(), "unknown field %qs in %qs",
13568 external_no->message_name().c_str(),
13569 (type->named_type() != NULL
13570 ? type->named_type()->message_name().c_str()
13571 : "unnamed struct"));
13572 return Expression::make_error(location);
13575 Expression_list* list = new Expression_list;
13576 list->reserve(field_count);
13577 for (size_t i = 0; i < field_count; ++i)
13578 list->push_back(vals[i]);
13580 Struct_construction_expression* ret =
13581 new Struct_construction_expression(type, list, location);
13582 ret->set_traverse_order(traverse_order);
13583 return ret;
13586 // Index/value/traversal-order triple.
13588 struct IVT_triple {
13589 unsigned long index;
13590 unsigned long traversal_order;
13591 Expression* expr;
13592 IVT_triple(unsigned long i, unsigned long to, Expression *e)
13593 : index(i), traversal_order(to), expr(e) { }
13594 bool operator<(const IVT_triple& other) const
13595 { return this->index < other.index; }
13598 // Lower an array composite literal.
13600 Expression*
13601 Composite_literal_expression::lower_array(Type* type)
13603 Location location = this->location();
13604 if (this->vals_ == NULL || !this->has_keys_)
13605 return this->make_array(type, NULL, this->vals_);
13607 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13608 indexes->reserve(this->vals_->size());
13609 bool indexes_out_of_order = false;
13610 Expression_list* vals = new Expression_list();
13611 vals->reserve(this->vals_->size());
13612 unsigned long index = 0;
13613 Expression_list::const_iterator p = this->vals_->begin();
13614 while (p != this->vals_->end())
13616 Expression* index_expr = *p;
13618 ++p;
13619 go_assert(p != this->vals_->end());
13620 Expression* val = *p;
13622 ++p;
13624 if (index_expr == NULL)
13626 if (!indexes->empty())
13627 indexes->push_back(index);
13629 else
13631 if (indexes->empty() && !vals->empty())
13633 for (size_t i = 0; i < vals->size(); ++i)
13634 indexes->push_back(i);
13637 Numeric_constant nc;
13638 if (!index_expr->numeric_constant_value(&nc))
13640 go_error_at(index_expr->location(),
13641 "index expression is not integer constant");
13642 return Expression::make_error(location);
13645 switch (nc.to_unsigned_long(&index))
13647 case Numeric_constant::NC_UL_VALID:
13648 break;
13649 case Numeric_constant::NC_UL_NOTINT:
13650 go_error_at(index_expr->location(),
13651 "index expression is not integer constant");
13652 return Expression::make_error(location);
13653 case Numeric_constant::NC_UL_NEGATIVE:
13654 go_error_at(index_expr->location(),
13655 "index expression is negative");
13656 return Expression::make_error(location);
13657 case Numeric_constant::NC_UL_BIG:
13658 go_error_at(index_expr->location(), "index value overflow");
13659 return Expression::make_error(location);
13660 default:
13661 go_unreachable();
13664 Named_type* ntype = Type::lookup_integer_type("int");
13665 Integer_type* inttype = ntype->integer_type();
13666 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13667 && index >> (inttype->bits() - 1) != 0)
13669 go_error_at(index_expr->location(), "index value overflow");
13670 return Expression::make_error(location);
13673 if (std::find(indexes->begin(), indexes->end(), index)
13674 != indexes->end())
13676 go_error_at(index_expr->location(),
13677 "duplicate value for index %lu",
13678 index);
13679 return Expression::make_error(location);
13682 if (!indexes->empty() && index < indexes->back())
13683 indexes_out_of_order = true;
13685 indexes->push_back(index);
13688 vals->push_back(val);
13690 ++index;
13693 if (indexes->empty())
13695 delete indexes;
13696 indexes = NULL;
13699 std::vector<unsigned long>* traverse_order = NULL;
13700 if (indexes_out_of_order)
13702 typedef std::vector<IVT_triple> V;
13704 V v;
13705 v.reserve(indexes->size());
13706 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13707 unsigned long torder = 0;
13708 for (Expression_list::const_iterator pe = vals->begin();
13709 pe != vals->end();
13710 ++pe, ++pi, ++torder)
13711 v.push_back(IVT_triple(*pi, torder, *pe));
13713 std::sort(v.begin(), v.end());
13715 delete indexes;
13716 delete vals;
13718 indexes = new std::vector<unsigned long>();
13719 indexes->reserve(v.size());
13720 vals = new Expression_list();
13721 vals->reserve(v.size());
13722 traverse_order = new std::vector<unsigned long>();
13723 traverse_order->reserve(v.size());
13725 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13727 indexes->push_back(p->index);
13728 vals->push_back(p->expr);
13729 traverse_order->push_back(p->traversal_order);
13733 Expression* ret = this->make_array(type, indexes, vals);
13734 Array_construction_expression* ace = ret->array_literal();
13735 if (ace != NULL && traverse_order != NULL)
13736 ace->set_traverse_order(traverse_order);
13737 return ret;
13740 // Actually build the array composite literal. This handles
13741 // [...]{...}.
13743 Expression*
13744 Composite_literal_expression::make_array(
13745 Type* type,
13746 const std::vector<unsigned long>* indexes,
13747 Expression_list* vals)
13749 Location location = this->location();
13750 Array_type* at = type->array_type();
13752 if (at->length() != NULL && at->length()->is_nil_expression())
13754 size_t size;
13755 if (vals == NULL)
13756 size = 0;
13757 else if (indexes != NULL)
13758 size = indexes->back() + 1;
13759 else
13761 size = vals->size();
13762 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13763 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13764 && size >> (it->bits() - 1) != 0)
13766 go_error_at(location, "too many elements in composite literal");
13767 return Expression::make_error(location);
13771 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13772 at = Type::make_array_type(at->element_type(), elen);
13773 type = at;
13775 else if (at->length() != NULL
13776 && !at->length()->is_error_expression()
13777 && this->vals_ != NULL)
13779 Numeric_constant nc;
13780 unsigned long val;
13781 if (at->length()->numeric_constant_value(&nc)
13782 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13784 if (indexes == NULL)
13786 if (this->vals_->size() > val)
13788 go_error_at(location,
13789 "too many elements in composite literal");
13790 return Expression::make_error(location);
13793 else
13795 unsigned long max = indexes->back();
13796 if (max >= val)
13798 go_error_at(location,
13799 ("some element keys in composite literal "
13800 "are out of range"));
13801 return Expression::make_error(location);
13807 if (at->length() != NULL)
13808 return new Fixed_array_construction_expression(type, indexes, vals,
13809 location);
13810 else
13811 return new Slice_construction_expression(type, indexes, vals, location);
13814 // Lower a map composite literal.
13816 Expression*
13817 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13818 Statement_inserter* inserter,
13819 Type* type)
13821 Location location = this->location();
13822 if (this->vals_ != NULL)
13824 if (!this->has_keys_)
13826 go_error_at(location, "map composite literal must have keys");
13827 return Expression::make_error(location);
13830 for (Expression_list::iterator p = this->vals_->begin();
13831 p != this->vals_->end();
13832 p += 2)
13834 if (*p == NULL)
13836 ++p;
13837 go_error_at((*p)->location(),
13838 ("map composite literal must "
13839 "have keys for every value"));
13840 return Expression::make_error(location);
13842 // Make sure we have lowered the key; it may not have been
13843 // lowered in order to handle keys for struct composite
13844 // literals. Lower it now to get the right error message.
13845 if ((*p)->unknown_expression() != NULL)
13847 (*p)->unknown_expression()->clear_is_composite_literal_key();
13848 gogo->lower_expression(function, inserter, &*p);
13849 go_assert((*p)->is_error_expression());
13850 return Expression::make_error(location);
13855 return new Map_construction_expression(type, this->vals_, location);
13858 // Dump ast representation for a composite literal expression.
13860 void
13861 Composite_literal_expression::do_dump_expression(
13862 Ast_dump_context* ast_dump_context) const
13864 ast_dump_context->ostream() << "composite(";
13865 ast_dump_context->dump_type(this->type_);
13866 ast_dump_context->ostream() << ", {";
13867 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13868 ast_dump_context->ostream() << "})";
13871 // Make a composite literal expression.
13873 Expression*
13874 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13875 Expression_list* vals, bool all_are_names,
13876 Location location)
13878 return new Composite_literal_expression(type, depth, has_keys, vals,
13879 all_are_names, location);
13882 // Return whether this expression is a composite literal.
13884 bool
13885 Expression::is_composite_literal() const
13887 switch (this->classification_)
13889 case EXPRESSION_COMPOSITE_LITERAL:
13890 case EXPRESSION_STRUCT_CONSTRUCTION:
13891 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13892 case EXPRESSION_SLICE_CONSTRUCTION:
13893 case EXPRESSION_MAP_CONSTRUCTION:
13894 return true;
13895 default:
13896 return false;
13900 // Return whether this expression is a composite literal which is not
13901 // constant.
13903 bool
13904 Expression::is_nonconstant_composite_literal() const
13906 switch (this->classification_)
13908 case EXPRESSION_STRUCT_CONSTRUCTION:
13910 const Struct_construction_expression *psce =
13911 static_cast<const Struct_construction_expression*>(this);
13912 return !psce->is_constant_struct();
13914 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13916 const Fixed_array_construction_expression *pace =
13917 static_cast<const Fixed_array_construction_expression*>(this);
13918 return !pace->is_constant_array();
13920 case EXPRESSION_SLICE_CONSTRUCTION:
13922 const Slice_construction_expression *pace =
13923 static_cast<const Slice_construction_expression*>(this);
13924 return !pace->is_constant_array();
13926 case EXPRESSION_MAP_CONSTRUCTION:
13927 return true;
13928 default:
13929 return false;
13933 // Return true if this is a variable or temporary_variable.
13935 bool
13936 Expression::is_variable() const
13938 switch (this->classification_)
13940 case EXPRESSION_VAR_REFERENCE:
13941 case EXPRESSION_TEMPORARY_REFERENCE:
13942 case EXPRESSION_SET_AND_USE_TEMPORARY:
13943 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
13944 return true;
13945 default:
13946 return false;
13950 // Return true if this is a reference to a local variable.
13952 bool
13953 Expression::is_local_variable() const
13955 const Var_expression* ve = this->var_expression();
13956 if (ve == NULL)
13957 return false;
13958 const Named_object* no = ve->named_object();
13959 return (no->is_result_variable()
13960 || (no->is_variable() && !no->var_value()->is_global()));
13963 // Class Type_guard_expression.
13965 // Traversal.
13968 Type_guard_expression::do_traverse(Traverse* traverse)
13970 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13971 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13972 return TRAVERSE_EXIT;
13973 return TRAVERSE_CONTINUE;
13976 Expression*
13977 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13978 Statement_inserter* inserter)
13980 if (this->expr_->is_error_expression()
13981 || this->expr_->type()->is_error_type())
13983 go_assert(saw_errors());
13984 return Expression::make_error(this->location());
13987 if (!this->expr_->is_variable())
13989 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13990 this->location());
13991 inserter->insert(temp);
13992 this->expr_ =
13993 Expression::make_temporary_reference(temp, this->location());
13995 return this;
13998 // Check types of a type guard expression. The expression must have
13999 // an interface type, but the actual type conversion is checked at run
14000 // time.
14002 void
14003 Type_guard_expression::do_check_types(Gogo*)
14005 Type* expr_type = this->expr_->type();
14006 if (expr_type->interface_type() == NULL)
14008 if (!expr_type->is_error() && !this->type_->is_error())
14009 this->report_error(_("type assertion only valid for interface types"));
14010 this->set_is_error();
14012 else if (this->type_->interface_type() == NULL)
14014 std::string reason;
14015 if (!expr_type->interface_type()->implements_interface(this->type_,
14016 &reason))
14018 if (!this->type_->is_error())
14020 if (reason.empty())
14021 this->report_error(_("impossible type assertion: "
14022 "type does not implement interface"));
14023 else
14024 go_error_at(this->location(),
14025 ("impossible type assertion: "
14026 "type does not implement interface (%s)"),
14027 reason.c_str());
14029 this->set_is_error();
14034 // Return the backend representation for a type guard expression.
14036 Bexpression*
14037 Type_guard_expression::do_get_backend(Translate_context* context)
14039 Expression* conversion;
14040 if (this->type_->interface_type() != NULL)
14041 conversion =
14042 Expression::convert_interface_to_interface(this->type_, this->expr_,
14043 true, this->location());
14044 else
14045 conversion =
14046 Expression::convert_for_assignment(context->gogo(), this->type_,
14047 this->expr_, this->location());
14049 return conversion->get_backend(context);
14052 // Dump ast representation for a type guard expression.
14054 void
14055 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14056 const
14058 this->expr_->dump_expression(ast_dump_context);
14059 ast_dump_context->ostream() << ".";
14060 ast_dump_context->dump_type(this->type_);
14063 // Make a type guard expression.
14065 Expression*
14066 Expression::make_type_guard(Expression* expr, Type* type,
14067 Location location)
14069 return new Type_guard_expression(expr, type, location);
14072 // Class Heap_expression.
14074 // Return the type of the expression stored on the heap.
14076 Type*
14077 Heap_expression::do_type()
14078 { return Type::make_pointer_type(this->expr_->type()); }
14080 // Return the backend representation for allocating an expression on the heap.
14082 Bexpression*
14083 Heap_expression::do_get_backend(Translate_context* context)
14085 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
14086 return context->backend()->error_expression();
14088 Location loc = this->location();
14089 Gogo* gogo = context->gogo();
14090 Btype* btype = this->type()->get_backend(gogo);
14092 Expression* alloc = Expression::make_allocation(this->expr_->type(), loc);
14093 Node* n = Node::make_node(this);
14094 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
14095 alloc->allocation_expression()->set_allocate_on_stack();
14096 Bexpression* space = alloc->get_backend(context);
14098 Bstatement* decl;
14099 Named_object* fn = context->function();
14100 go_assert(fn != NULL);
14101 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14102 Bvariable* space_temp =
14103 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14104 space, true, loc, &decl);
14105 space = gogo->backend()->var_expression(space_temp, loc);
14106 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
14107 Bexpression* ref =
14108 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14110 Bexpression* bexpr = this->expr_->get_backend(context);
14111 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
14112 decl = gogo->backend()->compound_statement(decl, assn);
14113 space = gogo->backend()->var_expression(space_temp, loc);
14114 return gogo->backend()->compound_expression(decl, space, loc);
14117 // Dump ast representation for a heap expression.
14119 void
14120 Heap_expression::do_dump_expression(
14121 Ast_dump_context* ast_dump_context) const
14123 ast_dump_context->ostream() << "&(";
14124 ast_dump_context->dump_expression(this->expr_);
14125 ast_dump_context->ostream() << ")";
14128 // Allocate an expression on the heap.
14130 Expression*
14131 Expression::make_heap_expression(Expression* expr, Location location)
14133 return new Heap_expression(expr, location);
14136 // Class Receive_expression.
14138 // Return the type of a receive expression.
14140 Type*
14141 Receive_expression::do_type()
14143 if (this->is_error_expression())
14144 return Type::make_error_type();
14145 Channel_type* channel_type = this->channel_->type()->channel_type();
14146 if (channel_type == NULL)
14148 this->report_error(_("expected channel"));
14149 return Type::make_error_type();
14151 return channel_type->element_type();
14154 // Check types for a receive expression.
14156 void
14157 Receive_expression::do_check_types(Gogo*)
14159 Type* type = this->channel_->type();
14160 if (type->is_error())
14162 go_assert(saw_errors());
14163 this->set_is_error();
14164 return;
14166 if (type->channel_type() == NULL)
14168 this->report_error(_("expected channel"));
14169 return;
14171 if (!type->channel_type()->may_receive())
14173 this->report_error(_("invalid receive on send-only channel"));
14174 return;
14178 // Flattening for receive expressions creates a temporary variable to store
14179 // received data in for receives.
14181 Expression*
14182 Receive_expression::do_flatten(Gogo*, Named_object*,
14183 Statement_inserter* inserter)
14185 Channel_type* channel_type = this->channel_->type()->channel_type();
14186 if (channel_type == NULL)
14188 go_assert(saw_errors());
14189 return this;
14191 else if (this->channel_->is_error_expression())
14193 go_assert(saw_errors());
14194 return Expression::make_error(this->location());
14197 Type* element_type = channel_type->element_type();
14198 if (this->temp_receiver_ == NULL)
14200 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
14201 this->location());
14202 this->temp_receiver_->set_is_address_taken();
14203 inserter->insert(this->temp_receiver_);
14206 return this;
14209 // Get the backend representation for a receive expression.
14211 Bexpression*
14212 Receive_expression::do_get_backend(Translate_context* context)
14214 Location loc = this->location();
14216 Channel_type* channel_type = this->channel_->type()->channel_type();
14217 if (channel_type == NULL)
14219 go_assert(this->channel_->type()->is_error());
14220 return context->backend()->error_expression();
14222 Expression* td = Expression::make_type_descriptor(channel_type, loc);
14224 Expression* recv_ref =
14225 Expression::make_temporary_reference(this->temp_receiver_, loc);
14226 Expression* recv_addr =
14227 Expression::make_temporary_reference(this->temp_receiver_, loc);
14228 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
14229 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 3,
14230 td, this->channel_, recv_addr);
14231 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
14234 // Dump ast representation for a receive expression.
14236 void
14237 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
14239 ast_dump_context->ostream() << " <- " ;
14240 ast_dump_context->dump_expression(channel_);
14243 // Make a receive expression.
14245 Receive_expression*
14246 Expression::make_receive(Expression* channel, Location location)
14248 return new Receive_expression(channel, location);
14251 // An expression which evaluates to a pointer to the type descriptor
14252 // of a type.
14254 class Type_descriptor_expression : public Expression
14256 public:
14257 Type_descriptor_expression(Type* type, Location location)
14258 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
14259 type_(type)
14262 protected:
14264 do_traverse(Traverse*);
14266 Type*
14267 do_type()
14268 { return Type::make_type_descriptor_ptr_type(); }
14270 bool
14271 do_is_static_initializer() const
14272 { return true; }
14274 void
14275 do_determine_type(const Type_context*)
14278 Expression*
14279 do_copy()
14280 { return this; }
14282 Bexpression*
14283 do_get_backend(Translate_context* context)
14285 return this->type_->type_descriptor_pointer(context->gogo(),
14286 this->location());
14289 void
14290 do_dump_expression(Ast_dump_context*) const;
14292 private:
14293 // The type for which this is the descriptor.
14294 Type* type_;
14298 Type_descriptor_expression::do_traverse(Traverse* traverse)
14300 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14301 return TRAVERSE_EXIT;
14302 return TRAVERSE_CONTINUE;
14305 // Dump ast representation for a type descriptor expression.
14307 void
14308 Type_descriptor_expression::do_dump_expression(
14309 Ast_dump_context* ast_dump_context) const
14311 ast_dump_context->dump_type(this->type_);
14314 // Make a type descriptor expression.
14316 Expression*
14317 Expression::make_type_descriptor(Type* type, Location location)
14319 return new Type_descriptor_expression(type, location);
14322 // An expression which evaluates to a pointer to the Garbage Collection symbol
14323 // of a type.
14325 class GC_symbol_expression : public Expression
14327 public:
14328 GC_symbol_expression(Type* type)
14329 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14330 type_(type)
14333 protected:
14334 Type*
14335 do_type()
14336 { return Type::lookup_integer_type("uintptr"); }
14338 bool
14339 do_is_static_initializer() const
14340 { return true; }
14342 void
14343 do_determine_type(const Type_context*)
14346 Expression*
14347 do_copy()
14348 { return this; }
14350 Bexpression*
14351 do_get_backend(Translate_context* context)
14352 { return this->type_->gc_symbol_pointer(context->gogo()); }
14354 void
14355 do_dump_expression(Ast_dump_context*) const;
14357 private:
14358 // The type which this gc symbol describes.
14359 Type* type_;
14362 // Dump ast representation for a gc symbol expression.
14364 void
14365 GC_symbol_expression::do_dump_expression(
14366 Ast_dump_context* ast_dump_context) const
14368 ast_dump_context->ostream() << "gcdata(";
14369 ast_dump_context->dump_type(this->type_);
14370 ast_dump_context->ostream() << ")";
14373 // Make a gc symbol expression.
14375 Expression*
14376 Expression::make_gc_symbol(Type* type)
14378 return new GC_symbol_expression(type);
14381 // An expression which evaluates to some characteristic of a type.
14382 // This is only used to initialize fields of a type descriptor. Using
14383 // a new expression class is slightly inefficient but gives us a good
14384 // separation between the frontend and the middle-end with regard to
14385 // how types are laid out.
14387 class Type_info_expression : public Expression
14389 public:
14390 Type_info_expression(Type* type, Type_info type_info)
14391 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14392 type_(type), type_info_(type_info)
14395 protected:
14396 bool
14397 do_is_static_initializer() const
14398 { return true; }
14400 Type*
14401 do_type();
14403 void
14404 do_determine_type(const Type_context*)
14407 Expression*
14408 do_copy()
14409 { return this; }
14411 Bexpression*
14412 do_get_backend(Translate_context* context);
14414 void
14415 do_dump_expression(Ast_dump_context*) const;
14417 private:
14418 // The type for which we are getting information.
14419 Type* type_;
14420 // What information we want.
14421 Type_info type_info_;
14424 // The type is chosen to match what the type descriptor struct
14425 // expects.
14427 Type*
14428 Type_info_expression::do_type()
14430 switch (this->type_info_)
14432 case TYPE_INFO_SIZE:
14433 return Type::lookup_integer_type("uintptr");
14434 case TYPE_INFO_ALIGNMENT:
14435 case TYPE_INFO_FIELD_ALIGNMENT:
14436 return Type::lookup_integer_type("uint8");
14437 default:
14438 go_unreachable();
14442 // Return the backend representation for type information.
14444 Bexpression*
14445 Type_info_expression::do_get_backend(Translate_context* context)
14447 Gogo* gogo = context->gogo();
14448 bool ok = true;
14449 int64_t val;
14450 switch (this->type_info_)
14452 case TYPE_INFO_SIZE:
14453 ok = this->type_->backend_type_size(gogo, &val);
14454 break;
14455 case TYPE_INFO_ALIGNMENT:
14456 ok = this->type_->backend_type_align(gogo, &val);
14457 break;
14458 case TYPE_INFO_FIELD_ALIGNMENT:
14459 ok = this->type_->backend_type_field_align(gogo, &val);
14460 break;
14461 default:
14462 go_unreachable();
14464 if (!ok)
14466 go_assert(saw_errors());
14467 return gogo->backend()->error_expression();
14469 Expression* e = Expression::make_integer_int64(val, this->type(),
14470 this->location());
14471 return e->get_backend(context);
14474 // Dump ast representation for a type info expression.
14476 void
14477 Type_info_expression::do_dump_expression(
14478 Ast_dump_context* ast_dump_context) const
14480 ast_dump_context->ostream() << "typeinfo(";
14481 ast_dump_context->dump_type(this->type_);
14482 ast_dump_context->ostream() << ",";
14483 ast_dump_context->ostream() <<
14484 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14485 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14486 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14487 : "unknown");
14488 ast_dump_context->ostream() << ")";
14491 // Make a type info expression.
14493 Expression*
14494 Expression::make_type_info(Type* type, Type_info type_info)
14496 return new Type_info_expression(type, type_info);
14499 // An expression that evaluates to some characteristic of a slice.
14500 // This is used when indexing, bound-checking, or nil checking a slice.
14502 class Slice_info_expression : public Expression
14504 public:
14505 Slice_info_expression(Expression* slice, Slice_info slice_info,
14506 Location location)
14507 : Expression(EXPRESSION_SLICE_INFO, location),
14508 slice_(slice), slice_info_(slice_info)
14511 protected:
14512 Type*
14513 do_type();
14515 void
14516 do_determine_type(const Type_context*)
14519 Expression*
14520 do_copy()
14522 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14523 this->location());
14526 Bexpression*
14527 do_get_backend(Translate_context* context);
14529 void
14530 do_dump_expression(Ast_dump_context*) const;
14532 void
14533 do_issue_nil_check()
14534 { this->slice_->issue_nil_check(); }
14536 private:
14537 // The slice for which we are getting information.
14538 Expression* slice_;
14539 // What information we want.
14540 Slice_info slice_info_;
14543 // Return the type of the slice info.
14545 Type*
14546 Slice_info_expression::do_type()
14548 switch (this->slice_info_)
14550 case SLICE_INFO_VALUE_POINTER:
14551 return Type::make_pointer_type(
14552 this->slice_->type()->array_type()->element_type());
14553 case SLICE_INFO_LENGTH:
14554 case SLICE_INFO_CAPACITY:
14555 return Type::lookup_integer_type("int");
14556 default:
14557 go_unreachable();
14561 // Return the backend information for slice information.
14563 Bexpression*
14564 Slice_info_expression::do_get_backend(Translate_context* context)
14566 Gogo* gogo = context->gogo();
14567 Bexpression* bslice = this->slice_->get_backend(context);
14568 switch (this->slice_info_)
14570 case SLICE_INFO_VALUE_POINTER:
14571 case SLICE_INFO_LENGTH:
14572 case SLICE_INFO_CAPACITY:
14573 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14574 this->location());
14575 break;
14576 default:
14577 go_unreachable();
14581 // Dump ast representation for a type info expression.
14583 void
14584 Slice_info_expression::do_dump_expression(
14585 Ast_dump_context* ast_dump_context) const
14587 ast_dump_context->ostream() << "sliceinfo(";
14588 this->slice_->dump_expression(ast_dump_context);
14589 ast_dump_context->ostream() << ",";
14590 ast_dump_context->ostream() <<
14591 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14592 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14593 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14594 : "unknown");
14595 ast_dump_context->ostream() << ")";
14598 // Make a slice info expression.
14600 Expression*
14601 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14602 Location location)
14604 return new Slice_info_expression(slice, slice_info, location);
14607 // An expression that represents a slice value: a struct with value pointer,
14608 // length, and capacity fields.
14610 class Slice_value_expression : public Expression
14612 public:
14613 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14614 Expression* cap, Location location)
14615 : Expression(EXPRESSION_SLICE_VALUE, location),
14616 type_(type), valptr_(valptr), len_(len), cap_(cap)
14619 protected:
14621 do_traverse(Traverse*);
14623 Type*
14624 do_type()
14625 { return this->type_; }
14627 void
14628 do_determine_type(const Type_context*)
14629 { go_unreachable(); }
14631 Expression*
14632 do_copy()
14634 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14635 this->len_->copy(), this->cap_->copy(),
14636 this->location());
14639 Bexpression*
14640 do_get_backend(Translate_context* context);
14642 void
14643 do_dump_expression(Ast_dump_context*) const;
14645 private:
14646 // The type of the slice value.
14647 Type* type_;
14648 // The pointer to the values in the slice.
14649 Expression* valptr_;
14650 // The length of the slice.
14651 Expression* len_;
14652 // The capacity of the slice.
14653 Expression* cap_;
14657 Slice_value_expression::do_traverse(Traverse* traverse)
14659 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
14660 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14661 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14662 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14663 return TRAVERSE_EXIT;
14664 return TRAVERSE_CONTINUE;
14667 Bexpression*
14668 Slice_value_expression::do_get_backend(Translate_context* context)
14670 std::vector<Bexpression*> vals(3);
14671 vals[0] = this->valptr_->get_backend(context);
14672 vals[1] = this->len_->get_backend(context);
14673 vals[2] = this->cap_->get_backend(context);
14675 Gogo* gogo = context->gogo();
14676 Btype* btype = this->type_->get_backend(gogo);
14677 return gogo->backend()->constructor_expression(btype, vals, this->location());
14680 void
14681 Slice_value_expression::do_dump_expression(
14682 Ast_dump_context* ast_dump_context) const
14684 ast_dump_context->ostream() << "slicevalue(";
14685 ast_dump_context->ostream() << "values: ";
14686 this->valptr_->dump_expression(ast_dump_context);
14687 ast_dump_context->ostream() << ", length: ";
14688 this->len_->dump_expression(ast_dump_context);
14689 ast_dump_context->ostream() << ", capacity: ";
14690 this->cap_->dump_expression(ast_dump_context);
14691 ast_dump_context->ostream() << ")";
14694 Expression*
14695 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14696 Expression* cap, Location location)
14698 go_assert(at->is_slice_type());
14699 return new Slice_value_expression(at, valptr, len, cap, location);
14702 // An expression that evaluates to some characteristic of a non-empty interface.
14703 // This is used to access the method table or underlying object of an interface.
14705 class Interface_info_expression : public Expression
14707 public:
14708 Interface_info_expression(Expression* iface, Interface_info iface_info,
14709 Location location)
14710 : Expression(EXPRESSION_INTERFACE_INFO, location),
14711 iface_(iface), iface_info_(iface_info)
14714 protected:
14715 Type*
14716 do_type();
14718 void
14719 do_determine_type(const Type_context*)
14722 Expression*
14723 do_copy()
14725 return new Interface_info_expression(this->iface_->copy(),
14726 this->iface_info_, this->location());
14729 Bexpression*
14730 do_get_backend(Translate_context* context);
14732 void
14733 do_dump_expression(Ast_dump_context*) const;
14735 void
14736 do_issue_nil_check()
14737 { this->iface_->issue_nil_check(); }
14739 private:
14740 // The interface for which we are getting information.
14741 Expression* iface_;
14742 // What information we want.
14743 Interface_info iface_info_;
14746 // Return the type of the interface info.
14748 Type*
14749 Interface_info_expression::do_type()
14751 switch (this->iface_info_)
14753 case INTERFACE_INFO_METHODS:
14755 typedef Unordered_map(Interface_type*, Type*) Hashtable;
14756 static Hashtable result_types;
14758 Interface_type* itype = this->iface_->type()->interface_type();
14760 Hashtable::const_iterator p = result_types.find(itype);
14761 if (p != result_types.end())
14762 return p->second;
14764 Type* pdt = Type::make_type_descriptor_ptr_type();
14765 if (itype->is_empty())
14767 result_types[itype] = pdt;
14768 return pdt;
14771 Location loc = this->location();
14772 Struct_field_list* sfl = new Struct_field_list();
14773 sfl->push_back(
14774 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14776 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14777 p != itype->methods()->end();
14778 ++p)
14780 Function_type* ft = p->type()->function_type();
14781 go_assert(ft->receiver() == NULL);
14783 const Typed_identifier_list* params = ft->parameters();
14784 Typed_identifier_list* mparams = new Typed_identifier_list();
14785 if (params != NULL)
14786 mparams->reserve(params->size() + 1);
14787 Type* vt = Type::make_pointer_type(Type::make_void_type());
14788 mparams->push_back(Typed_identifier("", vt, ft->location()));
14789 if (params != NULL)
14791 for (Typed_identifier_list::const_iterator pp = params->begin();
14792 pp != params->end();
14793 ++pp)
14794 mparams->push_back(*pp);
14797 Typed_identifier_list* mresults = (ft->results() == NULL
14798 ? NULL
14799 : ft->results()->copy());
14800 Backend_function_type* mft =
14801 Type::make_backend_function_type(NULL, mparams, mresults,
14802 ft->location());
14804 std::string fname = Gogo::unpack_hidden_name(p->name());
14805 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14808 Pointer_type *pt = Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14809 result_types[itype] = pt;
14810 return pt;
14812 case INTERFACE_INFO_OBJECT:
14813 return Type::make_pointer_type(Type::make_void_type());
14814 default:
14815 go_unreachable();
14819 // Return the backend representation for interface information.
14821 Bexpression*
14822 Interface_info_expression::do_get_backend(Translate_context* context)
14824 Gogo* gogo = context->gogo();
14825 Bexpression* biface = this->iface_->get_backend(context);
14826 switch (this->iface_info_)
14828 case INTERFACE_INFO_METHODS:
14829 case INTERFACE_INFO_OBJECT:
14830 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14831 this->location());
14832 break;
14833 default:
14834 go_unreachable();
14838 // Dump ast representation for an interface info expression.
14840 void
14841 Interface_info_expression::do_dump_expression(
14842 Ast_dump_context* ast_dump_context) const
14844 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14845 ast_dump_context->ostream() << "interfaceinfo(";
14846 this->iface_->dump_expression(ast_dump_context);
14847 ast_dump_context->ostream() << ",";
14848 ast_dump_context->ostream() <<
14849 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14850 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14851 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14852 : "unknown");
14853 ast_dump_context->ostream() << ")";
14856 // Make an interface info expression.
14858 Expression*
14859 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14860 Location location)
14862 return new Interface_info_expression(iface, iface_info, location);
14865 // An expression that represents an interface value. The first field is either
14866 // a type descriptor for an empty interface or a pointer to the interface method
14867 // table for a non-empty interface. The second field is always the object.
14869 class Interface_value_expression : public Expression
14871 public:
14872 Interface_value_expression(Type* type, Expression* first_field,
14873 Expression* obj, Location location)
14874 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14875 type_(type), first_field_(first_field), obj_(obj)
14878 protected:
14880 do_traverse(Traverse*);
14882 Type*
14883 do_type()
14884 { return this->type_; }
14886 void
14887 do_determine_type(const Type_context*)
14888 { go_unreachable(); }
14890 Expression*
14891 do_copy()
14893 return new Interface_value_expression(this->type_,
14894 this->first_field_->copy(),
14895 this->obj_->copy(), this->location());
14898 Bexpression*
14899 do_get_backend(Translate_context* context);
14901 void
14902 do_dump_expression(Ast_dump_context*) const;
14904 private:
14905 // The type of the interface value.
14906 Type* type_;
14907 // The first field of the interface (either a type descriptor or a pointer
14908 // to the method table.
14909 Expression* first_field_;
14910 // The underlying object of the interface.
14911 Expression* obj_;
14915 Interface_value_expression::do_traverse(Traverse* traverse)
14917 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14918 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14919 return TRAVERSE_EXIT;
14920 return TRAVERSE_CONTINUE;
14923 Bexpression*
14924 Interface_value_expression::do_get_backend(Translate_context* context)
14926 std::vector<Bexpression*> vals(2);
14927 vals[0] = this->first_field_->get_backend(context);
14928 vals[1] = this->obj_->get_backend(context);
14930 Gogo* gogo = context->gogo();
14931 Btype* btype = this->type_->get_backend(gogo);
14932 return gogo->backend()->constructor_expression(btype, vals, this->location());
14935 void
14936 Interface_value_expression::do_dump_expression(
14937 Ast_dump_context* ast_dump_context) const
14939 ast_dump_context->ostream() << "interfacevalue(";
14940 ast_dump_context->ostream() <<
14941 (this->type_->interface_type()->is_empty()
14942 ? "type_descriptor: "
14943 : "methods: ");
14944 this->first_field_->dump_expression(ast_dump_context);
14945 ast_dump_context->ostream() << ", object: ";
14946 this->obj_->dump_expression(ast_dump_context);
14947 ast_dump_context->ostream() << ")";
14950 Expression*
14951 Expression::make_interface_value(Type* type, Expression* first_value,
14952 Expression* object, Location location)
14954 return new Interface_value_expression(type, first_value, object, location);
14957 // An interface method table for a pair of types: an interface type and a type
14958 // that implements that interface.
14960 class Interface_mtable_expression : public Expression
14962 public:
14963 Interface_mtable_expression(Interface_type* itype, Type* type,
14964 bool is_pointer, Location location)
14965 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14966 itype_(itype), type_(type), is_pointer_(is_pointer),
14967 method_table_type_(NULL), bvar_(NULL)
14970 protected:
14972 do_traverse(Traverse*);
14974 Type*
14975 do_type();
14977 bool
14978 do_is_static_initializer() const
14979 { return true; }
14981 void
14982 do_determine_type(const Type_context*)
14983 { go_unreachable(); }
14985 Expression*
14986 do_copy()
14988 return new Interface_mtable_expression(this->itype_, this->type_,
14989 this->is_pointer_, this->location());
14992 bool
14993 do_is_addressable() const
14994 { return true; }
14996 Bexpression*
14997 do_get_backend(Translate_context* context);
14999 void
15000 do_dump_expression(Ast_dump_context*) const;
15002 private:
15003 // The interface type for which the methods are defined.
15004 Interface_type* itype_;
15005 // The type to construct the interface method table for.
15006 Type* type_;
15007 // Whether this table contains the method set for the receiver type or the
15008 // pointer receiver type.
15009 bool is_pointer_;
15010 // The type of the method table.
15011 Type* method_table_type_;
15012 // The backend variable that refers to the interface method table.
15013 Bvariable* bvar_;
15017 Interface_mtable_expression::do_traverse(Traverse* traverse)
15019 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15020 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15021 return TRAVERSE_EXIT;
15022 return TRAVERSE_CONTINUE;
15025 Type*
15026 Interface_mtable_expression::do_type()
15028 if (this->method_table_type_ != NULL)
15029 return this->method_table_type_;
15031 const Typed_identifier_list* interface_methods = this->itype_->methods();
15032 go_assert(!interface_methods->empty());
15034 Struct_field_list* sfl = new Struct_field_list;
15035 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15036 this->location());
15037 sfl->push_back(Struct_field(tid));
15038 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15039 p != interface_methods->end();
15040 ++p)
15041 sfl->push_back(Struct_field(*p));
15042 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
15043 return this->method_table_type_;
15046 Bexpression*
15047 Interface_mtable_expression::do_get_backend(Translate_context* context)
15049 Gogo* gogo = context->gogo();
15050 Location loc = Linemap::predeclared_location();
15051 if (this->bvar_ != NULL)
15052 return gogo->backend()->var_expression(this->bvar_, this->location());
15054 const Typed_identifier_list* interface_methods = this->itype_->methods();
15055 go_assert(!interface_methods->empty());
15057 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
15058 + this->itype_->mangled_name(gogo)
15059 + "__"
15060 + this->type_->mangled_name(gogo));
15062 // See whether this interface has any hidden methods.
15063 bool has_hidden_methods = false;
15064 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15065 p != interface_methods->end();
15066 ++p)
15068 if (Gogo::is_hidden_name(p->name()))
15070 has_hidden_methods = true;
15071 break;
15075 // We already know that the named type is convertible to the
15076 // interface. If the interface has hidden methods, and the named
15077 // type is defined in a different package, then the interface
15078 // conversion table will be defined by that other package.
15079 if (has_hidden_methods
15080 && this->type_->named_type() != NULL
15081 && this->type_->named_type()->named_object()->package() != NULL)
15083 Btype* btype = this->type()->get_backend(gogo);
15084 std::string asm_name(go_selectively_encode_id(mangled_name));
15085 this->bvar_ =
15086 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15087 btype, loc);
15088 return gogo->backend()->var_expression(this->bvar_, this->location());
15091 // The first element is the type descriptor.
15092 Type* td_type;
15093 if (!this->is_pointer_)
15094 td_type = this->type_;
15095 else
15096 td_type = Type::make_pointer_type(this->type_);
15098 // Build an interface method table for a type: a type descriptor followed by a
15099 // list of function pointers, one for each interface method. This is used for
15100 // interfaces.
15101 Expression_list* svals = new Expression_list();
15102 svals->push_back(Expression::make_type_descriptor(td_type, loc));
15104 Named_type* nt = this->type_->named_type();
15105 Struct_type* st = this->type_->struct_type();
15106 go_assert(nt != NULL || st != NULL);
15108 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15109 p != interface_methods->end();
15110 ++p)
15112 bool is_ambiguous;
15113 Method* m;
15114 if (nt != NULL)
15115 m = nt->method_function(p->name(), &is_ambiguous);
15116 else
15117 m = st->method_function(p->name(), &is_ambiguous);
15118 go_assert(m != NULL);
15119 Named_object* no = m->named_object();
15121 go_assert(no->is_function() || no->is_function_declaration());
15122 svals->push_back(Expression::make_func_code_reference(no, loc));
15125 Btype* btype = this->type()->get_backend(gogo);
15126 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
15127 svals, loc);
15128 Bexpression* ctor = mtable->get_backend(context);
15130 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
15131 std::string asm_name(go_selectively_encode_id(mangled_name));
15132 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
15133 !is_public, btype, loc);
15134 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
15135 !is_public, btype, loc, ctor);
15136 return gogo->backend()->var_expression(this->bvar_, loc);
15139 void
15140 Interface_mtable_expression::do_dump_expression(
15141 Ast_dump_context* ast_dump_context) const
15143 ast_dump_context->ostream() << "__go_"
15144 << (this->is_pointer_ ? "pimt__" : "imt_");
15145 ast_dump_context->dump_type(this->itype_);
15146 ast_dump_context->ostream() << "__";
15147 ast_dump_context->dump_type(this->type_);
15150 Expression*
15151 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
15152 bool is_pointer, Location location)
15154 return new Interface_mtable_expression(itype, type, is_pointer, location);
15157 // An expression which evaluates to the offset of a field within a
15158 // struct. This, like Type_info_expression, q.v., is only used to
15159 // initialize fields of a type descriptor.
15161 class Struct_field_offset_expression : public Expression
15163 public:
15164 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
15165 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
15166 Linemap::predeclared_location()),
15167 type_(type), field_(field)
15170 protected:
15171 bool
15172 do_is_static_initializer() const
15173 { return true; }
15175 Type*
15176 do_type()
15177 { return Type::lookup_integer_type("uintptr"); }
15179 void
15180 do_determine_type(const Type_context*)
15183 Expression*
15184 do_copy()
15185 { return this; }
15187 Bexpression*
15188 do_get_backend(Translate_context* context);
15190 void
15191 do_dump_expression(Ast_dump_context*) const;
15193 private:
15194 // The type of the struct.
15195 Struct_type* type_;
15196 // The field.
15197 const Struct_field* field_;
15200 // Return the backend representation for a struct field offset.
15202 Bexpression*
15203 Struct_field_offset_expression::do_get_backend(Translate_context* context)
15205 const Struct_field_list* fields = this->type_->fields();
15206 Struct_field_list::const_iterator p;
15207 unsigned i = 0;
15208 for (p = fields->begin();
15209 p != fields->end();
15210 ++p, ++i)
15211 if (&*p == this->field_)
15212 break;
15213 go_assert(&*p == this->field_);
15215 Gogo* gogo = context->gogo();
15216 Btype* btype = this->type_->get_backend(gogo);
15218 int64_t offset = gogo->backend()->type_field_offset(btype, i);
15219 Type* uptr_type = Type::lookup_integer_type("uintptr");
15220 Expression* ret =
15221 Expression::make_integer_int64(offset, uptr_type,
15222 Linemap::predeclared_location());
15223 return ret->get_backend(context);
15226 // Dump ast representation for a struct field offset expression.
15228 void
15229 Struct_field_offset_expression::do_dump_expression(
15230 Ast_dump_context* ast_dump_context) const
15232 ast_dump_context->ostream() << "unsafe.Offsetof(";
15233 ast_dump_context->dump_type(this->type_);
15234 ast_dump_context->ostream() << '.';
15235 ast_dump_context->ostream() <<
15236 Gogo::message_name(this->field_->field_name());
15237 ast_dump_context->ostream() << ")";
15240 // Make an expression for a struct field offset.
15242 Expression*
15243 Expression::make_struct_field_offset(Struct_type* type,
15244 const Struct_field* field)
15246 return new Struct_field_offset_expression(type, field);
15249 // An expression which evaluates to the address of an unnamed label.
15251 class Label_addr_expression : public Expression
15253 public:
15254 Label_addr_expression(Label* label, Location location)
15255 : Expression(EXPRESSION_LABEL_ADDR, location),
15256 label_(label)
15259 protected:
15260 Type*
15261 do_type()
15262 { return Type::make_pointer_type(Type::make_void_type()); }
15264 void
15265 do_determine_type(const Type_context*)
15268 Expression*
15269 do_copy()
15270 { return new Label_addr_expression(this->label_, this->location()); }
15272 Bexpression*
15273 do_get_backend(Translate_context* context)
15274 { return this->label_->get_addr(context, this->location()); }
15276 void
15277 do_dump_expression(Ast_dump_context* ast_dump_context) const
15278 { ast_dump_context->ostream() << this->label_->name(); }
15280 private:
15281 // The label whose address we are taking.
15282 Label* label_;
15285 // Make an expression for the address of an unnamed label.
15287 Expression*
15288 Expression::make_label_addr(Label* label, Location location)
15290 return new Label_addr_expression(label, location);
15293 // Class Conditional_expression.
15295 // Traversal.
15298 Conditional_expression::do_traverse(Traverse* traverse)
15300 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15301 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15302 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15303 return TRAVERSE_EXIT;
15304 return TRAVERSE_CONTINUE;
15307 // Return the type of the conditional expression.
15309 Type*
15310 Conditional_expression::do_type()
15312 Type* result_type = Type::make_void_type();
15313 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15314 NULL))
15315 result_type = this->then_->type();
15316 else if (this->then_->is_nil_expression()
15317 || this->else_->is_nil_expression())
15318 result_type = (!this->then_->is_nil_expression()
15319 ? this->then_->type()
15320 : this->else_->type());
15321 return result_type;
15324 // Determine type for a conditional expression.
15326 void
15327 Conditional_expression::do_determine_type(const Type_context* context)
15329 this->cond_->determine_type_no_context();
15330 this->then_->determine_type(context);
15331 this->else_->determine_type(context);
15334 // Get the backend representation of a conditional expression.
15336 Bexpression*
15337 Conditional_expression::do_get_backend(Translate_context* context)
15339 Gogo* gogo = context->gogo();
15340 Btype* result_btype = this->type()->get_backend(gogo);
15341 Bexpression* cond = this->cond_->get_backend(context);
15342 Bexpression* then = this->then_->get_backend(context);
15343 Bexpression* belse = this->else_->get_backend(context);
15344 return gogo->backend()->conditional_expression(result_btype, cond, then,
15345 belse, this->location());
15348 // Dump ast representation of a conditional expression.
15350 void
15351 Conditional_expression::do_dump_expression(
15352 Ast_dump_context* ast_dump_context) const
15354 ast_dump_context->ostream() << "(";
15355 ast_dump_context->dump_expression(this->cond_);
15356 ast_dump_context->ostream() << " ? ";
15357 ast_dump_context->dump_expression(this->then_);
15358 ast_dump_context->ostream() << " : ";
15359 ast_dump_context->dump_expression(this->else_);
15360 ast_dump_context->ostream() << ") ";
15363 // Make a conditional expression.
15365 Expression*
15366 Expression::make_conditional(Expression* cond, Expression* then,
15367 Expression* else_expr, Location location)
15369 return new Conditional_expression(cond, then, else_expr, location);
15372 // Class Compound_expression.
15374 // Traversal.
15377 Compound_expression::do_traverse(Traverse* traverse)
15379 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15380 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15381 return TRAVERSE_EXIT;
15382 return TRAVERSE_CONTINUE;
15385 // Return the type of the compound expression.
15387 Type*
15388 Compound_expression::do_type()
15390 return this->expr_->type();
15393 // Determine type for a compound expression.
15395 void
15396 Compound_expression::do_determine_type(const Type_context* context)
15398 this->init_->determine_type_no_context();
15399 this->expr_->determine_type(context);
15402 // Get the backend representation of a compound expression.
15404 Bexpression*
15405 Compound_expression::do_get_backend(Translate_context* context)
15407 Gogo* gogo = context->gogo();
15408 Bexpression* binit = this->init_->get_backend(context);
15409 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15410 Bexpression* bexpr = this->expr_->get_backend(context);
15411 return gogo->backend()->compound_expression(init_stmt, bexpr,
15412 this->location());
15415 // Dump ast representation of a conditional expression.
15417 void
15418 Compound_expression::do_dump_expression(
15419 Ast_dump_context* ast_dump_context) const
15421 ast_dump_context->ostream() << "(";
15422 ast_dump_context->dump_expression(this->init_);
15423 ast_dump_context->ostream() << ",";
15424 ast_dump_context->dump_expression(this->expr_);
15425 ast_dump_context->ostream() << ") ";
15428 // Make a compound expression.
15430 Expression*
15431 Expression::make_compound(Expression* init, Expression* expr, Location location)
15433 return new Compound_expression(init, expr, location);
15436 // Import an expression. This comes at the end in order to see the
15437 // various class definitions.
15439 Expression*
15440 Expression::import_expression(Import* imp)
15442 int c = imp->peek_char();
15443 if (imp->match_c_string("- ")
15444 || imp->match_c_string("! ")
15445 || imp->match_c_string("^ "))
15446 return Unary_expression::do_import(imp);
15447 else if (c == '(')
15448 return Binary_expression::do_import(imp);
15449 else if (imp->match_c_string("true")
15450 || imp->match_c_string("false"))
15451 return Boolean_expression::do_import(imp);
15452 else if (c == '"')
15453 return String_expression::do_import(imp);
15454 else if (c == '-' || (c >= '0' && c <= '9'))
15456 // This handles integers, floats and complex constants.
15457 return Integer_expression::do_import(imp);
15459 else if (imp->match_c_string("nil"))
15460 return Nil_expression::do_import(imp);
15461 else if (imp->match_c_string("convert"))
15462 return Type_conversion_expression::do_import(imp);
15463 else
15465 go_error_at(imp->location(), "import error: expected expression");
15466 return Expression::make_error(imp->location());
15470 // Class Expression_list.
15472 // Traverse the list.
15475 Expression_list::traverse(Traverse* traverse)
15477 for (Expression_list::iterator p = this->begin();
15478 p != this->end();
15479 ++p)
15481 if (*p != NULL)
15483 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15484 return TRAVERSE_EXIT;
15487 return TRAVERSE_CONTINUE;
15490 // Copy the list.
15492 Expression_list*
15493 Expression_list::copy()
15495 Expression_list* ret = new Expression_list();
15496 for (Expression_list::iterator p = this->begin();
15497 p != this->end();
15498 ++p)
15500 if (*p == NULL)
15501 ret->push_back(NULL);
15502 else
15503 ret->push_back((*p)->copy());
15505 return ret;
15508 // Return whether an expression list has an error expression.
15510 bool
15511 Expression_list::contains_error() const
15513 for (Expression_list::const_iterator p = this->begin();
15514 p != this->end();
15515 ++p)
15516 if (*p != NULL && (*p)->is_error_expression())
15517 return true;
15518 return false;
15521 // Class Numeric_constant.
15523 // Destructor.
15525 Numeric_constant::~Numeric_constant()
15527 this->clear();
15530 // Copy constructor.
15532 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15533 : classification_(a.classification_), type_(a.type_)
15535 switch (a.classification_)
15537 case NC_INVALID:
15538 break;
15539 case NC_INT:
15540 case NC_RUNE:
15541 mpz_init_set(this->u_.int_val, a.u_.int_val);
15542 break;
15543 case NC_FLOAT:
15544 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15545 break;
15546 case NC_COMPLEX:
15547 mpc_init2(this->u_.complex_val, mpc_precision);
15548 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15549 break;
15550 default:
15551 go_unreachable();
15555 // Assignment operator.
15557 Numeric_constant&
15558 Numeric_constant::operator=(const Numeric_constant& a)
15560 this->clear();
15561 this->classification_ = a.classification_;
15562 this->type_ = a.type_;
15563 switch (a.classification_)
15565 case NC_INVALID:
15566 break;
15567 case NC_INT:
15568 case NC_RUNE:
15569 mpz_init_set(this->u_.int_val, a.u_.int_val);
15570 break;
15571 case NC_FLOAT:
15572 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15573 break;
15574 case NC_COMPLEX:
15575 mpc_init2(this->u_.complex_val, mpc_precision);
15576 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
15577 break;
15578 default:
15579 go_unreachable();
15581 return *this;
15584 // Clear the contents.
15586 void
15587 Numeric_constant::clear()
15589 switch (this->classification_)
15591 case NC_INVALID:
15592 break;
15593 case NC_INT:
15594 case NC_RUNE:
15595 mpz_clear(this->u_.int_val);
15596 break;
15597 case NC_FLOAT:
15598 mpfr_clear(this->u_.float_val);
15599 break;
15600 case NC_COMPLEX:
15601 mpc_clear(this->u_.complex_val);
15602 break;
15603 default:
15604 go_unreachable();
15606 this->classification_ = NC_INVALID;
15609 // Set to an unsigned long value.
15611 void
15612 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15614 this->clear();
15615 this->classification_ = NC_INT;
15616 this->type_ = type;
15617 mpz_init_set_ui(this->u_.int_val, val);
15620 // Set to an integer value.
15622 void
15623 Numeric_constant::set_int(Type* type, const mpz_t val)
15625 this->clear();
15626 this->classification_ = NC_INT;
15627 this->type_ = type;
15628 mpz_init_set(this->u_.int_val, val);
15631 // Set to a rune value.
15633 void
15634 Numeric_constant::set_rune(Type* type, const mpz_t val)
15636 this->clear();
15637 this->classification_ = NC_RUNE;
15638 this->type_ = type;
15639 mpz_init_set(this->u_.int_val, val);
15642 // Set to a floating point value.
15644 void
15645 Numeric_constant::set_float(Type* type, const mpfr_t val)
15647 this->clear();
15648 this->classification_ = NC_FLOAT;
15649 this->type_ = type;
15650 // Numeric constants do not have negative zero values, so remove
15651 // them here. They also don't have infinity or NaN values, but we
15652 // should never see them here.
15653 if (mpfr_zero_p(val))
15654 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15655 else
15656 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
15659 // Set to a complex value.
15661 void
15662 Numeric_constant::set_complex(Type* type, const mpc_t val)
15664 this->clear();
15665 this->classification_ = NC_COMPLEX;
15666 this->type_ = type;
15667 mpc_init2(this->u_.complex_val, mpc_precision);
15668 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
15671 // Get an int value.
15673 void
15674 Numeric_constant::get_int(mpz_t* val) const
15676 go_assert(this->is_int());
15677 mpz_init_set(*val, this->u_.int_val);
15680 // Get a rune value.
15682 void
15683 Numeric_constant::get_rune(mpz_t* val) const
15685 go_assert(this->is_rune());
15686 mpz_init_set(*val, this->u_.int_val);
15689 // Get a floating point value.
15691 void
15692 Numeric_constant::get_float(mpfr_t* val) const
15694 go_assert(this->is_float());
15695 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15698 // Get a complex value.
15700 void
15701 Numeric_constant::get_complex(mpc_t* val) const
15703 go_assert(this->is_complex());
15704 mpc_init2(*val, mpc_precision);
15705 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
15708 // Express value as unsigned long if possible.
15710 Numeric_constant::To_unsigned_long
15711 Numeric_constant::to_unsigned_long(unsigned long* val) const
15713 switch (this->classification_)
15715 case NC_INT:
15716 case NC_RUNE:
15717 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15718 case NC_FLOAT:
15719 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15720 case NC_COMPLEX:
15721 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15722 return NC_UL_NOTINT;
15723 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
15724 val);
15725 default:
15726 go_unreachable();
15730 // Express integer value as unsigned long if possible.
15732 Numeric_constant::To_unsigned_long
15733 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15734 unsigned long *val) const
15736 if (mpz_sgn(ival) < 0)
15737 return NC_UL_NEGATIVE;
15738 unsigned long ui = mpz_get_ui(ival);
15739 if (mpz_cmp_ui(ival, ui) != 0)
15740 return NC_UL_BIG;
15741 *val = ui;
15742 return NC_UL_VALID;
15745 // Express floating point value as unsigned long if possible.
15747 Numeric_constant::To_unsigned_long
15748 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15749 unsigned long *val) const
15751 if (!mpfr_integer_p(fval))
15752 return NC_UL_NOTINT;
15753 mpz_t ival;
15754 mpz_init(ival);
15755 mpfr_get_z(ival, fval, GMP_RNDN);
15756 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15757 mpz_clear(ival);
15758 return ret;
15761 // Convert value to integer if possible.
15763 bool
15764 Numeric_constant::to_int(mpz_t* val) const
15766 switch (this->classification_)
15768 case NC_INT:
15769 case NC_RUNE:
15770 mpz_init_set(*val, this->u_.int_val);
15771 return true;
15772 case NC_FLOAT:
15773 if (!mpfr_integer_p(this->u_.float_val))
15774 return false;
15775 mpz_init(*val);
15776 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15777 return true;
15778 case NC_COMPLEX:
15779 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
15780 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
15781 return false;
15782 mpz_init(*val);
15783 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15784 return true;
15785 default:
15786 go_unreachable();
15790 // Convert value to floating point if possible.
15792 bool
15793 Numeric_constant::to_float(mpfr_t* val) const
15795 switch (this->classification_)
15797 case NC_INT:
15798 case NC_RUNE:
15799 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15800 return true;
15801 case NC_FLOAT:
15802 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15803 return true;
15804 case NC_COMPLEX:
15805 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15806 return false;
15807 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15808 return true;
15809 default:
15810 go_unreachable();
15814 // Convert value to complex.
15816 bool
15817 Numeric_constant::to_complex(mpc_t* val) const
15819 mpc_init2(*val, mpc_precision);
15820 switch (this->classification_)
15822 case NC_INT:
15823 case NC_RUNE:
15824 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
15825 return true;
15826 case NC_FLOAT:
15827 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
15828 return true;
15829 case NC_COMPLEX:
15830 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
15831 return true;
15832 default:
15833 go_unreachable();
15837 // Get the type.
15839 Type*
15840 Numeric_constant::type() const
15842 if (this->type_ != NULL)
15843 return this->type_;
15844 switch (this->classification_)
15846 case NC_INT:
15847 return Type::make_abstract_integer_type();
15848 case NC_RUNE:
15849 return Type::make_abstract_character_type();
15850 case NC_FLOAT:
15851 return Type::make_abstract_float_type();
15852 case NC_COMPLEX:
15853 return Type::make_abstract_complex_type();
15854 default:
15855 go_unreachable();
15859 // If the constant can be expressed in TYPE, then set the type of the
15860 // constant to TYPE and return true. Otherwise return false, and, if
15861 // ISSUE_ERROR is true, report an appropriate error message.
15863 bool
15864 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15866 bool ret;
15867 if (type == NULL || type->is_error())
15868 ret = true;
15869 else if (type->integer_type() != NULL)
15870 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15871 else if (type->float_type() != NULL)
15872 ret = this->check_float_type(type->float_type(), issue_error, loc);
15873 else if (type->complex_type() != NULL)
15874 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15875 else
15877 ret = false;
15878 if (issue_error)
15879 go_assert(saw_errors());
15881 if (ret)
15882 this->type_ = type;
15883 return ret;
15886 // Check whether the constant can be expressed in an integer type.
15888 bool
15889 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15890 Location location)
15892 mpz_t val;
15893 switch (this->classification_)
15895 case NC_INT:
15896 case NC_RUNE:
15897 mpz_init_set(val, this->u_.int_val);
15898 break;
15900 case NC_FLOAT:
15901 if (!mpfr_integer_p(this->u_.float_val))
15903 if (issue_error)
15905 go_error_at(location,
15906 "floating point constant truncated to integer");
15907 this->set_invalid();
15909 return false;
15911 mpz_init(val);
15912 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15913 break;
15915 case NC_COMPLEX:
15916 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15917 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15919 if (issue_error)
15921 go_error_at(location, "complex constant truncated to integer");
15922 this->set_invalid();
15924 return false;
15926 mpz_init(val);
15927 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15928 break;
15930 default:
15931 go_unreachable();
15934 bool ret;
15935 if (type->is_abstract())
15936 ret = true;
15937 else
15939 int bits = mpz_sizeinbase(val, 2);
15940 if (type->is_unsigned())
15942 // For an unsigned type we can only accept a nonnegative
15943 // number, and we must be able to represents at least BITS.
15944 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15946 else
15948 // For a signed type we need an extra bit to indicate the
15949 // sign. We have to handle the most negative integer
15950 // specially.
15951 ret = (bits + 1 <= type->bits()
15952 || (bits <= type->bits()
15953 && mpz_sgn(val) < 0
15954 && (mpz_scan1(val, 0)
15955 == static_cast<unsigned long>(type->bits() - 1))
15956 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15960 if (!ret && issue_error)
15962 go_error_at(location, "integer constant overflow");
15963 this->set_invalid();
15966 return ret;
15969 // Check whether the constant can be expressed in a floating point
15970 // type.
15972 bool
15973 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15974 Location location)
15976 mpfr_t val;
15977 switch (this->classification_)
15979 case NC_INT:
15980 case NC_RUNE:
15981 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15982 break;
15984 case NC_FLOAT:
15985 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15986 break;
15988 case NC_COMPLEX:
15989 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15991 if (issue_error)
15993 this->set_invalid();
15994 go_error_at(location, "complex constant truncated to float");
15996 return false;
15998 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15999 break;
16001 default:
16002 go_unreachable();
16005 bool ret;
16006 if (type->is_abstract())
16007 ret = true;
16008 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
16010 // A NaN or Infinity always fits in the range of the type.
16011 ret = true;
16013 else
16015 mp_exp_t exp = mpfr_get_exp(val);
16016 mp_exp_t max_exp;
16017 switch (type->bits())
16019 case 32:
16020 max_exp = 128;
16021 break;
16022 case 64:
16023 max_exp = 1024;
16024 break;
16025 default:
16026 go_unreachable();
16029 ret = exp <= max_exp;
16031 if (ret)
16033 // Round the constant to the desired type.
16034 mpfr_t t;
16035 mpfr_init(t);
16036 switch (type->bits())
16038 case 32:
16039 mpfr_set_prec(t, 24);
16040 break;
16041 case 64:
16042 mpfr_set_prec(t, 53);
16043 break;
16044 default:
16045 go_unreachable();
16047 mpfr_set(t, val, GMP_RNDN);
16048 mpfr_set(val, t, GMP_RNDN);
16049 mpfr_clear(t);
16051 this->set_float(type, val);
16055 mpfr_clear(val);
16057 if (!ret && issue_error)
16059 go_error_at(location, "floating point constant overflow");
16060 this->set_invalid();
16063 return ret;
16066 // Check whether the constant can be expressed in a complex type.
16068 bool
16069 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
16070 Location location)
16072 if (type->is_abstract())
16073 return true;
16075 mp_exp_t max_exp;
16076 switch (type->bits())
16078 case 64:
16079 max_exp = 128;
16080 break;
16081 case 128:
16082 max_exp = 1024;
16083 break;
16084 default:
16085 go_unreachable();
16088 mpc_t val;
16089 mpc_init2(val, mpc_precision);
16090 switch (this->classification_)
16092 case NC_INT:
16093 case NC_RUNE:
16094 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
16095 break;
16097 case NC_FLOAT:
16098 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
16099 break;
16101 case NC_COMPLEX:
16102 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
16103 break;
16105 default:
16106 go_unreachable();
16109 bool ret = true;
16110 if (!mpfr_nan_p(mpc_realref(val))
16111 && !mpfr_inf_p(mpc_realref(val))
16112 && !mpfr_zero_p(mpc_realref(val))
16113 && mpfr_get_exp(mpc_realref(val)) > max_exp)
16115 if (issue_error)
16117 go_error_at(location, "complex real part overflow");
16118 this->set_invalid();
16120 ret = false;
16123 if (!mpfr_nan_p(mpc_imagref(val))
16124 && !mpfr_inf_p(mpc_imagref(val))
16125 && !mpfr_zero_p(mpc_imagref(val))
16126 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
16128 if (issue_error)
16130 go_error_at(location, "complex imaginary part overflow");
16131 this->set_invalid();
16133 ret = false;
16136 if (ret)
16138 // Round the constant to the desired type.
16139 mpc_t t;
16140 switch (type->bits())
16142 case 64:
16143 mpc_init2(t, 24);
16144 break;
16145 case 128:
16146 mpc_init2(t, 53);
16147 break;
16148 default:
16149 go_unreachable();
16151 mpc_set(t, val, MPC_RNDNN);
16152 mpc_set(val, t, MPC_RNDNN);
16153 mpc_clear(t);
16155 this->set_complex(type, val);
16158 mpc_clear(val);
16160 return ret;
16163 // Return an Expression for this value.
16165 Expression*
16166 Numeric_constant::expression(Location loc) const
16168 switch (this->classification_)
16170 case NC_INT:
16171 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
16172 case NC_RUNE:
16173 return Expression::make_character(&this->u_.int_val, this->type_, loc);
16174 case NC_FLOAT:
16175 return Expression::make_float(&this->u_.float_val, this->type_, loc);
16176 case NC_COMPLEX:
16177 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
16178 case NC_INVALID:
16179 go_assert(saw_errors());
16180 return Expression::make_error(loc);
16181 default:
16182 go_unreachable();