libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / gcc / go / gofrontend / expressions.cc
blobc481bc59c8fbca0eae8d0d399a2cdd0c912ac69d
1 // expressions.cc -- Go frontend expression handling.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include <algorithm>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "types.h"
14 #include "export.h"
15 #include "import.h"
16 #include "statements.h"
17 #include "lex.h"
18 #include "runtime.h"
19 #include "backend.h"
20 #include "expressions.h"
21 #include "ast-dump.h"
23 // Class Expression.
25 Expression::Expression(Expression_classification classification,
26 Location location)
27 : classification_(classification), location_(location)
31 Expression::~Expression()
35 // Traverse the expressions.
37 int
38 Expression::traverse(Expression** pexpr, Traverse* traverse)
40 Expression* expr = *pexpr;
41 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
43 int t = traverse->expression(pexpr);
44 if (t == TRAVERSE_EXIT)
45 return TRAVERSE_EXIT;
46 else if (t == TRAVERSE_SKIP_COMPONENTS)
47 return TRAVERSE_CONTINUE;
49 return expr->do_traverse(traverse);
52 // Traverse subexpressions of this expression.
54 int
55 Expression::traverse_subexpressions(Traverse* traverse)
57 return this->do_traverse(traverse);
60 // Default implementation for do_traverse for child classes.
62 int
63 Expression::do_traverse(Traverse*)
65 return TRAVERSE_CONTINUE;
68 // This virtual function is called by the parser if the value of this
69 // expression is being discarded. By default, we give an error.
70 // Expressions with side effects override.
72 bool
73 Expression::do_discarding_value()
75 this->unused_value_error();
76 return false;
79 // This virtual function is called to export expressions. This will
80 // only be used by expressions which may be constant.
82 void
83 Expression::do_export(Export*) const
85 go_unreachable();
88 // Give an error saying that the value of the expression is not used.
90 void
91 Expression::unused_value_error()
93 this->report_error(_("value computed is not used"));
96 // Note that this expression is an error. This is called by children
97 // when they discover an error.
99 void
100 Expression::set_is_error()
102 this->classification_ = EXPRESSION_ERROR;
105 // For children to call to report an error conveniently.
107 void
108 Expression::report_error(const char* msg)
110 error_at(this->location_, "%s", msg);
111 this->set_is_error();
114 // Set types of variables and constants. This is implemented by the
115 // child class.
117 void
118 Expression::determine_type(const Type_context* context)
120 this->do_determine_type(context);
123 // Set types when there is no context.
125 void
126 Expression::determine_type_no_context()
128 Type_context context;
129 this->do_determine_type(&context);
132 // Return an expression handling any conversions which must be done during
133 // assignment.
135 Expression*
136 Expression::convert_for_assignment(Gogo* gogo, Type* lhs_type,
137 Expression* rhs, Location location)
139 Type* rhs_type = rhs->type();
140 if (lhs_type->is_error()
141 || rhs_type->is_error()
142 || rhs->is_error_expression())
143 return Expression::make_error(location);
145 if (lhs_type->forwarded() != rhs_type->forwarded()
146 && lhs_type->interface_type() != NULL)
148 if (rhs_type->interface_type() == NULL)
149 return Expression::convert_type_to_interface(lhs_type, rhs, location);
150 else
151 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
152 location);
154 else if (lhs_type->forwarded() != rhs_type->forwarded()
155 && rhs_type->interface_type() != NULL)
156 return Expression::convert_interface_to_type(lhs_type, rhs, location);
157 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
159 // Assigning nil to a slice.
160 mpz_t zval;
161 mpz_init_set_ui(zval, 0UL);
162 Expression* zero = Expression::make_integer(&zval, NULL, location);
163 mpz_clear(zval);
164 Expression* nil = Expression::make_nil(location);
165 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
167 else if (rhs_type->is_nil_type())
168 return Expression::make_nil(location);
169 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
171 // No conversion is needed.
172 return rhs;
174 else if (lhs_type->points_to() != NULL)
175 return Expression::make_unsafe_cast(lhs_type, rhs, location);
176 else if (lhs_type->is_numeric_type())
177 return Expression::make_cast(lhs_type, rhs, location);
178 else if ((lhs_type->struct_type() != NULL
179 && rhs_type->struct_type() != NULL)
180 || (lhs_type->array_type() != NULL
181 && rhs_type->array_type() != NULL))
183 // Avoid confusion from zero sized variables which may be
184 // represented as non-zero-sized.
185 // TODO(cmang): This check is for a GCC-specific issue, and should be
186 // removed from the frontend. FIXME.
187 size_t lhs_size = gogo->backend()->type_size(lhs_type->get_backend(gogo));
188 size_t rhs_size = gogo->backend()->type_size(rhs_type->get_backend(gogo));
189 if (rhs_size == 0 || lhs_size == 0)
190 return rhs;
192 // This conversion must be permitted by Go, or we wouldn't have
193 // gotten here.
194 return Expression::make_unsafe_cast(lhs_type, rhs, location);
196 else
197 return rhs;
200 // Return an expression for a conversion from a non-interface type to an
201 // interface type.
203 Expression*
204 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
205 Location location)
207 Interface_type* lhs_interface_type = lhs_type->interface_type();
208 bool lhs_is_empty = lhs_interface_type->is_empty();
210 // Since RHS_TYPE is a static type, we can create the interface
211 // method table at compile time.
213 // When setting an interface to nil, we just set both fields to
214 // NULL.
215 Type* rhs_type = rhs->type();
216 if (rhs_type->is_nil_type())
218 Expression* nil = Expression::make_nil(location);
219 return Expression::make_interface_value(lhs_type, nil, nil, location);
222 // This should have been checked already.
223 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
225 // An interface is a tuple. If LHS_TYPE is an empty interface type,
226 // then the first field is the type descriptor for RHS_TYPE.
227 // Otherwise it is the interface method table for RHS_TYPE.
228 Expression* first_field;
229 if (lhs_is_empty)
230 first_field = Expression::make_type_descriptor(rhs_type, location);
231 else
233 // Build the interface method table for this interface and this
234 // object type: a list of function pointers for each interface
235 // method.
236 Named_type* rhs_named_type = rhs_type->named_type();
237 Struct_type* rhs_struct_type = rhs_type->struct_type();
238 bool is_pointer = false;
239 if (rhs_named_type == NULL && rhs_struct_type == NULL)
241 rhs_named_type = rhs_type->deref()->named_type();
242 rhs_struct_type = rhs_type->deref()->struct_type();
243 is_pointer = true;
245 if (rhs_named_type != NULL)
246 first_field =
247 rhs_named_type->interface_method_table(lhs_interface_type,
248 is_pointer);
249 else if (rhs_struct_type != NULL)
250 first_field =
251 rhs_struct_type->interface_method_table(lhs_interface_type,
252 is_pointer);
253 else
254 first_field = Expression::make_nil(location);
257 Expression* obj;
258 if (rhs_type->points_to() != NULL)
260 // We are assigning a pointer to the interface; the interface
261 // holds the pointer itself.
262 obj = rhs;
264 else
266 // We are assigning a non-pointer value to the interface; the
267 // interface gets a copy of the value in the heap.
268 obj = Expression::make_heap_expression(rhs, location);
271 return Expression::make_interface_value(lhs_type, first_field, obj, location);
274 // Return an expression for the type descriptor of RHS.
276 Expression*
277 Expression::get_interface_type_descriptor(Expression* rhs)
279 go_assert(rhs->type()->interface_type() != NULL);
280 Location location = rhs->location();
282 // The type descriptor is the first field of an empty interface.
283 if (rhs->type()->interface_type()->is_empty())
284 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
285 location);
287 Expression* mtable =
288 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
290 Expression* descriptor =
291 Expression::make_unary(OPERATOR_MULT, mtable, location);
292 descriptor = Expression::make_field_reference(descriptor, 0, location);
293 Expression* nil = Expression::make_nil(location);
295 Expression* eq =
296 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
297 return Expression::make_conditional(eq, nil, descriptor, location);
300 // Return an expression for the conversion of an interface type to an
301 // interface type.
303 Expression*
304 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
305 bool for_type_guard,
306 Location location)
308 Interface_type* lhs_interface_type = lhs_type->interface_type();
309 bool lhs_is_empty = lhs_interface_type->is_empty();
311 // In the general case this requires runtime examination of the type
312 // method table to match it up with the interface methods.
314 // FIXME: If all of the methods in the right hand side interface
315 // also appear in the left hand side interface, then we don't need
316 // to do a runtime check, although we still need to build a new
317 // method table.
319 // Get the type descriptor for the right hand side. This will be
320 // NULL for a nil interface.
321 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
322 Expression* lhs_type_expr =
323 Expression::make_type_descriptor(lhs_type, location);
325 Expression* first_field;
326 if (for_type_guard)
328 // A type assertion fails when converting a nil interface.
329 first_field =
330 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
331 lhs_type_expr, rhs_type_expr);
333 else if (lhs_is_empty)
335 // A conversion to an empty interface always succeeds, and the
336 // first field is just the type descriptor of the object.
337 first_field = rhs_type_expr;
339 else
341 // A conversion to a non-empty interface may fail, but unlike a
342 // type assertion converting nil will always succeed.
343 first_field =
344 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
345 lhs_type_expr, rhs_type_expr);
348 // The second field is simply the object pointer.
349 Expression* obj =
350 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
351 return Expression::make_interface_value(lhs_type, first_field, obj, location);
354 // Return an expression for the conversion of an interface type to a
355 // non-interface type.
357 Expression*
358 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
359 Location location)
361 // Call a function to check that the type is valid. The function
362 // will panic with an appropriate runtime type error if the type is
363 // not valid.
364 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
365 location);
366 Expression* rhs_descriptor =
367 Expression::get_interface_type_descriptor(rhs);
369 Type* rhs_type = rhs->type();
370 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
371 location);
373 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
374 location, 3, lhs_type_expr,
375 rhs_descriptor, rhs_inter_expr);
377 // If the call succeeds, pull out the value.
378 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
379 location);
381 // If the value is a pointer, then it is the value we want.
382 // Otherwise it points to the value.
383 if (lhs_type->points_to() == NULL)
385 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
386 location);
387 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
389 return Expression::make_compound(check_iface, obj, location);
392 // Convert an expression to its backend representation. This is implemented by
393 // the child class. Not that it is not in general safe to call this multiple
394 // times for a single expression, but that we don't catch such errors.
396 Bexpression*
397 Expression::get_backend(Translate_context* context)
399 // The child may have marked this expression as having an error.
400 if (this->classification_ == EXPRESSION_ERROR)
401 return context->backend()->error_expression();
403 return this->do_get_backend(context);
406 // Return a backend expression for VAL.
407 Bexpression*
408 Expression::backend_numeric_constant_expression(Translate_context* context,
409 Numeric_constant* val)
411 Gogo* gogo = context->gogo();
412 Type* type = val->type();
413 if (type == NULL)
414 return gogo->backend()->error_expression();
416 Btype* btype = type->get_backend(gogo);
417 Bexpression* ret;
418 if (type->integer_type() != NULL)
420 mpz_t ival;
421 if (!val->to_int(&ival))
423 go_assert(saw_errors());
424 return gogo->backend()->error_expression();
426 ret = gogo->backend()->integer_constant_expression(btype, ival);
427 mpz_clear(ival);
429 else if (type->float_type() != NULL)
431 mpfr_t fval;
432 if (!val->to_float(&fval))
434 go_assert(saw_errors());
435 return gogo->backend()->error_expression();
437 ret = gogo->backend()->float_constant_expression(btype, fval);
438 mpfr_clear(fval);
440 else if (type->complex_type() != NULL)
442 mpfr_t real;
443 mpfr_t imag;
444 if (!val->to_complex(&real, &imag))
446 go_assert(saw_errors());
447 return gogo->backend()->error_expression();
449 ret = gogo->backend()->complex_constant_expression(btype, real, imag);
450 mpfr_clear(real);
451 mpfr_clear(imag);
453 else
454 go_unreachable();
456 return ret;
459 // Return an expression which evaluates to true if VAL, of arbitrary integer
460 // type, is negative or is more than the maximum value of the Go type "int".
462 Expression*
463 Expression::check_bounds(Expression* val, Location loc)
465 Type* val_type = val->type();
466 Type* bound_type = Type::lookup_integer_type("int");
468 int val_type_size;
469 bool val_is_unsigned = false;
470 if (val_type->integer_type() != NULL)
472 val_type_size = val_type->integer_type()->bits();
473 val_is_unsigned = val_type->integer_type()->is_unsigned();
475 else
477 if (!val_type->is_numeric_type()
478 || !Type::are_convertible(bound_type, val_type, NULL))
480 go_assert(saw_errors());
481 return Expression::make_boolean(true, loc);
484 if (val_type->complex_type() != NULL)
485 val_type_size = val_type->complex_type()->bits();
486 else
487 val_type_size = val_type->float_type()->bits();
490 Expression* negative_index = Expression::make_boolean(false, loc);
491 Expression* index_overflows = Expression::make_boolean(false, loc);
492 if (!val_is_unsigned)
494 mpz_t zval;
495 mpz_init_set_ui(zval, 0UL);
496 Expression* zero = Expression::make_integer(&zval, val_type, loc);
497 mpz_clear(zval);
499 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
502 int bound_type_size = bound_type->integer_type()->bits();
503 if (val_type_size > bound_type_size
504 || (val_type_size == bound_type_size
505 && val_is_unsigned))
507 mpz_t one;
508 mpz_init_set_ui(one, 1UL);
510 // maxval = 2^(bound_type_size - 1) - 1
511 mpz_t maxval;
512 mpz_init(maxval);
513 mpz_mul_2exp(maxval, one, bound_type_size - 1);
514 mpz_sub_ui(maxval, maxval, 1);
515 Expression* max = Expression::make_integer(&maxval, val_type, loc);
516 mpz_clear(one);
517 mpz_clear(maxval);
519 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
522 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
523 loc);
526 void
527 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
529 this->do_dump_expression(ast_dump_context);
532 // Error expressions. This are used to avoid cascading errors.
534 class Error_expression : public Expression
536 public:
537 Error_expression(Location location)
538 : Expression(EXPRESSION_ERROR, location)
541 protected:
542 bool
543 do_is_constant() const
544 { return true; }
546 bool
547 do_is_immutable() const
548 { return true; }
550 bool
551 do_numeric_constant_value(Numeric_constant* nc) const
553 nc->set_unsigned_long(NULL, 0);
554 return true;
557 bool
558 do_discarding_value()
559 { return true; }
561 Type*
562 do_type()
563 { return Type::make_error_type(); }
565 void
566 do_determine_type(const Type_context*)
569 Expression*
570 do_copy()
571 { return this; }
573 bool
574 do_is_addressable() const
575 { return true; }
577 Bexpression*
578 do_get_backend(Translate_context* context)
579 { return context->backend()->error_expression(); }
581 void
582 do_dump_expression(Ast_dump_context*) const;
585 // Dump the ast representation for an error expression to a dump context.
587 void
588 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
590 ast_dump_context->ostream() << "_Error_" ;
593 Expression*
594 Expression::make_error(Location location)
596 return new Error_expression(location);
599 // An expression which is really a type. This is used during parsing.
600 // It is an error if these survive after lowering.
602 class
603 Type_expression : public Expression
605 public:
606 Type_expression(Type* type, Location location)
607 : Expression(EXPRESSION_TYPE, location),
608 type_(type)
611 protected:
613 do_traverse(Traverse* traverse)
614 { return Type::traverse(this->type_, traverse); }
616 Type*
617 do_type()
618 { return this->type_; }
620 void
621 do_determine_type(const Type_context*)
624 void
625 do_check_types(Gogo*)
626 { this->report_error(_("invalid use of type")); }
628 Expression*
629 do_copy()
630 { return this; }
632 Bexpression*
633 do_get_backend(Translate_context*)
634 { go_unreachable(); }
636 void do_dump_expression(Ast_dump_context*) const;
638 private:
639 // The type which we are representing as an expression.
640 Type* type_;
643 void
644 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
646 ast_dump_context->dump_type(this->type_);
649 Expression*
650 Expression::make_type(Type* type, Location location)
652 return new Type_expression(type, location);
655 // Class Parser_expression.
657 Type*
658 Parser_expression::do_type()
660 // We should never really ask for the type of a Parser_expression.
661 // However, it can happen, at least when we have an invalid const
662 // whose initializer refers to the const itself. In that case we
663 // may ask for the type when lowering the const itself.
664 go_assert(saw_errors());
665 return Type::make_error_type();
668 // Class Var_expression.
670 // Lower a variable expression. Here we just make sure that the
671 // initialization expression of the variable has been lowered. This
672 // ensures that we will be able to determine the type of the variable
673 // if necessary.
675 Expression*
676 Var_expression::do_lower(Gogo* gogo, Named_object* function,
677 Statement_inserter* inserter, int)
679 if (this->variable_->is_variable())
681 Variable* var = this->variable_->var_value();
682 // This is either a local variable or a global variable. A
683 // reference to a variable which is local to an enclosing
684 // function will be a reference to a field in a closure.
685 if (var->is_global())
687 function = NULL;
688 inserter = NULL;
690 var->lower_init_expression(gogo, function, inserter);
692 return this;
695 // Return the type of a reference to a variable.
697 Type*
698 Var_expression::do_type()
700 if (this->variable_->is_variable())
701 return this->variable_->var_value()->type();
702 else if (this->variable_->is_result_variable())
703 return this->variable_->result_var_value()->type();
704 else
705 go_unreachable();
708 // Determine the type of a reference to a variable.
710 void
711 Var_expression::do_determine_type(const Type_context*)
713 if (this->variable_->is_variable())
714 this->variable_->var_value()->determine_type();
717 // Something takes the address of this variable. This means that we
718 // may want to move the variable onto the heap.
720 void
721 Var_expression::do_address_taken(bool escapes)
723 if (!escapes)
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_non_escaping_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_non_escaping_address_taken();
729 else
730 go_unreachable();
732 else
734 if (this->variable_->is_variable())
735 this->variable_->var_value()->set_address_taken();
736 else if (this->variable_->is_result_variable())
737 this->variable_->result_var_value()->set_address_taken();
738 else
739 go_unreachable();
743 // Get the backend representation for a reference to a variable.
745 Bexpression*
746 Var_expression::do_get_backend(Translate_context* context)
748 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
749 context->function());
750 bool is_in_heap;
751 Location loc = this->location();
752 Btype* btype;
753 Gogo* gogo = context->gogo();
754 if (this->variable_->is_variable())
756 is_in_heap = this->variable_->var_value()->is_in_heap();
757 btype = this->variable_->var_value()->type()->get_backend(gogo);
759 else if (this->variable_->is_result_variable())
761 is_in_heap = this->variable_->result_var_value()->is_in_heap();
762 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
764 else
765 go_unreachable();
767 Bexpression* ret = context->backend()->var_expression(bvar, loc);
768 if (is_in_heap)
769 ret = context->backend()->indirect_expression(btype, ret, true, loc);
770 return ret;
773 // Ast dump for variable expression.
775 void
776 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
778 ast_dump_context->ostream() << this->variable_->name() ;
781 // Make a reference to a variable in an expression.
783 Expression*
784 Expression::make_var_reference(Named_object* var, Location location)
786 if (var->is_sink())
787 return Expression::make_sink(location);
789 // FIXME: Creating a new object for each reference to a variable is
790 // wasteful.
791 return new Var_expression(var, location);
794 // Class Temporary_reference_expression.
796 // The type.
798 Type*
799 Temporary_reference_expression::do_type()
801 return this->statement_->type();
804 // Called if something takes the address of this temporary variable.
805 // We never have to move temporary variables to the heap, but we do
806 // need to know that they must live in the stack rather than in a
807 // register.
809 void
810 Temporary_reference_expression::do_address_taken(bool)
812 this->statement_->set_is_address_taken();
815 // Get a backend expression referring to the variable.
817 Bexpression*
818 Temporary_reference_expression::do_get_backend(Translate_context* context)
820 Gogo* gogo = context->gogo();
821 Bvariable* bvar = this->statement_->get_backend_variable(context);
822 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
824 // The backend can't always represent the same set of recursive types
825 // that the Go frontend can. In some cases this means that a
826 // temporary variable won't have the right backend type. Correct
827 // that here by adding a type cast. We need to use base() to push
828 // the circularity down one level.
829 Type* stype = this->statement_->type();
830 if (!this->is_lvalue_
831 && stype->has_pointer()
832 && stype->deref()->is_void_type())
834 Btype* btype = this->type()->base()->get_backend(gogo);
835 ret = gogo->backend()->convert_expression(btype, ret, this->location());
837 return ret;
840 // Ast dump for temporary reference.
842 void
843 Temporary_reference_expression::do_dump_expression(
844 Ast_dump_context* ast_dump_context) const
846 ast_dump_context->dump_temp_variable_name(this->statement_);
849 // Make a reference to a temporary variable.
851 Temporary_reference_expression*
852 Expression::make_temporary_reference(Temporary_statement* statement,
853 Location location)
855 return new Temporary_reference_expression(statement, location);
858 // Class Set_and_use_temporary_expression.
860 // Return the type.
862 Type*
863 Set_and_use_temporary_expression::do_type()
865 return this->statement_->type();
868 // Determine the type of the expression.
870 void
871 Set_and_use_temporary_expression::do_determine_type(
872 const Type_context* context)
874 this->expr_->determine_type(context);
877 // Take the address.
879 void
880 Set_and_use_temporary_expression::do_address_taken(bool)
882 this->statement_->set_is_address_taken();
885 // Return the backend representation.
887 Bexpression*
888 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
890 Location loc = this->location();
891 Gogo* gogo = context->gogo();
892 Bvariable* bvar = this->statement_->get_backend_variable(context);
893 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
895 Bexpression* bexpr = this->expr_->get_backend(context);
896 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
897 var_ref = gogo->backend()->var_expression(bvar, loc);
898 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
899 return ret;
902 // Dump.
904 void
905 Set_and_use_temporary_expression::do_dump_expression(
906 Ast_dump_context* ast_dump_context) const
908 ast_dump_context->ostream() << '(';
909 ast_dump_context->dump_temp_variable_name(this->statement_);
910 ast_dump_context->ostream() << " = ";
911 this->expr_->dump_expression(ast_dump_context);
912 ast_dump_context->ostream() << ')';
915 // Make a set-and-use temporary.
917 Set_and_use_temporary_expression*
918 Expression::make_set_and_use_temporary(Temporary_statement* statement,
919 Expression* expr, Location location)
921 return new Set_and_use_temporary_expression(statement, expr, location);
924 // A sink expression--a use of the blank identifier _.
926 class Sink_expression : public Expression
928 public:
929 Sink_expression(Location location)
930 : Expression(EXPRESSION_SINK, location),
931 type_(NULL), bvar_(NULL)
934 protected:
935 bool
936 do_discarding_value()
937 { return true; }
939 Type*
940 do_type();
942 void
943 do_determine_type(const Type_context*);
945 Expression*
946 do_copy()
947 { return new Sink_expression(this->location()); }
949 Bexpression*
950 do_get_backend(Translate_context*);
952 void
953 do_dump_expression(Ast_dump_context*) const;
955 private:
956 // The type of this sink variable.
957 Type* type_;
958 // The temporary variable we generate.
959 Bvariable* bvar_;
962 // Return the type of a sink expression.
964 Type*
965 Sink_expression::do_type()
967 if (this->type_ == NULL)
968 return Type::make_sink_type();
969 return this->type_;
972 // Determine the type of a sink expression.
974 void
975 Sink_expression::do_determine_type(const Type_context* context)
977 if (context->type != NULL)
978 this->type_ = context->type;
981 // Return a temporary variable for a sink expression. This will
982 // presumably be a write-only variable which the middle-end will drop.
984 Bexpression*
985 Sink_expression::do_get_backend(Translate_context* context)
987 Location loc = this->location();
988 Gogo* gogo = context->gogo();
989 if (this->bvar_ == NULL)
991 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
992 Named_object* fn = context->function();
993 go_assert(fn != NULL);
994 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
995 Btype* bt = this->type_->get_backend(context->gogo());
996 Bstatement* decl;
997 this->bvar_ =
998 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
999 false, loc, &decl);
1000 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
1001 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1002 return var_ref;
1004 return gogo->backend()->var_expression(this->bvar_, loc);
1007 // Ast dump for sink expression.
1009 void
1010 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1012 ast_dump_context->ostream() << "_" ;
1015 // Make a sink expression.
1017 Expression*
1018 Expression::make_sink(Location location)
1020 return new Sink_expression(location);
1023 // Class Func_expression.
1025 // FIXME: Can a function expression appear in a constant expression?
1026 // The value is unchanging. Initializing a constant to the address of
1027 // a function seems like it could work, though there might be little
1028 // point to it.
1030 // Traversal.
1033 Func_expression::do_traverse(Traverse* traverse)
1035 return (this->closure_ == NULL
1036 ? TRAVERSE_CONTINUE
1037 : Expression::traverse(&this->closure_, traverse));
1040 // Return the type of a function expression.
1042 Type*
1043 Func_expression::do_type()
1045 if (this->function_->is_function())
1046 return this->function_->func_value()->type();
1047 else if (this->function_->is_function_declaration())
1048 return this->function_->func_declaration_value()->type();
1049 else
1050 go_unreachable();
1053 // Get the backend representation for the code of a function expression.
1055 Bexpression*
1056 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1058 Function_type* fntype;
1059 if (no->is_function())
1060 fntype = no->func_value()->type();
1061 else if (no->is_function_declaration())
1062 fntype = no->func_declaration_value()->type();
1063 else
1064 go_unreachable();
1066 // Builtin functions are handled specially by Call_expression. We
1067 // can't take their address.
1068 if (fntype->is_builtin())
1070 error_at(loc,
1071 "invalid use of special builtin function %qs; must be called",
1072 no->message_name().c_str());
1073 return gogo->backend()->error_expression();
1076 Bfunction* fndecl;
1077 if (no->is_function())
1078 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1079 else if (no->is_function_declaration())
1080 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1081 else
1082 go_unreachable();
1084 return gogo->backend()->function_code_expression(fndecl, loc);
1087 // Get the backend representation for a function expression. This is used when
1088 // we take the address of a function rather than simply calling it. A func
1089 // value is represented as a pointer to a block of memory. The first
1090 // word of that memory is a pointer to the function code. The
1091 // remaining parts of that memory are the addresses of variables that
1092 // the function closes over.
1094 Bexpression*
1095 Func_expression::do_get_backend(Translate_context* context)
1097 // If there is no closure, just use the function descriptor.
1098 if (this->closure_ == NULL)
1100 Gogo* gogo = context->gogo();
1101 Named_object* no = this->function_;
1102 Expression* descriptor;
1103 if (no->is_function())
1104 descriptor = no->func_value()->descriptor(gogo, no);
1105 else if (no->is_function_declaration())
1107 if (no->func_declaration_value()->type()->is_builtin())
1109 error_at(this->location(),
1110 ("invalid use of special builtin function %qs; "
1111 "must be called"),
1112 no->message_name().c_str());
1113 return gogo->backend()->error_expression();
1115 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1117 else
1118 go_unreachable();
1120 Bexpression* bdesc = descriptor->get_backend(context);
1121 return gogo->backend()->address_expression(bdesc, this->location());
1124 go_assert(this->function_->func_value()->enclosing() != NULL);
1126 // If there is a closure, then the closure is itself the function
1127 // expression. It is a pointer to a struct whose first field points
1128 // to the function code and whose remaining fields are the addresses
1129 // of the closed-over variables.
1130 return this->closure_->get_backend(context);
1133 // Ast dump for function.
1135 void
1136 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1138 ast_dump_context->ostream() << this->function_->name();
1139 if (this->closure_ != NULL)
1141 ast_dump_context->ostream() << " {closure = ";
1142 this->closure_->dump_expression(ast_dump_context);
1143 ast_dump_context->ostream() << "}";
1147 // Make a reference to a function in an expression.
1149 Expression*
1150 Expression::make_func_reference(Named_object* function, Expression* closure,
1151 Location location)
1153 return new Func_expression(function, closure, location);
1156 // Class Func_descriptor_expression.
1158 // Constructor.
1160 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1161 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1162 fn_(fn), dvar_(NULL)
1164 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1167 // Traversal.
1170 Func_descriptor_expression::do_traverse(Traverse*)
1172 return TRAVERSE_CONTINUE;
1175 // All function descriptors have the same type.
1177 Type* Func_descriptor_expression::descriptor_type;
1179 void
1180 Func_descriptor_expression::make_func_descriptor_type()
1182 if (Func_descriptor_expression::descriptor_type != NULL)
1183 return;
1184 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1185 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1186 Func_descriptor_expression::descriptor_type =
1187 Type::make_builtin_named_type("functionDescriptor", struct_type);
1190 Type*
1191 Func_descriptor_expression::do_type()
1193 Func_descriptor_expression::make_func_descriptor_type();
1194 return Func_descriptor_expression::descriptor_type;
1197 // The backend representation for a function descriptor.
1199 Bexpression*
1200 Func_descriptor_expression::do_get_backend(Translate_context* context)
1202 Named_object* no = this->fn_;
1203 Location loc = no->location();
1204 if (this->dvar_ != NULL)
1205 return context->backend()->var_expression(this->dvar_, loc);
1207 Gogo* gogo = context->gogo();
1208 std::string var_name;
1209 if (no->package() == NULL)
1210 var_name = gogo->pkgpath_symbol();
1211 else
1212 var_name = no->package()->pkgpath_symbol();
1213 var_name.push_back('.');
1214 var_name.append(Gogo::unpack_hidden_name(no->name()));
1215 var_name.append("$descriptor");
1217 Btype* btype = this->type()->get_backend(gogo);
1219 Bvariable* bvar;
1220 if (no->package() != NULL
1221 || Linemap::is_predeclared_location(no->location()))
1222 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1223 loc);
1224 else
1226 Location bloc = Linemap::predeclared_location();
1227 bool is_hidden = ((no->is_function()
1228 && no->func_value()->enclosing() != NULL)
1229 || Gogo::is_thunk(no));
1230 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1231 btype, bloc);
1232 Expression_list* vals = new Expression_list();
1233 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1234 Expression* init =
1235 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1236 Translate_context bcontext(gogo, NULL, NULL, NULL);
1237 bcontext.set_is_const();
1238 Bexpression* binit = init->get_backend(&bcontext);
1239 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1240 false, btype, bloc, binit);
1243 this->dvar_ = bvar;
1244 return gogo->backend()->var_expression(bvar, loc);
1247 // Print a function descriptor expression.
1249 void
1250 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1252 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1255 // Make a function descriptor expression.
1257 Func_descriptor_expression*
1258 Expression::make_func_descriptor(Named_object* fn)
1260 return new Func_descriptor_expression(fn);
1263 // Make the function descriptor type, so that it can be converted.
1265 void
1266 Expression::make_func_descriptor_type()
1268 Func_descriptor_expression::make_func_descriptor_type();
1271 // A reference to just the code of a function.
1273 class Func_code_reference_expression : public Expression
1275 public:
1276 Func_code_reference_expression(Named_object* function, Location location)
1277 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1278 function_(function)
1281 protected:
1283 do_traverse(Traverse*)
1284 { return TRAVERSE_CONTINUE; }
1286 bool
1287 do_is_immutable() const
1288 { return true; }
1290 Type*
1291 do_type()
1292 { return Type::make_pointer_type(Type::make_void_type()); }
1294 void
1295 do_determine_type(const Type_context*)
1298 Expression*
1299 do_copy()
1301 return Expression::make_func_code_reference(this->function_,
1302 this->location());
1305 Bexpression*
1306 do_get_backend(Translate_context*);
1308 void
1309 do_dump_expression(Ast_dump_context* context) const
1310 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1312 private:
1313 // The function.
1314 Named_object* function_;
1317 // Get the backend representation for a reference to function code.
1319 Bexpression*
1320 Func_code_reference_expression::do_get_backend(Translate_context* context)
1322 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1323 this->location());
1326 // Make a reference to the code of a function.
1328 Expression*
1329 Expression::make_func_code_reference(Named_object* function, Location location)
1331 return new Func_code_reference_expression(function, location);
1334 // Class Unknown_expression.
1336 // Return the name of an unknown expression.
1338 const std::string&
1339 Unknown_expression::name() const
1341 return this->named_object_->name();
1344 // Lower a reference to an unknown name.
1346 Expression*
1347 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1349 Location location = this->location();
1350 Named_object* no = this->named_object_;
1351 Named_object* real;
1352 if (!no->is_unknown())
1353 real = no;
1354 else
1356 real = no->unknown_value()->real_named_object();
1357 if (real == NULL)
1359 if (this->is_composite_literal_key_)
1360 return this;
1361 if (!this->no_error_message_)
1362 error_at(location, "reference to undefined name %qs",
1363 this->named_object_->message_name().c_str());
1364 return Expression::make_error(location);
1367 switch (real->classification())
1369 case Named_object::NAMED_OBJECT_CONST:
1370 return Expression::make_const_reference(real, location);
1371 case Named_object::NAMED_OBJECT_TYPE:
1372 return Expression::make_type(real->type_value(), location);
1373 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1374 if (this->is_composite_literal_key_)
1375 return this;
1376 if (!this->no_error_message_)
1377 error_at(location, "reference to undefined type %qs",
1378 real->message_name().c_str());
1379 return Expression::make_error(location);
1380 case Named_object::NAMED_OBJECT_VAR:
1381 real->var_value()->set_is_used();
1382 return Expression::make_var_reference(real, location);
1383 case Named_object::NAMED_OBJECT_FUNC:
1384 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1385 return Expression::make_func_reference(real, NULL, location);
1386 case Named_object::NAMED_OBJECT_PACKAGE:
1387 if (this->is_composite_literal_key_)
1388 return this;
1389 if (!this->no_error_message_)
1390 error_at(location, "unexpected reference to package");
1391 return Expression::make_error(location);
1392 default:
1393 go_unreachable();
1397 // Dump the ast representation for an unknown expression to a dump context.
1399 void
1400 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1402 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1403 << ")";
1406 // Make a reference to an unknown name.
1408 Unknown_expression*
1409 Expression::make_unknown_reference(Named_object* no, Location location)
1411 return new Unknown_expression(no, location);
1414 // A boolean expression.
1416 class Boolean_expression : public Expression
1418 public:
1419 Boolean_expression(bool val, Location location)
1420 : Expression(EXPRESSION_BOOLEAN, location),
1421 val_(val), type_(NULL)
1424 static Expression*
1425 do_import(Import*);
1427 protected:
1428 bool
1429 do_is_constant() const
1430 { return true; }
1432 bool
1433 do_is_immutable() const
1434 { return true; }
1436 Type*
1437 do_type();
1439 void
1440 do_determine_type(const Type_context*);
1442 Expression*
1443 do_copy()
1444 { return this; }
1446 Bexpression*
1447 do_get_backend(Translate_context* context)
1448 { return context->backend()->boolean_constant_expression(this->val_); }
1450 void
1451 do_export(Export* exp) const
1452 { exp->write_c_string(this->val_ ? "true" : "false"); }
1454 void
1455 do_dump_expression(Ast_dump_context* ast_dump_context) const
1456 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1458 private:
1459 // The constant.
1460 bool val_;
1461 // The type as determined by context.
1462 Type* type_;
1465 // Get the type.
1467 Type*
1468 Boolean_expression::do_type()
1470 if (this->type_ == NULL)
1471 this->type_ = Type::make_boolean_type();
1472 return this->type_;
1475 // Set the type from the context.
1477 void
1478 Boolean_expression::do_determine_type(const Type_context* context)
1480 if (this->type_ != NULL && !this->type_->is_abstract())
1482 else if (context->type != NULL && context->type->is_boolean_type())
1483 this->type_ = context->type;
1484 else if (!context->may_be_abstract)
1485 this->type_ = Type::lookup_bool_type();
1488 // Import a boolean constant.
1490 Expression*
1491 Boolean_expression::do_import(Import* imp)
1493 if (imp->peek_char() == 't')
1495 imp->require_c_string("true");
1496 return Expression::make_boolean(true, imp->location());
1498 else
1500 imp->require_c_string("false");
1501 return Expression::make_boolean(false, imp->location());
1505 // Make a boolean expression.
1507 Expression*
1508 Expression::make_boolean(bool val, Location location)
1510 return new Boolean_expression(val, location);
1513 // Class String_expression.
1515 // Get the type.
1517 Type*
1518 String_expression::do_type()
1520 if (this->type_ == NULL)
1521 this->type_ = Type::make_string_type();
1522 return this->type_;
1525 // Set the type from the context.
1527 void
1528 String_expression::do_determine_type(const Type_context* context)
1530 if (this->type_ != NULL && !this->type_->is_abstract())
1532 else if (context->type != NULL && context->type->is_string_type())
1533 this->type_ = context->type;
1534 else if (!context->may_be_abstract)
1535 this->type_ = Type::lookup_string_type();
1538 // Build a string constant.
1540 Bexpression*
1541 String_expression::do_get_backend(Translate_context* context)
1543 Gogo* gogo = context->gogo();
1544 Btype* btype = Type::make_string_type()->get_backend(gogo);
1546 Location loc = this->location();
1547 std::vector<Bexpression*> init(2);
1548 Bexpression* str_cst =
1549 gogo->backend()->string_constant_expression(this->val_);
1550 init[0] = gogo->backend()->address_expression(str_cst, loc);
1552 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1553 mpz_t lenval;
1554 mpz_init_set_ui(lenval, this->val_.length());
1555 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1556 mpz_clear(lenval);
1558 return gogo->backend()->constructor_expression(btype, init, loc);
1561 // Write string literal to string dump.
1563 void
1564 String_expression::export_string(String_dump* exp,
1565 const String_expression* str)
1567 std::string s;
1568 s.reserve(str->val_.length() * 4 + 2);
1569 s += '"';
1570 for (std::string::const_iterator p = str->val_.begin();
1571 p != str->val_.end();
1572 ++p)
1574 if (*p == '\\' || *p == '"')
1576 s += '\\';
1577 s += *p;
1579 else if (*p >= 0x20 && *p < 0x7f)
1580 s += *p;
1581 else if (*p == '\n')
1582 s += "\\n";
1583 else if (*p == '\t')
1584 s += "\\t";
1585 else
1587 s += "\\x";
1588 unsigned char c = *p;
1589 unsigned int dig = c >> 4;
1590 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1591 dig = c & 0xf;
1592 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1595 s += '"';
1596 exp->write_string(s);
1599 // Export a string expression.
1601 void
1602 String_expression::do_export(Export* exp) const
1604 String_expression::export_string(exp, this);
1607 // Import a string expression.
1609 Expression*
1610 String_expression::do_import(Import* imp)
1612 imp->require_c_string("\"");
1613 std::string val;
1614 while (true)
1616 int c = imp->get_char();
1617 if (c == '"' || c == -1)
1618 break;
1619 if (c != '\\')
1620 val += static_cast<char>(c);
1621 else
1623 c = imp->get_char();
1624 if (c == '\\' || c == '"')
1625 val += static_cast<char>(c);
1626 else if (c == 'n')
1627 val += '\n';
1628 else if (c == 't')
1629 val += '\t';
1630 else if (c == 'x')
1632 c = imp->get_char();
1633 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1634 c = imp->get_char();
1635 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1636 char v = (vh << 4) | vl;
1637 val += v;
1639 else
1641 error_at(imp->location(), "bad string constant");
1642 return Expression::make_error(imp->location());
1646 return Expression::make_string(val, imp->location());
1649 // Ast dump for string expression.
1651 void
1652 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1654 String_expression::export_string(ast_dump_context, this);
1657 // Make a string expression.
1659 Expression*
1660 Expression::make_string(const std::string& val, Location location)
1662 return new String_expression(val, location);
1665 // An expression that evaluates to some characteristic of a string.
1666 // This is used when indexing, bound-checking, or nil checking a string.
1668 class String_info_expression : public Expression
1670 public:
1671 String_info_expression(Expression* string, String_info string_info,
1672 Location location)
1673 : Expression(EXPRESSION_STRING_INFO, location),
1674 string_(string), string_info_(string_info)
1677 protected:
1678 Type*
1679 do_type();
1681 void
1682 do_determine_type(const Type_context*)
1683 { go_unreachable(); }
1685 Expression*
1686 do_copy()
1688 return new String_info_expression(this->string_->copy(), this->string_info_,
1689 this->location());
1692 Bexpression*
1693 do_get_backend(Translate_context* context);
1695 void
1696 do_dump_expression(Ast_dump_context*) const;
1698 void
1699 do_issue_nil_check()
1700 { this->string_->issue_nil_check(); }
1702 private:
1703 // The string for which we are getting information.
1704 Expression* string_;
1705 // What information we want.
1706 String_info string_info_;
1709 // Return the type of the string info.
1711 Type*
1712 String_info_expression::do_type()
1714 switch (this->string_info_)
1716 case STRING_INFO_DATA:
1718 Type* byte_type = Type::lookup_integer_type("uint8");
1719 return Type::make_pointer_type(byte_type);
1721 case STRING_INFO_LENGTH:
1722 return Type::lookup_integer_type("int");
1723 default:
1724 go_unreachable();
1728 // Return string information in GENERIC.
1730 Bexpression*
1731 String_info_expression::do_get_backend(Translate_context* context)
1733 Gogo* gogo = context->gogo();
1735 Bexpression* bstring = this->string_->get_backend(context);
1736 switch (this->string_info_)
1738 case STRING_INFO_DATA:
1739 case STRING_INFO_LENGTH:
1740 return gogo->backend()->struct_field_expression(bstring,
1741 this->string_info_,
1742 this->location());
1743 break;
1744 default:
1745 go_unreachable();
1749 // Dump ast representation for a type info expression.
1751 void
1752 String_info_expression::do_dump_expression(
1753 Ast_dump_context* ast_dump_context) const
1755 ast_dump_context->ostream() << "stringinfo(";
1756 this->string_->dump_expression(ast_dump_context);
1757 ast_dump_context->ostream() << ",";
1758 ast_dump_context->ostream() <<
1759 (this->string_info_ == STRING_INFO_DATA ? "data"
1760 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1761 : "unknown");
1762 ast_dump_context->ostream() << ")";
1765 // Make a string info expression.
1767 Expression*
1768 Expression::make_string_info(Expression* string, String_info string_info,
1769 Location location)
1771 return new String_info_expression(string, string_info, location);
1774 // Make an integer expression.
1776 class Integer_expression : public Expression
1778 public:
1779 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1780 Location location)
1781 : Expression(EXPRESSION_INTEGER, location),
1782 type_(type), is_character_constant_(is_character_constant)
1783 { mpz_init_set(this->val_, *val); }
1785 static Expression*
1786 do_import(Import*);
1788 // Write VAL to string dump.
1789 static void
1790 export_integer(String_dump* exp, const mpz_t val);
1792 // Write VAL to dump context.
1793 static void
1794 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1796 protected:
1797 bool
1798 do_is_constant() const
1799 { return true; }
1801 bool
1802 do_is_immutable() const
1803 { return true; }
1805 bool
1806 do_numeric_constant_value(Numeric_constant* nc) const;
1808 Type*
1809 do_type();
1811 void
1812 do_determine_type(const Type_context* context);
1814 void
1815 do_check_types(Gogo*);
1817 Bexpression*
1818 do_get_backend(Translate_context*);
1820 Expression*
1821 do_copy()
1823 if (this->is_character_constant_)
1824 return Expression::make_character(&this->val_, this->type_,
1825 this->location());
1826 else
1827 return Expression::make_integer(&this->val_, this->type_,
1828 this->location());
1831 void
1832 do_export(Export*) const;
1834 void
1835 do_dump_expression(Ast_dump_context*) const;
1837 private:
1838 // The integer value.
1839 mpz_t val_;
1840 // The type so far.
1841 Type* type_;
1842 // Whether this is a character constant.
1843 bool is_character_constant_;
1846 // Return a numeric constant for this expression. We have to mark
1847 // this as a character when appropriate.
1849 bool
1850 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1852 if (this->is_character_constant_)
1853 nc->set_rune(this->type_, this->val_);
1854 else
1855 nc->set_int(this->type_, this->val_);
1856 return true;
1859 // Return the current type. If we haven't set the type yet, we return
1860 // an abstract integer type.
1862 Type*
1863 Integer_expression::do_type()
1865 if (this->type_ == NULL)
1867 if (this->is_character_constant_)
1868 this->type_ = Type::make_abstract_character_type();
1869 else
1870 this->type_ = Type::make_abstract_integer_type();
1872 return this->type_;
1875 // Set the type of the integer value. Here we may switch from an
1876 // abstract type to a real type.
1878 void
1879 Integer_expression::do_determine_type(const Type_context* context)
1881 if (this->type_ != NULL && !this->type_->is_abstract())
1883 else if (context->type != NULL && context->type->is_numeric_type())
1884 this->type_ = context->type;
1885 else if (!context->may_be_abstract)
1887 if (this->is_character_constant_)
1888 this->type_ = Type::lookup_integer_type("int32");
1889 else
1890 this->type_ = Type::lookup_integer_type("int");
1894 // Check the type of an integer constant.
1896 void
1897 Integer_expression::do_check_types(Gogo*)
1899 Type* type = this->type_;
1900 if (type == NULL)
1901 return;
1902 Numeric_constant nc;
1903 if (this->is_character_constant_)
1904 nc.set_rune(NULL, this->val_);
1905 else
1906 nc.set_int(NULL, this->val_);
1907 if (!nc.set_type(type, true, this->location()))
1908 this->set_is_error();
1911 // Get the backend representation for an integer constant.
1913 Bexpression*
1914 Integer_expression::do_get_backend(Translate_context* context)
1916 Type* resolved_type = NULL;
1917 if (this->type_ != NULL && !this->type_->is_abstract())
1918 resolved_type = this->type_;
1919 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1921 // We are converting to an abstract floating point type.
1922 resolved_type = Type::lookup_float_type("float64");
1924 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1926 // We are converting to an abstract complex type.
1927 resolved_type = Type::lookup_complex_type("complex128");
1929 else
1931 // If we still have an abstract type here, then this is being
1932 // used in a constant expression which didn't get reduced for
1933 // some reason. Use a type which will fit the value. We use <,
1934 // not <=, because we need an extra bit for the sign bit.
1935 int bits = mpz_sizeinbase(this->val_, 2);
1936 Type* int_type = Type::lookup_integer_type("int");
1937 if (bits < int_type->integer_type()->bits())
1938 resolved_type = int_type;
1939 else if (bits < 64)
1940 resolved_type = Type::lookup_integer_type("int64");
1941 else
1943 if (!saw_errors())
1944 error_at(this->location(),
1945 "unknown type for large integer constant");
1946 return context->gogo()->backend()->error_expression();
1949 Numeric_constant nc;
1950 nc.set_int(resolved_type, this->val_);
1951 return Expression::backend_numeric_constant_expression(context, &nc);
1954 // Write VAL to export data.
1956 void
1957 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1959 char* s = mpz_get_str(NULL, 10, val);
1960 exp->write_c_string(s);
1961 free(s);
1964 // Export an integer in a constant expression.
1966 void
1967 Integer_expression::do_export(Export* exp) const
1969 Integer_expression::export_integer(exp, this->val_);
1970 if (this->is_character_constant_)
1971 exp->write_c_string("'");
1972 // A trailing space lets us reliably identify the end of the number.
1973 exp->write_c_string(" ");
1976 // Import an integer, floating point, or complex value. This handles
1977 // all these types because they all start with digits.
1979 Expression*
1980 Integer_expression::do_import(Import* imp)
1982 std::string num = imp->read_identifier();
1983 imp->require_c_string(" ");
1984 if (!num.empty() && num[num.length() - 1] == 'i')
1986 mpfr_t real;
1987 size_t plus_pos = num.find('+', 1);
1988 size_t minus_pos = num.find('-', 1);
1989 size_t pos;
1990 if (plus_pos == std::string::npos)
1991 pos = minus_pos;
1992 else if (minus_pos == std::string::npos)
1993 pos = plus_pos;
1994 else
1996 error_at(imp->location(), "bad number in import data: %qs",
1997 num.c_str());
1998 return Expression::make_error(imp->location());
2000 if (pos == std::string::npos)
2001 mpfr_set_ui(real, 0, GMP_RNDN);
2002 else
2004 std::string real_str = num.substr(0, pos);
2005 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2007 error_at(imp->location(), "bad number in import data: %qs",
2008 real_str.c_str());
2009 return Expression::make_error(imp->location());
2013 std::string imag_str;
2014 if (pos == std::string::npos)
2015 imag_str = num;
2016 else
2017 imag_str = num.substr(pos);
2018 imag_str = imag_str.substr(0, imag_str.size() - 1);
2019 mpfr_t imag;
2020 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2022 error_at(imp->location(), "bad number in import data: %qs",
2023 imag_str.c_str());
2024 return Expression::make_error(imp->location());
2026 Expression* ret = Expression::make_complex(&real, &imag, NULL,
2027 imp->location());
2028 mpfr_clear(real);
2029 mpfr_clear(imag);
2030 return ret;
2032 else if (num.find('.') == std::string::npos
2033 && num.find('E') == std::string::npos)
2035 bool is_character_constant = (!num.empty()
2036 && num[num.length() - 1] == '\'');
2037 if (is_character_constant)
2038 num = num.substr(0, num.length() - 1);
2039 mpz_t val;
2040 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2042 error_at(imp->location(), "bad number in import data: %qs",
2043 num.c_str());
2044 return Expression::make_error(imp->location());
2046 Expression* ret;
2047 if (is_character_constant)
2048 ret = Expression::make_character(&val, NULL, imp->location());
2049 else
2050 ret = Expression::make_integer(&val, NULL, imp->location());
2051 mpz_clear(val);
2052 return ret;
2054 else
2056 mpfr_t val;
2057 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2059 error_at(imp->location(), "bad number in import data: %qs",
2060 num.c_str());
2061 return Expression::make_error(imp->location());
2063 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2064 mpfr_clear(val);
2065 return ret;
2068 // Ast dump for integer expression.
2070 void
2071 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2073 if (this->is_character_constant_)
2074 ast_dump_context->ostream() << '\'';
2075 Integer_expression::export_integer(ast_dump_context, this->val_);
2076 if (this->is_character_constant_)
2077 ast_dump_context->ostream() << '\'';
2080 // Build a new integer value.
2082 Expression*
2083 Expression::make_integer(const mpz_t* val, Type* type, Location location)
2085 return new Integer_expression(val, type, false, location);
2088 // Build a new character constant value.
2090 Expression*
2091 Expression::make_character(const mpz_t* val, Type* type, Location location)
2093 return new Integer_expression(val, type, true, location);
2096 // Floats.
2098 class Float_expression : public Expression
2100 public:
2101 Float_expression(const mpfr_t* val, Type* type, Location location)
2102 : Expression(EXPRESSION_FLOAT, location),
2103 type_(type)
2105 mpfr_init_set(this->val_, *val, GMP_RNDN);
2108 // Write VAL to export data.
2109 static void
2110 export_float(String_dump* exp, const mpfr_t val);
2112 // Write VAL to dump file.
2113 static void
2114 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2116 protected:
2117 bool
2118 do_is_constant() const
2119 { return true; }
2121 bool
2122 do_is_immutable() const
2123 { return true; }
2125 bool
2126 do_numeric_constant_value(Numeric_constant* nc) const
2128 nc->set_float(this->type_, this->val_);
2129 return true;
2132 Type*
2133 do_type();
2135 void
2136 do_determine_type(const Type_context*);
2138 void
2139 do_check_types(Gogo*);
2141 Expression*
2142 do_copy()
2143 { return Expression::make_float(&this->val_, this->type_,
2144 this->location()); }
2146 Bexpression*
2147 do_get_backend(Translate_context*);
2149 void
2150 do_export(Export*) const;
2152 void
2153 do_dump_expression(Ast_dump_context*) const;
2155 private:
2156 // The floating point value.
2157 mpfr_t val_;
2158 // The type so far.
2159 Type* type_;
2162 // Return the current type. If we haven't set the type yet, we return
2163 // an abstract float type.
2165 Type*
2166 Float_expression::do_type()
2168 if (this->type_ == NULL)
2169 this->type_ = Type::make_abstract_float_type();
2170 return this->type_;
2173 // Set the type of the float value. Here we may switch from an
2174 // abstract type to a real type.
2176 void
2177 Float_expression::do_determine_type(const Type_context* context)
2179 if (this->type_ != NULL && !this->type_->is_abstract())
2181 else if (context->type != NULL
2182 && (context->type->integer_type() != NULL
2183 || context->type->float_type() != NULL
2184 || context->type->complex_type() != NULL))
2185 this->type_ = context->type;
2186 else if (!context->may_be_abstract)
2187 this->type_ = Type::lookup_float_type("float64");
2190 // Check the type of a float value.
2192 void
2193 Float_expression::do_check_types(Gogo*)
2195 Type* type = this->type_;
2196 if (type == NULL)
2197 return;
2198 Numeric_constant nc;
2199 nc.set_float(NULL, this->val_);
2200 if (!nc.set_type(this->type_, true, this->location()))
2201 this->set_is_error();
2204 // Get the backend representation for a float constant.
2206 Bexpression*
2207 Float_expression::do_get_backend(Translate_context* context)
2209 Type* resolved_type;
2210 if (this->type_ != NULL && !this->type_->is_abstract())
2211 resolved_type = this->type_;
2212 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2214 // We have an abstract integer type. We just hope for the best.
2215 resolved_type = Type::lookup_integer_type("int");
2217 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2219 // We are converting to an abstract complex type.
2220 resolved_type = Type::lookup_complex_type("complex128");
2222 else
2224 // If we still have an abstract type here, then this is being
2225 // used in a constant expression which didn't get reduced. We
2226 // just use float64 and hope for the best.
2227 resolved_type = Type::lookup_float_type("float64");
2230 Numeric_constant nc;
2231 nc.set_float(resolved_type, this->val_);
2232 return Expression::backend_numeric_constant_expression(context, &nc);
2235 // Write a floating point number to a string dump.
2237 void
2238 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2240 mp_exp_t exponent;
2241 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2242 if (*s == '-')
2243 exp->write_c_string("-");
2244 exp->write_c_string("0.");
2245 exp->write_c_string(*s == '-' ? s + 1 : s);
2246 mpfr_free_str(s);
2247 char buf[30];
2248 snprintf(buf, sizeof buf, "E%ld", exponent);
2249 exp->write_c_string(buf);
2252 // Export a floating point number in a constant expression.
2254 void
2255 Float_expression::do_export(Export* exp) const
2257 Float_expression::export_float(exp, this->val_);
2258 // A trailing space lets us reliably identify the end of the number.
2259 exp->write_c_string(" ");
2262 // Dump a floating point number to the dump file.
2264 void
2265 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2267 Float_expression::export_float(ast_dump_context, this->val_);
2270 // Make a float expression.
2272 Expression*
2273 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2275 return new Float_expression(val, type, location);
2278 // Complex numbers.
2280 class Complex_expression : public Expression
2282 public:
2283 Complex_expression(const mpfr_t* real, const mpfr_t* imag, Type* type,
2284 Location location)
2285 : Expression(EXPRESSION_COMPLEX, location),
2286 type_(type)
2288 mpfr_init_set(this->real_, *real, GMP_RNDN);
2289 mpfr_init_set(this->imag_, *imag, GMP_RNDN);
2292 // Write REAL/IMAG to string dump.
2293 static void
2294 export_complex(String_dump* exp, const mpfr_t real, const mpfr_t val);
2296 // Write REAL/IMAG to dump context.
2297 static void
2298 dump_complex(Ast_dump_context* ast_dump_context,
2299 const mpfr_t real, const mpfr_t val);
2301 protected:
2302 bool
2303 do_is_constant() const
2304 { return true; }
2306 bool
2307 do_is_immutable() const
2308 { return true; }
2310 bool
2311 do_numeric_constant_value(Numeric_constant* nc) const
2313 nc->set_complex(this->type_, this->real_, this->imag_);
2314 return true;
2317 Type*
2318 do_type();
2320 void
2321 do_determine_type(const Type_context*);
2323 void
2324 do_check_types(Gogo*);
2326 Expression*
2327 do_copy()
2329 return Expression::make_complex(&this->real_, &this->imag_, this->type_,
2330 this->location());
2333 Bexpression*
2334 do_get_backend(Translate_context*);
2336 void
2337 do_export(Export*) const;
2339 void
2340 do_dump_expression(Ast_dump_context*) const;
2342 private:
2343 // The real part.
2344 mpfr_t real_;
2345 // The imaginary part;
2346 mpfr_t imag_;
2347 // The type if known.
2348 Type* type_;
2351 // Return the current type. If we haven't set the type yet, we return
2352 // an abstract complex type.
2354 Type*
2355 Complex_expression::do_type()
2357 if (this->type_ == NULL)
2358 this->type_ = Type::make_abstract_complex_type();
2359 return this->type_;
2362 // Set the type of the complex value. Here we may switch from an
2363 // abstract type to a real type.
2365 void
2366 Complex_expression::do_determine_type(const Type_context* context)
2368 if (this->type_ != NULL && !this->type_->is_abstract())
2370 else if (context->type != NULL
2371 && context->type->complex_type() != NULL)
2372 this->type_ = context->type;
2373 else if (!context->may_be_abstract)
2374 this->type_ = Type::lookup_complex_type("complex128");
2377 // Check the type of a complex value.
2379 void
2380 Complex_expression::do_check_types(Gogo*)
2382 Type* type = this->type_;
2383 if (type == NULL)
2384 return;
2385 Numeric_constant nc;
2386 nc.set_complex(NULL, this->real_, this->imag_);
2387 if (!nc.set_type(this->type_, true, this->location()))
2388 this->set_is_error();
2391 // Get the backend representation for a complex constant.
2393 Bexpression*
2394 Complex_expression::do_get_backend(Translate_context* context)
2396 Type* resolved_type;
2397 if (this->type_ != NULL && !this->type_->is_abstract())
2398 resolved_type = this->type_;
2399 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2401 // We are converting to an abstract integer type.
2402 resolved_type = Type::lookup_integer_type("int");
2404 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2406 // We are converting to an abstract float type.
2407 resolved_type = Type::lookup_float_type("float64");
2409 else
2411 // If we still have an abstract type here, this this is being
2412 // used in a constant expression which didn't get reduced. We
2413 // just use complex128 and hope for the best.
2414 resolved_type = Type::lookup_complex_type("complex128");
2417 Numeric_constant nc;
2418 nc.set_complex(resolved_type, this->real_, this->imag_);
2419 return Expression::backend_numeric_constant_expression(context, &nc);
2422 // Write REAL/IMAG to export data.
2424 void
2425 Complex_expression::export_complex(String_dump* exp, const mpfr_t real,
2426 const mpfr_t imag)
2428 if (!mpfr_zero_p(real))
2430 Float_expression::export_float(exp, real);
2431 if (mpfr_sgn(imag) > 0)
2432 exp->write_c_string("+");
2434 Float_expression::export_float(exp, imag);
2435 exp->write_c_string("i");
2438 // Export a complex number in a constant expression.
2440 void
2441 Complex_expression::do_export(Export* exp) const
2443 Complex_expression::export_complex(exp, this->real_, this->imag_);
2444 // A trailing space lets us reliably identify the end of the number.
2445 exp->write_c_string(" ");
2448 // Dump a complex expression to the dump file.
2450 void
2451 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2453 Complex_expression::export_complex(ast_dump_context,
2454 this->real_,
2455 this->imag_);
2458 // Make a complex expression.
2460 Expression*
2461 Expression::make_complex(const mpfr_t* real, const mpfr_t* imag, Type* type,
2462 Location location)
2464 return new Complex_expression(real, imag, type, location);
2467 // Find a named object in an expression.
2469 class Find_named_object : public Traverse
2471 public:
2472 Find_named_object(Named_object* no)
2473 : Traverse(traverse_expressions),
2474 no_(no), found_(false)
2477 // Whether we found the object.
2478 bool
2479 found() const
2480 { return this->found_; }
2482 protected:
2484 expression(Expression**);
2486 private:
2487 // The object we are looking for.
2488 Named_object* no_;
2489 // Whether we found it.
2490 bool found_;
2493 // A reference to a const in an expression.
2495 class Const_expression : public Expression
2497 public:
2498 Const_expression(Named_object* constant, Location location)
2499 : Expression(EXPRESSION_CONST_REFERENCE, location),
2500 constant_(constant), type_(NULL), seen_(false)
2503 Named_object*
2504 named_object()
2505 { return this->constant_; }
2507 // Check that the initializer does not refer to the constant itself.
2508 void
2509 check_for_init_loop();
2511 protected:
2513 do_traverse(Traverse*);
2515 Expression*
2516 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2518 bool
2519 do_is_constant() const
2520 { return true; }
2522 bool
2523 do_is_immutable() const
2524 { return true; }
2526 bool
2527 do_numeric_constant_value(Numeric_constant* nc) const;
2529 bool
2530 do_string_constant_value(std::string* val) const;
2532 Type*
2533 do_type();
2535 // The type of a const is set by the declaration, not the use.
2536 void
2537 do_determine_type(const Type_context*);
2539 void
2540 do_check_types(Gogo*);
2542 Expression*
2543 do_copy()
2544 { return this; }
2546 Bexpression*
2547 do_get_backend(Translate_context* context);
2549 // When exporting a reference to a const as part of a const
2550 // expression, we export the value. We ignore the fact that it has
2551 // a name.
2552 void
2553 do_export(Export* exp) const
2554 { this->constant_->const_value()->expr()->export_expression(exp); }
2556 void
2557 do_dump_expression(Ast_dump_context*) const;
2559 private:
2560 // The constant.
2561 Named_object* constant_;
2562 // The type of this reference. This is used if the constant has an
2563 // abstract type.
2564 Type* type_;
2565 // Used to prevent infinite recursion when a constant incorrectly
2566 // refers to itself.
2567 mutable bool seen_;
2570 // Traversal.
2573 Const_expression::do_traverse(Traverse* traverse)
2575 if (this->type_ != NULL)
2576 return Type::traverse(this->type_, traverse);
2577 return TRAVERSE_CONTINUE;
2580 // Lower a constant expression. This is where we convert the
2581 // predeclared constant iota into an integer value.
2583 Expression*
2584 Const_expression::do_lower(Gogo* gogo, Named_object*,
2585 Statement_inserter*, int iota_value)
2587 if (this->constant_->const_value()->expr()->classification()
2588 == EXPRESSION_IOTA)
2590 if (iota_value == -1)
2592 error_at(this->location(),
2593 "iota is only defined in const declarations");
2594 iota_value = 0;
2596 mpz_t val;
2597 mpz_init_set_ui(val, static_cast<unsigned long>(iota_value));
2598 Expression* ret = Expression::make_integer(&val, NULL,
2599 this->location());
2600 mpz_clear(val);
2601 return ret;
2604 // Make sure that the constant itself has been lowered.
2605 gogo->lower_constant(this->constant_);
2607 return this;
2610 // Return a numeric constant value.
2612 bool
2613 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2615 if (this->seen_)
2616 return false;
2618 Expression* e = this->constant_->const_value()->expr();
2620 this->seen_ = true;
2622 bool r = e->numeric_constant_value(nc);
2624 this->seen_ = false;
2626 Type* ctype;
2627 if (this->type_ != NULL)
2628 ctype = this->type_;
2629 else
2630 ctype = this->constant_->const_value()->type();
2631 if (r && ctype != NULL)
2633 if (!nc->set_type(ctype, false, this->location()))
2634 return false;
2637 return r;
2640 bool
2641 Const_expression::do_string_constant_value(std::string* val) const
2643 if (this->seen_)
2644 return false;
2646 Expression* e = this->constant_->const_value()->expr();
2648 this->seen_ = true;
2649 bool ok = e->string_constant_value(val);
2650 this->seen_ = false;
2652 return ok;
2655 // Return the type of the const reference.
2657 Type*
2658 Const_expression::do_type()
2660 if (this->type_ != NULL)
2661 return this->type_;
2663 Named_constant* nc = this->constant_->const_value();
2665 if (this->seen_ || nc->lowering())
2667 this->report_error(_("constant refers to itself"));
2668 this->type_ = Type::make_error_type();
2669 return this->type_;
2672 this->seen_ = true;
2674 Type* ret = nc->type();
2676 if (ret != NULL)
2678 this->seen_ = false;
2679 return ret;
2682 // During parsing, a named constant may have a NULL type, but we
2683 // must not return a NULL type here.
2684 ret = nc->expr()->type();
2686 this->seen_ = false;
2688 return ret;
2691 // Set the type of the const reference.
2693 void
2694 Const_expression::do_determine_type(const Type_context* context)
2696 Type* ctype = this->constant_->const_value()->type();
2697 Type* cetype = (ctype != NULL
2698 ? ctype
2699 : this->constant_->const_value()->expr()->type());
2700 if (ctype != NULL && !ctype->is_abstract())
2702 else if (context->type != NULL
2703 && context->type->is_numeric_type()
2704 && cetype->is_numeric_type())
2705 this->type_ = context->type;
2706 else if (context->type != NULL
2707 && context->type->is_string_type()
2708 && cetype->is_string_type())
2709 this->type_ = context->type;
2710 else if (context->type != NULL
2711 && context->type->is_boolean_type()
2712 && cetype->is_boolean_type())
2713 this->type_ = context->type;
2714 else if (!context->may_be_abstract)
2716 if (cetype->is_abstract())
2717 cetype = cetype->make_non_abstract_type();
2718 this->type_ = cetype;
2722 // Check for a loop in which the initializer of a constant refers to
2723 // the constant itself.
2725 void
2726 Const_expression::check_for_init_loop()
2728 if (this->type_ != NULL && this->type_->is_error())
2729 return;
2731 if (this->seen_)
2733 this->report_error(_("constant refers to itself"));
2734 this->type_ = Type::make_error_type();
2735 return;
2738 Expression* init = this->constant_->const_value()->expr();
2739 Find_named_object find_named_object(this->constant_);
2741 this->seen_ = true;
2742 Expression::traverse(&init, &find_named_object);
2743 this->seen_ = false;
2745 if (find_named_object.found())
2747 if (this->type_ == NULL || !this->type_->is_error())
2749 this->report_error(_("constant refers to itself"));
2750 this->type_ = Type::make_error_type();
2752 return;
2756 // Check types of a const reference.
2758 void
2759 Const_expression::do_check_types(Gogo*)
2761 if (this->type_ != NULL && this->type_->is_error())
2762 return;
2764 this->check_for_init_loop();
2766 // Check that numeric constant fits in type.
2767 if (this->type_ != NULL && this->type_->is_numeric_type())
2769 Numeric_constant nc;
2770 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2772 if (!nc.set_type(this->type_, true, this->location()))
2773 this->set_is_error();
2778 // Return the backend representation for a const reference.
2780 Bexpression*
2781 Const_expression::do_get_backend(Translate_context* context)
2783 if (this->type_ != NULL && this->type_->is_error())
2784 return context->backend()->error_expression();
2786 // If the type has been set for this expression, but the underlying
2787 // object is an abstract int or float, we try to get the abstract
2788 // value. Otherwise we may lose something in the conversion.
2789 Expression* expr = this->constant_->const_value()->expr();
2790 if (this->type_ != NULL
2791 && this->type_->is_numeric_type()
2792 && (this->constant_->const_value()->type() == NULL
2793 || this->constant_->const_value()->type()->is_abstract()))
2795 Numeric_constant nc;
2796 if (expr->numeric_constant_value(&nc)
2797 && nc.set_type(this->type_, false, this->location()))
2799 Expression* e = nc.expression(this->location());
2800 return e->get_backend(context);
2804 if (this->type_ != NULL)
2805 expr = Expression::make_cast(this->type_, expr, this->location());
2806 return expr->get_backend(context);
2809 // Dump ast representation for constant expression.
2811 void
2812 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2814 ast_dump_context->ostream() << this->constant_->name();
2817 // Make a reference to a constant in an expression.
2819 Expression*
2820 Expression::make_const_reference(Named_object* constant,
2821 Location location)
2823 return new Const_expression(constant, location);
2826 // Find a named object in an expression.
2829 Find_named_object::expression(Expression** pexpr)
2831 switch ((*pexpr)->classification())
2833 case Expression::EXPRESSION_CONST_REFERENCE:
2835 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2836 if (ce->named_object() == this->no_)
2837 break;
2839 // We need to check a constant initializer explicitly, as
2840 // loops here will not be caught by the loop checking for
2841 // variable initializers.
2842 ce->check_for_init_loop();
2844 return TRAVERSE_CONTINUE;
2847 case Expression::EXPRESSION_VAR_REFERENCE:
2848 if ((*pexpr)->var_expression()->named_object() == this->no_)
2849 break;
2850 return TRAVERSE_CONTINUE;
2851 case Expression::EXPRESSION_FUNC_REFERENCE:
2852 if ((*pexpr)->func_expression()->named_object() == this->no_)
2853 break;
2854 return TRAVERSE_CONTINUE;
2855 default:
2856 return TRAVERSE_CONTINUE;
2858 this->found_ = true;
2859 return TRAVERSE_EXIT;
2862 // The nil value.
2864 class Nil_expression : public Expression
2866 public:
2867 Nil_expression(Location location)
2868 : Expression(EXPRESSION_NIL, location)
2871 static Expression*
2872 do_import(Import*);
2874 protected:
2875 bool
2876 do_is_constant() const
2877 { return true; }
2879 bool
2880 do_is_immutable() const
2881 { return true; }
2883 Type*
2884 do_type()
2885 { return Type::make_nil_type(); }
2887 void
2888 do_determine_type(const Type_context*)
2891 Expression*
2892 do_copy()
2893 { return this; }
2895 Bexpression*
2896 do_get_backend(Translate_context* context)
2897 { return context->backend()->nil_pointer_expression(); }
2899 void
2900 do_export(Export* exp) const
2901 { exp->write_c_string("nil"); }
2903 void
2904 do_dump_expression(Ast_dump_context* ast_dump_context) const
2905 { ast_dump_context->ostream() << "nil"; }
2908 // Import a nil expression.
2910 Expression*
2911 Nil_expression::do_import(Import* imp)
2913 imp->require_c_string("nil");
2914 return Expression::make_nil(imp->location());
2917 // Make a nil expression.
2919 Expression*
2920 Expression::make_nil(Location location)
2922 return new Nil_expression(location);
2925 // The value of the predeclared constant iota. This is little more
2926 // than a marker. This will be lowered to an integer in
2927 // Const_expression::do_lower, which is where we know the value that
2928 // it should have.
2930 class Iota_expression : public Parser_expression
2932 public:
2933 Iota_expression(Location location)
2934 : Parser_expression(EXPRESSION_IOTA, location)
2937 protected:
2938 Expression*
2939 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2940 { go_unreachable(); }
2942 // There should only ever be one of these.
2943 Expression*
2944 do_copy()
2945 { go_unreachable(); }
2947 void
2948 do_dump_expression(Ast_dump_context* ast_dump_context) const
2949 { ast_dump_context->ostream() << "iota"; }
2952 // Make an iota expression. This is only called for one case: the
2953 // value of the predeclared constant iota.
2955 Expression*
2956 Expression::make_iota()
2958 static Iota_expression iota_expression(Linemap::unknown_location());
2959 return &iota_expression;
2962 // A type conversion expression.
2964 class Type_conversion_expression : public Expression
2966 public:
2967 Type_conversion_expression(Type* type, Expression* expr,
2968 Location location)
2969 : Expression(EXPRESSION_CONVERSION, location),
2970 type_(type), expr_(expr), may_convert_function_types_(false)
2973 // Return the type to which we are converting.
2974 Type*
2975 type() const
2976 { return this->type_; }
2978 // Return the expression which we are converting.
2979 Expression*
2980 expr() const
2981 { return this->expr_; }
2983 // Permit converting from one function type to another. This is
2984 // used internally for method expressions.
2985 void
2986 set_may_convert_function_types()
2988 this->may_convert_function_types_ = true;
2991 // Import a type conversion expression.
2992 static Expression*
2993 do_import(Import*);
2995 protected:
2997 do_traverse(Traverse* traverse);
2999 Expression*
3000 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
3002 Expression*
3003 do_flatten(Gogo*, Named_object*, Statement_inserter*);
3005 bool
3006 do_is_constant() const;
3008 bool
3009 do_is_immutable() const;
3011 bool
3012 do_numeric_constant_value(Numeric_constant*) const;
3014 bool
3015 do_string_constant_value(std::string*) const;
3017 Type*
3018 do_type()
3019 { return this->type_; }
3021 void
3022 do_determine_type(const Type_context*)
3024 Type_context subcontext(this->type_, false);
3025 this->expr_->determine_type(&subcontext);
3028 void
3029 do_check_types(Gogo*);
3031 Expression*
3032 do_copy()
3034 return new Type_conversion_expression(this->type_, this->expr_->copy(),
3035 this->location());
3038 Bexpression*
3039 do_get_backend(Translate_context* context);
3041 void
3042 do_export(Export*) const;
3044 void
3045 do_dump_expression(Ast_dump_context*) const;
3047 private:
3048 // The type to convert to.
3049 Type* type_;
3050 // The expression to convert.
3051 Expression* expr_;
3052 // True if this is permitted to convert function types. This is
3053 // used internally for method expressions.
3054 bool may_convert_function_types_;
3057 // Traversal.
3060 Type_conversion_expression::do_traverse(Traverse* traverse)
3062 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3063 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3064 return TRAVERSE_EXIT;
3065 return TRAVERSE_CONTINUE;
3068 // Convert to a constant at lowering time.
3070 Expression*
3071 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3072 Statement_inserter*, int)
3074 Type* type = this->type_;
3075 Expression* val = this->expr_;
3076 Location location = this->location();
3078 if (type->is_numeric_type())
3080 Numeric_constant nc;
3081 if (val->numeric_constant_value(&nc))
3083 if (!nc.set_type(type, true, location))
3084 return Expression::make_error(location);
3085 return nc.expression(location);
3089 if (type->is_slice_type())
3091 Type* element_type = type->array_type()->element_type()->forwarded();
3092 bool is_byte = (element_type->integer_type() != NULL
3093 && element_type->integer_type()->is_byte());
3094 bool is_rune = (element_type->integer_type() != NULL
3095 && element_type->integer_type()->is_rune());
3096 if (is_byte || is_rune)
3098 std::string s;
3099 if (val->string_constant_value(&s))
3101 Expression_list* vals = new Expression_list();
3102 if (is_byte)
3104 for (std::string::const_iterator p = s.begin();
3105 p != s.end();
3106 p++)
3108 mpz_t val;
3109 mpz_init_set_ui(val, static_cast<unsigned char>(*p));
3110 Expression* v = Expression::make_integer(&val,
3111 element_type,
3112 location);
3113 vals->push_back(v);
3114 mpz_clear(val);
3117 else
3119 const char *p = s.data();
3120 const char *pend = s.data() + s.length();
3121 while (p < pend)
3123 unsigned int c;
3124 int adv = Lex::fetch_char(p, &c);
3125 if (adv == 0)
3127 warning_at(this->location(), 0,
3128 "invalid UTF-8 encoding");
3129 adv = 1;
3131 p += adv;
3132 mpz_t val;
3133 mpz_init_set_ui(val, c);
3134 Expression* v = Expression::make_integer(&val,
3135 element_type,
3136 location);
3137 vals->push_back(v);
3138 mpz_clear(val);
3142 return Expression::make_slice_composite_literal(type, vals,
3143 location);
3148 return this;
3151 // Flatten a type conversion by using a temporary variable for the slice
3152 // in slice to string conversions.
3154 Expression*
3155 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3156 Statement_inserter* inserter)
3158 if (((this->type()->is_string_type()
3159 && this->expr_->type()->is_slice_type())
3160 || (this->type()->interface_type() != NULL
3161 && this->expr_->type()->interface_type() != NULL))
3162 && !this->expr_->is_variable())
3164 Temporary_statement* temp =
3165 Statement::make_temporary(NULL, this->expr_, this->location());
3166 inserter->insert(temp);
3167 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3169 return this;
3172 // Return whether a type conversion is a constant.
3174 bool
3175 Type_conversion_expression::do_is_constant() const
3177 if (!this->expr_->is_constant())
3178 return false;
3180 // A conversion to a type that may not be used as a constant is not
3181 // a constant. For example, []byte(nil).
3182 Type* type = this->type_;
3183 if (type->integer_type() == NULL
3184 && type->float_type() == NULL
3185 && type->complex_type() == NULL
3186 && !type->is_boolean_type()
3187 && !type->is_string_type())
3188 return false;
3190 return true;
3193 // Return whether a type conversion is immutable.
3195 bool
3196 Type_conversion_expression::do_is_immutable() const
3198 Type* type = this->type_;
3199 Type* expr_type = this->expr_->type();
3201 if (type->interface_type() != NULL
3202 || expr_type->interface_type() != NULL)
3203 return false;
3205 if (!this->expr_->is_immutable())
3206 return false;
3208 if (Type::are_identical(type, expr_type, false, NULL))
3209 return true;
3211 return type->is_basic_type() && expr_type->is_basic_type();
3214 // Return the constant numeric value if there is one.
3216 bool
3217 Type_conversion_expression::do_numeric_constant_value(
3218 Numeric_constant* nc) const
3220 if (!this->type_->is_numeric_type())
3221 return false;
3222 if (!this->expr_->numeric_constant_value(nc))
3223 return false;
3224 return nc->set_type(this->type_, false, this->location());
3227 // Return the constant string value if there is one.
3229 bool
3230 Type_conversion_expression::do_string_constant_value(std::string* val) const
3232 if (this->type_->is_string_type()
3233 && this->expr_->type()->integer_type() != NULL)
3235 Numeric_constant nc;
3236 if (this->expr_->numeric_constant_value(&nc))
3238 unsigned long ival;
3239 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3241 val->clear();
3242 Lex::append_char(ival, true, val, this->location());
3243 return true;
3248 // FIXME: Could handle conversion from const []int here.
3250 return false;
3253 // Check that types are convertible.
3255 void
3256 Type_conversion_expression::do_check_types(Gogo*)
3258 Type* type = this->type_;
3259 Type* expr_type = this->expr_->type();
3260 std::string reason;
3262 if (type->is_error() || expr_type->is_error())
3264 this->set_is_error();
3265 return;
3268 if (this->may_convert_function_types_
3269 && type->function_type() != NULL
3270 && expr_type->function_type() != NULL)
3271 return;
3273 if (Type::are_convertible(type, expr_type, &reason))
3274 return;
3276 error_at(this->location(), "%s", reason.c_str());
3277 this->set_is_error();
3280 // Get the backend representation for a type conversion.
3282 Bexpression*
3283 Type_conversion_expression::do_get_backend(Translate_context* context)
3285 Type* type = this->type_;
3286 Type* expr_type = this->expr_->type();
3288 Gogo* gogo = context->gogo();
3289 Btype* btype = type->get_backend(gogo);
3290 Bexpression* bexpr = this->expr_->get_backend(context);
3291 Location loc = this->location();
3293 if (Type::are_identical(type, expr_type, false, NULL))
3294 return gogo->backend()->convert_expression(btype, bexpr, loc);
3295 else if (type->interface_type() != NULL
3296 || expr_type->interface_type() != NULL)
3298 Expression* conversion =
3299 Expression::convert_for_assignment(gogo, type, this->expr_,
3300 this->location());
3301 return conversion->get_backend(context);
3303 else if (type->is_string_type()
3304 && expr_type->integer_type() != NULL)
3306 mpz_t intval;
3307 Numeric_constant nc;
3308 if (this->expr_->numeric_constant_value(&nc)
3309 && nc.to_int(&intval)
3310 && mpz_fits_ushort_p(intval))
3312 std::string s;
3313 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3314 mpz_clear(intval);
3315 Expression* se = Expression::make_string(s, loc);
3316 return se->get_backend(context);
3319 Expression* i2s_expr =
3320 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3321 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3323 else if (type->is_string_type() && expr_type->is_slice_type())
3325 Array_type* a = expr_type->array_type();
3326 Type* e = a->element_type()->forwarded();
3327 go_assert(e->integer_type() != NULL);
3328 go_assert(this->expr_->is_variable());
3330 Runtime::Function code;
3331 if (e->integer_type()->is_byte())
3332 code = Runtime::BYTE_ARRAY_TO_STRING;
3333 else
3335 go_assert(e->integer_type()->is_rune());
3336 code = Runtime::INT_ARRAY_TO_STRING;
3338 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3339 Expression* len = a->get_length(gogo, this->expr_);
3340 return Runtime::make_call(code, loc, 2, valptr,
3341 len)->get_backend(context);
3343 else if (type->is_slice_type() && expr_type->is_string_type())
3345 Type* e = type->array_type()->element_type()->forwarded();
3346 go_assert(e->integer_type() != NULL);
3348 Runtime::Function code;
3349 if (e->integer_type()->is_byte())
3350 code = Runtime::STRING_TO_BYTE_ARRAY;
3351 else
3353 go_assert(e->integer_type()->is_rune());
3354 code = Runtime::STRING_TO_INT_ARRAY;
3356 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3357 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3359 else if (type->is_numeric_type())
3361 go_assert(Type::are_convertible(type, expr_type, NULL));
3362 return gogo->backend()->convert_expression(btype, bexpr, loc);
3364 else if ((type->is_unsafe_pointer_type()
3365 && (expr_type->points_to() != NULL
3366 || expr_type->integer_type()))
3367 || (expr_type->is_unsafe_pointer_type()
3368 && type->points_to() != NULL)
3369 || (this->may_convert_function_types_
3370 && type->function_type() != NULL
3371 && expr_type->function_type() != NULL))
3372 return gogo->backend()->convert_expression(btype, bexpr, loc);
3373 else
3375 Expression* conversion =
3376 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3377 return conversion->get_backend(context);
3381 // Output a type conversion in a constant expression.
3383 void
3384 Type_conversion_expression::do_export(Export* exp) const
3386 exp->write_c_string("convert(");
3387 exp->write_type(this->type_);
3388 exp->write_c_string(", ");
3389 this->expr_->export_expression(exp);
3390 exp->write_c_string(")");
3393 // Import a type conversion or a struct construction.
3395 Expression*
3396 Type_conversion_expression::do_import(Import* imp)
3398 imp->require_c_string("convert(");
3399 Type* type = imp->read_type();
3400 imp->require_c_string(", ");
3401 Expression* val = Expression::import_expression(imp);
3402 imp->require_c_string(")");
3403 return Expression::make_cast(type, val, imp->location());
3406 // Dump ast representation for a type conversion expression.
3408 void
3409 Type_conversion_expression::do_dump_expression(
3410 Ast_dump_context* ast_dump_context) const
3412 ast_dump_context->dump_type(this->type_);
3413 ast_dump_context->ostream() << "(";
3414 ast_dump_context->dump_expression(this->expr_);
3415 ast_dump_context->ostream() << ") ";
3418 // Make a type cast expression.
3420 Expression*
3421 Expression::make_cast(Type* type, Expression* val, Location location)
3423 if (type->is_error_type() || val->is_error_expression())
3424 return Expression::make_error(location);
3425 return new Type_conversion_expression(type, val, location);
3428 // An unsafe type conversion, used to pass values to builtin functions.
3430 class Unsafe_type_conversion_expression : public Expression
3432 public:
3433 Unsafe_type_conversion_expression(Type* type, Expression* expr,
3434 Location location)
3435 : Expression(EXPRESSION_UNSAFE_CONVERSION, location),
3436 type_(type), expr_(expr)
3439 protected:
3441 do_traverse(Traverse* traverse);
3443 Type*
3444 do_type()
3445 { return this->type_; }
3447 void
3448 do_determine_type(const Type_context*)
3449 { this->expr_->determine_type_no_context(); }
3451 Expression*
3452 do_copy()
3454 return new Unsafe_type_conversion_expression(this->type_,
3455 this->expr_->copy(),
3456 this->location());
3459 Bexpression*
3460 do_get_backend(Translate_context*);
3462 void
3463 do_dump_expression(Ast_dump_context*) const;
3465 private:
3466 // The type to convert to.
3467 Type* type_;
3468 // The expression to convert.
3469 Expression* expr_;
3472 // Traversal.
3475 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3477 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3478 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3479 return TRAVERSE_EXIT;
3480 return TRAVERSE_CONTINUE;
3483 // Convert to backend representation.
3485 Bexpression*
3486 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3488 // We are only called for a limited number of cases.
3490 Type* t = this->type_;
3491 Type* et = this->expr_->type();
3492 if (t->array_type() != NULL)
3493 go_assert(et->array_type() != NULL
3494 && t->is_slice_type() == et->is_slice_type());
3495 else if (t->struct_type() != NULL)
3497 if (t->named_type() != NULL
3498 && et->named_type() != NULL
3499 && !Type::are_convertible(t, et, NULL))
3501 go_assert(saw_errors());
3502 return context->backend()->error_expression();
3505 go_assert(et->struct_type() != NULL
3506 && Type::are_convertible(t, et, NULL));
3508 else if (t->map_type() != NULL)
3509 go_assert(et->map_type() != NULL);
3510 else if (t->channel_type() != NULL)
3511 go_assert(et->channel_type() != NULL);
3512 else if (t->points_to() != NULL)
3513 go_assert(et->points_to() != NULL
3514 || et->channel_type() != NULL
3515 || et->map_type() != NULL
3516 || et->function_type() != NULL
3517 || et->is_nil_type());
3518 else if (et->is_unsafe_pointer_type())
3519 go_assert(t->points_to() != NULL);
3520 else if (t->interface_type() != NULL)
3522 bool empty_iface = t->interface_type()->is_empty();
3523 go_assert(et->interface_type() != NULL
3524 && et->interface_type()->is_empty() == empty_iface);
3526 else if (t->integer_type() != NULL)
3527 go_assert(et->is_boolean_type()
3528 || et->integer_type() != NULL
3529 || et->function_type() != NULL
3530 || et->points_to() != NULL
3531 || et->map_type() != NULL
3532 || et->channel_type() != NULL);
3533 else
3534 go_unreachable();
3536 Gogo* gogo = context->gogo();
3537 Btype* btype = t->get_backend(gogo);
3538 Bexpression* bexpr = this->expr_->get_backend(context);
3539 Location loc = this->location();
3540 return gogo->backend()->convert_expression(btype, bexpr, loc);
3543 // Dump ast representation for an unsafe type conversion expression.
3545 void
3546 Unsafe_type_conversion_expression::do_dump_expression(
3547 Ast_dump_context* ast_dump_context) const
3549 ast_dump_context->dump_type(this->type_);
3550 ast_dump_context->ostream() << "(";
3551 ast_dump_context->dump_expression(this->expr_);
3552 ast_dump_context->ostream() << ") ";
3555 // Make an unsafe type conversion expression.
3557 Expression*
3558 Expression::make_unsafe_cast(Type* type, Expression* expr,
3559 Location location)
3561 return new Unsafe_type_conversion_expression(type, expr, location);
3564 // Class Unary_expression.
3566 // If we are taking the address of a composite literal, and the
3567 // contents are not constant, then we want to make a heap expression
3568 // instead.
3570 Expression*
3571 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3573 Location loc = this->location();
3574 Operator op = this->op_;
3575 Expression* expr = this->expr_;
3577 if (op == OPERATOR_MULT && expr->is_type_expression())
3578 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3580 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3581 // moving x to the heap. FIXME: Is it worth doing a real escape
3582 // analysis here? This case is found in math/unsafe.go and is
3583 // therefore worth special casing.
3584 if (op == OPERATOR_MULT)
3586 Expression* e = expr;
3587 while (e->classification() == EXPRESSION_CONVERSION)
3589 Type_conversion_expression* te
3590 = static_cast<Type_conversion_expression*>(e);
3591 e = te->expr();
3594 if (e->classification() == EXPRESSION_UNARY)
3596 Unary_expression* ue = static_cast<Unary_expression*>(e);
3597 if (ue->op_ == OPERATOR_AND)
3599 if (e == expr)
3601 // *&x == x.
3602 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3604 error_at(ue->location(),
3605 "invalid operand for unary %<&%>");
3606 this->set_is_error();
3608 return ue->expr_;
3610 ue->set_does_not_escape();
3615 // Catching an invalid indirection of unsafe.Pointer here avoid
3616 // having to deal with TYPE_VOID in other places.
3617 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3619 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3620 return Expression::make_error(this->location());
3623 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3625 Numeric_constant nc;
3626 if (expr->numeric_constant_value(&nc))
3628 Numeric_constant result;
3629 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3630 return result.expression(loc);
3634 return this;
3637 // Flatten expression if a nil check must be performed and create temporary
3638 // variables if necessary.
3640 Expression*
3641 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3642 Statement_inserter* inserter)
3644 if (this->is_error_expression() || this->expr_->is_error_expression())
3645 return Expression::make_error(this->location());
3647 Location location = this->location();
3648 if (this->op_ == OPERATOR_MULT
3649 && !this->expr_->is_variable())
3651 go_assert(this->expr_->type()->points_to() != NULL);
3652 Type* ptype = this->expr_->type()->points_to();
3653 if (!ptype->is_void_type())
3655 Btype* pbtype = ptype->get_backend(gogo);
3656 size_t s = gogo->backend()->type_size(pbtype);
3657 if (s >= 4096 || this->issue_nil_check_)
3659 Temporary_statement* temp =
3660 Statement::make_temporary(NULL, this->expr_, location);
3661 inserter->insert(temp);
3662 this->expr_ =
3663 Expression::make_temporary_reference(temp, location);
3668 if (this->create_temp_ && !this->expr_->is_variable())
3670 Temporary_statement* temp =
3671 Statement::make_temporary(NULL, this->expr_, location);
3672 inserter->insert(temp);
3673 this->expr_ = Expression::make_temporary_reference(temp, location);
3676 return this;
3679 // Return whether a unary expression is a constant.
3681 bool
3682 Unary_expression::do_is_constant() const
3684 if (this->op_ == OPERATOR_MULT)
3686 // Indirecting through a pointer is only constant if the object
3687 // to which the expression points is constant, but we currently
3688 // have no way to determine that.
3689 return false;
3691 else if (this->op_ == OPERATOR_AND)
3693 // Taking the address of a variable is constant if it is a
3694 // global variable, not constant otherwise. In other cases taking the
3695 // address is probably not a constant.
3696 Var_expression* ve = this->expr_->var_expression();
3697 if (ve != NULL)
3699 Named_object* no = ve->named_object();
3700 return no->is_variable() && no->var_value()->is_global();
3702 return false;
3704 else
3705 return this->expr_->is_constant();
3708 // Apply unary opcode OP to UNC, setting NC. Return true if this
3709 // could be done, false if not. Issue errors for overflow.
3711 bool
3712 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3713 Location location, Numeric_constant* nc)
3715 switch (op)
3717 case OPERATOR_PLUS:
3718 *nc = *unc;
3719 return true;
3721 case OPERATOR_MINUS:
3722 if (unc->is_int() || unc->is_rune())
3723 break;
3724 else if (unc->is_float())
3726 mpfr_t uval;
3727 unc->get_float(&uval);
3728 mpfr_t val;
3729 mpfr_init(val);
3730 mpfr_neg(val, uval, GMP_RNDN);
3731 nc->set_float(unc->type(), val);
3732 mpfr_clear(uval);
3733 mpfr_clear(val);
3734 return true;
3736 else if (unc->is_complex())
3738 mpfr_t ureal, uimag;
3739 unc->get_complex(&ureal, &uimag);
3740 mpfr_t real, imag;
3741 mpfr_init(real);
3742 mpfr_init(imag);
3743 mpfr_neg(real, ureal, GMP_RNDN);
3744 mpfr_neg(imag, uimag, GMP_RNDN);
3745 nc->set_complex(unc->type(), real, imag);
3746 mpfr_clear(ureal);
3747 mpfr_clear(uimag);
3748 mpfr_clear(real);
3749 mpfr_clear(imag);
3750 return true;
3752 else
3753 go_unreachable();
3755 case OPERATOR_XOR:
3756 break;
3758 case OPERATOR_NOT:
3759 case OPERATOR_AND:
3760 case OPERATOR_MULT:
3761 return false;
3763 default:
3764 go_unreachable();
3767 if (!unc->is_int() && !unc->is_rune())
3768 return false;
3770 mpz_t uval;
3771 if (unc->is_rune())
3772 unc->get_rune(&uval);
3773 else
3774 unc->get_int(&uval);
3775 mpz_t val;
3776 mpz_init(val);
3778 switch (op)
3780 case OPERATOR_MINUS:
3781 mpz_neg(val, uval);
3782 break;
3784 case OPERATOR_NOT:
3785 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3786 break;
3788 case OPERATOR_XOR:
3790 Type* utype = unc->type();
3791 if (utype->integer_type() == NULL
3792 || utype->integer_type()->is_abstract())
3793 mpz_com(val, uval);
3794 else
3796 // The number of HOST_WIDE_INTs that it takes to represent
3797 // UVAL.
3798 size_t count = ((mpz_sizeinbase(uval, 2)
3799 + HOST_BITS_PER_WIDE_INT
3800 - 1)
3801 / HOST_BITS_PER_WIDE_INT);
3803 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3804 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3806 size_t obits = utype->integer_type()->bits();
3808 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3810 mpz_t adj;
3811 mpz_init_set_ui(adj, 1);
3812 mpz_mul_2exp(adj, adj, obits);
3813 mpz_add(uval, uval, adj);
3814 mpz_clear(adj);
3817 size_t ecount;
3818 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3819 go_assert(ecount <= count);
3821 // Trim down to the number of words required by the type.
3822 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3823 / HOST_BITS_PER_WIDE_INT);
3824 go_assert(ocount <= count);
3826 for (size_t i = 0; i < ocount; ++i)
3827 phwi[i] = ~phwi[i];
3829 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3830 if (clearbits != 0)
3831 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3832 >> clearbits);
3834 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3836 if (!utype->integer_type()->is_unsigned()
3837 && mpz_tstbit(val, obits - 1))
3839 mpz_t adj;
3840 mpz_init_set_ui(adj, 1);
3841 mpz_mul_2exp(adj, adj, obits);
3842 mpz_sub(val, val, adj);
3843 mpz_clear(adj);
3846 delete[] phwi;
3849 break;
3851 default:
3852 go_unreachable();
3855 if (unc->is_rune())
3856 nc->set_rune(NULL, val);
3857 else
3858 nc->set_int(NULL, val);
3860 mpz_clear(uval);
3861 mpz_clear(val);
3863 return nc->set_type(unc->type(), true, location);
3866 // Return the integral constant value of a unary expression, if it has one.
3868 bool
3869 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3871 Numeric_constant unc;
3872 if (!this->expr_->numeric_constant_value(&unc))
3873 return false;
3874 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3875 nc);
3878 // Return the type of a unary expression.
3880 Type*
3881 Unary_expression::do_type()
3883 switch (this->op_)
3885 case OPERATOR_PLUS:
3886 case OPERATOR_MINUS:
3887 case OPERATOR_NOT:
3888 case OPERATOR_XOR:
3889 return this->expr_->type();
3891 case OPERATOR_AND:
3892 return Type::make_pointer_type(this->expr_->type());
3894 case OPERATOR_MULT:
3896 Type* subtype = this->expr_->type();
3897 Type* points_to = subtype->points_to();
3898 if (points_to == NULL)
3899 return Type::make_error_type();
3900 return points_to;
3903 default:
3904 go_unreachable();
3908 // Determine abstract types for a unary expression.
3910 void
3911 Unary_expression::do_determine_type(const Type_context* context)
3913 switch (this->op_)
3915 case OPERATOR_PLUS:
3916 case OPERATOR_MINUS:
3917 case OPERATOR_NOT:
3918 case OPERATOR_XOR:
3919 this->expr_->determine_type(context);
3920 break;
3922 case OPERATOR_AND:
3923 // Taking the address of something.
3925 Type* subtype = (context->type == NULL
3926 ? NULL
3927 : context->type->points_to());
3928 Type_context subcontext(subtype, false);
3929 this->expr_->determine_type(&subcontext);
3931 break;
3933 case OPERATOR_MULT:
3934 // Indirecting through a pointer.
3936 Type* subtype = (context->type == NULL
3937 ? NULL
3938 : Type::make_pointer_type(context->type));
3939 Type_context subcontext(subtype, false);
3940 this->expr_->determine_type(&subcontext);
3942 break;
3944 default:
3945 go_unreachable();
3949 // Check types for a unary expression.
3951 void
3952 Unary_expression::do_check_types(Gogo*)
3954 Type* type = this->expr_->type();
3955 if (type->is_error())
3957 this->set_is_error();
3958 return;
3961 switch (this->op_)
3963 case OPERATOR_PLUS:
3964 case OPERATOR_MINUS:
3965 if (type->integer_type() == NULL
3966 && type->float_type() == NULL
3967 && type->complex_type() == NULL)
3968 this->report_error(_("expected numeric type"));
3969 break;
3971 case OPERATOR_NOT:
3972 if (!type->is_boolean_type())
3973 this->report_error(_("expected boolean type"));
3974 break;
3976 case OPERATOR_XOR:
3977 if (type->integer_type() == NULL
3978 && !type->is_boolean_type())
3979 this->report_error(_("expected integer or boolean type"));
3980 break;
3982 case OPERATOR_AND:
3983 if (!this->expr_->is_addressable())
3985 if (!this->create_temp_)
3987 error_at(this->location(), "invalid operand for unary %<&%>");
3988 this->set_is_error();
3991 else
3993 this->expr_->address_taken(this->escapes_);
3994 this->expr_->issue_nil_check();
3996 break;
3998 case OPERATOR_MULT:
3999 // Indirecting through a pointer.
4000 if (type->points_to() == NULL)
4001 this->report_error(_("expected pointer"));
4002 break;
4004 default:
4005 go_unreachable();
4009 // Get the backend representation for a unary expression.
4011 Bexpression*
4012 Unary_expression::do_get_backend(Translate_context* context)
4014 Gogo* gogo = context->gogo();
4015 Location loc = this->location();
4017 // Taking the address of a set-and-use-temporary expression requires
4018 // setting the temporary and then taking the address.
4019 if (this->op_ == OPERATOR_AND)
4021 Set_and_use_temporary_expression* sut =
4022 this->expr_->set_and_use_temporary_expression();
4023 if (sut != NULL)
4025 Temporary_statement* temp = sut->temporary();
4026 Bvariable* bvar = temp->get_backend_variable(context);
4027 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
4028 Bexpression* bval = sut->expression()->get_backend(context);
4030 Bstatement* bassign =
4031 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
4032 Bexpression* bvar_addr =
4033 gogo->backend()->address_expression(bvar_expr, loc);
4034 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4038 Bexpression* ret;
4039 Bexpression* bexpr = this->expr_->get_backend(context);
4040 Btype* btype = this->expr_->type()->get_backend(gogo);
4041 switch (this->op_)
4043 case OPERATOR_PLUS:
4044 ret = bexpr;
4045 break;
4047 case OPERATOR_MINUS:
4048 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4049 ret = gogo->backend()->convert_expression(btype, ret, loc);
4050 break;
4052 case OPERATOR_NOT:
4053 case OPERATOR_XOR:
4054 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4055 break;
4057 case OPERATOR_AND:
4058 if (!this->create_temp_)
4060 // We should not see a non-constant constructor here; cases
4061 // where we would see one should have been moved onto the
4062 // heap at parse time. Taking the address of a nonconstant
4063 // constructor will not do what the programmer expects.
4065 go_assert(!this->expr_->is_composite_literal()
4066 || this->expr_->is_immutable());
4067 if (this->expr_->classification() == EXPRESSION_UNARY)
4069 Unary_expression* ue =
4070 static_cast<Unary_expression*>(this->expr_);
4071 go_assert(ue->op() != OPERATOR_AND);
4075 static unsigned int counter;
4076 char buf[100];
4077 if (this->is_gc_root_ || this->is_slice_init_)
4079 bool copy_to_heap = false;
4080 if (this->is_gc_root_)
4082 // Build a decl for a GC root variable. GC roots are mutable, so
4083 // they cannot be represented as an immutable_struct in the
4084 // backend.
4085 static unsigned int root_counter;
4086 snprintf(buf, sizeof buf, "gc%u", root_counter);
4087 ++root_counter;
4089 else
4091 // Build a decl for a slice value initializer. An immutable slice
4092 // value initializer may have to be copied to the heap if it
4093 // contains pointers in a non-constant context.
4094 snprintf(buf, sizeof buf, "C%u", counter);
4095 ++counter;
4097 Array_type* at = this->expr_->type()->array_type();
4098 go_assert(at != NULL);
4100 // If we are not copying the value to the heap, we will only
4101 // initialize the value once, so we can use this directly
4102 // rather than copying it. In that case we can't make it
4103 // read-only, because the program is permitted to change it.
4104 copy_to_heap = (at->element_type()->has_pointer()
4105 && !context->is_const());
4107 Bvariable* implicit =
4108 gogo->backend()->implicit_variable(buf, btype, bexpr, copy_to_heap,
4109 false, 0);
4110 bexpr = gogo->backend()->var_expression(implicit, loc);
4112 else if ((this->expr_->is_composite_literal()
4113 || this->expr_->string_expression() != NULL)
4114 && this->expr_->is_immutable())
4116 // Build a decl for a constant constructor.
4117 snprintf(buf, sizeof buf, "C%u", counter);
4118 ++counter;
4120 Bvariable* decl =
4121 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4122 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4123 btype, loc, bexpr);
4124 bexpr = gogo->backend()->var_expression(decl, loc);
4127 go_assert(!this->create_temp_ || this->expr_->is_variable());
4128 ret = gogo->backend()->address_expression(bexpr, loc);
4129 break;
4131 case OPERATOR_MULT:
4133 go_assert(this->expr_->type()->points_to() != NULL);
4135 // If we are dereferencing the pointer to a large struct, we
4136 // need to check for nil. We don't bother to check for small
4137 // structs because we expect the system to crash on a nil
4138 // pointer dereference. However, if we know the address of this
4139 // expression is being taken, we must always check for nil.
4141 Type* ptype = this->expr_->type()->points_to();
4142 Btype* pbtype = ptype->get_backend(gogo);
4143 if (!ptype->is_void_type())
4145 size_t s = gogo->backend()->type_size(pbtype);
4146 if (s >= 4096 || this->issue_nil_check_)
4148 go_assert(this->expr_->is_variable());
4149 Bexpression* nil =
4150 Expression::make_nil(loc)->get_backend(context);
4151 Bexpression* compare =
4152 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4153 nil, loc);
4154 Bexpression* crash =
4155 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4156 loc)->get_backend(context);
4157 bexpr = gogo->backend()->conditional_expression(btype, compare,
4158 crash, bexpr,
4159 loc);
4163 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4165 break;
4167 default:
4168 go_unreachable();
4171 return ret;
4174 // Export a unary expression.
4176 void
4177 Unary_expression::do_export(Export* exp) const
4179 switch (this->op_)
4181 case OPERATOR_PLUS:
4182 exp->write_c_string("+ ");
4183 break;
4184 case OPERATOR_MINUS:
4185 exp->write_c_string("- ");
4186 break;
4187 case OPERATOR_NOT:
4188 exp->write_c_string("! ");
4189 break;
4190 case OPERATOR_XOR:
4191 exp->write_c_string("^ ");
4192 break;
4193 case OPERATOR_AND:
4194 case OPERATOR_MULT:
4195 default:
4196 go_unreachable();
4198 this->expr_->export_expression(exp);
4201 // Import a unary expression.
4203 Expression*
4204 Unary_expression::do_import(Import* imp)
4206 Operator op;
4207 switch (imp->get_char())
4209 case '+':
4210 op = OPERATOR_PLUS;
4211 break;
4212 case '-':
4213 op = OPERATOR_MINUS;
4214 break;
4215 case '!':
4216 op = OPERATOR_NOT;
4217 break;
4218 case '^':
4219 op = OPERATOR_XOR;
4220 break;
4221 default:
4222 go_unreachable();
4224 imp->require_c_string(" ");
4225 Expression* expr = Expression::import_expression(imp);
4226 return Expression::make_unary(op, expr, imp->location());
4229 // Dump ast representation of an unary expression.
4231 void
4232 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4234 ast_dump_context->dump_operator(this->op_);
4235 ast_dump_context->ostream() << "(";
4236 ast_dump_context->dump_expression(this->expr_);
4237 ast_dump_context->ostream() << ") ";
4240 // Make a unary expression.
4242 Expression*
4243 Expression::make_unary(Operator op, Expression* expr, Location location)
4245 return new Unary_expression(op, expr, location);
4248 // If this is an indirection through a pointer, return the expression
4249 // being pointed through. Otherwise return this.
4251 Expression*
4252 Expression::deref()
4254 if (this->classification_ == EXPRESSION_UNARY)
4256 Unary_expression* ue = static_cast<Unary_expression*>(this);
4257 if (ue->op() == OPERATOR_MULT)
4258 return ue->operand();
4260 return this;
4263 // Class Binary_expression.
4265 // Traversal.
4268 Binary_expression::do_traverse(Traverse* traverse)
4270 int t = Expression::traverse(&this->left_, traverse);
4271 if (t == TRAVERSE_EXIT)
4272 return TRAVERSE_EXIT;
4273 return Expression::traverse(&this->right_, traverse);
4276 // Return the type to use for a binary operation on operands of
4277 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4278 // such may be NULL or abstract.
4280 bool
4281 Binary_expression::operation_type(Operator op, Type* left_type,
4282 Type* right_type, Type** result_type)
4284 if (left_type != right_type
4285 && !left_type->is_abstract()
4286 && !right_type->is_abstract()
4287 && left_type->base() != right_type->base()
4288 && op != OPERATOR_LSHIFT
4289 && op != OPERATOR_RSHIFT)
4291 // May be a type error--let it be diagnosed elsewhere.
4292 return false;
4295 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4297 if (left_type->integer_type() != NULL)
4298 *result_type = left_type;
4299 else
4300 *result_type = Type::make_abstract_integer_type();
4302 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4303 *result_type = left_type;
4304 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4305 *result_type = right_type;
4306 else if (!left_type->is_abstract())
4307 *result_type = left_type;
4308 else if (!right_type->is_abstract())
4309 *result_type = right_type;
4310 else if (left_type->complex_type() != NULL)
4311 *result_type = left_type;
4312 else if (right_type->complex_type() != NULL)
4313 *result_type = right_type;
4314 else if (left_type->float_type() != NULL)
4315 *result_type = left_type;
4316 else if (right_type->float_type() != NULL)
4317 *result_type = right_type;
4318 else if (left_type->integer_type() != NULL
4319 && left_type->integer_type()->is_rune())
4320 *result_type = left_type;
4321 else if (right_type->integer_type() != NULL
4322 && right_type->integer_type()->is_rune())
4323 *result_type = right_type;
4324 else
4325 *result_type = left_type;
4327 return true;
4330 // Convert an integer comparison code and an operator to a boolean
4331 // value.
4333 bool
4334 Binary_expression::cmp_to_bool(Operator op, int cmp)
4336 switch (op)
4338 case OPERATOR_EQEQ:
4339 return cmp == 0;
4340 break;
4341 case OPERATOR_NOTEQ:
4342 return cmp != 0;
4343 break;
4344 case OPERATOR_LT:
4345 return cmp < 0;
4346 break;
4347 case OPERATOR_LE:
4348 return cmp <= 0;
4349 case OPERATOR_GT:
4350 return cmp > 0;
4351 case OPERATOR_GE:
4352 return cmp >= 0;
4353 default:
4354 go_unreachable();
4358 // Compare constants according to OP.
4360 bool
4361 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4362 Numeric_constant* right_nc,
4363 Location location, bool* result)
4365 Type* left_type = left_nc->type();
4366 Type* right_type = right_nc->type();
4368 Type* type;
4369 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4370 return false;
4372 // When comparing an untyped operand to a typed operand, we are
4373 // effectively coercing the untyped operand to the other operand's
4374 // type, so make sure that is valid.
4375 if (!left_nc->set_type(type, true, location)
4376 || !right_nc->set_type(type, true, location))
4377 return false;
4379 bool ret;
4380 int cmp;
4381 if (type->complex_type() != NULL)
4383 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4384 return false;
4385 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4387 else if (type->float_type() != NULL)
4388 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4389 else
4390 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4392 if (ret)
4393 *result = Binary_expression::cmp_to_bool(op, cmp);
4395 return ret;
4398 // Compare integer constants.
4400 bool
4401 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4402 const Numeric_constant* right_nc,
4403 int* cmp)
4405 mpz_t left_val;
4406 if (!left_nc->to_int(&left_val))
4407 return false;
4408 mpz_t right_val;
4409 if (!right_nc->to_int(&right_val))
4411 mpz_clear(left_val);
4412 return false;
4415 *cmp = mpz_cmp(left_val, right_val);
4417 mpz_clear(left_val);
4418 mpz_clear(right_val);
4420 return true;
4423 // Compare floating point constants.
4425 bool
4426 Binary_expression::compare_float(const Numeric_constant* left_nc,
4427 const Numeric_constant* right_nc,
4428 int* cmp)
4430 mpfr_t left_val;
4431 if (!left_nc->to_float(&left_val))
4432 return false;
4433 mpfr_t right_val;
4434 if (!right_nc->to_float(&right_val))
4436 mpfr_clear(left_val);
4437 return false;
4440 // We already coerced both operands to the same type. If that type
4441 // is not an abstract type, we need to round the values accordingly.
4442 Type* type = left_nc->type();
4443 if (!type->is_abstract() && type->float_type() != NULL)
4445 int bits = type->float_type()->bits();
4446 mpfr_prec_round(left_val, bits, GMP_RNDN);
4447 mpfr_prec_round(right_val, bits, GMP_RNDN);
4450 *cmp = mpfr_cmp(left_val, right_val);
4452 mpfr_clear(left_val);
4453 mpfr_clear(right_val);
4455 return true;
4458 // Compare complex constants. Complex numbers may only be compared
4459 // for equality.
4461 bool
4462 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4463 const Numeric_constant* right_nc,
4464 int* cmp)
4466 mpfr_t left_real, left_imag;
4467 if (!left_nc->to_complex(&left_real, &left_imag))
4468 return false;
4469 mpfr_t right_real, right_imag;
4470 if (!right_nc->to_complex(&right_real, &right_imag))
4472 mpfr_clear(left_real);
4473 mpfr_clear(left_imag);
4474 return false;
4477 // We already coerced both operands to the same type. If that type
4478 // is not an abstract type, we need to round the values accordingly.
4479 Type* type = left_nc->type();
4480 if (!type->is_abstract() && type->complex_type() != NULL)
4482 int bits = type->complex_type()->bits();
4483 mpfr_prec_round(left_real, bits / 2, GMP_RNDN);
4484 mpfr_prec_round(left_imag, bits / 2, GMP_RNDN);
4485 mpfr_prec_round(right_real, bits / 2, GMP_RNDN);
4486 mpfr_prec_round(right_imag, bits / 2, GMP_RNDN);
4489 *cmp = (mpfr_cmp(left_real, right_real) != 0
4490 || mpfr_cmp(left_imag, right_imag) != 0);
4492 mpfr_clear(left_real);
4493 mpfr_clear(left_imag);
4494 mpfr_clear(right_real);
4495 mpfr_clear(right_imag);
4497 return true;
4500 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4501 // true if this could be done, false if not. Issue errors at LOCATION
4502 // as appropriate.
4504 bool
4505 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4506 Numeric_constant* right_nc,
4507 Location location, Numeric_constant* nc)
4509 switch (op)
4511 case OPERATOR_OROR:
4512 case OPERATOR_ANDAND:
4513 case OPERATOR_EQEQ:
4514 case OPERATOR_NOTEQ:
4515 case OPERATOR_LT:
4516 case OPERATOR_LE:
4517 case OPERATOR_GT:
4518 case OPERATOR_GE:
4519 // These return boolean values, not numeric.
4520 return false;
4521 default:
4522 break;
4525 Type* left_type = left_nc->type();
4526 Type* right_type = right_nc->type();
4528 Type* type;
4529 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4530 return false;
4532 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4534 // When combining an untyped operand with a typed operand, we are
4535 // effectively coercing the untyped operand to the other operand's
4536 // type, so make sure that is valid.
4537 if (!left_nc->set_type(type, true, location))
4538 return false;
4539 if (!is_shift && !right_nc->set_type(type, true, location))
4540 return false;
4542 bool r;
4543 if (type->complex_type() != NULL)
4544 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4545 else if (type->float_type() != NULL)
4546 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4547 else
4548 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4550 if (r)
4551 r = nc->set_type(type, true, location);
4553 return r;
4556 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4557 // integer operations. Return true if this could be done, false if
4558 // not.
4560 bool
4561 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4562 const Numeric_constant* right_nc,
4563 Location location, Numeric_constant* nc)
4565 mpz_t left_val;
4566 if (!left_nc->to_int(&left_val))
4567 return false;
4568 mpz_t right_val;
4569 if (!right_nc->to_int(&right_val))
4571 mpz_clear(left_val);
4572 return false;
4575 mpz_t val;
4576 mpz_init(val);
4578 switch (op)
4580 case OPERATOR_PLUS:
4581 mpz_add(val, left_val, right_val);
4582 if (mpz_sizeinbase(val, 2) > 0x100000)
4584 error_at(location, "constant addition overflow");
4585 mpz_set_ui(val, 1);
4587 break;
4588 case OPERATOR_MINUS:
4589 mpz_sub(val, left_val, right_val);
4590 if (mpz_sizeinbase(val, 2) > 0x100000)
4592 error_at(location, "constant subtraction overflow");
4593 mpz_set_ui(val, 1);
4595 break;
4596 case OPERATOR_OR:
4597 mpz_ior(val, left_val, right_val);
4598 break;
4599 case OPERATOR_XOR:
4600 mpz_xor(val, left_val, right_val);
4601 break;
4602 case OPERATOR_MULT:
4603 mpz_mul(val, left_val, right_val);
4604 if (mpz_sizeinbase(val, 2) > 0x100000)
4606 error_at(location, "constant multiplication overflow");
4607 mpz_set_ui(val, 1);
4609 break;
4610 case OPERATOR_DIV:
4611 if (mpz_sgn(right_val) != 0)
4612 mpz_tdiv_q(val, left_val, right_val);
4613 else
4615 error_at(location, "division by zero");
4616 mpz_set_ui(val, 0);
4618 break;
4619 case OPERATOR_MOD:
4620 if (mpz_sgn(right_val) != 0)
4621 mpz_tdiv_r(val, left_val, right_val);
4622 else
4624 error_at(location, "division by zero");
4625 mpz_set_ui(val, 0);
4627 break;
4628 case OPERATOR_LSHIFT:
4630 unsigned long shift = mpz_get_ui(right_val);
4631 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4632 mpz_mul_2exp(val, left_val, shift);
4633 else
4635 error_at(location, "shift count overflow");
4636 mpz_set_ui(val, 1);
4638 break;
4640 break;
4641 case OPERATOR_RSHIFT:
4643 unsigned long shift = mpz_get_ui(right_val);
4644 if (mpz_cmp_ui(right_val, shift) != 0)
4646 error_at(location, "shift count overflow");
4647 mpz_set_ui(val, 1);
4649 else
4651 if (mpz_cmp_ui(left_val, 0) >= 0)
4652 mpz_tdiv_q_2exp(val, left_val, shift);
4653 else
4654 mpz_fdiv_q_2exp(val, left_val, shift);
4656 break;
4658 break;
4659 case OPERATOR_AND:
4660 mpz_and(val, left_val, right_val);
4661 break;
4662 case OPERATOR_BITCLEAR:
4664 mpz_t tval;
4665 mpz_init(tval);
4666 mpz_com(tval, right_val);
4667 mpz_and(val, left_val, tval);
4668 mpz_clear(tval);
4670 break;
4671 default:
4672 go_unreachable();
4675 mpz_clear(left_val);
4676 mpz_clear(right_val);
4678 if (left_nc->is_rune()
4679 || (op != OPERATOR_LSHIFT
4680 && op != OPERATOR_RSHIFT
4681 && right_nc->is_rune()))
4682 nc->set_rune(NULL, val);
4683 else
4684 nc->set_int(NULL, val);
4686 mpz_clear(val);
4688 return true;
4691 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4692 // floating point operations. Return true if this could be done,
4693 // false if not.
4695 bool
4696 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4697 const Numeric_constant* right_nc,
4698 Location location, Numeric_constant* nc)
4700 mpfr_t left_val;
4701 if (!left_nc->to_float(&left_val))
4702 return false;
4703 mpfr_t right_val;
4704 if (!right_nc->to_float(&right_val))
4706 mpfr_clear(left_val);
4707 return false;
4710 mpfr_t val;
4711 mpfr_init(val);
4713 bool ret = true;
4714 switch (op)
4716 case OPERATOR_PLUS:
4717 mpfr_add(val, left_val, right_val, GMP_RNDN);
4718 break;
4719 case OPERATOR_MINUS:
4720 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4721 break;
4722 case OPERATOR_OR:
4723 case OPERATOR_XOR:
4724 case OPERATOR_AND:
4725 case OPERATOR_BITCLEAR:
4726 case OPERATOR_MOD:
4727 case OPERATOR_LSHIFT:
4728 case OPERATOR_RSHIFT:
4729 mpfr_set_ui(val, 0, GMP_RNDN);
4730 ret = false;
4731 break;
4732 case OPERATOR_MULT:
4733 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4734 break;
4735 case OPERATOR_DIV:
4736 if (!mpfr_zero_p(right_val))
4737 mpfr_div(val, left_val, right_val, GMP_RNDN);
4738 else
4740 error_at(location, "division by zero");
4741 mpfr_set_ui(val, 0, GMP_RNDN);
4743 break;
4744 default:
4745 go_unreachable();
4748 mpfr_clear(left_val);
4749 mpfr_clear(right_val);
4751 nc->set_float(NULL, val);
4752 mpfr_clear(val);
4754 return ret;
4757 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4758 // complex operations. Return true if this could be done, false if
4759 // not.
4761 bool
4762 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4763 const Numeric_constant* right_nc,
4764 Location location, Numeric_constant* nc)
4766 mpfr_t left_real, left_imag;
4767 if (!left_nc->to_complex(&left_real, &left_imag))
4768 return false;
4769 mpfr_t right_real, right_imag;
4770 if (!right_nc->to_complex(&right_real, &right_imag))
4772 mpfr_clear(left_real);
4773 mpfr_clear(left_imag);
4774 return false;
4777 mpfr_t real, imag;
4778 mpfr_init(real);
4779 mpfr_init(imag);
4781 bool ret = true;
4782 switch (op)
4784 case OPERATOR_PLUS:
4785 mpfr_add(real, left_real, right_real, GMP_RNDN);
4786 mpfr_add(imag, left_imag, right_imag, GMP_RNDN);
4787 break;
4788 case OPERATOR_MINUS:
4789 mpfr_sub(real, left_real, right_real, GMP_RNDN);
4790 mpfr_sub(imag, left_imag, right_imag, GMP_RNDN);
4791 break;
4792 case OPERATOR_OR:
4793 case OPERATOR_XOR:
4794 case OPERATOR_AND:
4795 case OPERATOR_BITCLEAR:
4796 case OPERATOR_MOD:
4797 case OPERATOR_LSHIFT:
4798 case OPERATOR_RSHIFT:
4799 mpfr_set_ui(real, 0, GMP_RNDN);
4800 mpfr_set_ui(imag, 0, GMP_RNDN);
4801 ret = false;
4802 break;
4803 case OPERATOR_MULT:
4805 // You might think that multiplying two complex numbers would
4806 // be simple, and you would be right, until you start to think
4807 // about getting the right answer for infinity. If one
4808 // operand here is infinity and the other is anything other
4809 // than zero or NaN, then we are going to wind up subtracting
4810 // two infinity values. That will give us a NaN, but the
4811 // correct answer is infinity.
4813 mpfr_t lrrr;
4814 mpfr_init(lrrr);
4815 mpfr_mul(lrrr, left_real, right_real, GMP_RNDN);
4817 mpfr_t lrri;
4818 mpfr_init(lrri);
4819 mpfr_mul(lrri, left_real, right_imag, GMP_RNDN);
4821 mpfr_t lirr;
4822 mpfr_init(lirr);
4823 mpfr_mul(lirr, left_imag, right_real, GMP_RNDN);
4825 mpfr_t liri;
4826 mpfr_init(liri);
4827 mpfr_mul(liri, left_imag, right_imag, GMP_RNDN);
4829 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4830 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4832 // If we get NaN on both sides, check whether it should really
4833 // be infinity. The rule is that if either side of the
4834 // complex number is infinity, then the whole value is
4835 // infinity, even if the other side is NaN. So the only case
4836 // we have to fix is the one in which both sides are NaN.
4837 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
4838 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
4839 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
4841 bool is_infinity = false;
4843 mpfr_t lr;
4844 mpfr_t li;
4845 mpfr_init_set(lr, left_real, GMP_RNDN);
4846 mpfr_init_set(li, left_imag, GMP_RNDN);
4848 mpfr_t rr;
4849 mpfr_t ri;
4850 mpfr_init_set(rr, right_real, GMP_RNDN);
4851 mpfr_init_set(ri, right_imag, GMP_RNDN);
4853 // If the left side is infinity, then the result is
4854 // infinity.
4855 if (mpfr_inf_p(lr) || mpfr_inf_p(li))
4857 mpfr_set_ui(lr, mpfr_inf_p(lr) ? 1 : 0, GMP_RNDN);
4858 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4859 mpfr_set_ui(li, mpfr_inf_p(li) ? 1 : 0, GMP_RNDN);
4860 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4861 if (mpfr_nan_p(rr))
4863 mpfr_set_ui(rr, 0, GMP_RNDN);
4864 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4866 if (mpfr_nan_p(ri))
4868 mpfr_set_ui(ri, 0, GMP_RNDN);
4869 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4871 is_infinity = true;
4874 // If the right side is infinity, then the result is
4875 // infinity.
4876 if (mpfr_inf_p(rr) || mpfr_inf_p(ri))
4878 mpfr_set_ui(rr, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
4879 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4880 mpfr_set_ui(ri, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
4881 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4882 if (mpfr_nan_p(lr))
4884 mpfr_set_ui(lr, 0, GMP_RNDN);
4885 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4887 if (mpfr_nan_p(li))
4889 mpfr_set_ui(li, 0, GMP_RNDN);
4890 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4892 is_infinity = true;
4895 // If we got an overflow in the intermediate computations,
4896 // then the result is infinity.
4897 if (!is_infinity
4898 && (mpfr_inf_p(lrrr) || mpfr_inf_p(lrri)
4899 || mpfr_inf_p(lirr) || mpfr_inf_p(liri)))
4901 if (mpfr_nan_p(lr))
4903 mpfr_set_ui(lr, 0, GMP_RNDN);
4904 mpfr_copysign(lr, lr, left_real, GMP_RNDN);
4906 if (mpfr_nan_p(li))
4908 mpfr_set_ui(li, 0, GMP_RNDN);
4909 mpfr_copysign(li, li, left_imag, GMP_RNDN);
4911 if (mpfr_nan_p(rr))
4913 mpfr_set_ui(rr, 0, GMP_RNDN);
4914 mpfr_copysign(rr, rr, right_real, GMP_RNDN);
4916 if (mpfr_nan_p(ri))
4918 mpfr_set_ui(ri, 0, GMP_RNDN);
4919 mpfr_copysign(ri, ri, right_imag, GMP_RNDN);
4921 is_infinity = true;
4924 if (is_infinity)
4926 mpfr_mul(lrrr, lr, rr, GMP_RNDN);
4927 mpfr_mul(lrri, lr, ri, GMP_RNDN);
4928 mpfr_mul(lirr, li, rr, GMP_RNDN);
4929 mpfr_mul(liri, li, ri, GMP_RNDN);
4930 mpfr_sub(real, lrrr, liri, GMP_RNDN);
4931 mpfr_add(imag, lrri, lirr, GMP_RNDN);
4932 mpfr_set_inf(real, mpfr_sgn(real));
4933 mpfr_set_inf(imag, mpfr_sgn(imag));
4936 mpfr_clear(lr);
4937 mpfr_clear(li);
4938 mpfr_clear(rr);
4939 mpfr_clear(ri);
4942 mpfr_clear(lrrr);
4943 mpfr_clear(lrri);
4944 mpfr_clear(lirr);
4945 mpfr_clear(liri);
4947 break;
4948 case OPERATOR_DIV:
4950 // For complex division we want to avoid having an
4951 // intermediate overflow turn the whole result in a NaN. We
4952 // scale the values to try to avoid this.
4954 if (mpfr_zero_p(right_real) && mpfr_zero_p(right_imag))
4956 error_at(location, "division by zero");
4957 mpfr_set_ui(real, 0, GMP_RNDN);
4958 mpfr_set_ui(imag, 0, GMP_RNDN);
4959 break;
4962 mpfr_t rra;
4963 mpfr_t ria;
4964 mpfr_init(rra);
4965 mpfr_init(ria);
4966 mpfr_abs(rra, right_real, GMP_RNDN);
4967 mpfr_abs(ria, right_imag, GMP_RNDN);
4968 mpfr_t t;
4969 mpfr_init(t);
4970 mpfr_max(t, rra, ria, GMP_RNDN);
4972 mpfr_t rr;
4973 mpfr_t ri;
4974 mpfr_init_set(rr, right_real, GMP_RNDN);
4975 mpfr_init_set(ri, right_imag, GMP_RNDN);
4976 long ilogbw = 0;
4977 if (!mpfr_inf_p(t) && !mpfr_nan_p(t) && !mpfr_zero_p(t))
4979 ilogbw = mpfr_get_exp(t);
4980 mpfr_mul_2si(rr, rr, - ilogbw, GMP_RNDN);
4981 mpfr_mul_2si(ri, ri, - ilogbw, GMP_RNDN);
4984 mpfr_t denom;
4985 mpfr_init(denom);
4986 mpfr_mul(denom, rr, rr, GMP_RNDN);
4987 mpfr_mul(t, ri, ri, GMP_RNDN);
4988 mpfr_add(denom, denom, t, GMP_RNDN);
4990 mpfr_mul(real, left_real, rr, GMP_RNDN);
4991 mpfr_mul(t, left_imag, ri, GMP_RNDN);
4992 mpfr_add(real, real, t, GMP_RNDN);
4993 mpfr_div(real, real, denom, GMP_RNDN);
4994 mpfr_mul_2si(real, real, - ilogbw, GMP_RNDN);
4996 mpfr_mul(imag, left_imag, rr, GMP_RNDN);
4997 mpfr_mul(t, left_real, ri, GMP_RNDN);
4998 mpfr_sub(imag, imag, t, GMP_RNDN);
4999 mpfr_div(imag, imag, denom, GMP_RNDN);
5000 mpfr_mul_2si(imag, imag, - ilogbw, GMP_RNDN);
5002 // If we wind up with NaN on both sides, check whether we
5003 // should really have infinity. The rule is that if either
5004 // side of the complex number is infinity, then the whole
5005 // value is infinity, even if the other side is NaN. So the
5006 // only case we have to fix is the one in which both sides are
5007 // NaN.
5008 if (mpfr_nan_p(real) && mpfr_nan_p(imag)
5009 && (!mpfr_nan_p(left_real) || !mpfr_nan_p(left_imag))
5010 && (!mpfr_nan_p(right_real) || !mpfr_nan_p(right_imag)))
5012 if (mpfr_zero_p(denom))
5014 mpfr_set_inf(real, mpfr_sgn(rr));
5015 mpfr_mul(real, real, left_real, GMP_RNDN);
5016 mpfr_set_inf(imag, mpfr_sgn(rr));
5017 mpfr_mul(imag, imag, left_imag, GMP_RNDN);
5019 else if ((mpfr_inf_p(left_real) || mpfr_inf_p(left_imag))
5020 && mpfr_number_p(rr) && mpfr_number_p(ri))
5022 mpfr_set_ui(t, mpfr_inf_p(left_real) ? 1 : 0, GMP_RNDN);
5023 mpfr_copysign(t, t, left_real, GMP_RNDN);
5025 mpfr_t t2;
5026 mpfr_init_set_ui(t2, mpfr_inf_p(left_imag) ? 1 : 0, GMP_RNDN);
5027 mpfr_copysign(t2, t2, left_imag, GMP_RNDN);
5029 mpfr_t t3;
5030 mpfr_init(t3);
5031 mpfr_mul(t3, t, rr, GMP_RNDN);
5033 mpfr_t t4;
5034 mpfr_init(t4);
5035 mpfr_mul(t4, t2, ri, GMP_RNDN);
5037 mpfr_add(t3, t3, t4, GMP_RNDN);
5038 mpfr_set_inf(real, mpfr_sgn(t3));
5040 mpfr_mul(t3, t2, rr, GMP_RNDN);
5041 mpfr_mul(t4, t, ri, GMP_RNDN);
5042 mpfr_sub(t3, t3, t4, GMP_RNDN);
5043 mpfr_set_inf(imag, mpfr_sgn(t3));
5045 mpfr_clear(t2);
5046 mpfr_clear(t3);
5047 mpfr_clear(t4);
5049 else if ((mpfr_inf_p(right_real) || mpfr_inf_p(right_imag))
5050 && mpfr_number_p(left_real) && mpfr_number_p(left_imag))
5052 mpfr_set_ui(t, mpfr_inf_p(rr) ? 1 : 0, GMP_RNDN);
5053 mpfr_copysign(t, t, rr, GMP_RNDN);
5055 mpfr_t t2;
5056 mpfr_init_set_ui(t2, mpfr_inf_p(ri) ? 1 : 0, GMP_RNDN);
5057 mpfr_copysign(t2, t2, ri, GMP_RNDN);
5059 mpfr_t t3;
5060 mpfr_init(t3);
5061 mpfr_mul(t3, left_real, t, GMP_RNDN);
5063 mpfr_t t4;
5064 mpfr_init(t4);
5065 mpfr_mul(t4, left_imag, t2, GMP_RNDN);
5067 mpfr_add(t3, t3, t4, GMP_RNDN);
5068 mpfr_set_ui(real, 0, GMP_RNDN);
5069 mpfr_mul(real, real, t3, GMP_RNDN);
5071 mpfr_mul(t3, left_imag, t, GMP_RNDN);
5072 mpfr_mul(t4, left_real, t2, GMP_RNDN);
5073 mpfr_sub(t3, t3, t4, GMP_RNDN);
5074 mpfr_set_ui(imag, 0, GMP_RNDN);
5075 mpfr_mul(imag, imag, t3, GMP_RNDN);
5077 mpfr_clear(t2);
5078 mpfr_clear(t3);
5079 mpfr_clear(t4);
5083 mpfr_clear(denom);
5084 mpfr_clear(rr);
5085 mpfr_clear(ri);
5086 mpfr_clear(t);
5087 mpfr_clear(rra);
5088 mpfr_clear(ria);
5090 break;
5091 default:
5092 go_unreachable();
5095 mpfr_clear(left_real);
5096 mpfr_clear(left_imag);
5097 mpfr_clear(right_real);
5098 mpfr_clear(right_imag);
5100 nc->set_complex(NULL, real, imag);
5101 mpfr_clear(real);
5102 mpfr_clear(imag);
5104 return ret;
5107 // Lower a binary expression. We have to evaluate constant
5108 // expressions now, in order to implement Go's unlimited precision
5109 // constants.
5111 Expression*
5112 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5113 Statement_inserter* inserter, int)
5115 Location location = this->location();
5116 Operator op = this->op_;
5117 Expression* left = this->left_;
5118 Expression* right = this->right_;
5120 const bool is_comparison = (op == OPERATOR_EQEQ
5121 || op == OPERATOR_NOTEQ
5122 || op == OPERATOR_LT
5123 || op == OPERATOR_LE
5124 || op == OPERATOR_GT
5125 || op == OPERATOR_GE);
5127 // Numeric constant expressions.
5129 Numeric_constant left_nc;
5130 Numeric_constant right_nc;
5131 if (left->numeric_constant_value(&left_nc)
5132 && right->numeric_constant_value(&right_nc))
5134 if (is_comparison)
5136 bool result;
5137 if (!Binary_expression::compare_constant(op, &left_nc,
5138 &right_nc, location,
5139 &result))
5140 return this;
5141 return Expression::make_cast(Type::make_boolean_type(),
5142 Expression::make_boolean(result,
5143 location),
5144 location);
5146 else
5148 Numeric_constant nc;
5149 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5150 location, &nc))
5151 return this;
5152 return nc.expression(location);
5157 // String constant expressions.
5158 if (left->type()->is_string_type() && right->type()->is_string_type())
5160 std::string left_string;
5161 std::string right_string;
5162 if (left->string_constant_value(&left_string)
5163 && right->string_constant_value(&right_string))
5165 if (op == OPERATOR_PLUS)
5166 return Expression::make_string(left_string + right_string,
5167 location);
5168 else if (is_comparison)
5170 int cmp = left_string.compare(right_string);
5171 bool r = Binary_expression::cmp_to_bool(op, cmp);
5172 return Expression::make_boolean(r, location);
5177 // Lower struct, array, and some interface comparisons.
5178 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5180 if (left->type()->struct_type() != NULL)
5181 return this->lower_struct_comparison(gogo, inserter);
5182 else if (left->type()->array_type() != NULL
5183 && !left->type()->is_slice_type())
5184 return this->lower_array_comparison(gogo, inserter);
5185 else if ((left->type()->interface_type() != NULL
5186 && right->type()->interface_type() == NULL)
5187 || (left->type()->interface_type() == NULL
5188 && right->type()->interface_type() != NULL))
5189 return this->lower_interface_value_comparison(gogo, inserter);
5192 return this;
5195 // Lower a struct comparison.
5197 Expression*
5198 Binary_expression::lower_struct_comparison(Gogo* gogo,
5199 Statement_inserter* inserter)
5201 Struct_type* st = this->left_->type()->struct_type();
5202 Struct_type* st2 = this->right_->type()->struct_type();
5203 if (st2 == NULL)
5204 return this;
5205 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
5206 return this;
5207 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5208 this->right_->type(), NULL))
5209 return this;
5211 // See if we can compare using memcmp. As a heuristic, we use
5212 // memcmp rather than field references and comparisons if there are
5213 // more than two fields.
5214 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5215 return this->lower_compare_to_memcmp(gogo, inserter);
5217 Location loc = this->location();
5219 Expression* left = this->left_;
5220 Temporary_statement* left_temp = NULL;
5221 if (left->var_expression() == NULL
5222 && left->temporary_reference_expression() == NULL)
5224 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5225 inserter->insert(left_temp);
5226 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5229 Expression* right = this->right_;
5230 Temporary_statement* right_temp = NULL;
5231 if (right->var_expression() == NULL
5232 && right->temporary_reference_expression() == NULL)
5234 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5235 inserter->insert(right_temp);
5236 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5239 Expression* ret = Expression::make_boolean(true, loc);
5240 const Struct_field_list* fields = st->fields();
5241 unsigned int field_index = 0;
5242 for (Struct_field_list::const_iterator pf = fields->begin();
5243 pf != fields->end();
5244 ++pf, ++field_index)
5246 if (Gogo::is_sink_name(pf->field_name()))
5247 continue;
5249 if (field_index > 0)
5251 if (left_temp == NULL)
5252 left = left->copy();
5253 else
5254 left = Expression::make_temporary_reference(left_temp, loc);
5255 if (right_temp == NULL)
5256 right = right->copy();
5257 else
5258 right = Expression::make_temporary_reference(right_temp, loc);
5260 Expression* f1 = Expression::make_field_reference(left, field_index,
5261 loc);
5262 Expression* f2 = Expression::make_field_reference(right, field_index,
5263 loc);
5264 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5265 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5268 if (this->op_ == OPERATOR_NOTEQ)
5269 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5271 return ret;
5274 // Lower an array comparison.
5276 Expression*
5277 Binary_expression::lower_array_comparison(Gogo* gogo,
5278 Statement_inserter* inserter)
5280 Array_type* at = this->left_->type()->array_type();
5281 Array_type* at2 = this->right_->type()->array_type();
5282 if (at2 == NULL)
5283 return this;
5284 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
5285 return this;
5286 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5287 this->right_->type(), NULL))
5288 return this;
5290 // Call memcmp directly if possible. This may let the middle-end
5291 // optimize the call.
5292 if (at->compare_is_identity(gogo))
5293 return this->lower_compare_to_memcmp(gogo, inserter);
5295 // Call the array comparison function.
5296 Named_object* hash_fn;
5297 Named_object* equal_fn;
5298 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5299 &hash_fn, &equal_fn);
5301 Location loc = this->location();
5303 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5305 Expression_list* args = new Expression_list();
5306 args->push_back(this->operand_address(inserter, this->left_));
5307 args->push_back(this->operand_address(inserter, this->right_));
5308 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
5310 Expression* ret = Expression::make_call(func, args, false, loc);
5312 if (this->op_ == OPERATOR_NOTEQ)
5313 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5315 return ret;
5318 // Lower an interface to value comparison.
5320 Expression*
5321 Binary_expression::lower_interface_value_comparison(Gogo*,
5322 Statement_inserter* inserter)
5324 Type* left_type = this->left_->type();
5325 Type* right_type = this->right_->type();
5326 Interface_type* ift;
5327 if (left_type->interface_type() != NULL)
5329 ift = left_type->interface_type();
5330 if (!ift->implements_interface(right_type, NULL))
5331 return this;
5333 else
5335 ift = right_type->interface_type();
5336 if (!ift->implements_interface(left_type, NULL))
5337 return this;
5339 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5340 return this;
5342 Location loc = this->location();
5344 if (left_type->interface_type() == NULL
5345 && left_type->points_to() == NULL
5346 && !this->left_->is_addressable())
5348 Temporary_statement* temp =
5349 Statement::make_temporary(left_type, NULL, loc);
5350 inserter->insert(temp);
5351 this->left_ =
5352 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5355 if (right_type->interface_type() == NULL
5356 && right_type->points_to() == NULL
5357 && !this->right_->is_addressable())
5359 Temporary_statement* temp =
5360 Statement::make_temporary(right_type, NULL, loc);
5361 inserter->insert(temp);
5362 this->right_ =
5363 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5366 return this;
5369 // Lower a struct or array comparison to a call to memcmp.
5371 Expression*
5372 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5374 Location loc = this->location();
5376 Expression* a1 = this->operand_address(inserter, this->left_);
5377 Expression* a2 = this->operand_address(inserter, this->right_);
5378 Expression* len = Expression::make_type_info(this->left_->type(),
5379 TYPE_INFO_SIZE);
5381 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5383 mpz_t zval;
5384 mpz_init_set_ui(zval, 0);
5385 Expression* zero = Expression::make_integer(&zval, NULL, loc);
5386 mpz_clear(zval);
5388 return Expression::make_binary(this->op_, call, zero, loc);
5391 Expression*
5392 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5393 Statement_inserter* inserter)
5395 Location loc = this->location();
5396 Temporary_statement* temp;
5397 if (this->left_->type()->is_string_type()
5398 && this->op_ == OPERATOR_PLUS)
5400 if (!this->left_->is_variable())
5402 temp = Statement::make_temporary(NULL, this->left_, loc);
5403 inserter->insert(temp);
5404 this->left_ = Expression::make_temporary_reference(temp, loc);
5406 if (!this->right_->is_variable())
5408 temp =
5409 Statement::make_temporary(this->left_->type(), this->right_, loc);
5410 this->right_ = Expression::make_temporary_reference(temp, loc);
5411 inserter->insert(temp);
5415 Type* left_type = this->left_->type();
5416 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5417 || this->op_ == OPERATOR_RSHIFT);
5418 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5419 left_type->integer_type() != NULL)
5420 || this->op_ == OPERATOR_MOD);
5422 if (is_shift_op
5423 || (is_idiv_op
5424 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5426 if (!this->left_->is_variable())
5428 temp = Statement::make_temporary(NULL, this->left_, loc);
5429 inserter->insert(temp);
5430 this->left_ = Expression::make_temporary_reference(temp, loc);
5432 if (!this->right_->is_variable())
5434 temp =
5435 Statement::make_temporary(NULL, this->right_, loc);
5436 this->right_ = Expression::make_temporary_reference(temp, loc);
5437 inserter->insert(temp);
5440 return this;
5444 // Return the address of EXPR, cast to unsafe.Pointer.
5446 Expression*
5447 Binary_expression::operand_address(Statement_inserter* inserter,
5448 Expression* expr)
5450 Location loc = this->location();
5452 if (!expr->is_addressable())
5454 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5455 loc);
5456 inserter->insert(temp);
5457 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5459 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5460 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5461 Type* void_type = Type::make_void_type();
5462 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5463 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5466 // Return the numeric constant value, if it has one.
5468 bool
5469 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5471 Numeric_constant left_nc;
5472 if (!this->left_->numeric_constant_value(&left_nc))
5473 return false;
5474 Numeric_constant right_nc;
5475 if (!this->right_->numeric_constant_value(&right_nc))
5476 return false;
5477 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5478 this->location(), nc);
5481 // Note that the value is being discarded.
5483 bool
5484 Binary_expression::do_discarding_value()
5486 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5487 return this->right_->discarding_value();
5488 else
5490 this->unused_value_error();
5491 return false;
5495 // Get type.
5497 Type*
5498 Binary_expression::do_type()
5500 if (this->classification() == EXPRESSION_ERROR)
5501 return Type::make_error_type();
5503 switch (this->op_)
5505 case OPERATOR_EQEQ:
5506 case OPERATOR_NOTEQ:
5507 case OPERATOR_LT:
5508 case OPERATOR_LE:
5509 case OPERATOR_GT:
5510 case OPERATOR_GE:
5511 if (this->type_ == NULL)
5512 this->type_ = Type::make_boolean_type();
5513 return this->type_;
5515 case OPERATOR_PLUS:
5516 case OPERATOR_MINUS:
5517 case OPERATOR_OR:
5518 case OPERATOR_XOR:
5519 case OPERATOR_MULT:
5520 case OPERATOR_DIV:
5521 case OPERATOR_MOD:
5522 case OPERATOR_AND:
5523 case OPERATOR_BITCLEAR:
5524 case OPERATOR_OROR:
5525 case OPERATOR_ANDAND:
5527 Type* type;
5528 if (!Binary_expression::operation_type(this->op_,
5529 this->left_->type(),
5530 this->right_->type(),
5531 &type))
5532 return Type::make_error_type();
5533 return type;
5536 case OPERATOR_LSHIFT:
5537 case OPERATOR_RSHIFT:
5538 return this->left_->type();
5540 default:
5541 go_unreachable();
5545 // Set type for a binary expression.
5547 void
5548 Binary_expression::do_determine_type(const Type_context* context)
5550 Type* tleft = this->left_->type();
5551 Type* tright = this->right_->type();
5553 // Both sides should have the same type, except for the shift
5554 // operations. For a comparison, we should ignore the incoming
5555 // type.
5557 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5558 || this->op_ == OPERATOR_RSHIFT);
5560 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5561 || this->op_ == OPERATOR_NOTEQ
5562 || this->op_ == OPERATOR_LT
5563 || this->op_ == OPERATOR_LE
5564 || this->op_ == OPERATOR_GT
5565 || this->op_ == OPERATOR_GE);
5567 Type_context subcontext(*context);
5569 if (is_comparison)
5571 // In a comparison, the context does not determine the types of
5572 // the operands.
5573 subcontext.type = NULL;
5576 if (this->op_ == OPERATOR_ANDAND || this->op_ == OPERATOR_OROR)
5578 // For a logical operation, the context does not determine the
5579 // types of the operands. The operands must be some boolean
5580 // type but if the context has a boolean type they do not
5581 // inherit it. See http://golang.org/issue/3924.
5582 subcontext.type = NULL;
5585 // Set the context for the left hand operand.
5586 if (is_shift_op)
5588 // The right hand operand of a shift plays no role in
5589 // determining the type of the left hand operand.
5591 else if (!tleft->is_abstract())
5592 subcontext.type = tleft;
5593 else if (!tright->is_abstract())
5594 subcontext.type = tright;
5595 else if (subcontext.type == NULL)
5597 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5598 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5599 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5601 // Both sides have an abstract integer, abstract float, or
5602 // abstract complex type. Just let CONTEXT determine
5603 // whether they may remain abstract or not.
5605 else if (tleft->complex_type() != NULL)
5606 subcontext.type = tleft;
5607 else if (tright->complex_type() != NULL)
5608 subcontext.type = tright;
5609 else if (tleft->float_type() != NULL)
5610 subcontext.type = tleft;
5611 else if (tright->float_type() != NULL)
5612 subcontext.type = tright;
5613 else
5614 subcontext.type = tleft;
5616 if (subcontext.type != NULL && !context->may_be_abstract)
5617 subcontext.type = subcontext.type->make_non_abstract_type();
5620 this->left_->determine_type(&subcontext);
5622 if (is_shift_op)
5624 // We may have inherited an unusable type for the shift operand.
5625 // Give a useful error if that happened.
5626 if (tleft->is_abstract()
5627 && subcontext.type != NULL
5628 && !subcontext.may_be_abstract
5629 && subcontext.type->interface_type() == NULL
5630 && subcontext.type->integer_type() == NULL)
5631 this->report_error(("invalid context-determined non-integer type "
5632 "for left operand of shift"));
5634 // The context for the right hand operand is the same as for the
5635 // left hand operand, except for a shift operator.
5636 subcontext.type = Type::lookup_integer_type("uint");
5637 subcontext.may_be_abstract = false;
5640 this->right_->determine_type(&subcontext);
5642 if (is_comparison)
5644 if (this->type_ != NULL && !this->type_->is_abstract())
5646 else if (context->type != NULL && context->type->is_boolean_type())
5647 this->type_ = context->type;
5648 else if (!context->may_be_abstract)
5649 this->type_ = Type::lookup_bool_type();
5653 // Report an error if the binary operator OP does not support TYPE.
5654 // OTYPE is the type of the other operand. Return whether the
5655 // operation is OK. This should not be used for shift.
5657 bool
5658 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5659 Location location)
5661 switch (op)
5663 case OPERATOR_OROR:
5664 case OPERATOR_ANDAND:
5665 if (!type->is_boolean_type())
5667 error_at(location, "expected boolean type");
5668 return false;
5670 break;
5672 case OPERATOR_EQEQ:
5673 case OPERATOR_NOTEQ:
5675 std::string reason;
5676 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5678 error_at(location, "%s", reason.c_str());
5679 return false;
5682 break;
5684 case OPERATOR_LT:
5685 case OPERATOR_LE:
5686 case OPERATOR_GT:
5687 case OPERATOR_GE:
5689 std::string reason;
5690 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5692 error_at(location, "%s", reason.c_str());
5693 return false;
5696 break;
5698 case OPERATOR_PLUS:
5699 case OPERATOR_PLUSEQ:
5700 if (type->integer_type() == NULL
5701 && type->float_type() == NULL
5702 && type->complex_type() == NULL
5703 && !type->is_string_type())
5705 error_at(location,
5706 "expected integer, floating, complex, or string type");
5707 return false;
5709 break;
5711 case OPERATOR_MINUS:
5712 case OPERATOR_MINUSEQ:
5713 case OPERATOR_MULT:
5714 case OPERATOR_MULTEQ:
5715 case OPERATOR_DIV:
5716 case OPERATOR_DIVEQ:
5717 if (type->integer_type() == NULL
5718 && type->float_type() == NULL
5719 && type->complex_type() == NULL)
5721 error_at(location, "expected integer, floating, or complex type");
5722 return false;
5724 break;
5726 case OPERATOR_MOD:
5727 case OPERATOR_MODEQ:
5728 case OPERATOR_OR:
5729 case OPERATOR_OREQ:
5730 case OPERATOR_AND:
5731 case OPERATOR_ANDEQ:
5732 case OPERATOR_XOR:
5733 case OPERATOR_XOREQ:
5734 case OPERATOR_BITCLEAR:
5735 case OPERATOR_BITCLEAREQ:
5736 if (type->integer_type() == NULL)
5738 error_at(location, "expected integer type");
5739 return false;
5741 break;
5743 default:
5744 go_unreachable();
5747 return true;
5750 // Check types.
5752 void
5753 Binary_expression::do_check_types(Gogo*)
5755 if (this->classification() == EXPRESSION_ERROR)
5756 return;
5758 Type* left_type = this->left_->type();
5759 Type* right_type = this->right_->type();
5760 if (left_type->is_error() || right_type->is_error())
5762 this->set_is_error();
5763 return;
5766 if (this->op_ == OPERATOR_EQEQ
5767 || this->op_ == OPERATOR_NOTEQ
5768 || this->op_ == OPERATOR_LT
5769 || this->op_ == OPERATOR_LE
5770 || this->op_ == OPERATOR_GT
5771 || this->op_ == OPERATOR_GE)
5773 if (left_type->is_nil_type() && right_type->is_nil_type())
5775 this->report_error(_("invalid comparison of nil with nil"));
5776 return;
5778 if (!Type::are_assignable(left_type, right_type, NULL)
5779 && !Type::are_assignable(right_type, left_type, NULL))
5781 this->report_error(_("incompatible types in binary expression"));
5782 return;
5784 if (!Binary_expression::check_operator_type(this->op_, left_type,
5785 right_type,
5786 this->location())
5787 || !Binary_expression::check_operator_type(this->op_, right_type,
5788 left_type,
5789 this->location()))
5791 this->set_is_error();
5792 return;
5795 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5797 if (!Type::are_compatible_for_binop(left_type, right_type))
5799 this->report_error(_("incompatible types in binary expression"));
5800 return;
5802 if (!Binary_expression::check_operator_type(this->op_, left_type,
5803 right_type,
5804 this->location()))
5806 this->set_is_error();
5807 return;
5809 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5811 // Division by a zero integer constant is an error.
5812 Numeric_constant rconst;
5813 unsigned long rval;
5814 if (left_type->integer_type() != NULL
5815 && this->right_->numeric_constant_value(&rconst)
5816 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5817 && rval == 0)
5819 this->report_error(_("integer division by zero"));
5820 return;
5824 else
5826 if (left_type->integer_type() == NULL)
5827 this->report_error(_("shift of non-integer operand"));
5829 if (!right_type->is_abstract()
5830 && (right_type->integer_type() == NULL
5831 || !right_type->integer_type()->is_unsigned()))
5832 this->report_error(_("shift count not unsigned integer"));
5833 else
5835 Numeric_constant nc;
5836 if (this->right_->numeric_constant_value(&nc))
5838 mpz_t val;
5839 if (!nc.to_int(&val))
5840 this->report_error(_("shift count not unsigned integer"));
5841 else
5843 if (mpz_sgn(val) < 0)
5845 this->report_error(_("negative shift count"));
5846 mpz_set_ui(val, 0);
5847 Location rloc = this->right_->location();
5848 this->right_ = Expression::make_integer(&val, right_type,
5849 rloc);
5851 mpz_clear(val);
5858 // Get the backend representation for a binary expression.
5860 Bexpression*
5861 Binary_expression::do_get_backend(Translate_context* context)
5863 Gogo* gogo = context->gogo();
5864 Location loc = this->location();
5865 Type* left_type = this->left_->type();
5866 Type* right_type = this->right_->type();
5868 bool use_left_type = true;
5869 bool is_shift_op = false;
5870 bool is_idiv_op = false;
5871 switch (this->op_)
5873 case OPERATOR_EQEQ:
5874 case OPERATOR_NOTEQ:
5875 case OPERATOR_LT:
5876 case OPERATOR_LE:
5877 case OPERATOR_GT:
5878 case OPERATOR_GE:
5879 return Expression::comparison(context, this->type_, this->op_,
5880 this->left_, this->right_, loc);
5882 case OPERATOR_OROR:
5883 case OPERATOR_ANDAND:
5884 use_left_type = false;
5885 break;
5886 case OPERATOR_PLUS:
5887 case OPERATOR_MINUS:
5888 case OPERATOR_OR:
5889 case OPERATOR_XOR:
5890 case OPERATOR_MULT:
5891 break;
5892 case OPERATOR_DIV:
5893 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5894 break;
5895 case OPERATOR_MOD:
5896 is_idiv_op = true;
5897 break;
5898 case OPERATOR_LSHIFT:
5899 case OPERATOR_RSHIFT:
5900 is_shift_op = true;
5901 break;
5902 case OPERATOR_BITCLEAR:
5903 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5904 case OPERATOR_AND:
5905 break;
5906 default:
5907 go_unreachable();
5910 if (left_type->is_string_type())
5912 go_assert(this->op_ == OPERATOR_PLUS);
5913 Expression* string_plus =
5914 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5915 this->left_, this->right_);
5916 return string_plus->get_backend(context);
5919 // For complex division Go might want slightly different results than the
5920 // backend implementation provides, so we have our own runtime routine.
5921 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5923 Runtime::Function complex_code;
5924 switch (this->left_->type()->complex_type()->bits())
5926 case 64:
5927 complex_code = Runtime::COMPLEX64_DIV;
5928 break;
5929 case 128:
5930 complex_code = Runtime::COMPLEX128_DIV;
5931 break;
5932 default:
5933 go_unreachable();
5935 Expression* complex_div =
5936 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5937 return complex_div->get_backend(context);
5940 Bexpression* left = this->left_->get_backend(context);
5941 Bexpression* right = this->right_->get_backend(context);
5943 Type* type = use_left_type ? left_type : right_type;
5944 Btype* btype = type->get_backend(gogo);
5946 Bexpression* ret =
5947 gogo->backend()->binary_expression(this->op_, left, right, loc);
5948 ret = gogo->backend()->convert_expression(btype, ret, loc);
5950 // Initialize overflow constants.
5951 Bexpression* overflow;
5952 mpz_t zero;
5953 mpz_init_set_ui(zero, 0UL);
5954 mpz_t one;
5955 mpz_init_set_ui(one, 1UL);
5956 mpz_t neg_one;
5957 mpz_init_set_si(neg_one, -1);
5959 Btype* left_btype = left_type->get_backend(gogo);
5960 Btype* right_btype = right_type->get_backend(gogo);
5962 // In Go, a shift larger than the size of the type is well-defined.
5963 // This is not true in C, so we need to insert a conditional.
5964 if (is_shift_op)
5966 go_assert(left_type->integer_type() != NULL);
5968 mpz_t bitsval;
5969 int bits = left_type->integer_type()->bits();
5970 mpz_init_set_ui(bitsval, bits);
5971 Bexpression* bits_expr =
5972 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5973 Bexpression* compare =
5974 gogo->backend()->binary_expression(OPERATOR_LT,
5975 right, bits_expr, loc);
5977 Bexpression* zero_expr =
5978 gogo->backend()->integer_constant_expression(left_btype, zero);
5979 overflow = zero_expr;
5980 if (this->op_ == OPERATOR_RSHIFT
5981 && !left_type->integer_type()->is_unsigned())
5983 Bexpression* neg_expr =
5984 gogo->backend()->binary_expression(OPERATOR_LT, left,
5985 zero_expr, loc);
5986 Bexpression* neg_one_expr =
5987 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5988 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5989 neg_one_expr,
5990 zero_expr, loc);
5992 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5993 overflow, loc);
5994 mpz_clear(bitsval);
5997 // Add checks for division by zero and division overflow as needed.
5998 if (is_idiv_op)
6000 if (gogo->check_divide_by_zero())
6002 // right == 0
6003 Bexpression* zero_expr =
6004 gogo->backend()->integer_constant_expression(right_btype, zero);
6005 Bexpression* check =
6006 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6007 right, zero_expr, loc);
6009 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6010 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6011 Bexpression* crash = gogo->runtime_error(errcode,
6012 loc)->get_backend(context);
6014 // right == 0 ? (__go_runtime_error(...), 0) : ret
6015 ret = gogo->backend()->conditional_expression(btype, check, crash,
6016 ret, loc);
6019 if (gogo->check_divide_overflow())
6021 // right == -1
6022 // FIXME: It would be nice to say that this test is expected
6023 // to return false.
6025 Bexpression* neg_one_expr =
6026 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6027 Bexpression* check =
6028 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6029 right, neg_one_expr, loc);
6031 Bexpression* zero_expr =
6032 gogo->backend()->integer_constant_expression(btype, zero);
6033 Bexpression* one_expr =
6034 gogo->backend()->integer_constant_expression(btype, one);
6036 if (type->integer_type()->is_unsigned())
6038 // An unsigned -1 is the largest possible number, so
6039 // dividing is always 1 or 0.
6041 Bexpression* cmp =
6042 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6043 left, right, loc);
6044 if (this->op_ == OPERATOR_DIV)
6045 overflow =
6046 gogo->backend()->conditional_expression(btype, cmp,
6047 one_expr, zero_expr,
6048 loc);
6049 else
6050 overflow =
6051 gogo->backend()->conditional_expression(btype, cmp,
6052 zero_expr, left,
6053 loc);
6055 else
6057 // Computing left / -1 is the same as computing - left,
6058 // which does not overflow since Go sets -fwrapv.
6059 if (this->op_ == OPERATOR_DIV)
6061 Expression* negate_expr =
6062 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6063 overflow = negate_expr->get_backend(context);
6065 else
6066 overflow = zero_expr;
6068 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6070 // right == -1 ? - left : ret
6071 ret = gogo->backend()->conditional_expression(btype, check, overflow,
6072 ret, loc);
6076 mpz_clear(zero);
6077 mpz_clear(one);
6078 mpz_clear(neg_one);
6079 return ret;
6082 // Export a binary expression.
6084 void
6085 Binary_expression::do_export(Export* exp) const
6087 exp->write_c_string("(");
6088 this->left_->export_expression(exp);
6089 switch (this->op_)
6091 case OPERATOR_OROR:
6092 exp->write_c_string(" || ");
6093 break;
6094 case OPERATOR_ANDAND:
6095 exp->write_c_string(" && ");
6096 break;
6097 case OPERATOR_EQEQ:
6098 exp->write_c_string(" == ");
6099 break;
6100 case OPERATOR_NOTEQ:
6101 exp->write_c_string(" != ");
6102 break;
6103 case OPERATOR_LT:
6104 exp->write_c_string(" < ");
6105 break;
6106 case OPERATOR_LE:
6107 exp->write_c_string(" <= ");
6108 break;
6109 case OPERATOR_GT:
6110 exp->write_c_string(" > ");
6111 break;
6112 case OPERATOR_GE:
6113 exp->write_c_string(" >= ");
6114 break;
6115 case OPERATOR_PLUS:
6116 exp->write_c_string(" + ");
6117 break;
6118 case OPERATOR_MINUS:
6119 exp->write_c_string(" - ");
6120 break;
6121 case OPERATOR_OR:
6122 exp->write_c_string(" | ");
6123 break;
6124 case OPERATOR_XOR:
6125 exp->write_c_string(" ^ ");
6126 break;
6127 case OPERATOR_MULT:
6128 exp->write_c_string(" * ");
6129 break;
6130 case OPERATOR_DIV:
6131 exp->write_c_string(" / ");
6132 break;
6133 case OPERATOR_MOD:
6134 exp->write_c_string(" % ");
6135 break;
6136 case OPERATOR_LSHIFT:
6137 exp->write_c_string(" << ");
6138 break;
6139 case OPERATOR_RSHIFT:
6140 exp->write_c_string(" >> ");
6141 break;
6142 case OPERATOR_AND:
6143 exp->write_c_string(" & ");
6144 break;
6145 case OPERATOR_BITCLEAR:
6146 exp->write_c_string(" &^ ");
6147 break;
6148 default:
6149 go_unreachable();
6151 this->right_->export_expression(exp);
6152 exp->write_c_string(")");
6155 // Import a binary expression.
6157 Expression*
6158 Binary_expression::do_import(Import* imp)
6160 imp->require_c_string("(");
6162 Expression* left = Expression::import_expression(imp);
6164 Operator op;
6165 if (imp->match_c_string(" || "))
6167 op = OPERATOR_OROR;
6168 imp->advance(4);
6170 else if (imp->match_c_string(" && "))
6172 op = OPERATOR_ANDAND;
6173 imp->advance(4);
6175 else if (imp->match_c_string(" == "))
6177 op = OPERATOR_EQEQ;
6178 imp->advance(4);
6180 else if (imp->match_c_string(" != "))
6182 op = OPERATOR_NOTEQ;
6183 imp->advance(4);
6185 else if (imp->match_c_string(" < "))
6187 op = OPERATOR_LT;
6188 imp->advance(3);
6190 else if (imp->match_c_string(" <= "))
6192 op = OPERATOR_LE;
6193 imp->advance(4);
6195 else if (imp->match_c_string(" > "))
6197 op = OPERATOR_GT;
6198 imp->advance(3);
6200 else if (imp->match_c_string(" >= "))
6202 op = OPERATOR_GE;
6203 imp->advance(4);
6205 else if (imp->match_c_string(" + "))
6207 op = OPERATOR_PLUS;
6208 imp->advance(3);
6210 else if (imp->match_c_string(" - "))
6212 op = OPERATOR_MINUS;
6213 imp->advance(3);
6215 else if (imp->match_c_string(" | "))
6217 op = OPERATOR_OR;
6218 imp->advance(3);
6220 else if (imp->match_c_string(" ^ "))
6222 op = OPERATOR_XOR;
6223 imp->advance(3);
6225 else if (imp->match_c_string(" * "))
6227 op = OPERATOR_MULT;
6228 imp->advance(3);
6230 else if (imp->match_c_string(" / "))
6232 op = OPERATOR_DIV;
6233 imp->advance(3);
6235 else if (imp->match_c_string(" % "))
6237 op = OPERATOR_MOD;
6238 imp->advance(3);
6240 else if (imp->match_c_string(" << "))
6242 op = OPERATOR_LSHIFT;
6243 imp->advance(4);
6245 else if (imp->match_c_string(" >> "))
6247 op = OPERATOR_RSHIFT;
6248 imp->advance(4);
6250 else if (imp->match_c_string(" & "))
6252 op = OPERATOR_AND;
6253 imp->advance(3);
6255 else if (imp->match_c_string(" &^ "))
6257 op = OPERATOR_BITCLEAR;
6258 imp->advance(4);
6260 else
6262 error_at(imp->location(), "unrecognized binary operator");
6263 return Expression::make_error(imp->location());
6266 Expression* right = Expression::import_expression(imp);
6268 imp->require_c_string(")");
6270 return Expression::make_binary(op, left, right, imp->location());
6273 // Dump ast representation of a binary expression.
6275 void
6276 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6278 ast_dump_context->ostream() << "(";
6279 ast_dump_context->dump_expression(this->left_);
6280 ast_dump_context->ostream() << " ";
6281 ast_dump_context->dump_operator(this->op_);
6282 ast_dump_context->ostream() << " ";
6283 ast_dump_context->dump_expression(this->right_);
6284 ast_dump_context->ostream() << ") ";
6287 // Make a binary expression.
6289 Expression*
6290 Expression::make_binary(Operator op, Expression* left, Expression* right,
6291 Location location)
6293 return new Binary_expression(op, left, right, location);
6296 // Implement a comparison.
6298 Bexpression*
6299 Expression::comparison(Translate_context* context, Type* result_type,
6300 Operator op, Expression* left, Expression* right,
6301 Location location)
6303 Type* left_type = left->type();
6304 Type* right_type = right->type();
6306 mpz_t zval;
6307 mpz_init_set_ui(zval, 0UL);
6308 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
6309 mpz_clear(zval);
6311 if (left_type->is_string_type() && right_type->is_string_type())
6313 left = Runtime::make_call(Runtime::STRCMP, location, 2,
6314 left, right);
6315 right = zexpr;
6317 else if ((left_type->interface_type() != NULL
6318 && right_type->interface_type() == NULL
6319 && !right_type->is_nil_type())
6320 || (left_type->interface_type() == NULL
6321 && !left_type->is_nil_type()
6322 && right_type->interface_type() != NULL))
6324 // Comparing an interface value to a non-interface value.
6325 if (left_type->interface_type() == NULL)
6327 std::swap(left_type, right_type);
6328 std::swap(left, right);
6331 // The right operand is not an interface. We need to take its
6332 // address if it is not a pointer.
6333 Expression* pointer_arg = NULL;
6334 if (right_type->points_to() != NULL)
6335 pointer_arg = right;
6336 else
6338 go_assert(right->is_addressable());
6339 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6340 location);
6343 Expression* descriptor =
6344 Expression::make_type_descriptor(right_type, location);
6345 left =
6346 Runtime::make_call((left_type->interface_type()->is_empty()
6347 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6348 : Runtime::INTERFACE_VALUE_COMPARE),
6349 location, 3, left, descriptor,
6350 pointer_arg);
6351 right = zexpr;
6353 else if (left_type->interface_type() != NULL
6354 && right_type->interface_type() != NULL)
6356 Runtime::Function compare_function;
6357 if (left_type->interface_type()->is_empty()
6358 && right_type->interface_type()->is_empty())
6359 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6360 else if (!left_type->interface_type()->is_empty()
6361 && !right_type->interface_type()->is_empty())
6362 compare_function = Runtime::INTERFACE_COMPARE;
6363 else
6365 if (left_type->interface_type()->is_empty())
6367 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6368 std::swap(left_type, right_type);
6369 std::swap(left, right);
6371 go_assert(!left_type->interface_type()->is_empty());
6372 go_assert(right_type->interface_type()->is_empty());
6373 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6376 left = Runtime::make_call(compare_function, location, 2, left, right);
6377 right = zexpr;
6380 if (left_type->is_nil_type()
6381 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6383 std::swap(left_type, right_type);
6384 std::swap(left, right);
6387 if (right_type->is_nil_type())
6389 right = Expression::make_nil(location);
6390 if (left_type->array_type() != NULL
6391 && left_type->array_type()->length() == NULL)
6393 Array_type* at = left_type->array_type();
6394 left = at->get_value_pointer(context->gogo(), left);
6396 else if (left_type->interface_type() != NULL)
6398 // An interface is nil if the first field is nil.
6399 left = Expression::make_field_reference(left, 0, location);
6403 Bexpression* left_bexpr = left->get_backend(context);
6404 Bexpression* right_bexpr = right->get_backend(context);
6406 Gogo* gogo = context->gogo();
6407 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6408 right_bexpr, location);
6409 if (result_type != NULL)
6410 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6411 ret, location);
6412 return ret;
6415 // Class Bound_method_expression.
6417 // Traversal.
6420 Bound_method_expression::do_traverse(Traverse* traverse)
6422 return Expression::traverse(&this->expr_, traverse);
6425 // Lower the expression. If this is a method value rather than being
6426 // called, and the method is accessed via a pointer, we may need to
6427 // add nil checks. Introduce a temporary variable so that those nil
6428 // checks do not cause multiple evaluation.
6430 Expression*
6431 Bound_method_expression::do_lower(Gogo*, Named_object*,
6432 Statement_inserter* inserter, int)
6434 // For simplicity we use a temporary for every call to an embedded
6435 // method, even though some of them might be pure value methods and
6436 // not require a temporary.
6437 if (this->expr_->var_expression() == NULL
6438 && this->expr_->temporary_reference_expression() == NULL
6439 && this->expr_->set_and_use_temporary_expression() == NULL
6440 && (this->method_->field_indexes() != NULL
6441 || (this->method_->is_value_method()
6442 && this->expr_->type()->points_to() != NULL)))
6444 Temporary_statement* temp =
6445 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6446 inserter->insert(temp);
6447 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6448 this->location());
6450 return this;
6453 // Return the type of a bound method expression. The type of this
6454 // object is simply the type of the method with no receiver.
6456 Type*
6457 Bound_method_expression::do_type()
6459 Named_object* fn = this->method_->named_object();
6460 Function_type* fntype;
6461 if (fn->is_function())
6462 fntype = fn->func_value()->type();
6463 else if (fn->is_function_declaration())
6464 fntype = fn->func_declaration_value()->type();
6465 else
6466 return Type::make_error_type();
6467 return fntype->copy_without_receiver();
6470 // Determine the types of a method expression.
6472 void
6473 Bound_method_expression::do_determine_type(const Type_context*)
6475 Named_object* fn = this->method_->named_object();
6476 Function_type* fntype;
6477 if (fn->is_function())
6478 fntype = fn->func_value()->type();
6479 else if (fn->is_function_declaration())
6480 fntype = fn->func_declaration_value()->type();
6481 else
6482 fntype = NULL;
6483 if (fntype == NULL || !fntype->is_method())
6484 this->expr_->determine_type_no_context();
6485 else
6487 Type_context subcontext(fntype->receiver()->type(), false);
6488 this->expr_->determine_type(&subcontext);
6492 // Check the types of a method expression.
6494 void
6495 Bound_method_expression::do_check_types(Gogo*)
6497 Named_object* fn = this->method_->named_object();
6498 if (!fn->is_function() && !fn->is_function_declaration())
6500 this->report_error(_("object is not a method"));
6501 return;
6504 Function_type* fntype;
6505 if (fn->is_function())
6506 fntype = fn->func_value()->type();
6507 else if (fn->is_function_declaration())
6508 fntype = fn->func_declaration_value()->type();
6509 else
6510 go_unreachable();
6511 Type* rtype = fntype->receiver()->type()->deref();
6512 Type* etype = (this->expr_type_ != NULL
6513 ? this->expr_type_
6514 : this->expr_->type());
6515 etype = etype->deref();
6516 if (!Type::are_identical(rtype, etype, true, NULL))
6517 this->report_error(_("method type does not match object type"));
6520 // If a bound method expression is not simply called, then it is
6521 // represented as a closure. The closure will hold a single variable,
6522 // the receiver to pass to the method. The function will be a simple
6523 // thunk that pulls that value from the closure and calls the method
6524 // with the remaining arguments.
6526 // Because method values are not common, we don't build all thunks for
6527 // every methods, but instead only build them as we need them. In
6528 // particular, we even build them on demand for methods defined in
6529 // other packages.
6531 Bound_method_expression::Method_value_thunks
6532 Bound_method_expression::method_value_thunks;
6534 // Find or create the thunk for METHOD.
6536 Named_object*
6537 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6538 Named_object* fn)
6540 std::pair<Named_object*, Named_object*> val(fn, NULL);
6541 std::pair<Method_value_thunks::iterator, bool> ins =
6542 Bound_method_expression::method_value_thunks.insert(val);
6543 if (!ins.second)
6545 // We have seen this method before.
6546 go_assert(ins.first->second != NULL);
6547 return ins.first->second;
6550 Location loc = fn->location();
6552 Function_type* orig_fntype;
6553 if (fn->is_function())
6554 orig_fntype = fn->func_value()->type();
6555 else if (fn->is_function_declaration())
6556 orig_fntype = fn->func_declaration_value()->type();
6557 else
6558 orig_fntype = NULL;
6560 if (orig_fntype == NULL || !orig_fntype->is_method())
6562 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6563 return ins.first->second;
6566 Struct_field_list* sfl = new Struct_field_list();
6567 // The type here is wrong--it should be the C function type. But it
6568 // doesn't really matter.
6569 Type* vt = Type::make_pointer_type(Type::make_void_type());
6570 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6571 sfl->push_back(Struct_field(Typed_identifier("val.1",
6572 orig_fntype->receiver()->type(),
6573 loc)));
6574 Type* closure_type = Type::make_struct_type(sfl, loc);
6575 closure_type = Type::make_pointer_type(closure_type);
6577 Function_type* new_fntype = orig_fntype->copy_with_names();
6579 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
6580 false, loc);
6582 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6583 cvar->set_is_used();
6584 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
6585 new_no->func_value()->set_closure_var(cp);
6587 gogo->start_block(loc);
6589 // Field 0 of the closure is the function code pointer, field 1 is
6590 // the value on which to invoke the method.
6591 Expression* arg = Expression::make_var_reference(cp, loc);
6592 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6593 arg = Expression::make_field_reference(arg, 1, loc);
6595 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6597 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6598 Expression_list* args;
6599 if (orig_params == NULL || orig_params->empty())
6600 args = NULL;
6601 else
6603 const Typed_identifier_list* new_params = new_fntype->parameters();
6604 args = new Expression_list();
6605 for (Typed_identifier_list::const_iterator p = new_params->begin();
6606 p != new_params->end();
6607 ++p)
6609 Named_object* p_no = gogo->lookup(p->name(), NULL);
6610 go_assert(p_no != NULL
6611 && p_no->is_variable()
6612 && p_no->var_value()->is_parameter());
6613 args->push_back(Expression::make_var_reference(p_no, loc));
6617 Call_expression* call = Expression::make_call(bme, args,
6618 orig_fntype->is_varargs(),
6619 loc);
6620 call->set_varargs_are_lowered();
6622 Statement* s = Statement::make_return_from_call(call, loc);
6623 gogo->add_statement(s);
6624 Block* b = gogo->finish_block(loc);
6625 gogo->add_block(b, loc);
6626 gogo->lower_block(new_no, b);
6627 gogo->flatten_block(new_no, b);
6628 gogo->finish_function(loc);
6630 ins.first->second = new_no;
6631 return new_no;
6634 // Return an expression to check *REF for nil while dereferencing
6635 // according to FIELD_INDEXES. Update *REF to build up the field
6636 // reference. This is a static function so that we don't have to
6637 // worry about declaring Field_indexes in expressions.h.
6639 static Expression*
6640 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6641 Expression** ref)
6643 if (field_indexes == NULL)
6644 return Expression::make_boolean(false, loc);
6645 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6646 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6647 go_assert(stype != NULL
6648 && field_indexes->field_index < stype->field_count());
6649 if ((*ref)->type()->struct_type() == NULL)
6651 go_assert((*ref)->type()->points_to() != NULL);
6652 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6653 Expression::make_nil(loc),
6654 loc);
6655 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6656 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6657 go_assert((*ref)->type()->struct_type() == stype);
6659 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6660 loc);
6661 return cond;
6664 // Get the backend representation for a method value.
6666 Bexpression*
6667 Bound_method_expression::do_get_backend(Translate_context* context)
6669 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6670 this->method_,
6671 this->function_);
6672 if (thunk->is_erroneous())
6674 go_assert(saw_errors());
6675 return context->backend()->error_expression();
6678 // FIXME: We should lower this earlier, but we can't lower it in the
6679 // lowering pass because at that point we don't know whether we need
6680 // to create the thunk or not. If the expression is called, we
6681 // don't need the thunk.
6683 Location loc = this->location();
6685 // If the method expects a value, and we have a pointer, we need to
6686 // dereference the pointer.
6688 Named_object* fn = this->method_->named_object();
6689 Function_type* fntype;
6690 if (fn->is_function())
6691 fntype = fn->func_value()->type();
6692 else if (fn->is_function_declaration())
6693 fntype = fn->func_declaration_value()->type();
6694 else
6695 go_unreachable();
6697 Expression* val = this->expr_;
6698 if (fntype->receiver()->type()->points_to() == NULL
6699 && val->type()->points_to() != NULL)
6700 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6702 // Note that we are ignoring this->expr_type_ here. The thunk will
6703 // expect a closure whose second field has type this->expr_type_ (if
6704 // that is not NULL). We are going to pass it a closure whose
6705 // second field has type this->expr_->type(). Since
6706 // this->expr_type_ is only not-NULL for pointer types, we can get
6707 // away with this.
6709 Struct_field_list* fields = new Struct_field_list();
6710 fields->push_back(Struct_field(Typed_identifier("fn.0",
6711 thunk->func_value()->type(),
6712 loc)));
6713 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6714 Struct_type* st = Type::make_struct_type(fields, loc);
6716 Expression_list* vals = new Expression_list();
6717 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6718 vals->push_back(val);
6720 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6721 ret = Expression::make_heap_expression(ret, loc);
6723 // See whether the expression or any embedded pointers are nil.
6725 Expression* nil_check = NULL;
6726 Expression* expr = this->expr_;
6727 if (this->method_->field_indexes() != NULL)
6729 // Note that we are evaluating this->expr_ twice, but that is OK
6730 // because in the lowering pass we forced it into a temporary
6731 // variable.
6732 Expression* ref = expr;
6733 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6734 expr = ref;
6737 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6739 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6740 Expression::make_nil(loc),
6741 loc);
6742 if (nil_check == NULL)
6743 nil_check = n;
6744 else
6745 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6748 Bexpression* bme = ret->get_backend(context);
6749 if (nil_check != NULL)
6751 Gogo* gogo = context->gogo();
6752 Bexpression* crash =
6753 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6754 loc)->get_backend(context);
6755 Btype* btype = ret->type()->get_backend(gogo);
6756 Bexpression* bcheck = nil_check->get_backend(context);
6757 bme = gogo->backend()->conditional_expression(btype, bcheck, crash,
6758 bme, loc);
6760 return bme;
6763 // Dump ast representation of a bound method expression.
6765 void
6766 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6767 const
6769 if (this->expr_type_ != NULL)
6770 ast_dump_context->ostream() << "(";
6771 ast_dump_context->dump_expression(this->expr_);
6772 if (this->expr_type_ != NULL)
6774 ast_dump_context->ostream() << ":";
6775 ast_dump_context->dump_type(this->expr_type_);
6776 ast_dump_context->ostream() << ")";
6779 ast_dump_context->ostream() << "." << this->function_->name();
6782 // Make a method expression.
6784 Bound_method_expression*
6785 Expression::make_bound_method(Expression* expr, const Method* method,
6786 Named_object* function, Location location)
6788 return new Bound_method_expression(expr, method, function, location);
6791 // Class Builtin_call_expression. This is used for a call to a
6792 // builtin function.
6794 class Builtin_call_expression : public Call_expression
6796 public:
6797 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6798 bool is_varargs, Location location);
6800 protected:
6801 // This overrides Call_expression::do_lower.
6802 Expression*
6803 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6805 Expression*
6806 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6808 bool
6809 do_is_constant() const;
6811 bool
6812 do_numeric_constant_value(Numeric_constant*) const;
6814 bool
6815 do_discarding_value();
6817 Type*
6818 do_type();
6820 void
6821 do_determine_type(const Type_context*);
6823 void
6824 do_check_types(Gogo*);
6826 Expression*
6827 do_copy()
6829 return new Builtin_call_expression(this->gogo_, this->fn()->copy(),
6830 this->args()->copy(),
6831 this->is_varargs(),
6832 this->location());
6835 Bexpression*
6836 do_get_backend(Translate_context*);
6838 void
6839 do_export(Export*) const;
6841 virtual bool
6842 do_is_recover_call() const;
6844 virtual void
6845 do_set_recover_arg(Expression*);
6847 private:
6848 // The builtin functions.
6849 enum Builtin_function_code
6851 BUILTIN_INVALID,
6853 // Predeclared builtin functions.
6854 BUILTIN_APPEND,
6855 BUILTIN_CAP,
6856 BUILTIN_CLOSE,
6857 BUILTIN_COMPLEX,
6858 BUILTIN_COPY,
6859 BUILTIN_DELETE,
6860 BUILTIN_IMAG,
6861 BUILTIN_LEN,
6862 BUILTIN_MAKE,
6863 BUILTIN_NEW,
6864 BUILTIN_PANIC,
6865 BUILTIN_PRINT,
6866 BUILTIN_PRINTLN,
6867 BUILTIN_REAL,
6868 BUILTIN_RECOVER,
6870 // Builtin functions from the unsafe package.
6871 BUILTIN_ALIGNOF,
6872 BUILTIN_OFFSETOF,
6873 BUILTIN_SIZEOF
6876 Expression*
6877 one_arg() const;
6879 bool
6880 check_one_arg();
6882 static Type*
6883 real_imag_type(Type*);
6885 static Type*
6886 complex_type(Type*);
6888 Expression*
6889 lower_make();
6891 bool
6892 check_int_value(Expression*, bool is_length);
6894 // A pointer back to the general IR structure. This avoids a global
6895 // variable, or passing it around everywhere.
6896 Gogo* gogo_;
6897 // The builtin function being called.
6898 Builtin_function_code code_;
6899 // Used to stop endless loops when the length of an array uses len
6900 // or cap of the array itself.
6901 mutable bool seen_;
6904 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6905 Expression* fn,
6906 Expression_list* args,
6907 bool is_varargs,
6908 Location location)
6909 : Call_expression(fn, args, is_varargs, location),
6910 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false)
6912 Func_expression* fnexp = this->fn()->func_expression();
6913 go_assert(fnexp != NULL);
6914 const std::string& name(fnexp->named_object()->name());
6915 if (name == "append")
6916 this->code_ = BUILTIN_APPEND;
6917 else if (name == "cap")
6918 this->code_ = BUILTIN_CAP;
6919 else if (name == "close")
6920 this->code_ = BUILTIN_CLOSE;
6921 else if (name == "complex")
6922 this->code_ = BUILTIN_COMPLEX;
6923 else if (name == "copy")
6924 this->code_ = BUILTIN_COPY;
6925 else if (name == "delete")
6926 this->code_ = BUILTIN_DELETE;
6927 else if (name == "imag")
6928 this->code_ = BUILTIN_IMAG;
6929 else if (name == "len")
6930 this->code_ = BUILTIN_LEN;
6931 else if (name == "make")
6932 this->code_ = BUILTIN_MAKE;
6933 else if (name == "new")
6934 this->code_ = BUILTIN_NEW;
6935 else if (name == "panic")
6936 this->code_ = BUILTIN_PANIC;
6937 else if (name == "print")
6938 this->code_ = BUILTIN_PRINT;
6939 else if (name == "println")
6940 this->code_ = BUILTIN_PRINTLN;
6941 else if (name == "real")
6942 this->code_ = BUILTIN_REAL;
6943 else if (name == "recover")
6944 this->code_ = BUILTIN_RECOVER;
6945 else if (name == "Alignof")
6946 this->code_ = BUILTIN_ALIGNOF;
6947 else if (name == "Offsetof")
6948 this->code_ = BUILTIN_OFFSETOF;
6949 else if (name == "Sizeof")
6950 this->code_ = BUILTIN_SIZEOF;
6951 else
6952 go_unreachable();
6955 // Return whether this is a call to recover. This is a virtual
6956 // function called from the parent class.
6958 bool
6959 Builtin_call_expression::do_is_recover_call() const
6961 if (this->classification() == EXPRESSION_ERROR)
6962 return false;
6963 return this->code_ == BUILTIN_RECOVER;
6966 // Set the argument for a call to recover.
6968 void
6969 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6971 const Expression_list* args = this->args();
6972 go_assert(args == NULL || args->empty());
6973 Expression_list* new_args = new Expression_list();
6974 new_args->push_back(arg);
6975 this->set_args(new_args);
6978 // Lower a builtin call expression. This turns new and make into
6979 // specific expressions. We also convert to a constant if we can.
6981 Expression*
6982 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6983 Statement_inserter* inserter, int)
6985 if (this->classification() == EXPRESSION_ERROR)
6986 return this;
6988 Location loc = this->location();
6990 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6992 this->report_error(_("invalid use of %<...%> with builtin function"));
6993 return Expression::make_error(loc);
6996 if (this->code_ == BUILTIN_OFFSETOF)
6998 Expression* arg = this->one_arg();
7000 if (arg->bound_method_expression() != NULL
7001 || arg->interface_field_reference_expression() != NULL)
7003 this->report_error(_("invalid use of method value as argument "
7004 "of Offsetof"));
7005 return this;
7008 Field_reference_expression* farg = arg->field_reference_expression();
7009 while (farg != NULL)
7011 if (!farg->implicit())
7012 break;
7013 // When the selector refers to an embedded field,
7014 // it must not be reached through pointer indirections.
7015 if (farg->expr()->deref() != farg->expr())
7017 this->report_error(_("argument of Offsetof implies "
7018 "indirection of an embedded field"));
7019 return this;
7021 // Go up until we reach the original base.
7022 farg = farg->expr()->field_reference_expression();
7026 if (this->is_constant())
7028 Numeric_constant nc;
7029 if (this->numeric_constant_value(&nc))
7030 return nc.expression(loc);
7033 switch (this->code_)
7035 default:
7036 break;
7038 case BUILTIN_NEW:
7040 const Expression_list* args = this->args();
7041 if (args == NULL || args->size() < 1)
7042 this->report_error(_("not enough arguments"));
7043 else if (args->size() > 1)
7044 this->report_error(_("too many arguments"));
7045 else
7047 Expression* arg = args->front();
7048 if (!arg->is_type_expression())
7050 error_at(arg->location(), "expected type");
7051 this->set_is_error();
7053 else
7054 return Expression::make_allocation(arg->type(), loc);
7057 break;
7059 case BUILTIN_MAKE:
7060 return this->lower_make();
7062 case BUILTIN_RECOVER:
7063 if (function != NULL)
7064 function->func_value()->set_calls_recover();
7065 else
7067 // Calling recover outside of a function always returns the
7068 // nil empty interface.
7069 Type* eface = Type::make_empty_interface_type(loc);
7070 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7072 break;
7074 case BUILTIN_APPEND:
7076 // Lower the varargs.
7077 const Expression_list* args = this->args();
7078 if (args == NULL || args->empty())
7079 return this;
7080 Type* slice_type = args->front()->type();
7081 if (!slice_type->is_slice_type())
7083 if (slice_type->is_nil_type())
7084 error_at(args->front()->location(), "use of untyped nil");
7085 else
7086 error_at(args->front()->location(),
7087 "argument 1 must be a slice");
7088 this->set_is_error();
7089 return this;
7091 Type* element_type = slice_type->array_type()->element_type();
7092 this->lower_varargs(gogo, function, inserter,
7093 Type::make_array_type(element_type, NULL),
7096 break;
7098 case BUILTIN_DELETE:
7100 // Lower to a runtime function call.
7101 const Expression_list* args = this->args();
7102 if (args == NULL || args->size() < 2)
7103 this->report_error(_("not enough arguments"));
7104 else if (args->size() > 2)
7105 this->report_error(_("too many arguments"));
7106 else if (args->front()->type()->map_type() == NULL)
7107 this->report_error(_("argument 1 must be a map"));
7108 else
7110 // Since this function returns no value it must appear in
7111 // a statement by itself, so we don't have to worry about
7112 // order of evaluation of values around it. Evaluate the
7113 // map first to get order of evaluation right.
7114 Map_type* mt = args->front()->type()->map_type();
7115 Temporary_statement* map_temp =
7116 Statement::make_temporary(mt, args->front(), loc);
7117 inserter->insert(map_temp);
7119 Temporary_statement* key_temp =
7120 Statement::make_temporary(mt->key_type(), args->back(), loc);
7121 inserter->insert(key_temp);
7123 Expression* e1 = Expression::make_temporary_reference(map_temp,
7124 loc);
7125 Expression* e2 = Expression::make_temporary_reference(key_temp,
7126 loc);
7127 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
7128 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7129 2, e1, e2);
7132 break;
7135 return this;
7138 // Flatten a builtin call expression. This turns the arguments of copy and
7139 // append into temporary expressions.
7141 Expression*
7142 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
7143 Statement_inserter* inserter)
7145 if (this->code_ == BUILTIN_APPEND
7146 || this->code_ == BUILTIN_COPY)
7148 Location loc = this->location();
7149 Type* at = this->args()->front()->type();
7150 for (Expression_list::iterator pa = this->args()->begin();
7151 pa != this->args()->end();
7152 ++pa)
7154 if ((*pa)->is_nil_expression())
7155 *pa = Expression::make_slice_composite_literal(at, NULL, loc);
7156 if (!(*pa)->is_variable())
7158 Temporary_statement* temp =
7159 Statement::make_temporary(NULL, *pa, loc);
7160 inserter->insert(temp);
7161 *pa = Expression::make_temporary_reference(temp, loc);
7165 return this;
7168 // Lower a make expression.
7170 Expression*
7171 Builtin_call_expression::lower_make()
7173 Location loc = this->location();
7175 const Expression_list* args = this->args();
7176 if (args == NULL || args->size() < 1)
7178 this->report_error(_("not enough arguments"));
7179 return Expression::make_error(this->location());
7182 Expression_list::const_iterator parg = args->begin();
7184 Expression* first_arg = *parg;
7185 if (!first_arg->is_type_expression())
7187 error_at(first_arg->location(), "expected type");
7188 this->set_is_error();
7189 return Expression::make_error(this->location());
7191 Type* type = first_arg->type();
7193 bool is_slice = false;
7194 bool is_map = false;
7195 bool is_chan = false;
7196 if (type->is_slice_type())
7197 is_slice = true;
7198 else if (type->map_type() != NULL)
7199 is_map = true;
7200 else if (type->channel_type() != NULL)
7201 is_chan = true;
7202 else
7204 this->report_error(_("invalid type for make function"));
7205 return Expression::make_error(this->location());
7208 bool have_big_args = false;
7209 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7210 int uintptr_bits = uintptr_type->integer_type()->bits();
7212 Type_context int_context(Type::lookup_integer_type("int"), false);
7214 ++parg;
7215 Expression* len_arg;
7216 if (parg == args->end())
7218 if (is_slice)
7220 this->report_error(_("length required when allocating a slice"));
7221 return Expression::make_error(this->location());
7224 mpz_t zval;
7225 mpz_init_set_ui(zval, 0);
7226 len_arg = Expression::make_integer(&zval, NULL, loc);
7227 mpz_clear(zval);
7229 else
7231 len_arg = *parg;
7232 len_arg->determine_type(&int_context);
7233 if (!this->check_int_value(len_arg, true))
7234 return Expression::make_error(this->location());
7235 if (len_arg->type()->integer_type() != NULL
7236 && len_arg->type()->integer_type()->bits() > uintptr_bits)
7237 have_big_args = true;
7238 ++parg;
7241 Expression* cap_arg = NULL;
7242 if (is_slice && parg != args->end())
7244 cap_arg = *parg;
7245 cap_arg->determine_type(&int_context);
7246 if (!this->check_int_value(cap_arg, false))
7247 return Expression::make_error(this->location());
7249 Numeric_constant nclen;
7250 Numeric_constant nccap;
7251 unsigned long vlen;
7252 unsigned long vcap;
7253 if (len_arg->numeric_constant_value(&nclen)
7254 && cap_arg->numeric_constant_value(&nccap)
7255 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7256 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7257 && vlen > vcap)
7259 this->report_error(_("len larger than cap"));
7260 return Expression::make_error(this->location());
7263 if (cap_arg->type()->integer_type() != NULL
7264 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
7265 have_big_args = true;
7266 ++parg;
7269 if (parg != args->end())
7271 this->report_error(_("too many arguments to make"));
7272 return Expression::make_error(this->location());
7275 Location type_loc = first_arg->location();
7276 Expression* type_arg;
7277 if (is_slice || is_chan)
7278 type_arg = Expression::make_type_descriptor(type, type_loc);
7279 else if (is_map)
7280 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
7281 else
7282 go_unreachable();
7284 Expression* call;
7285 if (is_slice)
7287 if (cap_arg == NULL)
7288 call = Runtime::make_call((have_big_args
7289 ? Runtime::MAKESLICE1BIG
7290 : Runtime::MAKESLICE1),
7291 loc, 2, type_arg, len_arg);
7292 else
7293 call = Runtime::make_call((have_big_args
7294 ? Runtime::MAKESLICE2BIG
7295 : Runtime::MAKESLICE2),
7296 loc, 3, type_arg, len_arg, cap_arg);
7298 else if (is_map)
7299 call = Runtime::make_call((have_big_args
7300 ? Runtime::MAKEMAPBIG
7301 : Runtime::MAKEMAP),
7302 loc, 2, type_arg, len_arg);
7303 else if (is_chan)
7304 call = Runtime::make_call((have_big_args
7305 ? Runtime::MAKECHANBIG
7306 : Runtime::MAKECHAN),
7307 loc, 2, type_arg, len_arg);
7308 else
7309 go_unreachable();
7311 return Expression::make_unsafe_cast(type, call, loc);
7314 // Return whether an expression has an integer value. Report an error
7315 // if not. This is used when handling calls to the predeclared make
7316 // function.
7318 bool
7319 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7321 Numeric_constant nc;
7322 if (e->numeric_constant_value(&nc))
7324 unsigned long v;
7325 switch (nc.to_unsigned_long(&v))
7327 case Numeric_constant::NC_UL_VALID:
7328 break;
7329 case Numeric_constant::NC_UL_NOTINT:
7330 error_at(e->location(), "non-integer %s argument to make",
7331 is_length ? "len" : "cap");
7332 return false;
7333 case Numeric_constant::NC_UL_NEGATIVE:
7334 error_at(e->location(), "negative %s argument to make",
7335 is_length ? "len" : "cap");
7336 return false;
7337 case Numeric_constant::NC_UL_BIG:
7338 // We don't want to give a compile-time error for a 64-bit
7339 // value on a 32-bit target.
7340 break;
7343 mpz_t val;
7344 if (!nc.to_int(&val))
7345 go_unreachable();
7346 int bits = mpz_sizeinbase(val, 2);
7347 mpz_clear(val);
7348 Type* int_type = Type::lookup_integer_type("int");
7349 if (bits >= int_type->integer_type()->bits())
7351 error_at(e->location(), "%s argument too large for make",
7352 is_length ? "len" : "cap");
7353 return false;
7356 return true;
7359 if (e->type()->integer_type() != NULL)
7360 return true;
7362 error_at(e->location(), "non-integer %s argument to make",
7363 is_length ? "len" : "cap");
7364 return false;
7367 // Return the type of the real or imag functions, given the type of
7368 // the argument. We need to map complex to float, complex64 to
7369 // float32, and complex128 to float64, so it has to be done by name.
7370 // This returns NULL if it can't figure out the type.
7372 Type*
7373 Builtin_call_expression::real_imag_type(Type* arg_type)
7375 if (arg_type == NULL || arg_type->is_abstract())
7376 return NULL;
7377 Named_type* nt = arg_type->named_type();
7378 if (nt == NULL)
7379 return NULL;
7380 while (nt->real_type()->named_type() != NULL)
7381 nt = nt->real_type()->named_type();
7382 if (nt->name() == "complex64")
7383 return Type::lookup_float_type("float32");
7384 else if (nt->name() == "complex128")
7385 return Type::lookup_float_type("float64");
7386 else
7387 return NULL;
7390 // Return the type of the complex function, given the type of one of the
7391 // argments. Like real_imag_type, we have to map by name.
7393 Type*
7394 Builtin_call_expression::complex_type(Type* arg_type)
7396 if (arg_type == NULL || arg_type->is_abstract())
7397 return NULL;
7398 Named_type* nt = arg_type->named_type();
7399 if (nt == NULL)
7400 return NULL;
7401 while (nt->real_type()->named_type() != NULL)
7402 nt = nt->real_type()->named_type();
7403 if (nt->name() == "float32")
7404 return Type::lookup_complex_type("complex64");
7405 else if (nt->name() == "float64")
7406 return Type::lookup_complex_type("complex128");
7407 else
7408 return NULL;
7411 // Return a single argument, or NULL if there isn't one.
7413 Expression*
7414 Builtin_call_expression::one_arg() const
7416 const Expression_list* args = this->args();
7417 if (args == NULL || args->size() != 1)
7418 return NULL;
7419 return args->front();
7422 // A traversal class which looks for a call or receive expression.
7424 class Find_call_expression : public Traverse
7426 public:
7427 Find_call_expression()
7428 : Traverse(traverse_expressions),
7429 found_(false)
7433 expression(Expression**);
7435 bool
7436 found()
7437 { return this->found_; }
7439 private:
7440 bool found_;
7444 Find_call_expression::expression(Expression** pexpr)
7446 if ((*pexpr)->call_expression() != NULL
7447 || (*pexpr)->receive_expression() != NULL)
7449 this->found_ = true;
7450 return TRAVERSE_EXIT;
7452 return TRAVERSE_CONTINUE;
7455 // Return whether this is constant: len of a string constant, or len
7456 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7457 // unsafe.Alignof.
7459 bool
7460 Builtin_call_expression::do_is_constant() const
7462 if (this->is_error_expression())
7463 return true;
7464 switch (this->code_)
7466 case BUILTIN_LEN:
7467 case BUILTIN_CAP:
7469 if (this->seen_)
7470 return false;
7472 Expression* arg = this->one_arg();
7473 if (arg == NULL)
7474 return false;
7475 Type* arg_type = arg->type();
7477 if (arg_type->points_to() != NULL
7478 && arg_type->points_to()->array_type() != NULL
7479 && !arg_type->points_to()->is_slice_type())
7480 arg_type = arg_type->points_to();
7482 // The len and cap functions are only constant if there are no
7483 // function calls or channel operations in the arguments.
7484 // Otherwise we have to make the call.
7485 if (!arg->is_constant())
7487 Find_call_expression find_call;
7488 Expression::traverse(&arg, &find_call);
7489 if (find_call.found())
7490 return false;
7493 if (arg_type->array_type() != NULL
7494 && arg_type->array_type()->length() != NULL)
7495 return true;
7497 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7499 this->seen_ = true;
7500 bool ret = arg->is_constant();
7501 this->seen_ = false;
7502 return ret;
7505 break;
7507 case BUILTIN_SIZEOF:
7508 case BUILTIN_ALIGNOF:
7509 return this->one_arg() != NULL;
7511 case BUILTIN_OFFSETOF:
7513 Expression* arg = this->one_arg();
7514 if (arg == NULL)
7515 return false;
7516 return arg->field_reference_expression() != NULL;
7519 case BUILTIN_COMPLEX:
7521 const Expression_list* args = this->args();
7522 if (args != NULL && args->size() == 2)
7523 return args->front()->is_constant() && args->back()->is_constant();
7525 break;
7527 case BUILTIN_REAL:
7528 case BUILTIN_IMAG:
7530 Expression* arg = this->one_arg();
7531 return arg != NULL && arg->is_constant();
7534 default:
7535 break;
7538 return false;
7541 // Return a numeric constant if possible.
7543 bool
7544 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7546 if (this->code_ == BUILTIN_LEN
7547 || this->code_ == BUILTIN_CAP)
7549 Expression* arg = this->one_arg();
7550 if (arg == NULL)
7551 return false;
7552 Type* arg_type = arg->type();
7554 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7556 std::string sval;
7557 if (arg->string_constant_value(&sval))
7559 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7560 sval.length());
7561 return true;
7565 if (arg_type->points_to() != NULL
7566 && arg_type->points_to()->array_type() != NULL
7567 && !arg_type->points_to()->is_slice_type())
7568 arg_type = arg_type->points_to();
7570 if (arg_type->array_type() != NULL
7571 && arg_type->array_type()->length() != NULL)
7573 if (this->seen_)
7574 return false;
7575 Expression* e = arg_type->array_type()->length();
7576 this->seen_ = true;
7577 bool r = e->numeric_constant_value(nc);
7578 this->seen_ = false;
7579 if (r)
7581 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7582 this->location()))
7583 r = false;
7585 return r;
7588 else if (this->code_ == BUILTIN_SIZEOF
7589 || this->code_ == BUILTIN_ALIGNOF)
7591 Expression* arg = this->one_arg();
7592 if (arg == NULL)
7593 return false;
7594 Type* arg_type = arg->type();
7595 if (arg_type->is_error())
7596 return false;
7597 if (arg_type->is_abstract())
7598 return false;
7599 if (this->seen_)
7600 return false;
7602 unsigned long ret;
7603 if (this->code_ == BUILTIN_SIZEOF)
7605 this->seen_ = true;
7606 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7607 this->seen_ = false;
7608 if (!ok)
7609 return false;
7611 else if (this->code_ == BUILTIN_ALIGNOF)
7613 bool ok;
7614 this->seen_ = true;
7615 if (arg->field_reference_expression() == NULL)
7616 ok = arg_type->backend_type_align(this->gogo_, &ret);
7617 else
7619 // Calling unsafe.Alignof(s.f) returns the alignment of
7620 // the type of f when it is used as a field in a struct.
7621 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7623 this->seen_ = false;
7624 if (!ok)
7625 return false;
7627 else
7628 go_unreachable();
7630 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"), ret);
7631 return true;
7633 else if (this->code_ == BUILTIN_OFFSETOF)
7635 Expression* arg = this->one_arg();
7636 if (arg == NULL)
7637 return false;
7638 Field_reference_expression* farg = arg->field_reference_expression();
7639 if (farg == NULL)
7640 return false;
7641 if (this->seen_)
7642 return false;
7644 unsigned int total_offset = 0;
7645 while (true)
7647 Expression* struct_expr = farg->expr();
7648 Type* st = struct_expr->type();
7649 if (st->struct_type() == NULL)
7650 return false;
7651 if (st->named_type() != NULL)
7652 st->named_type()->convert(this->gogo_);
7653 unsigned int offset;
7654 this->seen_ = true;
7655 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7656 farg->field_index(),
7657 &offset);
7658 this->seen_ = false;
7659 if (!ok)
7660 return false;
7661 total_offset += offset;
7662 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7664 // Go up until we reach the original base.
7665 farg = struct_expr->field_reference_expression();
7666 continue;
7668 break;
7670 nc->set_unsigned_long(Type::lookup_integer_type("uintptr"),
7671 static_cast<unsigned long>(total_offset));
7672 return true;
7674 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7676 Expression* arg = this->one_arg();
7677 if (arg == NULL)
7678 return false;
7680 Numeric_constant argnc;
7681 if (!arg->numeric_constant_value(&argnc))
7682 return false;
7684 mpfr_t real;
7685 mpfr_t imag;
7686 if (!argnc.to_complex(&real, &imag))
7687 return false;
7689 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7690 if (this->code_ == BUILTIN_REAL)
7691 nc->set_float(type, real);
7692 else
7693 nc->set_float(type, imag);
7694 return true;
7696 else if (this->code_ == BUILTIN_COMPLEX)
7698 const Expression_list* args = this->args();
7699 if (args == NULL || args->size() != 2)
7700 return false;
7702 Numeric_constant rnc;
7703 if (!args->front()->numeric_constant_value(&rnc))
7704 return false;
7705 Numeric_constant inc;
7706 if (!args->back()->numeric_constant_value(&inc))
7707 return false;
7709 if (rnc.type() != NULL
7710 && !rnc.type()->is_abstract()
7711 && inc.type() != NULL
7712 && !inc.type()->is_abstract()
7713 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7714 return false;
7716 mpfr_t r;
7717 if (!rnc.to_float(&r))
7718 return false;
7719 mpfr_t i;
7720 if (!inc.to_float(&i))
7722 mpfr_clear(r);
7723 return false;
7726 Type* arg_type = rnc.type();
7727 if (arg_type == NULL || arg_type->is_abstract())
7728 arg_type = inc.type();
7730 Type* type = Builtin_call_expression::complex_type(arg_type);
7731 nc->set_complex(type, r, i);
7733 mpfr_clear(r);
7734 mpfr_clear(i);
7736 return true;
7739 return false;
7742 // Give an error if we are discarding the value of an expression which
7743 // should not normally be discarded. We don't give an error for
7744 // discarding the value of an ordinary function call, but we do for
7745 // builtin functions, purely for consistency with the gc compiler.
7747 bool
7748 Builtin_call_expression::do_discarding_value()
7750 switch (this->code_)
7752 case BUILTIN_INVALID:
7753 default:
7754 go_unreachable();
7756 case BUILTIN_APPEND:
7757 case BUILTIN_CAP:
7758 case BUILTIN_COMPLEX:
7759 case BUILTIN_IMAG:
7760 case BUILTIN_LEN:
7761 case BUILTIN_MAKE:
7762 case BUILTIN_NEW:
7763 case BUILTIN_REAL:
7764 case BUILTIN_ALIGNOF:
7765 case BUILTIN_OFFSETOF:
7766 case BUILTIN_SIZEOF:
7767 this->unused_value_error();
7768 return false;
7770 case BUILTIN_CLOSE:
7771 case BUILTIN_COPY:
7772 case BUILTIN_DELETE:
7773 case BUILTIN_PANIC:
7774 case BUILTIN_PRINT:
7775 case BUILTIN_PRINTLN:
7776 case BUILTIN_RECOVER:
7777 return true;
7781 // Return the type.
7783 Type*
7784 Builtin_call_expression::do_type()
7786 switch (this->code_)
7788 case BUILTIN_INVALID:
7789 default:
7790 go_unreachable();
7792 case BUILTIN_NEW:
7793 case BUILTIN_MAKE:
7795 const Expression_list* args = this->args();
7796 if (args == NULL || args->empty())
7797 return Type::make_error_type();
7798 return Type::make_pointer_type(args->front()->type());
7801 case BUILTIN_CAP:
7802 case BUILTIN_COPY:
7803 case BUILTIN_LEN:
7804 return Type::lookup_integer_type("int");
7806 case BUILTIN_ALIGNOF:
7807 case BUILTIN_OFFSETOF:
7808 case BUILTIN_SIZEOF:
7809 return Type::lookup_integer_type("uintptr");
7811 case BUILTIN_CLOSE:
7812 case BUILTIN_DELETE:
7813 case BUILTIN_PANIC:
7814 case BUILTIN_PRINT:
7815 case BUILTIN_PRINTLN:
7816 return Type::make_void_type();
7818 case BUILTIN_RECOVER:
7819 return Type::make_empty_interface_type(Linemap::predeclared_location());
7821 case BUILTIN_APPEND:
7823 const Expression_list* args = this->args();
7824 if (args == NULL || args->empty())
7825 return Type::make_error_type();
7826 Type *ret = args->front()->type();
7827 if (!ret->is_slice_type())
7828 return Type::make_error_type();
7829 return ret;
7832 case BUILTIN_REAL:
7833 case BUILTIN_IMAG:
7835 Expression* arg = this->one_arg();
7836 if (arg == NULL)
7837 return Type::make_error_type();
7838 Type* t = arg->type();
7839 if (t->is_abstract())
7840 t = t->make_non_abstract_type();
7841 t = Builtin_call_expression::real_imag_type(t);
7842 if (t == NULL)
7843 t = Type::make_error_type();
7844 return t;
7847 case BUILTIN_COMPLEX:
7849 const Expression_list* args = this->args();
7850 if (args == NULL || args->size() != 2)
7851 return Type::make_error_type();
7852 Type* t = args->front()->type();
7853 if (t->is_abstract())
7855 t = args->back()->type();
7856 if (t->is_abstract())
7857 t = t->make_non_abstract_type();
7859 t = Builtin_call_expression::complex_type(t);
7860 if (t == NULL)
7861 t = Type::make_error_type();
7862 return t;
7867 // Determine the type.
7869 void
7870 Builtin_call_expression::do_determine_type(const Type_context* context)
7872 if (!this->determining_types())
7873 return;
7875 this->fn()->determine_type_no_context();
7877 const Expression_list* args = this->args();
7879 bool is_print;
7880 Type* arg_type = NULL;
7881 switch (this->code_)
7883 case BUILTIN_PRINT:
7884 case BUILTIN_PRINTLN:
7885 // Do not force a large integer constant to "int".
7886 is_print = true;
7887 break;
7889 case BUILTIN_REAL:
7890 case BUILTIN_IMAG:
7891 arg_type = Builtin_call_expression::complex_type(context->type);
7892 if (arg_type == NULL)
7893 arg_type = Type::lookup_complex_type("complex128");
7894 is_print = false;
7895 break;
7897 case BUILTIN_COMPLEX:
7899 // For the complex function the type of one operand can
7900 // determine the type of the other, as in a binary expression.
7901 arg_type = Builtin_call_expression::real_imag_type(context->type);
7902 if (arg_type == NULL)
7903 arg_type = Type::lookup_float_type("float64");
7904 if (args != NULL && args->size() == 2)
7906 Type* t1 = args->front()->type();
7907 Type* t2 = args->back()->type();
7908 if (!t1->is_abstract())
7909 arg_type = t1;
7910 else if (!t2->is_abstract())
7911 arg_type = t2;
7913 is_print = false;
7915 break;
7917 default:
7918 is_print = false;
7919 break;
7922 if (args != NULL)
7924 for (Expression_list::const_iterator pa = args->begin();
7925 pa != args->end();
7926 ++pa)
7928 Type_context subcontext;
7929 subcontext.type = arg_type;
7931 if (is_print)
7933 // We want to print large constants, we so can't just
7934 // use the appropriate nonabstract type. Use uint64 for
7935 // an integer if we know it is nonnegative, otherwise
7936 // use int64 for a integer, otherwise use float64 for a
7937 // float or complex128 for a complex.
7938 Type* want_type = NULL;
7939 Type* atype = (*pa)->type();
7940 if (atype->is_abstract())
7942 if (atype->integer_type() != NULL)
7944 Numeric_constant nc;
7945 if (this->numeric_constant_value(&nc))
7947 mpz_t val;
7948 if (nc.to_int(&val))
7950 if (mpz_sgn(val) >= 0)
7951 want_type = Type::lookup_integer_type("uint64");
7952 mpz_clear(val);
7955 if (want_type == NULL)
7956 want_type = Type::lookup_integer_type("int64");
7958 else if (atype->float_type() != NULL)
7959 want_type = Type::lookup_float_type("float64");
7960 else if (atype->complex_type() != NULL)
7961 want_type = Type::lookup_complex_type("complex128");
7962 else if (atype->is_abstract_string_type())
7963 want_type = Type::lookup_string_type();
7964 else if (atype->is_abstract_boolean_type())
7965 want_type = Type::lookup_bool_type();
7966 else
7967 go_unreachable();
7968 subcontext.type = want_type;
7972 (*pa)->determine_type(&subcontext);
7977 // If there is exactly one argument, return true. Otherwise give an
7978 // error message and return false.
7980 bool
7981 Builtin_call_expression::check_one_arg()
7983 const Expression_list* args = this->args();
7984 if (args == NULL || args->size() < 1)
7986 this->report_error(_("not enough arguments"));
7987 return false;
7989 else if (args->size() > 1)
7991 this->report_error(_("too many arguments"));
7992 return false;
7994 if (args->front()->is_error_expression()
7995 || args->front()->type()->is_error())
7997 this->set_is_error();
7998 return false;
8000 return true;
8003 // Check argument types for a builtin function.
8005 void
8006 Builtin_call_expression::do_check_types(Gogo*)
8008 if (this->is_error_expression())
8009 return;
8010 switch (this->code_)
8012 case BUILTIN_INVALID:
8013 case BUILTIN_NEW:
8014 case BUILTIN_MAKE:
8015 case BUILTIN_DELETE:
8016 return;
8018 case BUILTIN_LEN:
8019 case BUILTIN_CAP:
8021 // The single argument may be either a string or an array or a
8022 // map or a channel, or a pointer to a closed array.
8023 if (this->check_one_arg())
8025 Type* arg_type = this->one_arg()->type();
8026 if (arg_type->points_to() != NULL
8027 && arg_type->points_to()->array_type() != NULL
8028 && !arg_type->points_to()->is_slice_type())
8029 arg_type = arg_type->points_to();
8030 if (this->code_ == BUILTIN_CAP)
8032 if (!arg_type->is_error()
8033 && arg_type->array_type() == NULL
8034 && arg_type->channel_type() == NULL)
8035 this->report_error(_("argument must be array or slice "
8036 "or channel"));
8038 else
8040 if (!arg_type->is_error()
8041 && !arg_type->is_string_type()
8042 && arg_type->array_type() == NULL
8043 && arg_type->map_type() == NULL
8044 && arg_type->channel_type() == NULL)
8045 this->report_error(_("argument must be string or "
8046 "array or slice or map or channel"));
8050 break;
8052 case BUILTIN_PRINT:
8053 case BUILTIN_PRINTLN:
8055 const Expression_list* args = this->args();
8056 if (args == NULL)
8058 if (this->code_ == BUILTIN_PRINT)
8059 warning_at(this->location(), 0,
8060 "no arguments for builtin function %<%s%>",
8061 (this->code_ == BUILTIN_PRINT
8062 ? "print"
8063 : "println"));
8065 else
8067 for (Expression_list::const_iterator p = args->begin();
8068 p != args->end();
8069 ++p)
8071 Type* type = (*p)->type();
8072 if (type->is_error()
8073 || type->is_string_type()
8074 || type->integer_type() != NULL
8075 || type->float_type() != NULL
8076 || type->complex_type() != NULL
8077 || type->is_boolean_type()
8078 || type->points_to() != NULL
8079 || type->interface_type() != NULL
8080 || type->channel_type() != NULL
8081 || type->map_type() != NULL
8082 || type->function_type() != NULL
8083 || type->is_slice_type())
8085 else if ((*p)->is_type_expression())
8087 // If this is a type expression it's going to give
8088 // an error anyhow, so we don't need one here.
8090 else
8091 this->report_error(_("unsupported argument type to "
8092 "builtin function"));
8096 break;
8098 case BUILTIN_CLOSE:
8099 if (this->check_one_arg())
8101 if (this->one_arg()->type()->channel_type() == NULL)
8102 this->report_error(_("argument must be channel"));
8103 else if (!this->one_arg()->type()->channel_type()->may_send())
8104 this->report_error(_("cannot close receive-only channel"));
8106 break;
8108 case BUILTIN_PANIC:
8109 case BUILTIN_SIZEOF:
8110 case BUILTIN_ALIGNOF:
8111 this->check_one_arg();
8112 break;
8114 case BUILTIN_RECOVER:
8115 if (this->args() != NULL && !this->args()->empty())
8116 this->report_error(_("too many arguments"));
8117 break;
8119 case BUILTIN_OFFSETOF:
8120 if (this->check_one_arg())
8122 Expression* arg = this->one_arg();
8123 if (arg->field_reference_expression() == NULL)
8124 this->report_error(_("argument must be a field reference"));
8126 break;
8128 case BUILTIN_COPY:
8130 const Expression_list* args = this->args();
8131 if (args == NULL || args->size() < 2)
8133 this->report_error(_("not enough arguments"));
8134 break;
8136 else if (args->size() > 2)
8138 this->report_error(_("too many arguments"));
8139 break;
8141 Type* arg1_type = args->front()->type();
8142 Type* arg2_type = args->back()->type();
8143 if (arg1_type->is_error() || arg2_type->is_error())
8144 break;
8146 Type* e1;
8147 if (arg1_type->is_slice_type())
8148 e1 = arg1_type->array_type()->element_type();
8149 else
8151 this->report_error(_("left argument must be a slice"));
8152 break;
8155 if (arg2_type->is_slice_type())
8157 Type* e2 = arg2_type->array_type()->element_type();
8158 if (!Type::are_identical(e1, e2, true, NULL))
8159 this->report_error(_("element types must be the same"));
8161 else if (arg2_type->is_string_type())
8163 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
8164 this->report_error(_("first argument must be []byte"));
8166 else
8167 this->report_error(_("second argument must be slice or string"));
8169 break;
8171 case BUILTIN_APPEND:
8173 const Expression_list* args = this->args();
8174 if (args == NULL || args->size() < 2)
8176 this->report_error(_("not enough arguments"));
8177 break;
8179 if (args->size() > 2)
8181 this->report_error(_("too many arguments"));
8182 break;
8184 if (args->front()->type()->is_error()
8185 || args->back()->type()->is_error())
8186 break;
8188 Array_type* at = args->front()->type()->array_type();
8189 Type* e = at->element_type();
8191 // The language permits appending a string to a []byte, as a
8192 // special case.
8193 if (args->back()->type()->is_string_type())
8195 if (e->integer_type() != NULL && e->integer_type()->is_byte())
8196 break;
8199 // The language says that the second argument must be
8200 // assignable to a slice of the element type of the first
8201 // argument. We already know the first argument is a slice
8202 // type.
8203 Type* arg2_type = Type::make_array_type(e, NULL);
8204 std::string reason;
8205 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
8207 if (reason.empty())
8208 this->report_error(_("argument 2 has invalid type"));
8209 else
8211 error_at(this->location(), "argument 2 has invalid type (%s)",
8212 reason.c_str());
8213 this->set_is_error();
8216 break;
8219 case BUILTIN_REAL:
8220 case BUILTIN_IMAG:
8221 if (this->check_one_arg())
8223 if (this->one_arg()->type()->complex_type() == NULL)
8224 this->report_error(_("argument must have complex type"));
8226 break;
8228 case BUILTIN_COMPLEX:
8230 const Expression_list* args = this->args();
8231 if (args == NULL || args->size() < 2)
8232 this->report_error(_("not enough arguments"));
8233 else if (args->size() > 2)
8234 this->report_error(_("too many arguments"));
8235 else if (args->front()->is_error_expression()
8236 || args->front()->type()->is_error()
8237 || args->back()->is_error_expression()
8238 || args->back()->type()->is_error())
8239 this->set_is_error();
8240 else if (!Type::are_identical(args->front()->type(),
8241 args->back()->type(), true, NULL))
8242 this->report_error(_("complex arguments must have identical types"));
8243 else if (args->front()->type()->float_type() == NULL)
8244 this->report_error(_("complex arguments must have "
8245 "floating-point type"));
8247 break;
8249 default:
8250 go_unreachable();
8254 // Return the backend representation for a builtin function.
8256 Bexpression*
8257 Builtin_call_expression::do_get_backend(Translate_context* context)
8259 Gogo* gogo = context->gogo();
8260 Location location = this->location();
8261 switch (this->code_)
8263 case BUILTIN_INVALID:
8264 case BUILTIN_NEW:
8265 case BUILTIN_MAKE:
8266 go_unreachable();
8268 case BUILTIN_LEN:
8269 case BUILTIN_CAP:
8271 const Expression_list* args = this->args();
8272 go_assert(args != NULL && args->size() == 1);
8273 Expression* arg = args->front();
8274 Type* arg_type = arg->type();
8276 if (this->seen_)
8278 go_assert(saw_errors());
8279 return context->backend()->error_expression();
8281 this->seen_ = true;
8282 this->seen_ = false;
8283 if (arg_type->points_to() != NULL)
8285 arg_type = arg_type->points_to();
8286 go_assert(arg_type->array_type() != NULL
8287 && !arg_type->is_slice_type());
8288 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8291 Type* int_type = Type::lookup_integer_type("int");
8292 Expression* val;
8293 if (this->code_ == BUILTIN_LEN)
8295 if (arg_type->is_string_type())
8296 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8297 location);
8298 else if (arg_type->array_type() != NULL)
8300 if (this->seen_)
8302 go_assert(saw_errors());
8303 return context->backend()->error_expression();
8305 this->seen_ = true;
8306 val = arg_type->array_type()->get_length(gogo, arg);
8307 this->seen_ = false;
8309 else if (arg_type->map_type() != NULL)
8310 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8311 else if (arg_type->channel_type() != NULL)
8312 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8313 else
8314 go_unreachable();
8316 else
8318 if (arg_type->array_type() != NULL)
8320 if (this->seen_)
8322 go_assert(saw_errors());
8323 return context->backend()->error_expression();
8325 this->seen_ = true;
8326 val = arg_type->array_type()->get_capacity(gogo, arg);
8327 this->seen_ = false;
8329 else if (arg_type->channel_type() != NULL)
8330 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8331 else
8332 go_unreachable();
8335 return Expression::make_cast(int_type, val,
8336 location)->get_backend(context);
8339 case BUILTIN_PRINT:
8340 case BUILTIN_PRINTLN:
8342 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8343 Expression* print_stmts = NULL;
8345 const Expression_list* call_args = this->args();
8346 if (call_args != NULL)
8348 for (Expression_list::const_iterator p = call_args->begin();
8349 p != call_args->end();
8350 ++p)
8352 if (is_ln && p != call_args->begin())
8354 Expression* print_space =
8355 Runtime::make_call(Runtime::PRINT_SPACE,
8356 this->location(), 0);
8358 print_stmts =
8359 Expression::make_compound(print_stmts, print_space,
8360 location);
8363 Expression* arg = *p;
8364 Type* type = arg->type();
8365 Runtime::Function code;
8366 if (type->is_string_type())
8367 code = Runtime::PRINT_STRING;
8368 else if (type->integer_type() != NULL
8369 && type->integer_type()->is_unsigned())
8371 Type* itype = Type::lookup_integer_type("uint64");
8372 arg = Expression::make_cast(itype, arg, location);
8373 code = Runtime::PRINT_UINT64;
8375 else if (type->integer_type() != NULL)
8377 Type* itype = Type::lookup_integer_type("int64");
8378 arg = Expression::make_cast(itype, arg, location);
8379 code = Runtime::PRINT_INT64;
8381 else if (type->float_type() != NULL)
8383 Type* dtype = Type::lookup_float_type("float64");
8384 arg = Expression::make_cast(dtype, arg, location);
8385 code = Runtime::PRINT_DOUBLE;
8387 else if (type->complex_type() != NULL)
8389 Type* ctype = Type::lookup_complex_type("complex128");
8390 arg = Expression::make_cast(ctype, arg, location);
8391 code = Runtime::PRINT_COMPLEX;
8393 else if (type->is_boolean_type())
8394 code = Runtime::PRINT_BOOL;
8395 else if (type->points_to() != NULL
8396 || type->channel_type() != NULL
8397 || type->map_type() != NULL
8398 || type->function_type() != NULL)
8400 arg = Expression::make_cast(type, arg, location);
8401 code = Runtime::PRINT_POINTER;
8403 else if (type->interface_type() != NULL)
8405 if (type->interface_type()->is_empty())
8406 code = Runtime::PRINT_EMPTY_INTERFACE;
8407 else
8408 code = Runtime::PRINT_INTERFACE;
8410 else if (type->is_slice_type())
8411 code = Runtime::PRINT_SLICE;
8412 else
8414 go_assert(saw_errors());
8415 return context->backend()->error_expression();
8418 Expression* call = Runtime::make_call(code, location, 1, arg);
8419 if (print_stmts == NULL)
8420 print_stmts = call;
8421 else
8422 print_stmts = Expression::make_compound(print_stmts, call,
8423 location);
8427 if (is_ln)
8429 Expression* print_nl =
8430 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8431 if (print_stmts == NULL)
8432 print_stmts = print_nl;
8433 else
8434 print_stmts = Expression::make_compound(print_stmts, print_nl,
8435 location);
8438 return print_stmts->get_backend(context);
8441 case BUILTIN_PANIC:
8443 const Expression_list* args = this->args();
8444 go_assert(args != NULL && args->size() == 1);
8445 Expression* arg = args->front();
8446 Type *empty =
8447 Type::make_empty_interface_type(Linemap::predeclared_location());
8448 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8450 Expression* panic =
8451 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8452 return panic->get_backend(context);
8455 case BUILTIN_RECOVER:
8457 // The argument is set when building recover thunks. It's a
8458 // boolean value which is true if we can recover a value now.
8459 const Expression_list* args = this->args();
8460 go_assert(args != NULL && args->size() == 1);
8461 Expression* arg = args->front();
8462 Type *empty =
8463 Type::make_empty_interface_type(Linemap::predeclared_location());
8465 Expression* nil = Expression::make_nil(location);
8466 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8468 // We need to handle a deferred call to recover specially,
8469 // because it changes whether it can recover a panic or not.
8470 // See test7 in test/recover1.go.
8471 Expression* recover = Runtime::make_call((this->is_deferred()
8472 ? Runtime::DEFERRED_RECOVER
8473 : Runtime::RECOVER),
8474 location, 0);
8475 Expression* cond =
8476 Expression::make_conditional(arg, recover, nil, location);
8477 return cond->get_backend(context);
8480 case BUILTIN_CLOSE:
8482 const Expression_list* args = this->args();
8483 go_assert(args != NULL && args->size() == 1);
8484 Expression* arg = args->front();
8485 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8486 1, arg);
8487 return close->get_backend(context);
8490 case BUILTIN_SIZEOF:
8491 case BUILTIN_OFFSETOF:
8492 case BUILTIN_ALIGNOF:
8494 Numeric_constant nc;
8495 unsigned long val;
8496 if (!this->numeric_constant_value(&nc)
8497 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8499 go_assert(saw_errors());
8500 return context->backend()->error_expression();
8502 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8503 mpz_t ival;
8504 nc.get_int(&ival);
8505 Expression* int_cst =
8506 Expression::make_integer(&ival, uintptr_type, location);
8507 mpz_clear(ival);
8508 return int_cst->get_backend(context);
8511 case BUILTIN_COPY:
8513 const Expression_list* args = this->args();
8514 go_assert(args != NULL && args->size() == 2);
8515 Expression* arg1 = args->front();
8516 Expression* arg2 = args->back();
8518 Type* arg1_type = arg1->type();
8519 Array_type* at = arg1_type->array_type();
8520 go_assert(arg1->is_variable());
8521 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8522 Expression* arg1_len = at->get_length(gogo, arg1);
8524 Type* arg2_type = arg2->type();
8525 go_assert(arg2->is_variable());
8526 Expression* arg2_val;
8527 Expression* arg2_len;
8528 if (arg2_type->is_slice_type())
8530 at = arg2_type->array_type();
8531 arg2_val = at->get_value_pointer(gogo, arg2);
8532 arg2_len = at->get_length(gogo, arg2);
8534 else
8536 go_assert(arg2->is_variable());
8537 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8538 location);
8539 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8540 location);
8542 Expression* cond =
8543 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8544 Expression* length =
8545 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8547 Type* element_type = at->element_type();
8548 Btype* element_btype = element_type->get_backend(gogo);
8550 mpz_t size;
8551 size_t element_size = gogo->backend()->type_size(element_btype);
8552 mpz_init_set_ui(size, element_size);
8553 Expression* size_expr = Expression::make_integer(&size, length->type(), location);
8554 mpz_clear(size);
8556 Expression* bytecount =
8557 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8558 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8559 arg1_val, arg2_val, bytecount);
8561 Expression* compound = Expression::make_compound(copy, length, location);
8562 return compound->get_backend(context);
8565 case BUILTIN_APPEND:
8567 const Expression_list* args = this->args();
8568 go_assert(args != NULL && args->size() == 2);
8569 Expression* arg1 = args->front();
8570 Expression* arg2 = args->back();
8572 Array_type* at = arg1->type()->array_type();
8573 Type* element_type = at->element_type()->forwarded();
8575 go_assert(arg2->is_variable());
8576 Expression* arg2_val;
8577 Expression* arg2_len;
8578 mpz_t size;
8579 if (arg2->type()->is_string_type()
8580 && element_type->integer_type() != NULL
8581 && element_type->integer_type()->is_byte())
8583 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8584 location);
8585 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8586 location);
8587 mpz_init_set_ui(size, 1UL);
8589 else
8591 arg2_val = at->get_value_pointer(gogo, arg2);
8592 arg2_len = at->get_length(gogo, arg2);
8593 Btype* element_btype = element_type->get_backend(gogo);
8594 size_t element_size = gogo->backend()->type_size(element_btype);
8595 mpz_init_set_ui(size, element_size);
8597 Expression* element_size =
8598 Expression::make_integer(&size, NULL, location);
8599 mpz_clear(size);
8601 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8602 arg1, arg2_val, arg2_len,
8603 element_size);
8604 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8605 return append->get_backend(context);
8608 case BUILTIN_REAL:
8609 case BUILTIN_IMAG:
8611 const Expression_list* args = this->args();
8612 go_assert(args != NULL && args->size() == 1);
8614 Bexpression* ret;
8615 Bexpression* bcomplex = args->front()->get_backend(context);
8616 if (this->code_ == BUILTIN_REAL)
8617 ret = gogo->backend()->real_part_expression(bcomplex, location);
8618 else
8619 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8620 return ret;
8623 case BUILTIN_COMPLEX:
8625 const Expression_list* args = this->args();
8626 go_assert(args != NULL && args->size() == 2);
8627 Bexpression* breal = args->front()->get_backend(context);
8628 Bexpression* bimag = args->back()->get_backend(context);
8629 return gogo->backend()->complex_expression(breal, bimag, location);
8632 default:
8633 go_unreachable();
8637 // We have to support exporting a builtin call expression, because
8638 // code can set a constant to the result of a builtin expression.
8640 void
8641 Builtin_call_expression::do_export(Export* exp) const
8643 Numeric_constant nc;
8644 if (!this->numeric_constant_value(&nc))
8646 error_at(this->location(), "value is not constant");
8647 return;
8650 if (nc.is_int())
8652 mpz_t val;
8653 nc.get_int(&val);
8654 Integer_expression::export_integer(exp, val);
8655 mpz_clear(val);
8657 else if (nc.is_float())
8659 mpfr_t fval;
8660 nc.get_float(&fval);
8661 Float_expression::export_float(exp, fval);
8662 mpfr_clear(fval);
8664 else if (nc.is_complex())
8666 mpfr_t real;
8667 mpfr_t imag;
8668 Complex_expression::export_complex(exp, real, imag);
8669 mpfr_clear(real);
8670 mpfr_clear(imag);
8672 else
8673 go_unreachable();
8675 // A trailing space lets us reliably identify the end of the number.
8676 exp->write_c_string(" ");
8679 // Class Call_expression.
8681 // A Go function can be viewed in a couple of different ways. The
8682 // code of a Go function becomes a backend function with parameters
8683 // whose types are simply the backend representation of the Go types.
8684 // If there are multiple results, they are returned as a backend
8685 // struct.
8687 // However, when Go code refers to a function other than simply
8688 // calling it, the backend type of that function is actually a struct.
8689 // The first field of the struct points to the Go function code
8690 // (sometimes a wrapper as described below). The remaining fields
8691 // hold addresses of closed-over variables. This struct is called a
8692 // closure.
8694 // There are a few cases to consider.
8696 // A direct function call of a known function in package scope. In
8697 // this case there are no closed-over variables, and we know the name
8698 // of the function code. We can simply produce a backend call to the
8699 // function directly, and not worry about the closure.
8701 // A direct function call of a known function literal. In this case
8702 // we know the function code and we know the closure. We generate the
8703 // function code such that it expects an additional final argument of
8704 // the closure type. We pass the closure as the last argument, after
8705 // the other arguments.
8707 // An indirect function call. In this case we have a closure. We
8708 // load the pointer to the function code from the first field of the
8709 // closure. We pass the address of the closure as the last argument.
8711 // A call to a method of an interface. Type methods are always at
8712 // package scope, so we call the function directly, and don't worry
8713 // about the closure.
8715 // This means that for a function at package scope we have two cases.
8716 // One is the direct call, which has no closure. The other is the
8717 // indirect call, which does have a closure. We can't simply ignore
8718 // the closure, even though it is the last argument, because that will
8719 // fail on targets where the function pops its arguments. So when
8720 // generating a closure for a package-scope function we set the
8721 // function code pointer in the closure to point to a wrapper
8722 // function. This wrapper function accepts a final argument that
8723 // points to the closure, ignores it, and calls the real function as a
8724 // direct function call. This wrapper will normally be efficient, and
8725 // can often simply be a tail call to the real function.
8727 // We don't use GCC's static chain pointer because 1) we don't need
8728 // it; 2) GCC only permits using a static chain to call a known
8729 // function, so we can't use it for an indirect call anyhow. Since we
8730 // can't use it for an indirect call, we may as well not worry about
8731 // using it for a direct call either.
8733 // We pass the closure last rather than first because it means that
8734 // the function wrapper we put into a closure for a package-scope
8735 // function can normally just be a tail call to the real function.
8737 // For method expressions we generate a wrapper that loads the
8738 // receiver from the closure and then calls the method. This
8739 // unfortunately forces reshuffling the arguments, since there is a
8740 // new first argument, but we can't avoid reshuffling either for
8741 // method expressions or for indirect calls of package-scope
8742 // functions, and since the latter are more common we reshuffle for
8743 // method expressions.
8745 // Note that the Go code retains the Go types. The extra final
8746 // argument only appears when we convert to the backend
8747 // representation.
8749 // Traversal.
8752 Call_expression::do_traverse(Traverse* traverse)
8754 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8755 return TRAVERSE_EXIT;
8756 if (this->args_ != NULL)
8758 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8759 return TRAVERSE_EXIT;
8761 return TRAVERSE_CONTINUE;
8764 // Lower a call statement.
8766 Expression*
8767 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8768 Statement_inserter* inserter, int)
8770 Location loc = this->location();
8772 // A type cast can look like a function call.
8773 if (this->fn_->is_type_expression()
8774 && this->args_ != NULL
8775 && this->args_->size() == 1)
8776 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8777 loc);
8779 // Because do_type will return an error type and thus prevent future
8780 // errors, check for that case now to ensure that the error gets
8781 // reported.
8782 Function_type* fntype = this->get_function_type();
8783 if (fntype == NULL)
8785 if (!this->fn_->type()->is_error())
8786 this->report_error(_("expected function"));
8787 return Expression::make_error(loc);
8790 // Handle an argument which is a call to a function which returns
8791 // multiple results.
8792 if (this->args_ != NULL
8793 && this->args_->size() == 1
8794 && this->args_->front()->call_expression() != NULL)
8796 size_t rc = this->args_->front()->call_expression()->result_count();
8797 if (rc > 1
8798 && ((fntype->parameters() != NULL
8799 && (fntype->parameters()->size() == rc
8800 || (fntype->is_varargs()
8801 && fntype->parameters()->size() - 1 <= rc)))
8802 || fntype->is_builtin()))
8804 Call_expression* call = this->args_->front()->call_expression();
8805 Expression_list* args = new Expression_list;
8806 for (size_t i = 0; i < rc; ++i)
8807 args->push_back(Expression::make_call_result(call, i));
8808 // We can't return a new call expression here, because this
8809 // one may be referenced by Call_result expressions. We
8810 // also can't delete the old arguments, because we may still
8811 // traverse them somewhere up the call stack. FIXME.
8812 this->args_ = args;
8816 // Recognize a call to a builtin function.
8817 if (fntype->is_builtin())
8818 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8819 this->is_varargs_, loc);
8821 // If this call returns multiple results, create a temporary
8822 // variable for each result.
8823 size_t rc = this->result_count();
8824 if (rc > 1 && this->results_ == NULL)
8826 std::vector<Temporary_statement*>* temps =
8827 new std::vector<Temporary_statement*>;
8828 temps->reserve(rc);
8829 const Typed_identifier_list* results = fntype->results();
8830 for (Typed_identifier_list::const_iterator p = results->begin();
8831 p != results->end();
8832 ++p)
8834 Temporary_statement* temp = Statement::make_temporary(p->type(),
8835 NULL, loc);
8836 inserter->insert(temp);
8837 temps->push_back(temp);
8839 this->results_ = temps;
8842 // Handle a call to a varargs function by packaging up the extra
8843 // parameters.
8844 if (fntype->is_varargs())
8846 const Typed_identifier_list* parameters = fntype->parameters();
8847 go_assert(parameters != NULL && !parameters->empty());
8848 Type* varargs_type = parameters->back().type();
8849 this->lower_varargs(gogo, function, inserter, varargs_type,
8850 parameters->size());
8853 // If this is call to a method, call the method directly passing the
8854 // object as the first parameter.
8855 Bound_method_expression* bme = this->fn_->bound_method_expression();
8856 if (bme != NULL)
8858 Named_object* methodfn = bme->function();
8859 Expression* first_arg = bme->first_argument();
8861 // We always pass a pointer when calling a method.
8862 if (first_arg->type()->points_to() == NULL
8863 && !first_arg->type()->is_error())
8865 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8866 // We may need to create a temporary variable so that we can
8867 // take the address. We can't do that here because it will
8868 // mess up the order of evaluation.
8869 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8870 ue->set_create_temp();
8873 // If we are calling a method which was inherited from an
8874 // embedded struct, and the method did not get a stub, then the
8875 // first type may be wrong.
8876 Type* fatype = bme->first_argument_type();
8877 if (fatype != NULL)
8879 if (fatype->points_to() == NULL)
8880 fatype = Type::make_pointer_type(fatype);
8881 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8884 Expression_list* new_args = new Expression_list();
8885 new_args->push_back(first_arg);
8886 if (this->args_ != NULL)
8888 for (Expression_list::const_iterator p = this->args_->begin();
8889 p != this->args_->end();
8890 ++p)
8891 new_args->push_back(*p);
8894 // We have to change in place because this structure may be
8895 // referenced by Call_result_expressions. We can't delete the
8896 // old arguments, because we may be traversing them up in some
8897 // caller. FIXME.
8898 this->args_ = new_args;
8899 this->fn_ = Expression::make_func_reference(methodfn, NULL,
8900 bme->location());
8903 return this;
8906 // Lower a call to a varargs function. FUNCTION is the function in
8907 // which the call occurs--it's not the function we are calling.
8908 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8909 // PARAM_COUNT is the number of parameters of the function we are
8910 // calling; the last of these parameters will be the varargs
8911 // parameter.
8913 void
8914 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8915 Statement_inserter* inserter,
8916 Type* varargs_type, size_t param_count)
8918 if (this->varargs_are_lowered_)
8919 return;
8921 Location loc = this->location();
8923 go_assert(param_count > 0);
8924 go_assert(varargs_type->is_slice_type());
8926 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8927 if (arg_count < param_count - 1)
8929 // Not enough arguments; will be caught in check_types.
8930 return;
8933 Expression_list* old_args = this->args_;
8934 Expression_list* new_args = new Expression_list();
8935 bool push_empty_arg = false;
8936 if (old_args == NULL || old_args->empty())
8938 go_assert(param_count == 1);
8939 push_empty_arg = true;
8941 else
8943 Expression_list::const_iterator pa;
8944 int i = 1;
8945 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8947 if (static_cast<size_t>(i) == param_count)
8948 break;
8949 new_args->push_back(*pa);
8952 // We have reached the varargs parameter.
8954 bool issued_error = false;
8955 if (pa == old_args->end())
8956 push_empty_arg = true;
8957 else if (pa + 1 == old_args->end() && this->is_varargs_)
8958 new_args->push_back(*pa);
8959 else if (this->is_varargs_)
8961 if ((*pa)->type()->is_slice_type())
8962 this->report_error(_("too many arguments"));
8963 else
8965 error_at(this->location(),
8966 _("invalid use of %<...%> with non-slice"));
8967 this->set_is_error();
8969 return;
8971 else
8973 Type* element_type = varargs_type->array_type()->element_type();
8974 Expression_list* vals = new Expression_list;
8975 for (; pa != old_args->end(); ++pa, ++i)
8977 // Check types here so that we get a better message.
8978 Type* patype = (*pa)->type();
8979 Location paloc = (*pa)->location();
8980 if (!this->check_argument_type(i, element_type, patype,
8981 paloc, issued_error))
8982 continue;
8983 vals->push_back(*pa);
8985 Expression* val =
8986 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8987 gogo->lower_expression(function, inserter, &val);
8988 new_args->push_back(val);
8992 if (push_empty_arg)
8993 new_args->push_back(Expression::make_nil(loc));
8995 // We can't return a new call expression here, because this one may
8996 // be referenced by Call_result expressions. FIXME. We can't
8997 // delete OLD_ARGS because we may have both a Call_expression and a
8998 // Builtin_call_expression which refer to them. FIXME.
8999 this->args_ = new_args;
9000 this->varargs_are_lowered_ = true;
9003 // Flatten a call with multiple results into a temporary.
9005 Expression*
9006 Call_expression::do_flatten(Gogo*, Named_object*, Statement_inserter* inserter)
9008 size_t rc = this->result_count();
9009 if (rc > 1 && this->call_temp_ == NULL)
9011 Struct_field_list* sfl = new Struct_field_list();
9012 Function_type* fntype = this->get_function_type();
9013 const Typed_identifier_list* results = fntype->results();
9014 Location loc = this->location();
9016 int i = 0;
9017 char buf[10];
9018 for (Typed_identifier_list::const_iterator p = results->begin();
9019 p != results->end();
9020 ++p, ++i)
9022 snprintf(buf, sizeof buf, "res%d", i);
9023 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9026 Struct_type* st = Type::make_struct_type(sfl, loc);
9027 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9028 inserter->insert(this->call_temp_);
9031 return this;
9034 // Get the function type. This can return NULL in error cases.
9036 Function_type*
9037 Call_expression::get_function_type() const
9039 return this->fn_->type()->function_type();
9042 // Return the number of values which this call will return.
9044 size_t
9045 Call_expression::result_count() const
9047 const Function_type* fntype = this->get_function_type();
9048 if (fntype == NULL)
9049 return 0;
9050 if (fntype->results() == NULL)
9051 return 0;
9052 return fntype->results()->size();
9055 // Return the temporary which holds a result.
9057 Temporary_statement*
9058 Call_expression::result(size_t i) const
9060 if (this->results_ == NULL || this->results_->size() <= i)
9062 go_assert(saw_errors());
9063 return NULL;
9065 return (*this->results_)[i];
9068 // Return whether this is a call to the predeclared function recover.
9070 bool
9071 Call_expression::is_recover_call() const
9073 return this->do_is_recover_call();
9076 // Set the argument to the recover function.
9078 void
9079 Call_expression::set_recover_arg(Expression* arg)
9081 this->do_set_recover_arg(arg);
9084 // Virtual functions also implemented by Builtin_call_expression.
9086 bool
9087 Call_expression::do_is_recover_call() const
9089 return false;
9092 void
9093 Call_expression::do_set_recover_arg(Expression*)
9095 go_unreachable();
9098 // We have found an error with this call expression; return true if
9099 // we should report it.
9101 bool
9102 Call_expression::issue_error()
9104 if (this->issued_error_)
9105 return false;
9106 else
9108 this->issued_error_ = true;
9109 return true;
9113 // Get the type.
9115 Type*
9116 Call_expression::do_type()
9118 if (this->type_ != NULL)
9119 return this->type_;
9121 Type* ret;
9122 Function_type* fntype = this->get_function_type();
9123 if (fntype == NULL)
9124 return Type::make_error_type();
9126 const Typed_identifier_list* results = fntype->results();
9127 if (results == NULL)
9128 ret = Type::make_void_type();
9129 else if (results->size() == 1)
9130 ret = results->begin()->type();
9131 else
9132 ret = Type::make_call_multiple_result_type(this);
9134 this->type_ = ret;
9136 return this->type_;
9139 // Determine types for a call expression. We can use the function
9140 // parameter types to set the types of the arguments.
9142 void
9143 Call_expression::do_determine_type(const Type_context*)
9145 if (!this->determining_types())
9146 return;
9148 this->fn_->determine_type_no_context();
9149 Function_type* fntype = this->get_function_type();
9150 const Typed_identifier_list* parameters = NULL;
9151 if (fntype != NULL)
9152 parameters = fntype->parameters();
9153 if (this->args_ != NULL)
9155 Typed_identifier_list::const_iterator pt;
9156 if (parameters != NULL)
9157 pt = parameters->begin();
9158 bool first = true;
9159 for (Expression_list::const_iterator pa = this->args_->begin();
9160 pa != this->args_->end();
9161 ++pa)
9163 if (first)
9165 first = false;
9166 // If this is a method, the first argument is the
9167 // receiver.
9168 if (fntype != NULL && fntype->is_method())
9170 Type* rtype = fntype->receiver()->type();
9171 // The receiver is always passed as a pointer.
9172 if (rtype->points_to() == NULL)
9173 rtype = Type::make_pointer_type(rtype);
9174 Type_context subcontext(rtype, false);
9175 (*pa)->determine_type(&subcontext);
9176 continue;
9180 if (parameters != NULL && pt != parameters->end())
9182 Type_context subcontext(pt->type(), false);
9183 (*pa)->determine_type(&subcontext);
9184 ++pt;
9186 else
9187 (*pa)->determine_type_no_context();
9192 // Called when determining types for a Call_expression. Return true
9193 // if we should go ahead, false if they have already been determined.
9195 bool
9196 Call_expression::determining_types()
9198 if (this->types_are_determined_)
9199 return false;
9200 else
9202 this->types_are_determined_ = true;
9203 return true;
9207 // Check types for parameter I.
9209 bool
9210 Call_expression::check_argument_type(int i, const Type* parameter_type,
9211 const Type* argument_type,
9212 Location argument_location,
9213 bool issued_error)
9215 std::string reason;
9216 bool ok;
9217 if (this->are_hidden_fields_ok_)
9218 ok = Type::are_assignable_hidden_ok(parameter_type, argument_type,
9219 &reason);
9220 else
9221 ok = Type::are_assignable(parameter_type, argument_type, &reason);
9222 if (!ok)
9224 if (!issued_error)
9226 if (reason.empty())
9227 error_at(argument_location, "argument %d has incompatible type", i);
9228 else
9229 error_at(argument_location,
9230 "argument %d has incompatible type (%s)",
9231 i, reason.c_str());
9233 this->set_is_error();
9234 return false;
9236 return true;
9239 // Check types.
9241 void
9242 Call_expression::do_check_types(Gogo*)
9244 if (this->classification() == EXPRESSION_ERROR)
9245 return;
9247 Function_type* fntype = this->get_function_type();
9248 if (fntype == NULL)
9250 if (!this->fn_->type()->is_error())
9251 this->report_error(_("expected function"));
9252 return;
9255 bool is_method = fntype->is_method();
9256 if (is_method)
9258 go_assert(this->args_ != NULL && !this->args_->empty());
9259 Type* rtype = fntype->receiver()->type();
9260 Expression* first_arg = this->args_->front();
9261 // The language permits copying hidden fields for a method
9262 // receiver. We dereference the values since receivers are
9263 // always passed as pointers.
9264 std::string reason;
9265 if (!Type::are_assignable_hidden_ok(rtype->deref(),
9266 first_arg->type()->deref(),
9267 &reason))
9269 if (reason.empty())
9270 this->report_error(_("incompatible type for receiver"));
9271 else
9273 error_at(this->location(),
9274 "incompatible type for receiver (%s)",
9275 reason.c_str());
9276 this->set_is_error();
9281 // Note that varargs was handled by the lower_varargs() method, so
9282 // we don't have to worry about it here unless something is wrong.
9283 if (this->is_varargs_ && !this->varargs_are_lowered_)
9285 if (!fntype->is_varargs())
9287 error_at(this->location(),
9288 _("invalid use of %<...%> calling non-variadic function"));
9289 this->set_is_error();
9290 return;
9294 const Typed_identifier_list* parameters = fntype->parameters();
9295 if (this->args_ == NULL)
9297 if (parameters != NULL && !parameters->empty())
9298 this->report_error(_("not enough arguments"));
9300 else if (parameters == NULL)
9302 if (!is_method || this->args_->size() > 1)
9303 this->report_error(_("too many arguments"));
9305 else
9307 int i = 0;
9308 Expression_list::const_iterator pa = this->args_->begin();
9309 if (is_method)
9310 ++pa;
9311 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9312 pt != parameters->end();
9313 ++pt, ++pa, ++i)
9315 if (pa == this->args_->end())
9317 this->report_error(_("not enough arguments"));
9318 return;
9320 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9321 (*pa)->location(), false);
9323 if (pa != this->args_->end())
9324 this->report_error(_("too many arguments"));
9328 // Return whether we have to use a temporary variable to ensure that
9329 // we evaluate this call expression in order. If the call returns no
9330 // results then it will inevitably be executed last.
9332 bool
9333 Call_expression::do_must_eval_in_order() const
9335 return this->result_count() > 0;
9338 // Get the function and the first argument to use when calling an
9339 // interface method.
9341 Expression*
9342 Call_expression::interface_method_function(
9343 Interface_field_reference_expression* interface_method,
9344 Expression** first_arg_ptr)
9346 *first_arg_ptr = interface_method->get_underlying_object();
9347 return interface_method->get_function();
9350 // Build the call expression.
9352 Bexpression*
9353 Call_expression::do_get_backend(Translate_context* context)
9355 if (this->call_ != NULL)
9356 return this->call_;
9358 Function_type* fntype = this->get_function_type();
9359 if (fntype == NULL)
9360 return context->backend()->error_expression();
9362 if (this->fn_->is_error_expression())
9363 return context->backend()->error_expression();
9365 Gogo* gogo = context->gogo();
9366 Location location = this->location();
9368 Func_expression* func = this->fn_->func_expression();
9369 Interface_field_reference_expression* interface_method =
9370 this->fn_->interface_field_reference_expression();
9371 const bool has_closure = func != NULL && func->closure() != NULL;
9372 const bool is_interface_method = interface_method != NULL;
9374 bool has_closure_arg;
9375 if (has_closure)
9376 has_closure_arg = true;
9377 else if (func != NULL)
9378 has_closure_arg = false;
9379 else if (is_interface_method)
9380 has_closure_arg = false;
9381 else
9382 has_closure_arg = true;
9384 int nargs;
9385 std::vector<Bexpression*> fn_args;
9386 if (this->args_ == NULL || this->args_->empty())
9388 nargs = is_interface_method ? 1 : 0;
9389 if (nargs > 0)
9390 fn_args.resize(1);
9392 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9394 // Passing a receiver parameter.
9395 go_assert(!is_interface_method
9396 && fntype->is_method()
9397 && this->args_->size() == 1);
9398 nargs = 1;
9399 fn_args.resize(1);
9400 fn_args[0] = this->args_->front()->get_backend(context);
9402 else
9404 const Typed_identifier_list* params = fntype->parameters();
9406 nargs = this->args_->size();
9407 int i = is_interface_method ? 1 : 0;
9408 nargs += i;
9409 fn_args.resize(nargs);
9411 Typed_identifier_list::const_iterator pp = params->begin();
9412 Expression_list::const_iterator pe = this->args_->begin();
9413 if (!is_interface_method && fntype->is_method())
9415 fn_args[i] = (*pe)->get_backend(context);
9416 ++pe;
9417 ++i;
9419 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9421 go_assert(pp != params->end());
9422 Expression* arg =
9423 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9424 location);
9425 fn_args[i] = arg->get_backend(context);
9427 go_assert(pp == params->end());
9428 go_assert(i == nargs);
9431 Expression* fn;
9432 Expression* closure = NULL;
9433 if (func != NULL)
9435 Named_object* no = func->named_object();
9436 fn = Expression::make_func_code_reference(no, location);
9437 if (has_closure)
9438 closure = func->closure();
9440 else if (!is_interface_method)
9442 closure = this->fn_;
9444 // The backend representation of this function type is a pointer
9445 // to a struct whose first field is the actual function to call.
9446 Type* pfntype =
9447 Type::make_pointer_type(
9448 Type::make_pointer_type(Type::make_void_type()));
9449 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9450 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9452 else
9454 Expression* first_arg;
9455 fn = this->interface_method_function(interface_method, &first_arg);
9456 fn_args[0] = first_arg->get_backend(context);
9459 if (!has_closure_arg)
9460 go_assert(closure == NULL);
9461 else
9463 // Pass the closure argument by calling the function function
9464 // __go_set_closure. In the order_evaluations pass we have
9465 // ensured that if any parameters contain call expressions, they
9466 // will have been moved out to temporary variables.
9467 go_assert(closure != NULL);
9468 Expression* set_closure =
9469 Runtime::make_call(Runtime::SET_CLOSURE, location, 1, closure);
9470 fn = Expression::make_compound(set_closure, fn, location);
9473 Bexpression* bfn = fn->get_backend(context);
9475 // When not calling a named function directly, use a type conversion
9476 // in case the type of the function is a recursive type which refers
9477 // to itself. We don't do this for an interface method because 1)
9478 // an interface method never refers to itself, so we always have a
9479 // function type here; 2) we pass an extra first argument to an
9480 // interface method, so fntype is not correct.
9481 if (func == NULL && !is_interface_method)
9483 Btype* bft = fntype->get_backend_fntype(gogo);
9484 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9487 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args, location);
9489 if (this->results_ != NULL)
9491 go_assert(this->call_temp_ != NULL);
9492 Expression* call_ref =
9493 Expression::make_temporary_reference(this->call_temp_, location);
9494 Bexpression* bcall_ref = call_ref->get_backend(context);
9495 Bstatement* assn_stmt =
9496 gogo->backend()->assignment_statement(bcall_ref, call, location);
9498 this->call_ = this->set_results(context, bcall_ref);
9500 Bexpression* set_and_call =
9501 gogo->backend()->compound_expression(assn_stmt, this->call_,
9502 location);
9503 return set_and_call;
9506 this->call_ = call;
9507 return this->call_;
9510 // Set the result variables if this call returns multiple results.
9512 Bexpression*
9513 Call_expression::set_results(Translate_context* context, Bexpression* call)
9515 Gogo* gogo = context->gogo();
9517 Bexpression* results = NULL;
9518 Location loc = this->location();
9520 size_t rc = this->result_count();
9521 for (size_t i = 0; i < rc; ++i)
9523 Temporary_statement* temp = this->result(i);
9524 if (temp == NULL)
9526 go_assert(saw_errors());
9527 return gogo->backend()->error_expression();
9529 Temporary_reference_expression* ref =
9530 Expression::make_temporary_reference(temp, loc);
9531 ref->set_is_lvalue();
9533 Bexpression* result_ref = ref->get_backend(context);
9534 Bexpression* call_result =
9535 gogo->backend()->struct_field_expression(call, i, loc);
9536 Bstatement* assn_stmt =
9537 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9539 Bexpression* result =
9540 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9542 if (results == NULL)
9543 results = result;
9544 else
9546 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9547 results =
9548 gogo->backend()->compound_expression(expr_stmt, results, loc);
9551 return results;
9554 // Dump ast representation for a call expressin.
9556 void
9557 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9559 this->fn_->dump_expression(ast_dump_context);
9560 ast_dump_context->ostream() << "(";
9561 if (args_ != NULL)
9562 ast_dump_context->dump_expression_list(this->args_);
9564 ast_dump_context->ostream() << ") ";
9567 // Make a call expression.
9569 Call_expression*
9570 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9571 Location location)
9573 return new Call_expression(fn, args, is_varargs, location);
9576 // A single result from a call which returns multiple results.
9578 class Call_result_expression : public Expression
9580 public:
9581 Call_result_expression(Call_expression* call, unsigned int index)
9582 : Expression(EXPRESSION_CALL_RESULT, call->location()),
9583 call_(call), index_(index)
9586 protected:
9588 do_traverse(Traverse*);
9590 Type*
9591 do_type();
9593 void
9594 do_determine_type(const Type_context*);
9596 void
9597 do_check_types(Gogo*);
9599 Expression*
9600 do_copy()
9602 return new Call_result_expression(this->call_->call_expression(),
9603 this->index_);
9606 bool
9607 do_must_eval_in_order() const
9608 { return true; }
9610 Bexpression*
9611 do_get_backend(Translate_context*);
9613 void
9614 do_dump_expression(Ast_dump_context*) const;
9616 private:
9617 // The underlying call expression.
9618 Expression* call_;
9619 // Which result we want.
9620 unsigned int index_;
9623 // Traverse a call result.
9626 Call_result_expression::do_traverse(Traverse* traverse)
9628 if (traverse->remember_expression(this->call_))
9630 // We have already traversed the call expression.
9631 return TRAVERSE_CONTINUE;
9633 return Expression::traverse(&this->call_, traverse);
9636 // Get the type.
9638 Type*
9639 Call_result_expression::do_type()
9641 if (this->classification() == EXPRESSION_ERROR)
9642 return Type::make_error_type();
9644 // THIS->CALL_ can be replaced with a temporary reference due to
9645 // Call_expression::do_must_eval_in_order when there is an error.
9646 Call_expression* ce = this->call_->call_expression();
9647 if (ce == NULL)
9649 this->set_is_error();
9650 return Type::make_error_type();
9652 Function_type* fntype = ce->get_function_type();
9653 if (fntype == NULL)
9655 if (ce->issue_error())
9657 if (!ce->fn()->type()->is_error())
9658 this->report_error(_("expected function"));
9660 this->set_is_error();
9661 return Type::make_error_type();
9663 const Typed_identifier_list* results = fntype->results();
9664 if (results == NULL || results->size() < 2)
9666 if (ce->issue_error())
9667 this->report_error(_("number of results does not match "
9668 "number of values"));
9669 return Type::make_error_type();
9671 Typed_identifier_list::const_iterator pr = results->begin();
9672 for (unsigned int i = 0; i < this->index_; ++i)
9674 if (pr == results->end())
9675 break;
9676 ++pr;
9678 if (pr == results->end())
9680 if (ce->issue_error())
9681 this->report_error(_("number of results does not match "
9682 "number of values"));
9683 return Type::make_error_type();
9685 return pr->type();
9688 // Check the type. Just make sure that we trigger the warning in
9689 // do_type.
9691 void
9692 Call_result_expression::do_check_types(Gogo*)
9694 this->type();
9697 // Determine the type. We have nothing to do here, but the 0 result
9698 // needs to pass down to the caller.
9700 void
9701 Call_result_expression::do_determine_type(const Type_context*)
9703 this->call_->determine_type_no_context();
9706 // Return the backend representation. We just refer to the temporary set by the
9707 // call expression. We don't do this at lowering time because it makes it
9708 // hard to evaluate the call at the right time.
9710 Bexpression*
9711 Call_result_expression::do_get_backend(Translate_context* context)
9713 Call_expression* ce = this->call_->call_expression();
9714 if (ce == NULL)
9716 go_assert(this->call_->is_error_expression());
9717 return context->backend()->error_expression();
9719 Temporary_statement* ts = ce->result(this->index_);
9720 if (ts == NULL)
9722 go_assert(saw_errors());
9723 return context->backend()->error_expression();
9725 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9726 return ref->get_backend(context);
9729 // Dump ast representation for a call result expression.
9731 void
9732 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9733 const
9735 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9736 // (struct) and the fields are referenced instead.
9737 ast_dump_context->ostream() << this->index_ << "@(";
9738 ast_dump_context->dump_expression(this->call_);
9739 ast_dump_context->ostream() << ")";
9742 // Make a reference to a single result of a call which returns
9743 // multiple results.
9745 Expression*
9746 Expression::make_call_result(Call_expression* call, unsigned int index)
9748 return new Call_result_expression(call, index);
9751 // Class Index_expression.
9753 // Traversal.
9756 Index_expression::do_traverse(Traverse* traverse)
9758 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9759 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9760 || (this->end_ != NULL
9761 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9762 || (this->cap_ != NULL
9763 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9764 return TRAVERSE_EXIT;
9765 return TRAVERSE_CONTINUE;
9768 // Lower an index expression. This converts the generic index
9769 // expression into an array index, a string index, or a map index.
9771 Expression*
9772 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9774 Location location = this->location();
9775 Expression* left = this->left_;
9776 Expression* start = this->start_;
9777 Expression* end = this->end_;
9778 Expression* cap = this->cap_;
9780 Type* type = left->type();
9781 if (type->is_error())
9782 return Expression::make_error(location);
9783 else if (left->is_type_expression())
9785 error_at(location, "attempt to index type expression");
9786 return Expression::make_error(location);
9788 else if (type->array_type() != NULL)
9789 return Expression::make_array_index(left, start, end, cap, location);
9790 else if (type->points_to() != NULL
9791 && type->points_to()->array_type() != NULL
9792 && !type->points_to()->is_slice_type())
9794 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9795 location);
9797 // For an ordinary index into the array, the pointer will be
9798 // dereferenced. For a slice it will not--the resulting slice
9799 // will simply reuse the pointer, which is incorrect if that
9800 // pointer is nil.
9801 if (end != NULL || cap != NULL)
9802 deref->issue_nil_check();
9804 return Expression::make_array_index(deref, start, end, cap, location);
9806 else if (type->is_string_type())
9808 if (cap != NULL)
9810 error_at(location, "invalid 3-index slice of string");
9811 return Expression::make_error(location);
9813 return Expression::make_string_index(left, start, end, location);
9815 else if (type->map_type() != NULL)
9817 if (end != NULL || cap != NULL)
9819 error_at(location, "invalid slice of map");
9820 return Expression::make_error(location);
9822 Map_index_expression* ret = Expression::make_map_index(left, start,
9823 location);
9824 if (this->is_lvalue_)
9825 ret->set_is_lvalue();
9826 return ret;
9828 else
9830 error_at(location,
9831 "attempt to index object which is not array, string, or map");
9832 return Expression::make_error(location);
9836 // Write an indexed expression
9837 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9839 void
9840 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9841 const Expression* expr,
9842 const Expression* start,
9843 const Expression* end,
9844 const Expression* cap)
9846 expr->dump_expression(ast_dump_context);
9847 ast_dump_context->ostream() << "[";
9848 start->dump_expression(ast_dump_context);
9849 if (end != NULL)
9851 ast_dump_context->ostream() << ":";
9852 end->dump_expression(ast_dump_context);
9854 if (cap != NULL)
9856 ast_dump_context->ostream() << ":";
9857 cap->dump_expression(ast_dump_context);
9859 ast_dump_context->ostream() << "]";
9862 // Dump ast representation for an index expression.
9864 void
9865 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9866 const
9868 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9869 this->start_, this->end_, this->cap_);
9872 // Make an index expression.
9874 Expression*
9875 Expression::make_index(Expression* left, Expression* start, Expression* end,
9876 Expression* cap, Location location)
9878 return new Index_expression(left, start, end, cap, location);
9881 // An array index. This is used for both indexing and slicing.
9883 class Array_index_expression : public Expression
9885 public:
9886 Array_index_expression(Expression* array, Expression* start,
9887 Expression* end, Expression* cap, Location location)
9888 : Expression(EXPRESSION_ARRAY_INDEX, location),
9889 array_(array), start_(start), end_(end), cap_(cap), type_(NULL)
9892 protected:
9894 do_traverse(Traverse*);
9896 Expression*
9897 do_flatten(Gogo*, Named_object*, Statement_inserter*);
9899 Type*
9900 do_type();
9902 void
9903 do_determine_type(const Type_context*);
9905 void
9906 do_check_types(Gogo*);
9908 Expression*
9909 do_copy()
9911 return Expression::make_array_index(this->array_->copy(),
9912 this->start_->copy(),
9913 (this->end_ == NULL
9914 ? NULL
9915 : this->end_->copy()),
9916 (this->cap_ == NULL
9917 ? NULL
9918 : this->cap_->copy()),
9919 this->location());
9922 bool
9923 do_must_eval_subexpressions_in_order(int* skip) const
9925 *skip = 1;
9926 return true;
9929 bool
9930 do_is_addressable() const;
9932 void
9933 do_address_taken(bool escapes)
9934 { this->array_->address_taken(escapes); }
9936 void
9937 do_issue_nil_check()
9938 { this->array_->issue_nil_check(); }
9940 Bexpression*
9941 do_get_backend(Translate_context*);
9943 void
9944 do_dump_expression(Ast_dump_context*) const;
9946 private:
9947 // The array we are getting a value from.
9948 Expression* array_;
9949 // The start or only index.
9950 Expression* start_;
9951 // The end index of a slice. This may be NULL for a simple array
9952 // index, or it may be a nil expression for the length of the array.
9953 Expression* end_;
9954 // The capacity argument of a slice. This may be NULL for an array index or
9955 // slice.
9956 Expression* cap_;
9957 // The type of the expression.
9958 Type* type_;
9961 // Array index traversal.
9964 Array_index_expression::do_traverse(Traverse* traverse)
9966 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9967 return TRAVERSE_EXIT;
9968 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9969 return TRAVERSE_EXIT;
9970 if (this->end_ != NULL)
9972 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9973 return TRAVERSE_EXIT;
9975 if (this->cap_ != NULL)
9977 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
9978 return TRAVERSE_EXIT;
9980 return TRAVERSE_CONTINUE;
9983 // Return the type of an array index.
9985 Type*
9986 Array_index_expression::do_type()
9988 if (this->type_ == NULL)
9990 Array_type* type = this->array_->type()->array_type();
9991 if (type == NULL)
9992 this->type_ = Type::make_error_type();
9993 else if (this->end_ == NULL)
9994 this->type_ = type->element_type();
9995 else if (type->is_slice_type())
9997 // A slice of a slice has the same type as the original
9998 // slice.
9999 this->type_ = this->array_->type()->deref();
10001 else
10003 // A slice of an array is a slice.
10004 this->type_ = Type::make_array_type(type->element_type(), NULL);
10007 return this->type_;
10010 // Set the type of an array index.
10012 void
10013 Array_index_expression::do_determine_type(const Type_context*)
10015 this->array_->determine_type_no_context();
10016 this->start_->determine_type_no_context();
10017 if (this->end_ != NULL)
10018 this->end_->determine_type_no_context();
10019 if (this->cap_ != NULL)
10020 this->cap_->determine_type_no_context();
10023 // Check types of an array index.
10025 void
10026 Array_index_expression::do_check_types(Gogo*)
10028 Numeric_constant nc;
10029 unsigned long v;
10030 if (this->start_->type()->integer_type() == NULL
10031 && !this->start_->type()->is_error()
10032 && (!this->start_->numeric_constant_value(&nc)
10033 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10034 this->report_error(_("index must be integer"));
10035 if (this->end_ != NULL
10036 && this->end_->type()->integer_type() == NULL
10037 && !this->end_->type()->is_error()
10038 && !this->end_->is_nil_expression()
10039 && !this->end_->is_error_expression()
10040 && (!this->end_->numeric_constant_value(&nc)
10041 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10042 this->report_error(_("slice end must be integer"));
10043 if (this->cap_ != NULL
10044 && this->cap_->type()->integer_type() == NULL
10045 && !this->cap_->type()->is_error()
10046 && !this->cap_->is_nil_expression()
10047 && !this->cap_->is_error_expression()
10048 && (!this->cap_->numeric_constant_value(&nc)
10049 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10050 this->report_error(_("slice capacity must be integer"));
10052 Array_type* array_type = this->array_->type()->array_type();
10053 if (array_type == NULL)
10055 go_assert(this->array_->type()->is_error());
10056 return;
10059 unsigned int int_bits =
10060 Type::lookup_integer_type("int")->integer_type()->bits();
10062 Numeric_constant lvalnc;
10063 mpz_t lval;
10064 bool lval_valid = (array_type->length() != NULL
10065 && array_type->length()->numeric_constant_value(&lvalnc)
10066 && lvalnc.to_int(&lval));
10067 Numeric_constant inc;
10068 mpz_t ival;
10069 bool ival_valid = false;
10070 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10072 ival_valid = true;
10073 if (mpz_sgn(ival) < 0
10074 || mpz_sizeinbase(ival, 2) >= int_bits
10075 || (lval_valid
10076 && (this->end_ == NULL
10077 ? mpz_cmp(ival, lval) >= 0
10078 : mpz_cmp(ival, lval) > 0)))
10080 error_at(this->start_->location(), "array index out of bounds");
10081 this->set_is_error();
10084 if (this->end_ != NULL && !this->end_->is_nil_expression())
10086 Numeric_constant enc;
10087 mpz_t eval;
10088 bool eval_valid = false;
10089 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10091 eval_valid = true;
10092 if (mpz_sgn(eval) < 0
10093 || mpz_sizeinbase(eval, 2) >= int_bits
10094 || (lval_valid && mpz_cmp(eval, lval) > 0))
10096 error_at(this->end_->location(), "array index out of bounds");
10097 this->set_is_error();
10099 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10100 this->report_error(_("inverted slice range"));
10103 Numeric_constant cnc;
10104 mpz_t cval;
10105 if (this->cap_ != NULL
10106 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
10108 if (mpz_sgn(cval) < 0
10109 || mpz_sizeinbase(cval, 2) >= int_bits
10110 || (lval_valid && mpz_cmp(cval, lval) > 0))
10112 error_at(this->cap_->location(), "array index out of bounds");
10113 this->set_is_error();
10115 else if (ival_valid && mpz_cmp(ival, cval) > 0)
10117 error_at(this->cap_->location(),
10118 "invalid slice index: capacity less than start");
10119 this->set_is_error();
10121 else if (eval_valid && mpz_cmp(eval, cval) > 0)
10123 error_at(this->cap_->location(),
10124 "invalid slice index: capacity less than length");
10125 this->set_is_error();
10127 mpz_clear(cval);
10130 if (eval_valid)
10131 mpz_clear(eval);
10133 if (ival_valid)
10134 mpz_clear(ival);
10135 if (lval_valid)
10136 mpz_clear(lval);
10138 // A slice of an array requires an addressable array. A slice of a
10139 // slice is always possible.
10140 if (this->end_ != NULL && !array_type->is_slice_type())
10142 if (!this->array_->is_addressable())
10143 this->report_error(_("slice of unaddressable value"));
10144 else
10145 this->array_->address_taken(true);
10149 // Flatten array indexing by using temporary variables for slices and indexes.
10151 Expression*
10152 Array_index_expression::do_flatten(Gogo*, Named_object*,
10153 Statement_inserter* inserter)
10155 Location loc = this->location();
10156 Temporary_statement* temp;
10157 if (this->array_->type()->is_slice_type() && !this->array_->is_variable())
10159 temp = Statement::make_temporary(NULL, this->array_, loc);
10160 inserter->insert(temp);
10161 this->array_ = Expression::make_temporary_reference(temp, loc);
10163 if (!this->start_->is_variable())
10165 temp = Statement::make_temporary(NULL, this->start_, loc);
10166 inserter->insert(temp);
10167 this->start_ = Expression::make_temporary_reference(temp, loc);
10169 if (this->end_ != NULL
10170 && !this->end_->is_nil_expression()
10171 && !this->end_->is_variable())
10173 temp = Statement::make_temporary(NULL, this->end_, loc);
10174 inserter->insert(temp);
10175 this->end_ = Expression::make_temporary_reference(temp, loc);
10177 if (this->cap_ != NULL && !this->cap_->is_variable())
10179 temp = Statement::make_temporary(NULL, this->cap_, loc);
10180 inserter->insert(temp);
10181 this->cap_ = Expression::make_temporary_reference(temp, loc);
10184 return this;
10187 // Return whether this expression is addressable.
10189 bool
10190 Array_index_expression::do_is_addressable() const
10192 // A slice expression is not addressable.
10193 if (this->end_ != NULL)
10194 return false;
10196 // An index into a slice is addressable.
10197 if (this->array_->type()->is_slice_type())
10198 return true;
10200 // An index into an array is addressable if the array is
10201 // addressable.
10202 return this->array_->is_addressable();
10205 // Get the backend representation for an array index.
10207 Bexpression*
10208 Array_index_expression::do_get_backend(Translate_context* context)
10210 Array_type* array_type = this->array_->type()->array_type();
10211 if (array_type == NULL)
10213 go_assert(this->array_->type()->is_error());
10214 return context->backend()->error_expression();
10216 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
10218 Location loc = this->location();
10219 Gogo* gogo = context->gogo();
10221 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
10223 // We need to convert the length and capacity to the Go "int" type here
10224 // because the length of a fixed-length array could be of type "uintptr"
10225 // and gimple disallows binary operations between "uintptr" and other
10226 // integer types. FIXME.
10227 Bexpression* length = NULL;
10228 if (this->end_ == NULL || this->end_->is_nil_expression())
10230 Expression* len = array_type->get_length(gogo, this->array_);
10231 length = len->get_backend(context);
10232 length = gogo->backend()->convert_expression(int_btype, length, loc);
10235 Bexpression* capacity = NULL;
10236 if (this->end_ != NULL)
10238 Expression* cap = array_type->get_capacity(gogo, this->array_);
10239 capacity = cap->get_backend(context);
10240 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10243 Bexpression* cap_arg = capacity;
10244 if (this->cap_ != NULL)
10246 cap_arg = this->cap_->get_backend(context);
10247 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10250 if (length == NULL)
10251 length = cap_arg;
10253 int code = (array_type->length() != NULL
10254 ? (this->end_ == NULL
10255 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10256 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10257 : (this->end_ == NULL
10258 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10259 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10260 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10262 Bexpression* bad_index =
10263 Expression::check_bounds(this->start_, loc)->get_backend(context);
10265 Bexpression* start = this->start_->get_backend(context);
10266 start = gogo->backend()->convert_expression(int_btype, start, loc);
10267 Bexpression* start_too_large =
10268 gogo->backend()->binary_expression((this->end_ == NULL
10269 ? OPERATOR_GE
10270 : OPERATOR_GT),
10271 start,
10272 (this->end_ == NULL
10273 ? length
10274 : capacity),
10275 loc);
10276 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10277 bad_index, loc);
10279 if (this->end_ == NULL)
10281 // Simple array indexing. This has to return an l-value, so
10282 // wrap the index check into START.
10283 start =
10284 gogo->backend()->conditional_expression(int_btype, bad_index,
10285 crash, start, loc);
10287 Bexpression* ret;
10288 if (array_type->length() != NULL)
10290 Bexpression* array = this->array_->get_backend(context);
10291 ret = gogo->backend()->array_index_expression(array, start, loc);
10293 else
10295 // Slice.
10296 Expression* valptr =
10297 array_type->get_value_pointer(gogo, this->array_);
10298 Bexpression* ptr = valptr->get_backend(context);
10299 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10301 Type* ele_type = this->array_->type()->array_type()->element_type();
10302 Btype* ele_btype = ele_type->get_backend(gogo);
10303 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
10305 return ret;
10308 // Array slice.
10310 if (this->cap_ != NULL)
10312 Bexpression* bounds_bcheck =
10313 Expression::check_bounds(this->cap_, loc)->get_backend(context);
10314 bad_index =
10315 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10316 bad_index, loc);
10317 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10319 Bexpression* cap_too_small =
10320 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10321 Bexpression* cap_too_large =
10322 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10323 Bexpression* bad_cap =
10324 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10325 cap_too_large, loc);
10326 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10327 bad_index, loc);
10330 Bexpression* end;
10331 if (this->end_->is_nil_expression())
10332 end = length;
10333 else
10335 Bexpression* bounds_bcheck =
10336 Expression::check_bounds(this->end_, loc)->get_backend(context);
10338 bad_index =
10339 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10340 bad_index, loc);
10342 end = this->end_->get_backend(context);
10343 end = gogo->backend()->convert_expression(int_btype, end, loc);
10344 Bexpression* end_too_small =
10345 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10346 Bexpression* end_too_large =
10347 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10348 Bexpression* bad_end =
10349 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10350 end_too_large, loc);
10351 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10352 bad_index, loc);
10355 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10356 Bexpression* val = valptr->get_backend(context);
10357 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10359 Bexpression* result_length =
10360 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10362 Bexpression* result_capacity =
10363 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10365 Btype* struct_btype = this->type()->get_backend(gogo);
10366 std::vector<Bexpression*> init;
10367 init.push_back(val);
10368 init.push_back(result_length);
10369 init.push_back(result_capacity);
10371 Bexpression* ctor =
10372 gogo->backend()->constructor_expression(struct_btype, init, loc);
10373 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10374 crash, ctor, loc);
10377 // Dump ast representation for an array index expression.
10379 void
10380 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10381 const
10383 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10384 this->start_, this->end_, this->cap_);
10387 // Make an array index expression. END and CAP may be NULL.
10389 Expression*
10390 Expression::make_array_index(Expression* array, Expression* start,
10391 Expression* end, Expression* cap,
10392 Location location)
10394 return new Array_index_expression(array, start, end, cap, location);
10397 // A string index. This is used for both indexing and slicing.
10399 class String_index_expression : public Expression
10401 public:
10402 String_index_expression(Expression* string, Expression* start,
10403 Expression* end, Location location)
10404 : Expression(EXPRESSION_STRING_INDEX, location),
10405 string_(string), start_(start), end_(end)
10408 protected:
10410 do_traverse(Traverse*);
10412 Expression*
10413 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10415 Type*
10416 do_type();
10418 void
10419 do_determine_type(const Type_context*);
10421 void
10422 do_check_types(Gogo*);
10424 Expression*
10425 do_copy()
10427 return Expression::make_string_index(this->string_->copy(),
10428 this->start_->copy(),
10429 (this->end_ == NULL
10430 ? NULL
10431 : this->end_->copy()),
10432 this->location());
10435 bool
10436 do_must_eval_subexpressions_in_order(int* skip) const
10438 *skip = 1;
10439 return true;
10442 Bexpression*
10443 do_get_backend(Translate_context*);
10445 void
10446 do_dump_expression(Ast_dump_context*) const;
10448 private:
10449 // The string we are getting a value from.
10450 Expression* string_;
10451 // The start or only index.
10452 Expression* start_;
10453 // The end index of a slice. This may be NULL for a single index,
10454 // or it may be a nil expression for the length of the string.
10455 Expression* end_;
10458 // String index traversal.
10461 String_index_expression::do_traverse(Traverse* traverse)
10463 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10464 return TRAVERSE_EXIT;
10465 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10466 return TRAVERSE_EXIT;
10467 if (this->end_ != NULL)
10469 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10470 return TRAVERSE_EXIT;
10472 return TRAVERSE_CONTINUE;
10475 Expression*
10476 String_index_expression::do_flatten(Gogo*, Named_object*,
10477 Statement_inserter* inserter)
10479 Temporary_statement* temp;
10480 Location loc = this->location();
10481 if (!this->string_->is_variable())
10483 temp = Statement::make_temporary(NULL, this->string_, loc);
10484 inserter->insert(temp);
10485 this->string_ = Expression::make_temporary_reference(temp, loc);
10487 if (!this->start_->is_variable())
10489 temp = Statement::make_temporary(NULL, this->start_, loc);
10490 inserter->insert(temp);
10491 this->start_ = Expression::make_temporary_reference(temp, loc);
10493 if (this->end_ != NULL
10494 && !this->end_->is_nil_expression()
10495 && !this->end_->is_variable())
10497 temp = Statement::make_temporary(NULL, this->end_, loc);
10498 inserter->insert(temp);
10499 this->end_ = Expression::make_temporary_reference(temp, loc);
10502 return this;
10505 // Return the type of a string index.
10507 Type*
10508 String_index_expression::do_type()
10510 if (this->end_ == NULL)
10511 return Type::lookup_integer_type("uint8");
10512 else
10513 return this->string_->type();
10516 // Determine the type of a string index.
10518 void
10519 String_index_expression::do_determine_type(const Type_context*)
10521 this->string_->determine_type_no_context();
10522 this->start_->determine_type_no_context();
10523 if (this->end_ != NULL)
10524 this->end_->determine_type_no_context();
10527 // Check types of a string index.
10529 void
10530 String_index_expression::do_check_types(Gogo*)
10532 Numeric_constant nc;
10533 unsigned long v;
10534 if (this->start_->type()->integer_type() == NULL
10535 && !this->start_->type()->is_error()
10536 && (!this->start_->numeric_constant_value(&nc)
10537 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10538 this->report_error(_("index must be integer"));
10539 if (this->end_ != NULL
10540 && this->end_->type()->integer_type() == NULL
10541 && !this->end_->type()->is_error()
10542 && !this->end_->is_nil_expression()
10543 && !this->end_->is_error_expression()
10544 && (!this->end_->numeric_constant_value(&nc)
10545 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10546 this->report_error(_("slice end must be integer"));
10548 std::string sval;
10549 bool sval_valid = this->string_->string_constant_value(&sval);
10551 Numeric_constant inc;
10552 mpz_t ival;
10553 bool ival_valid = false;
10554 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10556 ival_valid = true;
10557 if (mpz_sgn(ival) < 0
10558 || (sval_valid && mpz_cmp_ui(ival, sval.length()) >= 0))
10560 error_at(this->start_->location(), "string index out of bounds");
10561 this->set_is_error();
10564 if (this->end_ != NULL && !this->end_->is_nil_expression())
10566 Numeric_constant enc;
10567 mpz_t eval;
10568 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10570 if (mpz_sgn(eval) < 0
10571 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10573 error_at(this->end_->location(), "string index out of bounds");
10574 this->set_is_error();
10576 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10577 this->report_error(_("inverted slice range"));
10578 mpz_clear(eval);
10581 if (ival_valid)
10582 mpz_clear(ival);
10585 // Get the backend representation for a string index.
10587 Bexpression*
10588 String_index_expression::do_get_backend(Translate_context* context)
10590 Location loc = this->location();
10591 Expression* string_arg = this->string_;
10592 if (this->string_->type()->points_to() != NULL)
10593 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10595 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10597 int code = (this->end_ == NULL
10598 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10599 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10601 Gogo* gogo = context->gogo();
10602 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10604 Type* int_type = Type::lookup_integer_type("int");
10606 // It is possible that an error occurred earlier because the start index
10607 // cannot be represented as an integer type. In this case, we shouldn't
10608 // try casting the starting index into an integer since
10609 // Type_conversion_expression will fail to get the backend representation.
10610 // FIXME.
10611 if (this->start_->type()->integer_type() == NULL
10612 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10614 go_assert(saw_errors());
10615 return context->backend()->error_expression();
10618 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10620 if (this->end_ == NULL)
10622 Expression* length =
10623 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10625 Expression* start_too_large =
10626 Expression::make_binary(OPERATOR_GE, start, length, loc);
10627 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10628 bad_index, loc);
10629 Expression* bytes =
10630 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10632 Bexpression* bstart = start->get_backend(context);
10633 Bexpression* ptr = bytes->get_backend(context);
10634 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10635 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10636 Bexpression* index =
10637 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
10639 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10640 Bexpression* index_error = bad_index->get_backend(context);
10641 return gogo->backend()->conditional_expression(byte_btype, index_error,
10642 crash, index, loc);
10645 Expression* end = NULL;
10646 if (this->end_->is_nil_expression())
10648 mpz_t neg_one;
10649 mpz_init_set_si(neg_one, -1);
10650 end = Expression::make_integer(&neg_one, int_type, loc);
10651 mpz_clear(neg_one);
10653 else
10655 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10656 bad_index =
10657 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10658 end = Expression::make_cast(int_type, this->end_, loc);
10661 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10662 string_arg, start, end);
10663 Bexpression* bstrslice = strslice->get_backend(context);
10665 Btype* str_btype = strslice->type()->get_backend(gogo);
10666 Bexpression* index_error = bad_index->get_backend(context);
10667 return gogo->backend()->conditional_expression(str_btype, index_error,
10668 crash, bstrslice, loc);
10671 // Dump ast representation for a string index expression.
10673 void
10674 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10675 const
10677 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10678 this->start_, this->end_, NULL);
10681 // Make a string index expression. END may be NULL.
10683 Expression*
10684 Expression::make_string_index(Expression* string, Expression* start,
10685 Expression* end, Location location)
10687 return new String_index_expression(string, start, end, location);
10690 // Class Map_index.
10692 // Get the type of the map.
10694 Map_type*
10695 Map_index_expression::get_map_type() const
10697 Map_type* mt = this->map_->type()->deref()->map_type();
10698 if (mt == NULL)
10699 go_assert(saw_errors());
10700 return mt;
10703 // Map index traversal.
10706 Map_index_expression::do_traverse(Traverse* traverse)
10708 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10709 return TRAVERSE_EXIT;
10710 return Expression::traverse(&this->index_, traverse);
10713 // We need to pass in a pointer to the key, so flatten the index into a
10714 // temporary variable if it isn't already. The value pointer will be
10715 // dereferenced and checked for nil, so flatten into a temporary to avoid
10716 // recomputation.
10718 Expression*
10719 Map_index_expression::do_flatten(Gogo*, Named_object*,
10720 Statement_inserter* inserter)
10722 Map_type* mt = this->get_map_type();
10723 if (this->index_->type() != mt->key_type())
10724 this->index_ = Expression::make_cast(mt->key_type(), this->index_,
10725 this->location());
10727 if (!this->index_->is_variable())
10729 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10730 this->location());
10731 inserter->insert(temp);
10732 this->index_ = Expression::make_temporary_reference(temp,
10733 this->location());
10736 if (this->value_pointer_ == NULL)
10737 this->get_value_pointer(this->is_lvalue_);
10738 if (!this->value_pointer_->is_variable())
10740 Temporary_statement* temp =
10741 Statement::make_temporary(NULL, this->value_pointer_,
10742 this->location());
10743 inserter->insert(temp);
10744 this->value_pointer_ =
10745 Expression::make_temporary_reference(temp, this->location());
10748 return this;
10751 // Return the type of a map index.
10753 Type*
10754 Map_index_expression::do_type()
10756 Map_type* mt = this->get_map_type();
10757 if (mt == NULL)
10758 return Type::make_error_type();
10759 Type* type = mt->val_type();
10760 // If this map index is in a tuple assignment, we actually return a
10761 // pointer to the value type. Tuple_map_assignment_statement is
10762 // responsible for handling this correctly. We need to get the type
10763 // right in case this gets assigned to a temporary variable.
10764 if (this->is_in_tuple_assignment_)
10765 type = Type::make_pointer_type(type);
10766 return type;
10769 // Fix the type of a map index.
10771 void
10772 Map_index_expression::do_determine_type(const Type_context*)
10774 this->map_->determine_type_no_context();
10775 Map_type* mt = this->get_map_type();
10776 Type* key_type = mt == NULL ? NULL : mt->key_type();
10777 Type_context subcontext(key_type, false);
10778 this->index_->determine_type(&subcontext);
10781 // Check types of a map index.
10783 void
10784 Map_index_expression::do_check_types(Gogo*)
10786 std::string reason;
10787 Map_type* mt = this->get_map_type();
10788 if (mt == NULL)
10789 return;
10790 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10792 if (reason.empty())
10793 this->report_error(_("incompatible type for map index"));
10794 else
10796 error_at(this->location(), "incompatible type for map index (%s)",
10797 reason.c_str());
10798 this->set_is_error();
10803 // Get the backend representation for a map index.
10805 Bexpression*
10806 Map_index_expression::do_get_backend(Translate_context* context)
10808 Map_type* type = this->get_map_type();
10809 if (type == NULL)
10811 go_assert(saw_errors());
10812 return context->backend()->error_expression();
10815 go_assert(this->value_pointer_ != NULL
10816 && this->value_pointer_->is_variable());
10818 Bexpression* ret;
10819 if (this->is_lvalue_)
10821 Expression* val =
10822 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10823 this->location());
10824 ret = val->get_backend(context);
10826 else if (this->is_in_tuple_assignment_)
10828 // Tuple_map_assignment_statement is responsible for using this
10829 // appropriately.
10830 ret = this->value_pointer_->get_backend(context);
10832 else
10834 Location loc = this->location();
10836 Expression* nil_check =
10837 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10838 Expression::make_nil(loc), loc);
10839 Bexpression* bnil_check = nil_check->get_backend(context);
10840 Expression* val =
10841 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10842 Bexpression* bval = val->get_backend(context);
10844 Gogo* gogo = context->gogo();
10845 Btype* val_btype = type->val_type()->get_backend(gogo);
10846 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10847 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10848 val_zero, bval, loc);
10850 return ret;
10853 // Get an expression for the map index. This returns an expression which
10854 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10855 // not in the map.
10857 Expression*
10858 Map_index_expression::get_value_pointer(bool insert)
10860 if (this->value_pointer_ == NULL)
10862 Map_type* type = this->get_map_type();
10863 if (type == NULL)
10865 go_assert(saw_errors());
10866 return Expression::make_error(this->location());
10869 Location loc = this->location();
10870 Expression* map_ref = this->map_;
10871 if (this->map_->type()->points_to() != NULL)
10872 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10874 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10875 loc);
10876 Expression* map_index =
10877 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10878 map_ref, index_ptr,
10879 Expression::make_boolean(insert, loc));
10881 Type* val_type = type->val_type();
10882 this->value_pointer_ =
10883 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10884 map_index, this->location());
10886 return this->value_pointer_;
10889 // Dump ast representation for a map index expression
10891 void
10892 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10893 const
10895 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10896 this->index_, NULL, NULL);
10899 // Make a map index expression.
10901 Map_index_expression*
10902 Expression::make_map_index(Expression* map, Expression* index,
10903 Location location)
10905 return new Map_index_expression(map, index, location);
10908 // Class Field_reference_expression.
10910 // Lower a field reference expression. There is nothing to lower, but
10911 // this is where we generate the tracking information for fields with
10912 // the magic go:"track" tag.
10914 Expression*
10915 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10916 Statement_inserter* inserter, int)
10918 Struct_type* struct_type = this->expr_->type()->struct_type();
10919 if (struct_type == NULL)
10921 // Error will be reported elsewhere.
10922 return this;
10924 const Struct_field* field = struct_type->field(this->field_index_);
10925 if (field == NULL)
10926 return this;
10927 if (!field->has_tag())
10928 return this;
10929 if (field->tag().find("go:\"track\"") == std::string::npos)
10930 return this;
10932 // We have found a reference to a tracked field. Build a call to
10933 // the runtime function __go_fieldtrack with a string that describes
10934 // the field. FIXME: We should only call this once per referenced
10935 // field per function, not once for each reference to the field.
10937 if (this->called_fieldtrack_)
10938 return this;
10939 this->called_fieldtrack_ = true;
10941 Location loc = this->location();
10943 std::string s = "fieldtrack \"";
10944 Named_type* nt = this->expr_->type()->named_type();
10945 if (nt == NULL || nt->named_object()->package() == NULL)
10946 s.append(gogo->pkgpath());
10947 else
10948 s.append(nt->named_object()->package()->pkgpath());
10949 s.push_back('.');
10950 if (nt != NULL)
10951 s.append(Gogo::unpack_hidden_name(nt->name()));
10952 s.push_back('.');
10953 s.append(field->field_name());
10954 s.push_back('"');
10956 // We can't use a string here, because internally a string holds a
10957 // pointer to the actual bytes; when the linker garbage collects the
10958 // string, it won't garbage collect the bytes. So we use a
10959 // [...]byte.
10961 mpz_t val;
10962 mpz_init_set_ui(val, s.length());
10963 Expression* length_expr = Expression::make_integer(&val, NULL, loc);
10964 mpz_clear(val);
10966 Type* byte_type = gogo->lookup_global("byte")->type_value();
10967 Type* array_type = Type::make_array_type(byte_type, length_expr);
10969 Expression_list* bytes = new Expression_list();
10970 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
10972 mpz_init_set_ui(val, *p);
10973 Expression* byte = Expression::make_integer(&val, NULL, loc);
10974 mpz_clear(val);
10975 bytes->push_back(byte);
10978 Expression* e = Expression::make_composite_literal(array_type, 0, false,
10979 bytes, false, loc);
10981 Variable* var = new Variable(array_type, e, true, false, false, loc);
10983 static int count;
10984 char buf[50];
10985 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
10986 ++count;
10988 Named_object* no = gogo->add_variable(buf, var);
10989 e = Expression::make_var_reference(no, loc);
10990 e = Expression::make_unary(OPERATOR_AND, e, loc);
10992 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
10993 inserter->insert(Statement::make_statement(call, false));
10995 // Put this function, and the global variable we just created, into
10996 // unique sections. This will permit the linker to garbage collect
10997 // them if they are not referenced. The effect is that the only
10998 // strings, indicating field references, that will wind up in the
10999 // executable will be those for functions that are actually needed.
11000 if (function != NULL)
11001 function->func_value()->set_in_unique_section();
11002 var->set_in_unique_section();
11004 return this;
11007 // Return the type of a field reference.
11009 Type*
11010 Field_reference_expression::do_type()
11012 Type* type = this->expr_->type();
11013 if (type->is_error())
11014 return type;
11015 Struct_type* struct_type = type->struct_type();
11016 go_assert(struct_type != NULL);
11017 return struct_type->field(this->field_index_)->type();
11020 // Check the types for a field reference.
11022 void
11023 Field_reference_expression::do_check_types(Gogo*)
11025 Type* type = this->expr_->type();
11026 if (type->is_error())
11027 return;
11028 Struct_type* struct_type = type->struct_type();
11029 go_assert(struct_type != NULL);
11030 go_assert(struct_type->field(this->field_index_) != NULL);
11033 // Get the backend representation for a field reference.
11035 Bexpression*
11036 Field_reference_expression::do_get_backend(Translate_context* context)
11038 Bexpression* bstruct = this->expr_->get_backend(context);
11039 return context->gogo()->backend()->struct_field_expression(bstruct,
11040 this->field_index_,
11041 this->location());
11044 // Dump ast representation for a field reference expression.
11046 void
11047 Field_reference_expression::do_dump_expression(
11048 Ast_dump_context* ast_dump_context) const
11050 this->expr_->dump_expression(ast_dump_context);
11051 ast_dump_context->ostream() << "." << this->field_index_;
11054 // Make a reference to a qualified identifier in an expression.
11056 Field_reference_expression*
11057 Expression::make_field_reference(Expression* expr, unsigned int field_index,
11058 Location location)
11060 return new Field_reference_expression(expr, field_index, location);
11063 // Class Interface_field_reference_expression.
11065 // Return an expression for the pointer to the function to call.
11067 Expression*
11068 Interface_field_reference_expression::get_function()
11070 Expression* ref = this->expr_;
11071 Location loc = this->location();
11072 if (ref->type()->points_to() != NULL)
11073 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
11075 Expression* mtable =
11076 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
11077 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
11079 std::string name = Gogo::unpack_hidden_name(this->name_);
11080 unsigned int index;
11081 const Struct_field* field = mtable_type->find_local_field(name, &index);
11082 go_assert(field != NULL);
11083 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
11084 return Expression::make_field_reference(mtable, index, loc);
11087 // Return an expression for the first argument to pass to the interface
11088 // function.
11090 Expression*
11091 Interface_field_reference_expression::get_underlying_object()
11093 Expression* expr = this->expr_;
11094 if (expr->type()->points_to() != NULL)
11095 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
11096 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
11097 this->location());
11100 // Traversal.
11103 Interface_field_reference_expression::do_traverse(Traverse* traverse)
11105 return Expression::traverse(&this->expr_, traverse);
11108 // Lower the expression. If this expression is not called, we need to
11109 // evaluate the expression twice when converting to the backend
11110 // interface. So introduce a temporary variable if necessary.
11112 Expression*
11113 Interface_field_reference_expression::do_lower(Gogo*, Named_object*,
11114 Statement_inserter* inserter,
11115 int)
11117 if (!this->expr_->is_variable())
11119 Temporary_statement* temp =
11120 Statement::make_temporary(this->expr_->type(), NULL, this->location());
11121 inserter->insert(temp);
11122 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
11123 this->location());
11125 return this;
11128 // Return the type of an interface field reference.
11130 Type*
11131 Interface_field_reference_expression::do_type()
11133 Type* expr_type = this->expr_->type();
11135 Type* points_to = expr_type->points_to();
11136 if (points_to != NULL)
11137 expr_type = points_to;
11139 Interface_type* interface_type = expr_type->interface_type();
11140 if (interface_type == NULL)
11141 return Type::make_error_type();
11143 const Typed_identifier* method = interface_type->find_method(this->name_);
11144 if (method == NULL)
11145 return Type::make_error_type();
11147 return method->type();
11150 // Determine types.
11152 void
11153 Interface_field_reference_expression::do_determine_type(const Type_context*)
11155 this->expr_->determine_type_no_context();
11158 // Check the types for an interface field reference.
11160 void
11161 Interface_field_reference_expression::do_check_types(Gogo*)
11163 Type* type = this->expr_->type();
11165 Type* points_to = type->points_to();
11166 if (points_to != NULL)
11167 type = points_to;
11169 Interface_type* interface_type = type->interface_type();
11170 if (interface_type == NULL)
11172 if (!type->is_error_type())
11173 this->report_error(_("expected interface or pointer to interface"));
11175 else
11177 const Typed_identifier* method =
11178 interface_type->find_method(this->name_);
11179 if (method == NULL)
11181 error_at(this->location(), "method %qs not in interface",
11182 Gogo::message_name(this->name_).c_str());
11183 this->set_is_error();
11188 // If an interface field reference is not simply called, then it is
11189 // represented as a closure. The closure will hold a single variable,
11190 // the value of the interface on which the method should be called.
11191 // The function will be a simple thunk that pulls the value from the
11192 // closure and calls the method with the remaining arguments.
11194 // Because method values are not common, we don't build all thunks for
11195 // all possible interface methods, but instead only build them as we
11196 // need them. In particular, we even build them on demand for
11197 // interface methods defined in other packages.
11199 Interface_field_reference_expression::Interface_method_thunks
11200 Interface_field_reference_expression::interface_method_thunks;
11202 // Find or create the thunk to call method NAME on TYPE.
11204 Named_object*
11205 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11206 Interface_type* type,
11207 const std::string& name)
11209 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11210 std::pair<Interface_method_thunks::iterator, bool> ins =
11211 Interface_field_reference_expression::interface_method_thunks.insert(val);
11212 if (ins.second)
11214 // This is the first time we have seen this interface.
11215 ins.first->second = new Method_thunks();
11218 for (Method_thunks::const_iterator p = ins.first->second->begin();
11219 p != ins.first->second->end();
11220 p++)
11221 if (p->first == name)
11222 return p->second;
11224 Location loc = type->location();
11226 const Typed_identifier* method_id = type->find_method(name);
11227 if (method_id == NULL)
11228 return Named_object::make_erroneous_name(Gogo::thunk_name());
11230 Function_type* orig_fntype = method_id->type()->function_type();
11231 if (orig_fntype == NULL)
11232 return Named_object::make_erroneous_name(Gogo::thunk_name());
11234 Struct_field_list* sfl = new Struct_field_list();
11235 // The type here is wrong--it should be the C function type. But it
11236 // doesn't really matter.
11237 Type* vt = Type::make_pointer_type(Type::make_void_type());
11238 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11239 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11240 Type* closure_type = Type::make_struct_type(sfl, loc);
11241 closure_type = Type::make_pointer_type(closure_type);
11243 Function_type* new_fntype = orig_fntype->copy_with_names();
11245 Named_object* new_no = gogo->start_function(Gogo::thunk_name(), new_fntype,
11246 false, loc);
11248 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11249 cvar->set_is_used();
11250 Named_object* cp = Named_object::make_variable("$closure", NULL, cvar);
11251 new_no->func_value()->set_closure_var(cp);
11253 gogo->start_block(loc);
11255 // Field 0 of the closure is the function code pointer, field 1 is
11256 // the value on which to invoke the method.
11257 Expression* arg = Expression::make_var_reference(cp, loc);
11258 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11259 arg = Expression::make_field_reference(arg, 1, loc);
11261 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11262 loc);
11264 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11265 Expression_list* args;
11266 if (orig_params == NULL || orig_params->empty())
11267 args = NULL;
11268 else
11270 const Typed_identifier_list* new_params = new_fntype->parameters();
11271 args = new Expression_list();
11272 for (Typed_identifier_list::const_iterator p = new_params->begin();
11273 p != new_params->end();
11274 ++p)
11276 Named_object* p_no = gogo->lookup(p->name(), NULL);
11277 go_assert(p_no != NULL
11278 && p_no->is_variable()
11279 && p_no->var_value()->is_parameter());
11280 args->push_back(Expression::make_var_reference(p_no, loc));
11284 Call_expression* call = Expression::make_call(ifre, args,
11285 orig_fntype->is_varargs(),
11286 loc);
11287 call->set_varargs_are_lowered();
11289 Statement* s = Statement::make_return_from_call(call, loc);
11290 gogo->add_statement(s);
11291 Block* b = gogo->finish_block(loc);
11292 gogo->add_block(b, loc);
11293 gogo->lower_block(new_no, b);
11294 gogo->flatten_block(new_no, b);
11295 gogo->finish_function(loc);
11297 ins.first->second->push_back(std::make_pair(name, new_no));
11298 return new_no;
11301 // Get the backend representation for a method value.
11303 Bexpression*
11304 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11306 Interface_type* type = this->expr_->type()->interface_type();
11307 if (type == NULL)
11309 go_assert(saw_errors());
11310 return context->backend()->error_expression();
11313 Named_object* thunk =
11314 Interface_field_reference_expression::create_thunk(context->gogo(),
11315 type, this->name_);
11316 if (thunk->is_erroneous())
11318 go_assert(saw_errors());
11319 return context->backend()->error_expression();
11322 // FIXME: We should lower this earlier, but we can't it lower it in
11323 // the lowering pass because at that point we don't know whether we
11324 // need to create the thunk or not. If the expression is called, we
11325 // don't need the thunk.
11327 Location loc = this->location();
11329 Struct_field_list* fields = new Struct_field_list();
11330 fields->push_back(Struct_field(Typed_identifier("fn.0",
11331 thunk->func_value()->type(),
11332 loc)));
11333 fields->push_back(Struct_field(Typed_identifier("val.1",
11334 this->expr_->type(),
11335 loc)));
11336 Struct_type* st = Type::make_struct_type(fields, loc);
11338 Expression_list* vals = new Expression_list();
11339 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11340 vals->push_back(this->expr_);
11342 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11343 Bexpression* bclosure =
11344 Expression::make_heap_expression(expr, loc)->get_backend(context);
11346 Expression* nil_check =
11347 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11348 Expression::make_nil(loc), loc);
11349 Bexpression* bnil_check = nil_check->get_backend(context);
11351 Gogo* gogo = context->gogo();
11352 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11353 loc)->get_backend(context);
11355 Bexpression* bcond =
11356 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11357 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11358 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11361 // Dump ast representation for an interface field reference.
11363 void
11364 Interface_field_reference_expression::do_dump_expression(
11365 Ast_dump_context* ast_dump_context) const
11367 this->expr_->dump_expression(ast_dump_context);
11368 ast_dump_context->ostream() << "." << this->name_;
11371 // Make a reference to a field in an interface.
11373 Expression*
11374 Expression::make_interface_field_reference(Expression* expr,
11375 const std::string& field,
11376 Location location)
11378 return new Interface_field_reference_expression(expr, field, location);
11381 // A general selector. This is a Parser_expression for LEFT.NAME. It
11382 // is lowered after we know the type of the left hand side.
11384 class Selector_expression : public Parser_expression
11386 public:
11387 Selector_expression(Expression* left, const std::string& name,
11388 Location location)
11389 : Parser_expression(EXPRESSION_SELECTOR, location),
11390 left_(left), name_(name)
11393 protected:
11395 do_traverse(Traverse* traverse)
11396 { return Expression::traverse(&this->left_, traverse); }
11398 Expression*
11399 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11401 Expression*
11402 do_copy()
11404 return new Selector_expression(this->left_->copy(), this->name_,
11405 this->location());
11408 void
11409 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11411 private:
11412 Expression*
11413 lower_method_expression(Gogo*);
11415 // The expression on the left hand side.
11416 Expression* left_;
11417 // The name on the right hand side.
11418 std::string name_;
11421 // Lower a selector expression once we know the real type of the left
11422 // hand side.
11424 Expression*
11425 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11426 int)
11428 Expression* left = this->left_;
11429 if (left->is_type_expression())
11430 return this->lower_method_expression(gogo);
11431 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11432 this->location());
11435 // Lower a method expression T.M or (*T).M. We turn this into a
11436 // function literal.
11438 Expression*
11439 Selector_expression::lower_method_expression(Gogo* gogo)
11441 Location location = this->location();
11442 Type* type = this->left_->type();
11443 const std::string& name(this->name_);
11445 bool is_pointer;
11446 if (type->points_to() == NULL)
11447 is_pointer = false;
11448 else
11450 is_pointer = true;
11451 type = type->points_to();
11453 Named_type* nt = type->named_type();
11454 if (nt == NULL)
11456 error_at(location,
11457 ("method expression requires named type or "
11458 "pointer to named type"));
11459 return Expression::make_error(location);
11462 bool is_ambiguous;
11463 Method* method = nt->method_function(name, &is_ambiguous);
11464 const Typed_identifier* imethod = NULL;
11465 if (method == NULL && !is_pointer)
11467 Interface_type* it = nt->interface_type();
11468 if (it != NULL)
11469 imethod = it->find_method(name);
11472 if (method == NULL && imethod == NULL)
11474 if (!is_ambiguous)
11475 error_at(location, "type %<%s%s%> has no method %<%s%>",
11476 is_pointer ? "*" : "",
11477 nt->message_name().c_str(),
11478 Gogo::message_name(name).c_str());
11479 else
11480 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11481 Gogo::message_name(name).c_str(),
11482 is_pointer ? "*" : "",
11483 nt->message_name().c_str());
11484 return Expression::make_error(location);
11487 if (method != NULL && !is_pointer && !method->is_value_method())
11489 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11490 nt->message_name().c_str(),
11491 Gogo::message_name(name).c_str());
11492 return Expression::make_error(location);
11495 // Build a new function type in which the receiver becomes the first
11496 // argument.
11497 Function_type* method_type;
11498 if (method != NULL)
11500 method_type = method->type();
11501 go_assert(method_type->is_method());
11503 else
11505 method_type = imethod->type()->function_type();
11506 go_assert(method_type != NULL && !method_type->is_method());
11509 const char* const receiver_name = "$this";
11510 Typed_identifier_list* parameters = new Typed_identifier_list();
11511 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11512 location));
11514 const Typed_identifier_list* method_parameters = method_type->parameters();
11515 if (method_parameters != NULL)
11517 int i = 0;
11518 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11519 p != method_parameters->end();
11520 ++p, ++i)
11522 if (!p->name().empty())
11523 parameters->push_back(*p);
11524 else
11526 char buf[20];
11527 snprintf(buf, sizeof buf, "$param%d", i);
11528 parameters->push_back(Typed_identifier(buf, p->type(),
11529 p->location()));
11534 const Typed_identifier_list* method_results = method_type->results();
11535 Typed_identifier_list* results;
11536 if (method_results == NULL)
11537 results = NULL;
11538 else
11540 results = new Typed_identifier_list();
11541 for (Typed_identifier_list::const_iterator p = method_results->begin();
11542 p != method_results->end();
11543 ++p)
11544 results->push_back(*p);
11547 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11548 location);
11549 if (method_type->is_varargs())
11550 fntype->set_is_varargs();
11552 // We generate methods which always takes a pointer to the receiver
11553 // as their first argument. If this is for a pointer type, we can
11554 // simply reuse the existing function. We use an internal hack to
11555 // get the right type.
11556 // FIXME: This optimization is disabled because it doesn't yet work
11557 // with function descriptors when the method expression is not
11558 // directly called.
11559 if (method != NULL && is_pointer && false)
11561 Named_object* mno = (method->needs_stub_method()
11562 ? method->stub_object()
11563 : method->named_object());
11564 Expression* f = Expression::make_func_reference(mno, NULL, location);
11565 f = Expression::make_cast(fntype, f, location);
11566 Type_conversion_expression* tce =
11567 static_cast<Type_conversion_expression*>(f);
11568 tce->set_may_convert_function_types();
11569 return f;
11572 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11573 location);
11575 Named_object* vno = gogo->lookup(receiver_name, NULL);
11576 go_assert(vno != NULL);
11577 Expression* ve = Expression::make_var_reference(vno, location);
11578 Expression* bm;
11579 if (method != NULL)
11580 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11581 else
11582 bm = Expression::make_interface_field_reference(ve, name, location);
11584 // Even though we found the method above, if it has an error type we
11585 // may see an error here.
11586 if (bm->is_error_expression())
11588 gogo->finish_function(location);
11589 return bm;
11592 Expression_list* args;
11593 if (parameters->size() <= 1)
11594 args = NULL;
11595 else
11597 args = new Expression_list();
11598 Typed_identifier_list::const_iterator p = parameters->begin();
11599 ++p;
11600 for (; p != parameters->end(); ++p)
11602 vno = gogo->lookup(p->name(), NULL);
11603 go_assert(vno != NULL);
11604 args->push_back(Expression::make_var_reference(vno, location));
11608 gogo->start_block(location);
11610 Call_expression* call = Expression::make_call(bm, args,
11611 method_type->is_varargs(),
11612 location);
11614 Statement* s = Statement::make_return_from_call(call, location);
11615 gogo->add_statement(s);
11617 Block* b = gogo->finish_block(location);
11619 gogo->add_block(b, location);
11621 // Lower the call in case there are multiple results.
11622 gogo->lower_block(no, b);
11623 gogo->flatten_block(no, b);
11625 gogo->finish_function(location);
11627 return Expression::make_func_reference(no, NULL, location);
11630 // Dump the ast for a selector expression.
11632 void
11633 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11634 const
11636 ast_dump_context->dump_expression(this->left_);
11637 ast_dump_context->ostream() << ".";
11638 ast_dump_context->ostream() << this->name_;
11641 // Make a selector expression.
11643 Expression*
11644 Expression::make_selector(Expression* left, const std::string& name,
11645 Location location)
11647 return new Selector_expression(left, name, location);
11650 // Implement the builtin function new.
11652 class Allocation_expression : public Expression
11654 public:
11655 Allocation_expression(Type* type, Location location)
11656 : Expression(EXPRESSION_ALLOCATION, location),
11657 type_(type)
11660 protected:
11662 do_traverse(Traverse* traverse)
11663 { return Type::traverse(this->type_, traverse); }
11665 Type*
11666 do_type()
11667 { return Type::make_pointer_type(this->type_); }
11669 void
11670 do_determine_type(const Type_context*)
11673 Expression*
11674 do_copy()
11675 { return new Allocation_expression(this->type_, this->location()); }
11677 Bexpression*
11678 do_get_backend(Translate_context*);
11680 void
11681 do_dump_expression(Ast_dump_context*) const;
11683 private:
11684 // The type we are allocating.
11685 Type* type_;
11688 // Return the backend representation for an allocation expression.
11690 Bexpression*
11691 Allocation_expression::do_get_backend(Translate_context* context)
11693 Gogo* gogo = context->gogo();
11694 Location loc = this->location();
11695 Bexpression* space =
11696 gogo->allocate_memory(this->type_, loc)->get_backend(context);
11697 Btype* pbtype = gogo->backend()->pointer_type(this->type_->get_backend(gogo));
11698 return gogo->backend()->convert_expression(pbtype, space, loc);
11701 // Dump ast representation for an allocation expression.
11703 void
11704 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11705 const
11707 ast_dump_context->ostream() << "new(";
11708 ast_dump_context->dump_type(this->type_);
11709 ast_dump_context->ostream() << ")";
11712 // Make an allocation expression.
11714 Expression*
11715 Expression::make_allocation(Type* type, Location location)
11717 return new Allocation_expression(type, location);
11720 // Construct a struct.
11722 class Struct_construction_expression : public Expression
11724 public:
11725 Struct_construction_expression(Type* type, Expression_list* vals,
11726 Location location)
11727 : Expression(EXPRESSION_STRUCT_CONSTRUCTION, location),
11728 type_(type), vals_(vals), traverse_order_(NULL)
11731 // Set the traversal order, used to ensure that we implement the
11732 // order of evaluation rules. Takes ownership of the argument.
11733 void
11734 set_traverse_order(std::vector<int>* traverse_order)
11735 { this->traverse_order_ = traverse_order; }
11737 // Return whether this is a constant initializer.
11738 bool
11739 is_constant_struct() const;
11741 protected:
11743 do_traverse(Traverse* traverse);
11745 bool
11746 do_is_immutable() const;
11748 Type*
11749 do_type()
11750 { return this->type_; }
11752 void
11753 do_determine_type(const Type_context*);
11755 void
11756 do_check_types(Gogo*);
11758 Expression*
11759 do_copy()
11761 Struct_construction_expression* ret =
11762 new Struct_construction_expression(this->type_, this->vals_->copy(),
11763 this->location());
11764 if (this->traverse_order_ != NULL)
11765 ret->set_traverse_order(this->traverse_order_);
11766 return ret;
11769 Bexpression*
11770 do_get_backend(Translate_context*);
11772 void
11773 do_export(Export*) const;
11775 void
11776 do_dump_expression(Ast_dump_context*) const;
11778 private:
11779 // The type of the struct to construct.
11780 Type* type_;
11781 // The list of values, in order of the fields in the struct. A NULL
11782 // entry means that the field should be zero-initialized.
11783 Expression_list* vals_;
11784 // If not NULL, the order in which to traverse vals_. This is used
11785 // so that we implement the order of evaluation rules correctly.
11786 std::vector<int>* traverse_order_;
11789 // Traversal.
11792 Struct_construction_expression::do_traverse(Traverse* traverse)
11794 if (this->vals_ != NULL)
11796 if (this->traverse_order_ == NULL)
11798 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11799 return TRAVERSE_EXIT;
11801 else
11803 for (std::vector<int>::const_iterator p =
11804 this->traverse_order_->begin();
11805 p != this->traverse_order_->end();
11806 ++p)
11808 if (Expression::traverse(&this->vals_->at(*p), traverse)
11809 == TRAVERSE_EXIT)
11810 return TRAVERSE_EXIT;
11814 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11815 return TRAVERSE_EXIT;
11816 return TRAVERSE_CONTINUE;
11819 // Return whether this is a constant initializer.
11821 bool
11822 Struct_construction_expression::is_constant_struct() const
11824 if (this->vals_ == NULL)
11825 return true;
11826 for (Expression_list::const_iterator pv = this->vals_->begin();
11827 pv != this->vals_->end();
11828 ++pv)
11830 if (*pv != NULL
11831 && !(*pv)->is_constant()
11832 && (!(*pv)->is_composite_literal()
11833 || (*pv)->is_nonconstant_composite_literal()))
11834 return false;
11837 const Struct_field_list* fields = this->type_->struct_type()->fields();
11838 for (Struct_field_list::const_iterator pf = fields->begin();
11839 pf != fields->end();
11840 ++pf)
11842 // There are no constant constructors for interfaces.
11843 if (pf->type()->interface_type() != NULL)
11844 return false;
11847 return true;
11850 // Return whether this struct is immutable.
11852 bool
11853 Struct_construction_expression::do_is_immutable() const
11855 if (this->vals_ == NULL)
11856 return true;
11857 for (Expression_list::const_iterator pv = this->vals_->begin();
11858 pv != this->vals_->end();
11859 ++pv)
11861 if (*pv != NULL && !(*pv)->is_immutable())
11862 return false;
11864 return true;
11867 // Final type determination.
11869 void
11870 Struct_construction_expression::do_determine_type(const Type_context*)
11872 if (this->vals_ == NULL)
11873 return;
11874 const Struct_field_list* fields = this->type_->struct_type()->fields();
11875 Expression_list::const_iterator pv = this->vals_->begin();
11876 for (Struct_field_list::const_iterator pf = fields->begin();
11877 pf != fields->end();
11878 ++pf, ++pv)
11880 if (pv == this->vals_->end())
11881 return;
11882 if (*pv != NULL)
11884 Type_context subcontext(pf->type(), false);
11885 (*pv)->determine_type(&subcontext);
11888 // Extra values are an error we will report elsewhere; we still want
11889 // to determine the type to avoid knockon errors.
11890 for (; pv != this->vals_->end(); ++pv)
11891 (*pv)->determine_type_no_context();
11894 // Check types.
11896 void
11897 Struct_construction_expression::do_check_types(Gogo*)
11899 if (this->vals_ == NULL)
11900 return;
11902 Struct_type* st = this->type_->struct_type();
11903 if (this->vals_->size() > st->field_count())
11905 this->report_error(_("too many expressions for struct"));
11906 return;
11909 const Struct_field_list* fields = st->fields();
11910 Expression_list::const_iterator pv = this->vals_->begin();
11911 int i = 0;
11912 for (Struct_field_list::const_iterator pf = fields->begin();
11913 pf != fields->end();
11914 ++pf, ++pv, ++i)
11916 if (pv == this->vals_->end())
11918 this->report_error(_("too few expressions for struct"));
11919 break;
11922 if (*pv == NULL)
11923 continue;
11925 std::string reason;
11926 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11928 if (reason.empty())
11929 error_at((*pv)->location(),
11930 "incompatible type for field %d in struct construction",
11931 i + 1);
11932 else
11933 error_at((*pv)->location(),
11934 ("incompatible type for field %d in "
11935 "struct construction (%s)"),
11936 i + 1, reason.c_str());
11937 this->set_is_error();
11940 go_assert(pv == this->vals_->end());
11943 // Return the backend representation for constructing a struct.
11945 Bexpression*
11946 Struct_construction_expression::do_get_backend(Translate_context* context)
11948 Gogo* gogo = context->gogo();
11950 Btype* btype = this->type_->get_backend(gogo);
11951 if (this->vals_ == NULL)
11952 return gogo->backend()->zero_expression(btype);
11954 const Struct_field_list* fields = this->type_->struct_type()->fields();
11955 Expression_list::const_iterator pv = this->vals_->begin();
11956 std::vector<Bexpression*> init;
11957 for (Struct_field_list::const_iterator pf = fields->begin();
11958 pf != fields->end();
11959 ++pf)
11961 Btype* fbtype = pf->type()->get_backend(gogo);
11962 if (pv == this->vals_->end())
11963 init.push_back(gogo->backend()->zero_expression(fbtype));
11964 else if (*pv == NULL)
11966 init.push_back(gogo->backend()->zero_expression(fbtype));
11967 ++pv;
11969 else
11971 Expression* val =
11972 Expression::convert_for_assignment(gogo, pf->type(),
11973 *pv, this->location());
11974 init.push_back(val->get_backend(context));
11975 ++pv;
11978 return gogo->backend()->constructor_expression(btype, init, this->location());
11981 // Export a struct construction.
11983 void
11984 Struct_construction_expression::do_export(Export* exp) const
11986 exp->write_c_string("convert(");
11987 exp->write_type(this->type_);
11988 for (Expression_list::const_iterator pv = this->vals_->begin();
11989 pv != this->vals_->end();
11990 ++pv)
11992 exp->write_c_string(", ");
11993 if (*pv != NULL)
11994 (*pv)->export_expression(exp);
11996 exp->write_c_string(")");
11999 // Dump ast representation of a struct construction expression.
12001 void
12002 Struct_construction_expression::do_dump_expression(
12003 Ast_dump_context* ast_dump_context) const
12005 ast_dump_context->dump_type(this->type_);
12006 ast_dump_context->ostream() << "{";
12007 ast_dump_context->dump_expression_list(this->vals_);
12008 ast_dump_context->ostream() << "}";
12011 // Make a struct composite literal. This used by the thunk code.
12013 Expression*
12014 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
12015 Location location)
12017 go_assert(type->struct_type() != NULL);
12018 return new Struct_construction_expression(type, vals, location);
12021 // Construct an array. This class is not used directly; instead we
12022 // use the child classes, Fixed_array_construction_expression and
12023 // Slice_construction_expression.
12025 class Array_construction_expression : public Expression
12027 protected:
12028 Array_construction_expression(Expression_classification classification,
12029 Type* type,
12030 const std::vector<unsigned long>* indexes,
12031 Expression_list* vals, Location location)
12032 : Expression(classification, location),
12033 type_(type), indexes_(indexes), vals_(vals)
12034 { go_assert(indexes == NULL || indexes->size() == vals->size()); }
12036 public:
12037 // Return whether this is a constant initializer.
12038 bool
12039 is_constant_array() const;
12041 // Return the number of elements.
12042 size_t
12043 element_count() const
12044 { return this->vals_ == NULL ? 0 : this->vals_->size(); }
12046 protected:
12048 do_traverse(Traverse* traverse);
12050 bool
12051 do_is_immutable() const;
12053 Type*
12054 do_type()
12055 { return this->type_; }
12057 void
12058 do_determine_type(const Type_context*);
12060 void
12061 do_check_types(Gogo*);
12063 void
12064 do_export(Export*) const;
12066 // The indexes.
12067 const std::vector<unsigned long>*
12068 indexes()
12069 { return this->indexes_; }
12071 // The list of values.
12072 Expression_list*
12073 vals()
12074 { return this->vals_; }
12076 // Get the backend constructor for the array values.
12077 Bexpression*
12078 get_constructor(Translate_context* context, Btype* btype);
12080 void
12081 do_dump_expression(Ast_dump_context*) const;
12083 private:
12084 // The type of the array to construct.
12085 Type* type_;
12086 // The list of indexes into the array, one for each value. This may
12087 // be NULL, in which case the indexes start at zero and increment.
12088 const std::vector<unsigned long>* indexes_;
12089 // The list of values. This may be NULL if there are no values.
12090 Expression_list* vals_;
12093 // Traversal.
12096 Array_construction_expression::do_traverse(Traverse* traverse)
12098 if (this->vals_ != NULL
12099 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12100 return TRAVERSE_EXIT;
12101 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12102 return TRAVERSE_EXIT;
12103 return TRAVERSE_CONTINUE;
12106 // Return whether this is a constant initializer.
12108 bool
12109 Array_construction_expression::is_constant_array() const
12111 if (this->vals_ == NULL)
12112 return true;
12114 // There are no constant constructors for interfaces.
12115 if (this->type_->array_type()->element_type()->interface_type() != NULL)
12116 return false;
12118 for (Expression_list::const_iterator pv = this->vals_->begin();
12119 pv != this->vals_->end();
12120 ++pv)
12122 if (*pv != NULL
12123 && !(*pv)->is_constant()
12124 && (!(*pv)->is_composite_literal()
12125 || (*pv)->is_nonconstant_composite_literal()))
12126 return false;
12128 return true;
12131 // Return whether this is an immutable array initializer.
12133 bool
12134 Array_construction_expression::do_is_immutable() const
12136 if (this->vals_ == NULL)
12137 return true;
12138 for (Expression_list::const_iterator pv = this->vals_->begin();
12139 pv != this->vals_->end();
12140 ++pv)
12142 if (*pv != NULL && !(*pv)->is_immutable())
12143 return false;
12145 return true;
12148 // Final type determination.
12150 void
12151 Array_construction_expression::do_determine_type(const Type_context*)
12153 if (this->vals_ == NULL)
12154 return;
12155 Type_context subcontext(this->type_->array_type()->element_type(), false);
12156 for (Expression_list::const_iterator pv = this->vals_->begin();
12157 pv != this->vals_->end();
12158 ++pv)
12160 if (*pv != NULL)
12161 (*pv)->determine_type(&subcontext);
12165 // Check types.
12167 void
12168 Array_construction_expression::do_check_types(Gogo*)
12170 if (this->vals_ == NULL)
12171 return;
12173 Array_type* at = this->type_->array_type();
12174 int i = 0;
12175 Type* element_type = at->element_type();
12176 for (Expression_list::const_iterator pv = this->vals_->begin();
12177 pv != this->vals_->end();
12178 ++pv, ++i)
12180 if (*pv != NULL
12181 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
12183 error_at((*pv)->location(),
12184 "incompatible type for element %d in composite literal",
12185 i + 1);
12186 this->set_is_error();
12191 // Get a constructor expression for the array values.
12193 Bexpression*
12194 Array_construction_expression::get_constructor(Translate_context* context,
12195 Btype* array_btype)
12197 Type* element_type = this->type_->array_type()->element_type();
12199 std::vector<unsigned long> indexes;
12200 std::vector<Bexpression*> vals;
12201 Gogo* gogo = context->gogo();
12202 if (this->vals_ != NULL)
12204 size_t i = 0;
12205 std::vector<unsigned long>::const_iterator pi;
12206 if (this->indexes_ != NULL)
12207 pi = this->indexes_->begin();
12208 for (Expression_list::const_iterator pv = this->vals_->begin();
12209 pv != this->vals_->end();
12210 ++pv, ++i)
12212 if (this->indexes_ != NULL)
12213 go_assert(pi != this->indexes_->end());
12215 if (this->indexes_ == NULL)
12216 indexes.push_back(i);
12217 else
12218 indexes.push_back(*pi);
12219 if (*pv == NULL)
12221 Btype* ebtype = element_type->get_backend(gogo);
12222 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
12223 vals.push_back(zv);
12225 else
12227 Expression* val_expr =
12228 Expression::convert_for_assignment(gogo, element_type, *pv,
12229 this->location());
12230 vals.push_back(val_expr->get_backend(context));
12232 if (this->indexes_ != NULL)
12233 ++pi;
12235 if (this->indexes_ != NULL)
12236 go_assert(pi == this->indexes_->end());
12238 return gogo->backend()->array_constructor_expression(array_btype, indexes,
12239 vals, this->location());
12242 // Export an array construction.
12244 void
12245 Array_construction_expression::do_export(Export* exp) const
12247 exp->write_c_string("convert(");
12248 exp->write_type(this->type_);
12249 if (this->vals_ != NULL)
12251 std::vector<unsigned long>::const_iterator pi;
12252 if (this->indexes_ != NULL)
12253 pi = this->indexes_->begin();
12254 for (Expression_list::const_iterator pv = this->vals_->begin();
12255 pv != this->vals_->end();
12256 ++pv)
12258 exp->write_c_string(", ");
12260 if (this->indexes_ != NULL)
12262 char buf[100];
12263 snprintf(buf, sizeof buf, "%lu", *pi);
12264 exp->write_c_string(buf);
12265 exp->write_c_string(":");
12268 if (*pv != NULL)
12269 (*pv)->export_expression(exp);
12271 if (this->indexes_ != NULL)
12272 ++pi;
12275 exp->write_c_string(")");
12278 // Dump ast representation of an array construction expressin.
12280 void
12281 Array_construction_expression::do_dump_expression(
12282 Ast_dump_context* ast_dump_context) const
12284 Expression* length = this->type_->array_type()->length();
12286 ast_dump_context->ostream() << "[" ;
12287 if (length != NULL)
12289 ast_dump_context->dump_expression(length);
12291 ast_dump_context->ostream() << "]" ;
12292 ast_dump_context->dump_type(this->type_);
12293 ast_dump_context->ostream() << "{" ;
12294 if (this->indexes_ == NULL)
12295 ast_dump_context->dump_expression_list(this->vals_);
12296 else
12298 Expression_list::const_iterator pv = this->vals_->begin();
12299 for (std::vector<unsigned long>::const_iterator pi =
12300 this->indexes_->begin();
12301 pi != this->indexes_->end();
12302 ++pi, ++pv)
12304 if (pi != this->indexes_->begin())
12305 ast_dump_context->ostream() << ", ";
12306 ast_dump_context->ostream() << *pi << ':';
12307 ast_dump_context->dump_expression(*pv);
12310 ast_dump_context->ostream() << "}" ;
12314 // Construct a fixed array.
12316 class Fixed_array_construction_expression :
12317 public Array_construction_expression
12319 public:
12320 Fixed_array_construction_expression(Type* type,
12321 const std::vector<unsigned long>* indexes,
12322 Expression_list* vals, Location location)
12323 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12324 type, indexes, vals, location)
12325 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12327 protected:
12328 Expression*
12329 do_copy()
12331 return new Fixed_array_construction_expression(this->type(),
12332 this->indexes(),
12333 (this->vals() == NULL
12334 ? NULL
12335 : this->vals()->copy()),
12336 this->location());
12339 Bexpression*
12340 do_get_backend(Translate_context*);
12343 // Return the backend representation for constructing a fixed array.
12345 Bexpression*
12346 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
12348 Type* type = this->type();
12349 Btype* btype = type->get_backend(context->gogo());
12350 return this->get_constructor(context, btype);
12353 Expression*
12354 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12355 Location location)
12357 go_assert(type->array_type() != NULL && !type->is_slice_type());
12358 return new Fixed_array_construction_expression(type, NULL, vals, location);
12361 // Construct a slice.
12363 class Slice_construction_expression : public Array_construction_expression
12365 public:
12366 Slice_construction_expression(Type* type,
12367 const std::vector<unsigned long>* indexes,
12368 Expression_list* vals, Location location)
12369 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12370 type, indexes, vals, location),
12371 valtype_(NULL)
12372 { go_assert(type->is_slice_type()); }
12374 protected:
12375 // Note that taking the address of a slice literal is invalid.
12377 Expression*
12378 do_copy()
12380 return new Slice_construction_expression(this->type(), this->indexes(),
12381 (this->vals() == NULL
12382 ? NULL
12383 : this->vals()->copy()),
12384 this->location());
12387 Bexpression*
12388 do_get_backend(Translate_context*);
12390 private:
12391 // The type of the values in this slice.
12392 Type* valtype_;
12395 // Return the backend representation for constructing a slice.
12397 Bexpression*
12398 Slice_construction_expression::do_get_backend(Translate_context* context)
12400 Array_type* array_type = this->type()->array_type();
12401 if (array_type == NULL)
12403 go_assert(this->type()->is_error());
12404 return context->backend()->error_expression();
12407 Location loc = this->location();
12408 Type* element_type = array_type->element_type();
12409 if (this->valtype_ == NULL)
12411 mpz_t lenval;
12412 Expression* length;
12413 if (this->vals() == NULL || this->vals()->empty())
12414 mpz_init_set_ui(lenval, 0);
12415 else
12417 if (this->indexes() == NULL)
12418 mpz_init_set_ui(lenval, this->vals()->size());
12419 else
12420 mpz_init_set_ui(lenval, this->indexes()->back() + 1);
12422 Type* int_type = Type::lookup_integer_type("int");
12423 length = Expression::make_integer(&lenval, int_type, loc);
12424 mpz_clear(lenval);
12425 this->valtype_ = Type::make_array_type(element_type, length);
12428 Expression_list* vals = this->vals();
12429 if (this->vals() == NULL || this->vals()->empty())
12431 // We need to create a unique value for the empty array literal.
12432 vals = new Expression_list;
12433 vals->push_back(NULL);
12435 Expression* array_val =
12436 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12437 vals, loc);
12439 bool is_constant_initializer = array_val->is_immutable();
12441 // We have to copy the initial values into heap memory if we are in
12442 // a function or if the values are not constants. We also have to
12443 // copy them if they may contain pointers in a non-constant context,
12444 // as otherwise the garbage collector won't see them.
12445 bool copy_to_heap = (context->function() != NULL
12446 || !is_constant_initializer
12447 || (element_type->has_pointer()
12448 && !context->is_const()));
12450 Expression* space;
12451 if (!copy_to_heap)
12453 // The initializer will only run once.
12454 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12455 space->unary_expression()->set_is_slice_init();
12457 else
12458 space = Expression::make_heap_expression(array_val, loc);
12460 // Build a constructor for the slice.
12462 Expression* len = this->valtype_->array_type()->length();
12463 Expression* slice_val =
12464 Expression::make_slice_value(this->type(), space, len, len, loc);
12465 return slice_val->get_backend(context);
12468 // Make a slice composite literal. This is used by the type
12469 // descriptor code.
12471 Expression*
12472 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12473 Location location)
12475 go_assert(type->is_slice_type());
12476 return new Slice_construction_expression(type, NULL, vals, location);
12479 // Construct a map.
12481 class Map_construction_expression : public Expression
12483 public:
12484 Map_construction_expression(Type* type, Expression_list* vals,
12485 Location location)
12486 : Expression(EXPRESSION_MAP_CONSTRUCTION, location),
12487 type_(type), vals_(vals), element_type_(NULL), constructor_temp_(NULL)
12488 { go_assert(vals == NULL || vals->size() % 2 == 0); }
12490 protected:
12492 do_traverse(Traverse* traverse);
12494 Expression*
12495 do_flatten(Gogo*, Named_object*, Statement_inserter*);
12497 Type*
12498 do_type()
12499 { return this->type_; }
12501 void
12502 do_determine_type(const Type_context*);
12504 void
12505 do_check_types(Gogo*);
12507 Expression*
12508 do_copy()
12510 return new Map_construction_expression(this->type_, this->vals_->copy(),
12511 this->location());
12514 Bexpression*
12515 do_get_backend(Translate_context*);
12517 void
12518 do_export(Export*) const;
12520 void
12521 do_dump_expression(Ast_dump_context*) const;
12523 private:
12524 // The type of the map to construct.
12525 Type* type_;
12526 // The list of values.
12527 Expression_list* vals_;
12528 // The type of the key-value pair struct for each map element.
12529 Struct_type* element_type_;
12530 // A temporary reference to the variable storing the constructor initializer.
12531 Temporary_statement* constructor_temp_;
12534 // Traversal.
12537 Map_construction_expression::do_traverse(Traverse* traverse)
12539 if (this->vals_ != NULL
12540 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12541 return TRAVERSE_EXIT;
12542 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12543 return TRAVERSE_EXIT;
12544 return TRAVERSE_CONTINUE;
12547 // Flatten constructor initializer into a temporary variable since
12548 // we need to take its address for __go_construct_map.
12550 Expression*
12551 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12552 Statement_inserter* inserter)
12554 if (!this->is_error_expression()
12555 && this->vals_ != NULL
12556 && !this->vals_->empty()
12557 && this->constructor_temp_ == NULL)
12559 Map_type* mt = this->type_->map_type();
12560 Type* key_type = mt->key_type();
12561 Type* val_type = mt->val_type();
12562 this->element_type_ = Type::make_builtin_struct_type(2,
12563 "__key", key_type,
12564 "__val", val_type);
12566 Expression_list* value_pairs = new Expression_list();
12567 Location loc = this->location();
12569 size_t i = 0;
12570 for (Expression_list::const_iterator pv = this->vals_->begin();
12571 pv != this->vals_->end();
12572 ++pv, ++i)
12574 Expression_list* key_value_pair = new Expression_list();
12575 Expression* key =
12576 Expression::convert_for_assignment(gogo, key_type, *pv, loc);
12578 ++pv;
12579 Expression* val =
12580 Expression::convert_for_assignment(gogo, val_type, *pv, loc);
12582 key_value_pair->push_back(key);
12583 key_value_pair->push_back(val);
12584 value_pairs->push_back(
12585 Expression::make_struct_composite_literal(this->element_type_,
12586 key_value_pair, loc));
12589 mpz_t lenval;
12590 mpz_init_set_ui(lenval, i);
12591 Expression* element_count = Expression::make_integer(&lenval, NULL, loc);
12592 mpz_clear(lenval);
12594 Type* ctor_type =
12595 Type::make_array_type(this->element_type_, element_count);
12596 Expression* constructor =
12597 new Fixed_array_construction_expression(ctor_type, NULL,
12598 value_pairs, loc);
12600 this->constructor_temp_ =
12601 Statement::make_temporary(NULL, constructor, loc);
12602 constructor->issue_nil_check();
12603 this->constructor_temp_->set_is_address_taken();
12604 inserter->insert(this->constructor_temp_);
12607 return this;
12610 // Final type determination.
12612 void
12613 Map_construction_expression::do_determine_type(const Type_context*)
12615 if (this->vals_ == NULL)
12616 return;
12618 Map_type* mt = this->type_->map_type();
12619 Type_context key_context(mt->key_type(), false);
12620 Type_context val_context(mt->val_type(), false);
12621 for (Expression_list::const_iterator pv = this->vals_->begin();
12622 pv != this->vals_->end();
12623 ++pv)
12625 (*pv)->determine_type(&key_context);
12626 ++pv;
12627 (*pv)->determine_type(&val_context);
12631 // Check types.
12633 void
12634 Map_construction_expression::do_check_types(Gogo*)
12636 if (this->vals_ == NULL)
12637 return;
12639 Map_type* mt = this->type_->map_type();
12640 int i = 0;
12641 Type* key_type = mt->key_type();
12642 Type* val_type = mt->val_type();
12643 for (Expression_list::const_iterator pv = this->vals_->begin();
12644 pv != this->vals_->end();
12645 ++pv, ++i)
12647 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12649 error_at((*pv)->location(),
12650 "incompatible type for element %d key in map construction",
12651 i + 1);
12652 this->set_is_error();
12654 ++pv;
12655 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12657 error_at((*pv)->location(),
12658 ("incompatible type for element %d value "
12659 "in map construction"),
12660 i + 1);
12661 this->set_is_error();
12666 // Return the backend representation for constructing a map.
12668 Bexpression*
12669 Map_construction_expression::do_get_backend(Translate_context* context)
12671 if (this->is_error_expression())
12672 return context->backend()->error_expression();
12673 Location loc = this->location();
12675 size_t i = 0;
12676 Expression* ventries;
12677 if (this->vals_ == NULL || this->vals_->empty())
12678 ventries = Expression::make_nil(loc);
12679 else
12681 go_assert(this->constructor_temp_ != NULL);
12682 i = this->vals_->size() / 2;
12684 Expression* ctor_ref =
12685 Expression::make_temporary_reference(this->constructor_temp_, loc);
12686 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12689 Map_type* mt = this->type_->map_type();
12690 if (this->element_type_ == NULL)
12691 this->element_type_ =
12692 Type::make_builtin_struct_type(2,
12693 "__key", mt->key_type(),
12694 "__val", mt->val_type());
12695 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12697 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12698 mpz_t countval;
12699 mpz_init_set_ui(countval, i);
12700 Expression* count = Expression::make_integer(&countval, uintptr_t, loc);
12701 mpz_clear(countval);
12703 Expression* entry_size =
12704 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12706 unsigned int field_index;
12707 const Struct_field* valfield =
12708 this->element_type_->find_local_field("__val", &field_index);
12709 Expression* val_offset =
12710 Expression::make_struct_field_offset(this->element_type_, valfield);
12711 Expression* val_size =
12712 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12714 Expression* map_ctor =
12715 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12716 entry_size, val_offset, val_size, ventries);
12717 return map_ctor->get_backend(context);
12720 // Export an array construction.
12722 void
12723 Map_construction_expression::do_export(Export* exp) const
12725 exp->write_c_string("convert(");
12726 exp->write_type(this->type_);
12727 for (Expression_list::const_iterator pv = this->vals_->begin();
12728 pv != this->vals_->end();
12729 ++pv)
12731 exp->write_c_string(", ");
12732 (*pv)->export_expression(exp);
12734 exp->write_c_string(")");
12737 // Dump ast representation for a map construction expression.
12739 void
12740 Map_construction_expression::do_dump_expression(
12741 Ast_dump_context* ast_dump_context) const
12743 ast_dump_context->ostream() << "{" ;
12744 ast_dump_context->dump_expression_list(this->vals_, true);
12745 ast_dump_context->ostream() << "}";
12748 // A general composite literal. This is lowered to a type specific
12749 // version.
12751 class Composite_literal_expression : public Parser_expression
12753 public:
12754 Composite_literal_expression(Type* type, int depth, bool has_keys,
12755 Expression_list* vals, bool all_are_names,
12756 Location location)
12757 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12758 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12759 all_are_names_(all_are_names)
12762 protected:
12764 do_traverse(Traverse* traverse);
12766 Expression*
12767 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12769 Expression*
12770 do_copy()
12772 return new Composite_literal_expression(this->type_, this->depth_,
12773 this->has_keys_,
12774 (this->vals_ == NULL
12775 ? NULL
12776 : this->vals_->copy()),
12777 this->all_are_names_,
12778 this->location());
12781 void
12782 do_dump_expression(Ast_dump_context*) const;
12784 private:
12785 Expression*
12786 lower_struct(Gogo*, Type*);
12788 Expression*
12789 lower_array(Type*);
12791 Expression*
12792 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12794 Expression*
12795 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12797 // The type of the composite literal.
12798 Type* type_;
12799 // The depth within a list of composite literals within a composite
12800 // literal, when the type is omitted.
12801 int depth_;
12802 // The values to put in the composite literal.
12803 Expression_list* vals_;
12804 // If this is true, then VALS_ is a list of pairs: a key and a
12805 // value. In an array initializer, a missing key will be NULL.
12806 bool has_keys_;
12807 // If this is true, then HAS_KEYS_ is true, and every key is a
12808 // simple identifier.
12809 bool all_are_names_;
12812 // Traversal.
12815 Composite_literal_expression::do_traverse(Traverse* traverse)
12817 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12818 return TRAVERSE_EXIT;
12820 // If this is a struct composite literal with keys, then the keys
12821 // are field names, not expressions. We don't want to traverse them
12822 // in that case. If we do, we can give an erroneous error "variable
12823 // initializer refers to itself." See bug482.go in the testsuite.
12824 if (this->has_keys_ && this->vals_ != NULL)
12826 // The type may not be resolvable at this point.
12827 Type* type = this->type_;
12829 for (int depth = this->depth_; depth > 0; --depth)
12831 if (type->array_type() != NULL)
12832 type = type->array_type()->element_type();
12833 else if (type->map_type() != NULL)
12834 type = type->map_type()->val_type();
12835 else
12837 // This error will be reported during lowering.
12838 return TRAVERSE_CONTINUE;
12842 while (true)
12844 if (type->classification() == Type::TYPE_NAMED)
12845 type = type->named_type()->real_type();
12846 else if (type->classification() == Type::TYPE_FORWARD)
12848 Type* t = type->forwarded();
12849 if (t == type)
12850 break;
12851 type = t;
12853 else
12854 break;
12857 if (type->classification() == Type::TYPE_STRUCT)
12859 Expression_list::iterator p = this->vals_->begin();
12860 while (p != this->vals_->end())
12862 // Skip key.
12863 ++p;
12864 go_assert(p != this->vals_->end());
12865 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12866 return TRAVERSE_EXIT;
12867 ++p;
12869 return TRAVERSE_CONTINUE;
12873 if (this->vals_ != NULL)
12874 return this->vals_->traverse(traverse);
12876 return TRAVERSE_CONTINUE;
12879 // Lower a generic composite literal into a specific version based on
12880 // the type.
12882 Expression*
12883 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12884 Statement_inserter* inserter, int)
12886 Type* type = this->type_;
12888 for (int depth = this->depth_; depth > 0; --depth)
12890 if (type->array_type() != NULL)
12891 type = type->array_type()->element_type();
12892 else if (type->map_type() != NULL)
12893 type = type->map_type()->val_type();
12894 else
12896 if (!type->is_error())
12897 error_at(this->location(),
12898 ("may only omit types within composite literals "
12899 "of slice, array, or map type"));
12900 return Expression::make_error(this->location());
12904 Type *pt = type->points_to();
12905 bool is_pointer = false;
12906 if (pt != NULL)
12908 is_pointer = true;
12909 type = pt;
12912 Expression* ret;
12913 if (type->is_error())
12914 return Expression::make_error(this->location());
12915 else if (type->struct_type() != NULL)
12916 ret = this->lower_struct(gogo, type);
12917 else if (type->array_type() != NULL)
12918 ret = this->lower_array(type);
12919 else if (type->map_type() != NULL)
12920 ret = this->lower_map(gogo, function, inserter, type);
12921 else
12923 error_at(this->location(),
12924 ("expected struct, slice, array, or map type "
12925 "for composite literal"));
12926 return Expression::make_error(this->location());
12929 if (is_pointer)
12930 ret = Expression::make_heap_expression(ret, this->location());
12932 return ret;
12935 // Lower a struct composite literal.
12937 Expression*
12938 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12940 Location location = this->location();
12941 Struct_type* st = type->struct_type();
12942 if (this->vals_ == NULL || !this->has_keys_)
12944 if (this->vals_ != NULL
12945 && !this->vals_->empty()
12946 && type->named_type() != NULL
12947 && type->named_type()->named_object()->package() != NULL)
12949 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12950 pf != st->fields()->end();
12951 ++pf)
12953 if (Gogo::is_hidden_name(pf->field_name()))
12954 error_at(this->location(),
12955 "assignment of unexported field %qs in %qs literal",
12956 Gogo::message_name(pf->field_name()).c_str(),
12957 type->named_type()->message_name().c_str());
12961 return new Struct_construction_expression(type, this->vals_, location);
12964 size_t field_count = st->field_count();
12965 std::vector<Expression*> vals(field_count);
12966 std::vector<int>* traverse_order = new(std::vector<int>);
12967 Expression_list::const_iterator p = this->vals_->begin();
12968 Expression* external_expr = NULL;
12969 const Named_object* external_no = NULL;
12970 while (p != this->vals_->end())
12972 Expression* name_expr = *p;
12974 ++p;
12975 go_assert(p != this->vals_->end());
12976 Expression* val = *p;
12978 ++p;
12980 if (name_expr == NULL)
12982 error_at(val->location(), "mixture of field and value initializers");
12983 return Expression::make_error(location);
12986 bool bad_key = false;
12987 std::string name;
12988 const Named_object* no = NULL;
12989 switch (name_expr->classification())
12991 case EXPRESSION_UNKNOWN_REFERENCE:
12992 name = name_expr->unknown_expression()->name();
12993 break;
12995 case EXPRESSION_CONST_REFERENCE:
12996 no = static_cast<Const_expression*>(name_expr)->named_object();
12997 break;
12999 case EXPRESSION_TYPE:
13001 Type* t = name_expr->type();
13002 Named_type* nt = t->named_type();
13003 if (nt == NULL)
13004 bad_key = true;
13005 else
13006 no = nt->named_object();
13008 break;
13010 case EXPRESSION_VAR_REFERENCE:
13011 no = name_expr->var_expression()->named_object();
13012 break;
13014 case EXPRESSION_FUNC_REFERENCE:
13015 no = name_expr->func_expression()->named_object();
13016 break;
13018 case EXPRESSION_UNARY:
13019 // If there is a local variable around with the same name as
13020 // the field, and this occurs in the closure, then the
13021 // parser may turn the field reference into an indirection
13022 // through the closure. FIXME: This is a mess.
13024 bad_key = true;
13025 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
13026 if (ue->op() == OPERATOR_MULT)
13028 Field_reference_expression* fre =
13029 ue->operand()->field_reference_expression();
13030 if (fre != NULL)
13032 Struct_type* st =
13033 fre->expr()->type()->deref()->struct_type();
13034 if (st != NULL)
13036 const Struct_field* sf = st->field(fre->field_index());
13037 name = sf->field_name();
13039 // See below. FIXME.
13040 if (!Gogo::is_hidden_name(name)
13041 && name[0] >= 'a'
13042 && name[0] <= 'z')
13044 if (gogo->lookup_global(name.c_str()) != NULL)
13045 name = gogo->pack_hidden_name(name, false);
13048 char buf[20];
13049 snprintf(buf, sizeof buf, "%u", fre->field_index());
13050 size_t buflen = strlen(buf);
13051 if (name.compare(name.length() - buflen, buflen, buf)
13052 == 0)
13054 name = name.substr(0, name.length() - buflen);
13055 bad_key = false;
13061 break;
13063 default:
13064 bad_key = true;
13065 break;
13067 if (bad_key)
13069 error_at(name_expr->location(), "expected struct field name");
13070 return Expression::make_error(location);
13073 if (no != NULL)
13075 if (no->package() != NULL && external_expr == NULL)
13077 external_expr = name_expr;
13078 external_no = no;
13081 name = no->name();
13083 // A predefined name won't be packed. If it starts with a
13084 // lower case letter we need to check for that case, because
13085 // the field name will be packed. FIXME.
13086 if (!Gogo::is_hidden_name(name)
13087 && name[0] >= 'a'
13088 && name[0] <= 'z')
13090 Named_object* gno = gogo->lookup_global(name.c_str());
13091 if (gno == no)
13092 name = gogo->pack_hidden_name(name, false);
13096 unsigned int index;
13097 const Struct_field* sf = st->find_local_field(name, &index);
13098 if (sf == NULL)
13100 error_at(name_expr->location(), "unknown field %qs in %qs",
13101 Gogo::message_name(name).c_str(),
13102 (type->named_type() != NULL
13103 ? type->named_type()->message_name().c_str()
13104 : "unnamed struct"));
13105 return Expression::make_error(location);
13107 if (vals[index] != NULL)
13109 error_at(name_expr->location(),
13110 "duplicate value for field %qs in %qs",
13111 Gogo::message_name(name).c_str(),
13112 (type->named_type() != NULL
13113 ? type->named_type()->message_name().c_str()
13114 : "unnamed struct"));
13115 return Expression::make_error(location);
13118 if (type->named_type() != NULL
13119 && type->named_type()->named_object()->package() != NULL
13120 && Gogo::is_hidden_name(sf->field_name()))
13121 error_at(name_expr->location(),
13122 "assignment of unexported field %qs in %qs literal",
13123 Gogo::message_name(sf->field_name()).c_str(),
13124 type->named_type()->message_name().c_str());
13126 vals[index] = val;
13127 traverse_order->push_back(index);
13130 if (!this->all_are_names_)
13132 // This is a weird case like bug462 in the testsuite.
13133 if (external_expr == NULL)
13134 error_at(this->location(), "unknown field in %qs literal",
13135 (type->named_type() != NULL
13136 ? type->named_type()->message_name().c_str()
13137 : "unnamed struct"));
13138 else
13139 error_at(external_expr->location(), "unknown field %qs in %qs",
13140 external_no->message_name().c_str(),
13141 (type->named_type() != NULL
13142 ? type->named_type()->message_name().c_str()
13143 : "unnamed struct"));
13144 return Expression::make_error(location);
13147 Expression_list* list = new Expression_list;
13148 list->reserve(field_count);
13149 for (size_t i = 0; i < field_count; ++i)
13150 list->push_back(vals[i]);
13152 Struct_construction_expression* ret =
13153 new Struct_construction_expression(type, list, location);
13154 ret->set_traverse_order(traverse_order);
13155 return ret;
13158 // Used to sort an index/value array.
13160 class Index_value_compare
13162 public:
13163 bool
13164 operator()(const std::pair<unsigned long, Expression*>& a,
13165 const std::pair<unsigned long, Expression*>& b)
13166 { return a.first < b.first; }
13169 // Lower an array composite literal.
13171 Expression*
13172 Composite_literal_expression::lower_array(Type* type)
13174 Location location = this->location();
13175 if (this->vals_ == NULL || !this->has_keys_)
13176 return this->make_array(type, NULL, this->vals_);
13178 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
13179 indexes->reserve(this->vals_->size());
13180 bool indexes_out_of_order = false;
13181 Expression_list* vals = new Expression_list();
13182 vals->reserve(this->vals_->size());
13183 unsigned long index = 0;
13184 Expression_list::const_iterator p = this->vals_->begin();
13185 while (p != this->vals_->end())
13187 Expression* index_expr = *p;
13189 ++p;
13190 go_assert(p != this->vals_->end());
13191 Expression* val = *p;
13193 ++p;
13195 if (index_expr == NULL)
13197 if (!indexes->empty())
13198 indexes->push_back(index);
13200 else
13202 if (indexes->empty() && !vals->empty())
13204 for (size_t i = 0; i < vals->size(); ++i)
13205 indexes->push_back(i);
13208 Numeric_constant nc;
13209 if (!index_expr->numeric_constant_value(&nc))
13211 error_at(index_expr->location(),
13212 "index expression is not integer constant");
13213 return Expression::make_error(location);
13216 switch (nc.to_unsigned_long(&index))
13218 case Numeric_constant::NC_UL_VALID:
13219 break;
13220 case Numeric_constant::NC_UL_NOTINT:
13221 error_at(index_expr->location(),
13222 "index expression is not integer constant");
13223 return Expression::make_error(location);
13224 case Numeric_constant::NC_UL_NEGATIVE:
13225 error_at(index_expr->location(), "index expression is negative");
13226 return Expression::make_error(location);
13227 case Numeric_constant::NC_UL_BIG:
13228 error_at(index_expr->location(), "index value overflow");
13229 return Expression::make_error(location);
13230 default:
13231 go_unreachable();
13234 Named_type* ntype = Type::lookup_integer_type("int");
13235 Integer_type* inttype = ntype->integer_type();
13236 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
13237 && index >> (inttype->bits() - 1) != 0)
13239 error_at(index_expr->location(), "index value overflow");
13240 return Expression::make_error(location);
13243 if (std::find(indexes->begin(), indexes->end(), index)
13244 != indexes->end())
13246 error_at(index_expr->location(), "duplicate value for index %lu",
13247 index);
13248 return Expression::make_error(location);
13251 if (!indexes->empty() && index < indexes->back())
13252 indexes_out_of_order = true;
13254 indexes->push_back(index);
13257 vals->push_back(val);
13259 ++index;
13262 if (indexes->empty())
13264 delete indexes;
13265 indexes = NULL;
13268 if (indexes_out_of_order)
13270 typedef std::vector<std::pair<unsigned long, Expression*> > V;
13272 V v;
13273 v.reserve(indexes->size());
13274 std::vector<unsigned long>::const_iterator pi = indexes->begin();
13275 for (Expression_list::const_iterator pe = vals->begin();
13276 pe != vals->end();
13277 ++pe, ++pi)
13278 v.push_back(std::make_pair(*pi, *pe));
13280 std::sort(v.begin(), v.end(), Index_value_compare());
13282 delete indexes;
13283 delete vals;
13284 indexes = new std::vector<unsigned long>();
13285 indexes->reserve(v.size());
13286 vals = new Expression_list();
13287 vals->reserve(v.size());
13289 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
13291 indexes->push_back(p->first);
13292 vals->push_back(p->second);
13296 return this->make_array(type, indexes, vals);
13299 // Actually build the array composite literal. This handles
13300 // [...]{...}.
13302 Expression*
13303 Composite_literal_expression::make_array(
13304 Type* type,
13305 const std::vector<unsigned long>* indexes,
13306 Expression_list* vals)
13308 Location location = this->location();
13309 Array_type* at = type->array_type();
13311 if (at->length() != NULL && at->length()->is_nil_expression())
13313 size_t size;
13314 if (vals == NULL)
13315 size = 0;
13316 else if (indexes != NULL)
13317 size = indexes->back() + 1;
13318 else
13320 size = vals->size();
13321 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13322 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13323 && size >> (it->bits() - 1) != 0)
13325 error_at(location, "too many elements in composite literal");
13326 return Expression::make_error(location);
13330 mpz_t vlen;
13331 mpz_init_set_ui(vlen, size);
13332 Expression* elen = Expression::make_integer(&vlen, NULL, location);
13333 mpz_clear(vlen);
13334 at = Type::make_array_type(at->element_type(), elen);
13335 type = at;
13337 else if (at->length() != NULL
13338 && !at->length()->is_error_expression()
13339 && this->vals_ != NULL)
13341 Numeric_constant nc;
13342 unsigned long val;
13343 if (at->length()->numeric_constant_value(&nc)
13344 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13346 if (indexes == NULL)
13348 if (this->vals_->size() > val)
13350 error_at(location, "too many elements in composite literal");
13351 return Expression::make_error(location);
13354 else
13356 unsigned long max = indexes->back();
13357 if (max >= val)
13359 error_at(location,
13360 ("some element keys in composite literal "
13361 "are out of range"));
13362 return Expression::make_error(location);
13368 if (at->length() != NULL)
13369 return new Fixed_array_construction_expression(type, indexes, vals,
13370 location);
13371 else
13372 return new Slice_construction_expression(type, indexes, vals, location);
13375 // Lower a map composite literal.
13377 Expression*
13378 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13379 Statement_inserter* inserter,
13380 Type* type)
13382 Location location = this->location();
13383 if (this->vals_ != NULL)
13385 if (!this->has_keys_)
13387 error_at(location, "map composite literal must have keys");
13388 return Expression::make_error(location);
13391 for (Expression_list::iterator p = this->vals_->begin();
13392 p != this->vals_->end();
13393 p += 2)
13395 if (*p == NULL)
13397 ++p;
13398 error_at((*p)->location(),
13399 "map composite literal must have keys for every value");
13400 return Expression::make_error(location);
13402 // Make sure we have lowered the key; it may not have been
13403 // lowered in order to handle keys for struct composite
13404 // literals. Lower it now to get the right error message.
13405 if ((*p)->unknown_expression() != NULL)
13407 (*p)->unknown_expression()->clear_is_composite_literal_key();
13408 gogo->lower_expression(function, inserter, &*p);
13409 go_assert((*p)->is_error_expression());
13410 return Expression::make_error(location);
13415 return new Map_construction_expression(type, this->vals_, location);
13418 // Dump ast representation for a composite literal expression.
13420 void
13421 Composite_literal_expression::do_dump_expression(
13422 Ast_dump_context* ast_dump_context) const
13424 ast_dump_context->ostream() << "composite(";
13425 ast_dump_context->dump_type(this->type_);
13426 ast_dump_context->ostream() << ", {";
13427 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13428 ast_dump_context->ostream() << "})";
13431 // Make a composite literal expression.
13433 Expression*
13434 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13435 Expression_list* vals, bool all_are_names,
13436 Location location)
13438 return new Composite_literal_expression(type, depth, has_keys, vals,
13439 all_are_names, location);
13442 // Return whether this expression is a composite literal.
13444 bool
13445 Expression::is_composite_literal() const
13447 switch (this->classification_)
13449 case EXPRESSION_COMPOSITE_LITERAL:
13450 case EXPRESSION_STRUCT_CONSTRUCTION:
13451 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13452 case EXPRESSION_SLICE_CONSTRUCTION:
13453 case EXPRESSION_MAP_CONSTRUCTION:
13454 return true;
13455 default:
13456 return false;
13460 // Return whether this expression is a composite literal which is not
13461 // constant.
13463 bool
13464 Expression::is_nonconstant_composite_literal() const
13466 switch (this->classification_)
13468 case EXPRESSION_STRUCT_CONSTRUCTION:
13470 const Struct_construction_expression *psce =
13471 static_cast<const Struct_construction_expression*>(this);
13472 return !psce->is_constant_struct();
13474 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13476 const Fixed_array_construction_expression *pace =
13477 static_cast<const Fixed_array_construction_expression*>(this);
13478 return !pace->is_constant_array();
13480 case EXPRESSION_SLICE_CONSTRUCTION:
13482 const Slice_construction_expression *pace =
13483 static_cast<const Slice_construction_expression*>(this);
13484 return !pace->is_constant_array();
13486 case EXPRESSION_MAP_CONSTRUCTION:
13487 return true;
13488 default:
13489 return false;
13493 // Return true if this is a variable or temporary_variable.
13495 bool
13496 Expression::is_variable() const
13498 switch (this->classification_)
13500 case EXPRESSION_VAR_REFERENCE:
13501 case EXPRESSION_TEMPORARY_REFERENCE:
13502 case EXPRESSION_SET_AND_USE_TEMPORARY:
13503 return true;
13504 default:
13505 return false;
13509 // Return true if this is a reference to a local variable.
13511 bool
13512 Expression::is_local_variable() const
13514 const Var_expression* ve = this->var_expression();
13515 if (ve == NULL)
13516 return false;
13517 const Named_object* no = ve->named_object();
13518 return (no->is_result_variable()
13519 || (no->is_variable() && !no->var_value()->is_global()));
13522 // Class Type_guard_expression.
13524 // Traversal.
13527 Type_guard_expression::do_traverse(Traverse* traverse)
13529 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13530 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13531 return TRAVERSE_EXIT;
13532 return TRAVERSE_CONTINUE;
13535 Expression*
13536 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13537 Statement_inserter* inserter)
13539 if (!this->expr_->is_variable())
13541 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13542 this->location());
13543 inserter->insert(temp);
13544 this->expr_ =
13545 Expression::make_temporary_reference(temp, this->location());
13547 return this;
13550 // Check types of a type guard expression. The expression must have
13551 // an interface type, but the actual type conversion is checked at run
13552 // time.
13554 void
13555 Type_guard_expression::do_check_types(Gogo*)
13557 Type* expr_type = this->expr_->type();
13558 if (expr_type->interface_type() == NULL)
13560 if (!expr_type->is_error() && !this->type_->is_error())
13561 this->report_error(_("type assertion only valid for interface types"));
13562 this->set_is_error();
13564 else if (this->type_->interface_type() == NULL)
13566 std::string reason;
13567 if (!expr_type->interface_type()->implements_interface(this->type_,
13568 &reason))
13570 if (!this->type_->is_error())
13572 if (reason.empty())
13573 this->report_error(_("impossible type assertion: "
13574 "type does not implement interface"));
13575 else
13576 error_at(this->location(),
13577 ("impossible type assertion: "
13578 "type does not implement interface (%s)"),
13579 reason.c_str());
13581 this->set_is_error();
13586 // Return the backend representation for a type guard expression.
13588 Bexpression*
13589 Type_guard_expression::do_get_backend(Translate_context* context)
13591 Expression* conversion;
13592 if (this->type_->interface_type() != NULL)
13593 conversion =
13594 Expression::convert_interface_to_interface(this->type_, this->expr_,
13595 true, this->location());
13596 else
13597 conversion =
13598 Expression::convert_for_assignment(context->gogo(), this->type_,
13599 this->expr_, this->location());
13601 return conversion->get_backend(context);
13604 // Dump ast representation for a type guard expression.
13606 void
13607 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13608 const
13610 this->expr_->dump_expression(ast_dump_context);
13611 ast_dump_context->ostream() << ".";
13612 ast_dump_context->dump_type(this->type_);
13615 // Make a type guard expression.
13617 Expression*
13618 Expression::make_type_guard(Expression* expr, Type* type,
13619 Location location)
13621 return new Type_guard_expression(expr, type, location);
13624 // Class Heap_expression.
13626 // When you take the address of an escaping expression, it is allocated
13627 // on the heap. This class implements that.
13629 class Heap_expression : public Expression
13631 public:
13632 Heap_expression(Expression* expr, Location location)
13633 : Expression(EXPRESSION_HEAP, location),
13634 expr_(expr)
13637 protected:
13639 do_traverse(Traverse* traverse)
13640 { return Expression::traverse(&this->expr_, traverse); }
13642 Type*
13643 do_type()
13644 { return Type::make_pointer_type(this->expr_->type()); }
13646 void
13647 do_determine_type(const Type_context*)
13648 { this->expr_->determine_type_no_context(); }
13650 Expression*
13651 do_copy()
13653 return Expression::make_heap_expression(this->expr_->copy(),
13654 this->location());
13657 Bexpression*
13658 do_get_backend(Translate_context*);
13660 // We only export global objects, and the parser does not generate
13661 // this in global scope.
13662 void
13663 do_export(Export*) const
13664 { go_unreachable(); }
13666 void
13667 do_dump_expression(Ast_dump_context*) const;
13669 private:
13670 // The expression which is being put on the heap.
13671 Expression* expr_;
13674 // Return the backend representation for allocating an expression on the heap.
13676 Bexpression*
13677 Heap_expression::do_get_backend(Translate_context* context)
13679 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
13680 return context->backend()->error_expression();
13682 Location loc = this->location();
13683 Gogo* gogo = context->gogo();
13684 Btype* btype = this->type()->get_backend(gogo);
13685 Bexpression* space = Expression::make_allocation(this->expr_->type(),
13686 loc)->get_backend(context);
13688 Bstatement* decl;
13689 Named_object* fn = context->function();
13690 go_assert(fn != NULL);
13691 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13692 Bvariable* space_temp =
13693 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13694 space, true, loc, &decl);
13695 space = gogo->backend()->var_expression(space_temp, loc);
13696 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13697 Bexpression* ref =
13698 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
13700 Bexpression* bexpr = this->expr_->get_backend(context);
13701 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13702 decl = gogo->backend()->compound_statement(decl, assn);
13703 space = gogo->backend()->var_expression(space_temp, loc);
13704 return gogo->backend()->compound_expression(decl, space, loc);
13707 // Dump ast representation for a heap expression.
13709 void
13710 Heap_expression::do_dump_expression(
13711 Ast_dump_context* ast_dump_context) const
13713 ast_dump_context->ostream() << "&(";
13714 ast_dump_context->dump_expression(this->expr_);
13715 ast_dump_context->ostream() << ")";
13718 // Allocate an expression on the heap.
13720 Expression*
13721 Expression::make_heap_expression(Expression* expr, Location location)
13723 return new Heap_expression(expr, location);
13726 // Class Receive_expression.
13728 // Return the type of a receive expression.
13730 Type*
13731 Receive_expression::do_type()
13733 Channel_type* channel_type = this->channel_->type()->channel_type();
13734 if (channel_type == NULL)
13735 return Type::make_error_type();
13736 return channel_type->element_type();
13739 // Check types for a receive expression.
13741 void
13742 Receive_expression::do_check_types(Gogo*)
13744 Type* type = this->channel_->type();
13745 if (type->is_error())
13747 this->set_is_error();
13748 return;
13750 if (type->channel_type() == NULL)
13752 this->report_error(_("expected channel"));
13753 return;
13755 if (!type->channel_type()->may_receive())
13757 this->report_error(_("invalid receive on send-only channel"));
13758 return;
13762 // Flattening for receive expressions creates a temporary variable to store
13763 // received data in for receives.
13765 Expression*
13766 Receive_expression::do_flatten(Gogo*, Named_object*,
13767 Statement_inserter* inserter)
13769 Channel_type* channel_type = this->channel_->type()->channel_type();
13770 if (channel_type == NULL)
13772 go_assert(saw_errors());
13773 return this;
13776 Type* element_type = channel_type->element_type();
13777 if (this->temp_receiver_ == NULL)
13779 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13780 this->location());
13781 this->temp_receiver_->set_is_address_taken();
13782 inserter->insert(this->temp_receiver_);
13785 return this;
13788 // Get the backend representation for a receive expression.
13790 Bexpression*
13791 Receive_expression::do_get_backend(Translate_context* context)
13793 Location loc = this->location();
13795 Channel_type* channel_type = this->channel_->type()->channel_type();
13796 if (channel_type == NULL)
13798 go_assert(this->channel_->type()->is_error());
13799 return context->backend()->error_expression();
13801 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13803 Expression* recv_ref =
13804 Expression::make_temporary_reference(this->temp_receiver_, loc);
13805 Expression* recv_addr =
13806 Expression::make_temporary_reference(this->temp_receiver_, loc);
13807 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13808 Expression* recv =
13809 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13810 td, this->channel_, recv_addr);
13811 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
13814 // Dump ast representation for a receive expression.
13816 void
13817 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13819 ast_dump_context->ostream() << " <- " ;
13820 ast_dump_context->dump_expression(channel_);
13823 // Make a receive expression.
13825 Receive_expression*
13826 Expression::make_receive(Expression* channel, Location location)
13828 return new Receive_expression(channel, location);
13831 // An expression which evaluates to a pointer to the type descriptor
13832 // of a type.
13834 class Type_descriptor_expression : public Expression
13836 public:
13837 Type_descriptor_expression(Type* type, Location location)
13838 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13839 type_(type)
13842 protected:
13843 Type*
13844 do_type()
13845 { return Type::make_type_descriptor_ptr_type(); }
13847 bool
13848 do_is_immutable() const
13849 { return true; }
13851 void
13852 do_determine_type(const Type_context*)
13855 Expression*
13856 do_copy()
13857 { return this; }
13859 Bexpression*
13860 do_get_backend(Translate_context* context)
13862 return this->type_->type_descriptor_pointer(context->gogo(),
13863 this->location());
13866 void
13867 do_dump_expression(Ast_dump_context*) const;
13869 private:
13870 // The type for which this is the descriptor.
13871 Type* type_;
13874 // Dump ast representation for a type descriptor expression.
13876 void
13877 Type_descriptor_expression::do_dump_expression(
13878 Ast_dump_context* ast_dump_context) const
13880 ast_dump_context->dump_type(this->type_);
13883 // Make a type descriptor expression.
13885 Expression*
13886 Expression::make_type_descriptor(Type* type, Location location)
13888 return new Type_descriptor_expression(type, location);
13891 // An expression which evaluates to some characteristic of a type.
13892 // This is only used to initialize fields of a type descriptor. Using
13893 // a new expression class is slightly inefficient but gives us a good
13894 // separation between the frontend and the middle-end with regard to
13895 // how types are laid out.
13897 class Type_info_expression : public Expression
13899 public:
13900 Type_info_expression(Type* type, Type_info type_info)
13901 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13902 type_(type), type_info_(type_info)
13905 protected:
13906 bool
13907 do_is_immutable() const
13908 { return true; }
13910 Type*
13911 do_type();
13913 void
13914 do_determine_type(const Type_context*)
13917 Expression*
13918 do_copy()
13919 { return this; }
13921 Bexpression*
13922 do_get_backend(Translate_context* context);
13924 void
13925 do_dump_expression(Ast_dump_context*) const;
13927 private:
13928 // The type for which we are getting information.
13929 Type* type_;
13930 // What information we want.
13931 Type_info type_info_;
13934 // The type is chosen to match what the type descriptor struct
13935 // expects.
13937 Type*
13938 Type_info_expression::do_type()
13940 switch (this->type_info_)
13942 case TYPE_INFO_SIZE:
13943 return Type::lookup_integer_type("uintptr");
13944 case TYPE_INFO_ALIGNMENT:
13945 case TYPE_INFO_FIELD_ALIGNMENT:
13946 return Type::lookup_integer_type("uint8");
13947 default:
13948 go_unreachable();
13952 // Return the backend representation for type information.
13954 Bexpression*
13955 Type_info_expression::do_get_backend(Translate_context* context)
13957 Btype* btype = this->type_->get_backend(context->gogo());
13958 Gogo* gogo = context->gogo();
13959 size_t val;
13960 switch (this->type_info_)
13962 case TYPE_INFO_SIZE:
13963 val = gogo->backend()->type_size(btype);
13964 break;
13965 case TYPE_INFO_ALIGNMENT:
13966 val = gogo->backend()->type_alignment(btype);
13967 break;
13968 case TYPE_INFO_FIELD_ALIGNMENT:
13969 val = gogo->backend()->type_field_alignment(btype);
13970 break;
13971 default:
13972 go_unreachable();
13974 mpz_t cst;
13975 mpz_init_set_ui(cst, val);
13976 Btype* int_btype = this->type()->get_backend(gogo);
13977 Bexpression* ret =
13978 gogo->backend()->integer_constant_expression(int_btype, cst);
13979 mpz_clear(cst);
13980 return ret;
13983 // Dump ast representation for a type info expression.
13985 void
13986 Type_info_expression::do_dump_expression(
13987 Ast_dump_context* ast_dump_context) const
13989 ast_dump_context->ostream() << "typeinfo(";
13990 ast_dump_context->dump_type(this->type_);
13991 ast_dump_context->ostream() << ",";
13992 ast_dump_context->ostream() <<
13993 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13994 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13995 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13996 : "unknown");
13997 ast_dump_context->ostream() << ")";
14000 // Make a type info expression.
14002 Expression*
14003 Expression::make_type_info(Type* type, Type_info type_info)
14005 return new Type_info_expression(type, type_info);
14008 // An expression that evaluates to some characteristic of a slice.
14009 // This is used when indexing, bound-checking, or nil checking a slice.
14011 class Slice_info_expression : public Expression
14013 public:
14014 Slice_info_expression(Expression* slice, Slice_info slice_info,
14015 Location location)
14016 : Expression(EXPRESSION_SLICE_INFO, location),
14017 slice_(slice), slice_info_(slice_info)
14020 protected:
14021 Type*
14022 do_type();
14024 void
14025 do_determine_type(const Type_context*)
14028 Expression*
14029 do_copy()
14031 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
14032 this->location());
14035 Bexpression*
14036 do_get_backend(Translate_context* context);
14038 void
14039 do_dump_expression(Ast_dump_context*) const;
14041 void
14042 do_issue_nil_check()
14043 { this->slice_->issue_nil_check(); }
14045 private:
14046 // The slice for which we are getting information.
14047 Expression* slice_;
14048 // What information we want.
14049 Slice_info slice_info_;
14052 // Return the type of the slice info.
14054 Type*
14055 Slice_info_expression::do_type()
14057 switch (this->slice_info_)
14059 case SLICE_INFO_VALUE_POINTER:
14060 return Type::make_pointer_type(
14061 this->slice_->type()->array_type()->element_type());
14062 case SLICE_INFO_LENGTH:
14063 case SLICE_INFO_CAPACITY:
14064 return Type::lookup_integer_type("int");
14065 default:
14066 go_unreachable();
14070 // Return the backend information for slice information.
14072 Bexpression*
14073 Slice_info_expression::do_get_backend(Translate_context* context)
14075 Gogo* gogo = context->gogo();
14076 Bexpression* bslice = this->slice_->get_backend(context);
14077 switch (this->slice_info_)
14079 case SLICE_INFO_VALUE_POINTER:
14080 case SLICE_INFO_LENGTH:
14081 case SLICE_INFO_CAPACITY:
14082 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
14083 this->location());
14084 break;
14085 default:
14086 go_unreachable();
14090 // Dump ast representation for a type info expression.
14092 void
14093 Slice_info_expression::do_dump_expression(
14094 Ast_dump_context* ast_dump_context) const
14096 ast_dump_context->ostream() << "sliceinfo(";
14097 this->slice_->dump_expression(ast_dump_context);
14098 ast_dump_context->ostream() << ",";
14099 ast_dump_context->ostream() <<
14100 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
14101 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
14102 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
14103 : "unknown");
14104 ast_dump_context->ostream() << ")";
14107 // Make a slice info expression.
14109 Expression*
14110 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
14111 Location location)
14113 return new Slice_info_expression(slice, slice_info, location);
14116 // An expression that represents a slice value: a struct with value pointer,
14117 // length, and capacity fields.
14119 class Slice_value_expression : public Expression
14121 public:
14122 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
14123 Expression* cap, Location location)
14124 : Expression(EXPRESSION_SLICE_VALUE, location),
14125 type_(type), valptr_(valptr), len_(len), cap_(cap)
14128 protected:
14130 do_traverse(Traverse*);
14132 Type*
14133 do_type()
14134 { return this->type_; }
14136 void
14137 do_determine_type(const Type_context*)
14138 { go_unreachable(); }
14140 Expression*
14141 do_copy()
14143 return new Slice_value_expression(this->type_, this->valptr_->copy(),
14144 this->len_->copy(), this->cap_->copy(),
14145 this->location());
14148 Bexpression*
14149 do_get_backend(Translate_context* context);
14151 void
14152 do_dump_expression(Ast_dump_context*) const;
14154 private:
14155 // The type of the slice value.
14156 Type* type_;
14157 // The pointer to the values in the slice.
14158 Expression* valptr_;
14159 // The length of the slice.
14160 Expression* len_;
14161 // The capacity of the slice.
14162 Expression* cap_;
14166 Slice_value_expression::do_traverse(Traverse* traverse)
14168 if (Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
14169 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
14170 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
14171 return TRAVERSE_EXIT;
14172 return TRAVERSE_CONTINUE;
14175 Bexpression*
14176 Slice_value_expression::do_get_backend(Translate_context* context)
14178 std::vector<Bexpression*> vals(3);
14179 vals[0] = this->valptr_->get_backend(context);
14180 vals[1] = this->len_->get_backend(context);
14181 vals[2] = this->cap_->get_backend(context);
14183 Gogo* gogo = context->gogo();
14184 Btype* btype = this->type_->get_backend(gogo);
14185 return gogo->backend()->constructor_expression(btype, vals, this->location());
14188 void
14189 Slice_value_expression::do_dump_expression(
14190 Ast_dump_context* ast_dump_context) const
14192 ast_dump_context->ostream() << "slicevalue(";
14193 ast_dump_context->ostream() << "values: ";
14194 this->valptr_->dump_expression(ast_dump_context);
14195 ast_dump_context->ostream() << ", length: ";
14196 this->len_->dump_expression(ast_dump_context);
14197 ast_dump_context->ostream() << ", capacity: ";
14198 this->cap_->dump_expression(ast_dump_context);
14199 ast_dump_context->ostream() << ")";
14202 Expression*
14203 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
14204 Expression* cap, Location location)
14206 go_assert(at->is_slice_type());
14207 return new Slice_value_expression(at, valptr, len, cap, location);
14210 // An expression that evaluates to some characteristic of a non-empty interface.
14211 // This is used to access the method table or underlying object of an interface.
14213 class Interface_info_expression : public Expression
14215 public:
14216 Interface_info_expression(Expression* iface, Interface_info iface_info,
14217 Location location)
14218 : Expression(EXPRESSION_INTERFACE_INFO, location),
14219 iface_(iface), iface_info_(iface_info)
14222 protected:
14223 Type*
14224 do_type();
14226 void
14227 do_determine_type(const Type_context*)
14230 Expression*
14231 do_copy()
14233 return new Interface_info_expression(this->iface_->copy(),
14234 this->iface_info_, this->location());
14237 Bexpression*
14238 do_get_backend(Translate_context* context);
14240 void
14241 do_dump_expression(Ast_dump_context*) const;
14243 void
14244 do_issue_nil_check()
14245 { this->iface_->issue_nil_check(); }
14247 private:
14248 // The interface for which we are getting information.
14249 Expression* iface_;
14250 // What information we want.
14251 Interface_info iface_info_;
14254 // Return the type of the interface info.
14256 Type*
14257 Interface_info_expression::do_type()
14259 switch (this->iface_info_)
14261 case INTERFACE_INFO_METHODS:
14263 Type* pdt = Type::make_type_descriptor_ptr_type();
14264 if (this->iface_->type()->interface_type()->is_empty())
14265 return pdt;
14267 Location loc = this->location();
14268 Struct_field_list* sfl = new Struct_field_list();
14269 sfl->push_back(
14270 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
14272 Interface_type* itype = this->iface_->type()->interface_type();
14273 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14274 p != itype->methods()->end();
14275 ++p)
14277 Function_type* ft = p->type()->function_type();
14278 go_assert(ft->receiver() == NULL);
14280 const Typed_identifier_list* params = ft->parameters();
14281 Typed_identifier_list* mparams = new Typed_identifier_list();
14282 if (params != NULL)
14283 mparams->reserve(params->size() + 1);
14284 Type* vt = Type::make_pointer_type(Type::make_void_type());
14285 mparams->push_back(Typed_identifier("", vt, ft->location()));
14286 if (params != NULL)
14288 for (Typed_identifier_list::const_iterator pp = params->begin();
14289 pp != params->end();
14290 ++pp)
14291 mparams->push_back(*pp);
14294 Typed_identifier_list* mresults = (ft->results() == NULL
14295 ? NULL
14296 : ft->results()->copy());
14297 Backend_function_type* mft =
14298 Type::make_backend_function_type(NULL, mparams, mresults,
14299 ft->location());
14301 std::string fname = Gogo::unpack_hidden_name(p->name());
14302 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14305 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14307 case INTERFACE_INFO_OBJECT:
14308 return Type::make_pointer_type(Type::make_void_type());
14309 default:
14310 go_unreachable();
14314 // Return the backend representation for interface information.
14316 Bexpression*
14317 Interface_info_expression::do_get_backend(Translate_context* context)
14319 Gogo* gogo = context->gogo();
14320 Bexpression* biface = this->iface_->get_backend(context);
14321 switch (this->iface_info_)
14323 case INTERFACE_INFO_METHODS:
14324 case INTERFACE_INFO_OBJECT:
14325 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14326 this->location());
14327 break;
14328 default:
14329 go_unreachable();
14333 // Dump ast representation for an interface info expression.
14335 void
14336 Interface_info_expression::do_dump_expression(
14337 Ast_dump_context* ast_dump_context) const
14339 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14340 ast_dump_context->ostream() << "interfaceinfo(";
14341 this->iface_->dump_expression(ast_dump_context);
14342 ast_dump_context->ostream() << ",";
14343 ast_dump_context->ostream() <<
14344 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14345 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14346 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14347 : "unknown");
14348 ast_dump_context->ostream() << ")";
14351 // Make an interface info expression.
14353 Expression*
14354 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14355 Location location)
14357 return new Interface_info_expression(iface, iface_info, location);
14360 // An expression that represents an interface value. The first field is either
14361 // a type descriptor for an empty interface or a pointer to the interface method
14362 // table for a non-empty interface. The second field is always the object.
14364 class Interface_value_expression : public Expression
14366 public:
14367 Interface_value_expression(Type* type, Expression* first_field,
14368 Expression* obj, Location location)
14369 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14370 type_(type), first_field_(first_field), obj_(obj)
14373 protected:
14375 do_traverse(Traverse*);
14377 Type*
14378 do_type()
14379 { return this->type_; }
14381 void
14382 do_determine_type(const Type_context*)
14383 { go_unreachable(); }
14385 Expression*
14386 do_copy()
14388 return new Interface_value_expression(this->type_,
14389 this->first_field_->copy(),
14390 this->obj_->copy(), this->location());
14393 Bexpression*
14394 do_get_backend(Translate_context* context);
14396 void
14397 do_dump_expression(Ast_dump_context*) const;
14399 private:
14400 // The type of the interface value.
14401 Type* type_;
14402 // The first field of the interface (either a type descriptor or a pointer
14403 // to the method table.
14404 Expression* first_field_;
14405 // The underlying object of the interface.
14406 Expression* obj_;
14410 Interface_value_expression::do_traverse(Traverse* traverse)
14412 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14413 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14414 return TRAVERSE_EXIT;
14415 return TRAVERSE_CONTINUE;
14418 Bexpression*
14419 Interface_value_expression::do_get_backend(Translate_context* context)
14421 std::vector<Bexpression*> vals(2);
14422 vals[0] = this->first_field_->get_backend(context);
14423 vals[1] = this->obj_->get_backend(context);
14425 Gogo* gogo = context->gogo();
14426 Btype* btype = this->type_->get_backend(gogo);
14427 return gogo->backend()->constructor_expression(btype, vals, this->location());
14430 void
14431 Interface_value_expression::do_dump_expression(
14432 Ast_dump_context* ast_dump_context) const
14434 ast_dump_context->ostream() << "interfacevalue(";
14435 ast_dump_context->ostream() <<
14436 (this->type_->interface_type()->is_empty()
14437 ? "type_descriptor: "
14438 : "methods: ");
14439 this->first_field_->dump_expression(ast_dump_context);
14440 ast_dump_context->ostream() << ", object: ";
14441 this->obj_->dump_expression(ast_dump_context);
14442 ast_dump_context->ostream() << ")";
14445 Expression*
14446 Expression::make_interface_value(Type* type, Expression* first_value,
14447 Expression* object, Location location)
14449 return new Interface_value_expression(type, first_value, object, location);
14452 // An interface method table for a pair of types: an interface type and a type
14453 // that implements that interface.
14455 class Interface_mtable_expression : public Expression
14457 public:
14458 Interface_mtable_expression(Interface_type* itype, Type* type,
14459 bool is_pointer, Location location)
14460 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14461 itype_(itype), type_(type), is_pointer_(is_pointer),
14462 method_table_type_(NULL), bvar_(NULL)
14465 protected:
14467 do_traverse(Traverse*);
14469 Type*
14470 do_type();
14472 bool
14473 is_immutable() const
14474 { return true; }
14476 void
14477 do_determine_type(const Type_context*)
14478 { go_unreachable(); }
14480 Expression*
14481 do_copy()
14483 return new Interface_mtable_expression(this->itype_, this->type_,
14484 this->is_pointer_, this->location());
14487 bool
14488 do_is_addressable() const
14489 { return true; }
14491 Bexpression*
14492 do_get_backend(Translate_context* context);
14494 void
14495 do_dump_expression(Ast_dump_context*) const;
14497 private:
14498 // The interface type for which the methods are defined.
14499 Interface_type* itype_;
14500 // The type to construct the interface method table for.
14501 Type* type_;
14502 // Whether this table contains the method set for the receiver type or the
14503 // pointer receiver type.
14504 bool is_pointer_;
14505 // The type of the method table.
14506 Type* method_table_type_;
14507 // The backend variable that refers to the interface method table.
14508 Bvariable* bvar_;
14512 Interface_mtable_expression::do_traverse(Traverse* traverse)
14514 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14515 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14516 return TRAVERSE_EXIT;
14517 return TRAVERSE_CONTINUE;
14520 Type*
14521 Interface_mtable_expression::do_type()
14523 if (this->method_table_type_ != NULL)
14524 return this->method_table_type_;
14526 const Typed_identifier_list* interface_methods = this->itype_->methods();
14527 go_assert(!interface_methods->empty());
14529 Struct_field_list* sfl = new Struct_field_list;
14530 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14531 this->location());
14532 sfl->push_back(Struct_field(tid));
14533 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14534 p != interface_methods->end();
14535 ++p)
14536 sfl->push_back(Struct_field(*p));
14537 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14538 return this->method_table_type_;
14541 Bexpression*
14542 Interface_mtable_expression::do_get_backend(Translate_context* context)
14544 Gogo* gogo = context->gogo();
14545 Location loc = Linemap::predeclared_location();
14546 if (this->bvar_ != NULL)
14547 return gogo->backend()->var_expression(this->bvar_, this->location());
14549 const Typed_identifier_list* interface_methods = this->itype_->methods();
14550 go_assert(!interface_methods->empty());
14552 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14553 + this->itype_->mangled_name(gogo)
14554 + "__"
14555 + this->type_->mangled_name(gogo));
14557 // See whether this interface has any hidden methods.
14558 bool has_hidden_methods = false;
14559 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14560 p != interface_methods->end();
14561 ++p)
14563 if (Gogo::is_hidden_name(p->name()))
14565 has_hidden_methods = true;
14566 break;
14570 // We already know that the named type is convertible to the
14571 // interface. If the interface has hidden methods, and the named
14572 // type is defined in a different package, then the interface
14573 // conversion table will be defined by that other package.
14574 if (has_hidden_methods
14575 && this->type_->named_type() != NULL
14576 && this->type_->named_type()->named_object()->package() != NULL)
14578 Btype* btype = this->type()->get_backend(gogo);
14579 this->bvar_ =
14580 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14581 return gogo->backend()->var_expression(this->bvar_, this->location());
14584 // The first element is the type descriptor.
14585 Type* td_type;
14586 if (!this->is_pointer_)
14587 td_type = this->type_;
14588 else
14589 td_type = Type::make_pointer_type(this->type_);
14591 // Build an interface method table for a type: a type descriptor followed by a
14592 // list of function pointers, one for each interface method. This is used for
14593 // interfaces.
14594 Expression_list* svals = new Expression_list();
14595 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14597 Named_type* nt = this->type_->named_type();
14598 Struct_type* st = this->type_->struct_type();
14599 go_assert(nt != NULL || st != NULL);
14601 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14602 p != interface_methods->end();
14603 ++p)
14605 bool is_ambiguous;
14606 Method* m;
14607 if (nt != NULL)
14608 m = nt->method_function(p->name(), &is_ambiguous);
14609 else
14610 m = st->method_function(p->name(), &is_ambiguous);
14611 go_assert(m != NULL);
14612 Named_object* no = m->named_object();
14614 go_assert(no->is_function() || no->is_function_declaration());
14615 svals->push_back(Expression::make_func_code_reference(no, loc));
14618 Btype* btype = this->type()->get_backend(gogo);
14619 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14620 svals, loc);
14621 Bexpression* ctor = mtable->get_backend(context);
14623 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14624 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14625 !is_public, btype, loc);
14626 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14627 !is_public, btype, loc, ctor);
14628 return gogo->backend()->var_expression(this->bvar_, loc);
14631 void
14632 Interface_mtable_expression::do_dump_expression(
14633 Ast_dump_context* ast_dump_context) const
14635 ast_dump_context->ostream() << "__go_"
14636 << (this->is_pointer_ ? "pimt__" : "imt_");
14637 ast_dump_context->dump_type(this->itype_);
14638 ast_dump_context->ostream() << "__";
14639 ast_dump_context->dump_type(this->type_);
14642 Expression*
14643 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14644 bool is_pointer, Location location)
14646 return new Interface_mtable_expression(itype, type, is_pointer, location);
14649 // An expression which evaluates to the offset of a field within a
14650 // struct. This, like Type_info_expression, q.v., is only used to
14651 // initialize fields of a type descriptor.
14653 class Struct_field_offset_expression : public Expression
14655 public:
14656 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14657 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14658 Linemap::predeclared_location()),
14659 type_(type), field_(field)
14662 protected:
14663 bool
14664 do_is_immutable() const
14665 { return true; }
14667 Type*
14668 do_type()
14669 { return Type::lookup_integer_type("uintptr"); }
14671 void
14672 do_determine_type(const Type_context*)
14675 Expression*
14676 do_copy()
14677 { return this; }
14679 Bexpression*
14680 do_get_backend(Translate_context* context);
14682 void
14683 do_dump_expression(Ast_dump_context*) const;
14685 private:
14686 // The type of the struct.
14687 Struct_type* type_;
14688 // The field.
14689 const Struct_field* field_;
14692 // Return the backend representation for a struct field offset.
14694 Bexpression*
14695 Struct_field_offset_expression::do_get_backend(Translate_context* context)
14697 const Struct_field_list* fields = this->type_->fields();
14698 Struct_field_list::const_iterator p;
14699 unsigned i = 0;
14700 for (p = fields->begin();
14701 p != fields->end();
14702 ++p, ++i)
14703 if (&*p == this->field_)
14704 break;
14705 go_assert(&*p == this->field_);
14707 Gogo* gogo = context->gogo();
14708 Btype* btype = this->type_->get_backend(gogo);
14710 size_t offset = gogo->backend()->type_field_offset(btype, i);
14711 mpz_t offsetval;
14712 mpz_init_set_ui(offsetval, offset);
14713 Type* uptr_type = Type::lookup_integer_type("uintptr");
14714 Expression* ret = Expression::make_integer(&offsetval, uptr_type,
14715 Linemap::predeclared_location());
14716 mpz_clear(offsetval);
14717 return ret->get_backend(context);
14720 // Dump ast representation for a struct field offset expression.
14722 void
14723 Struct_field_offset_expression::do_dump_expression(
14724 Ast_dump_context* ast_dump_context) const
14726 ast_dump_context->ostream() << "unsafe.Offsetof(";
14727 ast_dump_context->dump_type(this->type_);
14728 ast_dump_context->ostream() << '.';
14729 ast_dump_context->ostream() <<
14730 Gogo::message_name(this->field_->field_name());
14731 ast_dump_context->ostream() << ")";
14734 // Make an expression for a struct field offset.
14736 Expression*
14737 Expression::make_struct_field_offset(Struct_type* type,
14738 const Struct_field* field)
14740 return new Struct_field_offset_expression(type, field);
14743 // An expression which evaluates to a pointer to the map descriptor of
14744 // a map type.
14746 class Map_descriptor_expression : public Expression
14748 public:
14749 Map_descriptor_expression(Map_type* type, Location location)
14750 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14751 type_(type)
14754 protected:
14755 Type*
14756 do_type()
14757 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14759 void
14760 do_determine_type(const Type_context*)
14763 Expression*
14764 do_copy()
14765 { return this; }
14767 Bexpression*
14768 do_get_backend(Translate_context* context)
14770 return this->type_->map_descriptor_pointer(context->gogo(),
14771 this->location());
14774 void
14775 do_dump_expression(Ast_dump_context*) const;
14777 private:
14778 // The type for which this is the descriptor.
14779 Map_type* type_;
14782 // Dump ast representation for a map descriptor expression.
14784 void
14785 Map_descriptor_expression::do_dump_expression(
14786 Ast_dump_context* ast_dump_context) const
14788 ast_dump_context->ostream() << "map_descriptor(";
14789 ast_dump_context->dump_type(this->type_);
14790 ast_dump_context->ostream() << ")";
14793 // Make a map descriptor expression.
14795 Expression*
14796 Expression::make_map_descriptor(Map_type* type, Location location)
14798 return new Map_descriptor_expression(type, location);
14801 // An expression which evaluates to the address of an unnamed label.
14803 class Label_addr_expression : public Expression
14805 public:
14806 Label_addr_expression(Label* label, Location location)
14807 : Expression(EXPRESSION_LABEL_ADDR, location),
14808 label_(label)
14811 protected:
14812 Type*
14813 do_type()
14814 { return Type::make_pointer_type(Type::make_void_type()); }
14816 void
14817 do_determine_type(const Type_context*)
14820 Expression*
14821 do_copy()
14822 { return new Label_addr_expression(this->label_, this->location()); }
14824 Bexpression*
14825 do_get_backend(Translate_context* context)
14826 { return this->label_->get_addr(context, this->location()); }
14828 void
14829 do_dump_expression(Ast_dump_context* ast_dump_context) const
14830 { ast_dump_context->ostream() << this->label_->name(); }
14832 private:
14833 // The label whose address we are taking.
14834 Label* label_;
14837 // Make an expression for the address of an unnamed label.
14839 Expression*
14840 Expression::make_label_addr(Label* label, Location location)
14842 return new Label_addr_expression(label, location);
14845 // Conditional expressions.
14847 class Conditional_expression : public Expression
14849 public:
14850 Conditional_expression(Expression* cond, Expression* then_expr,
14851 Expression* else_expr, Location location)
14852 : Expression(EXPRESSION_CONDITIONAL, location),
14853 cond_(cond), then_(then_expr), else_(else_expr)
14856 protected:
14858 do_traverse(Traverse*);
14860 Type*
14861 do_type();
14863 void
14864 do_determine_type(const Type_context*);
14866 Expression*
14867 do_copy()
14869 return new Conditional_expression(this->cond_->copy(), this->then_->copy(),
14870 this->else_->copy(), this->location());
14873 Bexpression*
14874 do_get_backend(Translate_context* context);
14876 void
14877 do_dump_expression(Ast_dump_context*) const;
14879 private:
14880 // The condition to be checked.
14881 Expression* cond_;
14882 // The expression to execute if the condition is true.
14883 Expression* then_;
14884 // The expression to execute if the condition is false.
14885 Expression* else_;
14888 // Traversal.
14891 Conditional_expression::do_traverse(Traverse* traverse)
14893 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14894 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14895 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14896 return TRAVERSE_EXIT;
14897 return TRAVERSE_CONTINUE;
14900 // Return the type of the conditional expression.
14902 Type*
14903 Conditional_expression::do_type()
14905 Type* result_type = Type::make_void_type();
14906 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
14907 NULL))
14908 result_type = this->then_->type();
14909 else if (this->then_->is_nil_expression()
14910 || this->else_->is_nil_expression())
14911 result_type = (!this->then_->is_nil_expression()
14912 ? this->then_->type()
14913 : this->else_->type());
14914 return result_type;
14917 // Determine type for a conditional expression.
14919 void
14920 Conditional_expression::do_determine_type(const Type_context* context)
14922 this->cond_->determine_type_no_context();
14923 this->then_->determine_type(context);
14924 this->else_->determine_type(context);
14927 // Get the backend representation of a conditional expression.
14929 Bexpression*
14930 Conditional_expression::do_get_backend(Translate_context* context)
14932 Gogo* gogo = context->gogo();
14933 Btype* result_btype = this->type()->get_backend(gogo);
14934 Bexpression* cond = this->cond_->get_backend(context);
14935 Bexpression* then = this->then_->get_backend(context);
14936 Bexpression* belse = this->else_->get_backend(context);
14937 return gogo->backend()->conditional_expression(result_btype, cond, then,
14938 belse, this->location());
14941 // Dump ast representation of a conditional expression.
14943 void
14944 Conditional_expression::do_dump_expression(
14945 Ast_dump_context* ast_dump_context) const
14947 ast_dump_context->ostream() << "(";
14948 ast_dump_context->dump_expression(this->cond_);
14949 ast_dump_context->ostream() << " ? ";
14950 ast_dump_context->dump_expression(this->then_);
14951 ast_dump_context->ostream() << " : ";
14952 ast_dump_context->dump_expression(this->else_);
14953 ast_dump_context->ostream() << ") ";
14956 // Make a conditional expression.
14958 Expression*
14959 Expression::make_conditional(Expression* cond, Expression* then,
14960 Expression* else_expr, Location location)
14962 return new Conditional_expression(cond, then, else_expr, location);
14965 // Compound expressions.
14967 class Compound_expression : public Expression
14969 public:
14970 Compound_expression(Expression* init, Expression* expr, Location location)
14971 : Expression(EXPRESSION_COMPOUND, location), init_(init), expr_(expr)
14974 protected:
14976 do_traverse(Traverse*);
14978 Type*
14979 do_type();
14981 void
14982 do_determine_type(const Type_context*);
14984 Expression*
14985 do_copy()
14987 return new Compound_expression(this->init_->copy(), this->expr_->copy(),
14988 this->location());
14991 Bexpression*
14992 do_get_backend(Translate_context* context);
14994 void
14995 do_dump_expression(Ast_dump_context*) const;
14997 private:
14998 // The expression that is evaluated first and discarded.
14999 Expression* init_;
15000 // The expression that is evaluated and returned.
15001 Expression* expr_;
15004 // Traversal.
15007 Compound_expression::do_traverse(Traverse* traverse)
15009 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
15010 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
15011 return TRAVERSE_EXIT;
15012 return TRAVERSE_CONTINUE;
15015 // Return the type of the compound expression.
15017 Type*
15018 Compound_expression::do_type()
15020 return this->expr_->type();
15023 // Determine type for a compound expression.
15025 void
15026 Compound_expression::do_determine_type(const Type_context* context)
15028 this->init_->determine_type_no_context();
15029 this->expr_->determine_type(context);
15032 // Get the backend representation of a compound expression.
15034 Bexpression*
15035 Compound_expression::do_get_backend(Translate_context* context)
15037 Gogo* gogo = context->gogo();
15038 Bexpression* binit = this->init_->get_backend(context);
15039 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
15040 Bexpression* bexpr = this->expr_->get_backend(context);
15041 return gogo->backend()->compound_expression(init_stmt, bexpr,
15042 this->location());
15045 // Dump ast representation of a conditional expression.
15047 void
15048 Compound_expression::do_dump_expression(
15049 Ast_dump_context* ast_dump_context) const
15051 ast_dump_context->ostream() << "(";
15052 ast_dump_context->dump_expression(this->init_);
15053 ast_dump_context->ostream() << ",";
15054 ast_dump_context->dump_expression(this->expr_);
15055 ast_dump_context->ostream() << ") ";
15058 // Make a compound expression.
15060 Expression*
15061 Expression::make_compound(Expression* init, Expression* expr, Location location)
15063 return new Compound_expression(init, expr, location);
15066 // Import an expression. This comes at the end in order to see the
15067 // various class definitions.
15069 Expression*
15070 Expression::import_expression(Import* imp)
15072 int c = imp->peek_char();
15073 if (imp->match_c_string("- ")
15074 || imp->match_c_string("! ")
15075 || imp->match_c_string("^ "))
15076 return Unary_expression::do_import(imp);
15077 else if (c == '(')
15078 return Binary_expression::do_import(imp);
15079 else if (imp->match_c_string("true")
15080 || imp->match_c_string("false"))
15081 return Boolean_expression::do_import(imp);
15082 else if (c == '"')
15083 return String_expression::do_import(imp);
15084 else if (c == '-' || (c >= '0' && c <= '9'))
15086 // This handles integers, floats and complex constants.
15087 return Integer_expression::do_import(imp);
15089 else if (imp->match_c_string("nil"))
15090 return Nil_expression::do_import(imp);
15091 else if (imp->match_c_string("convert"))
15092 return Type_conversion_expression::do_import(imp);
15093 else
15095 error_at(imp->location(), "import error: expected expression");
15096 return Expression::make_error(imp->location());
15100 // Class Expression_list.
15102 // Traverse the list.
15105 Expression_list::traverse(Traverse* traverse)
15107 for (Expression_list::iterator p = this->begin();
15108 p != this->end();
15109 ++p)
15111 if (*p != NULL)
15113 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
15114 return TRAVERSE_EXIT;
15117 return TRAVERSE_CONTINUE;
15120 // Copy the list.
15122 Expression_list*
15123 Expression_list::copy()
15125 Expression_list* ret = new Expression_list();
15126 for (Expression_list::iterator p = this->begin();
15127 p != this->end();
15128 ++p)
15130 if (*p == NULL)
15131 ret->push_back(NULL);
15132 else
15133 ret->push_back((*p)->copy());
15135 return ret;
15138 // Return whether an expression list has an error expression.
15140 bool
15141 Expression_list::contains_error() const
15143 for (Expression_list::const_iterator p = this->begin();
15144 p != this->end();
15145 ++p)
15146 if (*p != NULL && (*p)->is_error_expression())
15147 return true;
15148 return false;
15151 // Class Numeric_constant.
15153 // Destructor.
15155 Numeric_constant::~Numeric_constant()
15157 this->clear();
15160 // Copy constructor.
15162 Numeric_constant::Numeric_constant(const Numeric_constant& a)
15163 : classification_(a.classification_), type_(a.type_)
15165 switch (a.classification_)
15167 case NC_INVALID:
15168 break;
15169 case NC_INT:
15170 case NC_RUNE:
15171 mpz_init_set(this->u_.int_val, a.u_.int_val);
15172 break;
15173 case NC_FLOAT:
15174 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15175 break;
15176 case NC_COMPLEX:
15177 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15178 GMP_RNDN);
15179 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15180 GMP_RNDN);
15181 break;
15182 default:
15183 go_unreachable();
15187 // Assignment operator.
15189 Numeric_constant&
15190 Numeric_constant::operator=(const Numeric_constant& a)
15192 this->clear();
15193 this->classification_ = a.classification_;
15194 this->type_ = a.type_;
15195 switch (a.classification_)
15197 case NC_INVALID:
15198 break;
15199 case NC_INT:
15200 case NC_RUNE:
15201 mpz_init_set(this->u_.int_val, a.u_.int_val);
15202 break;
15203 case NC_FLOAT:
15204 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
15205 break;
15206 case NC_COMPLEX:
15207 mpfr_init_set(this->u_.complex_val.real, a.u_.complex_val.real,
15208 GMP_RNDN);
15209 mpfr_init_set(this->u_.complex_val.imag, a.u_.complex_val.imag,
15210 GMP_RNDN);
15211 break;
15212 default:
15213 go_unreachable();
15215 return *this;
15218 // Clear the contents.
15220 void
15221 Numeric_constant::clear()
15223 switch (this->classification_)
15225 case NC_INVALID:
15226 break;
15227 case NC_INT:
15228 case NC_RUNE:
15229 mpz_clear(this->u_.int_val);
15230 break;
15231 case NC_FLOAT:
15232 mpfr_clear(this->u_.float_val);
15233 break;
15234 case NC_COMPLEX:
15235 mpfr_clear(this->u_.complex_val.real);
15236 mpfr_clear(this->u_.complex_val.imag);
15237 break;
15238 default:
15239 go_unreachable();
15241 this->classification_ = NC_INVALID;
15244 // Set to an unsigned long value.
15246 void
15247 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
15249 this->clear();
15250 this->classification_ = NC_INT;
15251 this->type_ = type;
15252 mpz_init_set_ui(this->u_.int_val, val);
15255 // Set to an integer value.
15257 void
15258 Numeric_constant::set_int(Type* type, const mpz_t val)
15260 this->clear();
15261 this->classification_ = NC_INT;
15262 this->type_ = type;
15263 mpz_init_set(this->u_.int_val, val);
15266 // Set to a rune value.
15268 void
15269 Numeric_constant::set_rune(Type* type, const mpz_t val)
15271 this->clear();
15272 this->classification_ = NC_RUNE;
15273 this->type_ = type;
15274 mpz_init_set(this->u_.int_val, val);
15277 // Set to a floating point value.
15279 void
15280 Numeric_constant::set_float(Type* type, const mpfr_t val)
15282 this->clear();
15283 this->classification_ = NC_FLOAT;
15284 this->type_ = type;
15285 // Numeric constants do not have negative zero values, so remove
15286 // them here. They also don't have infinity or NaN values, but we
15287 // should never see them here.
15288 if (mpfr_zero_p(val))
15289 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
15290 else
15291 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
15294 // Set to a complex value.
15296 void
15297 Numeric_constant::set_complex(Type* type, const mpfr_t real, const mpfr_t imag)
15299 this->clear();
15300 this->classification_ = NC_COMPLEX;
15301 this->type_ = type;
15302 mpfr_init_set(this->u_.complex_val.real, real, GMP_RNDN);
15303 mpfr_init_set(this->u_.complex_val.imag, imag, GMP_RNDN);
15306 // Get an int value.
15308 void
15309 Numeric_constant::get_int(mpz_t* val) const
15311 go_assert(this->is_int());
15312 mpz_init_set(*val, this->u_.int_val);
15315 // Get a rune value.
15317 void
15318 Numeric_constant::get_rune(mpz_t* val) const
15320 go_assert(this->is_rune());
15321 mpz_init_set(*val, this->u_.int_val);
15324 // Get a floating point value.
15326 void
15327 Numeric_constant::get_float(mpfr_t* val) const
15329 go_assert(this->is_float());
15330 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15333 // Get a complex value.
15335 void
15336 Numeric_constant::get_complex(mpfr_t* real, mpfr_t* imag) const
15338 go_assert(this->is_complex());
15339 mpfr_init_set(*real, this->u_.complex_val.real, GMP_RNDN);
15340 mpfr_init_set(*imag, this->u_.complex_val.imag, GMP_RNDN);
15343 // Express value as unsigned long if possible.
15345 Numeric_constant::To_unsigned_long
15346 Numeric_constant::to_unsigned_long(unsigned long* val) const
15348 switch (this->classification_)
15350 case NC_INT:
15351 case NC_RUNE:
15352 return this->mpz_to_unsigned_long(this->u_.int_val, val);
15353 case NC_FLOAT:
15354 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
15355 case NC_COMPLEX:
15356 if (!mpfr_zero_p(this->u_.complex_val.imag))
15357 return NC_UL_NOTINT;
15358 return this->mpfr_to_unsigned_long(this->u_.complex_val.real, val);
15359 default:
15360 go_unreachable();
15364 // Express integer value as unsigned long if possible.
15366 Numeric_constant::To_unsigned_long
15367 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15368 unsigned long *val) const
15370 if (mpz_sgn(ival) < 0)
15371 return NC_UL_NEGATIVE;
15372 unsigned long ui = mpz_get_ui(ival);
15373 if (mpz_cmp_ui(ival, ui) != 0)
15374 return NC_UL_BIG;
15375 *val = ui;
15376 return NC_UL_VALID;
15379 // Express floating point value as unsigned long if possible.
15381 Numeric_constant::To_unsigned_long
15382 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15383 unsigned long *val) const
15385 if (!mpfr_integer_p(fval))
15386 return NC_UL_NOTINT;
15387 mpz_t ival;
15388 mpz_init(ival);
15389 mpfr_get_z(ival, fval, GMP_RNDN);
15390 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15391 mpz_clear(ival);
15392 return ret;
15395 // Convert value to integer if possible.
15397 bool
15398 Numeric_constant::to_int(mpz_t* val) const
15400 switch (this->classification_)
15402 case NC_INT:
15403 case NC_RUNE:
15404 mpz_init_set(*val, this->u_.int_val);
15405 return true;
15406 case NC_FLOAT:
15407 if (!mpfr_integer_p(this->u_.float_val))
15408 return false;
15409 mpz_init(*val);
15410 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15411 return true;
15412 case NC_COMPLEX:
15413 if (!mpfr_zero_p(this->u_.complex_val.imag)
15414 || !mpfr_integer_p(this->u_.complex_val.real))
15415 return false;
15416 mpz_init(*val);
15417 mpfr_get_z(*val, this->u_.complex_val.real, GMP_RNDN);
15418 return true;
15419 default:
15420 go_unreachable();
15424 // Convert value to floating point if possible.
15426 bool
15427 Numeric_constant::to_float(mpfr_t* val) const
15429 switch (this->classification_)
15431 case NC_INT:
15432 case NC_RUNE:
15433 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15434 return true;
15435 case NC_FLOAT:
15436 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15437 return true;
15438 case NC_COMPLEX:
15439 if (!mpfr_zero_p(this->u_.complex_val.imag))
15440 return false;
15441 mpfr_init_set(*val, this->u_.complex_val.real, GMP_RNDN);
15442 return true;
15443 default:
15444 go_unreachable();
15448 // Convert value to complex.
15450 bool
15451 Numeric_constant::to_complex(mpfr_t* vr, mpfr_t* vi) const
15453 switch (this->classification_)
15455 case NC_INT:
15456 case NC_RUNE:
15457 mpfr_init_set_z(*vr, this->u_.int_val, GMP_RNDN);
15458 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15459 return true;
15460 case NC_FLOAT:
15461 mpfr_init_set(*vr, this->u_.float_val, GMP_RNDN);
15462 mpfr_init_set_ui(*vi, 0, GMP_RNDN);
15463 return true;
15464 case NC_COMPLEX:
15465 mpfr_init_set(*vr, this->u_.complex_val.real, GMP_RNDN);
15466 mpfr_init_set(*vi, this->u_.complex_val.imag, GMP_RNDN);
15467 return true;
15468 default:
15469 go_unreachable();
15473 // Get the type.
15475 Type*
15476 Numeric_constant::type() const
15478 if (this->type_ != NULL)
15479 return this->type_;
15480 switch (this->classification_)
15482 case NC_INT:
15483 return Type::make_abstract_integer_type();
15484 case NC_RUNE:
15485 return Type::make_abstract_character_type();
15486 case NC_FLOAT:
15487 return Type::make_abstract_float_type();
15488 case NC_COMPLEX:
15489 return Type::make_abstract_complex_type();
15490 default:
15491 go_unreachable();
15495 // If the constant can be expressed in TYPE, then set the type of the
15496 // constant to TYPE and return true. Otherwise return false, and, if
15497 // ISSUE_ERROR is true, report an appropriate error message.
15499 bool
15500 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15502 bool ret;
15503 if (type == NULL)
15504 ret = true;
15505 else if (type->integer_type() != NULL)
15506 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15507 else if (type->float_type() != NULL)
15508 ret = this->check_float_type(type->float_type(), issue_error, loc);
15509 else if (type->complex_type() != NULL)
15510 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15511 else
15512 go_unreachable();
15513 if (ret)
15514 this->type_ = type;
15515 return ret;
15518 // Check whether the constant can be expressed in an integer type.
15520 bool
15521 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15522 Location location) const
15524 mpz_t val;
15525 switch (this->classification_)
15527 case NC_INT:
15528 case NC_RUNE:
15529 mpz_init_set(val, this->u_.int_val);
15530 break;
15532 case NC_FLOAT:
15533 if (!mpfr_integer_p(this->u_.float_val))
15535 if (issue_error)
15536 error_at(location, "floating point constant truncated to integer");
15537 return false;
15539 mpz_init(val);
15540 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15541 break;
15543 case NC_COMPLEX:
15544 if (!mpfr_integer_p(this->u_.complex_val.real)
15545 || !mpfr_zero_p(this->u_.complex_val.imag))
15547 if (issue_error)
15548 error_at(location, "complex constant truncated to integer");
15549 return false;
15551 mpz_init(val);
15552 mpfr_get_z(val, this->u_.complex_val.real, GMP_RNDN);
15553 break;
15555 default:
15556 go_unreachable();
15559 bool ret;
15560 if (type->is_abstract())
15561 ret = true;
15562 else
15564 int bits = mpz_sizeinbase(val, 2);
15565 if (type->is_unsigned())
15567 // For an unsigned type we can only accept a nonnegative
15568 // number, and we must be able to represents at least BITS.
15569 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15571 else
15573 // For a signed type we need an extra bit to indicate the
15574 // sign. We have to handle the most negative integer
15575 // specially.
15576 ret = (bits + 1 <= type->bits()
15577 || (bits <= type->bits()
15578 && mpz_sgn(val) < 0
15579 && (mpz_scan1(val, 0)
15580 == static_cast<unsigned long>(type->bits() - 1))
15581 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15585 if (!ret && issue_error)
15586 error_at(location, "integer constant overflow");
15588 return ret;
15591 // Check whether the constant can be expressed in a floating point
15592 // type.
15594 bool
15595 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15596 Location location)
15598 mpfr_t val;
15599 switch (this->classification_)
15601 case NC_INT:
15602 case NC_RUNE:
15603 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15604 break;
15606 case NC_FLOAT:
15607 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15608 break;
15610 case NC_COMPLEX:
15611 if (!mpfr_zero_p(this->u_.complex_val.imag))
15613 if (issue_error)
15614 error_at(location, "complex constant truncated to float");
15615 return false;
15617 mpfr_init_set(val, this->u_.complex_val.real, GMP_RNDN);
15618 break;
15620 default:
15621 go_unreachable();
15624 bool ret;
15625 if (type->is_abstract())
15626 ret = true;
15627 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15629 // A NaN or Infinity always fits in the range of the type.
15630 ret = true;
15632 else
15634 mp_exp_t exp = mpfr_get_exp(val);
15635 mp_exp_t max_exp;
15636 switch (type->bits())
15638 case 32:
15639 max_exp = 128;
15640 break;
15641 case 64:
15642 max_exp = 1024;
15643 break;
15644 default:
15645 go_unreachable();
15648 ret = exp <= max_exp;
15650 if (ret)
15652 // Round the constant to the desired type.
15653 mpfr_t t;
15654 mpfr_init(t);
15655 switch (type->bits())
15657 case 32:
15658 mpfr_set_prec(t, 24);
15659 break;
15660 case 64:
15661 mpfr_set_prec(t, 53);
15662 break;
15663 default:
15664 go_unreachable();
15666 mpfr_set(t, val, GMP_RNDN);
15667 mpfr_set(val, t, GMP_RNDN);
15668 mpfr_clear(t);
15670 this->set_float(type, val);
15674 mpfr_clear(val);
15676 if (!ret && issue_error)
15677 error_at(location, "floating point constant overflow");
15679 return ret;
15682 // Check whether the constant can be expressed in a complex type.
15684 bool
15685 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15686 Location location)
15688 if (type->is_abstract())
15689 return true;
15691 mp_exp_t max_exp;
15692 switch (type->bits())
15694 case 64:
15695 max_exp = 128;
15696 break;
15697 case 128:
15698 max_exp = 1024;
15699 break;
15700 default:
15701 go_unreachable();
15704 mpfr_t real;
15705 mpfr_t imag;
15706 switch (this->classification_)
15708 case NC_INT:
15709 case NC_RUNE:
15710 mpfr_init_set_z(real, this->u_.int_val, GMP_RNDN);
15711 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15712 break;
15714 case NC_FLOAT:
15715 mpfr_init_set(real, this->u_.float_val, GMP_RNDN);
15716 mpfr_init_set_ui(imag, 0, GMP_RNDN);
15717 break;
15719 case NC_COMPLEX:
15720 mpfr_init_set(real, this->u_.complex_val.real, GMP_RNDN);
15721 mpfr_init_set(imag, this->u_.complex_val.imag, GMP_RNDN);
15722 break;
15724 default:
15725 go_unreachable();
15728 bool ret = true;
15729 if (!mpfr_nan_p(real)
15730 && !mpfr_inf_p(real)
15731 && !mpfr_zero_p(real)
15732 && mpfr_get_exp(real) > max_exp)
15734 if (issue_error)
15735 error_at(location, "complex real part overflow");
15736 ret = false;
15739 if (!mpfr_nan_p(imag)
15740 && !mpfr_inf_p(imag)
15741 && !mpfr_zero_p(imag)
15742 && mpfr_get_exp(imag) > max_exp)
15744 if (issue_error)
15745 error_at(location, "complex imaginary part overflow");
15746 ret = false;
15749 if (ret)
15751 // Round the constant to the desired type.
15752 mpfr_t t;
15753 mpfr_init(t);
15754 switch (type->bits())
15756 case 64:
15757 mpfr_set_prec(t, 24);
15758 break;
15759 case 128:
15760 mpfr_set_prec(t, 53);
15761 break;
15762 default:
15763 go_unreachable();
15765 mpfr_set(t, real, GMP_RNDN);
15766 mpfr_set(real, t, GMP_RNDN);
15767 mpfr_set(t, imag, GMP_RNDN);
15768 mpfr_set(imag, t, GMP_RNDN);
15769 mpfr_clear(t);
15771 this->set_complex(type, real, imag);
15774 mpfr_clear(real);
15775 mpfr_clear(imag);
15777 return ret;
15780 // Return an Expression for this value.
15782 Expression*
15783 Numeric_constant::expression(Location loc) const
15785 switch (this->classification_)
15787 case NC_INT:
15788 return Expression::make_integer(&this->u_.int_val, this->type_, loc);
15789 case NC_RUNE:
15790 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15791 case NC_FLOAT:
15792 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15793 case NC_COMPLEX:
15794 return Expression::make_complex(&this->u_.complex_val.real,
15795 &this->u_.complex_val.imag,
15796 this->type_, loc);
15797 default:
15798 go_unreachable();