compiler: Simplify making integer expressions.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob0ec65691dd802f0f2f8498007d0243e148a7ab88
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 "types.h"
14 #include "export.h"
15 #include "import.h"
16 #include "statements.h"
17 #include "lex.h"
18 #include "runtime.h"
19 #include "backend.h"
20 #include "expressions.h"
21 #include "ast-dump.h"
23 // Class Expression.
25 Expression::Expression(Expression_classification classification,
26 Location location)
27 : classification_(classification), location_(location)
31 Expression::~Expression()
35 // Traverse the expressions.
37 int
38 Expression::traverse(Expression** pexpr, Traverse* traverse)
40 Expression* expr = *pexpr;
41 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
43 int t = traverse->expression(pexpr);
44 if (t == TRAVERSE_EXIT)
45 return TRAVERSE_EXIT;
46 else if (t == TRAVERSE_SKIP_COMPONENTS)
47 return TRAVERSE_CONTINUE;
49 return expr->do_traverse(traverse);
52 // Traverse subexpressions of this expression.
54 int
55 Expression::traverse_subexpressions(Traverse* traverse)
57 return this->do_traverse(traverse);
60 // Default implementation for do_traverse for child classes.
62 int
63 Expression::do_traverse(Traverse*)
65 return TRAVERSE_CONTINUE;
68 // This virtual function is called by the parser if the value of this
69 // expression is being discarded. By default, we give an error.
70 // Expressions with side effects override.
72 bool
73 Expression::do_discarding_value()
75 this->unused_value_error();
76 return false;
79 // This virtual function is called to export expressions. This will
80 // only be used by expressions which may be constant.
82 void
83 Expression::do_export(Export*) const
85 go_unreachable();
88 // Give an error saying that the value of the expression is not used.
90 void
91 Expression::unused_value_error()
93 this->report_error(_("value computed is not used"));
96 // Note that this expression is an error. This is called by children
97 // when they discover an error.
99 void
100 Expression::set_is_error()
102 this->classification_ = EXPRESSION_ERROR;
105 // For children to call to report an error conveniently.
107 void
108 Expression::report_error(const char* msg)
110 error_at(this->location_, "%s", msg);
111 this->set_is_error();
114 // Set types of variables and constants. This is implemented by the
115 // child class.
117 void
118 Expression::determine_type(const Type_context* context)
120 this->do_determine_type(context);
123 // Set types when there is no context.
125 void
126 Expression::determine_type_no_context()
128 Type_context context;
129 this->do_determine_type(&context);
132 // Return an expression handling any conversions which must be done during
133 // assignment.
135 Expression*
136 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
137 Expression* rhs, Location location)
139 Type* rhs_type = rhs->type();
140 if (lhs_type->is_error()
141 || rhs_type->is_error()
142 || rhs->is_error_expression())
143 return Expression::make_error(location);
145 if (lhs_type->forwarded() != rhs_type->forwarded()
146 && lhs_type->interface_type() != NULL)
148 if (rhs_type->interface_type() == NULL)
149 return Expression::convert_type_to_interface(lhs_type, rhs, location);
150 else
151 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
152 location);
154 else if (lhs_type->forwarded() != rhs_type->forwarded()
155 && rhs_type->interface_type() != NULL)
156 return Expression::convert_interface_to_type(lhs_type, rhs, location);
157 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
159 // Assigning nil to a slice.
160 Expression* nil = Expression::make_nil(location);
161 Expression* zero = Expression::make_integer_ul(0, NULL, location);
162 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
164 else if (rhs_type->is_nil_type())
165 return Expression::make_nil(location);
166 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
168 // No conversion is needed.
169 return rhs;
171 else if (lhs_type->points_to() != NULL)
172 return Expression::make_unsafe_cast(lhs_type, rhs, location);
173 else if (lhs_type->is_numeric_type())
174 return Expression::make_cast(lhs_type, rhs, location);
175 else if ((lhs_type->struct_type() != NULL
176 && rhs_type->struct_type() != NULL)
177 || (lhs_type->array_type() != NULL
178 && rhs_type->array_type() != NULL))
180 // Avoid confusion from zero sized variables which may be
181 // represented as non-zero-sized.
182 // TODO(cmang): This check is for a GCC-specific issue, and should be
183 // removed from the frontend. FIXME.
184 size_t lhs_size = gogo->backend()->type_size(lhs_type->get_backend(gogo));
185 size_t rhs_size = gogo->backend()->type_size(rhs_type->get_backend(gogo));
186 if (rhs_size == 0 || lhs_size == 0)
187 return rhs;
189 // This conversion must be permitted by Go, or we wouldn't have
190 // gotten here.
191 return Expression::make_unsafe_cast(lhs_type, rhs, location);
193 else
194 return rhs;
197 // Return an expression for a conversion from a non-interface type to an
198 // interface type.
200 Expression*
201 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
202 Location location)
204 Interface_type* lhs_interface_type = lhs_type->interface_type();
205 bool lhs_is_empty = lhs_interface_type->is_empty();
207 // Since RHS_TYPE is a static type, we can create the interface
208 // method table at compile time.
210 // When setting an interface to nil, we just set both fields to
211 // NULL.
212 Type* rhs_type = rhs->type();
213 if (rhs_type->is_nil_type())
215 Expression* nil = Expression::make_nil(location);
216 return Expression::make_interface_value(lhs_type, nil, nil, location);
219 // This should have been checked already.
220 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
222 // An interface is a tuple. If LHS_TYPE is an empty interface type,
223 // then the first field is the type descriptor for RHS_TYPE.
224 // Otherwise it is the interface method table for RHS_TYPE.
225 Expression* first_field;
226 if (lhs_is_empty)
227 first_field = Expression::make_type_descriptor(rhs_type, location);
228 else
230 // Build the interface method table for this interface and this
231 // object type: a list of function pointers for each interface
232 // method.
233 Named_type* rhs_named_type = rhs_type->named_type();
234 Struct_type* rhs_struct_type = rhs_type->struct_type();
235 bool is_pointer = false;
236 if (rhs_named_type == NULL && rhs_struct_type == NULL)
238 rhs_named_type = rhs_type->deref()->named_type();
239 rhs_struct_type = rhs_type->deref()->struct_type();
240 is_pointer = true;
242 if (rhs_named_type != NULL)
243 first_field =
244 rhs_named_type->interface_method_table(lhs_interface_type,
245 is_pointer);
246 else if (rhs_struct_type != NULL)
247 first_field =
248 rhs_struct_type->interface_method_table(lhs_interface_type,
249 is_pointer);
250 else
251 first_field = Expression::make_nil(location);
254 Expression* obj;
255 if (rhs_type->points_to() != NULL)
257 // We are assigning a pointer to the interface; the interface
258 // holds the pointer itself.
259 obj = rhs;
261 else
263 // We are assigning a non-pointer value to the interface; the
264 // interface gets a copy of the value in the heap.
265 obj = Expression::make_heap_expression(rhs, location);
268 return Expression::make_interface_value(lhs_type, first_field, obj, location);
271 // Return an expression for the type descriptor of RHS.
273 Expression*
274 Expression::get_interface_type_descriptor(Expression* rhs)
276 go_assert(rhs->type()->interface_type() != NULL);
277 Location location = rhs->location();
279 // The type descriptor is the first field of an empty interface.
280 if (rhs->type()->interface_type()->is_empty())
281 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
282 location);
284 Expression* mtable =
285 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
287 Expression* descriptor =
288 Expression::make_unary(OPERATOR_MULT, mtable, location);
289 descriptor = Expression::make_field_reference(descriptor, 0, location);
290 Expression* nil = Expression::make_nil(location);
292 Expression* eq =
293 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
294 return Expression::make_conditional(eq, nil, descriptor, location);
297 // Return an expression for the conversion of an interface type to an
298 // interface type.
300 Expression*
301 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
302 bool for_type_guard,
303 Location location)
305 Interface_type* lhs_interface_type = lhs_type->interface_type();
306 bool lhs_is_empty = lhs_interface_type->is_empty();
308 // In the general case this requires runtime examination of the type
309 // method table to match it up with the interface methods.
311 // FIXME: If all of the methods in the right hand side interface
312 // also appear in the left hand side interface, then we don't need
313 // to do a runtime check, although we still need to build a new
314 // method table.
316 // Get the type descriptor for the right hand side. This will be
317 // NULL for a nil interface.
318 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
319 Expression* lhs_type_expr =
320 Expression::make_type_descriptor(lhs_type, location);
322 Expression* first_field;
323 if (for_type_guard)
325 // A type assertion fails when converting a nil interface.
326 first_field =
327 Runtime::make_call(Runtime::ASSERT_INTERFACE, 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 =
341 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
342 lhs_type_expr, rhs_type_expr);
345 // The second field is simply the object pointer.
346 Expression* obj =
347 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
348 return Expression::make_interface_value(lhs_type, first_field, obj, location);
351 // Return an expression for the conversion of an interface type to a
352 // non-interface type.
354 Expression*
355 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
356 Location location)
358 // Call a function to check that the type is valid. The function
359 // will panic with an appropriate runtime type error if the type is
360 // not valid.
361 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
362 location);
363 Expression* rhs_descriptor =
364 Expression::get_interface_type_descriptor(rhs);
366 Type* rhs_type = rhs->type();
367 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
368 location);
370 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
371 location, 3, lhs_type_expr,
372 rhs_descriptor, rhs_inter_expr);
374 // If the call succeeds, pull out the value.
375 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
376 location);
378 // If the value is a pointer, then it is the value we want.
379 // Otherwise it points to the value.
380 if (lhs_type->points_to() == NULL)
382 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
383 location);
384 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
386 return Expression::make_compound(check_iface, obj, location);
389 // Convert an expression to its backend representation. This is implemented by
390 // the child class. Not that it is not in general safe to call this multiple
391 // times for a single expression, but that we don't catch such errors.
393 Bexpression*
394 Expression::get_backend(Translate_context* context)
396 // The child may have marked this expression as having an error.
397 if (this->classification_ == EXPRESSION_ERROR)
398 return context->backend()->error_expression();
400 return this->do_get_backend(context);
403 // Return a backend expression for VAL.
404 Bexpression*
405 Expression::backend_numeric_constant_expression(Translate_context* context,
406 Numeric_constant* val)
408 Gogo* gogo = context->gogo();
409 Type* type = val->type();
410 if (type == NULL)
411 return gogo->backend()->error_expression();
413 Btype* btype = type->get_backend(gogo);
414 Bexpression* ret;
415 if (type->integer_type() != NULL)
417 mpz_t ival;
418 if (!val->to_int(&ival))
420 go_assert(saw_errors());
421 return gogo->backend()->error_expression();
423 ret = gogo->backend()->integer_constant_expression(btype, ival);
424 mpz_clear(ival);
426 else if (type->float_type() != NULL)
428 mpfr_t fval;
429 if (!val->to_float(&fval))
431 go_assert(saw_errors());
432 return gogo->backend()->error_expression();
434 ret = gogo->backend()->float_constant_expression(btype, fval);
435 mpfr_clear(fval);
437 else if (type->complex_type() != NULL)
439 mpfr_t real;
440 mpfr_t imag;
441 if (!val->to_complex(&real, &imag))
443 go_assert(saw_errors());
444 return gogo->backend()->error_expression();
446 ret = gogo->backend()->complex_constant_expression(btype, real, imag);
447 mpfr_clear(real);
448 mpfr_clear(imag);
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_is_immutable() const
541 { return true; }
543 bool
544 do_numeric_constant_value(Numeric_constant* nc) const
546 nc->set_unsigned_long(NULL, 0);
547 return true;
550 bool
551 do_discarding_value()
552 { return true; }
554 Type*
555 do_type()
556 { return Type::make_error_type(); }
558 void
559 do_determine_type(const Type_context*)
562 Expression*
563 do_copy()
564 { return this; }
566 bool
567 do_is_addressable() const
568 { return true; }
570 Bexpression*
571 do_get_backend(Translate_context* context)
572 { return context->backend()->error_expression(); }
574 void
575 do_dump_expression(Ast_dump_context*) const;
578 // Dump the ast representation for an error expression to a dump context.
580 void
581 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
583 ast_dump_context->ostream() << "_Error_" ;
586 Expression*
587 Expression::make_error(Location location)
589 return new Error_expression(location);
592 // An expression which is really a type. This is used during parsing.
593 // It is an error if these survive after lowering.
595 class
596 Type_expression : public Expression
598 public:
599 Type_expression(Type* type, Location location)
600 : Expression(EXPRESSION_TYPE, location),
601 type_(type)
604 protected:
606 do_traverse(Traverse* traverse)
607 { return Type::traverse(this->type_, traverse); }
609 Type*
610 do_type()
611 { return this->type_; }
613 void
614 do_determine_type(const Type_context*)
617 void
618 do_check_types(Gogo*)
619 { this->report_error(_("invalid use of type")); }
621 Expression*
622 do_copy()
623 { return this; }
625 Bexpression*
626 do_get_backend(Translate_context*)
627 { go_unreachable(); }
629 void do_dump_expression(Ast_dump_context*) const;
631 private:
632 // The type which we are representing as an expression.
633 Type* type_;
636 void
637 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
639 ast_dump_context->dump_type(this->type_);
642 Expression*
643 Expression::make_type(Type* type, Location location)
645 return new Type_expression(type, location);
648 // Class Parser_expression.
650 Type*
651 Parser_expression::do_type()
653 // We should never really ask for the type of a Parser_expression.
654 // However, it can happen, at least when we have an invalid const
655 // whose initializer refers to the const itself. In that case we
656 // may ask for the type when lowering the const itself.
657 go_assert(saw_errors());
658 return Type::make_error_type();
661 // Class Var_expression.
663 // Lower a variable expression. Here we just make sure that the
664 // initialization expression of the variable has been lowered. This
665 // ensures that we will be able to determine the type of the variable
666 // if necessary.
668 Expression*
669 Var_expression::do_lower(Gogo* gogo, Named_object* function,
670 Statement_inserter* inserter, int)
672 if (this->variable_->is_variable())
674 Variable* var = this->variable_->var_value();
675 // This is either a local variable or a global variable. A
676 // reference to a variable which is local to an enclosing
677 // function will be a reference to a field in a closure.
678 if (var->is_global())
680 function = NULL;
681 inserter = NULL;
683 var->lower_init_expression(gogo, function, inserter);
685 return this;
688 // Return the type of a reference to a variable.
690 Type*
691 Var_expression::do_type()
693 if (this->variable_->is_variable())
694 return this->variable_->var_value()->type();
695 else if (this->variable_->is_result_variable())
696 return this->variable_->result_var_value()->type();
697 else
698 go_unreachable();
701 // Determine the type of a reference to a variable.
703 void
704 Var_expression::do_determine_type(const Type_context*)
706 if (this->variable_->is_variable())
707 this->variable_->var_value()->determine_type();
710 // Something takes the address of this variable. This means that we
711 // may want to move the variable onto the heap.
713 void
714 Var_expression::do_address_taken(bool escapes)
716 if (!escapes)
718 if (this->variable_->is_variable())
719 this->variable_->var_value()->set_non_escaping_address_taken();
720 else if (this->variable_->is_result_variable())
721 this->variable_->result_var_value()->set_non_escaping_address_taken();
722 else
723 go_unreachable();
725 else
727 if (this->variable_->is_variable())
728 this->variable_->var_value()->set_address_taken();
729 else if (this->variable_->is_result_variable())
730 this->variable_->result_var_value()->set_address_taken();
731 else
732 go_unreachable();
736 // Get the backend representation for a reference to a variable.
738 Bexpression*
739 Var_expression::do_get_backend(Translate_context* context)
741 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
742 context->function());
743 bool is_in_heap;
744 Location loc = this->location();
745 Btype* btype;
746 Gogo* gogo = context->gogo();
747 if (this->variable_->is_variable())
749 is_in_heap = this->variable_->var_value()->is_in_heap();
750 btype = this->variable_->var_value()->type()->get_backend(gogo);
752 else if (this->variable_->is_result_variable())
754 is_in_heap = this->variable_->result_var_value()->is_in_heap();
755 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
757 else
758 go_unreachable();
760 Bexpression* ret = context->backend()->var_expression(bvar, loc);
761 if (is_in_heap)
762 ret = context->backend()->indirect_expression(btype, ret, true, loc);
763 return ret;
766 // Ast dump for variable expression.
768 void
769 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
771 ast_dump_context->ostream() << this->variable_->name() ;
774 // Make a reference to a variable in an expression.
776 Expression*
777 Expression::make_var_reference(Named_object* var, Location location)
779 if (var->is_sink())
780 return Expression::make_sink(location);
782 // FIXME: Creating a new object for each reference to a variable is
783 // wasteful.
784 return new Var_expression(var, location);
787 // Class Temporary_reference_expression.
789 // The type.
791 Type*
792 Temporary_reference_expression::do_type()
794 return this->statement_->type();
797 // Called if something takes the address of this temporary variable.
798 // We never have to move temporary variables to the heap, but we do
799 // need to know that they must live in the stack rather than in a
800 // register.
802 void
803 Temporary_reference_expression::do_address_taken(bool)
805 this->statement_->set_is_address_taken();
808 // Get a backend expression referring to the variable.
810 Bexpression*
811 Temporary_reference_expression::do_get_backend(Translate_context* context)
813 Gogo* gogo = context->gogo();
814 Bvariable* bvar = this->statement_->get_backend_variable(context);
815 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
817 // The backend can't always represent the same set of recursive types
818 // that the Go frontend can. In some cases this means that a
819 // temporary variable won't have the right backend type. Correct
820 // that here by adding a type cast. We need to use base() to push
821 // the circularity down one level.
822 Type* stype = this->statement_->type();
823 if (!this->is_lvalue_
824 && stype->has_pointer()
825 && stype->deref()->is_void_type())
827 Btype* btype = this->type()->base()->get_backend(gogo);
828 ret = gogo->backend()->convert_expression(btype, ret, this->location());
830 return ret;
833 // Ast dump for temporary reference.
835 void
836 Temporary_reference_expression::do_dump_expression(
837 Ast_dump_context* ast_dump_context) const
839 ast_dump_context->dump_temp_variable_name(this->statement_);
842 // Make a reference to a temporary variable.
844 Temporary_reference_expression*
845 Expression::make_temporary_reference(Temporary_statement* statement,
846 Location location)
848 return new Temporary_reference_expression(statement, location);
851 // Class Set_and_use_temporary_expression.
853 // Return the type.
855 Type*
856 Set_and_use_temporary_expression::do_type()
858 return this->statement_->type();
861 // Determine the type of the expression.
863 void
864 Set_and_use_temporary_expression::do_determine_type(
865 const Type_context* context)
867 this->expr_->determine_type(context);
870 // Take the address.
872 void
873 Set_and_use_temporary_expression::do_address_taken(bool)
875 this->statement_->set_is_address_taken();
878 // Return the backend representation.
880 Bexpression*
881 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
883 Location loc = this->location();
884 Gogo* gogo = context->gogo();
885 Bvariable* bvar = this->statement_->get_backend_variable(context);
886 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
888 Bexpression* bexpr = this->expr_->get_backend(context);
889 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
890 var_ref = gogo->backend()->var_expression(bvar, loc);
891 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
892 return ret;
895 // Dump.
897 void
898 Set_and_use_temporary_expression::do_dump_expression(
899 Ast_dump_context* ast_dump_context) const
901 ast_dump_context->ostream() << '(';
902 ast_dump_context->dump_temp_variable_name(this->statement_);
903 ast_dump_context->ostream() << " = ";
904 this->expr_->dump_expression(ast_dump_context);
905 ast_dump_context->ostream() << ')';
908 // Make a set-and-use temporary.
910 Set_and_use_temporary_expression*
911 Expression::make_set_and_use_temporary(Temporary_statement* statement,
912 Expression* expr, Location location)
914 return new Set_and_use_temporary_expression(statement, expr, location);
917 // A sink expression--a use of the blank identifier _.
919 class Sink_expression : public Expression
921 public:
922 Sink_expression(Location location)
923 : Expression(EXPRESSION_SINK, location),
924 type_(NULL), bvar_(NULL)
927 protected:
928 bool
929 do_discarding_value()
930 { return true; }
932 Type*
933 do_type();
935 void
936 do_determine_type(const Type_context*);
938 Expression*
939 do_copy()
940 { return new Sink_expression(this->location()); }
942 Bexpression*
943 do_get_backend(Translate_context*);
945 void
946 do_dump_expression(Ast_dump_context*) const;
948 private:
949 // The type of this sink variable.
950 Type* type_;
951 // The temporary variable we generate.
952 Bvariable* bvar_;
955 // Return the type of a sink expression.
957 Type*
958 Sink_expression::do_type()
960 if (this->type_ == NULL)
961 return Type::make_sink_type();
962 return this->type_;
965 // Determine the type of a sink expression.
967 void
968 Sink_expression::do_determine_type(const Type_context* context)
970 if (context->type != NULL)
971 this->type_ = context->type;
974 // Return a temporary variable for a sink expression. This will
975 // presumably be a write-only variable which the middle-end will drop.
977 Bexpression*
978 Sink_expression::do_get_backend(Translate_context* context)
980 Location loc = this->location();
981 Gogo* gogo = context->gogo();
982 if (this->bvar_ == NULL)
984 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
985 Named_object* fn = context->function();
986 go_assert(fn != NULL);
987 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
988 Btype* bt = this->type_->get_backend(context->gogo());
989 Bstatement* decl;
990 this->bvar_ =
991 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
992 false, loc, &decl);
993 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
994 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
995 return var_ref;
997 return gogo->backend()->var_expression(this->bvar_, loc);
1000 // Ast dump for sink expression.
1002 void
1003 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1005 ast_dump_context->ostream() << "_" ;
1008 // Make a sink expression.
1010 Expression*
1011 Expression::make_sink(Location location)
1013 return new Sink_expression(location);
1016 // Class Func_expression.
1018 // FIXME: Can a function expression appear in a constant expression?
1019 // The value is unchanging. Initializing a constant to the address of
1020 // a function seems like it could work, though there might be little
1021 // point to it.
1023 // Traversal.
1026 Func_expression::do_traverse(Traverse* traverse)
1028 return (this->closure_ == NULL
1029 ? TRAVERSE_CONTINUE
1030 : Expression::traverse(&this->closure_, traverse));
1033 // Return the type of a function expression.
1035 Type*
1036 Func_expression::do_type()
1038 if (this->function_->is_function())
1039 return this->function_->func_value()->type();
1040 else if (this->function_->is_function_declaration())
1041 return this->function_->func_declaration_value()->type();
1042 else
1043 go_unreachable();
1046 // Get the backend representation for the code of a function expression.
1048 Bexpression*
1049 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1051 Function_type* fntype;
1052 if (no->is_function())
1053 fntype = no->func_value()->type();
1054 else if (no->is_function_declaration())
1055 fntype = no->func_declaration_value()->type();
1056 else
1057 go_unreachable();
1059 // Builtin functions are handled specially by Call_expression. We
1060 // can't take their address.
1061 if (fntype->is_builtin())
1063 error_at(loc,
1064 "invalid use of special builtin function %qs; must be called",
1065 no->message_name().c_str());
1066 return gogo->backend()->error_expression();
1069 Bfunction* fndecl;
1070 if (no->is_function())
1071 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1072 else if (no->is_function_declaration())
1073 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1074 else
1075 go_unreachable();
1077 return gogo->backend()->function_code_expression(fndecl, loc);
1080 // Get the backend representation for a function expression. This is used when
1081 // we take the address of a function rather than simply calling it. A func
1082 // value is represented as a pointer to a block of memory. The first
1083 // word of that memory is a pointer to the function code. The
1084 // remaining parts of that memory are the addresses of variables that
1085 // the function closes over.
1087 Bexpression*
1088 Func_expression::do_get_backend(Translate_context* context)
1090 // If there is no closure, just use the function descriptor.
1091 if (this->closure_ == NULL)
1093 Gogo* gogo = context->gogo();
1094 Named_object* no = this->function_;
1095 Expression* descriptor;
1096 if (no->is_function())
1097 descriptor = no->func_value()->descriptor(gogo, no);
1098 else if (no->is_function_declaration())
1100 if (no->func_declaration_value()->type()->is_builtin())
1102 error_at(this->location(),
1103 ("invalid use of special builtin function %qs; "
1104 "must be called"),
1105 no->message_name().c_str());
1106 return gogo->backend()->error_expression();
1108 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1110 else
1111 go_unreachable();
1113 Bexpression* bdesc = descriptor->get_backend(context);
1114 return gogo->backend()->address_expression(bdesc, this->location());
1117 go_assert(this->function_->func_value()->enclosing() != NULL);
1119 // If there is a closure, then the closure is itself the function
1120 // expression. It is a pointer to a struct whose first field points
1121 // to the function code and whose remaining fields are the addresses
1122 // of the closed-over variables.
1123 return this->closure_->get_backend(context);
1126 // Ast dump for function.
1128 void
1129 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1131 ast_dump_context->ostream() << this->function_->name();
1132 if (this->closure_ != NULL)
1134 ast_dump_context->ostream() << " {closure = ";
1135 this->closure_->dump_expression(ast_dump_context);
1136 ast_dump_context->ostream() << "}";
1140 // Make a reference to a function in an expression.
1142 Expression*
1143 Expression::make_func_reference(Named_object* function, Expression* closure,
1144 Location location)
1146 return new Func_expression(function, closure, location);
1149 // Class Func_descriptor_expression.
1151 // Constructor.
1153 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1154 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1155 fn_(fn), dvar_(NULL)
1157 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1160 // Traversal.
1163 Func_descriptor_expression::do_traverse(Traverse*)
1165 return TRAVERSE_CONTINUE;
1168 // All function descriptors have the same type.
1170 Type* Func_descriptor_expression::descriptor_type;
1172 void
1173 Func_descriptor_expression::make_func_descriptor_type()
1175 if (Func_descriptor_expression::descriptor_type != NULL)
1176 return;
1177 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1178 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1179 Func_descriptor_expression::descriptor_type =
1180 Type::make_builtin_named_type("functionDescriptor", struct_type);
1183 Type*
1184 Func_descriptor_expression::do_type()
1186 Func_descriptor_expression::make_func_descriptor_type();
1187 return Func_descriptor_expression::descriptor_type;
1190 // The backend representation for a function descriptor.
1192 Bexpression*
1193 Func_descriptor_expression::do_get_backend(Translate_context* context)
1195 Named_object* no = this->fn_;
1196 Location loc = no->location();
1197 if (this->dvar_ != NULL)
1198 return context->backend()->var_expression(this->dvar_, loc);
1200 Gogo* gogo = context->gogo();
1201 std::string var_name;
1202 if (no->package() == NULL)
1203 var_name = gogo->pkgpath_symbol();
1204 else
1205 var_name = no->package()->pkgpath_symbol();
1206 var_name.push_back('.');
1207 var_name.append(Gogo::unpack_hidden_name(no->name()));
1208 var_name.append("$descriptor");
1210 Btype* btype = this->type()->get_backend(gogo);
1212 Bvariable* bvar;
1213 if (no->package() != NULL
1214 || Linemap::is_predeclared_location(no->location()))
1215 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1216 loc);
1217 else
1219 Location bloc = Linemap::predeclared_location();
1220 bool is_hidden = ((no->is_function()
1221 && no->func_value()->enclosing() != NULL)
1222 || Gogo::is_thunk(no));
1223 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1224 btype, bloc);
1225 Expression_list* vals = new Expression_list();
1226 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1227 Expression* init =
1228 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1229 Translate_context bcontext(gogo, NULL, NULL, NULL);
1230 bcontext.set_is_const();
1231 Bexpression* binit = init->get_backend(&bcontext);
1232 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1233 false, btype, bloc, binit);
1236 this->dvar_ = bvar;
1237 return gogo->backend()->var_expression(bvar, loc);
1240 // Print a function descriptor expression.
1242 void
1243 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1245 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1248 // Make a function descriptor expression.
1250 Func_descriptor_expression*
1251 Expression::make_func_descriptor(Named_object* fn)
1253 return new Func_descriptor_expression(fn);
1256 // Make the function descriptor type, so that it can be converted.
1258 void
1259 Expression::make_func_descriptor_type()
1261 Func_descriptor_expression::make_func_descriptor_type();
1264 // A reference to just the code of a function.
1266 class Func_code_reference_expression : public Expression
1268 public:
1269 Func_code_reference_expression(Named_object* function, Location location)
1270 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1271 function_(function)
1274 protected:
1276 do_traverse(Traverse*)
1277 { return TRAVERSE_CONTINUE; }
1279 bool
1280 do_is_immutable() const
1281 { return true; }
1283 Type*
1284 do_type()
1285 { return Type::make_pointer_type(Type::make_void_type()); }
1287 void
1288 do_determine_type(const Type_context*)
1291 Expression*
1292 do_copy()
1294 return Expression::make_func_code_reference(this->function_,
1295 this->location());
1298 Bexpression*
1299 do_get_backend(Translate_context*);
1301 void
1302 do_dump_expression(Ast_dump_context* context) const
1303 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1305 private:
1306 // The function.
1307 Named_object* function_;
1310 // Get the backend representation for a reference to function code.
1312 Bexpression*
1313 Func_code_reference_expression::do_get_backend(Translate_context* context)
1315 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1316 this->location());
1319 // Make a reference to the code of a function.
1321 Expression*
1322 Expression::make_func_code_reference(Named_object* function, Location location)
1324 return new Func_code_reference_expression(function, location);
1327 // Class Unknown_expression.
1329 // Return the name of an unknown expression.
1331 const std::string&
1332 Unknown_expression::name() const
1334 return this->named_object_->name();
1337 // Lower a reference to an unknown name.
1339 Expression*
1340 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1342 Location location = this->location();
1343 Named_object* no = this->named_object_;
1344 Named_object* real;
1345 if (!no->is_unknown())
1346 real = no;
1347 else
1349 real = no->unknown_value()->real_named_object();
1350 if (real == NULL)
1352 if (this->is_composite_literal_key_)
1353 return this;
1354 if (!this->no_error_message_)
1355 error_at(location, "reference to undefined name %qs",
1356 this->named_object_->message_name().c_str());
1357 return Expression::make_error(location);
1360 switch (real->classification())
1362 case Named_object::NAMED_OBJECT_CONST:
1363 return Expression::make_const_reference(real, location);
1364 case Named_object::NAMED_OBJECT_TYPE:
1365 return Expression::make_type(real->type_value(), location);
1366 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1367 if (this->is_composite_literal_key_)
1368 return this;
1369 if (!this->no_error_message_)
1370 error_at(location, "reference to undefined type %qs",
1371 real->message_name().c_str());
1372 return Expression::make_error(location);
1373 case Named_object::NAMED_OBJECT_VAR:
1374 real->var_value()->set_is_used();
1375 return Expression::make_var_reference(real, location);
1376 case Named_object::NAMED_OBJECT_FUNC:
1377 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1378 return Expression::make_func_reference(real, NULL, location);
1379 case Named_object::NAMED_OBJECT_PACKAGE:
1380 if (this->is_composite_literal_key_)
1381 return this;
1382 if (!this->no_error_message_)
1383 error_at(location, "unexpected reference to package");
1384 return Expression::make_error(location);
1385 default:
1386 go_unreachable();
1390 // Dump the ast representation for an unknown expression to a dump context.
1392 void
1393 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1395 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1396 << ")";
1399 // Make a reference to an unknown name.
1401 Unknown_expression*
1402 Expression::make_unknown_reference(Named_object* no, Location location)
1404 return new Unknown_expression(no, location);
1407 // A boolean expression.
1409 class Boolean_expression : public Expression
1411 public:
1412 Boolean_expression(bool val, Location location)
1413 : Expression(EXPRESSION_BOOLEAN, location),
1414 val_(val), type_(NULL)
1417 static Expression*
1418 do_import(Import*);
1420 protected:
1421 bool
1422 do_is_constant() const
1423 { return true; }
1425 bool
1426 do_is_immutable() const
1427 { return true; }
1429 Type*
1430 do_type();
1432 void
1433 do_determine_type(const Type_context*);
1435 Expression*
1436 do_copy()
1437 { return this; }
1439 Bexpression*
1440 do_get_backend(Translate_context* context)
1441 { return context->backend()->boolean_constant_expression(this->val_); }
1443 void
1444 do_export(Export* exp) const
1445 { exp->write_c_string(this->val_ ? "true" : "false"); }
1447 void
1448 do_dump_expression(Ast_dump_context* ast_dump_context) const
1449 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1451 private:
1452 // The constant.
1453 bool val_;
1454 // The type as determined by context.
1455 Type* type_;
1458 // Get the type.
1460 Type*
1461 Boolean_expression::do_type()
1463 if (this->type_ == NULL)
1464 this->type_ = Type::make_boolean_type();
1465 return this->type_;
1468 // Set the type from the context.
1470 void
1471 Boolean_expression::do_determine_type(const Type_context* context)
1473 if (this->type_ != NULL && !this->type_->is_abstract())
1475 else if (context->type != NULL && context->type->is_boolean_type())
1476 this->type_ = context->type;
1477 else if (!context->may_be_abstract)
1478 this->type_ = Type::lookup_bool_type();
1481 // Import a boolean constant.
1483 Expression*
1484 Boolean_expression::do_import(Import* imp)
1486 if (imp->peek_char() == 't')
1488 imp->require_c_string("true");
1489 return Expression::make_boolean(true, imp->location());
1491 else
1493 imp->require_c_string("false");
1494 return Expression::make_boolean(false, imp->location());
1498 // Make a boolean expression.
1500 Expression*
1501 Expression::make_boolean(bool val, Location location)
1503 return new Boolean_expression(val, location);
1506 // Class String_expression.
1508 // Get the type.
1510 Type*
1511 String_expression::do_type()
1513 if (this->type_ == NULL)
1514 this->type_ = Type::make_string_type();
1515 return this->type_;
1518 // Set the type from the context.
1520 void
1521 String_expression::do_determine_type(const Type_context* context)
1523 if (this->type_ != NULL && !this->type_->is_abstract())
1525 else if (context->type != NULL && context->type->is_string_type())
1526 this->type_ = context->type;
1527 else if (!context->may_be_abstract)
1528 this->type_ = Type::lookup_string_type();
1531 // Build a string constant.
1533 Bexpression*
1534 String_expression::do_get_backend(Translate_context* context)
1536 Gogo* gogo = context->gogo();
1537 Btype* btype = Type::make_string_type()->get_backend(gogo);
1539 Location loc = this->location();
1540 std::vector<Bexpression*> init(2);
1541 Bexpression* str_cst =
1542 gogo->backend()->string_constant_expression(this->val_);
1543 init[0] = gogo->backend()->address_expression(str_cst, loc);
1545 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1546 mpz_t lenval;
1547 mpz_init_set_ui(lenval, this->val_.length());
1548 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1549 mpz_clear(lenval);
1551 return gogo->backend()->constructor_expression(btype, init, loc);
1554 // Write string literal to string dump.
1556 void
1557 String_expression::export_string(String_dump* exp,
1558 const String_expression* str)
1560 std::string s;
1561 s.reserve(str->val_.length() * 4 + 2);
1562 s += '"';
1563 for (std::string::const_iterator p = str->val_.begin();
1564 p != str->val_.end();
1565 ++p)
1567 if (*p == '\\' || *p == '"')
1569 s += '\\';
1570 s += *p;
1572 else if (*p >= 0x20 && *p < 0x7f)
1573 s += *p;
1574 else if (*p == '\n')
1575 s += "\\n";
1576 else if (*p == '\t')
1577 s += "\\t";
1578 else
1580 s += "\\x";
1581 unsigned char c = *p;
1582 unsigned int dig = c >> 4;
1583 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1584 dig = c & 0xf;
1585 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1588 s += '"';
1589 exp->write_string(s);
1592 // Export a string expression.
1594 void
1595 String_expression::do_export(Export* exp) const
1597 String_expression::export_string(exp, this);
1600 // Import a string expression.
1602 Expression*
1603 String_expression::do_import(Import* imp)
1605 imp->require_c_string("\"");
1606 std::string val;
1607 while (true)
1609 int c = imp->get_char();
1610 if (c == '"' || c == -1)
1611 break;
1612 if (c != '\\')
1613 val += static_cast<char>(c);
1614 else
1616 c = imp->get_char();
1617 if (c == '\\' || c == '"')
1618 val += static_cast<char>(c);
1619 else if (c == 'n')
1620 val += '\n';
1621 else if (c == 't')
1622 val += '\t';
1623 else if (c == 'x')
1625 c = imp->get_char();
1626 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1627 c = imp->get_char();
1628 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1629 char v = (vh << 4) | vl;
1630 val += v;
1632 else
1634 error_at(imp->location(), "bad string constant");
1635 return Expression::make_error(imp->location());
1639 return Expression::make_string(val, imp->location());
1642 // Ast dump for string expression.
1644 void
1645 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1647 String_expression::export_string(ast_dump_context, this);
1650 // Make a string expression.
1652 Expression*
1653 Expression::make_string(const std::string& val, Location location)
1655 return new String_expression(val, location);
1658 // An expression that evaluates to some characteristic of a string.
1659 // This is used when indexing, bound-checking, or nil checking a string.
1661 class String_info_expression : public Expression
1663 public:
1664 String_info_expression(Expression* string, String_info string_info,
1665 Location location)
1666 : Expression(EXPRESSION_STRING_INFO, location),
1667 string_(string), string_info_(string_info)
1670 protected:
1671 Type*
1672 do_type();
1674 void
1675 do_determine_type(const Type_context*)
1676 { go_unreachable(); }
1678 Expression*
1679 do_copy()
1681 return new String_info_expression(this->string_->copy(), this->string_info_,
1682 this->location());
1685 Bexpression*
1686 do_get_backend(Translate_context* context);
1688 void
1689 do_dump_expression(Ast_dump_context*) const;
1691 void
1692 do_issue_nil_check()
1693 { this->string_->issue_nil_check(); }
1695 private:
1696 // The string for which we are getting information.
1697 Expression* string_;
1698 // What information we want.
1699 String_info string_info_;
1702 // Return the type of the string info.
1704 Type*
1705 String_info_expression::do_type()
1707 switch (this->string_info_)
1709 case STRING_INFO_DATA:
1711 Type* byte_type = Type::lookup_integer_type("uint8");
1712 return Type::make_pointer_type(byte_type);
1714 case STRING_INFO_LENGTH:
1715 return Type::lookup_integer_type("int");
1716 default:
1717 go_unreachable();
1721 // Return string information in GENERIC.
1723 Bexpression*
1724 String_info_expression::do_get_backend(Translate_context* context)
1726 Gogo* gogo = context->gogo();
1728 Bexpression* bstring = this->string_->get_backend(context);
1729 switch (this->string_info_)
1731 case STRING_INFO_DATA:
1732 case STRING_INFO_LENGTH:
1733 return gogo->backend()->struct_field_expression(bstring,
1734 this->string_info_,
1735 this->location());
1736 break;
1737 default:
1738 go_unreachable();
1742 // Dump ast representation for a type info expression.
1744 void
1745 String_info_expression::do_dump_expression(
1746 Ast_dump_context* ast_dump_context) const
1748 ast_dump_context->ostream() << "stringinfo(";
1749 this->string_->dump_expression(ast_dump_context);
1750 ast_dump_context->ostream() << ",";
1751 ast_dump_context->ostream() <<
1752 (this->string_info_ == STRING_INFO_DATA ? "data"
1753 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1754 : "unknown");
1755 ast_dump_context->ostream() << ")";
1758 // Make a string info expression.
1760 Expression*
1761 Expression::make_string_info(Expression* string, String_info string_info,
1762 Location location)
1764 return new String_info_expression(string, string_info, location);
1767 // Make an integer expression.
1769 class Integer_expression : public Expression
1771 public:
1772 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1773 Location location)
1774 : Expression(EXPRESSION_INTEGER, location),
1775 type_(type), is_character_constant_(is_character_constant)
1776 { mpz_init_set(this->val_, *val); }
1778 static Expression*
1779 do_import(Import*);
1781 // Write VAL to string dump.
1782 static void
1783 export_integer(String_dump* exp, const mpz_t val);
1785 // Write VAL to dump context.
1786 static void
1787 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1789 protected:
1790 bool
1791 do_is_constant() const
1792 { return true; }
1794 bool
1795 do_is_immutable() const
1796 { return true; }
1798 bool
1799 do_numeric_constant_value(Numeric_constant* nc) const;
1801 Type*
1802 do_type();
1804 void
1805 do_determine_type(const Type_context* context);
1807 void
1808 do_check_types(Gogo*);
1810 Bexpression*
1811 do_get_backend(Translate_context*);
1813 Expression*
1814 do_copy()
1816 if (this->is_character_constant_)
1817 return Expression::make_character(&this->val_, this->type_,
1818 this->location());
1819 else
1820 return Expression::make_integer_z(&this->val_, this->type_,
1821 this->location());
1824 void
1825 do_export(Export*) const;
1827 void
1828 do_dump_expression(Ast_dump_context*) const;
1830 private:
1831 // The integer value.
1832 mpz_t val_;
1833 // The type so far.
1834 Type* type_;
1835 // Whether this is a character constant.
1836 bool is_character_constant_;
1839 // Return a numeric constant for this expression. We have to mark
1840 // this as a character when appropriate.
1842 bool
1843 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1845 if (this->is_character_constant_)
1846 nc->set_rune(this->type_, this->val_);
1847 else
1848 nc->set_int(this->type_, this->val_);
1849 return true;
1852 // Return the current type. If we haven't set the type yet, we return
1853 // an abstract integer type.
1855 Type*
1856 Integer_expression::do_type()
1858 if (this->type_ == NULL)
1860 if (this->is_character_constant_)
1861 this->type_ = Type::make_abstract_character_type();
1862 else
1863 this->type_ = Type::make_abstract_integer_type();
1865 return this->type_;
1868 // Set the type of the integer value. Here we may switch from an
1869 // abstract type to a real type.
1871 void
1872 Integer_expression::do_determine_type(const Type_context* context)
1874 if (this->type_ != NULL && !this->type_->is_abstract())
1876 else if (context->type != NULL && context->type->is_numeric_type())
1877 this->type_ = context->type;
1878 else if (!context->may_be_abstract)
1880 if (this->is_character_constant_)
1881 this->type_ = Type::lookup_integer_type("int32");
1882 else
1883 this->type_ = Type::lookup_integer_type("int");
1887 // Check the type of an integer constant.
1889 void
1890 Integer_expression::do_check_types(Gogo*)
1892 Type* type = this->type_;
1893 if (type == NULL)
1894 return;
1895 Numeric_constant nc;
1896 if (this->is_character_constant_)
1897 nc.set_rune(NULL, this->val_);
1898 else
1899 nc.set_int(NULL, this->val_);
1900 if (!nc.set_type(type, true, this->location()))
1901 this->set_is_error();
1904 // Get the backend representation for an integer constant.
1906 Bexpression*
1907 Integer_expression::do_get_backend(Translate_context* context)
1909 Type* resolved_type = NULL;
1910 if (this->type_ != NULL && !this->type_->is_abstract())
1911 resolved_type = this->type_;
1912 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1914 // We are converting to an abstract floating point type.
1915 resolved_type = Type::lookup_float_type("float64");
1917 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1919 // We are converting to an abstract complex type.
1920 resolved_type = Type::lookup_complex_type("complex128");
1922 else
1924 // If we still have an abstract type here, then this is being
1925 // used in a constant expression which didn't get reduced for
1926 // some reason. Use a type which will fit the value. We use <,
1927 // not <=, because we need an extra bit for the sign bit.
1928 int bits = mpz_sizeinbase(this->val_, 2);
1929 Type* int_type = Type::lookup_integer_type("int");
1930 if (bits < int_type->integer_type()->bits())
1931 resolved_type = int_type;
1932 else if (bits < 64)
1933 resolved_type = Type::lookup_integer_type("int64");
1934 else
1936 if (!saw_errors())
1937 error_at(this->location(),
1938 "unknown type for large integer constant");
1939 return context->gogo()->backend()->error_expression();
1942 Numeric_constant nc;
1943 nc.set_int(resolved_type, this->val_);
1944 return Expression::backend_numeric_constant_expression(context, &nc);
1947 // Write VAL to export data.
1949 void
1950 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1952 char* s = mpz_get_str(NULL, 10, val);
1953 exp->write_c_string(s);
1954 free(s);
1957 // Export an integer in a constant expression.
1959 void
1960 Integer_expression::do_export(Export* exp) const
1962 Integer_expression::export_integer(exp, this->val_);
1963 if (this->is_character_constant_)
1964 exp->write_c_string("'");
1965 // A trailing space lets us reliably identify the end of the number.
1966 exp->write_c_string(" ");
1969 // Import an integer, floating point, or complex value. This handles
1970 // all these types because they all start with digits.
1972 Expression*
1973 Integer_expression::do_import(Import* imp)
1975 std::string num = imp->read_identifier();
1976 imp->require_c_string(" ");
1977 if (!num.empty() && num[num.length() - 1] == 'i')
1979 mpfr_t real;
1980 size_t plus_pos = num.find('+', 1);
1981 size_t minus_pos = num.find('-', 1);
1982 size_t pos;
1983 if (plus_pos == std::string::npos)
1984 pos = minus_pos;
1985 else if (minus_pos == std::string::npos)
1986 pos = plus_pos;
1987 else
1989 error_at(imp->location(), "bad number in import data: %qs",
1990 num.c_str());
1991 return Expression::make_error(imp->location());
1993 if (pos == std::string::npos)
1994 mpfr_set_ui(real, 0, GMP_RNDN);
1995 else
1997 std::string real_str = num.substr(0, pos);
1998 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2000 error_at(imp->location(), "bad number in import data: %qs",
2001 real_str.c_str());
2002 return Expression::make_error(imp->location());
2006 std::string imag_str;
2007 if (pos == std::string::npos)
2008 imag_str = num;
2009 else
2010 imag_str = num.substr(pos);
2011 imag_str = imag_str.substr(0, imag_str.size() - 1);
2012 mpfr_t imag;
2013 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2015 error_at(imp->location(), "bad number in import data: %qs",
2016 imag_str.c_str());
2017 return Expression::make_error(imp->location());
2019 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2020 imp->location());
2021 mpfr_clear(real);
2022 mpfr_clear(imag);
2023 return ret;
2025 else if (num.find('.') == std::string::npos
2026 && num.find('E') == std::string::npos)
2028 bool is_character_constant = (!num.empty()
2029 && num[num.length() - 1] == '\'');
2030 if (is_character_constant)
2031 num = num.substr(0, num.length() - 1);
2032 mpz_t val;
2033 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2035 error_at(imp->location(), "bad number in import data: %qs",
2036 num.c_str());
2037 return Expression::make_error(imp->location());
2039 Expression* ret;
2040 if (is_character_constant)
2041 ret = Expression::make_character(&val, NULL, imp->location());
2042 else
2043 ret = Expression::make_integer_z(&val, NULL, imp->location());
2044 mpz_clear(val);
2045 return ret;
2047 else
2049 mpfr_t val;
2050 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2052 error_at(imp->location(), "bad number in import data: %qs",
2053 num.c_str());
2054 return Expression::make_error(imp->location());
2056 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2057 mpfr_clear(val);
2058 return ret;
2061 // Ast dump for integer expression.
2063 void
2064 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2066 if (this->is_character_constant_)
2067 ast_dump_context->ostream() << '\'';
2068 Integer_expression::export_integer(ast_dump_context, this->val_);
2069 if (this->is_character_constant_)
2070 ast_dump_context->ostream() << '\'';
2073 // Build a new integer value from a multi-precision integer.
2075 Expression*
2076 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2078 return new Integer_expression(val, type, false, location);
2081 // Build a new integer value from an unsigned long.
2083 Expression*
2084 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2086 mpz_t zval;
2087 mpz_init_set_ui(zval, val);
2088 Expression* ret = Expression::make_integer_z(&zval, type, location);
2089 mpz_clear(zval);
2090 return ret;
2093 // Build a new integer value from a signed long.
2095 Expression*
2096 Expression::make_integer_sl(long val, Type *type, Location location)
2098 mpz_t zval;
2099 mpz_init_set_si(zval, val);
2100 Expression* ret = Expression::make_integer_z(&zval, type, location);
2101 mpz_clear(zval);
2102 return ret;
2105 // Build a new character constant value.
2107 Expression*
2108 Expression::make_character(const mpz_t* val, Type* type, Location location)
2110 return new Integer_expression(val, type, true, location);
2113 // Floats.
2115 class Float_expression : public Expression
2117 public:
2118 Float_expression(const mpfr_t* val, Type* type, Location location)
2119 : Expression(EXPRESSION_FLOAT, location),
2120 type_(type)
2122 mpfr_init_set(this->val_, *val, GMP_RNDN);
2125 // Write VAL to export data.
2126 static void
2127 export_float(String_dump* exp, const mpfr_t val);
2129 // Write VAL to dump file.
2130 static void
2131 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2133 protected:
2134 bool
2135 do_is_constant() const
2136 { return true; }
2138 bool
2139 do_is_immutable() const
2140 { return true; }
2142 bool
2143 do_numeric_constant_value(Numeric_constant* nc) const
2145 nc->set_float(this->type_, this->val_);
2146 return true;
2149 Type*
2150 do_type();
2152 void
2153 do_determine_type(const Type_context*);
2155 void
2156 do_check_types(Gogo*);
2158 Expression*
2159 do_copy()
2160 { return Expression::make_float(&this->val_, this->type_,
2161 this->location()); }
2163 Bexpression*
2164 do_get_backend(Translate_context*);
2166 void
2167 do_export(Export*) const;
2169 void
2170 do_dump_expression(Ast_dump_context*) const;
2172 private:
2173 // The floating point value.
2174 mpfr_t val_;
2175 // The type so far.
2176 Type* type_;
2179 // Return the current type. If we haven't set the type yet, we return
2180 // an abstract float type.
2182 Type*
2183 Float_expression::do_type()
2185 if (this->type_ == NULL)
2186 this->type_ = Type::make_abstract_float_type();
2187 return this->type_;
2190 // Set the type of the float value. Here we may switch from an
2191 // abstract type to a real type.
2193 void
2194 Float_expression::do_determine_type(const Type_context* context)
2196 if (this->type_ != NULL && !this->type_->is_abstract())
2198 else if (context->type != NULL
2199 && (context->type->integer_type() != NULL
2200 || context->type->float_type() != NULL
2201 || context->type->complex_type() != NULL))
2202 this->type_ = context->type;
2203 else if (!context->may_be_abstract)
2204 this->type_ = Type::lookup_float_type("float64");
2207 // Check the type of a float value.
2209 void
2210 Float_expression::do_check_types(Gogo*)
2212 Type* type = this->type_;
2213 if (type == NULL)
2214 return;
2215 Numeric_constant nc;
2216 nc.set_float(NULL, this->val_);
2217 if (!nc.set_type(this->type_, true, this->location()))
2218 this->set_is_error();
2221 // Get the backend representation for a float constant.
2223 Bexpression*
2224 Float_expression::do_get_backend(Translate_context* context)
2226 Type* resolved_type;
2227 if (this->type_ != NULL && !this->type_->is_abstract())
2228 resolved_type = this->type_;
2229 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2231 // We have an abstract integer type. We just hope for the best.
2232 resolved_type = Type::lookup_integer_type("int");
2234 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2236 // We are converting to an abstract complex type.
2237 resolved_type = Type::lookup_complex_type("complex128");
2239 else
2241 // If we still have an abstract type here, then this is being
2242 // used in a constant expression which didn't get reduced. We
2243 // just use float64 and hope for the best.
2244 resolved_type = Type::lookup_float_type("float64");
2247 Numeric_constant nc;
2248 nc.set_float(resolved_type, this->val_);
2249 return Expression::backend_numeric_constant_expression(context, &nc);
2252 // Write a floating point number to a string dump.
2254 void
2255 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2257 mp_exp_t exponent;
2258 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2259 if (*s == '-')
2260 exp->write_c_string("-");
2261 exp->write_c_string("0.");
2262 exp->write_c_string(*s == '-' ? s + 1 : s);
2263 mpfr_free_str(s);
2264 char buf[30];
2265 snprintf(buf, sizeof buf, "E%ld", exponent);
2266 exp->write_c_string(buf);
2269 // Export a floating point number in a constant expression.
2271 void
2272 Float_expression::do_export(Export* exp) const
2274 Float_expression::export_float(exp, this->val_);
2275 // A trailing space lets us reliably identify the end of the number.
2276 exp->write_c_string(" ");
2279 // Dump a floating point number to the dump file.
2281 void
2282 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2284 Float_expression::export_float(ast_dump_context, this->val_);
2287 // Make a float expression.
2289 Expression*
2290 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2292 return new Float_expression(val, type, location);
2295 // Complex numbers.
2297 class Complex_expression : public Expression
2299 public:
2300 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2301 Location location)
2302 : Expression(EXPRESSION_COMPLEX, location),
2303 type_(type)
2305 mpfr_init_set(this->real_, *real, GMP_RNDN);
2306 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2309 // Write REAL/IMAG to string dump.
2310 static void
2311 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2313 // Write REAL/IMAG to dump context.
2314 static void
2315 dump_complex(Ast_dump_context* ast_dump_context,
2316 const mpfr_t real, const mpfr_t val);
2318 protected:
2319 bool
2320 do_is_constant() const
2321 { return true; }
2323 bool
2324 do_is_immutable() const
2325 { return true; }
2327 bool
2328 do_numeric_constant_value(Numeric_constant* nc) const
2330 nc->set_complex(this->type_, this->real_, this->imag_);
2331 return true;
2334 Type*
2335 do_type();
2337 void
2338 do_determine_type(const Type_context*);
2340 void
2341 do_check_types(Gogo*);
2343 Expression*
2344 do_copy()
2346 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2347 this->location());
2350 Bexpression*
2351 do_get_backend(Translate_context*);
2353 void
2354 do_export(Export*) const;
2356 void
2357 do_dump_expression(Ast_dump_context*) const;
2359 private:
2360 // The real part.
2361 mpfr_t real_;
2362 // The imaginary part;
2363 mpfr_t imag_;
2364 // The type if known.
2365 Type* type_;
2368 // Return the current type. If we haven't set the type yet, we return
2369 // an abstract complex type.
2371 Type*
2372 Complex_expression::do_type()
2374 if (this->type_ == NULL)
2375 this->type_ = Type::make_abstract_complex_type();
2376 return this->type_;
2379 // Set the type of the complex value. Here we may switch from an
2380 // abstract type to a real type.
2382 void
2383 Complex_expression::do_determine_type(const Type_context* context)
2385 if (this->type_ != NULL && !this->type_->is_abstract())
2387 else if (context->type != NULL
2388 && context->type->complex_type() != NULL)
2389 this->type_ = context->type;
2390 else if (!context->may_be_abstract)
2391 this->type_ = Type::lookup_complex_type("complex128");
2394 // Check the type of a complex value.
2396 void
2397 Complex_expression::do_check_types(Gogo*)
2399 Type* type = this->type_;
2400 if (type == NULL)
2401 return;
2402 Numeric_constant nc;
2403 nc.set_complex(NULL, this->real_, this->imag_);
2404 if (!nc.set_type(this->type_, true, this->location()))
2405 this->set_is_error();
2408 // Get the backend representation for a complex constant.
2410 Bexpression*
2411 Complex_expression::do_get_backend(Translate_context* context)
2413 Type* resolved_type;
2414 if (this->type_ != NULL && !this->type_->is_abstract())
2415 resolved_type = this->type_;
2416 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2418 // We are converting to an abstract integer type.
2419 resolved_type = Type::lookup_integer_type("int");
2421 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2423 // We are converting to an abstract float type.
2424 resolved_type = Type::lookup_float_type("float64");
2426 else
2428 // If we still have an abstract type here, this this is being
2429 // used in a constant expression which didn't get reduced. We
2430 // just use complex128 and hope for the best.
2431 resolved_type = Type::lookup_complex_type("complex128");
2434 Numeric_constant nc;
2435 nc.set_complex(resolved_type, this->real_, this->imag_);
2436 return Expression::backend_numeric_constant_expression(context, &nc);
2439 // Write REAL/IMAG to export data.
2441 void
2442 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2443 const mpfr_t imag)
2445 if (!mpfr_zero_p(real))
2447 Float_expression::export_float(exp, real);
2448 if (mpfr_sgn(imag) > 0)
2449 exp->write_c_string("+");
2451 Float_expression::export_float(exp, imag);
2452 exp->write_c_string("i");
2455 // Export a complex number in a constant expression.
2457 void
2458 Complex_expression::do_export(Export* exp) const
2460 Complex_expression::export_complex(exp, this->real_, this->imag_);
2461 // A trailing space lets us reliably identify the end of the number.
2462 exp->write_c_string(" ");
2465 // Dump a complex expression to the dump file.
2467 void
2468 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2470 Complex_expression::export_complex(ast_dump_context,
2471 this->real_,
2472 this->imag_);
2475 // Make a complex expression.
2477 Expression*
2478 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2479 Location location)
2481 return new Complex_expression(real, imag, type, location);
2484 // Find a named object in an expression.
2486 class Find_named_object : public Traverse
2488 public:
2489 Find_named_object(Named_object* no)
2490 : Traverse(traverse_expressions),
2491 no_(no), found_(false)
2494 // Whether we found the object.
2495 bool
2496 found() const
2497 { return this->found_; }
2499 protected:
2501 expression(Expression**);
2503 private:
2504 // The object we are looking for.
2505 Named_object* no_;
2506 // Whether we found it.
2507 bool found_;
2510 // A reference to a const in an expression.
2512 class Const_expression : public Expression
2514 public:
2515 Const_expression(Named_object* constant, Location location)
2516 : Expression(EXPRESSION_CONST_REFERENCE, location),
2517 constant_(constant), type_(NULL), seen_(false)
2520 Named_object*
2521 named_object()
2522 { return this->constant_; }
2524 // Check that the initializer does not refer to the constant itself.
2525 void
2526 check_for_init_loop();
2528 protected:
2530 do_traverse(Traverse*);
2532 Expression*
2533 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2535 bool
2536 do_is_constant() const
2537 { return true; }
2539 bool
2540 do_is_immutable() const
2541 { return true; }
2543 bool
2544 do_numeric_constant_value(Numeric_constant* nc) const;
2546 bool
2547 do_string_constant_value(std::string* val) const;
2549 Type*
2550 do_type();
2552 // The type of a const is set by the declaration, not the use.
2553 void
2554 do_determine_type(const Type_context*);
2556 void
2557 do_check_types(Gogo*);
2559 Expression*
2560 do_copy()
2561 { return this; }
2563 Bexpression*
2564 do_get_backend(Translate_context* context);
2566 // When exporting a reference to a const as part of a const
2567 // expression, we export the value. We ignore the fact that it has
2568 // a name.
2569 void
2570 do_export(Export* exp) const
2571 { this->constant_->const_value()->expr()->export_expression(exp); }
2573 void
2574 do_dump_expression(Ast_dump_context*) const;
2576 private:
2577 // The constant.
2578 Named_object* constant_;
2579 // The type of this reference. This is used if the constant has an
2580 // abstract type.
2581 Type* type_;
2582 // Used to prevent infinite recursion when a constant incorrectly
2583 // refers to itself.
2584 mutable bool seen_;
2587 // Traversal.
2590 Const_expression::do_traverse(Traverse* traverse)
2592 if (this->type_ != NULL)
2593 return Type::traverse(this->type_, traverse);
2594 return TRAVERSE_CONTINUE;
2597 // Lower a constant expression. This is where we convert the
2598 // predeclared constant iota into an integer value.
2600 Expression*
2601 Const_expression::do_lower(Gogo* gogo, Named_object*,
2602 Statement_inserter*, int iota_value)
2604 if (this->constant_->const_value()->expr()->classification()
2605 == EXPRESSION_IOTA)
2607 if (iota_value == -1)
2609 error_at(this->location(),
2610 "iota is only defined in const declarations");
2611 iota_value = 0;
2613 return Expression::make_integer_ul(iota_value, NULL, this->location());
2616 // Make sure that the constant itself has been lowered.
2617 gogo->lower_constant(this->constant_);
2619 return this;
2622 // Return a numeric constant value.
2624 bool
2625 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2627 if (this->seen_)
2628 return false;
2630 Expression* e = this->constant_->const_value()->expr();
2632 this->seen_ = true;
2634 bool r = e->numeric_constant_value(nc);
2636 this->seen_ = false;
2638 Type* ctype;
2639 if (this->type_ != NULL)
2640 ctype = this->type_;
2641 else
2642 ctype = this->constant_->const_value()->type();
2643 if (r && ctype != NULL)
2645 if (!nc->set_type(ctype, false, this->location()))
2646 return false;
2649 return r;
2652 bool
2653 Const_expression::do_string_constant_value(std::string* val) const
2655 if (this->seen_)
2656 return false;
2658 Expression* e = this->constant_->const_value()->expr();
2660 this->seen_ = true;
2661 bool ok = e->string_constant_value(val);
2662 this->seen_ = false;
2664 return ok;
2667 // Return the type of the const reference.
2669 Type*
2670 Const_expression::do_type()
2672 if (this->type_ != NULL)
2673 return this->type_;
2675 Named_constant* nc = this->constant_->const_value();
2677 if (this->seen_ || nc->lowering())
2679 this->report_error(_("constant refers to itself"));
2680 this->type_ = Type::make_error_type();
2681 return this->type_;
2684 this->seen_ = true;
2686 Type* ret = nc->type();
2688 if (ret != NULL)
2690 this->seen_ = false;
2691 return ret;
2694 // During parsing, a named constant may have a NULL type, but we
2695 // must not return a NULL type here.
2696 ret = nc->expr()->type();
2698 this->seen_ = false;
2700 return ret;
2703 // Set the type of the const reference.
2705 void
2706 Const_expression::do_determine_type(const Type_context* context)
2708 Type* ctype = this->constant_->const_value()->type();
2709 Type* cetype = (ctype != NULL
2710 ? ctype
2711 : this->constant_->const_value()->expr()->type());
2712 if (ctype != NULL && !ctype->is_abstract())
2714 else if (context->type != NULL
2715 && context->type->is_numeric_type()
2716 && cetype->is_numeric_type())
2717 this->type_ = context->type;
2718 else if (context->type != NULL
2719 && context->type->is_string_type()
2720 && cetype->is_string_type())
2721 this->type_ = context->type;
2722 else if (context->type != NULL
2723 && context->type->is_boolean_type()
2724 && cetype->is_boolean_type())
2725 this->type_ = context->type;
2726 else if (!context->may_be_abstract)
2728 if (cetype->is_abstract())
2729 cetype = cetype->make_non_abstract_type();
2730 this->type_ = cetype;
2734 // Check for a loop in which the initializer of a constant refers to
2735 // the constant itself.
2737 void
2738 Const_expression::check_for_init_loop()
2740 if (this->type_ != NULL && this->type_->is_error())
2741 return;
2743 if (this->seen_)
2745 this->report_error(_("constant refers to itself"));
2746 this->type_ = Type::make_error_type();
2747 return;
2750 Expression* init = this->constant_->const_value()->expr();
2751 Find_named_object find_named_object(this->constant_);
2753 this->seen_ = true;
2754 Expression::traverse(&init, &find_named_object);
2755 this->seen_ = false;
2757 if (find_named_object.found())
2759 if (this->type_ == NULL || !this->type_->is_error())
2761 this->report_error(_("constant refers to itself"));
2762 this->type_ = Type::make_error_type();
2764 return;
2768 // Check types of a const reference.
2770 void
2771 Const_expression::do_check_types(Gogo*)
2773 if (this->type_ != NULL && this->type_->is_error())
2774 return;
2776 this->check_for_init_loop();
2778 // Check that numeric constant fits in type.
2779 if (this->type_ != NULL && this->type_->is_numeric_type())
2781 Numeric_constant nc;
2782 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2784 if (!nc.set_type(this->type_, true, this->location()))
2785 this->set_is_error();
2790 // Return the backend representation for a const reference.
2792 Bexpression*
2793 Const_expression::do_get_backend(Translate_context* context)
2795 if (this->type_ != NULL && this->type_->is_error())
2796 return context->backend()->error_expression();
2798 // If the type has been set for this expression, but the underlying
2799 // object is an abstract int or float, we try to get the abstract
2800 // value. Otherwise we may lose something in the conversion.
2801 Expression* expr = this->constant_->const_value()->expr();
2802 if (this->type_ != NULL
2803 && this->type_->is_numeric_type()
2804 && (this->constant_->const_value()->type() == NULL
2805 || this->constant_->const_value()->type()->is_abstract()))
2807 Numeric_constant nc;
2808 if (expr->numeric_constant_value(&nc)
2809 && nc.set_type(this->type_, false, this->location()))
2811 Expression* e = nc.expression(this->location());
2812 return e->get_backend(context);
2816 if (this->type_ != NULL)
2817 expr = Expression::make_cast(this->type_, expr, this->location());
2818 return expr->get_backend(context);
2821 // Dump ast representation for constant expression.
2823 void
2824 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2826 ast_dump_context->ostream() << this->constant_->name();
2829 // Make a reference to a constant in an expression.
2831 Expression*
2832 Expression::make_const_reference(Named_object* constant,
2833 Location location)
2835 return new Const_expression(constant, location);
2838 // Find a named object in an expression.
2841 Find_named_object::expression(Expression** pexpr)
2843 switch ((*pexpr)->classification())
2845 case Expression::EXPRESSION_CONST_REFERENCE:
2847 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2848 if (ce->named_object() == this->no_)
2849 break;
2851 // We need to check a constant initializer explicitly, as
2852 // loops here will not be caught by the loop checking for
2853 // variable initializers.
2854 ce->check_for_init_loop();
2856 return TRAVERSE_CONTINUE;
2859 case Expression::EXPRESSION_VAR_REFERENCE:
2860 if ((*pexpr)->var_expression()->named_object() == this->no_)
2861 break;
2862 return TRAVERSE_CONTINUE;
2863 case Expression::EXPRESSION_FUNC_REFERENCE:
2864 if ((*pexpr)->func_expression()->named_object() == this->no_)
2865 break;
2866 return TRAVERSE_CONTINUE;
2867 default:
2868 return TRAVERSE_CONTINUE;
2870 this->found_ = true;
2871 return TRAVERSE_EXIT;
2874 // The nil value.
2876 class Nil_expression : public Expression
2878 public:
2879 Nil_expression(Location location)
2880 : Expression(EXPRESSION_NIL, location)
2883 static Expression*
2884 do_import(Import*);
2886 protected:
2887 bool
2888 do_is_constant() const
2889 { return true; }
2891 bool
2892 do_is_immutable() const
2893 { return true; }
2895 Type*
2896 do_type()
2897 { return Type::make_nil_type(); }
2899 void
2900 do_determine_type(const Type_context*)
2903 Expression*
2904 do_copy()
2905 { return this; }
2907 Bexpression*
2908 do_get_backend(Translate_context* context)
2909 { return context->backend()->nil_pointer_expression(); }
2911 void
2912 do_export(Export* exp) const
2913 { exp->write_c_string("nil"); }
2915 void
2916 do_dump_expression(Ast_dump_context* ast_dump_context) const
2917 { ast_dump_context->ostream() << "nil"; }
2920 // Import a nil expression.
2922 Expression*
2923 Nil_expression::do_import(Import* imp)
2925 imp->require_c_string("nil");
2926 return Expression::make_nil(imp->location());
2929 // Make a nil expression.
2931 Expression*
2932 Expression::make_nil(Location location)
2934 return new Nil_expression(location);
2937 // The value of the predeclared constant iota. This is little more
2938 // than a marker. This will be lowered to an integer in
2939 // Const_expression::do_lower, which is where we know the value that
2940 // it should have.
2942 class Iota_expression : public Parser_expression
2944 public:
2945 Iota_expression(Location location)
2946 : Parser_expression(EXPRESSION_IOTA, location)
2949 protected:
2950 Expression*
2951 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2952 { go_unreachable(); }
2954 // There should only ever be one of these.
2955 Expression*
2956 do_copy()
2957 { go_unreachable(); }
2959 void
2960 do_dump_expression(Ast_dump_context* ast_dump_context) const
2961 { ast_dump_context->ostream() << "iota"; }
2964 // Make an iota expression. This is only called for one case: the
2965 // value of the predeclared constant iota.
2967 Expression*
2968 Expression::make_iota()
2970 static Iota_expression iota_expression(Linemap::unknown_location());
2971 return &iota_expression;
2974 // A type conversion expression.
2976 class Type_conversion_expression : public Expression
2978 public:
2979 Type_conversion_expression(Type* type, Expression* expr,
2980 Location location)
2981 : Expression(EXPRESSION_CONVERSION, location),
2982 type_(type), expr_(expr), may_convert_function_types_(false)
2985 // Return the type to which we are converting.
2986 Type*
2987 type() const
2988 { return this->type_; }
2990 // Return the expression which we are converting.
2991 Expression*
2992 expr() const
2993 { return this->expr_; }
2995 // Permit converting from one function type to another. This is
2996 // used internally for method expressions.
2997 void
2998 set_may_convert_function_types()
3000 this->may_convert_function_types_ = true;
3003 // Import a type conversion expression.
3004 static Expression*
3005 do_import(Import*);
3007 protected:
3009 do_traverse(Traverse* traverse);
3011 Expression*
3012 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3014 Expression*
3015 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3017 bool
3018 do_is_constant() const;
3020 bool
3021 do_is_immutable() const;
3023 bool
3024 do_numeric_constant_value(Numeric_constant*) const;
3026 bool
3027 do_string_constant_value(std::string*) const;
3029 Type*
3030 do_type()
3031 { return this->type_; }
3033 void
3034 do_determine_type(const Type_context*)
3036 Type_context subcontext(this->type_, false);
3037 this->expr_->determine_type(&subcontext);
3040 void
3041 do_check_types(Gogo*);
3043 Expression*
3044 do_copy()
3046 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3047 this->location());
3050 Bexpression*
3051 do_get_backend(Translate_context* context);
3053 void
3054 do_export(Export*) const;
3056 void
3057 do_dump_expression(Ast_dump_context*) const;
3059 private:
3060 // The type to convert to.
3061 Type* type_;
3062 // The expression to convert.
3063 Expression* expr_;
3064 // True if this is permitted to convert function types. This is
3065 // used internally for method expressions.
3066 bool may_convert_function_types_;
3069 // Traversal.
3072 Type_conversion_expression::do_traverse(Traverse* traverse)
3074 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3075 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3076 return TRAVERSE_EXIT;
3077 return TRAVERSE_CONTINUE;
3080 // Convert to a constant at lowering time.
3082 Expression*
3083 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3084 Statement_inserter*, int)
3086 Type* type = this->type_;
3087 Expression* val = this->expr_;
3088 Location location = this->location();
3090 if (type->is_numeric_type())
3092 Numeric_constant nc;
3093 if (val->numeric_constant_value(&nc))
3095 if (!nc.set_type(type, true, location))
3096 return Expression::make_error(location);
3097 return nc.expression(location);
3101 if (type->is_slice_type())
3103 Type* element_type = type->array_type()->element_type()->forwarded();
3104 bool is_byte = (element_type->integer_type() != NULL
3105 && element_type->integer_type()->is_byte());
3106 bool is_rune = (element_type->integer_type() != NULL
3107 && element_type->integer_type()->is_rune());
3108 if (is_byte || is_rune)
3110 std::string s;
3111 if (val->string_constant_value(&s))
3113 Expression_list* vals = new Expression_list();
3114 if (is_byte)
3116 for (std::string::const_iterator p = s.begin();
3117 p != s.end();
3118 p++)
3120 unsigned char c = static_cast<unsigned char>(*p);
3121 vals->push_back(Expression::make_integer_ul(c,
3122 element_type,
3123 location));
3126 else
3128 const char *p = s.data();
3129 const char *pend = s.data() + s.length();
3130 while (p < pend)
3132 unsigned int c;
3133 int adv = Lex::fetch_char(p, &c);
3134 if (adv == 0)
3136 warning_at(this->location(), 0,
3137 "invalid UTF-8 encoding");
3138 adv = 1;
3140 p += adv;
3141 vals->push_back(Expression::make_integer_ul(c,
3142 element_type,
3143 location));
3147 return Expression::make_slice_composite_literal(type, vals,
3148 location);
3153 return this;
3156 // Flatten a type conversion by using a temporary variable for the slice
3157 // in slice to string conversions.
3159 Expression*
3160 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3161 Statement_inserter* inserter)
3163 if (((this->type()->is_string_type()
3164 && this->expr_->type()->is_slice_type())
3165 || (this->type()->interface_type() != NULL
3166 && this->expr_->type()->interface_type() != NULL))
3167 && !this->expr_->is_variable())
3169 Temporary_statement* temp =
3170 Statement::make_temporary(NULL, this->expr_, this->location());
3171 inserter->insert(temp);
3172 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3174 return this;
3177 // Return whether a type conversion is a constant.
3179 bool
3180 Type_conversion_expression::do_is_constant() const
3182 if (!this->expr_->is_constant())
3183 return false;
3185 // A conversion to a type that may not be used as a constant is not
3186 // a constant. For example, []byte(nil).
3187 Type* type = this->type_;
3188 if (type->integer_type() == NULL
3189 && type->float_type() == NULL
3190 && type->complex_type() == NULL
3191 && !type->is_boolean_type()
3192 && !type->is_string_type())
3193 return false;
3195 return true;
3198 // Return whether a type conversion is immutable.
3200 bool
3201 Type_conversion_expression::do_is_immutable() const
3203 Type* type = this->type_;
3204 Type* expr_type = this->expr_->type();
3206 if (type->interface_type() != NULL
3207 || expr_type->interface_type() != NULL)
3208 return false;
3210 if (!this->expr_->is_immutable())
3211 return false;
3213 if (Type::are_identical(type, expr_type, false, NULL))
3214 return true;
3216 return type->is_basic_type() && expr_type->is_basic_type();
3219 // Return the constant numeric value if there is one.
3221 bool
3222 Type_conversion_expression::do_numeric_constant_value(
3223 Numeric_constant* nc) const
3225 if (!this->type_->is_numeric_type())
3226 return false;
3227 if (!this->expr_->numeric_constant_value(nc))
3228 return false;
3229 return nc->set_type(this->type_, false, this->location());
3232 // Return the constant string value if there is one.
3234 bool
3235 Type_conversion_expression::do_string_constant_value(std::string* val) const
3237 if (this->type_->is_string_type()
3238 && this->expr_->type()->integer_type() != NULL)
3240 Numeric_constant nc;
3241 if (this->expr_->numeric_constant_value(&nc))
3243 unsigned long ival;
3244 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3246 val->clear();
3247 Lex::append_char(ival, true, val, this->location());
3248 return true;
3253 // FIXME: Could handle conversion from const []int here.
3255 return false;
3258 // Check that types are convertible.
3260 void
3261 Type_conversion_expression::do_check_types(Gogo*)
3263 Type* type = this->type_;
3264 Type* expr_type = this->expr_->type();
3265 std::string reason;
3267 if (type->is_error() || expr_type->is_error())
3269 this->set_is_error();
3270 return;
3273 if (this->may_convert_function_types_
3274 && type->function_type() != NULL
3275 && expr_type->function_type() != NULL)
3276 return;
3278 if (Type::are_convertible(type, expr_type, &reason))
3279 return;
3281 error_at(this->location(), "%s", reason.c_str());
3282 this->set_is_error();
3285 // Get the backend representation for a type conversion.
3287 Bexpression*
3288 Type_conversion_expression::do_get_backend(Translate_context* context)
3290 Type* type = this->type_;
3291 Type* expr_type = this->expr_->type();
3293 Gogo* gogo = context->gogo();
3294 Btype* btype = type->get_backend(gogo);
3295 Bexpression* bexpr = this->expr_->get_backend(context);
3296 Location loc = this->location();
3298 if (Type::are_identical(type, expr_type, false, NULL))
3299 return gogo->backend()->convert_expression(btype, bexpr, loc);
3300 else if (type->interface_type() != NULL
3301 || expr_type->interface_type() != NULL)
3303 Expression* conversion =
3304 Expression::convert_for_assignment(gogo, type, this->expr_,
3305 this->location());
3306 return conversion->get_backend(context);
3308 else if (type->is_string_type()
3309 && expr_type->integer_type() != NULL)
3311 mpz_t intval;
3312 Numeric_constant nc;
3313 if (this->expr_->numeric_constant_value(&nc)
3314 && nc.to_int(&intval)
3315 && mpz_fits_ushort_p(intval))
3317 std::string s;
3318 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3319 mpz_clear(intval);
3320 Expression* se = Expression::make_string(s, loc);
3321 return se->get_backend(context);
3324 Expression* i2s_expr =
3325 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3326 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3328 else if (type->is_string_type() && expr_type->is_slice_type())
3330 Array_type* a = expr_type->array_type();
3331 Type* e = a->element_type()->forwarded();
3332 go_assert(e->integer_type() != NULL);
3333 go_assert(this->expr_->is_variable());
3335 Runtime::Function code;
3336 if (e->integer_type()->is_byte())
3337 code = Runtime::BYTE_ARRAY_TO_STRING;
3338 else
3340 go_assert(e->integer_type()->is_rune());
3341 code = Runtime::INT_ARRAY_TO_STRING;
3343 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3344 Expression* len = a->get_length(gogo, this->expr_);
3345 return Runtime::make_call(code, loc, 2, valptr,
3346 len)->get_backend(context);
3348 else if (type->is_slice_type() && expr_type->is_string_type())
3350 Type* e = type->array_type()->element_type()->forwarded();
3351 go_assert(e->integer_type() != NULL);
3353 Runtime::Function code;
3354 if (e->integer_type()->is_byte())
3355 code = Runtime::STRING_TO_BYTE_ARRAY;
3356 else
3358 go_assert(e->integer_type()->is_rune());
3359 code = Runtime::STRING_TO_INT_ARRAY;
3361 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3362 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3364 else if (type->is_numeric_type())
3366 go_assert(Type::are_convertible(type, expr_type, NULL));
3367 return gogo->backend()->convert_expression(btype, bexpr, loc);
3369 else if ((type->is_unsafe_pointer_type()
3370 && (expr_type->points_to() != NULL
3371 || expr_type->integer_type()))
3372 || (expr_type->is_unsafe_pointer_type()
3373 && type->points_to() != NULL)
3374 || (this->may_convert_function_types_
3375 && type->function_type() != NULL
3376 && expr_type->function_type() != NULL))
3377 return gogo->backend()->convert_expression(btype, bexpr, loc);
3378 else
3380 Expression* conversion =
3381 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3382 return conversion->get_backend(context);
3386 // Output a type conversion in a constant expression.
3388 void
3389 Type_conversion_expression::do_export(Export* exp) const
3391 exp->write_c_string("convert(");
3392 exp->write_type(this->type_);
3393 exp->write_c_string(", ");
3394 this->expr_->export_expression(exp);
3395 exp->write_c_string(")");
3398 // Import a type conversion or a struct construction.
3400 Expression*
3401 Type_conversion_expression::do_import(Import* imp)
3403 imp->require_c_string("convert(");
3404 Type* type = imp->read_type();
3405 imp->require_c_string(", ");
3406 Expression* val = Expression::import_expression(imp);
3407 imp->require_c_string(")");
3408 return Expression::make_cast(type, val, imp->location());
3411 // Dump ast representation for a type conversion expression.
3413 void
3414 Type_conversion_expression::do_dump_expression(
3415 Ast_dump_context* ast_dump_context) const
3417 ast_dump_context->dump_type(this->type_);
3418 ast_dump_context->ostream() << "(";
3419 ast_dump_context->dump_expression(this->expr_);
3420 ast_dump_context->ostream() << ") ";
3423 // Make a type cast expression.
3425 Expression*
3426 Expression::make_cast(Type* type, Expression* val, Location location)
3428 if (type->is_error_type() || val->is_error_expression())
3429 return Expression::make_error(location);
3430 return new Type_conversion_expression(type, val, location);
3433 // An unsafe type conversion, used to pass values to builtin functions.
3435 class Unsafe_type_conversion_expression : public Expression
3437 public:
3438 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3439 Location location)
3440 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3441 type_(type), expr_(expr)
3444 protected:
3446 do_traverse(Traverse* traverse);
3448 bool
3449 do_is_immutable() const;
3451 Type*
3452 do_type()
3453 { return this->type_; }
3455 void
3456 do_determine_type(const Type_context*)
3457 { this->expr_->determine_type_no_context(); }
3459 Expression*
3460 do_copy()
3462 return new Unsafe_type_conversion_expression(this->type_,
3463 this->expr_->copy(),
3464 this->location());
3467 Bexpression*
3468 do_get_backend(Translate_context*);
3470 void
3471 do_dump_expression(Ast_dump_context*) const;
3473 private:
3474 // The type to convert to.
3475 Type* type_;
3476 // The expression to convert.
3477 Expression* expr_;
3480 // Traversal.
3483 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3485 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3486 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3487 return TRAVERSE_EXIT;
3488 return TRAVERSE_CONTINUE;
3491 // Return whether an unsafe type conversion is immutable.
3493 bool
3494 Unsafe_type_conversion_expression::do_is_immutable() const
3496 Type* type = this->type_;
3497 Type* expr_type = this->expr_->type();
3499 if (type->interface_type() != NULL
3500 || expr_type->interface_type() != NULL)
3501 return false;
3503 if (!this->expr_->is_immutable())
3504 return false;
3506 if (Type::are_convertible(type, expr_type, NULL))
3507 return true;
3509 return type->is_basic_type() && expr_type->is_basic_type();
3512 // Convert to backend representation.
3514 Bexpression*
3515 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3517 // We are only called for a limited number of cases.
3519 Type* t = this->type_;
3520 Type* et = this->expr_->type();
3521 if (t->array_type() != NULL)
3522 go_assert(et->array_type() != NULL
3523 && t->is_slice_type() == et->is_slice_type());
3524 else if (t->struct_type() != NULL)
3526 if (t->named_type() != NULL
3527 && et->named_type() != NULL
3528 && !Type::are_convertible(t, et, NULL))
3530 go_assert(saw_errors());
3531 return context->backend()->error_expression();
3534 go_assert(et->struct_type() != NULL
3535 && Type::are_convertible(t, et, NULL));
3537 else if (t->map_type() != NULL)
3538 go_assert(et->map_type() != NULL);
3539 else if (t->channel_type() != NULL)
3540 go_assert(et->channel_type() != NULL);
3541 else if (t->points_to() != NULL)
3542 go_assert(et->points_to() != NULL
3543 || et->channel_type() != NULL
3544 || et->map_type() != NULL
3545 || et->function_type() != NULL
3546 || et->is_nil_type());
3547 else if (et->is_unsafe_pointer_type())
3548 go_assert(t->points_to() != NULL);
3549 else if (t->interface_type() != NULL)
3551 bool empty_iface = t->interface_type()->is_empty();
3552 go_assert(et->interface_type() != NULL
3553 && et->interface_type()->is_empty() == empty_iface);
3555 else if (t->integer_type() != NULL)
3556 go_assert(et->is_boolean_type()
3557 || et->integer_type() != NULL
3558 || et->function_type() != NULL
3559 || et->points_to() != NULL
3560 || et->map_type() != NULL
3561 || et->channel_type() != NULL);
3562 else
3563 go_unreachable();
3565 Gogo* gogo = context->gogo();
3566 Btype* btype = t->get_backend(gogo);
3567 Bexpression* bexpr = this->expr_->get_backend(context);
3568 Location loc = this->location();
3569 return gogo->backend()->convert_expression(btype, bexpr, loc);
3572 // Dump ast representation for an unsafe type conversion expression.
3574 void
3575 Unsafe_type_conversion_expression::do_dump_expression(
3576 Ast_dump_context* ast_dump_context) const
3578 ast_dump_context->dump_type(this->type_);
3579 ast_dump_context->ostream() << "(";
3580 ast_dump_context->dump_expression(this->expr_);
3581 ast_dump_context->ostream() << ") ";
3584 // Make an unsafe type conversion expression.
3586 Expression*
3587 Expression::make_unsafe_cast(Type* type, Expression* expr,
3588 Location location)
3590 return new Unsafe_type_conversion_expression(type, expr, location);
3593 // Class Unary_expression.
3595 // If we are taking the address of a composite literal, and the
3596 // contents are not constant, then we want to make a heap expression
3597 // instead.
3599 Expression*
3600 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3602 Location loc = this->location();
3603 Operator op = this->op_;
3604 Expression* expr = this->expr_;
3606 if (op == OPERATOR_MULT && expr->is_type_expression())
3607 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3609 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3610 // moving x to the heap. FIXME: Is it worth doing a real escape
3611 // analysis here? This case is found in math/unsafe.go and is
3612 // therefore worth special casing.
3613 if (op == OPERATOR_MULT)
3615 Expression* e = expr;
3616 while (e->classification() == EXPRESSION_CONVERSION)
3618 Type_conversion_expression* te
3619 = static_cast<Type_conversion_expression*>(e);
3620 e = te->expr();
3623 if (e->classification() == EXPRESSION_UNARY)
3625 Unary_expression* ue = static_cast<Unary_expression*>(e);
3626 if (ue->op_ == OPERATOR_AND)
3628 if (e == expr)
3630 // *&x == x.
3631 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3633 error_at(ue->location(),
3634 "invalid operand for unary %<&%>");
3635 this->set_is_error();
3637 return ue->expr_;
3639 ue->set_does_not_escape();
3644 // Catching an invalid indirection of unsafe.Pointer here avoid
3645 // having to deal with TYPE_VOID in other places.
3646 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3648 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3649 return Expression::make_error(this->location());
3652 // Check for an invalid pointer dereference. We need to do this
3653 // here because Unary_expression::do_type will return an error type
3654 // in this case. That can cause code to appear erroneous, and
3655 // therefore disappear at lowering time, without any error message.
3656 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3658 this->report_error(_("expected pointer"));
3659 return Expression::make_error(this->location());
3662 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3664 Numeric_constant nc;
3665 if (expr->numeric_constant_value(&nc))
3667 Numeric_constant result;
3668 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3669 return result.expression(loc);
3673 return this;
3676 // Flatten expression if a nil check must be performed and create temporary
3677 // variables if necessary.
3679 Expression*
3680 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3681 Statement_inserter* inserter)
3683 if (this->is_error_expression() || this->expr_->is_error_expression())
3684 return Expression::make_error(this->location());
3686 Location location = this->location();
3687 if (this->op_ == OPERATOR_MULT
3688 && !this->expr_->is_variable())
3690 go_assert(this->expr_->type()->points_to() != NULL);
3691 Type* ptype = this->expr_->type()->points_to();
3692 if (!ptype->is_void_type())
3694 Btype* pbtype = ptype->get_backend(gogo);
3695 size_t s = gogo->backend()->type_size(pbtype);
3696 if (s >= 4096 || this->issue_nil_check_)
3698 Temporary_statement* temp =
3699 Statement::make_temporary(NULL, this->expr_, location);
3700 inserter->insert(temp);
3701 this->expr_ =
3702 Expression::make_temporary_reference(temp, location);
3707 if (this->create_temp_ && !this->expr_->is_variable())
3709 Temporary_statement* temp =
3710 Statement::make_temporary(NULL, this->expr_, location);
3711 inserter->insert(temp);
3712 this->expr_ = Expression::make_temporary_reference(temp, location);
3715 return this;
3718 // Return whether a unary expression is a constant.
3720 bool
3721 Unary_expression::do_is_constant() const
3723 if (this->op_ == OPERATOR_MULT)
3725 // Indirecting through a pointer is only constant if the object
3726 // to which the expression points is constant, but we currently
3727 // have no way to determine that.
3728 return false;
3730 else if (this->op_ == OPERATOR_AND)
3732 // Taking the address of a variable is constant if it is a
3733 // global variable, not constant otherwise. In other cases taking the
3734 // address is probably not a constant.
3735 Var_expression* ve = this->expr_->var_expression();
3736 if (ve != NULL)
3738 Named_object* no = ve->named_object();
3739 return no->is_variable() && no->var_value()->is_global();
3741 return false;
3743 else
3744 return this->expr_->is_constant();
3747 // Apply unary opcode OP to UNC, setting NC. Return true if this
3748 // could be done, false if not. Issue errors for overflow.
3750 bool
3751 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3752 Location location, Numeric_constant* nc)
3754 switch (op)
3756 case OPERATOR_PLUS:
3757 *nc = *unc;
3758 return true;
3760 case OPERATOR_MINUS:
3761 if (unc->is_int() || unc->is_rune())
3762 break;
3763 else if (unc->is_float())
3765 mpfr_t uval;
3766 unc->get_float(&uval);
3767 mpfr_t val;
3768 mpfr_init(val);
3769 mpfr_neg(val, uval, GMP_RNDN);
3770 nc->set_float(unc->type(), val);
3771 mpfr_clear(uval);
3772 mpfr_clear(val);
3773 return true;
3775 else if (unc->is_complex())
3777 mpfr_t ureal, uimag;
3778 unc->get_complex(&ureal, &uimag);
3779 mpfr_t real, imag;
3780 mpfr_init(real);
3781 mpfr_init(imag);
3782 mpfr_neg(real, ureal, GMP_RNDN);
3783 mpfr_neg(imag, uimag, GMP_RNDN);
3784 nc->set_complex(unc->type(), real, imag);
3785 mpfr_clear(ureal);
3786 mpfr_clear(uimag);
3787 mpfr_clear(real);
3788 mpfr_clear(imag);
3789 return true;
3791 else
3792 go_unreachable();
3794 case OPERATOR_XOR:
3795 break;
3797 case OPERATOR_NOT:
3798 case OPERATOR_AND:
3799 case OPERATOR_MULT:
3800 return false;
3802 default:
3803 go_unreachable();
3806 if (!unc->is_int() && !unc->is_rune())
3807 return false;
3809 mpz_t uval;
3810 if (unc->is_rune())
3811 unc->get_rune(&uval);
3812 else
3813 unc->get_int(&uval);
3814 mpz_t val;
3815 mpz_init(val);
3817 switch (op)
3819 case OPERATOR_MINUS:
3820 mpz_neg(val, uval);
3821 break;
3823 case OPERATOR_NOT:
3824 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3825 break;
3827 case OPERATOR_XOR:
3829 Type* utype = unc->type();
3830 if (utype->integer_type() == NULL
3831 || utype->integer_type()->is_abstract())
3832 mpz_com(val, uval);
3833 else
3835 // The number of HOST_WIDE_INTs that it takes to represent
3836 // UVAL.
3837 size_t count = ((mpz_sizeinbase(uval, 2)
3838 + HOST_BITS_PER_WIDE_INT
3839 - 1)
3840 / HOST_BITS_PER_WIDE_INT);
3842 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3843 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3845 size_t obits = utype->integer_type()->bits();
3847 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3849 mpz_t adj;
3850 mpz_init_set_ui(adj, 1);
3851 mpz_mul_2exp(adj, adj, obits);
3852 mpz_add(uval, uval, adj);
3853 mpz_clear(adj);
3856 size_t ecount;
3857 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3858 go_assert(ecount <= count);
3860 // Trim down to the number of words required by the type.
3861 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3862 / HOST_BITS_PER_WIDE_INT);
3863 go_assert(ocount <= count);
3865 for (size_t i = 0; i < ocount; ++i)
3866 phwi[i] = ~phwi[i];
3868 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3869 if (clearbits != 0)
3870 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3871 >> clearbits);
3873 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3875 if (!utype->integer_type()->is_unsigned()
3876 && mpz_tstbit(val, obits - 1))
3878 mpz_t adj;
3879 mpz_init_set_ui(adj, 1);
3880 mpz_mul_2exp(adj, adj, obits);
3881 mpz_sub(val, val, adj);
3882 mpz_clear(adj);
3885 delete[] phwi;
3888 break;
3890 default:
3891 go_unreachable();
3894 if (unc->is_rune())
3895 nc->set_rune(NULL, val);
3896 else
3897 nc->set_int(NULL, val);
3899 mpz_clear(uval);
3900 mpz_clear(val);
3902 return nc->set_type(unc->type(), true, location);
3905 // Return the integral constant value of a unary expression, if it has one.
3907 bool
3908 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3910 Numeric_constant unc;
3911 if (!this->expr_->numeric_constant_value(&unc))
3912 return false;
3913 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3914 nc);
3917 // Return the type of a unary expression.
3919 Type*
3920 Unary_expression::do_type()
3922 switch (this->op_)
3924 case OPERATOR_PLUS:
3925 case OPERATOR_MINUS:
3926 case OPERATOR_NOT:
3927 case OPERATOR_XOR:
3928 return this->expr_->type();
3930 case OPERATOR_AND:
3931 return Type::make_pointer_type(this->expr_->type());
3933 case OPERATOR_MULT:
3935 Type* subtype = this->expr_->type();
3936 Type* points_to = subtype->points_to();
3937 if (points_to == NULL)
3938 return Type::make_error_type();
3939 return points_to;
3942 default:
3943 go_unreachable();
3947 // Determine abstract types for a unary expression.
3949 void
3950 Unary_expression::do_determine_type(const Type_context* context)
3952 switch (this->op_)
3954 case OPERATOR_PLUS:
3955 case OPERATOR_MINUS:
3956 case OPERATOR_NOT:
3957 case OPERATOR_XOR:
3958 this->expr_->determine_type(context);
3959 break;
3961 case OPERATOR_AND:
3962 // Taking the address of something.
3964 Type* subtype = (context->type == NULL
3965 ? NULL
3966 : context->type->points_to());
3967 Type_context subcontext(subtype, false);
3968 this->expr_->determine_type(&subcontext);
3970 break;
3972 case OPERATOR_MULT:
3973 // Indirecting through a pointer.
3975 Type* subtype = (context->type == NULL
3976 ? NULL
3977 : Type::make_pointer_type(context->type));
3978 Type_context subcontext(subtype, false);
3979 this->expr_->determine_type(&subcontext);
3981 break;
3983 default:
3984 go_unreachable();
3988 // Check types for a unary expression.
3990 void
3991 Unary_expression::do_check_types(Gogo*)
3993 Type* type = this->expr_->type();
3994 if (type->is_error())
3996 this->set_is_error();
3997 return;
4000 switch (this->op_)
4002 case OPERATOR_PLUS:
4003 case OPERATOR_MINUS:
4004 if (type->integer_type() == NULL
4005 && type->float_type() == NULL
4006 && type->complex_type() == NULL)
4007 this->report_error(_("expected numeric type"));
4008 break;
4010 case OPERATOR_NOT:
4011 if (!type->is_boolean_type())
4012 this->report_error(_("expected boolean type"));
4013 break;
4015 case OPERATOR_XOR:
4016 if (type->integer_type() == NULL
4017 && !type->is_boolean_type())
4018 this->report_error(_("expected integer or boolean type"));
4019 break;
4021 case OPERATOR_AND:
4022 if (!this->expr_->is_addressable())
4024 if (!this->create_temp_)
4026 error_at(this->location(), "invalid operand for unary %<&%>");
4027 this->set_is_error();
4030 else
4032 this->expr_->address_taken(this->escapes_);
4033 this->expr_->issue_nil_check();
4035 break;
4037 case OPERATOR_MULT:
4038 // Indirecting through a pointer.
4039 if (type->points_to() == NULL)
4040 this->report_error(_("expected pointer"));
4041 break;
4043 default:
4044 go_unreachable();
4048 // Get the backend representation for a unary expression.
4050 Bexpression*
4051 Unary_expression::do_get_backend(Translate_context* context)
4053 Gogo* gogo = context->gogo();
4054 Location loc = this->location();
4056 // Taking the address of a set-and-use-temporary expression requires
4057 // setting the temporary and then taking the address.
4058 if (this->op_ == OPERATOR_AND)
4060 Set_and_use_temporary_expression* sut =
4061 this->expr_->set_and_use_temporary_expression();
4062 if (sut != NULL)
4064 Temporary_statement* temp = sut->temporary();
4065 Bvariable* bvar = temp->get_backend_variable(context);
4066 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4067 Bexpression* bval = sut->expression()->get_backend(context);
4069 Bstatement* bassign =
4070 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4071 Bexpression* bvar_addr =
4072 gogo->backend()->address_expression(bvar_expr, loc);
4073 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4077 Bexpression* ret;
4078 Bexpression* bexpr = this->expr_->get_backend(context);
4079 Btype* btype = this->expr_->type()->get_backend(gogo);
4080 switch (this->op_)
4082 case OPERATOR_PLUS:
4083 ret = bexpr;
4084 break;
4086 case OPERATOR_MINUS:
4087 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4088 ret = gogo->backend()->convert_expression(btype, ret, loc);
4089 break;
4091 case OPERATOR_NOT:
4092 case OPERATOR_XOR:
4093 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4094 break;
4096 case OPERATOR_AND:
4097 if (!this->create_temp_)
4099 // We should not see a non-constant constructor here; cases
4100 // where we would see one should have been moved onto the
4101 // heap at parse time. Taking the address of a nonconstant
4102 // constructor will not do what the programmer expects.
4104 go_assert(!this->expr_->is_composite_literal()
4105 || this->expr_->is_immutable());
4106 if (this->expr_->classification() == EXPRESSION_UNARY)
4108 Unary_expression* ue =
4109 static_cast<Unary_expression*>(this->expr_);
4110 go_assert(ue->op() != OPERATOR_AND);
4114 static unsigned int counter;
4115 char buf[100];
4116 if (this->is_gc_root_ || this->is_slice_init_)
4118 bool copy_to_heap = false;
4119 if (this->is_gc_root_)
4121 // Build a decl for a GC root variable. GC roots are mutable, so
4122 // they cannot be represented as an immutable_struct in the
4123 // backend.
4124 static unsigned int root_counter;
4125 snprintf(buf, sizeof buf, "gc%u", root_counter);
4126 ++root_counter;
4128 else
4130 // Build a decl for a slice value initializer. An immutable slice
4131 // value initializer may have to be copied to the heap if it
4132 // contains pointers in a non-constant context.
4133 snprintf(buf, sizeof buf, "C%u", counter);
4134 ++counter;
4136 Array_type* at = this->expr_->type()->array_type();
4137 go_assert(at != NULL);
4139 // If we are not copying the value to the heap, we will only
4140 // initialize the value once, so we can use this directly
4141 // rather than copying it. In that case we can't make it
4142 // read-only, because the program is permitted to change it.
4143 copy_to_heap = (at->element_type()->has_pointer()
4144 && !context->is_const());
4146 Bvariable* implicit =
4147 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
4148 false, 0);
4149 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4150 true, copy_to_heap, false,
4151 bexpr);
4152 bexpr = gogo->backend()->var_expression(implicit, loc);
4154 else if ((this->expr_->is_composite_literal()
4155 || this->expr_->string_expression() != NULL)
4156 && this->expr_->is_immutable())
4158 // Build a decl for a constant constructor.
4159 snprintf(buf, sizeof buf, "C%u", counter);
4160 ++counter;
4162 Bvariable* decl =
4163 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4164 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4165 btype, loc, bexpr);
4166 bexpr = gogo->backend()->var_expression(decl, loc);
4169 go_assert(!this->create_temp_ || this->expr_->is_variable());
4170 ret = gogo->backend()->address_expression(bexpr, loc);
4171 break;
4173 case OPERATOR_MULT:
4175 go_assert(this->expr_->type()->points_to() != NULL);
4177 // If we are dereferencing the pointer to a large struct, we
4178 // need to check for nil. We don't bother to check for small
4179 // structs because we expect the system to crash on a nil
4180 // pointer dereference. However, if we know the address of this
4181 // expression is being taken, we must always check for nil.
4183 Type* ptype = this->expr_->type()->points_to();
4184 Btype* pbtype = ptype->get_backend(gogo);
4185 if (!ptype->is_void_type())
4187 size_t s = gogo->backend()->type_size(pbtype);
4188 if (s >= 4096 || this->issue_nil_check_)
4190 go_assert(this->expr_->is_variable());
4191 Bexpression* nil =
4192 Expression::make_nil(loc)->get_backend(context);
4193 Bexpression* compare =
4194 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4195 nil, loc);
4196 Bexpression* crash =
4197 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4198 loc)->get_backend(context);
4199 bexpr = gogo->backend()->conditional_expression(btype, compare,
4200 crash, bexpr,
4201 loc);
4205 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4207 break;
4209 default:
4210 go_unreachable();
4213 return ret;
4216 // Export a unary expression.
4218 void
4219 Unary_expression::do_export(Export* exp) const
4221 switch (this->op_)
4223 case OPERATOR_PLUS:
4224 exp->write_c_string("+ ");
4225 break;
4226 case OPERATOR_MINUS:
4227 exp->write_c_string("- ");
4228 break;
4229 case OPERATOR_NOT:
4230 exp->write_c_string("! ");
4231 break;
4232 case OPERATOR_XOR:
4233 exp->write_c_string("^ ");
4234 break;
4235 case OPERATOR_AND:
4236 case OPERATOR_MULT:
4237 default:
4238 go_unreachable();
4240 this->expr_->export_expression(exp);
4243 // Import a unary expression.
4245 Expression*
4246 Unary_expression::do_import(Import* imp)
4248 Operator op;
4249 switch (imp->get_char())
4251 case '+':
4252 op = OPERATOR_PLUS;
4253 break;
4254 case '-':
4255 op = OPERATOR_MINUS;
4256 break;
4257 case '!':
4258 op = OPERATOR_NOT;
4259 break;
4260 case '^':
4261 op = OPERATOR_XOR;
4262 break;
4263 default:
4264 go_unreachable();
4266 imp->require_c_string(" ");
4267 Expression* expr = Expression::import_expression(imp);
4268 return Expression::make_unary(op, expr, imp->location());
4271 // Dump ast representation of an unary expression.
4273 void
4274 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4276 ast_dump_context->dump_operator(this->op_);
4277 ast_dump_context->ostream() << "(";
4278 ast_dump_context->dump_expression(this->expr_);
4279 ast_dump_context->ostream() << ") ";
4282 // Make a unary expression.
4284 Expression*
4285 Expression::make_unary(Operator op, Expression* expr, Location location)
4287 return new Unary_expression(op, expr, location);
4290 // If this is an indirection through a pointer, return the expression
4291 // being pointed through. Otherwise return this.
4293 Expression*
4294 Expression::deref()
4296 if (this->classification_ == EXPRESSION_UNARY)
4298 Unary_expression* ue = static_cast<Unary_expression*>(this);
4299 if (ue->op() == OPERATOR_MULT)
4300 return ue->operand();
4302 return this;
4305 // Class Binary_expression.
4307 // Traversal.
4310 Binary_expression::do_traverse(Traverse* traverse)
4312 int t = Expression::traverse(&this->left_, traverse);
4313 if (t == TRAVERSE_EXIT)
4314 return TRAVERSE_EXIT;
4315 return Expression::traverse(&this->right_, traverse);
4318 // Return the type to use for a binary operation on operands of
4319 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4320 // such may be NULL or abstract.
4322 bool
4323 Binary_expression::operation_type(Operator op, Type* left_type,
4324 Type* right_type, Type** result_type)
4326 if (left_type != right_type
4327 && !left_type->is_abstract()
4328 && !right_type->is_abstract()
4329 && left_type->base() != right_type->base()
4330 && op != OPERATOR_LSHIFT
4331 && op != OPERATOR_RSHIFT)
4333 // May be a type error--let it be diagnosed elsewhere.
4334 return false;
4337 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4339 if (left_type->integer_type() != NULL)
4340 *result_type = left_type;
4341 else
4342 *result_type = Type::make_abstract_integer_type();
4344 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4345 *result_type = left_type;
4346 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4347 *result_type = right_type;
4348 else if (!left_type->is_abstract())
4349 *result_type = left_type;
4350 else if (!right_type->is_abstract())
4351 *result_type = right_type;
4352 else if (left_type->complex_type() != NULL)
4353 *result_type = left_type;
4354 else if (right_type->complex_type() != NULL)
4355 *result_type = right_type;
4356 else if (left_type->float_type() != NULL)
4357 *result_type = left_type;
4358 else if (right_type->float_type() != NULL)
4359 *result_type = right_type;
4360 else if (left_type->integer_type() != NULL
4361 && left_type->integer_type()->is_rune())
4362 *result_type = left_type;
4363 else if (right_type->integer_type() != NULL
4364 && right_type->integer_type()->is_rune())
4365 *result_type = right_type;
4366 else
4367 *result_type = left_type;
4369 return true;
4372 // Convert an integer comparison code and an operator to a boolean
4373 // value.
4375 bool
4376 Binary_expression::cmp_to_bool(Operator op, int cmp)
4378 switch (op)
4380 case OPERATOR_EQEQ:
4381 return cmp == 0;
4382 break;
4383 case OPERATOR_NOTEQ:
4384 return cmp != 0;
4385 break;
4386 case OPERATOR_LT:
4387 return cmp < 0;
4388 break;
4389 case OPERATOR_LE:
4390 return cmp <= 0;
4391 case OPERATOR_GT:
4392 return cmp > 0;
4393 case OPERATOR_GE:
4394 return cmp >= 0;
4395 default:
4396 go_unreachable();
4400 // Compare constants according to OP.
4402 bool
4403 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4404 Numeric_constant* right_nc,
4405 Location location, bool* result)
4407 Type* left_type = left_nc->type();
4408 Type* right_type = right_nc->type();
4410 Type* type;
4411 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4412 return false;
4414 // When comparing an untyped operand to a typed operand, we are
4415 // effectively coercing the untyped operand to the other operand's
4416 // type, so make sure that is valid.
4417 if (!left_nc->set_type(type, true, location)
4418 || !right_nc->set_type(type, true, location))
4419 return false;
4421 bool ret;
4422 int cmp;
4423 if (type->complex_type() != NULL)
4425 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4426 return false;
4427 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4429 else if (type->float_type() != NULL)
4430 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4431 else
4432 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4434 if (ret)
4435 *result = Binary_expression::cmp_to_bool(op, cmp);
4437 return ret;
4440 // Compare integer constants.
4442 bool
4443 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4444 const Numeric_constant* right_nc,
4445 int* cmp)
4447 mpz_t left_val;
4448 if (!left_nc->to_int(&left_val))
4449 return false;
4450 mpz_t right_val;
4451 if (!right_nc->to_int(&right_val))
4453 mpz_clear(left_val);
4454 return false;
4457 *cmp = mpz_cmp(left_val, right_val);
4459 mpz_clear(left_val);
4460 mpz_clear(right_val);
4462 return true;
4465 // Compare floating point constants.
4467 bool
4468 Binary_expression::compare_float(const Numeric_constant* left_nc,
4469 const Numeric_constant* right_nc,
4470 int* cmp)
4472 mpfr_t left_val;
4473 if (!left_nc->to_float(&left_val))
4474 return false;
4475 mpfr_t right_val;
4476 if (!right_nc->to_float(&right_val))
4478 mpfr_clear(left_val);
4479 return false;
4482 // We already coerced both operands to the same type. If that type
4483 // is not an abstract type, we need to round the values accordingly.
4484 Type* type = left_nc->type();
4485 if (!type->is_abstract() && type->float_type() != NULL)
4487 int bits = type->float_type()->bits();
4488 mpfr_prec_round(left_val, bits, GMP_RNDN);
4489 mpfr_prec_round(right_val, bits, GMP_RNDN);
4492 *cmp = mpfr_cmp(left_val, right_val);
4494 mpfr_clear(left_val);
4495 mpfr_clear(right_val);
4497 return true;
4500 // Compare complex constants. Complex numbers may only be compared
4501 // for equality.
4503 bool
4504 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4505 const Numeric_constant* right_nc,
4506 int* cmp)
4508 mpfr_t left_real, left_imag;
4509 if (!left_nc->to_complex(&left_real, &left_imag))
4510 return false;
4511 mpfr_t right_real, right_imag;
4512 if (!right_nc->to_complex(&right_real, &right_imag))
4514 mpfr_clear(left_real);
4515 mpfr_clear(left_imag);
4516 return false;
4519 // We already coerced both operands to the same type. If that type
4520 // is not an abstract type, we need to round the values accordingly.
4521 Type* type = left_nc->type();
4522 if (!type->is_abstract() && type->complex_type() != NULL)
4524 int bits = type->complex_type()->bits();
4525 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4526 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4527 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4528 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4531 *cmp = (mpfr_cmp(left_real, right_real) != 0
4532 || mpfr_cmp(left_imag, right_imag) != 0);
4534 mpfr_clear(left_real);
4535 mpfr_clear(left_imag);
4536 mpfr_clear(right_real);
4537 mpfr_clear(right_imag);
4539 return true;
4542 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4543 // true if this could be done, false if not. Issue errors at LOCATION
4544 // as appropriate.
4546 bool
4547 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4548 Numeric_constant* right_nc,
4549 Location location, Numeric_constant* nc)
4551 switch (op)
4553 case OPERATOR_OROR:
4554 case OPERATOR_ANDAND:
4555 case OPERATOR_EQEQ:
4556 case OPERATOR_NOTEQ:
4557 case OPERATOR_LT:
4558 case OPERATOR_LE:
4559 case OPERATOR_GT:
4560 case OPERATOR_GE:
4561 // These return boolean values, not numeric.
4562 return false;
4563 default:
4564 break;
4567 Type* left_type = left_nc->type();
4568 Type* right_type = right_nc->type();
4570 Type* type;
4571 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4572 return false;
4574 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4576 // When combining an untyped operand with a typed operand, we are
4577 // effectively coercing the untyped operand to the other operand's
4578 // type, so make sure that is valid.
4579 if (!left_nc->set_type(type, true, location))
4580 return false;
4581 if (!is_shift && !right_nc->set_type(type, true, location))
4582 return false;
4584 bool r;
4585 if (type->complex_type() != NULL)
4586 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4587 else if (type->float_type() != NULL)
4588 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4589 else
4590 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4592 if (r)
4593 r = nc->set_type(type, true, location);
4595 return r;
4598 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4599 // integer operations. Return true if this could be done, false if
4600 // not.
4602 bool
4603 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4604 const Numeric_constant* right_nc,
4605 Location location, Numeric_constant* nc)
4607 mpz_t left_val;
4608 if (!left_nc->to_int(&left_val))
4609 return false;
4610 mpz_t right_val;
4611 if (!right_nc->to_int(&right_val))
4613 mpz_clear(left_val);
4614 return false;
4617 mpz_t val;
4618 mpz_init(val);
4620 switch (op)
4622 case OPERATOR_PLUS:
4623 mpz_add(val, left_val, right_val);
4624 if (mpz_sizeinbase(val, 2) > 0x100000)
4626 error_at(location, "constant addition overflow");
4627 mpz_set_ui(val, 1);
4629 break;
4630 case OPERATOR_MINUS:
4631 mpz_sub(val, left_val, right_val);
4632 if (mpz_sizeinbase(val, 2) > 0x100000)
4634 error_at(location, "constant subtraction overflow");
4635 mpz_set_ui(val, 1);
4637 break;
4638 case OPERATOR_OR:
4639 mpz_ior(val, left_val, right_val);
4640 break;
4641 case OPERATOR_XOR:
4642 mpz_xor(val, left_val, right_val);
4643 break;
4644 case OPERATOR_MULT:
4645 mpz_mul(val, left_val, right_val);
4646 if (mpz_sizeinbase(val, 2) > 0x100000)
4648 error_at(location, "constant multiplication overflow");
4649 mpz_set_ui(val, 1);
4651 break;
4652 case OPERATOR_DIV:
4653 if (mpz_sgn(right_val) != 0)
4654 mpz_tdiv_q(val, left_val, right_val);
4655 else
4657 error_at(location, "division by zero");
4658 mpz_set_ui(val, 0);
4660 break;
4661 case OPERATOR_MOD:
4662 if (mpz_sgn(right_val) != 0)
4663 mpz_tdiv_r(val, left_val, right_val);
4664 else
4666 error_at(location, "division by zero");
4667 mpz_set_ui(val, 0);
4669 break;
4670 case OPERATOR_LSHIFT:
4672 unsigned long shift = mpz_get_ui(right_val);
4673 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4674 mpz_mul_2exp(val, left_val, shift);
4675 else
4677 error_at(location, "shift count overflow");
4678 mpz_set_ui(val, 1);
4680 break;
4682 break;
4683 case OPERATOR_RSHIFT:
4685 unsigned long shift = mpz_get_ui(right_val);
4686 if (mpz_cmp_ui(right_val, shift) != 0)
4688 error_at(location, "shift count overflow");
4689 mpz_set_ui(val, 1);
4691 else
4693 if (mpz_cmp_ui(left_val, 0) >= 0)
4694 mpz_tdiv_q_2exp(val, left_val, shift);
4695 else
4696 mpz_fdiv_q_2exp(val, left_val, shift);
4698 break;
4700 break;
4701 case OPERATOR_AND:
4702 mpz_and(val, left_val, right_val);
4703 break;
4704 case OPERATOR_BITCLEAR:
4706 mpz_t tval;
4707 mpz_init(tval);
4708 mpz_com(tval, right_val);
4709 mpz_and(val, left_val, tval);
4710 mpz_clear(tval);
4712 break;
4713 default:
4714 go_unreachable();
4717 mpz_clear(left_val);
4718 mpz_clear(right_val);
4720 if (left_nc->is_rune()
4721 || (op != OPERATOR_LSHIFT
4722 && op != OPERATOR_RSHIFT
4723 && right_nc->is_rune()))
4724 nc->set_rune(NULL, val);
4725 else
4726 nc->set_int(NULL, val);
4728 mpz_clear(val);
4730 return true;
4733 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4734 // floating point operations. Return true if this could be done,
4735 // false if not.
4737 bool
4738 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4739 const Numeric_constant* right_nc,
4740 Location location, Numeric_constant* nc)
4742 mpfr_t left_val;
4743 if (!left_nc->to_float(&left_val))
4744 return false;
4745 mpfr_t right_val;
4746 if (!right_nc->to_float(&right_val))
4748 mpfr_clear(left_val);
4749 return false;
4752 mpfr_t val;
4753 mpfr_init(val);
4755 bool ret = true;
4756 switch (op)
4758 case OPERATOR_PLUS:
4759 mpfr_add(val, left_val, right_val, GMP_RNDN);
4760 break;
4761 case OPERATOR_MINUS:
4762 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4763 break;
4764 case OPERATOR_OR:
4765 case OPERATOR_XOR:
4766 case OPERATOR_AND:
4767 case OPERATOR_BITCLEAR:
4768 case OPERATOR_MOD:
4769 case OPERATOR_LSHIFT:
4770 case OPERATOR_RSHIFT:
4771 mpfr_set_ui(val, 0, GMP_RNDN);
4772 ret = false;
4773 break;
4774 case OPERATOR_MULT:
4775 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4776 break;
4777 case OPERATOR_DIV:
4778 if (!mpfr_zero_p(right_val))
4779 mpfr_div(val, left_val, right_val, GMP_RNDN);
4780 else
4782 error_at(location, "division by zero");
4783 mpfr_set_ui(val, 0, GMP_RNDN);
4785 break;
4786 default:
4787 go_unreachable();
4790 mpfr_clear(left_val);
4791 mpfr_clear(right_val);
4793 nc->set_float(NULL, val);
4794 mpfr_clear(val);
4796 return ret;
4799 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4800 // complex operations. Return true if this could be done, false if
4801 // not.
4803 bool
4804 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4805 const Numeric_constant* right_nc,
4806 Location location, Numeric_constant* nc)
4808 mpfr_t left_real, left_imag;
4809 if (!left_nc->to_complex(&left_real, &left_imag))
4810 return false;
4811 mpfr_t right_real, right_imag;
4812 if (!right_nc->to_complex(&right_real, &right_imag))
4814 mpfr_clear(left_real);
4815 mpfr_clear(left_imag);
4816 return false;
4819 mpfr_t real, imag;
4820 mpfr_init(real);
4821 mpfr_init(imag);
4823 bool ret = true;
4824 switch (op)
4826 case OPERATOR_PLUS:
4827 mpfr_add(real, left_real, right_real, GMP_RNDN);
4828 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4829 break;
4830 case OPERATOR_MINUS:
4831 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4832 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4833 break;
4834 case OPERATOR_OR:
4835 case OPERATOR_XOR:
4836 case OPERATOR_AND:
4837 case OPERATOR_BITCLEAR:
4838 case OPERATOR_MOD:
4839 case OPERATOR_LSHIFT:
4840 case OPERATOR_RSHIFT:
4841 mpfr_set_ui(real, 0, GMP_RNDN);
4842 mpfr_set_ui(imag, 0, GMP_RNDN);
4843 ret = false;
4844 break;
4845 case OPERATOR_MULT:
4847 // You might think that multiplying two complex numbers would
4848 // be simple, and you would be right, until you start to think
4849 // about getting the right answer for infinity. If one
4850 // operand here is infinity and the other is anything other
4851 // than zero or NaN, then we are going to wind up subtracting
4852 // two infinity values. That will give us a NaN, but the
4853 // correct answer is infinity.
4855 mpfr_t lrrr;
4856 mpfr_init(lrrr);
4857 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4859 mpfr_t lrri;
4860 mpfr_init(lrri);
4861 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4863 mpfr_t lirr;
4864 mpfr_init(lirr);
4865 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4867 mpfr_t liri;
4868 mpfr_init(liri);
4869 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4871 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4872 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4874 // If we get NaN on both sides, check whether it should really
4875 // be infinity. The rule is that if either side of the
4876 // complex number is infinity, then the whole value is
4877 // infinity, even if the other side is NaN. So the only case
4878 // we have to fix is the one in which both sides are NaN.
4879 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4880 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4881 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4883 bool is_infinity = false;
4885 mpfr_t lr;
4886 mpfr_t li;
4887 mpfr_init_set(lr, left_real, GMP_RNDN);
4888 mpfr_init_set(li, left_imag, GMP_RNDN);
4890 mpfr_t rr;
4891 mpfr_t ri;
4892 mpfr_init_set(rr, right_real, GMP_RNDN);
4893 mpfr_init_set(ri, right_imag, GMP_RNDN);
4895 // If the left side is infinity, then the result is
4896 // infinity.
4897 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4899 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4900 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4901 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4902 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4903 if (mpfr_nan_p(rr))
4905 mpfr_set_ui(rr, 0, GMP_RNDN);
4906 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4908 if (mpfr_nan_p(ri))
4910 mpfr_set_ui(ri, 0, GMP_RNDN);
4911 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4913 is_infinity = true;
4916 // If the right side is infinity, then the result is
4917 // infinity.
4918 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4920 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4921 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4922 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4923 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4924 if (mpfr_nan_p(lr))
4926 mpfr_set_ui(lr, 0, GMP_RNDN);
4927 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4929 if (mpfr_nan_p(li))
4931 mpfr_set_ui(li, 0, GMP_RNDN);
4932 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4934 is_infinity = true;
4937 // If we got an overflow in the intermediate computations,
4938 // then the result is infinity.
4939 if (!is_infinity
4940 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4941 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4943 if (mpfr_nan_p(lr))
4945 mpfr_set_ui(lr, 0, GMP_RNDN);
4946 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4948 if (mpfr_nan_p(li))
4950 mpfr_set_ui(li, 0, GMP_RNDN);
4951 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4953 if (mpfr_nan_p(rr))
4955 mpfr_set_ui(rr, 0, GMP_RNDN);
4956 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4958 if (mpfr_nan_p(ri))
4960 mpfr_set_ui(ri, 0, GMP_RNDN);
4961 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4963 is_infinity = true;
4966 if (is_infinity)
4968 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4969 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4970 mpfr_mul(lirr, li, rr, GMP_RNDN);
4971 mpfr_mul(liri, li, ri, GMP_RNDN);
4972 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4973 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4974 mpfr_set_inf(real, mpfr_sgn(real));
4975 mpfr_set_inf(imag, mpfr_sgn(imag));
4978 mpfr_clear(lr);
4979 mpfr_clear(li);
4980 mpfr_clear(rr);
4981 mpfr_clear(ri);
4984 mpfr_clear(lrrr);
4985 mpfr_clear(lrri);
4986 mpfr_clear(lirr);
4987 mpfr_clear(liri);
4989 break;
4990 case OPERATOR_DIV:
4992 // For complex division we want to avoid having an
4993 // intermediate overflow turn the whole result in a NaN. We
4994 // scale the values to try to avoid this.
4996 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4998 error_at(location, "division by zero");
4999 mpfr_set_ui(real, 0, GMP_RNDN);
5000 mpfr_set_ui(imag, 0, GMP_RNDN);
5001 break;
5004 mpfr_t rra;
5005 mpfr_t ria;
5006 mpfr_init(rra);
5007 mpfr_init(ria);
5008 mpfr_abs(rra, right_real, GMP_RNDN);
5009 mpfr_abs(ria, right_imag, GMP_RNDN);
5010 mpfr_t t;
5011 mpfr_init(t);
5012 mpfr_max(t, rra, ria, GMP_RNDN);
5014 mpfr_t rr;
5015 mpfr_t ri;
5016 mpfr_init_set(rr, right_real, GMP_RNDN);
5017 mpfr_init_set(ri, right_imag, GMP_RNDN);
5018 long ilogbw = 0;
5019 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
5021 ilogbw = mpfr_get_exp(t);
5022 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
5023 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
5026 mpfr_t denom;
5027 mpfr_init(denom);
5028 mpfr_mul(denom, rr, rr, GMP_RNDN);
5029 mpfr_mul(t, ri, ri, GMP_RNDN);
5030 mpfr_add(denom, denom, t, GMP_RNDN);
5032 mpfr_mul(real, left_real, rr, GMP_RNDN);
5033 mpfr_mul(t, left_imag, ri, GMP_RNDN);
5034 mpfr_add(real, real, t, GMP_RNDN);
5035 mpfr_div(real, real, denom, GMP_RNDN);
5036 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
5038 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
5039 mpfr_mul(t, left_real, ri, GMP_RNDN);
5040 mpfr_sub(imag, imag, t, GMP_RNDN);
5041 mpfr_div(imag, imag, denom, GMP_RNDN);
5042 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5044 // If we wind up with NaN on both sides, check whether we
5045 // should really have infinity. The rule is that if either
5046 // side of the complex number is infinity, then the whole
5047 // value is infinity, even if the other side is NaN. So the
5048 // only case we have to fix is the one in which both sides are
5049 // NaN.
5050 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5051 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5052 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5054 if (mpfr_zero_p(denom))
5056 mpfr_set_inf(real, mpfr_sgn(rr));
5057 mpfr_mul(real, real, left_real, GMP_RNDN);
5058 mpfr_set_inf(imag, mpfr_sgn(rr));
5059 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5061 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5062 && mpfr_number_p(rr) && mpfr_number_p(ri))
5064 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5065 mpfr_copysign(t, t, left_real, GMP_RNDN);
5067 mpfr_t t2;
5068 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5069 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5071 mpfr_t t3;
5072 mpfr_init(t3);
5073 mpfr_mul(t3, t, rr, GMP_RNDN);
5075 mpfr_t t4;
5076 mpfr_init(t4);
5077 mpfr_mul(t4, t2, ri, GMP_RNDN);
5079 mpfr_add(t3, t3, t4, GMP_RNDN);
5080 mpfr_set_inf(real, mpfr_sgn(t3));
5082 mpfr_mul(t3, t2, rr, GMP_RNDN);
5083 mpfr_mul(t4, t, ri, GMP_RNDN);
5084 mpfr_sub(t3, t3, t4, GMP_RNDN);
5085 mpfr_set_inf(imag, mpfr_sgn(t3));
5087 mpfr_clear(t2);
5088 mpfr_clear(t3);
5089 mpfr_clear(t4);
5091 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5092 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5094 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5095 mpfr_copysign(t, t, rr, GMP_RNDN);
5097 mpfr_t t2;
5098 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5099 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5101 mpfr_t t3;
5102 mpfr_init(t3);
5103 mpfr_mul(t3, left_real, t, GMP_RNDN);
5105 mpfr_t t4;
5106 mpfr_init(t4);
5107 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5109 mpfr_add(t3, t3, t4, GMP_RNDN);
5110 mpfr_set_ui(real, 0, GMP_RNDN);
5111 mpfr_mul(real, real, t3, GMP_RNDN);
5113 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5114 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5115 mpfr_sub(t3, t3, t4, GMP_RNDN);
5116 mpfr_set_ui(imag, 0, GMP_RNDN);
5117 mpfr_mul(imag, imag, t3, GMP_RNDN);
5119 mpfr_clear(t2);
5120 mpfr_clear(t3);
5121 mpfr_clear(t4);
5125 mpfr_clear(denom);
5126 mpfr_clear(rr);
5127 mpfr_clear(ri);
5128 mpfr_clear(t);
5129 mpfr_clear(rra);
5130 mpfr_clear(ria);
5132 break;
5133 default:
5134 go_unreachable();
5137 mpfr_clear(left_real);
5138 mpfr_clear(left_imag);
5139 mpfr_clear(right_real);
5140 mpfr_clear(right_imag);
5142 nc->set_complex(NULL, real, imag);
5143 mpfr_clear(real);
5144 mpfr_clear(imag);
5146 return ret;
5149 // Lower a binary expression. We have to evaluate constant
5150 // expressions now, in order to implement Go's unlimited precision
5151 // constants.
5153 Expression*
5154 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5155 Statement_inserter* inserter, int)
5157 Location location = this->location();
5158 Operator op = this->op_;
5159 Expression* left = this->left_;
5160 Expression* right = this->right_;
5162 const bool is_comparison = (op == OPERATOR_EQEQ
5163 || op == OPERATOR_NOTEQ
5164 || op == OPERATOR_LT
5165 || op == OPERATOR_LE
5166 || op == OPERATOR_GT
5167 || op == OPERATOR_GE);
5169 // Numeric constant expressions.
5171 Numeric_constant left_nc;
5172 Numeric_constant right_nc;
5173 if (left->numeric_constant_value(&left_nc)
5174 && right->numeric_constant_value(&right_nc))
5176 if (is_comparison)
5178 bool result;
5179 if (!Binary_expression::compare_constant(op, &left_nc,
5180 &right_nc, location,
5181 &result))
5182 return this;
5183 return Expression::make_cast(Type::make_boolean_type(),
5184 Expression::make_boolean(result,
5185 location),
5186 location);
5188 else
5190 Numeric_constant nc;
5191 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5192 location, &nc))
5193 return this;
5194 return nc.expression(location);
5199 // String constant expressions.
5200 if (left->type()->is_string_type() && right->type()->is_string_type())
5202 std::string left_string;
5203 std::string right_string;
5204 if (left->string_constant_value(&left_string)
5205 && right->string_constant_value(&right_string))
5207 if (op == OPERATOR_PLUS)
5208 return Expression::make_string(left_string + right_string,
5209 location);
5210 else if (is_comparison)
5212 int cmp = left_string.compare(right_string);
5213 bool r = Binary_expression::cmp_to_bool(op, cmp);
5214 return Expression::make_boolean(r, location);
5219 // Lower struct, array, and some interface comparisons.
5220 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5222 if (left->type()->struct_type() != NULL
5223 && right->type()->struct_type() != NULL)
5224 return this->lower_struct_comparison(gogo, inserter);
5225 else if (left->type()->array_type() != NULL
5226 && !left->type()->is_slice_type()
5227 && right->type()->array_type() != NULL
5228 && !right->type()->is_slice_type())
5229 return this->lower_array_comparison(gogo, inserter);
5230 else if ((left->type()->interface_type() != NULL
5231 && right->type()->interface_type() == NULL)
5232 || (left->type()->interface_type() == NULL
5233 && right->type()->interface_type() != NULL))
5234 return this->lower_interface_value_comparison(gogo, inserter);
5237 return this;
5240 // Lower a struct comparison.
5242 Expression*
5243 Binary_expression::lower_struct_comparison(Gogo* gogo,
5244 Statement_inserter* inserter)
5246 Struct_type* st = this->left_->type()->struct_type();
5247 Struct_type* st2 = this->right_->type()->struct_type();
5248 if (st2 == NULL)
5249 return this;
5250 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5251 return this;
5252 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5253 this->right_->type(), NULL))
5254 return this;
5256 // See if we can compare using memcmp. As a heuristic, we use
5257 // memcmp rather than field references and comparisons if there are
5258 // more than two fields.
5259 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5260 return this->lower_compare_to_memcmp(gogo, inserter);
5262 Location loc = this->location();
5264 Expression* left = this->left_;
5265 Temporary_statement* left_temp = NULL;
5266 if (left->var_expression() == NULL
5267 && left->temporary_reference_expression() == NULL)
5269 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5270 inserter->insert(left_temp);
5271 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5274 Expression* right = this->right_;
5275 Temporary_statement* right_temp = NULL;
5276 if (right->var_expression() == NULL
5277 && right->temporary_reference_expression() == NULL)
5279 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5280 inserter->insert(right_temp);
5281 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5284 Expression* ret = Expression::make_boolean(true, loc);
5285 const Struct_field_list* fields = st->fields();
5286 unsigned int field_index = 0;
5287 for (Struct_field_list::const_iterator pf = fields->begin();
5288 pf != fields->end();
5289 ++pf, ++field_index)
5291 if (Gogo::is_sink_name(pf->field_name()))
5292 continue;
5294 if (field_index > 0)
5296 if (left_temp == NULL)
5297 left = left->copy();
5298 else
5299 left = Expression::make_temporary_reference(left_temp, loc);
5300 if (right_temp == NULL)
5301 right = right->copy();
5302 else
5303 right = Expression::make_temporary_reference(right_temp, loc);
5305 Expression* f1 = Expression::make_field_reference(left, field_index,
5306 loc);
5307 Expression* f2 = Expression::make_field_reference(right, field_index,
5308 loc);
5309 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5310 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5313 if (this->op_ == OPERATOR_NOTEQ)
5314 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5316 return ret;
5319 // Lower an array comparison.
5321 Expression*
5322 Binary_expression::lower_array_comparison(Gogo* gogo,
5323 Statement_inserter* inserter)
5325 Array_type* at = this->left_->type()->array_type();
5326 Array_type* at2 = this->right_->type()->array_type();
5327 if (at2 == NULL)
5328 return this;
5329 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5330 return this;
5331 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5332 this->right_->type(), NULL))
5333 return this;
5335 // Call memcmp directly if possible. This may let the middle-end
5336 // optimize the call.
5337 if (at->compare_is_identity(gogo))
5338 return this->lower_compare_to_memcmp(gogo, inserter);
5340 // Call the array comparison function.
5341 Named_object* hash_fn;
5342 Named_object* equal_fn;
5343 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5344 &hash_fn, &equal_fn);
5346 Location loc = this->location();
5348 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5350 Expression_list* args = new Expression_list();
5351 args->push_back(this->operand_address(inserter, this->left_));
5352 args->push_back(this->operand_address(inserter, this->right_));
5353 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5355 Expression* ret = Expression::make_call(func, args, false, loc);
5357 if (this->op_ == OPERATOR_NOTEQ)
5358 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5360 return ret;
5363 // Lower an interface to value comparison.
5365 Expression*
5366 Binary_expression::lower_interface_value_comparison(Gogo*,
5367 Statement_inserter* inserter)
5369 Type* left_type = this->left_->type();
5370 Type* right_type = this->right_->type();
5371 Interface_type* ift;
5372 if (left_type->interface_type() != NULL)
5374 ift = left_type->interface_type();
5375 if (!ift->implements_interface(right_type, NULL))
5376 return this;
5378 else
5380 ift = right_type->interface_type();
5381 if (!ift->implements_interface(left_type, NULL))
5382 return this;
5384 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5385 return this;
5387 Location loc = this->location();
5389 if (left_type->interface_type() == NULL
5390 && left_type->points_to() == NULL
5391 && !this->left_->is_addressable())
5393 Temporary_statement* temp =
5394 Statement::make_temporary(left_type, NULL, loc);
5395 inserter->insert(temp);
5396 this->left_ =
5397 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5400 if (right_type->interface_type() == NULL
5401 && right_type->points_to() == NULL
5402 && !this->right_->is_addressable())
5404 Temporary_statement* temp =
5405 Statement::make_temporary(right_type, NULL, loc);
5406 inserter->insert(temp);
5407 this->right_ =
5408 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5411 return this;
5414 // Lower a struct or array comparison to a call to memcmp.
5416 Expression*
5417 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5419 Location loc = this->location();
5421 Expression* a1 = this->operand_address(inserter, this->left_);
5422 Expression* a2 = this->operand_address(inserter, this->right_);
5423 Expression* len = Expression::make_type_info(this->left_->type(),
5424 TYPE_INFO_SIZE);
5426 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5427 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5428 return Expression::make_binary(this->op_, call, zero, loc);
5431 Expression*
5432 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5433 Statement_inserter* inserter)
5435 Location loc = this->location();
5436 Temporary_statement* temp;
5437 if (this->left_->type()->is_string_type()
5438 && this->op_ == OPERATOR_PLUS)
5440 if (!this->left_->is_variable())
5442 temp = Statement::make_temporary(NULL, this->left_, loc);
5443 inserter->insert(temp);
5444 this->left_ = Expression::make_temporary_reference(temp, loc);
5446 if (!this->right_->is_variable())
5448 temp =
5449 Statement::make_temporary(this->left_->type(), this->right_, loc);
5450 this->right_ = Expression::make_temporary_reference(temp, loc);
5451 inserter->insert(temp);
5455 Type* left_type = this->left_->type();
5456 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5457 || this->op_ == OPERATOR_RSHIFT);
5458 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5459 left_type->integer_type() != NULL)
5460 || this->op_ == OPERATOR_MOD);
5462 if (is_shift_op
5463 || (is_idiv_op
5464 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5466 if (!this->left_->is_variable())
5468 temp = Statement::make_temporary(NULL, this->left_, loc);
5469 inserter->insert(temp);
5470 this->left_ = Expression::make_temporary_reference(temp, loc);
5472 if (!this->right_->is_variable())
5474 temp =
5475 Statement::make_temporary(NULL, this->right_, loc);
5476 this->right_ = Expression::make_temporary_reference(temp, loc);
5477 inserter->insert(temp);
5480 return this;
5484 // Return the address of EXPR, cast to unsafe.Pointer.
5486 Expression*
5487 Binary_expression::operand_address(Statement_inserter* inserter,
5488 Expression* expr)
5490 Location loc = this->location();
5492 if (!expr->is_addressable())
5494 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5495 loc);
5496 inserter->insert(temp);
5497 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5499 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5500 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5501 Type* void_type = Type::make_void_type();
5502 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5503 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5506 // Return the numeric constant value, if it has one.
5508 bool
5509 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5511 Numeric_constant left_nc;
5512 if (!this->left_->numeric_constant_value(&left_nc))
5513 return false;
5514 Numeric_constant right_nc;
5515 if (!this->right_->numeric_constant_value(&right_nc))
5516 return false;
5517 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5518 this->location(), nc);
5521 // Note that the value is being discarded.
5523 bool
5524 Binary_expression::do_discarding_value()
5526 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5527 return this->right_->discarding_value();
5528 else
5530 this->unused_value_error();
5531 return false;
5535 // Get type.
5537 Type*
5538 Binary_expression::do_type()
5540 if (this->classification() == EXPRESSION_ERROR)
5541 return Type::make_error_type();
5543 switch (this->op_)
5545 case OPERATOR_EQEQ:
5546 case OPERATOR_NOTEQ:
5547 case OPERATOR_LT:
5548 case OPERATOR_LE:
5549 case OPERATOR_GT:
5550 case OPERATOR_GE:
5551 if (this->type_ == NULL)
5552 this->type_ = Type::make_boolean_type();
5553 return this->type_;
5555 case OPERATOR_PLUS:
5556 case OPERATOR_MINUS:
5557 case OPERATOR_OR:
5558 case OPERATOR_XOR:
5559 case OPERATOR_MULT:
5560 case OPERATOR_DIV:
5561 case OPERATOR_MOD:
5562 case OPERATOR_AND:
5563 case OPERATOR_BITCLEAR:
5564 case OPERATOR_OROR:
5565 case OPERATOR_ANDAND:
5567 Type* type;
5568 if (!Binary_expression::operation_type(this->op_,
5569 this->left_->type(),
5570 this->right_->type(),
5571 &type))
5572 return Type::make_error_type();
5573 return type;
5576 case OPERATOR_LSHIFT:
5577 case OPERATOR_RSHIFT:
5578 return this->left_->type();
5580 default:
5581 go_unreachable();
5585 // Set type for a binary expression.
5587 void
5588 Binary_expression::do_determine_type(const Type_context* context)
5590 Type* tleft = this->left_->type();
5591 Type* tright = this->right_->type();
5593 // Both sides should have the same type, except for the shift
5594 // operations. For a comparison, we should ignore the incoming
5595 // type.
5597 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5598 || this->op_ == OPERATOR_RSHIFT);
5600 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5601 || this->op_ == OPERATOR_NOTEQ
5602 || this->op_ == OPERATOR_LT
5603 || this->op_ == OPERATOR_LE
5604 || this->op_ == OPERATOR_GT
5605 || this->op_ == OPERATOR_GE);
5607 Type_context subcontext(*context);
5609 if (is_comparison)
5611 // In a comparison, the context does not determine the types of
5612 // the operands.
5613 subcontext.type = NULL;
5616 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5618 // For a logical operation, the context does not determine the
5619 // types of the operands. The operands must be some boolean
5620 // type but if the context has a boolean type they do not
5621 // inherit it. See http://golang.org/issue/3924.
5622 subcontext.type = NULL;
5625 // Set the context for the left hand operand.
5626 if (is_shift_op)
5628 // The right hand operand of a shift plays no role in
5629 // determining the type of the left hand operand.
5631 else if (!tleft->is_abstract())
5632 subcontext.type = tleft;
5633 else if (!tright->is_abstract())
5634 subcontext.type = tright;
5635 else if (subcontext.type == NULL)
5637 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5638 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5639 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5641 // Both sides have an abstract integer, abstract float, or
5642 // abstract complex type. Just let CONTEXT determine
5643 // whether they may remain abstract or not.
5645 else if (tleft->complex_type() != NULL)
5646 subcontext.type = tleft;
5647 else if (tright->complex_type() != NULL)
5648 subcontext.type = tright;
5649 else if (tleft->float_type() != NULL)
5650 subcontext.type = tleft;
5651 else if (tright->float_type() != NULL)
5652 subcontext.type = tright;
5653 else
5654 subcontext.type = tleft;
5656 if (subcontext.type != NULL && !context->may_be_abstract)
5657 subcontext.type = subcontext.type->make_non_abstract_type();
5660 this->left_->determine_type(&subcontext);
5662 if (is_shift_op)
5664 // We may have inherited an unusable type for the shift operand.
5665 // Give a useful error if that happened.
5666 if (tleft->is_abstract()
5667 && subcontext.type != NULL
5668 && !subcontext.may_be_abstract
5669 && subcontext.type->interface_type() == NULL
5670 && subcontext.type->integer_type() == NULL)
5671 this->report_error(("invalid context-determined non-integer type "
5672 "for left operand of shift"));
5674 // The context for the right hand operand is the same as for the
5675 // left hand operand, except for a shift operator.
5676 subcontext.type = Type::lookup_integer_type("uint");
5677 subcontext.may_be_abstract = false;
5680 this->right_->determine_type(&subcontext);
5682 if (is_comparison)
5684 if (this->type_ != NULL && !this->type_->is_abstract())
5686 else if (context->type != NULL && context->type->is_boolean_type())
5687 this->type_ = context->type;
5688 else if (!context->may_be_abstract)
5689 this->type_ = Type::lookup_bool_type();
5693 // Report an error if the binary operator OP does not support TYPE.
5694 // OTYPE is the type of the other operand. Return whether the
5695 // operation is OK. This should not be used for shift.
5697 bool
5698 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5699 Location location)
5701 switch (op)
5703 case OPERATOR_OROR:
5704 case OPERATOR_ANDAND:
5705 if (!type->is_boolean_type())
5707 error_at(location, "expected boolean type");
5708 return false;
5710 break;
5712 case OPERATOR_EQEQ:
5713 case OPERATOR_NOTEQ:
5715 std::string reason;
5716 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5718 error_at(location, "%s", reason.c_str());
5719 return false;
5722 break;
5724 case OPERATOR_LT:
5725 case OPERATOR_LE:
5726 case OPERATOR_GT:
5727 case OPERATOR_GE:
5729 std::string reason;
5730 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5732 error_at(location, "%s", reason.c_str());
5733 return false;
5736 break;
5738 case OPERATOR_PLUS:
5739 case OPERATOR_PLUSEQ:
5740 if (type->integer_type() == NULL
5741 && type->float_type() == NULL
5742 && type->complex_type() == NULL
5743 && !type->is_string_type())
5745 error_at(location,
5746 "expected integer, floating, complex, or string type");
5747 return false;
5749 break;
5751 case OPERATOR_MINUS:
5752 case OPERATOR_MINUSEQ:
5753 case OPERATOR_MULT:
5754 case OPERATOR_MULTEQ:
5755 case OPERATOR_DIV:
5756 case OPERATOR_DIVEQ:
5757 if (type->integer_type() == NULL
5758 && type->float_type() == NULL
5759 && type->complex_type() == NULL)
5761 error_at(location, "expected integer, floating, or complex type");
5762 return false;
5764 break;
5766 case OPERATOR_MOD:
5767 case OPERATOR_MODEQ:
5768 case OPERATOR_OR:
5769 case OPERATOR_OREQ:
5770 case OPERATOR_AND:
5771 case OPERATOR_ANDEQ:
5772 case OPERATOR_XOR:
5773 case OPERATOR_XOREQ:
5774 case OPERATOR_BITCLEAR:
5775 case OPERATOR_BITCLEAREQ:
5776 if (type->integer_type() == NULL)
5778 error_at(location, "expected integer type");
5779 return false;
5781 break;
5783 default:
5784 go_unreachable();
5787 return true;
5790 // Check types.
5792 void
5793 Binary_expression::do_check_types(Gogo*)
5795 if (this->classification() == EXPRESSION_ERROR)
5796 return;
5798 Type* left_type = this->left_->type();
5799 Type* right_type = this->right_->type();
5800 if (left_type->is_error() || right_type->is_error())
5802 this->set_is_error();
5803 return;
5806 if (this->op_ == OPERATOR_EQEQ
5807 || this->op_ == OPERATOR_NOTEQ
5808 || this->op_ == OPERATOR_LT
5809 || this->op_ == OPERATOR_LE
5810 || this->op_ == OPERATOR_GT
5811 || this->op_ == OPERATOR_GE)
5813 if (left_type->is_nil_type() && right_type->is_nil_type())
5815 this->report_error(_("invalid comparison of nil with nil"));
5816 return;
5818 if (!Type::are_assignable(left_type, right_type, NULL)
5819 && !Type::are_assignable(right_type, left_type, NULL))
5821 this->report_error(_("incompatible types in binary expression"));
5822 return;
5824 if (!Binary_expression::check_operator_type(this->op_, left_type,
5825 right_type,
5826 this->location())
5827 || !Binary_expression::check_operator_type(this->op_, right_type,
5828 left_type,
5829 this->location()))
5831 this->set_is_error();
5832 return;
5835 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5837 if (!Type::are_compatible_for_binop(left_type, right_type))
5839 this->report_error(_("incompatible types in binary expression"));
5840 return;
5842 if (!Binary_expression::check_operator_type(this->op_, left_type,
5843 right_type,
5844 this->location()))
5846 this->set_is_error();
5847 return;
5849 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5851 // Division by a zero integer constant is an error.
5852 Numeric_constant rconst;
5853 unsigned long rval;
5854 if (left_type->integer_type() != NULL
5855 && this->right_->numeric_constant_value(&rconst)
5856 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5857 && rval == 0)
5859 this->report_error(_("integer division by zero"));
5860 return;
5864 else
5866 if (left_type->integer_type() == NULL)
5867 this->report_error(_("shift of non-integer operand"));
5869 if (!right_type->is_abstract()
5870 && (right_type->integer_type() == NULL
5871 || !right_type->integer_type()->is_unsigned()))
5872 this->report_error(_("shift count not unsigned integer"));
5873 else
5875 Numeric_constant nc;
5876 if (this->right_->numeric_constant_value(&nc))
5878 mpz_t val;
5879 if (!nc.to_int(&val))
5880 this->report_error(_("shift count not unsigned integer"));
5881 else
5883 if (mpz_sgn(val) < 0)
5885 this->report_error(_("negative shift count"));
5886 Location rloc = this->right_->location();
5887 this->right_ = Expression::make_integer_ul(0, right_type,
5888 rloc);
5890 mpz_clear(val);
5897 // Get the backend representation for a binary expression.
5899 Bexpression*
5900 Binary_expression::do_get_backend(Translate_context* context)
5902 Gogo* gogo = context->gogo();
5903 Location loc = this->location();
5904 Type* left_type = this->left_->type();
5905 Type* right_type = this->right_->type();
5907 bool use_left_type = true;
5908 bool is_shift_op = false;
5909 bool is_idiv_op = false;
5910 switch (this->op_)
5912 case OPERATOR_EQEQ:
5913 case OPERATOR_NOTEQ:
5914 case OPERATOR_LT:
5915 case OPERATOR_LE:
5916 case OPERATOR_GT:
5917 case OPERATOR_GE:
5918 return Expression::comparison(context, this->type_, this->op_,
5919 this->left_, this->right_, loc);
5921 case OPERATOR_OROR:
5922 case OPERATOR_ANDAND:
5923 use_left_type = false;
5924 break;
5925 case OPERATOR_PLUS:
5926 case OPERATOR_MINUS:
5927 case OPERATOR_OR:
5928 case OPERATOR_XOR:
5929 case OPERATOR_MULT:
5930 break;
5931 case OPERATOR_DIV:
5932 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5933 break;
5934 case OPERATOR_MOD:
5935 is_idiv_op = true;
5936 break;
5937 case OPERATOR_LSHIFT:
5938 case OPERATOR_RSHIFT:
5939 is_shift_op = true;
5940 break;
5941 case OPERATOR_BITCLEAR:
5942 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5943 case OPERATOR_AND:
5944 break;
5945 default:
5946 go_unreachable();
5949 if (left_type->is_string_type())
5951 go_assert(this->op_ == OPERATOR_PLUS);
5952 Expression* string_plus =
5953 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5954 this->left_, this->right_);
5955 return string_plus->get_backend(context);
5958 // For complex division Go might want slightly different results than the
5959 // backend implementation provides, so we have our own runtime routine.
5960 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5962 Runtime::Function complex_code;
5963 switch (this->left_->type()->complex_type()->bits())
5965 case 64:
5966 complex_code = Runtime::COMPLEX64_DIV;
5967 break;
5968 case 128:
5969 complex_code = Runtime::COMPLEX128_DIV;
5970 break;
5971 default:
5972 go_unreachable();
5974 Expression* complex_div =
5975 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5976 return complex_div->get_backend(context);
5979 Bexpression* left = this->left_->get_backend(context);
5980 Bexpression* right = this->right_->get_backend(context);
5982 Type* type = use_left_type ? left_type : right_type;
5983 Btype* btype = type->get_backend(gogo);
5985 Bexpression* ret =
5986 gogo->backend()->binary_expression(this->op_, left, right, loc);
5987 ret = gogo->backend()->convert_expression(btype, ret, loc);
5989 // Initialize overflow constants.
5990 Bexpression* overflow;
5991 mpz_t zero;
5992 mpz_init_set_ui(zero, 0UL);
5993 mpz_t one;
5994 mpz_init_set_ui(one, 1UL);
5995 mpz_t neg_one;
5996 mpz_init_set_si(neg_one, -1);
5998 Btype* left_btype = left_type->get_backend(gogo);
5999 Btype* right_btype = right_type->get_backend(gogo);
6001 // In Go, a shift larger than the size of the type is well-defined.
6002 // This is not true in C, so we need to insert a conditional.
6003 if (is_shift_op)
6005 go_assert(left_type->integer_type() != NULL);
6007 mpz_t bitsval;
6008 int bits = left_type->integer_type()->bits();
6009 mpz_init_set_ui(bitsval, bits);
6010 Bexpression* bits_expr =
6011 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6012 Bexpression* compare =
6013 gogo->backend()->binary_expression(OPERATOR_LT,
6014 right, bits_expr, loc);
6016 Bexpression* zero_expr =
6017 gogo->backend()->integer_constant_expression(left_btype, zero);
6018 overflow = zero_expr;
6019 if (this->op_ == OPERATOR_RSHIFT
6020 && !left_type->integer_type()->is_unsigned())
6022 Bexpression* neg_expr =
6023 gogo->backend()->binary_expression(OPERATOR_LT, left,
6024 zero_expr, loc);
6025 Bexpression* neg_one_expr =
6026 gogo->backend()->integer_constant_expression(left_btype, neg_one);
6027 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
6028 neg_one_expr,
6029 zero_expr, loc);
6031 ret = gogo->backend()->conditional_expression(btype, compare, ret,
6032 overflow, loc);
6033 mpz_clear(bitsval);
6036 // Add checks for division by zero and division overflow as needed.
6037 if (is_idiv_op)
6039 if (gogo->check_divide_by_zero())
6041 // right == 0
6042 Bexpression* zero_expr =
6043 gogo->backend()->integer_constant_expression(right_btype, zero);
6044 Bexpression* check =
6045 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6046 right, zero_expr, loc);
6048 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6049 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6050 Bexpression* crash = gogo->runtime_error(errcode,
6051 loc)->get_backend(context);
6053 // right == 0 ? (__go_runtime_error(...), 0) : ret
6054 ret = gogo->backend()->conditional_expression(btype, check, crash,
6055 ret, loc);
6058 if (gogo->check_divide_overflow())
6060 // right == -1
6061 // FIXME: It would be nice to say that this test is expected
6062 // to return false.
6064 Bexpression* neg_one_expr =
6065 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6066 Bexpression* check =
6067 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6068 right, neg_one_expr, loc);
6070 Bexpression* zero_expr =
6071 gogo->backend()->integer_constant_expression(btype, zero);
6072 Bexpression* one_expr =
6073 gogo->backend()->integer_constant_expression(btype, one);
6075 if (type->integer_type()->is_unsigned())
6077 // An unsigned -1 is the largest possible number, so
6078 // dividing is always 1 or 0.
6080 Bexpression* cmp =
6081 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6082 left, right, loc);
6083 if (this->op_ == OPERATOR_DIV)
6084 overflow =
6085 gogo->backend()->conditional_expression(btype, cmp,
6086 one_expr, zero_expr,
6087 loc);
6088 else
6089 overflow =
6090 gogo->backend()->conditional_expression(btype, cmp,
6091 zero_expr, left,
6092 loc);
6094 else
6096 // Computing left / -1 is the same as computing - left,
6097 // which does not overflow since Go sets -fwrapv.
6098 if (this->op_ == OPERATOR_DIV)
6100 Expression* negate_expr =
6101 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6102 overflow = negate_expr->get_backend(context);
6104 else
6105 overflow = zero_expr;
6107 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6109 // right == -1 ? - left : ret
6110 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6111 ret, loc);
6115 mpz_clear(zero);
6116 mpz_clear(one);
6117 mpz_clear(neg_one);
6118 return ret;
6121 // Export a binary expression.
6123 void
6124 Binary_expression::do_export(Export* exp) const
6126 exp->write_c_string("(");
6127 this->left_->export_expression(exp);
6128 switch (this->op_)
6130 case OPERATOR_OROR:
6131 exp->write_c_string(" || ");
6132 break;
6133 case OPERATOR_ANDAND:
6134 exp->write_c_string(" && ");
6135 break;
6136 case OPERATOR_EQEQ:
6137 exp->write_c_string(" == ");
6138 break;
6139 case OPERATOR_NOTEQ:
6140 exp->write_c_string(" != ");
6141 break;
6142 case OPERATOR_LT:
6143 exp->write_c_string(" < ");
6144 break;
6145 case OPERATOR_LE:
6146 exp->write_c_string(" <= ");
6147 break;
6148 case OPERATOR_GT:
6149 exp->write_c_string(" > ");
6150 break;
6151 case OPERATOR_GE:
6152 exp->write_c_string(" >= ");
6153 break;
6154 case OPERATOR_PLUS:
6155 exp->write_c_string(" + ");
6156 break;
6157 case OPERATOR_MINUS:
6158 exp->write_c_string(" - ");
6159 break;
6160 case OPERATOR_OR:
6161 exp->write_c_string(" | ");
6162 break;
6163 case OPERATOR_XOR:
6164 exp->write_c_string(" ^ ");
6165 break;
6166 case OPERATOR_MULT:
6167 exp->write_c_string(" * ");
6168 break;
6169 case OPERATOR_DIV:
6170 exp->write_c_string(" / ");
6171 break;
6172 case OPERATOR_MOD:
6173 exp->write_c_string(" % ");
6174 break;
6175 case OPERATOR_LSHIFT:
6176 exp->write_c_string(" << ");
6177 break;
6178 case OPERATOR_RSHIFT:
6179 exp->write_c_string(" >> ");
6180 break;
6181 case OPERATOR_AND:
6182 exp->write_c_string(" & ");
6183 break;
6184 case OPERATOR_BITCLEAR:
6185 exp->write_c_string(" &^ ");
6186 break;
6187 default:
6188 go_unreachable();
6190 this->right_->export_expression(exp);
6191 exp->write_c_string(")");
6194 // Import a binary expression.
6196 Expression*
6197 Binary_expression::do_import(Import* imp)
6199 imp->require_c_string("(");
6201 Expression* left = Expression::import_expression(imp);
6203 Operator op;
6204 if (imp->match_c_string(" || "))
6206 op = OPERATOR_OROR;
6207 imp->advance(4);
6209 else if (imp->match_c_string(" && "))
6211 op = OPERATOR_ANDAND;
6212 imp->advance(4);
6214 else if (imp->match_c_string(" == "))
6216 op = OPERATOR_EQEQ;
6217 imp->advance(4);
6219 else if (imp->match_c_string(" != "))
6221 op = OPERATOR_NOTEQ;
6222 imp->advance(4);
6224 else if (imp->match_c_string(" < "))
6226 op = OPERATOR_LT;
6227 imp->advance(3);
6229 else if (imp->match_c_string(" <= "))
6231 op = OPERATOR_LE;
6232 imp->advance(4);
6234 else if (imp->match_c_string(" > "))
6236 op = OPERATOR_GT;
6237 imp->advance(3);
6239 else if (imp->match_c_string(" >= "))
6241 op = OPERATOR_GE;
6242 imp->advance(4);
6244 else if (imp->match_c_string(" + "))
6246 op = OPERATOR_PLUS;
6247 imp->advance(3);
6249 else if (imp->match_c_string(" - "))
6251 op = OPERATOR_MINUS;
6252 imp->advance(3);
6254 else if (imp->match_c_string(" | "))
6256 op = OPERATOR_OR;
6257 imp->advance(3);
6259 else if (imp->match_c_string(" ^ "))
6261 op = OPERATOR_XOR;
6262 imp->advance(3);
6264 else if (imp->match_c_string(" * "))
6266 op = OPERATOR_MULT;
6267 imp->advance(3);
6269 else if (imp->match_c_string(" / "))
6271 op = OPERATOR_DIV;
6272 imp->advance(3);
6274 else if (imp->match_c_string(" % "))
6276 op = OPERATOR_MOD;
6277 imp->advance(3);
6279 else if (imp->match_c_string(" << "))
6281 op = OPERATOR_LSHIFT;
6282 imp->advance(4);
6284 else if (imp->match_c_string(" >> "))
6286 op = OPERATOR_RSHIFT;
6287 imp->advance(4);
6289 else if (imp->match_c_string(" & "))
6291 op = OPERATOR_AND;
6292 imp->advance(3);
6294 else if (imp->match_c_string(" &^ "))
6296 op = OPERATOR_BITCLEAR;
6297 imp->advance(4);
6299 else
6301 error_at(imp->location(), "unrecognized binary operator");
6302 return Expression::make_error(imp->location());
6305 Expression* right = Expression::import_expression(imp);
6307 imp->require_c_string(")");
6309 return Expression::make_binary(op, left, right, imp->location());
6312 // Dump ast representation of a binary expression.
6314 void
6315 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6317 ast_dump_context->ostream() << "(";
6318 ast_dump_context->dump_expression(this->left_);
6319 ast_dump_context->ostream() << " ";
6320 ast_dump_context->dump_operator(this->op_);
6321 ast_dump_context->ostream() << " ";
6322 ast_dump_context->dump_expression(this->right_);
6323 ast_dump_context->ostream() << ") ";
6326 // Make a binary expression.
6328 Expression*
6329 Expression::make_binary(Operator op, Expression* left, Expression* right,
6330 Location location)
6332 return new Binary_expression(op, left, right, location);
6335 // Implement a comparison.
6337 Bexpression*
6338 Expression::comparison(Translate_context* context, Type* result_type,
6339 Operator op, Expression* left, Expression* right,
6340 Location location)
6342 Type* left_type = left->type();
6343 Type* right_type = right->type();
6345 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6347 if (left_type->is_string_type() && right_type->is_string_type())
6349 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6350 left, right);
6351 right = zexpr;
6353 else if ((left_type->interface_type() != NULL
6354 && right_type->interface_type() == NULL
6355 && !right_type->is_nil_type())
6356 || (left_type->interface_type() == NULL
6357 && !left_type->is_nil_type()
6358 && right_type->interface_type() != NULL))
6360 // Comparing an interface value to a non-interface value.
6361 if (left_type->interface_type() == NULL)
6363 std::swap(left_type, right_type);
6364 std::swap(left, right);
6367 // The right operand is not an interface. We need to take its
6368 // address if it is not a pointer.
6369 Expression* pointer_arg = NULL;
6370 if (right_type->points_to() != NULL)
6371 pointer_arg = right;
6372 else
6374 go_assert(right->is_addressable());
6375 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6376 location);
6379 Expression* descriptor =
6380 Expression::make_type_descriptor(right_type, location);
6381 left =
6382 Runtime::make_call((left_type->interface_type()->is_empty()
6383 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6384 : Runtime::INTERFACE_VALUE_COMPARE),
6385 location, 3, left, descriptor,
6386 pointer_arg);
6387 right = zexpr;
6389 else if (left_type->interface_type() != NULL
6390 && right_type->interface_type() != NULL)
6392 Runtime::Function compare_function;
6393 if (left_type->interface_type()->is_empty()
6394 && right_type->interface_type()->is_empty())
6395 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6396 else if (!left_type->interface_type()->is_empty()
6397 && !right_type->interface_type()->is_empty())
6398 compare_function = Runtime::INTERFACE_COMPARE;
6399 else
6401 if (left_type->interface_type()->is_empty())
6403 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6404 std::swap(left_type, right_type);
6405 std::swap(left, right);
6407 go_assert(!left_type->interface_type()->is_empty());
6408 go_assert(right_type->interface_type()->is_empty());
6409 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6412 left = Runtime::make_call(compare_function, location, 2, left, right);
6413 right = zexpr;
6416 if (left_type->is_nil_type()
6417 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6419 std::swap(left_type, right_type);
6420 std::swap(left, right);
6423 if (right_type->is_nil_type())
6425 right = Expression::make_nil(location);
6426 if (left_type->array_type() != NULL
6427 && left_type->array_type()->length() == NULL)
6429 Array_type* at = left_type->array_type();
6430 left = at->get_value_pointer(context->gogo(), left);
6432 else if (left_type->interface_type() != NULL)
6434 // An interface is nil if the first field is nil.
6435 left = Expression::make_field_reference(left, 0, location);
6439 Bexpression* left_bexpr = left->get_backend(context);
6440 Bexpression* right_bexpr = right->get_backend(context);
6442 Gogo* gogo = context->gogo();
6443 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6444 right_bexpr, location);
6445 if (result_type != NULL)
6446 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6447 ret, location);
6448 return ret;
6451 // Class Bound_method_expression.
6453 // Traversal.
6456 Bound_method_expression::do_traverse(Traverse* traverse)
6458 return Expression::traverse(&this->expr_, traverse);
6461 // Lower the expression. If this is a method value rather than being
6462 // called, and the method is accessed via a pointer, we may need to
6463 // add nil checks. Introduce a temporary variable so that those nil
6464 // checks do not cause multiple evaluation.
6466 Expression*
6467 Bound_method_expression::do_lower(Gogo*, Named_object*,
6468 Statement_inserter* inserter, int)
6470 // For simplicity we use a temporary for every call to an embedded
6471 // method, even though some of them might be pure value methods and
6472 // not require a temporary.
6473 if (this->expr_->var_expression() == NULL
6474 && this->expr_->temporary_reference_expression() == NULL
6475 && this->expr_->set_and_use_temporary_expression() == NULL
6476 && (this->method_->field_indexes() != NULL
6477 || (this->method_->is_value_method()
6478 && this->expr_->type()->points_to() != NULL)))
6480 Temporary_statement* temp =
6481 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6482 inserter->insert(temp);
6483 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6484 this->location());
6486 return this;
6489 // Return the type of a bound method expression. The type of this
6490 // object is simply the type of the method with no receiver.
6492 Type*
6493 Bound_method_expression::do_type()
6495 Named_object* fn = this->method_->named_object();
6496 Function_type* fntype;
6497 if (fn->is_function())
6498 fntype = fn->func_value()->type();
6499 else if (fn->is_function_declaration())
6500 fntype = fn->func_declaration_value()->type();
6501 else
6502 return Type::make_error_type();
6503 return fntype->copy_without_receiver();
6506 // Determine the types of a method expression.
6508 void
6509 Bound_method_expression::do_determine_type(const Type_context*)
6511 Named_object* fn = this->method_->named_object();
6512 Function_type* fntype;
6513 if (fn->is_function())
6514 fntype = fn->func_value()->type();
6515 else if (fn->is_function_declaration())
6516 fntype = fn->func_declaration_value()->type();
6517 else
6518 fntype = NULL;
6519 if (fntype == NULL || !fntype->is_method())
6520 this->expr_->determine_type_no_context();
6521 else
6523 Type_context subcontext(fntype->receiver()->type(), false);
6524 this->expr_->determine_type(&subcontext);
6528 // Check the types of a method expression.
6530 void
6531 Bound_method_expression::do_check_types(Gogo*)
6533 Named_object* fn = this->method_->named_object();
6534 if (!fn->is_function() && !fn->is_function_declaration())
6536 this->report_error(_("object is not a method"));
6537 return;
6540 Function_type* fntype;
6541 if (fn->is_function())
6542 fntype = fn->func_value()->type();
6543 else if (fn->is_function_declaration())
6544 fntype = fn->func_declaration_value()->type();
6545 else
6546 go_unreachable();
6547 Type* rtype = fntype->receiver()->type()->deref();
6548 Type* etype = (this->expr_type_ != NULL
6549 ? this->expr_type_
6550 : this->expr_->type());
6551 etype = etype->deref();
6552 if (!Type::are_identical(rtype, etype, true, NULL))
6553 this->report_error(_("method type does not match object type"));
6556 // If a bound method expression is not simply called, then it is
6557 // represented as a closure. The closure will hold a single variable,
6558 // the receiver to pass to the method. The function will be a simple
6559 // thunk that pulls that value from the closure and calls the method
6560 // with the remaining arguments.
6562 // Because method values are not common, we don't build all thunks for
6563 // every methods, but instead only build them as we need them. In
6564 // particular, we even build them on demand for methods defined in
6565 // other packages.
6567 Bound_method_expression::Method_value_thunks
6568 Bound_method_expression::method_value_thunks;
6570 // Find or create the thunk for METHOD.
6572 Named_object*
6573 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6574 Named_object* fn)
6576 std::pair<Named_object*, Named_object*> val(fn, NULL);
6577 std::pair<Method_value_thunks::iterator, bool> ins =
6578 Bound_method_expression::method_value_thunks.insert(val);
6579 if (!ins.second)
6581 // We have seen this method before.
6582 go_assert(ins.first->second != NULL);
6583 return ins.first->second;
6586 Location loc = fn->location();
6588 Function_type* orig_fntype;
6589 if (fn->is_function())
6590 orig_fntype = fn->func_value()->type();
6591 else if (fn->is_function_declaration())
6592 orig_fntype = fn->func_declaration_value()->type();
6593 else
6594 orig_fntype = NULL;
6596 if (orig_fntype == NULL || !orig_fntype->is_method())
6598 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6599 return ins.first->second;
6602 Struct_field_list* sfl = new Struct_field_list();
6603 // The type here is wrong--it should be the C function type. But it
6604 // doesn't really matter.
6605 Type* vt = Type::make_pointer_type(Type::make_void_type());
6606 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6607 sfl->push_back(Struct_field(Typed_identifier("val.1",
6608 orig_fntype->receiver()->type(),
6609 loc)));
6610 Type* closure_type = Type::make_struct_type(sfl, loc);
6611 closure_type = Type::make_pointer_type(closure_type);
6613 Function_type* new_fntype = orig_fntype->copy_with_names();
6615 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6616 false, loc);
6618 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6619 cvar->set_is_used();
6620 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6621 new_no->func_value()->set_closure_var(cp);
6623 gogo->start_block(loc);
6625 // Field 0 of the closure is the function code pointer, field 1 is
6626 // the value on which to invoke the method.
6627 Expression* arg = Expression::make_var_reference(cp, loc);
6628 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6629 arg = Expression::make_field_reference(arg, 1, loc);
6631 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6633 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6634 Expression_list* args;
6635 if (orig_params == NULL || orig_params->empty())
6636 args = NULL;
6637 else
6639 const Typed_identifier_list* new_params = new_fntype->parameters();
6640 args = new Expression_list();
6641 for (Typed_identifier_list::const_iterator p = new_params->begin();
6642 p != new_params->end();
6643 ++p)
6645 Named_object* p_no = gogo->lookup(p->name(), NULL);
6646 go_assert(p_no != NULL
6647 && p_no->is_variable()
6648 && p_no->var_value()->is_parameter());
6649 args->push_back(Expression::make_var_reference(p_no, loc));
6653 Call_expression* call = Expression::make_call(bme, args,
6654 orig_fntype->is_varargs(),
6655 loc);
6656 call->set_varargs_are_lowered();
6658 Statement* s = Statement::make_return_from_call(call, loc);
6659 gogo->add_statement(s);
6660 Block* b = gogo->finish_block(loc);
6661 gogo->add_block(b, loc);
6662 gogo->lower_block(new_no, b);
6663 gogo->flatten_block(new_no, b);
6664 gogo->finish_function(loc);
6666 ins.first->second = new_no;
6667 return new_no;
6670 // Return an expression to check *REF for nil while dereferencing
6671 // according to FIELD_INDEXES. Update *REF to build up the field
6672 // reference. This is a static function so that we don't have to
6673 // worry about declaring Field_indexes in expressions.h.
6675 static Expression*
6676 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6677 Expression** ref)
6679 if (field_indexes == NULL)
6680 return Expression::make_boolean(false, loc);
6681 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6682 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6683 go_assert(stype != NULL
6684 && field_indexes->field_index < stype->field_count());
6685 if ((*ref)->type()->struct_type() == NULL)
6687 go_assert((*ref)->type()->points_to() != NULL);
6688 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6689 Expression::make_nil(loc),
6690 loc);
6691 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6692 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6693 go_assert((*ref)->type()->struct_type() == stype);
6695 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6696 loc);
6697 return cond;
6700 // Get the backend representation for a method value.
6702 Bexpression*
6703 Bound_method_expression::do_get_backend(Translate_context* context)
6705 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6706 this->method_,
6707 this->function_);
6708 if (thunk->is_erroneous())
6710 go_assert(saw_errors());
6711 return context->backend()->error_expression();
6714 // FIXME: We should lower this earlier, but we can't lower it in the
6715 // lowering pass because at that point we don't know whether we need
6716 // to create the thunk or not. If the expression is called, we
6717 // don't need the thunk.
6719 Location loc = this->location();
6721 // If the method expects a value, and we have a pointer, we need to
6722 // dereference the pointer.
6724 Named_object* fn = this->method_->named_object();
6725 Function_type* fntype;
6726 if (fn->is_function())
6727 fntype = fn->func_value()->type();
6728 else if (fn->is_function_declaration())
6729 fntype = fn->func_declaration_value()->type();
6730 else
6731 go_unreachable();
6733 Expression* val = this->expr_;
6734 if (fntype->receiver()->type()->points_to() == NULL
6735 && val->type()->points_to() != NULL)
6736 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6738 // Note that we are ignoring this->expr_type_ here. The thunk will
6739 // expect a closure whose second field has type this->expr_type_ (if
6740 // that is not NULL). We are going to pass it a closure whose
6741 // second field has type this->expr_->type(). Since
6742 // this->expr_type_ is only not-NULL for pointer types, we can get
6743 // away with this.
6745 Struct_field_list* fields = new Struct_field_list();
6746 fields->push_back(Struct_field(Typed_identifier("fn.0",
6747 thunk->func_value()->type(),
6748 loc)));
6749 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6750 Struct_type* st = Type::make_struct_type(fields, loc);
6752 Expression_list* vals = new Expression_list();
6753 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6754 vals->push_back(val);
6756 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6757 ret = Expression::make_heap_expression(ret, loc);
6759 // See whether the expression or any embedded pointers are nil.
6761 Expression* nil_check = NULL;
6762 Expression* expr = this->expr_;
6763 if (this->method_->field_indexes() != NULL)
6765 // Note that we are evaluating this->expr_ twice, but that is OK
6766 // because in the lowering pass we forced it into a temporary
6767 // variable.
6768 Expression* ref = expr;
6769 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6770 expr = ref;
6773 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6775 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6776 Expression::make_nil(loc),
6777 loc);
6778 if (nil_check == NULL)
6779 nil_check = n;
6780 else
6781 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6784 Bexpression* bme = ret->get_backend(context);
6785 if (nil_check != NULL)
6787 Gogo* gogo = context->gogo();
6788 Bexpression* crash =
6789 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6790 loc)->get_backend(context);
6791 Btype* btype = ret->type()->get_backend(gogo);
6792 Bexpression* bcheck = nil_check->get_backend(context);
6793 bme = gogo->backend()->conditional_expression(btype, bcheck, crash,
6794 bme, loc);
6796 return bme;
6799 // Dump ast representation of a bound method expression.
6801 void
6802 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6803 const
6805 if (this->expr_type_ != NULL)
6806 ast_dump_context->ostream() << "(";
6807 ast_dump_context->dump_expression(this->expr_);
6808 if (this->expr_type_ != NULL)
6810 ast_dump_context->ostream() << ":";
6811 ast_dump_context->dump_type(this->expr_type_);
6812 ast_dump_context->ostream() << ")";
6815 ast_dump_context->ostream() << "." << this->function_->name();
6818 // Make a method expression.
6820 Bound_method_expression*
6821 Expression::make_bound_method(Expression* expr, const Method* method,
6822 Named_object* function, Location location)
6824 return new Bound_method_expression(expr, method, function, location);
6827 // Class Builtin_call_expression. This is used for a call to a
6828 // builtin function.
6830 class Builtin_call_expression : public Call_expression
6832 public:
6833 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6834 bool is_varargs, Location location);
6836 protected:
6837 // This overrides Call_expression::do_lower.
6838 Expression*
6839 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6841 Expression*
6842 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6844 bool
6845 do_is_constant() const;
6847 bool
6848 do_numeric_constant_value(Numeric_constant*) const;
6850 bool
6851 do_discarding_value();
6853 Type*
6854 do_type();
6856 void
6857 do_determine_type(const Type_context*);
6859 void
6860 do_check_types(Gogo*);
6862 Expression*
6863 do_copy()
6865 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6866 this->args()->copy(),
6867 this->is_varargs(),
6868 this->location());
6871 Bexpression*
6872 do_get_backend(Translate_context*);
6874 void
6875 do_export(Export*) const;
6877 virtual bool
6878 do_is_recover_call() const;
6880 virtual void
6881 do_set_recover_arg(Expression*);
6883 private:
6884 // The builtin functions.
6885 enum Builtin_function_code
6887 BUILTIN_INVALID,
6889 // Predeclared builtin functions.
6890 BUILTIN_APPEND,
6891 BUILTIN_CAP,
6892 BUILTIN_CLOSE,
6893 BUILTIN_COMPLEX,
6894 BUILTIN_COPY,
6895 BUILTIN_DELETE,
6896 BUILTIN_IMAG,
6897 BUILTIN_LEN,
6898 BUILTIN_MAKE,
6899 BUILTIN_NEW,
6900 BUILTIN_PANIC,
6901 BUILTIN_PRINT,
6902 BUILTIN_PRINTLN,
6903 BUILTIN_REAL,
6904 BUILTIN_RECOVER,
6906 // Builtin functions from the unsafe package.
6907 BUILTIN_ALIGNOF,
6908 BUILTIN_OFFSETOF,
6909 BUILTIN_SIZEOF
6912 Expression*
6913 one_arg() const;
6915 bool
6916 check_one_arg();
6918 static Type*
6919 real_imag_type(Type*);
6921 static Type*
6922 complex_type(Type*);
6924 Expression*
6925 lower_make();
6927 bool
6928 check_int_value(Expression*, bool is_length);
6930 // A pointer back to the general IR structure. This avoids a global
6931 // variable, or passing it around everywhere.
6932 Gogo* gogo_;
6933 // The builtin function being called.
6934 Builtin_function_code code_;
6935 // Used to stop endless loops when the length of an array uses len
6936 // or cap of the array itself.
6937 mutable bool seen_;
6940 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6941 Expression* fn,
6942 Expression_list* args,
6943 bool is_varargs,
6944 Location location)
6945 : Call_expression(fn, args, is_varargs, location),
6946 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6948 Func_expression* fnexp = this->fn()->func_expression();
6949 go_assert(fnexp != NULL);
6950 const std::string& name(fnexp->named_object()->name());
6951 if (name == "append")
6952 this->code_ = BUILTIN_APPEND;
6953 else if (name == "cap")
6954 this->code_ = BUILTIN_CAP;
6955 else if (name == "close")
6956 this->code_ = BUILTIN_CLOSE;
6957 else if (name == "complex")
6958 this->code_ = BUILTIN_COMPLEX;
6959 else if (name == "copy")
6960 this->code_ = BUILTIN_COPY;
6961 else if (name == "delete")
6962 this->code_ = BUILTIN_DELETE;
6963 else if (name == "imag")
6964 this->code_ = BUILTIN_IMAG;
6965 else if (name == "len")
6966 this->code_ = BUILTIN_LEN;
6967 else if (name == "make")
6968 this->code_ = BUILTIN_MAKE;
6969 else if (name == "new")
6970 this->code_ = BUILTIN_NEW;
6971 else if (name == "panic")
6972 this->code_ = BUILTIN_PANIC;
6973 else if (name == "print")
6974 this->code_ = BUILTIN_PRINT;
6975 else if (name == "println")
6976 this->code_ = BUILTIN_PRINTLN;
6977 else if (name == "real")
6978 this->code_ = BUILTIN_REAL;
6979 else if (name == "recover")
6980 this->code_ = BUILTIN_RECOVER;
6981 else if (name == "Alignof")
6982 this->code_ = BUILTIN_ALIGNOF;
6983 else if (name == "Offsetof")
6984 this->code_ = BUILTIN_OFFSETOF;
6985 else if (name == "Sizeof")
6986 this->code_ = BUILTIN_SIZEOF;
6987 else
6988 go_unreachable();
6991 // Return whether this is a call to recover. This is a virtual
6992 // function called from the parent class.
6994 bool
6995 Builtin_call_expression::do_is_recover_call() const
6997 if (this->classification() == EXPRESSION_ERROR)
6998 return false;
6999 return this->code_ == BUILTIN_RECOVER;
7002 // Set the argument for a call to recover.
7004 void
7005 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7007 const Expression_list* args = this->args();
7008 go_assert(args == NULL || args->empty());
7009 Expression_list* new_args = new Expression_list();
7010 new_args->push_back(arg);
7011 this->set_args(new_args);
7014 // Lower a builtin call expression. This turns new and make into
7015 // specific expressions. We also convert to a constant if we can.
7017 Expression*
7018 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
7019 Statement_inserter* inserter, int)
7021 if (this->classification() == EXPRESSION_ERROR)
7022 return this;
7024 Location loc = this->location();
7026 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7028 this->report_error(_("invalid use of %<...%> with builtin function"));
7029 return Expression::make_error(loc);
7032 if (this->code_ == BUILTIN_OFFSETOF)
7034 Expression* arg = this->one_arg();
7036 if (arg->bound_method_expression() != NULL
7037 || arg->interface_field_reference_expression() != NULL)
7039 this->report_error(_("invalid use of method value as argument "
7040 "of Offsetof"));
7041 return this;
7044 Field_reference_expression* farg = arg->field_reference_expression();
7045 while (farg != NULL)
7047 if (!farg->implicit())
7048 break;
7049 // When the selector refers to an embedded field,
7050 // it must not be reached through pointer indirections.
7051 if (farg->expr()->deref() != farg->expr())
7053 this->report_error(_("argument of Offsetof implies "
7054 "indirection of an embedded field"));
7055 return this;
7057 // Go up until we reach the original base.
7058 farg = farg->expr()->field_reference_expression();
7062 if (this->is_constant())
7064 Numeric_constant nc;
7065 if (this->numeric_constant_value(&nc))
7066 return nc.expression(loc);
7069 switch (this->code_)
7071 default:
7072 break;
7074 case BUILTIN_NEW:
7076 const Expression_list* args = this->args();
7077 if (args == NULL || args->size() < 1)
7078 this->report_error(_("not enough arguments"));
7079 else if (args->size() > 1)
7080 this->report_error(_("too many arguments"));
7081 else
7083 Expression* arg = args->front();
7084 if (!arg->is_type_expression())
7086 error_at(arg->location(), "expected type");
7087 this->set_is_error();
7089 else
7090 return Expression::make_allocation(arg->type(), loc);
7093 break;
7095 case BUILTIN_MAKE:
7096 return this->lower_make();
7098 case BUILTIN_RECOVER:
7099 if (function != NULL)
7100 function->func_value()->set_calls_recover();
7101 else
7103 // Calling recover outside of a function always returns the
7104 // nil empty interface.
7105 Type* eface = Type::make_empty_interface_type(loc);
7106 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7108 break;
7110 case BUILTIN_APPEND:
7112 // Lower the varargs.
7113 const Expression_list* args = this->args();
7114 if (args == NULL || args->empty())
7115 return this;
7116 Type* slice_type = args->front()->type();
7117 if (!slice_type->is_slice_type())
7119 if (slice_type->is_nil_type())
7120 error_at(args->front()->location(), "use of untyped nil");
7121 else
7122 error_at(args->front()->location(),
7123 "argument 1 must be a slice");
7124 this->set_is_error();
7125 return this;
7127 Type* element_type = slice_type->array_type()->element_type();
7128 this->lower_varargs(gogo, function, inserter,
7129 Type::make_array_type(element_type, NULL),
7132 break;
7134 case BUILTIN_DELETE:
7136 // Lower to a runtime function call.
7137 const Expression_list* args = this->args();
7138 if (args == NULL || args->size() < 2)
7139 this->report_error(_("not enough arguments"));
7140 else if (args->size() > 2)
7141 this->report_error(_("too many arguments"));
7142 else if (args->front()->type()->map_type() == NULL)
7143 this->report_error(_("argument 1 must be a map"));
7144 else
7146 // Since this function returns no value it must appear in
7147 // a statement by itself, so we don't have to worry about
7148 // order of evaluation of values around it. Evaluate the
7149 // map first to get order of evaluation right.
7150 Map_type* mt = args->front()->type()->map_type();
7151 Temporary_statement* map_temp =
7152 Statement::make_temporary(mt, args->front(), loc);
7153 inserter->insert(map_temp);
7155 Temporary_statement* key_temp =
7156 Statement::make_temporary(mt->key_type(), args->back(), loc);
7157 inserter->insert(key_temp);
7159 Expression* e1 = Expression::make_temporary_reference(map_temp,
7160 loc);
7161 Expression* e2 = Expression::make_temporary_reference(key_temp,
7162 loc);
7163 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7164 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7165 2, e1, e2);
7168 break;
7171 return this;
7174 // Flatten a builtin call expression. This turns the arguments of copy and
7175 // append into temporary expressions.
7177 Expression*
7178 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7179 Statement_inserter* inserter)
7181 if (this->code_ == BUILTIN_APPEND
7182 || this->code_ == BUILTIN_COPY)
7184 Location loc = this->location();
7185 Type* at = this->args()->front()->type();
7186 for (Expression_list::iterator pa = this->args()->begin();
7187 pa != this->args()->end();
7188 ++pa)
7190 if ((*pa)->is_nil_expression())
7191 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7192 if (!(*pa)->is_variable())
7194 Temporary_statement* temp =
7195 Statement::make_temporary(NULL, *pa, loc);
7196 inserter->insert(temp);
7197 *pa = Expression::make_temporary_reference(temp, loc);
7201 return this;
7204 // Lower a make expression.
7206 Expression*
7207 Builtin_call_expression::lower_make()
7209 Location loc = this->location();
7211 const Expression_list* args = this->args();
7212 if (args == NULL || args->size() < 1)
7214 this->report_error(_("not enough arguments"));
7215 return Expression::make_error(this->location());
7218 Expression_list::const_iterator parg = args->begin();
7220 Expression* first_arg = *parg;
7221 if (!first_arg->is_type_expression())
7223 error_at(first_arg->location(), "expected type");
7224 this->set_is_error();
7225 return Expression::make_error(this->location());
7227 Type* type = first_arg->type();
7229 bool is_slice = false;
7230 bool is_map = false;
7231 bool is_chan = false;
7232 if (type->is_slice_type())
7233 is_slice = true;
7234 else if (type->map_type() != NULL)
7235 is_map = true;
7236 else if (type->channel_type() != NULL)
7237 is_chan = true;
7238 else
7240 this->report_error(_("invalid type for make function"));
7241 return Expression::make_error(this->location());
7244 bool have_big_args = false;
7245 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7246 int uintptr_bits = uintptr_type->integer_type()->bits();
7248 Type_context int_context(Type::lookup_integer_type("int"), false);
7250 ++parg;
7251 Expression* len_arg;
7252 if (parg == args->end())
7254 if (is_slice)
7256 this->report_error(_("length required when allocating a slice"));
7257 return Expression::make_error(this->location());
7259 len_arg = Expression::make_integer_ul(0, NULL, loc);
7261 else
7263 len_arg = *parg;
7264 len_arg->determine_type(&int_context);
7265 if (!this->check_int_value(len_arg, true))
7266 return Expression::make_error(this->location());
7267 if (len_arg->type()->integer_type() != NULL
7268 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7269 have_big_args = true;
7270 ++parg;
7273 Expression* cap_arg = NULL;
7274 if (is_slice && parg != args->end())
7276 cap_arg = *parg;
7277 cap_arg->determine_type(&int_context);
7278 if (!this->check_int_value(cap_arg, false))
7279 return Expression::make_error(this->location());
7281 Numeric_constant nclen;
7282 Numeric_constant nccap;
7283 unsigned long vlen;
7284 unsigned long vcap;
7285 if (len_arg->numeric_constant_value(&nclen)
7286 && cap_arg->numeric_constant_value(&nccap)
7287 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7288 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7289 && vlen > vcap)
7291 this->report_error(_("len larger than cap"));
7292 return Expression::make_error(this->location());
7295 if (cap_arg->type()->integer_type() != NULL
7296 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7297 have_big_args = true;
7298 ++parg;
7301 if (parg != args->end())
7303 this->report_error(_("too many arguments to make"));
7304 return Expression::make_error(this->location());
7307 Location type_loc = first_arg->location();
7308 Expression* type_arg;
7309 if (is_slice || is_chan)
7310 type_arg = Expression::make_type_descriptor(type, type_loc);
7311 else if (is_map)
7312 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7313 else
7314 go_unreachable();
7316 Expression* call;
7317 if (is_slice)
7319 if (cap_arg == NULL)
7320 call = Runtime::make_call((have_big_args
7321 ? Runtime::MAKESLICE1BIG
7322 : Runtime::MAKESLICE1),
7323 loc, 2, type_arg, len_arg);
7324 else
7325 call = Runtime::make_call((have_big_args
7326 ? Runtime::MAKESLICE2BIG
7327 : Runtime::MAKESLICE2),
7328 loc, 3, type_arg, len_arg, cap_arg);
7330 else if (is_map)
7331 call = Runtime::make_call((have_big_args
7332 ? Runtime::MAKEMAPBIG
7333 : Runtime::MAKEMAP),
7334 loc, 2, type_arg, len_arg);
7335 else if (is_chan)
7336 call = Runtime::make_call((have_big_args
7337 ? Runtime::MAKECHANBIG
7338 : Runtime::MAKECHAN),
7339 loc, 2, type_arg, len_arg);
7340 else
7341 go_unreachable();
7343 return Expression::make_unsafe_cast(type, call, loc);
7346 // Return whether an expression has an integer value. Report an error
7347 // if not. This is used when handling calls to the predeclared make
7348 // function.
7350 bool
7351 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7353 Numeric_constant nc;
7354 if (e->numeric_constant_value(&nc))
7356 unsigned long v;
7357 switch (nc.to_unsigned_long(&v))
7359 case Numeric_constant::NC_UL_VALID:
7360 break;
7361 case Numeric_constant::NC_UL_NOTINT:
7362 error_at(e->location(), "non-integer %s argument to make",
7363 is_length ? "len" : "cap");
7364 return false;
7365 case Numeric_constant::NC_UL_NEGATIVE:
7366 error_at(e->location(), "negative %s argument to make",
7367 is_length ? "len" : "cap");
7368 return false;
7369 case Numeric_constant::NC_UL_BIG:
7370 // We don't want to give a compile-time error for a 64-bit
7371 // value on a 32-bit target.
7372 break;
7375 mpz_t val;
7376 if (!nc.to_int(&val))
7377 go_unreachable();
7378 int bits = mpz_sizeinbase(val, 2);
7379 mpz_clear(val);
7380 Type* int_type = Type::lookup_integer_type("int");
7381 if (bits >= int_type->integer_type()->bits())
7383 error_at(e->location(), "%s argument too large for make",
7384 is_length ? "len" : "cap");
7385 return false;
7388 return true;
7391 if (e->type()->integer_type() != NULL)
7392 return true;
7394 error_at(e->location(), "non-integer %s argument to make",
7395 is_length ? "len" : "cap");
7396 return false;
7399 // Return the type of the real or imag functions, given the type of
7400 // the argument. We need to map complex to float, complex64 to
7401 // float32, and complex128 to float64, so it has to be done by name.
7402 // This returns NULL if it can't figure out the type.
7404 Type*
7405 Builtin_call_expression::real_imag_type(Type* arg_type)
7407 if (arg_type == NULL || arg_type->is_abstract())
7408 return NULL;
7409 Named_type* nt = arg_type->named_type();
7410 if (nt == NULL)
7411 return NULL;
7412 while (nt->real_type()->named_type() != NULL)
7413 nt = nt->real_type()->named_type();
7414 if (nt->name() == "complex64")
7415 return Type::lookup_float_type("float32");
7416 else if (nt->name() == "complex128")
7417 return Type::lookup_float_type("float64");
7418 else
7419 return NULL;
7422 // Return the type of the complex function, given the type of one of the
7423 // argments. Like real_imag_type, we have to map by name.
7425 Type*
7426 Builtin_call_expression::complex_type(Type* arg_type)
7428 if (arg_type == NULL || arg_type->is_abstract())
7429 return NULL;
7430 Named_type* nt = arg_type->named_type();
7431 if (nt == NULL)
7432 return NULL;
7433 while (nt->real_type()->named_type() != NULL)
7434 nt = nt->real_type()->named_type();
7435 if (nt->name() == "float32")
7436 return Type::lookup_complex_type("complex64");
7437 else if (nt->name() == "float64")
7438 return Type::lookup_complex_type("complex128");
7439 else
7440 return NULL;
7443 // Return a single argument, or NULL if there isn't one.
7445 Expression*
7446 Builtin_call_expression::one_arg() const
7448 const Expression_list* args = this->args();
7449 if (args == NULL || args->size() != 1)
7450 return NULL;
7451 return args->front();
7454 // A traversal class which looks for a call or receive expression.
7456 class Find_call_expression : public Traverse
7458 public:
7459 Find_call_expression()
7460 : Traverse(traverse_expressions),
7461 found_(false)
7465 expression(Expression**);
7467 bool
7468 found()
7469 { return this->found_; }
7471 private:
7472 bool found_;
7476 Find_call_expression::expression(Expression** pexpr)
7478 if ((*pexpr)->call_expression() != NULL
7479 || (*pexpr)->receive_expression() != NULL)
7481 this->found_ = true;
7482 return TRAVERSE_EXIT;
7484 return TRAVERSE_CONTINUE;
7487 // Return whether this is constant: len of a string constant, or len
7488 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7489 // unsafe.Alignof.
7491 bool
7492 Builtin_call_expression::do_is_constant() const
7494 if (this->is_error_expression())
7495 return true;
7496 switch (this->code_)
7498 case BUILTIN_LEN:
7499 case BUILTIN_CAP:
7501 if (this->seen_)
7502 return false;
7504 Expression* arg = this->one_arg();
7505 if (arg == NULL)
7506 return false;
7507 Type* arg_type = arg->type();
7509 if (arg_type->points_to() != NULL
7510 && arg_type->points_to()->array_type() != NULL
7511 && !arg_type->points_to()->is_slice_type())
7512 arg_type = arg_type->points_to();
7514 // The len and cap functions are only constant if there are no
7515 // function calls or channel operations in the arguments.
7516 // Otherwise we have to make the call.
7517 if (!arg->is_constant())
7519 Find_call_expression find_call;
7520 Expression::traverse(&arg, &find_call);
7521 if (find_call.found())
7522 return false;
7525 if (arg_type->array_type() != NULL
7526 && arg_type->array_type()->length() != NULL)
7527 return true;
7529 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7531 this->seen_ = true;
7532 bool ret = arg->is_constant();
7533 this->seen_ = false;
7534 return ret;
7537 break;
7539 case BUILTIN_SIZEOF:
7540 case BUILTIN_ALIGNOF:
7541 return this->one_arg() != NULL;
7543 case BUILTIN_OFFSETOF:
7545 Expression* arg = this->one_arg();
7546 if (arg == NULL)
7547 return false;
7548 return arg->field_reference_expression() != NULL;
7551 case BUILTIN_COMPLEX:
7553 const Expression_list* args = this->args();
7554 if (args != NULL && args->size() == 2)
7555 return args->front()->is_constant() && args->back()->is_constant();
7557 break;
7559 case BUILTIN_REAL:
7560 case BUILTIN_IMAG:
7562 Expression* arg = this->one_arg();
7563 return arg != NULL && arg->is_constant();
7566 default:
7567 break;
7570 return false;
7573 // Return a numeric constant if possible.
7575 bool
7576 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7578 if (this->code_ == BUILTIN_LEN
7579 || this->code_ == BUILTIN_CAP)
7581 Expression* arg = this->one_arg();
7582 if (arg == NULL)
7583 return false;
7584 Type* arg_type = arg->type();
7586 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7588 std::string sval;
7589 if (arg->string_constant_value(&sval))
7591 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7592 sval.length());
7593 return true;
7597 if (arg_type->points_to() != NULL
7598 && arg_type->points_to()->array_type() != NULL
7599 && !arg_type->points_to()->is_slice_type())
7600 arg_type = arg_type->points_to();
7602 if (arg_type->array_type() != NULL
7603 && arg_type->array_type()->length() != NULL)
7605 if (this->seen_)
7606 return false;
7607 Expression* e = arg_type->array_type()->length();
7608 this->seen_ = true;
7609 bool r = e->numeric_constant_value(nc);
7610 this->seen_ = false;
7611 if (r)
7613 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7614 this->location()))
7615 r = false;
7617 return r;
7620 else if (this->code_ == BUILTIN_SIZEOF
7621 || this->code_ == BUILTIN_ALIGNOF)
7623 Expression* arg = this->one_arg();
7624 if (arg == NULL)
7625 return false;
7626 Type* arg_type = arg->type();
7627 if (arg_type->is_error())
7628 return false;
7629 if (arg_type->is_abstract())
7630 return false;
7631 if (this->seen_)
7632 return false;
7634 unsigned long ret;
7635 if (this->code_ == BUILTIN_SIZEOF)
7637 this->seen_ = true;
7638 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7639 this->seen_ = false;
7640 if (!ok)
7641 return false;
7643 else if (this->code_ == BUILTIN_ALIGNOF)
7645 bool ok;
7646 this->seen_ = true;
7647 if (arg->field_reference_expression() == NULL)
7648 ok = arg_type->backend_type_align(this->gogo_, &ret);
7649 else
7651 // Calling unsafe.Alignof(s.f) returns the alignment of
7652 // the type of f when it is used as a field in a struct.
7653 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7655 this->seen_ = false;
7656 if (!ok)
7657 return false;
7659 else
7660 go_unreachable();
7662 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"), ret);
7663 return true;
7665 else if (this->code_ == BUILTIN_OFFSETOF)
7667 Expression* arg = this->one_arg();
7668 if (arg == NULL)
7669 return false;
7670 Field_reference_expression* farg = arg->field_reference_expression();
7671 if (farg == NULL)
7672 return false;
7673 if (this->seen_)
7674 return false;
7676 unsigned int total_offset = 0;
7677 while (true)
7679 Expression* struct_expr = farg->expr();
7680 Type* st = struct_expr->type();
7681 if (st->struct_type() == NULL)
7682 return false;
7683 if (st->named_type() != NULL)
7684 st->named_type()->convert(this->gogo_);
7685 unsigned int offset;
7686 this->seen_ = true;
7687 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7688 farg->field_index(),
7689 &offset);
7690 this->seen_ = false;
7691 if (!ok)
7692 return false;
7693 total_offset += offset;
7694 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7696 // Go up until we reach the original base.
7697 farg = struct_expr->field_reference_expression();
7698 continue;
7700 break;
7702 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7703 static_cast<unsigned long>(total_offset));
7704 return true;
7706 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7708 Expression* arg = this->one_arg();
7709 if (arg == NULL)
7710 return false;
7712 Numeric_constant argnc;
7713 if (!arg->numeric_constant_value(&argnc))
7714 return false;
7716 mpfr_t real;
7717 mpfr_t imag;
7718 if (!argnc.to_complex(&real, &imag))
7719 return false;
7721 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7722 if (this->code_ == BUILTIN_REAL)
7723 nc->set_float(type, real);
7724 else
7725 nc->set_float(type, imag);
7726 return true;
7728 else if (this->code_ == BUILTIN_COMPLEX)
7730 const Expression_list* args = this->args();
7731 if (args == NULL || args->size() != 2)
7732 return false;
7734 Numeric_constant rnc;
7735 if (!args->front()->numeric_constant_value(&rnc))
7736 return false;
7737 Numeric_constant inc;
7738 if (!args->back()->numeric_constant_value(&inc))
7739 return false;
7741 if (rnc.type() != NULL
7742 && !rnc.type()->is_abstract()
7743 && inc.type() != NULL
7744 && !inc.type()->is_abstract()
7745 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7746 return false;
7748 mpfr_t r;
7749 if (!rnc.to_float(&r))
7750 return false;
7751 mpfr_t i;
7752 if (!inc.to_float(&i))
7754 mpfr_clear(r);
7755 return false;
7758 Type* arg_type = rnc.type();
7759 if (arg_type == NULL || arg_type->is_abstract())
7760 arg_type = inc.type();
7762 Type* type = Builtin_call_expression::complex_type(arg_type);
7763 nc->set_complex(type, r, i);
7765 mpfr_clear(r);
7766 mpfr_clear(i);
7768 return true;
7771 return false;
7774 // Give an error if we are discarding the value of an expression which
7775 // should not normally be discarded. We don't give an error for
7776 // discarding the value of an ordinary function call, but we do for
7777 // builtin functions, purely for consistency with the gc compiler.
7779 bool
7780 Builtin_call_expression::do_discarding_value()
7782 switch (this->code_)
7784 case BUILTIN_INVALID:
7785 default:
7786 go_unreachable();
7788 case BUILTIN_APPEND:
7789 case BUILTIN_CAP:
7790 case BUILTIN_COMPLEX:
7791 case BUILTIN_IMAG:
7792 case BUILTIN_LEN:
7793 case BUILTIN_MAKE:
7794 case BUILTIN_NEW:
7795 case BUILTIN_REAL:
7796 case BUILTIN_ALIGNOF:
7797 case BUILTIN_OFFSETOF:
7798 case BUILTIN_SIZEOF:
7799 this->unused_value_error();
7800 return false;
7802 case BUILTIN_CLOSE:
7803 case BUILTIN_COPY:
7804 case BUILTIN_DELETE:
7805 case BUILTIN_PANIC:
7806 case BUILTIN_PRINT:
7807 case BUILTIN_PRINTLN:
7808 case BUILTIN_RECOVER:
7809 return true;
7813 // Return the type.
7815 Type*
7816 Builtin_call_expression::do_type()
7818 switch (this->code_)
7820 case BUILTIN_INVALID:
7821 default:
7822 go_unreachable();
7824 case BUILTIN_NEW:
7825 case BUILTIN_MAKE:
7827 const Expression_list* args = this->args();
7828 if (args == NULL || args->empty())
7829 return Type::make_error_type();
7830 return Type::make_pointer_type(args->front()->type());
7833 case BUILTIN_CAP:
7834 case BUILTIN_COPY:
7835 case BUILTIN_LEN:
7836 return Type::lookup_integer_type("int");
7838 case BUILTIN_ALIGNOF:
7839 case BUILTIN_OFFSETOF:
7840 case BUILTIN_SIZEOF:
7841 return Type::lookup_integer_type("uintptr");
7843 case BUILTIN_CLOSE:
7844 case BUILTIN_DELETE:
7845 case BUILTIN_PANIC:
7846 case BUILTIN_PRINT:
7847 case BUILTIN_PRINTLN:
7848 return Type::make_void_type();
7850 case BUILTIN_RECOVER:
7851 return Type::make_empty_interface_type(Linemap::predeclared_location());
7853 case BUILTIN_APPEND:
7855 const Expression_list* args = this->args();
7856 if (args == NULL || args->empty())
7857 return Type::make_error_type();
7858 Type *ret = args->front()->type();
7859 if (!ret->is_slice_type())
7860 return Type::make_error_type();
7861 return ret;
7864 case BUILTIN_REAL:
7865 case BUILTIN_IMAG:
7867 Expression* arg = this->one_arg();
7868 if (arg == NULL)
7869 return Type::make_error_type();
7870 Type* t = arg->type();
7871 if (t->is_abstract())
7872 t = t->make_non_abstract_type();
7873 t = Builtin_call_expression::real_imag_type(t);
7874 if (t == NULL)
7875 t = Type::make_error_type();
7876 return t;
7879 case BUILTIN_COMPLEX:
7881 const Expression_list* args = this->args();
7882 if (args == NULL || args->size() != 2)
7883 return Type::make_error_type();
7884 Type* t = args->front()->type();
7885 if (t->is_abstract())
7887 t = args->back()->type();
7888 if (t->is_abstract())
7889 t = t->make_non_abstract_type();
7891 t = Builtin_call_expression::complex_type(t);
7892 if (t == NULL)
7893 t = Type::make_error_type();
7894 return t;
7899 // Determine the type.
7901 void
7902 Builtin_call_expression::do_determine_type(const Type_context* context)
7904 if (!this->determining_types())
7905 return;
7907 this->fn()->determine_type_no_context();
7909 const Expression_list* args = this->args();
7911 bool is_print;
7912 Type* arg_type = NULL;
7913 switch (this->code_)
7915 case BUILTIN_PRINT:
7916 case BUILTIN_PRINTLN:
7917 // Do not force a large integer constant to "int".
7918 is_print = true;
7919 break;
7921 case BUILTIN_REAL:
7922 case BUILTIN_IMAG:
7923 arg_type = Builtin_call_expression::complex_type(context->type);
7924 if (arg_type == NULL)
7925 arg_type = Type::lookup_complex_type("complex128");
7926 is_print = false;
7927 break;
7929 case BUILTIN_COMPLEX:
7931 // For the complex function the type of one operand can
7932 // determine the type of the other, as in a binary expression.
7933 arg_type = Builtin_call_expression::real_imag_type(context->type);
7934 if (arg_type == NULL)
7935 arg_type = Type::lookup_float_type("float64");
7936 if (args != NULL && args->size() == 2)
7938 Type* t1 = args->front()->type();
7939 Type* t2 = args->back()->type();
7940 if (!t1->is_abstract())
7941 arg_type = t1;
7942 else if (!t2->is_abstract())
7943 arg_type = t2;
7945 is_print = false;
7947 break;
7949 default:
7950 is_print = false;
7951 break;
7954 if (args != NULL)
7956 for (Expression_list::const_iterator pa = args->begin();
7957 pa != args->end();
7958 ++pa)
7960 Type_context subcontext;
7961 subcontext.type = arg_type;
7963 if (is_print)
7965 // We want to print large constants, we so can't just
7966 // use the appropriate nonabstract type. Use uint64 for
7967 // an integer if we know it is nonnegative, otherwise
7968 // use int64 for a integer, otherwise use float64 for a
7969 // float or complex128 for a complex.
7970 Type* want_type = NULL;
7971 Type* atype = (*pa)->type();
7972 if (atype->is_abstract())
7974 if (atype->integer_type() != NULL)
7976 Numeric_constant nc;
7977 if (this->numeric_constant_value(&nc))
7979 mpz_t val;
7980 if (nc.to_int(&val))
7982 if (mpz_sgn(val) >= 0)
7983 want_type = Type::lookup_integer_type("uint64");
7984 mpz_clear(val);
7987 if (want_type == NULL)
7988 want_type = Type::lookup_integer_type("int64");
7990 else if (atype->float_type() != NULL)
7991 want_type = Type::lookup_float_type("float64");
7992 else if (atype->complex_type() != NULL)
7993 want_type = Type::lookup_complex_type("complex128");
7994 else if (atype->is_abstract_string_type())
7995 want_type = Type::lookup_string_type();
7996 else if (atype->is_abstract_boolean_type())
7997 want_type = Type::lookup_bool_type();
7998 else
7999 go_unreachable();
8000 subcontext.type = want_type;
8004 (*pa)->determine_type(&subcontext);
8009 // If there is exactly one argument, return true. Otherwise give an
8010 // error message and return false.
8012 bool
8013 Builtin_call_expression::check_one_arg()
8015 const Expression_list* args = this->args();
8016 if (args == NULL || args->size() < 1)
8018 this->report_error(_("not enough arguments"));
8019 return false;
8021 else if (args->size() > 1)
8023 this->report_error(_("too many arguments"));
8024 return false;
8026 if (args->front()->is_error_expression()
8027 || args->front()->type()->is_error())
8029 this->set_is_error();
8030 return false;
8032 return true;
8035 // Check argument types for a builtin function.
8037 void
8038 Builtin_call_expression::do_check_types(Gogo*)
8040 if (this->is_error_expression())
8041 return;
8042 switch (this->code_)
8044 case BUILTIN_INVALID:
8045 case BUILTIN_NEW:
8046 case BUILTIN_MAKE:
8047 case BUILTIN_DELETE:
8048 return;
8050 case BUILTIN_LEN:
8051 case BUILTIN_CAP:
8053 // The single argument may be either a string or an array or a
8054 // map or a channel, or a pointer to a closed array.
8055 if (this->check_one_arg())
8057 Type* arg_type = this->one_arg()->type();
8058 if (arg_type->points_to() != NULL
8059 && arg_type->points_to()->array_type() != NULL
8060 && !arg_type->points_to()->is_slice_type())
8061 arg_type = arg_type->points_to();
8062 if (this->code_ == BUILTIN_CAP)
8064 if (!arg_type->is_error()
8065 && arg_type->array_type() == NULL
8066 && arg_type->channel_type() == NULL)
8067 this->report_error(_("argument must be array or slice "
8068 "or channel"));
8070 else
8072 if (!arg_type->is_error()
8073 && !arg_type->is_string_type()
8074 && arg_type->array_type() == NULL
8075 && arg_type->map_type() == NULL
8076 && arg_type->channel_type() == NULL)
8077 this->report_error(_("argument must be string or "
8078 "array or slice or map or channel"));
8082 break;
8084 case BUILTIN_PRINT:
8085 case BUILTIN_PRINTLN:
8087 const Expression_list* args = this->args();
8088 if (args == NULL)
8090 if (this->code_ == BUILTIN_PRINT)
8091 warning_at(this->location(), 0,
8092 "no arguments for builtin function %<%s%>",
8093 (this->code_ == BUILTIN_PRINT
8094 ? "print"
8095 : "println"));
8097 else
8099 for (Expression_list::const_iterator p = args->begin();
8100 p != args->end();
8101 ++p)
8103 Type* type = (*p)->type();
8104 if (type->is_error()
8105 || type->is_string_type()
8106 || type->integer_type() != NULL
8107 || type->float_type() != NULL
8108 || type->complex_type() != NULL
8109 || type->is_boolean_type()
8110 || type->points_to() != NULL
8111 || type->interface_type() != NULL
8112 || type->channel_type() != NULL
8113 || type->map_type() != NULL
8114 || type->function_type() != NULL
8115 || type->is_slice_type())
8117 else if ((*p)->is_type_expression())
8119 // If this is a type expression it's going to give
8120 // an error anyhow, so we don't need one here.
8122 else
8123 this->report_error(_("unsupported argument type to "
8124 "builtin function"));
8128 break;
8130 case BUILTIN_CLOSE:
8131 if (this->check_one_arg())
8133 if (this->one_arg()->type()->channel_type() == NULL)
8134 this->report_error(_("argument must be channel"));
8135 else if (!this->one_arg()->type()->channel_type()->may_send())
8136 this->report_error(_("cannot close receive-only channel"));
8138 break;
8140 case BUILTIN_PANIC:
8141 case BUILTIN_SIZEOF:
8142 case BUILTIN_ALIGNOF:
8143 this->check_one_arg();
8144 break;
8146 case BUILTIN_RECOVER:
8147 if (this->args() != NULL && !this->args()->empty())
8148 this->report_error(_("too many arguments"));
8149 break;
8151 case BUILTIN_OFFSETOF:
8152 if (this->check_one_arg())
8154 Expression* arg = this->one_arg();
8155 if (arg->field_reference_expression() == NULL)
8156 this->report_error(_("argument must be a field reference"));
8158 break;
8160 case BUILTIN_COPY:
8162 const Expression_list* args = this->args();
8163 if (args == NULL || args->size() < 2)
8165 this->report_error(_("not enough arguments"));
8166 break;
8168 else if (args->size() > 2)
8170 this->report_error(_("too many arguments"));
8171 break;
8173 Type* arg1_type = args->front()->type();
8174 Type* arg2_type = args->back()->type();
8175 if (arg1_type->is_error() || arg2_type->is_error())
8176 break;
8178 Type* e1;
8179 if (arg1_type->is_slice_type())
8180 e1 = arg1_type->array_type()->element_type();
8181 else
8183 this->report_error(_("left argument must be a slice"));
8184 break;
8187 if (arg2_type->is_slice_type())
8189 Type* e2 = arg2_type->array_type()->element_type();
8190 if (!Type::are_identical(e1, e2, true, NULL))
8191 this->report_error(_("element types must be the same"));
8193 else if (arg2_type->is_string_type())
8195 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8196 this->report_error(_("first argument must be []byte"));
8198 else
8199 this->report_error(_("second argument must be slice or string"));
8201 break;
8203 case BUILTIN_APPEND:
8205 const Expression_list* args = this->args();
8206 if (args == NULL || args->size() < 2)
8208 this->report_error(_("not enough arguments"));
8209 break;
8211 if (args->size() > 2)
8213 this->report_error(_("too many arguments"));
8214 break;
8216 if (args->front()->type()->is_error()
8217 || args->back()->type()->is_error())
8218 break;
8220 Array_type* at = args->front()->type()->array_type();
8221 Type* e = at->element_type();
8223 // The language permits appending a string to a []byte, as a
8224 // special case.
8225 if (args->back()->type()->is_string_type())
8227 if (e->integer_type() != NULL && e->integer_type()->is_byte())
8228 break;
8231 // The language says that the second argument must be
8232 // assignable to a slice of the element type of the first
8233 // argument. We already know the first argument is a slice
8234 // type.
8235 Type* arg2_type = Type::make_array_type(e, NULL);
8236 std::string reason;
8237 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8239 if (reason.empty())
8240 this->report_error(_("argument 2 has invalid type"));
8241 else
8243 error_at(this->location(), "argument 2 has invalid type (%s)",
8244 reason.c_str());
8245 this->set_is_error();
8248 break;
8251 case BUILTIN_REAL:
8252 case BUILTIN_IMAG:
8253 if (this->check_one_arg())
8255 if (this->one_arg()->type()->complex_type() == NULL)
8256 this->report_error(_("argument must have complex type"));
8258 break;
8260 case BUILTIN_COMPLEX:
8262 const Expression_list* args = this->args();
8263 if (args == NULL || args->size() < 2)
8264 this->report_error(_("not enough arguments"));
8265 else if (args->size() > 2)
8266 this->report_error(_("too many arguments"));
8267 else if (args->front()->is_error_expression()
8268 || args->front()->type()->is_error()
8269 || args->back()->is_error_expression()
8270 || args->back()->type()->is_error())
8271 this->set_is_error();
8272 else if (!Type::are_identical(args->front()->type(),
8273 args->back()->type(), true, NULL))
8274 this->report_error(_("complex arguments must have identical types"));
8275 else if (args->front()->type()->float_type() == NULL)
8276 this->report_error(_("complex arguments must have "
8277 "floating-point type"));
8279 break;
8281 default:
8282 go_unreachable();
8286 // Return the backend representation for a builtin function.
8288 Bexpression*
8289 Builtin_call_expression::do_get_backend(Translate_context* context)
8291 Gogo* gogo = context->gogo();
8292 Location location = this->location();
8293 switch (this->code_)
8295 case BUILTIN_INVALID:
8296 case BUILTIN_NEW:
8297 case BUILTIN_MAKE:
8298 go_unreachable();
8300 case BUILTIN_LEN:
8301 case BUILTIN_CAP:
8303 const Expression_list* args = this->args();
8304 go_assert(args != NULL && args->size() == 1);
8305 Expression* arg = args->front();
8306 Type* arg_type = arg->type();
8308 if (this->seen_)
8310 go_assert(saw_errors());
8311 return context->backend()->error_expression();
8313 this->seen_ = true;
8314 this->seen_ = false;
8315 if (arg_type->points_to() != NULL)
8317 arg_type = arg_type->points_to();
8318 go_assert(arg_type->array_type() != NULL
8319 && !arg_type->is_slice_type());
8320 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8323 Type* int_type = Type::lookup_integer_type("int");
8324 Expression* val;
8325 if (this->code_ == BUILTIN_LEN)
8327 if (arg_type->is_string_type())
8328 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8329 location);
8330 else if (arg_type->array_type() != NULL)
8332 if (this->seen_)
8334 go_assert(saw_errors());
8335 return context->backend()->error_expression();
8337 this->seen_ = true;
8338 val = arg_type->array_type()->get_length(gogo, arg);
8339 this->seen_ = false;
8341 else if (arg_type->map_type() != NULL)
8342 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8343 else if (arg_type->channel_type() != NULL)
8344 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8345 else
8346 go_unreachable();
8348 else
8350 if (arg_type->array_type() != NULL)
8352 if (this->seen_)
8354 go_assert(saw_errors());
8355 return context->backend()->error_expression();
8357 this->seen_ = true;
8358 val = arg_type->array_type()->get_capacity(gogo, arg);
8359 this->seen_ = false;
8361 else if (arg_type->channel_type() != NULL)
8362 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8363 else
8364 go_unreachable();
8367 return Expression::make_cast(int_type, val,
8368 location)->get_backend(context);
8371 case BUILTIN_PRINT:
8372 case BUILTIN_PRINTLN:
8374 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8375 Expression* print_stmts = NULL;
8377 const Expression_list* call_args = this->args();
8378 if (call_args != NULL)
8380 for (Expression_list::const_iterator p = call_args->begin();
8381 p != call_args->end();
8382 ++p)
8384 if (is_ln && p != call_args->begin())
8386 Expression* print_space =
8387 Runtime::make_call(Runtime::PRINT_SPACE,
8388 this->location(), 0);
8390 print_stmts =
8391 Expression::make_compound(print_stmts, print_space,
8392 location);
8395 Expression* arg = *p;
8396 Type* type = arg->type();
8397 Runtime::Function code;
8398 if (type->is_string_type())
8399 code = Runtime::PRINT_STRING;
8400 else if (type->integer_type() != NULL
8401 && type->integer_type()->is_unsigned())
8403 Type* itype = Type::lookup_integer_type("uint64");
8404 arg = Expression::make_cast(itype, arg, location);
8405 code = Runtime::PRINT_UINT64;
8407 else if (type->integer_type() != NULL)
8409 Type* itype = Type::lookup_integer_type("int64");
8410 arg = Expression::make_cast(itype, arg, location);
8411 code = Runtime::PRINT_INT64;
8413 else if (type->float_type() != NULL)
8415 Type* dtype = Type::lookup_float_type("float64");
8416 arg = Expression::make_cast(dtype, arg, location);
8417 code = Runtime::PRINT_DOUBLE;
8419 else if (type->complex_type() != NULL)
8421 Type* ctype = Type::lookup_complex_type("complex128");
8422 arg = Expression::make_cast(ctype, arg, location);
8423 code = Runtime::PRINT_COMPLEX;
8425 else if (type->is_boolean_type())
8426 code = Runtime::PRINT_BOOL;
8427 else if (type->points_to() != NULL
8428 || type->channel_type() != NULL
8429 || type->map_type() != NULL
8430 || type->function_type() != NULL)
8432 arg = Expression::make_cast(type, arg, location);
8433 code = Runtime::PRINT_POINTER;
8435 else if (type->interface_type() != NULL)
8437 if (type->interface_type()->is_empty())
8438 code = Runtime::PRINT_EMPTY_INTERFACE;
8439 else
8440 code = Runtime::PRINT_INTERFACE;
8442 else if (type->is_slice_type())
8443 code = Runtime::PRINT_SLICE;
8444 else
8446 go_assert(saw_errors());
8447 return context->backend()->error_expression();
8450 Expression* call = Runtime::make_call(code, location, 1, arg);
8451 if (print_stmts == NULL)
8452 print_stmts = call;
8453 else
8454 print_stmts = Expression::make_compound(print_stmts, call,
8455 location);
8459 if (is_ln)
8461 Expression* print_nl =
8462 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8463 if (print_stmts == NULL)
8464 print_stmts = print_nl;
8465 else
8466 print_stmts = Expression::make_compound(print_stmts, print_nl,
8467 location);
8470 return print_stmts->get_backend(context);
8473 case BUILTIN_PANIC:
8475 const Expression_list* args = this->args();
8476 go_assert(args != NULL && args->size() == 1);
8477 Expression* arg = args->front();
8478 Type *empty =
8479 Type::make_empty_interface_type(Linemap::predeclared_location());
8480 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8482 Expression* panic =
8483 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8484 return panic->get_backend(context);
8487 case BUILTIN_RECOVER:
8489 // The argument is set when building recover thunks. It's a
8490 // boolean value which is true if we can recover a value now.
8491 const Expression_list* args = this->args();
8492 go_assert(args != NULL && args->size() == 1);
8493 Expression* arg = args->front();
8494 Type *empty =
8495 Type::make_empty_interface_type(Linemap::predeclared_location());
8497 Expression* nil = Expression::make_nil(location);
8498 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8500 // We need to handle a deferred call to recover specially,
8501 // because it changes whether it can recover a panic or not.
8502 // See test7 in test/recover1.go.
8503 Expression* recover = Runtime::make_call((this->is_deferred()
8504 ? Runtime::DEFERRED_RECOVER
8505 : Runtime::RECOVER),
8506 location, 0);
8507 Expression* cond =
8508 Expression::make_conditional(arg, recover, nil, location);
8509 return cond->get_backend(context);
8512 case BUILTIN_CLOSE:
8514 const Expression_list* args = this->args();
8515 go_assert(args != NULL && args->size() == 1);
8516 Expression* arg = args->front();
8517 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8518 1, arg);
8519 return close->get_backend(context);
8522 case BUILTIN_SIZEOF:
8523 case BUILTIN_OFFSETOF:
8524 case BUILTIN_ALIGNOF:
8526 Numeric_constant nc;
8527 unsigned long val;
8528 if (!this->numeric_constant_value(&nc)
8529 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8531 go_assert(saw_errors());
8532 return context->backend()->error_expression();
8534 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8535 mpz_t ival;
8536 nc.get_int(&ival);
8537 Expression* int_cst =
8538 Expression::make_integer_z(&ival, uintptr_type, location);
8539 mpz_clear(ival);
8540 return int_cst->get_backend(context);
8543 case BUILTIN_COPY:
8545 const Expression_list* args = this->args();
8546 go_assert(args != NULL && args->size() == 2);
8547 Expression* arg1 = args->front();
8548 Expression* arg2 = args->back();
8550 Type* arg1_type = arg1->type();
8551 Array_type* at = arg1_type->array_type();
8552 go_assert(arg1->is_variable());
8553 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8554 Expression* arg1_len = at->get_length(gogo, arg1);
8556 Type* arg2_type = arg2->type();
8557 go_assert(arg2->is_variable());
8558 Expression* arg2_val;
8559 Expression* arg2_len;
8560 if (arg2_type->is_slice_type())
8562 at = arg2_type->array_type();
8563 arg2_val = at->get_value_pointer(gogo, arg2);
8564 arg2_len = at->get_length(gogo, arg2);
8566 else
8568 go_assert(arg2->is_variable());
8569 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8570 location);
8571 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8572 location);
8574 Expression* cond =
8575 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8576 Expression* length =
8577 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8579 Type* element_type = at->element_type();
8580 Btype* element_btype = element_type->get_backend(gogo);
8581 size_t element_size = gogo->backend()->type_size(element_btype);
8582 Expression* size_expr = Expression::make_integer_ul(element_size,
8583 length->type(),
8584 location);
8585 Expression* bytecount =
8586 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8587 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8588 arg1_val, arg2_val, bytecount);
8590 Expression* compound = Expression::make_compound(copy, length, location);
8591 return compound->get_backend(context);
8594 case BUILTIN_APPEND:
8596 const Expression_list* args = this->args();
8597 go_assert(args != NULL && args->size() == 2);
8598 Expression* arg1 = args->front();
8599 Expression* arg2 = args->back();
8601 Array_type* at = arg1->type()->array_type();
8602 Type* element_type = at->element_type()->forwarded();
8604 go_assert(arg2->is_variable());
8605 Expression* arg2_val;
8606 Expression* arg2_len;
8607 unsigned long size;
8608 if (arg2->type()->is_string_type()
8609 && element_type->integer_type() != NULL
8610 && element_type->integer_type()->is_byte())
8612 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8613 location);
8614 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8615 location);
8616 size = 1;
8618 else
8620 arg2_val = at->get_value_pointer(gogo, arg2);
8621 arg2_len = at->get_length(gogo, arg2);
8622 Btype* element_btype = element_type->get_backend(gogo);
8623 size = gogo->backend()->type_size(element_btype);
8625 Expression* element_size =
8626 Expression::make_integer_ul(size, NULL, location);
8628 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8629 arg1, arg2_val, arg2_len,
8630 element_size);
8631 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8632 return append->get_backend(context);
8635 case BUILTIN_REAL:
8636 case BUILTIN_IMAG:
8638 const Expression_list* args = this->args();
8639 go_assert(args != NULL && args->size() == 1);
8641 Bexpression* ret;
8642 Bexpression* bcomplex = args->front()->get_backend(context);
8643 if (this->code_ == BUILTIN_REAL)
8644 ret = gogo->backend()->real_part_expression(bcomplex, location);
8645 else
8646 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8647 return ret;
8650 case BUILTIN_COMPLEX:
8652 const Expression_list* args = this->args();
8653 go_assert(args != NULL && args->size() == 2);
8654 Bexpression* breal = args->front()->get_backend(context);
8655 Bexpression* bimag = args->back()->get_backend(context);
8656 return gogo->backend()->complex_expression(breal, bimag, location);
8659 default:
8660 go_unreachable();
8664 // We have to support exporting a builtin call expression, because
8665 // code can set a constant to the result of a builtin expression.
8667 void
8668 Builtin_call_expression::do_export(Export* exp) const
8670 Numeric_constant nc;
8671 if (!this->numeric_constant_value(&nc))
8673 error_at(this->location(), "value is not constant");
8674 return;
8677 if (nc.is_int())
8679 mpz_t val;
8680 nc.get_int(&val);
8681 Integer_expression::export_integer(exp, val);
8682 mpz_clear(val);
8684 else if (nc.is_float())
8686 mpfr_t fval;
8687 nc.get_float(&fval);
8688 Float_expression::export_float(exp, fval);
8689 mpfr_clear(fval);
8691 else if (nc.is_complex())
8693 mpfr_t real;
8694 mpfr_t imag;
8695 Complex_expression::export_complex(exp, real, imag);
8696 mpfr_clear(real);
8697 mpfr_clear(imag);
8699 else
8700 go_unreachable();
8702 // A trailing space lets us reliably identify the end of the number.
8703 exp->write_c_string(" ");
8706 // Class Call_expression.
8708 // A Go function can be viewed in a couple of different ways. The
8709 // code of a Go function becomes a backend function with parameters
8710 // whose types are simply the backend representation of the Go types.
8711 // If there are multiple results, they are returned as a backend
8712 // struct.
8714 // However, when Go code refers to a function other than simply
8715 // calling it, the backend type of that function is actually a struct.
8716 // The first field of the struct points to the Go function code
8717 // (sometimes a wrapper as described below). The remaining fields
8718 // hold addresses of closed-over variables. This struct is called a
8719 // closure.
8721 // There are a few cases to consider.
8723 // A direct function call of a known function in package scope. In
8724 // this case there are no closed-over variables, and we know the name
8725 // of the function code. We can simply produce a backend call to the
8726 // function directly, and not worry about the closure.
8728 // A direct function call of a known function literal. In this case
8729 // we know the function code and we know the closure. We generate the
8730 // function code such that it expects an additional final argument of
8731 // the closure type. We pass the closure as the last argument, after
8732 // the other arguments.
8734 // An indirect function call. In this case we have a closure. We
8735 // load the pointer to the function code from the first field of the
8736 // closure. We pass the address of the closure as the last argument.
8738 // A call to a method of an interface. Type methods are always at
8739 // package scope, so we call the function directly, and don't worry
8740 // about the closure.
8742 // This means that for a function at package scope we have two cases.
8743 // One is the direct call, which has no closure. The other is the
8744 // indirect call, which does have a closure. We can't simply ignore
8745 // the closure, even though it is the last argument, because that will
8746 // fail on targets where the function pops its arguments. So when
8747 // generating a closure for a package-scope function we set the
8748 // function code pointer in the closure to point to a wrapper
8749 // function. This wrapper function accepts a final argument that
8750 // points to the closure, ignores it, and calls the real function as a
8751 // direct function call. This wrapper will normally be efficient, and
8752 // can often simply be a tail call to the real function.
8754 // We don't use GCC's static chain pointer because 1) we don't need
8755 // it; 2) GCC only permits using a static chain to call a known
8756 // function, so we can't use it for an indirect call anyhow. Since we
8757 // can't use it for an indirect call, we may as well not worry about
8758 // using it for a direct call either.
8760 // We pass the closure last rather than first because it means that
8761 // the function wrapper we put into a closure for a package-scope
8762 // function can normally just be a tail call to the real function.
8764 // For method expressions we generate a wrapper that loads the
8765 // receiver from the closure and then calls the method. This
8766 // unfortunately forces reshuffling the arguments, since there is a
8767 // new first argument, but we can't avoid reshuffling either for
8768 // method expressions or for indirect calls of package-scope
8769 // functions, and since the latter are more common we reshuffle for
8770 // method expressions.
8772 // Note that the Go code retains the Go types. The extra final
8773 // argument only appears when we convert to the backend
8774 // representation.
8776 // Traversal.
8779 Call_expression::do_traverse(Traverse* traverse)
8781 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8782 return TRAVERSE_EXIT;
8783 if (this->args_ != NULL)
8785 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8786 return TRAVERSE_EXIT;
8788 return TRAVERSE_CONTINUE;
8791 // Lower a call statement.
8793 Expression*
8794 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8795 Statement_inserter* inserter, int)
8797 Location loc = this->location();
8799 // A type cast can look like a function call.
8800 if (this->fn_->is_type_expression()
8801 && this->args_ != NULL
8802 && this->args_->size() == 1)
8803 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8804 loc);
8806 // Because do_type will return an error type and thus prevent future
8807 // errors, check for that case now to ensure that the error gets
8808 // reported.
8809 Function_type* fntype = this->get_function_type();
8810 if (fntype == NULL)
8812 if (!this->fn_->type()->is_error())
8813 this->report_error(_("expected function"));
8814 return Expression::make_error(loc);
8817 // Handle an argument which is a call to a function which returns
8818 // multiple results.
8819 if (this->args_ != NULL
8820 && this->args_->size() == 1
8821 && this->args_->front()->call_expression() != NULL)
8823 size_t rc = this->args_->front()->call_expression()->result_count();
8824 if (rc > 1
8825 && ((fntype->parameters() != NULL
8826 && (fntype->parameters()->size() == rc
8827 || (fntype->is_varargs()
8828 && fntype->parameters()->size() - 1 <= rc)))
8829 || fntype->is_builtin()))
8831 Call_expression* call = this->args_->front()->call_expression();
8832 Expression_list* args = new Expression_list;
8833 for (size_t i = 0; i < rc; ++i)
8834 args->push_back(Expression::make_call_result(call, i));
8835 // We can't return a new call expression here, because this
8836 // one may be referenced by Call_result expressions. We
8837 // also can't delete the old arguments, because we may still
8838 // traverse them somewhere up the call stack. FIXME.
8839 this->args_ = args;
8843 // Recognize a call to a builtin function.
8844 if (fntype->is_builtin())
8845 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8846 this->is_varargs_, loc);
8848 // If this call returns multiple results, create a temporary
8849 // variable for each result.
8850 size_t rc = this->result_count();
8851 if (rc > 1 && this->results_ == NULL)
8853 std::vector<Temporary_statement*>* temps =
8854 new std::vector<Temporary_statement*>;
8855 temps->reserve(rc);
8856 const Typed_identifier_list* results = fntype->results();
8857 for (Typed_identifier_list::const_iterator p = results->begin();
8858 p != results->end();
8859 ++p)
8861 Temporary_statement* temp = Statement::make_temporary(p->type(),
8862 NULL, loc);
8863 inserter->insert(temp);
8864 temps->push_back(temp);
8866 this->results_ = temps;
8869 // Handle a call to a varargs function by packaging up the extra
8870 // parameters.
8871 if (fntype->is_varargs())
8873 const Typed_identifier_list* parameters = fntype->parameters();
8874 go_assert(parameters != NULL && !parameters->empty());
8875 Type* varargs_type = parameters->back().type();
8876 this->lower_varargs(gogo, function, inserter, varargs_type,
8877 parameters->size());
8880 // If this is call to a method, call the method directly passing the
8881 // object as the first parameter.
8882 Bound_method_expression* bme = this->fn_->bound_method_expression();
8883 if (bme != NULL)
8885 Named_object* methodfn = bme->function();
8886 Expression* first_arg = bme->first_argument();
8888 // We always pass a pointer when calling a method.
8889 if (first_arg->type()->points_to() == NULL
8890 && !first_arg->type()->is_error())
8892 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8893 // We may need to create a temporary variable so that we can
8894 // take the address. We can't do that here because it will
8895 // mess up the order of evaluation.
8896 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8897 ue->set_create_temp();
8900 // If we are calling a method which was inherited from an
8901 // embedded struct, and the method did not get a stub, then the
8902 // first type may be wrong.
8903 Type* fatype = bme->first_argument_type();
8904 if (fatype != NULL)
8906 if (fatype->points_to() == NULL)
8907 fatype = Type::make_pointer_type(fatype);
8908 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8911 Expression_list* new_args = new Expression_list();
8912 new_args->push_back(first_arg);
8913 if (this->args_ != NULL)
8915 for (Expression_list::const_iterator p = this->args_->begin();
8916 p != this->args_->end();
8917 ++p)
8918 new_args->push_back(*p);
8921 // We have to change in place because this structure may be
8922 // referenced by Call_result_expressions. We can't delete the
8923 // old arguments, because we may be traversing them up in some
8924 // caller. FIXME.
8925 this->args_ = new_args;
8926 this->fn_ = Expression::make_func_reference(methodfn, NULL,
8927 bme->location());
8930 return this;
8933 // Lower a call to a varargs function. FUNCTION is the function in
8934 // which the call occurs--it's not the function we are calling.
8935 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8936 // PARAM_COUNT is the number of parameters of the function we are
8937 // calling; the last of these parameters will be the varargs
8938 // parameter.
8940 void
8941 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8942 Statement_inserter* inserter,
8943 Type* varargs_type, size_t param_count)
8945 if (this->varargs_are_lowered_)
8946 return;
8948 Location loc = this->location();
8950 go_assert(param_count > 0);
8951 go_assert(varargs_type->is_slice_type());
8953 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8954 if (arg_count < param_count - 1)
8956 // Not enough arguments; will be caught in check_types.
8957 return;
8960 Expression_list* old_args = this->args_;
8961 Expression_list* new_args = new Expression_list();
8962 bool push_empty_arg = false;
8963 if (old_args == NULL || old_args->empty())
8965 go_assert(param_count == 1);
8966 push_empty_arg = true;
8968 else
8970 Expression_list::const_iterator pa;
8971 int i = 1;
8972 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8974 if (static_cast<size_t>(i) == param_count)
8975 break;
8976 new_args->push_back(*pa);
8979 // We have reached the varargs parameter.
8981 bool issued_error = false;
8982 if (pa == old_args->end())
8983 push_empty_arg = true;
8984 else if (pa + 1 == old_args->end() && this->is_varargs_)
8985 new_args->push_back(*pa);
8986 else if (this->is_varargs_)
8988 if ((*pa)->type()->is_slice_type())
8989 this->report_error(_("too many arguments"));
8990 else
8992 error_at(this->location(),
8993 _("invalid use of %<...%> with non-slice"));
8994 this->set_is_error();
8996 return;
8998 else
9000 Type* element_type = varargs_type->array_type()->element_type();
9001 Expression_list* vals = new Expression_list;
9002 for (; pa != old_args->end(); ++pa, ++i)
9004 // Check types here so that we get a better message.
9005 Type* patype = (*pa)->type();
9006 Location paloc = (*pa)->location();
9007 if (!this->check_argument_type(i, element_type, patype,
9008 paloc, issued_error))
9009 continue;
9010 vals->push_back(*pa);
9012 Expression* val =
9013 Expression::make_slice_composite_literal(varargs_type, vals, loc);
9014 gogo->lower_expression(function, inserter, &val);
9015 new_args->push_back(val);
9019 if (push_empty_arg)
9020 new_args->push_back(Expression::make_nil(loc));
9022 // We can't return a new call expression here, because this one may
9023 // be referenced by Call_result expressions. FIXME. We can't
9024 // delete OLD_ARGS because we may have both a Call_expression and a
9025 // Builtin_call_expression which refer to them. FIXME.
9026 this->args_ = new_args;
9027 this->varargs_are_lowered_ = true;
9030 // Flatten a call with multiple results into a temporary.
9032 Expression*
9033 Call_expression::do_flatten(Gogo* gogo, Named_object*,
9034 Statement_inserter* inserter)
9036 if (this->classification() == EXPRESSION_ERROR)
9037 return this;
9039 // Add temporary variables for all arguments that require type
9040 // conversion.
9041 Function_type* fntype = this->get_function_type();
9042 go_assert(fntype != NULL);
9043 if (this->args_ != NULL && !this->args_->empty()
9044 && fntype->parameters() != NULL && !fntype->parameters()->empty())
9046 bool is_interface_method =
9047 this->fn_->interface_field_reference_expression() != NULL;
9049 Expression_list *args = new Expression_list();
9050 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
9051 Expression_list::const_iterator pa = this->args_->begin();
9052 if (!is_interface_method && fntype->is_method())
9054 // The receiver argument.
9055 args->push_back(*pa);
9056 ++pa;
9058 for (; pa != this->args_->end(); ++pa, ++pp)
9060 go_assert(pp != fntype->parameters()->end());
9061 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
9062 args->push_back(*pa);
9063 else
9065 Location loc = (*pa)->location();
9066 Expression* arg =
9067 Expression::convert_for_assignment(gogo, pp->type(), *pa, loc);
9068 Temporary_statement* temp =
9069 Statement::make_temporary(pp->type(), arg, loc);
9070 inserter->insert(temp);
9071 args->push_back(Expression::make_temporary_reference(temp, loc));
9074 delete this->args_;
9075 this->args_ = args;
9078 size_t rc = this->result_count();
9079 if (rc > 1 && this->call_temp_ == NULL)
9081 Struct_field_list* sfl = new Struct_field_list();
9082 Function_type* fntype = this->get_function_type();
9083 const Typed_identifier_list* results = fntype->results();
9084 Location loc = this->location();
9086 int i = 0;
9087 char buf[10];
9088 for (Typed_identifier_list::const_iterator p = results->begin();
9089 p != results->end();
9090 ++p, ++i)
9092 snprintf(buf, sizeof buf, "res%d", i);
9093 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9096 Struct_type* st = Type::make_struct_type(sfl, loc);
9097 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9098 inserter->insert(this->call_temp_);
9101 return this;
9104 // Get the function type. This can return NULL in error cases.
9106 Function_type*
9107 Call_expression::get_function_type() const
9109 return this->fn_->type()->function_type();
9112 // Return the number of values which this call will return.
9114 size_t
9115 Call_expression::result_count() const
9117 const Function_type* fntype = this->get_function_type();
9118 if (fntype == NULL)
9119 return 0;
9120 if (fntype->results() == NULL)
9121 return 0;
9122 return fntype->results()->size();
9125 // Return the temporary which holds a result.
9127 Temporary_statement*
9128 Call_expression::result(size_t i) const
9130 if (this->results_ == NULL || this->results_->size() <= i)
9132 go_assert(saw_errors());
9133 return NULL;
9135 return (*this->results_)[i];
9138 // Set the number of results expected from a call expression.
9140 void
9141 Call_expression::set_expected_result_count(size_t count)
9143 go_assert(this->expected_result_count_ == 0);
9144 this->expected_result_count_ = count;
9147 // Return whether this is a call to the predeclared function recover.
9149 bool
9150 Call_expression::is_recover_call() const
9152 return this->do_is_recover_call();
9155 // Set the argument to the recover function.
9157 void
9158 Call_expression::set_recover_arg(Expression* arg)
9160 this->do_set_recover_arg(arg);
9163 // Virtual functions also implemented by Builtin_call_expression.
9165 bool
9166 Call_expression::do_is_recover_call() const
9168 return false;
9171 void
9172 Call_expression::do_set_recover_arg(Expression*)
9174 go_unreachable();
9177 // We have found an error with this call expression; return true if
9178 // we should report it.
9180 bool
9181 Call_expression::issue_error()
9183 if (this->issued_error_)
9184 return false;
9185 else
9187 this->issued_error_ = true;
9188 return true;
9192 // Get the type.
9194 Type*
9195 Call_expression::do_type()
9197 if (this->type_ != NULL)
9198 return this->type_;
9200 Type* ret;
9201 Function_type* fntype = this->get_function_type();
9202 if (fntype == NULL)
9203 return Type::make_error_type();
9205 const Typed_identifier_list* results = fntype->results();
9206 if (results == NULL)
9207 ret = Type::make_void_type();
9208 else if (results->size() == 1)
9209 ret = results->begin()->type();
9210 else
9211 ret = Type::make_call_multiple_result_type(this);
9213 this->type_ = ret;
9215 return this->type_;
9218 // Determine types for a call expression. We can use the function
9219 // parameter types to set the types of the arguments.
9221 void
9222 Call_expression::do_determine_type(const Type_context*)
9224 if (!this->determining_types())
9225 return;
9227 this->fn_->determine_type_no_context();
9228 Function_type* fntype = this->get_function_type();
9229 const Typed_identifier_list* parameters = NULL;
9230 if (fntype != NULL)
9231 parameters = fntype->parameters();
9232 if (this->args_ != NULL)
9234 Typed_identifier_list::const_iterator pt;
9235 if (parameters != NULL)
9236 pt = parameters->begin();
9237 bool first = true;
9238 for (Expression_list::const_iterator pa = this->args_->begin();
9239 pa != this->args_->end();
9240 ++pa)
9242 if (first)
9244 first = false;
9245 // If this is a method, the first argument is the
9246 // receiver.
9247 if (fntype != NULL && fntype->is_method())
9249 Type* rtype = fntype->receiver()->type();
9250 // The receiver is always passed as a pointer.
9251 if (rtype->points_to() == NULL)
9252 rtype = Type::make_pointer_type(rtype);
9253 Type_context subcontext(rtype, false);
9254 (*pa)->determine_type(&subcontext);
9255 continue;
9259 if (parameters != NULL && pt != parameters->end())
9261 Type_context subcontext(pt->type(), false);
9262 (*pa)->determine_type(&subcontext);
9263 ++pt;
9265 else
9266 (*pa)->determine_type_no_context();
9271 // Called when determining types for a Call_expression. Return true
9272 // if we should go ahead, false if they have already been determined.
9274 bool
9275 Call_expression::determining_types()
9277 if (this->types_are_determined_)
9278 return false;
9279 else
9281 this->types_are_determined_ = true;
9282 return true;
9286 // Check types for parameter I.
9288 bool
9289 Call_expression::check_argument_type(int i, const Type* parameter_type,
9290 const Type* argument_type,
9291 Location argument_location,
9292 bool issued_error)
9294 std::string reason;
9295 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9297 if (!issued_error)
9299 if (reason.empty())
9300 error_at(argument_location, "argument %d has incompatible type", i);
9301 else
9302 error_at(argument_location,
9303 "argument %d has incompatible type (%s)",
9304 i, reason.c_str());
9306 this->set_is_error();
9307 return false;
9309 return true;
9312 // Check types.
9314 void
9315 Call_expression::do_check_types(Gogo*)
9317 if (this->classification() == EXPRESSION_ERROR)
9318 return;
9320 Function_type* fntype = this->get_function_type();
9321 if (fntype == NULL)
9323 if (!this->fn_->type()->is_error())
9324 this->report_error(_("expected function"));
9325 return;
9328 if (this->expected_result_count_ != 0
9329 && this->expected_result_count_ != this->result_count())
9331 if (this->issue_error())
9332 this->report_error(_("function result count mismatch"));
9333 this->set_is_error();
9334 return;
9337 bool is_method = fntype->is_method();
9338 if (is_method)
9340 go_assert(this->args_ != NULL && !this->args_->empty());
9341 Type* rtype = fntype->receiver()->type();
9342 Expression* first_arg = this->args_->front();
9343 // We dereference the values since receivers are always passed
9344 // as pointers.
9345 std::string reason;
9346 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9347 &reason))
9349 if (reason.empty())
9350 this->report_error(_("incompatible type for receiver"));
9351 else
9353 error_at(this->location(),
9354 "incompatible type for receiver (%s)",
9355 reason.c_str());
9356 this->set_is_error();
9361 // Note that varargs was handled by the lower_varargs() method, so
9362 // we don't have to worry about it here unless something is wrong.
9363 if (this->is_varargs_ && !this->varargs_are_lowered_)
9365 if (!fntype->is_varargs())
9367 error_at(this->location(),
9368 _("invalid use of %<...%> calling non-variadic function"));
9369 this->set_is_error();
9370 return;
9374 const Typed_identifier_list* parameters = fntype->parameters();
9375 if (this->args_ == NULL)
9377 if (parameters != NULL && !parameters->empty())
9378 this->report_error(_("not enough arguments"));
9380 else if (parameters == NULL)
9382 if (!is_method || this->args_->size() > 1)
9383 this->report_error(_("too many arguments"));
9385 else if (this->args_->size() == 1
9386 && this->args_->front()->call_expression() != NULL
9387 && this->args_->front()->call_expression()->result_count() > 1)
9389 // This is F(G()) when G returns more than one result. If the
9390 // results can be matched to parameters, it would have been
9391 // lowered in do_lower. If we get here we know there is a
9392 // mismatch.
9393 if (this->args_->front()->call_expression()->result_count()
9394 < parameters->size())
9395 this->report_error(_("not enough arguments"));
9396 else
9397 this->report_error(_("too many arguments"));
9399 else
9401 int i = 0;
9402 Expression_list::const_iterator pa = this->args_->begin();
9403 if (is_method)
9404 ++pa;
9405 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9406 pt != parameters->end();
9407 ++pt, ++pa, ++i)
9409 if (pa == this->args_->end())
9411 this->report_error(_("not enough arguments"));
9412 return;
9414 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9415 (*pa)->location(), false);
9417 if (pa != this->args_->end())
9418 this->report_error(_("too many arguments"));
9422 // Return whether we have to use a temporary variable to ensure that
9423 // we evaluate this call expression in order. If the call returns no
9424 // results then it will inevitably be executed last.
9426 bool
9427 Call_expression::do_must_eval_in_order() const
9429 return this->result_count() > 0;
9432 // Get the function and the first argument to use when calling an
9433 // interface method.
9435 Expression*
9436 Call_expression::interface_method_function(
9437 Interface_field_reference_expression* interface_method,
9438 Expression** first_arg_ptr)
9440 *first_arg_ptr = interface_method->get_underlying_object();
9441 return interface_method->get_function();
9444 // Build the call expression.
9446 Bexpression*
9447 Call_expression::do_get_backend(Translate_context* context)
9449 if (this->call_ != NULL)
9450 return this->call_;
9452 Function_type* fntype = this->get_function_type();
9453 if (fntype == NULL)
9454 return context->backend()->error_expression();
9456 if (this->fn_->is_error_expression())
9457 return context->backend()->error_expression();
9459 Gogo* gogo = context->gogo();
9460 Location location = this->location();
9462 Func_expression* func = this->fn_->func_expression();
9463 Interface_field_reference_expression* interface_method =
9464 this->fn_->interface_field_reference_expression();
9465 const bool has_closure = func != NULL && func->closure() != NULL;
9466 const bool is_interface_method = interface_method != NULL;
9468 bool has_closure_arg;
9469 if (has_closure)
9470 has_closure_arg = true;
9471 else if (func != NULL)
9472 has_closure_arg = false;
9473 else if (is_interface_method)
9474 has_closure_arg = false;
9475 else
9476 has_closure_arg = true;
9478 int nargs;
9479 std::vector<Bexpression*> fn_args;
9480 if (this->args_ == NULL || this->args_->empty())
9482 nargs = is_interface_method ? 1 : 0;
9483 if (nargs > 0)
9484 fn_args.resize(1);
9486 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9488 // Passing a receiver parameter.
9489 go_assert(!is_interface_method
9490 && fntype->is_method()
9491 && this->args_->size() == 1);
9492 nargs = 1;
9493 fn_args.resize(1);
9494 fn_args[0] = this->args_->front()->get_backend(context);
9496 else
9498 const Typed_identifier_list* params = fntype->parameters();
9500 nargs = this->args_->size();
9501 int i = is_interface_method ? 1 : 0;
9502 nargs += i;
9503 fn_args.resize(nargs);
9505 Typed_identifier_list::const_iterator pp = params->begin();
9506 Expression_list::const_iterator pe = this->args_->begin();
9507 if (!is_interface_method && fntype->is_method())
9509 fn_args[i] = (*pe)->get_backend(context);
9510 ++pe;
9511 ++i;
9513 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9515 go_assert(pp != params->end());
9516 Expression* arg =
9517 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9518 location);
9519 fn_args[i] = arg->get_backend(context);
9521 go_assert(pp == params->end());
9522 go_assert(i == nargs);
9525 Expression* fn;
9526 Expression* closure = NULL;
9527 if (func != NULL)
9529 Named_object* no = func->named_object();
9530 fn = Expression::make_func_code_reference(no, location);
9531 if (has_closure)
9532 closure = func->closure();
9534 else if (!is_interface_method)
9536 closure = this->fn_;
9538 // The backend representation of this function type is a pointer
9539 // to a struct whose first field is the actual function to call.
9540 Type* pfntype =
9541 Type::make_pointer_type(
9542 Type::make_pointer_type(Type::make_void_type()));
9543 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9544 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9546 else
9548 Expression* first_arg;
9549 fn = this->interface_method_function(interface_method, &first_arg);
9550 fn_args[0] = first_arg->get_backend(context);
9553 if (!has_closure_arg)
9554 go_assert(closure == NULL);
9555 else
9557 // Pass the closure argument by calling the function function
9558 // __go_set_closure. In the order_evaluations pass we have
9559 // ensured that if any parameters contain call expressions, they
9560 // will have been moved out to temporary variables.
9561 go_assert(closure != NULL);
9562 Expression* set_closure =
9563 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9564 fn = Expression::make_compound(set_closure, fn, location);
9567 Bexpression* bfn = fn->get_backend(context);
9569 // When not calling a named function directly, use a type conversion
9570 // in case the type of the function is a recursive type which refers
9571 // to itself. We don't do this for an interface method because 1)
9572 // an interface method never refers to itself, so we always have a
9573 // function type here; 2) we pass an extra first argument to an
9574 // interface method, so fntype is not correct.
9575 if (func == NULL && !is_interface_method)
9577 Btype* bft = fntype->get_backend_fntype(gogo);
9578 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9581 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
9583 if (this->results_ != NULL)
9585 go_assert(this->call_temp_ != NULL);
9586 Expression* call_ref =
9587 Expression::make_temporary_reference(this->call_temp_, location);
9588 Bexpression* bcall_ref = call_ref->get_backend(context);
9589 Bstatement* assn_stmt =
9590 gogo->backend()->assignment_statement(bcall_ref, call, location);
9592 this->call_ = this->set_results(context, bcall_ref);
9594 Bexpression* set_and_call =
9595 gogo->backend()->compound_expression(assn_stmt, this->call_,
9596 location);
9597 return set_and_call;
9600 this->call_ = call;
9601 return this->call_;
9604 // Set the result variables if this call returns multiple results.
9606 Bexpression*
9607 Call_expression::set_results(Translate_context* context, Bexpression* call)
9609 Gogo* gogo = context->gogo();
9611 Bexpression* results = NULL;
9612 Location loc = this->location();
9614 size_t rc = this->result_count();
9615 for (size_t i = 0; i < rc; ++i)
9617 Temporary_statement* temp = this->result(i);
9618 if (temp == NULL)
9620 go_assert(saw_errors());
9621 return gogo->backend()->error_expression();
9623 Temporary_reference_expression* ref =
9624 Expression::make_temporary_reference(temp, loc);
9625 ref->set_is_lvalue();
9627 Bexpression* result_ref = ref->get_backend(context);
9628 Bexpression* call_result =
9629 gogo->backend()->struct_field_expression(call, i, loc);
9630 Bstatement* assn_stmt =
9631 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9633 Bexpression* result =
9634 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9636 if (results == NULL)
9637 results = result;
9638 else
9640 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9641 results =
9642 gogo->backend()->compound_expression(expr_stmt, results, loc);
9645 return results;
9648 // Dump ast representation for a call expressin.
9650 void
9651 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9653 this->fn_->dump_expression(ast_dump_context);
9654 ast_dump_context->ostream() << "(";
9655 if (args_ != NULL)
9656 ast_dump_context->dump_expression_list(this->args_);
9658 ast_dump_context->ostream() << ") ";
9661 // Make a call expression.
9663 Call_expression*
9664 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9665 Location location)
9667 return new Call_expression(fn, args, is_varargs, location);
9670 // A single result from a call which returns multiple results.
9672 class Call_result_expression : public Expression
9674 public:
9675 Call_result_expression(Call_expression* call, unsigned int index)
9676 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9677 call_(call), index_(index)
9680 protected:
9682 do_traverse(Traverse*);
9684 Type*
9685 do_type();
9687 void
9688 do_determine_type(const Type_context*);
9690 void
9691 do_check_types(Gogo*);
9693 Expression*
9694 do_copy()
9696 return new Call_result_expression(this->call_->call_expression(),
9697 this->index_);
9700 bool
9701 do_must_eval_in_order() const
9702 { return true; }
9704 Bexpression*
9705 do_get_backend(Translate_context*);
9707 void
9708 do_dump_expression(Ast_dump_context*) const;
9710 private:
9711 // The underlying call expression.
9712 Expression* call_;
9713 // Which result we want.
9714 unsigned int index_;
9717 // Traverse a call result.
9720 Call_result_expression::do_traverse(Traverse* traverse)
9722 if (traverse->remember_expression(this->call_))
9724 // We have already traversed the call expression.
9725 return TRAVERSE_CONTINUE;
9727 return Expression::traverse(&this->call_, traverse);
9730 // Get the type.
9732 Type*
9733 Call_result_expression::do_type()
9735 if (this->classification() == EXPRESSION_ERROR)
9736 return Type::make_error_type();
9738 // THIS->CALL_ can be replaced with a temporary reference due to
9739 // Call_expression::do_must_eval_in_order when there is an error.
9740 Call_expression* ce = this->call_->call_expression();
9741 if (ce == NULL)
9743 this->set_is_error();
9744 return Type::make_error_type();
9746 Function_type* fntype = ce->get_function_type();
9747 if (fntype == NULL)
9749 if (ce->issue_error())
9751 if (!ce->fn()->type()->is_error())
9752 this->report_error(_("expected function"));
9754 this->set_is_error();
9755 return Type::make_error_type();
9757 const Typed_identifier_list* results = fntype->results();
9758 if (results == NULL || results->size() < 2)
9760 if (ce->issue_error())
9761 this->report_error(_("number of results does not match "
9762 "number of values"));
9763 return Type::make_error_type();
9765 Typed_identifier_list::const_iterator pr = results->begin();
9766 for (unsigned int i = 0; i < this->index_; ++i)
9768 if (pr == results->end())
9769 break;
9770 ++pr;
9772 if (pr == results->end())
9774 if (ce->issue_error())
9775 this->report_error(_("number of results does not match "
9776 "number of values"));
9777 return Type::make_error_type();
9779 return pr->type();
9782 // Check the type. Just make sure that we trigger the warning in
9783 // do_type.
9785 void
9786 Call_result_expression::do_check_types(Gogo*)
9788 this->type();
9791 // Determine the type. We have nothing to do here, but the 0 result
9792 // needs to pass down to the caller.
9794 void
9795 Call_result_expression::do_determine_type(const Type_context*)
9797 this->call_->determine_type_no_context();
9800 // Return the backend representation. We just refer to the temporary set by the
9801 // call expression. We don't do this at lowering time because it makes it
9802 // hard to evaluate the call at the right time.
9804 Bexpression*
9805 Call_result_expression::do_get_backend(Translate_context* context)
9807 Call_expression* ce = this->call_->call_expression();
9808 if (ce == NULL)
9810 go_assert(this->call_->is_error_expression());
9811 return context->backend()->error_expression();
9813 Temporary_statement* ts = ce->result(this->index_);
9814 if (ts == NULL)
9816 go_assert(saw_errors());
9817 return context->backend()->error_expression();
9819 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9820 return ref->get_backend(context);
9823 // Dump ast representation for a call result expression.
9825 void
9826 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9827 const
9829 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9830 // (struct) and the fields are referenced instead.
9831 ast_dump_context->ostream() << this->index_ << "@(";
9832 ast_dump_context->dump_expression(this->call_);
9833 ast_dump_context->ostream() << ")";
9836 // Make a reference to a single result of a call which returns
9837 // multiple results.
9839 Expression*
9840 Expression::make_call_result(Call_expression* call, unsigned int index)
9842 return new Call_result_expression(call, index);
9845 // Class Index_expression.
9847 // Traversal.
9850 Index_expression::do_traverse(Traverse* traverse)
9852 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9853 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9854 || (this->end_ != NULL
9855 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9856 || (this->cap_ != NULL
9857 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9858 return TRAVERSE_EXIT;
9859 return TRAVERSE_CONTINUE;
9862 // Lower an index expression. This converts the generic index
9863 // expression into an array index, a string index, or a map index.
9865 Expression*
9866 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9868 Location location = this->location();
9869 Expression* left = this->left_;
9870 Expression* start = this->start_;
9871 Expression* end = this->end_;
9872 Expression* cap = this->cap_;
9874 Type* type = left->type();
9875 if (type->is_error())
9877 go_assert(saw_errors());
9878 return Expression::make_error(location);
9880 else if (left->is_type_expression())
9882 error_at(location, "attempt to index type expression");
9883 return Expression::make_error(location);
9885 else if (type->array_type() != NULL)
9886 return Expression::make_array_index(left, start, end, cap, location);
9887 else if (type->points_to() != NULL
9888 && type->points_to()->array_type() != NULL
9889 && !type->points_to()->is_slice_type())
9891 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9892 location);
9894 // For an ordinary index into the array, the pointer will be
9895 // dereferenced. For a slice it will not--the resulting slice
9896 // will simply reuse the pointer, which is incorrect if that
9897 // pointer is nil.
9898 if (end != NULL || cap != NULL)
9899 deref->issue_nil_check();
9901 return Expression::make_array_index(deref, start, end, cap, location);
9903 else if (type->is_string_type())
9905 if (cap != NULL)
9907 error_at(location, "invalid 3-index slice of string");
9908 return Expression::make_error(location);
9910 return Expression::make_string_index(left, start, end, location);
9912 else if (type->map_type() != NULL)
9914 if (end != NULL || cap != NULL)
9916 error_at(location, "invalid slice of map");
9917 return Expression::make_error(location);
9919 Map_index_expression* ret = Expression::make_map_index(left, start,
9920 location);
9921 if (this->is_lvalue_)
9922 ret->set_is_lvalue();
9923 return ret;
9925 else
9927 error_at(location,
9928 "attempt to index object which is not array, string, or map");
9929 return Expression::make_error(location);
9933 // Write an indexed expression
9934 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9936 void
9937 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9938 const Expression* expr,
9939 const Expression* start,
9940 const Expression* end,
9941 const Expression* cap)
9943 expr->dump_expression(ast_dump_context);
9944 ast_dump_context->ostream() << "[";
9945 start->dump_expression(ast_dump_context);
9946 if (end != NULL)
9948 ast_dump_context->ostream() << ":";
9949 end->dump_expression(ast_dump_context);
9951 if (cap != NULL)
9953 ast_dump_context->ostream() << ":";
9954 cap->dump_expression(ast_dump_context);
9956 ast_dump_context->ostream() << "]";
9959 // Dump ast representation for an index expression.
9961 void
9962 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9963 const
9965 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9966 this->start_, this->end_, this->cap_);
9969 // Make an index expression.
9971 Expression*
9972 Expression::make_index(Expression* left, Expression* start, Expression* end,
9973 Expression* cap, Location location)
9975 return new Index_expression(left, start, end, cap, location);
9978 // An array index. This is used for both indexing and slicing.
9980 class Array_index_expression : public Expression
9982 public:
9983 Array_index_expression(Expression* array, Expression* start,
9984 Expression* end, Expression* cap, Location location)
9985 : Expression(EXPRESSION_ARRAY_INDEX, location),
9986 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
9989 protected:
9991 do_traverse(Traverse*);
9993 Expression*
9994 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9996 Type*
9997 do_type();
9999 void
10000 do_determine_type(const Type_context*);
10002 void
10003 do_check_types(Gogo*);
10005 Expression*
10006 do_copy()
10008 return Expression::make_array_index(this->array_->copy(),
10009 this->start_->copy(),
10010 (this->end_ == NULL
10011 ? NULL
10012 : this->end_->copy()),
10013 (this->cap_ == NULL
10014 ? NULL
10015 : this->cap_->copy()),
10016 this->location());
10019 bool
10020 do_must_eval_subexpressions_in_order(int* skip) const
10022 *skip = 1;
10023 return true;
10026 bool
10027 do_is_addressable() const;
10029 void
10030 do_address_taken(bool escapes)
10031 { this->array_->address_taken(escapes); }
10033 void
10034 do_issue_nil_check()
10035 { this->array_->issue_nil_check(); }
10037 Bexpression*
10038 do_get_backend(Translate_context*);
10040 void
10041 do_dump_expression(Ast_dump_context*) const;
10043 private:
10044 // The array we are getting a value from.
10045 Expression* array_;
10046 // The start or only index.
10047 Expression* start_;
10048 // The end index of a slice. This may be NULL for a simple array
10049 // index, or it may be a nil expression for the length of the array.
10050 Expression* end_;
10051 // The capacity argument of a slice. This may be NULL for an array index or
10052 // slice.
10053 Expression* cap_;
10054 // The type of the expression.
10055 Type* type_;
10058 // Array index traversal.
10061 Array_index_expression::do_traverse(Traverse* traverse)
10063 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
10064 return TRAVERSE_EXIT;
10065 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10066 return TRAVERSE_EXIT;
10067 if (this->end_ != NULL)
10069 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10070 return TRAVERSE_EXIT;
10072 if (this->cap_ != NULL)
10074 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
10075 return TRAVERSE_EXIT;
10077 return TRAVERSE_CONTINUE;
10080 // Return the type of an array index.
10082 Type*
10083 Array_index_expression::do_type()
10085 if (this->type_ == NULL)
10087 Array_type* type = this->array_->type()->array_type();
10088 if (type == NULL)
10089 this->type_ = Type::make_error_type();
10090 else if (this->end_ == NULL)
10091 this->type_ = type->element_type();
10092 else if (type->is_slice_type())
10094 // A slice of a slice has the same type as the original
10095 // slice.
10096 this->type_ = this->array_->type()->deref();
10098 else
10100 // A slice of an array is a slice.
10101 this->type_ = Type::make_array_type(type->element_type(), NULL);
10104 return this->type_;
10107 // Set the type of an array index.
10109 void
10110 Array_index_expression::do_determine_type(const Type_context*)
10112 this->array_->determine_type_no_context();
10113 this->start_->determine_type_no_context();
10114 if (this->end_ != NULL)
10115 this->end_->determine_type_no_context();
10116 if (this->cap_ != NULL)
10117 this->cap_->determine_type_no_context();
10120 // Check types of an array index.
10122 void
10123 Array_index_expression::do_check_types(Gogo*)
10125 Numeric_constant nc;
10126 unsigned long v;
10127 if (this->start_->type()->integer_type() == NULL
10128 && !this->start_->type()->is_error()
10129 && (!this->start_->numeric_constant_value(&nc)
10130 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10131 this->report_error(_("index must be integer"));
10132 if (this->end_ != NULL
10133 && this->end_->type()->integer_type() == NULL
10134 && !this->end_->type()->is_error()
10135 && !this->end_->is_nil_expression()
10136 && !this->end_->is_error_expression()
10137 && (!this->end_->numeric_constant_value(&nc)
10138 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10139 this->report_error(_("slice end must be integer"));
10140 if (this->cap_ != NULL
10141 && this->cap_->type()->integer_type() == NULL
10142 && !this->cap_->type()->is_error()
10143 && !this->cap_->is_nil_expression()
10144 && !this->cap_->is_error_expression()
10145 && (!this->cap_->numeric_constant_value(&nc)
10146 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10147 this->report_error(_("slice capacity must be integer"));
10149 Array_type* array_type = this->array_->type()->array_type();
10150 if (array_type == NULL)
10152 go_assert(this->array_->type()->is_error());
10153 return;
10156 unsigned int int_bits =
10157 Type::lookup_integer_type("int")->integer_type()->bits();
10159 Numeric_constant lvalnc;
10160 mpz_t lval;
10161 bool lval_valid = (array_type->length() != NULL
10162 && array_type->length()->numeric_constant_value(&lvalnc)
10163 && lvalnc.to_int(&lval));
10164 Numeric_constant inc;
10165 mpz_t ival;
10166 bool ival_valid = false;
10167 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10169 ival_valid = true;
10170 if (mpz_sgn(ival) < 0
10171 || mpz_sizeinbase(ival, 2) >= int_bits
10172 || (lval_valid
10173 && (this->end_ == NULL
10174 ? mpz_cmp(ival, lval) >= 0
10175 : mpz_cmp(ival, lval) > 0)))
10177 error_at(this->start_->location(), "array index out of bounds");
10178 this->set_is_error();
10181 if (this->end_ != NULL && !this->end_->is_nil_expression())
10183 Numeric_constant enc;
10184 mpz_t eval;
10185 bool eval_valid = false;
10186 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10188 eval_valid = true;
10189 if (mpz_sgn(eval) < 0
10190 || mpz_sizeinbase(eval, 2) >= int_bits
10191 || (lval_valid && mpz_cmp(eval, lval) > 0))
10193 error_at(this->end_->location(), "array index out of bounds");
10194 this->set_is_error();
10196 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10197 this->report_error(_("inverted slice range"));
10200 Numeric_constant cnc;
10201 mpz_t cval;
10202 if (this->cap_ != NULL
10203 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10205 if (mpz_sgn(cval) < 0
10206 || mpz_sizeinbase(cval, 2) >= int_bits
10207 || (lval_valid && mpz_cmp(cval, lval) > 0))
10209 error_at(this->cap_->location(), "array index out of bounds");
10210 this->set_is_error();
10212 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10214 error_at(this->cap_->location(),
10215 "invalid slice index: capacity less than start");
10216 this->set_is_error();
10218 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10220 error_at(this->cap_->location(),
10221 "invalid slice index: capacity less than length");
10222 this->set_is_error();
10224 mpz_clear(cval);
10227 if (eval_valid)
10228 mpz_clear(eval);
10230 if (ival_valid)
10231 mpz_clear(ival);
10232 if (lval_valid)
10233 mpz_clear(lval);
10235 // A slice of an array requires an addressable array. A slice of a
10236 // slice is always possible.
10237 if (this->end_ != NULL && !array_type->is_slice_type())
10239 if (!this->array_->is_addressable())
10240 this->report_error(_("slice of unaddressable value"));
10241 else
10242 this->array_->address_taken(true);
10246 // Flatten array indexing by using temporary variables for slices and indexes.
10248 Expression*
10249 Array_index_expression::do_flatten(Gogo*, Named_object*,
10250 Statement_inserter* inserter)
10252 Location loc = this->location();
10253 Temporary_statement* temp;
10254 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10256 temp = Statement::make_temporary(NULL, this->array_, loc);
10257 inserter->insert(temp);
10258 this->array_ = Expression::make_temporary_reference(temp, loc);
10260 if (!this->start_->is_variable())
10262 temp = Statement::make_temporary(NULL, this->start_, loc);
10263 inserter->insert(temp);
10264 this->start_ = Expression::make_temporary_reference(temp, loc);
10266 if (this->end_ != NULL
10267 && !this->end_->is_nil_expression()
10268 && !this->end_->is_variable())
10270 temp = Statement::make_temporary(NULL, this->end_, loc);
10271 inserter->insert(temp);
10272 this->end_ = Expression::make_temporary_reference(temp, loc);
10274 if (this->cap_ != NULL && !this->cap_->is_variable())
10276 temp = Statement::make_temporary(NULL, this->cap_, loc);
10277 inserter->insert(temp);
10278 this->cap_ = Expression::make_temporary_reference(temp, loc);
10281 return this;
10284 // Return whether this expression is addressable.
10286 bool
10287 Array_index_expression::do_is_addressable() const
10289 // A slice expression is not addressable.
10290 if (this->end_ != NULL)
10291 return false;
10293 // An index into a slice is addressable.
10294 if (this->array_->type()->is_slice_type())
10295 return true;
10297 // An index into an array is addressable if the array is
10298 // addressable.
10299 return this->array_->is_addressable();
10302 // Get the backend representation for an array index.
10304 Bexpression*
10305 Array_index_expression::do_get_backend(Translate_context* context)
10307 Array_type* array_type = this->array_->type()->array_type();
10308 if (array_type == NULL)
10310 go_assert(this->array_->type()->is_error());
10311 return context->backend()->error_expression();
10313 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10315 Location loc = this->location();
10316 Gogo* gogo = context->gogo();
10318 Type* int_type = Type::lookup_integer_type("int");
10319 Btype* int_btype = int_type->get_backend(gogo);
10321 // We need to convert the length and capacity to the Go "int" type here
10322 // because the length of a fixed-length array could be of type "uintptr"
10323 // and gimple disallows binary operations between "uintptr" and other
10324 // integer types. FIXME.
10325 Bexpression* length = NULL;
10326 if (this->end_ == NULL || this->end_->is_nil_expression())
10328 Expression* len = array_type->get_length(gogo, this->array_);
10329 length = len->get_backend(context);
10330 length = gogo->backend()->convert_expression(int_btype, length, loc);
10333 Bexpression* capacity = NULL;
10334 if (this->end_ != NULL)
10336 Expression* cap = array_type->get_capacity(gogo, this->array_);
10337 capacity = cap->get_backend(context);
10338 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10341 Bexpression* cap_arg = capacity;
10342 if (this->cap_ != NULL)
10344 cap_arg = this->cap_->get_backend(context);
10345 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10348 if (length == NULL)
10349 length = cap_arg;
10351 int code = (array_type->length() != NULL
10352 ? (this->end_ == NULL
10353 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10354 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10355 : (this->end_ == NULL
10356 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10357 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10358 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10360 if (this->start_->type()->integer_type() == NULL
10361 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10363 go_assert(saw_errors());
10364 return context->backend()->error_expression();
10367 Bexpression* bad_index =
10368 Expression::check_bounds(this->start_, loc)->get_backend(context);
10370 Bexpression* start = this->start_->get_backend(context);
10371 start = gogo->backend()->convert_expression(int_btype, start, loc);
10372 Bexpression* start_too_large =
10373 gogo->backend()->binary_expression((this->end_ == NULL
10374 ? OPERATOR_GE
10375 : OPERATOR_GT),
10376 start,
10377 (this->end_ == NULL
10378 ? length
10379 : capacity),
10380 loc);
10381 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10382 bad_index, loc);
10384 if (this->end_ == NULL)
10386 // Simple array indexing. This has to return an l-value, so
10387 // wrap the index check into START.
10388 start =
10389 gogo->backend()->conditional_expression(int_btype, bad_index,
10390 crash, start, loc);
10392 Bexpression* ret;
10393 if (array_type->length() != NULL)
10395 Bexpression* array = this->array_->get_backend(context);
10396 ret = gogo->backend()->array_index_expression(array, start, loc);
10398 else
10400 // Slice.
10401 Expression* valptr =
10402 array_type->get_value_pointer(gogo, this->array_);
10403 Bexpression* ptr = valptr->get_backend(context);
10404 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10406 Type* ele_type = this->array_->type()->array_type()->element_type();
10407 Btype* ele_btype = ele_type->get_backend(gogo);
10408 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
10410 return ret;
10413 // Array slice.
10415 if (this->cap_ != NULL)
10417 Bexpression* bounds_bcheck =
10418 Expression::check_bounds(this->cap_, loc)->get_backend(context);
10419 bad_index =
10420 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10421 bad_index, loc);
10422 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10424 Bexpression* cap_too_small =
10425 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10426 Bexpression* cap_too_large =
10427 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10428 Bexpression* bad_cap =
10429 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10430 cap_too_large, loc);
10431 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10432 bad_index, loc);
10435 Bexpression* end;
10436 if (this->end_->is_nil_expression())
10437 end = length;
10438 else
10440 Bexpression* bounds_bcheck =
10441 Expression::check_bounds(this->end_, loc)->get_backend(context);
10443 bad_index =
10444 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10445 bad_index, loc);
10447 end = this->end_->get_backend(context);
10448 end = gogo->backend()->convert_expression(int_btype, end, loc);
10449 Bexpression* end_too_small =
10450 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10451 Bexpression* end_too_large =
10452 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10453 Bexpression* bad_end =
10454 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10455 end_too_large, loc);
10456 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10457 bad_index, loc);
10460 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10461 Bexpression* val = valptr->get_backend(context);
10462 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10464 Bexpression* result_length =
10465 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10467 Bexpression* result_capacity =
10468 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10470 Btype* struct_btype = this->type()->get_backend(gogo);
10471 std::vector<Bexpression*> init;
10472 init.push_back(val);
10473 init.push_back(result_length);
10474 init.push_back(result_capacity);
10476 Bexpression* ctor =
10477 gogo->backend()->constructor_expression(struct_btype, init, loc);
10478 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10479 crash, ctor, loc);
10482 // Dump ast representation for an array index expression.
10484 void
10485 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10486 const
10488 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10489 this->start_, this->end_, this->cap_);
10492 // Make an array index expression. END and CAP may be NULL.
10494 Expression*
10495 Expression::make_array_index(Expression* array, Expression* start,
10496 Expression* end, Expression* cap,
10497 Location location)
10499 return new Array_index_expression(array, start, end, cap, location);
10502 // A string index. This is used for both indexing and slicing.
10504 class String_index_expression : public Expression
10506 public:
10507 String_index_expression(Expression* string, Expression* start,
10508 Expression* end, Location location)
10509 : Expression(EXPRESSION_STRING_INDEX, location),
10510 string_(string), start_(start), end_(end)
10513 protected:
10515 do_traverse(Traverse*);
10517 Expression*
10518 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10520 Type*
10521 do_type();
10523 void
10524 do_determine_type(const Type_context*);
10526 void
10527 do_check_types(Gogo*);
10529 Expression*
10530 do_copy()
10532 return Expression::make_string_index(this->string_->copy(),
10533 this->start_->copy(),
10534 (this->end_ == NULL
10535 ? NULL
10536 : this->end_->copy()),
10537 this->location());
10540 bool
10541 do_must_eval_subexpressions_in_order(int* skip) const
10543 *skip = 1;
10544 return true;
10547 Bexpression*
10548 do_get_backend(Translate_context*);
10550 void
10551 do_dump_expression(Ast_dump_context*) const;
10553 private:
10554 // The string we are getting a value from.
10555 Expression* string_;
10556 // The start or only index.
10557 Expression* start_;
10558 // The end index of a slice. This may be NULL for a single index,
10559 // or it may be a nil expression for the length of the string.
10560 Expression* end_;
10563 // String index traversal.
10566 String_index_expression::do_traverse(Traverse* traverse)
10568 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10569 return TRAVERSE_EXIT;
10570 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10571 return TRAVERSE_EXIT;
10572 if (this->end_ != NULL)
10574 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10575 return TRAVERSE_EXIT;
10577 return TRAVERSE_CONTINUE;
10580 Expression*
10581 String_index_expression::do_flatten(Gogo*, Named_object*,
10582 Statement_inserter* inserter)
10584 Temporary_statement* temp;
10585 Location loc = this->location();
10586 if (!this->string_->is_variable())
10588 temp = Statement::make_temporary(NULL, this->string_, loc);
10589 inserter->insert(temp);
10590 this->string_ = Expression::make_temporary_reference(temp, loc);
10592 if (!this->start_->is_variable())
10594 temp = Statement::make_temporary(NULL, this->start_, loc);
10595 inserter->insert(temp);
10596 this->start_ = Expression::make_temporary_reference(temp, loc);
10598 if (this->end_ != NULL
10599 && !this->end_->is_nil_expression()
10600 && !this->end_->is_variable())
10602 temp = Statement::make_temporary(NULL, this->end_, loc);
10603 inserter->insert(temp);
10604 this->end_ = Expression::make_temporary_reference(temp, loc);
10607 return this;
10610 // Return the type of a string index.
10612 Type*
10613 String_index_expression::do_type()
10615 if (this->end_ == NULL)
10616 return Type::lookup_integer_type("uint8");
10617 else
10618 return this->string_->type();
10621 // Determine the type of a string index.
10623 void
10624 String_index_expression::do_determine_type(const Type_context*)
10626 this->string_->determine_type_no_context();
10627 this->start_->determine_type_no_context();
10628 if (this->end_ != NULL)
10629 this->end_->determine_type_no_context();
10632 // Check types of a string index.
10634 void
10635 String_index_expression::do_check_types(Gogo*)
10637 Numeric_constant nc;
10638 unsigned long v;
10639 if (this->start_->type()->integer_type() == NULL
10640 && !this->start_->type()->is_error()
10641 && (!this->start_->numeric_constant_value(&nc)
10642 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10643 this->report_error(_("index must be integer"));
10644 if (this->end_ != NULL
10645 && this->end_->type()->integer_type() == NULL
10646 && !this->end_->type()->is_error()
10647 && !this->end_->is_nil_expression()
10648 && !this->end_->is_error_expression()
10649 && (!this->end_->numeric_constant_value(&nc)
10650 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10651 this->report_error(_("slice end must be integer"));
10653 std::string sval;
10654 bool sval_valid = this->string_->string_constant_value(&sval);
10656 Numeric_constant inc;
10657 mpz_t ival;
10658 bool ival_valid = false;
10659 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10661 ival_valid = true;
10662 if (mpz_sgn(ival) < 0
10663 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10665 error_at(this->start_->location(), "string index out of bounds");
10666 this->set_is_error();
10669 if (this->end_ != NULL && !this->end_->is_nil_expression())
10671 Numeric_constant enc;
10672 mpz_t eval;
10673 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10675 if (mpz_sgn(eval) < 0
10676 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10678 error_at(this->end_->location(), "string index out of bounds");
10679 this->set_is_error();
10681 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10682 this->report_error(_("inverted slice range"));
10683 mpz_clear(eval);
10686 if (ival_valid)
10687 mpz_clear(ival);
10690 // Get the backend representation for a string index.
10692 Bexpression*
10693 String_index_expression::do_get_backend(Translate_context* context)
10695 Location loc = this->location();
10696 Expression* string_arg = this->string_;
10697 if (this->string_->type()->points_to() != NULL)
10698 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10700 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10702 int code = (this->end_ == NULL
10703 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10704 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10706 Gogo* gogo = context->gogo();
10707 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10709 Type* int_type = Type::lookup_integer_type("int");
10711 // It is possible that an error occurred earlier because the start index
10712 // cannot be represented as an integer type. In this case, we shouldn't
10713 // try casting the starting index into an integer since
10714 // Type_conversion_expression will fail to get the backend representation.
10715 // FIXME.
10716 if (this->start_->type()->integer_type() == NULL
10717 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10719 go_assert(saw_errors());
10720 return context->backend()->error_expression();
10723 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10725 if (this->end_ == NULL)
10727 Expression* length =
10728 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10730 Expression* start_too_large =
10731 Expression::make_binary(OPERATOR_GE, start, length, loc);
10732 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10733 bad_index, loc);
10734 Expression* bytes =
10735 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10737 Bexpression* bstart = start->get_backend(context);
10738 Bexpression* ptr = bytes->get_backend(context);
10739 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10740 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10741 Bexpression* index =
10742 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
10744 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10745 Bexpression* index_error = bad_index->get_backend(context);
10746 return gogo->backend()->conditional_expression(byte_btype, index_error,
10747 crash, index, loc);
10750 Expression* end = NULL;
10751 if (this->end_->is_nil_expression())
10752 end = Expression::make_integer_sl(-1, int_type, loc);
10753 else
10755 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10756 bad_index =
10757 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10758 end = Expression::make_cast(int_type, this->end_, loc);
10761 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10762 string_arg, start, end);
10763 Bexpression* bstrslice = strslice->get_backend(context);
10765 Btype* str_btype = strslice->type()->get_backend(gogo);
10766 Bexpression* index_error = bad_index->get_backend(context);
10767 return gogo->backend()->conditional_expression(str_btype, index_error,
10768 crash, bstrslice, loc);
10771 // Dump ast representation for a string index expression.
10773 void
10774 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10775 const
10777 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10778 this->start_, this->end_, NULL);
10781 // Make a string index expression. END may be NULL.
10783 Expression*
10784 Expression::make_string_index(Expression* string, Expression* start,
10785 Expression* end, Location location)
10787 return new String_index_expression(string, start, end, location);
10790 // Class Map_index.
10792 // Get the type of the map.
10794 Map_type*
10795 Map_index_expression::get_map_type() const
10797 Map_type* mt = this->map_->type()->deref()->map_type();
10798 if (mt == NULL)
10799 go_assert(saw_errors());
10800 return mt;
10803 // Map index traversal.
10806 Map_index_expression::do_traverse(Traverse* traverse)
10808 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10809 return TRAVERSE_EXIT;
10810 return Expression::traverse(&this->index_, traverse);
10813 // We need to pass in a pointer to the key, so flatten the index into a
10814 // temporary variable if it isn't already. The value pointer will be
10815 // dereferenced and checked for nil, so flatten into a temporary to avoid
10816 // recomputation.
10818 Expression*
10819 Map_index_expression::do_flatten(Gogo*, Named_object*,
10820 Statement_inserter* inserter)
10822 Map_type* mt = this->get_map_type();
10823 if (this->index_->type() != mt->key_type())
10824 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10825 this->location());
10827 if (!this->index_->is_variable())
10829 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10830 this->location());
10831 inserter->insert(temp);
10832 this->index_ = Expression::make_temporary_reference(temp,
10833 this->location());
10836 if (this->value_pointer_ == NULL)
10837 this->get_value_pointer(this->is_lvalue_);
10838 if (!this->value_pointer_->is_variable())
10840 Temporary_statement* temp =
10841 Statement::make_temporary(NULL, this->value_pointer_,
10842 this->location());
10843 inserter->insert(temp);
10844 this->value_pointer_ =
10845 Expression::make_temporary_reference(temp, this->location());
10848 return this;
10851 // Return the type of a map index.
10853 Type*
10854 Map_index_expression::do_type()
10856 Map_type* mt = this->get_map_type();
10857 if (mt == NULL)
10858 return Type::make_error_type();
10859 Type* type = mt->val_type();
10860 // If this map index is in a tuple assignment, we actually return a
10861 // pointer to the value type. Tuple_map_assignment_statement is
10862 // responsible for handling this correctly. We need to get the type
10863 // right in case this gets assigned to a temporary variable.
10864 if (this->is_in_tuple_assignment_)
10865 type = Type::make_pointer_type(type);
10866 return type;
10869 // Fix the type of a map index.
10871 void
10872 Map_index_expression::do_determine_type(const Type_context*)
10874 this->map_->determine_type_no_context();
10875 Map_type* mt = this->get_map_type();
10876 Type* key_type = mt == NULL ? NULL : mt->key_type();
10877 Type_context subcontext(key_type, false);
10878 this->index_->determine_type(&subcontext);
10881 // Check types of a map index.
10883 void
10884 Map_index_expression::do_check_types(Gogo*)
10886 std::string reason;
10887 Map_type* mt = this->get_map_type();
10888 if (mt == NULL)
10889 return;
10890 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10892 if (reason.empty())
10893 this->report_error(_("incompatible type for map index"));
10894 else
10896 error_at(this->location(), "incompatible type for map index (%s)",
10897 reason.c_str());
10898 this->set_is_error();
10903 // Get the backend representation for a map index.
10905 Bexpression*
10906 Map_index_expression::do_get_backend(Translate_context* context)
10908 Map_type* type = this->get_map_type();
10909 if (type == NULL)
10911 go_assert(saw_errors());
10912 return context->backend()->error_expression();
10915 go_assert(this->value_pointer_ != NULL
10916 && this->value_pointer_->is_variable());
10918 Bexpression* ret;
10919 if (this->is_lvalue_)
10921 Expression* val =
10922 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10923 this->location());
10924 ret = val->get_backend(context);
10926 else if (this->is_in_tuple_assignment_)
10928 // Tuple_map_assignment_statement is responsible for using this
10929 // appropriately.
10930 ret = this->value_pointer_->get_backend(context);
10932 else
10934 Location loc = this->location();
10936 Expression* nil_check =
10937 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10938 Expression::make_nil(loc), loc);
10939 Bexpression* bnil_check = nil_check->get_backend(context);
10940 Expression* val =
10941 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10942 Bexpression* bval = val->get_backend(context);
10944 Gogo* gogo = context->gogo();
10945 Btype* val_btype = type->val_type()->get_backend(gogo);
10946 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10947 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10948 val_zero, bval, loc);
10950 return ret;
10953 // Get an expression for the map index. This returns an expression which
10954 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10955 // not in the map.
10957 Expression*
10958 Map_index_expression::get_value_pointer(bool insert)
10960 if (this->value_pointer_ == NULL)
10962 Map_type* type = this->get_map_type();
10963 if (type == NULL)
10965 go_assert(saw_errors());
10966 return Expression::make_error(this->location());
10969 Location loc = this->location();
10970 Expression* map_ref = this->map_;
10971 if (this->map_->type()->points_to() != NULL)
10972 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10974 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10975 loc);
10976 Expression* map_index =
10977 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10978 map_ref, index_ptr,
10979 Expression::make_boolean(insert, loc));
10981 Type* val_type = type->val_type();
10982 this->value_pointer_ =
10983 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10984 map_index, this->location());
10986 return this->value_pointer_;
10989 // Dump ast representation for a map index expression
10991 void
10992 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10993 const
10995 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10996 this->index_, NULL, NULL);
10999 // Make a map index expression.
11001 Map_index_expression*
11002 Expression::make_map_index(Expression* map, Expression* index,
11003 Location location)
11005 return new Map_index_expression(map, index, location);
11008 // Class Field_reference_expression.
11010 // Lower a field reference expression. There is nothing to lower, but
11011 // this is where we generate the tracking information for fields with
11012 // the magic go:"track" tag.
11014 Expression*
11015 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
11016 Statement_inserter* inserter, int)
11018 Struct_type* struct_type = this->expr_->type()->struct_type();
11019 if (struct_type == NULL)
11021 // Error will be reported elsewhere.
11022 return this;
11024 const Struct_field* field = struct_type->field(this->field_index_);
11025 if (field == NULL)
11026 return this;
11027 if (!field->has_tag())
11028 return this;
11029 if (field->tag().find("go:\"track\"") == std::string::npos)
11030 return this;
11032 // We have found a reference to a tracked field. Build a call to
11033 // the runtime function __go_fieldtrack with a string that describes
11034 // the field. FIXME: We should only call this once per referenced
11035 // field per function, not once for each reference to the field.
11037 if (this->called_fieldtrack_)
11038 return this;
11039 this->called_fieldtrack_ = true;
11041 Location loc = this->location();
11043 std::string s = "fieldtrack \"";
11044 Named_type* nt = this->expr_->type()->named_type();
11045 if (nt == NULL || nt->named_object()->package() == NULL)
11046 s.append(gogo->pkgpath());
11047 else
11048 s.append(nt->named_object()->package()->pkgpath());
11049 s.push_back('.');
11050 if (nt != NULL)
11051 s.append(Gogo::unpack_hidden_name(nt->name()));
11052 s.push_back('.');
11053 s.append(field->field_name());
11054 s.push_back('"');
11056 // We can't use a string here, because internally a string holds a
11057 // pointer to the actual bytes; when the linker garbage collects the
11058 // string, it won't garbage collect the bytes. So we use a
11059 // [...]byte.
11061 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
11063 Type* byte_type = gogo->lookup_global("byte")->type_value();
11064 Type* array_type = Type::make_array_type(byte_type, length_expr);
11066 Expression_list* bytes = new Expression_list();
11067 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
11069 unsigned char c = static_cast<unsigned char>(*p);
11070 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
11073 Expression* e = Expression::make_composite_literal(array_type, 0, false,
11074 bytes, false, loc);
11076 Variable* var = new Variable(array_type, e, true, false, false, loc);
11078 static int count;
11079 char buf[50];
11080 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
11081 ++count;
11083 Named_object* no = gogo->add_variable(buf, var);
11084 e = Expression::make_var_reference(no, loc);
11085 e = Expression::make_unary(OPERATOR_AND, e, loc);
11087 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
11088 inserter->insert(Statement::make_statement(call, false));
11090 // Put this function, and the global variable we just created, into
11091 // unique sections. This will permit the linker to garbage collect
11092 // them if they are not referenced. The effect is that the only
11093 // strings, indicating field references, that will wind up in the
11094 // executable will be those for functions that are actually needed.
11095 if (function != NULL)
11096 function->func_value()->set_in_unique_section();
11097 var->set_in_unique_section();
11099 return this;
11102 // Return the type of a field reference.
11104 Type*
11105 Field_reference_expression::do_type()
11107 Type* type = this->expr_->type();
11108 if (type->is_error())
11109 return type;
11110 Struct_type* struct_type = type->struct_type();
11111 go_assert(struct_type != NULL);
11112 return struct_type->field(this->field_index_)->type();
11115 // Check the types for a field reference.
11117 void
11118 Field_reference_expression::do_check_types(Gogo*)
11120 Type* type = this->expr_->type();
11121 if (type->is_error())
11122 return;
11123 Struct_type* struct_type = type->struct_type();
11124 go_assert(struct_type != NULL);
11125 go_assert(struct_type->field(this->field_index_) != NULL);
11128 // Get the backend representation for a field reference.
11130 Bexpression*
11131 Field_reference_expression::do_get_backend(Translate_context* context)
11133 Bexpression* bstruct = this->expr_->get_backend(context);
11134 return context->gogo()->backend()->struct_field_expression(bstruct,
11135 this->field_index_,
11136 this->location());
11139 // Dump ast representation for a field reference expression.
11141 void
11142 Field_reference_expression::do_dump_expression(
11143 Ast_dump_context* ast_dump_context) const
11145 this->expr_->dump_expression(ast_dump_context);
11146 ast_dump_context->ostream() << "." << this->field_index_;
11149 // Make a reference to a qualified identifier in an expression.
11151 Field_reference_expression*
11152 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11153 Location location)
11155 return new Field_reference_expression(expr, field_index, location);
11158 // Class Interface_field_reference_expression.
11160 // Return an expression for the pointer to the function to call.
11162 Expression*
11163 Interface_field_reference_expression::get_function()
11165 Expression* ref = this->expr_;
11166 Location loc = this->location();
11167 if (ref->type()->points_to() != NULL)
11168 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
11170 Expression* mtable =
11171 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11172 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11174 std::string name = Gogo::unpack_hidden_name(this->name_);
11175 unsigned int index;
11176 const Struct_field* field = mtable_type->find_local_field(name, &index);
11177 go_assert(field != NULL);
11178 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11179 return Expression::make_field_reference(mtable, index, loc);
11182 // Return an expression for the first argument to pass to the interface
11183 // function.
11185 Expression*
11186 Interface_field_reference_expression::get_underlying_object()
11188 Expression* expr = this->expr_;
11189 if (expr->type()->points_to() != NULL)
11190 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11191 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11192 this->location());
11195 // Traversal.
11198 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11200 return Expression::traverse(&this->expr_, traverse);
11203 // Lower the expression. If this expression is not called, we need to
11204 // evaluate the expression twice when converting to the backend
11205 // interface. So introduce a temporary variable if necessary.
11207 Expression*
11208 Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11209 Statement_inserter* inserter,
11210 int)
11212 if (!this->expr_->is_variable())
11214 Temporary_statement* temp =
11215 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11216 inserter->insert(temp);
11217 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11218 this->location());
11220 return this;
11223 // Return the type of an interface field reference.
11225 Type*
11226 Interface_field_reference_expression::do_type()
11228 Type* expr_type = this->expr_->type();
11230 Type* points_to = expr_type->points_to();
11231 if (points_to != NULL)
11232 expr_type = points_to;
11234 Interface_type* interface_type = expr_type->interface_type();
11235 if (interface_type == NULL)
11236 return Type::make_error_type();
11238 const Typed_identifier* method = interface_type->find_method(this->name_);
11239 if (method == NULL)
11240 return Type::make_error_type();
11242 return method->type();
11245 // Determine types.
11247 void
11248 Interface_field_reference_expression::do_determine_type(const Type_context*)
11250 this->expr_->determine_type_no_context();
11253 // Check the types for an interface field reference.
11255 void
11256 Interface_field_reference_expression::do_check_types(Gogo*)
11258 Type* type = this->expr_->type();
11260 Type* points_to = type->points_to();
11261 if (points_to != NULL)
11262 type = points_to;
11264 Interface_type* interface_type = type->interface_type();
11265 if (interface_type == NULL)
11267 if (!type->is_error_type())
11268 this->report_error(_("expected interface or pointer to interface"));
11270 else
11272 const Typed_identifier* method =
11273 interface_type->find_method(this->name_);
11274 if (method == NULL)
11276 error_at(this->location(), "method %qs not in interface",
11277 Gogo::message_name(this->name_).c_str());
11278 this->set_is_error();
11283 // If an interface field reference is not simply called, then it is
11284 // represented as a closure. The closure will hold a single variable,
11285 // the value of the interface on which the method should be called.
11286 // The function will be a simple thunk that pulls the value from the
11287 // closure and calls the method with the remaining arguments.
11289 // Because method values are not common, we don't build all thunks for
11290 // all possible interface methods, but instead only build them as we
11291 // need them. In particular, we even build them on demand for
11292 // interface methods defined in other packages.
11294 Interface_field_reference_expression::Interface_method_thunks
11295 Interface_field_reference_expression::interface_method_thunks;
11297 // Find or create the thunk to call method NAME on TYPE.
11299 Named_object*
11300 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11301 Interface_type* type,
11302 const std::string& name)
11304 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11305 std::pair<Interface_method_thunks::iterator, bool> ins =
11306 Interface_field_reference_expression::interface_method_thunks.insert(val);
11307 if (ins.second)
11309 // This is the first time we have seen this interface.
11310 ins.first->second = new Method_thunks();
11313 for (Method_thunks::const_iterator p = ins.first->second->begin();
11314 p != ins.first->second->end();
11315 p++)
11316 if (p->first == name)
11317 return p->second;
11319 Location loc = type->location();
11321 const Typed_identifier* method_id = type->find_method(name);
11322 if (method_id == NULL)
11323 return Named_object::make_erroneous_name(Gogo::thunk_name());
11325 Function_type* orig_fntype = method_id->type()->function_type();
11326 if (orig_fntype == NULL)
11327 return Named_object::make_erroneous_name(Gogo::thunk_name());
11329 Struct_field_list* sfl = new Struct_field_list();
11330 // The type here is wrong--it should be the C function type. But it
11331 // doesn't really matter.
11332 Type* vt = Type::make_pointer_type(Type::make_void_type());
11333 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11334 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11335 Type* closure_type = Type::make_struct_type(sfl, loc);
11336 closure_type = Type::make_pointer_type(closure_type);
11338 Function_type* new_fntype = orig_fntype->copy_with_names();
11340 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11341 false, loc);
11343 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11344 cvar->set_is_used();
11345 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11346 new_no->func_value()->set_closure_var(cp);
11348 gogo->start_block(loc);
11350 // Field 0 of the closure is the function code pointer, field 1 is
11351 // the value on which to invoke the method.
11352 Expression* arg = Expression::make_var_reference(cp, loc);
11353 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11354 arg = Expression::make_field_reference(arg, 1, loc);
11356 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11357 loc);
11359 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11360 Expression_list* args;
11361 if (orig_params == NULL || orig_params->empty())
11362 args = NULL;
11363 else
11365 const Typed_identifier_list* new_params = new_fntype->parameters();
11366 args = new Expression_list();
11367 for (Typed_identifier_list::const_iterator p = new_params->begin();
11368 p != new_params->end();
11369 ++p)
11371 Named_object* p_no = gogo->lookup(p->name(), NULL);
11372 go_assert(p_no != NULL
11373 && p_no->is_variable()
11374 && p_no->var_value()->is_parameter());
11375 args->push_back(Expression::make_var_reference(p_no, loc));
11379 Call_expression* call = Expression::make_call(ifre, args,
11380 orig_fntype->is_varargs(),
11381 loc);
11382 call->set_varargs_are_lowered();
11384 Statement* s = Statement::make_return_from_call(call, loc);
11385 gogo->add_statement(s);
11386 Block* b = gogo->finish_block(loc);
11387 gogo->add_block(b, loc);
11388 gogo->lower_block(new_no, b);
11389 gogo->flatten_block(new_no, b);
11390 gogo->finish_function(loc);
11392 ins.first->second->push_back(std::make_pair(name, new_no));
11393 return new_no;
11396 // Get the backend representation for a method value.
11398 Bexpression*
11399 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11401 Interface_type* type = this->expr_->type()->interface_type();
11402 if (type == NULL)
11404 go_assert(saw_errors());
11405 return context->backend()->error_expression();
11408 Named_object* thunk =
11409 Interface_field_reference_expression::create_thunk(context->gogo(),
11410 type, this->name_);
11411 if (thunk->is_erroneous())
11413 go_assert(saw_errors());
11414 return context->backend()->error_expression();
11417 // FIXME: We should lower this earlier, but we can't it lower it in
11418 // the lowering pass because at that point we don't know whether we
11419 // need to create the thunk or not. If the expression is called, we
11420 // don't need the thunk.
11422 Location loc = this->location();
11424 Struct_field_list* fields = new Struct_field_list();
11425 fields->push_back(Struct_field(Typed_identifier("fn.0",
11426 thunk->func_value()->type(),
11427 loc)));
11428 fields->push_back(Struct_field(Typed_identifier("val.1",
11429 this->expr_->type(),
11430 loc)));
11431 Struct_type* st = Type::make_struct_type(fields, loc);
11433 Expression_list* vals = new Expression_list();
11434 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11435 vals->push_back(this->expr_);
11437 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11438 Bexpression* bclosure =
11439 Expression::make_heap_expression(expr, loc)->get_backend(context);
11441 Expression* nil_check =
11442 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11443 Expression::make_nil(loc), loc);
11444 Bexpression* bnil_check = nil_check->get_backend(context);
11446 Gogo* gogo = context->gogo();
11447 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11448 loc)->get_backend(context);
11450 Bexpression* bcond =
11451 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11452 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11453 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11456 // Dump ast representation for an interface field reference.
11458 void
11459 Interface_field_reference_expression::do_dump_expression(
11460 Ast_dump_context* ast_dump_context) const
11462 this->expr_->dump_expression(ast_dump_context);
11463 ast_dump_context->ostream() << "." << this->name_;
11466 // Make a reference to a field in an interface.
11468 Expression*
11469 Expression::make_interface_field_reference(Expression* expr,
11470 const std::string& field,
11471 Location location)
11473 return new Interface_field_reference_expression(expr, field, location);
11476 // A general selector. This is a Parser_expression for LEFT.NAME. It
11477 // is lowered after we know the type of the left hand side.
11479 class Selector_expression : public Parser_expression
11481 public:
11482 Selector_expression(Expression* left, const std::string& name,
11483 Location location)
11484 : Parser_expression(EXPRESSION_SELECTOR, location),
11485 left_(left), name_(name)
11488 protected:
11490 do_traverse(Traverse* traverse)
11491 { return Expression::traverse(&this->left_, traverse); }
11493 Expression*
11494 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11496 Expression*
11497 do_copy()
11499 return new Selector_expression(this->left_->copy(), this->name_,
11500 this->location());
11503 void
11504 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11506 private:
11507 Expression*
11508 lower_method_expression(Gogo*);
11510 // The expression on the left hand side.
11511 Expression* left_;
11512 // The name on the right hand side.
11513 std::string name_;
11516 // Lower a selector expression once we know the real type of the left
11517 // hand side.
11519 Expression*
11520 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11521 int)
11523 Expression* left = this->left_;
11524 if (left->is_type_expression())
11525 return this->lower_method_expression(gogo);
11526 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11527 this->location());
11530 // Lower a method expression T.M or (*T).M. We turn this into a
11531 // function literal.
11533 Expression*
11534 Selector_expression::lower_method_expression(Gogo* gogo)
11536 Location location = this->location();
11537 Type* type = this->left_->type();
11538 const std::string& name(this->name_);
11540 bool is_pointer;
11541 if (type->points_to() == NULL)
11542 is_pointer = false;
11543 else
11545 is_pointer = true;
11546 type = type->points_to();
11548 Named_type* nt = type->named_type();
11549 if (nt == NULL)
11551 error_at(location,
11552 ("method expression requires named type or "
11553 "pointer to named type"));
11554 return Expression::make_error(location);
11557 bool is_ambiguous;
11558 Method* method = nt->method_function(name, &is_ambiguous);
11559 const Typed_identifier* imethod = NULL;
11560 if (method == NULL && !is_pointer)
11562 Interface_type* it = nt->interface_type();
11563 if (it != NULL)
11564 imethod = it->find_method(name);
11567 if (method == NULL && imethod == NULL)
11569 if (!is_ambiguous)
11570 error_at(location, "type %<%s%s%> has no method %<%s%>",
11571 is_pointer ? "*" : "",
11572 nt->message_name().c_str(),
11573 Gogo::message_name(name).c_str());
11574 else
11575 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11576 Gogo::message_name(name).c_str(),
11577 is_pointer ? "*" : "",
11578 nt->message_name().c_str());
11579 return Expression::make_error(location);
11582 if (method != NULL && !is_pointer && !method->is_value_method())
11584 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11585 nt->message_name().c_str(),
11586 Gogo::message_name(name).c_str());
11587 return Expression::make_error(location);
11590 // Build a new function type in which the receiver becomes the first
11591 // argument.
11592 Function_type* method_type;
11593 if (method != NULL)
11595 method_type = method->type();
11596 go_assert(method_type->is_method());
11598 else
11600 method_type = imethod->type()->function_type();
11601 go_assert(method_type != NULL && !method_type->is_method());
11604 const char* const receiver_name = "$this";
11605 Typed_identifier_list* parameters = new Typed_identifier_list();
11606 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11607 location));
11609 const Typed_identifier_list* method_parameters = method_type->parameters();
11610 if (method_parameters != NULL)
11612 int i = 0;
11613 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11614 p != method_parameters->end();
11615 ++p, ++i)
11617 if (!p->name().empty())
11618 parameters->push_back(*p);
11619 else
11621 char buf[20];
11622 snprintf(buf, sizeof buf, "$param%d", i);
11623 parameters->push_back(Typed_identifier(buf, p->type(),
11624 p->location()));
11629 const Typed_identifier_list* method_results = method_type->results();
11630 Typed_identifier_list* results;
11631 if (method_results == NULL)
11632 results = NULL;
11633 else
11635 results = new Typed_identifier_list();
11636 for (Typed_identifier_list::const_iterator p = method_results->begin();
11637 p != method_results->end();
11638 ++p)
11639 results->push_back(*p);
11642 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11643 location);
11644 if (method_type->is_varargs())
11645 fntype->set_is_varargs();
11647 // We generate methods which always takes a pointer to the receiver
11648 // as their first argument. If this is for a pointer type, we can
11649 // simply reuse the existing function. We use an internal hack to
11650 // get the right type.
11651 // FIXME: This optimization is disabled because it doesn't yet work
11652 // with function descriptors when the method expression is not
11653 // directly called.
11654 if (method != NULL && is_pointer && false)
11656 Named_object* mno = (method->needs_stub_method()
11657 ? method->stub_object()
11658 : method->named_object());
11659 Expression* f = Expression::make_func_reference(mno, NULL, location);
11660 f = Expression::make_cast(fntype, f, location);
11661 Type_conversion_expression* tce =
11662 static_cast<Type_conversion_expression*>(f);
11663 tce->set_may_convert_function_types();
11664 return f;
11667 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11668 location);
11670 Named_object* vno = gogo->lookup(receiver_name, NULL);
11671 go_assert(vno != NULL);
11672 Expression* ve = Expression::make_var_reference(vno, location);
11673 Expression* bm;
11674 if (method != NULL)
11675 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11676 else
11677 bm = Expression::make_interface_field_reference(ve, name, location);
11679 // Even though we found the method above, if it has an error type we
11680 // may see an error here.
11681 if (bm->is_error_expression())
11683 gogo->finish_function(location);
11684 return bm;
11687 Expression_list* args;
11688 if (parameters->size() <= 1)
11689 args = NULL;
11690 else
11692 args = new Expression_list();
11693 Typed_identifier_list::const_iterator p = parameters->begin();
11694 ++p;
11695 for (; p != parameters->end(); ++p)
11697 vno = gogo->lookup(p->name(), NULL);
11698 go_assert(vno != NULL);
11699 args->push_back(Expression::make_var_reference(vno, location));
11703 gogo->start_block(location);
11705 Call_expression* call = Expression::make_call(bm, args,
11706 method_type->is_varargs(),
11707 location);
11709 Statement* s = Statement::make_return_from_call(call, location);
11710 gogo->add_statement(s);
11712 Block* b = gogo->finish_block(location);
11714 gogo->add_block(b, location);
11716 // Lower the call in case there are multiple results.
11717 gogo->lower_block(no, b);
11718 gogo->flatten_block(no, b);
11720 gogo->finish_function(location);
11722 return Expression::make_func_reference(no, NULL, location);
11725 // Dump the ast for a selector expression.
11727 void
11728 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11729 const
11731 ast_dump_context->dump_expression(this->left_);
11732 ast_dump_context->ostream() << ".";
11733 ast_dump_context->ostream() << this->name_;
11736 // Make a selector expression.
11738 Expression*
11739 Expression::make_selector(Expression* left, const std::string& name,
11740 Location location)
11742 return new Selector_expression(left, name, location);
11745 // Implement the builtin function new.
11747 class Allocation_expression : public Expression
11749 public:
11750 Allocation_expression(Type* type, Location location)
11751 : Expression(EXPRESSION_ALLOCATION, location),
11752 type_(type)
11755 protected:
11757 do_traverse(Traverse* traverse)
11758 { return Type::traverse(this->type_, traverse); }
11760 Type*
11761 do_type()
11762 { return Type::make_pointer_type(this->type_); }
11764 void
11765 do_determine_type(const Type_context*)
11768 Expression*
11769 do_copy()
11770 { return new Allocation_expression(this->type_, this->location()); }
11772 Bexpression*
11773 do_get_backend(Translate_context*);
11775 void
11776 do_dump_expression(Ast_dump_context*) const;
11778 private:
11779 // The type we are allocating.
11780 Type* type_;
11783 // Return the backend representation for an allocation expression.
11785 Bexpression*
11786 Allocation_expression::do_get_backend(Translate_context* context)
11788 Gogo* gogo = context->gogo();
11789 Location loc = this->location();
11790 Bexpression* space =
11791 gogo->allocate_memory(this->type_, loc)->get_backend(context);
11792 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11793 return gogo->backend()->convert_expression(pbtype, space, loc);
11796 // Dump ast representation for an allocation expression.
11798 void
11799 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11800 const
11802 ast_dump_context->ostream() << "new(";
11803 ast_dump_context->dump_type(this->type_);
11804 ast_dump_context->ostream() << ")";
11807 // Make an allocation expression.
11809 Expression*
11810 Expression::make_allocation(Type* type, Location location)
11812 return new Allocation_expression(type, location);
11815 // Construct a struct.
11817 class Struct_construction_expression : public Expression
11819 public:
11820 Struct_construction_expression(Type* type, Expression_list* vals,
11821 Location location)
11822 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11823 type_(type), vals_(vals), traverse_order_(NULL)
11826 // Set the traversal order, used to ensure that we implement the
11827 // order of evaluation rules. Takes ownership of the argument.
11828 void
11829 set_traverse_order(std::vector<int>* traverse_order)
11830 { this->traverse_order_ = traverse_order; }
11832 // Return whether this is a constant initializer.
11833 bool
11834 is_constant_struct() const;
11836 protected:
11838 do_traverse(Traverse* traverse);
11840 bool
11841 do_is_immutable() const;
11843 Type*
11844 do_type()
11845 { return this->type_; }
11847 void
11848 do_determine_type(const Type_context*);
11850 void
11851 do_check_types(Gogo*);
11853 Expression*
11854 do_copy()
11856 Struct_construction_expression* ret =
11857 new Struct_construction_expression(this->type_, this->vals_->copy(),
11858 this->location());
11859 if (this->traverse_order_ != NULL)
11860 ret->set_traverse_order(this->traverse_order_);
11861 return ret;
11864 Bexpression*
11865 do_get_backend(Translate_context*);
11867 void
11868 do_export(Export*) const;
11870 void
11871 do_dump_expression(Ast_dump_context*) const;
11873 private:
11874 // The type of the struct to construct.
11875 Type* type_;
11876 // The list of values, in order of the fields in the struct. A NULL
11877 // entry means that the field should be zero-initialized.
11878 Expression_list* vals_;
11879 // If not NULL, the order in which to traverse vals_. This is used
11880 // so that we implement the order of evaluation rules correctly.
11881 std::vector<int>* traverse_order_;
11884 // Traversal.
11887 Struct_construction_expression::do_traverse(Traverse* traverse)
11889 if (this->vals_ != NULL)
11891 if (this->traverse_order_ == NULL)
11893 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11894 return TRAVERSE_EXIT;
11896 else
11898 for (std::vector<int>::const_iterator p =
11899 this->traverse_order_->begin();
11900 p != this->traverse_order_->end();
11901 ++p)
11903 if (Expression::traverse(&this->vals_->at(*p), traverse)
11904 == TRAVERSE_EXIT)
11905 return TRAVERSE_EXIT;
11909 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11910 return TRAVERSE_EXIT;
11911 return TRAVERSE_CONTINUE;
11914 // Return whether this is a constant initializer.
11916 bool
11917 Struct_construction_expression::is_constant_struct() const
11919 if (this->vals_ == NULL)
11920 return true;
11921 for (Expression_list::const_iterator pv = this->vals_->begin();
11922 pv != this->vals_->end();
11923 ++pv)
11925 if (*pv != NULL
11926 && !(*pv)->is_constant()
11927 && (!(*pv)->is_composite_literal()
11928 || (*pv)->is_nonconstant_composite_literal()))
11929 return false;
11932 const Struct_field_list* fields = this->type_->struct_type()->fields();
11933 for (Struct_field_list::const_iterator pf = fields->begin();
11934 pf != fields->end();
11935 ++pf)
11937 // There are no constant constructors for interfaces.
11938 if (pf->type()->interface_type() != NULL)
11939 return false;
11942 return true;
11945 // Return whether this struct is immutable.
11947 bool
11948 Struct_construction_expression::do_is_immutable() const
11950 if (this->vals_ == NULL)
11951 return true;
11952 for (Expression_list::const_iterator pv = this->vals_->begin();
11953 pv != this->vals_->end();
11954 ++pv)
11956 if (*pv != NULL && !(*pv)->is_immutable())
11957 return false;
11959 return true;
11962 // Final type determination.
11964 void
11965 Struct_construction_expression::do_determine_type(const Type_context*)
11967 if (this->vals_ == NULL)
11968 return;
11969 const Struct_field_list* fields = this->type_->struct_type()->fields();
11970 Expression_list::const_iterator pv = this->vals_->begin();
11971 for (Struct_field_list::const_iterator pf = fields->begin();
11972 pf != fields->end();
11973 ++pf, ++pv)
11975 if (pv == this->vals_->end())
11976 return;
11977 if (*pv != NULL)
11979 Type_context subcontext(pf->type(), false);
11980 (*pv)->determine_type(&subcontext);
11983 // Extra values are an error we will report elsewhere; we still want
11984 // to determine the type to avoid knockon errors.
11985 for (; pv != this->vals_->end(); ++pv)
11986 (*pv)->determine_type_no_context();
11989 // Check types.
11991 void
11992 Struct_construction_expression::do_check_types(Gogo*)
11994 if (this->vals_ == NULL)
11995 return;
11997 Struct_type* st = this->type_->struct_type();
11998 if (this->vals_->size() > st->field_count())
12000 this->report_error(_("too many expressions for struct"));
12001 return;
12004 const Struct_field_list* fields = st->fields();
12005 Expression_list::const_iterator pv = this->vals_->begin();
12006 int i = 0;
12007 for (Struct_field_list::const_iterator pf = fields->begin();
12008 pf != fields->end();
12009 ++pf, ++pv, ++i)
12011 if (pv == this->vals_->end())
12013 this->report_error(_("too few expressions for struct"));
12014 break;
12017 if (*pv == NULL)
12018 continue;
12020 std::string reason;
12021 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
12023 if (reason.empty())
12024 error_at((*pv)->location(),
12025 "incompatible type for field %d in struct construction",
12026 i + 1);
12027 else
12028 error_at((*pv)->location(),
12029 ("incompatible type for field %d in "
12030 "struct construction (%s)"),
12031 i + 1, reason.c_str());
12032 this->set_is_error();
12035 go_assert(pv == this->vals_->end());
12038 // Return the backend representation for constructing a struct.
12040 Bexpression*
12041 Struct_construction_expression::do_get_backend(Translate_context* context)
12043 Gogo* gogo = context->gogo();
12045 Btype* btype = this->type_->get_backend(gogo);
12046 if (this->vals_ == NULL)
12047 return gogo->backend()->zero_expression(btype);
12049 const Struct_field_list* fields = this->type_->struct_type()->fields();
12050 Expression_list::const_iterator pv = this->vals_->begin();
12051 std::vector<Bexpression*> init;
12052 for (Struct_field_list::const_iterator pf = fields->begin();
12053 pf != fields->end();
12054 ++pf)
12056 Btype* fbtype = pf->type()->get_backend(gogo);
12057 if (pv == this->vals_->end())
12058 init.push_back(gogo->backend()->zero_expression(fbtype));
12059 else if (*pv == NULL)
12061 init.push_back(gogo->backend()->zero_expression(fbtype));
12062 ++pv;
12064 else
12066 Expression* val =
12067 Expression::convert_for_assignment(gogo, pf->type(),
12068 *pv, this->location());
12069 init.push_back(val->get_backend(context));
12070 ++pv;
12073 return gogo->backend()->constructor_expression(btype, init, this->location());
12076 // Export a struct construction.
12078 void
12079 Struct_construction_expression::do_export(Export* exp) const
12081 exp->write_c_string("convert(");
12082 exp->write_type(this->type_);
12083 for (Expression_list::const_iterator pv = this->vals_->begin();
12084 pv != this->vals_->end();
12085 ++pv)
12087 exp->write_c_string(", ");
12088 if (*pv != NULL)
12089 (*pv)->export_expression(exp);
12091 exp->write_c_string(")");
12094 // Dump ast representation of a struct construction expression.
12096 void
12097 Struct_construction_expression::do_dump_expression(
12098 Ast_dump_context* ast_dump_context) const
12100 ast_dump_context->dump_type(this->type_);
12101 ast_dump_context->ostream() << "{";
12102 ast_dump_context->dump_expression_list(this->vals_);
12103 ast_dump_context->ostream() << "}";
12106 // Make a struct composite literal. This used by the thunk code.
12108 Expression*
12109 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12110 Location location)
12112 go_assert(type->struct_type() != NULL);
12113 return new Struct_construction_expression(type, vals, location);
12116 // Construct an array. This class is not used directly; instead we
12117 // use the child classes, Fixed_array_construction_expression and
12118 // Slice_construction_expression.
12120 class Array_construction_expression : public Expression
12122 protected:
12123 Array_construction_expression(Expression_classification classification,
12124 Type* type,
12125 const std::vector<unsigned long>* indexes,
12126 Expression_list* vals, Location location)
12127 : Expression(classification, location),
12128 type_(type), indexes_(indexes), vals_(vals)
12129 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
12131 public:
12132 // Return whether this is a constant initializer.
12133 bool
12134 is_constant_array() const;
12136 // Return the number of elements.
12137 size_t
12138 element_count() const
12139 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12141 protected:
12142 virtual int
12143 do_traverse(Traverse* traverse);
12145 bool
12146 do_is_immutable() const;
12148 Type*
12149 do_type()
12150 { return this->type_; }
12152 void
12153 do_determine_type(const Type_context*);
12155 void
12156 do_check_types(Gogo*);
12158 void
12159 do_export(Export*) const;
12161 // The indexes.
12162 const std::vector<unsigned long>*
12163 indexes()
12164 { return this->indexes_; }
12166 // The list of values.
12167 Expression_list*
12168 vals()
12169 { return this->vals_; }
12171 // Get the backend constructor for the array values.
12172 Bexpression*
12173 get_constructor(Translate_context* context, Btype* btype);
12175 void
12176 do_dump_expression(Ast_dump_context*) const;
12178 private:
12179 // The type of the array to construct.
12180 Type* type_;
12181 // The list of indexes into the array, one for each value. This may
12182 // be NULL, in which case the indexes start at zero and increment.
12183 const std::vector<unsigned long>* indexes_;
12184 // The list of values. This may be NULL if there are no values.
12185 Expression_list* vals_;
12188 // Traversal.
12191 Array_construction_expression::do_traverse(Traverse* traverse)
12193 if (this->vals_ != NULL
12194 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12195 return TRAVERSE_EXIT;
12196 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12197 return TRAVERSE_EXIT;
12198 return TRAVERSE_CONTINUE;
12201 // Return whether this is a constant initializer.
12203 bool
12204 Array_construction_expression::is_constant_array() const
12206 if (this->vals_ == NULL)
12207 return true;
12209 // There are no constant constructors for interfaces.
12210 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12211 return false;
12213 for (Expression_list::const_iterator pv = this->vals_->begin();
12214 pv != this->vals_->end();
12215 ++pv)
12217 if (*pv != NULL
12218 && !(*pv)->is_constant()
12219 && (!(*pv)->is_composite_literal()
12220 || (*pv)->is_nonconstant_composite_literal()))
12221 return false;
12223 return true;
12226 // Return whether this is an immutable array initializer.
12228 bool
12229 Array_construction_expression::do_is_immutable() const
12231 if (this->vals_ == NULL)
12232 return true;
12233 for (Expression_list::const_iterator pv = this->vals_->begin();
12234 pv != this->vals_->end();
12235 ++pv)
12237 if (*pv != NULL && !(*pv)->is_immutable())
12238 return false;
12240 return true;
12243 // Final type determination.
12245 void
12246 Array_construction_expression::do_determine_type(const Type_context*)
12248 if (this->vals_ == NULL)
12249 return;
12250 Type_context subcontext(this->type_->array_type()->element_type(), false);
12251 for (Expression_list::const_iterator pv = this->vals_->begin();
12252 pv != this->vals_->end();
12253 ++pv)
12255 if (*pv != NULL)
12256 (*pv)->determine_type(&subcontext);
12260 // Check types.
12262 void
12263 Array_construction_expression::do_check_types(Gogo*)
12265 if (this->vals_ == NULL)
12266 return;
12268 Array_type* at = this->type_->array_type();
12269 int i = 0;
12270 Type* element_type = at->element_type();
12271 for (Expression_list::const_iterator pv = this->vals_->begin();
12272 pv != this->vals_->end();
12273 ++pv, ++i)
12275 if (*pv != NULL
12276 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12278 error_at((*pv)->location(),
12279 "incompatible type for element %d in composite literal",
12280 i + 1);
12281 this->set_is_error();
12286 // Get a constructor expression for the array values.
12288 Bexpression*
12289 Array_construction_expression::get_constructor(Translate_context* context,
12290 Btype* array_btype)
12292 Type* element_type = this->type_->array_type()->element_type();
12294 std::vector<unsigned long> indexes;
12295 std::vector<Bexpression*> vals;
12296 Gogo* gogo = context->gogo();
12297 if (this->vals_ != NULL)
12299 size_t i = 0;
12300 std::vector<unsigned long>::const_iterator pi;
12301 if (this->indexes_ != NULL)
12302 pi = this->indexes_->begin();
12303 for (Expression_list::const_iterator pv = this->vals_->begin();
12304 pv != this->vals_->end();
12305 ++pv, ++i)
12307 if (this->indexes_ != NULL)
12308 go_assert(pi != this->indexes_->end());
12310 if (this->indexes_ == NULL)
12311 indexes.push_back(i);
12312 else
12313 indexes.push_back(*pi);
12314 if (*pv == NULL)
12316 Btype* ebtype = element_type->get_backend(gogo);
12317 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12318 vals.push_back(zv);
12320 else
12322 Expression* val_expr =
12323 Expression::convert_for_assignment(gogo, element_type, *pv,
12324 this->location());
12325 vals.push_back(val_expr->get_backend(context));
12327 if (this->indexes_ != NULL)
12328 ++pi;
12330 if (this->indexes_ != NULL)
12331 go_assert(pi == this->indexes_->end());
12333 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12334 vals, this->location());
12337 // Export an array construction.
12339 void
12340 Array_construction_expression::do_export(Export* exp) const
12342 exp->write_c_string("convert(");
12343 exp->write_type(this->type_);
12344 if (this->vals_ != NULL)
12346 std::vector<unsigned long>::const_iterator pi;
12347 if (this->indexes_ != NULL)
12348 pi = this->indexes_->begin();
12349 for (Expression_list::const_iterator pv = this->vals_->begin();
12350 pv != this->vals_->end();
12351 ++pv)
12353 exp->write_c_string(", ");
12355 if (this->indexes_ != NULL)
12357 char buf[100];
12358 snprintf(buf, sizeof buf, "%lu", *pi);
12359 exp->write_c_string(buf);
12360 exp->write_c_string(":");
12363 if (*pv != NULL)
12364 (*pv)->export_expression(exp);
12366 if (this->indexes_ != NULL)
12367 ++pi;
12370 exp->write_c_string(")");
12373 // Dump ast representation of an array construction expressin.
12375 void
12376 Array_construction_expression::do_dump_expression(
12377 Ast_dump_context* ast_dump_context) const
12379 Expression* length = this->type_->array_type()->length();
12381 ast_dump_context->ostream() << "[" ;
12382 if (length != NULL)
12384 ast_dump_context->dump_expression(length);
12386 ast_dump_context->ostream() << "]" ;
12387 ast_dump_context->dump_type(this->type_);
12388 ast_dump_context->ostream() << "{" ;
12389 if (this->indexes_ == NULL)
12390 ast_dump_context->dump_expression_list(this->vals_);
12391 else
12393 Expression_list::const_iterator pv = this->vals_->begin();
12394 for (std::vector<unsigned long>::const_iterator pi =
12395 this->indexes_->begin();
12396 pi != this->indexes_->end();
12397 ++pi, ++pv)
12399 if (pi != this->indexes_->begin())
12400 ast_dump_context->ostream() << ", ";
12401 ast_dump_context->ostream() << *pi << ':';
12402 ast_dump_context->dump_expression(*pv);
12405 ast_dump_context->ostream() << "}" ;
12409 // Construct a fixed array.
12411 class Fixed_array_construction_expression :
12412 public Array_construction_expression
12414 public:
12415 Fixed_array_construction_expression(Type* type,
12416 const std::vector<unsigned long>* indexes,
12417 Expression_list* vals, Location location)
12418 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12419 type, indexes, vals, location)
12420 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12422 protected:
12423 Expression*
12424 do_copy()
12426 return new Fixed_array_construction_expression(this->type(),
12427 this->indexes(),
12428 (this->vals() == NULL
12429 ? NULL
12430 : this->vals()->copy()),
12431 this->location());
12434 Bexpression*
12435 do_get_backend(Translate_context*);
12438 // Return the backend representation for constructing a fixed array.
12440 Bexpression*
12441 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
12443 Type* type = this->type();
12444 Btype* btype = type->get_backend(context->gogo());
12445 return this->get_constructor(context, btype);
12448 Expression*
12449 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12450 Location location)
12452 go_assert(type->array_type() != NULL && !type->is_slice_type());
12453 return new Fixed_array_construction_expression(type, NULL, vals, location);
12456 // Construct a slice.
12458 class Slice_construction_expression : public Array_construction_expression
12460 public:
12461 Slice_construction_expression(Type* type,
12462 const std::vector<unsigned long>* indexes,
12463 Expression_list* vals, Location location)
12464 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12465 type, indexes, vals, location),
12466 valtype_(NULL)
12468 go_assert(type->is_slice_type());
12470 unsigned long lenval;
12471 Expression* length;
12472 if (vals == NULL || vals->empty())
12473 lenval = 0;
12474 else
12476 if (this->indexes() == NULL)
12477 lenval = vals->size();
12478 else
12479 lenval = indexes->back() + 1;
12481 Type* int_type = Type::lookup_integer_type("int");
12482 length = Expression::make_integer_ul(lenval, int_type, location);
12483 Type* element_type = type->array_type()->element_type();
12484 this->valtype_ = Type::make_array_type(element_type, length);
12487 protected:
12488 // Note that taking the address of a slice literal is invalid.
12491 do_traverse(Traverse* traverse);
12493 Expression*
12494 do_copy()
12496 return new Slice_construction_expression(this->type(), this->indexes(),
12497 (this->vals() == NULL
12498 ? NULL
12499 : this->vals()->copy()),
12500 this->location());
12503 Bexpression*
12504 do_get_backend(Translate_context*);
12506 private:
12507 // The type of the values in this slice.
12508 Type* valtype_;
12511 // Traversal.
12514 Slice_construction_expression::do_traverse(Traverse* traverse)
12516 if (this->Array_construction_expression::do_traverse(traverse)
12517 == TRAVERSE_EXIT)
12518 return TRAVERSE_EXIT;
12519 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12520 return TRAVERSE_EXIT;
12521 return TRAVERSE_CONTINUE;
12524 // Return the backend representation for constructing a slice.
12526 Bexpression*
12527 Slice_construction_expression::do_get_backend(Translate_context* context)
12529 Array_type* array_type = this->type()->array_type();
12530 if (array_type == NULL)
12532 go_assert(this->type()->is_error());
12533 return context->backend()->error_expression();
12536 Location loc = this->location();
12537 Type* element_type = array_type->element_type();
12538 go_assert(this->valtype_ != NULL);
12540 Expression_list* vals = this->vals();
12541 if (this->vals() == NULL || this->vals()->empty())
12543 // We need to create a unique value for the empty array literal.
12544 vals = new Expression_list;
12545 vals->push_back(NULL);
12547 Expression* array_val =
12548 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12549 vals, loc);
12551 bool is_constant_initializer = array_val->is_immutable();
12553 // We have to copy the initial values into heap memory if we are in
12554 // a function or if the values are not constants. We also have to
12555 // copy them if they may contain pointers in a non-constant context,
12556 // as otherwise the garbage collector won't see them.
12557 bool copy_to_heap = (context->function() != NULL
12558 || !is_constant_initializer
12559 || (element_type->has_pointer()
12560 && !context->is_const()));
12562 Expression* space;
12563 if (!copy_to_heap)
12565 // The initializer will only run once.
12566 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12567 space->unary_expression()->set_is_slice_init();
12569 else
12570 space = Expression::make_heap_expression(array_val, loc);
12572 // Build a constructor for the slice.
12574 Expression* len = this->valtype_->array_type()->length();
12575 Expression* slice_val =
12576 Expression::make_slice_value(this->type(), space, len, len, loc);
12577 return slice_val->get_backend(context);
12580 // Make a slice composite literal. This is used by the type
12581 // descriptor code.
12583 Expression*
12584 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12585 Location location)
12587 go_assert(type->is_slice_type());
12588 return new Slice_construction_expression(type, NULL, vals, location);
12591 // Construct a map.
12593 class Map_construction_expression : public Expression
12595 public:
12596 Map_construction_expression(Type* type, Expression_list* vals,
12597 Location location)
12598 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
12599 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
12600 { go_assert(vals == NULL || vals->size() % 2 == 0); }
12602 protected:
12604 do_traverse(Traverse* traverse);
12606 Expression*
12607 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12609 Type*
12610 do_type()
12611 { return this->type_; }
12613 void
12614 do_determine_type(const Type_context*);
12616 void
12617 do_check_types(Gogo*);
12619 Expression*
12620 do_copy()
12622 return new Map_construction_expression(this->type_, this->vals_->copy(),
12623 this->location());
12626 Bexpression*
12627 do_get_backend(Translate_context*);
12629 void
12630 do_export(Export*) const;
12632 void
12633 do_dump_expression(Ast_dump_context*) const;
12635 private:
12636 // The type of the map to construct.
12637 Type* type_;
12638 // The list of values.
12639 Expression_list* vals_;
12640 // The type of the key-value pair struct for each map element.
12641 Struct_type* element_type_;
12642 // A temporary reference to the variable storing the constructor initializer.
12643 Temporary_statement* constructor_temp_;
12646 // Traversal.
12649 Map_construction_expression::do_traverse(Traverse* traverse)
12651 if (this->vals_ != NULL
12652 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12653 return TRAVERSE_EXIT;
12654 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12655 return TRAVERSE_EXIT;
12656 return TRAVERSE_CONTINUE;
12659 // Flatten constructor initializer into a temporary variable since
12660 // we need to take its address for __go_construct_map.
12662 Expression*
12663 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12664 Statement_inserter* inserter)
12666 if (!this->is_error_expression()
12667 && this->vals_ != NULL
12668 && !this->vals_->empty()
12669 && this->constructor_temp_ == NULL)
12671 Map_type* mt = this->type_->map_type();
12672 Type* key_type = mt->key_type();
12673 Type* val_type = mt->val_type();
12674 this->element_type_ = Type::make_builtin_struct_type(2,
12675 "__key", key_type,
12676 "__val", val_type);
12678 Expression_list* value_pairs = new Expression_list();
12679 Location loc = this->location();
12681 size_t i = 0;
12682 for (Expression_list::const_iterator pv = this->vals_->begin();
12683 pv != this->vals_->end();
12684 ++pv, ++i)
12686 Expression_list* key_value_pair = new Expression_list();
12687 Expression* key =
12688 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12690 ++pv;
12691 Expression* val =
12692 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12694 key_value_pair->push_back(key);
12695 key_value_pair->push_back(val);
12696 value_pairs->push_back(
12697 Expression::make_struct_composite_literal(this->element_type_,
12698 key_value_pair, loc));
12701 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
12702 Type* ctor_type =
12703 Type::make_array_type(this->element_type_, element_count);
12704 Expression* constructor =
12705 new Fixed_array_construction_expression(ctor_type, NULL,
12706 value_pairs, loc);
12708 this->constructor_temp_ =
12709 Statement::make_temporary(NULL, constructor, loc);
12710 constructor->issue_nil_check();
12711 this->constructor_temp_->set_is_address_taken();
12712 inserter->insert(this->constructor_temp_);
12715 return this;
12718 // Final type determination.
12720 void
12721 Map_construction_expression::do_determine_type(const Type_context*)
12723 if (this->vals_ == NULL)
12724 return;
12726 Map_type* mt = this->type_->map_type();
12727 Type_context key_context(mt->key_type(), false);
12728 Type_context val_context(mt->val_type(), false);
12729 for (Expression_list::const_iterator pv = this->vals_->begin();
12730 pv != this->vals_->end();
12731 ++pv)
12733 (*pv)->determine_type(&key_context);
12734 ++pv;
12735 (*pv)->determine_type(&val_context);
12739 // Check types.
12741 void
12742 Map_construction_expression::do_check_types(Gogo*)
12744 if (this->vals_ == NULL)
12745 return;
12747 Map_type* mt = this->type_->map_type();
12748 int i = 0;
12749 Type* key_type = mt->key_type();
12750 Type* val_type = mt->val_type();
12751 for (Expression_list::const_iterator pv = this->vals_->begin();
12752 pv != this->vals_->end();
12753 ++pv, ++i)
12755 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12757 error_at((*pv)->location(),
12758 "incompatible type for element %d key in map construction",
12759 i + 1);
12760 this->set_is_error();
12762 ++pv;
12763 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12765 error_at((*pv)->location(),
12766 ("incompatible type for element %d value "
12767 "in map construction"),
12768 i + 1);
12769 this->set_is_error();
12774 // Return the backend representation for constructing a map.
12776 Bexpression*
12777 Map_construction_expression::do_get_backend(Translate_context* context)
12779 if (this->is_error_expression())
12780 return context->backend()->error_expression();
12781 Location loc = this->location();
12783 size_t i = 0;
12784 Expression* ventries;
12785 if (this->vals_ == NULL || this->vals_->empty())
12786 ventries = Expression::make_nil(loc);
12787 else
12789 go_assert(this->constructor_temp_ != NULL);
12790 i = this->vals_->size() / 2;
12792 Expression* ctor_ref =
12793 Expression::make_temporary_reference(this->constructor_temp_, loc);
12794 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12797 Map_type* mt = this->type_->map_type();
12798 if (this->element_type_ == NULL)
12799 this->element_type_ =
12800 Type::make_builtin_struct_type(2,
12801 "__key", mt->key_type(),
12802 "__val", mt->val_type());
12803 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12805 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12806 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
12808 Expression* entry_size =
12809 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12811 unsigned int field_index;
12812 const Struct_field* valfield =
12813 this->element_type_->find_local_field("__val", &field_index);
12814 Expression* val_offset =
12815 Expression::make_struct_field_offset(this->element_type_, valfield);
12816 Expression* val_size =
12817 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12819 Expression* map_ctor =
12820 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12821 entry_size, val_offset, val_size, ventries);
12822 return map_ctor->get_backend(context);
12825 // Export an array construction.
12827 void
12828 Map_construction_expression::do_export(Export* exp) const
12830 exp->write_c_string("convert(");
12831 exp->write_type(this->type_);
12832 for (Expression_list::const_iterator pv = this->vals_->begin();
12833 pv != this->vals_->end();
12834 ++pv)
12836 exp->write_c_string(", ");
12837 (*pv)->export_expression(exp);
12839 exp->write_c_string(")");
12842 // Dump ast representation for a map construction expression.
12844 void
12845 Map_construction_expression::do_dump_expression(
12846 Ast_dump_context* ast_dump_context) const
12848 ast_dump_context->ostream() << "{" ;
12849 ast_dump_context->dump_expression_list(this->vals_, true);
12850 ast_dump_context->ostream() << "}";
12853 // A general composite literal. This is lowered to a type specific
12854 // version.
12856 class Composite_literal_expression : public Parser_expression
12858 public:
12859 Composite_literal_expression(Type* type, int depth, bool has_keys,
12860 Expression_list* vals, bool all_are_names,
12861 Location location)
12862 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12863 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12864 all_are_names_(all_are_names)
12867 protected:
12869 do_traverse(Traverse* traverse);
12871 Expression*
12872 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12874 Expression*
12875 do_copy()
12877 return new Composite_literal_expression(this->type_, this->depth_,
12878 this->has_keys_,
12879 (this->vals_ == NULL
12880 ? NULL
12881 : this->vals_->copy()),
12882 this->all_are_names_,
12883 this->location());
12886 void
12887 do_dump_expression(Ast_dump_context*) const;
12889 private:
12890 Expression*
12891 lower_struct(Gogo*, Type*);
12893 Expression*
12894 lower_array(Type*);
12896 Expression*
12897 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12899 Expression*
12900 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12902 // The type of the composite literal.
12903 Type* type_;
12904 // The depth within a list of composite literals within a composite
12905 // literal, when the type is omitted.
12906 int depth_;
12907 // The values to put in the composite literal.
12908 Expression_list* vals_;
12909 // If this is true, then VALS_ is a list of pairs: a key and a
12910 // value. In an array initializer, a missing key will be NULL.
12911 bool has_keys_;
12912 // If this is true, then HAS_KEYS_ is true, and every key is a
12913 // simple identifier.
12914 bool all_are_names_;
12917 // Traversal.
12920 Composite_literal_expression::do_traverse(Traverse* traverse)
12922 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12923 return TRAVERSE_EXIT;
12925 // If this is a struct composite literal with keys, then the keys
12926 // are field names, not expressions. We don't want to traverse them
12927 // in that case. If we do, we can give an erroneous error "variable
12928 // initializer refers to itself." See bug482.go in the testsuite.
12929 if (this->has_keys_ && this->vals_ != NULL)
12931 // The type may not be resolvable at this point.
12932 Type* type = this->type_;
12934 for (int depth = this->depth_; depth > 0; --depth)
12936 if (type->array_type() != NULL)
12937 type = type->array_type()->element_type();
12938 else if (type->map_type() != NULL)
12939 type = type->map_type()->val_type();
12940 else
12942 // This error will be reported during lowering.
12943 return TRAVERSE_CONTINUE;
12947 while (true)
12949 if (type->classification() == Type::TYPE_NAMED)
12950 type = type->named_type()->real_type();
12951 else if (type->classification() == Type::TYPE_FORWARD)
12953 Type* t = type->forwarded();
12954 if (t == type)
12955 break;
12956 type = t;
12958 else
12959 break;
12962 if (type->classification() == Type::TYPE_STRUCT)
12964 Expression_list::iterator p = this->vals_->begin();
12965 while (p != this->vals_->end())
12967 // Skip key.
12968 ++p;
12969 go_assert(p != this->vals_->end());
12970 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12971 return TRAVERSE_EXIT;
12972 ++p;
12974 return TRAVERSE_CONTINUE;
12978 if (this->vals_ != NULL)
12979 return this->vals_->traverse(traverse);
12981 return TRAVERSE_CONTINUE;
12984 // Lower a generic composite literal into a specific version based on
12985 // the type.
12987 Expression*
12988 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12989 Statement_inserter* inserter, int)
12991 Type* type = this->type_;
12993 for (int depth = this->depth_; depth > 0; --depth)
12995 if (type->array_type() != NULL)
12996 type = type->array_type()->element_type();
12997 else if (type->map_type() != NULL)
12998 type = type->map_type()->val_type();
12999 else
13001 if (!type->is_error())
13002 error_at(this->location(),
13003 ("may only omit types within composite literals "
13004 "of slice, array, or map type"));
13005 return Expression::make_error(this->location());
13009 Type *pt = type->points_to();
13010 bool is_pointer = false;
13011 if (pt != NULL)
13013 is_pointer = true;
13014 type = pt;
13017 Expression* ret;
13018 if (type->is_error())
13019 return Expression::make_error(this->location());
13020 else if (type->struct_type() != NULL)
13021 ret = this->lower_struct(gogo, type);
13022 else if (type->array_type() != NULL)
13023 ret = this->lower_array(type);
13024 else if (type->map_type() != NULL)
13025 ret = this->lower_map(gogo, function, inserter, type);
13026 else
13028 error_at(this->location(),
13029 ("expected struct, slice, array, or map type "
13030 "for composite literal"));
13031 return Expression::make_error(this->location());
13034 if (is_pointer)
13035 ret = Expression::make_heap_expression(ret, this->location());
13037 return ret;
13040 // Lower a struct composite literal.
13042 Expression*
13043 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
13045 Location location = this->location();
13046 Struct_type* st = type->struct_type();
13047 if (this->vals_ == NULL || !this->has_keys_)
13049 if (this->vals_ != NULL
13050 && !this->vals_->empty()
13051 && type->named_type() != NULL
13052 && type->named_type()->named_object()->package() != NULL)
13054 for (Struct_field_list::const_iterator pf = st->fields()->begin();
13055 pf != st->fields()->end();
13056 ++pf)
13058 if (Gogo::is_hidden_name(pf->field_name()))
13059 error_at(this->location(),
13060 "assignment of unexported field %qs in %qs literal",
13061 Gogo::message_name(pf->field_name()).c_str(),
13062 type->named_type()->message_name().c_str());
13066 return new Struct_construction_expression(type, this->vals_, location);
13069 size_t field_count = st->field_count();
13070 std::vector<Expression*> vals(field_count);
13071 std::vector<int>* traverse_order = new(std::vector<int>);
13072 Expression_list::const_iterator p = this->vals_->begin();
13073 Expression* external_expr = NULL;
13074 const Named_object* external_no = NULL;
13075 while (p != this->vals_->end())
13077 Expression* name_expr = *p;
13079 ++p;
13080 go_assert(p != this->vals_->end());
13081 Expression* val = *p;
13083 ++p;
13085 if (name_expr == NULL)
13087 error_at(val->location(), "mixture of field and value initializers");
13088 return Expression::make_error(location);
13091 bool bad_key = false;
13092 std::string name;
13093 const Named_object* no = NULL;
13094 switch (name_expr->classification())
13096 case EXPRESSION_UNKNOWN_REFERENCE:
13097 name = name_expr->unknown_expression()->name();
13098 break;
13100 case EXPRESSION_CONST_REFERENCE:
13101 no = static_cast<Const_expression*>(name_expr)->named_object();
13102 break;
13104 case EXPRESSION_TYPE:
13106 Type* t = name_expr->type();
13107 Named_type* nt = t->named_type();
13108 if (nt == NULL)
13109 bad_key = true;
13110 else
13111 no = nt->named_object();
13113 break;
13115 case EXPRESSION_VAR_REFERENCE:
13116 no = name_expr->var_expression()->named_object();
13117 break;
13119 case EXPRESSION_FUNC_REFERENCE:
13120 no = name_expr->func_expression()->named_object();
13121 break;
13123 case EXPRESSION_UNARY:
13124 // If there is a local variable around with the same name as
13125 // the field, and this occurs in the closure, then the
13126 // parser may turn the field reference into an indirection
13127 // through the closure. FIXME: This is a mess.
13129 bad_key = true;
13130 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13131 if (ue->op() == OPERATOR_MULT)
13133 Field_reference_expression* fre =
13134 ue->operand()->field_reference_expression();
13135 if (fre != NULL)
13137 Struct_type* st =
13138 fre->expr()->type()->deref()->struct_type();
13139 if (st != NULL)
13141 const Struct_field* sf = st->field(fre->field_index());
13142 name = sf->field_name();
13144 // See below. FIXME.
13145 if (!Gogo::is_hidden_name(name)
13146 && name[0] >= 'a'
13147 && name[0] <= 'z')
13149 if (gogo->lookup_global(name.c_str()) != NULL)
13150 name = gogo->pack_hidden_name(name, false);
13153 char buf[20];
13154 snprintf(buf, sizeof buf, "%u", fre->field_index());
13155 size_t buflen = strlen(buf);
13156 if (name.compare(name.length() - buflen, buflen, buf)
13157 == 0)
13159 name = name.substr(0, name.length() - buflen);
13160 bad_key = false;
13166 break;
13168 default:
13169 bad_key = true;
13170 break;
13172 if (bad_key)
13174 error_at(name_expr->location(), "expected struct field name");
13175 return Expression::make_error(location);
13178 if (no != NULL)
13180 if (no->package() != NULL && external_expr == NULL)
13182 external_expr = name_expr;
13183 external_no = no;
13186 name = no->name();
13188 // A predefined name won't be packed. If it starts with a
13189 // lower case letter we need to check for that case, because
13190 // the field name will be packed. FIXME.
13191 if (!Gogo::is_hidden_name(name)
13192 && name[0] >= 'a'
13193 && name[0] <= 'z')
13195 Named_object* gno = gogo->lookup_global(name.c_str());
13196 if (gno == no)
13197 name = gogo->pack_hidden_name(name, false);
13201 unsigned int index;
13202 const Struct_field* sf = st->find_local_field(name, &index);
13203 if (sf == NULL)
13205 error_at(name_expr->location(), "unknown field %qs in %qs",
13206 Gogo::message_name(name).c_str(),
13207 (type->named_type() != NULL
13208 ? type->named_type()->message_name().c_str()
13209 : "unnamed struct"));
13210 return Expression::make_error(location);
13212 if (vals[index] != NULL)
13214 error_at(name_expr->location(),
13215 "duplicate value for field %qs in %qs",
13216 Gogo::message_name(name).c_str(),
13217 (type->named_type() != NULL
13218 ? type->named_type()->message_name().c_str()
13219 : "unnamed struct"));
13220 return Expression::make_error(location);
13223 if (type->named_type() != NULL
13224 && type->named_type()->named_object()->package() != NULL
13225 && Gogo::is_hidden_name(sf->field_name()))
13226 error_at(name_expr->location(),
13227 "assignment of unexported field %qs in %qs literal",
13228 Gogo::message_name(sf->field_name()).c_str(),
13229 type->named_type()->message_name().c_str());
13231 vals[index] = val;
13232 traverse_order->push_back(index);
13235 if (!this->all_are_names_)
13237 // This is a weird case like bug462 in the testsuite.
13238 if (external_expr == NULL)
13239 error_at(this->location(), "unknown field in %qs literal",
13240 (type->named_type() != NULL
13241 ? type->named_type()->message_name().c_str()
13242 : "unnamed struct"));
13243 else
13244 error_at(external_expr->location(), "unknown field %qs in %qs",
13245 external_no->message_name().c_str(),
13246 (type->named_type() != NULL
13247 ? type->named_type()->message_name().c_str()
13248 : "unnamed struct"));
13249 return Expression::make_error(location);
13252 Expression_list* list = new Expression_list;
13253 list->reserve(field_count);
13254 for (size_t i = 0; i < field_count; ++i)
13255 list->push_back(vals[i]);
13257 Struct_construction_expression* ret =
13258 new Struct_construction_expression(type, list, location);
13259 ret->set_traverse_order(traverse_order);
13260 return ret;
13263 // Used to sort an index/value array.
13265 class Index_value_compare
13267 public:
13268 bool
13269 operator()(const std::pair<unsigned long, Expression*>& a,
13270 const std::pair<unsigned long, Expression*>& b)
13271 { return a.first < b.first; }
13274 // Lower an array composite literal.
13276 Expression*
13277 Composite_literal_expression::lower_array(Type* type)
13279 Location location = this->location();
13280 if (this->vals_ == NULL || !this->has_keys_)
13281 return this->make_array(type, NULL, this->vals_);
13283 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13284 indexes->reserve(this->vals_->size());
13285 bool indexes_out_of_order = false;
13286 Expression_list* vals = new Expression_list();
13287 vals->reserve(this->vals_->size());
13288 unsigned long index = 0;
13289 Expression_list::const_iterator p = this->vals_->begin();
13290 while (p != this->vals_->end())
13292 Expression* index_expr = *p;
13294 ++p;
13295 go_assert(p != this->vals_->end());
13296 Expression* val = *p;
13298 ++p;
13300 if (index_expr == NULL)
13302 if (!indexes->empty())
13303 indexes->push_back(index);
13305 else
13307 if (indexes->empty() && !vals->empty())
13309 for (size_t i = 0; i < vals->size(); ++i)
13310 indexes->push_back(i);
13313 Numeric_constant nc;
13314 if (!index_expr->numeric_constant_value(&nc))
13316 error_at(index_expr->location(),
13317 "index expression is not integer constant");
13318 return Expression::make_error(location);
13321 switch (nc.to_unsigned_long(&index))
13323 case Numeric_constant::NC_UL_VALID:
13324 break;
13325 case Numeric_constant::NC_UL_NOTINT:
13326 error_at(index_expr->location(),
13327 "index expression is not integer constant");
13328 return Expression::make_error(location);
13329 case Numeric_constant::NC_UL_NEGATIVE:
13330 error_at(index_expr->location(), "index expression is negative");
13331 return Expression::make_error(location);
13332 case Numeric_constant::NC_UL_BIG:
13333 error_at(index_expr->location(), "index value overflow");
13334 return Expression::make_error(location);
13335 default:
13336 go_unreachable();
13339 Named_type* ntype = Type::lookup_integer_type("int");
13340 Integer_type* inttype = ntype->integer_type();
13341 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13342 && index >> (inttype->bits() - 1) != 0)
13344 error_at(index_expr->location(), "index value overflow");
13345 return Expression::make_error(location);
13348 if (std::find(indexes->begin(), indexes->end(), index)
13349 != indexes->end())
13351 error_at(index_expr->location(), "duplicate value for index %lu",
13352 index);
13353 return Expression::make_error(location);
13356 if (!indexes->empty() && index < indexes->back())
13357 indexes_out_of_order = true;
13359 indexes->push_back(index);
13362 vals->push_back(val);
13364 ++index;
13367 if (indexes->empty())
13369 delete indexes;
13370 indexes = NULL;
13373 if (indexes_out_of_order)
13375 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13377 V v;
13378 v.reserve(indexes->size());
13379 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13380 for (Expression_list::const_iterator pe = vals->begin();
13381 pe != vals->end();
13382 ++pe, ++pi)
13383 v.push_back(std::make_pair(*pi, *pe));
13385 std::sort(v.begin(), v.end(), Index_value_compare());
13387 delete indexes;
13388 delete vals;
13389 indexes = new std::vector<unsigned long>();
13390 indexes->reserve(v.size());
13391 vals = new Expression_list();
13392 vals->reserve(v.size());
13394 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13396 indexes->push_back(p->first);
13397 vals->push_back(p->second);
13401 return this->make_array(type, indexes, vals);
13404 // Actually build the array composite literal. This handles
13405 // [...]{...}.
13407 Expression*
13408 Composite_literal_expression::make_array(
13409 Type* type,
13410 const std::vector<unsigned long>* indexes,
13411 Expression_list* vals)
13413 Location location = this->location();
13414 Array_type* at = type->array_type();
13416 if (at->length() != NULL && at->length()->is_nil_expression())
13418 size_t size;
13419 if (vals == NULL)
13420 size = 0;
13421 else if (indexes != NULL)
13422 size = indexes->back() + 1;
13423 else
13425 size = vals->size();
13426 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13427 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13428 && size >> (it->bits() - 1) != 0)
13430 error_at(location, "too many elements in composite literal");
13431 return Expression::make_error(location);
13435 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13436 at = Type::make_array_type(at->element_type(), elen);
13437 type = at;
13439 else if (at->length() != NULL
13440 && !at->length()->is_error_expression()
13441 && this->vals_ != NULL)
13443 Numeric_constant nc;
13444 unsigned long val;
13445 if (at->length()->numeric_constant_value(&nc)
13446 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13448 if (indexes == NULL)
13450 if (this->vals_->size() > val)
13452 error_at(location, "too many elements in composite literal");
13453 return Expression::make_error(location);
13456 else
13458 unsigned long max = indexes->back();
13459 if (max >= val)
13461 error_at(location,
13462 ("some element keys in composite literal "
13463 "are out of range"));
13464 return Expression::make_error(location);
13470 if (at->length() != NULL)
13471 return new Fixed_array_construction_expression(type, indexes, vals,
13472 location);
13473 else
13474 return new Slice_construction_expression(type, indexes, vals, location);
13477 // Lower a map composite literal.
13479 Expression*
13480 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13481 Statement_inserter* inserter,
13482 Type* type)
13484 Location location = this->location();
13485 if (this->vals_ != NULL)
13487 if (!this->has_keys_)
13489 error_at(location, "map composite literal must have keys");
13490 return Expression::make_error(location);
13493 for (Expression_list::iterator p = this->vals_->begin();
13494 p != this->vals_->end();
13495 p += 2)
13497 if (*p == NULL)
13499 ++p;
13500 error_at((*p)->location(),
13501 "map composite literal must have keys for every value");
13502 return Expression::make_error(location);
13504 // Make sure we have lowered the key; it may not have been
13505 // lowered in order to handle keys for struct composite
13506 // literals. Lower it now to get the right error message.
13507 if ((*p)->unknown_expression() != NULL)
13509 (*p)->unknown_expression()->clear_is_composite_literal_key();
13510 gogo->lower_expression(function, inserter, &*p);
13511 go_assert((*p)->is_error_expression());
13512 return Expression::make_error(location);
13517 return new Map_construction_expression(type, this->vals_, location);
13520 // Dump ast representation for a composite literal expression.
13522 void
13523 Composite_literal_expression::do_dump_expression(
13524 Ast_dump_context* ast_dump_context) const
13526 ast_dump_context->ostream() << "composite(";
13527 ast_dump_context->dump_type(this->type_);
13528 ast_dump_context->ostream() << ", {";
13529 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13530 ast_dump_context->ostream() << "})";
13533 // Make a composite literal expression.
13535 Expression*
13536 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13537 Expression_list* vals, bool all_are_names,
13538 Location location)
13540 return new Composite_literal_expression(type, depth, has_keys, vals,
13541 all_are_names, location);
13544 // Return whether this expression is a composite literal.
13546 bool
13547 Expression::is_composite_literal() const
13549 switch (this->classification_)
13551 case EXPRESSION_COMPOSITE_LITERAL:
13552 case EXPRESSION_STRUCT_CONSTRUCTION:
13553 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13554 case EXPRESSION_SLICE_CONSTRUCTION:
13555 case EXPRESSION_MAP_CONSTRUCTION:
13556 return true;
13557 default:
13558 return false;
13562 // Return whether this expression is a composite literal which is not
13563 // constant.
13565 bool
13566 Expression::is_nonconstant_composite_literal() const
13568 switch (this->classification_)
13570 case EXPRESSION_STRUCT_CONSTRUCTION:
13572 const Struct_construction_expression *psce =
13573 static_cast<const Struct_construction_expression*>(this);
13574 return !psce->is_constant_struct();
13576 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13578 const Fixed_array_construction_expression *pace =
13579 static_cast<const Fixed_array_construction_expression*>(this);
13580 return !pace->is_constant_array();
13582 case EXPRESSION_SLICE_CONSTRUCTION:
13584 const Slice_construction_expression *pace =
13585 static_cast<const Slice_construction_expression*>(this);
13586 return !pace->is_constant_array();
13588 case EXPRESSION_MAP_CONSTRUCTION:
13589 return true;
13590 default:
13591 return false;
13595 // Return true if this is a variable or temporary_variable.
13597 bool
13598 Expression::is_variable() const
13600 switch (this->classification_)
13602 case EXPRESSION_VAR_REFERENCE:
13603 case EXPRESSION_TEMPORARY_REFERENCE:
13604 case EXPRESSION_SET_AND_USE_TEMPORARY:
13605 return true;
13606 default:
13607 return false;
13611 // Return true if this is a reference to a local variable.
13613 bool
13614 Expression::is_local_variable() const
13616 const Var_expression* ve = this->var_expression();
13617 if (ve == NULL)
13618 return false;
13619 const Named_object* no = ve->named_object();
13620 return (no->is_result_variable()
13621 || (no->is_variable() && !no->var_value()->is_global()));
13624 // Class Type_guard_expression.
13626 // Traversal.
13629 Type_guard_expression::do_traverse(Traverse* traverse)
13631 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13632 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13633 return TRAVERSE_EXIT;
13634 return TRAVERSE_CONTINUE;
13637 Expression*
13638 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13639 Statement_inserter* inserter)
13641 if (!this->expr_->is_variable())
13643 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13644 this->location());
13645 inserter->insert(temp);
13646 this->expr_ =
13647 Expression::make_temporary_reference(temp, this->location());
13649 return this;
13652 // Check types of a type guard expression. The expression must have
13653 // an interface type, but the actual type conversion is checked at run
13654 // time.
13656 void
13657 Type_guard_expression::do_check_types(Gogo*)
13659 Type* expr_type = this->expr_->type();
13660 if (expr_type->interface_type() == NULL)
13662 if (!expr_type->is_error() && !this->type_->is_error())
13663 this->report_error(_("type assertion only valid for interface types"));
13664 this->set_is_error();
13666 else if (this->type_->interface_type() == NULL)
13668 std::string reason;
13669 if (!expr_type->interface_type()->implements_interface(this->type_,
13670 &reason))
13672 if (!this->type_->is_error())
13674 if (reason.empty())
13675 this->report_error(_("impossible type assertion: "
13676 "type does not implement interface"));
13677 else
13678 error_at(this->location(),
13679 ("impossible type assertion: "
13680 "type does not implement interface (%s)"),
13681 reason.c_str());
13683 this->set_is_error();
13688 // Return the backend representation for a type guard expression.
13690 Bexpression*
13691 Type_guard_expression::do_get_backend(Translate_context* context)
13693 Expression* conversion;
13694 if (this->type_->interface_type() != NULL)
13695 conversion =
13696 Expression::convert_interface_to_interface(this->type_, this->expr_,
13697 true, this->location());
13698 else
13699 conversion =
13700 Expression::convert_for_assignment(context->gogo(), this->type_,
13701 this->expr_, this->location());
13703 return conversion->get_backend(context);
13706 // Dump ast representation for a type guard expression.
13708 void
13709 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13710 const
13712 this->expr_->dump_expression(ast_dump_context);
13713 ast_dump_context->ostream() << ".";
13714 ast_dump_context->dump_type(this->type_);
13717 // Make a type guard expression.
13719 Expression*
13720 Expression::make_type_guard(Expression* expr, Type* type,
13721 Location location)
13723 return new Type_guard_expression(expr, type, location);
13726 // Class Heap_expression.
13728 // When you take the address of an escaping expression, it is allocated
13729 // on the heap. This class implements that.
13731 class Heap_expression : public Expression
13733 public:
13734 Heap_expression(Expression* expr, Location location)
13735 : Expression(EXPRESSION_HEAP, location),
13736 expr_(expr)
13739 protected:
13741 do_traverse(Traverse* traverse)
13742 { return Expression::traverse(&this->expr_, traverse); }
13744 Type*
13745 do_type()
13746 { return Type::make_pointer_type(this->expr_->type()); }
13748 void
13749 do_determine_type(const Type_context*)
13750 { this->expr_->determine_type_no_context(); }
13752 Expression*
13753 do_copy()
13755 return Expression::make_heap_expression(this->expr_->copy(),
13756 this->location());
13759 Bexpression*
13760 do_get_backend(Translate_context*);
13762 // We only export global objects, and the parser does not generate
13763 // this in global scope.
13764 void
13765 do_export(Export*) const
13766 { go_unreachable(); }
13768 void
13769 do_dump_expression(Ast_dump_context*) const;
13771 private:
13772 // The expression which is being put on the heap.
13773 Expression* expr_;
13776 // Return the backend representation for allocating an expression on the heap.
13778 Bexpression*
13779 Heap_expression::do_get_backend(Translate_context* context)
13781 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
13782 return context->backend()->error_expression();
13784 Location loc = this->location();
13785 Gogo* gogo = context->gogo();
13786 Btype* btype = this->type()->get_backend(gogo);
13787 Bexpression* space = Expression::make_allocation(this->expr_->type(),
13788 loc)->get_backend(context);
13790 Bstatement* decl;
13791 Named_object* fn = context->function();
13792 go_assert(fn != NULL);
13793 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13794 Bvariable* space_temp =
13795 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13796 space, true, loc, &decl);
13797 space = gogo->backend()->var_expression(space_temp, loc);
13798 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13799 Bexpression* ref =
13800 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
13802 Bexpression* bexpr = this->expr_->get_backend(context);
13803 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13804 decl = gogo->backend()->compound_statement(decl, assn);
13805 space = gogo->backend()->var_expression(space_temp, loc);
13806 return gogo->backend()->compound_expression(decl, space, loc);
13809 // Dump ast representation for a heap expression.
13811 void
13812 Heap_expression::do_dump_expression(
13813 Ast_dump_context* ast_dump_context) const
13815 ast_dump_context->ostream() << "&(";
13816 ast_dump_context->dump_expression(this->expr_);
13817 ast_dump_context->ostream() << ")";
13820 // Allocate an expression on the heap.
13822 Expression*
13823 Expression::make_heap_expression(Expression* expr, Location location)
13825 return new Heap_expression(expr, location);
13828 // Class Receive_expression.
13830 // Return the type of a receive expression.
13832 Type*
13833 Receive_expression::do_type()
13835 Channel_type* channel_type = this->channel_->type()->channel_type();
13836 if (channel_type == NULL)
13837 return Type::make_error_type();
13838 return channel_type->element_type();
13841 // Check types for a receive expression.
13843 void
13844 Receive_expression::do_check_types(Gogo*)
13846 Type* type = this->channel_->type();
13847 if (type->is_error())
13849 this->set_is_error();
13850 return;
13852 if (type->channel_type() == NULL)
13854 this->report_error(_("expected channel"));
13855 return;
13857 if (!type->channel_type()->may_receive())
13859 this->report_error(_("invalid receive on send-only channel"));
13860 return;
13864 // Flattening for receive expressions creates a temporary variable to store
13865 // received data in for receives.
13867 Expression*
13868 Receive_expression::do_flatten(Gogo*, Named_object*,
13869 Statement_inserter* inserter)
13871 Channel_type* channel_type = this->channel_->type()->channel_type();
13872 if (channel_type == NULL)
13874 go_assert(saw_errors());
13875 return this;
13878 Type* element_type = channel_type->element_type();
13879 if (this->temp_receiver_ == NULL)
13881 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13882 this->location());
13883 this->temp_receiver_->set_is_address_taken();
13884 inserter->insert(this->temp_receiver_);
13887 return this;
13890 // Get the backend representation for a receive expression.
13892 Bexpression*
13893 Receive_expression::do_get_backend(Translate_context* context)
13895 Location loc = this->location();
13897 Channel_type* channel_type = this->channel_->type()->channel_type();
13898 if (channel_type == NULL)
13900 go_assert(this->channel_->type()->is_error());
13901 return context->backend()->error_expression();
13903 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13905 Expression* recv_ref =
13906 Expression::make_temporary_reference(this->temp_receiver_, loc);
13907 Expression* recv_addr =
13908 Expression::make_temporary_reference(this->temp_receiver_, loc);
13909 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13910 Expression* recv =
13911 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13912 td, this->channel_, recv_addr);
13913 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
13916 // Dump ast representation for a receive expression.
13918 void
13919 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13921 ast_dump_context->ostream() << " <- " ;
13922 ast_dump_context->dump_expression(channel_);
13925 // Make a receive expression.
13927 Receive_expression*
13928 Expression::make_receive(Expression* channel, Location location)
13930 return new Receive_expression(channel, location);
13933 // An expression which evaluates to a pointer to the type descriptor
13934 // of a type.
13936 class Type_descriptor_expression : public Expression
13938 public:
13939 Type_descriptor_expression(Type* type, Location location)
13940 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13941 type_(type)
13944 protected:
13945 Type*
13946 do_type()
13947 { return Type::make_type_descriptor_ptr_type(); }
13949 bool
13950 do_is_immutable() const
13951 { return true; }
13953 void
13954 do_determine_type(const Type_context*)
13957 Expression*
13958 do_copy()
13959 { return this; }
13961 Bexpression*
13962 do_get_backend(Translate_context* context)
13964 return this->type_->type_descriptor_pointer(context->gogo(),
13965 this->location());
13968 void
13969 do_dump_expression(Ast_dump_context*) const;
13971 private:
13972 // The type for which this is the descriptor.
13973 Type* type_;
13976 // Dump ast representation for a type descriptor expression.
13978 void
13979 Type_descriptor_expression::do_dump_expression(
13980 Ast_dump_context* ast_dump_context) const
13982 ast_dump_context->dump_type(this->type_);
13985 // Make a type descriptor expression.
13987 Expression*
13988 Expression::make_type_descriptor(Type* type, Location location)
13990 return new Type_descriptor_expression(type, location);
13993 // An expression which evaluates to a pointer to the Garbage Collection symbol
13994 // of a type.
13996 class GC_symbol_expression : public Expression
13998 public:
13999 GC_symbol_expression(Type* type)
14000 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
14001 type_(type)
14004 protected:
14005 Type*
14006 do_type()
14007 { return Type::lookup_integer_type("uintptr"); }
14009 bool
14010 do_is_immutable() const
14011 { return true; }
14013 void
14014 do_determine_type(const Type_context*)
14017 Expression*
14018 do_copy()
14019 { return this; }
14021 Bexpression*
14022 do_get_backend(Translate_context* context)
14023 { return this->type_->gc_symbol_pointer(context->gogo()); }
14025 void
14026 do_dump_expression(Ast_dump_context*) const;
14028 private:
14029 // The type which this gc symbol describes.
14030 Type* type_;
14033 // Dump ast representation for a gc symbol expression.
14035 void
14036 GC_symbol_expression::do_dump_expression(
14037 Ast_dump_context* ast_dump_context) const
14039 ast_dump_context->ostream() << "gcdata(";
14040 ast_dump_context->dump_type(this->type_);
14041 ast_dump_context->ostream() << ")";
14044 // Make a gc symbol expression.
14046 Expression*
14047 Expression::make_gc_symbol(Type* type)
14049 return new GC_symbol_expression(type);
14052 // An expression which evaluates to some characteristic of a type.
14053 // This is only used to initialize fields of a type descriptor. Using
14054 // a new expression class is slightly inefficient but gives us a good
14055 // separation between the frontend and the middle-end with regard to
14056 // how types are laid out.
14058 class Type_info_expression : public Expression
14060 public:
14061 Type_info_expression(Type* type, Type_info type_info)
14062 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
14063 type_(type), type_info_(type_info)
14066 protected:
14067 bool
14068 do_is_immutable() const
14069 { return true; }
14071 Type*
14072 do_type();
14074 void
14075 do_determine_type(const Type_context*)
14078 Expression*
14079 do_copy()
14080 { return this; }
14082 Bexpression*
14083 do_get_backend(Translate_context* context);
14085 void
14086 do_dump_expression(Ast_dump_context*) const;
14088 private:
14089 // The type for which we are getting information.
14090 Type* type_;
14091 // What information we want.
14092 Type_info type_info_;
14095 // The type is chosen to match what the type descriptor struct
14096 // expects.
14098 Type*
14099 Type_info_expression::do_type()
14101 switch (this->type_info_)
14103 case TYPE_INFO_SIZE:
14104 return Type::lookup_integer_type("uintptr");
14105 case TYPE_INFO_ALIGNMENT:
14106 case TYPE_INFO_FIELD_ALIGNMENT:
14107 return Type::lookup_integer_type("uint8");
14108 default:
14109 go_unreachable();
14113 // Return the backend representation for type information.
14115 Bexpression*
14116 Type_info_expression::do_get_backend(Translate_context* context)
14118 Btype* btype = this->type_->get_backend(context->gogo());
14119 Gogo* gogo = context->gogo();
14120 size_t val;
14121 switch (this->type_info_)
14123 case TYPE_INFO_SIZE:
14124 val = gogo->backend()->type_size(btype);
14125 break;
14126 case TYPE_INFO_ALIGNMENT:
14127 val = gogo->backend()->type_alignment(btype);
14128 break;
14129 case TYPE_INFO_FIELD_ALIGNMENT:
14130 val = gogo->backend()->type_field_alignment(btype);
14131 break;
14132 default:
14133 go_unreachable();
14135 mpz_t cst;
14136 mpz_init_set_ui(cst, val);
14137 Btype* int_btype = this->type()->get_backend(gogo);
14138 Bexpression* ret =
14139 gogo->backend()->integer_constant_expression(int_btype, cst);
14140 mpz_clear(cst);
14141 return ret;
14144 // Dump ast representation for a type info expression.
14146 void
14147 Type_info_expression::do_dump_expression(
14148 Ast_dump_context* ast_dump_context) const
14150 ast_dump_context->ostream() << "typeinfo(";
14151 ast_dump_context->dump_type(this->type_);
14152 ast_dump_context->ostream() << ",";
14153 ast_dump_context->ostream() <<
14154 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
14155 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
14156 : this->type_info_ == TYPE_INFO_SIZE ? "size "
14157 : "unknown");
14158 ast_dump_context->ostream() << ")";
14161 // Make a type info expression.
14163 Expression*
14164 Expression::make_type_info(Type* type, Type_info type_info)
14166 return new Type_info_expression(type, type_info);
14169 // An expression that evaluates to some characteristic of a slice.
14170 // This is used when indexing, bound-checking, or nil checking a slice.
14172 class Slice_info_expression : public Expression
14174 public:
14175 Slice_info_expression(Expression* slice, Slice_info slice_info,
14176 Location location)
14177 : Expression(EXPRESSION_SLICE_INFO, location),
14178 slice_(slice), slice_info_(slice_info)
14181 protected:
14182 Type*
14183 do_type();
14185 void
14186 do_determine_type(const Type_context*)
14189 Expression*
14190 do_copy()
14192 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14193 this->location());
14196 Bexpression*
14197 do_get_backend(Translate_context* context);
14199 void
14200 do_dump_expression(Ast_dump_context*) const;
14202 void
14203 do_issue_nil_check()
14204 { this->slice_->issue_nil_check(); }
14206 private:
14207 // The slice for which we are getting information.
14208 Expression* slice_;
14209 // What information we want.
14210 Slice_info slice_info_;
14213 // Return the type of the slice info.
14215 Type*
14216 Slice_info_expression::do_type()
14218 switch (this->slice_info_)
14220 case SLICE_INFO_VALUE_POINTER:
14221 return Type::make_pointer_type(
14222 this->slice_->type()->array_type()->element_type());
14223 case SLICE_INFO_LENGTH:
14224 case SLICE_INFO_CAPACITY:
14225 return Type::lookup_integer_type("int");
14226 default:
14227 go_unreachable();
14231 // Return the backend information for slice information.
14233 Bexpression*
14234 Slice_info_expression::do_get_backend(Translate_context* context)
14236 Gogo* gogo = context->gogo();
14237 Bexpression* bslice = this->slice_->get_backend(context);
14238 switch (this->slice_info_)
14240 case SLICE_INFO_VALUE_POINTER:
14241 case SLICE_INFO_LENGTH:
14242 case SLICE_INFO_CAPACITY:
14243 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14244 this->location());
14245 break;
14246 default:
14247 go_unreachable();
14251 // Dump ast representation for a type info expression.
14253 void
14254 Slice_info_expression::do_dump_expression(
14255 Ast_dump_context* ast_dump_context) const
14257 ast_dump_context->ostream() << "sliceinfo(";
14258 this->slice_->dump_expression(ast_dump_context);
14259 ast_dump_context->ostream() << ",";
14260 ast_dump_context->ostream() <<
14261 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14262 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14263 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14264 : "unknown");
14265 ast_dump_context->ostream() << ")";
14268 // Make a slice info expression.
14270 Expression*
14271 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14272 Location location)
14274 return new Slice_info_expression(slice, slice_info, location);
14277 // An expression that represents a slice value: a struct with value pointer,
14278 // length, and capacity fields.
14280 class Slice_value_expression : public Expression
14282 public:
14283 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14284 Expression* cap, Location location)
14285 : Expression(EXPRESSION_SLICE_VALUE, location),
14286 type_(type), valptr_(valptr), len_(len), cap_(cap)
14289 protected:
14291 do_traverse(Traverse*);
14293 Type*
14294 do_type()
14295 { return this->type_; }
14297 void
14298 do_determine_type(const Type_context*)
14299 { go_unreachable(); }
14301 Expression*
14302 do_copy()
14304 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14305 this->len_->copy(), this->cap_->copy(),
14306 this->location());
14309 Bexpression*
14310 do_get_backend(Translate_context* context);
14312 void
14313 do_dump_expression(Ast_dump_context*) const;
14315 private:
14316 // The type of the slice value.
14317 Type* type_;
14318 // The pointer to the values in the slice.
14319 Expression* valptr_;
14320 // The length of the slice.
14321 Expression* len_;
14322 // The capacity of the slice.
14323 Expression* cap_;
14327 Slice_value_expression::do_traverse(Traverse* traverse)
14329 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14330 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14331 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14332 return TRAVERSE_EXIT;
14333 return TRAVERSE_CONTINUE;
14336 Bexpression*
14337 Slice_value_expression::do_get_backend(Translate_context* context)
14339 std::vector<Bexpression*> vals(3);
14340 vals[0] = this->valptr_->get_backend(context);
14341 vals[1] = this->len_->get_backend(context);
14342 vals[2] = this->cap_->get_backend(context);
14344 Gogo* gogo = context->gogo();
14345 Btype* btype = this->type_->get_backend(gogo);
14346 return gogo->backend()->constructor_expression(btype, vals, this->location());
14349 void
14350 Slice_value_expression::do_dump_expression(
14351 Ast_dump_context* ast_dump_context) const
14353 ast_dump_context->ostream() << "slicevalue(";
14354 ast_dump_context->ostream() << "values: ";
14355 this->valptr_->dump_expression(ast_dump_context);
14356 ast_dump_context->ostream() << ", length: ";
14357 this->len_->dump_expression(ast_dump_context);
14358 ast_dump_context->ostream() << ", capacity: ";
14359 this->cap_->dump_expression(ast_dump_context);
14360 ast_dump_context->ostream() << ")";
14363 Expression*
14364 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14365 Expression* cap, Location location)
14367 go_assert(at->is_slice_type());
14368 return new Slice_value_expression(at, valptr, len, cap, location);
14371 // An expression that evaluates to some characteristic of a non-empty interface.
14372 // This is used to access the method table or underlying object of an interface.
14374 class Interface_info_expression : public Expression
14376 public:
14377 Interface_info_expression(Expression* iface, Interface_info iface_info,
14378 Location location)
14379 : Expression(EXPRESSION_INTERFACE_INFO, location),
14380 iface_(iface), iface_info_(iface_info)
14383 protected:
14384 Type*
14385 do_type();
14387 void
14388 do_determine_type(const Type_context*)
14391 Expression*
14392 do_copy()
14394 return new Interface_info_expression(this->iface_->copy(),
14395 this->iface_info_, this->location());
14398 Bexpression*
14399 do_get_backend(Translate_context* context);
14401 void
14402 do_dump_expression(Ast_dump_context*) const;
14404 void
14405 do_issue_nil_check()
14406 { this->iface_->issue_nil_check(); }
14408 private:
14409 // The interface for which we are getting information.
14410 Expression* iface_;
14411 // What information we want.
14412 Interface_info iface_info_;
14415 // Return the type of the interface info.
14417 Type*
14418 Interface_info_expression::do_type()
14420 switch (this->iface_info_)
14422 case INTERFACE_INFO_METHODS:
14424 Type* pdt = Type::make_type_descriptor_ptr_type();
14425 if (this->iface_->type()->interface_type()->is_empty())
14426 return pdt;
14428 Location loc = this->location();
14429 Struct_field_list* sfl = new Struct_field_list();
14430 sfl->push_back(
14431 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14433 Interface_type* itype = this->iface_->type()->interface_type();
14434 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14435 p != itype->methods()->end();
14436 ++p)
14438 Function_type* ft = p->type()->function_type();
14439 go_assert(ft->receiver() == NULL);
14441 const Typed_identifier_list* params = ft->parameters();
14442 Typed_identifier_list* mparams = new Typed_identifier_list();
14443 if (params != NULL)
14444 mparams->reserve(params->size() + 1);
14445 Type* vt = Type::make_pointer_type(Type::make_void_type());
14446 mparams->push_back(Typed_identifier("", vt, ft->location()));
14447 if (params != NULL)
14449 for (Typed_identifier_list::const_iterator pp = params->begin();
14450 pp != params->end();
14451 ++pp)
14452 mparams->push_back(*pp);
14455 Typed_identifier_list* mresults = (ft->results() == NULL
14456 ? NULL
14457 : ft->results()->copy());
14458 Backend_function_type* mft =
14459 Type::make_backend_function_type(NULL, mparams, mresults,
14460 ft->location());
14462 std::string fname = Gogo::unpack_hidden_name(p->name());
14463 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14466 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14468 case INTERFACE_INFO_OBJECT:
14469 return Type::make_pointer_type(Type::make_void_type());
14470 default:
14471 go_unreachable();
14475 // Return the backend representation for interface information.
14477 Bexpression*
14478 Interface_info_expression::do_get_backend(Translate_context* context)
14480 Gogo* gogo = context->gogo();
14481 Bexpression* biface = this->iface_->get_backend(context);
14482 switch (this->iface_info_)
14484 case INTERFACE_INFO_METHODS:
14485 case INTERFACE_INFO_OBJECT:
14486 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14487 this->location());
14488 break;
14489 default:
14490 go_unreachable();
14494 // Dump ast representation for an interface info expression.
14496 void
14497 Interface_info_expression::do_dump_expression(
14498 Ast_dump_context* ast_dump_context) const
14500 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14501 ast_dump_context->ostream() << "interfaceinfo(";
14502 this->iface_->dump_expression(ast_dump_context);
14503 ast_dump_context->ostream() << ",";
14504 ast_dump_context->ostream() <<
14505 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14506 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14507 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14508 : "unknown");
14509 ast_dump_context->ostream() << ")";
14512 // Make an interface info expression.
14514 Expression*
14515 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14516 Location location)
14518 return new Interface_info_expression(iface, iface_info, location);
14521 // An expression that represents an interface value. The first field is either
14522 // a type descriptor for an empty interface or a pointer to the interface method
14523 // table for a non-empty interface. The second field is always the object.
14525 class Interface_value_expression : public Expression
14527 public:
14528 Interface_value_expression(Type* type, Expression* first_field,
14529 Expression* obj, Location location)
14530 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14531 type_(type), first_field_(first_field), obj_(obj)
14534 protected:
14536 do_traverse(Traverse*);
14538 Type*
14539 do_type()
14540 { return this->type_; }
14542 void
14543 do_determine_type(const Type_context*)
14544 { go_unreachable(); }
14546 Expression*
14547 do_copy()
14549 return new Interface_value_expression(this->type_,
14550 this->first_field_->copy(),
14551 this->obj_->copy(), this->location());
14554 Bexpression*
14555 do_get_backend(Translate_context* context);
14557 void
14558 do_dump_expression(Ast_dump_context*) const;
14560 private:
14561 // The type of the interface value.
14562 Type* type_;
14563 // The first field of the interface (either a type descriptor or a pointer
14564 // to the method table.
14565 Expression* first_field_;
14566 // The underlying object of the interface.
14567 Expression* obj_;
14571 Interface_value_expression::do_traverse(Traverse* traverse)
14573 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14574 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14575 return TRAVERSE_EXIT;
14576 return TRAVERSE_CONTINUE;
14579 Bexpression*
14580 Interface_value_expression::do_get_backend(Translate_context* context)
14582 std::vector<Bexpression*> vals(2);
14583 vals[0] = this->first_field_->get_backend(context);
14584 vals[1] = this->obj_->get_backend(context);
14586 Gogo* gogo = context->gogo();
14587 Btype* btype = this->type_->get_backend(gogo);
14588 return gogo->backend()->constructor_expression(btype, vals, this->location());
14591 void
14592 Interface_value_expression::do_dump_expression(
14593 Ast_dump_context* ast_dump_context) const
14595 ast_dump_context->ostream() << "interfacevalue(";
14596 ast_dump_context->ostream() <<
14597 (this->type_->interface_type()->is_empty()
14598 ? "type_descriptor: "
14599 : "methods: ");
14600 this->first_field_->dump_expression(ast_dump_context);
14601 ast_dump_context->ostream() << ", object: ";
14602 this->obj_->dump_expression(ast_dump_context);
14603 ast_dump_context->ostream() << ")";
14606 Expression*
14607 Expression::make_interface_value(Type* type, Expression* first_value,
14608 Expression* object, Location location)
14610 return new Interface_value_expression(type, first_value, object, location);
14613 // An interface method table for a pair of types: an interface type and a type
14614 // that implements that interface.
14616 class Interface_mtable_expression : public Expression
14618 public:
14619 Interface_mtable_expression(Interface_type* itype, Type* type,
14620 bool is_pointer, Location location)
14621 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14622 itype_(itype), type_(type), is_pointer_(is_pointer),
14623 method_table_type_(NULL), bvar_(NULL)
14626 protected:
14628 do_traverse(Traverse*);
14630 Type*
14631 do_type();
14633 bool
14634 is_immutable() const
14635 { return true; }
14637 void
14638 do_determine_type(const Type_context*)
14639 { go_unreachable(); }
14641 Expression*
14642 do_copy()
14644 return new Interface_mtable_expression(this->itype_, this->type_,
14645 this->is_pointer_, this->location());
14648 bool
14649 do_is_addressable() const
14650 { return true; }
14652 Bexpression*
14653 do_get_backend(Translate_context* context);
14655 void
14656 do_dump_expression(Ast_dump_context*) const;
14658 private:
14659 // The interface type for which the methods are defined.
14660 Interface_type* itype_;
14661 // The type to construct the interface method table for.
14662 Type* type_;
14663 // Whether this table contains the method set for the receiver type or the
14664 // pointer receiver type.
14665 bool is_pointer_;
14666 // The type of the method table.
14667 Type* method_table_type_;
14668 // The backend variable that refers to the interface method table.
14669 Bvariable* bvar_;
14673 Interface_mtable_expression::do_traverse(Traverse* traverse)
14675 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14676 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14677 return TRAVERSE_EXIT;
14678 return TRAVERSE_CONTINUE;
14681 Type*
14682 Interface_mtable_expression::do_type()
14684 if (this->method_table_type_ != NULL)
14685 return this->method_table_type_;
14687 const Typed_identifier_list* interface_methods = this->itype_->methods();
14688 go_assert(!interface_methods->empty());
14690 Struct_field_list* sfl = new Struct_field_list;
14691 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14692 this->location());
14693 sfl->push_back(Struct_field(tid));
14694 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14695 p != interface_methods->end();
14696 ++p)
14697 sfl->push_back(Struct_field(*p));
14698 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14699 return this->method_table_type_;
14702 Bexpression*
14703 Interface_mtable_expression::do_get_backend(Translate_context* context)
14705 Gogo* gogo = context->gogo();
14706 Location loc = Linemap::predeclared_location();
14707 if (this->bvar_ != NULL)
14708 return gogo->backend()->var_expression(this->bvar_, this->location());
14710 const Typed_identifier_list* interface_methods = this->itype_->methods();
14711 go_assert(!interface_methods->empty());
14713 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14714 + this->itype_->mangled_name(gogo)
14715 + "__"
14716 + this->type_->mangled_name(gogo));
14718 // See whether this interface has any hidden methods.
14719 bool has_hidden_methods = false;
14720 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14721 p != interface_methods->end();
14722 ++p)
14724 if (Gogo::is_hidden_name(p->name()))
14726 has_hidden_methods = true;
14727 break;
14731 // We already know that the named type is convertible to the
14732 // interface. If the interface has hidden methods, and the named
14733 // type is defined in a different package, then the interface
14734 // conversion table will be defined by that other package.
14735 if (has_hidden_methods
14736 && this->type_->named_type() != NULL
14737 && this->type_->named_type()->named_object()->package() != NULL)
14739 Btype* btype = this->type()->get_backend(gogo);
14740 this->bvar_ =
14741 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14742 return gogo->backend()->var_expression(this->bvar_, this->location());
14745 // The first element is the type descriptor.
14746 Type* td_type;
14747 if (!this->is_pointer_)
14748 td_type = this->type_;
14749 else
14750 td_type = Type::make_pointer_type(this->type_);
14752 // Build an interface method table for a type: a type descriptor followed by a
14753 // list of function pointers, one for each interface method. This is used for
14754 // interfaces.
14755 Expression_list* svals = new Expression_list();
14756 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14758 Named_type* nt = this->type_->named_type();
14759 Struct_type* st = this->type_->struct_type();
14760 go_assert(nt != NULL || st != NULL);
14762 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14763 p != interface_methods->end();
14764 ++p)
14766 bool is_ambiguous;
14767 Method* m;
14768 if (nt != NULL)
14769 m = nt->method_function(p->name(), &is_ambiguous);
14770 else
14771 m = st->method_function(p->name(), &is_ambiguous);
14772 go_assert(m != NULL);
14773 Named_object* no = m->named_object();
14775 go_assert(no->is_function() || no->is_function_declaration());
14776 svals->push_back(Expression::make_func_code_reference(no, loc));
14779 Btype* btype = this->type()->get_backend(gogo);
14780 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14781 svals, loc);
14782 Bexpression* ctor = mtable->get_backend(context);
14784 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14785 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14786 !is_public, btype, loc);
14787 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14788 !is_public, btype, loc, ctor);
14789 return gogo->backend()->var_expression(this->bvar_, loc);
14792 void
14793 Interface_mtable_expression::do_dump_expression(
14794 Ast_dump_context* ast_dump_context) const
14796 ast_dump_context->ostream() << "__go_"
14797 << (this->is_pointer_ ? "pimt__" : "imt_");
14798 ast_dump_context->dump_type(this->itype_);
14799 ast_dump_context->ostream() << "__";
14800 ast_dump_context->dump_type(this->type_);
14803 Expression*
14804 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14805 bool is_pointer, Location location)
14807 return new Interface_mtable_expression(itype, type, is_pointer, location);
14810 // An expression which evaluates to the offset of a field within a
14811 // struct. This, like Type_info_expression, q.v., is only used to
14812 // initialize fields of a type descriptor.
14814 class Struct_field_offset_expression : public Expression
14816 public:
14817 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14818 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14819 Linemap::predeclared_location()),
14820 type_(type), field_(field)
14823 protected:
14824 bool
14825 do_is_immutable() const
14826 { return true; }
14828 Type*
14829 do_type()
14830 { return Type::lookup_integer_type("uintptr"); }
14832 void
14833 do_determine_type(const Type_context*)
14836 Expression*
14837 do_copy()
14838 { return this; }
14840 Bexpression*
14841 do_get_backend(Translate_context* context);
14843 void
14844 do_dump_expression(Ast_dump_context*) const;
14846 private:
14847 // The type of the struct.
14848 Struct_type* type_;
14849 // The field.
14850 const Struct_field* field_;
14853 // Return the backend representation for a struct field offset.
14855 Bexpression*
14856 Struct_field_offset_expression::do_get_backend(Translate_context* context)
14858 const Struct_field_list* fields = this->type_->fields();
14859 Struct_field_list::const_iterator p;
14860 unsigned i = 0;
14861 for (p = fields->begin();
14862 p != fields->end();
14863 ++p, ++i)
14864 if (&*p == this->field_)
14865 break;
14866 go_assert(&*p == this->field_);
14868 Gogo* gogo = context->gogo();
14869 Btype* btype = this->type_->get_backend(gogo);
14871 size_t offset = gogo->backend()->type_field_offset(btype, i);
14872 Type* uptr_type = Type::lookup_integer_type("uintptr");
14873 Expression* ret =
14874 Expression::make_integer_ul(offset, uptr_type,
14875 Linemap::predeclared_location());
14876 return ret->get_backend(context);
14879 // Dump ast representation for a struct field offset expression.
14881 void
14882 Struct_field_offset_expression::do_dump_expression(
14883 Ast_dump_context* ast_dump_context) const
14885 ast_dump_context->ostream() << "unsafe.Offsetof(";
14886 ast_dump_context->dump_type(this->type_);
14887 ast_dump_context->ostream() << '.';
14888 ast_dump_context->ostream() <<
14889 Gogo::message_name(this->field_->field_name());
14890 ast_dump_context->ostream() << ")";
14893 // Make an expression for a struct field offset.
14895 Expression*
14896 Expression::make_struct_field_offset(Struct_type* type,
14897 const Struct_field* field)
14899 return new Struct_field_offset_expression(type, field);
14902 // An expression which evaluates to a pointer to the map descriptor of
14903 // a map type.
14905 class Map_descriptor_expression : public Expression
14907 public:
14908 Map_descriptor_expression(Map_type* type, Location location)
14909 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14910 type_(type)
14913 protected:
14914 Type*
14915 do_type()
14916 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14918 void
14919 do_determine_type(const Type_context*)
14922 Expression*
14923 do_copy()
14924 { return this; }
14926 Bexpression*
14927 do_get_backend(Translate_context* context)
14929 return this->type_->map_descriptor_pointer(context->gogo(),
14930 this->location());
14933 void
14934 do_dump_expression(Ast_dump_context*) const;
14936 private:
14937 // The type for which this is the descriptor.
14938 Map_type* type_;
14941 // Dump ast representation for a map descriptor expression.
14943 void
14944 Map_descriptor_expression::do_dump_expression(
14945 Ast_dump_context* ast_dump_context) const
14947 ast_dump_context->ostream() << "map_descriptor(";
14948 ast_dump_context->dump_type(this->type_);
14949 ast_dump_context->ostream() << ")";
14952 // Make a map descriptor expression.
14954 Expression*
14955 Expression::make_map_descriptor(Map_type* type, Location location)
14957 return new Map_descriptor_expression(type, location);
14960 // An expression which evaluates to the address of an unnamed label.
14962 class Label_addr_expression : public Expression
14964 public:
14965 Label_addr_expression(Label* label, Location location)
14966 : Expression(EXPRESSION_LABEL_ADDR, location),
14967 label_(label)
14970 protected:
14971 Type*
14972 do_type()
14973 { return Type::make_pointer_type(Type::make_void_type()); }
14975 void
14976 do_determine_type(const Type_context*)
14979 Expression*
14980 do_copy()
14981 { return new Label_addr_expression(this->label_, this->location()); }
14983 Bexpression*
14984 do_get_backend(Translate_context* context)
14985 { return this->label_->get_addr(context, this->location()); }
14987 void
14988 do_dump_expression(Ast_dump_context* ast_dump_context) const
14989 { ast_dump_context->ostream() << this->label_->name(); }
14991 private:
14992 // The label whose address we are taking.
14993 Label* label_;
14996 // Make an expression for the address of an unnamed label.
14998 Expression*
14999 Expression::make_label_addr(Label* label, Location location)
15001 return new Label_addr_expression(label, location);
15004 // Conditional expressions.
15006 class Conditional_expression : public Expression
15008 public:
15009 Conditional_expression(Expression* cond, Expression* then_expr,
15010 Expression* else_expr, Location location)
15011 : Expression(EXPRESSION_CONDITIONAL, location),
15012 cond_(cond), then_(then_expr), else_(else_expr)
15015 protected:
15017 do_traverse(Traverse*);
15019 Type*
15020 do_type();
15022 void
15023 do_determine_type(const Type_context*);
15025 Expression*
15026 do_copy()
15028 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
15029 this->else_->copy(), this->location());
15032 Bexpression*
15033 do_get_backend(Translate_context* context);
15035 void
15036 do_dump_expression(Ast_dump_context*) const;
15038 private:
15039 // The condition to be checked.
15040 Expression* cond_;
15041 // The expression to execute if the condition is true.
15042 Expression* then_;
15043 // The expression to execute if the condition is false.
15044 Expression* else_;
15047 // Traversal.
15050 Conditional_expression::do_traverse(Traverse* traverse)
15052 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
15053 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
15054 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
15055 return TRAVERSE_EXIT;
15056 return TRAVERSE_CONTINUE;
15059 // Return the type of the conditional expression.
15061 Type*
15062 Conditional_expression::do_type()
15064 Type* result_type = Type::make_void_type();
15065 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
15066 NULL))
15067 result_type = this->then_->type();
15068 else if (this->then_->is_nil_expression()
15069 || this->else_->is_nil_expression())
15070 result_type = (!this->then_->is_nil_expression()
15071 ? this->then_->type()
15072 : this->else_->type());
15073 return result_type;
15076 // Determine type for a conditional expression.
15078 void
15079 Conditional_expression::do_determine_type(const Type_context* context)
15081 this->cond_->determine_type_no_context();
15082 this->then_->determine_type(context);
15083 this->else_->determine_type(context);
15086 // Get the backend representation of a conditional expression.
15088 Bexpression*
15089 Conditional_expression::do_get_backend(Translate_context* context)
15091 Gogo* gogo = context->gogo();
15092 Btype* result_btype = this->type()->get_backend(gogo);
15093 Bexpression* cond = this->cond_->get_backend(context);
15094 Bexpression* then = this->then_->get_backend(context);
15095 Bexpression* belse = this->else_->get_backend(context);
15096 return gogo->backend()->conditional_expression(result_btype, cond, then,
15097 belse, this->location());
15100 // Dump ast representation of a conditional expression.
15102 void
15103 Conditional_expression::do_dump_expression(
15104 Ast_dump_context* ast_dump_context) const
15106 ast_dump_context->ostream() << "(";
15107 ast_dump_context->dump_expression(this->cond_);
15108 ast_dump_context->ostream() << " ? ";
15109 ast_dump_context->dump_expression(this->then_);
15110 ast_dump_context->ostream() << " : ";
15111 ast_dump_context->dump_expression(this->else_);
15112 ast_dump_context->ostream() << ") ";
15115 // Make a conditional expression.
15117 Expression*
15118 Expression::make_conditional(Expression* cond, Expression* then,
15119 Expression* else_expr, Location location)
15121 return new Conditional_expression(cond, then, else_expr, location);
15124 // Compound expressions.
15126 class Compound_expression : public Expression
15128 public:
15129 Compound_expression(Expression* init, Expression* expr, Location location)
15130 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
15133 protected:
15135 do_traverse(Traverse*);
15137 Type*
15138 do_type();
15140 void
15141 do_determine_type(const Type_context*);
15143 Expression*
15144 do_copy()
15146 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
15147 this->location());
15150 Bexpression*
15151 do_get_backend(Translate_context* context);
15153 void
15154 do_dump_expression(Ast_dump_context*) const;
15156 private:
15157 // The expression that is evaluated first and discarded.
15158 Expression* init_;
15159 // The expression that is evaluated and returned.
15160 Expression* expr_;
15163 // Traversal.
15166 Compound_expression::do_traverse(Traverse* traverse)
15168 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15169 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15170 return TRAVERSE_EXIT;
15171 return TRAVERSE_CONTINUE;
15174 // Return the type of the compound expression.
15176 Type*
15177 Compound_expression::do_type()
15179 return this->expr_->type();
15182 // Determine type for a compound expression.
15184 void
15185 Compound_expression::do_determine_type(const Type_context* context)
15187 this->init_->determine_type_no_context();
15188 this->expr_->determine_type(context);
15191 // Get the backend representation of a compound expression.
15193 Bexpression*
15194 Compound_expression::do_get_backend(Translate_context* context)
15196 Gogo* gogo = context->gogo();
15197 Bexpression* binit = this->init_->get_backend(context);
15198 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15199 Bexpression* bexpr = this->expr_->get_backend(context);
15200 return gogo->backend()->compound_expression(init_stmt, bexpr,
15201 this->location());
15204 // Dump ast representation of a conditional expression.
15206 void
15207 Compound_expression::do_dump_expression(
15208 Ast_dump_context* ast_dump_context) const
15210 ast_dump_context->ostream() << "(";
15211 ast_dump_context->dump_expression(this->init_);
15212 ast_dump_context->ostream() << ",";
15213 ast_dump_context->dump_expression(this->expr_);
15214 ast_dump_context->ostream() << ") ";
15217 // Make a compound expression.
15219 Expression*
15220 Expression::make_compound(Expression* init, Expression* expr, Location location)
15222 return new Compound_expression(init, expr, location);
15225 // Import an expression. This comes at the end in order to see the
15226 // various class definitions.
15228 Expression*
15229 Expression::import_expression(Import* imp)
15231 int c = imp->peek_char();
15232 if (imp->match_c_string("- ")
15233 || imp->match_c_string("! ")
15234 || imp->match_c_string("^ "))
15235 return Unary_expression::do_import(imp);
15236 else if (c == '(')
15237 return Binary_expression::do_import(imp);
15238 else if (imp->match_c_string("true")
15239 || imp->match_c_string("false"))
15240 return Boolean_expression::do_import(imp);
15241 else if (c == '"')
15242 return String_expression::do_import(imp);
15243 else if (c == '-' || (c >= '0' && c <= '9'))
15245 // This handles integers, floats and complex constants.
15246 return Integer_expression::do_import(imp);
15248 else if (imp->match_c_string("nil"))
15249 return Nil_expression::do_import(imp);
15250 else if (imp->match_c_string("convert"))
15251 return Type_conversion_expression::do_import(imp);
15252 else
15254 error_at(imp->location(), "import error: expected expression");
15255 return Expression::make_error(imp->location());
15259 // Class Expression_list.
15261 // Traverse the list.
15264 Expression_list::traverse(Traverse* traverse)
15266 for (Expression_list::iterator p = this->begin();
15267 p != this->end();
15268 ++p)
15270 if (*p != NULL)
15272 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15273 return TRAVERSE_EXIT;
15276 return TRAVERSE_CONTINUE;
15279 // Copy the list.
15281 Expression_list*
15282 Expression_list::copy()
15284 Expression_list* ret = new Expression_list();
15285 for (Expression_list::iterator p = this->begin();
15286 p != this->end();
15287 ++p)
15289 if (*p == NULL)
15290 ret->push_back(NULL);
15291 else
15292 ret->push_back((*p)->copy());
15294 return ret;
15297 // Return whether an expression list has an error expression.
15299 bool
15300 Expression_list::contains_error() const
15302 for (Expression_list::const_iterator p = this->begin();
15303 p != this->end();
15304 ++p)
15305 if (*p != NULL && (*p)->is_error_expression())
15306 return true;
15307 return false;
15310 // Class Numeric_constant.
15312 // Destructor.
15314 Numeric_constant::~Numeric_constant()
15316 this->clear();
15319 // Copy constructor.
15321 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15322 : classification_(a.classification_), type_(a.type_)
15324 switch (a.classification_)
15326 case NC_INVALID:
15327 break;
15328 case NC_INT:
15329 case NC_RUNE:
15330 mpz_init_set(this->u_.int_val, a.u_.int_val);
15331 break;
15332 case NC_FLOAT:
15333 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15334 break;
15335 case NC_COMPLEX:
15336 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15337 GMP_RNDN);
15338 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15339 GMP_RNDN);
15340 break;
15341 default:
15342 go_unreachable();
15346 // Assignment operator.
15348 Numeric_constant&
15349 Numeric_constant::operator=(const Numeric_constant& a)
15351 this->clear();
15352 this->classification_ = a.classification_;
15353 this->type_ = a.type_;
15354 switch (a.classification_)
15356 case NC_INVALID:
15357 break;
15358 case NC_INT:
15359 case NC_RUNE:
15360 mpz_init_set(this->u_.int_val, a.u_.int_val);
15361 break;
15362 case NC_FLOAT:
15363 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15364 break;
15365 case NC_COMPLEX:
15366 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15367 GMP_RNDN);
15368 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15369 GMP_RNDN);
15370 break;
15371 default:
15372 go_unreachable();
15374 return *this;
15377 // Clear the contents.
15379 void
15380 Numeric_constant::clear()
15382 switch (this->classification_)
15384 case NC_INVALID:
15385 break;
15386 case NC_INT:
15387 case NC_RUNE:
15388 mpz_clear(this->u_.int_val);
15389 break;
15390 case NC_FLOAT:
15391 mpfr_clear(this->u_.float_val);
15392 break;
15393 case NC_COMPLEX:
15394 mpfr_clear(this->u_.complex_val.real);
15395 mpfr_clear(this->u_.complex_val.imag);
15396 break;
15397 default:
15398 go_unreachable();
15400 this->classification_ = NC_INVALID;
15403 // Set to an unsigned long value.
15405 void
15406 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15408 this->clear();
15409 this->classification_ = NC_INT;
15410 this->type_ = type;
15411 mpz_init_set_ui(this->u_.int_val, val);
15414 // Set to an integer value.
15416 void
15417 Numeric_constant::set_int(Type* type, const mpz_t val)
15419 this->clear();
15420 this->classification_ = NC_INT;
15421 this->type_ = type;
15422 mpz_init_set(this->u_.int_val, val);
15425 // Set to a rune value.
15427 void
15428 Numeric_constant::set_rune(Type* type, const mpz_t val)
15430 this->clear();
15431 this->classification_ = NC_RUNE;
15432 this->type_ = type;
15433 mpz_init_set(this->u_.int_val, val);
15436 // Set to a floating point value.
15438 void
15439 Numeric_constant::set_float(Type* type, const mpfr_t val)
15441 this->clear();
15442 this->classification_ = NC_FLOAT;
15443 this->type_ = type;
15444 // Numeric constants do not have negative zero values, so remove
15445 // them here. They also don't have infinity or NaN values, but we
15446 // should never see them here.
15447 if (mpfr_zero_p(val))
15448 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15449 else
15450 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
15453 // Set to a complex value.
15455 void
15456 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15458 this->clear();
15459 this->classification_ = NC_COMPLEX;
15460 this->type_ = type;
15461 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15462 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15465 // Get an int value.
15467 void
15468 Numeric_constant::get_int(mpz_t* val) const
15470 go_assert(this->is_int());
15471 mpz_init_set(*val, this->u_.int_val);
15474 // Get a rune value.
15476 void
15477 Numeric_constant::get_rune(mpz_t* val) const
15479 go_assert(this->is_rune());
15480 mpz_init_set(*val, this->u_.int_val);
15483 // Get a floating point value.
15485 void
15486 Numeric_constant::get_float(mpfr_t* val) const
15488 go_assert(this->is_float());
15489 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15492 // Get a complex value.
15494 void
15495 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15497 go_assert(this->is_complex());
15498 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15499 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15502 // Express value as unsigned long if possible.
15504 Numeric_constant::To_unsigned_long
15505 Numeric_constant::to_unsigned_long(unsigned long* val) const
15507 switch (this->classification_)
15509 case NC_INT:
15510 case NC_RUNE:
15511 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15512 case NC_FLOAT:
15513 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15514 case NC_COMPLEX:
15515 if (!mpfr_zero_p(this->u_.complex_val.imag))
15516 return NC_UL_NOTINT;
15517 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15518 default:
15519 go_unreachable();
15523 // Express integer value as unsigned long if possible.
15525 Numeric_constant::To_unsigned_long
15526 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15527 unsigned long *val) const
15529 if (mpz_sgn(ival) < 0)
15530 return NC_UL_NEGATIVE;
15531 unsigned long ui = mpz_get_ui(ival);
15532 if (mpz_cmp_ui(ival, ui) != 0)
15533 return NC_UL_BIG;
15534 *val = ui;
15535 return NC_UL_VALID;
15538 // Express floating point value as unsigned long if possible.
15540 Numeric_constant::To_unsigned_long
15541 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15542 unsigned long *val) const
15544 if (!mpfr_integer_p(fval))
15545 return NC_UL_NOTINT;
15546 mpz_t ival;
15547 mpz_init(ival);
15548 mpfr_get_z(ival, fval, GMP_RNDN);
15549 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15550 mpz_clear(ival);
15551 return ret;
15554 // Convert value to integer if possible.
15556 bool
15557 Numeric_constant::to_int(mpz_t* val) const
15559 switch (this->classification_)
15561 case NC_INT:
15562 case NC_RUNE:
15563 mpz_init_set(*val, this->u_.int_val);
15564 return true;
15565 case NC_FLOAT:
15566 if (!mpfr_integer_p(this->u_.float_val))
15567 return false;
15568 mpz_init(*val);
15569 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15570 return true;
15571 case NC_COMPLEX:
15572 if (!mpfr_zero_p(this->u_.complex_val.imag)
15573 || !mpfr_integer_p(this->u_.complex_val.real))
15574 return false;
15575 mpz_init(*val);
15576 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15577 return true;
15578 default:
15579 go_unreachable();
15583 // Convert value to floating point if possible.
15585 bool
15586 Numeric_constant::to_float(mpfr_t* val) const
15588 switch (this->classification_)
15590 case NC_INT:
15591 case NC_RUNE:
15592 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15593 return true;
15594 case NC_FLOAT:
15595 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15596 return true;
15597 case NC_COMPLEX:
15598 if (!mpfr_zero_p(this->u_.complex_val.imag))
15599 return false;
15600 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15601 return true;
15602 default:
15603 go_unreachable();
15607 // Convert value to complex.
15609 bool
15610 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15612 switch (this->classification_)
15614 case NC_INT:
15615 case NC_RUNE:
15616 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15617 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15618 return true;
15619 case NC_FLOAT:
15620 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15621 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15622 return true;
15623 case NC_COMPLEX:
15624 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15625 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15626 return true;
15627 default:
15628 go_unreachable();
15632 // Get the type.
15634 Type*
15635 Numeric_constant::type() const
15637 if (this->type_ != NULL)
15638 return this->type_;
15639 switch (this->classification_)
15641 case NC_INT:
15642 return Type::make_abstract_integer_type();
15643 case NC_RUNE:
15644 return Type::make_abstract_character_type();
15645 case NC_FLOAT:
15646 return Type::make_abstract_float_type();
15647 case NC_COMPLEX:
15648 return Type::make_abstract_complex_type();
15649 default:
15650 go_unreachable();
15654 // If the constant can be expressed in TYPE, then set the type of the
15655 // constant to TYPE and return true. Otherwise return false, and, if
15656 // ISSUE_ERROR is true, report an appropriate error message.
15658 bool
15659 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15661 bool ret;
15662 if (type == NULL)
15663 ret = true;
15664 else if (type->integer_type() != NULL)
15665 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15666 else if (type->float_type() != NULL)
15667 ret = this->check_float_type(type->float_type(), issue_error, loc);
15668 else if (type->complex_type() != NULL)
15669 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15670 else
15671 go_unreachable();
15672 if (ret)
15673 this->type_ = type;
15674 return ret;
15677 // Check whether the constant can be expressed in an integer type.
15679 bool
15680 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15681 Location location) const
15683 mpz_t val;
15684 switch (this->classification_)
15686 case NC_INT:
15687 case NC_RUNE:
15688 mpz_init_set(val, this->u_.int_val);
15689 break;
15691 case NC_FLOAT:
15692 if (!mpfr_integer_p(this->u_.float_val))
15694 if (issue_error)
15695 error_at(location, "floating point constant truncated to integer");
15696 return false;
15698 mpz_init(val);
15699 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15700 break;
15702 case NC_COMPLEX:
15703 if (!mpfr_integer_p(this->u_.complex_val.real)
15704 || !mpfr_zero_p(this->u_.complex_val.imag))
15706 if (issue_error)
15707 error_at(location, "complex constant truncated to integer");
15708 return false;
15710 mpz_init(val);
15711 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15712 break;
15714 default:
15715 go_unreachable();
15718 bool ret;
15719 if (type->is_abstract())
15720 ret = true;
15721 else
15723 int bits = mpz_sizeinbase(val, 2);
15724 if (type->is_unsigned())
15726 // For an unsigned type we can only accept a nonnegative
15727 // number, and we must be able to represents at least BITS.
15728 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15730 else
15732 // For a signed type we need an extra bit to indicate the
15733 // sign. We have to handle the most negative integer
15734 // specially.
15735 ret = (bits + 1 <= type->bits()
15736 || (bits <= type->bits()
15737 && mpz_sgn(val) < 0
15738 && (mpz_scan1(val, 0)
15739 == static_cast<unsigned long>(type->bits() - 1))
15740 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15744 if (!ret && issue_error)
15745 error_at(location, "integer constant overflow");
15747 return ret;
15750 // Check whether the constant can be expressed in a floating point
15751 // type.
15753 bool
15754 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15755 Location location)
15757 mpfr_t val;
15758 switch (this->classification_)
15760 case NC_INT:
15761 case NC_RUNE:
15762 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15763 break;
15765 case NC_FLOAT:
15766 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15767 break;
15769 case NC_COMPLEX:
15770 if (!mpfr_zero_p(this->u_.complex_val.imag))
15772 if (issue_error)
15773 error_at(location, "complex constant truncated to float");
15774 return false;
15776 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15777 break;
15779 default:
15780 go_unreachable();
15783 bool ret;
15784 if (type->is_abstract())
15785 ret = true;
15786 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15788 // A NaN or Infinity always fits in the range of the type.
15789 ret = true;
15791 else
15793 mp_exp_t exp = mpfr_get_exp(val);
15794 mp_exp_t max_exp;
15795 switch (type->bits())
15797 case 32:
15798 max_exp = 128;
15799 break;
15800 case 64:
15801 max_exp = 1024;
15802 break;
15803 default:
15804 go_unreachable();
15807 ret = exp <= max_exp;
15809 if (ret)
15811 // Round the constant to the desired type.
15812 mpfr_t t;
15813 mpfr_init(t);
15814 switch (type->bits())
15816 case 32:
15817 mpfr_set_prec(t, 24);
15818 break;
15819 case 64:
15820 mpfr_set_prec(t, 53);
15821 break;
15822 default:
15823 go_unreachable();
15825 mpfr_set(t, val, GMP_RNDN);
15826 mpfr_set(val, t, GMP_RNDN);
15827 mpfr_clear(t);
15829 this->set_float(type, val);
15833 mpfr_clear(val);
15835 if (!ret && issue_error)
15836 error_at(location, "floating point constant overflow");
15838 return ret;
15841 // Check whether the constant can be expressed in a complex type.
15843 bool
15844 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15845 Location location)
15847 if (type->is_abstract())
15848 return true;
15850 mp_exp_t max_exp;
15851 switch (type->bits())
15853 case 64:
15854 max_exp = 128;
15855 break;
15856 case 128:
15857 max_exp = 1024;
15858 break;
15859 default:
15860 go_unreachable();
15863 mpfr_t real;
15864 mpfr_t imag;
15865 switch (this->classification_)
15867 case NC_INT:
15868 case NC_RUNE:
15869 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
15870 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15871 break;
15873 case NC_FLOAT:
15874 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
15875 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15876 break;
15878 case NC_COMPLEX:
15879 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
15880 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
15881 break;
15883 default:
15884 go_unreachable();
15887 bool ret = true;
15888 if (!mpfr_nan_p(real)
15889 && !mpfr_inf_p(real)
15890 && !mpfr_zero_p(real)
15891 && mpfr_get_exp(real) > max_exp)
15893 if (issue_error)
15894 error_at(location, "complex real part overflow");
15895 ret = false;
15898 if (!mpfr_nan_p(imag)
15899 && !mpfr_inf_p(imag)
15900 && !mpfr_zero_p(imag)
15901 && mpfr_get_exp(imag) > max_exp)
15903 if (issue_error)
15904 error_at(location, "complex imaginary part overflow");
15905 ret = false;
15908 if (ret)
15910 // Round the constant to the desired type.
15911 mpfr_t t;
15912 mpfr_init(t);
15913 switch (type->bits())
15915 case 64:
15916 mpfr_set_prec(t, 24);
15917 break;
15918 case 128:
15919 mpfr_set_prec(t, 53);
15920 break;
15921 default:
15922 go_unreachable();
15924 mpfr_set(t, real, GMP_RNDN);
15925 mpfr_set(real, t, GMP_RNDN);
15926 mpfr_set(t, imag, GMP_RNDN);
15927 mpfr_set(imag, t, GMP_RNDN);
15928 mpfr_clear(t);
15930 this->set_complex(type, real, imag);
15933 mpfr_clear(real);
15934 mpfr_clear(imag);
15936 return ret;
15939 // Return an Expression for this value.
15941 Expression*
15942 Numeric_constant::expression(Location loc) const
15944 switch (this->classification_)
15946 case NC_INT:
15947 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
15948 case NC_RUNE:
15949 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15950 case NC_FLOAT:
15951 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15952 case NC_COMPLEX:
15953 return Expression::make_complex(&this->u_.complex_val.real,
15954 &this->u_.complex_val.imag,
15955 this->type_, loc);
15956 default:
15957 go_unreachable();