compiler: Report errors for malformed builtin calls.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blob976e34b3688b409fbaa95ff15fb10470dd2c3c28
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*, 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 // This conversion must be permitted by Go, or we wouldn't have
181 // gotten here.
182 return Expression::make_unsafe_cast(lhs_type, rhs, location);
184 else
185 return rhs;
188 // Return an expression for a conversion from a non-interface type to an
189 // interface type.
191 Expression*
192 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
193 Location location)
195 Interface_type* lhs_interface_type = lhs_type->interface_type();
196 bool lhs_is_empty = lhs_interface_type->is_empty();
198 // Since RHS_TYPE is a static type, we can create the interface
199 // method table at compile time.
201 // When setting an interface to nil, we just set both fields to
202 // NULL.
203 Type* rhs_type = rhs->type();
204 if (rhs_type->is_nil_type())
206 Expression* nil = Expression::make_nil(location);
207 return Expression::make_interface_value(lhs_type, nil, nil, location);
210 // This should have been checked already.
211 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
213 // An interface is a tuple. If LHS_TYPE is an empty interface type,
214 // then the first field is the type descriptor for RHS_TYPE.
215 // Otherwise it is the interface method table for RHS_TYPE.
216 Expression* first_field;
217 if (lhs_is_empty)
218 first_field = Expression::make_type_descriptor(rhs_type, location);
219 else
221 // Build the interface method table for this interface and this
222 // object type: a list of function pointers for each interface
223 // method.
224 Named_type* rhs_named_type = rhs_type->named_type();
225 Struct_type* rhs_struct_type = rhs_type->struct_type();
226 bool is_pointer = false;
227 if (rhs_named_type == NULL && rhs_struct_type == NULL)
229 rhs_named_type = rhs_type->deref()->named_type();
230 rhs_struct_type = rhs_type->deref()->struct_type();
231 is_pointer = true;
233 if (rhs_named_type != NULL)
234 first_field =
235 rhs_named_type->interface_method_table(lhs_interface_type,
236 is_pointer);
237 else if (rhs_struct_type != NULL)
238 first_field =
239 rhs_struct_type->interface_method_table(lhs_interface_type,
240 is_pointer);
241 else
242 first_field = Expression::make_nil(location);
245 Expression* obj;
246 if (rhs_type->points_to() != NULL)
248 // We are assigning a pointer to the interface; the interface
249 // holds the pointer itself.
250 obj = rhs;
252 else
254 // We are assigning a non-pointer value to the interface; the
255 // interface gets a copy of the value in the heap.
256 obj = Expression::make_heap_expression(rhs, location);
259 return Expression::make_interface_value(lhs_type, first_field, obj, location);
262 // Return an expression for the type descriptor of RHS.
264 Expression*
265 Expression::get_interface_type_descriptor(Expression* rhs)
267 go_assert(rhs->type()->interface_type() != NULL);
268 Location location = rhs->location();
270 // The type descriptor is the first field of an empty interface.
271 if (rhs->type()->interface_type()->is_empty())
272 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
273 location);
275 Expression* mtable =
276 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
278 Expression* descriptor =
279 Expression::make_unary(OPERATOR_MULT, mtable, location);
280 descriptor = Expression::make_field_reference(descriptor, 0, location);
281 Expression* nil = Expression::make_nil(location);
283 Expression* eq =
284 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
285 return Expression::make_conditional(eq, nil, descriptor, location);
288 // Return an expression for the conversion of an interface type to an
289 // interface type.
291 Expression*
292 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
293 bool for_type_guard,
294 Location location)
296 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
297 return rhs;
299 Interface_type* lhs_interface_type = lhs_type->interface_type();
300 bool lhs_is_empty = lhs_interface_type->is_empty();
302 // In the general case this requires runtime examination of the type
303 // method table to match it up with the interface methods.
305 // FIXME: If all of the methods in the right hand side interface
306 // also appear in the left hand side interface, then we don't need
307 // to do a runtime check, although we still need to build a new
308 // method table.
310 // We are going to evaluate RHS multiple times.
311 go_assert(rhs->is_variable());
313 // Get the type descriptor for the right hand side. This will be
314 // NULL for a nil interface.
315 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
316 Expression* lhs_type_expr =
317 Expression::make_type_descriptor(lhs_type, location);
319 Expression* first_field;
320 if (for_type_guard)
322 // A type assertion fails when converting a nil interface.
323 first_field =
324 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
325 lhs_type_expr, rhs_type_expr);
327 else if (lhs_is_empty)
329 // A conversion to an empty interface always succeeds, and the
330 // first field is just the type descriptor of the object.
331 first_field = rhs_type_expr;
333 else
335 // A conversion to a non-empty interface may fail, but unlike a
336 // type assertion converting nil will always succeed.
337 first_field =
338 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
339 lhs_type_expr, rhs_type_expr);
342 // The second field is simply the object pointer.
343 Expression* obj =
344 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
345 return Expression::make_interface_value(lhs_type, first_field, obj, location);
348 // Return an expression for the conversion of an interface type to a
349 // non-interface type.
351 Expression*
352 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
353 Location location)
355 // We are going to evaluate RHS multiple times.
356 go_assert(rhs->is_variable());
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 mpc_t cval;
440 if (!val->to_complex(&cval))
442 go_assert(saw_errors());
443 return gogo->backend()->error_expression();
445 ret = gogo->backend()->complex_constant_expression(btype, cval);
446 mpc_clear(cval);
448 else
449 go_unreachable();
451 return ret;
454 // Return an expression which evaluates to true if VAL, of arbitrary integer
455 // type, is negative or is more than the maximum value of the Go type "int".
457 Expression*
458 Expression::check_bounds(Expression* val, Location loc)
460 Type* val_type = val->type();
461 Type* bound_type = Type::lookup_integer_type("int");
463 int val_type_size;
464 bool val_is_unsigned = false;
465 if (val_type->integer_type() != NULL)
467 val_type_size = val_type->integer_type()->bits();
468 val_is_unsigned = val_type->integer_type()->is_unsigned();
470 else
472 if (!val_type->is_numeric_type()
473 || !Type::are_convertible(bound_type, val_type, NULL))
475 go_assert(saw_errors());
476 return Expression::make_boolean(true, loc);
479 if (val_type->complex_type() != NULL)
480 val_type_size = val_type->complex_type()->bits();
481 else
482 val_type_size = val_type->float_type()->bits();
485 Expression* negative_index = Expression::make_boolean(false, loc);
486 Expression* index_overflows = Expression::make_boolean(false, loc);
487 if (!val_is_unsigned)
489 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
490 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
493 int bound_type_size = bound_type->integer_type()->bits();
494 if (val_type_size > bound_type_size
495 || (val_type_size == bound_type_size
496 && val_is_unsigned))
498 mpz_t one;
499 mpz_init_set_ui(one, 1UL);
501 // maxval = 2^(bound_type_size - 1) - 1
502 mpz_t maxval;
503 mpz_init(maxval);
504 mpz_mul_2exp(maxval, one, bound_type_size - 1);
505 mpz_sub_ui(maxval, maxval, 1);
506 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
507 mpz_clear(one);
508 mpz_clear(maxval);
510 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
513 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
514 loc);
517 void
518 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
520 this->do_dump_expression(ast_dump_context);
523 // Error expressions. This are used to avoid cascading errors.
525 class Error_expression : public Expression
527 public:
528 Error_expression(Location location)
529 : Expression(EXPRESSION_ERROR, location)
532 protected:
533 bool
534 do_is_constant() const
535 { return true; }
537 bool
538 do_is_immutable() const
539 { return true; }
541 bool
542 do_numeric_constant_value(Numeric_constant* nc) const
544 nc->set_unsigned_long(NULL, 0);
545 return true;
548 bool
549 do_discarding_value()
550 { return true; }
552 Type*
553 do_type()
554 { return Type::make_error_type(); }
556 void
557 do_determine_type(const Type_context*)
560 Expression*
561 do_copy()
562 { return this; }
564 bool
565 do_is_addressable() const
566 { return true; }
568 Bexpression*
569 do_get_backend(Translate_context* context)
570 { return context->backend()->error_expression(); }
572 void
573 do_dump_expression(Ast_dump_context*) const;
576 // Dump the ast representation for an error expression to a dump context.
578 void
579 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
581 ast_dump_context->ostream() << "_Error_" ;
584 Expression*
585 Expression::make_error(Location location)
587 return new Error_expression(location);
590 // An expression which is really a type. This is used during parsing.
591 // It is an error if these survive after lowering.
593 class
594 Type_expression : public Expression
596 public:
597 Type_expression(Type* type, Location location)
598 : Expression(EXPRESSION_TYPE, location),
599 type_(type)
602 protected:
604 do_traverse(Traverse* traverse)
605 { return Type::traverse(this->type_, traverse); }
607 Type*
608 do_type()
609 { return this->type_; }
611 void
612 do_determine_type(const Type_context*)
615 void
616 do_check_types(Gogo*)
617 { this->report_error(_("invalid use of type")); }
619 Expression*
620 do_copy()
621 { return this; }
623 Bexpression*
624 do_get_backend(Translate_context*)
625 { go_unreachable(); }
627 void do_dump_expression(Ast_dump_context*) const;
629 private:
630 // The type which we are representing as an expression.
631 Type* type_;
634 void
635 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
637 ast_dump_context->dump_type(this->type_);
640 Expression*
641 Expression::make_type(Type* type, Location location)
643 return new Type_expression(type, location);
646 // Class Parser_expression.
648 Type*
649 Parser_expression::do_type()
651 // We should never really ask for the type of a Parser_expression.
652 // However, it can happen, at least when we have an invalid const
653 // whose initializer refers to the const itself. In that case we
654 // may ask for the type when lowering the const itself.
655 go_assert(saw_errors());
656 return Type::make_error_type();
659 // Class Var_expression.
661 // Lower a variable expression. Here we just make sure that the
662 // initialization expression of the variable has been lowered. This
663 // ensures that we will be able to determine the type of the variable
664 // if necessary.
666 Expression*
667 Var_expression::do_lower(Gogo* gogo, Named_object* function,
668 Statement_inserter* inserter, int)
670 if (this->variable_->is_variable())
672 Variable* var = this->variable_->var_value();
673 // This is either a local variable or a global variable. A
674 // reference to a variable which is local to an enclosing
675 // function will be a reference to a field in a closure.
676 if (var->is_global())
678 function = NULL;
679 inserter = NULL;
681 var->lower_init_expression(gogo, function, inserter);
683 return this;
686 // Return the type of a reference to a variable.
688 Type*
689 Var_expression::do_type()
691 if (this->variable_->is_variable())
692 return this->variable_->var_value()->type();
693 else if (this->variable_->is_result_variable())
694 return this->variable_->result_var_value()->type();
695 else
696 go_unreachable();
699 // Determine the type of a reference to a variable.
701 void
702 Var_expression::do_determine_type(const Type_context*)
704 if (this->variable_->is_variable())
705 this->variable_->var_value()->determine_type();
708 // Something takes the address of this variable. This means that we
709 // may want to move the variable onto the heap.
711 void
712 Var_expression::do_address_taken(bool escapes)
714 if (!escapes)
716 if (this->variable_->is_variable())
717 this->variable_->var_value()->set_non_escaping_address_taken();
718 else if (this->variable_->is_result_variable())
719 this->variable_->result_var_value()->set_non_escaping_address_taken();
720 else
721 go_unreachable();
723 else
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_address_taken();
729 else
730 go_unreachable();
734 // Get the backend representation for a reference to a variable.
736 Bexpression*
737 Var_expression::do_get_backend(Translate_context* context)
739 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
740 context->function());
741 bool is_in_heap;
742 Location loc = this->location();
743 Btype* btype;
744 Gogo* gogo = context->gogo();
745 if (this->variable_->is_variable())
747 is_in_heap = this->variable_->var_value()->is_in_heap();
748 btype = this->variable_->var_value()->type()->get_backend(gogo);
750 else if (this->variable_->is_result_variable())
752 is_in_heap = this->variable_->result_var_value()->is_in_heap();
753 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
755 else
756 go_unreachable();
758 Bexpression* ret = context->backend()->var_expression(bvar, loc);
759 if (is_in_heap)
760 ret = context->backend()->indirect_expression(btype, ret, true, loc);
761 return ret;
764 // Ast dump for variable expression.
766 void
767 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
769 ast_dump_context->ostream() << this->variable_->name() ;
772 // Make a reference to a variable in an expression.
774 Expression*
775 Expression::make_var_reference(Named_object* var, Location location)
777 if (var->is_sink())
778 return Expression::make_sink(location);
780 // FIXME: Creating a new object for each reference to a variable is
781 // wasteful.
782 return new Var_expression(var, location);
785 // Class Temporary_reference_expression.
787 // The type.
789 Type*
790 Temporary_reference_expression::do_type()
792 return this->statement_->type();
795 // Called if something takes the address of this temporary variable.
796 // We never have to move temporary variables to the heap, but we do
797 // need to know that they must live in the stack rather than in a
798 // register.
800 void
801 Temporary_reference_expression::do_address_taken(bool)
803 this->statement_->set_is_address_taken();
806 // Get a backend expression referring to the variable.
808 Bexpression*
809 Temporary_reference_expression::do_get_backend(Translate_context* context)
811 Gogo* gogo = context->gogo();
812 Bvariable* bvar = this->statement_->get_backend_variable(context);
813 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
815 // The backend can't always represent the same set of recursive types
816 // that the Go frontend can. In some cases this means that a
817 // temporary variable won't have the right backend type. Correct
818 // that here by adding a type cast. We need to use base() to push
819 // the circularity down one level.
820 Type* stype = this->statement_->type();
821 if (!this->is_lvalue_
822 && stype->has_pointer()
823 && stype->deref()->is_void_type())
825 Btype* btype = this->type()->base()->get_backend(gogo);
826 ret = gogo->backend()->convert_expression(btype, ret, this->location());
828 return ret;
831 // Ast dump for temporary reference.
833 void
834 Temporary_reference_expression::do_dump_expression(
835 Ast_dump_context* ast_dump_context) const
837 ast_dump_context->dump_temp_variable_name(this->statement_);
840 // Make a reference to a temporary variable.
842 Temporary_reference_expression*
843 Expression::make_temporary_reference(Temporary_statement* statement,
844 Location location)
846 return new Temporary_reference_expression(statement, location);
849 // Class Set_and_use_temporary_expression.
851 // Return the type.
853 Type*
854 Set_and_use_temporary_expression::do_type()
856 return this->statement_->type();
859 // Determine the type of the expression.
861 void
862 Set_and_use_temporary_expression::do_determine_type(
863 const Type_context* context)
865 this->expr_->determine_type(context);
868 // Take the address.
870 void
871 Set_and_use_temporary_expression::do_address_taken(bool)
873 this->statement_->set_is_address_taken();
876 // Return the backend representation.
878 Bexpression*
879 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
881 Location loc = this->location();
882 Gogo* gogo = context->gogo();
883 Bvariable* bvar = this->statement_->get_backend_variable(context);
884 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
886 Bexpression* bexpr = this->expr_->get_backend(context);
887 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
888 var_ref = gogo->backend()->var_expression(bvar, loc);
889 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
890 return ret;
893 // Dump.
895 void
896 Set_and_use_temporary_expression::do_dump_expression(
897 Ast_dump_context* ast_dump_context) const
899 ast_dump_context->ostream() << '(';
900 ast_dump_context->dump_temp_variable_name(this->statement_);
901 ast_dump_context->ostream() << " = ";
902 this->expr_->dump_expression(ast_dump_context);
903 ast_dump_context->ostream() << ')';
906 // Make a set-and-use temporary.
908 Set_and_use_temporary_expression*
909 Expression::make_set_and_use_temporary(Temporary_statement* statement,
910 Expression* expr, Location location)
912 return new Set_and_use_temporary_expression(statement, expr, location);
915 // A sink expression--a use of the blank identifier _.
917 class Sink_expression : public Expression
919 public:
920 Sink_expression(Location location)
921 : Expression(EXPRESSION_SINK, location),
922 type_(NULL), bvar_(NULL)
925 protected:
926 bool
927 do_discarding_value()
928 { return true; }
930 Type*
931 do_type();
933 void
934 do_determine_type(const Type_context*);
936 Expression*
937 do_copy()
938 { return new Sink_expression(this->location()); }
940 Bexpression*
941 do_get_backend(Translate_context*);
943 void
944 do_dump_expression(Ast_dump_context*) const;
946 private:
947 // The type of this sink variable.
948 Type* type_;
949 // The temporary variable we generate.
950 Bvariable* bvar_;
953 // Return the type of a sink expression.
955 Type*
956 Sink_expression::do_type()
958 if (this->type_ == NULL)
959 return Type::make_sink_type();
960 return this->type_;
963 // Determine the type of a sink expression.
965 void
966 Sink_expression::do_determine_type(const Type_context* context)
968 if (context->type != NULL)
969 this->type_ = context->type;
972 // Return a temporary variable for a sink expression. This will
973 // presumably be a write-only variable which the middle-end will drop.
975 Bexpression*
976 Sink_expression::do_get_backend(Translate_context* context)
978 Location loc = this->location();
979 Gogo* gogo = context->gogo();
980 if (this->bvar_ == NULL)
982 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
983 Named_object* fn = context->function();
984 go_assert(fn != NULL);
985 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
986 Btype* bt = this->type_->get_backend(context->gogo());
987 Bstatement* decl;
988 this->bvar_ =
989 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
990 false, loc, &decl);
991 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
992 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
993 return var_ref;
995 return gogo->backend()->var_expression(this->bvar_, loc);
998 // Ast dump for sink expression.
1000 void
1001 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1003 ast_dump_context->ostream() << "_" ;
1006 // Make a sink expression.
1008 Expression*
1009 Expression::make_sink(Location location)
1011 return new Sink_expression(location);
1014 // Class Func_expression.
1016 // FIXME: Can a function expression appear in a constant expression?
1017 // The value is unchanging. Initializing a constant to the address of
1018 // a function seems like it could work, though there might be little
1019 // point to it.
1021 // Traversal.
1024 Func_expression::do_traverse(Traverse* traverse)
1026 return (this->closure_ == NULL
1027 ? TRAVERSE_CONTINUE
1028 : Expression::traverse(&this->closure_, traverse));
1031 // Return the type of a function expression.
1033 Type*
1034 Func_expression::do_type()
1036 if (this->function_->is_function())
1037 return this->function_->func_value()->type();
1038 else if (this->function_->is_function_declaration())
1039 return this->function_->func_declaration_value()->type();
1040 else
1041 go_unreachable();
1044 // Get the backend representation for the code of a function expression.
1046 Bexpression*
1047 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1049 Function_type* fntype;
1050 if (no->is_function())
1051 fntype = no->func_value()->type();
1052 else if (no->is_function_declaration())
1053 fntype = no->func_declaration_value()->type();
1054 else
1055 go_unreachable();
1057 // Builtin functions are handled specially by Call_expression. We
1058 // can't take their address.
1059 if (fntype->is_builtin())
1061 error_at(loc,
1062 "invalid use of special builtin function %qs; must be called",
1063 no->message_name().c_str());
1064 return gogo->backend()->error_expression();
1067 Bfunction* fndecl;
1068 if (no->is_function())
1069 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1070 else if (no->is_function_declaration())
1071 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1072 else
1073 go_unreachable();
1075 return gogo->backend()->function_code_expression(fndecl, loc);
1078 // Get the backend representation for a function expression. This is used when
1079 // we take the address of a function rather than simply calling it. A func
1080 // value is represented as a pointer to a block of memory. The first
1081 // word of that memory is a pointer to the function code. The
1082 // remaining parts of that memory are the addresses of variables that
1083 // the function closes over.
1085 Bexpression*
1086 Func_expression::do_get_backend(Translate_context* context)
1088 // If there is no closure, just use the function descriptor.
1089 if (this->closure_ == NULL)
1091 Gogo* gogo = context->gogo();
1092 Named_object* no = this->function_;
1093 Expression* descriptor;
1094 if (no->is_function())
1095 descriptor = no->func_value()->descriptor(gogo, no);
1096 else if (no->is_function_declaration())
1098 if (no->func_declaration_value()->type()->is_builtin())
1100 error_at(this->location(),
1101 ("invalid use of special builtin function %qs; "
1102 "must be called"),
1103 no->message_name().c_str());
1104 return gogo->backend()->error_expression();
1106 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1108 else
1109 go_unreachable();
1111 Bexpression* bdesc = descriptor->get_backend(context);
1112 return gogo->backend()->address_expression(bdesc, this->location());
1115 go_assert(this->function_->func_value()->enclosing() != NULL);
1117 // If there is a closure, then the closure is itself the function
1118 // expression. It is a pointer to a struct whose first field points
1119 // to the function code and whose remaining fields are the addresses
1120 // of the closed-over variables.
1121 return this->closure_->get_backend(context);
1124 // Ast dump for function.
1126 void
1127 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1129 ast_dump_context->ostream() << this->function_->name();
1130 if (this->closure_ != NULL)
1132 ast_dump_context->ostream() << " {closure = ";
1133 this->closure_->dump_expression(ast_dump_context);
1134 ast_dump_context->ostream() << "}";
1138 // Make a reference to a function in an expression.
1140 Expression*
1141 Expression::make_func_reference(Named_object* function, Expression* closure,
1142 Location location)
1144 return new Func_expression(function, closure, location);
1147 // Class Func_descriptor_expression.
1149 // Constructor.
1151 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1152 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1153 fn_(fn), dvar_(NULL)
1155 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1158 // Traversal.
1161 Func_descriptor_expression::do_traverse(Traverse*)
1163 return TRAVERSE_CONTINUE;
1166 // All function descriptors have the same type.
1168 Type* Func_descriptor_expression::descriptor_type;
1170 void
1171 Func_descriptor_expression::make_func_descriptor_type()
1173 if (Func_descriptor_expression::descriptor_type != NULL)
1174 return;
1175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1176 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1177 Func_descriptor_expression::descriptor_type =
1178 Type::make_builtin_named_type("functionDescriptor", struct_type);
1181 Type*
1182 Func_descriptor_expression::do_type()
1184 Func_descriptor_expression::make_func_descriptor_type();
1185 return Func_descriptor_expression::descriptor_type;
1188 // The backend representation for a function descriptor.
1190 Bexpression*
1191 Func_descriptor_expression::do_get_backend(Translate_context* context)
1193 Named_object* no = this->fn_;
1194 Location loc = no->location();
1195 if (this->dvar_ != NULL)
1196 return context->backend()->var_expression(this->dvar_, loc);
1198 Gogo* gogo = context->gogo();
1199 std::string var_name;
1200 if (no->package() == NULL)
1201 var_name = gogo->pkgpath_symbol();
1202 else
1203 var_name = no->package()->pkgpath_symbol();
1204 var_name.push_back('.');
1205 var_name.append(Gogo::unpack_hidden_name(no->name()));
1206 var_name.append("$descriptor");
1208 Btype* btype = this->type()->get_backend(gogo);
1210 Bvariable* bvar;
1211 if (no->package() != NULL
1212 || Linemap::is_predeclared_location(no->location()))
1213 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1214 loc);
1215 else
1217 Location bloc = Linemap::predeclared_location();
1218 bool is_hidden = ((no->is_function()
1219 && no->func_value()->enclosing() != NULL)
1220 || Gogo::is_thunk(no));
1221 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1222 btype, bloc);
1223 Expression_list* vals = new Expression_list();
1224 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1225 Expression* init =
1226 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1227 Translate_context bcontext(gogo, NULL, NULL, NULL);
1228 bcontext.set_is_const();
1229 Bexpression* binit = init->get_backend(&bcontext);
1230 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1231 false, btype, bloc, binit);
1234 this->dvar_ = bvar;
1235 return gogo->backend()->var_expression(bvar, loc);
1238 // Print a function descriptor expression.
1240 void
1241 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1243 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1246 // Make a function descriptor expression.
1248 Func_descriptor_expression*
1249 Expression::make_func_descriptor(Named_object* fn)
1251 return new Func_descriptor_expression(fn);
1254 // Make the function descriptor type, so that it can be converted.
1256 void
1257 Expression::make_func_descriptor_type()
1259 Func_descriptor_expression::make_func_descriptor_type();
1262 // A reference to just the code of a function.
1264 class Func_code_reference_expression : public Expression
1266 public:
1267 Func_code_reference_expression(Named_object* function, Location location)
1268 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1269 function_(function)
1272 protected:
1274 do_traverse(Traverse*)
1275 { return TRAVERSE_CONTINUE; }
1277 bool
1278 do_is_immutable() const
1279 { return true; }
1281 Type*
1282 do_type()
1283 { return Type::make_pointer_type(Type::make_void_type()); }
1285 void
1286 do_determine_type(const Type_context*)
1289 Expression*
1290 do_copy()
1292 return Expression::make_func_code_reference(this->function_,
1293 this->location());
1296 Bexpression*
1297 do_get_backend(Translate_context*);
1299 void
1300 do_dump_expression(Ast_dump_context* context) const
1301 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1303 private:
1304 // The function.
1305 Named_object* function_;
1308 // Get the backend representation for a reference to function code.
1310 Bexpression*
1311 Func_code_reference_expression::do_get_backend(Translate_context* context)
1313 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1314 this->location());
1317 // Make a reference to the code of a function.
1319 Expression*
1320 Expression::make_func_code_reference(Named_object* function, Location location)
1322 return new Func_code_reference_expression(function, location);
1325 // Class Unknown_expression.
1327 // Return the name of an unknown expression.
1329 const std::string&
1330 Unknown_expression::name() const
1332 return this->named_object_->name();
1335 // Lower a reference to an unknown name.
1337 Expression*
1338 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1340 Location location = this->location();
1341 Named_object* no = this->named_object_;
1342 Named_object* real;
1343 if (!no->is_unknown())
1344 real = no;
1345 else
1347 real = no->unknown_value()->real_named_object();
1348 if (real == NULL)
1350 if (this->is_composite_literal_key_)
1351 return this;
1352 if (!this->no_error_message_)
1353 error_at(location, "reference to undefined name %qs",
1354 this->named_object_->message_name().c_str());
1355 return Expression::make_error(location);
1358 switch (real->classification())
1360 case Named_object::NAMED_OBJECT_CONST:
1361 return Expression::make_const_reference(real, location);
1362 case Named_object::NAMED_OBJECT_TYPE:
1363 return Expression::make_type(real->type_value(), location);
1364 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1365 if (this->is_composite_literal_key_)
1366 return this;
1367 if (!this->no_error_message_)
1368 error_at(location, "reference to undefined type %qs",
1369 real->message_name().c_str());
1370 return Expression::make_error(location);
1371 case Named_object::NAMED_OBJECT_VAR:
1372 real->var_value()->set_is_used();
1373 return Expression::make_var_reference(real, location);
1374 case Named_object::NAMED_OBJECT_FUNC:
1375 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1376 return Expression::make_func_reference(real, NULL, location);
1377 case Named_object::NAMED_OBJECT_PACKAGE:
1378 if (this->is_composite_literal_key_)
1379 return this;
1380 if (!this->no_error_message_)
1381 error_at(location, "unexpected reference to package");
1382 return Expression::make_error(location);
1383 default:
1384 go_unreachable();
1388 // Dump the ast representation for an unknown expression to a dump context.
1390 void
1391 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1393 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1394 << ")";
1397 // Make a reference to an unknown name.
1399 Unknown_expression*
1400 Expression::make_unknown_reference(Named_object* no, Location location)
1402 return new Unknown_expression(no, location);
1405 // A boolean expression.
1407 class Boolean_expression : public Expression
1409 public:
1410 Boolean_expression(bool val, Location location)
1411 : Expression(EXPRESSION_BOOLEAN, location),
1412 val_(val), type_(NULL)
1415 static Expression*
1416 do_import(Import*);
1418 protected:
1419 bool
1420 do_is_constant() const
1421 { return true; }
1423 bool
1424 do_is_immutable() const
1425 { return true; }
1427 Type*
1428 do_type();
1430 void
1431 do_determine_type(const Type_context*);
1433 Expression*
1434 do_copy()
1435 { return this; }
1437 Bexpression*
1438 do_get_backend(Translate_context* context)
1439 { return context->backend()->boolean_constant_expression(this->val_); }
1441 void
1442 do_export(Export* exp) const
1443 { exp->write_c_string(this->val_ ? "true" : "false"); }
1445 void
1446 do_dump_expression(Ast_dump_context* ast_dump_context) const
1447 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1449 private:
1450 // The constant.
1451 bool val_;
1452 // The type as determined by context.
1453 Type* type_;
1456 // Get the type.
1458 Type*
1459 Boolean_expression::do_type()
1461 if (this->type_ == NULL)
1462 this->type_ = Type::make_boolean_type();
1463 return this->type_;
1466 // Set the type from the context.
1468 void
1469 Boolean_expression::do_determine_type(const Type_context* context)
1471 if (this->type_ != NULL && !this->type_->is_abstract())
1473 else if (context->type != NULL && context->type->is_boolean_type())
1474 this->type_ = context->type;
1475 else if (!context->may_be_abstract)
1476 this->type_ = Type::lookup_bool_type();
1479 // Import a boolean constant.
1481 Expression*
1482 Boolean_expression::do_import(Import* imp)
1484 if (imp->peek_char() == 't')
1486 imp->require_c_string("true");
1487 return Expression::make_boolean(true, imp->location());
1489 else
1491 imp->require_c_string("false");
1492 return Expression::make_boolean(false, imp->location());
1496 // Make a boolean expression.
1498 Expression*
1499 Expression::make_boolean(bool val, Location location)
1501 return new Boolean_expression(val, location);
1504 // Class String_expression.
1506 // Get the type.
1508 Type*
1509 String_expression::do_type()
1511 if (this->type_ == NULL)
1512 this->type_ = Type::make_string_type();
1513 return this->type_;
1516 // Set the type from the context.
1518 void
1519 String_expression::do_determine_type(const Type_context* context)
1521 if (this->type_ != NULL && !this->type_->is_abstract())
1523 else if (context->type != NULL && context->type->is_string_type())
1524 this->type_ = context->type;
1525 else if (!context->may_be_abstract)
1526 this->type_ = Type::lookup_string_type();
1529 // Build a string constant.
1531 Bexpression*
1532 String_expression::do_get_backend(Translate_context* context)
1534 Gogo* gogo = context->gogo();
1535 Btype* btype = Type::make_string_type()->get_backend(gogo);
1537 Location loc = this->location();
1538 std::vector<Bexpression*> init(2);
1539 Bexpression* str_cst =
1540 gogo->backend()->string_constant_expression(this->val_);
1541 init[0] = gogo->backend()->address_expression(str_cst, loc);
1543 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1544 mpz_t lenval;
1545 mpz_init_set_ui(lenval, this->val_.length());
1546 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1547 mpz_clear(lenval);
1549 return gogo->backend()->constructor_expression(btype, init, loc);
1552 // Write string literal to string dump.
1554 void
1555 String_expression::export_string(String_dump* exp,
1556 const String_expression* str)
1558 std::string s;
1559 s.reserve(str->val_.length() * 4 + 2);
1560 s += '"';
1561 for (std::string::const_iterator p = str->val_.begin();
1562 p != str->val_.end();
1563 ++p)
1565 if (*p == '\\' || *p == '"')
1567 s += '\\';
1568 s += *p;
1570 else if (*p >= 0x20 && *p < 0x7f)
1571 s += *p;
1572 else if (*p == '\n')
1573 s += "\\n";
1574 else if (*p == '\t')
1575 s += "\\t";
1576 else
1578 s += "\\x";
1579 unsigned char c = *p;
1580 unsigned int dig = c >> 4;
1581 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1582 dig = c & 0xf;
1583 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1586 s += '"';
1587 exp->write_string(s);
1590 // Export a string expression.
1592 void
1593 String_expression::do_export(Export* exp) const
1595 String_expression::export_string(exp, this);
1598 // Import a string expression.
1600 Expression*
1601 String_expression::do_import(Import* imp)
1603 imp->require_c_string("\"");
1604 std::string val;
1605 while (true)
1607 int c = imp->get_char();
1608 if (c == '"' || c == -1)
1609 break;
1610 if (c != '\\')
1611 val += static_cast<char>(c);
1612 else
1614 c = imp->get_char();
1615 if (c == '\\' || c == '"')
1616 val += static_cast<char>(c);
1617 else if (c == 'n')
1618 val += '\n';
1619 else if (c == 't')
1620 val += '\t';
1621 else if (c == 'x')
1623 c = imp->get_char();
1624 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1625 c = imp->get_char();
1626 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1627 char v = (vh << 4) | vl;
1628 val += v;
1630 else
1632 error_at(imp->location(), "bad string constant");
1633 return Expression::make_error(imp->location());
1637 return Expression::make_string(val, imp->location());
1640 // Ast dump for string expression.
1642 void
1643 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1645 String_expression::export_string(ast_dump_context, this);
1648 // Make a string expression.
1650 Expression*
1651 Expression::make_string(const std::string& val, Location location)
1653 return new String_expression(val, location);
1656 // An expression that evaluates to some characteristic of a string.
1657 // This is used when indexing, bound-checking, or nil checking a string.
1659 class String_info_expression : public Expression
1661 public:
1662 String_info_expression(Expression* string, String_info string_info,
1663 Location location)
1664 : Expression(EXPRESSION_STRING_INFO, location),
1665 string_(string), string_info_(string_info)
1668 protected:
1669 Type*
1670 do_type();
1672 void
1673 do_determine_type(const Type_context*)
1674 { go_unreachable(); }
1676 Expression*
1677 do_copy()
1679 return new String_info_expression(this->string_->copy(), this->string_info_,
1680 this->location());
1683 Bexpression*
1684 do_get_backend(Translate_context* context);
1686 void
1687 do_dump_expression(Ast_dump_context*) const;
1689 void
1690 do_issue_nil_check()
1691 { this->string_->issue_nil_check(); }
1693 private:
1694 // The string for which we are getting information.
1695 Expression* string_;
1696 // What information we want.
1697 String_info string_info_;
1700 // Return the type of the string info.
1702 Type*
1703 String_info_expression::do_type()
1705 switch (this->string_info_)
1707 case STRING_INFO_DATA:
1709 Type* byte_type = Type::lookup_integer_type("uint8");
1710 return Type::make_pointer_type(byte_type);
1712 case STRING_INFO_LENGTH:
1713 return Type::lookup_integer_type("int");
1714 default:
1715 go_unreachable();
1719 // Return string information in GENERIC.
1721 Bexpression*
1722 String_info_expression::do_get_backend(Translate_context* context)
1724 Gogo* gogo = context->gogo();
1726 Bexpression* bstring = this->string_->get_backend(context);
1727 switch (this->string_info_)
1729 case STRING_INFO_DATA:
1730 case STRING_INFO_LENGTH:
1731 return gogo->backend()->struct_field_expression(bstring,
1732 this->string_info_,
1733 this->location());
1734 break;
1735 default:
1736 go_unreachable();
1740 // Dump ast representation for a type info expression.
1742 void
1743 String_info_expression::do_dump_expression(
1744 Ast_dump_context* ast_dump_context) const
1746 ast_dump_context->ostream() << "stringinfo(";
1747 this->string_->dump_expression(ast_dump_context);
1748 ast_dump_context->ostream() << ",";
1749 ast_dump_context->ostream() <<
1750 (this->string_info_ == STRING_INFO_DATA ? "data"
1751 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1752 : "unknown");
1753 ast_dump_context->ostream() << ")";
1756 // Make a string info expression.
1758 Expression*
1759 Expression::make_string_info(Expression* string, String_info string_info,
1760 Location location)
1762 return new String_info_expression(string, string_info, location);
1765 // Make an integer expression.
1767 class Integer_expression : public Expression
1769 public:
1770 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1771 Location location)
1772 : Expression(EXPRESSION_INTEGER, location),
1773 type_(type), is_character_constant_(is_character_constant)
1774 { mpz_init_set(this->val_, *val); }
1776 static Expression*
1777 do_import(Import*);
1779 // Write VAL to string dump.
1780 static void
1781 export_integer(String_dump* exp, const mpz_t val);
1783 // Write VAL to dump context.
1784 static void
1785 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1787 protected:
1788 bool
1789 do_is_constant() const
1790 { return true; }
1792 bool
1793 do_is_immutable() const
1794 { return true; }
1796 bool
1797 do_numeric_constant_value(Numeric_constant* nc) const;
1799 Type*
1800 do_type();
1802 void
1803 do_determine_type(const Type_context* context);
1805 void
1806 do_check_types(Gogo*);
1808 Bexpression*
1809 do_get_backend(Translate_context*);
1811 Expression*
1812 do_copy()
1814 if (this->is_character_constant_)
1815 return Expression::make_character(&this->val_, this->type_,
1816 this->location());
1817 else
1818 return Expression::make_integer_z(&this->val_, this->type_,
1819 this->location());
1822 void
1823 do_export(Export*) const;
1825 void
1826 do_dump_expression(Ast_dump_context*) const;
1828 private:
1829 // The integer value.
1830 mpz_t val_;
1831 // The type so far.
1832 Type* type_;
1833 // Whether this is a character constant.
1834 bool is_character_constant_;
1837 // Return a numeric constant for this expression. We have to mark
1838 // this as a character when appropriate.
1840 bool
1841 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1843 if (this->is_character_constant_)
1844 nc->set_rune(this->type_, this->val_);
1845 else
1846 nc->set_int(this->type_, this->val_);
1847 return true;
1850 // Return the current type. If we haven't set the type yet, we return
1851 // an abstract integer type.
1853 Type*
1854 Integer_expression::do_type()
1856 if (this->type_ == NULL)
1858 if (this->is_character_constant_)
1859 this->type_ = Type::make_abstract_character_type();
1860 else
1861 this->type_ = Type::make_abstract_integer_type();
1863 return this->type_;
1866 // Set the type of the integer value. Here we may switch from an
1867 // abstract type to a real type.
1869 void
1870 Integer_expression::do_determine_type(const Type_context* context)
1872 if (this->type_ != NULL && !this->type_->is_abstract())
1874 else if (context->type != NULL && context->type->is_numeric_type())
1875 this->type_ = context->type;
1876 else if (!context->may_be_abstract)
1878 if (this->is_character_constant_)
1879 this->type_ = Type::lookup_integer_type("int32");
1880 else
1881 this->type_ = Type::lookup_integer_type("int");
1885 // Check the type of an integer constant.
1887 void
1888 Integer_expression::do_check_types(Gogo*)
1890 Type* type = this->type_;
1891 if (type == NULL)
1892 return;
1893 Numeric_constant nc;
1894 if (this->is_character_constant_)
1895 nc.set_rune(NULL, this->val_);
1896 else
1897 nc.set_int(NULL, this->val_);
1898 if (!nc.set_type(type, true, this->location()))
1899 this->set_is_error();
1902 // Get the backend representation for an integer constant.
1904 Bexpression*
1905 Integer_expression::do_get_backend(Translate_context* context)
1907 Type* resolved_type = NULL;
1908 if (this->type_ != NULL && !this->type_->is_abstract())
1909 resolved_type = this->type_;
1910 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1912 // We are converting to an abstract floating point type.
1913 resolved_type = Type::lookup_float_type("float64");
1915 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1917 // We are converting to an abstract complex type.
1918 resolved_type = Type::lookup_complex_type("complex128");
1920 else
1922 // If we still have an abstract type here, then this is being
1923 // used in a constant expression which didn't get reduced for
1924 // some reason. Use a type which will fit the value. We use <,
1925 // not <=, because we need an extra bit for the sign bit.
1926 int bits = mpz_sizeinbase(this->val_, 2);
1927 Type* int_type = Type::lookup_integer_type("int");
1928 if (bits < int_type->integer_type()->bits())
1929 resolved_type = int_type;
1930 else if (bits < 64)
1931 resolved_type = Type::lookup_integer_type("int64");
1932 else
1934 if (!saw_errors())
1935 error_at(this->location(),
1936 "unknown type for large integer constant");
1937 return context->gogo()->backend()->error_expression();
1940 Numeric_constant nc;
1941 nc.set_int(resolved_type, this->val_);
1942 return Expression::backend_numeric_constant_expression(context, &nc);
1945 // Write VAL to export data.
1947 void
1948 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1950 char* s = mpz_get_str(NULL, 10, val);
1951 exp->write_c_string(s);
1952 free(s);
1955 // Export an integer in a constant expression.
1957 void
1958 Integer_expression::do_export(Export* exp) const
1960 Integer_expression::export_integer(exp, this->val_);
1961 if (this->is_character_constant_)
1962 exp->write_c_string("'");
1963 // A trailing space lets us reliably identify the end of the number.
1964 exp->write_c_string(" ");
1967 // Import an integer, floating point, or complex value. This handles
1968 // all these types because they all start with digits.
1970 Expression*
1971 Integer_expression::do_import(Import* imp)
1973 std::string num = imp->read_identifier();
1974 imp->require_c_string(" ");
1975 if (!num.empty() && num[num.length() - 1] == 'i')
1977 mpfr_t real;
1978 size_t plus_pos = num.find('+', 1);
1979 size_t minus_pos = num.find('-', 1);
1980 size_t pos;
1981 if (plus_pos == std::string::npos)
1982 pos = minus_pos;
1983 else if (minus_pos == std::string::npos)
1984 pos = plus_pos;
1985 else
1987 error_at(imp->location(), "bad number in import data: %qs",
1988 num.c_str());
1989 return Expression::make_error(imp->location());
1991 if (pos == std::string::npos)
1992 mpfr_set_ui(real, 0, GMP_RNDN);
1993 else
1995 std::string real_str = num.substr(0, pos);
1996 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1998 error_at(imp->location(), "bad number in import data: %qs",
1999 real_str.c_str());
2000 return Expression::make_error(imp->location());
2004 std::string imag_str;
2005 if (pos == std::string::npos)
2006 imag_str = num;
2007 else
2008 imag_str = num.substr(pos);
2009 imag_str = imag_str.substr(0, imag_str.size() - 1);
2010 mpfr_t imag;
2011 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2013 error_at(imp->location(), "bad number in import data: %qs",
2014 imag_str.c_str());
2015 return Expression::make_error(imp->location());
2017 mpc_t cval;
2018 mpc_init2(cval, mpc_precision);
2019 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2020 mpfr_clear(real);
2021 mpfr_clear(imag);
2022 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2023 mpc_clear(cval);
2024 return ret;
2026 else if (num.find('.') == std::string::npos
2027 && num.find('E') == std::string::npos)
2029 bool is_character_constant = (!num.empty()
2030 && num[num.length() - 1] == '\'');
2031 if (is_character_constant)
2032 num = num.substr(0, num.length() - 1);
2033 mpz_t val;
2034 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2036 error_at(imp->location(), "bad number in import data: %qs",
2037 num.c_str());
2038 return Expression::make_error(imp->location());
2040 Expression* ret;
2041 if (is_character_constant)
2042 ret = Expression::make_character(&val, NULL, imp->location());
2043 else
2044 ret = Expression::make_integer_z(&val, NULL, imp->location());
2045 mpz_clear(val);
2046 return ret;
2048 else
2050 mpfr_t val;
2051 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2053 error_at(imp->location(), "bad number in import data: %qs",
2054 num.c_str());
2055 return Expression::make_error(imp->location());
2057 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2058 mpfr_clear(val);
2059 return ret;
2062 // Ast dump for integer expression.
2064 void
2065 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2067 if (this->is_character_constant_)
2068 ast_dump_context->ostream() << '\'';
2069 Integer_expression::export_integer(ast_dump_context, this->val_);
2070 if (this->is_character_constant_)
2071 ast_dump_context->ostream() << '\'';
2074 // Build a new integer value from a multi-precision integer.
2076 Expression*
2077 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2079 return new Integer_expression(val, type, false, location);
2082 // Build a new integer value from an unsigned long.
2084 Expression*
2085 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2087 mpz_t zval;
2088 mpz_init_set_ui(zval, val);
2089 Expression* ret = Expression::make_integer_z(&zval, type, location);
2090 mpz_clear(zval);
2091 return ret;
2094 // Build a new integer value from a signed long.
2096 Expression*
2097 Expression::make_integer_sl(long val, Type *type, Location location)
2099 mpz_t zval;
2100 mpz_init_set_si(zval, val);
2101 Expression* ret = Expression::make_integer_z(&zval, type, location);
2102 mpz_clear(zval);
2103 return ret;
2106 // Store an int64_t in an uninitialized mpz_t.
2108 static void
2109 set_mpz_from_int64(mpz_t* zval, int64_t val)
2111 if (val >= 0)
2113 unsigned long ul = static_cast<unsigned long>(val);
2114 if (static_cast<int64_t>(ul) == val)
2116 mpz_init_set_ui(*zval, ul);
2117 return;
2120 uint64_t uv;
2121 if (val >= 0)
2122 uv = static_cast<uint64_t>(val);
2123 else
2124 uv = static_cast<uint64_t>(- val);
2125 unsigned long ul = uv & 0xffffffffUL;
2126 mpz_init_set_ui(*zval, ul);
2127 mpz_t hval;
2128 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2129 mpz_mul_2exp(hval, hval, 32);
2130 mpz_add(*zval, *zval, hval);
2131 mpz_clear(hval);
2132 if (val < 0)
2133 mpz_neg(*zval, *zval);
2136 // Build a new integer value from an int64_t.
2138 Expression*
2139 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2141 mpz_t zval;
2142 set_mpz_from_int64(&zval, val);
2143 Expression* ret = Expression::make_integer_z(&zval, type, location);
2144 mpz_clear(zval);
2145 return ret;
2148 // Build a new character constant value.
2150 Expression*
2151 Expression::make_character(const mpz_t* val, Type* type, Location location)
2153 return new Integer_expression(val, type, true, location);
2156 // Floats.
2158 class Float_expression : public Expression
2160 public:
2161 Float_expression(const mpfr_t* val, Type* type, Location location)
2162 : Expression(EXPRESSION_FLOAT, location),
2163 type_(type)
2165 mpfr_init_set(this->val_, *val, GMP_RNDN);
2168 // Write VAL to export data.
2169 static void
2170 export_float(String_dump* exp, const mpfr_t val);
2172 // Write VAL to dump file.
2173 static void
2174 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2176 protected:
2177 bool
2178 do_is_constant() const
2179 { return true; }
2181 bool
2182 do_is_immutable() const
2183 { return true; }
2185 bool
2186 do_numeric_constant_value(Numeric_constant* nc) const
2188 nc->set_float(this->type_, this->val_);
2189 return true;
2192 Type*
2193 do_type();
2195 void
2196 do_determine_type(const Type_context*);
2198 void
2199 do_check_types(Gogo*);
2201 Expression*
2202 do_copy()
2203 { return Expression::make_float(&this->val_, this->type_,
2204 this->location()); }
2206 Bexpression*
2207 do_get_backend(Translate_context*);
2209 void
2210 do_export(Export*) const;
2212 void
2213 do_dump_expression(Ast_dump_context*) const;
2215 private:
2216 // The floating point value.
2217 mpfr_t val_;
2218 // The type so far.
2219 Type* type_;
2222 // Return the current type. If we haven't set the type yet, we return
2223 // an abstract float type.
2225 Type*
2226 Float_expression::do_type()
2228 if (this->type_ == NULL)
2229 this->type_ = Type::make_abstract_float_type();
2230 return this->type_;
2233 // Set the type of the float value. Here we may switch from an
2234 // abstract type to a real type.
2236 void
2237 Float_expression::do_determine_type(const Type_context* context)
2239 if (this->type_ != NULL && !this->type_->is_abstract())
2241 else if (context->type != NULL
2242 && (context->type->integer_type() != NULL
2243 || context->type->float_type() != NULL
2244 || context->type->complex_type() != NULL))
2245 this->type_ = context->type;
2246 else if (!context->may_be_abstract)
2247 this->type_ = Type::lookup_float_type("float64");
2250 // Check the type of a float value.
2252 void
2253 Float_expression::do_check_types(Gogo*)
2255 Type* type = this->type_;
2256 if (type == NULL)
2257 return;
2258 Numeric_constant nc;
2259 nc.set_float(NULL, this->val_);
2260 if (!nc.set_type(this->type_, true, this->location()))
2261 this->set_is_error();
2264 // Get the backend representation for a float constant.
2266 Bexpression*
2267 Float_expression::do_get_backend(Translate_context* context)
2269 Type* resolved_type;
2270 if (this->type_ != NULL && !this->type_->is_abstract())
2271 resolved_type = this->type_;
2272 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2274 // We have an abstract integer type. We just hope for the best.
2275 resolved_type = Type::lookup_integer_type("int");
2277 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2279 // We are converting to an abstract complex type.
2280 resolved_type = Type::lookup_complex_type("complex128");
2282 else
2284 // If we still have an abstract type here, then this is being
2285 // used in a constant expression which didn't get reduced. We
2286 // just use float64 and hope for the best.
2287 resolved_type = Type::lookup_float_type("float64");
2290 Numeric_constant nc;
2291 nc.set_float(resolved_type, this->val_);
2292 return Expression::backend_numeric_constant_expression(context, &nc);
2295 // Write a floating point number to a string dump.
2297 void
2298 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2300 mp_exp_t exponent;
2301 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2302 if (*s == '-')
2303 exp->write_c_string("-");
2304 exp->write_c_string("0.");
2305 exp->write_c_string(*s == '-' ? s + 1 : s);
2306 mpfr_free_str(s);
2307 char buf[30];
2308 snprintf(buf, sizeof buf, "E%ld", exponent);
2309 exp->write_c_string(buf);
2312 // Export a floating point number in a constant expression.
2314 void
2315 Float_expression::do_export(Export* exp) const
2317 Float_expression::export_float(exp, this->val_);
2318 // A trailing space lets us reliably identify the end of the number.
2319 exp->write_c_string(" ");
2322 // Dump a floating point number to the dump file.
2324 void
2325 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2327 Float_expression::export_float(ast_dump_context, this->val_);
2330 // Make a float expression.
2332 Expression*
2333 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2335 return new Float_expression(val, type, location);
2338 // Complex numbers.
2340 class Complex_expression : public Expression
2342 public:
2343 Complex_expression(const mpc_t* val, Type* type, Location location)
2344 : Expression(EXPRESSION_COMPLEX, location),
2345 type_(type)
2347 mpc_init2(this->val_, mpc_precision);
2348 mpc_set(this->val_, *val, MPC_RNDNN);
2351 // Write VAL to string dump.
2352 static void
2353 export_complex(String_dump* exp, const mpc_t val);
2355 // Write REAL/IMAG to dump context.
2356 static void
2357 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2359 protected:
2360 bool
2361 do_is_constant() const
2362 { return true; }
2364 bool
2365 do_is_immutable() const
2366 { return true; }
2368 bool
2369 do_numeric_constant_value(Numeric_constant* nc) const
2371 nc->set_complex(this->type_, this->val_);
2372 return true;
2375 Type*
2376 do_type();
2378 void
2379 do_determine_type(const Type_context*);
2381 void
2382 do_check_types(Gogo*);
2384 Expression*
2385 do_copy()
2387 return Expression::make_complex(&this->val_, this->type_,
2388 this->location());
2391 Bexpression*
2392 do_get_backend(Translate_context*);
2394 void
2395 do_export(Export*) const;
2397 void
2398 do_dump_expression(Ast_dump_context*) const;
2400 private:
2401 // The complex value.
2402 mpc_t val_;
2403 // The type if known.
2404 Type* type_;
2407 // Return the current type. If we haven't set the type yet, we return
2408 // an abstract complex type.
2410 Type*
2411 Complex_expression::do_type()
2413 if (this->type_ == NULL)
2414 this->type_ = Type::make_abstract_complex_type();
2415 return this->type_;
2418 // Set the type of the complex value. Here we may switch from an
2419 // abstract type to a real type.
2421 void
2422 Complex_expression::do_determine_type(const Type_context* context)
2424 if (this->type_ != NULL && !this->type_->is_abstract())
2426 else if (context->type != NULL
2427 && context->type->complex_type() != NULL)
2428 this->type_ = context->type;
2429 else if (!context->may_be_abstract)
2430 this->type_ = Type::lookup_complex_type("complex128");
2433 // Check the type of a complex value.
2435 void
2436 Complex_expression::do_check_types(Gogo*)
2438 Type* type = this->type_;
2439 if (type == NULL)
2440 return;
2441 Numeric_constant nc;
2442 nc.set_complex(NULL, this->val_);
2443 if (!nc.set_type(this->type_, true, this->location()))
2444 this->set_is_error();
2447 // Get the backend representation for a complex constant.
2449 Bexpression*
2450 Complex_expression::do_get_backend(Translate_context* context)
2452 Type* resolved_type;
2453 if (this->type_ != NULL && !this->type_->is_abstract())
2454 resolved_type = this->type_;
2455 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2457 // We are converting to an abstract integer type.
2458 resolved_type = Type::lookup_integer_type("int");
2460 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2462 // We are converting to an abstract float type.
2463 resolved_type = Type::lookup_float_type("float64");
2465 else
2467 // If we still have an abstract type here, this is being
2468 // used in a constant expression which didn't get reduced. We
2469 // just use complex128 and hope for the best.
2470 resolved_type = Type::lookup_complex_type("complex128");
2473 Numeric_constant nc;
2474 nc.set_complex(resolved_type, this->val_);
2475 return Expression::backend_numeric_constant_expression(context, &nc);
2478 // Write REAL/IMAG to export data.
2480 void
2481 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2483 if (!mpfr_zero_p(mpc_realref(val)))
2485 Float_expression::export_float(exp, mpc_realref(val));
2486 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2487 exp->write_c_string("+");
2489 Float_expression::export_float(exp, mpc_imagref(val));
2490 exp->write_c_string("i");
2493 // Export a complex number in a constant expression.
2495 void
2496 Complex_expression::do_export(Export* exp) const
2498 Complex_expression::export_complex(exp, this->val_);
2499 // A trailing space lets us reliably identify the end of the number.
2500 exp->write_c_string(" ");
2503 // Dump a complex expression to the dump file.
2505 void
2506 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2508 Complex_expression::export_complex(ast_dump_context, this->val_);
2511 // Make a complex expression.
2513 Expression*
2514 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2516 return new Complex_expression(val, type, location);
2519 // Find a named object in an expression.
2521 class Find_named_object : public Traverse
2523 public:
2524 Find_named_object(Named_object* no)
2525 : Traverse(traverse_expressions),
2526 no_(no), found_(false)
2529 // Whether we found the object.
2530 bool
2531 found() const
2532 { return this->found_; }
2534 protected:
2536 expression(Expression**);
2538 private:
2539 // The object we are looking for.
2540 Named_object* no_;
2541 // Whether we found it.
2542 bool found_;
2545 // A reference to a const in an expression.
2547 class Const_expression : public Expression
2549 public:
2550 Const_expression(Named_object* constant, Location location)
2551 : Expression(EXPRESSION_CONST_REFERENCE, location),
2552 constant_(constant), type_(NULL), seen_(false)
2555 Named_object*
2556 named_object()
2557 { return this->constant_; }
2559 // Check that the initializer does not refer to the constant itself.
2560 void
2561 check_for_init_loop();
2563 protected:
2565 do_traverse(Traverse*);
2567 Expression*
2568 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2570 bool
2571 do_is_constant() const
2572 { return true; }
2574 bool
2575 do_is_immutable() const
2576 { return true; }
2578 bool
2579 do_numeric_constant_value(Numeric_constant* nc) const;
2581 bool
2582 do_string_constant_value(std::string* val) const;
2584 Type*
2585 do_type();
2587 // The type of a const is set by the declaration, not the use.
2588 void
2589 do_determine_type(const Type_context*);
2591 void
2592 do_check_types(Gogo*);
2594 Expression*
2595 do_copy()
2596 { return this; }
2598 Bexpression*
2599 do_get_backend(Translate_context* context);
2601 // When exporting a reference to a const as part of a const
2602 // expression, we export the value. We ignore the fact that it has
2603 // a name.
2604 void
2605 do_export(Export* exp) const
2606 { this->constant_->const_value()->expr()->export_expression(exp); }
2608 void
2609 do_dump_expression(Ast_dump_context*) const;
2611 private:
2612 // The constant.
2613 Named_object* constant_;
2614 // The type of this reference. This is used if the constant has an
2615 // abstract type.
2616 Type* type_;
2617 // Used to prevent infinite recursion when a constant incorrectly
2618 // refers to itself.
2619 mutable bool seen_;
2622 // Traversal.
2625 Const_expression::do_traverse(Traverse* traverse)
2627 if (this->type_ != NULL)
2628 return Type::traverse(this->type_, traverse);
2629 return TRAVERSE_CONTINUE;
2632 // Lower a constant expression. This is where we convert the
2633 // predeclared constant iota into an integer value.
2635 Expression*
2636 Const_expression::do_lower(Gogo* gogo, Named_object*,
2637 Statement_inserter*, int iota_value)
2639 if (this->constant_->const_value()->expr()->classification()
2640 == EXPRESSION_IOTA)
2642 if (iota_value == -1)
2644 error_at(this->location(),
2645 "iota is only defined in const declarations");
2646 iota_value = 0;
2648 return Expression::make_integer_ul(iota_value, NULL, this->location());
2651 // Make sure that the constant itself has been lowered.
2652 gogo->lower_constant(this->constant_);
2654 return this;
2657 // Return a numeric constant value.
2659 bool
2660 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2662 if (this->seen_)
2663 return false;
2665 Expression* e = this->constant_->const_value()->expr();
2667 this->seen_ = true;
2669 bool r = e->numeric_constant_value(nc);
2671 this->seen_ = false;
2673 Type* ctype;
2674 if (this->type_ != NULL)
2675 ctype = this->type_;
2676 else
2677 ctype = this->constant_->const_value()->type();
2678 if (r && ctype != NULL)
2680 if (!nc->set_type(ctype, false, this->location()))
2681 return false;
2684 return r;
2687 bool
2688 Const_expression::do_string_constant_value(std::string* val) const
2690 if (this->seen_)
2691 return false;
2693 Expression* e = this->constant_->const_value()->expr();
2695 this->seen_ = true;
2696 bool ok = e->string_constant_value(val);
2697 this->seen_ = false;
2699 return ok;
2702 // Return the type of the const reference.
2704 Type*
2705 Const_expression::do_type()
2707 if (this->type_ != NULL)
2708 return this->type_;
2710 Named_constant* nc = this->constant_->const_value();
2712 if (this->seen_ || nc->lowering())
2714 this->report_error(_("constant refers to itself"));
2715 this->type_ = Type::make_error_type();
2716 return this->type_;
2719 this->seen_ = true;
2721 Type* ret = nc->type();
2723 if (ret != NULL)
2725 this->seen_ = false;
2726 return ret;
2729 // During parsing, a named constant may have a NULL type, but we
2730 // must not return a NULL type here.
2731 ret = nc->expr()->type();
2733 this->seen_ = false;
2735 return ret;
2738 // Set the type of the const reference.
2740 void
2741 Const_expression::do_determine_type(const Type_context* context)
2743 Type* ctype = this->constant_->const_value()->type();
2744 Type* cetype = (ctype != NULL
2745 ? ctype
2746 : this->constant_->const_value()->expr()->type());
2747 if (ctype != NULL && !ctype->is_abstract())
2749 else if (context->type != NULL
2750 && context->type->is_numeric_type()
2751 && cetype->is_numeric_type())
2752 this->type_ = context->type;
2753 else if (context->type != NULL
2754 && context->type->is_string_type()
2755 && cetype->is_string_type())
2756 this->type_ = context->type;
2757 else if (context->type != NULL
2758 && context->type->is_boolean_type()
2759 && cetype->is_boolean_type())
2760 this->type_ = context->type;
2761 else if (!context->may_be_abstract)
2763 if (cetype->is_abstract())
2764 cetype = cetype->make_non_abstract_type();
2765 this->type_ = cetype;
2769 // Check for a loop in which the initializer of a constant refers to
2770 // the constant itself.
2772 void
2773 Const_expression::check_for_init_loop()
2775 if (this->type_ != NULL && this->type_->is_error())
2776 return;
2778 if (this->seen_)
2780 this->report_error(_("constant refers to itself"));
2781 this->type_ = Type::make_error_type();
2782 return;
2785 Expression* init = this->constant_->const_value()->expr();
2786 Find_named_object find_named_object(this->constant_);
2788 this->seen_ = true;
2789 Expression::traverse(&init, &find_named_object);
2790 this->seen_ = false;
2792 if (find_named_object.found())
2794 if (this->type_ == NULL || !this->type_->is_error())
2796 this->report_error(_("constant refers to itself"));
2797 this->type_ = Type::make_error_type();
2799 return;
2803 // Check types of a const reference.
2805 void
2806 Const_expression::do_check_types(Gogo*)
2808 if (this->type_ != NULL && this->type_->is_error())
2809 return;
2811 this->check_for_init_loop();
2813 // Check that numeric constant fits in type.
2814 if (this->type_ != NULL && this->type_->is_numeric_type())
2816 Numeric_constant nc;
2817 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2819 if (!nc.set_type(this->type_, true, this->location()))
2820 this->set_is_error();
2825 // Return the backend representation for a const reference.
2827 Bexpression*
2828 Const_expression::do_get_backend(Translate_context* context)
2830 if (this->type_ != NULL && this->type_->is_error())
2831 return context->backend()->error_expression();
2833 // If the type has been set for this expression, but the underlying
2834 // object is an abstract int or float, we try to get the abstract
2835 // value. Otherwise we may lose something in the conversion.
2836 Expression* expr = this->constant_->const_value()->expr();
2837 if (this->type_ != NULL
2838 && this->type_->is_numeric_type()
2839 && (this->constant_->const_value()->type() == NULL
2840 || this->constant_->const_value()->type()->is_abstract()))
2842 Numeric_constant nc;
2843 if (expr->numeric_constant_value(&nc)
2844 && nc.set_type(this->type_, false, this->location()))
2846 Expression* e = nc.expression(this->location());
2847 return e->get_backend(context);
2851 if (this->type_ != NULL)
2852 expr = Expression::make_cast(this->type_, expr, this->location());
2853 return expr->get_backend(context);
2856 // Dump ast representation for constant expression.
2858 void
2859 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2861 ast_dump_context->ostream() << this->constant_->name();
2864 // Make a reference to a constant in an expression.
2866 Expression*
2867 Expression::make_const_reference(Named_object* constant,
2868 Location location)
2870 return new Const_expression(constant, location);
2873 // Find a named object in an expression.
2876 Find_named_object::expression(Expression** pexpr)
2878 switch ((*pexpr)->classification())
2880 case Expression::EXPRESSION_CONST_REFERENCE:
2882 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2883 if (ce->named_object() == this->no_)
2884 break;
2886 // We need to check a constant initializer explicitly, as
2887 // loops here will not be caught by the loop checking for
2888 // variable initializers.
2889 ce->check_for_init_loop();
2891 return TRAVERSE_CONTINUE;
2894 case Expression::EXPRESSION_VAR_REFERENCE:
2895 if ((*pexpr)->var_expression()->named_object() == this->no_)
2896 break;
2897 return TRAVERSE_CONTINUE;
2898 case Expression::EXPRESSION_FUNC_REFERENCE:
2899 if ((*pexpr)->func_expression()->named_object() == this->no_)
2900 break;
2901 return TRAVERSE_CONTINUE;
2902 default:
2903 return TRAVERSE_CONTINUE;
2905 this->found_ = true;
2906 return TRAVERSE_EXIT;
2909 // The nil value.
2911 class Nil_expression : public Expression
2913 public:
2914 Nil_expression(Location location)
2915 : Expression(EXPRESSION_NIL, location)
2918 static Expression*
2919 do_import(Import*);
2921 protected:
2922 bool
2923 do_is_constant() const
2924 { return true; }
2926 bool
2927 do_is_immutable() const
2928 { return true; }
2930 Type*
2931 do_type()
2932 { return Type::make_nil_type(); }
2934 void
2935 do_determine_type(const Type_context*)
2938 Expression*
2939 do_copy()
2940 { return this; }
2942 Bexpression*
2943 do_get_backend(Translate_context* context)
2944 { return context->backend()->nil_pointer_expression(); }
2946 void
2947 do_export(Export* exp) const
2948 { exp->write_c_string("nil"); }
2950 void
2951 do_dump_expression(Ast_dump_context* ast_dump_context) const
2952 { ast_dump_context->ostream() << "nil"; }
2955 // Import a nil expression.
2957 Expression*
2958 Nil_expression::do_import(Import* imp)
2960 imp->require_c_string("nil");
2961 return Expression::make_nil(imp->location());
2964 // Make a nil expression.
2966 Expression*
2967 Expression::make_nil(Location location)
2969 return new Nil_expression(location);
2972 // The value of the predeclared constant iota. This is little more
2973 // than a marker. This will be lowered to an integer in
2974 // Const_expression::do_lower, which is where we know the value that
2975 // it should have.
2977 class Iota_expression : public Parser_expression
2979 public:
2980 Iota_expression(Location location)
2981 : Parser_expression(EXPRESSION_IOTA, location)
2984 protected:
2985 Expression*
2986 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2987 { go_unreachable(); }
2989 // There should only ever be one of these.
2990 Expression*
2991 do_copy()
2992 { go_unreachable(); }
2994 void
2995 do_dump_expression(Ast_dump_context* ast_dump_context) const
2996 { ast_dump_context->ostream() << "iota"; }
2999 // Make an iota expression. This is only called for one case: the
3000 // value of the predeclared constant iota.
3002 Expression*
3003 Expression::make_iota()
3005 static Iota_expression iota_expression(Linemap::unknown_location());
3006 return &iota_expression;
3009 // Class Type_conversion_expression.
3011 // Traversal.
3014 Type_conversion_expression::do_traverse(Traverse* traverse)
3016 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3017 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3018 return TRAVERSE_EXIT;
3019 return TRAVERSE_CONTINUE;
3022 // Convert to a constant at lowering time.
3024 Expression*
3025 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3026 Statement_inserter*, int)
3028 Type* type = this->type_;
3029 Expression* val = this->expr_;
3030 Location location = this->location();
3032 if (type->is_numeric_type())
3034 Numeric_constant nc;
3035 if (val->numeric_constant_value(&nc))
3037 if (!nc.set_type(type, true, location))
3038 return Expression::make_error(location);
3039 return nc.expression(location);
3043 if (type->is_slice_type())
3045 Type* element_type = type->array_type()->element_type()->forwarded();
3046 bool is_byte = (element_type->integer_type() != NULL
3047 && element_type->integer_type()->is_byte());
3048 bool is_rune = (element_type->integer_type() != NULL
3049 && element_type->integer_type()->is_rune());
3050 if (is_byte || is_rune)
3052 std::string s;
3053 if (val->string_constant_value(&s))
3055 Expression_list* vals = new Expression_list();
3056 if (is_byte)
3058 for (std::string::const_iterator p = s.begin();
3059 p != s.end();
3060 p++)
3062 unsigned char c = static_cast<unsigned char>(*p);
3063 vals->push_back(Expression::make_integer_ul(c,
3064 element_type,
3065 location));
3068 else
3070 const char *p = s.data();
3071 const char *pend = s.data() + s.length();
3072 while (p < pend)
3074 unsigned int c;
3075 int adv = Lex::fetch_char(p, &c);
3076 if (adv == 0)
3078 warning_at(this->location(), 0,
3079 "invalid UTF-8 encoding");
3080 adv = 1;
3082 p += adv;
3083 vals->push_back(Expression::make_integer_ul(c,
3084 element_type,
3085 location));
3089 return Expression::make_slice_composite_literal(type, vals,
3090 location);
3095 return this;
3098 // Flatten a type conversion by using a temporary variable for the slice
3099 // in slice to string conversions.
3101 Expression*
3102 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3103 Statement_inserter* inserter)
3105 if (((this->type()->is_string_type()
3106 && this->expr_->type()->is_slice_type())
3107 || this->expr_->type()->interface_type() != NULL)
3108 && !this->expr_->is_variable())
3110 Temporary_statement* temp =
3111 Statement::make_temporary(NULL, this->expr_, this->location());
3112 inserter->insert(temp);
3113 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3115 return this;
3118 // Return whether a type conversion is a constant.
3120 bool
3121 Type_conversion_expression::do_is_constant() const
3123 if (!this->expr_->is_constant())
3124 return false;
3126 // A conversion to a type that may not be used as a constant is not
3127 // a constant. For example, []byte(nil).
3128 Type* type = this->type_;
3129 if (type->integer_type() == NULL
3130 && type->float_type() == NULL
3131 && type->complex_type() == NULL
3132 && !type->is_boolean_type()
3133 && !type->is_string_type())
3134 return false;
3136 return true;
3139 // Return whether a type conversion is immutable.
3141 bool
3142 Type_conversion_expression::do_is_immutable() const
3144 Type* type = this->type_;
3145 Type* expr_type = this->expr_->type();
3147 if (type->interface_type() != NULL
3148 || expr_type->interface_type() != NULL)
3149 return false;
3151 if (!this->expr_->is_immutable())
3152 return false;
3154 if (Type::are_identical(type, expr_type, false, NULL))
3155 return true;
3157 return type->is_basic_type() && expr_type->is_basic_type();
3160 // Return the constant numeric value if there is one.
3162 bool
3163 Type_conversion_expression::do_numeric_constant_value(
3164 Numeric_constant* nc) const
3166 if (!this->type_->is_numeric_type())
3167 return false;
3168 if (!this->expr_->numeric_constant_value(nc))
3169 return false;
3170 return nc->set_type(this->type_, false, this->location());
3173 // Return the constant string value if there is one.
3175 bool
3176 Type_conversion_expression::do_string_constant_value(std::string* val) const
3178 if (this->type_->is_string_type()
3179 && this->expr_->type()->integer_type() != NULL)
3181 Numeric_constant nc;
3182 if (this->expr_->numeric_constant_value(&nc))
3184 unsigned long ival;
3185 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3187 val->clear();
3188 Lex::append_char(ival, true, val, this->location());
3189 return true;
3194 // FIXME: Could handle conversion from const []int here.
3196 return false;
3199 // Determine the resulting type of the conversion.
3201 void
3202 Type_conversion_expression::do_determine_type(const Type_context*)
3204 Type_context subcontext(this->type_, false);
3205 this->expr_->determine_type(&subcontext);
3208 // Check that types are convertible.
3210 void
3211 Type_conversion_expression::do_check_types(Gogo*)
3213 Type* type = this->type_;
3214 Type* expr_type = this->expr_->type();
3215 std::string reason;
3217 if (type->is_error() || expr_type->is_error())
3219 this->set_is_error();
3220 return;
3223 if (this->may_convert_function_types_
3224 && type->function_type() != NULL
3225 && expr_type->function_type() != NULL)
3226 return;
3228 if (Type::are_convertible(type, expr_type, &reason))
3229 return;
3231 error_at(this->location(), "%s", reason.c_str());
3232 this->set_is_error();
3235 // Get the backend representation for a type conversion.
3237 Bexpression*
3238 Type_conversion_expression::do_get_backend(Translate_context* context)
3240 Type* type = this->type_;
3241 Type* expr_type = this->expr_->type();
3243 Gogo* gogo = context->gogo();
3244 Btype* btype = type->get_backend(gogo);
3245 Bexpression* bexpr = this->expr_->get_backend(context);
3246 Location loc = this->location();
3248 if (Type::are_identical(type, expr_type, false, NULL))
3249 return gogo->backend()->convert_expression(btype, bexpr, loc);
3250 else if (type->interface_type() != NULL
3251 || expr_type->interface_type() != NULL)
3253 Expression* conversion =
3254 Expression::convert_for_assignment(gogo, type, this->expr_,
3255 this->location());
3256 return conversion->get_backend(context);
3258 else if (type->is_string_type()
3259 && expr_type->integer_type() != NULL)
3261 mpz_t intval;
3262 Numeric_constant nc;
3263 if (this->expr_->numeric_constant_value(&nc)
3264 && nc.to_int(&intval)
3265 && mpz_fits_ushort_p(intval))
3267 std::string s;
3268 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3269 mpz_clear(intval);
3270 Expression* se = Expression::make_string(s, loc);
3271 return se->get_backend(context);
3274 Expression* i2s_expr =
3275 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3276 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3278 else if (type->is_string_type() && expr_type->is_slice_type())
3280 Array_type* a = expr_type->array_type();
3281 Type* e = a->element_type()->forwarded();
3282 go_assert(e->integer_type() != NULL);
3283 go_assert(this->expr_->is_variable());
3285 Runtime::Function code;
3286 if (e->integer_type()->is_byte())
3287 code = Runtime::BYTE_ARRAY_TO_STRING;
3288 else
3290 go_assert(e->integer_type()->is_rune());
3291 code = Runtime::INT_ARRAY_TO_STRING;
3293 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3294 Expression* len = a->get_length(gogo, this->expr_);
3295 return Runtime::make_call(code, loc, 2, valptr,
3296 len)->get_backend(context);
3298 else if (type->is_slice_type() && expr_type->is_string_type())
3300 Type* e = type->array_type()->element_type()->forwarded();
3301 go_assert(e->integer_type() != NULL);
3303 Runtime::Function code;
3304 if (e->integer_type()->is_byte())
3305 code = Runtime::STRING_TO_BYTE_ARRAY;
3306 else
3308 go_assert(e->integer_type()->is_rune());
3309 code = Runtime::STRING_TO_INT_ARRAY;
3311 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3312 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3314 else if (type->is_numeric_type())
3316 go_assert(Type::are_convertible(type, expr_type, NULL));
3317 return gogo->backend()->convert_expression(btype, bexpr, loc);
3319 else if ((type->is_unsafe_pointer_type()
3320 && (expr_type->points_to() != NULL
3321 || expr_type->integer_type()))
3322 || (expr_type->is_unsafe_pointer_type()
3323 && type->points_to() != NULL)
3324 || (this->may_convert_function_types_
3325 && type->function_type() != NULL
3326 && expr_type->function_type() != NULL))
3327 return gogo->backend()->convert_expression(btype, bexpr, loc);
3328 else
3330 Expression* conversion =
3331 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3332 return conversion->get_backend(context);
3336 // Output a type conversion in a constant expression.
3338 void
3339 Type_conversion_expression::do_export(Export* exp) const
3341 exp->write_c_string("convert(");
3342 exp->write_type(this->type_);
3343 exp->write_c_string(", ");
3344 this->expr_->export_expression(exp);
3345 exp->write_c_string(")");
3348 // Import a type conversion or a struct construction.
3350 Expression*
3351 Type_conversion_expression::do_import(Import* imp)
3353 imp->require_c_string("convert(");
3354 Type* type = imp->read_type();
3355 imp->require_c_string(", ");
3356 Expression* val = Expression::import_expression(imp);
3357 imp->require_c_string(")");
3358 return Expression::make_cast(type, val, imp->location());
3361 // Dump ast representation for a type conversion expression.
3363 void
3364 Type_conversion_expression::do_dump_expression(
3365 Ast_dump_context* ast_dump_context) const
3367 ast_dump_context->dump_type(this->type_);
3368 ast_dump_context->ostream() << "(";
3369 ast_dump_context->dump_expression(this->expr_);
3370 ast_dump_context->ostream() << ") ";
3373 // Make a type cast expression.
3375 Expression*
3376 Expression::make_cast(Type* type, Expression* val, Location location)
3378 if (type->is_error_type() || val->is_error_expression())
3379 return Expression::make_error(location);
3380 return new Type_conversion_expression(type, val, location);
3383 // Class Unsafe_type_conversion_expression.
3385 // Traversal.
3388 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3390 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3391 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3392 return TRAVERSE_EXIT;
3393 return TRAVERSE_CONTINUE;
3396 // Return whether an unsafe type conversion is immutable.
3398 bool
3399 Unsafe_type_conversion_expression::do_is_immutable() const
3401 Type* type = this->type_;
3402 Type* expr_type = this->expr_->type();
3404 if (type->interface_type() != NULL
3405 || expr_type->interface_type() != NULL)
3406 return false;
3408 if (!this->expr_->is_immutable())
3409 return false;
3411 if (Type::are_convertible(type, expr_type, NULL))
3412 return true;
3414 return type->is_basic_type() && expr_type->is_basic_type();
3417 // Convert to backend representation.
3419 Bexpression*
3420 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3422 // We are only called for a limited number of cases.
3424 Type* t = this->type_;
3425 Type* et = this->expr_->type();
3426 if (t->array_type() != NULL)
3427 go_assert(et->array_type() != NULL
3428 && t->is_slice_type() == et->is_slice_type());
3429 else if (t->struct_type() != NULL)
3431 if (t->named_type() != NULL
3432 && et->named_type() != NULL
3433 && !Type::are_convertible(t, et, NULL))
3435 go_assert(saw_errors());
3436 return context->backend()->error_expression();
3439 go_assert(et->struct_type() != NULL
3440 && Type::are_convertible(t, et, NULL));
3442 else if (t->map_type() != NULL)
3443 go_assert(et->map_type() != NULL);
3444 else if (t->channel_type() != NULL)
3445 go_assert(et->channel_type() != NULL);
3446 else if (t->points_to() != NULL)
3447 go_assert(et->points_to() != NULL
3448 || et->channel_type() != NULL
3449 || et->map_type() != NULL
3450 || et->function_type() != NULL
3451 || et->is_nil_type());
3452 else if (et->is_unsafe_pointer_type())
3453 go_assert(t->points_to() != NULL);
3454 else if (t->interface_type() != NULL)
3456 bool empty_iface = t->interface_type()->is_empty();
3457 go_assert(et->interface_type() != NULL
3458 && et->interface_type()->is_empty() == empty_iface);
3460 else if (t->integer_type() != NULL)
3461 go_assert(et->is_boolean_type()
3462 || et->integer_type() != NULL
3463 || et->function_type() != NULL
3464 || et->points_to() != NULL
3465 || et->map_type() != NULL
3466 || et->channel_type() != NULL
3467 || et->is_nil_type());
3468 else
3469 go_unreachable();
3471 Gogo* gogo = context->gogo();
3472 Btype* btype = t->get_backend(gogo);
3473 Bexpression* bexpr = this->expr_->get_backend(context);
3474 Location loc = this->location();
3475 return gogo->backend()->convert_expression(btype, bexpr, loc);
3478 // Dump ast representation for an unsafe type conversion expression.
3480 void
3481 Unsafe_type_conversion_expression::do_dump_expression(
3482 Ast_dump_context* ast_dump_context) const
3484 ast_dump_context->dump_type(this->type_);
3485 ast_dump_context->ostream() << "(";
3486 ast_dump_context->dump_expression(this->expr_);
3487 ast_dump_context->ostream() << ") ";
3490 // Make an unsafe type conversion expression.
3492 Expression*
3493 Expression::make_unsafe_cast(Type* type, Expression* expr,
3494 Location location)
3496 return new Unsafe_type_conversion_expression(type, expr, location);
3499 // Class Unary_expression.
3501 // If we are taking the address of a composite literal, and the
3502 // contents are not constant, then we want to make a heap expression
3503 // instead.
3505 Expression*
3506 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3508 Location loc = this->location();
3509 Operator op = this->op_;
3510 Expression* expr = this->expr_;
3512 if (op == OPERATOR_MULT && expr->is_type_expression())
3513 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3515 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3516 // moving x to the heap. FIXME: Is it worth doing a real escape
3517 // analysis here? This case is found in math/unsafe.go and is
3518 // therefore worth special casing.
3519 if (op == OPERATOR_MULT)
3521 Expression* e = expr;
3522 while (e->classification() == EXPRESSION_CONVERSION)
3524 Type_conversion_expression* te
3525 = static_cast<Type_conversion_expression*>(e);
3526 e = te->expr();
3529 if (e->classification() == EXPRESSION_UNARY)
3531 Unary_expression* ue = static_cast<Unary_expression*>(e);
3532 if (ue->op_ == OPERATOR_AND)
3534 if (e == expr)
3536 // *&x == x.
3537 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3539 error_at(ue->location(),
3540 "invalid operand for unary %<&%>");
3541 this->set_is_error();
3543 return ue->expr_;
3545 ue->set_does_not_escape();
3550 // Catching an invalid indirection of unsafe.Pointer here avoid
3551 // having to deal with TYPE_VOID in other places.
3552 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3554 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3555 return Expression::make_error(this->location());
3558 // Check for an invalid pointer dereference. We need to do this
3559 // here because Unary_expression::do_type will return an error type
3560 // in this case. That can cause code to appear erroneous, and
3561 // therefore disappear at lowering time, without any error message.
3562 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3564 this->report_error(_("expected pointer"));
3565 return Expression::make_error(this->location());
3568 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3570 Numeric_constant nc;
3571 if (expr->numeric_constant_value(&nc))
3573 Numeric_constant result;
3574 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3575 return result.expression(loc);
3579 return this;
3582 // Flatten expression if a nil check must be performed and create temporary
3583 // variables if necessary.
3585 Expression*
3586 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3587 Statement_inserter* inserter)
3589 if (this->is_error_expression() || this->expr_->is_error_expression())
3590 return Expression::make_error(this->location());
3592 Location location = this->location();
3593 if (this->op_ == OPERATOR_MULT
3594 && !this->expr_->is_variable())
3596 go_assert(this->expr_->type()->points_to() != NULL);
3597 Type* ptype = this->expr_->type()->points_to();
3598 if (!ptype->is_void_type())
3600 Btype* pbtype = ptype->get_backend(gogo);
3601 int64_t s = gogo->backend()->type_size(pbtype);
3602 if (s >= 4096 || this->issue_nil_check_)
3604 Temporary_statement* temp =
3605 Statement::make_temporary(NULL, this->expr_, location);
3606 inserter->insert(temp);
3607 this->expr_ =
3608 Expression::make_temporary_reference(temp, location);
3613 if (this->op_ == OPERATOR_AND)
3615 // If this->escapes_ is false at this point, then it was set to
3616 // false by an explicit call to set_does_not_escape, and the
3617 // value does not escape. If this->escapes_ is true, we may be
3618 // able to set it to false if taking the address of a variable
3619 // that does not escape.
3620 if (this->escapes_ && this->expr_->var_expression() != NULL)
3622 Named_object* var = this->expr_->var_expression()->named_object();
3623 if (var->is_variable())
3624 this->escapes_ = var->var_value()->escapes();
3625 if (var->is_result_variable())
3626 this->escapes_ = var->result_var_value()->escapes();
3628 this->expr_->address_taken(this->escapes_);
3631 if (this->create_temp_ && !this->expr_->is_variable())
3633 Temporary_statement* temp =
3634 Statement::make_temporary(NULL, this->expr_, location);
3635 inserter->insert(temp);
3636 this->expr_ = Expression::make_temporary_reference(temp, location);
3639 return this;
3642 // Return whether a unary expression is a constant.
3644 bool
3645 Unary_expression::do_is_constant() const
3647 if (this->op_ == OPERATOR_MULT)
3649 // Indirecting through a pointer is only constant if the object
3650 // to which the expression points is constant, but we currently
3651 // have no way to determine that.
3652 return false;
3654 else if (this->op_ == OPERATOR_AND)
3656 // Taking the address of a variable is constant if it is a
3657 // global variable, not constant otherwise. In other cases taking the
3658 // address is probably not a constant.
3659 Var_expression* ve = this->expr_->var_expression();
3660 if (ve != NULL)
3662 Named_object* no = ve->named_object();
3663 return no->is_variable() && no->var_value()->is_global();
3665 return false;
3667 else
3668 return this->expr_->is_constant();
3671 // Apply unary opcode OP to UNC, setting NC. Return true if this
3672 // could be done, false if not. Issue errors for overflow.
3674 bool
3675 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3676 Location location, Numeric_constant* nc)
3678 switch (op)
3680 case OPERATOR_PLUS:
3681 *nc = *unc;
3682 return true;
3684 case OPERATOR_MINUS:
3685 if (unc->is_int() || unc->is_rune())
3686 break;
3687 else if (unc->is_float())
3689 mpfr_t uval;
3690 unc->get_float(&uval);
3691 mpfr_t val;
3692 mpfr_init(val);
3693 mpfr_neg(val, uval, GMP_RNDN);
3694 nc->set_float(unc->type(), val);
3695 mpfr_clear(uval);
3696 mpfr_clear(val);
3697 return true;
3699 else if (unc->is_complex())
3701 mpc_t uval;
3702 unc->get_complex(&uval);
3703 mpc_t val;
3704 mpc_init2(val, mpc_precision);
3705 mpc_neg(val, uval, MPC_RNDNN);
3706 nc->set_complex(unc->type(), val);
3707 mpc_clear(uval);
3708 mpc_clear(val);
3709 return true;
3711 else
3712 go_unreachable();
3714 case OPERATOR_XOR:
3715 break;
3717 case OPERATOR_NOT:
3718 case OPERATOR_AND:
3719 case OPERATOR_MULT:
3720 return false;
3722 default:
3723 go_unreachable();
3726 if (!unc->is_int() && !unc->is_rune())
3727 return false;
3729 mpz_t uval;
3730 if (unc->is_rune())
3731 unc->get_rune(&uval);
3732 else
3733 unc->get_int(&uval);
3734 mpz_t val;
3735 mpz_init(val);
3737 switch (op)
3739 case OPERATOR_MINUS:
3740 mpz_neg(val, uval);
3741 break;
3743 case OPERATOR_NOT:
3744 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3745 break;
3747 case OPERATOR_XOR:
3749 Type* utype = unc->type();
3750 if (utype->integer_type() == NULL
3751 || utype->integer_type()->is_abstract())
3752 mpz_com(val, uval);
3753 else
3755 // The number of HOST_WIDE_INTs that it takes to represent
3756 // UVAL.
3757 size_t count = ((mpz_sizeinbase(uval, 2)
3758 + HOST_BITS_PER_WIDE_INT
3759 - 1)
3760 / HOST_BITS_PER_WIDE_INT);
3762 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3763 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3765 size_t obits = utype->integer_type()->bits();
3767 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3769 mpz_t adj;
3770 mpz_init_set_ui(adj, 1);
3771 mpz_mul_2exp(adj, adj, obits);
3772 mpz_add(uval, uval, adj);
3773 mpz_clear(adj);
3776 size_t ecount;
3777 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3778 go_assert(ecount <= count);
3780 // Trim down to the number of words required by the type.
3781 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3782 / HOST_BITS_PER_WIDE_INT);
3783 go_assert(ocount <= count);
3785 for (size_t i = 0; i < ocount; ++i)
3786 phwi[i] = ~phwi[i];
3788 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3789 if (clearbits != 0)
3790 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3791 >> clearbits);
3793 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3795 if (!utype->integer_type()->is_unsigned()
3796 && mpz_tstbit(val, obits - 1))
3798 mpz_t adj;
3799 mpz_init_set_ui(adj, 1);
3800 mpz_mul_2exp(adj, adj, obits);
3801 mpz_sub(val, val, adj);
3802 mpz_clear(adj);
3805 delete[] phwi;
3808 break;
3810 default:
3811 go_unreachable();
3814 if (unc->is_rune())
3815 nc->set_rune(NULL, val);
3816 else
3817 nc->set_int(NULL, val);
3819 mpz_clear(uval);
3820 mpz_clear(val);
3822 return nc->set_type(unc->type(), true, location);
3825 // Return the integral constant value of a unary expression, if it has one.
3827 bool
3828 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3830 Numeric_constant unc;
3831 if (!this->expr_->numeric_constant_value(&unc))
3832 return false;
3833 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3834 nc);
3837 // Return the type of a unary expression.
3839 Type*
3840 Unary_expression::do_type()
3842 switch (this->op_)
3844 case OPERATOR_PLUS:
3845 case OPERATOR_MINUS:
3846 case OPERATOR_NOT:
3847 case OPERATOR_XOR:
3848 return this->expr_->type();
3850 case OPERATOR_AND:
3851 return Type::make_pointer_type(this->expr_->type());
3853 case OPERATOR_MULT:
3855 Type* subtype = this->expr_->type();
3856 Type* points_to = subtype->points_to();
3857 if (points_to == NULL)
3858 return Type::make_error_type();
3859 return points_to;
3862 default:
3863 go_unreachable();
3867 // Determine abstract types for a unary expression.
3869 void
3870 Unary_expression::do_determine_type(const Type_context* context)
3872 switch (this->op_)
3874 case OPERATOR_PLUS:
3875 case OPERATOR_MINUS:
3876 case OPERATOR_NOT:
3877 case OPERATOR_XOR:
3878 this->expr_->determine_type(context);
3879 break;
3881 case OPERATOR_AND:
3882 // Taking the address of something.
3884 Type* subtype = (context->type == NULL
3885 ? NULL
3886 : context->type->points_to());
3887 Type_context subcontext(subtype, false);
3888 this->expr_->determine_type(&subcontext);
3890 break;
3892 case OPERATOR_MULT:
3893 // Indirecting through a pointer.
3895 Type* subtype = (context->type == NULL
3896 ? NULL
3897 : Type::make_pointer_type(context->type));
3898 Type_context subcontext(subtype, false);
3899 this->expr_->determine_type(&subcontext);
3901 break;
3903 default:
3904 go_unreachable();
3908 // Check types for a unary expression.
3910 void
3911 Unary_expression::do_check_types(Gogo*)
3913 Type* type = this->expr_->type();
3914 if (type->is_error())
3916 this->set_is_error();
3917 return;
3920 switch (this->op_)
3922 case OPERATOR_PLUS:
3923 case OPERATOR_MINUS:
3924 if (type->integer_type() == NULL
3925 && type->float_type() == NULL
3926 && type->complex_type() == NULL)
3927 this->report_error(_("expected numeric type"));
3928 break;
3930 case OPERATOR_NOT:
3931 if (!type->is_boolean_type())
3932 this->report_error(_("expected boolean type"));
3933 break;
3935 case OPERATOR_XOR:
3936 if (type->integer_type() == NULL
3937 && !type->is_boolean_type())
3938 this->report_error(_("expected integer or boolean type"));
3939 break;
3941 case OPERATOR_AND:
3942 if (!this->expr_->is_addressable())
3944 if (!this->create_temp_)
3946 error_at(this->location(), "invalid operand for unary %<&%>");
3947 this->set_is_error();
3950 else
3951 this->expr_->issue_nil_check();
3952 break;
3954 case OPERATOR_MULT:
3955 // Indirecting through a pointer.
3956 if (type->points_to() == NULL)
3957 this->report_error(_("expected pointer"));
3958 if (type->points_to()->is_error())
3959 this->set_is_error();
3960 break;
3962 default:
3963 go_unreachable();
3967 // Get the backend representation for a unary expression.
3969 Bexpression*
3970 Unary_expression::do_get_backend(Translate_context* context)
3972 Gogo* gogo = context->gogo();
3973 Location loc = this->location();
3975 // Taking the address of a set-and-use-temporary expression requires
3976 // setting the temporary and then taking the address.
3977 if (this->op_ == OPERATOR_AND)
3979 Set_and_use_temporary_expression* sut =
3980 this->expr_->set_and_use_temporary_expression();
3981 if (sut != NULL)
3983 Temporary_statement* temp = sut->temporary();
3984 Bvariable* bvar = temp->get_backend_variable(context);
3985 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
3986 Bexpression* bval = sut->expression()->get_backend(context);
3988 Bstatement* bassign =
3989 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
3990 Bexpression* bvar_addr =
3991 gogo->backend()->address_expression(bvar_expr, loc);
3992 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
3996 Bexpression* ret;
3997 Bexpression* bexpr = this->expr_->get_backend(context);
3998 Btype* btype = this->expr_->type()->get_backend(gogo);
3999 switch (this->op_)
4001 case OPERATOR_PLUS:
4002 ret = bexpr;
4003 break;
4005 case OPERATOR_MINUS:
4006 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4007 ret = gogo->backend()->convert_expression(btype, ret, loc);
4008 break;
4010 case OPERATOR_NOT:
4011 case OPERATOR_XOR:
4012 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4013 break;
4015 case OPERATOR_AND:
4016 if (!this->create_temp_)
4018 // We should not see a non-constant constructor here; cases
4019 // where we would see one should have been moved onto the
4020 // heap at parse time. Taking the address of a nonconstant
4021 // constructor will not do what the programmer expects.
4023 go_assert(!this->expr_->is_composite_literal()
4024 || this->expr_->is_immutable());
4025 if (this->expr_->classification() == EXPRESSION_UNARY)
4027 Unary_expression* ue =
4028 static_cast<Unary_expression*>(this->expr_);
4029 go_assert(ue->op() != OPERATOR_AND);
4033 static unsigned int counter;
4034 char buf[100];
4035 if (this->is_gc_root_ || this->is_slice_init_)
4037 bool copy_to_heap = false;
4038 if (this->is_gc_root_)
4040 // Build a decl for a GC root variable. GC roots are mutable, so
4041 // they cannot be represented as an immutable_struct in the
4042 // backend.
4043 static unsigned int root_counter;
4044 snprintf(buf, sizeof buf, "gc%u", root_counter);
4045 ++root_counter;
4047 else
4049 // Build a decl for a slice value initializer. An immutable slice
4050 // value initializer may have to be copied to the heap if it
4051 // contains pointers in a non-constant context.
4052 snprintf(buf, sizeof buf, "C%u", counter);
4053 ++counter;
4055 Array_type* at = this->expr_->type()->array_type();
4056 go_assert(at != NULL);
4058 // If we are not copying the value to the heap, we will only
4059 // initialize the value once, so we can use this directly
4060 // rather than copying it. In that case we can't make it
4061 // read-only, because the program is permitted to change it.
4062 copy_to_heap = (at->element_type()->has_pointer()
4063 && !context->is_const());
4065 Bvariable* implicit =
4066 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
4067 false, 0);
4068 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4069 true, copy_to_heap, false,
4070 bexpr);
4071 bexpr = gogo->backend()->var_expression(implicit, loc);
4073 else if ((this->expr_->is_composite_literal()
4074 || this->expr_->string_expression() != NULL)
4075 && this->expr_->is_immutable())
4077 // Build a decl for a constant constructor.
4078 snprintf(buf, sizeof buf, "C%u", counter);
4079 ++counter;
4081 Bvariable* decl =
4082 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4083 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4084 btype, loc, bexpr);
4085 bexpr = gogo->backend()->var_expression(decl, loc);
4088 go_assert(!this->create_temp_ || this->expr_->is_variable());
4089 ret = gogo->backend()->address_expression(bexpr, loc);
4090 break;
4092 case OPERATOR_MULT:
4094 go_assert(this->expr_->type()->points_to() != NULL);
4096 // If we are dereferencing the pointer to a large struct, we
4097 // need to check for nil. We don't bother to check for small
4098 // structs because we expect the system to crash on a nil
4099 // pointer dereference. However, if we know the address of this
4100 // expression is being taken, we must always check for nil.
4102 Type* ptype = this->expr_->type()->points_to();
4103 Btype* pbtype = ptype->get_backend(gogo);
4104 if (!ptype->is_void_type())
4106 int64_t s = gogo->backend()->type_size(pbtype);
4107 if (s >= 4096 || this->issue_nil_check_)
4109 go_assert(this->expr_->is_variable());
4110 Bexpression* nil =
4111 Expression::make_nil(loc)->get_backend(context);
4112 Bexpression* compare =
4113 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4114 nil, loc);
4115 Bexpression* crash =
4116 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4117 loc)->get_backend(context);
4118 bexpr = gogo->backend()->conditional_expression(btype, compare,
4119 crash, bexpr,
4120 loc);
4124 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4126 break;
4128 default:
4129 go_unreachable();
4132 return ret;
4135 // Export a unary expression.
4137 void
4138 Unary_expression::do_export(Export* exp) const
4140 switch (this->op_)
4142 case OPERATOR_PLUS:
4143 exp->write_c_string("+ ");
4144 break;
4145 case OPERATOR_MINUS:
4146 exp->write_c_string("- ");
4147 break;
4148 case OPERATOR_NOT:
4149 exp->write_c_string("! ");
4150 break;
4151 case OPERATOR_XOR:
4152 exp->write_c_string("^ ");
4153 break;
4154 case OPERATOR_AND:
4155 case OPERATOR_MULT:
4156 default:
4157 go_unreachable();
4159 this->expr_->export_expression(exp);
4162 // Import a unary expression.
4164 Expression*
4165 Unary_expression::do_import(Import* imp)
4167 Operator op;
4168 switch (imp->get_char())
4170 case '+':
4171 op = OPERATOR_PLUS;
4172 break;
4173 case '-':
4174 op = OPERATOR_MINUS;
4175 break;
4176 case '!':
4177 op = OPERATOR_NOT;
4178 break;
4179 case '^':
4180 op = OPERATOR_XOR;
4181 break;
4182 default:
4183 go_unreachable();
4185 imp->require_c_string(" ");
4186 Expression* expr = Expression::import_expression(imp);
4187 return Expression::make_unary(op, expr, imp->location());
4190 // Dump ast representation of an unary expression.
4192 void
4193 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4195 ast_dump_context->dump_operator(this->op_);
4196 ast_dump_context->ostream() << "(";
4197 ast_dump_context->dump_expression(this->expr_);
4198 ast_dump_context->ostream() << ") ";
4201 // Make a unary expression.
4203 Expression*
4204 Expression::make_unary(Operator op, Expression* expr, Location location)
4206 return new Unary_expression(op, expr, location);
4209 // If this is an indirection through a pointer, return the expression
4210 // being pointed through. Otherwise return this.
4212 Expression*
4213 Expression::deref()
4215 if (this->classification_ == EXPRESSION_UNARY)
4217 Unary_expression* ue = static_cast<Unary_expression*>(this);
4218 if (ue->op() == OPERATOR_MULT)
4219 return ue->operand();
4221 return this;
4224 // Class Binary_expression.
4226 // Traversal.
4229 Binary_expression::do_traverse(Traverse* traverse)
4231 int t = Expression::traverse(&this->left_, traverse);
4232 if (t == TRAVERSE_EXIT)
4233 return TRAVERSE_EXIT;
4234 return Expression::traverse(&this->right_, traverse);
4237 // Return the type to use for a binary operation on operands of
4238 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4239 // such may be NULL or abstract.
4241 bool
4242 Binary_expression::operation_type(Operator op, Type* left_type,
4243 Type* right_type, Type** result_type)
4245 if (left_type != right_type
4246 && !left_type->is_abstract()
4247 && !right_type->is_abstract()
4248 && left_type->base() != right_type->base()
4249 && op != OPERATOR_LSHIFT
4250 && op != OPERATOR_RSHIFT)
4252 // May be a type error--let it be diagnosed elsewhere.
4253 return false;
4256 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4258 if (left_type->integer_type() != NULL)
4259 *result_type = left_type;
4260 else
4261 *result_type = Type::make_abstract_integer_type();
4263 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4264 *result_type = left_type;
4265 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4266 *result_type = right_type;
4267 else if (!left_type->is_abstract())
4268 *result_type = left_type;
4269 else if (!right_type->is_abstract())
4270 *result_type = right_type;
4271 else if (left_type->complex_type() != NULL)
4272 *result_type = left_type;
4273 else if (right_type->complex_type() != NULL)
4274 *result_type = right_type;
4275 else if (left_type->float_type() != NULL)
4276 *result_type = left_type;
4277 else if (right_type->float_type() != NULL)
4278 *result_type = right_type;
4279 else if (left_type->integer_type() != NULL
4280 && left_type->integer_type()->is_rune())
4281 *result_type = left_type;
4282 else if (right_type->integer_type() != NULL
4283 && right_type->integer_type()->is_rune())
4284 *result_type = right_type;
4285 else
4286 *result_type = left_type;
4288 return true;
4291 // Convert an integer comparison code and an operator to a boolean
4292 // value.
4294 bool
4295 Binary_expression::cmp_to_bool(Operator op, int cmp)
4297 switch (op)
4299 case OPERATOR_EQEQ:
4300 return cmp == 0;
4301 break;
4302 case OPERATOR_NOTEQ:
4303 return cmp != 0;
4304 break;
4305 case OPERATOR_LT:
4306 return cmp < 0;
4307 break;
4308 case OPERATOR_LE:
4309 return cmp <= 0;
4310 case OPERATOR_GT:
4311 return cmp > 0;
4312 case OPERATOR_GE:
4313 return cmp >= 0;
4314 default:
4315 go_unreachable();
4319 // Compare constants according to OP.
4321 bool
4322 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4323 Numeric_constant* right_nc,
4324 Location location, bool* result)
4326 Type* left_type = left_nc->type();
4327 Type* right_type = right_nc->type();
4329 Type* type;
4330 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4331 return false;
4333 // When comparing an untyped operand to a typed operand, we are
4334 // effectively coercing the untyped operand to the other operand's
4335 // type, so make sure that is valid.
4336 if (!left_nc->set_type(type, true, location)
4337 || !right_nc->set_type(type, true, location))
4338 return false;
4340 bool ret;
4341 int cmp;
4342 if (type->complex_type() != NULL)
4344 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4345 return false;
4346 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4348 else if (type->float_type() != NULL)
4349 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4350 else
4351 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4353 if (ret)
4354 *result = Binary_expression::cmp_to_bool(op, cmp);
4356 return ret;
4359 // Compare integer constants.
4361 bool
4362 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4363 const Numeric_constant* right_nc,
4364 int* cmp)
4366 mpz_t left_val;
4367 if (!left_nc->to_int(&left_val))
4368 return false;
4369 mpz_t right_val;
4370 if (!right_nc->to_int(&right_val))
4372 mpz_clear(left_val);
4373 return false;
4376 *cmp = mpz_cmp(left_val, right_val);
4378 mpz_clear(left_val);
4379 mpz_clear(right_val);
4381 return true;
4384 // Compare floating point constants.
4386 bool
4387 Binary_expression::compare_float(const Numeric_constant* left_nc,
4388 const Numeric_constant* right_nc,
4389 int* cmp)
4391 mpfr_t left_val;
4392 if (!left_nc->to_float(&left_val))
4393 return false;
4394 mpfr_t right_val;
4395 if (!right_nc->to_float(&right_val))
4397 mpfr_clear(left_val);
4398 return false;
4401 // We already coerced both operands to the same type. If that type
4402 // is not an abstract type, we need to round the values accordingly.
4403 Type* type = left_nc->type();
4404 if (!type->is_abstract() && type->float_type() != NULL)
4406 int bits = type->float_type()->bits();
4407 mpfr_prec_round(left_val, bits, GMP_RNDN);
4408 mpfr_prec_round(right_val, bits, GMP_RNDN);
4411 *cmp = mpfr_cmp(left_val, right_val);
4413 mpfr_clear(left_val);
4414 mpfr_clear(right_val);
4416 return true;
4419 // Compare complex constants. Complex numbers may only be compared
4420 // for equality.
4422 bool
4423 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4424 const Numeric_constant* right_nc,
4425 int* cmp)
4427 mpc_t left_val;
4428 if (!left_nc->to_complex(&left_val))
4429 return false;
4430 mpc_t right_val;
4431 if (!right_nc->to_complex(&right_val))
4433 mpc_clear(left_val);
4434 return false;
4437 // We already coerced both operands to the same type. If that type
4438 // is not an abstract type, we need to round the values accordingly.
4439 Type* type = left_nc->type();
4440 if (!type->is_abstract() && type->complex_type() != NULL)
4442 int bits = type->complex_type()->bits();
4443 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4444 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4445 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4446 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4449 *cmp = mpc_cmp(left_val, right_val) != 0;
4451 mpc_clear(left_val);
4452 mpc_clear(right_val);
4454 return true;
4457 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4458 // true if this could be done, false if not. Issue errors at LOCATION
4459 // as appropriate.
4461 bool
4462 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4463 Numeric_constant* right_nc,
4464 Location location, Numeric_constant* nc)
4466 switch (op)
4468 case OPERATOR_OROR:
4469 case OPERATOR_ANDAND:
4470 case OPERATOR_EQEQ:
4471 case OPERATOR_NOTEQ:
4472 case OPERATOR_LT:
4473 case OPERATOR_LE:
4474 case OPERATOR_GT:
4475 case OPERATOR_GE:
4476 // These return boolean values, not numeric.
4477 return false;
4478 default:
4479 break;
4482 Type* left_type = left_nc->type();
4483 Type* right_type = right_nc->type();
4485 Type* type;
4486 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4487 return false;
4489 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4491 // When combining an untyped operand with a typed operand, we are
4492 // effectively coercing the untyped operand to the other operand's
4493 // type, so make sure that is valid.
4494 if (!left_nc->set_type(type, true, location))
4495 return false;
4496 if (!is_shift && !right_nc->set_type(type, true, location))
4497 return false;
4499 bool r;
4500 if (type->complex_type() != NULL)
4501 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4502 else if (type->float_type() != NULL)
4503 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4504 else
4505 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4507 if (r)
4508 r = nc->set_type(type, true, location);
4510 return r;
4513 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4514 // integer operations. Return true if this could be done, false if
4515 // not.
4517 bool
4518 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4519 const Numeric_constant* right_nc,
4520 Location location, Numeric_constant* nc)
4522 mpz_t left_val;
4523 if (!left_nc->to_int(&left_val))
4524 return false;
4525 mpz_t right_val;
4526 if (!right_nc->to_int(&right_val))
4528 mpz_clear(left_val);
4529 return false;
4532 mpz_t val;
4533 mpz_init(val);
4535 switch (op)
4537 case OPERATOR_PLUS:
4538 mpz_add(val, left_val, right_val);
4539 if (mpz_sizeinbase(val, 2) > 0x100000)
4541 error_at(location, "constant addition overflow");
4542 mpz_set_ui(val, 1);
4544 break;
4545 case OPERATOR_MINUS:
4546 mpz_sub(val, left_val, right_val);
4547 if (mpz_sizeinbase(val, 2) > 0x100000)
4549 error_at(location, "constant subtraction overflow");
4550 mpz_set_ui(val, 1);
4552 break;
4553 case OPERATOR_OR:
4554 mpz_ior(val, left_val, right_val);
4555 break;
4556 case OPERATOR_XOR:
4557 mpz_xor(val, left_val, right_val);
4558 break;
4559 case OPERATOR_MULT:
4560 mpz_mul(val, left_val, right_val);
4561 if (mpz_sizeinbase(val, 2) > 0x100000)
4563 error_at(location, "constant multiplication overflow");
4564 mpz_set_ui(val, 1);
4566 break;
4567 case OPERATOR_DIV:
4568 if (mpz_sgn(right_val) != 0)
4569 mpz_tdiv_q(val, left_val, right_val);
4570 else
4572 error_at(location, "division by zero");
4573 mpz_set_ui(val, 0);
4575 break;
4576 case OPERATOR_MOD:
4577 if (mpz_sgn(right_val) != 0)
4578 mpz_tdiv_r(val, left_val, right_val);
4579 else
4581 error_at(location, "division by zero");
4582 mpz_set_ui(val, 0);
4584 break;
4585 case OPERATOR_LSHIFT:
4587 unsigned long shift = mpz_get_ui(right_val);
4588 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4589 mpz_mul_2exp(val, left_val, shift);
4590 else
4592 error_at(location, "shift count overflow");
4593 mpz_set_ui(val, 1);
4595 break;
4597 break;
4598 case OPERATOR_RSHIFT:
4600 unsigned long shift = mpz_get_ui(right_val);
4601 if (mpz_cmp_ui(right_val, shift) != 0)
4603 error_at(location, "shift count overflow");
4604 mpz_set_ui(val, 1);
4606 else
4608 if (mpz_cmp_ui(left_val, 0) >= 0)
4609 mpz_tdiv_q_2exp(val, left_val, shift);
4610 else
4611 mpz_fdiv_q_2exp(val, left_val, shift);
4613 break;
4615 break;
4616 case OPERATOR_AND:
4617 mpz_and(val, left_val, right_val);
4618 break;
4619 case OPERATOR_BITCLEAR:
4621 mpz_t tval;
4622 mpz_init(tval);
4623 mpz_com(tval, right_val);
4624 mpz_and(val, left_val, tval);
4625 mpz_clear(tval);
4627 break;
4628 default:
4629 go_unreachable();
4632 mpz_clear(left_val);
4633 mpz_clear(right_val);
4635 if (left_nc->is_rune()
4636 || (op != OPERATOR_LSHIFT
4637 && op != OPERATOR_RSHIFT
4638 && right_nc->is_rune()))
4639 nc->set_rune(NULL, val);
4640 else
4641 nc->set_int(NULL, val);
4643 mpz_clear(val);
4645 return true;
4648 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4649 // floating point operations. Return true if this could be done,
4650 // false if not.
4652 bool
4653 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4654 const Numeric_constant* right_nc,
4655 Location location, Numeric_constant* nc)
4657 mpfr_t left_val;
4658 if (!left_nc->to_float(&left_val))
4659 return false;
4660 mpfr_t right_val;
4661 if (!right_nc->to_float(&right_val))
4663 mpfr_clear(left_val);
4664 return false;
4667 mpfr_t val;
4668 mpfr_init(val);
4670 bool ret = true;
4671 switch (op)
4673 case OPERATOR_PLUS:
4674 mpfr_add(val, left_val, right_val, GMP_RNDN);
4675 break;
4676 case OPERATOR_MINUS:
4677 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4678 break;
4679 case OPERATOR_OR:
4680 case OPERATOR_XOR:
4681 case OPERATOR_AND:
4682 case OPERATOR_BITCLEAR:
4683 case OPERATOR_MOD:
4684 case OPERATOR_LSHIFT:
4685 case OPERATOR_RSHIFT:
4686 mpfr_set_ui(val, 0, GMP_RNDN);
4687 ret = false;
4688 break;
4689 case OPERATOR_MULT:
4690 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4691 break;
4692 case OPERATOR_DIV:
4693 if (!mpfr_zero_p(right_val))
4694 mpfr_div(val, left_val, right_val, GMP_RNDN);
4695 else
4697 error_at(location, "division by zero");
4698 mpfr_set_ui(val, 0, GMP_RNDN);
4700 break;
4701 default:
4702 go_unreachable();
4705 mpfr_clear(left_val);
4706 mpfr_clear(right_val);
4708 nc->set_float(NULL, val);
4709 mpfr_clear(val);
4711 return ret;
4714 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4715 // complex operations. Return true if this could be done, false if
4716 // not.
4718 bool
4719 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4720 const Numeric_constant* right_nc,
4721 Location location, Numeric_constant* nc)
4723 mpc_t left_val;
4724 if (!left_nc->to_complex(&left_val))
4725 return false;
4726 mpc_t right_val;
4727 if (!right_nc->to_complex(&right_val))
4729 mpc_clear(left_val);
4730 return false;
4733 mpc_t val;
4734 mpc_init2(val, mpc_precision);
4736 bool ret = true;
4737 switch (op)
4739 case OPERATOR_PLUS:
4740 mpc_add(val, left_val, right_val, MPC_RNDNN);
4741 break;
4742 case OPERATOR_MINUS:
4743 mpc_sub(val, left_val, right_val, MPC_RNDNN);
4744 break;
4745 case OPERATOR_OR:
4746 case OPERATOR_XOR:
4747 case OPERATOR_AND:
4748 case OPERATOR_BITCLEAR:
4749 case OPERATOR_MOD:
4750 case OPERATOR_LSHIFT:
4751 case OPERATOR_RSHIFT:
4752 mpc_set_ui(val, 0, MPC_RNDNN);
4753 ret = false;
4754 break;
4755 case OPERATOR_MULT:
4756 mpc_mul(val, left_val, right_val, MPC_RNDNN);
4757 break;
4758 case OPERATOR_DIV:
4759 if (mpc_cmp_si(right_val, 0) == 0)
4761 error_at(location, "division by zero");
4762 mpc_set_ui(val, 0, MPC_RNDNN);
4763 break;
4765 mpc_div(val, left_val, right_val, MPC_RNDNN);
4766 break;
4767 default:
4768 go_unreachable();
4771 mpc_clear(left_val);
4772 mpc_clear(right_val);
4774 nc->set_complex(NULL, val);
4775 mpc_clear(val);
4777 return ret;
4780 // Lower a binary expression. We have to evaluate constant
4781 // expressions now, in order to implement Go's unlimited precision
4782 // constants.
4784 Expression*
4785 Binary_expression::do_lower(Gogo* gogo, Named_object*,
4786 Statement_inserter* inserter, int)
4788 Location location = this->location();
4789 Operator op = this->op_;
4790 Expression* left = this->left_;
4791 Expression* right = this->right_;
4793 const bool is_comparison = (op == OPERATOR_EQEQ
4794 || op == OPERATOR_NOTEQ
4795 || op == OPERATOR_LT
4796 || op == OPERATOR_LE
4797 || op == OPERATOR_GT
4798 || op == OPERATOR_GE);
4800 // Numeric constant expressions.
4802 Numeric_constant left_nc;
4803 Numeric_constant right_nc;
4804 if (left->numeric_constant_value(&left_nc)
4805 && right->numeric_constant_value(&right_nc))
4807 if (is_comparison)
4809 bool result;
4810 if (!Binary_expression::compare_constant(op, &left_nc,
4811 &right_nc, location,
4812 &result))
4813 return this;
4814 return Expression::make_cast(Type::make_boolean_type(),
4815 Expression::make_boolean(result,
4816 location),
4817 location);
4819 else
4821 Numeric_constant nc;
4822 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
4823 location, &nc))
4824 return this;
4825 return nc.expression(location);
4830 // String constant expressions.
4831 if (left->type()->is_string_type() && right->type()->is_string_type())
4833 std::string left_string;
4834 std::string right_string;
4835 if (left->string_constant_value(&left_string)
4836 && right->string_constant_value(&right_string))
4838 if (op == OPERATOR_PLUS)
4839 return Expression::make_string(left_string + right_string,
4840 location);
4841 else if (is_comparison)
4843 int cmp = left_string.compare(right_string);
4844 bool r = Binary_expression::cmp_to_bool(op, cmp);
4845 return Expression::make_boolean(r, location);
4850 // Lower struct, array, and some interface comparisons.
4851 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
4853 if (left->type()->struct_type() != NULL
4854 && right->type()->struct_type() != NULL)
4855 return this->lower_struct_comparison(gogo, inserter);
4856 else if (left->type()->array_type() != NULL
4857 && !left->type()->is_slice_type()
4858 && right->type()->array_type() != NULL
4859 && !right->type()->is_slice_type())
4860 return this->lower_array_comparison(gogo, inserter);
4861 else if ((left->type()->interface_type() != NULL
4862 && right->type()->interface_type() == NULL)
4863 || (left->type()->interface_type() == NULL
4864 && right->type()->interface_type() != NULL))
4865 return this->lower_interface_value_comparison(gogo, inserter);
4868 return this;
4871 // Lower a struct comparison.
4873 Expression*
4874 Binary_expression::lower_struct_comparison(Gogo* gogo,
4875 Statement_inserter* inserter)
4877 Struct_type* st = this->left_->type()->struct_type();
4878 Struct_type* st2 = this->right_->type()->struct_type();
4879 if (st2 == NULL)
4880 return this;
4881 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
4882 return this;
4883 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
4884 this->right_->type(), NULL))
4885 return this;
4887 // See if we can compare using memcmp. As a heuristic, we use
4888 // memcmp rather than field references and comparisons if there are
4889 // more than two fields.
4890 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
4891 return this->lower_compare_to_memcmp(gogo, inserter);
4893 Location loc = this->location();
4895 Expression* left = this->left_;
4896 Temporary_statement* left_temp = NULL;
4897 if (left->var_expression() == NULL
4898 && left->temporary_reference_expression() == NULL)
4900 left_temp = Statement::make_temporary(left->type(), NULL, loc);
4901 inserter->insert(left_temp);
4902 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
4905 Expression* right = this->right_;
4906 Temporary_statement* right_temp = NULL;
4907 if (right->var_expression() == NULL
4908 && right->temporary_reference_expression() == NULL)
4910 right_temp = Statement::make_temporary(right->type(), NULL, loc);
4911 inserter->insert(right_temp);
4912 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
4915 Expression* ret = Expression::make_boolean(true, loc);
4916 const Struct_field_list* fields = st->fields();
4917 unsigned int field_index = 0;
4918 for (Struct_field_list::const_iterator pf = fields->begin();
4919 pf != fields->end();
4920 ++pf, ++field_index)
4922 if (Gogo::is_sink_name(pf->field_name()))
4923 continue;
4925 if (field_index > 0)
4927 if (left_temp == NULL)
4928 left = left->copy();
4929 else
4930 left = Expression::make_temporary_reference(left_temp, loc);
4931 if (right_temp == NULL)
4932 right = right->copy();
4933 else
4934 right = Expression::make_temporary_reference(right_temp, loc);
4936 Expression* f1 = Expression::make_field_reference(left, field_index,
4937 loc);
4938 Expression* f2 = Expression::make_field_reference(right, field_index,
4939 loc);
4940 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
4941 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
4944 if (this->op_ == OPERATOR_NOTEQ)
4945 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
4947 return ret;
4950 // Lower an array comparison.
4952 Expression*
4953 Binary_expression::lower_array_comparison(Gogo* gogo,
4954 Statement_inserter* inserter)
4956 Array_type* at = this->left_->type()->array_type();
4957 Array_type* at2 = this->right_->type()->array_type();
4958 if (at2 == NULL)
4959 return this;
4960 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
4961 return this;
4962 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
4963 this->right_->type(), NULL))
4964 return this;
4966 // Call memcmp directly if possible. This may let the middle-end
4967 // optimize the call.
4968 if (at->compare_is_identity(gogo))
4969 return this->lower_compare_to_memcmp(gogo, inserter);
4971 // Call the array comparison function.
4972 Named_object* hash_fn;
4973 Named_object* equal_fn;
4974 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
4975 &hash_fn, &equal_fn);
4977 Location loc = this->location();
4979 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
4981 Expression_list* args = new Expression_list();
4982 args->push_back(this->operand_address(inserter, this->left_));
4983 args->push_back(this->operand_address(inserter, this->right_));
4984 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
4986 Expression* ret = Expression::make_call(func, args, false, loc);
4988 if (this->op_ == OPERATOR_NOTEQ)
4989 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
4991 return ret;
4994 // Lower an interface to value comparison.
4996 Expression*
4997 Binary_expression::lower_interface_value_comparison(Gogo*,
4998 Statement_inserter* inserter)
5000 Type* left_type = this->left_->type();
5001 Type* right_type = this->right_->type();
5002 Interface_type* ift;
5003 if (left_type->interface_type() != NULL)
5005 ift = left_type->interface_type();
5006 if (!ift->implements_interface(right_type, NULL))
5007 return this;
5009 else
5011 ift = right_type->interface_type();
5012 if (!ift->implements_interface(left_type, NULL))
5013 return this;
5015 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5016 return this;
5018 Location loc = this->location();
5020 if (left_type->interface_type() == NULL
5021 && left_type->points_to() == NULL
5022 && !this->left_->is_addressable())
5024 Temporary_statement* temp =
5025 Statement::make_temporary(left_type, NULL, loc);
5026 inserter->insert(temp);
5027 this->left_ =
5028 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5031 if (right_type->interface_type() == NULL
5032 && right_type->points_to() == NULL
5033 && !this->right_->is_addressable())
5035 Temporary_statement* temp =
5036 Statement::make_temporary(right_type, NULL, loc);
5037 inserter->insert(temp);
5038 this->right_ =
5039 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5042 return this;
5045 // Lower a struct or array comparison to a call to memcmp.
5047 Expression*
5048 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5050 Location loc = this->location();
5052 Expression* a1 = this->operand_address(inserter, this->left_);
5053 Expression* a2 = this->operand_address(inserter, this->right_);
5054 Expression* len = Expression::make_type_info(this->left_->type(),
5055 TYPE_INFO_SIZE);
5057 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5058 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5059 return Expression::make_binary(this->op_, call, zero, loc);
5062 Expression*
5063 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5064 Statement_inserter* inserter)
5066 if (this->classification() == EXPRESSION_ERROR)
5067 return this;
5069 Location loc = this->location();
5070 Temporary_statement* temp;
5071 if (this->left_->type()->is_string_type()
5072 && this->op_ == OPERATOR_PLUS)
5074 if (!this->left_->is_variable()
5075 && !this->left_->is_constant())
5077 temp = Statement::make_temporary(NULL, this->left_, loc);
5078 inserter->insert(temp);
5079 this->left_ = Expression::make_temporary_reference(temp, loc);
5081 if (!this->right_->is_variable()
5082 && !this->right_->is_constant())
5084 temp =
5085 Statement::make_temporary(this->left_->type(), this->right_, loc);
5086 this->right_ = Expression::make_temporary_reference(temp, loc);
5087 inserter->insert(temp);
5091 Type* left_type = this->left_->type();
5092 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5093 || this->op_ == OPERATOR_RSHIFT);
5094 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5095 left_type->integer_type() != NULL)
5096 || this->op_ == OPERATOR_MOD);
5098 if (is_shift_op
5099 || (is_idiv_op
5100 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5102 if (!this->left_->is_variable())
5104 temp = Statement::make_temporary(NULL, this->left_, loc);
5105 inserter->insert(temp);
5106 this->left_ = Expression::make_temporary_reference(temp, loc);
5108 if (!this->right_->is_variable())
5110 temp =
5111 Statement::make_temporary(NULL, this->right_, loc);
5112 this->right_ = Expression::make_temporary_reference(temp, loc);
5113 inserter->insert(temp);
5116 return this;
5120 // Return the address of EXPR, cast to unsafe.Pointer.
5122 Expression*
5123 Binary_expression::operand_address(Statement_inserter* inserter,
5124 Expression* expr)
5126 Location loc = this->location();
5128 if (!expr->is_addressable())
5130 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5131 loc);
5132 inserter->insert(temp);
5133 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5135 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5136 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5137 Type* void_type = Type::make_void_type();
5138 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5139 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5142 // Return the numeric constant value, if it has one.
5144 bool
5145 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5147 Numeric_constant left_nc;
5148 if (!this->left_->numeric_constant_value(&left_nc))
5149 return false;
5150 Numeric_constant right_nc;
5151 if (!this->right_->numeric_constant_value(&right_nc))
5152 return false;
5153 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5154 this->location(), nc);
5157 // Note that the value is being discarded.
5159 bool
5160 Binary_expression::do_discarding_value()
5162 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5163 return this->right_->discarding_value();
5164 else
5166 this->unused_value_error();
5167 return false;
5171 // Get type.
5173 Type*
5174 Binary_expression::do_type()
5176 if (this->classification() == EXPRESSION_ERROR)
5177 return Type::make_error_type();
5179 switch (this->op_)
5181 case OPERATOR_EQEQ:
5182 case OPERATOR_NOTEQ:
5183 case OPERATOR_LT:
5184 case OPERATOR_LE:
5185 case OPERATOR_GT:
5186 case OPERATOR_GE:
5187 if (this->type_ == NULL)
5188 this->type_ = Type::make_boolean_type();
5189 return this->type_;
5191 case OPERATOR_PLUS:
5192 case OPERATOR_MINUS:
5193 case OPERATOR_OR:
5194 case OPERATOR_XOR:
5195 case OPERATOR_MULT:
5196 case OPERATOR_DIV:
5197 case OPERATOR_MOD:
5198 case OPERATOR_AND:
5199 case OPERATOR_BITCLEAR:
5200 case OPERATOR_OROR:
5201 case OPERATOR_ANDAND:
5203 Type* type;
5204 if (!Binary_expression::operation_type(this->op_,
5205 this->left_->type(),
5206 this->right_->type(),
5207 &type))
5208 return Type::make_error_type();
5209 return type;
5212 case OPERATOR_LSHIFT:
5213 case OPERATOR_RSHIFT:
5214 return this->left_->type();
5216 default:
5217 go_unreachable();
5221 // Set type for a binary expression.
5223 void
5224 Binary_expression::do_determine_type(const Type_context* context)
5226 Type* tleft = this->left_->type();
5227 Type* tright = this->right_->type();
5229 // Both sides should have the same type, except for the shift
5230 // operations. For a comparison, we should ignore the incoming
5231 // type.
5233 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5234 || this->op_ == OPERATOR_RSHIFT);
5236 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5237 || this->op_ == OPERATOR_NOTEQ
5238 || this->op_ == OPERATOR_LT
5239 || this->op_ == OPERATOR_LE
5240 || this->op_ == OPERATOR_GT
5241 || this->op_ == OPERATOR_GE);
5243 Type_context subcontext(*context);
5245 if (is_comparison)
5247 // In a comparison, the context does not determine the types of
5248 // the operands.
5249 subcontext.type = NULL;
5252 // Set the context for the left hand operand.
5253 if (is_shift_op)
5255 // The right hand operand of a shift plays no role in
5256 // determining the type of the left hand operand.
5258 else if (!tleft->is_abstract())
5259 subcontext.type = tleft;
5260 else if (!tright->is_abstract())
5261 subcontext.type = tright;
5262 else if (subcontext.type == NULL)
5264 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5265 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5266 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5268 // Both sides have an abstract integer, abstract float, or
5269 // abstract complex type. Just let CONTEXT determine
5270 // whether they may remain abstract or not.
5272 else if (tleft->complex_type() != NULL)
5273 subcontext.type = tleft;
5274 else if (tright->complex_type() != NULL)
5275 subcontext.type = tright;
5276 else if (tleft->float_type() != NULL)
5277 subcontext.type = tleft;
5278 else if (tright->float_type() != NULL)
5279 subcontext.type = tright;
5280 else
5281 subcontext.type = tleft;
5283 if (subcontext.type != NULL && !context->may_be_abstract)
5284 subcontext.type = subcontext.type->make_non_abstract_type();
5287 this->left_->determine_type(&subcontext);
5289 if (is_shift_op)
5291 // We may have inherited an unusable type for the shift operand.
5292 // Give a useful error if that happened.
5293 if (tleft->is_abstract()
5294 && subcontext.type != NULL
5295 && !subcontext.may_be_abstract
5296 && subcontext.type->interface_type() == NULL
5297 && subcontext.type->integer_type() == NULL)
5298 this->report_error(("invalid context-determined non-integer type "
5299 "for left operand of shift"));
5301 // The context for the right hand operand is the same as for the
5302 // left hand operand, except for a shift operator.
5303 subcontext.type = Type::lookup_integer_type("uint");
5304 subcontext.may_be_abstract = false;
5307 this->right_->determine_type(&subcontext);
5309 if (is_comparison)
5311 if (this->type_ != NULL && !this->type_->is_abstract())
5313 else if (context->type != NULL && context->type->is_boolean_type())
5314 this->type_ = context->type;
5315 else if (!context->may_be_abstract)
5316 this->type_ = Type::lookup_bool_type();
5320 // Report an error if the binary operator OP does not support TYPE.
5321 // OTYPE is the type of the other operand. Return whether the
5322 // operation is OK. This should not be used for shift.
5324 bool
5325 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5326 Location location)
5328 switch (op)
5330 case OPERATOR_OROR:
5331 case OPERATOR_ANDAND:
5332 if (!type->is_boolean_type())
5334 error_at(location, "expected boolean type");
5335 return false;
5337 break;
5339 case OPERATOR_EQEQ:
5340 case OPERATOR_NOTEQ:
5342 std::string reason;
5343 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5345 error_at(location, "%s", reason.c_str());
5346 return false;
5349 break;
5351 case OPERATOR_LT:
5352 case OPERATOR_LE:
5353 case OPERATOR_GT:
5354 case OPERATOR_GE:
5356 std::string reason;
5357 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5359 error_at(location, "%s", reason.c_str());
5360 return false;
5363 break;
5365 case OPERATOR_PLUS:
5366 case OPERATOR_PLUSEQ:
5367 if (type->integer_type() == NULL
5368 && type->float_type() == NULL
5369 && type->complex_type() == NULL
5370 && !type->is_string_type())
5372 error_at(location,
5373 "expected integer, floating, complex, or string type");
5374 return false;
5376 break;
5378 case OPERATOR_MINUS:
5379 case OPERATOR_MINUSEQ:
5380 case OPERATOR_MULT:
5381 case OPERATOR_MULTEQ:
5382 case OPERATOR_DIV:
5383 case OPERATOR_DIVEQ:
5384 if (type->integer_type() == NULL
5385 && type->float_type() == NULL
5386 && type->complex_type() == NULL)
5388 error_at(location, "expected integer, floating, or complex type");
5389 return false;
5391 break;
5393 case OPERATOR_MOD:
5394 case OPERATOR_MODEQ:
5395 case OPERATOR_OR:
5396 case OPERATOR_OREQ:
5397 case OPERATOR_AND:
5398 case OPERATOR_ANDEQ:
5399 case OPERATOR_XOR:
5400 case OPERATOR_XOREQ:
5401 case OPERATOR_BITCLEAR:
5402 case OPERATOR_BITCLEAREQ:
5403 if (type->integer_type() == NULL)
5405 error_at(location, "expected integer type");
5406 return false;
5408 break;
5410 default:
5411 go_unreachable();
5414 return true;
5417 // Check types.
5419 void
5420 Binary_expression::do_check_types(Gogo*)
5422 if (this->classification() == EXPRESSION_ERROR)
5423 return;
5425 Type* left_type = this->left_->type();
5426 Type* right_type = this->right_->type();
5427 if (left_type->is_error() || right_type->is_error())
5429 this->set_is_error();
5430 return;
5433 if (this->op_ == OPERATOR_EQEQ
5434 || this->op_ == OPERATOR_NOTEQ
5435 || this->op_ == OPERATOR_LT
5436 || this->op_ == OPERATOR_LE
5437 || this->op_ == OPERATOR_GT
5438 || this->op_ == OPERATOR_GE)
5440 if (left_type->is_nil_type() && right_type->is_nil_type())
5442 this->report_error(_("invalid comparison of nil with nil"));
5443 return;
5445 if (!Type::are_assignable(left_type, right_type, NULL)
5446 && !Type::are_assignable(right_type, left_type, NULL))
5448 this->report_error(_("incompatible types in binary expression"));
5449 return;
5451 if (!Binary_expression::check_operator_type(this->op_, left_type,
5452 right_type,
5453 this->location())
5454 || !Binary_expression::check_operator_type(this->op_, right_type,
5455 left_type,
5456 this->location()))
5458 this->set_is_error();
5459 return;
5462 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5464 if (!Type::are_compatible_for_binop(left_type, right_type))
5466 this->report_error(_("incompatible types in binary expression"));
5467 return;
5469 if (!Binary_expression::check_operator_type(this->op_, left_type,
5470 right_type,
5471 this->location()))
5473 this->set_is_error();
5474 return;
5476 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5478 // Division by a zero integer constant is an error.
5479 Numeric_constant rconst;
5480 unsigned long rval;
5481 if (left_type->integer_type() != NULL
5482 && this->right_->numeric_constant_value(&rconst)
5483 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5484 && rval == 0)
5486 this->report_error(_("integer division by zero"));
5487 return;
5491 else
5493 if (left_type->integer_type() == NULL)
5494 this->report_error(_("shift of non-integer operand"));
5496 if (!right_type->is_abstract()
5497 && (right_type->integer_type() == NULL
5498 || !right_type->integer_type()->is_unsigned()))
5499 this->report_error(_("shift count not unsigned integer"));
5500 else
5502 Numeric_constant nc;
5503 if (this->right_->numeric_constant_value(&nc))
5505 mpz_t val;
5506 if (!nc.to_int(&val))
5507 this->report_error(_("shift count not unsigned integer"));
5508 else
5510 if (mpz_sgn(val) < 0)
5512 this->report_error(_("negative shift count"));
5513 Location rloc = this->right_->location();
5514 this->right_ = Expression::make_integer_ul(0, right_type,
5515 rloc);
5517 mpz_clear(val);
5524 // Get the backend representation for a binary expression.
5526 Bexpression*
5527 Binary_expression::do_get_backend(Translate_context* context)
5529 Gogo* gogo = context->gogo();
5530 Location loc = this->location();
5531 Type* left_type = this->left_->type();
5532 Type* right_type = this->right_->type();
5534 bool use_left_type = true;
5535 bool is_shift_op = false;
5536 bool is_idiv_op = false;
5537 switch (this->op_)
5539 case OPERATOR_EQEQ:
5540 case OPERATOR_NOTEQ:
5541 case OPERATOR_LT:
5542 case OPERATOR_LE:
5543 case OPERATOR_GT:
5544 case OPERATOR_GE:
5545 return Expression::comparison(context, this->type_, this->op_,
5546 this->left_, this->right_, loc);
5548 case OPERATOR_OROR:
5549 case OPERATOR_ANDAND:
5550 use_left_type = false;
5551 break;
5552 case OPERATOR_PLUS:
5553 case OPERATOR_MINUS:
5554 case OPERATOR_OR:
5555 case OPERATOR_XOR:
5556 case OPERATOR_MULT:
5557 break;
5558 case OPERATOR_DIV:
5559 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5560 break;
5561 case OPERATOR_MOD:
5562 is_idiv_op = true;
5563 break;
5564 case OPERATOR_LSHIFT:
5565 case OPERATOR_RSHIFT:
5566 is_shift_op = true;
5567 break;
5568 case OPERATOR_BITCLEAR:
5569 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5570 case OPERATOR_AND:
5571 break;
5572 default:
5573 go_unreachable();
5576 if (left_type->is_string_type())
5578 go_assert(this->op_ == OPERATOR_PLUS);
5579 Expression* string_plus =
5580 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5581 this->left_, this->right_);
5582 return string_plus->get_backend(context);
5585 // For complex division Go might want slightly different results than the
5586 // backend implementation provides, so we have our own runtime routine.
5587 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5589 Runtime::Function complex_code;
5590 switch (this->left_->type()->complex_type()->bits())
5592 case 64:
5593 complex_code = Runtime::COMPLEX64_DIV;
5594 break;
5595 case 128:
5596 complex_code = Runtime::COMPLEX128_DIV;
5597 break;
5598 default:
5599 go_unreachable();
5601 Expression* complex_div =
5602 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5603 return complex_div->get_backend(context);
5606 Bexpression* left = this->left_->get_backend(context);
5607 Bexpression* right = this->right_->get_backend(context);
5609 Type* type = use_left_type ? left_type : right_type;
5610 Btype* btype = type->get_backend(gogo);
5612 Bexpression* ret =
5613 gogo->backend()->binary_expression(this->op_, left, right, loc);
5614 ret = gogo->backend()->convert_expression(btype, ret, loc);
5616 // Initialize overflow constants.
5617 Bexpression* overflow;
5618 mpz_t zero;
5619 mpz_init_set_ui(zero, 0UL);
5620 mpz_t one;
5621 mpz_init_set_ui(one, 1UL);
5622 mpz_t neg_one;
5623 mpz_init_set_si(neg_one, -1);
5625 Btype* left_btype = left_type->get_backend(gogo);
5626 Btype* right_btype = right_type->get_backend(gogo);
5628 // In Go, a shift larger than the size of the type is well-defined.
5629 // This is not true in C, so we need to insert a conditional.
5630 if (is_shift_op)
5632 go_assert(left_type->integer_type() != NULL);
5634 mpz_t bitsval;
5635 int bits = left_type->integer_type()->bits();
5636 mpz_init_set_ui(bitsval, bits);
5637 Bexpression* bits_expr =
5638 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5639 Bexpression* compare =
5640 gogo->backend()->binary_expression(OPERATOR_LT,
5641 right, bits_expr, loc);
5643 Bexpression* zero_expr =
5644 gogo->backend()->integer_constant_expression(left_btype, zero);
5645 overflow = zero_expr;
5646 if (this->op_ == OPERATOR_RSHIFT
5647 && !left_type->integer_type()->is_unsigned())
5649 Bexpression* neg_expr =
5650 gogo->backend()->binary_expression(OPERATOR_LT, left,
5651 zero_expr, loc);
5652 Bexpression* neg_one_expr =
5653 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5654 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5655 neg_one_expr,
5656 zero_expr, loc);
5658 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5659 overflow, loc);
5660 mpz_clear(bitsval);
5663 // Add checks for division by zero and division overflow as needed.
5664 if (is_idiv_op)
5666 if (gogo->check_divide_by_zero())
5668 // right == 0
5669 Bexpression* zero_expr =
5670 gogo->backend()->integer_constant_expression(right_btype, zero);
5671 Bexpression* check =
5672 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5673 right, zero_expr, loc);
5675 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
5676 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5677 Bexpression* crash = gogo->runtime_error(errcode,
5678 loc)->get_backend(context);
5680 // right == 0 ? (__go_runtime_error(...), 0) : ret
5681 ret = gogo->backend()->conditional_expression(btype, check, crash,
5682 ret, loc);
5685 if (gogo->check_divide_overflow())
5687 // right == -1
5688 // FIXME: It would be nice to say that this test is expected
5689 // to return false.
5691 Bexpression* neg_one_expr =
5692 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5693 Bexpression* check =
5694 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5695 right, neg_one_expr, loc);
5697 Bexpression* zero_expr =
5698 gogo->backend()->integer_constant_expression(btype, zero);
5699 Bexpression* one_expr =
5700 gogo->backend()->integer_constant_expression(btype, one);
5702 if (type->integer_type()->is_unsigned())
5704 // An unsigned -1 is the largest possible number, so
5705 // dividing is always 1 or 0.
5707 Bexpression* cmp =
5708 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5709 left, right, loc);
5710 if (this->op_ == OPERATOR_DIV)
5711 overflow =
5712 gogo->backend()->conditional_expression(btype, cmp,
5713 one_expr, zero_expr,
5714 loc);
5715 else
5716 overflow =
5717 gogo->backend()->conditional_expression(btype, cmp,
5718 zero_expr, left,
5719 loc);
5721 else
5723 // Computing left / -1 is the same as computing - left,
5724 // which does not overflow since Go sets -fwrapv.
5725 if (this->op_ == OPERATOR_DIV)
5727 Expression* negate_expr =
5728 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
5729 overflow = negate_expr->get_backend(context);
5731 else
5732 overflow = zero_expr;
5734 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
5736 // right == -1 ? - left : ret
5737 ret = gogo->backend()->conditional_expression(btype, check, overflow,
5738 ret, loc);
5742 mpz_clear(zero);
5743 mpz_clear(one);
5744 mpz_clear(neg_one);
5745 return ret;
5748 // Export a binary expression.
5750 void
5751 Binary_expression::do_export(Export* exp) const
5753 exp->write_c_string("(");
5754 this->left_->export_expression(exp);
5755 switch (this->op_)
5757 case OPERATOR_OROR:
5758 exp->write_c_string(" || ");
5759 break;
5760 case OPERATOR_ANDAND:
5761 exp->write_c_string(" && ");
5762 break;
5763 case OPERATOR_EQEQ:
5764 exp->write_c_string(" == ");
5765 break;
5766 case OPERATOR_NOTEQ:
5767 exp->write_c_string(" != ");
5768 break;
5769 case OPERATOR_LT:
5770 exp->write_c_string(" < ");
5771 break;
5772 case OPERATOR_LE:
5773 exp->write_c_string(" <= ");
5774 break;
5775 case OPERATOR_GT:
5776 exp->write_c_string(" > ");
5777 break;
5778 case OPERATOR_GE:
5779 exp->write_c_string(" >= ");
5780 break;
5781 case OPERATOR_PLUS:
5782 exp->write_c_string(" + ");
5783 break;
5784 case OPERATOR_MINUS:
5785 exp->write_c_string(" - ");
5786 break;
5787 case OPERATOR_OR:
5788 exp->write_c_string(" | ");
5789 break;
5790 case OPERATOR_XOR:
5791 exp->write_c_string(" ^ ");
5792 break;
5793 case OPERATOR_MULT:
5794 exp->write_c_string(" * ");
5795 break;
5796 case OPERATOR_DIV:
5797 exp->write_c_string(" / ");
5798 break;
5799 case OPERATOR_MOD:
5800 exp->write_c_string(" % ");
5801 break;
5802 case OPERATOR_LSHIFT:
5803 exp->write_c_string(" << ");
5804 break;
5805 case OPERATOR_RSHIFT:
5806 exp->write_c_string(" >> ");
5807 break;
5808 case OPERATOR_AND:
5809 exp->write_c_string(" & ");
5810 break;
5811 case OPERATOR_BITCLEAR:
5812 exp->write_c_string(" &^ ");
5813 break;
5814 default:
5815 go_unreachable();
5817 this->right_->export_expression(exp);
5818 exp->write_c_string(")");
5821 // Import a binary expression.
5823 Expression*
5824 Binary_expression::do_import(Import* imp)
5826 imp->require_c_string("(");
5828 Expression* left = Expression::import_expression(imp);
5830 Operator op;
5831 if (imp->match_c_string(" || "))
5833 op = OPERATOR_OROR;
5834 imp->advance(4);
5836 else if (imp->match_c_string(" && "))
5838 op = OPERATOR_ANDAND;
5839 imp->advance(4);
5841 else if (imp->match_c_string(" == "))
5843 op = OPERATOR_EQEQ;
5844 imp->advance(4);
5846 else if (imp->match_c_string(" != "))
5848 op = OPERATOR_NOTEQ;
5849 imp->advance(4);
5851 else if (imp->match_c_string(" < "))
5853 op = OPERATOR_LT;
5854 imp->advance(3);
5856 else if (imp->match_c_string(" <= "))
5858 op = OPERATOR_LE;
5859 imp->advance(4);
5861 else if (imp->match_c_string(" > "))
5863 op = OPERATOR_GT;
5864 imp->advance(3);
5866 else if (imp->match_c_string(" >= "))
5868 op = OPERATOR_GE;
5869 imp->advance(4);
5871 else if (imp->match_c_string(" + "))
5873 op = OPERATOR_PLUS;
5874 imp->advance(3);
5876 else if (imp->match_c_string(" - "))
5878 op = OPERATOR_MINUS;
5879 imp->advance(3);
5881 else if (imp->match_c_string(" | "))
5883 op = OPERATOR_OR;
5884 imp->advance(3);
5886 else if (imp->match_c_string(" ^ "))
5888 op = OPERATOR_XOR;
5889 imp->advance(3);
5891 else if (imp->match_c_string(" * "))
5893 op = OPERATOR_MULT;
5894 imp->advance(3);
5896 else if (imp->match_c_string(" / "))
5898 op = OPERATOR_DIV;
5899 imp->advance(3);
5901 else if (imp->match_c_string(" % "))
5903 op = OPERATOR_MOD;
5904 imp->advance(3);
5906 else if (imp->match_c_string(" << "))
5908 op = OPERATOR_LSHIFT;
5909 imp->advance(4);
5911 else if (imp->match_c_string(" >> "))
5913 op = OPERATOR_RSHIFT;
5914 imp->advance(4);
5916 else if (imp->match_c_string(" & "))
5918 op = OPERATOR_AND;
5919 imp->advance(3);
5921 else if (imp->match_c_string(" &^ "))
5923 op = OPERATOR_BITCLEAR;
5924 imp->advance(4);
5926 else
5928 error_at(imp->location(), "unrecognized binary operator");
5929 return Expression::make_error(imp->location());
5932 Expression* right = Expression::import_expression(imp);
5934 imp->require_c_string(")");
5936 return Expression::make_binary(op, left, right, imp->location());
5939 // Dump ast representation of a binary expression.
5941 void
5942 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5944 ast_dump_context->ostream() << "(";
5945 ast_dump_context->dump_expression(this->left_);
5946 ast_dump_context->ostream() << " ";
5947 ast_dump_context->dump_operator(this->op_);
5948 ast_dump_context->ostream() << " ";
5949 ast_dump_context->dump_expression(this->right_);
5950 ast_dump_context->ostream() << ") ";
5953 // Make a binary expression.
5955 Expression*
5956 Expression::make_binary(Operator op, Expression* left, Expression* right,
5957 Location location)
5959 return new Binary_expression(op, left, right, location);
5962 // Implement a comparison.
5964 Bexpression*
5965 Expression::comparison(Translate_context* context, Type* result_type,
5966 Operator op, Expression* left, Expression* right,
5967 Location location)
5969 Type* left_type = left->type();
5970 Type* right_type = right->type();
5972 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
5974 if (left_type->is_string_type() && right_type->is_string_type())
5976 left = Runtime::make_call(Runtime::STRCMP, location, 2,
5977 left, right);
5978 right = zexpr;
5980 else if ((left_type->interface_type() != NULL
5981 && right_type->interface_type() == NULL
5982 && !right_type->is_nil_type())
5983 || (left_type->interface_type() == NULL
5984 && !left_type->is_nil_type()
5985 && right_type->interface_type() != NULL))
5987 // Comparing an interface value to a non-interface value.
5988 if (left_type->interface_type() == NULL)
5990 std::swap(left_type, right_type);
5991 std::swap(left, right);
5994 // The right operand is not an interface. We need to take its
5995 // address if it is not a pointer.
5996 Expression* pointer_arg = NULL;
5997 if (right_type->points_to() != NULL)
5998 pointer_arg = right;
5999 else
6001 go_assert(right->is_addressable());
6002 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6003 location);
6006 Expression* descriptor =
6007 Expression::make_type_descriptor(right_type, location);
6008 left =
6009 Runtime::make_call((left_type->interface_type()->is_empty()
6010 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6011 : Runtime::INTERFACE_VALUE_COMPARE),
6012 location, 3, left, descriptor,
6013 pointer_arg);
6014 right = zexpr;
6016 else if (left_type->interface_type() != NULL
6017 && right_type->interface_type() != NULL)
6019 Runtime::Function compare_function;
6020 if (left_type->interface_type()->is_empty()
6021 && right_type->interface_type()->is_empty())
6022 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6023 else if (!left_type->interface_type()->is_empty()
6024 && !right_type->interface_type()->is_empty())
6025 compare_function = Runtime::INTERFACE_COMPARE;
6026 else
6028 if (left_type->interface_type()->is_empty())
6030 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6031 std::swap(left_type, right_type);
6032 std::swap(left, right);
6034 go_assert(!left_type->interface_type()->is_empty());
6035 go_assert(right_type->interface_type()->is_empty());
6036 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6039 left = Runtime::make_call(compare_function, location, 2, left, right);
6040 right = zexpr;
6043 if (left_type->is_nil_type()
6044 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6046 std::swap(left_type, right_type);
6047 std::swap(left, right);
6050 if (right_type->is_nil_type())
6052 right = Expression::make_nil(location);
6053 if (left_type->array_type() != NULL
6054 && left_type->array_type()->length() == NULL)
6056 Array_type* at = left_type->array_type();
6057 left = at->get_value_pointer(context->gogo(), left);
6059 else if (left_type->interface_type() != NULL)
6061 // An interface is nil if the first field is nil.
6062 left = Expression::make_field_reference(left, 0, location);
6066 Bexpression* left_bexpr = left->get_backend(context);
6067 Bexpression* right_bexpr = right->get_backend(context);
6069 Gogo* gogo = context->gogo();
6070 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6071 right_bexpr, location);
6072 if (result_type != NULL)
6073 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6074 ret, location);
6075 return ret;
6078 // Class Bound_method_expression.
6080 // Traversal.
6083 Bound_method_expression::do_traverse(Traverse* traverse)
6085 return Expression::traverse(&this->expr_, traverse);
6088 // Lower the expression. If this is a method value rather than being
6089 // called, and the method is accessed via a pointer, we may need to
6090 // add nil checks. Introduce a temporary variable so that those nil
6091 // checks do not cause multiple evaluation.
6093 Expression*
6094 Bound_method_expression::do_lower(Gogo*, Named_object*,
6095 Statement_inserter* inserter, int)
6097 // For simplicity we use a temporary for every call to an embedded
6098 // method, even though some of them might be pure value methods and
6099 // not require a temporary.
6100 if (this->expr_->var_expression() == NULL
6101 && this->expr_->temporary_reference_expression() == NULL
6102 && this->expr_->set_and_use_temporary_expression() == NULL
6103 && (this->method_->field_indexes() != NULL
6104 || (this->method_->is_value_method()
6105 && this->expr_->type()->points_to() != NULL)))
6107 Temporary_statement* temp =
6108 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6109 inserter->insert(temp);
6110 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6111 this->location());
6113 return this;
6116 // Return the type of a bound method expression. The type of this
6117 // object is simply the type of the method with no receiver.
6119 Type*
6120 Bound_method_expression::do_type()
6122 Named_object* fn = this->method_->named_object();
6123 Function_type* fntype;
6124 if (fn->is_function())
6125 fntype = fn->func_value()->type();
6126 else if (fn->is_function_declaration())
6127 fntype = fn->func_declaration_value()->type();
6128 else
6129 return Type::make_error_type();
6130 return fntype->copy_without_receiver();
6133 // Determine the types of a method expression.
6135 void
6136 Bound_method_expression::do_determine_type(const Type_context*)
6138 Named_object* fn = this->method_->named_object();
6139 Function_type* fntype;
6140 if (fn->is_function())
6141 fntype = fn->func_value()->type();
6142 else if (fn->is_function_declaration())
6143 fntype = fn->func_declaration_value()->type();
6144 else
6145 fntype = NULL;
6146 if (fntype == NULL || !fntype->is_method())
6147 this->expr_->determine_type_no_context();
6148 else
6150 Type_context subcontext(fntype->receiver()->type(), false);
6151 this->expr_->determine_type(&subcontext);
6155 // Check the types of a method expression.
6157 void
6158 Bound_method_expression::do_check_types(Gogo*)
6160 Named_object* fn = this->method_->named_object();
6161 if (!fn->is_function() && !fn->is_function_declaration())
6163 this->report_error(_("object is not a method"));
6164 return;
6167 Function_type* fntype;
6168 if (fn->is_function())
6169 fntype = fn->func_value()->type();
6170 else if (fn->is_function_declaration())
6171 fntype = fn->func_declaration_value()->type();
6172 else
6173 go_unreachable();
6174 Type* rtype = fntype->receiver()->type()->deref();
6175 Type* etype = (this->expr_type_ != NULL
6176 ? this->expr_type_
6177 : this->expr_->type());
6178 etype = etype->deref();
6179 if (!Type::are_identical(rtype, etype, true, NULL))
6180 this->report_error(_("method type does not match object type"));
6183 // If a bound method expression is not simply called, then it is
6184 // represented as a closure. The closure will hold a single variable,
6185 // the receiver to pass to the method. The function will be a simple
6186 // thunk that pulls that value from the closure and calls the method
6187 // with the remaining arguments.
6189 // Because method values are not common, we don't build all thunks for
6190 // every methods, but instead only build them as we need them. In
6191 // particular, we even build them on demand for methods defined in
6192 // other packages.
6194 Bound_method_expression::Method_value_thunks
6195 Bound_method_expression::method_value_thunks;
6197 // Find or create the thunk for METHOD.
6199 Named_object*
6200 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6201 Named_object* fn)
6203 std::pair<Named_object*, Named_object*> val(fn, NULL);
6204 std::pair<Method_value_thunks::iterator, bool> ins =
6205 Bound_method_expression::method_value_thunks.insert(val);
6206 if (!ins.second)
6208 // We have seen this method before.
6209 go_assert(ins.first->second != NULL);
6210 return ins.first->second;
6213 Location loc = fn->location();
6215 Function_type* orig_fntype;
6216 if (fn->is_function())
6217 orig_fntype = fn->func_value()->type();
6218 else if (fn->is_function_declaration())
6219 orig_fntype = fn->func_declaration_value()->type();
6220 else
6221 orig_fntype = NULL;
6223 if (orig_fntype == NULL || !orig_fntype->is_method())
6225 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6226 return ins.first->second;
6229 Struct_field_list* sfl = new Struct_field_list();
6230 // The type here is wrong--it should be the C function type. But it
6231 // doesn't really matter.
6232 Type* vt = Type::make_pointer_type(Type::make_void_type());
6233 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6234 sfl->push_back(Struct_field(Typed_identifier("val.1",
6235 orig_fntype->receiver()->type(),
6236 loc)));
6237 Type* closure_type = Type::make_struct_type(sfl, loc);
6238 closure_type = Type::make_pointer_type(closure_type);
6240 Function_type* new_fntype = orig_fntype->copy_with_names();
6242 std::string thunk_name = Gogo::thunk_name();
6243 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6244 false, loc);
6246 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6247 cvar->set_is_used();
6248 cvar->set_is_closure();
6249 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6250 NULL, cvar);
6251 new_no->func_value()->set_closure_var(cp);
6253 gogo->start_block(loc);
6255 // Field 0 of the closure is the function code pointer, field 1 is
6256 // the value on which to invoke the method.
6257 Expression* arg = Expression::make_var_reference(cp, loc);
6258 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6259 arg = Expression::make_field_reference(arg, 1, loc);
6261 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6263 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6264 Expression_list* args;
6265 if (orig_params == NULL || orig_params->empty())
6266 args = NULL;
6267 else
6269 const Typed_identifier_list* new_params = new_fntype->parameters();
6270 args = new Expression_list();
6271 for (Typed_identifier_list::const_iterator p = new_params->begin();
6272 p != new_params->end();
6273 ++p)
6275 Named_object* p_no = gogo->lookup(p->name(), NULL);
6276 go_assert(p_no != NULL
6277 && p_no->is_variable()
6278 && p_no->var_value()->is_parameter());
6279 args->push_back(Expression::make_var_reference(p_no, loc));
6283 Call_expression* call = Expression::make_call(bme, args,
6284 orig_fntype->is_varargs(),
6285 loc);
6286 call->set_varargs_are_lowered();
6288 Statement* s = Statement::make_return_from_call(call, loc);
6289 gogo->add_statement(s);
6290 Block* b = gogo->finish_block(loc);
6291 gogo->add_block(b, loc);
6292 gogo->lower_block(new_no, b);
6293 gogo->flatten_block(new_no, b);
6294 gogo->finish_function(loc);
6296 ins.first->second = new_no;
6297 return new_no;
6300 // Return an expression to check *REF for nil while dereferencing
6301 // according to FIELD_INDEXES. Update *REF to build up the field
6302 // reference. This is a static function so that we don't have to
6303 // worry about declaring Field_indexes in expressions.h.
6305 static Expression*
6306 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6307 Expression** ref)
6309 if (field_indexes == NULL)
6310 return Expression::make_boolean(false, loc);
6311 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6312 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6313 go_assert(stype != NULL
6314 && field_indexes->field_index < stype->field_count());
6315 if ((*ref)->type()->struct_type() == NULL)
6317 go_assert((*ref)->type()->points_to() != NULL);
6318 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6319 Expression::make_nil(loc),
6320 loc);
6321 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6322 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6323 go_assert((*ref)->type()->struct_type() == stype);
6325 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6326 loc);
6327 return cond;
6330 // Get the backend representation for a method value.
6332 Bexpression*
6333 Bound_method_expression::do_get_backend(Translate_context* context)
6335 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6336 this->method_,
6337 this->function_);
6338 if (thunk->is_erroneous())
6340 go_assert(saw_errors());
6341 return context->backend()->error_expression();
6344 // FIXME: We should lower this earlier, but we can't lower it in the
6345 // lowering pass because at that point we don't know whether we need
6346 // to create the thunk or not. If the expression is called, we
6347 // don't need the thunk.
6349 Location loc = this->location();
6351 // If the method expects a value, and we have a pointer, we need to
6352 // dereference the pointer.
6354 Named_object* fn = this->method_->named_object();
6355 Function_type* fntype;
6356 if (fn->is_function())
6357 fntype = fn->func_value()->type();
6358 else if (fn->is_function_declaration())
6359 fntype = fn->func_declaration_value()->type();
6360 else
6361 go_unreachable();
6363 Expression* val = this->expr_;
6364 if (fntype->receiver()->type()->points_to() == NULL
6365 && val->type()->points_to() != NULL)
6366 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6368 // Note that we are ignoring this->expr_type_ here. The thunk will
6369 // expect a closure whose second field has type this->expr_type_ (if
6370 // that is not NULL). We are going to pass it a closure whose
6371 // second field has type this->expr_->type(). Since
6372 // this->expr_type_ is only not-NULL for pointer types, we can get
6373 // away with this.
6375 Struct_field_list* fields = new Struct_field_list();
6376 fields->push_back(Struct_field(Typed_identifier("fn.0",
6377 thunk->func_value()->type(),
6378 loc)));
6379 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6380 Struct_type* st = Type::make_struct_type(fields, loc);
6382 Expression_list* vals = new Expression_list();
6383 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6384 vals->push_back(val);
6386 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6387 ret = Expression::make_heap_expression(ret, loc);
6389 // See whether the expression or any embedded pointers are nil.
6391 Expression* nil_check = NULL;
6392 Expression* expr = this->expr_;
6393 if (this->method_->field_indexes() != NULL)
6395 // Note that we are evaluating this->expr_ twice, but that is OK
6396 // because in the lowering pass we forced it into a temporary
6397 // variable.
6398 Expression* ref = expr;
6399 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6400 expr = ref;
6403 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6405 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6406 Expression::make_nil(loc),
6407 loc);
6408 if (nil_check == NULL)
6409 nil_check = n;
6410 else
6411 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6414 Bexpression* bme = ret->get_backend(context);
6415 if (nil_check != NULL)
6417 Gogo* gogo = context->gogo();
6418 Bexpression* crash =
6419 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6420 loc)->get_backend(context);
6421 Btype* btype = ret->type()->get_backend(gogo);
6422 Bexpression* bcheck = nil_check->get_backend(context);
6423 bme = gogo->backend()->conditional_expression(btype, bcheck, crash,
6424 bme, loc);
6426 return bme;
6429 // Dump ast representation of a bound method expression.
6431 void
6432 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6433 const
6435 if (this->expr_type_ != NULL)
6436 ast_dump_context->ostream() << "(";
6437 ast_dump_context->dump_expression(this->expr_);
6438 if (this->expr_type_ != NULL)
6440 ast_dump_context->ostream() << ":";
6441 ast_dump_context->dump_type(this->expr_type_);
6442 ast_dump_context->ostream() << ")";
6445 ast_dump_context->ostream() << "." << this->function_->name();
6448 // Make a method expression.
6450 Bound_method_expression*
6451 Expression::make_bound_method(Expression* expr, const Method* method,
6452 Named_object* function, Location location)
6454 return new Bound_method_expression(expr, method, function, location);
6457 // Class Builtin_call_expression. This is used for a call to a
6458 // builtin function.
6460 class Builtin_call_expression : public Call_expression
6462 public:
6463 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6464 bool is_varargs, Location location);
6466 protected:
6467 // This overrides Call_expression::do_lower.
6468 Expression*
6469 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6471 Expression*
6472 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6474 bool
6475 do_is_constant() const;
6477 bool
6478 do_numeric_constant_value(Numeric_constant*) const;
6480 bool
6481 do_discarding_value();
6483 Type*
6484 do_type();
6486 void
6487 do_determine_type(const Type_context*);
6489 void
6490 do_check_types(Gogo*);
6492 Expression*
6493 do_copy();
6495 Bexpression*
6496 do_get_backend(Translate_context*);
6498 void
6499 do_export(Export*) const;
6501 virtual bool
6502 do_is_recover_call() const;
6504 virtual void
6505 do_set_recover_arg(Expression*);
6507 private:
6508 // The builtin functions.
6509 enum Builtin_function_code
6511 BUILTIN_INVALID,
6513 // Predeclared builtin functions.
6514 BUILTIN_APPEND,
6515 BUILTIN_CAP,
6516 BUILTIN_CLOSE,
6517 BUILTIN_COMPLEX,
6518 BUILTIN_COPY,
6519 BUILTIN_DELETE,
6520 BUILTIN_IMAG,
6521 BUILTIN_LEN,
6522 BUILTIN_MAKE,
6523 BUILTIN_NEW,
6524 BUILTIN_PANIC,
6525 BUILTIN_PRINT,
6526 BUILTIN_PRINTLN,
6527 BUILTIN_REAL,
6528 BUILTIN_RECOVER,
6530 // Builtin functions from the unsafe package.
6531 BUILTIN_ALIGNOF,
6532 BUILTIN_OFFSETOF,
6533 BUILTIN_SIZEOF
6536 Expression*
6537 one_arg() const;
6539 bool
6540 check_one_arg();
6542 static Type*
6543 real_imag_type(Type*);
6545 static Type*
6546 complex_type(Type*);
6548 Expression*
6549 lower_make();
6551 bool
6552 check_int_value(Expression*, bool is_length);
6554 // A pointer back to the general IR structure. This avoids a global
6555 // variable, or passing it around everywhere.
6556 Gogo* gogo_;
6557 // The builtin function being called.
6558 Builtin_function_code code_;
6559 // Used to stop endless loops when the length of an array uses len
6560 // or cap of the array itself.
6561 mutable bool seen_;
6562 // Whether the argument is set for calls to BUILTIN_RECOVER.
6563 bool recover_arg_is_set_;
6566 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6567 Expression* fn,
6568 Expression_list* args,
6569 bool is_varargs,
6570 Location location)
6571 : Call_expression(fn, args, is_varargs, location),
6572 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
6573 recover_arg_is_set_(false)
6575 Func_expression* fnexp = this->fn()->func_expression();
6576 go_assert(fnexp != NULL);
6577 const std::string& name(fnexp->named_object()->name());
6578 if (name == "append")
6579 this->code_ = BUILTIN_APPEND;
6580 else if (name == "cap")
6581 this->code_ = BUILTIN_CAP;
6582 else if (name == "close")
6583 this->code_ = BUILTIN_CLOSE;
6584 else if (name == "complex")
6585 this->code_ = BUILTIN_COMPLEX;
6586 else if (name == "copy")
6587 this->code_ = BUILTIN_COPY;
6588 else if (name == "delete")
6589 this->code_ = BUILTIN_DELETE;
6590 else if (name == "imag")
6591 this->code_ = BUILTIN_IMAG;
6592 else if (name == "len")
6593 this->code_ = BUILTIN_LEN;
6594 else if (name == "make")
6595 this->code_ = BUILTIN_MAKE;
6596 else if (name == "new")
6597 this->code_ = BUILTIN_NEW;
6598 else if (name == "panic")
6599 this->code_ = BUILTIN_PANIC;
6600 else if (name == "print")
6601 this->code_ = BUILTIN_PRINT;
6602 else if (name == "println")
6603 this->code_ = BUILTIN_PRINTLN;
6604 else if (name == "real")
6605 this->code_ = BUILTIN_REAL;
6606 else if (name == "recover")
6607 this->code_ = BUILTIN_RECOVER;
6608 else if (name == "Alignof")
6609 this->code_ = BUILTIN_ALIGNOF;
6610 else if (name == "Offsetof")
6611 this->code_ = BUILTIN_OFFSETOF;
6612 else if (name == "Sizeof")
6613 this->code_ = BUILTIN_SIZEOF;
6614 else
6615 go_unreachable();
6618 // Return whether this is a call to recover. This is a virtual
6619 // function called from the parent class.
6621 bool
6622 Builtin_call_expression::do_is_recover_call() const
6624 if (this->classification() == EXPRESSION_ERROR)
6625 return false;
6626 return this->code_ == BUILTIN_RECOVER;
6629 // Set the argument for a call to recover.
6631 void
6632 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6634 const Expression_list* args = this->args();
6635 go_assert(args == NULL || args->empty());
6636 Expression_list* new_args = new Expression_list();
6637 new_args->push_back(arg);
6638 this->set_args(new_args);
6639 this->recover_arg_is_set_ = true;
6642 // Lower a builtin call expression. This turns new and make into
6643 // specific expressions. We also convert to a constant if we can.
6645 Expression*
6646 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6647 Statement_inserter* inserter, int)
6649 if (this->classification() == EXPRESSION_ERROR)
6650 return this;
6652 Location loc = this->location();
6654 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6656 this->report_error(_("invalid use of %<...%> with builtin function"));
6657 return Expression::make_error(loc);
6660 if (this->code_ == BUILTIN_OFFSETOF)
6662 Expression* arg = this->one_arg();
6664 if (arg->bound_method_expression() != NULL
6665 || arg->interface_field_reference_expression() != NULL)
6667 this->report_error(_("invalid use of method value as argument "
6668 "of Offsetof"));
6669 return this;
6672 Field_reference_expression* farg = arg->field_reference_expression();
6673 while (farg != NULL)
6675 if (!farg->implicit())
6676 break;
6677 // When the selector refers to an embedded field,
6678 // it must not be reached through pointer indirections.
6679 if (farg->expr()->deref() != farg->expr())
6681 this->report_error(_("argument of Offsetof implies "
6682 "indirection of an embedded field"));
6683 return this;
6685 // Go up until we reach the original base.
6686 farg = farg->expr()->field_reference_expression();
6690 if (this->is_constant())
6692 Numeric_constant nc;
6693 if (this->numeric_constant_value(&nc))
6694 return nc.expression(loc);
6697 switch (this->code_)
6699 default:
6700 break;
6702 case BUILTIN_NEW:
6704 const Expression_list* args = this->args();
6705 if (args == NULL || args->size() < 1)
6706 this->report_error(_("not enough arguments"));
6707 else if (args->size() > 1)
6708 this->report_error(_("too many arguments"));
6709 else
6711 Expression* arg = args->front();
6712 if (!arg->is_type_expression())
6714 error_at(arg->location(), "expected type");
6715 this->set_is_error();
6717 else
6718 return Expression::make_allocation(arg->type(), loc);
6721 break;
6723 case BUILTIN_MAKE:
6724 return this->lower_make();
6726 case BUILTIN_RECOVER:
6727 if (function != NULL)
6728 function->func_value()->set_calls_recover();
6729 else
6731 // Calling recover outside of a function always returns the
6732 // nil empty interface.
6733 Type* eface = Type::make_empty_interface_type(loc);
6734 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6736 break;
6738 case BUILTIN_APPEND:
6740 // Lower the varargs.
6741 const Expression_list* args = this->args();
6742 if (args == NULL || args->empty())
6743 return this;
6744 Type* slice_type = args->front()->type();
6745 if (!slice_type->is_slice_type())
6747 if (slice_type->is_nil_type())
6748 error_at(args->front()->location(), "use of untyped nil");
6749 else
6750 error_at(args->front()->location(),
6751 "argument 1 must be a slice");
6752 this->set_is_error();
6753 return this;
6755 Type* element_type = slice_type->array_type()->element_type();
6756 this->lower_varargs(gogo, function, inserter,
6757 Type::make_array_type(element_type, NULL),
6760 break;
6762 case BUILTIN_DELETE:
6764 // Lower to a runtime function call.
6765 const Expression_list* args = this->args();
6766 if (args == NULL || args->size() < 2)
6767 this->report_error(_("not enough arguments"));
6768 else if (args->size() > 2)
6769 this->report_error(_("too many arguments"));
6770 else if (args->front()->type()->map_type() == NULL)
6771 this->report_error(_("argument 1 must be a map"));
6772 else
6774 // Since this function returns no value it must appear in
6775 // a statement by itself, so we don't have to worry about
6776 // order of evaluation of values around it. Evaluate the
6777 // map first to get order of evaluation right.
6778 Map_type* mt = args->front()->type()->map_type();
6779 Temporary_statement* map_temp =
6780 Statement::make_temporary(mt, args->front(), loc);
6781 inserter->insert(map_temp);
6783 Temporary_statement* key_temp =
6784 Statement::make_temporary(mt->key_type(), args->back(), loc);
6785 inserter->insert(key_temp);
6787 Expression* e1 = Expression::make_temporary_reference(map_temp,
6788 loc);
6789 Expression* e2 = Expression::make_temporary_reference(key_temp,
6790 loc);
6791 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6792 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6793 2, e1, e2);
6796 break;
6799 return this;
6802 // Flatten a builtin call expression. This turns the arguments of copy and
6803 // append into temporary expressions.
6805 Expression*
6806 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
6807 Statement_inserter* inserter)
6809 Location loc = this->location();
6811 switch (this->code_)
6813 default:
6814 break;
6816 case BUILTIN_APPEND:
6817 case BUILTIN_COPY:
6819 Type* at = this->args()->front()->type();
6820 for (Expression_list::iterator pa = this->args()->begin();
6821 pa != this->args()->end();
6822 ++pa)
6824 if ((*pa)->is_nil_expression())
6826 Expression* nil = Expression::make_nil(loc);
6827 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
6828 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
6830 if (!(*pa)->is_variable())
6832 Temporary_statement* temp =
6833 Statement::make_temporary(NULL, *pa, loc);
6834 inserter->insert(temp);
6835 *pa = Expression::make_temporary_reference(temp, loc);
6839 break;
6841 case BUILTIN_PANIC:
6842 for (Expression_list::iterator pa = this->args()->begin();
6843 pa != this->args()->end();
6844 ++pa)
6846 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
6848 Temporary_statement* temp =
6849 Statement::make_temporary(NULL, *pa, loc);
6850 inserter->insert(temp);
6851 *pa = Expression::make_temporary_reference(temp, loc);
6856 return this;
6859 // Lower a make expression.
6861 Expression*
6862 Builtin_call_expression::lower_make()
6864 Location loc = this->location();
6866 const Expression_list* args = this->args();
6867 if (args == NULL || args->size() < 1)
6869 this->report_error(_("not enough arguments"));
6870 return Expression::make_error(this->location());
6873 Expression_list::const_iterator parg = args->begin();
6875 Expression* first_arg = *parg;
6876 if (!first_arg->is_type_expression())
6878 error_at(first_arg->location(), "expected type");
6879 this->set_is_error();
6880 return Expression::make_error(this->location());
6882 Type* type = first_arg->type();
6884 bool is_slice = false;
6885 bool is_map = false;
6886 bool is_chan = false;
6887 if (type->is_slice_type())
6888 is_slice = true;
6889 else if (type->map_type() != NULL)
6890 is_map = true;
6891 else if (type->channel_type() != NULL)
6892 is_chan = true;
6893 else
6895 this->report_error(_("invalid type for make function"));
6896 return Expression::make_error(this->location());
6899 bool have_big_args = false;
6900 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6901 int uintptr_bits = uintptr_type->integer_type()->bits();
6903 Type_context int_context(Type::lookup_integer_type("int"), false);
6905 ++parg;
6906 Expression* len_arg;
6907 if (parg == args->end())
6909 if (is_slice)
6911 this->report_error(_("length required when allocating a slice"));
6912 return Expression::make_error(this->location());
6914 len_arg = Expression::make_integer_ul(0, NULL, loc);
6916 else
6918 len_arg = *parg;
6919 len_arg->determine_type(&int_context);
6920 if (!this->check_int_value(len_arg, true))
6921 return Expression::make_error(this->location());
6922 if (len_arg->type()->integer_type() != NULL
6923 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6924 have_big_args = true;
6925 ++parg;
6928 Expression* cap_arg = NULL;
6929 if (is_slice && parg != args->end())
6931 cap_arg = *parg;
6932 cap_arg->determine_type(&int_context);
6933 if (!this->check_int_value(cap_arg, false))
6934 return Expression::make_error(this->location());
6936 Numeric_constant nclen;
6937 Numeric_constant nccap;
6938 unsigned long vlen;
6939 unsigned long vcap;
6940 if (len_arg->numeric_constant_value(&nclen)
6941 && cap_arg->numeric_constant_value(&nccap)
6942 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
6943 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
6944 && vlen > vcap)
6946 this->report_error(_("len larger than cap"));
6947 return Expression::make_error(this->location());
6950 if (cap_arg->type()->integer_type() != NULL
6951 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6952 have_big_args = true;
6953 ++parg;
6956 if (parg != args->end())
6958 this->report_error(_("too many arguments to make"));
6959 return Expression::make_error(this->location());
6962 Location type_loc = first_arg->location();
6963 Expression* type_arg;
6964 if (is_slice || is_chan)
6965 type_arg = Expression::make_type_descriptor(type, type_loc);
6966 else if (is_map)
6967 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6968 else
6969 go_unreachable();
6971 Expression* call;
6972 if (is_slice)
6974 if (cap_arg == NULL)
6975 call = Runtime::make_call((have_big_args
6976 ? Runtime::MAKESLICE1BIG
6977 : Runtime::MAKESLICE1),
6978 loc, 2, type_arg, len_arg);
6979 else
6980 call = Runtime::make_call((have_big_args
6981 ? Runtime::MAKESLICE2BIG
6982 : Runtime::MAKESLICE2),
6983 loc, 3, type_arg, len_arg, cap_arg);
6985 else if (is_map)
6986 call = Runtime::make_call((have_big_args
6987 ? Runtime::MAKEMAPBIG
6988 : Runtime::MAKEMAP),
6989 loc, 2, type_arg, len_arg);
6990 else if (is_chan)
6991 call = Runtime::make_call((have_big_args
6992 ? Runtime::MAKECHANBIG
6993 : Runtime::MAKECHAN),
6994 loc, 2, type_arg, len_arg);
6995 else
6996 go_unreachable();
6998 return Expression::make_unsafe_cast(type, call, loc);
7001 // Return whether an expression has an integer value. Report an error
7002 // if not. This is used when handling calls to the predeclared make
7003 // function.
7005 bool
7006 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7008 Numeric_constant nc;
7009 if (e->numeric_constant_value(&nc))
7011 unsigned long v;
7012 switch (nc.to_unsigned_long(&v))
7014 case Numeric_constant::NC_UL_VALID:
7015 break;
7016 case Numeric_constant::NC_UL_NOTINT:
7017 error_at(e->location(), "non-integer %s argument to make",
7018 is_length ? "len" : "cap");
7019 return false;
7020 case Numeric_constant::NC_UL_NEGATIVE:
7021 error_at(e->location(), "negative %s argument to make",
7022 is_length ? "len" : "cap");
7023 return false;
7024 case Numeric_constant::NC_UL_BIG:
7025 // We don't want to give a compile-time error for a 64-bit
7026 // value on a 32-bit target.
7027 break;
7030 mpz_t val;
7031 if (!nc.to_int(&val))
7032 go_unreachable();
7033 int bits = mpz_sizeinbase(val, 2);
7034 mpz_clear(val);
7035 Type* int_type = Type::lookup_integer_type("int");
7036 if (bits >= int_type->integer_type()->bits())
7038 error_at(e->location(), "%s argument too large for make",
7039 is_length ? "len" : "cap");
7040 return false;
7043 return true;
7046 if (e->type()->integer_type() != NULL)
7047 return true;
7049 error_at(e->location(), "non-integer %s argument to make",
7050 is_length ? "len" : "cap");
7051 return false;
7054 // Return the type of the real or imag functions, given the type of
7055 // the argument. We need to map complex64 to float32 and complex128
7056 // to float64, so it has to be done by name. This returns NULL if it
7057 // can't figure out the type.
7059 Type*
7060 Builtin_call_expression::real_imag_type(Type* arg_type)
7062 if (arg_type == NULL || arg_type->is_abstract())
7063 return NULL;
7064 Named_type* nt = arg_type->named_type();
7065 if (nt == NULL)
7066 return NULL;
7067 while (nt->real_type()->named_type() != NULL)
7068 nt = nt->real_type()->named_type();
7069 if (nt->name() == "complex64")
7070 return Type::lookup_float_type("float32");
7071 else if (nt->name() == "complex128")
7072 return Type::lookup_float_type("float64");
7073 else
7074 return NULL;
7077 // Return the type of the complex function, given the type of one of the
7078 // argments. Like real_imag_type, we have to map by name.
7080 Type*
7081 Builtin_call_expression::complex_type(Type* arg_type)
7083 if (arg_type == NULL || arg_type->is_abstract())
7084 return NULL;
7085 Named_type* nt = arg_type->named_type();
7086 if (nt == NULL)
7087 return NULL;
7088 while (nt->real_type()->named_type() != NULL)
7089 nt = nt->real_type()->named_type();
7090 if (nt->name() == "float32")
7091 return Type::lookup_complex_type("complex64");
7092 else if (nt->name() == "float64")
7093 return Type::lookup_complex_type("complex128");
7094 else
7095 return NULL;
7098 // Return a single argument, or NULL if there isn't one.
7100 Expression*
7101 Builtin_call_expression::one_arg() const
7103 const Expression_list* args = this->args();
7104 if (args == NULL || args->size() != 1)
7105 return NULL;
7106 return args->front();
7109 // A traversal class which looks for a call or receive expression.
7111 class Find_call_expression : public Traverse
7113 public:
7114 Find_call_expression()
7115 : Traverse(traverse_expressions),
7116 found_(false)
7120 expression(Expression**);
7122 bool
7123 found()
7124 { return this->found_; }
7126 private:
7127 bool found_;
7131 Find_call_expression::expression(Expression** pexpr)
7133 if ((*pexpr)->call_expression() != NULL
7134 || (*pexpr)->receive_expression() != NULL)
7136 this->found_ = true;
7137 return TRAVERSE_EXIT;
7139 return TRAVERSE_CONTINUE;
7142 // Return whether this is constant: len of a string constant, or len
7143 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7144 // unsafe.Alignof.
7146 bool
7147 Builtin_call_expression::do_is_constant() const
7149 if (this->is_error_expression())
7150 return true;
7151 switch (this->code_)
7153 case BUILTIN_LEN:
7154 case BUILTIN_CAP:
7156 if (this->seen_)
7157 return false;
7159 Expression* arg = this->one_arg();
7160 if (arg == NULL)
7161 return false;
7162 Type* arg_type = arg->type();
7164 if (arg_type->points_to() != NULL
7165 && arg_type->points_to()->array_type() != NULL
7166 && !arg_type->points_to()->is_slice_type())
7167 arg_type = arg_type->points_to();
7169 // The len and cap functions are only constant if there are no
7170 // function calls or channel operations in the arguments.
7171 // Otherwise we have to make the call.
7172 if (!arg->is_constant())
7174 Find_call_expression find_call;
7175 Expression::traverse(&arg, &find_call);
7176 if (find_call.found())
7177 return false;
7180 if (arg_type->array_type() != NULL
7181 && arg_type->array_type()->length() != NULL)
7182 return true;
7184 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7186 this->seen_ = true;
7187 bool ret = arg->is_constant();
7188 this->seen_ = false;
7189 return ret;
7192 break;
7194 case BUILTIN_SIZEOF:
7195 case BUILTIN_ALIGNOF:
7196 return this->one_arg() != NULL;
7198 case BUILTIN_OFFSETOF:
7200 Expression* arg = this->one_arg();
7201 if (arg == NULL)
7202 return false;
7203 return arg->field_reference_expression() != NULL;
7206 case BUILTIN_COMPLEX:
7208 const Expression_list* args = this->args();
7209 if (args != NULL && args->size() == 2)
7210 return args->front()->is_constant() && args->back()->is_constant();
7212 break;
7214 case BUILTIN_REAL:
7215 case BUILTIN_IMAG:
7217 Expression* arg = this->one_arg();
7218 return arg != NULL && arg->is_constant();
7221 default:
7222 break;
7225 return false;
7228 // Return a numeric constant if possible.
7230 bool
7231 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7233 if (this->code_ == BUILTIN_LEN
7234 || this->code_ == BUILTIN_CAP)
7236 Expression* arg = this->one_arg();
7237 if (arg == NULL)
7238 return false;
7239 Type* arg_type = arg->type();
7241 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7243 std::string sval;
7244 if (arg->string_constant_value(&sval))
7246 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7247 sval.length());
7248 return true;
7252 if (arg_type->points_to() != NULL
7253 && arg_type->points_to()->array_type() != NULL
7254 && !arg_type->points_to()->is_slice_type())
7255 arg_type = arg_type->points_to();
7257 if (arg_type->array_type() != NULL
7258 && arg_type->array_type()->length() != NULL)
7260 if (this->seen_)
7261 return false;
7262 Expression* e = arg_type->array_type()->length();
7263 this->seen_ = true;
7264 bool r = e->numeric_constant_value(nc);
7265 this->seen_ = false;
7266 if (r)
7268 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7269 this->location()))
7270 r = false;
7272 return r;
7275 else if (this->code_ == BUILTIN_SIZEOF
7276 || this->code_ == BUILTIN_ALIGNOF)
7278 Expression* arg = this->one_arg();
7279 if (arg == NULL)
7280 return false;
7281 Type* arg_type = arg->type();
7282 if (arg_type->is_error())
7283 return false;
7284 if (arg_type->is_abstract())
7285 return false;
7286 if (this->seen_)
7287 return false;
7289 int64_t ret;
7290 if (this->code_ == BUILTIN_SIZEOF)
7292 this->seen_ = true;
7293 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7294 this->seen_ = false;
7295 if (!ok)
7296 return false;
7298 else if (this->code_ == BUILTIN_ALIGNOF)
7300 bool ok;
7301 this->seen_ = true;
7302 if (arg->field_reference_expression() == NULL)
7303 ok = arg_type->backend_type_align(this->gogo_, &ret);
7304 else
7306 // Calling unsafe.Alignof(s.f) returns the alignment of
7307 // the type of f when it is used as a field in a struct.
7308 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7310 this->seen_ = false;
7311 if (!ok)
7312 return false;
7314 else
7315 go_unreachable();
7317 mpz_t zval;
7318 set_mpz_from_int64(&zval, ret);
7319 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7320 mpz_clear(zval);
7321 return true;
7323 else if (this->code_ == BUILTIN_OFFSETOF)
7325 Expression* arg = this->one_arg();
7326 if (arg == NULL)
7327 return false;
7328 Field_reference_expression* farg = arg->field_reference_expression();
7329 if (farg == NULL)
7330 return false;
7331 if (this->seen_)
7332 return false;
7334 int64_t total_offset = 0;
7335 while (true)
7337 Expression* struct_expr = farg->expr();
7338 Type* st = struct_expr->type();
7339 if (st->struct_type() == NULL)
7340 return false;
7341 if (st->named_type() != NULL)
7342 st->named_type()->convert(this->gogo_);
7343 int64_t offset;
7344 this->seen_ = true;
7345 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7346 farg->field_index(),
7347 &offset);
7348 this->seen_ = false;
7349 if (!ok)
7350 return false;
7351 total_offset += offset;
7352 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7354 // Go up until we reach the original base.
7355 farg = struct_expr->field_reference_expression();
7356 continue;
7358 break;
7360 mpz_t zval;
7361 set_mpz_from_int64(&zval, total_offset);
7362 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7363 mpz_clear(zval);
7364 return true;
7366 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7368 Expression* arg = this->one_arg();
7369 if (arg == NULL)
7370 return false;
7372 Numeric_constant argnc;
7373 if (!arg->numeric_constant_value(&argnc))
7374 return false;
7376 mpc_t val;
7377 if (!argnc.to_complex(&val))
7378 return false;
7380 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7381 if (this->code_ == BUILTIN_REAL)
7382 nc->set_float(type, mpc_realref(val));
7383 else
7384 nc->set_float(type, mpc_imagref(val));
7385 mpc_clear(val);
7386 return true;
7388 else if (this->code_ == BUILTIN_COMPLEX)
7390 const Expression_list* args = this->args();
7391 if (args == NULL || args->size() != 2)
7392 return false;
7394 Numeric_constant rnc;
7395 if (!args->front()->numeric_constant_value(&rnc))
7396 return false;
7397 Numeric_constant inc;
7398 if (!args->back()->numeric_constant_value(&inc))
7399 return false;
7401 if (rnc.type() != NULL
7402 && !rnc.type()->is_abstract()
7403 && inc.type() != NULL
7404 && !inc.type()->is_abstract()
7405 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7406 return false;
7408 mpfr_t r;
7409 if (!rnc.to_float(&r))
7410 return false;
7411 mpfr_t i;
7412 if (!inc.to_float(&i))
7414 mpfr_clear(r);
7415 return false;
7418 Type* arg_type = rnc.type();
7419 if (arg_type == NULL || arg_type->is_abstract())
7420 arg_type = inc.type();
7422 mpc_t val;
7423 mpc_init2(val, mpc_precision);
7424 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
7425 mpfr_clear(r);
7426 mpfr_clear(i);
7428 Type* type = Builtin_call_expression::complex_type(arg_type);
7429 nc->set_complex(type, val);
7431 mpc_clear(val);
7433 return true;
7436 return false;
7439 // Give an error if we are discarding the value of an expression which
7440 // should not normally be discarded. We don't give an error for
7441 // discarding the value of an ordinary function call, but we do for
7442 // builtin functions, purely for consistency with the gc compiler.
7444 bool
7445 Builtin_call_expression::do_discarding_value()
7447 switch (this->code_)
7449 case BUILTIN_INVALID:
7450 default:
7451 go_unreachable();
7453 case BUILTIN_APPEND:
7454 case BUILTIN_CAP:
7455 case BUILTIN_COMPLEX:
7456 case BUILTIN_IMAG:
7457 case BUILTIN_LEN:
7458 case BUILTIN_MAKE:
7459 case BUILTIN_NEW:
7460 case BUILTIN_REAL:
7461 case BUILTIN_ALIGNOF:
7462 case BUILTIN_OFFSETOF:
7463 case BUILTIN_SIZEOF:
7464 this->unused_value_error();
7465 return false;
7467 case BUILTIN_CLOSE:
7468 case BUILTIN_COPY:
7469 case BUILTIN_DELETE:
7470 case BUILTIN_PANIC:
7471 case BUILTIN_PRINT:
7472 case BUILTIN_PRINTLN:
7473 case BUILTIN_RECOVER:
7474 return true;
7478 // Return the type.
7480 Type*
7481 Builtin_call_expression::do_type()
7483 switch (this->code_)
7485 case BUILTIN_INVALID:
7486 default:
7487 go_unreachable();
7489 case BUILTIN_NEW:
7490 case BUILTIN_MAKE:
7492 const Expression_list* args = this->args();
7493 if (args == NULL || args->empty())
7494 return Type::make_error_type();
7495 return Type::make_pointer_type(args->front()->type());
7498 case BUILTIN_CAP:
7499 case BUILTIN_COPY:
7500 case BUILTIN_LEN:
7501 return Type::lookup_integer_type("int");
7503 case BUILTIN_ALIGNOF:
7504 case BUILTIN_OFFSETOF:
7505 case BUILTIN_SIZEOF:
7506 return Type::lookup_integer_type("uintptr");
7508 case BUILTIN_CLOSE:
7509 case BUILTIN_DELETE:
7510 case BUILTIN_PANIC:
7511 case BUILTIN_PRINT:
7512 case BUILTIN_PRINTLN:
7513 return Type::make_void_type();
7515 case BUILTIN_RECOVER:
7516 return Type::make_empty_interface_type(Linemap::predeclared_location());
7518 case BUILTIN_APPEND:
7520 const Expression_list* args = this->args();
7521 if (args == NULL || args->empty())
7522 return Type::make_error_type();
7523 Type *ret = args->front()->type();
7524 if (!ret->is_slice_type())
7525 return Type::make_error_type();
7526 return ret;
7529 case BUILTIN_REAL:
7530 case BUILTIN_IMAG:
7532 Expression* arg = this->one_arg();
7533 if (arg == NULL)
7534 return Type::make_error_type();
7535 Type* t = arg->type();
7536 if (t->is_abstract())
7537 t = t->make_non_abstract_type();
7538 t = Builtin_call_expression::real_imag_type(t);
7539 if (t == NULL)
7540 t = Type::make_error_type();
7541 return t;
7544 case BUILTIN_COMPLEX:
7546 const Expression_list* args = this->args();
7547 if (args == NULL || args->size() != 2)
7548 return Type::make_error_type();
7549 Type* t = args->front()->type();
7550 if (t->is_abstract())
7552 t = args->back()->type();
7553 if (t->is_abstract())
7554 t = t->make_non_abstract_type();
7556 t = Builtin_call_expression::complex_type(t);
7557 if (t == NULL)
7558 t = Type::make_error_type();
7559 return t;
7564 // Determine the type.
7566 void
7567 Builtin_call_expression::do_determine_type(const Type_context* context)
7569 if (!this->determining_types())
7570 return;
7572 this->fn()->determine_type_no_context();
7574 const Expression_list* args = this->args();
7576 bool is_print;
7577 Type* arg_type = NULL;
7578 switch (this->code_)
7580 case BUILTIN_PRINT:
7581 case BUILTIN_PRINTLN:
7582 // Do not force a large integer constant to "int".
7583 is_print = true;
7584 break;
7586 case BUILTIN_REAL:
7587 case BUILTIN_IMAG:
7588 arg_type = Builtin_call_expression::complex_type(context->type);
7589 if (arg_type == NULL)
7590 arg_type = Type::lookup_complex_type("complex128");
7591 is_print = false;
7592 break;
7594 case BUILTIN_COMPLEX:
7596 // For the complex function the type of one operand can
7597 // determine the type of the other, as in a binary expression.
7598 arg_type = Builtin_call_expression::real_imag_type(context->type);
7599 if (arg_type == NULL)
7600 arg_type = Type::lookup_float_type("float64");
7601 if (args != NULL && args->size() == 2)
7603 Type* t1 = args->front()->type();
7604 Type* t2 = args->back()->type();
7605 if (!t1->is_abstract())
7606 arg_type = t1;
7607 else if (!t2->is_abstract())
7608 arg_type = t2;
7610 is_print = false;
7612 break;
7614 default:
7615 is_print = false;
7616 break;
7619 if (args != NULL)
7621 for (Expression_list::const_iterator pa = args->begin();
7622 pa != args->end();
7623 ++pa)
7625 Type_context subcontext;
7626 subcontext.type = arg_type;
7628 if (is_print)
7630 // We want to print large constants, we so can't just
7631 // use the appropriate nonabstract type. Use uint64 for
7632 // an integer if we know it is nonnegative, otherwise
7633 // use int64 for a integer, otherwise use float64 for a
7634 // float or complex128 for a complex.
7635 Type* want_type = NULL;
7636 Type* atype = (*pa)->type();
7637 if (atype->is_abstract())
7639 if (atype->integer_type() != NULL)
7641 Numeric_constant nc;
7642 if (this->numeric_constant_value(&nc))
7644 mpz_t val;
7645 if (nc.to_int(&val))
7647 if (mpz_sgn(val) >= 0)
7648 want_type = Type::lookup_integer_type("uint64");
7649 mpz_clear(val);
7652 if (want_type == NULL)
7653 want_type = Type::lookup_integer_type("int64");
7655 else if (atype->float_type() != NULL)
7656 want_type = Type::lookup_float_type("float64");
7657 else if (atype->complex_type() != NULL)
7658 want_type = Type::lookup_complex_type("complex128");
7659 else if (atype->is_abstract_string_type())
7660 want_type = Type::lookup_string_type();
7661 else if (atype->is_abstract_boolean_type())
7662 want_type = Type::lookup_bool_type();
7663 else
7664 go_unreachable();
7665 subcontext.type = want_type;
7669 (*pa)->determine_type(&subcontext);
7674 // If there is exactly one argument, return true. Otherwise give an
7675 // error message and return false.
7677 bool
7678 Builtin_call_expression::check_one_arg()
7680 const Expression_list* args = this->args();
7681 if (args == NULL || args->size() < 1)
7683 this->report_error(_("not enough arguments"));
7684 return false;
7686 else if (args->size() > 1)
7688 this->report_error(_("too many arguments"));
7689 return false;
7691 if (args->front()->is_error_expression()
7692 || args->front()->type()->is_error())
7694 this->set_is_error();
7695 return false;
7697 return true;
7700 // Check argument types for a builtin function.
7702 void
7703 Builtin_call_expression::do_check_types(Gogo*)
7705 if (this->is_error_expression())
7706 return;
7707 switch (this->code_)
7709 case BUILTIN_INVALID:
7710 case BUILTIN_NEW:
7711 case BUILTIN_MAKE:
7712 case BUILTIN_DELETE:
7713 return;
7715 case BUILTIN_LEN:
7716 case BUILTIN_CAP:
7718 // The single argument may be either a string or an array or a
7719 // map or a channel, or a pointer to a closed array.
7720 if (this->check_one_arg())
7722 Type* arg_type = this->one_arg()->type();
7723 if (arg_type->points_to() != NULL
7724 && arg_type->points_to()->array_type() != NULL
7725 && !arg_type->points_to()->is_slice_type())
7726 arg_type = arg_type->points_to();
7727 if (this->code_ == BUILTIN_CAP)
7729 if (!arg_type->is_error()
7730 && arg_type->array_type() == NULL
7731 && arg_type->channel_type() == NULL)
7732 this->report_error(_("argument must be array or slice "
7733 "or channel"));
7735 else
7737 if (!arg_type->is_error()
7738 && !arg_type->is_string_type()
7739 && arg_type->array_type() == NULL
7740 && arg_type->map_type() == NULL
7741 && arg_type->channel_type() == NULL)
7742 this->report_error(_("argument must be string or "
7743 "array or slice or map or channel"));
7747 break;
7749 case BUILTIN_PRINT:
7750 case BUILTIN_PRINTLN:
7752 const Expression_list* args = this->args();
7753 if (args == NULL)
7755 if (this->code_ == BUILTIN_PRINT)
7756 warning_at(this->location(), 0,
7757 "no arguments for builtin function %<%s%>",
7758 (this->code_ == BUILTIN_PRINT
7759 ? "print"
7760 : "println"));
7762 else
7764 for (Expression_list::const_iterator p = args->begin();
7765 p != args->end();
7766 ++p)
7768 Type* type = (*p)->type();
7769 if (type->is_error()
7770 || type->is_string_type()
7771 || type->integer_type() != NULL
7772 || type->float_type() != NULL
7773 || type->complex_type() != NULL
7774 || type->is_boolean_type()
7775 || type->points_to() != NULL
7776 || type->interface_type() != NULL
7777 || type->channel_type() != NULL
7778 || type->map_type() != NULL
7779 || type->function_type() != NULL
7780 || type->is_slice_type())
7782 else if ((*p)->is_type_expression())
7784 // If this is a type expression it's going to give
7785 // an error anyhow, so we don't need one here.
7787 else
7788 this->report_error(_("unsupported argument type to "
7789 "builtin function"));
7793 break;
7795 case BUILTIN_CLOSE:
7796 if (this->check_one_arg())
7798 if (this->one_arg()->type()->channel_type() == NULL)
7799 this->report_error(_("argument must be channel"));
7800 else if (!this->one_arg()->type()->channel_type()->may_send())
7801 this->report_error(_("cannot close receive-only channel"));
7803 break;
7805 case BUILTIN_PANIC:
7806 case BUILTIN_SIZEOF:
7807 case BUILTIN_ALIGNOF:
7808 this->check_one_arg();
7809 break;
7811 case BUILTIN_RECOVER:
7812 if (this->args() != NULL
7813 && !this->args()->empty()
7814 && !this->recover_arg_is_set_)
7815 this->report_error(_("too many arguments"));
7816 break;
7818 case BUILTIN_OFFSETOF:
7819 if (this->check_one_arg())
7821 Expression* arg = this->one_arg();
7822 if (arg->field_reference_expression() == NULL)
7823 this->report_error(_("argument must be a field reference"));
7825 break;
7827 case BUILTIN_COPY:
7829 const Expression_list* args = this->args();
7830 if (args == NULL || args->size() < 2)
7832 this->report_error(_("not enough arguments"));
7833 break;
7835 else if (args->size() > 2)
7837 this->report_error(_("too many arguments"));
7838 break;
7840 Type* arg1_type = args->front()->type();
7841 Type* arg2_type = args->back()->type();
7842 if (arg1_type->is_error() || arg2_type->is_error())
7844 this->set_is_error();
7845 break;
7848 Type* e1;
7849 if (arg1_type->is_slice_type())
7850 e1 = arg1_type->array_type()->element_type();
7851 else
7853 this->report_error(_("left argument must be a slice"));
7854 break;
7857 if (arg2_type->is_slice_type())
7859 Type* e2 = arg2_type->array_type()->element_type();
7860 if (!Type::are_identical(e1, e2, true, NULL))
7861 this->report_error(_("element types must be the same"));
7863 else if (arg2_type->is_string_type())
7865 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7866 this->report_error(_("first argument must be []byte"));
7868 else
7869 this->report_error(_("second argument must be slice or string"));
7871 break;
7873 case BUILTIN_APPEND:
7875 const Expression_list* args = this->args();
7876 if (args == NULL || args->size() < 2)
7878 this->report_error(_("not enough arguments"));
7879 break;
7881 if (args->size() > 2)
7883 this->report_error(_("too many arguments"));
7884 break;
7886 if (args->front()->type()->is_error()
7887 || args->back()->type()->is_error())
7889 this->set_is_error();
7890 break;
7893 Array_type* at = args->front()->type()->array_type();
7894 Type* e = at->element_type();
7896 // The language permits appending a string to a []byte, as a
7897 // special case.
7898 if (args->back()->type()->is_string_type())
7900 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7901 break;
7904 // The language says that the second argument must be
7905 // assignable to a slice of the element type of the first
7906 // argument. We already know the first argument is a slice
7907 // type.
7908 Type* arg2_type = Type::make_array_type(e, NULL);
7909 std::string reason;
7910 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7912 if (reason.empty())
7913 this->report_error(_("argument 2 has invalid type"));
7914 else
7916 error_at(this->location(), "argument 2 has invalid type (%s)",
7917 reason.c_str());
7918 this->set_is_error();
7921 break;
7924 case BUILTIN_REAL:
7925 case BUILTIN_IMAG:
7926 if (this->check_one_arg())
7928 if (this->one_arg()->type()->complex_type() == NULL)
7929 this->report_error(_("argument must have complex type"));
7931 break;
7933 case BUILTIN_COMPLEX:
7935 const Expression_list* args = this->args();
7936 if (args == NULL || args->size() < 2)
7937 this->report_error(_("not enough arguments"));
7938 else if (args->size() > 2)
7939 this->report_error(_("too many arguments"));
7940 else if (args->front()->is_error_expression()
7941 || args->front()->type()->is_error()
7942 || args->back()->is_error_expression()
7943 || args->back()->type()->is_error())
7944 this->set_is_error();
7945 else if (!Type::are_identical(args->front()->type(),
7946 args->back()->type(), true, NULL))
7947 this->report_error(_("complex arguments must have identical types"));
7948 else if (args->front()->type()->float_type() == NULL)
7949 this->report_error(_("complex arguments must have "
7950 "floating-point type"));
7952 break;
7954 default:
7955 go_unreachable();
7959 Expression*
7960 Builtin_call_expression::do_copy()
7962 Call_expression* bce =
7963 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
7964 (this->args() == NULL
7965 ? NULL
7966 : this->args()->copy()),
7967 this->is_varargs(),
7968 this->location());
7970 if (this->varargs_are_lowered())
7971 bce->set_varargs_are_lowered();
7972 return bce;
7975 // Return the backend representation for a builtin function.
7977 Bexpression*
7978 Builtin_call_expression::do_get_backend(Translate_context* context)
7980 Gogo* gogo = context->gogo();
7981 Location location = this->location();
7982 switch (this->code_)
7984 case BUILTIN_INVALID:
7985 case BUILTIN_NEW:
7986 case BUILTIN_MAKE:
7987 go_unreachable();
7989 case BUILTIN_LEN:
7990 case BUILTIN_CAP:
7992 const Expression_list* args = this->args();
7993 go_assert(args != NULL && args->size() == 1);
7994 Expression* arg = args->front();
7995 Type* arg_type = arg->type();
7997 if (this->seen_)
7999 go_assert(saw_errors());
8000 return context->backend()->error_expression();
8002 this->seen_ = true;
8003 this->seen_ = false;
8004 if (arg_type->points_to() != NULL)
8006 arg_type = arg_type->points_to();
8007 go_assert(arg_type->array_type() != NULL
8008 && !arg_type->is_slice_type());
8009 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8012 Type* int_type = Type::lookup_integer_type("int");
8013 Expression* val;
8014 if (this->code_ == BUILTIN_LEN)
8016 if (arg_type->is_string_type())
8017 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8018 location);
8019 else if (arg_type->array_type() != NULL)
8021 if (this->seen_)
8023 go_assert(saw_errors());
8024 return context->backend()->error_expression();
8026 this->seen_ = true;
8027 val = arg_type->array_type()->get_length(gogo, arg);
8028 this->seen_ = false;
8030 else if (arg_type->map_type() != NULL)
8031 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8032 else if (arg_type->channel_type() != NULL)
8033 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8034 else
8035 go_unreachable();
8037 else
8039 if (arg_type->array_type() != NULL)
8041 if (this->seen_)
8043 go_assert(saw_errors());
8044 return context->backend()->error_expression();
8046 this->seen_ = true;
8047 val = arg_type->array_type()->get_capacity(gogo, arg);
8048 this->seen_ = false;
8050 else if (arg_type->channel_type() != NULL)
8051 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8052 else
8053 go_unreachable();
8056 return Expression::make_cast(int_type, val,
8057 location)->get_backend(context);
8060 case BUILTIN_PRINT:
8061 case BUILTIN_PRINTLN:
8063 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8064 Expression* print_stmts = NULL;
8066 const Expression_list* call_args = this->args();
8067 if (call_args != NULL)
8069 for (Expression_list::const_iterator p = call_args->begin();
8070 p != call_args->end();
8071 ++p)
8073 if (is_ln && p != call_args->begin())
8075 Expression* print_space =
8076 Runtime::make_call(Runtime::PRINT_SPACE,
8077 this->location(), 0);
8079 print_stmts =
8080 Expression::make_compound(print_stmts, print_space,
8081 location);
8084 Expression* arg = *p;
8085 Type* type = arg->type();
8086 Runtime::Function code;
8087 if (type->is_string_type())
8088 code = Runtime::PRINT_STRING;
8089 else if (type->integer_type() != NULL
8090 && type->integer_type()->is_unsigned())
8092 Type* itype = Type::lookup_integer_type("uint64");
8093 arg = Expression::make_cast(itype, arg, location);
8094 code = Runtime::PRINT_UINT64;
8096 else if (type->integer_type() != NULL)
8098 Type* itype = Type::lookup_integer_type("int64");
8099 arg = Expression::make_cast(itype, arg, location);
8100 code = Runtime::PRINT_INT64;
8102 else if (type->float_type() != NULL)
8104 Type* dtype = Type::lookup_float_type("float64");
8105 arg = Expression::make_cast(dtype, arg, location);
8106 code = Runtime::PRINT_DOUBLE;
8108 else if (type->complex_type() != NULL)
8110 Type* ctype = Type::lookup_complex_type("complex128");
8111 arg = Expression::make_cast(ctype, arg, location);
8112 code = Runtime::PRINT_COMPLEX;
8114 else if (type->is_boolean_type())
8115 code = Runtime::PRINT_BOOL;
8116 else if (type->points_to() != NULL
8117 || type->channel_type() != NULL
8118 || type->map_type() != NULL
8119 || type->function_type() != NULL)
8121 arg = Expression::make_cast(type, arg, location);
8122 code = Runtime::PRINT_POINTER;
8124 else if (type->interface_type() != NULL)
8126 if (type->interface_type()->is_empty())
8127 code = Runtime::PRINT_EMPTY_INTERFACE;
8128 else
8129 code = Runtime::PRINT_INTERFACE;
8131 else if (type->is_slice_type())
8132 code = Runtime::PRINT_SLICE;
8133 else
8135 go_assert(saw_errors());
8136 return context->backend()->error_expression();
8139 Expression* call = Runtime::make_call(code, location, 1, arg);
8140 if (print_stmts == NULL)
8141 print_stmts = call;
8142 else
8143 print_stmts = Expression::make_compound(print_stmts, call,
8144 location);
8148 if (is_ln)
8150 Expression* print_nl =
8151 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8152 if (print_stmts == NULL)
8153 print_stmts = print_nl;
8154 else
8155 print_stmts = Expression::make_compound(print_stmts, print_nl,
8156 location);
8159 return print_stmts->get_backend(context);
8162 case BUILTIN_PANIC:
8164 const Expression_list* args = this->args();
8165 go_assert(args != NULL && args->size() == 1);
8166 Expression* arg = args->front();
8167 Type *empty =
8168 Type::make_empty_interface_type(Linemap::predeclared_location());
8169 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8171 Expression* panic =
8172 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8173 return panic->get_backend(context);
8176 case BUILTIN_RECOVER:
8178 // The argument is set when building recover thunks. It's a
8179 // boolean value which is true if we can recover a value now.
8180 const Expression_list* args = this->args();
8181 go_assert(args != NULL && args->size() == 1);
8182 Expression* arg = args->front();
8183 Type *empty =
8184 Type::make_empty_interface_type(Linemap::predeclared_location());
8186 Expression* nil = Expression::make_nil(location);
8187 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8189 // We need to handle a deferred call to recover specially,
8190 // because it changes whether it can recover a panic or not.
8191 // See test7 in test/recover1.go.
8192 Expression* recover = Runtime::make_call((this->is_deferred()
8193 ? Runtime::DEFERRED_RECOVER
8194 : Runtime::RECOVER),
8195 location, 0);
8196 Expression* cond =
8197 Expression::make_conditional(arg, recover, nil, location);
8198 return cond->get_backend(context);
8201 case BUILTIN_CLOSE:
8203 const Expression_list* args = this->args();
8204 go_assert(args != NULL && args->size() == 1);
8205 Expression* arg = args->front();
8206 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8207 1, arg);
8208 return close->get_backend(context);
8211 case BUILTIN_SIZEOF:
8212 case BUILTIN_OFFSETOF:
8213 case BUILTIN_ALIGNOF:
8215 Numeric_constant nc;
8216 unsigned long val;
8217 if (!this->numeric_constant_value(&nc)
8218 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8220 go_assert(saw_errors());
8221 return context->backend()->error_expression();
8223 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8224 mpz_t ival;
8225 nc.get_int(&ival);
8226 Expression* int_cst =
8227 Expression::make_integer_z(&ival, uintptr_type, location);
8228 mpz_clear(ival);
8229 return int_cst->get_backend(context);
8232 case BUILTIN_COPY:
8234 const Expression_list* args = this->args();
8235 go_assert(args != NULL && args->size() == 2);
8236 Expression* arg1 = args->front();
8237 Expression* arg2 = args->back();
8239 Type* arg1_type = arg1->type();
8240 Array_type* at = arg1_type->array_type();
8241 go_assert(arg1->is_variable());
8242 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8243 Expression* arg1_len = at->get_length(gogo, arg1);
8245 Type* arg2_type = arg2->type();
8246 go_assert(arg2->is_variable());
8247 Expression* arg2_val;
8248 Expression* arg2_len;
8249 if (arg2_type->is_slice_type())
8251 at = arg2_type->array_type();
8252 arg2_val = at->get_value_pointer(gogo, arg2);
8253 arg2_len = at->get_length(gogo, arg2);
8255 else
8257 go_assert(arg2->is_variable());
8258 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8259 location);
8260 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8261 location);
8263 Expression* cond =
8264 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8265 Expression* length =
8266 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8268 Type* element_type = at->element_type();
8269 Btype* element_btype = element_type->get_backend(gogo);
8270 int64_t element_size = gogo->backend()->type_size(element_btype);
8271 Expression* size_expr = Expression::make_integer_int64(element_size,
8272 length->type(),
8273 location);
8274 Expression* bytecount =
8275 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8276 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8277 arg1_val, arg2_val, bytecount);
8279 Expression* compound = Expression::make_compound(copy, length, location);
8280 return compound->get_backend(context);
8283 case BUILTIN_APPEND:
8285 const Expression_list* args = this->args();
8286 go_assert(args != NULL && args->size() == 2);
8287 Expression* arg1 = args->front();
8288 Expression* arg2 = args->back();
8290 Array_type* at = arg1->type()->array_type();
8291 Type* element_type = at->element_type()->forwarded();
8293 go_assert(arg2->is_variable());
8294 Expression* arg2_val;
8295 Expression* arg2_len;
8296 int64_t size;
8297 if (arg2->type()->is_string_type()
8298 && element_type->integer_type() != NULL
8299 && element_type->integer_type()->is_byte())
8301 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8302 location);
8303 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8304 location);
8305 size = 1;
8307 else
8309 arg2_val = at->get_value_pointer(gogo, arg2);
8310 arg2_len = at->get_length(gogo, arg2);
8311 Btype* element_btype = element_type->get_backend(gogo);
8312 size = gogo->backend()->type_size(element_btype);
8314 Expression* element_size =
8315 Expression::make_integer_int64(size, NULL, location);
8317 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8318 arg1, arg2_val, arg2_len,
8319 element_size);
8320 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8321 return append->get_backend(context);
8324 case BUILTIN_REAL:
8325 case BUILTIN_IMAG:
8327 const Expression_list* args = this->args();
8328 go_assert(args != NULL && args->size() == 1);
8330 Bexpression* ret;
8331 Bexpression* bcomplex = args->front()->get_backend(context);
8332 if (this->code_ == BUILTIN_REAL)
8333 ret = gogo->backend()->real_part_expression(bcomplex, location);
8334 else
8335 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8336 return ret;
8339 case BUILTIN_COMPLEX:
8341 const Expression_list* args = this->args();
8342 go_assert(args != NULL && args->size() == 2);
8343 Bexpression* breal = args->front()->get_backend(context);
8344 Bexpression* bimag = args->back()->get_backend(context);
8345 return gogo->backend()->complex_expression(breal, bimag, location);
8348 default:
8349 go_unreachable();
8353 // We have to support exporting a builtin call expression, because
8354 // code can set a constant to the result of a builtin expression.
8356 void
8357 Builtin_call_expression::do_export(Export* exp) const
8359 Numeric_constant nc;
8360 if (!this->numeric_constant_value(&nc))
8362 error_at(this->location(), "value is not constant");
8363 return;
8366 if (nc.is_int())
8368 mpz_t val;
8369 nc.get_int(&val);
8370 Integer_expression::export_integer(exp, val);
8371 mpz_clear(val);
8373 else if (nc.is_float())
8375 mpfr_t fval;
8376 nc.get_float(&fval);
8377 Float_expression::export_float(exp, fval);
8378 mpfr_clear(fval);
8380 else if (nc.is_complex())
8382 mpc_t cval;
8383 nc.get_complex(&cval);
8384 Complex_expression::export_complex(exp, cval);
8385 mpc_clear(cval);
8387 else
8388 go_unreachable();
8390 // A trailing space lets us reliably identify the end of the number.
8391 exp->write_c_string(" ");
8394 // Class Call_expression.
8396 // A Go function can be viewed in a couple of different ways. The
8397 // code of a Go function becomes a backend function with parameters
8398 // whose types are simply the backend representation of the Go types.
8399 // If there are multiple results, they are returned as a backend
8400 // struct.
8402 // However, when Go code refers to a function other than simply
8403 // calling it, the backend type of that function is actually a struct.
8404 // The first field of the struct points to the Go function code
8405 // (sometimes a wrapper as described below). The remaining fields
8406 // hold addresses of closed-over variables. This struct is called a
8407 // closure.
8409 // There are a few cases to consider.
8411 // A direct function call of a known function in package scope. In
8412 // this case there are no closed-over variables, and we know the name
8413 // of the function code. We can simply produce a backend call to the
8414 // function directly, and not worry about the closure.
8416 // A direct function call of a known function literal. In this case
8417 // we know the function code and we know the closure. We generate the
8418 // function code such that it expects an additional final argument of
8419 // the closure type. We pass the closure as the last argument, after
8420 // the other arguments.
8422 // An indirect function call. In this case we have a closure. We
8423 // load the pointer to the function code from the first field of the
8424 // closure. We pass the address of the closure as the last argument.
8426 // A call to a method of an interface. Type methods are always at
8427 // package scope, so we call the function directly, and don't worry
8428 // about the closure.
8430 // This means that for a function at package scope we have two cases.
8431 // One is the direct call, which has no closure. The other is the
8432 // indirect call, which does have a closure. We can't simply ignore
8433 // the closure, even though it is the last argument, because that will
8434 // fail on targets where the function pops its arguments. So when
8435 // generating a closure for a package-scope function we set the
8436 // function code pointer in the closure to point to a wrapper
8437 // function. This wrapper function accepts a final argument that
8438 // points to the closure, ignores it, and calls the real function as a
8439 // direct function call. This wrapper will normally be efficient, and
8440 // can often simply be a tail call to the real function.
8442 // We don't use GCC's static chain pointer because 1) we don't need
8443 // it; 2) GCC only permits using a static chain to call a known
8444 // function, so we can't use it for an indirect call anyhow. Since we
8445 // can't use it for an indirect call, we may as well not worry about
8446 // using it for a direct call either.
8448 // We pass the closure last rather than first because it means that
8449 // the function wrapper we put into a closure for a package-scope
8450 // function can normally just be a tail call to the real function.
8452 // For method expressions we generate a wrapper that loads the
8453 // receiver from the closure and then calls the method. This
8454 // unfortunately forces reshuffling the arguments, since there is a
8455 // new first argument, but we can't avoid reshuffling either for
8456 // method expressions or for indirect calls of package-scope
8457 // functions, and since the latter are more common we reshuffle for
8458 // method expressions.
8460 // Note that the Go code retains the Go types. The extra final
8461 // argument only appears when we convert to the backend
8462 // representation.
8464 // Traversal.
8467 Call_expression::do_traverse(Traverse* traverse)
8469 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8470 return TRAVERSE_EXIT;
8471 if (this->args_ != NULL)
8473 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8474 return TRAVERSE_EXIT;
8476 return TRAVERSE_CONTINUE;
8479 // Lower a call statement.
8481 Expression*
8482 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8483 Statement_inserter* inserter, int)
8485 Location loc = this->location();
8487 // A type cast can look like a function call.
8488 if (this->fn_->is_type_expression()
8489 && this->args_ != NULL
8490 && this->args_->size() == 1)
8491 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8492 loc);
8494 // Because do_type will return an error type and thus prevent future
8495 // errors, check for that case now to ensure that the error gets
8496 // reported.
8497 Function_type* fntype = this->get_function_type();
8498 if (fntype == NULL)
8500 if (!this->fn_->type()->is_error())
8501 this->report_error(_("expected function"));
8502 this->set_is_error();
8503 return this;
8506 // Handle an argument which is a call to a function which returns
8507 // multiple results.
8508 if (this->args_ != NULL
8509 && this->args_->size() == 1
8510 && this->args_->front()->call_expression() != NULL)
8512 size_t rc = this->args_->front()->call_expression()->result_count();
8513 if (rc > 1
8514 && ((fntype->parameters() != NULL
8515 && (fntype->parameters()->size() == rc
8516 || (fntype->is_varargs()
8517 && fntype->parameters()->size() - 1 <= rc)))
8518 || fntype->is_builtin()))
8520 Call_expression* call = this->args_->front()->call_expression();
8521 call->set_is_multi_value_arg();
8522 if (this->is_varargs_)
8524 // It is not clear which result of a multiple result call
8525 // the ellipsis operator should be applied to. If we unpack the
8526 // the call into its individual results here, the ellipsis will be
8527 // applied to the last result.
8528 error_at(call->location(),
8529 _("multiple-value argument in single-value context"));
8530 return Expression::make_error(call->location());
8533 Expression_list* args = new Expression_list;
8534 for (size_t i = 0; i < rc; ++i)
8535 args->push_back(Expression::make_call_result(call, i));
8536 // We can't return a new call expression here, because this
8537 // one may be referenced by Call_result expressions. We
8538 // also can't delete the old arguments, because we may still
8539 // traverse them somewhere up the call stack. FIXME.
8540 this->args_ = args;
8544 // Recognize a call to a builtin function.
8545 if (fntype->is_builtin())
8546 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8547 this->is_varargs_, loc);
8549 // If this call returns multiple results, create a temporary
8550 // variable for each result.
8551 size_t rc = this->result_count();
8552 if (rc > 1 && this->results_ == NULL)
8554 std::vector<Temporary_statement*>* temps =
8555 new std::vector<Temporary_statement*>;
8556 temps->reserve(rc);
8557 const Typed_identifier_list* results = fntype->results();
8558 for (Typed_identifier_list::const_iterator p = results->begin();
8559 p != results->end();
8560 ++p)
8562 Temporary_statement* temp = Statement::make_temporary(p->type(),
8563 NULL, loc);
8564 inserter->insert(temp);
8565 temps->push_back(temp);
8567 this->results_ = temps;
8570 // Handle a call to a varargs function by packaging up the extra
8571 // parameters.
8572 if (fntype->is_varargs())
8574 const Typed_identifier_list* parameters = fntype->parameters();
8575 go_assert(parameters != NULL && !parameters->empty());
8576 Type* varargs_type = parameters->back().type();
8577 this->lower_varargs(gogo, function, inserter, varargs_type,
8578 parameters->size());
8581 // If this is call to a method, call the method directly passing the
8582 // object as the first parameter.
8583 Bound_method_expression* bme = this->fn_->bound_method_expression();
8584 if (bme != NULL)
8586 Named_object* methodfn = bme->function();
8587 Expression* first_arg = bme->first_argument();
8589 // We always pass a pointer when calling a method.
8590 if (first_arg->type()->points_to() == NULL
8591 && !first_arg->type()->is_error())
8593 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8594 // We may need to create a temporary variable so that we can
8595 // take the address. We can't do that here because it will
8596 // mess up the order of evaluation.
8597 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8598 ue->set_create_temp();
8601 // If we are calling a method which was inherited from an
8602 // embedded struct, and the method did not get a stub, then the
8603 // first type may be wrong.
8604 Type* fatype = bme->first_argument_type();
8605 if (fatype != NULL)
8607 if (fatype->points_to() == NULL)
8608 fatype = Type::make_pointer_type(fatype);
8609 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8612 Expression_list* new_args = new Expression_list();
8613 new_args->push_back(first_arg);
8614 if (this->args_ != NULL)
8616 for (Expression_list::const_iterator p = this->args_->begin();
8617 p != this->args_->end();
8618 ++p)
8619 new_args->push_back(*p);
8622 // We have to change in place because this structure may be
8623 // referenced by Call_result_expressions. We can't delete the
8624 // old arguments, because we may be traversing them up in some
8625 // caller. FIXME.
8626 this->args_ = new_args;
8627 this->fn_ = Expression::make_func_reference(methodfn, NULL,
8628 bme->location());
8631 return this;
8634 // Lower a call to a varargs function. FUNCTION is the function in
8635 // which the call occurs--it's not the function we are calling.
8636 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8637 // PARAM_COUNT is the number of parameters of the function we are
8638 // calling; the last of these parameters will be the varargs
8639 // parameter.
8641 void
8642 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8643 Statement_inserter* inserter,
8644 Type* varargs_type, size_t param_count)
8646 if (this->varargs_are_lowered_)
8647 return;
8649 Location loc = this->location();
8651 go_assert(param_count > 0);
8652 go_assert(varargs_type->is_slice_type());
8654 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8655 if (arg_count < param_count - 1)
8657 // Not enough arguments; will be caught in check_types.
8658 return;
8661 Expression_list* old_args = this->args_;
8662 Expression_list* new_args = new Expression_list();
8663 bool push_empty_arg = false;
8664 if (old_args == NULL || old_args->empty())
8666 go_assert(param_count == 1);
8667 push_empty_arg = true;
8669 else
8671 Expression_list::const_iterator pa;
8672 int i = 1;
8673 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8675 if (static_cast<size_t>(i) == param_count)
8676 break;
8677 new_args->push_back(*pa);
8680 // We have reached the varargs parameter.
8682 bool issued_error = false;
8683 if (pa == old_args->end())
8684 push_empty_arg = true;
8685 else if (pa + 1 == old_args->end() && this->is_varargs_)
8686 new_args->push_back(*pa);
8687 else if (this->is_varargs_)
8689 if ((*pa)->type()->is_slice_type())
8690 this->report_error(_("too many arguments"));
8691 else
8693 error_at(this->location(),
8694 _("invalid use of %<...%> with non-slice"));
8695 this->set_is_error();
8697 return;
8699 else
8701 Type* element_type = varargs_type->array_type()->element_type();
8702 Expression_list* vals = new Expression_list;
8703 for (; pa != old_args->end(); ++pa, ++i)
8705 // Check types here so that we get a better message.
8706 Type* patype = (*pa)->type();
8707 Location paloc = (*pa)->location();
8708 if (!this->check_argument_type(i, element_type, patype,
8709 paloc, issued_error))
8710 continue;
8711 vals->push_back(*pa);
8713 Expression* val =
8714 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8715 gogo->lower_expression(function, inserter, &val);
8716 new_args->push_back(val);
8720 if (push_empty_arg)
8721 new_args->push_back(Expression::make_nil(loc));
8723 // We can't return a new call expression here, because this one may
8724 // be referenced by Call_result expressions. FIXME. We can't
8725 // delete OLD_ARGS because we may have both a Call_expression and a
8726 // Builtin_call_expression which refer to them. FIXME.
8727 this->args_ = new_args;
8728 this->varargs_are_lowered_ = true;
8731 // Flatten a call with multiple results into a temporary.
8733 Expression*
8734 Call_expression::do_flatten(Gogo* gogo, Named_object*,
8735 Statement_inserter* inserter)
8737 if (this->classification() == EXPRESSION_ERROR)
8738 return this;
8740 if (this->is_flattened_)
8741 return this;
8742 this->is_flattened_ = true;
8744 // Add temporary variables for all arguments that require type
8745 // conversion.
8746 Function_type* fntype = this->get_function_type();
8747 if (fntype == NULL)
8749 go_assert(saw_errors());
8750 return this;
8752 if (this->args_ != NULL && !this->args_->empty()
8753 && fntype->parameters() != NULL && !fntype->parameters()->empty())
8755 bool is_interface_method =
8756 this->fn_->interface_field_reference_expression() != NULL;
8758 Expression_list *args = new Expression_list();
8759 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
8760 Expression_list::const_iterator pa = this->args_->begin();
8761 if (!is_interface_method && fntype->is_method())
8763 // The receiver argument.
8764 args->push_back(*pa);
8765 ++pa;
8767 for (; pa != this->args_->end(); ++pa, ++pp)
8769 go_assert(pp != fntype->parameters()->end());
8770 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
8771 args->push_back(*pa);
8772 else
8774 Location loc = (*pa)->location();
8775 Expression* arg = *pa;
8776 if (!arg->is_variable())
8778 Temporary_statement *temp =
8779 Statement::make_temporary(NULL, arg, loc);
8780 inserter->insert(temp);
8781 arg = Expression::make_temporary_reference(temp, loc);
8783 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
8784 loc);
8785 args->push_back(arg);
8788 delete this->args_;
8789 this->args_ = args;
8792 size_t rc = this->result_count();
8793 if (rc > 1 && this->call_temp_ == NULL)
8795 Struct_field_list* sfl = new Struct_field_list();
8796 Function_type* fntype = this->get_function_type();
8797 const Typed_identifier_list* results = fntype->results();
8798 Location loc = this->location();
8800 int i = 0;
8801 char buf[10];
8802 for (Typed_identifier_list::const_iterator p = results->begin();
8803 p != results->end();
8804 ++p, ++i)
8806 snprintf(buf, sizeof buf, "res%d", i);
8807 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
8810 Struct_type* st = Type::make_struct_type(sfl, loc);
8811 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
8812 inserter->insert(this->call_temp_);
8815 return this;
8818 // Get the function type. This can return NULL in error cases.
8820 Function_type*
8821 Call_expression::get_function_type() const
8823 return this->fn_->type()->function_type();
8826 // Return the number of values which this call will return.
8828 size_t
8829 Call_expression::result_count() const
8831 const Function_type* fntype = this->get_function_type();
8832 if (fntype == NULL)
8833 return 0;
8834 if (fntype->results() == NULL)
8835 return 0;
8836 return fntype->results()->size();
8839 // Return the temporary which holds a result.
8841 Temporary_statement*
8842 Call_expression::result(size_t i) const
8844 if (this->results_ == NULL || this->results_->size() <= i)
8846 go_assert(saw_errors());
8847 return NULL;
8849 return (*this->results_)[i];
8852 // Set the number of results expected from a call expression.
8854 void
8855 Call_expression::set_expected_result_count(size_t count)
8857 go_assert(this->expected_result_count_ == 0);
8858 this->expected_result_count_ = count;
8861 // Return whether this is a call to the predeclared function recover.
8863 bool
8864 Call_expression::is_recover_call() const
8866 return this->do_is_recover_call();
8869 // Set the argument to the recover function.
8871 void
8872 Call_expression::set_recover_arg(Expression* arg)
8874 this->do_set_recover_arg(arg);
8877 // Virtual functions also implemented by Builtin_call_expression.
8879 bool
8880 Call_expression::do_is_recover_call() const
8882 return false;
8885 void
8886 Call_expression::do_set_recover_arg(Expression*)
8888 go_unreachable();
8891 // We have found an error with this call expression; return true if
8892 // we should report it.
8894 bool
8895 Call_expression::issue_error()
8897 if (this->issued_error_)
8898 return false;
8899 else
8901 this->issued_error_ = true;
8902 return true;
8906 // Get the type.
8908 Type*
8909 Call_expression::do_type()
8911 if (this->type_ != NULL)
8912 return this->type_;
8914 Type* ret;
8915 Function_type* fntype = this->get_function_type();
8916 if (fntype == NULL)
8917 return Type::make_error_type();
8919 const Typed_identifier_list* results = fntype->results();
8920 if (results == NULL)
8921 ret = Type::make_void_type();
8922 else if (results->size() == 1)
8923 ret = results->begin()->type();
8924 else
8925 ret = Type::make_call_multiple_result_type(this);
8927 this->type_ = ret;
8929 return this->type_;
8932 // Determine types for a call expression. We can use the function
8933 // parameter types to set the types of the arguments.
8935 void
8936 Call_expression::do_determine_type(const Type_context*)
8938 if (!this->determining_types())
8939 return;
8941 this->fn_->determine_type_no_context();
8942 Function_type* fntype = this->get_function_type();
8943 const Typed_identifier_list* parameters = NULL;
8944 if (fntype != NULL)
8945 parameters = fntype->parameters();
8946 if (this->args_ != NULL)
8948 Typed_identifier_list::const_iterator pt;
8949 if (parameters != NULL)
8950 pt = parameters->begin();
8951 bool first = true;
8952 for (Expression_list::const_iterator pa = this->args_->begin();
8953 pa != this->args_->end();
8954 ++pa)
8956 if (first)
8958 first = false;
8959 // If this is a method, the first argument is the
8960 // receiver.
8961 if (fntype != NULL && fntype->is_method())
8963 Type* rtype = fntype->receiver()->type();
8964 // The receiver is always passed as a pointer.
8965 if (rtype->points_to() == NULL)
8966 rtype = Type::make_pointer_type(rtype);
8967 Type_context subcontext(rtype, false);
8968 (*pa)->determine_type(&subcontext);
8969 continue;
8973 if (parameters != NULL && pt != parameters->end())
8975 Type_context subcontext(pt->type(), false);
8976 (*pa)->determine_type(&subcontext);
8977 ++pt;
8979 else
8980 (*pa)->determine_type_no_context();
8985 // Called when determining types for a Call_expression. Return true
8986 // if we should go ahead, false if they have already been determined.
8988 bool
8989 Call_expression::determining_types()
8991 if (this->types_are_determined_)
8992 return false;
8993 else
8995 this->types_are_determined_ = true;
8996 return true;
9000 // Check types for parameter I.
9002 bool
9003 Call_expression::check_argument_type(int i, const Type* parameter_type,
9004 const Type* argument_type,
9005 Location argument_location,
9006 bool issued_error)
9008 std::string reason;
9009 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9011 if (!issued_error)
9013 if (reason.empty())
9014 error_at(argument_location, "argument %d has incompatible type", i);
9015 else
9016 error_at(argument_location,
9017 "argument %d has incompatible type (%s)",
9018 i, reason.c_str());
9020 this->set_is_error();
9021 return false;
9023 return true;
9026 // Check types.
9028 void
9029 Call_expression::do_check_types(Gogo*)
9031 if (this->classification() == EXPRESSION_ERROR)
9032 return;
9034 Function_type* fntype = this->get_function_type();
9035 if (fntype == NULL)
9037 if (!this->fn_->type()->is_error())
9038 this->report_error(_("expected function"));
9039 return;
9042 if (this->expected_result_count_ != 0
9043 && this->expected_result_count_ != this->result_count())
9045 if (this->issue_error())
9046 this->report_error(_("function result count mismatch"));
9047 this->set_is_error();
9048 return;
9051 bool is_method = fntype->is_method();
9052 if (is_method)
9054 go_assert(this->args_ != NULL && !this->args_->empty());
9055 Type* rtype = fntype->receiver()->type();
9056 Expression* first_arg = this->args_->front();
9057 // We dereference the values since receivers are always passed
9058 // as pointers.
9059 std::string reason;
9060 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9061 &reason))
9063 if (reason.empty())
9064 this->report_error(_("incompatible type for receiver"));
9065 else
9067 error_at(this->location(),
9068 "incompatible type for receiver (%s)",
9069 reason.c_str());
9070 this->set_is_error();
9075 // Note that varargs was handled by the lower_varargs() method, so
9076 // we don't have to worry about it here unless something is wrong.
9077 if (this->is_varargs_ && !this->varargs_are_lowered_)
9079 if (!fntype->is_varargs())
9081 error_at(this->location(),
9082 _("invalid use of %<...%> calling non-variadic function"));
9083 this->set_is_error();
9084 return;
9088 const Typed_identifier_list* parameters = fntype->parameters();
9089 if (this->args_ == NULL)
9091 if (parameters != NULL && !parameters->empty())
9092 this->report_error(_("not enough arguments"));
9094 else if (parameters == NULL)
9096 if (!is_method || this->args_->size() > 1)
9097 this->report_error(_("too many arguments"));
9099 else if (this->args_->size() == 1
9100 && this->args_->front()->call_expression() != NULL
9101 && this->args_->front()->call_expression()->result_count() > 1)
9103 // This is F(G()) when G returns more than one result. If the
9104 // results can be matched to parameters, it would have been
9105 // lowered in do_lower. If we get here we know there is a
9106 // mismatch.
9107 if (this->args_->front()->call_expression()->result_count()
9108 < parameters->size())
9109 this->report_error(_("not enough arguments"));
9110 else
9111 this->report_error(_("too many arguments"));
9113 else
9115 int i = 0;
9116 Expression_list::const_iterator pa = this->args_->begin();
9117 if (is_method)
9118 ++pa;
9119 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9120 pt != parameters->end();
9121 ++pt, ++pa, ++i)
9123 if (pa == this->args_->end())
9125 this->report_error(_("not enough arguments"));
9126 return;
9128 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9129 (*pa)->location(), false);
9131 if (pa != this->args_->end())
9132 this->report_error(_("too many arguments"));
9136 Expression*
9137 Call_expression::do_copy()
9139 Call_expression* call =
9140 Expression::make_call(this->fn_->copy(),
9141 (this->args_ == NULL
9142 ? NULL
9143 : this->args_->copy()),
9144 this->is_varargs_, this->location());
9146 if (this->varargs_are_lowered_)
9147 call->set_varargs_are_lowered();
9148 return call;
9151 // Return whether we have to use a temporary variable to ensure that
9152 // we evaluate this call expression in order. If the call returns no
9153 // results then it will inevitably be executed last.
9155 bool
9156 Call_expression::do_must_eval_in_order() const
9158 return this->result_count() > 0;
9161 // Get the function and the first argument to use when calling an
9162 // interface method.
9164 Expression*
9165 Call_expression::interface_method_function(
9166 Interface_field_reference_expression* interface_method,
9167 Expression** first_arg_ptr)
9169 *first_arg_ptr = interface_method->get_underlying_object();
9170 return interface_method->get_function();
9173 // Build the call expression.
9175 Bexpression*
9176 Call_expression::do_get_backend(Translate_context* context)
9178 if (this->call_ != NULL)
9179 return this->call_;
9181 Function_type* fntype = this->get_function_type();
9182 if (fntype == NULL)
9183 return context->backend()->error_expression();
9185 if (this->fn_->is_error_expression())
9186 return context->backend()->error_expression();
9188 Gogo* gogo = context->gogo();
9189 Location location = this->location();
9191 Func_expression* func = this->fn_->func_expression();
9192 Interface_field_reference_expression* interface_method =
9193 this->fn_->interface_field_reference_expression();
9194 const bool has_closure = func != NULL && func->closure() != NULL;
9195 const bool is_interface_method = interface_method != NULL;
9197 bool has_closure_arg;
9198 if (has_closure)
9199 has_closure_arg = true;
9200 else if (func != NULL)
9201 has_closure_arg = false;
9202 else if (is_interface_method)
9203 has_closure_arg = false;
9204 else
9205 has_closure_arg = true;
9207 int nargs;
9208 std::vector<Bexpression*> fn_args;
9209 if (this->args_ == NULL || this->args_->empty())
9211 nargs = is_interface_method ? 1 : 0;
9212 if (nargs > 0)
9213 fn_args.resize(1);
9215 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9217 // Passing a receiver parameter.
9218 go_assert(!is_interface_method
9219 && fntype->is_method()
9220 && this->args_->size() == 1);
9221 nargs = 1;
9222 fn_args.resize(1);
9223 fn_args[0] = this->args_->front()->get_backend(context);
9225 else
9227 const Typed_identifier_list* params = fntype->parameters();
9229 nargs = this->args_->size();
9230 int i = is_interface_method ? 1 : 0;
9231 nargs += i;
9232 fn_args.resize(nargs);
9234 Typed_identifier_list::const_iterator pp = params->begin();
9235 Expression_list::const_iterator pe = this->args_->begin();
9236 if (!is_interface_method && fntype->is_method())
9238 fn_args[i] = (*pe)->get_backend(context);
9239 ++pe;
9240 ++i;
9242 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9244 go_assert(pp != params->end());
9245 Expression* arg =
9246 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9247 location);
9248 fn_args[i] = arg->get_backend(context);
9250 go_assert(pp == params->end());
9251 go_assert(i == nargs);
9254 Expression* fn;
9255 Expression* closure = NULL;
9256 if (func != NULL)
9258 Named_object* no = func->named_object();
9259 fn = Expression::make_func_code_reference(no, location);
9260 if (has_closure)
9261 closure = func->closure();
9263 else if (!is_interface_method)
9265 closure = this->fn_;
9267 // The backend representation of this function type is a pointer
9268 // to a struct whose first field is the actual function to call.
9269 Type* pfntype =
9270 Type::make_pointer_type(
9271 Type::make_pointer_type(Type::make_void_type()));
9272 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9273 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9275 else
9277 Expression* first_arg;
9278 fn = this->interface_method_function(interface_method, &first_arg);
9279 fn_args[0] = first_arg->get_backend(context);
9282 Bexpression* bclosure = NULL;
9283 if (has_closure_arg)
9284 bclosure = closure->get_backend(context);
9285 else
9286 go_assert(closure == NULL);
9288 Bexpression* bfn = fn->get_backend(context);
9290 // When not calling a named function directly, use a type conversion
9291 // in case the type of the function is a recursive type which refers
9292 // to itself. We don't do this for an interface method because 1)
9293 // an interface method never refers to itself, so we always have a
9294 // function type here; 2) we pass an extra first argument to an
9295 // interface method, so fntype is not correct.
9296 if (func == NULL && !is_interface_method)
9298 Btype* bft = fntype->get_backend_fntype(gogo);
9299 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9302 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args,
9303 bclosure, location);
9305 if (this->results_ != NULL)
9307 go_assert(this->call_temp_ != NULL);
9308 Expression* call_ref =
9309 Expression::make_temporary_reference(this->call_temp_, location);
9310 Bexpression* bcall_ref = call_ref->get_backend(context);
9311 Bstatement* assn_stmt =
9312 gogo->backend()->assignment_statement(bcall_ref, call, location);
9314 this->call_ = this->set_results(context, bcall_ref);
9316 Bexpression* set_and_call =
9317 gogo->backend()->compound_expression(assn_stmt, this->call_,
9318 location);
9319 return set_and_call;
9322 this->call_ = call;
9323 return this->call_;
9326 // Set the result variables if this call returns multiple results.
9328 Bexpression*
9329 Call_expression::set_results(Translate_context* context, Bexpression* call)
9331 Gogo* gogo = context->gogo();
9333 Bexpression* results = NULL;
9334 Location loc = this->location();
9336 size_t rc = this->result_count();
9337 for (size_t i = 0; i < rc; ++i)
9339 Temporary_statement* temp = this->result(i);
9340 if (temp == NULL)
9342 go_assert(saw_errors());
9343 return gogo->backend()->error_expression();
9345 Temporary_reference_expression* ref =
9346 Expression::make_temporary_reference(temp, loc);
9347 ref->set_is_lvalue();
9349 Bexpression* result_ref = ref->get_backend(context);
9350 Bexpression* call_result =
9351 gogo->backend()->struct_field_expression(call, i, loc);
9352 Bstatement* assn_stmt =
9353 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9355 Bexpression* result =
9356 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9358 if (results == NULL)
9359 results = result;
9360 else
9362 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9363 results =
9364 gogo->backend()->compound_expression(expr_stmt, results, loc);
9367 return results;
9370 // Dump ast representation for a call expressin.
9372 void
9373 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9375 this->fn_->dump_expression(ast_dump_context);
9376 ast_dump_context->ostream() << "(";
9377 if (args_ != NULL)
9378 ast_dump_context->dump_expression_list(this->args_);
9380 ast_dump_context->ostream() << ") ";
9383 // Make a call expression.
9385 Call_expression*
9386 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9387 Location location)
9389 return new Call_expression(fn, args, is_varargs, location);
9392 // Class Call_result_expression.
9394 // Traverse a call result.
9397 Call_result_expression::do_traverse(Traverse* traverse)
9399 if (traverse->remember_expression(this->call_))
9401 // We have already traversed the call expression.
9402 return TRAVERSE_CONTINUE;
9404 return Expression::traverse(&this->call_, traverse);
9407 // Get the type.
9409 Type*
9410 Call_result_expression::do_type()
9412 if (this->classification() == EXPRESSION_ERROR)
9413 return Type::make_error_type();
9415 // THIS->CALL_ can be replaced with a temporary reference due to
9416 // Call_expression::do_must_eval_in_order when there is an error.
9417 Call_expression* ce = this->call_->call_expression();
9418 if (ce == NULL)
9420 this->set_is_error();
9421 return Type::make_error_type();
9423 Function_type* fntype = ce->get_function_type();
9424 if (fntype == NULL)
9426 if (ce->issue_error())
9428 if (!ce->fn()->type()->is_error())
9429 this->report_error(_("expected function"));
9431 this->set_is_error();
9432 return Type::make_error_type();
9434 const Typed_identifier_list* results = fntype->results();
9435 if (results == NULL || results->size() < 2)
9437 if (ce->issue_error())
9438 this->report_error(_("number of results does not match "
9439 "number of values"));
9440 return Type::make_error_type();
9442 Typed_identifier_list::const_iterator pr = results->begin();
9443 for (unsigned int i = 0; i < this->index_; ++i)
9445 if (pr == results->end())
9446 break;
9447 ++pr;
9449 if (pr == results->end())
9451 if (ce->issue_error())
9452 this->report_error(_("number of results does not match "
9453 "number of values"));
9454 return Type::make_error_type();
9456 return pr->type();
9459 // Check the type. Just make sure that we trigger the warning in
9460 // do_type.
9462 void
9463 Call_result_expression::do_check_types(Gogo*)
9465 this->type();
9468 // Determine the type. We have nothing to do here, but the 0 result
9469 // needs to pass down to the caller.
9471 void
9472 Call_result_expression::do_determine_type(const Type_context*)
9474 this->call_->determine_type_no_context();
9477 // Return the backend representation. We just refer to the temporary set by the
9478 // call expression. We don't do this at lowering time because it makes it
9479 // hard to evaluate the call at the right time.
9481 Bexpression*
9482 Call_result_expression::do_get_backend(Translate_context* context)
9484 Call_expression* ce = this->call_->call_expression();
9485 if (ce == NULL)
9487 go_assert(this->call_->is_error_expression());
9488 return context->backend()->error_expression();
9490 Temporary_statement* ts = ce->result(this->index_);
9491 if (ts == NULL)
9493 go_assert(saw_errors());
9494 return context->backend()->error_expression();
9496 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9497 return ref->get_backend(context);
9500 // Dump ast representation for a call result expression.
9502 void
9503 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9504 const
9506 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9507 // (struct) and the fields are referenced instead.
9508 ast_dump_context->ostream() << this->index_ << "@(";
9509 ast_dump_context->dump_expression(this->call_);
9510 ast_dump_context->ostream() << ")";
9513 // Make a reference to a single result of a call which returns
9514 // multiple results.
9516 Expression*
9517 Expression::make_call_result(Call_expression* call, unsigned int index)
9519 return new Call_result_expression(call, index);
9522 // Class Index_expression.
9524 // Traversal.
9527 Index_expression::do_traverse(Traverse* traverse)
9529 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9530 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9531 || (this->end_ != NULL
9532 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9533 || (this->cap_ != NULL
9534 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9535 return TRAVERSE_EXIT;
9536 return TRAVERSE_CONTINUE;
9539 // Lower an index expression. This converts the generic index
9540 // expression into an array index, a string index, or a map index.
9542 Expression*
9543 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9545 Location location = this->location();
9546 Expression* left = this->left_;
9547 Expression* start = this->start_;
9548 Expression* end = this->end_;
9549 Expression* cap = this->cap_;
9551 Type* type = left->type();
9552 if (type->is_error())
9554 go_assert(saw_errors());
9555 return Expression::make_error(location);
9557 else if (left->is_type_expression())
9559 error_at(location, "attempt to index type expression");
9560 return Expression::make_error(location);
9562 else if (type->array_type() != NULL)
9563 return Expression::make_array_index(left, start, end, cap, location);
9564 else if (type->points_to() != NULL
9565 && type->points_to()->array_type() != NULL
9566 && !type->points_to()->is_slice_type())
9568 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9569 location);
9571 // For an ordinary index into the array, the pointer will be
9572 // dereferenced. For a slice it will not--the resulting slice
9573 // will simply reuse the pointer, which is incorrect if that
9574 // pointer is nil.
9575 if (end != NULL || cap != NULL)
9576 deref->issue_nil_check();
9578 return Expression::make_array_index(deref, start, end, cap, location);
9580 else if (type->is_string_type())
9582 if (cap != NULL)
9584 error_at(location, "invalid 3-index slice of string");
9585 return Expression::make_error(location);
9587 return Expression::make_string_index(left, start, end, location);
9589 else if (type->map_type() != NULL)
9591 if (end != NULL || cap != NULL)
9593 error_at(location, "invalid slice of map");
9594 return Expression::make_error(location);
9596 Map_index_expression* ret = Expression::make_map_index(left, start,
9597 location);
9598 if (this->is_lvalue_)
9599 ret->set_is_lvalue();
9600 return ret;
9602 else
9604 error_at(location,
9605 "attempt to index object which is not array, string, or map");
9606 return Expression::make_error(location);
9610 // Write an indexed expression
9611 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9613 void
9614 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9615 const Expression* expr,
9616 const Expression* start,
9617 const Expression* end,
9618 const Expression* cap)
9620 expr->dump_expression(ast_dump_context);
9621 ast_dump_context->ostream() << "[";
9622 start->dump_expression(ast_dump_context);
9623 if (end != NULL)
9625 ast_dump_context->ostream() << ":";
9626 end->dump_expression(ast_dump_context);
9628 if (cap != NULL)
9630 ast_dump_context->ostream() << ":";
9631 cap->dump_expression(ast_dump_context);
9633 ast_dump_context->ostream() << "]";
9636 // Dump ast representation for an index expression.
9638 void
9639 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9640 const
9642 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9643 this->start_, this->end_, this->cap_);
9646 // Make an index expression.
9648 Expression*
9649 Expression::make_index(Expression* left, Expression* start, Expression* end,
9650 Expression* cap, Location location)
9652 return new Index_expression(left, start, end, cap, location);
9655 // Class Array_index_expression.
9657 // Array index traversal.
9660 Array_index_expression::do_traverse(Traverse* traverse)
9662 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9663 return TRAVERSE_EXIT;
9664 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9665 return TRAVERSE_EXIT;
9666 if (this->end_ != NULL)
9668 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9669 return TRAVERSE_EXIT;
9671 if (this->cap_ != NULL)
9673 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
9674 return TRAVERSE_EXIT;
9676 return TRAVERSE_CONTINUE;
9679 // Return the type of an array index.
9681 Type*
9682 Array_index_expression::do_type()
9684 if (this->type_ == NULL)
9686 Array_type* type = this->array_->type()->array_type();
9687 if (type == NULL)
9688 this->type_ = Type::make_error_type();
9689 else if (this->end_ == NULL)
9690 this->type_ = type->element_type();
9691 else if (type->is_slice_type())
9693 // A slice of a slice has the same type as the original
9694 // slice.
9695 this->type_ = this->array_->type()->deref();
9697 else
9699 // A slice of an array is a slice.
9700 this->type_ = Type::make_array_type(type->element_type(), NULL);
9703 return this->type_;
9706 // Set the type of an array index.
9708 void
9709 Array_index_expression::do_determine_type(const Type_context*)
9711 this->array_->determine_type_no_context();
9712 this->start_->determine_type_no_context();
9713 if (this->end_ != NULL)
9714 this->end_->determine_type_no_context();
9715 if (this->cap_ != NULL)
9716 this->cap_->determine_type_no_context();
9719 // Check types of an array index.
9721 void
9722 Array_index_expression::do_check_types(Gogo*)
9724 Numeric_constant nc;
9725 unsigned long v;
9726 if (this->start_->type()->integer_type() == NULL
9727 && !this->start_->type()->is_error()
9728 && (!this->start_->numeric_constant_value(&nc)
9729 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9730 this->report_error(_("index must be integer"));
9731 if (this->end_ != NULL
9732 && this->end_->type()->integer_type() == NULL
9733 && !this->end_->type()->is_error()
9734 && !this->end_->is_nil_expression()
9735 && !this->end_->is_error_expression()
9736 && (!this->end_->numeric_constant_value(&nc)
9737 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9738 this->report_error(_("slice end must be integer"));
9739 if (this->cap_ != NULL
9740 && this->cap_->type()->integer_type() == NULL
9741 && !this->cap_->type()->is_error()
9742 && !this->cap_->is_nil_expression()
9743 && !this->cap_->is_error_expression()
9744 && (!this->cap_->numeric_constant_value(&nc)
9745 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9746 this->report_error(_("slice capacity must be integer"));
9748 Array_type* array_type = this->array_->type()->array_type();
9749 if (array_type == NULL)
9751 go_assert(this->array_->type()->is_error());
9752 return;
9755 unsigned int int_bits =
9756 Type::lookup_integer_type("int")->integer_type()->bits();
9758 Numeric_constant lvalnc;
9759 mpz_t lval;
9760 bool lval_valid = (array_type->length() != NULL
9761 && array_type->length()->numeric_constant_value(&lvalnc)
9762 && lvalnc.to_int(&lval));
9763 Numeric_constant inc;
9764 mpz_t ival;
9765 bool ival_valid = false;
9766 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9768 ival_valid = true;
9769 if (mpz_sgn(ival) < 0
9770 || mpz_sizeinbase(ival, 2) >= int_bits
9771 || (lval_valid
9772 && (this->end_ == NULL
9773 ? mpz_cmp(ival, lval) >= 0
9774 : mpz_cmp(ival, lval) > 0)))
9776 error_at(this->start_->location(), "array index out of bounds");
9777 this->set_is_error();
9780 if (this->end_ != NULL && !this->end_->is_nil_expression())
9782 Numeric_constant enc;
9783 mpz_t eval;
9784 bool eval_valid = false;
9785 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9787 eval_valid = true;
9788 if (mpz_sgn(eval) < 0
9789 || mpz_sizeinbase(eval, 2) >= int_bits
9790 || (lval_valid && mpz_cmp(eval, lval) > 0))
9792 error_at(this->end_->location(), "array index out of bounds");
9793 this->set_is_error();
9795 else if (ival_valid && mpz_cmp(ival, eval) > 0)
9796 this->report_error(_("inverted slice range"));
9799 Numeric_constant cnc;
9800 mpz_t cval;
9801 if (this->cap_ != NULL
9802 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
9804 if (mpz_sgn(cval) < 0
9805 || mpz_sizeinbase(cval, 2) >= int_bits
9806 || (lval_valid && mpz_cmp(cval, lval) > 0))
9808 error_at(this->cap_->location(), "array index out of bounds");
9809 this->set_is_error();
9811 else if (ival_valid && mpz_cmp(ival, cval) > 0)
9813 error_at(this->cap_->location(),
9814 "invalid slice index: capacity less than start");
9815 this->set_is_error();
9817 else if (eval_valid && mpz_cmp(eval, cval) > 0)
9819 error_at(this->cap_->location(),
9820 "invalid slice index: capacity less than length");
9821 this->set_is_error();
9823 mpz_clear(cval);
9826 if (eval_valid)
9827 mpz_clear(eval);
9829 if (ival_valid)
9830 mpz_clear(ival);
9831 if (lval_valid)
9832 mpz_clear(lval);
9834 // A slice of an array requires an addressable array. A slice of a
9835 // slice is always possible.
9836 if (this->end_ != NULL && !array_type->is_slice_type())
9838 if (!this->array_->is_addressable())
9839 this->report_error(_("slice of unaddressable value"));
9840 else
9841 this->array_->address_taken(true);
9845 // Flatten array indexing by using temporary variables for slices and indexes.
9847 Expression*
9848 Array_index_expression::do_flatten(Gogo*, Named_object*,
9849 Statement_inserter* inserter)
9851 Location loc = this->location();
9852 Temporary_statement* temp;
9853 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
9855 temp = Statement::make_temporary(NULL, this->array_, loc);
9856 inserter->insert(temp);
9857 this->array_ = Expression::make_temporary_reference(temp, loc);
9859 if (!this->start_->is_variable())
9861 temp = Statement::make_temporary(NULL, this->start_, loc);
9862 inserter->insert(temp);
9863 this->start_ = Expression::make_temporary_reference(temp, loc);
9865 if (this->end_ != NULL
9866 && !this->end_->is_nil_expression()
9867 && !this->end_->is_variable())
9869 temp = Statement::make_temporary(NULL, this->end_, loc);
9870 inserter->insert(temp);
9871 this->end_ = Expression::make_temporary_reference(temp, loc);
9873 if (this->cap_ != NULL && !this->cap_->is_variable())
9875 temp = Statement::make_temporary(NULL, this->cap_, loc);
9876 inserter->insert(temp);
9877 this->cap_ = Expression::make_temporary_reference(temp, loc);
9880 return this;
9883 // Return whether this expression is addressable.
9885 bool
9886 Array_index_expression::do_is_addressable() const
9888 // A slice expression is not addressable.
9889 if (this->end_ != NULL)
9890 return false;
9892 // An index into a slice is addressable.
9893 if (this->array_->type()->is_slice_type())
9894 return true;
9896 // An index into an array is addressable if the array is
9897 // addressable.
9898 return this->array_->is_addressable();
9901 // Get the backend representation for an array index.
9903 Bexpression*
9904 Array_index_expression::do_get_backend(Translate_context* context)
9906 Array_type* array_type = this->array_->type()->array_type();
9907 if (array_type == NULL)
9909 go_assert(this->array_->type()->is_error());
9910 return context->backend()->error_expression();
9912 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
9914 Location loc = this->location();
9915 Gogo* gogo = context->gogo();
9917 Type* int_type = Type::lookup_integer_type("int");
9918 Btype* int_btype = int_type->get_backend(gogo);
9920 // We need to convert the length and capacity to the Go "int" type here
9921 // because the length of a fixed-length array could be of type "uintptr"
9922 // and gimple disallows binary operations between "uintptr" and other
9923 // integer types. FIXME.
9924 Bexpression* length = NULL;
9925 if (this->end_ == NULL || this->end_->is_nil_expression())
9927 Expression* len = array_type->get_length(gogo, this->array_);
9928 length = len->get_backend(context);
9929 length = gogo->backend()->convert_expression(int_btype, length, loc);
9932 Bexpression* capacity = NULL;
9933 if (this->end_ != NULL)
9935 Expression* cap = array_type->get_capacity(gogo, this->array_);
9936 capacity = cap->get_backend(context);
9937 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
9940 Bexpression* cap_arg = capacity;
9941 if (this->cap_ != NULL)
9943 cap_arg = this->cap_->get_backend(context);
9944 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
9947 if (length == NULL)
9948 length = cap_arg;
9950 int code = (array_type->length() != NULL
9951 ? (this->end_ == NULL
9952 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
9953 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
9954 : (this->end_ == NULL
9955 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
9956 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
9957 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
9959 if (this->start_->type()->integer_type() == NULL
9960 && !Type::are_convertible(int_type, this->start_->type(), NULL))
9962 go_assert(saw_errors());
9963 return context->backend()->error_expression();
9966 Bexpression* bad_index =
9967 Expression::check_bounds(this->start_, loc)->get_backend(context);
9969 Bexpression* start = this->start_->get_backend(context);
9970 start = gogo->backend()->convert_expression(int_btype, start, loc);
9971 Bexpression* start_too_large =
9972 gogo->backend()->binary_expression((this->end_ == NULL
9973 ? OPERATOR_GE
9974 : OPERATOR_GT),
9975 start,
9976 (this->end_ == NULL
9977 ? length
9978 : capacity),
9979 loc);
9980 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
9981 bad_index, loc);
9983 if (this->end_ == NULL)
9985 // Simple array indexing. This has to return an l-value, so
9986 // wrap the index check into START.
9987 start =
9988 gogo->backend()->conditional_expression(int_btype, bad_index,
9989 crash, start, loc);
9991 Bexpression* ret;
9992 if (array_type->length() != NULL)
9994 Bexpression* array = this->array_->get_backend(context);
9995 ret = gogo->backend()->array_index_expression(array, start, loc);
9997 else
9999 // Slice.
10000 Expression* valptr =
10001 array_type->get_value_pointer(gogo, this->array_);
10002 Bexpression* ptr = valptr->get_backend(context);
10003 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10005 Type* ele_type = this->array_->type()->array_type()->element_type();
10006 Btype* ele_btype = ele_type->get_backend(gogo);
10007 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
10009 return ret;
10012 // Array slice.
10014 if (this->cap_ != NULL)
10016 Bexpression* bounds_bcheck =
10017 Expression::check_bounds(this->cap_, loc)->get_backend(context);
10018 bad_index =
10019 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10020 bad_index, loc);
10021 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10023 Bexpression* cap_too_small =
10024 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10025 Bexpression* cap_too_large =
10026 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10027 Bexpression* bad_cap =
10028 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10029 cap_too_large, loc);
10030 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10031 bad_index, loc);
10034 Bexpression* end;
10035 if (this->end_->is_nil_expression())
10036 end = length;
10037 else
10039 Bexpression* bounds_bcheck =
10040 Expression::check_bounds(this->end_, loc)->get_backend(context);
10042 bad_index =
10043 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10044 bad_index, loc);
10046 end = this->end_->get_backend(context);
10047 end = gogo->backend()->convert_expression(int_btype, end, loc);
10048 Bexpression* end_too_small =
10049 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10050 Bexpression* end_too_large =
10051 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10052 Bexpression* bad_end =
10053 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10054 end_too_large, loc);
10055 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10056 bad_index, loc);
10059 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10060 Bexpression* val = valptr->get_backend(context);
10061 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10063 Bexpression* result_length =
10064 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10066 Bexpression* result_capacity =
10067 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10069 Btype* struct_btype = this->type()->get_backend(gogo);
10070 std::vector<Bexpression*> init;
10071 init.push_back(val);
10072 init.push_back(result_length);
10073 init.push_back(result_capacity);
10075 Bexpression* ctor =
10076 gogo->backend()->constructor_expression(struct_btype, init, loc);
10077 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10078 crash, ctor, loc);
10081 // Dump ast representation for an array index expression.
10083 void
10084 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10085 const
10087 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10088 this->start_, this->end_, this->cap_);
10091 // Make an array index expression. END and CAP may be NULL.
10093 Expression*
10094 Expression::make_array_index(Expression* array, Expression* start,
10095 Expression* end, Expression* cap,
10096 Location location)
10098 return new Array_index_expression(array, start, end, cap, location);
10101 // A string index. This is used for both indexing and slicing.
10103 class String_index_expression : public Expression
10105 public:
10106 String_index_expression(Expression* string, Expression* start,
10107 Expression* end, Location location)
10108 : Expression(EXPRESSION_STRING_INDEX, location),
10109 string_(string), start_(start), end_(end)
10112 protected:
10114 do_traverse(Traverse*);
10116 Expression*
10117 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10119 Type*
10120 do_type();
10122 void
10123 do_determine_type(const Type_context*);
10125 void
10126 do_check_types(Gogo*);
10128 Expression*
10129 do_copy()
10131 return Expression::make_string_index(this->string_->copy(),
10132 this->start_->copy(),
10133 (this->end_ == NULL
10134 ? NULL
10135 : this->end_->copy()),
10136 this->location());
10139 bool
10140 do_must_eval_subexpressions_in_order(int* skip) const
10142 *skip = 1;
10143 return true;
10146 Bexpression*
10147 do_get_backend(Translate_context*);
10149 void
10150 do_dump_expression(Ast_dump_context*) const;
10152 private:
10153 // The string we are getting a value from.
10154 Expression* string_;
10155 // The start or only index.
10156 Expression* start_;
10157 // The end index of a slice. This may be NULL for a single index,
10158 // or it may be a nil expression for the length of the string.
10159 Expression* end_;
10162 // String index traversal.
10165 String_index_expression::do_traverse(Traverse* traverse)
10167 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10168 return TRAVERSE_EXIT;
10169 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10170 return TRAVERSE_EXIT;
10171 if (this->end_ != NULL)
10173 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10174 return TRAVERSE_EXIT;
10176 return TRAVERSE_CONTINUE;
10179 Expression*
10180 String_index_expression::do_flatten(Gogo*, Named_object*,
10181 Statement_inserter* inserter)
10183 Temporary_statement* temp;
10184 Location loc = this->location();
10185 if (!this->string_->is_variable())
10187 temp = Statement::make_temporary(NULL, this->string_, loc);
10188 inserter->insert(temp);
10189 this->string_ = Expression::make_temporary_reference(temp, loc);
10191 if (!this->start_->is_variable())
10193 temp = Statement::make_temporary(NULL, this->start_, loc);
10194 inserter->insert(temp);
10195 this->start_ = Expression::make_temporary_reference(temp, loc);
10197 if (this->end_ != NULL
10198 && !this->end_->is_nil_expression()
10199 && !this->end_->is_variable())
10201 temp = Statement::make_temporary(NULL, this->end_, loc);
10202 inserter->insert(temp);
10203 this->end_ = Expression::make_temporary_reference(temp, loc);
10206 return this;
10209 // Return the type of a string index.
10211 Type*
10212 String_index_expression::do_type()
10214 if (this->end_ == NULL)
10215 return Type::lookup_integer_type("uint8");
10216 else
10217 return this->string_->type();
10220 // Determine the type of a string index.
10222 void
10223 String_index_expression::do_determine_type(const Type_context*)
10225 this->string_->determine_type_no_context();
10226 this->start_->determine_type_no_context();
10227 if (this->end_ != NULL)
10228 this->end_->determine_type_no_context();
10231 // Check types of a string index.
10233 void
10234 String_index_expression::do_check_types(Gogo*)
10236 Numeric_constant nc;
10237 unsigned long v;
10238 if (this->start_->type()->integer_type() == NULL
10239 && !this->start_->type()->is_error()
10240 && (!this->start_->numeric_constant_value(&nc)
10241 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10242 this->report_error(_("index must be integer"));
10243 if (this->end_ != NULL
10244 && this->end_->type()->integer_type() == NULL
10245 && !this->end_->type()->is_error()
10246 && !this->end_->is_nil_expression()
10247 && !this->end_->is_error_expression()
10248 && (!this->end_->numeric_constant_value(&nc)
10249 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10250 this->report_error(_("slice end must be integer"));
10252 std::string sval;
10253 bool sval_valid = this->string_->string_constant_value(&sval);
10255 Numeric_constant inc;
10256 mpz_t ival;
10257 bool ival_valid = false;
10258 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10260 ival_valid = true;
10261 if (mpz_sgn(ival) < 0
10262 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10264 error_at(this->start_->location(), "string index out of bounds");
10265 this->set_is_error();
10268 if (this->end_ != NULL && !this->end_->is_nil_expression())
10270 Numeric_constant enc;
10271 mpz_t eval;
10272 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10274 if (mpz_sgn(eval) < 0
10275 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10277 error_at(this->end_->location(), "string index out of bounds");
10278 this->set_is_error();
10280 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10281 this->report_error(_("inverted slice range"));
10282 mpz_clear(eval);
10285 if (ival_valid)
10286 mpz_clear(ival);
10289 // Get the backend representation for a string index.
10291 Bexpression*
10292 String_index_expression::do_get_backend(Translate_context* context)
10294 Location loc = this->location();
10295 Expression* string_arg = this->string_;
10296 if (this->string_->type()->points_to() != NULL)
10297 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10299 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10301 int code = (this->end_ == NULL
10302 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10303 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10305 Gogo* gogo = context->gogo();
10306 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10308 Type* int_type = Type::lookup_integer_type("int");
10310 // It is possible that an error occurred earlier because the start index
10311 // cannot be represented as an integer type. In this case, we shouldn't
10312 // try casting the starting index into an integer since
10313 // Type_conversion_expression will fail to get the backend representation.
10314 // FIXME.
10315 if (this->start_->type()->integer_type() == NULL
10316 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10318 go_assert(saw_errors());
10319 return context->backend()->error_expression();
10322 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10324 if (this->end_ == NULL)
10326 Expression* length =
10327 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10329 Expression* start_too_large =
10330 Expression::make_binary(OPERATOR_GE, start, length, loc);
10331 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10332 bad_index, loc);
10333 Expression* bytes =
10334 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10336 Bexpression* bstart = start->get_backend(context);
10337 Bexpression* ptr = bytes->get_backend(context);
10338 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10339 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10340 Bexpression* index =
10341 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
10343 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10344 Bexpression* index_error = bad_index->get_backend(context);
10345 return gogo->backend()->conditional_expression(byte_btype, index_error,
10346 crash, index, loc);
10349 Expression* end = NULL;
10350 if (this->end_->is_nil_expression())
10351 end = Expression::make_integer_sl(-1, int_type, loc);
10352 else
10354 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10355 bad_index =
10356 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10357 end = Expression::make_cast(int_type, this->end_, loc);
10360 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10361 string_arg, start, end);
10362 Bexpression* bstrslice = strslice->get_backend(context);
10364 Btype* str_btype = strslice->type()->get_backend(gogo);
10365 Bexpression* index_error = bad_index->get_backend(context);
10366 return gogo->backend()->conditional_expression(str_btype, index_error,
10367 crash, bstrslice, loc);
10370 // Dump ast representation for a string index expression.
10372 void
10373 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10374 const
10376 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10377 this->start_, this->end_, NULL);
10380 // Make a string index expression. END may be NULL.
10382 Expression*
10383 Expression::make_string_index(Expression* string, Expression* start,
10384 Expression* end, Location location)
10386 return new String_index_expression(string, start, end, location);
10389 // Class Map_index.
10391 // Get the type of the map.
10393 Map_type*
10394 Map_index_expression::get_map_type() const
10396 Map_type* mt = this->map_->type()->deref()->map_type();
10397 if (mt == NULL)
10398 go_assert(saw_errors());
10399 return mt;
10402 // Map index traversal.
10405 Map_index_expression::do_traverse(Traverse* traverse)
10407 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10408 return TRAVERSE_EXIT;
10409 return Expression::traverse(&this->index_, traverse);
10412 // We need to pass in a pointer to the key, so flatten the index into a
10413 // temporary variable if it isn't already. The value pointer will be
10414 // dereferenced and checked for nil, so flatten into a temporary to avoid
10415 // recomputation.
10417 Expression*
10418 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
10419 Statement_inserter* inserter)
10421 Location loc = this->location();
10422 Map_type* mt = this->get_map_type();
10423 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
10425 if (this->index_->type()->interface_type() != NULL
10426 && !this->index_->is_variable())
10428 Temporary_statement* temp =
10429 Statement::make_temporary(NULL, this->index_, loc);
10430 inserter->insert(temp);
10431 this->index_ = Expression::make_temporary_reference(temp, loc);
10433 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
10434 this->index_, loc);
10437 if (!this->index_->is_variable())
10439 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10440 loc);
10441 inserter->insert(temp);
10442 this->index_ = Expression::make_temporary_reference(temp, loc);
10445 if (this->value_pointer_ == NULL)
10446 this->get_value_pointer(this->is_lvalue_);
10447 if (!this->value_pointer_->is_variable())
10449 Temporary_statement* temp =
10450 Statement::make_temporary(NULL, this->value_pointer_, loc);
10451 inserter->insert(temp);
10452 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
10455 return this;
10458 // Return the type of a map index.
10460 Type*
10461 Map_index_expression::do_type()
10463 Map_type* mt = this->get_map_type();
10464 if (mt == NULL)
10465 return Type::make_error_type();
10466 Type* type = mt->val_type();
10467 // If this map index is in a tuple assignment, we actually return a
10468 // pointer to the value type. Tuple_map_assignment_statement is
10469 // responsible for handling this correctly. We need to get the type
10470 // right in case this gets assigned to a temporary variable.
10471 if (this->is_in_tuple_assignment_)
10472 type = Type::make_pointer_type(type);
10473 return type;
10476 // Fix the type of a map index.
10478 void
10479 Map_index_expression::do_determine_type(const Type_context*)
10481 this->map_->determine_type_no_context();
10482 Map_type* mt = this->get_map_type();
10483 Type* key_type = mt == NULL ? NULL : mt->key_type();
10484 Type_context subcontext(key_type, false);
10485 this->index_->determine_type(&subcontext);
10488 // Check types of a map index.
10490 void
10491 Map_index_expression::do_check_types(Gogo*)
10493 std::string reason;
10494 Map_type* mt = this->get_map_type();
10495 if (mt == NULL)
10496 return;
10497 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10499 if (reason.empty())
10500 this->report_error(_("incompatible type for map index"));
10501 else
10503 error_at(this->location(), "incompatible type for map index (%s)",
10504 reason.c_str());
10505 this->set_is_error();
10510 // Get the backend representation for a map index.
10512 Bexpression*
10513 Map_index_expression::do_get_backend(Translate_context* context)
10515 Map_type* type = this->get_map_type();
10516 if (type == NULL)
10518 go_assert(saw_errors());
10519 return context->backend()->error_expression();
10522 go_assert(this->value_pointer_ != NULL
10523 && this->value_pointer_->is_variable());
10525 Bexpression* ret;
10526 if (this->is_lvalue_)
10528 Expression* val =
10529 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10530 this->location());
10531 ret = val->get_backend(context);
10533 else if (this->is_in_tuple_assignment_)
10535 // Tuple_map_assignment_statement is responsible for using this
10536 // appropriately.
10537 ret = this->value_pointer_->get_backend(context);
10539 else
10541 Location loc = this->location();
10543 Expression* nil_check =
10544 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10545 Expression::make_nil(loc), loc);
10546 Bexpression* bnil_check = nil_check->get_backend(context);
10547 Expression* val =
10548 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10549 Bexpression* bval = val->get_backend(context);
10551 Gogo* gogo = context->gogo();
10552 Btype* val_btype = type->val_type()->get_backend(gogo);
10553 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10554 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10555 val_zero, bval, loc);
10557 return ret;
10560 // Get an expression for the map index. This returns an expression which
10561 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10562 // not in the map.
10564 Expression*
10565 Map_index_expression::get_value_pointer(bool insert)
10567 if (this->value_pointer_ == NULL)
10569 Map_type* type = this->get_map_type();
10570 if (type == NULL)
10572 go_assert(saw_errors());
10573 return Expression::make_error(this->location());
10576 Location loc = this->location();
10577 Expression* map_ref = this->map_;
10578 if (this->map_->type()->points_to() != NULL)
10579 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10581 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10582 loc);
10583 Expression* map_index =
10584 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10585 map_ref, index_ptr,
10586 Expression::make_boolean(insert, loc));
10588 Type* val_type = type->val_type();
10589 this->value_pointer_ =
10590 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10591 map_index, this->location());
10593 return this->value_pointer_;
10596 // Dump ast representation for a map index expression
10598 void
10599 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10600 const
10602 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10603 this->index_, NULL, NULL);
10606 // Make a map index expression.
10608 Map_index_expression*
10609 Expression::make_map_index(Expression* map, Expression* index,
10610 Location location)
10612 return new Map_index_expression(map, index, location);
10615 // Class Field_reference_expression.
10617 // Lower a field reference expression. There is nothing to lower, but
10618 // this is where we generate the tracking information for fields with
10619 // the magic go:"track" tag.
10621 Expression*
10622 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10623 Statement_inserter* inserter, int)
10625 Struct_type* struct_type = this->expr_->type()->struct_type();
10626 if (struct_type == NULL)
10628 // Error will be reported elsewhere.
10629 return this;
10631 const Struct_field* field = struct_type->field(this->field_index_);
10632 if (field == NULL)
10633 return this;
10634 if (!field->has_tag())
10635 return this;
10636 if (field->tag().find("go:\"track\"") == std::string::npos)
10637 return this;
10639 // References from functions generated by the compiler don't count.
10640 if (function != NULL && function->func_value()->is_type_specific_function())
10641 return this;
10643 // We have found a reference to a tracked field. Build a call to
10644 // the runtime function __go_fieldtrack with a string that describes
10645 // the field. FIXME: We should only call this once per referenced
10646 // field per function, not once for each reference to the field.
10648 if (this->called_fieldtrack_)
10649 return this;
10650 this->called_fieldtrack_ = true;
10652 Location loc = this->location();
10654 std::string s = "fieldtrack \"";
10655 Named_type* nt = this->expr_->type()->named_type();
10656 if (nt == NULL || nt->named_object()->package() == NULL)
10657 s.append(gogo->pkgpath());
10658 else
10659 s.append(nt->named_object()->package()->pkgpath());
10660 s.push_back('.');
10661 if (nt != NULL)
10662 s.append(Gogo::unpack_hidden_name(nt->name()));
10663 s.push_back('.');
10664 s.append(field->field_name());
10665 s.push_back('"');
10667 // We can't use a string here, because internally a string holds a
10668 // pointer to the actual bytes; when the linker garbage collects the
10669 // string, it won't garbage collect the bytes. So we use a
10670 // [...]byte.
10672 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
10674 Type* byte_type = gogo->lookup_global("byte")->type_value();
10675 Type* array_type = Type::make_array_type(byte_type, length_expr);
10677 Expression_list* bytes = new Expression_list();
10678 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
10680 unsigned char c = static_cast<unsigned char>(*p);
10681 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
10684 Expression* e = Expression::make_composite_literal(array_type, 0, false,
10685 bytes, false, loc);
10687 Variable* var = new Variable(array_type, e, true, false, false, loc);
10689 static int count;
10690 char buf[50];
10691 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
10692 ++count;
10694 Named_object* no = gogo->add_variable(buf, var);
10695 e = Expression::make_var_reference(no, loc);
10696 e = Expression::make_unary(OPERATOR_AND, e, loc);
10698 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
10699 gogo->lower_expression(function, inserter, &call);
10700 inserter->insert(Statement::make_statement(call, false));
10702 // Put this function, and the global variable we just created, into
10703 // unique sections. This will permit the linker to garbage collect
10704 // them if they are not referenced. The effect is that the only
10705 // strings, indicating field references, that will wind up in the
10706 // executable will be those for functions that are actually needed.
10707 if (function != NULL)
10708 function->func_value()->set_in_unique_section();
10709 var->set_in_unique_section();
10711 return this;
10714 // Return the type of a field reference.
10716 Type*
10717 Field_reference_expression::do_type()
10719 Type* type = this->expr_->type();
10720 if (type->is_error())
10721 return type;
10722 Struct_type* struct_type = type->struct_type();
10723 go_assert(struct_type != NULL);
10724 return struct_type->field(this->field_index_)->type();
10727 // Check the types for a field reference.
10729 void
10730 Field_reference_expression::do_check_types(Gogo*)
10732 Type* type = this->expr_->type();
10733 if (type->is_error())
10734 return;
10735 Struct_type* struct_type = type->struct_type();
10736 go_assert(struct_type != NULL);
10737 go_assert(struct_type->field(this->field_index_) != NULL);
10740 // Get the backend representation for a field reference.
10742 Bexpression*
10743 Field_reference_expression::do_get_backend(Translate_context* context)
10745 Bexpression* bstruct = this->expr_->get_backend(context);
10746 return context->gogo()->backend()->struct_field_expression(bstruct,
10747 this->field_index_,
10748 this->location());
10751 // Dump ast representation for a field reference expression.
10753 void
10754 Field_reference_expression::do_dump_expression(
10755 Ast_dump_context* ast_dump_context) const
10757 this->expr_->dump_expression(ast_dump_context);
10758 ast_dump_context->ostream() << "." << this->field_index_;
10761 // Make a reference to a qualified identifier in an expression.
10763 Field_reference_expression*
10764 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10765 Location location)
10767 return new Field_reference_expression(expr, field_index, location);
10770 // Class Interface_field_reference_expression.
10772 // Return an expression for the pointer to the function to call.
10774 Expression*
10775 Interface_field_reference_expression::get_function()
10777 Expression* ref = this->expr_;
10778 Location loc = this->location();
10779 if (ref->type()->points_to() != NULL)
10780 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
10782 Expression* mtable =
10783 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
10784 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
10786 std::string name = Gogo::unpack_hidden_name(this->name_);
10787 unsigned int index;
10788 const Struct_field* field = mtable_type->find_local_field(name, &index);
10789 go_assert(field != NULL);
10790 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
10791 return Expression::make_field_reference(mtable, index, loc);
10794 // Return an expression for the first argument to pass to the interface
10795 // function.
10797 Expression*
10798 Interface_field_reference_expression::get_underlying_object()
10800 Expression* expr = this->expr_;
10801 if (expr->type()->points_to() != NULL)
10802 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
10803 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
10804 this->location());
10807 // Traversal.
10810 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10812 return Expression::traverse(&this->expr_, traverse);
10815 // Lower the expression. If this expression is not called, we need to
10816 // evaluate the expression twice when converting to the backend
10817 // interface. So introduce a temporary variable if necessary.
10819 Expression*
10820 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
10821 Statement_inserter* inserter)
10823 if (!this->expr_->is_variable())
10825 Temporary_statement* temp =
10826 Statement::make_temporary(this->expr_->type(), NULL, this->location());
10827 inserter->insert(temp);
10828 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
10829 this->location());
10831 return this;
10834 // Return the type of an interface field reference.
10836 Type*
10837 Interface_field_reference_expression::do_type()
10839 Type* expr_type = this->expr_->type();
10841 Type* points_to = expr_type->points_to();
10842 if (points_to != NULL)
10843 expr_type = points_to;
10845 Interface_type* interface_type = expr_type->interface_type();
10846 if (interface_type == NULL)
10847 return Type::make_error_type();
10849 const Typed_identifier* method = interface_type->find_method(this->name_);
10850 if (method == NULL)
10851 return Type::make_error_type();
10853 return method->type();
10856 // Determine types.
10858 void
10859 Interface_field_reference_expression::do_determine_type(const Type_context*)
10861 this->expr_->determine_type_no_context();
10864 // Check the types for an interface field reference.
10866 void
10867 Interface_field_reference_expression::do_check_types(Gogo*)
10869 Type* type = this->expr_->type();
10871 Type* points_to = type->points_to();
10872 if (points_to != NULL)
10873 type = points_to;
10875 Interface_type* interface_type = type->interface_type();
10876 if (interface_type == NULL)
10878 if (!type->is_error_type())
10879 this->report_error(_("expected interface or pointer to interface"));
10881 else
10883 const Typed_identifier* method =
10884 interface_type->find_method(this->name_);
10885 if (method == NULL)
10887 error_at(this->location(), "method %qs not in interface",
10888 Gogo::message_name(this->name_).c_str());
10889 this->set_is_error();
10894 // If an interface field reference is not simply called, then it is
10895 // represented as a closure. The closure will hold a single variable,
10896 // the value of the interface on which the method should be called.
10897 // The function will be a simple thunk that pulls the value from the
10898 // closure and calls the method with the remaining arguments.
10900 // Because method values are not common, we don't build all thunks for
10901 // all possible interface methods, but instead only build them as we
10902 // need them. In particular, we even build them on demand for
10903 // interface methods defined in other packages.
10905 Interface_field_reference_expression::Interface_method_thunks
10906 Interface_field_reference_expression::interface_method_thunks;
10908 // Find or create the thunk to call method NAME on TYPE.
10910 Named_object*
10911 Interface_field_reference_expression::create_thunk(Gogo* gogo,
10912 Interface_type* type,
10913 const std::string& name)
10915 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
10916 std::pair<Interface_method_thunks::iterator, bool> ins =
10917 Interface_field_reference_expression::interface_method_thunks.insert(val);
10918 if (ins.second)
10920 // This is the first time we have seen this interface.
10921 ins.first->second = new Method_thunks();
10924 for (Method_thunks::const_iterator p = ins.first->second->begin();
10925 p != ins.first->second->end();
10926 p++)
10927 if (p->first == name)
10928 return p->second;
10930 Location loc = type->location();
10932 const Typed_identifier* method_id = type->find_method(name);
10933 if (method_id == NULL)
10934 return Named_object::make_erroneous_name(Gogo::thunk_name());
10936 Function_type* orig_fntype = method_id->type()->function_type();
10937 if (orig_fntype == NULL)
10938 return Named_object::make_erroneous_name(Gogo::thunk_name());
10940 Struct_field_list* sfl = new Struct_field_list();
10941 // The type here is wrong--it should be the C function type. But it
10942 // doesn't really matter.
10943 Type* vt = Type::make_pointer_type(Type::make_void_type());
10944 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
10945 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
10946 Type* closure_type = Type::make_struct_type(sfl, loc);
10947 closure_type = Type::make_pointer_type(closure_type);
10949 Function_type* new_fntype = orig_fntype->copy_with_names();
10951 std::string thunk_name = Gogo::thunk_name();
10952 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
10953 false, loc);
10955 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
10956 cvar->set_is_used();
10957 cvar->set_is_closure();
10958 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
10959 NULL, cvar);
10960 new_no->func_value()->set_closure_var(cp);
10962 gogo->start_block(loc);
10964 // Field 0 of the closure is the function code pointer, field 1 is
10965 // the value on which to invoke the method.
10966 Expression* arg = Expression::make_var_reference(cp, loc);
10967 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
10968 arg = Expression::make_field_reference(arg, 1, loc);
10970 Expression *ifre = Expression::make_interface_field_reference(arg, name,
10971 loc);
10973 const Typed_identifier_list* orig_params = orig_fntype->parameters();
10974 Expression_list* args;
10975 if (orig_params == NULL || orig_params->empty())
10976 args = NULL;
10977 else
10979 const Typed_identifier_list* new_params = new_fntype->parameters();
10980 args = new Expression_list();
10981 for (Typed_identifier_list::const_iterator p = new_params->begin();
10982 p != new_params->end();
10983 ++p)
10985 Named_object* p_no = gogo->lookup(p->name(), NULL);
10986 go_assert(p_no != NULL
10987 && p_no->is_variable()
10988 && p_no->var_value()->is_parameter());
10989 args->push_back(Expression::make_var_reference(p_no, loc));
10993 Call_expression* call = Expression::make_call(ifre, args,
10994 orig_fntype->is_varargs(),
10995 loc);
10996 call->set_varargs_are_lowered();
10998 Statement* s = Statement::make_return_from_call(call, loc);
10999 gogo->add_statement(s);
11000 Block* b = gogo->finish_block(loc);
11001 gogo->add_block(b, loc);
11002 gogo->lower_block(new_no, b);
11003 gogo->flatten_block(new_no, b);
11004 gogo->finish_function(loc);
11006 ins.first->second->push_back(std::make_pair(name, new_no));
11007 return new_no;
11010 // Get the backend representation for a method value.
11012 Bexpression*
11013 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11015 Interface_type* type = this->expr_->type()->interface_type();
11016 if (type == NULL)
11018 go_assert(saw_errors());
11019 return context->backend()->error_expression();
11022 Named_object* thunk =
11023 Interface_field_reference_expression::create_thunk(context->gogo(),
11024 type, this->name_);
11025 if (thunk->is_erroneous())
11027 go_assert(saw_errors());
11028 return context->backend()->error_expression();
11031 // FIXME: We should lower this earlier, but we can't it lower it in
11032 // the lowering pass because at that point we don't know whether we
11033 // need to create the thunk or not. If the expression is called, we
11034 // don't need the thunk.
11036 Location loc = this->location();
11038 Struct_field_list* fields = new Struct_field_list();
11039 fields->push_back(Struct_field(Typed_identifier("fn.0",
11040 thunk->func_value()->type(),
11041 loc)));
11042 fields->push_back(Struct_field(Typed_identifier("val.1",
11043 this->expr_->type(),
11044 loc)));
11045 Struct_type* st = Type::make_struct_type(fields, loc);
11047 Expression_list* vals = new Expression_list();
11048 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11049 vals->push_back(this->expr_);
11051 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11052 Bexpression* bclosure =
11053 Expression::make_heap_expression(expr, loc)->get_backend(context);
11055 Expression* nil_check =
11056 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11057 Expression::make_nil(loc), loc);
11058 Bexpression* bnil_check = nil_check->get_backend(context);
11060 Gogo* gogo = context->gogo();
11061 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11062 loc)->get_backend(context);
11064 Bexpression* bcond =
11065 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11066 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11067 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11070 // Dump ast representation for an interface field reference.
11072 void
11073 Interface_field_reference_expression::do_dump_expression(
11074 Ast_dump_context* ast_dump_context) const
11076 this->expr_->dump_expression(ast_dump_context);
11077 ast_dump_context->ostream() << "." << this->name_;
11080 // Make a reference to a field in an interface.
11082 Expression*
11083 Expression::make_interface_field_reference(Expression* expr,
11084 const std::string& field,
11085 Location location)
11087 return new Interface_field_reference_expression(expr, field, location);
11090 // A general selector. This is a Parser_expression for LEFT.NAME. It
11091 // is lowered after we know the type of the left hand side.
11093 class Selector_expression : public Parser_expression
11095 public:
11096 Selector_expression(Expression* left, const std::string& name,
11097 Location location)
11098 : Parser_expression(EXPRESSION_SELECTOR, location),
11099 left_(left), name_(name)
11102 protected:
11104 do_traverse(Traverse* traverse)
11105 { return Expression::traverse(&this->left_, traverse); }
11107 Expression*
11108 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11110 Expression*
11111 do_copy()
11113 return new Selector_expression(this->left_->copy(), this->name_,
11114 this->location());
11117 void
11118 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11120 private:
11121 Expression*
11122 lower_method_expression(Gogo*);
11124 // The expression on the left hand side.
11125 Expression* left_;
11126 // The name on the right hand side.
11127 std::string name_;
11130 // Lower a selector expression once we know the real type of the left
11131 // hand side.
11133 Expression*
11134 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11135 int)
11137 Expression* left = this->left_;
11138 if (left->is_type_expression())
11139 return this->lower_method_expression(gogo);
11140 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11141 this->location());
11144 // Lower a method expression T.M or (*T).M. We turn this into a
11145 // function literal.
11147 Expression*
11148 Selector_expression::lower_method_expression(Gogo* gogo)
11150 Location location = this->location();
11151 Type* type = this->left_->type();
11152 const std::string& name(this->name_);
11154 bool is_pointer;
11155 if (type->points_to() == NULL)
11156 is_pointer = false;
11157 else
11159 is_pointer = true;
11160 type = type->points_to();
11162 Named_type* nt = type->named_type();
11163 if (nt == NULL)
11165 error_at(location,
11166 ("method expression requires named type or "
11167 "pointer to named type"));
11168 return Expression::make_error(location);
11171 bool is_ambiguous;
11172 Method* method = nt->method_function(name, &is_ambiguous);
11173 const Typed_identifier* imethod = NULL;
11174 if (method == NULL && !is_pointer)
11176 Interface_type* it = nt->interface_type();
11177 if (it != NULL)
11178 imethod = it->find_method(name);
11181 if (method == NULL && imethod == NULL)
11183 if (!is_ambiguous)
11184 error_at(location, "type %<%s%s%> has no method %<%s%>",
11185 is_pointer ? "*" : "",
11186 nt->message_name().c_str(),
11187 Gogo::message_name(name).c_str());
11188 else
11189 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11190 Gogo::message_name(name).c_str(),
11191 is_pointer ? "*" : "",
11192 nt->message_name().c_str());
11193 return Expression::make_error(location);
11196 if (method != NULL && !is_pointer && !method->is_value_method())
11198 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11199 nt->message_name().c_str(),
11200 Gogo::message_name(name).c_str());
11201 return Expression::make_error(location);
11204 // Build a new function type in which the receiver becomes the first
11205 // argument.
11206 Function_type* method_type;
11207 if (method != NULL)
11209 method_type = method->type();
11210 go_assert(method_type->is_method());
11212 else
11214 method_type = imethod->type()->function_type();
11215 go_assert(method_type != NULL && !method_type->is_method());
11218 const char* const receiver_name = "$this";
11219 Typed_identifier_list* parameters = new Typed_identifier_list();
11220 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11221 location));
11223 const Typed_identifier_list* method_parameters = method_type->parameters();
11224 if (method_parameters != NULL)
11226 int i = 0;
11227 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11228 p != method_parameters->end();
11229 ++p, ++i)
11231 if (!p->name().empty())
11232 parameters->push_back(*p);
11233 else
11235 char buf[20];
11236 snprintf(buf, sizeof buf, "$param%d", i);
11237 parameters->push_back(Typed_identifier(buf, p->type(),
11238 p->location()));
11243 const Typed_identifier_list* method_results = method_type->results();
11244 Typed_identifier_list* results;
11245 if (method_results == NULL)
11246 results = NULL;
11247 else
11249 results = new Typed_identifier_list();
11250 for (Typed_identifier_list::const_iterator p = method_results->begin();
11251 p != method_results->end();
11252 ++p)
11253 results->push_back(*p);
11256 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11257 location);
11258 if (method_type->is_varargs())
11259 fntype->set_is_varargs();
11261 // We generate methods which always takes a pointer to the receiver
11262 // as their first argument. If this is for a pointer type, we can
11263 // simply reuse the existing function. We use an internal hack to
11264 // get the right type.
11265 // FIXME: This optimization is disabled because it doesn't yet work
11266 // with function descriptors when the method expression is not
11267 // directly called.
11268 if (method != NULL && is_pointer && false)
11270 Named_object* mno = (method->needs_stub_method()
11271 ? method->stub_object()
11272 : method->named_object());
11273 Expression* f = Expression::make_func_reference(mno, NULL, location);
11274 f = Expression::make_cast(fntype, f, location);
11275 Type_conversion_expression* tce =
11276 static_cast<Type_conversion_expression*>(f);
11277 tce->set_may_convert_function_types();
11278 return f;
11281 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11282 location);
11284 Named_object* vno = gogo->lookup(receiver_name, NULL);
11285 go_assert(vno != NULL);
11286 Expression* ve = Expression::make_var_reference(vno, location);
11287 Expression* bm;
11288 if (method != NULL)
11289 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11290 else
11291 bm = Expression::make_interface_field_reference(ve, name, location);
11293 // Even though we found the method above, if it has an error type we
11294 // may see an error here.
11295 if (bm->is_error_expression())
11297 gogo->finish_function(location);
11298 return bm;
11301 Expression_list* args;
11302 if (parameters->size() <= 1)
11303 args = NULL;
11304 else
11306 args = new Expression_list();
11307 Typed_identifier_list::const_iterator p = parameters->begin();
11308 ++p;
11309 for (; p != parameters->end(); ++p)
11311 vno = gogo->lookup(p->name(), NULL);
11312 go_assert(vno != NULL);
11313 args->push_back(Expression::make_var_reference(vno, location));
11317 gogo->start_block(location);
11319 Call_expression* call = Expression::make_call(bm, args,
11320 method_type->is_varargs(),
11321 location);
11323 Statement* s = Statement::make_return_from_call(call, location);
11324 gogo->add_statement(s);
11326 Block* b = gogo->finish_block(location);
11328 gogo->add_block(b, location);
11330 // Lower the call in case there are multiple results.
11331 gogo->lower_block(no, b);
11332 gogo->flatten_block(no, b);
11334 gogo->finish_function(location);
11336 return Expression::make_func_reference(no, NULL, location);
11339 // Dump the ast for a selector expression.
11341 void
11342 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11343 const
11345 ast_dump_context->dump_expression(this->left_);
11346 ast_dump_context->ostream() << ".";
11347 ast_dump_context->ostream() << this->name_;
11350 // Make a selector expression.
11352 Expression*
11353 Expression::make_selector(Expression* left, const std::string& name,
11354 Location location)
11356 return new Selector_expression(left, name, location);
11359 // Class Allocation_expression.
11362 Allocation_expression::do_traverse(Traverse* traverse)
11364 return Type::traverse(this->type_, traverse);
11367 Type*
11368 Allocation_expression::do_type()
11370 return Type::make_pointer_type(this->type_);
11373 // Make a copy of an allocation expression.
11375 Expression*
11376 Allocation_expression::do_copy()
11378 Allocation_expression* alloc =
11379 new Allocation_expression(this->type_, this->location());
11380 if (this->allocate_on_stack_)
11381 alloc->set_allocate_on_stack();
11382 return alloc;
11385 // Return the backend representation for an allocation expression.
11387 Bexpression*
11388 Allocation_expression::do_get_backend(Translate_context* context)
11390 Gogo* gogo = context->gogo();
11391 Location loc = this->location();
11393 Btype* btype = this->type_->get_backend(gogo);
11394 if (this->allocate_on_stack_)
11396 int64_t size = gogo->backend()->type_size(btype);
11397 return gogo->backend()->stack_allocation_expression(size, loc);
11400 Bexpression* space =
11401 gogo->allocate_memory(this->type_, loc)->get_backend(context);
11402 Btype* pbtype = gogo->backend()->pointer_type(btype);
11403 return gogo->backend()->convert_expression(pbtype, space, loc);
11406 // Dump ast representation for an allocation expression.
11408 void
11409 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11410 const
11412 ast_dump_context->ostream() << "new(";
11413 ast_dump_context->dump_type(this->type_);
11414 ast_dump_context->ostream() << ")";
11417 // Make an allocation expression.
11419 Expression*
11420 Expression::make_allocation(Type* type, Location location)
11422 return new Allocation_expression(type, location);
11425 // Class Struct_construction_expression.
11427 // Traversal.
11430 Struct_construction_expression::do_traverse(Traverse* traverse)
11432 if (this->vals_ != NULL)
11434 if (this->traverse_order_ == NULL)
11436 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11437 return TRAVERSE_EXIT;
11439 else
11441 for (std::vector<int>::const_iterator p =
11442 this->traverse_order_->begin();
11443 p != this->traverse_order_->end();
11444 ++p)
11446 if (Expression::traverse(&this->vals_->at(*p), traverse)
11447 == TRAVERSE_EXIT)
11448 return TRAVERSE_EXIT;
11452 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11453 return TRAVERSE_EXIT;
11454 return TRAVERSE_CONTINUE;
11457 // Return whether this is a constant initializer.
11459 bool
11460 Struct_construction_expression::is_constant_struct() const
11462 if (this->vals_ == NULL)
11463 return true;
11464 for (Expression_list::const_iterator pv = this->vals_->begin();
11465 pv != this->vals_->end();
11466 ++pv)
11468 if (*pv != NULL
11469 && !(*pv)->is_constant()
11470 && (!(*pv)->is_composite_literal()
11471 || (*pv)->is_nonconstant_composite_literal()))
11472 return false;
11475 const Struct_field_list* fields = this->type_->struct_type()->fields();
11476 for (Struct_field_list::const_iterator pf = fields->begin();
11477 pf != fields->end();
11478 ++pf)
11480 // There are no constant constructors for interfaces.
11481 if (pf->type()->interface_type() != NULL)
11482 return false;
11485 return true;
11488 // Return whether this struct is immutable.
11490 bool
11491 Struct_construction_expression::do_is_immutable() const
11493 if (this->vals_ == NULL)
11494 return true;
11495 for (Expression_list::const_iterator pv = this->vals_->begin();
11496 pv != this->vals_->end();
11497 ++pv)
11499 if (*pv != NULL && !(*pv)->is_immutable())
11500 return false;
11502 return true;
11505 // Final type determination.
11507 void
11508 Struct_construction_expression::do_determine_type(const Type_context*)
11510 if (this->vals_ == NULL)
11511 return;
11512 const Struct_field_list* fields = this->type_->struct_type()->fields();
11513 Expression_list::const_iterator pv = this->vals_->begin();
11514 for (Struct_field_list::const_iterator pf = fields->begin();
11515 pf != fields->end();
11516 ++pf, ++pv)
11518 if (pv == this->vals_->end())
11519 return;
11520 if (*pv != NULL)
11522 Type_context subcontext(pf->type(), false);
11523 (*pv)->determine_type(&subcontext);
11526 // Extra values are an error we will report elsewhere; we still want
11527 // to determine the type to avoid knockon errors.
11528 for (; pv != this->vals_->end(); ++pv)
11529 (*pv)->determine_type_no_context();
11532 // Check types.
11534 void
11535 Struct_construction_expression::do_check_types(Gogo*)
11537 if (this->vals_ == NULL)
11538 return;
11540 Struct_type* st = this->type_->struct_type();
11541 if (this->vals_->size() > st->field_count())
11543 this->report_error(_("too many expressions for struct"));
11544 return;
11547 const Struct_field_list* fields = st->fields();
11548 Expression_list::const_iterator pv = this->vals_->begin();
11549 int i = 0;
11550 for (Struct_field_list::const_iterator pf = fields->begin();
11551 pf != fields->end();
11552 ++pf, ++pv, ++i)
11554 if (pv == this->vals_->end())
11556 this->report_error(_("too few expressions for struct"));
11557 break;
11560 if (*pv == NULL)
11561 continue;
11563 std::string reason;
11564 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11566 if (reason.empty())
11567 error_at((*pv)->location(),
11568 "incompatible type for field %d in struct construction",
11569 i + 1);
11570 else
11571 error_at((*pv)->location(),
11572 ("incompatible type for field %d in "
11573 "struct construction (%s)"),
11574 i + 1, reason.c_str());
11575 this->set_is_error();
11578 go_assert(pv == this->vals_->end());
11581 // Flatten a struct construction expression. Store the values into
11582 // temporaries in case they need interface conversion.
11584 Expression*
11585 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
11586 Statement_inserter* inserter)
11588 if (this->vals_ == NULL)
11589 return this;
11591 // If this is a constant struct, we don't need temporaries.
11592 if (this->is_constant_struct())
11593 return this;
11595 Location loc = this->location();
11596 for (Expression_list::iterator pv = this->vals_->begin();
11597 pv != this->vals_->end();
11598 ++pv)
11600 if (*pv != NULL)
11602 if (!(*pv)->is_variable())
11604 Temporary_statement* temp =
11605 Statement::make_temporary(NULL, *pv, loc);
11606 inserter->insert(temp);
11607 *pv = Expression::make_temporary_reference(temp, loc);
11611 return this;
11614 // Return the backend representation for constructing a struct.
11616 Bexpression*
11617 Struct_construction_expression::do_get_backend(Translate_context* context)
11619 Gogo* gogo = context->gogo();
11621 Btype* btype = this->type_->get_backend(gogo);
11622 if (this->vals_ == NULL)
11623 return gogo->backend()->zero_expression(btype);
11625 const Struct_field_list* fields = this->type_->struct_type()->fields();
11626 Expression_list::const_iterator pv = this->vals_->begin();
11627 std::vector<Bexpression*> init;
11628 for (Struct_field_list::const_iterator pf = fields->begin();
11629 pf != fields->end();
11630 ++pf)
11632 Btype* fbtype = pf->type()->get_backend(gogo);
11633 if (pv == this->vals_->end())
11634 init.push_back(gogo->backend()->zero_expression(fbtype));
11635 else if (*pv == NULL)
11637 init.push_back(gogo->backend()->zero_expression(fbtype));
11638 ++pv;
11640 else
11642 Expression* val =
11643 Expression::convert_for_assignment(gogo, pf->type(),
11644 *pv, this->location());
11645 init.push_back(val->get_backend(context));
11646 ++pv;
11649 return gogo->backend()->constructor_expression(btype, init, this->location());
11652 // Export a struct construction.
11654 void
11655 Struct_construction_expression::do_export(Export* exp) const
11657 exp->write_c_string("convert(");
11658 exp->write_type(this->type_);
11659 for (Expression_list::const_iterator pv = this->vals_->begin();
11660 pv != this->vals_->end();
11661 ++pv)
11663 exp->write_c_string(", ");
11664 if (*pv != NULL)
11665 (*pv)->export_expression(exp);
11667 exp->write_c_string(")");
11670 // Dump ast representation of a struct construction expression.
11672 void
11673 Struct_construction_expression::do_dump_expression(
11674 Ast_dump_context* ast_dump_context) const
11676 ast_dump_context->dump_type(this->type_);
11677 ast_dump_context->ostream() << "{";
11678 ast_dump_context->dump_expression_list(this->vals_);
11679 ast_dump_context->ostream() << "}";
11682 // Make a struct composite literal. This used by the thunk code.
11684 Expression*
11685 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11686 Location location)
11688 go_assert(type->struct_type() != NULL);
11689 return new Struct_construction_expression(type, vals, location);
11692 // Class Array_construction_expression.
11694 // Traversal.
11697 Array_construction_expression::do_traverse(Traverse* traverse)
11699 if (this->vals_ != NULL
11700 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11701 return TRAVERSE_EXIT;
11702 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11703 return TRAVERSE_EXIT;
11704 return TRAVERSE_CONTINUE;
11707 // Return whether this is a constant initializer.
11709 bool
11710 Array_construction_expression::is_constant_array() const
11712 if (this->vals_ == NULL)
11713 return true;
11715 // There are no constant constructors for interfaces.
11716 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11717 return false;
11719 for (Expression_list::const_iterator pv = this->vals_->begin();
11720 pv != this->vals_->end();
11721 ++pv)
11723 if (*pv != NULL
11724 && !(*pv)->is_constant()
11725 && (!(*pv)->is_composite_literal()
11726 || (*pv)->is_nonconstant_composite_literal()))
11727 return false;
11729 return true;
11732 // Return whether this is an immutable array initializer.
11734 bool
11735 Array_construction_expression::do_is_immutable() const
11737 if (this->vals_ == NULL)
11738 return true;
11739 for (Expression_list::const_iterator pv = this->vals_->begin();
11740 pv != this->vals_->end();
11741 ++pv)
11743 if (*pv != NULL && !(*pv)->is_immutable())
11744 return false;
11746 return true;
11749 // Final type determination.
11751 void
11752 Array_construction_expression::do_determine_type(const Type_context*)
11754 if (this->vals_ == NULL)
11755 return;
11756 Type_context subcontext(this->type_->array_type()->element_type(), false);
11757 for (Expression_list::const_iterator pv = this->vals_->begin();
11758 pv != this->vals_->end();
11759 ++pv)
11761 if (*pv != NULL)
11762 (*pv)->determine_type(&subcontext);
11766 // Check types.
11768 void
11769 Array_construction_expression::do_check_types(Gogo*)
11771 if (this->vals_ == NULL)
11772 return;
11774 Array_type* at = this->type_->array_type();
11775 int i = 0;
11776 Type* element_type = at->element_type();
11777 for (Expression_list::const_iterator pv = this->vals_->begin();
11778 pv != this->vals_->end();
11779 ++pv, ++i)
11781 if (*pv != NULL
11782 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11784 error_at((*pv)->location(),
11785 "incompatible type for element %d in composite literal",
11786 i + 1);
11787 this->set_is_error();
11792 // Flatten an array construction expression. Store the values into
11793 // temporaries in case they need interface conversion.
11795 Expression*
11796 Array_construction_expression::do_flatten(Gogo*, Named_object*,
11797 Statement_inserter* inserter)
11799 if (this->vals_ == NULL)
11800 return this;
11802 // If this is a constant array, we don't need temporaries.
11803 if (this->is_constant_array())
11804 return this;
11806 Location loc = this->location();
11807 for (Expression_list::iterator pv = this->vals_->begin();
11808 pv != this->vals_->end();
11809 ++pv)
11811 if (*pv != NULL)
11813 if (!(*pv)->is_variable())
11815 Temporary_statement* temp =
11816 Statement::make_temporary(NULL, *pv, loc);
11817 inserter->insert(temp);
11818 *pv = Expression::make_temporary_reference(temp, loc);
11822 return this;
11825 // Get a constructor expression for the array values.
11827 Bexpression*
11828 Array_construction_expression::get_constructor(Translate_context* context,
11829 Btype* array_btype)
11831 Type* element_type = this->type_->array_type()->element_type();
11833 std::vector<unsigned long> indexes;
11834 std::vector<Bexpression*> vals;
11835 Gogo* gogo = context->gogo();
11836 if (this->vals_ != NULL)
11838 size_t i = 0;
11839 std::vector<unsigned long>::const_iterator pi;
11840 if (this->indexes_ != NULL)
11841 pi = this->indexes_->begin();
11842 for (Expression_list::const_iterator pv = this->vals_->begin();
11843 pv != this->vals_->end();
11844 ++pv, ++i)
11846 if (this->indexes_ != NULL)
11847 go_assert(pi != this->indexes_->end());
11849 if (this->indexes_ == NULL)
11850 indexes.push_back(i);
11851 else
11852 indexes.push_back(*pi);
11853 if (*pv == NULL)
11855 Btype* ebtype = element_type->get_backend(gogo);
11856 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11857 vals.push_back(zv);
11859 else
11861 Expression* val_expr =
11862 Expression::convert_for_assignment(gogo, element_type, *pv,
11863 this->location());
11864 vals.push_back(val_expr->get_backend(context));
11866 if (this->indexes_ != NULL)
11867 ++pi;
11869 if (this->indexes_ != NULL)
11870 go_assert(pi == this->indexes_->end());
11872 return gogo->backend()->array_constructor_expression(array_btype, indexes,
11873 vals, this->location());
11876 // Export an array construction.
11878 void
11879 Array_construction_expression::do_export(Export* exp) const
11881 exp->write_c_string("convert(");
11882 exp->write_type(this->type_);
11883 if (this->vals_ != NULL)
11885 std::vector<unsigned long>::const_iterator pi;
11886 if (this->indexes_ != NULL)
11887 pi = this->indexes_->begin();
11888 for (Expression_list::const_iterator pv = this->vals_->begin();
11889 pv != this->vals_->end();
11890 ++pv)
11892 exp->write_c_string(", ");
11894 if (this->indexes_ != NULL)
11896 char buf[100];
11897 snprintf(buf, sizeof buf, "%lu", *pi);
11898 exp->write_c_string(buf);
11899 exp->write_c_string(":");
11902 if (*pv != NULL)
11903 (*pv)->export_expression(exp);
11905 if (this->indexes_ != NULL)
11906 ++pi;
11909 exp->write_c_string(")");
11912 // Dump ast representation of an array construction expressin.
11914 void
11915 Array_construction_expression::do_dump_expression(
11916 Ast_dump_context* ast_dump_context) const
11918 Expression* length = this->type_->array_type()->length();
11920 ast_dump_context->ostream() << "[" ;
11921 if (length != NULL)
11923 ast_dump_context->dump_expression(length);
11925 ast_dump_context->ostream() << "]" ;
11926 ast_dump_context->dump_type(this->type_);
11927 ast_dump_context->ostream() << "{" ;
11928 if (this->indexes_ == NULL)
11929 ast_dump_context->dump_expression_list(this->vals_);
11930 else
11932 Expression_list::const_iterator pv = this->vals_->begin();
11933 for (std::vector<unsigned long>::const_iterator pi =
11934 this->indexes_->begin();
11935 pi != this->indexes_->end();
11936 ++pi, ++pv)
11938 if (pi != this->indexes_->begin())
11939 ast_dump_context->ostream() << ", ";
11940 ast_dump_context->ostream() << *pi << ':';
11941 ast_dump_context->dump_expression(*pv);
11944 ast_dump_context->ostream() << "}" ;
11948 // Class Fixed_array_construction_expression.
11950 Fixed_array_construction_expression::Fixed_array_construction_expression(
11951 Type* type, const std::vector<unsigned long>* indexes,
11952 Expression_list* vals, Location location)
11953 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
11954 type, indexes, vals, location)
11955 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
11957 // Return the backend representation for constructing a fixed array.
11959 Bexpression*
11960 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
11962 Type* type = this->type();
11963 Btype* btype = type->get_backend(context->gogo());
11964 return this->get_constructor(context, btype);
11967 Expression*
11968 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
11969 Location location)
11971 go_assert(type->array_type() != NULL && !type->is_slice_type());
11972 return new Fixed_array_construction_expression(type, NULL, vals, location);
11975 // Class Slice_construction_expression.
11977 Slice_construction_expression::Slice_construction_expression(
11978 Type* type, const std::vector<unsigned long>* indexes,
11979 Expression_list* vals, Location location)
11980 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
11981 type, indexes, vals, location),
11982 valtype_(NULL)
11984 go_assert(type->is_slice_type());
11986 unsigned long lenval;
11987 Expression* length;
11988 if (vals == NULL || vals->empty())
11989 lenval = 0;
11990 else
11992 if (this->indexes() == NULL)
11993 lenval = vals->size();
11994 else
11995 lenval = indexes->back() + 1;
11997 Type* int_type = Type::lookup_integer_type("int");
11998 length = Expression::make_integer_ul(lenval, int_type, location);
11999 Type* element_type = type->array_type()->element_type();
12000 this->valtype_ = Type::make_array_type(element_type, length);
12004 // Traversal.
12007 Slice_construction_expression::do_traverse(Traverse* traverse)
12009 if (this->Array_construction_expression::do_traverse(traverse)
12010 == TRAVERSE_EXIT)
12011 return TRAVERSE_EXIT;
12012 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12013 return TRAVERSE_EXIT;
12014 return TRAVERSE_CONTINUE;
12017 // Return the backend representation for constructing a slice.
12019 Bexpression*
12020 Slice_construction_expression::do_get_backend(Translate_context* context)
12022 Array_type* array_type = this->type()->array_type();
12023 if (array_type == NULL)
12025 go_assert(this->type()->is_error());
12026 return context->backend()->error_expression();
12029 Location loc = this->location();
12030 Type* element_type = array_type->element_type();
12031 go_assert(this->valtype_ != NULL);
12033 Expression_list* vals = this->vals();
12034 if (this->vals() == NULL || this->vals()->empty())
12036 // We need to create a unique value for the empty array literal.
12037 vals = new Expression_list;
12038 vals->push_back(NULL);
12040 Expression* array_val =
12041 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12042 vals, loc);
12044 bool is_constant_initializer = array_val->is_immutable();
12046 // We have to copy the initial values into heap memory if we are in
12047 // a function or if the values are not constants. We also have to
12048 // copy them if they may contain pointers in a non-constant context,
12049 // as otherwise the garbage collector won't see them.
12050 bool copy_to_heap = (context->function() != NULL
12051 || !is_constant_initializer
12052 || (element_type->has_pointer()
12053 && !context->is_const()));
12055 Expression* space;
12056 if (!copy_to_heap)
12058 // The initializer will only run once.
12059 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12060 space->unary_expression()->set_is_slice_init();
12062 else
12063 space = Expression::make_heap_expression(array_val, loc);
12065 // Build a constructor for the slice.
12067 Expression* len = this->valtype_->array_type()->length();
12068 Expression* slice_val =
12069 Expression::make_slice_value(this->type(), space, len, len, loc);
12070 return slice_val->get_backend(context);
12073 // Make a slice composite literal. This is used by the type
12074 // descriptor code.
12076 Expression*
12077 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12078 Location location)
12080 go_assert(type->is_slice_type());
12081 return new Slice_construction_expression(type, NULL, vals, location);
12084 // Class Map_construction_expression.
12086 // Traversal.
12089 Map_construction_expression::do_traverse(Traverse* traverse)
12091 if (this->vals_ != NULL
12092 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12093 return TRAVERSE_EXIT;
12094 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12095 return TRAVERSE_EXIT;
12096 return TRAVERSE_CONTINUE;
12099 // Flatten constructor initializer into a temporary variable since
12100 // we need to take its address for __go_construct_map.
12102 Expression*
12103 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12104 Statement_inserter* inserter)
12106 if (!this->is_error_expression()
12107 && this->vals_ != NULL
12108 && !this->vals_->empty()
12109 && this->constructor_temp_ == NULL)
12111 Map_type* mt = this->type_->map_type();
12112 Type* key_type = mt->key_type();
12113 Type* val_type = mt->val_type();
12114 this->element_type_ = Type::make_builtin_struct_type(2,
12115 "__key", key_type,
12116 "__val", val_type);
12118 Expression_list* value_pairs = new Expression_list();
12119 Location loc = this->location();
12121 size_t i = 0;
12122 for (Expression_list::const_iterator pv = this->vals_->begin();
12123 pv != this->vals_->end();
12124 ++pv, ++i)
12126 Expression_list* key_value_pair = new Expression_list();
12127 Expression* key = *pv;
12128 if (key->type()->interface_type() != NULL && !key->is_variable())
12130 Temporary_statement* temp =
12131 Statement::make_temporary(NULL, key, loc);
12132 inserter->insert(temp);
12133 key = Expression::make_temporary_reference(temp, loc);
12135 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
12137 ++pv;
12138 Expression* val = *pv;
12139 if (val->type()->interface_type() != NULL && !val->is_variable())
12141 Temporary_statement* temp =
12142 Statement::make_temporary(NULL, val, loc);
12143 inserter->insert(temp);
12144 val = Expression::make_temporary_reference(temp, loc);
12146 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
12148 key_value_pair->push_back(key);
12149 key_value_pair->push_back(val);
12150 value_pairs->push_back(
12151 Expression::make_struct_composite_literal(this->element_type_,
12152 key_value_pair, loc));
12155 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
12156 Type* ctor_type =
12157 Type::make_array_type(this->element_type_, element_count);
12158 Expression* constructor =
12159 new Fixed_array_construction_expression(ctor_type, NULL,
12160 value_pairs, loc);
12162 this->constructor_temp_ =
12163 Statement::make_temporary(NULL, constructor, loc);
12164 constructor->issue_nil_check();
12165 this->constructor_temp_->set_is_address_taken();
12166 inserter->insert(this->constructor_temp_);
12169 return this;
12172 // Final type determination.
12174 void
12175 Map_construction_expression::do_determine_type(const Type_context*)
12177 if (this->vals_ == NULL)
12178 return;
12180 Map_type* mt = this->type_->map_type();
12181 Type_context key_context(mt->key_type(), false);
12182 Type_context val_context(mt->val_type(), false);
12183 for (Expression_list::const_iterator pv = this->vals_->begin();
12184 pv != this->vals_->end();
12185 ++pv)
12187 (*pv)->determine_type(&key_context);
12188 ++pv;
12189 (*pv)->determine_type(&val_context);
12193 // Check types.
12195 void
12196 Map_construction_expression::do_check_types(Gogo*)
12198 if (this->vals_ == NULL)
12199 return;
12201 Map_type* mt = this->type_->map_type();
12202 int i = 0;
12203 Type* key_type = mt->key_type();
12204 Type* val_type = mt->val_type();
12205 for (Expression_list::const_iterator pv = this->vals_->begin();
12206 pv != this->vals_->end();
12207 ++pv, ++i)
12209 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12211 error_at((*pv)->location(),
12212 "incompatible type for element %d key in map construction",
12213 i + 1);
12214 this->set_is_error();
12216 ++pv;
12217 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12219 error_at((*pv)->location(),
12220 ("incompatible type for element %d value "
12221 "in map construction"),
12222 i + 1);
12223 this->set_is_error();
12228 // Return the backend representation for constructing a map.
12230 Bexpression*
12231 Map_construction_expression::do_get_backend(Translate_context* context)
12233 if (this->is_error_expression())
12234 return context->backend()->error_expression();
12235 Location loc = this->location();
12237 size_t i = 0;
12238 Expression* ventries;
12239 if (this->vals_ == NULL || this->vals_->empty())
12240 ventries = Expression::make_nil(loc);
12241 else
12243 go_assert(this->constructor_temp_ != NULL);
12244 i = this->vals_->size() / 2;
12246 Expression* ctor_ref =
12247 Expression::make_temporary_reference(this->constructor_temp_, loc);
12248 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12251 Map_type* mt = this->type_->map_type();
12252 if (this->element_type_ == NULL)
12253 this->element_type_ =
12254 Type::make_builtin_struct_type(2,
12255 "__key", mt->key_type(),
12256 "__val", mt->val_type());
12257 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12259 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12260 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
12262 Expression* entry_size =
12263 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12265 unsigned int field_index;
12266 const Struct_field* valfield =
12267 this->element_type_->find_local_field("__val", &field_index);
12268 Expression* val_offset =
12269 Expression::make_struct_field_offset(this->element_type_, valfield);
12270 Expression* val_size =
12271 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12273 Expression* map_ctor =
12274 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12275 entry_size, val_offset, val_size, ventries);
12276 return map_ctor->get_backend(context);
12279 // Export an array construction.
12281 void
12282 Map_construction_expression::do_export(Export* exp) const
12284 exp->write_c_string("convert(");
12285 exp->write_type(this->type_);
12286 for (Expression_list::const_iterator pv = this->vals_->begin();
12287 pv != this->vals_->end();
12288 ++pv)
12290 exp->write_c_string(", ");
12291 (*pv)->export_expression(exp);
12293 exp->write_c_string(")");
12296 // Dump ast representation for a map construction expression.
12298 void
12299 Map_construction_expression::do_dump_expression(
12300 Ast_dump_context* ast_dump_context) const
12302 ast_dump_context->ostream() << "{" ;
12303 ast_dump_context->dump_expression_list(this->vals_, true);
12304 ast_dump_context->ostream() << "}";
12307 // A general composite literal. This is lowered to a type specific
12308 // version.
12310 class Composite_literal_expression : public Parser_expression
12312 public:
12313 Composite_literal_expression(Type* type, int depth, bool has_keys,
12314 Expression_list* vals, bool all_are_names,
12315 Location location)
12316 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12317 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12318 all_are_names_(all_are_names)
12321 protected:
12323 do_traverse(Traverse* traverse);
12325 Expression*
12326 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12328 Expression*
12329 do_copy()
12331 return new Composite_literal_expression(this->type_, this->depth_,
12332 this->has_keys_,
12333 (this->vals_ == NULL
12334 ? NULL
12335 : this->vals_->copy()),
12336 this->all_are_names_,
12337 this->location());
12340 void
12341 do_dump_expression(Ast_dump_context*) const;
12343 private:
12344 Expression*
12345 lower_struct(Gogo*, Type*);
12347 Expression*
12348 lower_array(Type*);
12350 Expression*
12351 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12353 Expression*
12354 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12356 // The type of the composite literal.
12357 Type* type_;
12358 // The depth within a list of composite literals within a composite
12359 // literal, when the type is omitted.
12360 int depth_;
12361 // The values to put in the composite literal.
12362 Expression_list* vals_;
12363 // If this is true, then VALS_ is a list of pairs: a key and a
12364 // value. In an array initializer, a missing key will be NULL.
12365 bool has_keys_;
12366 // If this is true, then HAS_KEYS_ is true, and every key is a
12367 // simple identifier.
12368 bool all_are_names_;
12371 // Traversal.
12374 Composite_literal_expression::do_traverse(Traverse* traverse)
12376 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12377 return TRAVERSE_EXIT;
12379 // If this is a struct composite literal with keys, then the keys
12380 // are field names, not expressions. We don't want to traverse them
12381 // in that case. If we do, we can give an erroneous error "variable
12382 // initializer refers to itself." See bug482.go in the testsuite.
12383 if (this->has_keys_ && this->vals_ != NULL)
12385 // The type may not be resolvable at this point.
12386 Type* type = this->type_;
12388 for (int depth = this->depth_; depth > 0; --depth)
12390 if (type->array_type() != NULL)
12391 type = type->array_type()->element_type();
12392 else if (type->map_type() != NULL)
12393 type = type->map_type()->val_type();
12394 else
12396 // This error will be reported during lowering.
12397 return TRAVERSE_CONTINUE;
12401 while (true)
12403 if (type->classification() == Type::TYPE_NAMED)
12404 type = type->named_type()->real_type();
12405 else if (type->classification() == Type::TYPE_FORWARD)
12407 Type* t = type->forwarded();
12408 if (t == type)
12409 break;
12410 type = t;
12412 else
12413 break;
12416 if (type->classification() == Type::TYPE_STRUCT)
12418 Expression_list::iterator p = this->vals_->begin();
12419 while (p != this->vals_->end())
12421 // Skip key.
12422 ++p;
12423 go_assert(p != this->vals_->end());
12424 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12425 return TRAVERSE_EXIT;
12426 ++p;
12428 return TRAVERSE_CONTINUE;
12432 if (this->vals_ != NULL)
12433 return this->vals_->traverse(traverse);
12435 return TRAVERSE_CONTINUE;
12438 // Lower a generic composite literal into a specific version based on
12439 // the type.
12441 Expression*
12442 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12443 Statement_inserter* inserter, int)
12445 Type* type = this->type_;
12447 for (int depth = this->depth_; depth > 0; --depth)
12449 if (type->array_type() != NULL)
12450 type = type->array_type()->element_type();
12451 else if (type->map_type() != NULL)
12452 type = type->map_type()->val_type();
12453 else
12455 if (!type->is_error())
12456 error_at(this->location(),
12457 ("may only omit types within composite literals "
12458 "of slice, array, or map type"));
12459 return Expression::make_error(this->location());
12463 Type *pt = type->points_to();
12464 bool is_pointer = false;
12465 if (pt != NULL)
12467 is_pointer = true;
12468 type = pt;
12471 Expression* ret;
12472 if (type->is_error())
12473 return Expression::make_error(this->location());
12474 else if (type->struct_type() != NULL)
12475 ret = this->lower_struct(gogo, type);
12476 else if (type->array_type() != NULL)
12477 ret = this->lower_array(type);
12478 else if (type->map_type() != NULL)
12479 ret = this->lower_map(gogo, function, inserter, type);
12480 else
12482 error_at(this->location(),
12483 ("expected struct, slice, array, or map type "
12484 "for composite literal"));
12485 return Expression::make_error(this->location());
12488 if (is_pointer)
12489 ret = Expression::make_heap_expression(ret, this->location());
12491 return ret;
12494 // Lower a struct composite literal.
12496 Expression*
12497 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12499 Location location = this->location();
12500 Struct_type* st = type->struct_type();
12501 if (this->vals_ == NULL || !this->has_keys_)
12503 if (this->vals_ != NULL
12504 && !this->vals_->empty()
12505 && type->named_type() != NULL
12506 && type->named_type()->named_object()->package() != NULL)
12508 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12509 pf != st->fields()->end();
12510 ++pf)
12512 if (Gogo::is_hidden_name(pf->field_name())
12513 || pf->is_embedded_builtin(gogo))
12514 error_at(this->location(),
12515 "assignment of unexported field %qs in %qs literal",
12516 Gogo::message_name(pf->field_name()).c_str(),
12517 type->named_type()->message_name().c_str());
12521 return new Struct_construction_expression(type, this->vals_, location);
12524 size_t field_count = st->field_count();
12525 std::vector<Expression*> vals(field_count);
12526 std::vector<int>* traverse_order = new(std::vector<int>);
12527 Expression_list::const_iterator p = this->vals_->begin();
12528 Expression* external_expr = NULL;
12529 const Named_object* external_no = NULL;
12530 while (p != this->vals_->end())
12532 Expression* name_expr = *p;
12534 ++p;
12535 go_assert(p != this->vals_->end());
12536 Expression* val = *p;
12538 ++p;
12540 if (name_expr == NULL)
12542 error_at(val->location(), "mixture of field and value initializers");
12543 return Expression::make_error(location);
12546 bool bad_key = false;
12547 std::string name;
12548 const Named_object* no = NULL;
12549 switch (name_expr->classification())
12551 case EXPRESSION_UNKNOWN_REFERENCE:
12552 name = name_expr->unknown_expression()->name();
12553 if (type->named_type() != NULL)
12555 // If the named object found for this field name comes from a
12556 // different package than the struct it is a part of, do not count
12557 // this incorrect lookup as a usage of the object's package.
12558 no = name_expr->unknown_expression()->named_object();
12559 if (no->package() != NULL
12560 && no->package() != type->named_type()->named_object()->package())
12561 no->package()->forget_usage(name_expr);
12563 break;
12565 case EXPRESSION_CONST_REFERENCE:
12566 no = static_cast<Const_expression*>(name_expr)->named_object();
12567 break;
12569 case EXPRESSION_TYPE:
12571 Type* t = name_expr->type();
12572 Named_type* nt = t->named_type();
12573 if (nt == NULL)
12574 bad_key = true;
12575 else
12576 no = nt->named_object();
12578 break;
12580 case EXPRESSION_VAR_REFERENCE:
12581 no = name_expr->var_expression()->named_object();
12582 break;
12584 case EXPRESSION_FUNC_REFERENCE:
12585 no = name_expr->func_expression()->named_object();
12586 break;
12588 case EXPRESSION_UNARY:
12589 // If there is a local variable around with the same name as
12590 // the field, and this occurs in the closure, then the
12591 // parser may turn the field reference into an indirection
12592 // through the closure. FIXME: This is a mess.
12594 bad_key = true;
12595 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12596 if (ue->op() == OPERATOR_MULT)
12598 Field_reference_expression* fre =
12599 ue->operand()->field_reference_expression();
12600 if (fre != NULL)
12602 Struct_type* st =
12603 fre->expr()->type()->deref()->struct_type();
12604 if (st != NULL)
12606 const Struct_field* sf = st->field(fre->field_index());
12607 name = sf->field_name();
12609 // See below. FIXME.
12610 if (!Gogo::is_hidden_name(name)
12611 && name[0] >= 'a'
12612 && name[0] <= 'z')
12614 if (gogo->lookup_global(name.c_str()) != NULL)
12615 name = gogo->pack_hidden_name(name, false);
12618 char buf[20];
12619 snprintf(buf, sizeof buf, "%u", fre->field_index());
12620 size_t buflen = strlen(buf);
12621 if (name.compare(name.length() - buflen, buflen, buf)
12622 == 0)
12624 name = name.substr(0, name.length() - buflen);
12625 bad_key = false;
12631 break;
12633 default:
12634 bad_key = true;
12635 break;
12637 if (bad_key)
12639 error_at(name_expr->location(), "expected struct field name");
12640 return Expression::make_error(location);
12643 if (no != NULL)
12645 if (no->package() != NULL && external_expr == NULL)
12647 external_expr = name_expr;
12648 external_no = no;
12651 name = no->name();
12653 // A predefined name won't be packed. If it starts with a
12654 // lower case letter we need to check for that case, because
12655 // the field name will be packed. FIXME.
12656 if (!Gogo::is_hidden_name(name)
12657 && name[0] >= 'a'
12658 && name[0] <= 'z')
12660 Named_object* gno = gogo->lookup_global(name.c_str());
12661 if (gno == no)
12662 name = gogo->pack_hidden_name(name, false);
12666 unsigned int index;
12667 const Struct_field* sf = st->find_local_field(name, &index);
12668 if (sf == NULL)
12670 error_at(name_expr->location(), "unknown field %qs in %qs",
12671 Gogo::message_name(name).c_str(),
12672 (type->named_type() != NULL
12673 ? type->named_type()->message_name().c_str()
12674 : "unnamed struct"));
12675 return Expression::make_error(location);
12677 if (vals[index] != NULL)
12679 error_at(name_expr->location(),
12680 "duplicate value for field %qs in %qs",
12681 Gogo::message_name(name).c_str(),
12682 (type->named_type() != NULL
12683 ? type->named_type()->message_name().c_str()
12684 : "unnamed struct"));
12685 return Expression::make_error(location);
12688 if (type->named_type() != NULL
12689 && type->named_type()->named_object()->package() != NULL
12690 && (Gogo::is_hidden_name(sf->field_name())
12691 || sf->is_embedded_builtin(gogo)))
12692 error_at(name_expr->location(),
12693 "assignment of unexported field %qs in %qs literal",
12694 Gogo::message_name(sf->field_name()).c_str(),
12695 type->named_type()->message_name().c_str());
12697 vals[index] = val;
12698 traverse_order->push_back(index);
12701 if (!this->all_are_names_)
12703 // This is a weird case like bug462 in the testsuite.
12704 if (external_expr == NULL)
12705 error_at(this->location(), "unknown field in %qs literal",
12706 (type->named_type() != NULL
12707 ? type->named_type()->message_name().c_str()
12708 : "unnamed struct"));
12709 else
12710 error_at(external_expr->location(), "unknown field %qs in %qs",
12711 external_no->message_name().c_str(),
12712 (type->named_type() != NULL
12713 ? type->named_type()->message_name().c_str()
12714 : "unnamed struct"));
12715 return Expression::make_error(location);
12718 Expression_list* list = new Expression_list;
12719 list->reserve(field_count);
12720 for (size_t i = 0; i < field_count; ++i)
12721 list->push_back(vals[i]);
12723 Struct_construction_expression* ret =
12724 new Struct_construction_expression(type, list, location);
12725 ret->set_traverse_order(traverse_order);
12726 return ret;
12729 // Used to sort an index/value array.
12731 class Index_value_compare
12733 public:
12734 bool
12735 operator()(const std::pair<unsigned long, Expression*>& a,
12736 const std::pair<unsigned long, Expression*>& b)
12737 { return a.first < b.first; }
12740 // Lower an array composite literal.
12742 Expression*
12743 Composite_literal_expression::lower_array(Type* type)
12745 Location location = this->location();
12746 if (this->vals_ == NULL || !this->has_keys_)
12747 return this->make_array(type, NULL, this->vals_);
12749 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
12750 indexes->reserve(this->vals_->size());
12751 bool indexes_out_of_order = false;
12752 Expression_list* vals = new Expression_list();
12753 vals->reserve(this->vals_->size());
12754 unsigned long index = 0;
12755 Expression_list::const_iterator p = this->vals_->begin();
12756 while (p != this->vals_->end())
12758 Expression* index_expr = *p;
12760 ++p;
12761 go_assert(p != this->vals_->end());
12762 Expression* val = *p;
12764 ++p;
12766 if (index_expr == NULL)
12768 if (!indexes->empty())
12769 indexes->push_back(index);
12771 else
12773 if (indexes->empty() && !vals->empty())
12775 for (size_t i = 0; i < vals->size(); ++i)
12776 indexes->push_back(i);
12779 Numeric_constant nc;
12780 if (!index_expr->numeric_constant_value(&nc))
12782 error_at(index_expr->location(),
12783 "index expression is not integer constant");
12784 return Expression::make_error(location);
12787 switch (nc.to_unsigned_long(&index))
12789 case Numeric_constant::NC_UL_VALID:
12790 break;
12791 case Numeric_constant::NC_UL_NOTINT:
12792 error_at(index_expr->location(),
12793 "index expression is not integer constant");
12794 return Expression::make_error(location);
12795 case Numeric_constant::NC_UL_NEGATIVE:
12796 error_at(index_expr->location(), "index expression is negative");
12797 return Expression::make_error(location);
12798 case Numeric_constant::NC_UL_BIG:
12799 error_at(index_expr->location(), "index value overflow");
12800 return Expression::make_error(location);
12801 default:
12802 go_unreachable();
12805 Named_type* ntype = Type::lookup_integer_type("int");
12806 Integer_type* inttype = ntype->integer_type();
12807 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12808 && index >> (inttype->bits() - 1) != 0)
12810 error_at(index_expr->location(), "index value overflow");
12811 return Expression::make_error(location);
12814 if (std::find(indexes->begin(), indexes->end(), index)
12815 != indexes->end())
12817 error_at(index_expr->location(), "duplicate value for index %lu",
12818 index);
12819 return Expression::make_error(location);
12822 if (!indexes->empty() && index < indexes->back())
12823 indexes_out_of_order = true;
12825 indexes->push_back(index);
12828 vals->push_back(val);
12830 ++index;
12833 if (indexes->empty())
12835 delete indexes;
12836 indexes = NULL;
12839 if (indexes_out_of_order)
12841 typedef std::vector<std::pair<unsigned long, Expression*> > V;
12843 V v;
12844 v.reserve(indexes->size());
12845 std::vector<unsigned long>::const_iterator pi = indexes->begin();
12846 for (Expression_list::const_iterator pe = vals->begin();
12847 pe != vals->end();
12848 ++pe, ++pi)
12849 v.push_back(std::make_pair(*pi, *pe));
12851 std::sort(v.begin(), v.end(), Index_value_compare());
12853 delete indexes;
12854 delete vals;
12855 indexes = new std::vector<unsigned long>();
12856 indexes->reserve(v.size());
12857 vals = new Expression_list();
12858 vals->reserve(v.size());
12860 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
12862 indexes->push_back(p->first);
12863 vals->push_back(p->second);
12867 return this->make_array(type, indexes, vals);
12870 // Actually build the array composite literal. This handles
12871 // [...]{...}.
12873 Expression*
12874 Composite_literal_expression::make_array(
12875 Type* type,
12876 const std::vector<unsigned long>* indexes,
12877 Expression_list* vals)
12879 Location location = this->location();
12880 Array_type* at = type->array_type();
12882 if (at->length() != NULL && at->length()->is_nil_expression())
12884 size_t size;
12885 if (vals == NULL)
12886 size = 0;
12887 else if (indexes != NULL)
12888 size = indexes->back() + 1;
12889 else
12891 size = vals->size();
12892 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
12893 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
12894 && size >> (it->bits() - 1) != 0)
12896 error_at(location, "too many elements in composite literal");
12897 return Expression::make_error(location);
12901 Expression* elen = Expression::make_integer_ul(size, NULL, location);
12902 at = Type::make_array_type(at->element_type(), elen);
12903 type = at;
12905 else if (at->length() != NULL
12906 && !at->length()->is_error_expression()
12907 && this->vals_ != NULL)
12909 Numeric_constant nc;
12910 unsigned long val;
12911 if (at->length()->numeric_constant_value(&nc)
12912 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
12914 if (indexes == NULL)
12916 if (this->vals_->size() > val)
12918 error_at(location, "too many elements in composite literal");
12919 return Expression::make_error(location);
12922 else
12924 unsigned long max = indexes->back();
12925 if (max >= val)
12927 error_at(location,
12928 ("some element keys in composite literal "
12929 "are out of range"));
12930 return Expression::make_error(location);
12936 if (at->length() != NULL)
12937 return new Fixed_array_construction_expression(type, indexes, vals,
12938 location);
12939 else
12940 return new Slice_construction_expression(type, indexes, vals, location);
12943 // Lower a map composite literal.
12945 Expression*
12946 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
12947 Statement_inserter* inserter,
12948 Type* type)
12950 Location location = this->location();
12951 if (this->vals_ != NULL)
12953 if (!this->has_keys_)
12955 error_at(location, "map composite literal must have keys");
12956 return Expression::make_error(location);
12959 for (Expression_list::iterator p = this->vals_->begin();
12960 p != this->vals_->end();
12961 p += 2)
12963 if (*p == NULL)
12965 ++p;
12966 error_at((*p)->location(),
12967 "map composite literal must have keys for every value");
12968 return Expression::make_error(location);
12970 // Make sure we have lowered the key; it may not have been
12971 // lowered in order to handle keys for struct composite
12972 // literals. Lower it now to get the right error message.
12973 if ((*p)->unknown_expression() != NULL)
12975 (*p)->unknown_expression()->clear_is_composite_literal_key();
12976 gogo->lower_expression(function, inserter, &*p);
12977 go_assert((*p)->is_error_expression());
12978 return Expression::make_error(location);
12983 return new Map_construction_expression(type, this->vals_, location);
12986 // Dump ast representation for a composite literal expression.
12988 void
12989 Composite_literal_expression::do_dump_expression(
12990 Ast_dump_context* ast_dump_context) const
12992 ast_dump_context->ostream() << "composite(";
12993 ast_dump_context->dump_type(this->type_);
12994 ast_dump_context->ostream() << ", {";
12995 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
12996 ast_dump_context->ostream() << "})";
12999 // Make a composite literal expression.
13001 Expression*
13002 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13003 Expression_list* vals, bool all_are_names,
13004 Location location)
13006 return new Composite_literal_expression(type, depth, has_keys, vals,
13007 all_are_names, location);
13010 // Return whether this expression is a composite literal.
13012 bool
13013 Expression::is_composite_literal() const
13015 switch (this->classification_)
13017 case EXPRESSION_COMPOSITE_LITERAL:
13018 case EXPRESSION_STRUCT_CONSTRUCTION:
13019 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13020 case EXPRESSION_SLICE_CONSTRUCTION:
13021 case EXPRESSION_MAP_CONSTRUCTION:
13022 return true;
13023 default:
13024 return false;
13028 // Return whether this expression is a composite literal which is not
13029 // constant.
13031 bool
13032 Expression::is_nonconstant_composite_literal() const
13034 switch (this->classification_)
13036 case EXPRESSION_STRUCT_CONSTRUCTION:
13038 const Struct_construction_expression *psce =
13039 static_cast<const Struct_construction_expression*>(this);
13040 return !psce->is_constant_struct();
13042 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13044 const Fixed_array_construction_expression *pace =
13045 static_cast<const Fixed_array_construction_expression*>(this);
13046 return !pace->is_constant_array();
13048 case EXPRESSION_SLICE_CONSTRUCTION:
13050 const Slice_construction_expression *pace =
13051 static_cast<const Slice_construction_expression*>(this);
13052 return !pace->is_constant_array();
13054 case EXPRESSION_MAP_CONSTRUCTION:
13055 return true;
13056 default:
13057 return false;
13061 // Return true if this is a variable or temporary_variable.
13063 bool
13064 Expression::is_variable() const
13066 switch (this->classification_)
13068 case EXPRESSION_VAR_REFERENCE:
13069 case EXPRESSION_TEMPORARY_REFERENCE:
13070 case EXPRESSION_SET_AND_USE_TEMPORARY:
13071 return true;
13072 default:
13073 return false;
13077 // Return true if this is a reference to a local variable.
13079 bool
13080 Expression::is_local_variable() const
13082 const Var_expression* ve = this->var_expression();
13083 if (ve == NULL)
13084 return false;
13085 const Named_object* no = ve->named_object();
13086 return (no->is_result_variable()
13087 || (no->is_variable() && !no->var_value()->is_global()));
13090 // Class Type_guard_expression.
13092 // Traversal.
13095 Type_guard_expression::do_traverse(Traverse* traverse)
13097 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13098 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13099 return TRAVERSE_EXIT;
13100 return TRAVERSE_CONTINUE;
13103 Expression*
13104 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13105 Statement_inserter* inserter)
13107 if (!this->expr_->is_variable())
13109 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13110 this->location());
13111 inserter->insert(temp);
13112 this->expr_ =
13113 Expression::make_temporary_reference(temp, this->location());
13115 return this;
13118 // Check types of a type guard expression. The expression must have
13119 // an interface type, but the actual type conversion is checked at run
13120 // time.
13122 void
13123 Type_guard_expression::do_check_types(Gogo*)
13125 Type* expr_type = this->expr_->type();
13126 if (expr_type->interface_type() == NULL)
13128 if (!expr_type->is_error() && !this->type_->is_error())
13129 this->report_error(_("type assertion only valid for interface types"));
13130 this->set_is_error();
13132 else if (this->type_->interface_type() == NULL)
13134 std::string reason;
13135 if (!expr_type->interface_type()->implements_interface(this->type_,
13136 &reason))
13138 if (!this->type_->is_error())
13140 if (reason.empty())
13141 this->report_error(_("impossible type assertion: "
13142 "type does not implement interface"));
13143 else
13144 error_at(this->location(),
13145 ("impossible type assertion: "
13146 "type does not implement interface (%s)"),
13147 reason.c_str());
13149 this->set_is_error();
13154 // Return the backend representation for a type guard expression.
13156 Bexpression*
13157 Type_guard_expression::do_get_backend(Translate_context* context)
13159 Expression* conversion;
13160 if (this->type_->interface_type() != NULL)
13161 conversion =
13162 Expression::convert_interface_to_interface(this->type_, this->expr_,
13163 true, this->location());
13164 else
13165 conversion =
13166 Expression::convert_for_assignment(context->gogo(), this->type_,
13167 this->expr_, this->location());
13169 return conversion->get_backend(context);
13172 // Dump ast representation for a type guard expression.
13174 void
13175 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13176 const
13178 this->expr_->dump_expression(ast_dump_context);
13179 ast_dump_context->ostream() << ".";
13180 ast_dump_context->dump_type(this->type_);
13183 // Make a type guard expression.
13185 Expression*
13186 Expression::make_type_guard(Expression* expr, Type* type,
13187 Location location)
13189 return new Type_guard_expression(expr, type, location);
13192 // Class Heap_expression.
13194 // Return the type of the expression stored on the heap.
13196 Type*
13197 Heap_expression::do_type()
13198 { return Type::make_pointer_type(this->expr_->type()); }
13200 // Return the backend representation for allocating an expression on the heap.
13202 Bexpression*
13203 Heap_expression::do_get_backend(Translate_context* context)
13205 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
13206 return context->backend()->error_expression();
13208 Location loc = this->location();
13209 Gogo* gogo = context->gogo();
13210 Btype* btype = this->type()->get_backend(gogo);
13211 Bexpression* space = Expression::make_allocation(this->expr_->type(),
13212 loc)->get_backend(context);
13214 Bstatement* decl;
13215 Named_object* fn = context->function();
13216 go_assert(fn != NULL);
13217 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13218 Bvariable* space_temp =
13219 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13220 space, true, loc, &decl);
13221 space = gogo->backend()->var_expression(space_temp, loc);
13222 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13223 Bexpression* ref =
13224 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
13226 Bexpression* bexpr = this->expr_->get_backend(context);
13227 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13228 decl = gogo->backend()->compound_statement(decl, assn);
13229 space = gogo->backend()->var_expression(space_temp, loc);
13230 return gogo->backend()->compound_expression(decl, space, loc);
13233 // Dump ast representation for a heap expression.
13235 void
13236 Heap_expression::do_dump_expression(
13237 Ast_dump_context* ast_dump_context) const
13239 ast_dump_context->ostream() << "&(";
13240 ast_dump_context->dump_expression(this->expr_);
13241 ast_dump_context->ostream() << ")";
13244 // Allocate an expression on the heap.
13246 Expression*
13247 Expression::make_heap_expression(Expression* expr, Location location)
13249 return new Heap_expression(expr, location);
13252 // Class Receive_expression.
13254 // Return the type of a receive expression.
13256 Type*
13257 Receive_expression::do_type()
13259 Channel_type* channel_type = this->channel_->type()->channel_type();
13260 if (channel_type == NULL)
13261 return Type::make_error_type();
13262 return channel_type->element_type();
13265 // Check types for a receive expression.
13267 void
13268 Receive_expression::do_check_types(Gogo*)
13270 Type* type = this->channel_->type();
13271 if (type->is_error())
13273 this->set_is_error();
13274 return;
13276 if (type->channel_type() == NULL)
13278 this->report_error(_("expected channel"));
13279 return;
13281 if (!type->channel_type()->may_receive())
13283 this->report_error(_("invalid receive on send-only channel"));
13284 return;
13288 // Flattening for receive expressions creates a temporary variable to store
13289 // received data in for receives.
13291 Expression*
13292 Receive_expression::do_flatten(Gogo*, Named_object*,
13293 Statement_inserter* inserter)
13295 Channel_type* channel_type = this->channel_->type()->channel_type();
13296 if (channel_type == NULL)
13298 go_assert(saw_errors());
13299 return this;
13302 Type* element_type = channel_type->element_type();
13303 if (this->temp_receiver_ == NULL)
13305 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13306 this->location());
13307 this->temp_receiver_->set_is_address_taken();
13308 inserter->insert(this->temp_receiver_);
13311 return this;
13314 // Get the backend representation for a receive expression.
13316 Bexpression*
13317 Receive_expression::do_get_backend(Translate_context* context)
13319 Location loc = this->location();
13321 Channel_type* channel_type = this->channel_->type()->channel_type();
13322 if (channel_type == NULL)
13324 go_assert(this->channel_->type()->is_error());
13325 return context->backend()->error_expression();
13327 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13329 Expression* recv_ref =
13330 Expression::make_temporary_reference(this->temp_receiver_, loc);
13331 Expression* recv_addr =
13332 Expression::make_temporary_reference(this->temp_receiver_, loc);
13333 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13334 Expression* recv =
13335 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13336 td, this->channel_, recv_addr);
13337 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
13340 // Dump ast representation for a receive expression.
13342 void
13343 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13345 ast_dump_context->ostream() << " <- " ;
13346 ast_dump_context->dump_expression(channel_);
13349 // Make a receive expression.
13351 Receive_expression*
13352 Expression::make_receive(Expression* channel, Location location)
13354 return new Receive_expression(channel, location);
13357 // An expression which evaluates to a pointer to the type descriptor
13358 // of a type.
13360 class Type_descriptor_expression : public Expression
13362 public:
13363 Type_descriptor_expression(Type* type, Location location)
13364 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13365 type_(type)
13368 protected:
13370 do_traverse(Traverse*);
13372 Type*
13373 do_type()
13374 { return Type::make_type_descriptor_ptr_type(); }
13376 bool
13377 do_is_immutable() const
13378 { return true; }
13380 void
13381 do_determine_type(const Type_context*)
13384 Expression*
13385 do_copy()
13386 { return this; }
13388 Bexpression*
13389 do_get_backend(Translate_context* context)
13391 return this->type_->type_descriptor_pointer(context->gogo(),
13392 this->location());
13395 void
13396 do_dump_expression(Ast_dump_context*) const;
13398 private:
13399 // The type for which this is the descriptor.
13400 Type* type_;
13404 Type_descriptor_expression::do_traverse(Traverse* traverse)
13406 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13407 return TRAVERSE_EXIT;
13408 return TRAVERSE_CONTINUE;
13411 // Dump ast representation for a type descriptor expression.
13413 void
13414 Type_descriptor_expression::do_dump_expression(
13415 Ast_dump_context* ast_dump_context) const
13417 ast_dump_context->dump_type(this->type_);
13420 // Make a type descriptor expression.
13422 Expression*
13423 Expression::make_type_descriptor(Type* type, Location location)
13425 return new Type_descriptor_expression(type, location);
13428 // An expression which evaluates to a pointer to the Garbage Collection symbol
13429 // of a type.
13431 class GC_symbol_expression : public Expression
13433 public:
13434 GC_symbol_expression(Type* type)
13435 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
13436 type_(type)
13439 protected:
13440 Type*
13441 do_type()
13442 { return Type::lookup_integer_type("uintptr"); }
13444 bool
13445 do_is_immutable() const
13446 { return true; }
13448 void
13449 do_determine_type(const Type_context*)
13452 Expression*
13453 do_copy()
13454 { return this; }
13456 Bexpression*
13457 do_get_backend(Translate_context* context)
13458 { return this->type_->gc_symbol_pointer(context->gogo()); }
13460 void
13461 do_dump_expression(Ast_dump_context*) const;
13463 private:
13464 // The type which this gc symbol describes.
13465 Type* type_;
13468 // Dump ast representation for a gc symbol expression.
13470 void
13471 GC_symbol_expression::do_dump_expression(
13472 Ast_dump_context* ast_dump_context) const
13474 ast_dump_context->ostream() << "gcdata(";
13475 ast_dump_context->dump_type(this->type_);
13476 ast_dump_context->ostream() << ")";
13479 // Make a gc symbol expression.
13481 Expression*
13482 Expression::make_gc_symbol(Type* type)
13484 return new GC_symbol_expression(type);
13487 // An expression which evaluates to some characteristic of a type.
13488 // This is only used to initialize fields of a type descriptor. Using
13489 // a new expression class is slightly inefficient but gives us a good
13490 // separation between the frontend and the middle-end with regard to
13491 // how types are laid out.
13493 class Type_info_expression : public Expression
13495 public:
13496 Type_info_expression(Type* type, Type_info type_info)
13497 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13498 type_(type), type_info_(type_info)
13501 protected:
13502 bool
13503 do_is_immutable() const
13504 { return true; }
13506 Type*
13507 do_type();
13509 void
13510 do_determine_type(const Type_context*)
13513 Expression*
13514 do_copy()
13515 { return this; }
13517 Bexpression*
13518 do_get_backend(Translate_context* context);
13520 void
13521 do_dump_expression(Ast_dump_context*) const;
13523 private:
13524 // The type for which we are getting information.
13525 Type* type_;
13526 // What information we want.
13527 Type_info type_info_;
13530 // The type is chosen to match what the type descriptor struct
13531 // expects.
13533 Type*
13534 Type_info_expression::do_type()
13536 switch (this->type_info_)
13538 case TYPE_INFO_SIZE:
13539 return Type::lookup_integer_type("uintptr");
13540 case TYPE_INFO_ALIGNMENT:
13541 case TYPE_INFO_FIELD_ALIGNMENT:
13542 return Type::lookup_integer_type("uint8");
13543 default:
13544 go_unreachable();
13548 // Return the backend representation for type information.
13550 Bexpression*
13551 Type_info_expression::do_get_backend(Translate_context* context)
13553 Btype* btype = this->type_->get_backend(context->gogo());
13554 Gogo* gogo = context->gogo();
13555 int64_t val;
13556 switch (this->type_info_)
13558 case TYPE_INFO_SIZE:
13559 val = gogo->backend()->type_size(btype);
13560 break;
13561 case TYPE_INFO_ALIGNMENT:
13562 val = gogo->backend()->type_alignment(btype);
13563 break;
13564 case TYPE_INFO_FIELD_ALIGNMENT:
13565 val = gogo->backend()->type_field_alignment(btype);
13566 break;
13567 default:
13568 go_unreachable();
13570 Expression* e = Expression::make_integer_int64(val, this->type(),
13571 this->location());
13572 return e->get_backend(context);
13575 // Dump ast representation for a type info expression.
13577 void
13578 Type_info_expression::do_dump_expression(
13579 Ast_dump_context* ast_dump_context) const
13581 ast_dump_context->ostream() << "typeinfo(";
13582 ast_dump_context->dump_type(this->type_);
13583 ast_dump_context->ostream() << ",";
13584 ast_dump_context->ostream() <<
13585 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13586 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13587 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13588 : "unknown");
13589 ast_dump_context->ostream() << ")";
13592 // Make a type info expression.
13594 Expression*
13595 Expression::make_type_info(Type* type, Type_info type_info)
13597 return new Type_info_expression(type, type_info);
13600 // An expression that evaluates to some characteristic of a slice.
13601 // This is used when indexing, bound-checking, or nil checking a slice.
13603 class Slice_info_expression : public Expression
13605 public:
13606 Slice_info_expression(Expression* slice, Slice_info slice_info,
13607 Location location)
13608 : Expression(EXPRESSION_SLICE_INFO, location),
13609 slice_(slice), slice_info_(slice_info)
13612 protected:
13613 Type*
13614 do_type();
13616 void
13617 do_determine_type(const Type_context*)
13620 Expression*
13621 do_copy()
13623 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
13624 this->location());
13627 Bexpression*
13628 do_get_backend(Translate_context* context);
13630 void
13631 do_dump_expression(Ast_dump_context*) const;
13633 void
13634 do_issue_nil_check()
13635 { this->slice_->issue_nil_check(); }
13637 private:
13638 // The slice for which we are getting information.
13639 Expression* slice_;
13640 // What information we want.
13641 Slice_info slice_info_;
13644 // Return the type of the slice info.
13646 Type*
13647 Slice_info_expression::do_type()
13649 switch (this->slice_info_)
13651 case SLICE_INFO_VALUE_POINTER:
13652 return Type::make_pointer_type(
13653 this->slice_->type()->array_type()->element_type());
13654 case SLICE_INFO_LENGTH:
13655 case SLICE_INFO_CAPACITY:
13656 return Type::lookup_integer_type("int");
13657 default:
13658 go_unreachable();
13662 // Return the backend information for slice information.
13664 Bexpression*
13665 Slice_info_expression::do_get_backend(Translate_context* context)
13667 Gogo* gogo = context->gogo();
13668 Bexpression* bslice = this->slice_->get_backend(context);
13669 switch (this->slice_info_)
13671 case SLICE_INFO_VALUE_POINTER:
13672 case SLICE_INFO_LENGTH:
13673 case SLICE_INFO_CAPACITY:
13674 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
13675 this->location());
13676 break;
13677 default:
13678 go_unreachable();
13682 // Dump ast representation for a type info expression.
13684 void
13685 Slice_info_expression::do_dump_expression(
13686 Ast_dump_context* ast_dump_context) const
13688 ast_dump_context->ostream() << "sliceinfo(";
13689 this->slice_->dump_expression(ast_dump_context);
13690 ast_dump_context->ostream() << ",";
13691 ast_dump_context->ostream() <<
13692 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
13693 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
13694 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
13695 : "unknown");
13696 ast_dump_context->ostream() << ")";
13699 // Make a slice info expression.
13701 Expression*
13702 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
13703 Location location)
13705 return new Slice_info_expression(slice, slice_info, location);
13708 // An expression that represents a slice value: a struct with value pointer,
13709 // length, and capacity fields.
13711 class Slice_value_expression : public Expression
13713 public:
13714 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
13715 Expression* cap, Location location)
13716 : Expression(EXPRESSION_SLICE_VALUE, location),
13717 type_(type), valptr_(valptr), len_(len), cap_(cap)
13720 protected:
13722 do_traverse(Traverse*);
13724 Type*
13725 do_type()
13726 { return this->type_; }
13728 void
13729 do_determine_type(const Type_context*)
13730 { go_unreachable(); }
13732 Expression*
13733 do_copy()
13735 return new Slice_value_expression(this->type_, this->valptr_->copy(),
13736 this->len_->copy(), this->cap_->copy(),
13737 this->location());
13740 Bexpression*
13741 do_get_backend(Translate_context* context);
13743 void
13744 do_dump_expression(Ast_dump_context*) const;
13746 private:
13747 // The type of the slice value.
13748 Type* type_;
13749 // The pointer to the values in the slice.
13750 Expression* valptr_;
13751 // The length of the slice.
13752 Expression* len_;
13753 // The capacity of the slice.
13754 Expression* cap_;
13758 Slice_value_expression::do_traverse(Traverse* traverse)
13760 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
13761 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
13762 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
13763 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
13764 return TRAVERSE_EXIT;
13765 return TRAVERSE_CONTINUE;
13768 Bexpression*
13769 Slice_value_expression::do_get_backend(Translate_context* context)
13771 std::vector<Bexpression*> vals(3);
13772 vals[0] = this->valptr_->get_backend(context);
13773 vals[1] = this->len_->get_backend(context);
13774 vals[2] = this->cap_->get_backend(context);
13776 Gogo* gogo = context->gogo();
13777 Btype* btype = this->type_->get_backend(gogo);
13778 return gogo->backend()->constructor_expression(btype, vals, this->location());
13781 void
13782 Slice_value_expression::do_dump_expression(
13783 Ast_dump_context* ast_dump_context) const
13785 ast_dump_context->ostream() << "slicevalue(";
13786 ast_dump_context->ostream() << "values: ";
13787 this->valptr_->dump_expression(ast_dump_context);
13788 ast_dump_context->ostream() << ", length: ";
13789 this->len_->dump_expression(ast_dump_context);
13790 ast_dump_context->ostream() << ", capacity: ";
13791 this->cap_->dump_expression(ast_dump_context);
13792 ast_dump_context->ostream() << ")";
13795 Expression*
13796 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
13797 Expression* cap, Location location)
13799 go_assert(at->is_slice_type());
13800 return new Slice_value_expression(at, valptr, len, cap, location);
13803 // An expression that evaluates to some characteristic of a non-empty interface.
13804 // This is used to access the method table or underlying object of an interface.
13806 class Interface_info_expression : public Expression
13808 public:
13809 Interface_info_expression(Expression* iface, Interface_info iface_info,
13810 Location location)
13811 : Expression(EXPRESSION_INTERFACE_INFO, location),
13812 iface_(iface), iface_info_(iface_info)
13815 protected:
13816 Type*
13817 do_type();
13819 void
13820 do_determine_type(const Type_context*)
13823 Expression*
13824 do_copy()
13826 return new Interface_info_expression(this->iface_->copy(),
13827 this->iface_info_, this->location());
13830 Bexpression*
13831 do_get_backend(Translate_context* context);
13833 void
13834 do_dump_expression(Ast_dump_context*) const;
13836 void
13837 do_issue_nil_check()
13838 { this->iface_->issue_nil_check(); }
13840 private:
13841 // The interface for which we are getting information.
13842 Expression* iface_;
13843 // What information we want.
13844 Interface_info iface_info_;
13847 // Return the type of the interface info.
13849 Type*
13850 Interface_info_expression::do_type()
13852 switch (this->iface_info_)
13854 case INTERFACE_INFO_METHODS:
13856 Type* pdt = Type::make_type_descriptor_ptr_type();
13857 if (this->iface_->type()->interface_type()->is_empty())
13858 return pdt;
13860 Location loc = this->location();
13861 Struct_field_list* sfl = new Struct_field_list();
13862 sfl->push_back(
13863 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
13865 Interface_type* itype = this->iface_->type()->interface_type();
13866 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
13867 p != itype->methods()->end();
13868 ++p)
13870 Function_type* ft = p->type()->function_type();
13871 go_assert(ft->receiver() == NULL);
13873 const Typed_identifier_list* params = ft->parameters();
13874 Typed_identifier_list* mparams = new Typed_identifier_list();
13875 if (params != NULL)
13876 mparams->reserve(params->size() + 1);
13877 Type* vt = Type::make_pointer_type(Type::make_void_type());
13878 mparams->push_back(Typed_identifier("", vt, ft->location()));
13879 if (params != NULL)
13881 for (Typed_identifier_list::const_iterator pp = params->begin();
13882 pp != params->end();
13883 ++pp)
13884 mparams->push_back(*pp);
13887 Typed_identifier_list* mresults = (ft->results() == NULL
13888 ? NULL
13889 : ft->results()->copy());
13890 Backend_function_type* mft =
13891 Type::make_backend_function_type(NULL, mparams, mresults,
13892 ft->location());
13894 std::string fname = Gogo::unpack_hidden_name(p->name());
13895 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
13898 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
13900 case INTERFACE_INFO_OBJECT:
13901 return Type::make_pointer_type(Type::make_void_type());
13902 default:
13903 go_unreachable();
13907 // Return the backend representation for interface information.
13909 Bexpression*
13910 Interface_info_expression::do_get_backend(Translate_context* context)
13912 Gogo* gogo = context->gogo();
13913 Bexpression* biface = this->iface_->get_backend(context);
13914 switch (this->iface_info_)
13916 case INTERFACE_INFO_METHODS:
13917 case INTERFACE_INFO_OBJECT:
13918 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
13919 this->location());
13920 break;
13921 default:
13922 go_unreachable();
13926 // Dump ast representation for an interface info expression.
13928 void
13929 Interface_info_expression::do_dump_expression(
13930 Ast_dump_context* ast_dump_context) const
13932 bool is_empty = this->iface_->type()->interface_type()->is_empty();
13933 ast_dump_context->ostream() << "interfaceinfo(";
13934 this->iface_->dump_expression(ast_dump_context);
13935 ast_dump_context->ostream() << ",";
13936 ast_dump_context->ostream() <<
13937 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
13938 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
13939 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
13940 : "unknown");
13941 ast_dump_context->ostream() << ")";
13944 // Make an interface info expression.
13946 Expression*
13947 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
13948 Location location)
13950 return new Interface_info_expression(iface, iface_info, location);
13953 // An expression that represents an interface value. The first field is either
13954 // a type descriptor for an empty interface or a pointer to the interface method
13955 // table for a non-empty interface. The second field is always the object.
13957 class Interface_value_expression : public Expression
13959 public:
13960 Interface_value_expression(Type* type, Expression* first_field,
13961 Expression* obj, Location location)
13962 : Expression(EXPRESSION_INTERFACE_VALUE, location),
13963 type_(type), first_field_(first_field), obj_(obj)
13966 protected:
13968 do_traverse(Traverse*);
13970 Type*
13971 do_type()
13972 { return this->type_; }
13974 void
13975 do_determine_type(const Type_context*)
13976 { go_unreachable(); }
13978 Expression*
13979 do_copy()
13981 return new Interface_value_expression(this->type_,
13982 this->first_field_->copy(),
13983 this->obj_->copy(), this->location());
13986 Bexpression*
13987 do_get_backend(Translate_context* context);
13989 void
13990 do_dump_expression(Ast_dump_context*) const;
13992 private:
13993 // The type of the interface value.
13994 Type* type_;
13995 // The first field of the interface (either a type descriptor or a pointer
13996 // to the method table.
13997 Expression* first_field_;
13998 // The underlying object of the interface.
13999 Expression* obj_;
14003 Interface_value_expression::do_traverse(Traverse* traverse)
14005 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14006 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14007 return TRAVERSE_EXIT;
14008 return TRAVERSE_CONTINUE;
14011 Bexpression*
14012 Interface_value_expression::do_get_backend(Translate_context* context)
14014 std::vector<Bexpression*> vals(2);
14015 vals[0] = this->first_field_->get_backend(context);
14016 vals[1] = this->obj_->get_backend(context);
14018 Gogo* gogo = context->gogo();
14019 Btype* btype = this->type_->get_backend(gogo);
14020 return gogo->backend()->constructor_expression(btype, vals, this->location());
14023 void
14024 Interface_value_expression::do_dump_expression(
14025 Ast_dump_context* ast_dump_context) const
14027 ast_dump_context->ostream() << "interfacevalue(";
14028 ast_dump_context->ostream() <<
14029 (this->type_->interface_type()->is_empty()
14030 ? "type_descriptor: "
14031 : "methods: ");
14032 this->first_field_->dump_expression(ast_dump_context);
14033 ast_dump_context->ostream() << ", object: ";
14034 this->obj_->dump_expression(ast_dump_context);
14035 ast_dump_context->ostream() << ")";
14038 Expression*
14039 Expression::make_interface_value(Type* type, Expression* first_value,
14040 Expression* object, Location location)
14042 return new Interface_value_expression(type, first_value, object, location);
14045 // An interface method table for a pair of types: an interface type and a type
14046 // that implements that interface.
14048 class Interface_mtable_expression : public Expression
14050 public:
14051 Interface_mtable_expression(Interface_type* itype, Type* type,
14052 bool is_pointer, Location location)
14053 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14054 itype_(itype), type_(type), is_pointer_(is_pointer),
14055 method_table_type_(NULL), bvar_(NULL)
14058 protected:
14060 do_traverse(Traverse*);
14062 Type*
14063 do_type();
14065 bool
14066 is_immutable() const
14067 { return true; }
14069 void
14070 do_determine_type(const Type_context*)
14071 { go_unreachable(); }
14073 Expression*
14074 do_copy()
14076 return new Interface_mtable_expression(this->itype_, this->type_,
14077 this->is_pointer_, this->location());
14080 bool
14081 do_is_addressable() const
14082 { return true; }
14084 Bexpression*
14085 do_get_backend(Translate_context* context);
14087 void
14088 do_dump_expression(Ast_dump_context*) const;
14090 private:
14091 // The interface type for which the methods are defined.
14092 Interface_type* itype_;
14093 // The type to construct the interface method table for.
14094 Type* type_;
14095 // Whether this table contains the method set for the receiver type or the
14096 // pointer receiver type.
14097 bool is_pointer_;
14098 // The type of the method table.
14099 Type* method_table_type_;
14100 // The backend variable that refers to the interface method table.
14101 Bvariable* bvar_;
14105 Interface_mtable_expression::do_traverse(Traverse* traverse)
14107 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14108 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14109 return TRAVERSE_EXIT;
14110 return TRAVERSE_CONTINUE;
14113 Type*
14114 Interface_mtable_expression::do_type()
14116 if (this->method_table_type_ != NULL)
14117 return this->method_table_type_;
14119 const Typed_identifier_list* interface_methods = this->itype_->methods();
14120 go_assert(!interface_methods->empty());
14122 Struct_field_list* sfl = new Struct_field_list;
14123 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14124 this->location());
14125 sfl->push_back(Struct_field(tid));
14126 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14127 p != interface_methods->end();
14128 ++p)
14129 sfl->push_back(Struct_field(*p));
14130 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14131 return this->method_table_type_;
14134 Bexpression*
14135 Interface_mtable_expression::do_get_backend(Translate_context* context)
14137 Gogo* gogo = context->gogo();
14138 Location loc = Linemap::predeclared_location();
14139 if (this->bvar_ != NULL)
14140 return gogo->backend()->var_expression(this->bvar_, this->location());
14142 const Typed_identifier_list* interface_methods = this->itype_->methods();
14143 go_assert(!interface_methods->empty());
14145 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14146 + this->itype_->mangled_name(gogo)
14147 + "__"
14148 + this->type_->mangled_name(gogo));
14150 // See whether this interface has any hidden methods.
14151 bool has_hidden_methods = false;
14152 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14153 p != interface_methods->end();
14154 ++p)
14156 if (Gogo::is_hidden_name(p->name()))
14158 has_hidden_methods = true;
14159 break;
14163 // We already know that the named type is convertible to the
14164 // interface. If the interface has hidden methods, and the named
14165 // type is defined in a different package, then the interface
14166 // conversion table will be defined by that other package.
14167 if (has_hidden_methods
14168 && this->type_->named_type() != NULL
14169 && this->type_->named_type()->named_object()->package() != NULL)
14171 Btype* btype = this->type()->get_backend(gogo);
14172 this->bvar_ =
14173 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14174 return gogo->backend()->var_expression(this->bvar_, this->location());
14177 // The first element is the type descriptor.
14178 Type* td_type;
14179 if (!this->is_pointer_)
14180 td_type = this->type_;
14181 else
14182 td_type = Type::make_pointer_type(this->type_);
14184 // Build an interface method table for a type: a type descriptor followed by a
14185 // list of function pointers, one for each interface method. This is used for
14186 // interfaces.
14187 Expression_list* svals = new Expression_list();
14188 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14190 Named_type* nt = this->type_->named_type();
14191 Struct_type* st = this->type_->struct_type();
14192 go_assert(nt != NULL || st != NULL);
14194 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14195 p != interface_methods->end();
14196 ++p)
14198 bool is_ambiguous;
14199 Method* m;
14200 if (nt != NULL)
14201 m = nt->method_function(p->name(), &is_ambiguous);
14202 else
14203 m = st->method_function(p->name(), &is_ambiguous);
14204 go_assert(m != NULL);
14205 Named_object* no = m->named_object();
14207 go_assert(no->is_function() || no->is_function_declaration());
14208 svals->push_back(Expression::make_func_code_reference(no, loc));
14211 Btype* btype = this->type()->get_backend(gogo);
14212 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14213 svals, loc);
14214 Bexpression* ctor = mtable->get_backend(context);
14216 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14217 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14218 !is_public, btype, loc);
14219 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14220 !is_public, btype, loc, ctor);
14221 return gogo->backend()->var_expression(this->bvar_, loc);
14224 void
14225 Interface_mtable_expression::do_dump_expression(
14226 Ast_dump_context* ast_dump_context) const
14228 ast_dump_context->ostream() << "__go_"
14229 << (this->is_pointer_ ? "pimt__" : "imt_");
14230 ast_dump_context->dump_type(this->itype_);
14231 ast_dump_context->ostream() << "__";
14232 ast_dump_context->dump_type(this->type_);
14235 Expression*
14236 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14237 bool is_pointer, Location location)
14239 return new Interface_mtable_expression(itype, type, is_pointer, location);
14242 // An expression which evaluates to the offset of a field within a
14243 // struct. This, like Type_info_expression, q.v., is only used to
14244 // initialize fields of a type descriptor.
14246 class Struct_field_offset_expression : public Expression
14248 public:
14249 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14250 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14251 Linemap::predeclared_location()),
14252 type_(type), field_(field)
14255 protected:
14256 bool
14257 do_is_immutable() const
14258 { return true; }
14260 Type*
14261 do_type()
14262 { return Type::lookup_integer_type("uintptr"); }
14264 void
14265 do_determine_type(const Type_context*)
14268 Expression*
14269 do_copy()
14270 { return this; }
14272 Bexpression*
14273 do_get_backend(Translate_context* context);
14275 void
14276 do_dump_expression(Ast_dump_context*) const;
14278 private:
14279 // The type of the struct.
14280 Struct_type* type_;
14281 // The field.
14282 const Struct_field* field_;
14285 // Return the backend representation for a struct field offset.
14287 Bexpression*
14288 Struct_field_offset_expression::do_get_backend(Translate_context* context)
14290 const Struct_field_list* fields = this->type_->fields();
14291 Struct_field_list::const_iterator p;
14292 unsigned i = 0;
14293 for (p = fields->begin();
14294 p != fields->end();
14295 ++p, ++i)
14296 if (&*p == this->field_)
14297 break;
14298 go_assert(&*p == this->field_);
14300 Gogo* gogo = context->gogo();
14301 Btype* btype = this->type_->get_backend(gogo);
14303 int64_t offset = gogo->backend()->type_field_offset(btype, i);
14304 Type* uptr_type = Type::lookup_integer_type("uintptr");
14305 Expression* ret =
14306 Expression::make_integer_int64(offset, uptr_type,
14307 Linemap::predeclared_location());
14308 return ret->get_backend(context);
14311 // Dump ast representation for a struct field offset expression.
14313 void
14314 Struct_field_offset_expression::do_dump_expression(
14315 Ast_dump_context* ast_dump_context) const
14317 ast_dump_context->ostream() << "unsafe.Offsetof(";
14318 ast_dump_context->dump_type(this->type_);
14319 ast_dump_context->ostream() << '.';
14320 ast_dump_context->ostream() <<
14321 Gogo::message_name(this->field_->field_name());
14322 ast_dump_context->ostream() << ")";
14325 // Make an expression for a struct field offset.
14327 Expression*
14328 Expression::make_struct_field_offset(Struct_type* type,
14329 const Struct_field* field)
14331 return new Struct_field_offset_expression(type, field);
14334 // An expression which evaluates to a pointer to the map descriptor of
14335 // a map type.
14337 class Map_descriptor_expression : public Expression
14339 public:
14340 Map_descriptor_expression(Map_type* type, Location location)
14341 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14342 type_(type)
14345 protected:
14346 Type*
14347 do_type()
14348 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14350 void
14351 do_determine_type(const Type_context*)
14354 Expression*
14355 do_copy()
14356 { return this; }
14358 Bexpression*
14359 do_get_backend(Translate_context* context)
14361 return this->type_->map_descriptor_pointer(context->gogo(),
14362 this->location());
14365 void
14366 do_dump_expression(Ast_dump_context*) const;
14368 private:
14369 // The type for which this is the descriptor.
14370 Map_type* type_;
14373 // Dump ast representation for a map descriptor expression.
14375 void
14376 Map_descriptor_expression::do_dump_expression(
14377 Ast_dump_context* ast_dump_context) const
14379 ast_dump_context->ostream() << "map_descriptor(";
14380 ast_dump_context->dump_type(this->type_);
14381 ast_dump_context->ostream() << ")";
14384 // Make a map descriptor expression.
14386 Expression*
14387 Expression::make_map_descriptor(Map_type* type, Location location)
14389 return new Map_descriptor_expression(type, location);
14392 // An expression which evaluates to the address of an unnamed label.
14394 class Label_addr_expression : public Expression
14396 public:
14397 Label_addr_expression(Label* label, Location location)
14398 : Expression(EXPRESSION_LABEL_ADDR, location),
14399 label_(label)
14402 protected:
14403 Type*
14404 do_type()
14405 { return Type::make_pointer_type(Type::make_void_type()); }
14407 void
14408 do_determine_type(const Type_context*)
14411 Expression*
14412 do_copy()
14413 { return new Label_addr_expression(this->label_, this->location()); }
14415 Bexpression*
14416 do_get_backend(Translate_context* context)
14417 { return this->label_->get_addr(context, this->location()); }
14419 void
14420 do_dump_expression(Ast_dump_context* ast_dump_context) const
14421 { ast_dump_context->ostream() << this->label_->name(); }
14423 private:
14424 // The label whose address we are taking.
14425 Label* label_;
14428 // Make an expression for the address of an unnamed label.
14430 Expression*
14431 Expression::make_label_addr(Label* label, Location location)
14433 return new Label_addr_expression(label, location);
14436 // Class Conditional_expression.
14438 // Traversal.
14441 Conditional_expression::do_traverse(Traverse* traverse)
14443 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14444 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14445 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14446 return TRAVERSE_EXIT;
14447 return TRAVERSE_CONTINUE;
14450 // Return the type of the conditional expression.
14452 Type*
14453 Conditional_expression::do_type()
14455 Type* result_type = Type::make_void_type();
14456 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
14457 NULL))
14458 result_type = this->then_->type();
14459 else if (this->then_->is_nil_expression()
14460 || this->else_->is_nil_expression())
14461 result_type = (!this->then_->is_nil_expression()
14462 ? this->then_->type()
14463 : this->else_->type());
14464 return result_type;
14467 // Determine type for a conditional expression.
14469 void
14470 Conditional_expression::do_determine_type(const Type_context* context)
14472 this->cond_->determine_type_no_context();
14473 this->then_->determine_type(context);
14474 this->else_->determine_type(context);
14477 // Get the backend representation of a conditional expression.
14479 Bexpression*
14480 Conditional_expression::do_get_backend(Translate_context* context)
14482 Gogo* gogo = context->gogo();
14483 Btype* result_btype = this->type()->get_backend(gogo);
14484 Bexpression* cond = this->cond_->get_backend(context);
14485 Bexpression* then = this->then_->get_backend(context);
14486 Bexpression* belse = this->else_->get_backend(context);
14487 return gogo->backend()->conditional_expression(result_btype, cond, then,
14488 belse, this->location());
14491 // Dump ast representation of a conditional expression.
14493 void
14494 Conditional_expression::do_dump_expression(
14495 Ast_dump_context* ast_dump_context) const
14497 ast_dump_context->ostream() << "(";
14498 ast_dump_context->dump_expression(this->cond_);
14499 ast_dump_context->ostream() << " ? ";
14500 ast_dump_context->dump_expression(this->then_);
14501 ast_dump_context->ostream() << " : ";
14502 ast_dump_context->dump_expression(this->else_);
14503 ast_dump_context->ostream() << ") ";
14506 // Make a conditional expression.
14508 Expression*
14509 Expression::make_conditional(Expression* cond, Expression* then,
14510 Expression* else_expr, Location location)
14512 return new Conditional_expression(cond, then, else_expr, location);
14515 // Class Compound_expression.
14517 // Traversal.
14520 Compound_expression::do_traverse(Traverse* traverse)
14522 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
14523 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
14524 return TRAVERSE_EXIT;
14525 return TRAVERSE_CONTINUE;
14528 // Return the type of the compound expression.
14530 Type*
14531 Compound_expression::do_type()
14533 return this->expr_->type();
14536 // Determine type for a compound expression.
14538 void
14539 Compound_expression::do_determine_type(const Type_context* context)
14541 this->init_->determine_type_no_context();
14542 this->expr_->determine_type(context);
14545 // Get the backend representation of a compound expression.
14547 Bexpression*
14548 Compound_expression::do_get_backend(Translate_context* context)
14550 Gogo* gogo = context->gogo();
14551 Bexpression* binit = this->init_->get_backend(context);
14552 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
14553 Bexpression* bexpr = this->expr_->get_backend(context);
14554 return gogo->backend()->compound_expression(init_stmt, bexpr,
14555 this->location());
14558 // Dump ast representation of a conditional expression.
14560 void
14561 Compound_expression::do_dump_expression(
14562 Ast_dump_context* ast_dump_context) const
14564 ast_dump_context->ostream() << "(";
14565 ast_dump_context->dump_expression(this->init_);
14566 ast_dump_context->ostream() << ",";
14567 ast_dump_context->dump_expression(this->expr_);
14568 ast_dump_context->ostream() << ") ";
14571 // Make a compound expression.
14573 Expression*
14574 Expression::make_compound(Expression* init, Expression* expr, Location location)
14576 return new Compound_expression(init, expr, location);
14579 // Import an expression. This comes at the end in order to see the
14580 // various class definitions.
14582 Expression*
14583 Expression::import_expression(Import* imp)
14585 int c = imp->peek_char();
14586 if (imp->match_c_string("- ")
14587 || imp->match_c_string("! ")
14588 || imp->match_c_string("^ "))
14589 return Unary_expression::do_import(imp);
14590 else if (c == '(')
14591 return Binary_expression::do_import(imp);
14592 else if (imp->match_c_string("true")
14593 || imp->match_c_string("false"))
14594 return Boolean_expression::do_import(imp);
14595 else if (c == '"')
14596 return String_expression::do_import(imp);
14597 else if (c == '-' || (c >= '0' && c <= '9'))
14599 // This handles integers, floats and complex constants.
14600 return Integer_expression::do_import(imp);
14602 else if (imp->match_c_string("nil"))
14603 return Nil_expression::do_import(imp);
14604 else if (imp->match_c_string("convert"))
14605 return Type_conversion_expression::do_import(imp);
14606 else
14608 error_at(imp->location(), "import error: expected expression");
14609 return Expression::make_error(imp->location());
14613 // Class Expression_list.
14615 // Traverse the list.
14618 Expression_list::traverse(Traverse* traverse)
14620 for (Expression_list::iterator p = this->begin();
14621 p != this->end();
14622 ++p)
14624 if (*p != NULL)
14626 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
14627 return TRAVERSE_EXIT;
14630 return TRAVERSE_CONTINUE;
14633 // Copy the list.
14635 Expression_list*
14636 Expression_list::copy()
14638 Expression_list* ret = new Expression_list();
14639 for (Expression_list::iterator p = this->begin();
14640 p != this->end();
14641 ++p)
14643 if (*p == NULL)
14644 ret->push_back(NULL);
14645 else
14646 ret->push_back((*p)->copy());
14648 return ret;
14651 // Return whether an expression list has an error expression.
14653 bool
14654 Expression_list::contains_error() const
14656 for (Expression_list::const_iterator p = this->begin();
14657 p != this->end();
14658 ++p)
14659 if (*p != NULL && (*p)->is_error_expression())
14660 return true;
14661 return false;
14664 // Class Numeric_constant.
14666 // Destructor.
14668 Numeric_constant::~Numeric_constant()
14670 this->clear();
14673 // Copy constructor.
14675 Numeric_constant::Numeric_constant(const Numeric_constant& a)
14676 : classification_(a.classification_), type_(a.type_)
14678 switch (a.classification_)
14680 case NC_INVALID:
14681 break;
14682 case NC_INT:
14683 case NC_RUNE:
14684 mpz_init_set(this->u_.int_val, a.u_.int_val);
14685 break;
14686 case NC_FLOAT:
14687 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14688 break;
14689 case NC_COMPLEX:
14690 mpc_init2(this->u_.complex_val, mpc_precision);
14691 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
14692 break;
14693 default:
14694 go_unreachable();
14698 // Assignment operator.
14700 Numeric_constant&
14701 Numeric_constant::operator=(const Numeric_constant& a)
14703 this->clear();
14704 this->classification_ = a.classification_;
14705 this->type_ = a.type_;
14706 switch (a.classification_)
14708 case NC_INVALID:
14709 break;
14710 case NC_INT:
14711 case NC_RUNE:
14712 mpz_init_set(this->u_.int_val, a.u_.int_val);
14713 break;
14714 case NC_FLOAT:
14715 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14716 break;
14717 case NC_COMPLEX:
14718 mpc_init2(this->u_.complex_val, mpc_precision);
14719 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
14720 break;
14721 default:
14722 go_unreachable();
14724 return *this;
14727 // Clear the contents.
14729 void
14730 Numeric_constant::clear()
14732 switch (this->classification_)
14734 case NC_INVALID:
14735 break;
14736 case NC_INT:
14737 case NC_RUNE:
14738 mpz_clear(this->u_.int_val);
14739 break;
14740 case NC_FLOAT:
14741 mpfr_clear(this->u_.float_val);
14742 break;
14743 case NC_COMPLEX:
14744 mpc_clear(this->u_.complex_val);
14745 break;
14746 default:
14747 go_unreachable();
14749 this->classification_ = NC_INVALID;
14752 // Set to an unsigned long value.
14754 void
14755 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
14757 this->clear();
14758 this->classification_ = NC_INT;
14759 this->type_ = type;
14760 mpz_init_set_ui(this->u_.int_val, val);
14763 // Set to an integer value.
14765 void
14766 Numeric_constant::set_int(Type* type, const mpz_t val)
14768 this->clear();
14769 this->classification_ = NC_INT;
14770 this->type_ = type;
14771 mpz_init_set(this->u_.int_val, val);
14774 // Set to a rune value.
14776 void
14777 Numeric_constant::set_rune(Type* type, const mpz_t val)
14779 this->clear();
14780 this->classification_ = NC_RUNE;
14781 this->type_ = type;
14782 mpz_init_set(this->u_.int_val, val);
14785 // Set to a floating point value.
14787 void
14788 Numeric_constant::set_float(Type* type, const mpfr_t val)
14790 this->clear();
14791 this->classification_ = NC_FLOAT;
14792 this->type_ = type;
14793 // Numeric constants do not have negative zero values, so remove
14794 // them here. They also don't have infinity or NaN values, but we
14795 // should never see them here.
14796 if (mpfr_zero_p(val))
14797 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
14798 else
14799 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
14802 // Set to a complex value.
14804 void
14805 Numeric_constant::set_complex(Type* type, const mpc_t val)
14807 this->clear();
14808 this->classification_ = NC_COMPLEX;
14809 this->type_ = type;
14810 mpc_init2(this->u_.complex_val, mpc_precision);
14811 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
14814 // Get an int value.
14816 void
14817 Numeric_constant::get_int(mpz_t* val) const
14819 go_assert(this->is_int());
14820 mpz_init_set(*val, this->u_.int_val);
14823 // Get a rune value.
14825 void
14826 Numeric_constant::get_rune(mpz_t* val) const
14828 go_assert(this->is_rune());
14829 mpz_init_set(*val, this->u_.int_val);
14832 // Get a floating point value.
14834 void
14835 Numeric_constant::get_float(mpfr_t* val) const
14837 go_assert(this->is_float());
14838 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
14841 // Get a complex value.
14843 void
14844 Numeric_constant::get_complex(mpc_t* val) const
14846 go_assert(this->is_complex());
14847 mpc_init2(*val, mpc_precision);
14848 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
14851 // Express value as unsigned long if possible.
14853 Numeric_constant::To_unsigned_long
14854 Numeric_constant::to_unsigned_long(unsigned long* val) const
14856 switch (this->classification_)
14858 case NC_INT:
14859 case NC_RUNE:
14860 return this->mpz_to_unsigned_long(this->u_.int_val, val);
14861 case NC_FLOAT:
14862 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
14863 case NC_COMPLEX:
14864 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
14865 return NC_UL_NOTINT;
14866 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
14867 val);
14868 default:
14869 go_unreachable();
14873 // Express integer value as unsigned long if possible.
14875 Numeric_constant::To_unsigned_long
14876 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
14877 unsigned long *val) const
14879 if (mpz_sgn(ival) < 0)
14880 return NC_UL_NEGATIVE;
14881 unsigned long ui = mpz_get_ui(ival);
14882 if (mpz_cmp_ui(ival, ui) != 0)
14883 return NC_UL_BIG;
14884 *val = ui;
14885 return NC_UL_VALID;
14888 // Express floating point value as unsigned long if possible.
14890 Numeric_constant::To_unsigned_long
14891 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
14892 unsigned long *val) const
14894 if (!mpfr_integer_p(fval))
14895 return NC_UL_NOTINT;
14896 mpz_t ival;
14897 mpz_init(ival);
14898 mpfr_get_z(ival, fval, GMP_RNDN);
14899 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
14900 mpz_clear(ival);
14901 return ret;
14904 // Convert value to integer if possible.
14906 bool
14907 Numeric_constant::to_int(mpz_t* val) const
14909 switch (this->classification_)
14911 case NC_INT:
14912 case NC_RUNE:
14913 mpz_init_set(*val, this->u_.int_val);
14914 return true;
14915 case NC_FLOAT:
14916 if (!mpfr_integer_p(this->u_.float_val))
14917 return false;
14918 mpz_init(*val);
14919 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
14920 return true;
14921 case NC_COMPLEX:
14922 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
14923 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
14924 return false;
14925 mpz_init(*val);
14926 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
14927 return true;
14928 default:
14929 go_unreachable();
14933 // Convert value to floating point if possible.
14935 bool
14936 Numeric_constant::to_float(mpfr_t* val) const
14938 switch (this->classification_)
14940 case NC_INT:
14941 case NC_RUNE:
14942 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
14943 return true;
14944 case NC_FLOAT:
14945 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
14946 return true;
14947 case NC_COMPLEX:
14948 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
14949 return false;
14950 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
14951 return true;
14952 default:
14953 go_unreachable();
14957 // Convert value to complex.
14959 bool
14960 Numeric_constant::to_complex(mpc_t* val) const
14962 mpc_init2(*val, mpc_precision);
14963 switch (this->classification_)
14965 case NC_INT:
14966 case NC_RUNE:
14967 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
14968 return true;
14969 case NC_FLOAT:
14970 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
14971 return true;
14972 case NC_COMPLEX:
14973 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
14974 return true;
14975 default:
14976 go_unreachable();
14980 // Get the type.
14982 Type*
14983 Numeric_constant::type() const
14985 if (this->type_ != NULL)
14986 return this->type_;
14987 switch (this->classification_)
14989 case NC_INT:
14990 return Type::make_abstract_integer_type();
14991 case NC_RUNE:
14992 return Type::make_abstract_character_type();
14993 case NC_FLOAT:
14994 return Type::make_abstract_float_type();
14995 case NC_COMPLEX:
14996 return Type::make_abstract_complex_type();
14997 default:
14998 go_unreachable();
15002 // If the constant can be expressed in TYPE, then set the type of the
15003 // constant to TYPE and return true. Otherwise return false, and, if
15004 // ISSUE_ERROR is true, report an appropriate error message.
15006 bool
15007 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15009 bool ret;
15010 if (type == NULL || type->is_error())
15011 ret = true;
15012 else if (type->integer_type() != NULL)
15013 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15014 else if (type->float_type() != NULL)
15015 ret = this->check_float_type(type->float_type(), issue_error, loc);
15016 else if (type->complex_type() != NULL)
15017 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15018 else
15019 go_unreachable();
15020 if (ret)
15021 this->type_ = type;
15022 return ret;
15025 // Check whether the constant can be expressed in an integer type.
15027 bool
15028 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15029 Location location) const
15031 mpz_t val;
15032 switch (this->classification_)
15034 case NC_INT:
15035 case NC_RUNE:
15036 mpz_init_set(val, this->u_.int_val);
15037 break;
15039 case NC_FLOAT:
15040 if (!mpfr_integer_p(this->u_.float_val))
15042 if (issue_error)
15043 error_at(location, "floating point constant truncated to integer");
15044 return false;
15046 mpz_init(val);
15047 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15048 break;
15050 case NC_COMPLEX:
15051 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15052 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15054 if (issue_error)
15055 error_at(location, "complex constant truncated to integer");
15056 return false;
15058 mpz_init(val);
15059 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15060 break;
15062 default:
15063 go_unreachable();
15066 bool ret;
15067 if (type->is_abstract())
15068 ret = true;
15069 else
15071 int bits = mpz_sizeinbase(val, 2);
15072 if (type->is_unsigned())
15074 // For an unsigned type we can only accept a nonnegative
15075 // number, and we must be able to represents at least BITS.
15076 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15078 else
15080 // For a signed type we need an extra bit to indicate the
15081 // sign. We have to handle the most negative integer
15082 // specially.
15083 ret = (bits + 1 <= type->bits()
15084 || (bits <= type->bits()
15085 && mpz_sgn(val) < 0
15086 && (mpz_scan1(val, 0)
15087 == static_cast<unsigned long>(type->bits() - 1))
15088 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15092 if (!ret && issue_error)
15093 error_at(location, "integer constant overflow");
15095 return ret;
15098 // Check whether the constant can be expressed in a floating point
15099 // type.
15101 bool
15102 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15103 Location location)
15105 mpfr_t val;
15106 switch (this->classification_)
15108 case NC_INT:
15109 case NC_RUNE:
15110 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15111 break;
15113 case NC_FLOAT:
15114 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15115 break;
15117 case NC_COMPLEX:
15118 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15120 if (issue_error)
15121 error_at(location, "complex constant truncated to float");
15122 return false;
15124 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15125 break;
15127 default:
15128 go_unreachable();
15131 bool ret;
15132 if (type->is_abstract())
15133 ret = true;
15134 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15136 // A NaN or Infinity always fits in the range of the type.
15137 ret = true;
15139 else
15141 mp_exp_t exp = mpfr_get_exp(val);
15142 mp_exp_t max_exp;
15143 switch (type->bits())
15145 case 32:
15146 max_exp = 128;
15147 break;
15148 case 64:
15149 max_exp = 1024;
15150 break;
15151 default:
15152 go_unreachable();
15155 ret = exp <= max_exp;
15157 if (ret)
15159 // Round the constant to the desired type.
15160 mpfr_t t;
15161 mpfr_init(t);
15162 switch (type->bits())
15164 case 32:
15165 mpfr_set_prec(t, 24);
15166 break;
15167 case 64:
15168 mpfr_set_prec(t, 53);
15169 break;
15170 default:
15171 go_unreachable();
15173 mpfr_set(t, val, GMP_RNDN);
15174 mpfr_set(val, t, GMP_RNDN);
15175 mpfr_clear(t);
15177 this->set_float(type, val);
15181 mpfr_clear(val);
15183 if (!ret && issue_error)
15184 error_at(location, "floating point constant overflow");
15186 return ret;
15189 // Check whether the constant can be expressed in a complex type.
15191 bool
15192 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15193 Location location)
15195 if (type->is_abstract())
15196 return true;
15198 mp_exp_t max_exp;
15199 switch (type->bits())
15201 case 64:
15202 max_exp = 128;
15203 break;
15204 case 128:
15205 max_exp = 1024;
15206 break;
15207 default:
15208 go_unreachable();
15211 mpc_t val;
15212 mpc_init2(val, mpc_precision);
15213 switch (this->classification_)
15215 case NC_INT:
15216 case NC_RUNE:
15217 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
15218 break;
15220 case NC_FLOAT:
15221 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
15222 break;
15224 case NC_COMPLEX:
15225 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
15226 break;
15228 default:
15229 go_unreachable();
15232 bool ret = true;
15233 if (!mpfr_nan_p(mpc_realref(val))
15234 && !mpfr_inf_p(mpc_realref(val))
15235 && !mpfr_zero_p(mpc_realref(val))
15236 && mpfr_get_exp(mpc_realref(val)) > max_exp)
15238 if (issue_error)
15239 error_at(location, "complex real part overflow");
15240 ret = false;
15243 if (!mpfr_nan_p(mpc_imagref(val))
15244 && !mpfr_inf_p(mpc_imagref(val))
15245 && !mpfr_zero_p(mpc_imagref(val))
15246 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
15248 if (issue_error)
15249 error_at(location, "complex imaginary part overflow");
15250 ret = false;
15253 if (ret)
15255 // Round the constant to the desired type.
15256 mpc_t t;
15257 switch (type->bits())
15259 case 64:
15260 mpc_init2(t, 24);
15261 break;
15262 case 128:
15263 mpc_init2(t, 53);
15264 break;
15265 default:
15266 go_unreachable();
15268 mpc_set(t, val, MPC_RNDNN);
15269 mpc_set(val, t, MPC_RNDNN);
15270 mpc_clear(t);
15272 this->set_complex(type, val);
15275 mpc_clear(val);
15277 return ret;
15280 // Return an Expression for this value.
15282 Expression*
15283 Numeric_constant::expression(Location loc) const
15285 switch (this->classification_)
15287 case NC_INT:
15288 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
15289 case NC_RUNE:
15290 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15291 case NC_FLOAT:
15292 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15293 case NC_COMPLEX:
15294 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
15295 default:
15296 go_unreachable();