1 // expressions.cc -- Go frontend expression handling.
2
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.
6
7 #include "go-system.h"
8
9 #include <algorithm>
10
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "types.h"
16 #include "export.h"
17 #include "import.h"
18 #include "statements.h"
19 #include "lex.h"
20 #include "runtime.h"
21 #include "backend.h"
22 #include "expressions.h"
23 #include "ast-dump.h"
24
25 // Class Expression.
26
Expression(Expression_classification classification,Location location)27 Expression::Expression(Expression_classification classification,
28 Location location)
29 : classification_(classification), location_(location)
30 {
31 }
32
~Expression()33 Expression::~Expression()
34 {
35 }
36
37 // Traverse the expressions.
38
39 int
traverse(Expression ** pexpr,Traverse * traverse)40 Expression::traverse(Expression** pexpr, Traverse* traverse)
41 {
42 Expression* expr = *pexpr;
43 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
44 {
45 int t = traverse->expression(pexpr);
46 if (t == TRAVERSE_EXIT)
47 return TRAVERSE_EXIT;
48 else if (t == TRAVERSE_SKIP_COMPONENTS)
49 return TRAVERSE_CONTINUE;
50 }
51 return expr->do_traverse(traverse);
52 }
53
54 // Traverse subexpressions of this expression.
55
56 int
traverse_subexpressions(Traverse * traverse)57 Expression::traverse_subexpressions(Traverse* traverse)
58 {
59 return this->do_traverse(traverse);
60 }
61
62 // Default implementation for do_traverse for child classes.
63
64 int
do_traverse(Traverse *)65 Expression::do_traverse(Traverse*)
66 {
67 return TRAVERSE_CONTINUE;
68 }
69
70 // This virtual function is called by the parser if the value of this
71 // expression is being discarded. By default, we give an error.
72 // Expressions with side effects override.
73
74 bool
do_discarding_value()75 Expression::do_discarding_value()
76 {
77 this->unused_value_error();
78 return false;
79 }
80
81 // This virtual function is called to export expressions. This will
82 // only be used by expressions which may be constant.
83
84 void
do_export(Export_function_body *) const85 Expression::do_export(Export_function_body*) const
86 {
87 go_unreachable();
88 }
89
90 // Give an error saying that the value of the expression is not used.
91
92 void
unused_value_error()93 Expression::unused_value_error()
94 {
95 this->report_error(_("value computed is not used"));
96 }
97
98 // Note that this expression is an error. This is called by children
99 // when they discover an error.
100
101 void
set_is_error()102 Expression::set_is_error()
103 {
104 this->classification_ = EXPRESSION_ERROR;
105 }
106
107 // For children to call to report an error conveniently.
108
109 void
report_error(const char * msg)110 Expression::report_error(const char* msg)
111 {
112 go_error_at(this->location_, "%s", msg);
113 this->set_is_error();
114 }
115
116 // Set types of variables and constants. This is implemented by the
117 // child class.
118
119 void
determine_type(const Type_context * context)120 Expression::determine_type(const Type_context* context)
121 {
122 this->do_determine_type(context);
123 }
124
125 // Set types when there is no context.
126
127 void
determine_type_no_context()128 Expression::determine_type_no_context()
129 {
130 Type_context context;
131 this->do_determine_type(&context);
132 }
133
134 // Return true if two expressions refer to the same variable or struct
135 // field. This can only be true when there are no side effects.
136
137 bool
is_same_variable(Expression * a,Expression * b)138 Expression::is_same_variable(Expression* a, Expression* b)
139 {
140 if (a->classification() != b->classification())
141 return false;
142
143 Var_expression* av = a->var_expression();
144 if (av != NULL)
145 return av->named_object() == b->var_expression()->named_object();
146
147 Field_reference_expression* af = a->field_reference_expression();
148 if (af != NULL)
149 {
150 Field_reference_expression* bf = b->field_reference_expression();
151 return (af->field_index() == bf->field_index()
152 && Expression::is_same_variable(af->expr(), bf->expr()));
153 }
154
155 Unary_expression* au = a->unary_expression();
156 if (au != NULL)
157 {
158 Unary_expression* bu = b->unary_expression();
159 return (au->op() == OPERATOR_MULT
160 && bu->op() == OPERATOR_MULT
161 && Expression::is_same_variable(au->operand(),
162 bu->operand()));
163 }
164
165 return false;
166 }
167
168 // Return an expression handling any conversions which must be done during
169 // assignment.
170
171 Expression*
convert_for_assignment(Gogo *,Type * lhs_type,Expression * rhs,Location location)172 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
173 Expression* rhs, Location location)
174 {
175 Type* rhs_type = rhs->type();
176 if (lhs_type->is_error()
177 || rhs_type->is_error()
178 || rhs->is_error_expression())
179 return Expression::make_error(location);
180
181 bool are_identical = Type::are_identical(lhs_type, rhs_type,
182 (Type::COMPARE_ERRORS
183 | Type::COMPARE_TAGS),
184 NULL);
185 if (!are_identical && lhs_type->interface_type() != NULL)
186 {
187 if (rhs_type->interface_type() == NULL)
188 return Expression::convert_type_to_interface(lhs_type, rhs, location);
189 else
190 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
191 location);
192 }
193 else if (!are_identical && rhs_type->interface_type() != NULL)
194 return Expression::convert_interface_to_type(lhs_type, rhs, location);
195 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
196 {
197 // Assigning nil to a slice.
198 Expression* nil = Expression::make_nil(location);
199 Expression* zero = Expression::make_integer_ul(0, NULL, location);
200 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
201 }
202 else if (rhs_type->is_nil_type())
203 return Expression::make_nil(location);
204 else if (are_identical)
205 {
206 if (lhs_type->forwarded() != rhs_type->forwarded())
207 {
208 // Different but identical types require an explicit
209 // conversion. This happens with type aliases.
210 return Expression::make_cast(lhs_type, rhs, location);
211 }
212
213 // No conversion is needed.
214 return rhs;
215 }
216 else if (lhs_type->points_to() != NULL)
217 return Expression::make_unsafe_cast(lhs_type, rhs, location);
218 else if (lhs_type->is_numeric_type())
219 return Expression::make_cast(lhs_type, rhs, location);
220 else if ((lhs_type->struct_type() != NULL
221 && rhs_type->struct_type() != NULL)
222 || (lhs_type->array_type() != NULL
223 && rhs_type->array_type() != NULL))
224 {
225 // This conversion must be permitted by Go, or we wouldn't have
226 // gotten here.
227 return Expression::make_unsafe_cast(lhs_type, rhs, location);
228 }
229 else
230 return rhs;
231 }
232
233 // Return an expression for a conversion from a non-interface type to an
234 // interface type.
235
236 Expression*
convert_type_to_interface(Type * lhs_type,Expression * rhs,Location location)237 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
238 Location location)
239 {
240 Interface_type* lhs_interface_type = lhs_type->interface_type();
241 bool lhs_is_empty = lhs_interface_type->is_empty();
242
243 // Since RHS_TYPE is a static type, we can create the interface
244 // method table at compile time.
245
246 // When setting an interface to nil, we just set both fields to
247 // NULL.
248 Type* rhs_type = rhs->type();
249 if (rhs_type->is_nil_type())
250 {
251 Expression* nil = Expression::make_nil(location);
252 return Expression::make_interface_value(lhs_type, nil, nil, location);
253 }
254
255 // This should have been checked already.
256 if (!lhs_interface_type->implements_interface(rhs_type, NULL))
257 {
258 go_assert(saw_errors());
259 return Expression::make_error(location);
260 }
261
262 // An interface is a tuple. If LHS_TYPE is an empty interface type,
263 // then the first field is the type descriptor for RHS_TYPE.
264 // Otherwise it is the interface method table for RHS_TYPE.
265 Expression* first_field;
266 if (lhs_is_empty)
267 first_field = Expression::make_type_descriptor(rhs_type, location);
268 else
269 {
270 // Build the interface method table for this interface and this
271 // object type: a list of function pointers for each interface
272 // method.
273 Named_type* rhs_named_type = rhs_type->named_type();
274 Struct_type* rhs_struct_type = rhs_type->struct_type();
275 bool is_pointer = false;
276 if (rhs_named_type == NULL && rhs_struct_type == NULL)
277 {
278 rhs_named_type = rhs_type->deref()->named_type();
279 rhs_struct_type = rhs_type->deref()->struct_type();
280 is_pointer = true;
281 }
282 if (rhs_named_type != NULL)
283 first_field =
284 rhs_named_type->interface_method_table(lhs_interface_type,
285 is_pointer);
286 else if (rhs_struct_type != NULL)
287 first_field =
288 rhs_struct_type->interface_method_table(lhs_interface_type,
289 is_pointer);
290 else
291 first_field = Expression::make_nil(location);
292 }
293
294 Expression* obj;
295 if (rhs_type->points_to() != NULL)
296 {
297 // We are assigning a pointer to the interface; the interface
298 // holds the pointer itself.
299 obj = rhs;
300 }
301 else
302 {
303 // We are assigning a non-pointer value to the interface; the
304 // interface gets a copy of the value in the heap if it escapes.
305 // TODO(cmang): Associate escape state state of RHS with newly
306 // created OBJ.
307 obj = Expression::make_heap_expression(rhs, location);
308 }
309
310 return Expression::make_interface_value(lhs_type, first_field, obj, location);
311 }
312
313 // Return an expression for the type descriptor of RHS.
314
315 Expression*
get_interface_type_descriptor(Expression * rhs)316 Expression::get_interface_type_descriptor(Expression* rhs)
317 {
318 go_assert(rhs->type()->interface_type() != NULL);
319 Location location = rhs->location();
320
321 // The type descriptor is the first field of an empty interface.
322 if (rhs->type()->interface_type()->is_empty())
323 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
324 location);
325
326 Expression* mtable =
327 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
328
329 Expression* descriptor =
330 Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, location);
331 descriptor = Expression::make_field_reference(descriptor, 0, location);
332 Expression* nil = Expression::make_nil(location);
333
334 Expression* eq =
335 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
336 return Expression::make_conditional(eq, nil, descriptor, location);
337 }
338
339 // Return an expression for the conversion of an interface type to an
340 // interface type.
341
342 Expression*
convert_interface_to_interface(Type * lhs_type,Expression * rhs,bool for_type_guard,Location location)343 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
344 bool for_type_guard,
345 Location location)
346 {
347 if (Type::are_identical(lhs_type, rhs->type(),
348 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
349 NULL))
350 return rhs;
351
352 Interface_type* lhs_interface_type = lhs_type->interface_type();
353 bool lhs_is_empty = lhs_interface_type->is_empty();
354
355 // In the general case this requires runtime examination of the type
356 // method table to match it up with the interface methods.
357
358 // FIXME: If all of the methods in the right hand side interface
359 // also appear in the left hand side interface, then we don't need
360 // to do a runtime check, although we still need to build a new
361 // method table.
362
363 // We are going to evaluate RHS multiple times.
364 go_assert(rhs->is_variable());
365
366 // Get the type descriptor for the right hand side. This will be
367 // NULL for a nil interface.
368 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
369 Expression* lhs_type_expr =
370 Expression::make_type_descriptor(lhs_type, location);
371
372 Expression* first_field;
373 if (for_type_guard)
374 {
375 // A type assertion fails when converting a nil interface.
376 first_field = Runtime::make_call(Runtime::ASSERTITAB, location, 2,
377 lhs_type_expr, rhs_type_expr);
378 }
379 else if (lhs_is_empty)
380 {
381 // A conversion to an empty interface always succeeds, and the
382 // first field is just the type descriptor of the object.
383 first_field = rhs_type_expr;
384 }
385 else
386 {
387 // A conversion to a non-empty interface may fail, but unlike a
388 // type assertion converting nil will always succeed.
389 first_field = Runtime::make_call(Runtime::REQUIREITAB, location, 2,
390 lhs_type_expr, rhs_type_expr);
391 }
392
393 // The second field is simply the object pointer.
394 Expression* obj =
395 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
396 return Expression::make_interface_value(lhs_type, first_field, obj, location);
397 }
398
399 // Return an expression for the conversion of an interface type to a
400 // non-interface type.
401
402 Expression*
convert_interface_to_type(Type * lhs_type,Expression * rhs,Location location)403 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
404 Location location)
405 {
406 // We are going to evaluate RHS multiple times.
407 go_assert(rhs->is_variable());
408
409 // Call a function to check that the type is valid. The function
410 // will panic with an appropriate runtime type error if the type is
411 // not valid.
412 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
413 location);
414 Expression* rhs_descriptor =
415 Expression::get_interface_type_descriptor(rhs);
416
417 Type* rhs_type = rhs->type();
418 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
419 location);
420
421 Expression* check_iface = Runtime::make_call(Runtime::ASSERTI2T,
422 location, 3, lhs_type_expr,
423 rhs_descriptor, rhs_inter_expr);
424
425 // If the call succeeds, pull out the value.
426 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
427 location);
428
429 // If the value is a pointer, then it is the value we want.
430 // Otherwise it points to the value.
431 if (lhs_type->points_to() == NULL)
432 {
433 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
434 location);
435 obj = Expression::make_dereference(obj, NIL_CHECK_NOT_NEEDED,
436 location);
437 }
438 return Expression::make_compound(check_iface, obj, location);
439 }
440
441 // Convert an expression to its backend representation. This is implemented by
442 // the child class. Not that it is not in general safe to call this multiple
443 // times for a single expression, but that we don't catch such errors.
444
445 Bexpression*
get_backend(Translate_context * context)446 Expression::get_backend(Translate_context* context)
447 {
448 // The child may have marked this expression as having an error.
449 if (this->classification_ == EXPRESSION_ERROR)
450 return context->backend()->error_expression();
451
452 return this->do_get_backend(context);
453 }
454
455 // Return a backend expression for VAL.
456 Bexpression*
backend_numeric_constant_expression(Translate_context * context,Numeric_constant * val)457 Expression::backend_numeric_constant_expression(Translate_context* context,
458 Numeric_constant* val)
459 {
460 Gogo* gogo = context->gogo();
461 Type* type = val->type();
462 if (type == NULL)
463 return gogo->backend()->error_expression();
464
465 Btype* btype = type->get_backend(gogo);
466 Bexpression* ret;
467 if (type->integer_type() != NULL)
468 {
469 mpz_t ival;
470 if (!val->to_int(&ival))
471 {
472 go_assert(saw_errors());
473 return gogo->backend()->error_expression();
474 }
475 ret = gogo->backend()->integer_constant_expression(btype, ival);
476 mpz_clear(ival);
477 }
478 else if (type->float_type() != NULL)
479 {
480 mpfr_t fval;
481 if (!val->to_float(&fval))
482 {
483 go_assert(saw_errors());
484 return gogo->backend()->error_expression();
485 }
486 ret = gogo->backend()->float_constant_expression(btype, fval);
487 mpfr_clear(fval);
488 }
489 else if (type->complex_type() != NULL)
490 {
491 mpc_t cval;
492 if (!val->to_complex(&cval))
493 {
494 go_assert(saw_errors());
495 return gogo->backend()->error_expression();
496 }
497 ret = gogo->backend()->complex_constant_expression(btype, cval);
498 mpc_clear(cval);
499 }
500 else
501 go_unreachable();
502
503 return ret;
504 }
505
506 // Return an expression which evaluates to true if VAL, of arbitrary integer
507 // type, is negative or is more than the maximum value of the Go type "int".
508
509 Expression*
check_bounds(Expression * val,Location loc)510 Expression::check_bounds(Expression* val, Location loc)
511 {
512 Type* val_type = val->type();
513 Type* bound_type = Type::lookup_integer_type("int");
514
515 int val_type_size;
516 bool val_is_unsigned = false;
517 if (val_type->integer_type() != NULL)
518 {
519 val_type_size = val_type->integer_type()->bits();
520 val_is_unsigned = val_type->integer_type()->is_unsigned();
521 }
522 else
523 {
524 if (!val_type->is_numeric_type()
525 || !Type::are_convertible(bound_type, val_type, NULL))
526 {
527 go_assert(saw_errors());
528 return Expression::make_boolean(true, loc);
529 }
530
531 if (val_type->complex_type() != NULL)
532 val_type_size = val_type->complex_type()->bits();
533 else
534 val_type_size = val_type->float_type()->bits();
535 }
536
537 Expression* negative_index = Expression::make_boolean(false, loc);
538 Expression* index_overflows = Expression::make_boolean(false, loc);
539 if (!val_is_unsigned)
540 {
541 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
542 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
543 }
544
545 int bound_type_size = bound_type->integer_type()->bits();
546 if (val_type_size > bound_type_size
547 || (val_type_size == bound_type_size
548 && val_is_unsigned))
549 {
550 mpz_t one;
551 mpz_init_set_ui(one, 1UL);
552
553 // maxval = 2^(bound_type_size - 1) - 1
554 mpz_t maxval;
555 mpz_init(maxval);
556 mpz_mul_2exp(maxval, one, bound_type_size - 1);
557 mpz_sub_ui(maxval, maxval, 1);
558 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
559 mpz_clear(one);
560 mpz_clear(maxval);
561
562 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
563 }
564
565 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
566 loc);
567 }
568
569 void
dump_expression(Ast_dump_context * ast_dump_context) const570 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
571 {
572 this->do_dump_expression(ast_dump_context);
573 }
574
575 // Error expressions. This are used to avoid cascading errors.
576
577 class Error_expression : public Expression
578 {
579 public:
Error_expression(Location location)580 Error_expression(Location location)
581 : Expression(EXPRESSION_ERROR, location)
582 { }
583
584 protected:
585 bool
do_is_constant() const586 do_is_constant() const
587 { return true; }
588
589 bool
do_numeric_constant_value(Numeric_constant * nc) const590 do_numeric_constant_value(Numeric_constant* nc) const
591 {
592 nc->set_unsigned_long(NULL, 0);
593 return true;
594 }
595
596 bool
do_discarding_value()597 do_discarding_value()
598 { return true; }
599
600 Type*
do_type()601 do_type()
602 { return Type::make_error_type(); }
603
604 void
do_determine_type(const Type_context *)605 do_determine_type(const Type_context*)
606 { }
607
608 Expression*
do_copy()609 do_copy()
610 { return this; }
611
612 bool
do_is_addressable() const613 do_is_addressable() const
614 { return true; }
615
616 Bexpression*
do_get_backend(Translate_context * context)617 do_get_backend(Translate_context* context)
618 { return context->backend()->error_expression(); }
619
620 void
621 do_dump_expression(Ast_dump_context*) const;
622 };
623
624 // Dump the ast representation for an error expression to a dump context.
625
626 void
do_dump_expression(Ast_dump_context * ast_dump_context) const627 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
628 {
629 ast_dump_context->ostream() << "_Error_" ;
630 }
631
632 Expression*
make_error(Location location)633 Expression::make_error(Location location)
634 {
635 return new Error_expression(location);
636 }
637
638 // An expression which is really a type. This is used during parsing.
639 // It is an error if these survive after lowering.
640
641 class
642 Type_expression : public Expression
643 {
644 public:
Type_expression(Type * type,Location location)645 Type_expression(Type* type, Location location)
646 : Expression(EXPRESSION_TYPE, location),
647 type_(type)
648 { }
649
650 protected:
651 int
do_traverse(Traverse * traverse)652 do_traverse(Traverse* traverse)
653 { return Type::traverse(this->type_, traverse); }
654
655 Type*
do_type()656 do_type()
657 { return this->type_; }
658
659 void
do_determine_type(const Type_context *)660 do_determine_type(const Type_context*)
661 { }
662
663 void
do_check_types(Gogo *)664 do_check_types(Gogo*)
665 { this->report_error(_("invalid use of type")); }
666
667 Expression*
do_copy()668 do_copy()
669 { return this; }
670
671 Bexpression*
do_get_backend(Translate_context *)672 do_get_backend(Translate_context*)
673 { go_unreachable(); }
674
675 void do_dump_expression(Ast_dump_context*) const;
676
677 private:
678 // The type which we are representing as an expression.
679 Type* type_;
680 };
681
682 void
do_dump_expression(Ast_dump_context * ast_dump_context) const683 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
684 {
685 ast_dump_context->dump_type(this->type_);
686 }
687
688 Expression*
make_type(Type * type,Location location)689 Expression::make_type(Type* type, Location location)
690 {
691 return new Type_expression(type, location);
692 }
693
694 // Class Parser_expression.
695
696 Type*
do_type()697 Parser_expression::do_type()
698 {
699 // We should never really ask for the type of a Parser_expression.
700 // However, it can happen, at least when we have an invalid const
701 // whose initializer refers to the const itself. In that case we
702 // may ask for the type when lowering the const itself.
703 go_assert(saw_errors());
704 return Type::make_error_type();
705 }
706
707 // Class Var_expression.
708
709 // Lower a variable expression. Here we just make sure that the
710 // initialization expression of the variable has been lowered. This
711 // ensures that we will be able to determine the type of the variable
712 // if necessary.
713
714 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)715 Var_expression::do_lower(Gogo* gogo, Named_object* function,
716 Statement_inserter* inserter, int)
717 {
718 if (this->variable_->is_variable())
719 {
720 Variable* var = this->variable_->var_value();
721 // This is either a local variable or a global variable. A
722 // reference to a variable which is local to an enclosing
723 // function will be a reference to a field in a closure.
724 if (var->is_global())
725 {
726 function = NULL;
727 inserter = NULL;
728 }
729 var->lower_init_expression(gogo, function, inserter);
730 }
731 return this;
732 }
733
734 // Return the type of a reference to a variable.
735
736 Type*
do_type()737 Var_expression::do_type()
738 {
739 if (this->variable_->is_variable())
740 return this->variable_->var_value()->type();
741 else if (this->variable_->is_result_variable())
742 return this->variable_->result_var_value()->type();
743 else
744 go_unreachable();
745 }
746
747 // Determine the type of a reference to a variable.
748
749 void
do_determine_type(const Type_context *)750 Var_expression::do_determine_type(const Type_context*)
751 {
752 if (this->variable_->is_variable())
753 this->variable_->var_value()->determine_type();
754 }
755
756 // Something takes the address of this variable. This means that we
757 // may want to move the variable onto the heap.
758
759 void
do_address_taken(bool escapes)760 Var_expression::do_address_taken(bool escapes)
761 {
762 if (!escapes)
763 {
764 if (this->variable_->is_variable())
765 this->variable_->var_value()->set_non_escaping_address_taken();
766 else if (this->variable_->is_result_variable())
767 this->variable_->result_var_value()->set_non_escaping_address_taken();
768 else
769 go_unreachable();
770 }
771 else
772 {
773 if (this->variable_->is_variable())
774 this->variable_->var_value()->set_address_taken();
775 else if (this->variable_->is_result_variable())
776 this->variable_->result_var_value()->set_address_taken();
777 else
778 go_unreachable();
779 }
780
781 if (this->variable_->is_variable()
782 && this->variable_->var_value()->is_in_heap())
783 {
784 Node::make_node(this)->set_encoding(Node::ESCAPE_HEAP);
785 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
786 }
787 }
788
789 // The cost to inline a variable reference. We currently only support
790 // references to parameters.
791
792 int
do_inlining_cost() const793 Var_expression::do_inlining_cost() const
794 {
795 if (this->variable_->is_variable())
796 {
797 if (this->variable_->var_value()->is_parameter())
798 return 1;
799 }
800 else if (this->variable_->is_result_variable())
801 return 1;
802
803 return 0x100000;
804 }
805
806 // Export a reference to a variable.
807
808 void
do_export(Export_function_body * efb) const809 Var_expression::do_export(Export_function_body* efb) const
810 {
811 efb->write_string(Gogo::unpack_hidden_name(this->variable_->name()));
812 }
813
814 // Get the backend representation for a reference to a variable.
815
816 Bexpression*
do_get_backend(Translate_context * context)817 Var_expression::do_get_backend(Translate_context* context)
818 {
819 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
820 context->function());
821 bool is_in_heap;
822 Location loc = this->location();
823 Btype* btype;
824 Gogo* gogo = context->gogo();
825 if (this->variable_->is_variable())
826 {
827 is_in_heap = this->variable_->var_value()->is_in_heap();
828 btype = this->variable_->var_value()->type()->get_backend(gogo);
829 }
830 else if (this->variable_->is_result_variable())
831 {
832 is_in_heap = this->variable_->result_var_value()->is_in_heap();
833 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
834 }
835 else
836 go_unreachable();
837
838 Bexpression* ret =
839 context->backend()->var_expression(bvar, loc);
840 if (is_in_heap)
841 ret = context->backend()->indirect_expression(btype, ret, true, loc);
842 return ret;
843 }
844
845 // Ast dump for variable expression.
846
847 void
do_dump_expression(Ast_dump_context * ast_dump_context) const848 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
849 {
850 ast_dump_context->ostream() << this->variable_->message_name() ;
851 }
852
853 // Make a reference to a variable in an expression.
854
855 Expression*
make_var_reference(Named_object * var,Location location)856 Expression::make_var_reference(Named_object* var, Location location)
857 {
858 if (var->is_sink())
859 return Expression::make_sink(location);
860
861 // FIXME: Creating a new object for each reference to a variable is
862 // wasteful.
863 return new Var_expression(var, location);
864 }
865
866 // Class Enclosed_var_expression.
867
868 int
do_traverse(Traverse *)869 Enclosed_var_expression::do_traverse(Traverse*)
870 {
871 return TRAVERSE_CONTINUE;
872 }
873
874 // Lower the reference to the enclosed variable.
875
876 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)877 Enclosed_var_expression::do_lower(Gogo* gogo, Named_object* function,
878 Statement_inserter* inserter, int)
879 {
880 gogo->lower_expression(function, inserter, &this->reference_);
881 return this;
882 }
883
884 // Flatten the reference to the enclosed variable.
885
886 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)887 Enclosed_var_expression::do_flatten(Gogo* gogo, Named_object* function,
888 Statement_inserter* inserter)
889 {
890 gogo->flatten_expression(function, inserter, &this->reference_);
891 return this;
892 }
893
894 void
do_address_taken(bool escapes)895 Enclosed_var_expression::do_address_taken(bool escapes)
896 {
897 if (!escapes)
898 {
899 if (this->variable_->is_variable())
900 this->variable_->var_value()->set_non_escaping_address_taken();
901 else if (this->variable_->is_result_variable())
902 this->variable_->result_var_value()->set_non_escaping_address_taken();
903 else
904 go_unreachable();
905 }
906 else
907 {
908 if (this->variable_->is_variable())
909 this->variable_->var_value()->set_address_taken();
910 else if (this->variable_->is_result_variable())
911 this->variable_->result_var_value()->set_address_taken();
912 else
913 go_unreachable();
914 }
915
916 if (this->variable_->is_variable()
917 && this->variable_->var_value()->is_in_heap())
918 Node::make_node(this->variable_)->set_encoding(Node::ESCAPE_HEAP);
919 }
920
921 // Ast dump for enclosed variable expression.
922
923 void
do_dump_expression(Ast_dump_context * adc) const924 Enclosed_var_expression::do_dump_expression(Ast_dump_context* adc) const
925 {
926 adc->ostream() << this->variable_->message_name();
927 }
928
929 // Make a reference to a variable within an enclosing function.
930
931 Expression*
make_enclosing_var_reference(Expression * reference,Named_object * var,Location location)932 Expression::make_enclosing_var_reference(Expression* reference,
933 Named_object* var, Location location)
934 {
935 return new Enclosed_var_expression(reference, var, location);
936 }
937
938 // Class Temporary_reference_expression.
939
940 // The type.
941
942 Type*
do_type()943 Temporary_reference_expression::do_type()
944 {
945 return this->statement_->type();
946 }
947
948 // Called if something takes the address of this temporary variable.
949 // We never have to move temporary variables to the heap, but we do
950 // need to know that they must live in the stack rather than in a
951 // register.
952
953 void
do_address_taken(bool)954 Temporary_reference_expression::do_address_taken(bool)
955 {
956 this->statement_->set_is_address_taken();
957 }
958
959 // Get a backend expression referring to the variable.
960
961 Bexpression*
do_get_backend(Translate_context * context)962 Temporary_reference_expression::do_get_backend(Translate_context* context)
963 {
964 Gogo* gogo = context->gogo();
965 Bvariable* bvar = this->statement_->get_backend_variable(context);
966 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
967
968 // The backend can't always represent the same set of recursive types
969 // that the Go frontend can. In some cases this means that a
970 // temporary variable won't have the right backend type. Correct
971 // that here by adding a type cast. We need to use base() to push
972 // the circularity down one level.
973 Type* stype = this->statement_->type();
974 if (!this->is_lvalue_
975 && stype->points_to() != NULL
976 && stype->points_to()->is_void_type())
977 {
978 Btype* btype = this->type()->base()->get_backend(gogo);
979 ret = gogo->backend()->convert_expression(btype, ret, this->location());
980 }
981 return ret;
982 }
983
984 // Ast dump for temporary reference.
985
986 void
do_dump_expression(Ast_dump_context * ast_dump_context) const987 Temporary_reference_expression::do_dump_expression(
988 Ast_dump_context* ast_dump_context) const
989 {
990 ast_dump_context->dump_temp_variable_name(this->statement_);
991 }
992
993 // Make a reference to a temporary variable.
994
995 Temporary_reference_expression*
make_temporary_reference(Temporary_statement * statement,Location location)996 Expression::make_temporary_reference(Temporary_statement* statement,
997 Location location)
998 {
999 return new Temporary_reference_expression(statement, location);
1000 }
1001
1002 // Class Set_and_use_temporary_expression.
1003
1004 // Return the type.
1005
1006 Type*
do_type()1007 Set_and_use_temporary_expression::do_type()
1008 {
1009 return this->statement_->type();
1010 }
1011
1012 // Determine the type of the expression.
1013
1014 void
do_determine_type(const Type_context * context)1015 Set_and_use_temporary_expression::do_determine_type(
1016 const Type_context* context)
1017 {
1018 this->expr_->determine_type(context);
1019 }
1020
1021 // Take the address.
1022
1023 void
do_address_taken(bool)1024 Set_and_use_temporary_expression::do_address_taken(bool)
1025 {
1026 this->statement_->set_is_address_taken();
1027 }
1028
1029 // Return the backend representation.
1030
1031 Bexpression*
do_get_backend(Translate_context * context)1032 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
1033 {
1034 Location loc = this->location();
1035 Gogo* gogo = context->gogo();
1036 Bvariable* bvar = this->statement_->get_backend_variable(context);
1037 Bexpression* lvar_ref = gogo->backend()->var_expression(bvar, loc);
1038
1039 Named_object* fn = context->function();
1040 go_assert(fn != NULL);
1041 Bfunction* bfn = fn->func_value()->get_or_make_decl(gogo, fn);
1042 Bexpression* bexpr = this->expr_->get_backend(context);
1043 Bstatement* set = gogo->backend()->assignment_statement(bfn, lvar_ref,
1044 bexpr, loc);
1045 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
1046 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
1047 return ret;
1048 }
1049
1050 // Dump.
1051
1052 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1053 Set_and_use_temporary_expression::do_dump_expression(
1054 Ast_dump_context* ast_dump_context) const
1055 {
1056 ast_dump_context->ostream() << '(';
1057 ast_dump_context->dump_temp_variable_name(this->statement_);
1058 ast_dump_context->ostream() << " = ";
1059 this->expr_->dump_expression(ast_dump_context);
1060 ast_dump_context->ostream() << ')';
1061 }
1062
1063 // Make a set-and-use temporary.
1064
1065 Set_and_use_temporary_expression*
make_set_and_use_temporary(Temporary_statement * statement,Expression * expr,Location location)1066 Expression::make_set_and_use_temporary(Temporary_statement* statement,
1067 Expression* expr, Location location)
1068 {
1069 return new Set_and_use_temporary_expression(statement, expr, location);
1070 }
1071
1072 // A sink expression--a use of the blank identifier _.
1073
1074 class Sink_expression : public Expression
1075 {
1076 public:
Sink_expression(Location location)1077 Sink_expression(Location location)
1078 : Expression(EXPRESSION_SINK, location),
1079 type_(NULL), bvar_(NULL)
1080 { }
1081
1082 protected:
1083 bool
do_discarding_value()1084 do_discarding_value()
1085 { return true; }
1086
1087 Type*
1088 do_type();
1089
1090 void
1091 do_determine_type(const Type_context*);
1092
1093 Expression*
do_copy()1094 do_copy()
1095 { return new Sink_expression(this->location()); }
1096
1097 Bexpression*
1098 do_get_backend(Translate_context*);
1099
1100 void
1101 do_dump_expression(Ast_dump_context*) const;
1102
1103 private:
1104 // The type of this sink variable.
1105 Type* type_;
1106 // The temporary variable we generate.
1107 Bvariable* bvar_;
1108 };
1109
1110 // Return the type of a sink expression.
1111
1112 Type*
do_type()1113 Sink_expression::do_type()
1114 {
1115 if (this->type_ == NULL)
1116 return Type::make_sink_type();
1117 return this->type_;
1118 }
1119
1120 // Determine the type of a sink expression.
1121
1122 void
do_determine_type(const Type_context * context)1123 Sink_expression::do_determine_type(const Type_context* context)
1124 {
1125 if (context->type != NULL)
1126 this->type_ = context->type;
1127 }
1128
1129 // Return a temporary variable for a sink expression. This will
1130 // presumably be a write-only variable which the middle-end will drop.
1131
1132 Bexpression*
do_get_backend(Translate_context * context)1133 Sink_expression::do_get_backend(Translate_context* context)
1134 {
1135 Location loc = this->location();
1136 Gogo* gogo = context->gogo();
1137 if (this->bvar_ == NULL)
1138 {
1139 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
1140 Named_object* fn = context->function();
1141 go_assert(fn != NULL);
1142 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
1143 Btype* bt = this->type_->get_backend(context->gogo());
1144 Bstatement* decl;
1145 this->bvar_ =
1146 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
1147 false, loc, &decl);
1148 Bexpression* var_ref =
1149 gogo->backend()->var_expression(this->bvar_, loc);
1150 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
1151 return var_ref;
1152 }
1153 return gogo->backend()->var_expression(this->bvar_, loc);
1154 }
1155
1156 // Ast dump for sink expression.
1157
1158 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1159 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1160 {
1161 ast_dump_context->ostream() << "_" ;
1162 }
1163
1164 // Make a sink expression.
1165
1166 Expression*
make_sink(Location location)1167 Expression::make_sink(Location location)
1168 {
1169 return new Sink_expression(location);
1170 }
1171
1172 // Class Func_expression.
1173
1174 // FIXME: Can a function expression appear in a constant expression?
1175 // The value is unchanging. Initializing a constant to the address of
1176 // a function seems like it could work, though there might be little
1177 // point to it.
1178
1179 // Traversal.
1180
1181 int
do_traverse(Traverse * traverse)1182 Func_expression::do_traverse(Traverse* traverse)
1183 {
1184 return (this->closure_ == NULL
1185 ? TRAVERSE_CONTINUE
1186 : Expression::traverse(&this->closure_, traverse));
1187 }
1188
1189 // Return the type of a function expression.
1190
1191 Type*
do_type()1192 Func_expression::do_type()
1193 {
1194 if (this->function_->is_function())
1195 return this->function_->func_value()->type();
1196 else if (this->function_->is_function_declaration())
1197 return this->function_->func_declaration_value()->type();
1198 else
1199 go_unreachable();
1200 }
1201
1202 // Get the backend representation for the code of a function expression.
1203
1204 Bexpression*
get_code_pointer(Gogo * gogo,Named_object * no,Location loc)1205 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1206 {
1207 Function_type* fntype;
1208 if (no->is_function())
1209 fntype = no->func_value()->type();
1210 else if (no->is_function_declaration())
1211 fntype = no->func_declaration_value()->type();
1212 else
1213 go_unreachable();
1214
1215 // Builtin functions are handled specially by Call_expression. We
1216 // can't take their address.
1217 if (fntype->is_builtin())
1218 {
1219 go_error_at(loc,
1220 "invalid use of special builtin function %qs; must be called",
1221 no->message_name().c_str());
1222 return gogo->backend()->error_expression();
1223 }
1224
1225 Bfunction* fndecl;
1226 if (no->is_function())
1227 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1228 else if (no->is_function_declaration())
1229 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1230 else
1231 go_unreachable();
1232
1233 return gogo->backend()->function_code_expression(fndecl, loc);
1234 }
1235
1236 // Get the backend representation for a function expression. This is used when
1237 // we take the address of a function rather than simply calling it. A func
1238 // value is represented as a pointer to a block of memory. The first
1239 // word of that memory is a pointer to the function code. The
1240 // remaining parts of that memory are the addresses of variables that
1241 // the function closes over.
1242
1243 Bexpression*
do_get_backend(Translate_context * context)1244 Func_expression::do_get_backend(Translate_context* context)
1245 {
1246 // If there is no closure, just use the function descriptor.
1247 if (this->closure_ == NULL)
1248 {
1249 Gogo* gogo = context->gogo();
1250 Named_object* no = this->function_;
1251 Expression* descriptor;
1252 if (no->is_function())
1253 descriptor = no->func_value()->descriptor(gogo, no);
1254 else if (no->is_function_declaration())
1255 {
1256 if (no->func_declaration_value()->type()->is_builtin())
1257 {
1258 go_error_at(this->location(),
1259 ("invalid use of special builtin function %qs; "
1260 "must be called"),
1261 no->message_name().c_str());
1262 return gogo->backend()->error_expression();
1263 }
1264 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1265 }
1266 else
1267 go_unreachable();
1268
1269 Bexpression* bdesc = descriptor->get_backend(context);
1270 return gogo->backend()->address_expression(bdesc, this->location());
1271 }
1272
1273 go_assert(this->function_->func_value()->enclosing() != NULL);
1274
1275 // If there is a closure, then the closure is itself the function
1276 // expression. It is a pointer to a struct whose first field points
1277 // to the function code and whose remaining fields are the addresses
1278 // of the closed-over variables.
1279 Bexpression *bexpr = this->closure_->get_backend(context);
1280
1281 // Introduce a backend type conversion, to account for any differences
1282 // between the argument type (function descriptor, struct with a
1283 // single field) and the closure (struct with multiple fields).
1284 Gogo* gogo = context->gogo();
1285 Btype *btype = this->type()->get_backend(gogo);
1286 return gogo->backend()->convert_expression(btype, bexpr, this->location());
1287 }
1288
1289 // Ast dump for function.
1290
1291 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1292 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1293 {
1294 ast_dump_context->ostream() << this->function_->name();
1295 if (this->closure_ != NULL)
1296 {
1297 ast_dump_context->ostream() << " {closure = ";
1298 this->closure_->dump_expression(ast_dump_context);
1299 ast_dump_context->ostream() << "}";
1300 }
1301 }
1302
1303 // Make a reference to a function in an expression.
1304
1305 Expression*
make_func_reference(Named_object * function,Expression * closure,Location location)1306 Expression::make_func_reference(Named_object* function, Expression* closure,
1307 Location location)
1308 {
1309 Func_expression* fe = new Func_expression(function, closure, location);
1310
1311 // Detect references to builtin functions and set the runtime code if
1312 // appropriate.
1313 if (function->is_function_declaration())
1314 fe->set_runtime_code(Runtime::name_to_code(function->name()));
1315 return fe;
1316 }
1317
1318 // Class Func_descriptor_expression.
1319
1320 // Constructor.
1321
Func_descriptor_expression(Named_object * fn)1322 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1323 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1324 fn_(fn), dvar_(NULL)
1325 {
1326 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1327 }
1328
1329 // Traversal.
1330
1331 int
do_traverse(Traverse *)1332 Func_descriptor_expression::do_traverse(Traverse*)
1333 {
1334 return TRAVERSE_CONTINUE;
1335 }
1336
1337 // All function descriptors have the same type.
1338
1339 Type* Func_descriptor_expression::descriptor_type;
1340
1341 void
make_func_descriptor_type()1342 Func_descriptor_expression::make_func_descriptor_type()
1343 {
1344 if (Func_descriptor_expression::descriptor_type != NULL)
1345 return;
1346 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1347 Type* struct_type = Type::make_builtin_struct_type(1, "fn", uintptr_type);
1348 Func_descriptor_expression::descriptor_type =
1349 Type::make_builtin_named_type("functionDescriptor", struct_type);
1350 }
1351
1352 Type*
do_type()1353 Func_descriptor_expression::do_type()
1354 {
1355 Func_descriptor_expression::make_func_descriptor_type();
1356 return Func_descriptor_expression::descriptor_type;
1357 }
1358
1359 // The backend representation for a function descriptor.
1360
1361 Bexpression*
do_get_backend(Translate_context * context)1362 Func_descriptor_expression::do_get_backend(Translate_context* context)
1363 {
1364 Named_object* no = this->fn_;
1365 Location loc = no->location();
1366 if (this->dvar_ != NULL)
1367 return context->backend()->var_expression(this->dvar_, loc);
1368
1369 Gogo* gogo = context->gogo();
1370 std::string var_name(gogo->function_descriptor_name(no));
1371 bool is_descriptor = false;
1372 if (no->is_function_declaration()
1373 && !no->func_declaration_value()->asm_name().empty()
1374 && Linemap::is_predeclared_location(no->location()))
1375 is_descriptor = true;
1376
1377 // The runtime package implements some functions defined in the
1378 // syscall package. Let the syscall package define the descriptor
1379 // in this case.
1380 if (gogo->compiling_runtime()
1381 && gogo->package_name() == "runtime"
1382 && no->is_function()
1383 && !no->func_value()->asm_name().empty()
1384 && no->func_value()->asm_name().compare(0, 8, "syscall.") == 0)
1385 is_descriptor = true;
1386
1387 Btype* btype = this->type()->get_backend(gogo);
1388
1389 Bvariable* bvar;
1390 std::string asm_name(go_selectively_encode_id(var_name));
1391 if (no->package() != NULL || is_descriptor)
1392 bvar = context->backend()->immutable_struct_reference(var_name, asm_name,
1393 btype, loc);
1394 else
1395 {
1396 Location bloc = Linemap::predeclared_location();
1397
1398 // The runtime package has hash/equality functions that are
1399 // referenced by type descriptors outside of the runtime, so the
1400 // function descriptors must be visible even though they are not
1401 // exported.
1402 bool is_exported_runtime = false;
1403 if (gogo->compiling_runtime()
1404 && gogo->package_name() == "runtime"
1405 && (no->name().find("hash") != std::string::npos
1406 || no->name().find("equal") != std::string::npos))
1407 is_exported_runtime = true;
1408
1409 bool is_hidden = ((no->is_function()
1410 && no->func_value()->enclosing() != NULL)
1411 || (Gogo::is_hidden_name(no->name())
1412 && !is_exported_runtime)
1413 || Gogo::is_thunk(no));
1414
1415 bvar = context->backend()->immutable_struct(var_name, asm_name,
1416 is_hidden, false,
1417 btype, bloc);
1418 Expression_list* vals = new Expression_list();
1419 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1420 Expression* init =
1421 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1422 Translate_context bcontext(gogo, NULL, NULL, NULL);
1423 bcontext.set_is_const();
1424 Bexpression* binit = init->get_backend(&bcontext);
1425 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1426 false, btype, bloc, binit);
1427 }
1428
1429 this->dvar_ = bvar;
1430 return gogo->backend()->var_expression(bvar, loc);
1431 }
1432
1433 // Print a function descriptor expression.
1434
1435 void
do_dump_expression(Ast_dump_context * context) const1436 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1437 {
1438 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1439 }
1440
1441 // Make a function descriptor expression.
1442
1443 Func_descriptor_expression*
make_func_descriptor(Named_object * fn)1444 Expression::make_func_descriptor(Named_object* fn)
1445 {
1446 return new Func_descriptor_expression(fn);
1447 }
1448
1449 // Make the function descriptor type, so that it can be converted.
1450
1451 void
make_func_descriptor_type()1452 Expression::make_func_descriptor_type()
1453 {
1454 Func_descriptor_expression::make_func_descriptor_type();
1455 }
1456
1457 // A reference to just the code of a function.
1458
1459 class Func_code_reference_expression : public Expression
1460 {
1461 public:
Func_code_reference_expression(Named_object * function,Location location)1462 Func_code_reference_expression(Named_object* function, Location location)
1463 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1464 function_(function)
1465 { }
1466
1467 protected:
1468 int
do_traverse(Traverse *)1469 do_traverse(Traverse*)
1470 { return TRAVERSE_CONTINUE; }
1471
1472 bool
do_is_static_initializer() const1473 do_is_static_initializer() const
1474 { return true; }
1475
1476 Type*
do_type()1477 do_type()
1478 { return Type::make_pointer_type(Type::make_void_type()); }
1479
1480 void
do_determine_type(const Type_context *)1481 do_determine_type(const Type_context*)
1482 { }
1483
1484 Expression*
do_copy()1485 do_copy()
1486 {
1487 return Expression::make_func_code_reference(this->function_,
1488 this->location());
1489 }
1490
1491 Bexpression*
1492 do_get_backend(Translate_context*);
1493
1494 void
do_dump_expression(Ast_dump_context * context) const1495 do_dump_expression(Ast_dump_context* context) const
1496 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1497
1498 private:
1499 // The function.
1500 Named_object* function_;
1501 };
1502
1503 // Get the backend representation for a reference to function code.
1504
1505 Bexpression*
do_get_backend(Translate_context * context)1506 Func_code_reference_expression::do_get_backend(Translate_context* context)
1507 {
1508 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1509 this->location());
1510 }
1511
1512 // Make a reference to the code of a function.
1513
1514 Expression*
make_func_code_reference(Named_object * function,Location location)1515 Expression::make_func_code_reference(Named_object* function, Location location)
1516 {
1517 return new Func_code_reference_expression(function, location);
1518 }
1519
1520 // Class Unknown_expression.
1521
1522 // Return the name of an unknown expression.
1523
1524 const std::string&
name() const1525 Unknown_expression::name() const
1526 {
1527 return this->named_object_->name();
1528 }
1529
1530 // Lower a reference to an unknown name.
1531
1532 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)1533 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1534 {
1535 Location location = this->location();
1536 Named_object* no = this->named_object_;
1537 Named_object* real;
1538 if (!no->is_unknown())
1539 real = no;
1540 else
1541 {
1542 real = no->unknown_value()->real_named_object();
1543 if (real == NULL)
1544 {
1545 if (this->is_composite_literal_key_)
1546 return this;
1547 if (!this->no_error_message_)
1548 go_error_at(location, "reference to undefined name %qs",
1549 this->named_object_->message_name().c_str());
1550 return Expression::make_error(location);
1551 }
1552 }
1553 switch (real->classification())
1554 {
1555 case Named_object::NAMED_OBJECT_CONST:
1556 return Expression::make_const_reference(real, location);
1557 case Named_object::NAMED_OBJECT_TYPE:
1558 return Expression::make_type(real->type_value(), location);
1559 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1560 if (this->is_composite_literal_key_)
1561 return this;
1562 if (!this->no_error_message_)
1563 go_error_at(location, "reference to undefined type %qs",
1564 real->message_name().c_str());
1565 return Expression::make_error(location);
1566 case Named_object::NAMED_OBJECT_VAR:
1567 real->var_value()->set_is_used();
1568 return Expression::make_var_reference(real, location);
1569 case Named_object::NAMED_OBJECT_FUNC:
1570 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1571 return Expression::make_func_reference(real, NULL, location);
1572 case Named_object::NAMED_OBJECT_PACKAGE:
1573 if (this->is_composite_literal_key_)
1574 return this;
1575 if (!this->no_error_message_)
1576 go_error_at(location, "unexpected reference to package");
1577 return Expression::make_error(location);
1578 default:
1579 go_unreachable();
1580 }
1581 }
1582
1583 // Dump the ast representation for an unknown expression to a dump context.
1584
1585 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1586 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1587 {
1588 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1589 << ")";
1590 }
1591
1592 // Make a reference to an unknown name.
1593
1594 Unknown_expression*
make_unknown_reference(Named_object * no,Location location)1595 Expression::make_unknown_reference(Named_object* no, Location location)
1596 {
1597 return new Unknown_expression(no, location);
1598 }
1599
1600 // A boolean expression.
1601
1602 class Boolean_expression : public Expression
1603 {
1604 public:
Boolean_expression(bool val,Location location)1605 Boolean_expression(bool val, Location location)
1606 : Expression(EXPRESSION_BOOLEAN, location),
1607 val_(val), type_(NULL)
1608 { }
1609
1610 static Expression*
1611 do_import(Import_expression*, Location);
1612
1613 protected:
1614 bool
do_is_constant() const1615 do_is_constant() const
1616 { return true; }
1617
1618 bool
do_is_static_initializer() const1619 do_is_static_initializer() const
1620 { return true; }
1621
1622 Type*
1623 do_type();
1624
1625 void
1626 do_determine_type(const Type_context*);
1627
1628 Expression*
do_copy()1629 do_copy()
1630 { return this; }
1631
1632 Bexpression*
do_get_backend(Translate_context * context)1633 do_get_backend(Translate_context* context)
1634 { return context->backend()->boolean_constant_expression(this->val_); }
1635
1636 int
do_inlining_cost() const1637 do_inlining_cost() const
1638 { return 1; }
1639
1640 void
do_export(Export_function_body * efb) const1641 do_export(Export_function_body* efb) const
1642 { efb->write_c_string(this->val_ ? "$true" : "$false"); }
1643
1644 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1645 do_dump_expression(Ast_dump_context* ast_dump_context) const
1646 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1647
1648 private:
1649 // The constant.
1650 bool val_;
1651 // The type as determined by context.
1652 Type* type_;
1653 };
1654
1655 // Get the type.
1656
1657 Type*
do_type()1658 Boolean_expression::do_type()
1659 {
1660 if (this->type_ == NULL)
1661 this->type_ = Type::make_boolean_type();
1662 return this->type_;
1663 }
1664
1665 // Set the type from the context.
1666
1667 void
do_determine_type(const Type_context * context)1668 Boolean_expression::do_determine_type(const Type_context* context)
1669 {
1670 if (this->type_ != NULL && !this->type_->is_abstract())
1671 ;
1672 else if (context->type != NULL && context->type->is_boolean_type())
1673 this->type_ = context->type;
1674 else if (!context->may_be_abstract)
1675 this->type_ = Type::lookup_bool_type();
1676 }
1677
1678 // Import a boolean constant.
1679
1680 Expression*
do_import(Import_expression * imp,Location loc)1681 Boolean_expression::do_import(Import_expression* imp, Location loc)
1682 {
1683 if (imp->version() >= EXPORT_FORMAT_V3)
1684 imp->require_c_string("$");
1685 if (imp->peek_char() == 't')
1686 {
1687 imp->require_c_string("true");
1688 return Expression::make_boolean(true, loc);
1689 }
1690 else
1691 {
1692 imp->require_c_string("false");
1693 return Expression::make_boolean(false, loc);
1694 }
1695 }
1696
1697 // Make a boolean expression.
1698
1699 Expression*
make_boolean(bool val,Location location)1700 Expression::make_boolean(bool val, Location location)
1701 {
1702 return new Boolean_expression(val, location);
1703 }
1704
1705 // Class String_expression.
1706
1707 // Get the type.
1708
1709 Type*
do_type()1710 String_expression::do_type()
1711 {
1712 if (this->type_ == NULL)
1713 this->type_ = Type::make_string_type();
1714 return this->type_;
1715 }
1716
1717 // Set the type from the context.
1718
1719 void
do_determine_type(const Type_context * context)1720 String_expression::do_determine_type(const Type_context* context)
1721 {
1722 if (this->type_ != NULL && !this->type_->is_abstract())
1723 ;
1724 else if (context->type != NULL && context->type->is_string_type())
1725 this->type_ = context->type;
1726 else if (!context->may_be_abstract)
1727 this->type_ = Type::lookup_string_type();
1728 }
1729
1730 // Build a string constant.
1731
1732 Bexpression*
do_get_backend(Translate_context * context)1733 String_expression::do_get_backend(Translate_context* context)
1734 {
1735 Gogo* gogo = context->gogo();
1736 Btype* btype = Type::make_string_type()->get_backend(gogo);
1737
1738 Location loc = this->location();
1739 std::vector<Bexpression*> init(2);
1740 Bexpression* str_cst =
1741 gogo->backend()->string_constant_expression(this->val_);
1742 init[0] = gogo->backend()->address_expression(str_cst, loc);
1743
1744 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1745 mpz_t lenval;
1746 mpz_init_set_ui(lenval, this->val_.length());
1747 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1748 mpz_clear(lenval);
1749
1750 return gogo->backend()->constructor_expression(btype, init, loc);
1751 }
1752
1753 // Write string literal to string dump.
1754
1755 void
export_string(String_dump * exp,const String_expression * str)1756 String_expression::export_string(String_dump* exp,
1757 const String_expression* str)
1758 {
1759 std::string s;
1760 s.reserve(str->val_.length() * 4 + 2);
1761 s += '"';
1762 for (std::string::const_iterator p = str->val_.begin();
1763 p != str->val_.end();
1764 ++p)
1765 {
1766 if (*p == '\\' || *p == '"')
1767 {
1768 s += '\\';
1769 s += *p;
1770 }
1771 else if (*p >= 0x20 && *p < 0x7f)
1772 s += *p;
1773 else if (*p == '\n')
1774 s += "\\n";
1775 else if (*p == '\t')
1776 s += "\\t";
1777 else
1778 {
1779 s += "\\x";
1780 unsigned char c = *p;
1781 unsigned int dig = c >> 4;
1782 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1783 dig = c & 0xf;
1784 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1785 }
1786 }
1787 s += '"';
1788 exp->write_string(s);
1789 }
1790
1791 // Export a string expression.
1792
1793 void
do_export(Export_function_body * efb) const1794 String_expression::do_export(Export_function_body* efb) const
1795 {
1796 String_expression::export_string(efb, this);
1797 }
1798
1799 // Import a string expression.
1800
1801 Expression*
do_import(Import_expression * imp,Location loc)1802 String_expression::do_import(Import_expression* imp, Location loc)
1803 {
1804 imp->require_c_string("\"");
1805 std::string val;
1806 while (true)
1807 {
1808 int c = imp->get_char();
1809 if (c == '"' || c == -1)
1810 break;
1811 if (c != '\\')
1812 val += static_cast<char>(c);
1813 else
1814 {
1815 c = imp->get_char();
1816 if (c == '\\' || c == '"')
1817 val += static_cast<char>(c);
1818 else if (c == 'n')
1819 val += '\n';
1820 else if (c == 't')
1821 val += '\t';
1822 else if (c == 'x')
1823 {
1824 c = imp->get_char();
1825 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1826 c = imp->get_char();
1827 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1828 char v = (vh << 4) | vl;
1829 val += v;
1830 }
1831 else
1832 {
1833 go_error_at(imp->location(), "bad string constant");
1834 return Expression::make_error(loc);
1835 }
1836 }
1837 }
1838 return Expression::make_string(val, loc);
1839 }
1840
1841 // Ast dump for string expression.
1842
1843 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1844 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1845 {
1846 String_expression::export_string(ast_dump_context, this);
1847 }
1848
1849 // Make a string expression with abstract string type (common case).
1850
1851 Expression*
make_string(const std::string & val,Location location)1852 Expression::make_string(const std::string& val, Location location)
1853 {
1854 return new String_expression(val, NULL, location);
1855 }
1856
1857 // Make a string expression with a specific string type.
1858
1859 Expression*
make_string_typed(const std::string & val,Type * type,Location location)1860 Expression::make_string_typed(const std::string& val, Type* type, Location location)
1861 {
1862 return new String_expression(val, type, location);
1863 }
1864
1865 // An expression that evaluates to some characteristic of a string.
1866 // This is used when indexing, bound-checking, or nil checking a string.
1867
1868 class String_info_expression : public Expression
1869 {
1870 public:
String_info_expression(Expression * string,String_info string_info,Location location)1871 String_info_expression(Expression* string, String_info string_info,
1872 Location location)
1873 : Expression(EXPRESSION_STRING_INFO, location),
1874 string_(string), string_info_(string_info)
1875 { }
1876
1877 protected:
1878 Type*
1879 do_type();
1880
1881 void
do_determine_type(const Type_context *)1882 do_determine_type(const Type_context*)
1883 { go_unreachable(); }
1884
1885 Expression*
do_copy()1886 do_copy()
1887 {
1888 return new String_info_expression(this->string_->copy(), this->string_info_,
1889 this->location());
1890 }
1891
1892 Bexpression*
1893 do_get_backend(Translate_context* context);
1894
1895 void
1896 do_dump_expression(Ast_dump_context*) const;
1897
1898 void
do_issue_nil_check()1899 do_issue_nil_check()
1900 { this->string_->issue_nil_check(); }
1901
1902 private:
1903 // The string for which we are getting information.
1904 Expression* string_;
1905 // What information we want.
1906 String_info string_info_;
1907 };
1908
1909 // Return the type of the string info.
1910
1911 Type*
do_type()1912 String_info_expression::do_type()
1913 {
1914 switch (this->string_info_)
1915 {
1916 case STRING_INFO_DATA:
1917 {
1918 Type* byte_type = Type::lookup_integer_type("uint8");
1919 return Type::make_pointer_type(byte_type);
1920 }
1921 case STRING_INFO_LENGTH:
1922 return Type::lookup_integer_type("int");
1923 default:
1924 go_unreachable();
1925 }
1926 }
1927
1928 // Return string information in GENERIC.
1929
1930 Bexpression*
do_get_backend(Translate_context * context)1931 String_info_expression::do_get_backend(Translate_context* context)
1932 {
1933 Gogo* gogo = context->gogo();
1934
1935 Bexpression* bstring = this->string_->get_backend(context);
1936 switch (this->string_info_)
1937 {
1938 case STRING_INFO_DATA:
1939 case STRING_INFO_LENGTH:
1940 return gogo->backend()->struct_field_expression(bstring,
1941 this->string_info_,
1942 this->location());
1943 break;
1944 default:
1945 go_unreachable();
1946 }
1947 }
1948
1949 // Dump ast representation for a type info expression.
1950
1951 void
do_dump_expression(Ast_dump_context * ast_dump_context) const1952 String_info_expression::do_dump_expression(
1953 Ast_dump_context* ast_dump_context) const
1954 {
1955 ast_dump_context->ostream() << "stringinfo(";
1956 this->string_->dump_expression(ast_dump_context);
1957 ast_dump_context->ostream() << ",";
1958 ast_dump_context->ostream() <<
1959 (this->string_info_ == STRING_INFO_DATA ? "data"
1960 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1961 : "unknown");
1962 ast_dump_context->ostream() << ")";
1963 }
1964
1965 // Make a string info expression.
1966
1967 Expression*
make_string_info(Expression * string,String_info string_info,Location location)1968 Expression::make_string_info(Expression* string, String_info string_info,
1969 Location location)
1970 {
1971 return new String_info_expression(string, string_info, location);
1972 }
1973
1974 // Make an integer expression.
1975
1976 class Integer_expression : public Expression
1977 {
1978 public:
Integer_expression(const mpz_t * val,Type * type,bool is_character_constant,Location location)1979 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1980 Location location)
1981 : Expression(EXPRESSION_INTEGER, location),
1982 type_(type), is_character_constant_(is_character_constant)
1983 { mpz_init_set(this->val_, *val); }
1984
1985 static Expression*
1986 do_import(Import_expression*, Location);
1987
1988 // Write VAL to string dump.
1989 static void
1990 export_integer(String_dump* exp, const mpz_t val);
1991
1992 // Write VAL to dump context.
1993 static void
1994 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1995
1996 protected:
1997 bool
do_is_constant() const1998 do_is_constant() const
1999 { return true; }
2000
2001 bool
do_is_static_initializer() const2002 do_is_static_initializer() const
2003 { return true; }
2004
2005 bool
2006 do_numeric_constant_value(Numeric_constant* nc) const;
2007
2008 Type*
2009 do_type();
2010
2011 void
2012 do_determine_type(const Type_context* context);
2013
2014 void
2015 do_check_types(Gogo*);
2016
2017 Bexpression*
2018 do_get_backend(Translate_context*);
2019
2020 Expression*
do_copy()2021 do_copy()
2022 {
2023 if (this->is_character_constant_)
2024 return Expression::make_character(&this->val_,
2025 (this->type_ == NULL
2026 ? NULL
2027 : this->type_->copy_expressions()),
2028 this->location());
2029 else
2030 return Expression::make_integer_z(&this->val_,
2031 (this->type_ == NULL
2032 ? NULL
2033 : this->type_->copy_expressions()),
2034 this->location());
2035 }
2036
2037 int
do_inlining_cost() const2038 do_inlining_cost() const
2039 {
2040 if (this->type_ != NULL && this->type_->named_type() != NULL)
2041 return 0x100000;
2042 return 1;
2043 }
2044
2045 void
2046 do_export(Export_function_body*) const;
2047
2048 void
2049 do_dump_expression(Ast_dump_context*) const;
2050
2051 private:
2052 // The integer value.
2053 mpz_t val_;
2054 // The type so far.
2055 Type* type_;
2056 // Whether this is a character constant.
2057 bool is_character_constant_;
2058 };
2059
2060 // Return a numeric constant for this expression. We have to mark
2061 // this as a character when appropriate.
2062
2063 bool
do_numeric_constant_value(Numeric_constant * nc) const2064 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
2065 {
2066 if (this->is_character_constant_)
2067 nc->set_rune(this->type_, this->val_);
2068 else
2069 nc->set_int(this->type_, this->val_);
2070 return true;
2071 }
2072
2073 // Return the current type. If we haven't set the type yet, we return
2074 // an abstract integer type.
2075
2076 Type*
do_type()2077 Integer_expression::do_type()
2078 {
2079 if (this->type_ == NULL)
2080 {
2081 if (this->is_character_constant_)
2082 this->type_ = Type::make_abstract_character_type();
2083 else
2084 this->type_ = Type::make_abstract_integer_type();
2085 }
2086 return this->type_;
2087 }
2088
2089 // Set the type of the integer value. Here we may switch from an
2090 // abstract type to a real type.
2091
2092 void
do_determine_type(const Type_context * context)2093 Integer_expression::do_determine_type(const Type_context* context)
2094 {
2095 if (this->type_ != NULL && !this->type_->is_abstract())
2096 ;
2097 else if (context->type != NULL && context->type->is_numeric_type())
2098 this->type_ = context->type;
2099 else if (!context->may_be_abstract)
2100 {
2101 if (this->is_character_constant_)
2102 this->type_ = Type::lookup_integer_type("int32");
2103 else
2104 this->type_ = Type::lookup_integer_type("int");
2105 }
2106 }
2107
2108 // Check the type of an integer constant.
2109
2110 void
do_check_types(Gogo *)2111 Integer_expression::do_check_types(Gogo*)
2112 {
2113 Type* type = this->type_;
2114 if (type == NULL)
2115 return;
2116 Numeric_constant nc;
2117 if (this->is_character_constant_)
2118 nc.set_rune(NULL, this->val_);
2119 else
2120 nc.set_int(NULL, this->val_);
2121 if (!nc.set_type(type, true, this->location()))
2122 this->set_is_error();
2123 }
2124
2125 // Get the backend representation for an integer constant.
2126
2127 Bexpression*
do_get_backend(Translate_context * context)2128 Integer_expression::do_get_backend(Translate_context* context)
2129 {
2130 if (this->is_error_expression()
2131 || (this->type_ != NULL && this->type_->is_error_type()))
2132 {
2133 go_assert(saw_errors());
2134 return context->gogo()->backend()->error_expression();
2135 }
2136
2137 Type* resolved_type = NULL;
2138 if (this->type_ != NULL && !this->type_->is_abstract())
2139 resolved_type = this->type_;
2140 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2141 {
2142 // We are converting to an abstract floating point type.
2143 resolved_type = Type::lookup_float_type("float64");
2144 }
2145 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2146 {
2147 // We are converting to an abstract complex type.
2148 resolved_type = Type::lookup_complex_type("complex128");
2149 }
2150 else
2151 {
2152 // If we still have an abstract type here, then this is being
2153 // used in a constant expression which didn't get reduced for
2154 // some reason. Use a type which will fit the value. We use <,
2155 // not <=, because we need an extra bit for the sign bit.
2156 int bits = mpz_sizeinbase(this->val_, 2);
2157 Type* int_type = Type::lookup_integer_type("int");
2158 if (bits < int_type->integer_type()->bits())
2159 resolved_type = int_type;
2160 else if (bits < 64)
2161 resolved_type = Type::lookup_integer_type("int64");
2162 else
2163 {
2164 if (!saw_errors())
2165 go_error_at(this->location(),
2166 "unknown type for large integer constant");
2167 return context->gogo()->backend()->error_expression();
2168 }
2169 }
2170 Numeric_constant nc;
2171 nc.set_int(resolved_type, this->val_);
2172 return Expression::backend_numeric_constant_expression(context, &nc);
2173 }
2174
2175 // Write VAL to export data.
2176
2177 void
export_integer(String_dump * exp,const mpz_t val)2178 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
2179 {
2180 char* s = mpz_get_str(NULL, 10, val);
2181 exp->write_c_string(s);
2182 free(s);
2183 }
2184
2185 // Export an integer in a constant expression.
2186
2187 void
do_export(Export_function_body * efb) const2188 Integer_expression::do_export(Export_function_body* efb) const
2189 {
2190 bool added_type = false;
2191 if (this->type_ != NULL
2192 && !this->type_->is_abstract()
2193 && this->type_ != efb->type_context())
2194 {
2195 efb->write_c_string("$convert(");
2196 efb->write_type(this->type_);
2197 efb->write_c_string(", ");
2198 added_type = true;
2199 }
2200
2201 Integer_expression::export_integer(efb, this->val_);
2202 if (this->is_character_constant_)
2203 efb->write_c_string("'");
2204 // A trailing space lets us reliably identify the end of the number.
2205 efb->write_c_string(" ");
2206
2207 if (added_type)
2208 efb->write_c_string(")");
2209 }
2210
2211 // Import an integer, floating point, or complex value. This handles
2212 // all these types because they all start with digits.
2213
2214 Expression*
do_import(Import_expression * imp,Location loc)2215 Integer_expression::do_import(Import_expression* imp, Location loc)
2216 {
2217 std::string num = imp->read_identifier();
2218 imp->require_c_string(" ");
2219 if (!num.empty() && num[num.length() - 1] == 'i')
2220 {
2221 mpfr_t real;
2222 size_t plus_pos = num.find('+', 1);
2223 size_t minus_pos = num.find('-', 1);
2224 size_t pos;
2225 if (plus_pos == std::string::npos)
2226 pos = minus_pos;
2227 else if (minus_pos == std::string::npos)
2228 pos = plus_pos;
2229 else
2230 {
2231 go_error_at(imp->location(), "bad number in import data: %qs",
2232 num.c_str());
2233 return Expression::make_error(loc);
2234 }
2235 if (pos == std::string::npos)
2236 mpfr_set_ui(real, 0, GMP_RNDN);
2237 else
2238 {
2239 std::string real_str = num.substr(0, pos);
2240 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
2241 {
2242 go_error_at(imp->location(), "bad number in import data: %qs",
2243 real_str.c_str());
2244 return Expression::make_error(loc);
2245 }
2246 }
2247
2248 std::string imag_str;
2249 if (pos == std::string::npos)
2250 imag_str = num;
2251 else
2252 imag_str = num.substr(pos);
2253 imag_str = imag_str.substr(0, imag_str.size() - 1);
2254 mpfr_t imag;
2255 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2256 {
2257 go_error_at(imp->location(), "bad number in import data: %qs",
2258 imag_str.c_str());
2259 return Expression::make_error(loc);
2260 }
2261 mpc_t cval;
2262 mpc_init2(cval, mpc_precision);
2263 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2264 mpfr_clear(real);
2265 mpfr_clear(imag);
2266 Expression* ret = Expression::make_complex(&cval, NULL, loc);
2267 mpc_clear(cval);
2268 return ret;
2269 }
2270 else if (num.find('.') == std::string::npos
2271 && num.find('E') == std::string::npos)
2272 {
2273 bool is_character_constant = (!num.empty()
2274 && num[num.length() - 1] == '\'');
2275 if (is_character_constant)
2276 num = num.substr(0, num.length() - 1);
2277 mpz_t val;
2278 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2279 {
2280 go_error_at(imp->location(), "bad number in import data: %qs",
2281 num.c_str());
2282 return Expression::make_error(loc);
2283 }
2284 Expression* ret;
2285 if (is_character_constant)
2286 ret = Expression::make_character(&val, NULL, loc);
2287 else
2288 ret = Expression::make_integer_z(&val, NULL, loc);
2289 mpz_clear(val);
2290 return ret;
2291 }
2292 else
2293 {
2294 mpfr_t val;
2295 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2296 {
2297 go_error_at(imp->location(), "bad number in import data: %qs",
2298 num.c_str());
2299 return Expression::make_error(loc);
2300 }
2301 Expression* ret = Expression::make_float(&val, NULL, loc);
2302 mpfr_clear(val);
2303 return ret;
2304 }
2305 }
2306 // Ast dump for integer expression.
2307
2308 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2309 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2310 {
2311 if (this->is_character_constant_)
2312 ast_dump_context->ostream() << '\'';
2313 Integer_expression::export_integer(ast_dump_context, this->val_);
2314 if (this->is_character_constant_)
2315 ast_dump_context->ostream() << '\'';
2316 }
2317
2318 // Build a new integer value from a multi-precision integer.
2319
2320 Expression*
make_integer_z(const mpz_t * val,Type * type,Location location)2321 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2322 {
2323 return new Integer_expression(val, type, false, location);
2324 }
2325
2326 // Build a new integer value from an unsigned long.
2327
2328 Expression*
make_integer_ul(unsigned long val,Type * type,Location location)2329 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2330 {
2331 mpz_t zval;
2332 mpz_init_set_ui(zval, val);
2333 Expression* ret = Expression::make_integer_z(&zval, type, location);
2334 mpz_clear(zval);
2335 return ret;
2336 }
2337
2338 // Build a new integer value from a signed long.
2339
2340 Expression*
make_integer_sl(long val,Type * type,Location location)2341 Expression::make_integer_sl(long val, Type *type, Location location)
2342 {
2343 mpz_t zval;
2344 mpz_init_set_si(zval, val);
2345 Expression* ret = Expression::make_integer_z(&zval, type, location);
2346 mpz_clear(zval);
2347 return ret;
2348 }
2349
2350 // Store an int64_t in an uninitialized mpz_t.
2351
2352 static void
set_mpz_from_int64(mpz_t * zval,int64_t val)2353 set_mpz_from_int64(mpz_t* zval, int64_t val)
2354 {
2355 if (val >= 0)
2356 {
2357 unsigned long ul = static_cast<unsigned long>(val);
2358 if (static_cast<int64_t>(ul) == val)
2359 {
2360 mpz_init_set_ui(*zval, ul);
2361 return;
2362 }
2363 }
2364 uint64_t uv;
2365 if (val >= 0)
2366 uv = static_cast<uint64_t>(val);
2367 else
2368 uv = static_cast<uint64_t>(- val);
2369 unsigned long ul = uv & 0xffffffffUL;
2370 mpz_init_set_ui(*zval, ul);
2371 mpz_t hval;
2372 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2373 mpz_mul_2exp(hval, hval, 32);
2374 mpz_add(*zval, *zval, hval);
2375 mpz_clear(hval);
2376 if (val < 0)
2377 mpz_neg(*zval, *zval);
2378 }
2379
2380 // Build a new integer value from an int64_t.
2381
2382 Expression*
make_integer_int64(int64_t val,Type * type,Location location)2383 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2384 {
2385 mpz_t zval;
2386 set_mpz_from_int64(&zval, val);
2387 Expression* ret = Expression::make_integer_z(&zval, type, location);
2388 mpz_clear(zval);
2389 return ret;
2390 }
2391
2392 // Build a new character constant value.
2393
2394 Expression*
make_character(const mpz_t * val,Type * type,Location location)2395 Expression::make_character(const mpz_t* val, Type* type, Location location)
2396 {
2397 return new Integer_expression(val, type, true, location);
2398 }
2399
2400 // Floats.
2401
2402 class Float_expression : public Expression
2403 {
2404 public:
Float_expression(const mpfr_t * val,Type * type,Location location)2405 Float_expression(const mpfr_t* val, Type* type, Location location)
2406 : Expression(EXPRESSION_FLOAT, location),
2407 type_(type)
2408 {
2409 mpfr_init_set(this->val_, *val, GMP_RNDN);
2410 }
2411
2412 // Write VAL to export data.
2413 static void
2414 export_float(String_dump* exp, const mpfr_t val);
2415
2416 // Write VAL to dump file.
2417 static void
2418 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2419
2420 protected:
2421 bool
do_is_constant() const2422 do_is_constant() const
2423 { return true; }
2424
2425 bool
do_is_static_initializer() const2426 do_is_static_initializer() const
2427 { return true; }
2428
2429 bool
do_numeric_constant_value(Numeric_constant * nc) const2430 do_numeric_constant_value(Numeric_constant* nc) const
2431 {
2432 nc->set_float(this->type_, this->val_);
2433 return true;
2434 }
2435
2436 Type*
2437 do_type();
2438
2439 void
2440 do_determine_type(const Type_context*);
2441
2442 void
2443 do_check_types(Gogo*);
2444
2445 Expression*
do_copy()2446 do_copy()
2447 { return Expression::make_float(&this->val_,
2448 (this->type_ == NULL
2449 ? NULL
2450 : this->type_->copy_expressions()),
2451 this->location()); }
2452
2453 Bexpression*
2454 do_get_backend(Translate_context*);
2455
2456 int
do_inlining_cost() const2457 do_inlining_cost() const
2458 {
2459 if (this->type_ != NULL && this->type_->named_type() != NULL)
2460 return 0x100000;
2461 return 1;
2462 }
2463
2464 void
2465 do_export(Export_function_body*) const;
2466
2467 void
2468 do_dump_expression(Ast_dump_context*) const;
2469
2470 private:
2471 // The floating point value.
2472 mpfr_t val_;
2473 // The type so far.
2474 Type* type_;
2475 };
2476
2477 // Return the current type. If we haven't set the type yet, we return
2478 // an abstract float type.
2479
2480 Type*
do_type()2481 Float_expression::do_type()
2482 {
2483 if (this->type_ == NULL)
2484 this->type_ = Type::make_abstract_float_type();
2485 return this->type_;
2486 }
2487
2488 // Set the type of the float value. Here we may switch from an
2489 // abstract type to a real type.
2490
2491 void
do_determine_type(const Type_context * context)2492 Float_expression::do_determine_type(const Type_context* context)
2493 {
2494 if (this->type_ != NULL && !this->type_->is_abstract())
2495 ;
2496 else if (context->type != NULL
2497 && (context->type->integer_type() != NULL
2498 || context->type->float_type() != NULL
2499 || context->type->complex_type() != NULL))
2500 this->type_ = context->type;
2501 else if (!context->may_be_abstract)
2502 this->type_ = Type::lookup_float_type("float64");
2503 }
2504
2505 // Check the type of a float value.
2506
2507 void
do_check_types(Gogo *)2508 Float_expression::do_check_types(Gogo*)
2509 {
2510 Type* type = this->type_;
2511 if (type == NULL)
2512 return;
2513 Numeric_constant nc;
2514 nc.set_float(NULL, this->val_);
2515 if (!nc.set_type(this->type_, true, this->location()))
2516 this->set_is_error();
2517 }
2518
2519 // Get the backend representation for a float constant.
2520
2521 Bexpression*
do_get_backend(Translate_context * context)2522 Float_expression::do_get_backend(Translate_context* context)
2523 {
2524 if (this->is_error_expression()
2525 || (this->type_ != NULL && this->type_->is_error_type()))
2526 {
2527 go_assert(saw_errors());
2528 return context->gogo()->backend()->error_expression();
2529 }
2530
2531 Type* resolved_type;
2532 if (this->type_ != NULL && !this->type_->is_abstract())
2533 resolved_type = this->type_;
2534 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2535 {
2536 // We have an abstract integer type. We just hope for the best.
2537 resolved_type = Type::lookup_integer_type("int");
2538 }
2539 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2540 {
2541 // We are converting to an abstract complex type.
2542 resolved_type = Type::lookup_complex_type("complex128");
2543 }
2544 else
2545 {
2546 // If we still have an abstract type here, then this is being
2547 // used in a constant expression which didn't get reduced. We
2548 // just use float64 and hope for the best.
2549 resolved_type = Type::lookup_float_type("float64");
2550 }
2551
2552 Numeric_constant nc;
2553 nc.set_float(resolved_type, this->val_);
2554 return Expression::backend_numeric_constant_expression(context, &nc);
2555 }
2556
2557 // Write a floating point number to a string dump.
2558
2559 void
export_float(String_dump * exp,const mpfr_t val)2560 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2561 {
2562 mp_exp_t exponent;
2563 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2564 if (*s == '-')
2565 exp->write_c_string("-");
2566 exp->write_c_string("0.");
2567 exp->write_c_string(*s == '-' ? s + 1 : s);
2568 mpfr_free_str(s);
2569 char buf[30];
2570 snprintf(buf, sizeof buf, "E%ld", exponent);
2571 exp->write_c_string(buf);
2572 }
2573
2574 // Export a floating point number in a constant expression.
2575
2576 void
do_export(Export_function_body * efb) const2577 Float_expression::do_export(Export_function_body* efb) const
2578 {
2579 bool added_type = false;
2580 if (this->type_ != NULL
2581 && !this->type_->is_abstract()
2582 && this->type_ != efb->type_context())
2583 {
2584 efb->write_c_string("$convert(");
2585 efb->write_type(this->type_);
2586 efb->write_c_string(", ");
2587 added_type = true;
2588 }
2589
2590 Float_expression::export_float(efb, this->val_);
2591 // A trailing space lets us reliably identify the end of the number.
2592 efb->write_c_string(" ");
2593
2594 if (added_type)
2595 efb->write_c_string(")");
2596 }
2597
2598 // Dump a floating point number to the dump file.
2599
2600 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2601 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2602 {
2603 Float_expression::export_float(ast_dump_context, this->val_);
2604 }
2605
2606 // Make a float expression.
2607
2608 Expression*
make_float(const mpfr_t * val,Type * type,Location location)2609 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2610 {
2611 return new Float_expression(val, type, location);
2612 }
2613
2614 // Complex numbers.
2615
2616 class Complex_expression : public Expression
2617 {
2618 public:
Complex_expression(const mpc_t * val,Type * type,Location location)2619 Complex_expression(const mpc_t* val, Type* type, Location location)
2620 : Expression(EXPRESSION_COMPLEX, location),
2621 type_(type)
2622 {
2623 mpc_init2(this->val_, mpc_precision);
2624 mpc_set(this->val_, *val, MPC_RNDNN);
2625 }
2626
2627 // Write VAL to string dump.
2628 static void
2629 export_complex(String_dump* exp, const mpc_t val);
2630
2631 // Write REAL/IMAG to dump context.
2632 static void
2633 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2634
2635 protected:
2636 bool
do_is_constant() const2637 do_is_constant() const
2638 { return true; }
2639
2640 bool
do_is_static_initializer() const2641 do_is_static_initializer() const
2642 { return true; }
2643
2644 bool
do_numeric_constant_value(Numeric_constant * nc) const2645 do_numeric_constant_value(Numeric_constant* nc) const
2646 {
2647 nc->set_complex(this->type_, this->val_);
2648 return true;
2649 }
2650
2651 Type*
2652 do_type();
2653
2654 void
2655 do_determine_type(const Type_context*);
2656
2657 void
2658 do_check_types(Gogo*);
2659
2660 Expression*
do_copy()2661 do_copy()
2662 {
2663 return Expression::make_complex(&this->val_,
2664 (this->type_ == NULL
2665 ? NULL
2666 : this->type_->copy_expressions()),
2667 this->location());
2668 }
2669
2670 Bexpression*
2671 do_get_backend(Translate_context*);
2672
2673 int
do_inlining_cost() const2674 do_inlining_cost() const
2675 {
2676 if (this->type_ != NULL && this->type_->named_type() != NULL)
2677 return 0x100000;
2678 return 2;
2679 }
2680
2681 void
2682 do_export(Export_function_body*) const;
2683
2684 void
2685 do_dump_expression(Ast_dump_context*) const;
2686
2687 private:
2688 // The complex value.
2689 mpc_t val_;
2690 // The type if known.
2691 Type* type_;
2692 };
2693
2694 // Return the current type. If we haven't set the type yet, we return
2695 // an abstract complex type.
2696
2697 Type*
do_type()2698 Complex_expression::do_type()
2699 {
2700 if (this->type_ == NULL)
2701 this->type_ = Type::make_abstract_complex_type();
2702 return this->type_;
2703 }
2704
2705 // Set the type of the complex value. Here we may switch from an
2706 // abstract type to a real type.
2707
2708 void
do_determine_type(const Type_context * context)2709 Complex_expression::do_determine_type(const Type_context* context)
2710 {
2711 if (this->type_ != NULL && !this->type_->is_abstract())
2712 ;
2713 else if (context->type != NULL && context->type->is_numeric_type())
2714 this->type_ = context->type;
2715 else if (!context->may_be_abstract)
2716 this->type_ = Type::lookup_complex_type("complex128");
2717 }
2718
2719 // Check the type of a complex value.
2720
2721 void
do_check_types(Gogo *)2722 Complex_expression::do_check_types(Gogo*)
2723 {
2724 Type* type = this->type_;
2725 if (type == NULL)
2726 return;
2727 Numeric_constant nc;
2728 nc.set_complex(NULL, this->val_);
2729 if (!nc.set_type(this->type_, true, this->location()))
2730 this->set_is_error();
2731 }
2732
2733 // Get the backend representation for a complex constant.
2734
2735 Bexpression*
do_get_backend(Translate_context * context)2736 Complex_expression::do_get_backend(Translate_context* context)
2737 {
2738 if (this->is_error_expression()
2739 || (this->type_ != NULL && this->type_->is_error_type()))
2740 {
2741 go_assert(saw_errors());
2742 return context->gogo()->backend()->error_expression();
2743 }
2744
2745 Type* resolved_type;
2746 if (this->type_ != NULL && !this->type_->is_abstract())
2747 resolved_type = this->type_;
2748 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2749 {
2750 // We are converting to an abstract integer type.
2751 resolved_type = Type::lookup_integer_type("int");
2752 }
2753 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2754 {
2755 // We are converting to an abstract float type.
2756 resolved_type = Type::lookup_float_type("float64");
2757 }
2758 else
2759 {
2760 // If we still have an abstract type here, this is being
2761 // used in a constant expression which didn't get reduced. We
2762 // just use complex128 and hope for the best.
2763 resolved_type = Type::lookup_complex_type("complex128");
2764 }
2765
2766 Numeric_constant nc;
2767 nc.set_complex(resolved_type, this->val_);
2768 return Expression::backend_numeric_constant_expression(context, &nc);
2769 }
2770
2771 // Write REAL/IMAG to export data.
2772
2773 void
export_complex(String_dump * exp,const mpc_t val)2774 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2775 {
2776 if (!mpfr_zero_p(mpc_realref(val)))
2777 {
2778 Float_expression::export_float(exp, mpc_realref(val));
2779 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2780 exp->write_c_string("+");
2781 }
2782 Float_expression::export_float(exp, mpc_imagref(val));
2783 exp->write_c_string("i");
2784 }
2785
2786 // Export a complex number in a constant expression.
2787
2788 void
do_export(Export_function_body * efb) const2789 Complex_expression::do_export(Export_function_body* efb) const
2790 {
2791 bool added_type = false;
2792 if (this->type_ != NULL
2793 && !this->type_->is_abstract()
2794 && this->type_ != efb->type_context())
2795 {
2796 efb->write_c_string("$convert(");
2797 efb->write_type(this->type_);
2798 efb->write_c_string(", ");
2799 added_type = true;
2800 }
2801
2802 Complex_expression::export_complex(efb, this->val_);
2803 // A trailing space lets us reliably identify the end of the number.
2804 efb->write_c_string(" ");
2805
2806 if (added_type)
2807 efb->write_c_string(")");
2808 }
2809
2810 // Dump a complex expression to the dump file.
2811
2812 void
do_dump_expression(Ast_dump_context * ast_dump_context) const2813 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2814 {
2815 Complex_expression::export_complex(ast_dump_context, this->val_);
2816 }
2817
2818 // Make a complex expression.
2819
2820 Expression*
make_complex(const mpc_t * val,Type * type,Location location)2821 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2822 {
2823 return new Complex_expression(val, type, location);
2824 }
2825
2826 // Find a named object in an expression.
2827
2828 class Find_named_object : public Traverse
2829 {
2830 public:
Find_named_object(Named_object * no)2831 Find_named_object(Named_object* no)
2832 : Traverse(traverse_expressions),
2833 no_(no), found_(false)
2834 { }
2835
2836 // Whether we found the object.
2837 bool
found() const2838 found() const
2839 { return this->found_; }
2840
2841 protected:
2842 int
2843 expression(Expression**);
2844
2845 private:
2846 // The object we are looking for.
2847 Named_object* no_;
2848 // Whether we found it.
2849 bool found_;
2850 };
2851
2852 // A reference to a const in an expression.
2853
2854 class Const_expression : public Expression
2855 {
2856 public:
Const_expression(Named_object * constant,Location location)2857 Const_expression(Named_object* constant, Location location)
2858 : Expression(EXPRESSION_CONST_REFERENCE, location),
2859 constant_(constant), type_(NULL), seen_(false)
2860 { }
2861
2862 Named_object*
named_object()2863 named_object()
2864 { return this->constant_; }
2865
2866 // Check that the initializer does not refer to the constant itself.
2867 void
2868 check_for_init_loop();
2869
2870 protected:
2871 int
2872 do_traverse(Traverse*);
2873
2874 Expression*
2875 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2876
2877 bool
do_is_constant() const2878 do_is_constant() const
2879 { return true; }
2880
2881 bool
do_is_static_initializer() const2882 do_is_static_initializer() const
2883 { return true; }
2884
2885 bool
2886 do_numeric_constant_value(Numeric_constant* nc) const;
2887
2888 bool
2889 do_string_constant_value(std::string* val) const;
2890
2891 Type*
2892 do_type();
2893
2894 // The type of a const is set by the declaration, not the use.
2895 void
2896 do_determine_type(const Type_context*);
2897
2898 void
2899 do_check_types(Gogo*);
2900
2901 Expression*
do_copy()2902 do_copy()
2903 { return this; }
2904
2905 Bexpression*
2906 do_get_backend(Translate_context* context);
2907
2908 // When exporting a reference to a const as part of a const
2909 // expression, we export the value. We ignore the fact that it has
2910 // a name.
2911 void
do_export(Export_function_body * efb) const2912 do_export(Export_function_body* efb) const
2913 { this->constant_->const_value()->expr()->export_expression(efb); }
2914
2915 void
2916 do_dump_expression(Ast_dump_context*) const;
2917
2918 private:
2919 // The constant.
2920 Named_object* constant_;
2921 // The type of this reference. This is used if the constant has an
2922 // abstract type.
2923 Type* type_;
2924 // Used to prevent infinite recursion when a constant incorrectly
2925 // refers to itself.
2926 mutable bool seen_;
2927 };
2928
2929 // Traversal.
2930
2931 int
do_traverse(Traverse * traverse)2932 Const_expression::do_traverse(Traverse* traverse)
2933 {
2934 if (this->type_ != NULL)
2935 return Type::traverse(this->type_, traverse);
2936 return TRAVERSE_CONTINUE;
2937 }
2938
2939 // Lower a constant expression. This is where we convert the
2940 // predeclared constant iota into an integer value.
2941
2942 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int iota_value)2943 Const_expression::do_lower(Gogo* gogo, Named_object*,
2944 Statement_inserter*, int iota_value)
2945 {
2946 if (this->constant_->const_value()->expr()->classification()
2947 == EXPRESSION_IOTA)
2948 {
2949 if (iota_value == -1)
2950 {
2951 go_error_at(this->location(),
2952 "iota is only defined in const declarations");
2953 iota_value = 0;
2954 }
2955 return Expression::make_integer_ul(iota_value, NULL, this->location());
2956 }
2957
2958 // Make sure that the constant itself has been lowered.
2959 gogo->lower_constant(this->constant_);
2960
2961 return this;
2962 }
2963
2964 // Return a numeric constant value.
2965
2966 bool
do_numeric_constant_value(Numeric_constant * nc) const2967 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2968 {
2969 if (this->seen_)
2970 return false;
2971
2972 Expression* e = this->constant_->const_value()->expr();
2973
2974 this->seen_ = true;
2975
2976 bool r = e->numeric_constant_value(nc);
2977
2978 this->seen_ = false;
2979
2980 Type* ctype;
2981 if (this->type_ != NULL)
2982 ctype = this->type_;
2983 else
2984 ctype = this->constant_->const_value()->type();
2985 if (r && ctype != NULL)
2986 {
2987 if (!nc->set_type(ctype, false, this->location()))
2988 return false;
2989 }
2990
2991 return r;
2992 }
2993
2994 bool
do_string_constant_value(std::string * val) const2995 Const_expression::do_string_constant_value(std::string* val) const
2996 {
2997 if (this->seen_)
2998 return false;
2999
3000 Expression* e = this->constant_->const_value()->expr();
3001
3002 this->seen_ = true;
3003 bool ok = e->string_constant_value(val);
3004 this->seen_ = false;
3005
3006 return ok;
3007 }
3008
3009 // Return the type of the const reference.
3010
3011 Type*
do_type()3012 Const_expression::do_type()
3013 {
3014 if (this->type_ != NULL)
3015 return this->type_;
3016
3017 Named_constant* nc = this->constant_->const_value();
3018
3019 if (this->seen_ || nc->lowering())
3020 {
3021 if (nc->type() == NULL || !nc->type()->is_error_type())
3022 {
3023 Location loc = this->location();
3024 if (!this->seen_)
3025 loc = nc->location();
3026 go_error_at(loc, "constant refers to itself");
3027 }
3028 this->set_is_error();
3029 this->type_ = Type::make_error_type();
3030 nc->set_type(this->type_);
3031 return this->type_;
3032 }
3033
3034 this->seen_ = true;
3035
3036 Type* ret = nc->type();
3037
3038 if (ret != NULL)
3039 {
3040 this->seen_ = false;
3041 return ret;
3042 }
3043
3044 // During parsing, a named constant may have a NULL type, but we
3045 // must not return a NULL type here.
3046 ret = nc->expr()->type();
3047
3048 this->seen_ = false;
3049
3050 if (ret->is_error_type())
3051 nc->set_type(ret);
3052
3053 return ret;
3054 }
3055
3056 // Set the type of the const reference.
3057
3058 void
do_determine_type(const Type_context * context)3059 Const_expression::do_determine_type(const Type_context* context)
3060 {
3061 Type* ctype = this->constant_->const_value()->type();
3062 Type* cetype = (ctype != NULL
3063 ? ctype
3064 : this->constant_->const_value()->expr()->type());
3065 if (ctype != NULL && !ctype->is_abstract())
3066 ;
3067 else if (context->type != NULL
3068 && context->type->is_numeric_type()
3069 && cetype->is_numeric_type())
3070 this->type_ = context->type;
3071 else if (context->type != NULL
3072 && context->type->is_string_type()
3073 && cetype->is_string_type())
3074 this->type_ = context->type;
3075 else if (context->type != NULL
3076 && context->type->is_boolean_type()
3077 && cetype->is_boolean_type())
3078 this->type_ = context->type;
3079 else if (!context->may_be_abstract)
3080 {
3081 if (cetype->is_abstract())
3082 cetype = cetype->make_non_abstract_type();
3083 this->type_ = cetype;
3084 }
3085 }
3086
3087 // Check for a loop in which the initializer of a constant refers to
3088 // the constant itself.
3089
3090 void
check_for_init_loop()3091 Const_expression::check_for_init_loop()
3092 {
3093 if (this->type_ != NULL && this->type_->is_error())
3094 return;
3095
3096 if (this->seen_)
3097 {
3098 this->report_error(_("constant refers to itself"));
3099 this->type_ = Type::make_error_type();
3100 return;
3101 }
3102
3103 Expression* init = this->constant_->const_value()->expr();
3104 Find_named_object find_named_object(this->constant_);
3105
3106 this->seen_ = true;
3107 Expression::traverse(&init, &find_named_object);
3108 this->seen_ = false;
3109
3110 if (find_named_object.found())
3111 {
3112 if (this->type_ == NULL || !this->type_->is_error())
3113 {
3114 this->report_error(_("constant refers to itself"));
3115 this->type_ = Type::make_error_type();
3116 }
3117 return;
3118 }
3119 }
3120
3121 // Check types of a const reference.
3122
3123 void
do_check_types(Gogo *)3124 Const_expression::do_check_types(Gogo*)
3125 {
3126 if (this->type_ != NULL && this->type_->is_error())
3127 return;
3128
3129 this->check_for_init_loop();
3130
3131 // Check that numeric constant fits in type.
3132 if (this->type_ != NULL && this->type_->is_numeric_type())
3133 {
3134 Numeric_constant nc;
3135 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
3136 {
3137 if (!nc.set_type(this->type_, true, this->location()))
3138 this->set_is_error();
3139 }
3140 }
3141 }
3142
3143 // Return the backend representation for a const reference.
3144
3145 Bexpression*
do_get_backend(Translate_context * context)3146 Const_expression::do_get_backend(Translate_context* context)
3147 {
3148 if (this->is_error_expression()
3149 || (this->type_ != NULL && this->type_->is_error()))
3150 {
3151 go_assert(saw_errors());
3152 return context->backend()->error_expression();
3153 }
3154
3155 // If the type has been set for this expression, but the underlying
3156 // object is an abstract int or float, we try to get the abstract
3157 // value. Otherwise we may lose something in the conversion.
3158 Expression* expr = this->constant_->const_value()->expr();
3159 if (this->type_ != NULL
3160 && this->type_->is_numeric_type()
3161 && (this->constant_->const_value()->type() == NULL
3162 || this->constant_->const_value()->type()->is_abstract()))
3163 {
3164 Numeric_constant nc;
3165 if (expr->numeric_constant_value(&nc)
3166 && nc.set_type(this->type_, false, this->location()))
3167 {
3168 Expression* e = nc.expression(this->location());
3169 return e->get_backend(context);
3170 }
3171 }
3172
3173 if (this->type_ != NULL)
3174 expr = Expression::make_cast(this->type_, expr, this->location());
3175 return expr->get_backend(context);
3176 }
3177
3178 // Dump ast representation for constant expression.
3179
3180 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3181 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
3182 {
3183 ast_dump_context->ostream() << this->constant_->name();
3184 }
3185
3186 // Make a reference to a constant in an expression.
3187
3188 Expression*
make_const_reference(Named_object * constant,Location location)3189 Expression::make_const_reference(Named_object* constant,
3190 Location location)
3191 {
3192 return new Const_expression(constant, location);
3193 }
3194
3195 // Find a named object in an expression.
3196
3197 int
expression(Expression ** pexpr)3198 Find_named_object::expression(Expression** pexpr)
3199 {
3200 switch ((*pexpr)->classification())
3201 {
3202 case Expression::EXPRESSION_CONST_REFERENCE:
3203 {
3204 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
3205 if (ce->named_object() == this->no_)
3206 break;
3207
3208 // We need to check a constant initializer explicitly, as
3209 // loops here will not be caught by the loop checking for
3210 // variable initializers.
3211 ce->check_for_init_loop();
3212
3213 return TRAVERSE_CONTINUE;
3214 }
3215
3216 case Expression::EXPRESSION_VAR_REFERENCE:
3217 if ((*pexpr)->var_expression()->named_object() == this->no_)
3218 break;
3219 return TRAVERSE_CONTINUE;
3220 case Expression::EXPRESSION_FUNC_REFERENCE:
3221 if ((*pexpr)->func_expression()->named_object() == this->no_)
3222 break;
3223 return TRAVERSE_CONTINUE;
3224 default:
3225 return TRAVERSE_CONTINUE;
3226 }
3227 this->found_ = true;
3228 return TRAVERSE_EXIT;
3229 }
3230
3231 // The nil value.
3232
3233 class Nil_expression : public Expression
3234 {
3235 public:
Nil_expression(Location location)3236 Nil_expression(Location location)
3237 : Expression(EXPRESSION_NIL, location)
3238 { }
3239
3240 static Expression*
3241 do_import(Import_expression*, Location);
3242
3243 protected:
3244 bool
do_is_constant() const3245 do_is_constant() const
3246 { return true; }
3247
3248 bool
do_is_static_initializer() const3249 do_is_static_initializer() const
3250 { return true; }
3251
3252 Type*
do_type()3253 do_type()
3254 { return Type::make_nil_type(); }
3255
3256 void
do_determine_type(const Type_context *)3257 do_determine_type(const Type_context*)
3258 { }
3259
3260 Expression*
do_copy()3261 do_copy()
3262 { return this; }
3263
3264 Bexpression*
do_get_backend(Translate_context * context)3265 do_get_backend(Translate_context* context)
3266 { return context->backend()->nil_pointer_expression(); }
3267
3268 int
do_inlining_cost() const3269 do_inlining_cost() const
3270 { return 1; }
3271
3272 void
do_export(Export_function_body * efb) const3273 do_export(Export_function_body* efb) const
3274 { efb->write_c_string("$nil"); }
3275
3276 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3277 do_dump_expression(Ast_dump_context* ast_dump_context) const
3278 { ast_dump_context->ostream() << "nil"; }
3279 };
3280
3281 // Import a nil expression.
3282
3283 Expression*
do_import(Import_expression * imp,Location loc)3284 Nil_expression::do_import(Import_expression* imp, Location loc)
3285 {
3286 if (imp->version() >= EXPORT_FORMAT_V3)
3287 imp->require_c_string("$");
3288 imp->require_c_string("nil");
3289 return Expression::make_nil(loc);
3290 }
3291
3292 // Make a nil expression.
3293
3294 Expression*
make_nil(Location location)3295 Expression::make_nil(Location location)
3296 {
3297 return new Nil_expression(location);
3298 }
3299
3300 // The value of the predeclared constant iota. This is little more
3301 // than a marker. This will be lowered to an integer in
3302 // Const_expression::do_lower, which is where we know the value that
3303 // it should have.
3304
3305 class Iota_expression : public Parser_expression
3306 {
3307 public:
Iota_expression(Location location)3308 Iota_expression(Location location)
3309 : Parser_expression(EXPRESSION_IOTA, location)
3310 { }
3311
3312 protected:
3313 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3314 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3315 { go_unreachable(); }
3316
3317 // There should only ever be one of these.
3318 Expression*
do_copy()3319 do_copy()
3320 { go_unreachable(); }
3321
3322 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3323 do_dump_expression(Ast_dump_context* ast_dump_context) const
3324 { ast_dump_context->ostream() << "iota"; }
3325 };
3326
3327 // Make an iota expression. This is only called for one case: the
3328 // value of the predeclared constant iota.
3329
3330 Expression*
make_iota()3331 Expression::make_iota()
3332 {
3333 static Iota_expression iota_expression(Linemap::unknown_location());
3334 return &iota_expression;
3335 }
3336
3337 // Class Type_conversion_expression.
3338
3339 // Traversal.
3340
3341 int
do_traverse(Traverse * traverse)3342 Type_conversion_expression::do_traverse(Traverse* traverse)
3343 {
3344 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3345 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3346 return TRAVERSE_EXIT;
3347 return TRAVERSE_CONTINUE;
3348 }
3349
3350 // Convert to a constant at lowering time.
3351
3352 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3353 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3354 Statement_inserter*, int)
3355 {
3356 Type* type = this->type_;
3357 Expression* val = this->expr_;
3358 Location location = this->location();
3359
3360 if (type->is_numeric_type())
3361 {
3362 Numeric_constant nc;
3363 if (val->numeric_constant_value(&nc))
3364 {
3365 if (!nc.set_type(type, true, location))
3366 return Expression::make_error(location);
3367 return nc.expression(location);
3368 }
3369 }
3370
3371 // According to the language specification on string conversions
3372 // (http://golang.org/ref/spec#Conversions_to_and_from_a_string_type):
3373 // When converting an integer into a string, the string will be a UTF-8
3374 // representation of the integer and integers "outside the range of valid
3375 // Unicode code points are converted to '\uFFFD'."
3376 if (type->is_string_type())
3377 {
3378 Numeric_constant nc;
3379 if (val->numeric_constant_value(&nc) && nc.is_int())
3380 {
3381 // An integer value doesn't fit in the Unicode code point range if it
3382 // overflows the Go "int" type or is negative.
3383 unsigned long ul;
3384 if (!nc.set_type(Type::lookup_integer_type("int"), false, location)
3385 || nc.to_unsigned_long(&ul) == Numeric_constant::NC_UL_NEGATIVE)
3386 return Expression::make_string("\ufffd", location);
3387 }
3388 }
3389
3390 if (type->is_slice_type())
3391 {
3392 Type* element_type = type->array_type()->element_type()->forwarded();
3393 bool is_byte = (element_type->integer_type() != NULL
3394 && element_type->integer_type()->is_byte());
3395 bool is_rune = (element_type->integer_type() != NULL
3396 && element_type->integer_type()->is_rune());
3397 if (is_byte || is_rune)
3398 {
3399 std::string s;
3400 if (val->string_constant_value(&s))
3401 {
3402 Expression_list* vals = new Expression_list();
3403 if (is_byte)
3404 {
3405 for (std::string::const_iterator p = s.begin();
3406 p != s.end();
3407 p++)
3408 {
3409 unsigned char c = static_cast<unsigned char>(*p);
3410 vals->push_back(Expression::make_integer_ul(c,
3411 element_type,
3412 location));
3413 }
3414 }
3415 else
3416 {
3417 const char *p = s.data();
3418 const char *pend = s.data() + s.length();
3419 while (p < pend)
3420 {
3421 unsigned int c;
3422 int adv = Lex::fetch_char(p, &c);
3423 if (adv == 0)
3424 {
3425 go_warning_at(this->location(), 0,
3426 "invalid UTF-8 encoding");
3427 adv = 1;
3428 }
3429 p += adv;
3430 vals->push_back(Expression::make_integer_ul(c,
3431 element_type,
3432 location));
3433 }
3434 }
3435
3436 return Expression::make_slice_composite_literal(type, vals,
3437 location);
3438 }
3439 }
3440 }
3441
3442 return this;
3443 }
3444
3445 // Flatten a type conversion by using a temporary variable for the slice
3446 // in slice to string conversions.
3447
3448 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)3449 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3450 Statement_inserter* inserter)
3451 {
3452 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3453 {
3454 go_assert(saw_errors());
3455 return Expression::make_error(this->location());
3456 }
3457
3458 if (((this->type()->is_string_type()
3459 && this->expr_->type()->is_slice_type())
3460 || this->expr_->type()->interface_type() != NULL)
3461 && !this->expr_->is_variable())
3462 {
3463 Temporary_statement* temp =
3464 Statement::make_temporary(NULL, this->expr_, this->location());
3465 inserter->insert(temp);
3466 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3467 }
3468 return this;
3469 }
3470
3471 // Return whether a type conversion is a constant.
3472
3473 bool
do_is_constant() const3474 Type_conversion_expression::do_is_constant() const
3475 {
3476 if (!this->expr_->is_constant())
3477 return false;
3478
3479 // A conversion to a type that may not be used as a constant is not
3480 // a constant. For example, []byte(nil).
3481 Type* type = this->type_;
3482 if (type->integer_type() == NULL
3483 && type->float_type() == NULL
3484 && type->complex_type() == NULL
3485 && !type->is_boolean_type()
3486 && !type->is_string_type())
3487 return false;
3488
3489 return true;
3490 }
3491
3492 // Return whether a type conversion can be used in a constant
3493 // initializer.
3494
3495 bool
do_is_static_initializer() const3496 Type_conversion_expression::do_is_static_initializer() const
3497 {
3498 Type* type = this->type_;
3499 Type* expr_type = this->expr_->type();
3500
3501 if (type->interface_type() != NULL
3502 || expr_type->interface_type() != NULL)
3503 return false;
3504
3505 if (!this->expr_->is_static_initializer())
3506 return false;
3507
3508 if (Type::are_identical(type, expr_type,
3509 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
3510 NULL))
3511 return true;
3512
3513 if (type->is_string_type() && expr_type->is_string_type())
3514 return true;
3515
3516 if ((type->is_numeric_type()
3517 || type->is_boolean_type()
3518 || type->points_to() != NULL)
3519 && (expr_type->is_numeric_type()
3520 || expr_type->is_boolean_type()
3521 || expr_type->points_to() != NULL))
3522 return true;
3523
3524 return false;
3525 }
3526
3527 // Return the constant numeric value if there is one.
3528
3529 bool
do_numeric_constant_value(Numeric_constant * nc) const3530 Type_conversion_expression::do_numeric_constant_value(
3531 Numeric_constant* nc) const
3532 {
3533 if (!this->type_->is_numeric_type())
3534 return false;
3535 if (!this->expr_->numeric_constant_value(nc))
3536 return false;
3537 return nc->set_type(this->type_, false, this->location());
3538 }
3539
3540 // Return the constant string value if there is one.
3541
3542 bool
do_string_constant_value(std::string * val) const3543 Type_conversion_expression::do_string_constant_value(std::string* val) const
3544 {
3545 if (this->type_->is_string_type()
3546 && this->expr_->type()->integer_type() != NULL)
3547 {
3548 Numeric_constant nc;
3549 if (this->expr_->numeric_constant_value(&nc))
3550 {
3551 unsigned long ival;
3552 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3553 {
3554 val->clear();
3555 Lex::append_char(ival, true, val, this->location());
3556 return true;
3557 }
3558 }
3559 }
3560
3561 // FIXME: Could handle conversion from const []int here.
3562
3563 return false;
3564 }
3565
3566 // Determine the resulting type of the conversion.
3567
3568 void
do_determine_type(const Type_context *)3569 Type_conversion_expression::do_determine_type(const Type_context*)
3570 {
3571 Type_context subcontext(this->type_, false);
3572 this->expr_->determine_type(&subcontext);
3573 }
3574
3575 // Check that types are convertible.
3576
3577 void
do_check_types(Gogo *)3578 Type_conversion_expression::do_check_types(Gogo*)
3579 {
3580 Type* type = this->type_;
3581 Type* expr_type = this->expr_->type();
3582 std::string reason;
3583
3584 if (type->is_error() || expr_type->is_error())
3585 {
3586 this->set_is_error();
3587 return;
3588 }
3589
3590 if (this->may_convert_function_types_
3591 && type->function_type() != NULL
3592 && expr_type->function_type() != NULL)
3593 return;
3594
3595 if (Type::are_convertible(type, expr_type, &reason))
3596 return;
3597
3598 go_error_at(this->location(), "%s", reason.c_str());
3599 this->set_is_error();
3600 }
3601
3602 // Copy.
3603
3604 Expression*
do_copy()3605 Type_conversion_expression::do_copy()
3606 {
3607 return new Type_conversion_expression(this->type_->copy_expressions(),
3608 this->expr_->copy(),
3609 this->location());
3610 }
3611
3612 // Get the backend representation for a type conversion.
3613
3614 Bexpression*
do_get_backend(Translate_context * context)3615 Type_conversion_expression::do_get_backend(Translate_context* context)
3616 {
3617 Type* type = this->type_;
3618 Type* expr_type = this->expr_->type();
3619
3620 Gogo* gogo = context->gogo();
3621 Btype* btype = type->get_backend(gogo);
3622 Location loc = this->location();
3623
3624 if (Type::are_identical(type, expr_type,
3625 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
3626 NULL))
3627 {
3628 Bexpression* bexpr = this->expr_->get_backend(context);
3629 return gogo->backend()->convert_expression(btype, bexpr, loc);
3630 }
3631 else if (type->interface_type() != NULL
3632 || expr_type->interface_type() != NULL)
3633 {
3634 Expression* conversion =
3635 Expression::convert_for_assignment(gogo, type, this->expr_,
3636 this->location());
3637 return conversion->get_backend(context);
3638 }
3639 else if (type->is_string_type()
3640 && expr_type->integer_type() != NULL)
3641 {
3642 mpz_t intval;
3643 Numeric_constant nc;
3644 if (this->expr_->numeric_constant_value(&nc)
3645 && nc.to_int(&intval)
3646 && mpz_fits_ushort_p(intval))
3647 {
3648 std::string s;
3649 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3650 mpz_clear(intval);
3651 Expression* se = Expression::make_string(s, loc);
3652 return se->get_backend(context);
3653 }
3654
3655 Expression* i2s_expr =
3656 Runtime::make_call(Runtime::INTSTRING, loc, 2,
3657 Expression::make_nil(loc), this->expr_);
3658 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3659 }
3660 else if (type->is_string_type() && expr_type->is_slice_type())
3661 {
3662 Array_type* a = expr_type->array_type();
3663 Type* e = a->element_type()->forwarded();
3664 go_assert(e->integer_type() != NULL);
3665 go_assert(this->expr_->is_variable());
3666
3667 Runtime::Function code;
3668 if (e->integer_type()->is_byte())
3669 code = Runtime::SLICEBYTETOSTRING;
3670 else
3671 {
3672 go_assert(e->integer_type()->is_rune());
3673 code = Runtime::SLICERUNETOSTRING;
3674 }
3675 return Runtime::make_call(code, loc, 2, Expression::make_nil(loc),
3676 this->expr_)->get_backend(context);
3677 }
3678 else if (type->is_slice_type() && expr_type->is_string_type())
3679 {
3680 Type* e = type->array_type()->element_type()->forwarded();
3681 go_assert(e->integer_type() != NULL);
3682
3683 Runtime::Function code;
3684 if (e->integer_type()->is_byte())
3685 code = Runtime::STRINGTOSLICEBYTE;
3686 else
3687 {
3688 go_assert(e->integer_type()->is_rune());
3689 code = Runtime::STRINGTOSLICERUNE;
3690 }
3691 Expression* s2a = Runtime::make_call(code, loc, 2,
3692 Expression::make_nil(loc),
3693 this->expr_);
3694 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3695 }
3696 else if (type->is_numeric_type())
3697 {
3698 go_assert(Type::are_convertible(type, expr_type, NULL));
3699 Bexpression* bexpr = this->expr_->get_backend(context);
3700 return gogo->backend()->convert_expression(btype, bexpr, loc);
3701 }
3702 else if ((type->is_unsafe_pointer_type()
3703 && (expr_type->points_to() != NULL
3704 || expr_type->integer_type()))
3705 || (expr_type->is_unsafe_pointer_type()
3706 && type->points_to() != NULL)
3707 || (this->may_convert_function_types_
3708 && type->function_type() != NULL
3709 && expr_type->function_type() != NULL))
3710 {
3711 Bexpression* bexpr = this->expr_->get_backend(context);
3712 return gogo->backend()->convert_expression(btype, bexpr, loc);
3713 }
3714 else
3715 {
3716 Expression* conversion =
3717 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3718 return conversion->get_backend(context);
3719 }
3720 }
3721
3722 // Cost of inlining a type conversion.
3723
3724 int
do_inlining_cost() const3725 Type_conversion_expression::do_inlining_cost() const
3726 {
3727 Type* type = this->type_;
3728 Type* expr_type = this->expr_->type();
3729 if (type->interface_type() != NULL || expr_type->interface_type() != NULL)
3730 return 10;
3731 else if (type->is_string_type() && expr_type->integer_type() != NULL)
3732 return 10;
3733 else if (type->is_string_type() && expr_type->is_slice_type())
3734 return 10;
3735 else if (type->is_slice_type() && expr_type->is_string_type())
3736 return 10;
3737 else
3738 return 1;
3739 }
3740
3741 // Output a type conversion in a constant expression.
3742
3743 void
do_export(Export_function_body * efb) const3744 Type_conversion_expression::do_export(Export_function_body* efb) const
3745 {
3746 efb->write_c_string("$convert(");
3747 efb->write_type(this->type_);
3748 efb->write_c_string(", ");
3749
3750 Type* old_context = efb->type_context();
3751 efb->set_type_context(this->type_);
3752
3753 this->expr_->export_expression(efb);
3754
3755 efb->set_type_context(old_context);
3756
3757 efb->write_c_string(")");
3758 }
3759
3760 // Import a type conversion or a struct construction.
3761
3762 Expression*
do_import(Import_expression * imp,Location loc)3763 Type_conversion_expression::do_import(Import_expression* imp, Location loc)
3764 {
3765 imp->require_c_string("$convert(");
3766 Type* type = imp->read_type();
3767 imp->require_c_string(", ");
3768 Expression* val = Expression::import_expression(imp, loc);
3769 imp->require_c_string(")");
3770 return Expression::make_cast(type, val, loc);
3771 }
3772
3773 // Dump ast representation for a type conversion expression.
3774
3775 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3776 Type_conversion_expression::do_dump_expression(
3777 Ast_dump_context* ast_dump_context) const
3778 {
3779 ast_dump_context->dump_type(this->type_);
3780 ast_dump_context->ostream() << "(";
3781 ast_dump_context->dump_expression(this->expr_);
3782 ast_dump_context->ostream() << ") ";
3783 }
3784
3785 // Make a type cast expression.
3786
3787 Expression*
make_cast(Type * type,Expression * val,Location location)3788 Expression::make_cast(Type* type, Expression* val, Location location)
3789 {
3790 if (type->is_error_type() || val->is_error_expression())
3791 return Expression::make_error(location);
3792 return new Type_conversion_expression(type, val, location);
3793 }
3794
3795 // Class Unsafe_type_conversion_expression.
3796
3797 // Traversal.
3798
3799 int
do_traverse(Traverse * traverse)3800 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3801 {
3802 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3803 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3804 return TRAVERSE_EXIT;
3805 return TRAVERSE_CONTINUE;
3806 }
3807
3808 // Return whether an unsafe type conversion can be used as a constant
3809 // initializer.
3810
3811 bool
do_is_static_initializer() const3812 Unsafe_type_conversion_expression::do_is_static_initializer() const
3813 {
3814 Type* type = this->type_;
3815 Type* expr_type = this->expr_->type();
3816
3817 if (type->interface_type() != NULL
3818 || expr_type->interface_type() != NULL)
3819 return false;
3820
3821 if (!this->expr_->is_static_initializer())
3822 return false;
3823
3824 if (Type::are_convertible(type, expr_type, NULL))
3825 return true;
3826
3827 if (type->is_string_type() && expr_type->is_string_type())
3828 return true;
3829
3830 if ((type->is_numeric_type()
3831 || type->is_boolean_type()
3832 || type->points_to() != NULL)
3833 && (expr_type->is_numeric_type()
3834 || expr_type->is_boolean_type()
3835 || expr_type->points_to() != NULL))
3836 return true;
3837
3838 return false;
3839 }
3840
3841 // Copy.
3842
3843 Expression*
do_copy()3844 Unsafe_type_conversion_expression::do_copy()
3845 {
3846 return new Unsafe_type_conversion_expression(this->type_->copy_expressions(),
3847 this->expr_->copy(),
3848 this->location());
3849 }
3850
3851 // Convert to backend representation.
3852
3853 Bexpression*
do_get_backend(Translate_context * context)3854 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3855 {
3856 // We are only called for a limited number of cases.
3857
3858 Type* t = this->type_;
3859 Type* et = this->expr_->type();
3860
3861 if (t->is_error_type()
3862 || this->expr_->is_error_expression()
3863 || et->is_error_type())
3864 {
3865 go_assert(saw_errors());
3866 return context->backend()->error_expression();
3867 }
3868
3869 if (t->array_type() != NULL)
3870 go_assert(et->array_type() != NULL
3871 && t->is_slice_type() == et->is_slice_type());
3872 else if (t->struct_type() != NULL)
3873 {
3874 if (t->named_type() != NULL
3875 && et->named_type() != NULL
3876 && !Type::are_convertible(t, et, NULL))
3877 {
3878 go_assert(saw_errors());
3879 return context->backend()->error_expression();
3880 }
3881
3882 go_assert(et->struct_type() != NULL
3883 && Type::are_convertible(t, et, NULL));
3884 }
3885 else if (t->map_type() != NULL)
3886 go_assert(et->map_type() != NULL);
3887 else if (t->channel_type() != NULL)
3888 go_assert(et->channel_type() != NULL);
3889 else if (t->points_to() != NULL)
3890 go_assert(et->points_to() != NULL
3891 || et->channel_type() != NULL
3892 || et->map_type() != NULL
3893 || et->function_type() != NULL
3894 || et->integer_type() != NULL
3895 || et->is_nil_type());
3896 else if (et->is_unsafe_pointer_type())
3897 go_assert(t->points_to() != NULL
3898 || (t->integer_type() != NULL
3899 && t->integer_type() == Type::lookup_integer_type("uintptr")->real_type()));
3900 else if (t->interface_type() != NULL)
3901 {
3902 bool empty_iface = t->interface_type()->is_empty();
3903 go_assert(et->interface_type() != NULL
3904 && et->interface_type()->is_empty() == empty_iface);
3905 }
3906 else if (t->integer_type() != NULL)
3907 go_assert(et->is_boolean_type()
3908 || et->integer_type() != NULL
3909 || et->function_type() != NULL
3910 || et->points_to() != NULL
3911 || et->map_type() != NULL
3912 || et->channel_type() != NULL
3913 || et->is_nil_type());
3914 else if (t->function_type() != NULL)
3915 go_assert(et->points_to() != NULL);
3916 else
3917 go_unreachable();
3918
3919 Gogo* gogo = context->gogo();
3920 Btype* btype = t->get_backend(gogo);
3921 Bexpression* bexpr = this->expr_->get_backend(context);
3922 Location loc = this->location();
3923 return gogo->backend()->convert_expression(btype, bexpr, loc);
3924 }
3925
3926 // Dump ast representation for an unsafe type conversion expression.
3927
3928 void
do_dump_expression(Ast_dump_context * ast_dump_context) const3929 Unsafe_type_conversion_expression::do_dump_expression(
3930 Ast_dump_context* ast_dump_context) const
3931 {
3932 ast_dump_context->dump_type(this->type_);
3933 ast_dump_context->ostream() << "(";
3934 ast_dump_context->dump_expression(this->expr_);
3935 ast_dump_context->ostream() << ") ";
3936 }
3937
3938 // Make an unsafe type conversion expression.
3939
3940 Expression*
make_unsafe_cast(Type * type,Expression * expr,Location location)3941 Expression::make_unsafe_cast(Type* type, Expression* expr,
3942 Location location)
3943 {
3944 return new Unsafe_type_conversion_expression(type, expr, location);
3945 }
3946
3947 // Class Unary_expression.
3948
3949 // Call the address_taken method of the operand if needed. This is
3950 // called after escape analysis but before inserting write barriers.
3951
3952 void
check_operand_address_taken(Gogo *)3953 Unary_expression::check_operand_address_taken(Gogo*)
3954 {
3955 if (this->op_ != OPERATOR_AND)
3956 return;
3957
3958 // If this->escapes_ is false at this point, then it was set to
3959 // false by an explicit call to set_does_not_escape, and the value
3960 // does not escape. If this->escapes_ is true, we may be able to
3961 // set it to false based on the escape analysis pass.
3962 if (this->escapes_)
3963 {
3964 Node* n = Node::make_node(this);
3965 if ((n->encoding() & ESCAPE_MASK) == int(Node::ESCAPE_NONE))
3966 this->escapes_ = false;
3967 }
3968
3969 this->expr_->address_taken(this->escapes_);
3970 }
3971
3972 // If we are taking the address of a composite literal, and the
3973 // contents are not constant, then we want to make a heap expression
3974 // instead.
3975
3976 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)3977 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3978 {
3979 Location loc = this->location();
3980 Operator op = this->op_;
3981 Expression* expr = this->expr_;
3982
3983 if (op == OPERATOR_MULT && expr->is_type_expression())
3984 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3985
3986 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3987 // moving x to the heap. FIXME: Is it worth doing a real escape
3988 // analysis here? This case is found in math/unsafe.go and is
3989 // therefore worth special casing.
3990 if (op == OPERATOR_MULT)
3991 {
3992 Expression* e = expr;
3993 while (e->classification() == EXPRESSION_CONVERSION)
3994 {
3995 Type_conversion_expression* te
3996 = static_cast<Type_conversion_expression*>(e);
3997 e = te->expr();
3998 }
3999
4000 if (e->classification() == EXPRESSION_UNARY)
4001 {
4002 Unary_expression* ue = static_cast<Unary_expression*>(e);
4003 if (ue->op_ == OPERATOR_AND)
4004 {
4005 if (e == expr)
4006 {
4007 // *&x == x.
4008 if (!ue->expr_->is_addressable() && !ue->create_temp_)
4009 {
4010 go_error_at(ue->location(),
4011 "invalid operand for unary %<&%>");
4012 this->set_is_error();
4013 }
4014 return ue->expr_;
4015 }
4016 ue->set_does_not_escape();
4017 }
4018 }
4019 }
4020
4021 // Catching an invalid indirection of unsafe.Pointer here avoid
4022 // having to deal with TYPE_VOID in other places.
4023 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
4024 {
4025 go_error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
4026 return Expression::make_error(this->location());
4027 }
4028
4029 // Check for an invalid pointer dereference. We need to do this
4030 // here because Unary_expression::do_type will return an error type
4031 // in this case. That can cause code to appear erroneous, and
4032 // therefore disappear at lowering time, without any error message.
4033 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
4034 {
4035 this->report_error(_("expected pointer"));
4036 return Expression::make_error(this->location());
4037 }
4038
4039 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
4040 {
4041 Numeric_constant nc;
4042 if (expr->numeric_constant_value(&nc))
4043 {
4044 Numeric_constant result;
4045 bool issued_error;
4046 if (Unary_expression::eval_constant(op, &nc, loc, &result,
4047 &issued_error))
4048 return result.expression(loc);
4049 else if (issued_error)
4050 return Expression::make_error(this->location());
4051 }
4052 }
4053
4054 return this;
4055 }
4056
4057 // Flatten expression if a nil check must be performed and create temporary
4058 // variables if necessary.
4059
4060 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)4061 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
4062 Statement_inserter* inserter)
4063 {
4064 if (this->is_error_expression()
4065 || this->expr_->is_error_expression()
4066 || this->expr_->type()->is_error_type())
4067 {
4068 go_assert(saw_errors());
4069 return Expression::make_error(this->location());
4070 }
4071
4072 Location location = this->location();
4073 if (this->op_ == OPERATOR_MULT
4074 && !this->expr_->is_variable())
4075 {
4076 go_assert(this->expr_->type()->points_to() != NULL);
4077 switch (this->requires_nil_check(gogo))
4078 {
4079 case NIL_CHECK_ERROR_ENCOUNTERED:
4080 {
4081 go_assert(saw_errors());
4082 return Expression::make_error(this->location());
4083 }
4084 case NIL_CHECK_NOT_NEEDED:
4085 break;
4086 case NIL_CHECK_NEEDED:
4087 this->create_temp_ = true;
4088 break;
4089 case NIL_CHECK_DEFAULT:
4090 go_unreachable();
4091 }
4092 }
4093
4094 if (this->create_temp_ && !this->expr_->is_variable())
4095 {
4096 Temporary_statement* temp =
4097 Statement::make_temporary(NULL, this->expr_, location);
4098 inserter->insert(temp);
4099 this->expr_ = Expression::make_temporary_reference(temp, location);
4100 }
4101
4102 return this;
4103 }
4104
4105 // Return whether a unary expression is a constant.
4106
4107 bool
do_is_constant() const4108 Unary_expression::do_is_constant() const
4109 {
4110 if (this->op_ == OPERATOR_MULT)
4111 {
4112 // Indirecting through a pointer is only constant if the object
4113 // to which the expression points is constant, but we currently
4114 // have no way to determine that.
4115 return false;
4116 }
4117 else if (this->op_ == OPERATOR_AND)
4118 {
4119 // Taking the address of a variable is constant if it is a
4120 // global variable, not constant otherwise. In other cases taking the
4121 // address is probably not a constant.
4122 Var_expression* ve = this->expr_->var_expression();
4123 if (ve != NULL)
4124 {
4125 Named_object* no = ve->named_object();
4126 return no->is_variable() && no->var_value()->is_global();
4127 }
4128 return false;
4129 }
4130 else
4131 return this->expr_->is_constant();
4132 }
4133
4134 // Return whether a unary expression can be used as a constant
4135 // initializer.
4136
4137 bool
do_is_static_initializer() const4138 Unary_expression::do_is_static_initializer() const
4139 {
4140 if (this->op_ == OPERATOR_MULT)
4141 return false;
4142 else if (this->op_ == OPERATOR_AND)
4143 return Unary_expression::base_is_static_initializer(this->expr_);
4144 else
4145 return this->expr_->is_static_initializer();
4146 }
4147
4148 // Return whether the address of EXPR can be used as a static
4149 // initializer.
4150
4151 bool
base_is_static_initializer(Expression * expr)4152 Unary_expression::base_is_static_initializer(Expression* expr)
4153 {
4154 // The address of a field reference can be a static initializer if
4155 // the base can be a static initializer.
4156 Field_reference_expression* fre = expr->field_reference_expression();
4157 if (fre != NULL)
4158 return Unary_expression::base_is_static_initializer(fre->expr());
4159
4160 // The address of an index expression can be a static initializer if
4161 // the base can be a static initializer and the index is constant.
4162 Array_index_expression* aind = expr->array_index_expression();
4163 if (aind != NULL)
4164 return (aind->end() == NULL
4165 && aind->start()->is_constant()
4166 && Unary_expression::base_is_static_initializer(aind->array()));
4167
4168 // The address of a global variable can be a static initializer.
4169 Var_expression* ve = expr->var_expression();
4170 if (ve != NULL)
4171 {
4172 Named_object* no = ve->named_object();
4173 return no->is_variable() && no->var_value()->is_global();
4174 }
4175
4176 // The address of a composite literal can be used as a static
4177 // initializer if the composite literal is itself usable as a
4178 // static initializer.
4179 if (expr->is_composite_literal() && expr->is_static_initializer())
4180 return true;
4181
4182 // The address of a string constant can be used as a static
4183 // initializer. This can not be written in Go itself but this is
4184 // used when building a type descriptor.
4185 if (expr->string_expression() != NULL)
4186 return true;
4187
4188 return false;
4189 }
4190
4191 // Return whether this dereference expression requires an explicit nil
4192 // check. If we are dereferencing the pointer to a large struct
4193 // (greater than the specified size threshold), we need to check for
4194 // nil. We don't bother to check for small structs because we expect
4195 // the system to crash on a nil pointer dereference. However, if we
4196 // know the address of this expression is being taken, we must always
4197 // check for nil.
4198 Unary_expression::Nil_check_classification
requires_nil_check(Gogo * gogo)4199 Unary_expression::requires_nil_check(Gogo* gogo)
4200 {
4201 go_assert(this->op_ == OPERATOR_MULT);
4202 go_assert(this->expr_->type()->points_to() != NULL);
4203
4204 if (this->issue_nil_check_ == NIL_CHECK_NEEDED)
4205 return NIL_CHECK_NEEDED;
4206 else if (this->issue_nil_check_ == NIL_CHECK_NOT_NEEDED)
4207 return NIL_CHECK_NOT_NEEDED;
4208
4209 Type* ptype = this->expr_->type()->points_to();
4210 int64_t type_size = -1;
4211 if (!ptype->is_void_type())
4212 {
4213 bool ok = ptype->backend_type_size(gogo, &type_size);
4214 if (!ok)
4215 return NIL_CHECK_ERROR_ENCOUNTERED;
4216 }
4217
4218 int64_t size_cutoff = gogo->nil_check_size_threshold();
4219 if (size_cutoff == -1 || (type_size != -1 && type_size >= size_cutoff))
4220 this->issue_nil_check_ = NIL_CHECK_NEEDED;
4221 else
4222 this->issue_nil_check_ = NIL_CHECK_NOT_NEEDED;
4223 return this->issue_nil_check_;
4224 }
4225
4226 // Apply unary opcode OP to UNC, setting NC. Return true if this
4227 // could be done, false if not. On overflow, issues an error and sets
4228 // *ISSUED_ERROR.
4229
4230 bool
eval_constant(Operator op,const Numeric_constant * unc,Location location,Numeric_constant * nc,bool * issued_error)4231 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
4232 Location location, Numeric_constant* nc,
4233 bool* issued_error)
4234 {
4235 *issued_error = false;
4236 switch (op)
4237 {
4238 case OPERATOR_PLUS:
4239 *nc = *unc;
4240 return true;
4241
4242 case OPERATOR_MINUS:
4243 if (unc->is_int() || unc->is_rune())
4244 break;
4245 else if (unc->is_float())
4246 {
4247 mpfr_t uval;
4248 unc->get_float(&uval);
4249 mpfr_t val;
4250 mpfr_init(val);
4251 mpfr_neg(val, uval, GMP_RNDN);
4252 nc->set_float(unc->type(), val);
4253 mpfr_clear(uval);
4254 mpfr_clear(val);
4255 return true;
4256 }
4257 else if (unc->is_complex())
4258 {
4259 mpc_t uval;
4260 unc->get_complex(&uval);
4261 mpc_t val;
4262 mpc_init2(val, mpc_precision);
4263 mpc_neg(val, uval, MPC_RNDNN);
4264 nc->set_complex(unc->type(), val);
4265 mpc_clear(uval);
4266 mpc_clear(val);
4267 return true;
4268 }
4269 else
4270 go_unreachable();
4271
4272 case OPERATOR_XOR:
4273 break;
4274
4275 case OPERATOR_NOT:
4276 case OPERATOR_AND:
4277 case OPERATOR_MULT:
4278 return false;
4279
4280 default:
4281 go_unreachable();
4282 }
4283
4284 if (!unc->is_int() && !unc->is_rune())
4285 return false;
4286
4287 mpz_t uval;
4288 if (unc->is_rune())
4289 unc->get_rune(&uval);
4290 else
4291 unc->get_int(&uval);
4292 mpz_t val;
4293 mpz_init(val);
4294
4295 switch (op)
4296 {
4297 case OPERATOR_MINUS:
4298 mpz_neg(val, uval);
4299 break;
4300
4301 case OPERATOR_NOT:
4302 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
4303 break;
4304
4305 case OPERATOR_XOR:
4306 {
4307 Type* utype = unc->type();
4308 if (utype->integer_type() == NULL
4309 || utype->integer_type()->is_abstract())
4310 mpz_com(val, uval);
4311 else
4312 {
4313 // The number of HOST_WIDE_INTs that it takes to represent
4314 // UVAL.
4315 size_t count = ((mpz_sizeinbase(uval, 2)
4316 + HOST_BITS_PER_WIDE_INT
4317 - 1)
4318 / HOST_BITS_PER_WIDE_INT);
4319
4320 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
4321 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
4322
4323 size_t obits = utype->integer_type()->bits();
4324
4325 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
4326 {
4327 mpz_t adj;
4328 mpz_init_set_ui(adj, 1);
4329 mpz_mul_2exp(adj, adj, obits);
4330 mpz_add(uval, uval, adj);
4331 mpz_clear(adj);
4332 }
4333
4334 size_t ecount;
4335 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
4336 go_assert(ecount <= count);
4337
4338 // Trim down to the number of words required by the type.
4339 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
4340 / HOST_BITS_PER_WIDE_INT);
4341 go_assert(ocount <= count);
4342
4343 for (size_t i = 0; i < ocount; ++i)
4344 phwi[i] = ~phwi[i];
4345
4346 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
4347 if (clearbits != 0)
4348 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
4349 >> clearbits);
4350
4351 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
4352
4353 if (!utype->integer_type()->is_unsigned()
4354 && mpz_tstbit(val, obits - 1))
4355 {
4356 mpz_t adj;
4357 mpz_init_set_ui(adj, 1);
4358 mpz_mul_2exp(adj, adj, obits);
4359 mpz_sub(val, val, adj);
4360 mpz_clear(adj);
4361 }
4362
4363 delete[] phwi;
4364 }
4365 }
4366 break;
4367
4368 default:
4369 go_unreachable();
4370 }
4371
4372 if (unc->is_rune())
4373 nc->set_rune(NULL, val);
4374 else
4375 nc->set_int(NULL, val);
4376
4377 mpz_clear(uval);
4378 mpz_clear(val);
4379
4380 if (!nc->set_type(unc->type(), true, location))
4381 {
4382 *issued_error = true;
4383 return false;
4384 }
4385 return true;
4386 }
4387
4388 // Return the integral constant value of a unary expression, if it has one.
4389
4390 bool
do_numeric_constant_value(Numeric_constant * nc) const4391 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
4392 {
4393 Numeric_constant unc;
4394 if (!this->expr_->numeric_constant_value(&unc))
4395 return false;
4396 bool issued_error;
4397 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
4398 nc, &issued_error);
4399 }
4400
4401 // Return the type of a unary expression.
4402
4403 Type*
do_type()4404 Unary_expression::do_type()
4405 {
4406 switch (this->op_)
4407 {
4408 case OPERATOR_PLUS:
4409 case OPERATOR_MINUS:
4410 case OPERATOR_NOT:
4411 case OPERATOR_XOR:
4412 return this->expr_->type();
4413
4414 case OPERATOR_AND:
4415 return Type::make_pointer_type(this->expr_->type());
4416
4417 case OPERATOR_MULT:
4418 {
4419 Type* subtype = this->expr_->type();
4420 Type* points_to = subtype->points_to();
4421 if (points_to == NULL)
4422 return Type::make_error_type();
4423 return points_to;
4424 }
4425
4426 default:
4427 go_unreachable();
4428 }
4429 }
4430
4431 // Determine abstract types for a unary expression.
4432
4433 void
do_determine_type(const Type_context * context)4434 Unary_expression::do_determine_type(const Type_context* context)
4435 {
4436 switch (this->op_)
4437 {
4438 case OPERATOR_PLUS:
4439 case OPERATOR_MINUS:
4440 case OPERATOR_NOT:
4441 case OPERATOR_XOR:
4442 this->expr_->determine_type(context);
4443 break;
4444
4445 case OPERATOR_AND:
4446 // Taking the address of something.
4447 {
4448 Type* subtype = (context->type == NULL
4449 ? NULL
4450 : context->type->points_to());
4451 Type_context subcontext(subtype, false);
4452 this->expr_->determine_type(&subcontext);
4453 }
4454 break;
4455
4456 case OPERATOR_MULT:
4457 // Indirecting through a pointer.
4458 {
4459 Type* subtype = (context->type == NULL
4460 ? NULL
4461 : Type::make_pointer_type(context->type));
4462 Type_context subcontext(subtype, false);
4463 this->expr_->determine_type(&subcontext);
4464 }
4465 break;
4466
4467 default:
4468 go_unreachable();
4469 }
4470 }
4471
4472 // Check types for a unary expression.
4473
4474 void
do_check_types(Gogo *)4475 Unary_expression::do_check_types(Gogo*)
4476 {
4477 Type* type = this->expr_->type();
4478 if (type->is_error())
4479 {
4480 this->set_is_error();
4481 return;
4482 }
4483
4484 switch (this->op_)
4485 {
4486 case OPERATOR_PLUS:
4487 case OPERATOR_MINUS:
4488 if (type->integer_type() == NULL
4489 && type->float_type() == NULL
4490 && type->complex_type() == NULL)
4491 this->report_error(_("expected numeric type"));
4492 break;
4493
4494 case OPERATOR_NOT:
4495 if (!type->is_boolean_type())
4496 this->report_error(_("expected boolean type"));
4497 break;
4498
4499 case OPERATOR_XOR:
4500 if (type->integer_type() == NULL)
4501 this->report_error(_("expected integer"));
4502 break;
4503
4504 case OPERATOR_AND:
4505 if (!this->expr_->is_addressable())
4506 {
4507 if (!this->create_temp_)
4508 {
4509 go_error_at(this->location(), "invalid operand for unary %<&%>");
4510 this->set_is_error();
4511 }
4512 }
4513 else
4514 this->expr_->issue_nil_check();
4515 break;
4516
4517 case OPERATOR_MULT:
4518 // Indirecting through a pointer.
4519 if (type->points_to() == NULL)
4520 this->report_error(_("expected pointer"));
4521 if (type->points_to()->is_error())
4522 this->set_is_error();
4523 break;
4524
4525 default:
4526 go_unreachable();
4527 }
4528 }
4529
4530 // Get the backend representation for a unary expression.
4531
4532 Bexpression*
do_get_backend(Translate_context * context)4533 Unary_expression::do_get_backend(Translate_context* context)
4534 {
4535 Gogo* gogo = context->gogo();
4536 Location loc = this->location();
4537
4538 // Taking the address of a set-and-use-temporary expression requires
4539 // setting the temporary and then taking the address.
4540 if (this->op_ == OPERATOR_AND)
4541 {
4542 Set_and_use_temporary_expression* sut =
4543 this->expr_->set_and_use_temporary_expression();
4544 if (sut != NULL)
4545 {
4546 Temporary_statement* temp = sut->temporary();
4547 Bvariable* bvar = temp->get_backend_variable(context);
4548 Bexpression* bvar_expr =
4549 gogo->backend()->var_expression(bvar, loc);
4550 Bexpression* bval = sut->expression()->get_backend(context);
4551
4552 Named_object* fn = context->function();
4553 go_assert(fn != NULL);
4554 Bfunction* bfn =
4555 fn->func_value()->get_or_make_decl(gogo, fn);
4556 Bstatement* bassign =
4557 gogo->backend()->assignment_statement(bfn, bvar_expr, bval, loc);
4558 Bexpression* bvar_addr =
4559 gogo->backend()->address_expression(bvar_expr, loc);
4560 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4561 }
4562 }
4563
4564 Bexpression* ret;
4565 Bexpression* bexpr = this->expr_->get_backend(context);
4566 Btype* btype = this->expr_->type()->get_backend(gogo);
4567 switch (this->op_)
4568 {
4569 case OPERATOR_PLUS:
4570 ret = bexpr;
4571 break;
4572
4573 case OPERATOR_MINUS:
4574 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4575 ret = gogo->backend()->convert_expression(btype, ret, loc);
4576 break;
4577
4578 case OPERATOR_NOT:
4579 case OPERATOR_XOR:
4580 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4581 break;
4582
4583 case OPERATOR_AND:
4584 if (!this->create_temp_)
4585 {
4586 // We should not see a non-constant constructor here; cases
4587 // where we would see one should have been moved onto the
4588 // heap at parse time. Taking the address of a nonconstant
4589 // constructor will not do what the programmer expects.
4590
4591 go_assert(!this->expr_->is_composite_literal()
4592 || this->expr_->is_static_initializer());
4593 if (this->expr_->classification() == EXPRESSION_UNARY)
4594 {
4595 Unary_expression* ue =
4596 static_cast<Unary_expression*>(this->expr_);
4597 go_assert(ue->op() != OPERATOR_AND);
4598 }
4599 }
4600
4601 if (this->is_gc_root_ || this->is_slice_init_)
4602 {
4603 std::string var_name;
4604 bool copy_to_heap = false;
4605 if (this->is_gc_root_)
4606 {
4607 // Build a decl for a GC root variable. GC roots are mutable, so
4608 // they cannot be represented as an immutable_struct in the
4609 // backend.
4610 var_name = gogo->gc_root_name();
4611 }
4612 else
4613 {
4614 // Build a decl for a slice value initializer. An immutable slice
4615 // value initializer may have to be copied to the heap if it
4616 // contains pointers in a non-constant context.
4617 var_name = gogo->initializer_name();
4618
4619 Array_type* at = this->expr_->type()->array_type();
4620 go_assert(at != NULL);
4621
4622 // If we are not copying the value to the heap, we will only
4623 // initialize the value once, so we can use this directly
4624 // rather than copying it. In that case we can't make it
4625 // read-only, because the program is permitted to change it.
4626 copy_to_heap = (context->function() != NULL
4627 || context->is_const());
4628 }
4629 std::string asm_name(go_selectively_encode_id(var_name));
4630 Bvariable* implicit =
4631 gogo->backend()->implicit_variable(var_name, asm_name,
4632 btype, true, copy_to_heap,
4633 false, 0);
4634 gogo->backend()->implicit_variable_set_init(implicit, var_name, btype,
4635 true, copy_to_heap, false,
4636 bexpr);
4637 bexpr = gogo->backend()->var_expression(implicit, loc);
4638
4639 // If we are not copying a slice initializer to the heap,
4640 // then it can be changed by the program, so if it can
4641 // contain pointers we must register it as a GC root.
4642 if (this->is_slice_init_
4643 && !copy_to_heap
4644 && this->expr_->type()->has_pointer())
4645 {
4646 Bexpression* root =
4647 gogo->backend()->var_expression(implicit, loc);
4648 root = gogo->backend()->address_expression(root, loc);
4649 Type* type = Type::make_pointer_type(this->expr_->type());
4650 gogo->add_gc_root(Expression::make_backend(root, type, loc));
4651 }
4652 }
4653 else if ((this->expr_->is_composite_literal()
4654 || this->expr_->string_expression() != NULL)
4655 && this->expr_->is_static_initializer())
4656 {
4657 std::string var_name(gogo->initializer_name());
4658 std::string asm_name(go_selectively_encode_id(var_name));
4659 Bvariable* decl =
4660 gogo->backend()->immutable_struct(var_name, asm_name,
4661 true, false, btype, loc);
4662 gogo->backend()->immutable_struct_set_init(decl, var_name, true,
4663 false, btype, loc, bexpr);
4664 bexpr = gogo->backend()->var_expression(decl, loc);
4665 }
4666
4667 go_assert(!this->create_temp_ || this->expr_->is_variable());
4668 ret = gogo->backend()->address_expression(bexpr, loc);
4669 break;
4670
4671 case OPERATOR_MULT:
4672 {
4673 go_assert(this->expr_->type()->points_to() != NULL);
4674
4675 bool known_valid = false;
4676 Type* ptype = this->expr_->type()->points_to();
4677 Btype* pbtype = ptype->get_backend(gogo);
4678 switch (this->requires_nil_check(gogo))
4679 {
4680 case NIL_CHECK_NOT_NEEDED:
4681 break;
4682 case NIL_CHECK_ERROR_ENCOUNTERED:
4683 {
4684 go_assert(saw_errors());
4685 return gogo->backend()->error_expression();
4686 }
4687 case NIL_CHECK_NEEDED:
4688 {
4689 go_assert(this->expr_->is_variable());
4690
4691 // If we're nil-checking the result of a set-and-use-temporary
4692 // expression, then pick out the target temp and use that
4693 // for the final result of the conditional.
4694 Bexpression* tbexpr = bexpr;
4695 Bexpression* ubexpr = bexpr;
4696 Set_and_use_temporary_expression* sut =
4697 this->expr_->set_and_use_temporary_expression();
4698 if (sut != NULL) {
4699 Temporary_statement* temp = sut->temporary();
4700 Bvariable* bvar = temp->get_backend_variable(context);
4701 ubexpr = gogo->backend()->var_expression(bvar, loc);
4702 }
4703 Bexpression* nil =
4704 Expression::make_nil(loc)->get_backend(context);
4705 Bexpression* compare =
4706 gogo->backend()->binary_expression(OPERATOR_EQEQ, tbexpr,
4707 nil, loc);
4708 Bexpression* crash =
4709 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4710 loc)->get_backend(context);
4711 Bfunction* bfn = context->function()->func_value()->get_decl();
4712 bexpr = gogo->backend()->conditional_expression(bfn, btype,
4713 compare,
4714 crash, ubexpr,
4715 loc);
4716 known_valid = true;
4717 break;
4718 }
4719 case NIL_CHECK_DEFAULT:
4720 go_unreachable();
4721 }
4722 ret = gogo->backend()->indirect_expression(pbtype, bexpr,
4723 known_valid, loc);
4724 }
4725 break;
4726
4727 default:
4728 go_unreachable();
4729 }
4730
4731 return ret;
4732 }
4733
4734 // Export a unary expression.
4735
4736 void
do_export(Export_function_body * efb) const4737 Unary_expression::do_export(Export_function_body* efb) const
4738 {
4739 switch (this->op_)
4740 {
4741 case OPERATOR_PLUS:
4742 efb->write_c_string("+");
4743 break;
4744 case OPERATOR_MINUS:
4745 efb->write_c_string("-");
4746 break;
4747 case OPERATOR_NOT:
4748 efb->write_c_string("!");
4749 break;
4750 case OPERATOR_XOR:
4751 efb->write_c_string("^");
4752 break;
4753 case OPERATOR_AND:
4754 efb->write_c_string("&");
4755 break;
4756 case OPERATOR_MULT:
4757 efb->write_c_string("*");
4758 break;
4759 default:
4760 go_unreachable();
4761 }
4762 this->expr_->export_expression(efb);
4763 }
4764
4765 // Import a unary expression.
4766
4767 Expression*
do_import(Import_expression * imp,Location loc)4768 Unary_expression::do_import(Import_expression* imp, Location loc)
4769 {
4770 Operator op;
4771 switch (imp->get_char())
4772 {
4773 case '+':
4774 op = OPERATOR_PLUS;
4775 break;
4776 case '-':
4777 op = OPERATOR_MINUS;
4778 break;
4779 case '!':
4780 op = OPERATOR_NOT;
4781 break;
4782 case '^':
4783 op = OPERATOR_XOR;
4784 break;
4785 case '&':
4786 op = OPERATOR_AND;
4787 break;
4788 case '*':
4789 op = OPERATOR_MULT;
4790 break;
4791 default:
4792 go_unreachable();
4793 }
4794 if (imp->version() < EXPORT_FORMAT_V3)
4795 imp->require_c_string(" ");
4796 Expression* expr = Expression::import_expression(imp, loc);
4797 return Expression::make_unary(op, expr, loc);
4798 }
4799
4800 // Dump ast representation of an unary expression.
4801
4802 void
do_dump_expression(Ast_dump_context * ast_dump_context) const4803 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4804 {
4805 ast_dump_context->dump_operator(this->op_);
4806 ast_dump_context->ostream() << "(";
4807 ast_dump_context->dump_expression(this->expr_);
4808 ast_dump_context->ostream() << ") ";
4809 }
4810
4811 // Make a unary expression.
4812
4813 Expression*
make_unary(Operator op,Expression * expr,Location location)4814 Expression::make_unary(Operator op, Expression* expr, Location location)
4815 {
4816 return new Unary_expression(op, expr, location);
4817 }
4818
4819 Expression*
make_dereference(Expression * ptr,Nil_check_classification docheck,Location location)4820 Expression::make_dereference(Expression* ptr,
4821 Nil_check_classification docheck,
4822 Location location)
4823 {
4824 Expression* deref = Expression::make_unary(OPERATOR_MULT, ptr, location);
4825 if (docheck == NIL_CHECK_NEEDED)
4826 deref->unary_expression()->set_requires_nil_check(true);
4827 else if (docheck == NIL_CHECK_NOT_NEEDED)
4828 deref->unary_expression()->set_requires_nil_check(false);
4829 return deref;
4830 }
4831
4832 // If this is an indirection through a pointer, return the expression
4833 // being pointed through. Otherwise return this.
4834
4835 Expression*
deref()4836 Expression::deref()
4837 {
4838 if (this->classification_ == EXPRESSION_UNARY)
4839 {
4840 Unary_expression* ue = static_cast<Unary_expression*>(this);
4841 if (ue->op() == OPERATOR_MULT)
4842 return ue->operand();
4843 }
4844 return this;
4845 }
4846
4847 // Class Binary_expression.
4848
4849 // Traversal.
4850
4851 int
do_traverse(Traverse * traverse)4852 Binary_expression::do_traverse(Traverse* traverse)
4853 {
4854 int t = Expression::traverse(&this->left_, traverse);
4855 if (t == TRAVERSE_EXIT)
4856 return TRAVERSE_EXIT;
4857 return Expression::traverse(&this->right_, traverse);
4858 }
4859
4860 // Return whether this expression may be used as a static initializer.
4861
4862 bool
do_is_static_initializer() const4863 Binary_expression::do_is_static_initializer() const
4864 {
4865 if (!this->left_->is_static_initializer()
4866 || !this->right_->is_static_initializer())
4867 return false;
4868
4869 // Addresses can be static initializers, but we can't implement
4870 // arbitray binary expressions of them.
4871 Unary_expression* lu = this->left_->unary_expression();
4872 Unary_expression* ru = this->right_->unary_expression();
4873 if (lu != NULL && lu->op() == OPERATOR_AND)
4874 {
4875 if (ru != NULL && ru->op() == OPERATOR_AND)
4876 return this->op_ == OPERATOR_MINUS;
4877 else
4878 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4879 }
4880 else if (ru != NULL && ru->op() == OPERATOR_AND)
4881 return this->op_ == OPERATOR_PLUS || this->op_ == OPERATOR_MINUS;
4882
4883 // Other cases should resolve in the backend.
4884 return true;
4885 }
4886
4887 // Return the type to use for a binary operation on operands of
4888 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4889 // such may be NULL or abstract.
4890
4891 bool
operation_type(Operator op,Type * left_type,Type * right_type,Type ** result_type)4892 Binary_expression::operation_type(Operator op, Type* left_type,
4893 Type* right_type, Type** result_type)
4894 {
4895 if (left_type != right_type
4896 && !left_type->is_abstract()
4897 && !right_type->is_abstract()
4898 && left_type->base() != right_type->base()
4899 && op != OPERATOR_LSHIFT
4900 && op != OPERATOR_RSHIFT)
4901 {
4902 // May be a type error--let it be diagnosed elsewhere.
4903 return false;
4904 }
4905
4906 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4907 {
4908 if (left_type->integer_type() != NULL)
4909 *result_type = left_type;
4910 else
4911 *result_type = Type::make_abstract_integer_type();
4912 }
4913 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4914 *result_type = left_type;
4915 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4916 *result_type = right_type;
4917 else if (!left_type->is_abstract())
4918 *result_type = left_type;
4919 else if (!right_type->is_abstract())
4920 *result_type = right_type;
4921 else if (left_type->complex_type() != NULL)
4922 *result_type = left_type;
4923 else if (right_type->complex_type() != NULL)
4924 *result_type = right_type;
4925 else if (left_type->float_type() != NULL)
4926 *result_type = left_type;
4927 else if (right_type->float_type() != NULL)
4928 *result_type = right_type;
4929 else if (left_type->integer_type() != NULL
4930 && left_type->integer_type()->is_rune())
4931 *result_type = left_type;
4932 else if (right_type->integer_type() != NULL
4933 && right_type->integer_type()->is_rune())
4934 *result_type = right_type;
4935 else
4936 *result_type = left_type;
4937
4938 return true;
4939 }
4940
4941 // Convert an integer comparison code and an operator to a boolean
4942 // value.
4943
4944 bool
cmp_to_bool(Operator op,int cmp)4945 Binary_expression::cmp_to_bool(Operator op, int cmp)
4946 {
4947 switch (op)
4948 {
4949 case OPERATOR_EQEQ:
4950 return cmp == 0;
4951 break;
4952 case OPERATOR_NOTEQ:
4953 return cmp != 0;
4954 break;
4955 case OPERATOR_LT:
4956 return cmp < 0;
4957 break;
4958 case OPERATOR_LE:
4959 return cmp <= 0;
4960 case OPERATOR_GT:
4961 return cmp > 0;
4962 case OPERATOR_GE:
4963 return cmp >= 0;
4964 default:
4965 go_unreachable();
4966 }
4967 }
4968
4969 // Compare constants according to OP.
4970
4971 bool
compare_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,bool * result)4972 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4973 Numeric_constant* right_nc,
4974 Location location, bool* result)
4975 {
4976 Type* left_type = left_nc->type();
4977 Type* right_type = right_nc->type();
4978
4979 Type* type;
4980 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4981 return false;
4982
4983 // When comparing an untyped operand to a typed operand, we are
4984 // effectively coercing the untyped operand to the other operand's
4985 // type, so make sure that is valid.
4986 if (!left_nc->set_type(type, true, location)
4987 || !right_nc->set_type(type, true, location))
4988 return false;
4989
4990 bool ret;
4991 int cmp;
4992 if (type->complex_type() != NULL)
4993 {
4994 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4995 return false;
4996 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4997 }
4998 else if (type->float_type() != NULL)
4999 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
5000 else
5001 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
5002
5003 if (ret)
5004 *result = Binary_expression::cmp_to_bool(op, cmp);
5005
5006 return ret;
5007 }
5008
5009 // Compare integer constants.
5010
5011 bool
compare_integer(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5012 Binary_expression::compare_integer(const Numeric_constant* left_nc,
5013 const Numeric_constant* right_nc,
5014 int* cmp)
5015 {
5016 mpz_t left_val;
5017 if (!left_nc->to_int(&left_val))
5018 return false;
5019 mpz_t right_val;
5020 if (!right_nc->to_int(&right_val))
5021 {
5022 mpz_clear(left_val);
5023 return false;
5024 }
5025
5026 *cmp = mpz_cmp(left_val, right_val);
5027
5028 mpz_clear(left_val);
5029 mpz_clear(right_val);
5030
5031 return true;
5032 }
5033
5034 // Compare floating point constants.
5035
5036 bool
compare_float(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5037 Binary_expression::compare_float(const Numeric_constant* left_nc,
5038 const Numeric_constant* right_nc,
5039 int* cmp)
5040 {
5041 mpfr_t left_val;
5042 if (!left_nc->to_float(&left_val))
5043 return false;
5044 mpfr_t right_val;
5045 if (!right_nc->to_float(&right_val))
5046 {
5047 mpfr_clear(left_val);
5048 return false;
5049 }
5050
5051 // We already coerced both operands to the same type. If that type
5052 // is not an abstract type, we need to round the values accordingly.
5053 Type* type = left_nc->type();
5054 if (!type->is_abstract() && type->float_type() != NULL)
5055 {
5056 int bits = type->float_type()->bits();
5057 mpfr_prec_round(left_val, bits, GMP_RNDN);
5058 mpfr_prec_round(right_val, bits, GMP_RNDN);
5059 }
5060
5061 *cmp = mpfr_cmp(left_val, right_val);
5062
5063 mpfr_clear(left_val);
5064 mpfr_clear(right_val);
5065
5066 return true;
5067 }
5068
5069 // Compare complex constants. Complex numbers may only be compared
5070 // for equality.
5071
5072 bool
compare_complex(const Numeric_constant * left_nc,const Numeric_constant * right_nc,int * cmp)5073 Binary_expression::compare_complex(const Numeric_constant* left_nc,
5074 const Numeric_constant* right_nc,
5075 int* cmp)
5076 {
5077 mpc_t left_val;
5078 if (!left_nc->to_complex(&left_val))
5079 return false;
5080 mpc_t right_val;
5081 if (!right_nc->to_complex(&right_val))
5082 {
5083 mpc_clear(left_val);
5084 return false;
5085 }
5086
5087 // We already coerced both operands to the same type. If that type
5088 // is not an abstract type, we need to round the values accordingly.
5089 Type* type = left_nc->type();
5090 if (!type->is_abstract() && type->complex_type() != NULL)
5091 {
5092 int bits = type->complex_type()->bits();
5093 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
5094 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
5095 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
5096 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
5097 }
5098
5099 *cmp = mpc_cmp(left_val, right_val) != 0;
5100
5101 mpc_clear(left_val);
5102 mpc_clear(right_val);
5103
5104 return true;
5105 }
5106
5107 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
5108 // true if this could be done, false if not. Issue errors at LOCATION
5109 // as appropriate, and sets *ISSUED_ERROR if it did.
5110
5111 bool
eval_constant(Operator op,Numeric_constant * left_nc,Numeric_constant * right_nc,Location location,Numeric_constant * nc,bool * issued_error)5112 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
5113 Numeric_constant* right_nc,
5114 Location location, Numeric_constant* nc,
5115 bool* issued_error)
5116 {
5117 *issued_error = false;
5118 switch (op)
5119 {
5120 case OPERATOR_OROR:
5121 case OPERATOR_ANDAND:
5122 case OPERATOR_EQEQ:
5123 case OPERATOR_NOTEQ:
5124 case OPERATOR_LT:
5125 case OPERATOR_LE:
5126 case OPERATOR_GT:
5127 case OPERATOR_GE:
5128 // These return boolean values, not numeric.
5129 return false;
5130 default:
5131 break;
5132 }
5133
5134 Type* left_type = left_nc->type();
5135 Type* right_type = right_nc->type();
5136
5137 Type* type;
5138 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
5139 return false;
5140
5141 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
5142
5143 // When combining an untyped operand with a typed operand, we are
5144 // effectively coercing the untyped operand to the other operand's
5145 // type, so make sure that is valid.
5146 if (!left_nc->set_type(type, true, location))
5147 return false;
5148 if (!is_shift && !right_nc->set_type(type, true, location))
5149 return false;
5150 if (is_shift
5151 && ((left_type->integer_type() == NULL
5152 && !left_type->is_abstract())
5153 || (right_type->integer_type() == NULL
5154 && !right_type->is_abstract())))
5155 return false;
5156
5157 bool r;
5158 if (type->complex_type() != NULL)
5159 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
5160 else if (type->float_type() != NULL)
5161 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
5162 else
5163 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
5164
5165 if (r)
5166 {
5167 r = nc->set_type(type, true, location);
5168 if (!r)
5169 *issued_error = true;
5170 }
5171
5172 return r;
5173 }
5174
5175 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5176 // integer operations. Return true if this could be done, false if
5177 // not.
5178
5179 bool
eval_integer(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5180 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
5181 const Numeric_constant* right_nc,
5182 Location location, Numeric_constant* nc)
5183 {
5184 mpz_t left_val;
5185 if (!left_nc->to_int(&left_val))
5186 return false;
5187 mpz_t right_val;
5188 if (!right_nc->to_int(&right_val))
5189 {
5190 mpz_clear(left_val);
5191 return false;
5192 }
5193
5194 mpz_t val;
5195 mpz_init(val);
5196
5197 switch (op)
5198 {
5199 case OPERATOR_PLUS:
5200 mpz_add(val, left_val, right_val);
5201 if (mpz_sizeinbase(val, 2) > 0x100000)
5202 {
5203 go_error_at(location, "constant addition overflow");
5204 nc->set_invalid();
5205 mpz_set_ui(val, 1);
5206 }
5207 break;
5208 case OPERATOR_MINUS:
5209 mpz_sub(val, left_val, right_val);
5210 if (mpz_sizeinbase(val, 2) > 0x100000)
5211 {
5212 go_error_at(location, "constant subtraction overflow");
5213 nc->set_invalid();
5214 mpz_set_ui(val, 1);
5215 }
5216 break;
5217 case OPERATOR_OR:
5218 mpz_ior(val, left_val, right_val);
5219 break;
5220 case OPERATOR_XOR:
5221 mpz_xor(val, left_val, right_val);
5222 break;
5223 case OPERATOR_MULT:
5224 mpz_mul(val, left_val, right_val);
5225 if (mpz_sizeinbase(val, 2) > 0x100000)
5226 {
5227 go_error_at(location, "constant multiplication overflow");
5228 nc->set_invalid();
5229 mpz_set_ui(val, 1);
5230 }
5231 break;
5232 case OPERATOR_DIV:
5233 if (mpz_sgn(right_val) != 0)
5234 mpz_tdiv_q(val, left_val, right_val);
5235 else
5236 {
5237 go_error_at(location, "division by zero");
5238 nc->set_invalid();
5239 mpz_set_ui(val, 0);
5240 }
5241 break;
5242 case OPERATOR_MOD:
5243 if (mpz_sgn(right_val) != 0)
5244 mpz_tdiv_r(val, left_val, right_val);
5245 else
5246 {
5247 go_error_at(location, "division by zero");
5248 nc->set_invalid();
5249 mpz_set_ui(val, 0);
5250 }
5251 break;
5252 case OPERATOR_LSHIFT:
5253 {
5254 unsigned long shift = mpz_get_ui(right_val);
5255 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
5256 mpz_mul_2exp(val, left_val, shift);
5257 else
5258 {
5259 go_error_at(location, "shift count overflow");
5260 nc->set_invalid();
5261 mpz_set_ui(val, 1);
5262 }
5263 break;
5264 }
5265 break;
5266 case OPERATOR_RSHIFT:
5267 {
5268 unsigned long shift = mpz_get_ui(right_val);
5269 if (mpz_cmp_ui(right_val, shift) != 0)
5270 {
5271 go_error_at(location, "shift count overflow");
5272 nc->set_invalid();
5273 mpz_set_ui(val, 1);
5274 }
5275 else
5276 {
5277 if (mpz_cmp_ui(left_val, 0) >= 0)
5278 mpz_tdiv_q_2exp(val, left_val, shift);
5279 else
5280 mpz_fdiv_q_2exp(val, left_val, shift);
5281 }
5282 break;
5283 }
5284 break;
5285 case OPERATOR_AND:
5286 mpz_and(val, left_val, right_val);
5287 break;
5288 case OPERATOR_BITCLEAR:
5289 {
5290 mpz_t tval;
5291 mpz_init(tval);
5292 mpz_com(tval, right_val);
5293 mpz_and(val, left_val, tval);
5294 mpz_clear(tval);
5295 }
5296 break;
5297 default:
5298 go_unreachable();
5299 }
5300
5301 mpz_clear(left_val);
5302 mpz_clear(right_val);
5303
5304 if (left_nc->is_rune()
5305 || (op != OPERATOR_LSHIFT
5306 && op != OPERATOR_RSHIFT
5307 && right_nc->is_rune()))
5308 nc->set_rune(NULL, val);
5309 else
5310 nc->set_int(NULL, val);
5311
5312 mpz_clear(val);
5313
5314 return true;
5315 }
5316
5317 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5318 // floating point operations. Return true if this could be done,
5319 // false if not.
5320
5321 bool
eval_float(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5322 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
5323 const Numeric_constant* right_nc,
5324 Location location, Numeric_constant* nc)
5325 {
5326 mpfr_t left_val;
5327 if (!left_nc->to_float(&left_val))
5328 return false;
5329 mpfr_t right_val;
5330 if (!right_nc->to_float(&right_val))
5331 {
5332 mpfr_clear(left_val);
5333 return false;
5334 }
5335
5336 mpfr_t val;
5337 mpfr_init(val);
5338
5339 bool ret = true;
5340 switch (op)
5341 {
5342 case OPERATOR_PLUS:
5343 mpfr_add(val, left_val, right_val, GMP_RNDN);
5344 break;
5345 case OPERATOR_MINUS:
5346 mpfr_sub(val, left_val, right_val, GMP_RNDN);
5347 break;
5348 case OPERATOR_OR:
5349 case OPERATOR_XOR:
5350 case OPERATOR_AND:
5351 case OPERATOR_BITCLEAR:
5352 case OPERATOR_MOD:
5353 case OPERATOR_LSHIFT:
5354 case OPERATOR_RSHIFT:
5355 mpfr_set_ui(val, 0, GMP_RNDN);
5356 ret = false;
5357 break;
5358 case OPERATOR_MULT:
5359 mpfr_mul(val, left_val, right_val, GMP_RNDN);
5360 break;
5361 case OPERATOR_DIV:
5362 if (!mpfr_zero_p(right_val))
5363 mpfr_div(val, left_val, right_val, GMP_RNDN);
5364 else
5365 {
5366 go_error_at(location, "division by zero");
5367 nc->set_invalid();
5368 mpfr_set_ui(val, 0, GMP_RNDN);
5369 }
5370 break;
5371 default:
5372 go_unreachable();
5373 }
5374
5375 mpfr_clear(left_val);
5376 mpfr_clear(right_val);
5377
5378 nc->set_float(NULL, val);
5379 mpfr_clear(val);
5380
5381 return ret;
5382 }
5383
5384 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
5385 // complex operations. Return true if this could be done, false if
5386 // not.
5387
5388 bool
eval_complex(Operator op,const Numeric_constant * left_nc,const Numeric_constant * right_nc,Location location,Numeric_constant * nc)5389 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
5390 const Numeric_constant* right_nc,
5391 Location location, Numeric_constant* nc)
5392 {
5393 mpc_t left_val;
5394 if (!left_nc->to_complex(&left_val))
5395 return false;
5396 mpc_t right_val;
5397 if (!right_nc->to_complex(&right_val))
5398 {
5399 mpc_clear(left_val);
5400 return false;
5401 }
5402
5403 mpc_t val;
5404 mpc_init2(val, mpc_precision);
5405
5406 bool ret = true;
5407 switch (op)
5408 {
5409 case OPERATOR_PLUS:
5410 mpc_add(val, left_val, right_val, MPC_RNDNN);
5411 break;
5412 case OPERATOR_MINUS:
5413 mpc_sub(val, left_val, right_val, MPC_RNDNN);
5414 break;
5415 case OPERATOR_OR:
5416 case OPERATOR_XOR:
5417 case OPERATOR_AND:
5418 case OPERATOR_BITCLEAR:
5419 case OPERATOR_MOD:
5420 case OPERATOR_LSHIFT:
5421 case OPERATOR_RSHIFT:
5422 mpc_set_ui(val, 0, MPC_RNDNN);
5423 ret = false;
5424 break;
5425 case OPERATOR_MULT:
5426 mpc_mul(val, left_val, right_val, MPC_RNDNN);
5427 break;
5428 case OPERATOR_DIV:
5429 if (mpc_cmp_si(right_val, 0) == 0)
5430 {
5431 go_error_at(location, "division by zero");
5432 nc->set_invalid();
5433 mpc_set_ui(val, 0, MPC_RNDNN);
5434 break;
5435 }
5436 mpc_div(val, left_val, right_val, MPC_RNDNN);
5437 break;
5438 default:
5439 go_unreachable();
5440 }
5441
5442 mpc_clear(left_val);
5443 mpc_clear(right_val);
5444
5445 nc->set_complex(NULL, val);
5446 mpc_clear(val);
5447
5448 return ret;
5449 }
5450
5451 // Lower a binary expression. We have to evaluate constant
5452 // expressions now, in order to implement Go's unlimited precision
5453 // constants.
5454
5455 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter * inserter,int)5456 Binary_expression::do_lower(Gogo* gogo, Named_object*,
5457 Statement_inserter* inserter, int)
5458 {
5459 Location location = this->location();
5460 Operator op = this->op_;
5461 Expression* left = this->left_;
5462 Expression* right = this->right_;
5463
5464 const bool is_comparison = (op == OPERATOR_EQEQ
5465 || op == OPERATOR_NOTEQ
5466 || op == OPERATOR_LT
5467 || op == OPERATOR_LE
5468 || op == OPERATOR_GT
5469 || op == OPERATOR_GE);
5470
5471 // Numeric constant expressions.
5472 {
5473 Numeric_constant left_nc;
5474 Numeric_constant right_nc;
5475 if (left->numeric_constant_value(&left_nc)
5476 && right->numeric_constant_value(&right_nc))
5477 {
5478 if (is_comparison)
5479 {
5480 bool result;
5481 if (!Binary_expression::compare_constant(op, &left_nc,
5482 &right_nc, location,
5483 &result))
5484 return this;
5485 return Expression::make_cast(Type::make_boolean_type(),
5486 Expression::make_boolean(result,
5487 location),
5488 location);
5489 }
5490 else
5491 {
5492 Numeric_constant nc;
5493 bool issued_error;
5494 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
5495 location, &nc,
5496 &issued_error))
5497 {
5498 if (issued_error)
5499 return Expression::make_error(location);
5500 return this;
5501 }
5502 return nc.expression(location);
5503 }
5504 }
5505 }
5506
5507 // String constant expressions.
5508 //
5509 // Avoid constant folding here if the left and right types are incompatible
5510 // (leave the operation intact so that the type checker can complain about it
5511 // later on). If concatenating an abstract string with a named string type,
5512 // result type needs to be of the named type (see issue 31412).
5513 if (left->type()->is_string_type()
5514 && right->type()->is_string_type()
5515 && (left->type()->named_type() == NULL
5516 || right->type()->named_type() == NULL
5517 || left->type()->named_type() == right->type()->named_type()))
5518 {
5519 std::string left_string;
5520 std::string right_string;
5521 if (left->string_constant_value(&left_string)
5522 && right->string_constant_value(&right_string))
5523 {
5524 if (op == OPERATOR_PLUS)
5525 {
5526 Type* result_type = (left->type()->named_type() != NULL
5527 ? left->type()
5528 : right->type());
5529 return Expression::make_string_typed(left_string + right_string,
5530 result_type, location);
5531 }
5532 else if (is_comparison)
5533 {
5534 int cmp = left_string.compare(right_string);
5535 bool r = Binary_expression::cmp_to_bool(op, cmp);
5536 return Expression::make_boolean(r, location);
5537 }
5538 }
5539 }
5540
5541 // Lower struct, array, and some interface comparisons.
5542 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
5543 {
5544 if (left->type()->struct_type() != NULL
5545 && right->type()->struct_type() != NULL)
5546 return this->lower_struct_comparison(gogo, inserter);
5547 else if (left->type()->array_type() != NULL
5548 && !left->type()->is_slice_type()
5549 && right->type()->array_type() != NULL
5550 && !right->type()->is_slice_type())
5551 return this->lower_array_comparison(gogo, inserter);
5552 else if ((left->type()->interface_type() != NULL
5553 && right->type()->interface_type() == NULL)
5554 || (left->type()->interface_type() == NULL
5555 && right->type()->interface_type() != NULL))
5556 return this->lower_interface_value_comparison(gogo, inserter);
5557 }
5558
5559 // Lower string concatenation to String_concat_expression, so that
5560 // we can group sequences of string additions.
5561 if (this->left_->type()->is_string_type() && this->op_ == OPERATOR_PLUS)
5562 {
5563 Expression_list* exprs;
5564 String_concat_expression* left_sce =
5565 this->left_->string_concat_expression();
5566 if (left_sce != NULL)
5567 exprs = left_sce->exprs();
5568 else
5569 {
5570 exprs = new Expression_list();
5571 exprs->push_back(this->left_);
5572 }
5573
5574 String_concat_expression* right_sce =
5575 this->right_->string_concat_expression();
5576 if (right_sce != NULL)
5577 exprs->append(right_sce->exprs());
5578 else
5579 exprs->push_back(this->right_);
5580
5581 return Expression::make_string_concat(exprs);
5582 }
5583
5584 return this;
5585 }
5586
5587 // Lower a struct comparison.
5588
5589 Expression*
lower_struct_comparison(Gogo * gogo,Statement_inserter * inserter)5590 Binary_expression::lower_struct_comparison(Gogo* gogo,
5591 Statement_inserter* inserter)
5592 {
5593 Struct_type* st = this->left_->type()->struct_type();
5594 Struct_type* st2 = this->right_->type()->struct_type();
5595 if (st2 == NULL)
5596 return this;
5597 if (st != st2
5598 && !Type::are_identical(st, st2,
5599 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
5600 NULL))
5601 return this;
5602 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5603 this->right_->type(), NULL))
5604 return this;
5605
5606 // See if we can compare using memcmp. As a heuristic, we use
5607 // memcmp rather than field references and comparisons if there are
5608 // more than two fields.
5609 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
5610 return this->lower_compare_to_memcmp(gogo, inserter);
5611
5612 Location loc = this->location();
5613
5614 Expression* left = this->left_;
5615 Temporary_statement* left_temp = NULL;
5616 if (left->var_expression() == NULL
5617 && left->temporary_reference_expression() == NULL)
5618 {
5619 left_temp = Statement::make_temporary(left->type(), NULL, loc);
5620 inserter->insert(left_temp);
5621 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
5622 }
5623
5624 Expression* right = this->right_;
5625 Temporary_statement* right_temp = NULL;
5626 if (right->var_expression() == NULL
5627 && right->temporary_reference_expression() == NULL)
5628 {
5629 right_temp = Statement::make_temporary(right->type(), NULL, loc);
5630 inserter->insert(right_temp);
5631 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
5632 }
5633
5634 Expression* ret = Expression::make_boolean(true, loc);
5635 const Struct_field_list* fields = st->fields();
5636 unsigned int field_index = 0;
5637 for (Struct_field_list::const_iterator pf = fields->begin();
5638 pf != fields->end();
5639 ++pf, ++field_index)
5640 {
5641 if (Gogo::is_sink_name(pf->field_name()))
5642 continue;
5643
5644 if (field_index > 0)
5645 {
5646 if (left_temp == NULL)
5647 left = left->copy();
5648 else
5649 left = Expression::make_temporary_reference(left_temp, loc);
5650 if (right_temp == NULL)
5651 right = right->copy();
5652 else
5653 right = Expression::make_temporary_reference(right_temp, loc);
5654 }
5655 Expression* f1 = Expression::make_field_reference(left, field_index,
5656 loc);
5657 Expression* f2 = Expression::make_field_reference(right, field_index,
5658 loc);
5659 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
5660 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
5661 }
5662
5663 if (this->op_ == OPERATOR_NOTEQ)
5664 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5665
5666 return ret;
5667 }
5668
5669 // Lower an array comparison.
5670
5671 Expression*
lower_array_comparison(Gogo * gogo,Statement_inserter * inserter)5672 Binary_expression::lower_array_comparison(Gogo* gogo,
5673 Statement_inserter* inserter)
5674 {
5675 Array_type* at = this->left_->type()->array_type();
5676 Array_type* at2 = this->right_->type()->array_type();
5677 if (at2 == NULL)
5678 return this;
5679 if (at != at2
5680 && !Type::are_identical(at, at2,
5681 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
5682 NULL))
5683 return this;
5684 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
5685 this->right_->type(), NULL))
5686 return this;
5687
5688 // Call memcmp directly if possible. This may let the middle-end
5689 // optimize the call.
5690 if (at->compare_is_identity(gogo))
5691 return this->lower_compare_to_memcmp(gogo, inserter);
5692
5693 // Call the array comparison function.
5694 Named_object* hash_fn;
5695 Named_object* equal_fn;
5696 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
5697 &hash_fn, &equal_fn);
5698
5699 Location loc = this->location();
5700
5701 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
5702
5703 Expression_list* args = new Expression_list();
5704 args->push_back(this->operand_address(inserter, this->left_));
5705 args->push_back(this->operand_address(inserter, this->right_));
5706
5707 Expression* ret = Expression::make_call(func, args, false, loc);
5708
5709 if (this->op_ == OPERATOR_NOTEQ)
5710 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
5711
5712 return ret;
5713 }
5714
5715 // Lower an interface to value comparison.
5716
5717 Expression*
lower_interface_value_comparison(Gogo *,Statement_inserter * inserter)5718 Binary_expression::lower_interface_value_comparison(Gogo*,
5719 Statement_inserter* inserter)
5720 {
5721 Type* left_type = this->left_->type();
5722 Type* right_type = this->right_->type();
5723 Interface_type* ift;
5724 if (left_type->interface_type() != NULL)
5725 {
5726 ift = left_type->interface_type();
5727 if (!ift->implements_interface(right_type, NULL))
5728 return this;
5729 }
5730 else
5731 {
5732 ift = right_type->interface_type();
5733 if (!ift->implements_interface(left_type, NULL))
5734 return this;
5735 }
5736 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5737 return this;
5738
5739 Location loc = this->location();
5740
5741 if (left_type->interface_type() == NULL
5742 && left_type->points_to() == NULL
5743 && !this->left_->is_addressable())
5744 {
5745 Temporary_statement* temp =
5746 Statement::make_temporary(left_type, NULL, loc);
5747 inserter->insert(temp);
5748 this->left_ =
5749 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5750 }
5751
5752 if (right_type->interface_type() == NULL
5753 && right_type->points_to() == NULL
5754 && !this->right_->is_addressable())
5755 {
5756 Temporary_statement* temp =
5757 Statement::make_temporary(right_type, NULL, loc);
5758 inserter->insert(temp);
5759 this->right_ =
5760 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5761 }
5762
5763 return this;
5764 }
5765
5766 // Lower a struct or array comparison to a call to memcmp.
5767
5768 Expression*
lower_compare_to_memcmp(Gogo *,Statement_inserter * inserter)5769 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5770 {
5771 Location loc = this->location();
5772
5773 Expression* a1 = this->operand_address(inserter, this->left_);
5774 Expression* a2 = this->operand_address(inserter, this->right_);
5775 Expression* len = Expression::make_type_info(this->left_->type(),
5776 TYPE_INFO_SIZE);
5777
5778 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5779 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5780 return Expression::make_binary(this->op_, call, zero, loc);
5781 }
5782
5783 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)5784 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5785 Statement_inserter* inserter)
5786 {
5787 Location loc = this->location();
5788 if (this->left_->type()->is_error_type()
5789 || this->right_->type()->is_error_type()
5790 || this->left_->is_error_expression()
5791 || this->right_->is_error_expression())
5792 {
5793 go_assert(saw_errors());
5794 return Expression::make_error(loc);
5795 }
5796
5797 Temporary_statement* temp;
5798
5799 Type* left_type = this->left_->type();
5800 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5801 || this->op_ == OPERATOR_RSHIFT);
5802 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5803 left_type->integer_type() != NULL)
5804 || this->op_ == OPERATOR_MOD);
5805
5806 if (is_shift_op
5807 || (is_idiv_op
5808 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5809 {
5810 if (!this->left_->is_variable() && !this->left_->is_constant())
5811 {
5812 temp = Statement::make_temporary(NULL, this->left_, loc);
5813 inserter->insert(temp);
5814 this->left_ = Expression::make_temporary_reference(temp, loc);
5815 }
5816 if (!this->right_->is_variable() && !this->right_->is_constant())
5817 {
5818 temp =
5819 Statement::make_temporary(NULL, this->right_, loc);
5820 this->right_ = Expression::make_temporary_reference(temp, loc);
5821 inserter->insert(temp);
5822 }
5823 }
5824 return this;
5825 }
5826
5827
5828 // Return the address of EXPR, cast to unsafe.Pointer.
5829
5830 Expression*
operand_address(Statement_inserter * inserter,Expression * expr)5831 Binary_expression::operand_address(Statement_inserter* inserter,
5832 Expression* expr)
5833 {
5834 Location loc = this->location();
5835
5836 if (!expr->is_addressable())
5837 {
5838 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5839 loc);
5840 inserter->insert(temp);
5841 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5842 }
5843 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5844 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5845 Type* void_type = Type::make_void_type();
5846 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5847 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5848 }
5849
5850 // Return the numeric constant value, if it has one.
5851
5852 bool
do_numeric_constant_value(Numeric_constant * nc) const5853 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5854 {
5855 Numeric_constant left_nc;
5856 if (!this->left_->numeric_constant_value(&left_nc))
5857 return false;
5858 Numeric_constant right_nc;
5859 if (!this->right_->numeric_constant_value(&right_nc))
5860 return false;
5861 bool issued_error;
5862 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5863 this->location(), nc, &issued_error);
5864 }
5865
5866 // Note that the value is being discarded.
5867
5868 bool
do_discarding_value()5869 Binary_expression::do_discarding_value()
5870 {
5871 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5872 return this->right_->discarding_value();
5873 else
5874 {
5875 this->unused_value_error();
5876 return false;
5877 }
5878 }
5879
5880 // Get type.
5881
5882 Type*
do_type()5883 Binary_expression::do_type()
5884 {
5885 if (this->classification() == EXPRESSION_ERROR)
5886 return Type::make_error_type();
5887
5888 switch (this->op_)
5889 {
5890 case OPERATOR_EQEQ:
5891 case OPERATOR_NOTEQ:
5892 case OPERATOR_LT:
5893 case OPERATOR_LE:
5894 case OPERATOR_GT:
5895 case OPERATOR_GE:
5896 if (this->type_ == NULL)
5897 this->type_ = Type::make_boolean_type();
5898 return this->type_;
5899
5900 case OPERATOR_PLUS:
5901 case OPERATOR_MINUS:
5902 case OPERATOR_OR:
5903 case OPERATOR_XOR:
5904 case OPERATOR_MULT:
5905 case OPERATOR_DIV:
5906 case OPERATOR_MOD:
5907 case OPERATOR_AND:
5908 case OPERATOR_BITCLEAR:
5909 case OPERATOR_OROR:
5910 case OPERATOR_ANDAND:
5911 {
5912 Type* type;
5913 if (!Binary_expression::operation_type(this->op_,
5914 this->left_->type(),
5915 this->right_->type(),
5916 &type))
5917 return Type::make_error_type();
5918 return type;
5919 }
5920
5921 case OPERATOR_LSHIFT:
5922 case OPERATOR_RSHIFT:
5923 return this->left_->type();
5924
5925 default:
5926 go_unreachable();
5927 }
5928 }
5929
5930 // Set type for a binary expression.
5931
5932 void
do_determine_type(const Type_context * context)5933 Binary_expression::do_determine_type(const Type_context* context)
5934 {
5935 Type* tleft = this->left_->type();
5936 Type* tright = this->right_->type();
5937
5938 // Both sides should have the same type, except for the shift
5939 // operations. For a comparison, we should ignore the incoming
5940 // type.
5941
5942 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5943 || this->op_ == OPERATOR_RSHIFT);
5944
5945 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5946 || this->op_ == OPERATOR_NOTEQ
5947 || this->op_ == OPERATOR_LT
5948 || this->op_ == OPERATOR_LE
5949 || this->op_ == OPERATOR_GT
5950 || this->op_ == OPERATOR_GE);
5951
5952 // For constant expressions, the context of the result is not useful in
5953 // determining the types of the operands. It is only legal to use abstract
5954 // boolean, numeric, and string constants as operands where it is legal to
5955 // use non-abstract boolean, numeric, and string constants, respectively.
5956 // Any issues with the operation will be resolved in the check_types pass.
5957 bool is_constant_expr = (this->left_->is_constant()
5958 && this->right_->is_constant());
5959
5960 Type_context subcontext(*context);
5961
5962 if (is_constant_expr && !is_shift_op)
5963 {
5964 subcontext.type = NULL;
5965 subcontext.may_be_abstract = true;
5966 }
5967 else if (is_comparison)
5968 {
5969 // In a comparison, the context does not determine the types of
5970 // the operands.
5971 subcontext.type = NULL;
5972 }
5973
5974 // Set the context for the left hand operand.
5975 if (is_shift_op)
5976 {
5977 // The right hand operand of a shift plays no role in
5978 // determining the type of the left hand operand.
5979 }
5980 else if (!tleft->is_abstract())
5981 subcontext.type = tleft;
5982 else if (!tright->is_abstract())
5983 subcontext.type = tright;
5984 else if (subcontext.type == NULL)
5985 {
5986 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5987 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5988 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5989 {
5990 // Both sides have an abstract integer, abstract float, or
5991 // abstract complex type. Just let CONTEXT determine
5992 // whether they may remain abstract or not.
5993 }
5994 else if (tleft->complex_type() != NULL)
5995 subcontext.type = tleft;
5996 else if (tright->complex_type() != NULL)
5997 subcontext.type = tright;
5998 else if (tleft->float_type() != NULL)
5999 subcontext.type = tleft;
6000 else if (tright->float_type() != NULL)
6001 subcontext.type = tright;
6002 else
6003 subcontext.type = tleft;
6004
6005 if (subcontext.type != NULL && !context->may_be_abstract)
6006 subcontext.type = subcontext.type->make_non_abstract_type();
6007 }
6008
6009 this->left_->determine_type(&subcontext);
6010
6011 if (is_shift_op)
6012 {
6013 // We may have inherited an unusable type for the shift operand.
6014 // Give a useful error if that happened.
6015 if (tleft->is_abstract()
6016 && subcontext.type != NULL
6017 && !subcontext.may_be_abstract
6018 && subcontext.type->interface_type() == NULL
6019 && subcontext.type->integer_type() == NULL)
6020 this->report_error(("invalid context-determined non-integer type "
6021 "for left operand of shift"));
6022
6023 // The context for the right hand operand is the same as for the
6024 // left hand operand, except for a shift operator.
6025 subcontext.type = Type::lookup_integer_type("uint");
6026 subcontext.may_be_abstract = false;
6027 }
6028
6029 this->right_->determine_type(&subcontext);
6030
6031 if (is_comparison)
6032 {
6033 if (this->type_ != NULL && !this->type_->is_abstract())
6034 ;
6035 else if (context->type != NULL && context->type->is_boolean_type())
6036 this->type_ = context->type;
6037 else if (!context->may_be_abstract)
6038 this->type_ = Type::lookup_bool_type();
6039 }
6040 }
6041
6042 // Report an error if the binary operator OP does not support TYPE.
6043 // OTYPE is the type of the other operand. Return whether the
6044 // operation is OK. This should not be used for shift.
6045
6046 bool
check_operator_type(Operator op,Type * type,Type * otype,Location location)6047 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
6048 Location location)
6049 {
6050 switch (op)
6051 {
6052 case OPERATOR_OROR:
6053 case OPERATOR_ANDAND:
6054 if (!type->is_boolean_type()
6055 || !otype->is_boolean_type())
6056 {
6057 go_error_at(location, "expected boolean type");
6058 return false;
6059 }
6060 break;
6061
6062 case OPERATOR_EQEQ:
6063 case OPERATOR_NOTEQ:
6064 {
6065 std::string reason;
6066 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
6067 {
6068 go_error_at(location, "%s", reason.c_str());
6069 return false;
6070 }
6071 }
6072 break;
6073
6074 case OPERATOR_LT:
6075 case OPERATOR_LE:
6076 case OPERATOR_GT:
6077 case OPERATOR_GE:
6078 {
6079 std::string reason;
6080 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
6081 {
6082 go_error_at(location, "%s", reason.c_str());
6083 return false;
6084 }
6085 }
6086 break;
6087
6088 case OPERATOR_PLUS:
6089 case OPERATOR_PLUSEQ:
6090 if ((!type->is_numeric_type() && !type->is_string_type())
6091 || (!otype->is_numeric_type() && !otype->is_string_type()))
6092 {
6093 go_error_at(location,
6094 "expected integer, floating, complex, or string type");
6095 return false;
6096 }
6097 break;
6098
6099 case OPERATOR_MINUS:
6100 case OPERATOR_MINUSEQ:
6101 case OPERATOR_MULT:
6102 case OPERATOR_MULTEQ:
6103 case OPERATOR_DIV:
6104 case OPERATOR_DIVEQ:
6105 if (!type->is_numeric_type() || !otype->is_numeric_type())
6106 {
6107 go_error_at(location, "expected integer, floating, or complex type");
6108 return false;
6109 }
6110 break;
6111
6112 case OPERATOR_MOD:
6113 case OPERATOR_MODEQ:
6114 case OPERATOR_OR:
6115 case OPERATOR_OREQ:
6116 case OPERATOR_AND:
6117 case OPERATOR_ANDEQ:
6118 case OPERATOR_XOR:
6119 case OPERATOR_XOREQ:
6120 case OPERATOR_BITCLEAR:
6121 case OPERATOR_BITCLEAREQ:
6122 if (type->integer_type() == NULL || otype->integer_type() == NULL)
6123 {
6124 go_error_at(location, "expected integer type");
6125 return false;
6126 }
6127 break;
6128
6129 default:
6130 go_unreachable();
6131 }
6132
6133 return true;
6134 }
6135
6136 // Check types.
6137
6138 void
do_check_types(Gogo *)6139 Binary_expression::do_check_types(Gogo*)
6140 {
6141 if (this->classification() == EXPRESSION_ERROR)
6142 return;
6143
6144 Type* left_type = this->left_->type();
6145 Type* right_type = this->right_->type();
6146 if (left_type->is_error() || right_type->is_error())
6147 {
6148 this->set_is_error();
6149 return;
6150 }
6151
6152 if (this->op_ == OPERATOR_EQEQ
6153 || this->op_ == OPERATOR_NOTEQ
6154 || this->op_ == OPERATOR_LT
6155 || this->op_ == OPERATOR_LE
6156 || this->op_ == OPERATOR_GT
6157 || this->op_ == OPERATOR_GE)
6158 {
6159 if (left_type->is_nil_type() && right_type->is_nil_type())
6160 {
6161 this->report_error(_("invalid comparison of nil with nil"));
6162 return;
6163 }
6164 if (!Type::are_assignable(left_type, right_type, NULL)
6165 && !Type::are_assignable(right_type, left_type, NULL))
6166 {
6167 this->report_error(_("incompatible types in binary expression"));
6168 return;
6169 }
6170 if (!Binary_expression::check_operator_type(this->op_, left_type,
6171 right_type,
6172 this->location())
6173 || !Binary_expression::check_operator_type(this->op_, right_type,
6174 left_type,
6175 this->location()))
6176 {
6177 this->set_is_error();
6178 return;
6179 }
6180 }
6181 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
6182 {
6183 if (!Type::are_compatible_for_binop(left_type, right_type))
6184 {
6185 this->report_error(_("incompatible types in binary expression"));
6186 return;
6187 }
6188 if (!Binary_expression::check_operator_type(this->op_, left_type,
6189 right_type,
6190 this->location()))
6191 {
6192 this->set_is_error();
6193 return;
6194 }
6195 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
6196 {
6197 // Division by a zero integer constant is an error.
6198 Numeric_constant rconst;
6199 unsigned long rval;
6200 if (left_type->integer_type() != NULL
6201 && this->right_->numeric_constant_value(&rconst)
6202 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
6203 && rval == 0)
6204 {
6205 this->report_error(_("integer division by zero"));
6206 return;
6207 }
6208 }
6209 }
6210 else
6211 {
6212 if (left_type->integer_type() == NULL)
6213 this->report_error(_("shift of non-integer operand"));
6214
6215 if (right_type->is_string_type())
6216 this->report_error(_("shift count not unsigned integer"));
6217 else if (!right_type->is_abstract()
6218 && (right_type->integer_type() == NULL
6219 || !right_type->integer_type()->is_unsigned()))
6220 this->report_error(_("shift count not unsigned integer"));
6221 else
6222 {
6223 Numeric_constant nc;
6224 if (this->right_->numeric_constant_value(&nc))
6225 {
6226 mpz_t val;
6227 if (!nc.to_int(&val))
6228 this->report_error(_("shift count not unsigned integer"));
6229 else
6230 {
6231 if (mpz_sgn(val) < 0)
6232 {
6233 this->report_error(_("negative shift count"));
6234 Location rloc = this->right_->location();
6235 this->right_ = Expression::make_integer_ul(0, right_type,
6236 rloc);
6237 }
6238 mpz_clear(val);
6239 }
6240 }
6241 }
6242 }
6243 }
6244
6245 // Get the backend representation for a binary expression.
6246
6247 Bexpression*
do_get_backend(Translate_context * context)6248 Binary_expression::do_get_backend(Translate_context* context)
6249 {
6250 Gogo* gogo = context->gogo();
6251 Location loc = this->location();
6252 Type* left_type = this->left_->type();
6253 Type* right_type = this->right_->type();
6254
6255 bool use_left_type = true;
6256 bool is_shift_op = false;
6257 bool is_idiv_op = false;
6258 switch (this->op_)
6259 {
6260 case OPERATOR_EQEQ:
6261 case OPERATOR_NOTEQ:
6262 case OPERATOR_LT:
6263 case OPERATOR_LE:
6264 case OPERATOR_GT:
6265 case OPERATOR_GE:
6266 return Expression::comparison(context, this->type_, this->op_,
6267 this->left_, this->right_, loc);
6268
6269 case OPERATOR_OROR:
6270 case OPERATOR_ANDAND:
6271 use_left_type = false;
6272 break;
6273 case OPERATOR_PLUS:
6274 case OPERATOR_MINUS:
6275 case OPERATOR_OR:
6276 case OPERATOR_XOR:
6277 case OPERATOR_MULT:
6278 break;
6279 case OPERATOR_DIV:
6280 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
6281 break;
6282 // Fall through.
6283 case OPERATOR_MOD:
6284 is_idiv_op = true;
6285 break;
6286 case OPERATOR_LSHIFT:
6287 case OPERATOR_RSHIFT:
6288 is_shift_op = true;
6289 break;
6290 case OPERATOR_BITCLEAR:
6291 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
6292 case OPERATOR_AND:
6293 break;
6294 default:
6295 go_unreachable();
6296 }
6297
6298 // The only binary operation for string is +, and that should have
6299 // been converted to a String_concat_expression in do_lower.
6300 go_assert(!left_type->is_string_type());
6301
6302 // For complex division Go might want slightly different results than the
6303 // backend implementation provides, so we have our own runtime routine.
6304 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
6305 {
6306 Runtime::Function complex_code;
6307 switch (this->left_->type()->complex_type()->bits())
6308 {
6309 case 64:
6310 complex_code = Runtime::COMPLEX64_DIV;
6311 break;
6312 case 128:
6313 complex_code = Runtime::COMPLEX128_DIV;
6314 break;
6315 default:
6316 go_unreachable();
6317 }
6318 Expression* complex_div =
6319 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
6320 return complex_div->get_backend(context);
6321 }
6322
6323 Bexpression* left = this->left_->get_backend(context);
6324 Bexpression* right = this->right_->get_backend(context);
6325
6326 Type* type = use_left_type ? left_type : right_type;
6327 Btype* btype = type->get_backend(gogo);
6328
6329 Bexpression* ret =
6330 gogo->backend()->binary_expression(this->op_, left, right, loc);
6331 ret = gogo->backend()->convert_expression(btype, ret, loc);
6332
6333 // Initialize overflow constants.
6334 Bexpression* overflow;
6335 mpz_t zero;
6336 mpz_init_set_ui(zero, 0UL);
6337 mpz_t one;
6338 mpz_init_set_ui(one, 1UL);
6339 mpz_t neg_one;
6340 mpz_init_set_si(neg_one, -1);
6341
6342 Btype* left_btype = left_type->get_backend(gogo);
6343 Btype* right_btype = right_type->get_backend(gogo);
6344
6345 // In Go, a shift larger than the size of the type is well-defined.
6346 // This is not true in C, so we need to insert a conditional.
6347 if (is_shift_op)
6348 {
6349 go_assert(left_type->integer_type() != NULL);
6350
6351 int bits = left_type->integer_type()->bits();
6352
6353 Numeric_constant nc;
6354 unsigned long ul;
6355 if (!this->right_->numeric_constant_value(&nc)
6356 || nc.to_unsigned_long(&ul) != Numeric_constant::NC_UL_VALID
6357 || ul >= static_cast<unsigned long>(bits))
6358 {
6359 mpz_t bitsval;
6360 mpz_init_set_ui(bitsval, bits);
6361 Bexpression* bits_expr =
6362 gogo->backend()->integer_constant_expression(right_btype, bitsval);
6363 Bexpression* compare =
6364 gogo->backend()->binary_expression(OPERATOR_LT,
6365 right, bits_expr, loc);
6366
6367 Bexpression* zero_expr =
6368 gogo->backend()->integer_constant_expression(left_btype, zero);
6369 overflow = zero_expr;
6370 Bfunction* bfn = context->function()->func_value()->get_decl();
6371 if (this->op_ == OPERATOR_RSHIFT
6372 && !left_type->integer_type()->is_unsigned())
6373 {
6374 Bexpression* neg_expr =
6375 gogo->backend()->binary_expression(OPERATOR_LT, left,
6376 zero_expr, loc);
6377 Bexpression* neg_one_expr =
6378 gogo->backend()->integer_constant_expression(left_btype,
6379 neg_one);
6380 overflow = gogo->backend()->conditional_expression(bfn,
6381 btype,
6382 neg_expr,
6383 neg_one_expr,
6384 zero_expr,
6385 loc);
6386 }
6387 ret = gogo->backend()->conditional_expression(bfn, btype, compare,
6388 ret, overflow, loc);
6389 mpz_clear(bitsval);
6390 }
6391 }
6392
6393 // Add checks for division by zero and division overflow as needed.
6394 if (is_idiv_op)
6395 {
6396 if (gogo->check_divide_by_zero())
6397 {
6398 // right == 0
6399 Bexpression* zero_expr =
6400 gogo->backend()->integer_constant_expression(right_btype, zero);
6401 Bexpression* check =
6402 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6403 right, zero_expr, loc);
6404
6405 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
6406 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
6407 Bexpression* crash = gogo->runtime_error(errcode,
6408 loc)->get_backend(context);
6409
6410 // right == 0 ? (__go_runtime_error(...), 0) : ret
6411 Bfunction* bfn = context->function()->func_value()->get_decl();
6412 ret = gogo->backend()->conditional_expression(bfn, btype,
6413 check, crash,
6414 ret, loc);
6415 }
6416
6417 if (gogo->check_divide_overflow())
6418 {
6419 // right == -1
6420 // FIXME: It would be nice to say that this test is expected
6421 // to return false.
6422
6423 Bexpression* neg_one_expr =
6424 gogo->backend()->integer_constant_expression(right_btype, neg_one);
6425 Bexpression* check =
6426 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6427 right, neg_one_expr, loc);
6428
6429 Bexpression* zero_expr =
6430 gogo->backend()->integer_constant_expression(btype, zero);
6431 Bexpression* one_expr =
6432 gogo->backend()->integer_constant_expression(btype, one);
6433 Bfunction* bfn = context->function()->func_value()->get_decl();
6434
6435 if (type->integer_type()->is_unsigned())
6436 {
6437 // An unsigned -1 is the largest possible number, so
6438 // dividing is always 1 or 0.
6439
6440 Bexpression* cmp =
6441 gogo->backend()->binary_expression(OPERATOR_EQEQ,
6442 left, right, loc);
6443 if (this->op_ == OPERATOR_DIV)
6444 overflow =
6445 gogo->backend()->conditional_expression(bfn, btype, cmp,
6446 one_expr, zero_expr,
6447 loc);
6448 else
6449 overflow =
6450 gogo->backend()->conditional_expression(bfn, btype, cmp,
6451 zero_expr, left,
6452 loc);
6453 }
6454 else
6455 {
6456 // Computing left / -1 is the same as computing - left,
6457 // which does not overflow since Go sets -fwrapv.
6458 if (this->op_ == OPERATOR_DIV)
6459 {
6460 Expression* negate_expr =
6461 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
6462 overflow = negate_expr->get_backend(context);
6463 }
6464 else
6465 overflow = zero_expr;
6466 }
6467 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
6468
6469 // right == -1 ? - left : ret
6470 ret = gogo->backend()->conditional_expression(bfn, btype,
6471 check, overflow,
6472 ret, loc);
6473 }
6474 }
6475
6476 mpz_clear(zero);
6477 mpz_clear(one);
6478 mpz_clear(neg_one);
6479 return ret;
6480 }
6481
6482 // Export a binary expression.
6483
6484 void
do_export(Export_function_body * efb) const6485 Binary_expression::do_export(Export_function_body* efb) const
6486 {
6487 efb->write_c_string("(");
6488 this->left_->export_expression(efb);
6489 switch (this->op_)
6490 {
6491 case OPERATOR_OROR:
6492 efb->write_c_string(" || ");
6493 break;
6494 case OPERATOR_ANDAND:
6495 efb->write_c_string(" && ");
6496 break;
6497 case OPERATOR_EQEQ:
6498 efb->write_c_string(" == ");
6499 break;
6500 case OPERATOR_NOTEQ:
6501 efb->write_c_string(" != ");
6502 break;
6503 case OPERATOR_LT:
6504 efb->write_c_string(" < ");
6505 break;
6506 case OPERATOR_LE:
6507 efb->write_c_string(" <= ");
6508 break;
6509 case OPERATOR_GT:
6510 efb->write_c_string(" > ");
6511 break;
6512 case OPERATOR_GE:
6513 efb->write_c_string(" >= ");
6514 break;
6515 case OPERATOR_PLUS:
6516 efb->write_c_string(" + ");
6517 break;
6518 case OPERATOR_MINUS:
6519 efb->write_c_string(" - ");
6520 break;
6521 case OPERATOR_OR:
6522 efb->write_c_string(" | ");
6523 break;
6524 case OPERATOR_XOR:
6525 efb->write_c_string(" ^ ");
6526 break;
6527 case OPERATOR_MULT:
6528 efb->write_c_string(" * ");
6529 break;
6530 case OPERATOR_DIV:
6531 efb->write_c_string(" / ");
6532 break;
6533 case OPERATOR_MOD:
6534 efb->write_c_string(" % ");
6535 break;
6536 case OPERATOR_LSHIFT:
6537 efb->write_c_string(" << ");
6538 break;
6539 case OPERATOR_RSHIFT:
6540 efb->write_c_string(" >> ");
6541 break;
6542 case OPERATOR_AND:
6543 efb->write_c_string(" & ");
6544 break;
6545 case OPERATOR_BITCLEAR:
6546 efb->write_c_string(" &^ ");
6547 break;
6548 default:
6549 go_unreachable();
6550 }
6551 this->right_->export_expression(efb);
6552 efb->write_c_string(")");
6553 }
6554
6555 // Import a binary expression.
6556
6557 Expression*
do_import(Import_expression * imp,Location loc)6558 Binary_expression::do_import(Import_expression* imp, Location loc)
6559 {
6560 imp->require_c_string("(");
6561
6562 Expression* left = Expression::import_expression(imp, loc);
6563
6564 Operator op;
6565 if (imp->match_c_string(" || "))
6566 {
6567 op = OPERATOR_OROR;
6568 imp->advance(4);
6569 }
6570 else if (imp->match_c_string(" && "))
6571 {
6572 op = OPERATOR_ANDAND;
6573 imp->advance(4);
6574 }
6575 else if (imp->match_c_string(" == "))
6576 {
6577 op = OPERATOR_EQEQ;
6578 imp->advance(4);
6579 }
6580 else if (imp->match_c_string(" != "))
6581 {
6582 op = OPERATOR_NOTEQ;
6583 imp->advance(4);
6584 }
6585 else if (imp->match_c_string(" < "))
6586 {
6587 op = OPERATOR_LT;
6588 imp->advance(3);
6589 }
6590 else if (imp->match_c_string(" <= "))
6591 {
6592 op = OPERATOR_LE;
6593 imp->advance(4);
6594 }
6595 else if (imp->match_c_string(" > "))
6596 {
6597 op = OPERATOR_GT;
6598 imp->advance(3);
6599 }
6600 else if (imp->match_c_string(" >= "))
6601 {
6602 op = OPERATOR_GE;
6603 imp->advance(4);
6604 }
6605 else if (imp->match_c_string(" + "))
6606 {
6607 op = OPERATOR_PLUS;
6608 imp->advance(3);
6609 }
6610 else if (imp->match_c_string(" - "))
6611 {
6612 op = OPERATOR_MINUS;
6613 imp->advance(3);
6614 }
6615 else if (imp->match_c_string(" | "))
6616 {
6617 op = OPERATOR_OR;
6618 imp->advance(3);
6619 }
6620 else if (imp->match_c_string(" ^ "))
6621 {
6622 op = OPERATOR_XOR;
6623 imp->advance(3);
6624 }
6625 else if (imp->match_c_string(" * "))
6626 {
6627 op = OPERATOR_MULT;
6628 imp->advance(3);
6629 }
6630 else if (imp->match_c_string(" / "))
6631 {
6632 op = OPERATOR_DIV;
6633 imp->advance(3);
6634 }
6635 else if (imp->match_c_string(" % "))
6636 {
6637 op = OPERATOR_MOD;
6638 imp->advance(3);
6639 }
6640 else if (imp->match_c_string(" << "))
6641 {
6642 op = OPERATOR_LSHIFT;
6643 imp->advance(4);
6644 }
6645 else if (imp->match_c_string(" >> "))
6646 {
6647 op = OPERATOR_RSHIFT;
6648 imp->advance(4);
6649 }
6650 else if (imp->match_c_string(" & "))
6651 {
6652 op = OPERATOR_AND;
6653 imp->advance(3);
6654 }
6655 else if (imp->match_c_string(" &^ "))
6656 {
6657 op = OPERATOR_BITCLEAR;
6658 imp->advance(4);
6659 }
6660 else
6661 {
6662 go_error_at(imp->location(), "unrecognized binary operator");
6663 return Expression::make_error(loc);
6664 }
6665
6666 Expression* right = Expression::import_expression(imp, loc);
6667
6668 imp->require_c_string(")");
6669
6670 return Expression::make_binary(op, left, right, loc);
6671 }
6672
6673 // Dump ast representation of a binary expression.
6674
6675 void
do_dump_expression(Ast_dump_context * ast_dump_context) const6676 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
6677 {
6678 ast_dump_context->ostream() << "(";
6679 ast_dump_context->dump_expression(this->left_);
6680 ast_dump_context->ostream() << " ";
6681 ast_dump_context->dump_operator(this->op_);
6682 ast_dump_context->ostream() << " ";
6683 ast_dump_context->dump_expression(this->right_);
6684 ast_dump_context->ostream() << ") ";
6685 }
6686
6687 // Make a binary expression.
6688
6689 Expression*
make_binary(Operator op,Expression * left,Expression * right,Location location)6690 Expression::make_binary(Operator op, Expression* left, Expression* right,
6691 Location location)
6692 {
6693 return new Binary_expression(op, left, right, location);
6694 }
6695
6696 // Implement a comparison.
6697
6698 Bexpression*
comparison(Translate_context * context,Type * result_type,Operator op,Expression * left,Expression * right,Location location)6699 Expression::comparison(Translate_context* context, Type* result_type,
6700 Operator op, Expression* left, Expression* right,
6701 Location location)
6702 {
6703 Type* left_type = left->type();
6704 Type* right_type = right->type();
6705
6706 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
6707
6708 if (left_type->is_string_type() && right_type->is_string_type())
6709 {
6710 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
6711 {
6712 left = Runtime::make_call(Runtime::EQSTRING, location, 2,
6713 left, right);
6714 right = Expression::make_boolean(true, location);
6715 }
6716 else
6717 {
6718 left = Runtime::make_call(Runtime::CMPSTRING, location, 2,
6719 left, right);
6720 right = zexpr;
6721 }
6722 }
6723 else if ((left_type->interface_type() != NULL
6724 && right_type->interface_type() == NULL
6725 && !right_type->is_nil_type())
6726 || (left_type->interface_type() == NULL
6727 && !left_type->is_nil_type()
6728 && right_type->interface_type() != NULL))
6729 {
6730 // Comparing an interface value to a non-interface value.
6731 if (left_type->interface_type() == NULL)
6732 {
6733 std::swap(left_type, right_type);
6734 std::swap(left, right);
6735 }
6736
6737 // The right operand is not an interface. We need to take its
6738 // address if it is not a pointer.
6739 Expression* pointer_arg = NULL;
6740 if (right_type->points_to() != NULL)
6741 pointer_arg = right;
6742 else
6743 {
6744 go_assert(right->is_addressable());
6745 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6746 location);
6747 }
6748
6749 Expression* descriptor =
6750 Expression::make_type_descriptor(right_type, location);
6751 left =
6752 Runtime::make_call((left_type->interface_type()->is_empty()
6753 ? Runtime::EFACEVALEQ
6754 : Runtime::IFACEVALEQ),
6755 location, 3, left, descriptor,
6756 pointer_arg);
6757 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6758 right = Expression::make_boolean(true, location);
6759 }
6760 else if (left_type->interface_type() != NULL
6761 && right_type->interface_type() != NULL)
6762 {
6763 Runtime::Function compare_function;
6764 if (left_type->interface_type()->is_empty()
6765 && right_type->interface_type()->is_empty())
6766 compare_function = Runtime::EFACEEQ;
6767 else if (!left_type->interface_type()->is_empty()
6768 && !right_type->interface_type()->is_empty())
6769 compare_function = Runtime::IFACEEQ;
6770 else
6771 {
6772 if (left_type->interface_type()->is_empty())
6773 {
6774 std::swap(left_type, right_type);
6775 std::swap(left, right);
6776 }
6777 go_assert(!left_type->interface_type()->is_empty());
6778 go_assert(right_type->interface_type()->is_empty());
6779 compare_function = Runtime::IFACEEFACEEQ;
6780 }
6781
6782 left = Runtime::make_call(compare_function, location, 2, left, right);
6783 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6784 right = Expression::make_boolean(true, location);
6785 }
6786
6787 if (left_type->is_nil_type()
6788 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6789 {
6790 std::swap(left_type, right_type);
6791 std::swap(left, right);
6792 }
6793
6794 if (right_type->is_nil_type())
6795 {
6796 right = Expression::make_nil(location);
6797 if (left_type->array_type() != NULL
6798 && left_type->array_type()->length() == NULL)
6799 {
6800 Array_type* at = left_type->array_type();
6801 bool is_lvalue = false;
6802 left = at->get_value_pointer(context->gogo(), left, is_lvalue);
6803 }
6804 else if (left_type->interface_type() != NULL)
6805 {
6806 // An interface is nil if the first field is nil.
6807 left = Expression::make_field_reference(left, 0, location);
6808 }
6809 }
6810
6811 Bexpression* left_bexpr = left->get_backend(context);
6812 Bexpression* right_bexpr = right->get_backend(context);
6813
6814 Gogo* gogo = context->gogo();
6815 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6816 right_bexpr, location);
6817 if (result_type != NULL)
6818 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6819 ret, location);
6820 return ret;
6821 }
6822
6823 // Class String_concat_expression.
6824
6825 bool
do_is_constant() const6826 String_concat_expression::do_is_constant() const
6827 {
6828 for (Expression_list::const_iterator pe = this->exprs_->begin();
6829 pe != this->exprs_->end();
6830 ++pe)
6831 {
6832 if (!(*pe)->is_constant())
6833 return false;
6834 }
6835 return true;
6836 }
6837
6838 bool
do_is_static_initializer() const6839 String_concat_expression::do_is_static_initializer() const
6840 {
6841 for (Expression_list::const_iterator pe = this->exprs_->begin();
6842 pe != this->exprs_->end();
6843 ++pe)
6844 {
6845 if (!(*pe)->is_static_initializer())
6846 return false;
6847 }
6848 return true;
6849 }
6850
6851 Type*
do_type()6852 String_concat_expression::do_type()
6853 {
6854 Type* t = this->exprs_->front()->type();
6855 Expression_list::iterator pe = this->exprs_->begin();
6856 ++pe;
6857 for (; pe != this->exprs_->end(); ++pe)
6858 {
6859 Type* t1;
6860 if (!Binary_expression::operation_type(OPERATOR_PLUS, t,
6861 (*pe)->type(),
6862 &t1))
6863 return Type::make_error_type();
6864 t = t1;
6865 }
6866 return t;
6867 }
6868
6869 void
do_determine_type(const Type_context * context)6870 String_concat_expression::do_determine_type(const Type_context* context)
6871 {
6872 Type_context subcontext(*context);
6873 for (Expression_list::iterator pe = this->exprs_->begin();
6874 pe != this->exprs_->end();
6875 ++pe)
6876 {
6877 Type* t = (*pe)->type();
6878 if (!t->is_abstract())
6879 {
6880 subcontext.type = t;
6881 break;
6882 }
6883 }
6884 if (subcontext.type == NULL)
6885 subcontext.type = this->exprs_->front()->type();
6886 for (Expression_list::iterator pe = this->exprs_->begin();
6887 pe != this->exprs_->end();
6888 ++pe)
6889 (*pe)->determine_type(&subcontext);
6890 }
6891
6892 void
do_check_types(Gogo *)6893 String_concat_expression::do_check_types(Gogo*)
6894 {
6895 if (this->is_error_expression())
6896 return;
6897 Type* t = this->exprs_->front()->type();
6898 if (t->is_error())
6899 {
6900 this->set_is_error();
6901 return;
6902 }
6903 Expression_list::iterator pe = this->exprs_->begin();
6904 ++pe;
6905 for (; pe != this->exprs_->end(); ++pe)
6906 {
6907 Type* t1 = (*pe)->type();
6908 if (!Type::are_compatible_for_binop(t, t1))
6909 {
6910 this->report_error("incompatible types in binary expression");
6911 return;
6912 }
6913 if (!Binary_expression::check_operator_type(OPERATOR_PLUS, t, t1,
6914 this->location()))
6915 {
6916 this->set_is_error();
6917 return;
6918 }
6919 }
6920 }
6921
6922 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter *)6923 String_concat_expression::do_flatten(Gogo*, Named_object*,
6924 Statement_inserter*)
6925 {
6926 if (this->is_error_expression())
6927 return this;
6928 Location loc = this->location();
6929 Type* type = this->type();
6930 Expression* nil_arg = Expression::make_nil(loc);
6931 Expression* call;
6932 switch (this->exprs_->size())
6933 {
6934 case 0: case 1:
6935 go_unreachable();
6936
6937 case 2: case 3: case 4: case 5:
6938 {
6939 Expression* len = Expression::make_integer_ul(this->exprs_->size(),
6940 NULL, loc);
6941 Array_type* arg_type = Type::make_array_type(type, len);
6942 arg_type->set_is_array_incomparable();
6943 Expression* arg =
6944 Expression::make_array_composite_literal(arg_type, this->exprs_,
6945 loc);
6946 Runtime::Function code;
6947 switch (this->exprs_->size())
6948 {
6949 default:
6950 go_unreachable();
6951 case 2:
6952 code = Runtime::CONCATSTRING2;
6953 break;
6954 case 3:
6955 code = Runtime::CONCATSTRING3;
6956 break;
6957 case 4:
6958 code = Runtime::CONCATSTRING4;
6959 break;
6960 case 5:
6961 code = Runtime::CONCATSTRING5;
6962 break;
6963 }
6964 call = Runtime::make_call(code, loc, 2, nil_arg, arg);
6965 }
6966 break;
6967
6968 default:
6969 {
6970 Type* arg_type = Type::make_array_type(type, NULL);
6971 Slice_construction_expression* sce =
6972 Expression::make_slice_composite_literal(arg_type, this->exprs_,
6973 loc);
6974 sce->set_storage_does_not_escape();
6975 call = Runtime::make_call(Runtime::CONCATSTRINGS, loc, 2, nil_arg,
6976 sce);
6977 }
6978 break;
6979 }
6980
6981 return Expression::make_cast(type, call, loc);
6982 }
6983
6984 void
do_dump_expression(Ast_dump_context * ast_dump_context) const6985 String_concat_expression::do_dump_expression(
6986 Ast_dump_context* ast_dump_context) const
6987 {
6988 ast_dump_context->ostream() << "concat(";
6989 ast_dump_context->dump_expression_list(this->exprs_, false);
6990 ast_dump_context->ostream() << ")";
6991 }
6992
6993 Expression*
make_string_concat(Expression_list * exprs)6994 Expression::make_string_concat(Expression_list* exprs)
6995 {
6996 return new String_concat_expression(exprs);
6997 }
6998
6999 // Class Bound_method_expression.
7000
7001 // Traversal.
7002
7003 int
do_traverse(Traverse * traverse)7004 Bound_method_expression::do_traverse(Traverse* traverse)
7005 {
7006 return Expression::traverse(&this->expr_, traverse);
7007 }
7008
7009 // Return the type of a bound method expression. The type of this
7010 // object is simply the type of the method with no receiver.
7011
7012 Type*
do_type()7013 Bound_method_expression::do_type()
7014 {
7015 Named_object* fn = this->method_->named_object();
7016 Function_type* fntype;
7017 if (fn->is_function())
7018 fntype = fn->func_value()->type();
7019 else if (fn->is_function_declaration())
7020 fntype = fn->func_declaration_value()->type();
7021 else
7022 return Type::make_error_type();
7023 return fntype->copy_without_receiver();
7024 }
7025
7026 // Determine the types of a method expression.
7027
7028 void
do_determine_type(const Type_context *)7029 Bound_method_expression::do_determine_type(const Type_context*)
7030 {
7031 Named_object* fn = this->method_->named_object();
7032 Function_type* fntype;
7033 if (fn->is_function())
7034 fntype = fn->func_value()->type();
7035 else if (fn->is_function_declaration())
7036 fntype = fn->func_declaration_value()->type();
7037 else
7038 fntype = NULL;
7039 if (fntype == NULL || !fntype->is_method())
7040 this->expr_->determine_type_no_context();
7041 else
7042 {
7043 Type_context subcontext(fntype->receiver()->type(), false);
7044 this->expr_->determine_type(&subcontext);
7045 }
7046 }
7047
7048 // Check the types of a method expression.
7049
7050 void
do_check_types(Gogo *)7051 Bound_method_expression::do_check_types(Gogo*)
7052 {
7053 Named_object* fn = this->method_->named_object();
7054 if (!fn->is_function() && !fn->is_function_declaration())
7055 {
7056 this->report_error(_("object is not a method"));
7057 return;
7058 }
7059
7060 Function_type* fntype;
7061 if (fn->is_function())
7062 fntype = fn->func_value()->type();
7063 else if (fn->is_function_declaration())
7064 fntype = fn->func_declaration_value()->type();
7065 else
7066 go_unreachable();
7067 Type* rtype = fntype->receiver()->type()->deref();
7068 Type* etype = (this->expr_type_ != NULL
7069 ? this->expr_type_
7070 : this->expr_->type());
7071 etype = etype->deref();
7072 if (!Type::are_identical(rtype, etype, Type::COMPARE_TAGS, NULL))
7073 this->report_error(_("method type does not match object type"));
7074 }
7075
7076 // If a bound method expression is not simply called, then it is
7077 // represented as a closure. The closure will hold a single variable,
7078 // the receiver to pass to the method. The function will be a simple
7079 // thunk that pulls that value from the closure and calls the method
7080 // with the remaining arguments.
7081 //
7082 // Because method values are not common, we don't build all thunks for
7083 // every methods, but instead only build them as we need them. In
7084 // particular, we even build them on demand for methods defined in
7085 // other packages.
7086
7087 Bound_method_expression::Method_value_thunks
7088 Bound_method_expression::method_value_thunks;
7089
7090 // Find or create the thunk for METHOD.
7091
7092 Named_object*
create_thunk(Gogo * gogo,const Method * method,Named_object * fn)7093 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
7094 Named_object* fn)
7095 {
7096 std::pair<Named_object*, Named_object*> val(fn, NULL);
7097 std::pair<Method_value_thunks::iterator, bool> ins =
7098 Bound_method_expression::method_value_thunks.insert(val);
7099 if (!ins.second)
7100 {
7101 // We have seen this method before.
7102 go_assert(ins.first->second != NULL);
7103 return ins.first->second;
7104 }
7105
7106 Location loc = fn->location();
7107
7108 Function_type* orig_fntype;
7109 if (fn->is_function())
7110 orig_fntype = fn->func_value()->type();
7111 else if (fn->is_function_declaration())
7112 orig_fntype = fn->func_declaration_value()->type();
7113 else
7114 orig_fntype = NULL;
7115
7116 if (orig_fntype == NULL || !orig_fntype->is_method())
7117 {
7118 ins.first->second =
7119 Named_object::make_erroneous_name(gogo->thunk_name());
7120 return ins.first->second;
7121 }
7122
7123 Struct_field_list* sfl = new Struct_field_list();
7124 // The type here is wrong--it should be the C function type. But it
7125 // doesn't really matter.
7126 Type* vt = Type::make_pointer_type(Type::make_void_type());
7127 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
7128 sfl->push_back(Struct_field(Typed_identifier("val",
7129 orig_fntype->receiver()->type(),
7130 loc)));
7131 Struct_type* st = Type::make_struct_type(sfl, loc);
7132 st->set_is_struct_incomparable();
7133 Type* closure_type = Type::make_pointer_type(st);
7134
7135 Function_type* new_fntype = orig_fntype->copy_with_names();
7136
7137 std::string thunk_name = gogo->thunk_name();
7138 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
7139 false, loc);
7140
7141 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
7142 cvar->set_is_used();
7143 cvar->set_is_closure();
7144 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
7145 NULL, cvar);
7146 new_no->func_value()->set_closure_var(cp);
7147
7148 gogo->start_block(loc);
7149
7150 // Field 0 of the closure is the function code pointer, field 1 is
7151 // the value on which to invoke the method.
7152 Expression* arg = Expression::make_var_reference(cp, loc);
7153 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
7154 arg = Expression::make_field_reference(arg, 1, loc);
7155
7156 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
7157
7158 const Typed_identifier_list* orig_params = orig_fntype->parameters();
7159 Expression_list* args;
7160 if (orig_params == NULL || orig_params->empty())
7161 args = NULL;
7162 else
7163 {
7164 const Typed_identifier_list* new_params = new_fntype->parameters();
7165 args = new Expression_list();
7166 for (Typed_identifier_list::const_iterator p = new_params->begin();
7167 p != new_params->end();
7168 ++p)
7169 {
7170 Named_object* p_no = gogo->lookup(p->name(), NULL);
7171 go_assert(p_no != NULL
7172 && p_no->is_variable()
7173 && p_no->var_value()->is_parameter());
7174 args->push_back(Expression::make_var_reference(p_no, loc));
7175 }
7176 }
7177
7178 Call_expression* call = Expression::make_call(bme, args,
7179 orig_fntype->is_varargs(),
7180 loc);
7181 call->set_varargs_are_lowered();
7182
7183 Statement* s = Statement::make_return_from_call(call, loc);
7184 gogo->add_statement(s);
7185 Block* b = gogo->finish_block(loc);
7186 gogo->add_block(b, loc);
7187 gogo->lower_block(new_no, b);
7188 gogo->flatten_block(new_no, b);
7189 gogo->finish_function(loc);
7190
7191 ins.first->second = new_no;
7192 return new_no;
7193 }
7194
7195 // Return an expression to check *REF for nil while dereferencing
7196 // according to FIELD_INDEXES. Update *REF to build up the field
7197 // reference. This is a static function so that we don't have to
7198 // worry about declaring Field_indexes in expressions.h.
7199
7200 static Expression*
bme_check_nil(const Method::Field_indexes * field_indexes,Location loc,Expression ** ref)7201 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
7202 Expression** ref)
7203 {
7204 if (field_indexes == NULL)
7205 return Expression::make_boolean(false, loc);
7206 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
7207 Struct_type* stype = (*ref)->type()->deref()->struct_type();
7208 go_assert(stype != NULL
7209 && field_indexes->field_index < stype->field_count());
7210 if ((*ref)->type()->struct_type() == NULL)
7211 {
7212 go_assert((*ref)->type()->points_to() != NULL);
7213 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
7214 Expression::make_nil(loc),
7215 loc);
7216 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
7217 *ref = Expression::make_dereference(*ref, Expression::NIL_CHECK_DEFAULT,
7218 loc);
7219 go_assert((*ref)->type()->struct_type() == stype);
7220 }
7221 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
7222 loc);
7223 return cond;
7224 }
7225
7226 // Flatten a method value into a struct with nil checks. We can't do
7227 // this in the lowering phase, because if the method value is called
7228 // directly we don't need a thunk. That case will have been handled
7229 // by Call_expression::do_lower, so if we get here then we do need a
7230 // thunk.
7231
7232 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)7233 Bound_method_expression::do_flatten(Gogo* gogo, Named_object*,
7234 Statement_inserter* inserter)
7235 {
7236 Location loc = this->location();
7237
7238 Named_object* thunk = Bound_method_expression::create_thunk(gogo,
7239 this->method_,
7240 this->function_);
7241 if (thunk->is_erroneous())
7242 {
7243 go_assert(saw_errors());
7244 return Expression::make_error(loc);
7245 }
7246
7247 // Force the expression into a variable. This is only necessary if
7248 // we are going to do nil checks below, but it's easy enough to
7249 // always do it.
7250 Expression* expr = this->expr_;
7251 if (!expr->is_variable())
7252 {
7253 Temporary_statement* etemp = Statement::make_temporary(NULL, expr, loc);
7254 inserter->insert(etemp);
7255 expr = Expression::make_temporary_reference(etemp, loc);
7256 }
7257
7258 // If the method expects a value, and we have a pointer, we need to
7259 // dereference the pointer.
7260
7261 Named_object* fn = this->method_->named_object();
7262 Function_type *fntype;
7263 if (fn->is_function())
7264 fntype = fn->func_value()->type();
7265 else if (fn->is_function_declaration())
7266 fntype = fn->func_declaration_value()->type();
7267 else
7268 go_unreachable();
7269
7270 Expression* val = expr;
7271 if (fntype->receiver()->type()->points_to() == NULL
7272 && val->type()->points_to() != NULL)
7273 val = Expression::make_dereference(val, NIL_CHECK_DEFAULT, loc);
7274
7275 // Note that we are ignoring this->expr_type_ here. The thunk will
7276 // expect a closure whose second field has type this->expr_type_ (if
7277 // that is not NULL). We are going to pass it a closure whose
7278 // second field has type this->expr_->type(). Since
7279 // this->expr_type_ is only not-NULL for pointer types, we can get
7280 // away with this.
7281
7282 Struct_field_list* fields = new Struct_field_list();
7283 fields->push_back(Struct_field(Typed_identifier("fn",
7284 thunk->func_value()->type(),
7285 loc)));
7286 fields->push_back(Struct_field(Typed_identifier("val", val->type(), loc)));
7287 Struct_type* st = Type::make_struct_type(fields, loc);
7288 st->set_is_struct_incomparable();
7289
7290 Expression_list* vals = new Expression_list();
7291 vals->push_back(Expression::make_func_code_reference(thunk, loc));
7292 vals->push_back(val);
7293
7294 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
7295 ret = Expression::make_heap_expression(ret, loc);
7296
7297 Node* n = Node::make_node(this);
7298 if ((n->encoding() & ESCAPE_MASK) == Node::ESCAPE_NONE)
7299 ret->heap_expression()->set_allocate_on_stack();
7300 else if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
7301 go_error_at(loc, "%s escapes to heap, not allowed in runtime",
7302 n->ast_format(gogo).c_str());
7303
7304 // If necessary, check whether the expression or any embedded
7305 // pointers are nil.
7306
7307 Expression* nil_check = NULL;
7308 if (this->method_->field_indexes() != NULL)
7309 {
7310 Expression* ref = expr;
7311 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
7312 expr = ref;
7313 }
7314
7315 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
7316 {
7317 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
7318 Expression::make_nil(loc),
7319 loc);
7320 if (nil_check == NULL)
7321 nil_check = n;
7322 else
7323 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
7324 }
7325
7326 if (nil_check != NULL)
7327 {
7328 Expression* crash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
7329 loc);
7330 // Fix the type of the conditional expression by pretending to
7331 // evaluate to RET either way through the conditional.
7332 crash = Expression::make_compound(crash, ret, loc);
7333 ret = Expression::make_conditional(nil_check, crash, ret, loc);
7334 }
7335
7336 // RET is a pointer to a struct, but we want a function type.
7337 ret = Expression::make_unsafe_cast(this->type(), ret, loc);
7338
7339 return ret;
7340 }
7341
7342 // Dump ast representation of a bound method expression.
7343
7344 void
do_dump_expression(Ast_dump_context * ast_dump_context) const7345 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
7346 const
7347 {
7348 if (this->expr_type_ != NULL)
7349 ast_dump_context->ostream() << "(";
7350 ast_dump_context->dump_expression(this->expr_);
7351 if (this->expr_type_ != NULL)
7352 {
7353 ast_dump_context->ostream() << ":";
7354 ast_dump_context->dump_type(this->expr_type_);
7355 ast_dump_context->ostream() << ")";
7356 }
7357
7358 ast_dump_context->ostream() << "." << this->function_->name();
7359 }
7360
7361 // Make a method expression.
7362
7363 Bound_method_expression*
make_bound_method(Expression * expr,const Method * method,Named_object * function,Location location)7364 Expression::make_bound_method(Expression* expr, const Method* method,
7365 Named_object* function, Location location)
7366 {
7367 return new Bound_method_expression(expr, method, function, location);
7368 }
7369
7370 // Class Builtin_call_expression. This is used for a call to a
7371 // builtin function.
7372
Builtin_call_expression(Gogo * gogo,Expression * fn,Expression_list * args,bool is_varargs,Location location)7373 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
7374 Expression* fn,
7375 Expression_list* args,
7376 bool is_varargs,
7377 Location location)
7378 : Call_expression(fn, args, is_varargs, location),
7379 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
7380 recover_arg_is_set_(false)
7381 {
7382 Func_expression* fnexp = this->fn()->func_expression();
7383 if (fnexp == NULL)
7384 {
7385 this->code_ = BUILTIN_INVALID;
7386 return;
7387 }
7388 const std::string& name(fnexp->named_object()->name());
7389 if (name == "append")
7390 this->code_ = BUILTIN_APPEND;
7391 else if (name == "cap")
7392 this->code_ = BUILTIN_CAP;
7393 else if (name == "close")
7394 this->code_ = BUILTIN_CLOSE;
7395 else if (name == "complex")
7396 this->code_ = BUILTIN_COMPLEX;
7397 else if (name == "copy")
7398 this->code_ = BUILTIN_COPY;
7399 else if (name == "delete")
7400 this->code_ = BUILTIN_DELETE;
7401 else if (name == "imag")
7402 this->code_ = BUILTIN_IMAG;
7403 else if (name == "len")
7404 this->code_ = BUILTIN_LEN;
7405 else if (name == "make")
7406 this->code_ = BUILTIN_MAKE;
7407 else if (name == "new")
7408 this->code_ = BUILTIN_NEW;
7409 else if (name == "panic")
7410 this->code_ = BUILTIN_PANIC;
7411 else if (name == "print")
7412 this->code_ = BUILTIN_PRINT;
7413 else if (name == "println")
7414 this->code_ = BUILTIN_PRINTLN;
7415 else if (name == "real")
7416 this->code_ = BUILTIN_REAL;
7417 else if (name == "recover")
7418 this->code_ = BUILTIN_RECOVER;
7419 else if (name == "Alignof")
7420 this->code_ = BUILTIN_ALIGNOF;
7421 else if (name == "Offsetof")
7422 this->code_ = BUILTIN_OFFSETOF;
7423 else if (name == "Sizeof")
7424 this->code_ = BUILTIN_SIZEOF;
7425 else
7426 go_unreachable();
7427 }
7428
7429 // Return whether this is a call to recover. This is a virtual
7430 // function called from the parent class.
7431
7432 bool
do_is_recover_call() const7433 Builtin_call_expression::do_is_recover_call() const
7434 {
7435 if (this->classification() == EXPRESSION_ERROR)
7436 return false;
7437 return this->code_ == BUILTIN_RECOVER;
7438 }
7439
7440 // Set the argument for a call to recover.
7441
7442 void
do_set_recover_arg(Expression * arg)7443 Builtin_call_expression::do_set_recover_arg(Expression* arg)
7444 {
7445 const Expression_list* args = this->args();
7446 go_assert(args == NULL || args->empty());
7447 Expression_list* new_args = new Expression_list();
7448 new_args->push_back(arg);
7449 this->set_args(new_args);
7450 this->recover_arg_is_set_ = true;
7451 }
7452
7453 // Lower a builtin call expression. This turns new and make into
7454 // specific expressions. We also convert to a constant if we can.
7455
7456 Expression*
do_lower(Gogo *,Named_object * function,Statement_inserter * inserter,int)7457 Builtin_call_expression::do_lower(Gogo*, Named_object* function,
7458 Statement_inserter* inserter, int)
7459 {
7460 if (this->is_error_expression())
7461 return this;
7462
7463 Location loc = this->location();
7464
7465 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
7466 {
7467 this->report_error(_("invalid use of %<...%> with builtin function"));
7468 return Expression::make_error(loc);
7469 }
7470
7471 if (this->code_ == BUILTIN_OFFSETOF)
7472 {
7473 Expression* arg = this->one_arg();
7474
7475 if (arg->bound_method_expression() != NULL
7476 || arg->interface_field_reference_expression() != NULL)
7477 {
7478 this->report_error(_("invalid use of method value as argument "
7479 "of Offsetof"));
7480 return this;
7481 }
7482
7483 Field_reference_expression* farg = arg->field_reference_expression();
7484 while (farg != NULL)
7485 {
7486 if (!farg->implicit())
7487 break;
7488 // When the selector refers to an embedded field,
7489 // it must not be reached through pointer indirections.
7490 if (farg->expr()->deref() != farg->expr())
7491 {
7492 this->report_error(_("argument of Offsetof implies "
7493 "indirection of an embedded field"));
7494 return this;
7495 }
7496 // Go up until we reach the original base.
7497 farg = farg->expr()->field_reference_expression();
7498 }
7499 }
7500
7501 if (this->is_constant())
7502 {
7503 Numeric_constant nc;
7504 if (this->numeric_constant_value(&nc))
7505 return nc.expression(loc);
7506 }
7507
7508 switch (this->code_)
7509 {
7510 default:
7511 break;
7512
7513 case BUILTIN_NEW:
7514 {
7515 const Expression_list* args = this->args();
7516 if (args == NULL || args->size() < 1)
7517 this->report_error(_("not enough arguments"));
7518 else if (args->size() > 1)
7519 this->report_error(_("too many arguments"));
7520 else
7521 {
7522 Expression* arg = args->front();
7523 if (!arg->is_type_expression())
7524 {
7525 go_error_at(arg->location(), "expected type");
7526 this->set_is_error();
7527 }
7528 else
7529 return Expression::make_allocation(arg->type(), loc);
7530 }
7531 }
7532 break;
7533
7534 case BUILTIN_MAKE:
7535 return this->lower_make(inserter);
7536
7537 case BUILTIN_RECOVER:
7538 if (function != NULL)
7539 function->func_value()->set_calls_recover();
7540 else
7541 {
7542 // Calling recover outside of a function always returns the
7543 // nil empty interface.
7544 Type* eface = Type::make_empty_interface_type(loc);
7545 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
7546 }
7547 break;
7548
7549 case BUILTIN_DELETE:
7550 {
7551 // Lower to a runtime function call.
7552 const Expression_list* args = this->args();
7553 if (args == NULL || args->size() < 2)
7554 this->report_error(_("not enough arguments"));
7555 else if (args->size() > 2)
7556 this->report_error(_("too many arguments"));
7557 else if (args->front()->type()->map_type() == NULL)
7558 this->report_error(_("argument 1 must be a map"));
7559 else
7560 {
7561 // Since this function returns no value it must appear in
7562 // a statement by itself, so we don't have to worry about
7563 // order of evaluation of values around it. Evaluate the
7564 // map first to get order of evaluation right.
7565 Map_type* mt = args->front()->type()->map_type();
7566 Temporary_statement* map_temp =
7567 Statement::make_temporary(mt, args->front(), loc);
7568 inserter->insert(map_temp);
7569
7570 Temporary_statement* key_temp =
7571 Statement::make_temporary(mt->key_type(), args->back(), loc);
7572 inserter->insert(key_temp);
7573
7574 Expression* e1 = Expression::make_type_descriptor(mt, loc);
7575 Expression* e2 = Expression::make_temporary_reference(map_temp,
7576 loc);
7577 Expression* e3 = Expression::make_temporary_reference(key_temp,
7578 loc);
7579
7580 // If the call to delete is deferred, and is in a loop,
7581 // then the loop will only have a single instance of the
7582 // temporary variable. Passing the address of the
7583 // temporary variable here means that the deferred call
7584 // will see the last value in the loop, not the current
7585 // value. So for this unusual case copy the value into
7586 // the heap.
7587 if (!this->is_deferred())
7588 e3 = Expression::make_unary(OPERATOR_AND, e3, loc);
7589 else
7590 {
7591 Expression* a = Expression::make_allocation(mt->key_type(),
7592 loc);
7593 Temporary_statement* atemp =
7594 Statement::make_temporary(NULL, a, loc);
7595 inserter->insert(atemp);
7596
7597 a = Expression::make_temporary_reference(atemp, loc);
7598 a = Expression::make_dereference(a, NIL_CHECK_NOT_NEEDED, loc);
7599 Statement* s = Statement::make_assignment(a, e3, loc);
7600 inserter->insert(s);
7601
7602 e3 = Expression::make_temporary_reference(atemp, loc);
7603 }
7604
7605 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
7606 3, e1, e2, e3);
7607 }
7608 }
7609 break;
7610
7611 case BUILTIN_PRINT:
7612 case BUILTIN_PRINTLN:
7613 // Force all the arguments into temporary variables, so that we
7614 // don't try to evaluate something while holding the print lock.
7615 if (this->args() == NULL)
7616 break;
7617 for (Expression_list::iterator pa = this->args()->begin();
7618 pa != this->args()->end();
7619 ++pa)
7620 {
7621 if (!(*pa)->is_variable() && !(*pa)->is_constant())
7622 {
7623 Temporary_statement* temp =
7624 Statement::make_temporary(NULL, *pa, loc);
7625 inserter->insert(temp);
7626 *pa = Expression::make_temporary_reference(temp, loc);
7627 }
7628 }
7629 break;
7630 }
7631
7632 return this;
7633 }
7634
7635 // Flatten a builtin call expression. This turns the arguments of copy and
7636 // append into temporary expressions.
7637
7638 Expression*
do_flatten(Gogo * gogo,Named_object * function,Statement_inserter * inserter)7639 Builtin_call_expression::do_flatten(Gogo* gogo, Named_object* function,
7640 Statement_inserter* inserter)
7641 {
7642 Location loc = this->location();
7643
7644 switch (this->code_)
7645 {
7646 default:
7647 break;
7648
7649 case BUILTIN_APPEND:
7650 return this->flatten_append(gogo, function, inserter, NULL, NULL);
7651
7652 case BUILTIN_COPY:
7653 {
7654 Type* at = this->args()->front()->type();
7655 for (Expression_list::iterator pa = this->args()->begin();
7656 pa != this->args()->end();
7657 ++pa)
7658 {
7659 if ((*pa)->is_nil_expression())
7660 {
7661 Expression* nil = Expression::make_nil(loc);
7662 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
7663 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
7664 }
7665 if (!(*pa)->is_variable())
7666 {
7667 Temporary_statement* temp =
7668 Statement::make_temporary(NULL, *pa, loc);
7669 inserter->insert(temp);
7670 *pa = Expression::make_temporary_reference(temp, loc);
7671 }
7672 }
7673 }
7674 break;
7675
7676 case BUILTIN_PANIC:
7677 for (Expression_list::iterator pa = this->args()->begin();
7678 pa != this->args()->end();
7679 ++pa)
7680 {
7681 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
7682 {
7683 Temporary_statement* temp =
7684 Statement::make_temporary(NULL, *pa, loc);
7685 inserter->insert(temp);
7686 *pa = Expression::make_temporary_reference(temp, loc);
7687 }
7688 }
7689 break;
7690
7691 case BUILTIN_LEN:
7692 case BUILTIN_CAP:
7693 {
7694 Expression_list::iterator pa = this->args()->begin();
7695 if (!(*pa)->is_variable()
7696 && ((*pa)->type()->map_type() != NULL
7697 || (*pa)->type()->channel_type() != NULL))
7698 {
7699 Temporary_statement* temp =
7700 Statement::make_temporary(NULL, *pa, loc);
7701 inserter->insert(temp);
7702 *pa = Expression::make_temporary_reference(temp, loc);
7703 }
7704 }
7705 break;
7706 }
7707
7708 return this;
7709 }
7710
7711 // Lower a make expression.
7712
7713 Expression*
lower_make(Statement_inserter * inserter)7714 Builtin_call_expression::lower_make(Statement_inserter* inserter)
7715 {
7716 Location loc = this->location();
7717
7718 const Expression_list* args = this->args();
7719 if (args == NULL || args->size() < 1)
7720 {
7721 this->report_error(_("not enough arguments"));
7722 return Expression::make_error(this->location());
7723 }
7724
7725 Expression_list::const_iterator parg = args->begin();
7726
7727 Expression* first_arg = *parg;
7728 if (!first_arg->is_type_expression())
7729 {
7730 go_error_at(first_arg->location(), "expected type");
7731 this->set_is_error();
7732 return Expression::make_error(this->location());
7733 }
7734 Type* type = first_arg->type();
7735
7736 if (!type->in_heap())
7737 go_error_at(first_arg->location(),
7738 "can't make slice of go:notinheap type");
7739
7740 bool is_slice = false;
7741 bool is_map = false;
7742 bool is_chan = false;
7743 if (type->is_slice_type())
7744 is_slice = true;
7745 else if (type->map_type() != NULL)
7746 is_map = true;
7747 else if (type->channel_type() != NULL)
7748 is_chan = true;
7749 else
7750 {
7751 this->report_error(_("invalid type for make function"));
7752 return Expression::make_error(this->location());
7753 }
7754
7755 Type_context int_context(Type::lookup_integer_type("int"), false);
7756
7757 ++parg;
7758 Expression* len_arg;
7759 bool len_small = false;
7760 if (parg == args->end())
7761 {
7762 if (is_slice)
7763 {
7764 this->report_error(_("length required when allocating a slice"));
7765 return Expression::make_error(this->location());
7766 }
7767 len_arg = Expression::make_integer_ul(0, NULL, loc);
7768 len_small = true;
7769 }
7770 else
7771 {
7772 len_arg = *parg;
7773 len_arg->determine_type(&int_context);
7774 if (len_arg->type()->integer_type() == NULL)
7775 {
7776 go_error_at(len_arg->location(), "non-integer len argument in make");
7777 return Expression::make_error(this->location());
7778 }
7779 if (!this->check_int_value(len_arg, true, &len_small))
7780 return Expression::make_error(this->location());
7781 ++parg;
7782 }
7783
7784 Expression* cap_arg = NULL;
7785 bool cap_small = false;
7786 Numeric_constant nclen;
7787 Numeric_constant nccap;
7788 unsigned long vlen;
7789 unsigned long vcap;
7790 if (is_slice && parg != args->end())
7791 {
7792 cap_arg = *parg;
7793 cap_arg->determine_type(&int_context);
7794 if (cap_arg->type()->integer_type() == NULL)
7795 {
7796 go_error_at(cap_arg->location(), "non-integer cap argument in make");
7797 return Expression::make_error(this->location());
7798 }
7799 if (!this->check_int_value(cap_arg, false, &cap_small))
7800 return Expression::make_error(this->location());
7801
7802 if (len_arg->numeric_constant_value(&nclen)
7803 && cap_arg->numeric_constant_value(&nccap)
7804 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7805 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
7806 && vlen > vcap)
7807 {
7808 this->report_error(_("len larger than cap"));
7809 return Expression::make_error(this->location());
7810 }
7811
7812 ++parg;
7813 }
7814
7815 if (parg != args->end())
7816 {
7817 this->report_error(_("too many arguments to make"));
7818 return Expression::make_error(this->location());
7819 }
7820
7821 Location type_loc = first_arg->location();
7822
7823 Expression* call;
7824 if (is_slice)
7825 {
7826 Temporary_statement* len_temp = NULL;
7827 if (!len_arg->is_constant())
7828 {
7829 len_temp = Statement::make_temporary(NULL, len_arg, loc);
7830 inserter->insert(len_temp);
7831 len_arg = Expression::make_temporary_reference(len_temp, loc);
7832 }
7833
7834 if (cap_arg == NULL)
7835 {
7836 cap_small = len_small;
7837 if (len_temp == NULL)
7838 cap_arg = len_arg->copy();
7839 else
7840 cap_arg = Expression::make_temporary_reference(len_temp, loc);
7841 }
7842 else if (!cap_arg->is_constant())
7843 {
7844 Temporary_statement* cap_temp = Statement::make_temporary(NULL,
7845 cap_arg,
7846 loc);
7847 inserter->insert(cap_temp);
7848 cap_arg = Expression::make_temporary_reference(cap_temp, loc);
7849 }
7850
7851 Type* et = type->array_type()->element_type();
7852 Expression* type_arg = Expression::make_type_descriptor(et, type_loc);
7853 Runtime::Function code = Runtime::MAKESLICE;
7854 if (!len_small || !cap_small)
7855 code = Runtime::MAKESLICE64;
7856 Expression* mem = Runtime::make_call(code, loc, 3, type_arg, len_arg,
7857 cap_arg);
7858 mem = Expression::make_unsafe_cast(Type::make_pointer_type(et), mem,
7859 loc);
7860 Type* int_type = Type::lookup_integer_type("int");
7861 len_arg = Expression::make_cast(int_type, len_arg->copy(), loc);
7862 cap_arg = Expression::make_cast(int_type, cap_arg->copy(), loc);
7863 call = Expression::make_slice_value(type, mem, len_arg, cap_arg, loc);
7864 }
7865 else if (is_map)
7866 {
7867 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7868 if (!len_small)
7869 call = Runtime::make_call(Runtime::MAKEMAP64, loc, 3, type_arg,
7870 len_arg,
7871 Expression::make_nil(loc));
7872 else
7873 {
7874 Numeric_constant nclen;
7875 unsigned long vlen;
7876 if (len_arg->numeric_constant_value(&nclen)
7877 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
7878 && vlen <= Map_type::bucket_size)
7879 call = Runtime::make_call(Runtime::MAKEMAP_SMALL, loc, 0);
7880 else
7881 call = Runtime::make_call(Runtime::MAKEMAP, loc, 3, type_arg,
7882 len_arg,
7883 Expression::make_nil(loc));
7884 }
7885 }
7886 else if (is_chan)
7887 {
7888 Expression* type_arg = Expression::make_type_descriptor(type, type_loc);
7889 Runtime::Function code = Runtime::MAKECHAN;
7890 if (!len_small)
7891 code = Runtime::MAKECHAN64;
7892 call = Runtime::make_call(code, loc, 2, type_arg, len_arg);
7893 }
7894 else
7895 go_unreachable();
7896
7897 return Expression::make_unsafe_cast(type, call, loc);
7898 }
7899
7900 // Flatten a call to the predeclared append function. We do this in
7901 // the flatten phase, not the lowering phase, so that we run after
7902 // type checking and after order_evaluations. If ASSIGN_LHS is not
7903 // NULL, this append is the right-hand-side of an assignment and
7904 // ASSIGN_LHS is the left-hand-side; in that case, set LHS directly
7905 // rather than returning a slice. This lets us omit a write barrier
7906 // in common cases like a = append(a, ...) when the slice does not
7907 // need to grow. ENCLOSING is not NULL iff ASSIGN_LHS is not NULL.
7908
7909 Expression*
flatten_append(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Expression * assign_lhs,Block * enclosing)7910 Builtin_call_expression::flatten_append(Gogo* gogo, Named_object* function,
7911 Statement_inserter* inserter,
7912 Expression* assign_lhs,
7913 Block* enclosing)
7914 {
7915 if (this->is_error_expression())
7916 return this;
7917
7918 Location loc = this->location();
7919
7920 const Expression_list* args = this->args();
7921 go_assert(args != NULL && !args->empty());
7922
7923 Type* slice_type = args->front()->type();
7924 go_assert(slice_type->is_slice_type());
7925 Type* element_type = slice_type->array_type()->element_type();
7926
7927 if (args->size() == 1)
7928 {
7929 // append(s) evaluates to s.
7930 if (assign_lhs != NULL)
7931 return NULL;
7932 return args->front();
7933 }
7934
7935 Type* int_type = Type::lookup_integer_type("int");
7936 Type* uint_type = Type::lookup_integer_type("uint");
7937
7938 // Implementing
7939 // append(s1, s2...)
7940 // or
7941 // append(s1, a1, a2, a3, ...)
7942
7943 // s1tmp := s1
7944 Temporary_statement* s1tmp = Statement::make_temporary(NULL, args->front(),
7945 loc);
7946 inserter->insert(s1tmp);
7947
7948 // l1tmp := len(s1tmp)
7949 Named_object* lenfn = gogo->lookup_global("len");
7950 Expression* lenref = Expression::make_func_reference(lenfn, NULL, loc);
7951 Expression_list* call_args = new Expression_list();
7952 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
7953 Expression* len = Expression::make_call(lenref, call_args, false, loc);
7954 gogo->lower_expression(function, inserter, &len);
7955 gogo->flatten_expression(function, inserter, &len);
7956 Temporary_statement* l1tmp = Statement::make_temporary(int_type, len, loc);
7957 inserter->insert(l1tmp);
7958
7959 Temporary_statement* s2tmp = NULL;
7960 Temporary_statement* l2tmp = NULL;
7961 Expression_list* add = NULL;
7962 Expression* len2;
7963 if (this->is_varargs())
7964 {
7965 go_assert(args->size() == 2);
7966
7967 // s2tmp := s2
7968 s2tmp = Statement::make_temporary(NULL, args->back(), loc);
7969 inserter->insert(s2tmp);
7970
7971 // l2tmp := len(s2tmp)
7972 lenref = Expression::make_func_reference(lenfn, NULL, loc);
7973 call_args = new Expression_list();
7974 call_args->push_back(Expression::make_temporary_reference(s2tmp, loc));
7975 len = Expression::make_call(lenref, call_args, false, loc);
7976 gogo->lower_expression(function, inserter, &len);
7977 gogo->flatten_expression(function, inserter, &len);
7978 l2tmp = Statement::make_temporary(int_type, len, loc);
7979 inserter->insert(l2tmp);
7980
7981 // len2 = l2tmp
7982 len2 = Expression::make_temporary_reference(l2tmp, loc);
7983 }
7984 else
7985 {
7986 // We have to ensure that all the arguments are in variables
7987 // now, because otherwise if one of them is an index expression
7988 // into the current slice we could overwrite it before we fetch
7989 // it.
7990 add = new Expression_list();
7991 Expression_list::const_iterator pa = args->begin();
7992 for (++pa; pa != args->end(); ++pa)
7993 {
7994 if ((*pa)->is_variable())
7995 add->push_back(*pa);
7996 else
7997 {
7998 Temporary_statement* tmp = Statement::make_temporary(NULL, *pa,
7999 loc);
8000 inserter->insert(tmp);
8001 add->push_back(Expression::make_temporary_reference(tmp, loc));
8002 }
8003 }
8004
8005 // len2 = len(add)
8006 len2 = Expression::make_integer_ul(add->size(), int_type, loc);
8007 }
8008
8009 // ntmp := l1tmp + len2
8010 Expression* ref = Expression::make_temporary_reference(l1tmp, loc);
8011 Expression* sum = Expression::make_binary(OPERATOR_PLUS, ref, len2, loc);
8012 gogo->lower_expression(function, inserter, &sum);
8013 gogo->flatten_expression(function, inserter, &sum);
8014 Temporary_statement* ntmp = Statement::make_temporary(int_type, sum, loc);
8015 inserter->insert(ntmp);
8016
8017 // s1tmp = uint(ntmp) > uint(cap(s1tmp)) ?
8018 // growslice(type, s1tmp, ntmp) :
8019 // s1tmp[:ntmp]
8020 // Using uint here means that if the computation of ntmp overflowed,
8021 // we will call growslice which will panic.
8022
8023 Named_object* capfn = gogo->lookup_global("cap");
8024 Expression* capref = Expression::make_func_reference(capfn, NULL, loc);
8025 call_args = new Expression_list();
8026 call_args->push_back(Expression::make_temporary_reference(s1tmp, loc));
8027 Expression* cap = Expression::make_call(capref, call_args, false, loc);
8028 gogo->lower_expression(function, inserter, &cap);
8029 gogo->flatten_expression(function, inserter, &cap);
8030 Temporary_statement* c1tmp = Statement::make_temporary(int_type, cap, loc);
8031 inserter->insert(c1tmp);
8032
8033 Expression* left = Expression::make_temporary_reference(ntmp, loc);
8034 left = Expression::make_cast(uint_type, left, loc);
8035 Expression* right = Expression::make_temporary_reference(c1tmp, loc);
8036 right = Expression::make_cast(uint_type, right, loc);
8037
8038 Expression* cond = Expression::make_binary(OPERATOR_GT, left, right, loc);
8039
8040 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8041 Expression* a1 = Expression::make_type_descriptor(element_type, loc);
8042 Expression* a2 = Expression::make_temporary_reference(s1tmp, loc);
8043 a2 = slice_type->array_type()->get_value_pointer(gogo, a2, false);
8044 a2 = Expression::make_cast(unsafe_ptr_type, a2, loc);
8045 Expression* a3 = Expression::make_temporary_reference(l1tmp, loc);
8046 Expression* a4 = Expression::make_temporary_reference(c1tmp, loc);
8047 Expression* a5 = Expression::make_temporary_reference(ntmp, loc);
8048 Expression* call = Runtime::make_call(Runtime::GROWSLICE, loc, 5,
8049 a1, a2, a3, a4, a5);
8050 call = Expression::make_unsafe_cast(slice_type, call, loc);
8051
8052 ref = Expression::make_temporary_reference(s1tmp, loc);
8053 Expression* zero = Expression::make_integer_ul(0, int_type, loc);
8054 Expression* ref2 = Expression::make_temporary_reference(ntmp, loc);
8055 ref = Expression::make_array_index(ref, zero, ref2, NULL, loc);
8056 ref->array_index_expression()->set_needs_bounds_check(false);
8057
8058 if (assign_lhs == NULL)
8059 {
8060 Expression* rhs = Expression::make_conditional(cond, call, ref, loc);
8061
8062 gogo->lower_expression(function, inserter, &rhs);
8063 gogo->flatten_expression(function, inserter, &rhs);
8064
8065 ref = Expression::make_temporary_reference(s1tmp, loc);
8066 Statement* assign = Statement::make_assignment(ref, rhs, loc);
8067 inserter->insert(assign);
8068 }
8069 else
8070 {
8071 gogo->lower_expression(function, inserter, &cond);
8072 gogo->flatten_expression(function, inserter, &cond);
8073 gogo->lower_expression(function, inserter, &call);
8074 gogo->flatten_expression(function, inserter, &call);
8075 gogo->lower_expression(function, inserter, &ref);
8076 gogo->flatten_expression(function, inserter, &ref);
8077
8078 Block* then_block = new Block(enclosing, loc);
8079 Assignment_statement* assign =
8080 Statement::make_assignment(assign_lhs, call, loc);
8081 then_block->add_statement(assign);
8082
8083 Block* else_block = new Block(enclosing, loc);
8084 assign = Statement::make_assignment(assign_lhs->copy(), ref, loc);
8085 // This assignment will not change the pointer value, so it does
8086 // not need a write barrier.
8087 assign->set_omit_write_barrier();
8088 else_block->add_statement(assign);
8089
8090 Statement* s = Statement::make_if_statement(cond, then_block,
8091 else_block, loc);
8092 inserter->insert(s);
8093
8094 ref = Expression::make_temporary_reference(s1tmp, loc);
8095 assign = Statement::make_assignment(ref, assign_lhs->copy(), loc);
8096 inserter->insert(assign);
8097 }
8098
8099 if (this->is_varargs())
8100 {
8101 // copy(s1tmp[l1tmp:], s2tmp)
8102 a1 = Expression::make_temporary_reference(s1tmp, loc);
8103 ref = Expression::make_temporary_reference(l1tmp, loc);
8104 Expression* nil = Expression::make_nil(loc);
8105 a1 = Expression::make_array_index(a1, ref, nil, NULL, loc);
8106 a1->array_index_expression()->set_needs_bounds_check(false);
8107
8108 a2 = Expression::make_temporary_reference(s2tmp, loc);
8109
8110 Named_object* copyfn = gogo->lookup_global("copy");
8111 Expression* copyref = Expression::make_func_reference(copyfn, NULL, loc);
8112 call_args = new Expression_list();
8113 call_args->push_back(a1);
8114 call_args->push_back(a2);
8115 call = Expression::make_call(copyref, call_args, false, loc);
8116 gogo->lower_expression(function, inserter, &call);
8117 gogo->flatten_expression(function, inserter, &call);
8118 inserter->insert(Statement::make_statement(call, false));
8119 }
8120 else
8121 {
8122 // For each argument:
8123 // s1tmp[l1tmp+i] = a
8124 unsigned long i = 0;
8125 for (Expression_list::const_iterator pa = add->begin();
8126 pa != add->end();
8127 ++pa, ++i)
8128 {
8129 ref = Expression::make_temporary_reference(s1tmp, loc);
8130 ref2 = Expression::make_temporary_reference(l1tmp, loc);
8131 Expression* off = Expression::make_integer_ul(i, int_type, loc);
8132 ref2 = Expression::make_binary(OPERATOR_PLUS, ref2, off, loc);
8133 Expression* lhs = Expression::make_array_index(ref, ref2, NULL,
8134 NULL, loc);
8135 lhs->array_index_expression()->set_needs_bounds_check(false);
8136 gogo->lower_expression(function, inserter, &lhs);
8137 gogo->flatten_expression(function, inserter, &lhs);
8138 // The flatten pass runs after the write barrier pass, so we
8139 // need to insert a write barrier here if necessary.
8140 // However, if ASSIGN_LHS is not NULL, we have been called
8141 // directly before the write barrier pass.
8142 Statement* assign;
8143 if (assign_lhs != NULL
8144 || !gogo->assign_needs_write_barrier(lhs))
8145 assign = Statement::make_assignment(lhs, *pa, loc);
8146 else
8147 {
8148 Function* f = function == NULL ? NULL : function->func_value();
8149 assign = gogo->assign_with_write_barrier(f, NULL, inserter,
8150 lhs, *pa, loc);
8151 }
8152 inserter->insert(assign);
8153 }
8154 }
8155
8156 if (assign_lhs != NULL)
8157 return NULL;
8158
8159 return Expression::make_temporary_reference(s1tmp, loc);
8160 }
8161
8162 // Return whether an expression has an integer value. Report an error
8163 // if not. This is used when handling calls to the predeclared make
8164 // function. Set *SMALL if the value is known to fit in type "int".
8165
8166 bool
check_int_value(Expression * e,bool is_length,bool * small)8167 Builtin_call_expression::check_int_value(Expression* e, bool is_length,
8168 bool *small)
8169 {
8170 *small = false;
8171
8172 Numeric_constant nc;
8173 if (e->numeric_constant_value(&nc))
8174 {
8175 unsigned long v;
8176 switch (nc.to_unsigned_long(&v))
8177 {
8178 case Numeric_constant::NC_UL_VALID:
8179 break;
8180 case Numeric_constant::NC_UL_NOTINT:
8181 go_error_at(e->location(), "non-integer %s argument to make",
8182 is_length ? "len" : "cap");
8183 return false;
8184 case Numeric_constant::NC_UL_NEGATIVE:
8185 go_error_at(e->location(), "negative %s argument to make",
8186 is_length ? "len" : "cap");
8187 return false;
8188 case Numeric_constant::NC_UL_BIG:
8189 // We don't want to give a compile-time error for a 64-bit
8190 // value on a 32-bit target.
8191 break;
8192 }
8193
8194 mpz_t val;
8195 if (!nc.to_int(&val))
8196 go_unreachable();
8197 int bits = mpz_sizeinbase(val, 2);
8198 mpz_clear(val);
8199 Type* int_type = Type::lookup_integer_type("int");
8200 if (bits >= int_type->integer_type()->bits())
8201 {
8202 go_error_at(e->location(), "%s argument too large for make",
8203 is_length ? "len" : "cap");
8204 return false;
8205 }
8206
8207 *small = true;
8208 return true;
8209 }
8210
8211 if (e->type()->integer_type() != NULL)
8212 {
8213 int ebits = e->type()->integer_type()->bits();
8214 int intbits = Type::lookup_integer_type("int")->integer_type()->bits();
8215
8216 // We can treat ebits == intbits as small even for an unsigned
8217 // integer type, because we will convert the value to int and
8218 // then reject it in the runtime if it is negative.
8219 *small = ebits <= intbits;
8220
8221 return true;
8222 }
8223
8224 go_error_at(e->location(), "non-integer %s argument to make",
8225 is_length ? "len" : "cap");
8226 return false;
8227 }
8228
8229 // Return the type of the real or imag functions, given the type of
8230 // the argument. We need to map complex64 to float32 and complex128
8231 // to float64, so it has to be done by name. This returns NULL if it
8232 // can't figure out the type.
8233
8234 Type*
real_imag_type(Type * arg_type)8235 Builtin_call_expression::real_imag_type(Type* arg_type)
8236 {
8237 if (arg_type == NULL || arg_type->is_abstract())
8238 return NULL;
8239 Named_type* nt = arg_type->named_type();
8240 if (nt == NULL)
8241 return NULL;
8242 while (nt->real_type()->named_type() != NULL)
8243 nt = nt->real_type()->named_type();
8244 if (nt->name() == "complex64")
8245 return Type::lookup_float_type("float32");
8246 else if (nt->name() == "complex128")
8247 return Type::lookup_float_type("float64");
8248 else
8249 return NULL;
8250 }
8251
8252 // Return the type of the complex function, given the type of one of the
8253 // argments. Like real_imag_type, we have to map by name.
8254
8255 Type*
complex_type(Type * arg_type)8256 Builtin_call_expression::complex_type(Type* arg_type)
8257 {
8258 if (arg_type == NULL || arg_type->is_abstract())
8259 return NULL;
8260 Named_type* nt = arg_type->named_type();
8261 if (nt == NULL)
8262 return NULL;
8263 while (nt->real_type()->named_type() != NULL)
8264 nt = nt->real_type()->named_type();
8265 if (nt->name() == "float32")
8266 return Type::lookup_complex_type("complex64");
8267 else if (nt->name() == "float64")
8268 return Type::lookup_complex_type("complex128");
8269 else
8270 return NULL;
8271 }
8272
8273 // Return a single argument, or NULL if there isn't one.
8274
8275 Expression*
one_arg() const8276 Builtin_call_expression::one_arg() const
8277 {
8278 const Expression_list* args = this->args();
8279 if (args == NULL || args->size() != 1)
8280 return NULL;
8281 return args->front();
8282 }
8283
8284 // A traversal class which looks for a call or receive expression.
8285
8286 class Find_call_expression : public Traverse
8287 {
8288 public:
Find_call_expression()8289 Find_call_expression()
8290 : Traverse(traverse_expressions),
8291 found_(false)
8292 { }
8293
8294 int
8295 expression(Expression**);
8296
8297 bool
found()8298 found()
8299 { return this->found_; }
8300
8301 private:
8302 bool found_;
8303 };
8304
8305 int
expression(Expression ** pexpr)8306 Find_call_expression::expression(Expression** pexpr)
8307 {
8308 Expression* expr = *pexpr;
8309 if (!expr->is_constant()
8310 && (expr->call_expression() != NULL
8311 || expr->receive_expression() != NULL))
8312 {
8313 this->found_ = true;
8314 return TRAVERSE_EXIT;
8315 }
8316 return TRAVERSE_CONTINUE;
8317 }
8318
8319 // Return whether calling len or cap on EXPR, of array type, is a
8320 // constant. The language spec says "the expressions len(s) and
8321 // cap(s) are constants if the type of s is an array or pointer to an
8322 // array and the expression s does not contain channel receives or
8323 // (non-constant) function calls."
8324
8325 bool
array_len_is_constant(Expression * expr)8326 Builtin_call_expression::array_len_is_constant(Expression* expr)
8327 {
8328 go_assert(expr->type()->deref()->array_type() != NULL
8329 && !expr->type()->deref()->is_slice_type());
8330 if (expr->is_constant())
8331 return true;
8332 Find_call_expression find_call;
8333 Expression::traverse(&expr, &find_call);
8334 return !find_call.found();
8335 }
8336
8337 // Return whether this is constant: len of a string constant, or len
8338 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
8339 // unsafe.Alignof.
8340
8341 bool
do_is_constant() const8342 Builtin_call_expression::do_is_constant() const
8343 {
8344 if (this->is_error_expression())
8345 return true;
8346 switch (this->code_)
8347 {
8348 case BUILTIN_LEN:
8349 case BUILTIN_CAP:
8350 {
8351 if (this->seen_)
8352 return false;
8353
8354 Expression* arg = this->one_arg();
8355 if (arg == NULL)
8356 return false;
8357 Type* arg_type = arg->type();
8358
8359 if (arg_type->points_to() != NULL
8360 && arg_type->points_to()->array_type() != NULL
8361 && !arg_type->points_to()->is_slice_type())
8362 arg_type = arg_type->points_to();
8363
8364 if (arg_type->array_type() != NULL
8365 && arg_type->array_type()->length() != NULL)
8366 {
8367 this->seen_ = true;
8368 bool ret = Builtin_call_expression::array_len_is_constant(arg);
8369 this->seen_ = false;
8370 return ret;
8371 }
8372
8373 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8374 {
8375 this->seen_ = true;
8376 bool ret = arg->is_constant();
8377 this->seen_ = false;
8378 return ret;
8379 }
8380 }
8381 break;
8382
8383 case BUILTIN_SIZEOF:
8384 case BUILTIN_ALIGNOF:
8385 return this->one_arg() != NULL;
8386
8387 case BUILTIN_OFFSETOF:
8388 {
8389 Expression* arg = this->one_arg();
8390 if (arg == NULL)
8391 return false;
8392 return arg->field_reference_expression() != NULL;
8393 }
8394
8395 case BUILTIN_COMPLEX:
8396 {
8397 const Expression_list* args = this->args();
8398 if (args != NULL && args->size() == 2)
8399 return args->front()->is_constant() && args->back()->is_constant();
8400 }
8401 break;
8402
8403 case BUILTIN_REAL:
8404 case BUILTIN_IMAG:
8405 {
8406 Expression* arg = this->one_arg();
8407 return arg != NULL && arg->is_constant();
8408 }
8409
8410 default:
8411 break;
8412 }
8413
8414 return false;
8415 }
8416
8417 // Return a numeric constant if possible.
8418
8419 bool
do_numeric_constant_value(Numeric_constant * nc) const8420 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
8421 {
8422 if (this->code_ == BUILTIN_LEN
8423 || this->code_ == BUILTIN_CAP)
8424 {
8425 Expression* arg = this->one_arg();
8426 if (arg == NULL)
8427 return false;
8428 Type* arg_type = arg->type();
8429
8430 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
8431 {
8432 std::string sval;
8433 if (arg->string_constant_value(&sval))
8434 {
8435 nc->set_unsigned_long(Type::lookup_integer_type("int"),
8436 sval.length());
8437 return true;
8438 }
8439 }
8440
8441 if (arg_type->points_to() != NULL
8442 && arg_type->points_to()->array_type() != NULL
8443 && !arg_type->points_to()->is_slice_type())
8444 arg_type = arg_type->points_to();
8445
8446 if (arg_type->array_type() != NULL
8447 && arg_type->array_type()->length() != NULL)
8448 {
8449 if (this->seen_)
8450 return false;
8451 Expression* e = arg_type->array_type()->length();
8452 this->seen_ = true;
8453 bool r = e->numeric_constant_value(nc);
8454 this->seen_ = false;
8455 if (r)
8456 {
8457 if (!nc->set_type(Type::lookup_integer_type("int"), false,
8458 this->location()))
8459 r = false;
8460 }
8461 return r;
8462 }
8463 }
8464 else if (this->code_ == BUILTIN_SIZEOF
8465 || this->code_ == BUILTIN_ALIGNOF)
8466 {
8467 Expression* arg = this->one_arg();
8468 if (arg == NULL)
8469 return false;
8470 Type* arg_type = arg->type();
8471 if (arg_type->is_error())
8472 return false;
8473 if (arg_type->is_abstract())
8474 arg_type = arg_type->make_non_abstract_type();
8475 if (this->seen_)
8476 return false;
8477
8478 int64_t ret;
8479 if (this->code_ == BUILTIN_SIZEOF)
8480 {
8481 this->seen_ = true;
8482 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
8483 this->seen_ = false;
8484 if (!ok)
8485 return false;
8486 }
8487 else if (this->code_ == BUILTIN_ALIGNOF)
8488 {
8489 bool ok;
8490 this->seen_ = true;
8491 if (arg->field_reference_expression() == NULL)
8492 ok = arg_type->backend_type_align(this->gogo_, &ret);
8493 else
8494 {
8495 // Calling unsafe.Alignof(s.f) returns the alignment of
8496 // the type of f when it is used as a field in a struct.
8497 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
8498 }
8499 this->seen_ = false;
8500 if (!ok)
8501 return false;
8502 }
8503 else
8504 go_unreachable();
8505
8506 mpz_t zval;
8507 set_mpz_from_int64(&zval, ret);
8508 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8509 mpz_clear(zval);
8510 return true;
8511 }
8512 else if (this->code_ == BUILTIN_OFFSETOF)
8513 {
8514 Expression* arg = this->one_arg();
8515 if (arg == NULL)
8516 return false;
8517 Field_reference_expression* farg = arg->field_reference_expression();
8518 if (farg == NULL)
8519 return false;
8520 if (this->seen_)
8521 return false;
8522
8523 int64_t total_offset = 0;
8524 while (true)
8525 {
8526 Expression* struct_expr = farg->expr();
8527 Type* st = struct_expr->type();
8528 if (st->struct_type() == NULL)
8529 return false;
8530 if (st->named_type() != NULL)
8531 st->named_type()->convert(this->gogo_);
8532 if (st->is_error_type())
8533 {
8534 go_assert(saw_errors());
8535 return false;
8536 }
8537 int64_t offset;
8538 this->seen_ = true;
8539 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
8540 farg->field_index(),
8541 &offset);
8542 this->seen_ = false;
8543 if (!ok)
8544 return false;
8545 total_offset += offset;
8546 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
8547 {
8548 // Go up until we reach the original base.
8549 farg = struct_expr->field_reference_expression();
8550 continue;
8551 }
8552 break;
8553 }
8554 mpz_t zval;
8555 set_mpz_from_int64(&zval, total_offset);
8556 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
8557 mpz_clear(zval);
8558 return true;
8559 }
8560 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
8561 {
8562 Expression* arg = this->one_arg();
8563 if (arg == NULL)
8564 return false;
8565
8566 Numeric_constant argnc;
8567 if (!arg->numeric_constant_value(&argnc))
8568 return false;
8569
8570 mpc_t val;
8571 if (!argnc.to_complex(&val))
8572 return false;
8573
8574 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
8575 if (this->code_ == BUILTIN_REAL)
8576 nc->set_float(type, mpc_realref(val));
8577 else
8578 nc->set_float(type, mpc_imagref(val));
8579 mpc_clear(val);
8580 return true;
8581 }
8582 else if (this->code_ == BUILTIN_COMPLEX)
8583 {
8584 const Expression_list* args = this->args();
8585 if (args == NULL || args->size() != 2)
8586 return false;
8587
8588 Numeric_constant rnc;
8589 if (!args->front()->numeric_constant_value(&rnc))
8590 return false;
8591 Numeric_constant inc;
8592 if (!args->back()->numeric_constant_value(&inc))
8593 return false;
8594
8595 if (rnc.type() != NULL
8596 && !rnc.type()->is_abstract()
8597 && inc.type() != NULL
8598 && !inc.type()->is_abstract()
8599 && !Type::are_identical(rnc.type(), inc.type(),
8600 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
8601 NULL))
8602 return false;
8603
8604 mpfr_t r;
8605 if (!rnc.to_float(&r))
8606 return false;
8607 mpfr_t i;
8608 if (!inc.to_float(&i))
8609 {
8610 mpfr_clear(r);
8611 return false;
8612 }
8613
8614 Type* arg_type = rnc.type();
8615 if (arg_type == NULL || arg_type->is_abstract())
8616 arg_type = inc.type();
8617
8618 mpc_t val;
8619 mpc_init2(val, mpc_precision);
8620 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
8621 mpfr_clear(r);
8622 mpfr_clear(i);
8623
8624 Type* type = Builtin_call_expression::complex_type(arg_type);
8625 nc->set_complex(type, val);
8626
8627 mpc_clear(val);
8628
8629 return true;
8630 }
8631
8632 return false;
8633 }
8634
8635 // Give an error if we are discarding the value of an expression which
8636 // should not normally be discarded. We don't give an error for
8637 // discarding the value of an ordinary function call, but we do for
8638 // builtin functions, purely for consistency with the gc compiler.
8639
8640 bool
do_discarding_value()8641 Builtin_call_expression::do_discarding_value()
8642 {
8643 switch (this->code_)
8644 {
8645 case BUILTIN_INVALID:
8646 default:
8647 go_unreachable();
8648
8649 case BUILTIN_APPEND:
8650 case BUILTIN_CAP:
8651 case BUILTIN_COMPLEX:
8652 case BUILTIN_IMAG:
8653 case BUILTIN_LEN:
8654 case BUILTIN_MAKE:
8655 case BUILTIN_NEW:
8656 case BUILTIN_REAL:
8657 case BUILTIN_ALIGNOF:
8658 case BUILTIN_OFFSETOF:
8659 case BUILTIN_SIZEOF:
8660 this->unused_value_error();
8661 return false;
8662
8663 case BUILTIN_CLOSE:
8664 case BUILTIN_COPY:
8665 case BUILTIN_DELETE:
8666 case BUILTIN_PANIC:
8667 case BUILTIN_PRINT:
8668 case BUILTIN_PRINTLN:
8669 case BUILTIN_RECOVER:
8670 return true;
8671 }
8672 }
8673
8674 // Return the type.
8675
8676 Type*
do_type()8677 Builtin_call_expression::do_type()
8678 {
8679 if (this->is_error_expression())
8680 return Type::make_error_type();
8681 switch (this->code_)
8682 {
8683 case BUILTIN_INVALID:
8684 default:
8685 return Type::make_error_type();
8686
8687 case BUILTIN_NEW:
8688 {
8689 const Expression_list* args = this->args();
8690 if (args == NULL || args->empty())
8691 return Type::make_error_type();
8692 return Type::make_pointer_type(args->front()->type());
8693 }
8694
8695 case BUILTIN_MAKE:
8696 {
8697 const Expression_list* args = this->args();
8698 if (args == NULL || args->empty())
8699 return Type::make_error_type();
8700 return args->front()->type();
8701 }
8702
8703 case BUILTIN_CAP:
8704 case BUILTIN_COPY:
8705 case BUILTIN_LEN:
8706 return Type::lookup_integer_type("int");
8707
8708 case BUILTIN_ALIGNOF:
8709 case BUILTIN_OFFSETOF:
8710 case BUILTIN_SIZEOF:
8711 return Type::lookup_integer_type("uintptr");
8712
8713 case BUILTIN_CLOSE:
8714 case BUILTIN_DELETE:
8715 case BUILTIN_PANIC:
8716 case BUILTIN_PRINT:
8717 case BUILTIN_PRINTLN:
8718 return Type::make_void_type();
8719
8720 case BUILTIN_RECOVER:
8721 return Type::make_empty_interface_type(Linemap::predeclared_location());
8722
8723 case BUILTIN_APPEND:
8724 {
8725 const Expression_list* args = this->args();
8726 if (args == NULL || args->empty())
8727 return Type::make_error_type();
8728 Type *ret = args->front()->type();
8729 if (!ret->is_slice_type())
8730 return Type::make_error_type();
8731 return ret;
8732 }
8733
8734 case BUILTIN_REAL:
8735 case BUILTIN_IMAG:
8736 {
8737 Expression* arg = this->one_arg();
8738 if (arg == NULL)
8739 return Type::make_error_type();
8740 Type* t = arg->type();
8741 if (t->is_abstract())
8742 t = t->make_non_abstract_type();
8743 t = Builtin_call_expression::real_imag_type(t);
8744 if (t == NULL)
8745 t = Type::make_error_type();
8746 return t;
8747 }
8748
8749 case BUILTIN_COMPLEX:
8750 {
8751 const Expression_list* args = this->args();
8752 if (args == NULL || args->size() != 2)
8753 return Type::make_error_type();
8754 Type* t = args->front()->type();
8755 if (t->is_abstract())
8756 {
8757 t = args->back()->type();
8758 if (t->is_abstract())
8759 t = t->make_non_abstract_type();
8760 }
8761 t = Builtin_call_expression::complex_type(t);
8762 if (t == NULL)
8763 t = Type::make_error_type();
8764 return t;
8765 }
8766 }
8767 }
8768
8769 // Determine the type.
8770
8771 void
do_determine_type(const Type_context * context)8772 Builtin_call_expression::do_determine_type(const Type_context* context)
8773 {
8774 if (!this->determining_types())
8775 return;
8776
8777 this->fn()->determine_type_no_context();
8778
8779 const Expression_list* args = this->args();
8780
8781 bool is_print;
8782 Type* arg_type = NULL;
8783 Type* trailing_arg_types = NULL;
8784 switch (this->code_)
8785 {
8786 case BUILTIN_PRINT:
8787 case BUILTIN_PRINTLN:
8788 // Do not force a large integer constant to "int".
8789 is_print = true;
8790 break;
8791
8792 case BUILTIN_REAL:
8793 case BUILTIN_IMAG:
8794 arg_type = Builtin_call_expression::complex_type(context->type);
8795 if (arg_type == NULL)
8796 arg_type = Type::lookup_complex_type("complex128");
8797 is_print = false;
8798 break;
8799
8800 case BUILTIN_COMPLEX:
8801 {
8802 // For the complex function the type of one operand can
8803 // determine the type of the other, as in a binary expression.
8804 arg_type = Builtin_call_expression::real_imag_type(context->type);
8805 if (arg_type == NULL)
8806 arg_type = Type::lookup_float_type("float64");
8807 if (args != NULL && args->size() == 2)
8808 {
8809 Type* t1 = args->front()->type();
8810 Type* t2 = args->back()->type();
8811 if (!t1->is_abstract())
8812 arg_type = t1;
8813 else if (!t2->is_abstract())
8814 arg_type = t2;
8815 }
8816 is_print = false;
8817 }
8818 break;
8819
8820 case BUILTIN_APPEND:
8821 if (!this->is_varargs()
8822 && args != NULL
8823 && !args->empty()
8824 && args->front()->type()->is_slice_type())
8825 trailing_arg_types =
8826 args->front()->type()->array_type()->element_type();
8827 is_print = false;
8828 break;
8829
8830 default:
8831 is_print = false;
8832 break;
8833 }
8834
8835 if (args != NULL)
8836 {
8837 for (Expression_list::const_iterator pa = args->begin();
8838 pa != args->end();
8839 ++pa)
8840 {
8841 Type_context subcontext;
8842 subcontext.type = arg_type;
8843
8844 if (is_print)
8845 {
8846 // We want to print large constants, we so can't just
8847 // use the appropriate nonabstract type. Use uint64 for
8848 // an integer if we know it is nonnegative, otherwise
8849 // use int64 for a integer, otherwise use float64 for a
8850 // float or complex128 for a complex.
8851 Type* want_type = NULL;
8852 Type* atype = (*pa)->type();
8853 if (atype->is_abstract())
8854 {
8855 if (atype->integer_type() != NULL)
8856 {
8857 Numeric_constant nc;
8858 if (this->numeric_constant_value(&nc))
8859 {
8860 mpz_t val;
8861 if (nc.to_int(&val))
8862 {
8863 if (mpz_sgn(val) >= 0)
8864 want_type = Type::lookup_integer_type("uint64");
8865 mpz_clear(val);
8866 }
8867 }
8868 if (want_type == NULL)
8869 want_type = Type::lookup_integer_type("int64");
8870 }
8871 else if (atype->float_type() != NULL)
8872 want_type = Type::lookup_float_type("float64");
8873 else if (atype->complex_type() != NULL)
8874 want_type = Type::lookup_complex_type("complex128");
8875 else if (atype->is_abstract_string_type())
8876 want_type = Type::lookup_string_type();
8877 else if (atype->is_abstract_boolean_type())
8878 want_type = Type::lookup_bool_type();
8879 else
8880 go_unreachable();
8881 subcontext.type = want_type;
8882 }
8883 }
8884
8885 (*pa)->determine_type(&subcontext);
8886
8887 if (trailing_arg_types != NULL)
8888 {
8889 arg_type = trailing_arg_types;
8890 trailing_arg_types = NULL;
8891 }
8892 }
8893 }
8894 }
8895
8896 // If there is exactly one argument, return true. Otherwise give an
8897 // error message and return false.
8898
8899 bool
check_one_arg()8900 Builtin_call_expression::check_one_arg()
8901 {
8902 const Expression_list* args = this->args();
8903 if (args == NULL || args->size() < 1)
8904 {
8905 this->report_error(_("not enough arguments"));
8906 return false;
8907 }
8908 else if (args->size() > 1)
8909 {
8910 this->report_error(_("too many arguments"));
8911 return false;
8912 }
8913 if (args->front()->is_error_expression()
8914 || args->front()->type()->is_error())
8915 {
8916 this->set_is_error();
8917 return false;
8918 }
8919 return true;
8920 }
8921
8922 // Check argument types for a builtin function.
8923
8924 void
do_check_types(Gogo *)8925 Builtin_call_expression::do_check_types(Gogo*)
8926 {
8927 if (this->is_error_expression())
8928 return;
8929 switch (this->code_)
8930 {
8931 case BUILTIN_INVALID:
8932 case BUILTIN_NEW:
8933 case BUILTIN_MAKE:
8934 case BUILTIN_DELETE:
8935 return;
8936
8937 case BUILTIN_LEN:
8938 case BUILTIN_CAP:
8939 {
8940 // The single argument may be either a string or an array or a
8941 // map or a channel, or a pointer to a closed array.
8942 if (this->check_one_arg())
8943 {
8944 Type* arg_type = this->one_arg()->type();
8945 if (arg_type->points_to() != NULL
8946 && arg_type->points_to()->array_type() != NULL
8947 && !arg_type->points_to()->is_slice_type())
8948 arg_type = arg_type->points_to();
8949 if (this->code_ == BUILTIN_CAP)
8950 {
8951 if (!arg_type->is_error()
8952 && arg_type->array_type() == NULL
8953 && arg_type->channel_type() == NULL)
8954 this->report_error(_("argument must be array or slice "
8955 "or channel"));
8956 }
8957 else
8958 {
8959 if (!arg_type->is_error()
8960 && !arg_type->is_string_type()
8961 && arg_type->array_type() == NULL
8962 && arg_type->map_type() == NULL
8963 && arg_type->channel_type() == NULL)
8964 this->report_error(_("argument must be string or "
8965 "array or slice or map or channel"));
8966 }
8967 }
8968 }
8969 break;
8970
8971 case BUILTIN_PRINT:
8972 case BUILTIN_PRINTLN:
8973 {
8974 const Expression_list* args = this->args();
8975 if (args == NULL)
8976 {
8977 if (this->code_ == BUILTIN_PRINT)
8978 go_warning_at(this->location(), 0,
8979 "no arguments for builtin function %<%s%>",
8980 (this->code_ == BUILTIN_PRINT
8981 ? "print"
8982 : "println"));
8983 }
8984 else
8985 {
8986 for (Expression_list::const_iterator p = args->begin();
8987 p != args->end();
8988 ++p)
8989 {
8990 Type* type = (*p)->type();
8991 if (type->is_error()
8992 || type->is_string_type()
8993 || type->integer_type() != NULL
8994 || type->float_type() != NULL
8995 || type->complex_type() != NULL
8996 || type->is_boolean_type()
8997 || type->points_to() != NULL
8998 || type->interface_type() != NULL
8999 || type->channel_type() != NULL
9000 || type->map_type() != NULL
9001 || type->function_type() != NULL
9002 || type->is_slice_type())
9003 ;
9004 else if ((*p)->is_type_expression())
9005 {
9006 // If this is a type expression it's going to give
9007 // an error anyhow, so we don't need one here.
9008 }
9009 else
9010 this->report_error(_("unsupported argument type to "
9011 "builtin function"));
9012 }
9013 }
9014 }
9015 break;
9016
9017 case BUILTIN_CLOSE:
9018 if (this->check_one_arg())
9019 {
9020 if (this->one_arg()->type()->channel_type() == NULL)
9021 this->report_error(_("argument must be channel"));
9022 else if (!this->one_arg()->type()->channel_type()->may_send())
9023 this->report_error(_("cannot close receive-only channel"));
9024 }
9025 break;
9026
9027 case BUILTIN_PANIC:
9028 case BUILTIN_SIZEOF:
9029 case BUILTIN_ALIGNOF:
9030 this->check_one_arg();
9031 break;
9032
9033 case BUILTIN_RECOVER:
9034 if (this->args() != NULL
9035 && !this->args()->empty()
9036 && !this->recover_arg_is_set_)
9037 this->report_error(_("too many arguments"));
9038 break;
9039
9040 case BUILTIN_OFFSETOF:
9041 if (this->check_one_arg())
9042 {
9043 Expression* arg = this->one_arg();
9044 if (arg->field_reference_expression() == NULL)
9045 this->report_error(_("argument must be a field reference"));
9046 }
9047 break;
9048
9049 case BUILTIN_COPY:
9050 {
9051 const Expression_list* args = this->args();
9052 if (args == NULL || args->size() < 2)
9053 {
9054 this->report_error(_("not enough arguments"));
9055 break;
9056 }
9057 else if (args->size() > 2)
9058 {
9059 this->report_error(_("too many arguments"));
9060 break;
9061 }
9062 Type* arg1_type = args->front()->type();
9063 Type* arg2_type = args->back()->type();
9064 if (arg1_type->is_error() || arg2_type->is_error())
9065 {
9066 this->set_is_error();
9067 break;
9068 }
9069
9070 Type* e1;
9071 if (arg1_type->is_slice_type())
9072 e1 = arg1_type->array_type()->element_type();
9073 else
9074 {
9075 this->report_error(_("left argument must be a slice"));
9076 break;
9077 }
9078
9079 if (arg2_type->is_slice_type())
9080 {
9081 Type* e2 = arg2_type->array_type()->element_type();
9082 if (!Type::are_identical(e1, e2, Type::COMPARE_TAGS, NULL))
9083 this->report_error(_("element types must be the same"));
9084 }
9085 else if (arg2_type->is_string_type())
9086 {
9087 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
9088 this->report_error(_("first argument must be []byte"));
9089 }
9090 else
9091 this->report_error(_("second argument must be slice or string"));
9092 }
9093 break;
9094
9095 case BUILTIN_APPEND:
9096 {
9097 const Expression_list* args = this->args();
9098 if (args == NULL || args->empty())
9099 {
9100 this->report_error(_("not enough arguments"));
9101 break;
9102 }
9103
9104 Type* slice_type = args->front()->type();
9105 if (!slice_type->is_slice_type())
9106 {
9107 if (slice_type->is_error_type())
9108 break;
9109 if (slice_type->is_nil_type())
9110 go_error_at(args->front()->location(), "use of untyped nil");
9111 else
9112 go_error_at(args->front()->location(),
9113 "argument 1 must be a slice");
9114 this->set_is_error();
9115 break;
9116 }
9117
9118 Type* element_type = slice_type->array_type()->element_type();
9119 if (!element_type->in_heap())
9120 go_error_at(args->front()->location(),
9121 "can't append to slice of go:notinheap type");
9122 if (this->is_varargs())
9123 {
9124 if (!args->back()->type()->is_slice_type()
9125 && !args->back()->type()->is_string_type())
9126 {
9127 go_error_at(args->back()->location(),
9128 "invalid use of %<...%> with non-slice/non-string");
9129 this->set_is_error();
9130 break;
9131 }
9132
9133 if (args->size() < 2)
9134 {
9135 this->report_error(_("not enough arguments"));
9136 break;
9137 }
9138 if (args->size() > 2)
9139 {
9140 this->report_error(_("too many arguments"));
9141 break;
9142 }
9143
9144 if (args->back()->type()->is_string_type()
9145 && element_type->integer_type() != NULL
9146 && element_type->integer_type()->is_byte())
9147 {
9148 // Permit append(s1, s2...) when s1 is a slice of
9149 // bytes and s2 is a string type.
9150 }
9151 else
9152 {
9153 // We have to test for assignment compatibility to a
9154 // slice of the element type, which is not necessarily
9155 // the same as the type of the first argument: the
9156 // first argument might have a named type.
9157 Type* check_type = Type::make_array_type(element_type, NULL);
9158 std::string reason;
9159 if (!Type::are_assignable(check_type, args->back()->type(),
9160 &reason))
9161 {
9162 if (reason.empty())
9163 go_error_at(args->back()->location(),
9164 "argument 2 has invalid type");
9165 else
9166 go_error_at(args->back()->location(),
9167 "argument 2 has invalid type (%s)",
9168 reason.c_str());
9169 this->set_is_error();
9170 break;
9171 }
9172 }
9173 }
9174 else
9175 {
9176 Expression_list::const_iterator pa = args->begin();
9177 int i = 2;
9178 for (++pa; pa != args->end(); ++pa, ++i)
9179 {
9180 std::string reason;
9181 if (!Type::are_assignable(element_type, (*pa)->type(),
9182 &reason))
9183 {
9184 if (reason.empty())
9185 go_error_at((*pa)->location(),
9186 "argument %d has incompatible type", i);
9187 else
9188 go_error_at((*pa)->location(),
9189 "argument %d has incompatible type (%s)",
9190 i, reason.c_str());
9191 this->set_is_error();
9192 }
9193 }
9194 }
9195 }
9196 break;
9197
9198 case BUILTIN_REAL:
9199 case BUILTIN_IMAG:
9200 if (this->check_one_arg())
9201 {
9202 if (this->one_arg()->type()->complex_type() == NULL)
9203 this->report_error(_("argument must have complex type"));
9204 }
9205 break;
9206
9207 case BUILTIN_COMPLEX:
9208 {
9209 const Expression_list* args = this->args();
9210 if (args == NULL || args->size() < 2)
9211 this->report_error(_("not enough arguments"));
9212 else if (args->size() > 2)
9213 this->report_error(_("too many arguments"));
9214 else if (args->front()->is_error_expression()
9215 || args->front()->type()->is_error()
9216 || args->back()->is_error_expression()
9217 || args->back()->type()->is_error())
9218 this->set_is_error();
9219 else if (!Type::are_identical(args->front()->type(),
9220 args->back()->type(),
9221 Type::COMPARE_TAGS, NULL))
9222 this->report_error(_("complex arguments must have identical types"));
9223 else if (args->front()->type()->float_type() == NULL)
9224 this->report_error(_("complex arguments must have "
9225 "floating-point type"));
9226 }
9227 break;
9228
9229 default:
9230 go_unreachable();
9231 }
9232 }
9233
9234 Expression*
do_copy()9235 Builtin_call_expression::do_copy()
9236 {
9237 Call_expression* bce =
9238 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
9239 (this->args() == NULL
9240 ? NULL
9241 : this->args()->copy()),
9242 this->is_varargs(),
9243 this->location());
9244
9245 if (this->varargs_are_lowered())
9246 bce->set_varargs_are_lowered();
9247 if (this->is_deferred())
9248 bce->set_is_deferred();
9249 if (this->is_concurrent())
9250 bce->set_is_concurrent();
9251 return bce;
9252 }
9253
9254 // Return the backend representation for a builtin function.
9255
9256 Bexpression*
do_get_backend(Translate_context * context)9257 Builtin_call_expression::do_get_backend(Translate_context* context)
9258 {
9259 Gogo* gogo = context->gogo();
9260 Location location = this->location();
9261
9262 if (this->is_erroneous_call())
9263 {
9264 go_assert(saw_errors());
9265 return gogo->backend()->error_expression();
9266 }
9267
9268 switch (this->code_)
9269 {
9270 case BUILTIN_INVALID:
9271 case BUILTIN_NEW:
9272 case BUILTIN_MAKE:
9273 go_unreachable();
9274
9275 case BUILTIN_LEN:
9276 case BUILTIN_CAP:
9277 {
9278 const Expression_list* args = this->args();
9279 go_assert(args != NULL && args->size() == 1);
9280 Expression* arg = args->front();
9281 Type* arg_type = arg->type();
9282
9283 if (this->seen_)
9284 {
9285 go_assert(saw_errors());
9286 return context->backend()->error_expression();
9287 }
9288 this->seen_ = true;
9289 this->seen_ = false;
9290 if (arg_type->points_to() != NULL)
9291 {
9292 arg_type = arg_type->points_to();
9293 go_assert(arg_type->array_type() != NULL
9294 && !arg_type->is_slice_type());
9295 arg = Expression::make_dereference(arg, NIL_CHECK_DEFAULT,
9296 location);
9297 }
9298
9299 Type* int_type = Type::lookup_integer_type("int");
9300 Expression* val;
9301 if (this->code_ == BUILTIN_LEN)
9302 {
9303 if (arg_type->is_string_type())
9304 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
9305 location);
9306 else if (arg_type->array_type() != NULL)
9307 {
9308 if (this->seen_)
9309 {
9310 go_assert(saw_errors());
9311 return context->backend()->error_expression();
9312 }
9313 this->seen_ = true;
9314 val = arg_type->array_type()->get_length(gogo, arg);
9315 this->seen_ = false;
9316 }
9317 else if (arg_type->map_type() != NULL
9318 || arg_type->channel_type() != NULL)
9319 {
9320 // The first field is the length. If the pointer is
9321 // nil, the length is zero.
9322 Type* pint_type = Type::make_pointer_type(int_type);
9323 arg = Expression::make_unsafe_cast(pint_type, arg, location);
9324 Expression* nil = Expression::make_nil(location);
9325 nil = Expression::make_cast(pint_type, nil, location);
9326 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
9327 arg, nil, location);
9328 Expression* zero = Expression::make_integer_ul(0, int_type,
9329 location);
9330 Expression* indir =
9331 Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED,
9332 location);
9333 val = Expression::make_conditional(cmp, zero, indir, location);
9334 }
9335 else
9336 go_unreachable();
9337 }
9338 else
9339 {
9340 if (arg_type->array_type() != NULL)
9341 {
9342 if (this->seen_)
9343 {
9344 go_assert(saw_errors());
9345 return context->backend()->error_expression();
9346 }
9347 this->seen_ = true;
9348 val = arg_type->array_type()->get_capacity(gogo, arg);
9349 this->seen_ = false;
9350 }
9351 else if (arg_type->channel_type() != NULL)
9352 {
9353 // The second field is the capacity. If the pointer
9354 // is nil, the capacity is zero.
9355 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9356 Type* pint_type = Type::make_pointer_type(int_type);
9357 Expression* parg = Expression::make_unsafe_cast(uintptr_type,
9358 arg,
9359 location);
9360 int off = int_type->integer_type()->bits() / 8;
9361 Expression* eoff = Expression::make_integer_ul(off,
9362 uintptr_type,
9363 location);
9364 parg = Expression::make_binary(OPERATOR_PLUS, parg, eoff,
9365 location);
9366 parg = Expression::make_unsafe_cast(pint_type, parg, location);
9367 Expression* nil = Expression::make_nil(location);
9368 nil = Expression::make_cast(pint_type, nil, location);
9369 Expression* cmp = Expression::make_binary(OPERATOR_EQEQ,
9370 arg, nil, location);
9371 Expression* zero = Expression::make_integer_ul(0, int_type,
9372 location);
9373 Expression* indir =
9374 Expression::make_dereference(parg, NIL_CHECK_NOT_NEEDED,
9375 location);
9376 val = Expression::make_conditional(cmp, zero, indir, location);
9377 }
9378 else
9379 go_unreachable();
9380 }
9381
9382 return Expression::make_cast(int_type, val,
9383 location)->get_backend(context);
9384 }
9385
9386 case BUILTIN_PRINT:
9387 case BUILTIN_PRINTLN:
9388 {
9389 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
9390
9391 Expression* print_stmts = Runtime::make_call(Runtime::PRINTLOCK,
9392 location, 0);
9393
9394 const Expression_list* call_args = this->args();
9395 if (call_args != NULL)
9396 {
9397 for (Expression_list::const_iterator p = call_args->begin();
9398 p != call_args->end();
9399 ++p)
9400 {
9401 if (is_ln && p != call_args->begin())
9402 {
9403 Expression* print_space =
9404 Runtime::make_call(Runtime::PRINTSP, location, 0);
9405
9406 print_stmts =
9407 Expression::make_compound(print_stmts, print_space,
9408 location);
9409 }
9410
9411 Expression* arg = *p;
9412 Type* type = arg->type();
9413 Runtime::Function code;
9414 if (type->is_string_type())
9415 code = Runtime::PRINTSTRING;
9416 else if (type->integer_type() != NULL
9417 && type->integer_type()->is_unsigned())
9418 {
9419 Type* itype = Type::lookup_integer_type("uint64");
9420 arg = Expression::make_cast(itype, arg, location);
9421 code = Runtime::PRINTUINT;
9422 }
9423 else if (type->integer_type() != NULL)
9424 {
9425 Type* itype = Type::lookup_integer_type("int64");
9426 arg = Expression::make_cast(itype, arg, location);
9427 code = Runtime::PRINTINT;
9428 }
9429 else if (type->float_type() != NULL)
9430 {
9431 Type* dtype = Type::lookup_float_type("float64");
9432 arg = Expression::make_cast(dtype, arg, location);
9433 code = Runtime::PRINTFLOAT;
9434 }
9435 else if (type->complex_type() != NULL)
9436 {
9437 Type* ctype = Type::lookup_complex_type("complex128");
9438 arg = Expression::make_cast(ctype, arg, location);
9439 code = Runtime::PRINTCOMPLEX;
9440 }
9441 else if (type->is_boolean_type())
9442 code = Runtime::PRINTBOOL;
9443 else if (type->points_to() != NULL
9444 || type->channel_type() != NULL
9445 || type->map_type() != NULL
9446 || type->function_type() != NULL)
9447 {
9448 arg = Expression::make_cast(type, arg, location);
9449 code = Runtime::PRINTPOINTER;
9450 }
9451 else if (type->interface_type() != NULL)
9452 {
9453 if (type->interface_type()->is_empty())
9454 code = Runtime::PRINTEFACE;
9455 else
9456 code = Runtime::PRINTIFACE;
9457 }
9458 else if (type->is_slice_type())
9459 code = Runtime::PRINTSLICE;
9460 else
9461 {
9462 go_assert(saw_errors());
9463 return context->backend()->error_expression();
9464 }
9465
9466 Expression* call = Runtime::make_call(code, location, 1, arg);
9467 print_stmts = Expression::make_compound(print_stmts, call,
9468 location);
9469 }
9470 }
9471
9472 if (is_ln)
9473 {
9474 Expression* print_nl =
9475 Runtime::make_call(Runtime::PRINTNL, location, 0);
9476 print_stmts = Expression::make_compound(print_stmts, print_nl,
9477 location);
9478 }
9479
9480 Expression* unlock = Runtime::make_call(Runtime::PRINTUNLOCK,
9481 location, 0);
9482 print_stmts = Expression::make_compound(print_stmts, unlock, location);
9483
9484 return print_stmts->get_backend(context);
9485 }
9486
9487 case BUILTIN_PANIC:
9488 {
9489 const Expression_list* args = this->args();
9490 go_assert(args != NULL && args->size() == 1);
9491 Expression* arg = args->front();
9492 Type *empty =
9493 Type::make_empty_interface_type(Linemap::predeclared_location());
9494 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
9495
9496 Expression* panic =
9497 Runtime::make_call(Runtime::GOPANIC, location, 1, arg);
9498 return panic->get_backend(context);
9499 }
9500
9501 case BUILTIN_RECOVER:
9502 {
9503 // The argument is set when building recover thunks. It's a
9504 // boolean value which is true if we can recover a value now.
9505 const Expression_list* args = this->args();
9506 go_assert(args != NULL && args->size() == 1);
9507 Expression* arg = args->front();
9508 Type *empty =
9509 Type::make_empty_interface_type(Linemap::predeclared_location());
9510
9511 Expression* nil = Expression::make_nil(location);
9512 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
9513
9514 // We need to handle a deferred call to recover specially,
9515 // because it changes whether it can recover a panic or not.
9516 // See test7 in test/recover1.go.
9517 Expression* recover = Runtime::make_call((this->is_deferred()
9518 ? Runtime::DEFERREDRECOVER
9519 : Runtime::GORECOVER),
9520 location, 0);
9521 Expression* cond =
9522 Expression::make_conditional(arg, recover, nil, location);
9523 return cond->get_backend(context);
9524 }
9525
9526 case BUILTIN_CLOSE:
9527 {
9528 const Expression_list* args = this->args();
9529 go_assert(args != NULL && args->size() == 1);
9530 Expression* arg = args->front();
9531 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
9532 1, arg);
9533 return close->get_backend(context);
9534 }
9535
9536 case BUILTIN_SIZEOF:
9537 case BUILTIN_OFFSETOF:
9538 case BUILTIN_ALIGNOF:
9539 {
9540 Numeric_constant nc;
9541 unsigned long val;
9542 if (!this->numeric_constant_value(&nc)
9543 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
9544 {
9545 go_assert(saw_errors());
9546 return context->backend()->error_expression();
9547 }
9548 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9549 mpz_t ival;
9550 nc.get_int(&ival);
9551 Expression* int_cst =
9552 Expression::make_integer_z(&ival, uintptr_type, location);
9553 mpz_clear(ival);
9554 return int_cst->get_backend(context);
9555 }
9556
9557 case BUILTIN_COPY:
9558 {
9559 const Expression_list* args = this->args();
9560 go_assert(args != NULL && args->size() == 2);
9561 Expression* arg1 = args->front();
9562 Expression* arg2 = args->back();
9563
9564 Type* arg1_type = arg1->type();
9565 Array_type* at = arg1_type->array_type();
9566 go_assert(arg1->is_variable());
9567
9568 Expression* call;
9569
9570 Type* arg2_type = arg2->type();
9571 go_assert(arg2->is_variable());
9572 if (arg2_type->is_string_type())
9573 call = Runtime::make_call(Runtime::SLICESTRINGCOPY, location,
9574 2, arg1, arg2);
9575 else
9576 {
9577 Type* et = at->element_type();
9578 if (et->has_pointer())
9579 {
9580 Expression* td = Expression::make_type_descriptor(et,
9581 location);
9582 call = Runtime::make_call(Runtime::TYPEDSLICECOPY, location,
9583 3, td, arg1, arg2);
9584 }
9585 else
9586 {
9587 Expression* sz = Expression::make_type_info(et,
9588 TYPE_INFO_SIZE);
9589 call = Runtime::make_call(Runtime::SLICECOPY, location, 3,
9590 arg1, arg2, sz);
9591 }
9592 }
9593
9594 return call->get_backend(context);
9595 }
9596
9597 case BUILTIN_APPEND:
9598 // Handled in Builtin_call_expression::flatten_append.
9599 go_unreachable();
9600
9601 case BUILTIN_REAL:
9602 case BUILTIN_IMAG:
9603 {
9604 const Expression_list* args = this->args();
9605 go_assert(args != NULL && args->size() == 1);
9606
9607 Bexpression* ret;
9608 Bexpression* bcomplex = args->front()->get_backend(context);
9609 if (this->code_ == BUILTIN_REAL)
9610 ret = gogo->backend()->real_part_expression(bcomplex, location);
9611 else
9612 ret = gogo->backend()->imag_part_expression(bcomplex, location);
9613 return ret;
9614 }
9615
9616 case BUILTIN_COMPLEX:
9617 {
9618 const Expression_list* args = this->args();
9619 go_assert(args != NULL && args->size() == 2);
9620 Bexpression* breal = args->front()->get_backend(context);
9621 Bexpression* bimag = args->back()->get_backend(context);
9622 return gogo->backend()->complex_expression(breal, bimag, location);
9623 }
9624
9625 default:
9626 go_unreachable();
9627 }
9628 }
9629
9630 // We have to support exporting a builtin call expression, because
9631 // code can set a constant to the result of a builtin expression.
9632
9633 void
do_export(Export_function_body * efb) const9634 Builtin_call_expression::do_export(Export_function_body* efb) const
9635 {
9636 Numeric_constant nc;
9637 if (!this->numeric_constant_value(&nc))
9638 {
9639 go_error_at(this->location(), "value is not constant");
9640 return;
9641 }
9642
9643 if (nc.is_int())
9644 {
9645 mpz_t val;
9646 nc.get_int(&val);
9647 Integer_expression::export_integer(efb, val);
9648 mpz_clear(val);
9649 }
9650 else if (nc.is_float())
9651 {
9652 mpfr_t fval;
9653 nc.get_float(&fval);
9654 Float_expression::export_float(efb, fval);
9655 mpfr_clear(fval);
9656 }
9657 else if (nc.is_complex())
9658 {
9659 mpc_t cval;
9660 nc.get_complex(&cval);
9661 Complex_expression::export_complex(efb, cval);
9662 mpc_clear(cval);
9663 }
9664 else
9665 go_unreachable();
9666
9667 // A trailing space lets us reliably identify the end of the number.
9668 efb->write_c_string(" ");
9669 }
9670
9671 // Class Call_expression.
9672
9673 // A Go function can be viewed in a couple of different ways. The
9674 // code of a Go function becomes a backend function with parameters
9675 // whose types are simply the backend representation of the Go types.
9676 // If there are multiple results, they are returned as a backend
9677 // struct.
9678
9679 // However, when Go code refers to a function other than simply
9680 // calling it, the backend type of that function is actually a struct.
9681 // The first field of the struct points to the Go function code
9682 // (sometimes a wrapper as described below). The remaining fields
9683 // hold addresses of closed-over variables. This struct is called a
9684 // closure.
9685
9686 // There are a few cases to consider.
9687
9688 // A direct function call of a known function in package scope. In
9689 // this case there are no closed-over variables, and we know the name
9690 // of the function code. We can simply produce a backend call to the
9691 // function directly, and not worry about the closure.
9692
9693 // A direct function call of a known function literal. In this case
9694 // we know the function code and we know the closure. We generate the
9695 // function code such that it expects an additional final argument of
9696 // the closure type. We pass the closure as the last argument, after
9697 // the other arguments.
9698
9699 // An indirect function call. In this case we have a closure. We
9700 // load the pointer to the function code from the first field of the
9701 // closure. We pass the address of the closure as the last argument.
9702
9703 // A call to a method of an interface. Type methods are always at
9704 // package scope, so we call the function directly, and don't worry
9705 // about the closure.
9706
9707 // This means that for a function at package scope we have two cases.
9708 // One is the direct call, which has no closure. The other is the
9709 // indirect call, which does have a closure. We can't simply ignore
9710 // the closure, even though it is the last argument, because that will
9711 // fail on targets where the function pops its arguments. So when
9712 // generating a closure for a package-scope function we set the
9713 // function code pointer in the closure to point to a wrapper
9714 // function. This wrapper function accepts a final argument that
9715 // points to the closure, ignores it, and calls the real function as a
9716 // direct function call. This wrapper will normally be efficient, and
9717 // can often simply be a tail call to the real function.
9718
9719 // We don't use GCC's static chain pointer because 1) we don't need
9720 // it; 2) GCC only permits using a static chain to call a known
9721 // function, so we can't use it for an indirect call anyhow. Since we
9722 // can't use it for an indirect call, we may as well not worry about
9723 // using it for a direct call either.
9724
9725 // We pass the closure last rather than first because it means that
9726 // the function wrapper we put into a closure for a package-scope
9727 // function can normally just be a tail call to the real function.
9728
9729 // For method expressions we generate a wrapper that loads the
9730 // receiver from the closure and then calls the method. This
9731 // unfortunately forces reshuffling the arguments, since there is a
9732 // new first argument, but we can't avoid reshuffling either for
9733 // method expressions or for indirect calls of package-scope
9734 // functions, and since the latter are more common we reshuffle for
9735 // method expressions.
9736
9737 // Note that the Go code retains the Go types. The extra final
9738 // argument only appears when we convert to the backend
9739 // representation.
9740
9741 // Traversal.
9742
9743 int
do_traverse(Traverse * traverse)9744 Call_expression::do_traverse(Traverse* traverse)
9745 {
9746 // If we are calling a function in a different package that returns
9747 // an unnamed type, this may be the only chance we get to traverse
9748 // that type. We don't traverse this->type_ because it may be a
9749 // Call_multiple_result_type that will just lead back here.
9750 if (this->type_ != NULL && !this->type_->is_error_type())
9751 {
9752 Function_type *fntype = this->get_function_type();
9753 if (fntype != NULL && Type::traverse(fntype, traverse) == TRAVERSE_EXIT)
9754 return TRAVERSE_EXIT;
9755 }
9756 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
9757 return TRAVERSE_EXIT;
9758 if (this->args_ != NULL)
9759 {
9760 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
9761 return TRAVERSE_EXIT;
9762 }
9763 return TRAVERSE_CONTINUE;
9764 }
9765
9766 // Lower a call statement.
9767
9768 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)9769 Call_expression::do_lower(Gogo* gogo, Named_object* function,
9770 Statement_inserter* inserter, int)
9771 {
9772 Location loc = this->location();
9773
9774 // A type cast can look like a function call.
9775 if (this->fn_->is_type_expression()
9776 && this->args_ != NULL
9777 && this->args_->size() == 1)
9778 return Expression::make_cast(this->fn_->type(), this->args_->front(),
9779 loc);
9780
9781 // Because do_type will return an error type and thus prevent future
9782 // errors, check for that case now to ensure that the error gets
9783 // reported.
9784 Function_type* fntype = this->get_function_type();
9785 if (fntype == NULL)
9786 {
9787 if (!this->fn_->type()->is_error())
9788 this->report_error(_("expected function"));
9789 this->set_is_error();
9790 return this;
9791 }
9792
9793 // Handle an argument which is a call to a function which returns
9794 // multiple results.
9795 if (this->args_ != NULL
9796 && this->args_->size() == 1
9797 && this->args_->front()->call_expression() != NULL)
9798 {
9799 size_t rc = this->args_->front()->call_expression()->result_count();
9800 if (rc > 1
9801 && ((fntype->parameters() != NULL
9802 && (fntype->parameters()->size() == rc
9803 || (fntype->is_varargs()
9804 && fntype->parameters()->size() - 1 <= rc)))
9805 || fntype->is_builtin()))
9806 {
9807 Call_expression* call = this->args_->front()->call_expression();
9808 call->set_is_multi_value_arg();
9809 if (this->is_varargs_)
9810 {
9811 // It is not clear which result of a multiple result call
9812 // the ellipsis operator should be applied to. If we unpack the
9813 // the call into its individual results here, the ellipsis will be
9814 // applied to the last result.
9815 go_error_at(call->location(),
9816 _("multiple-value argument in single-value context"));
9817 return Expression::make_error(call->location());
9818 }
9819
9820 Expression_list* args = new Expression_list;
9821 for (size_t i = 0; i < rc; ++i)
9822 args->push_back(Expression::make_call_result(call, i));
9823 // We can't return a new call expression here, because this
9824 // one may be referenced by Call_result expressions. We
9825 // also can't delete the old arguments, because we may still
9826 // traverse them somewhere up the call stack. FIXME.
9827 this->args_ = args;
9828 }
9829 }
9830
9831 // Recognize a call to a builtin function.
9832 if (fntype->is_builtin())
9833 {
9834 Builtin_call_expression* bce =
9835 new Builtin_call_expression(gogo, this->fn_, this->args_,
9836 this->is_varargs_, loc);
9837 if (this->is_deferred_)
9838 bce->set_is_deferred();
9839 if (this->is_concurrent_)
9840 bce->set_is_concurrent();
9841 return bce;
9842 }
9843
9844 // If this call returns multiple results, create a temporary
9845 // variable to hold them.
9846 if (this->result_count() > 1 && this->call_temp_ == NULL)
9847 {
9848 Struct_field_list* sfl = new Struct_field_list();
9849 Function_type* fntype = this->get_function_type();
9850 const Typed_identifier_list* results = fntype->results();
9851 Location loc = this->location();
9852
9853 int i = 0;
9854 char buf[20];
9855 for (Typed_identifier_list::const_iterator p = results->begin();
9856 p != results->end();
9857 ++p, ++i)
9858 {
9859 snprintf(buf, sizeof buf, "res%d", i);
9860 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
9861 }
9862
9863 Struct_type* st = Type::make_struct_type(sfl, loc);
9864 st->set_is_struct_incomparable();
9865 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
9866 inserter->insert(this->call_temp_);
9867 }
9868
9869 // Handle a call to a varargs function by packaging up the extra
9870 // parameters.
9871 if (fntype->is_varargs())
9872 {
9873 const Typed_identifier_list* parameters = fntype->parameters();
9874 go_assert(parameters != NULL && !parameters->empty());
9875 Type* varargs_type = parameters->back().type();
9876 this->lower_varargs(gogo, function, inserter, varargs_type,
9877 parameters->size(), SLICE_STORAGE_MAY_ESCAPE);
9878 }
9879
9880 // If this is call to a method, call the method directly passing the
9881 // object as the first parameter.
9882 Bound_method_expression* bme = this->fn_->bound_method_expression();
9883 if (bme != NULL)
9884 {
9885 Named_object* methodfn = bme->function();
9886 Expression* first_arg = bme->first_argument();
9887
9888 // We always pass a pointer when calling a method.
9889 if (first_arg->type()->points_to() == NULL
9890 && !first_arg->type()->is_error())
9891 {
9892 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
9893 // We may need to create a temporary variable so that we can
9894 // take the address. We can't do that here because it will
9895 // mess up the order of evaluation.
9896 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
9897 ue->set_create_temp();
9898 }
9899
9900 // If we are calling a method which was inherited from an
9901 // embedded struct, and the method did not get a stub, then the
9902 // first type may be wrong.
9903 Type* fatype = bme->first_argument_type();
9904 if (fatype != NULL)
9905 {
9906 if (fatype->points_to() == NULL)
9907 fatype = Type::make_pointer_type(fatype);
9908 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
9909 }
9910
9911 Expression_list* new_args = new Expression_list();
9912 new_args->push_back(first_arg);
9913 if (this->args_ != NULL)
9914 {
9915 for (Expression_list::const_iterator p = this->args_->begin();
9916 p != this->args_->end();
9917 ++p)
9918 new_args->push_back(*p);
9919 }
9920
9921 // We have to change in place because this structure may be
9922 // referenced by Call_result_expressions. We can't delete the
9923 // old arguments, because we may be traversing them up in some
9924 // caller. FIXME.
9925 this->args_ = new_args;
9926 this->fn_ = Expression::make_func_reference(methodfn, NULL,
9927 bme->location());
9928 }
9929
9930 // Handle a couple of special runtime functions. In the runtime
9931 // package, getcallerpc returns the PC of the caller, and
9932 // getcallersp returns the frame pointer of the caller. Implement
9933 // these by turning them into calls to GCC builtin functions. We
9934 // could implement them in normal code, but then we would have to
9935 // explicitly unwind the stack. These functions are intended to be
9936 // efficient. Note that this technique obviously only works for
9937 // direct calls, but that is the only way they are used.
9938 if (gogo->compiling_runtime() && gogo->package_name() == "runtime")
9939 {
9940 Func_expression* fe = this->fn_->func_expression();
9941 if (fe != NULL
9942 && fe->named_object()->is_function_declaration()
9943 && fe->named_object()->package() == NULL)
9944 {
9945 std::string n = Gogo::unpack_hidden_name(fe->named_object()->name());
9946 if ((this->args_ == NULL || this->args_->size() == 0)
9947 && n == "getcallerpc")
9948 {
9949 static Named_object* builtin_return_address;
9950 int arg = 0;
9951 return this->lower_to_builtin(&builtin_return_address,
9952 "__builtin_return_address",
9953 &arg);
9954 }
9955 else if ((this->args_ == NULL || this->args_->size() == 0)
9956 && n == "getcallersp")
9957 {
9958 static Named_object* builtin_dwarf_cfa;
9959 return this->lower_to_builtin(&builtin_dwarf_cfa,
9960 "__builtin_dwarf_cfa",
9961 NULL);
9962 }
9963 }
9964 }
9965
9966 // If this is a call to an imported function for which we have an
9967 // inlinable function body, add it to the list of functions to give
9968 // to the backend as inlining opportunities.
9969 Func_expression* fe = this->fn_->func_expression();
9970 if (fe != NULL
9971 && fe->named_object()->is_function_declaration()
9972 && fe->named_object()->func_declaration_value()->has_imported_body())
9973 gogo->add_imported_inlinable_function(fe->named_object());
9974
9975 return this;
9976 }
9977
9978 // Lower a call to a varargs function. FUNCTION is the function in
9979 // which the call occurs--it's not the function we are calling.
9980 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
9981 // PARAM_COUNT is the number of parameters of the function we are
9982 // calling; the last of these parameters will be the varargs
9983 // parameter.
9984
9985 void
lower_varargs(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * varargs_type,size_t param_count,Slice_storage_escape_disp escape_disp)9986 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
9987 Statement_inserter* inserter,
9988 Type* varargs_type, size_t param_count,
9989 Slice_storage_escape_disp escape_disp)
9990 {
9991 if (this->varargs_are_lowered_)
9992 return;
9993
9994 Location loc = this->location();
9995
9996 go_assert(param_count > 0);
9997 go_assert(varargs_type->is_slice_type());
9998
9999 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
10000 if (arg_count < param_count - 1)
10001 {
10002 // Not enough arguments; will be caught in check_types.
10003 return;
10004 }
10005
10006 Expression_list* old_args = this->args_;
10007 Expression_list* new_args = new Expression_list();
10008 bool push_empty_arg = false;
10009 if (old_args == NULL || old_args->empty())
10010 {
10011 go_assert(param_count == 1);
10012 push_empty_arg = true;
10013 }
10014 else
10015 {
10016 Expression_list::const_iterator pa;
10017 int i = 1;
10018 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
10019 {
10020 if (static_cast<size_t>(i) == param_count)
10021 break;
10022 new_args->push_back(*pa);
10023 }
10024
10025 // We have reached the varargs parameter.
10026
10027 bool issued_error = false;
10028 if (pa == old_args->end())
10029 push_empty_arg = true;
10030 else if (pa + 1 == old_args->end() && this->is_varargs_)
10031 new_args->push_back(*pa);
10032 else if (this->is_varargs_)
10033 {
10034 if ((*pa)->type()->is_slice_type())
10035 this->report_error(_("too many arguments"));
10036 else
10037 {
10038 go_error_at(this->location(),
10039 _("invalid use of %<...%> with non-slice"));
10040 this->set_is_error();
10041 }
10042 return;
10043 }
10044 else
10045 {
10046 Type* element_type = varargs_type->array_type()->element_type();
10047 Expression_list* vals = new Expression_list;
10048 for (; pa != old_args->end(); ++pa, ++i)
10049 {
10050 // Check types here so that we get a better message.
10051 Type* patype = (*pa)->type();
10052 Location paloc = (*pa)->location();
10053 if (!this->check_argument_type(i, element_type, patype,
10054 paloc, issued_error))
10055 continue;
10056 vals->push_back(*pa);
10057 }
10058 Slice_construction_expression* sce =
10059 Expression::make_slice_composite_literal(varargs_type, vals, loc);
10060 if (escape_disp == SLICE_STORAGE_DOES_NOT_ESCAPE)
10061 sce->set_storage_does_not_escape();
10062 Expression* val = sce;
10063 gogo->lower_expression(function, inserter, &val);
10064 new_args->push_back(val);
10065 }
10066 }
10067
10068 if (push_empty_arg)
10069 new_args->push_back(Expression::make_nil(loc));
10070
10071 // We can't return a new call expression here, because this one may
10072 // be referenced by Call_result expressions. FIXME. We can't
10073 // delete OLD_ARGS because we may have both a Call_expression and a
10074 // Builtin_call_expression which refer to them. FIXME.
10075 this->args_ = new_args;
10076 this->varargs_are_lowered_ = true;
10077 }
10078
10079 // Return a call to __builtin_return_address or __builtin_dwarf_cfa.
10080
10081 Expression*
lower_to_builtin(Named_object ** pno,const char * name,int * arg)10082 Call_expression::lower_to_builtin(Named_object** pno, const char* name,
10083 int* arg)
10084 {
10085 if (*pno == NULL)
10086 *pno = Gogo::declare_builtin_rf_address(name, arg != NULL);
10087
10088 Location loc = this->location();
10089
10090 Expression* fn = Expression::make_func_reference(*pno, NULL, loc);
10091 Expression_list *args = new Expression_list();
10092 if (arg != NULL)
10093 {
10094 Expression* a = Expression::make_integer_ul(*arg, NULL, loc);
10095 args->push_back(a);
10096 }
10097 Expression* call = Expression::make_call(fn, args, false, loc);
10098
10099 // The builtin functions return void*, but the Go functions return uintptr.
10100 Type* uintptr_type = Type::lookup_integer_type("uintptr");
10101 return Expression::make_cast(uintptr_type, call, loc);
10102 }
10103
10104 // Flatten a call with multiple results into a temporary.
10105
10106 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)10107 Call_expression::do_flatten(Gogo* gogo, Named_object*,
10108 Statement_inserter* inserter)
10109 {
10110 if (this->is_erroneous_call())
10111 {
10112 go_assert(saw_errors());
10113 return Expression::make_error(this->location());
10114 }
10115
10116 if (this->is_flattened_)
10117 return this;
10118 this->is_flattened_ = true;
10119
10120 // Add temporary variables for all arguments that require type
10121 // conversion.
10122 Function_type* fntype = this->get_function_type();
10123 if (fntype == NULL)
10124 {
10125 go_assert(saw_errors());
10126 return this;
10127 }
10128 if (this->args_ != NULL && !this->args_->empty()
10129 && fntype->parameters() != NULL && !fntype->parameters()->empty())
10130 {
10131 bool is_interface_method =
10132 this->fn_->interface_field_reference_expression() != NULL;
10133
10134 Expression_list *args = new Expression_list();
10135 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
10136 Expression_list::const_iterator pa = this->args_->begin();
10137 if (!is_interface_method && fntype->is_method())
10138 {
10139 // The receiver argument.
10140 args->push_back(*pa);
10141 ++pa;
10142 }
10143 for (; pa != this->args_->end(); ++pa, ++pp)
10144 {
10145 go_assert(pp != fntype->parameters()->end());
10146 if (Type::are_identical(pp->type(), (*pa)->type(),
10147 Type::COMPARE_TAGS, NULL))
10148 args->push_back(*pa);
10149 else
10150 {
10151 Location loc = (*pa)->location();
10152 Expression* arg = *pa;
10153 if (!arg->is_variable())
10154 {
10155 Temporary_statement *temp =
10156 Statement::make_temporary(NULL, arg, loc);
10157 inserter->insert(temp);
10158 arg = Expression::make_temporary_reference(temp, loc);
10159 }
10160 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
10161 loc);
10162 args->push_back(arg);
10163 }
10164 }
10165 delete this->args_;
10166 this->args_ = args;
10167 }
10168
10169 return this;
10170 }
10171
10172 // Get the function type. This can return NULL in error cases.
10173
10174 Function_type*
get_function_type() const10175 Call_expression::get_function_type() const
10176 {
10177 return this->fn_->type()->function_type();
10178 }
10179
10180 // Return the number of values which this call will return.
10181
10182 size_t
result_count() const10183 Call_expression::result_count() const
10184 {
10185 const Function_type* fntype = this->get_function_type();
10186 if (fntype == NULL)
10187 return 0;
10188 if (fntype->results() == NULL)
10189 return 0;
10190 return fntype->results()->size();
10191 }
10192
10193 // Return the temporary that holds the result for a call with multiple
10194 // results.
10195
10196 Temporary_statement*
results() const10197 Call_expression::results() const
10198 {
10199 if (this->call_temp_ == NULL)
10200 {
10201 go_assert(saw_errors());
10202 return NULL;
10203 }
10204 return this->call_temp_;
10205 }
10206
10207 // Set the number of results expected from a call expression.
10208
10209 void
set_expected_result_count(size_t count)10210 Call_expression::set_expected_result_count(size_t count)
10211 {
10212 go_assert(this->expected_result_count_ == 0);
10213 this->expected_result_count_ = count;
10214 }
10215
10216 // Return whether this is a call to the predeclared function recover.
10217
10218 bool
is_recover_call() const10219 Call_expression::is_recover_call() const
10220 {
10221 return this->do_is_recover_call();
10222 }
10223
10224 // Set the argument to the recover function.
10225
10226 void
set_recover_arg(Expression * arg)10227 Call_expression::set_recover_arg(Expression* arg)
10228 {
10229 this->do_set_recover_arg(arg);
10230 }
10231
10232 // Virtual functions also implemented by Builtin_call_expression.
10233
10234 bool
do_is_recover_call() const10235 Call_expression::do_is_recover_call() const
10236 {
10237 return false;
10238 }
10239
10240 void
do_set_recover_arg(Expression *)10241 Call_expression::do_set_recover_arg(Expression*)
10242 {
10243 go_unreachable();
10244 }
10245
10246 // We have found an error with this call expression; return true if
10247 // we should report it.
10248
10249 bool
issue_error()10250 Call_expression::issue_error()
10251 {
10252 if (this->issued_error_)
10253 return false;
10254 else
10255 {
10256 this->issued_error_ = true;
10257 return true;
10258 }
10259 }
10260
10261 // Whether or not this call contains errors, either in the call or the
10262 // arguments to the call.
10263
10264 bool
is_erroneous_call()10265 Call_expression::is_erroneous_call()
10266 {
10267 if (this->is_error_expression() || this->fn()->is_error_expression())
10268 return true;
10269
10270 if (this->args() == NULL)
10271 return false;
10272 for (Expression_list::iterator pa = this->args()->begin();
10273 pa != this->args()->end();
10274 ++pa)
10275 {
10276 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
10277 return true;
10278 }
10279 return false;
10280 }
10281
10282 // Get the type.
10283
10284 Type*
do_type()10285 Call_expression::do_type()
10286 {
10287 if (this->type_ != NULL)
10288 return this->type_;
10289
10290 Type* ret;
10291 Function_type* fntype = this->get_function_type();
10292 if (fntype == NULL)
10293 return Type::make_error_type();
10294
10295 const Typed_identifier_list* results = fntype->results();
10296 if (results == NULL)
10297 ret = Type::make_void_type();
10298 else if (results->size() == 1)
10299 ret = results->begin()->type();
10300 else
10301 ret = Type::make_call_multiple_result_type(this);
10302
10303 this->type_ = ret;
10304
10305 return this->type_;
10306 }
10307
10308 // Determine types for a call expression. We can use the function
10309 // parameter types to set the types of the arguments.
10310
10311 void
do_determine_type(const Type_context *)10312 Call_expression::do_determine_type(const Type_context*)
10313 {
10314 if (!this->determining_types())
10315 return;
10316
10317 this->fn_->determine_type_no_context();
10318 Function_type* fntype = this->get_function_type();
10319 const Typed_identifier_list* parameters = NULL;
10320 if (fntype != NULL)
10321 parameters = fntype->parameters();
10322 if (this->args_ != NULL)
10323 {
10324 Typed_identifier_list::const_iterator pt;
10325 if (parameters != NULL)
10326 pt = parameters->begin();
10327 bool first = true;
10328 for (Expression_list::const_iterator pa = this->args_->begin();
10329 pa != this->args_->end();
10330 ++pa)
10331 {
10332 if (first)
10333 {
10334 first = false;
10335 // If this is a method, the first argument is the
10336 // receiver.
10337 if (fntype != NULL && fntype->is_method())
10338 {
10339 Type* rtype = fntype->receiver()->type();
10340 // The receiver is always passed as a pointer.
10341 if (rtype->points_to() == NULL)
10342 rtype = Type::make_pointer_type(rtype);
10343 Type_context subcontext(rtype, false);
10344 (*pa)->determine_type(&subcontext);
10345 continue;
10346 }
10347 }
10348
10349 if (parameters != NULL && pt != parameters->end())
10350 {
10351 Type_context subcontext(pt->type(), false);
10352 (*pa)->determine_type(&subcontext);
10353 ++pt;
10354 }
10355 else
10356 (*pa)->determine_type_no_context();
10357 }
10358 }
10359 }
10360
10361 // Called when determining types for a Call_expression. Return true
10362 // if we should go ahead, false if they have already been determined.
10363
10364 bool
determining_types()10365 Call_expression::determining_types()
10366 {
10367 if (this->types_are_determined_)
10368 return false;
10369 else
10370 {
10371 this->types_are_determined_ = true;
10372 return true;
10373 }
10374 }
10375
10376 // Check types for parameter I.
10377
10378 bool
check_argument_type(int i,const Type * parameter_type,const Type * argument_type,Location argument_location,bool issued_error)10379 Call_expression::check_argument_type(int i, const Type* parameter_type,
10380 const Type* argument_type,
10381 Location argument_location,
10382 bool issued_error)
10383 {
10384 std::string reason;
10385 if (!Type::are_assignable(parameter_type, argument_type, &reason))
10386 {
10387 if (!issued_error)
10388 {
10389 if (reason.empty())
10390 go_error_at(argument_location, "argument %d has incompatible type", i);
10391 else
10392 go_error_at(argument_location,
10393 "argument %d has incompatible type (%s)",
10394 i, reason.c_str());
10395 }
10396 this->set_is_error();
10397 return false;
10398 }
10399 return true;
10400 }
10401
10402 // Check types.
10403
10404 void
do_check_types(Gogo *)10405 Call_expression::do_check_types(Gogo*)
10406 {
10407 if (this->classification() == EXPRESSION_ERROR)
10408 return;
10409
10410 Function_type* fntype = this->get_function_type();
10411 if (fntype == NULL)
10412 {
10413 if (!this->fn_->type()->is_error())
10414 this->report_error(_("expected function"));
10415 return;
10416 }
10417
10418 if (this->expected_result_count_ != 0
10419 && this->expected_result_count_ != this->result_count())
10420 {
10421 if (this->issue_error())
10422 this->report_error(_("function result count mismatch"));
10423 this->set_is_error();
10424 return;
10425 }
10426
10427 bool is_method = fntype->is_method();
10428 if (is_method)
10429 {
10430 go_assert(this->args_ != NULL && !this->args_->empty());
10431 Type* rtype = fntype->receiver()->type();
10432 Expression* first_arg = this->args_->front();
10433 // We dereference the values since receivers are always passed
10434 // as pointers.
10435 std::string reason;
10436 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
10437 &reason))
10438 {
10439 if (reason.empty())
10440 this->report_error(_("incompatible type for receiver"));
10441 else
10442 {
10443 go_error_at(this->location(),
10444 "incompatible type for receiver (%s)",
10445 reason.c_str());
10446 this->set_is_error();
10447 }
10448 }
10449 }
10450
10451 // Note that varargs was handled by the lower_varargs() method, so
10452 // we don't have to worry about it here unless something is wrong.
10453 if (this->is_varargs_ && !this->varargs_are_lowered_)
10454 {
10455 if (!fntype->is_varargs())
10456 {
10457 go_error_at(this->location(),
10458 _("invalid use of %<...%> calling non-variadic function"));
10459 this->set_is_error();
10460 return;
10461 }
10462 }
10463
10464 const Typed_identifier_list* parameters = fntype->parameters();
10465 if (this->args_ == NULL || this->args_->size() == 0)
10466 {
10467 if (parameters != NULL && !parameters->empty())
10468 this->report_error(_("not enough arguments"));
10469 }
10470 else if (parameters == NULL)
10471 {
10472 if (!is_method || this->args_->size() > 1)
10473 this->report_error(_("too many arguments"));
10474 }
10475 else if (this->args_->size() == 1
10476 && this->args_->front()->call_expression() != NULL
10477 && this->args_->front()->call_expression()->result_count() > 1)
10478 {
10479 // This is F(G()) when G returns more than one result. If the
10480 // results can be matched to parameters, it would have been
10481 // lowered in do_lower. If we get here we know there is a
10482 // mismatch.
10483 if (this->args_->front()->call_expression()->result_count()
10484 < parameters->size())
10485 this->report_error(_("not enough arguments"));
10486 else
10487 this->report_error(_("too many arguments"));
10488 }
10489 else
10490 {
10491 int i = 0;
10492 Expression_list::const_iterator pa = this->args_->begin();
10493 if (is_method)
10494 ++pa;
10495 for (Typed_identifier_list::const_iterator pt = parameters->begin();
10496 pt != parameters->end();
10497 ++pt, ++pa, ++i)
10498 {
10499 if (pa == this->args_->end())
10500 {
10501 this->report_error(_("not enough arguments"));
10502 return;
10503 }
10504 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
10505 (*pa)->location(), false);
10506 }
10507 if (pa != this->args_->end())
10508 this->report_error(_("too many arguments"));
10509 }
10510 }
10511
10512 Expression*
do_copy()10513 Call_expression::do_copy()
10514 {
10515 Call_expression* call =
10516 Expression::make_call(this->fn_->copy(),
10517 (this->args_ == NULL
10518 ? NULL
10519 : this->args_->copy()),
10520 this->is_varargs_, this->location());
10521
10522 if (this->varargs_are_lowered_)
10523 call->set_varargs_are_lowered();
10524 if (this->is_deferred_)
10525 call->set_is_deferred();
10526 if (this->is_concurrent_)
10527 call->set_is_concurrent();
10528 return call;
10529 }
10530
10531 // Return whether we have to use a temporary variable to ensure that
10532 // we evaluate this call expression in order. If the call returns no
10533 // results then it will inevitably be executed last.
10534
10535 bool
do_must_eval_in_order() const10536 Call_expression::do_must_eval_in_order() const
10537 {
10538 return this->result_count() > 0;
10539 }
10540
10541 // Get the function and the first argument to use when calling an
10542 // interface method.
10543
10544 Expression*
interface_method_function(Interface_field_reference_expression * interface_method,Expression ** first_arg_ptr,Location location)10545 Call_expression::interface_method_function(
10546 Interface_field_reference_expression* interface_method,
10547 Expression** first_arg_ptr,
10548 Location location)
10549 {
10550 Expression* object = interface_method->get_underlying_object();
10551 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
10552 *first_arg_ptr =
10553 Expression::make_unsafe_cast(unsafe_ptr_type, object, location);
10554 return interface_method->get_function();
10555 }
10556
10557 // Build the call expression.
10558
10559 Bexpression*
do_get_backend(Translate_context * context)10560 Call_expression::do_get_backend(Translate_context* context)
10561 {
10562 Location location = this->location();
10563
10564 if (this->call_ != NULL)
10565 {
10566 // If the call returns multiple results, make a new reference to
10567 // the temporary.
10568 if (this->call_temp_ != NULL)
10569 {
10570 Expression* ref =
10571 Expression::make_temporary_reference(this->call_temp_, location);
10572 return ref->get_backend(context);
10573 }
10574
10575 return this->call_;
10576 }
10577
10578 Function_type* fntype = this->get_function_type();
10579 if (fntype == NULL)
10580 return context->backend()->error_expression();
10581
10582 if (this->fn_->is_error_expression())
10583 return context->backend()->error_expression();
10584
10585 Gogo* gogo = context->gogo();
10586
10587 Func_expression* func = this->fn_->func_expression();
10588 Interface_field_reference_expression* interface_method =
10589 this->fn_->interface_field_reference_expression();
10590 const bool has_closure = func != NULL && func->closure() != NULL;
10591 const bool is_interface_method = interface_method != NULL;
10592
10593 bool has_closure_arg;
10594 if (has_closure)
10595 has_closure_arg = true;
10596 else if (func != NULL)
10597 has_closure_arg = false;
10598 else if (is_interface_method)
10599 has_closure_arg = false;
10600 else
10601 has_closure_arg = true;
10602
10603 int nargs;
10604 std::vector<Bexpression*> fn_args;
10605 if (this->args_ == NULL || this->args_->empty())
10606 {
10607 nargs = is_interface_method ? 1 : 0;
10608 if (nargs > 0)
10609 fn_args.resize(1);
10610 }
10611 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
10612 {
10613 // Passing a receiver parameter.
10614 go_assert(!is_interface_method
10615 && fntype->is_method()
10616 && this->args_->size() == 1);
10617 nargs = 1;
10618 fn_args.resize(1);
10619 fn_args[0] = this->args_->front()->get_backend(context);
10620 }
10621 else
10622 {
10623 const Typed_identifier_list* params = fntype->parameters();
10624
10625 nargs = this->args_->size();
10626 int i = is_interface_method ? 1 : 0;
10627 nargs += i;
10628 fn_args.resize(nargs);
10629
10630 Typed_identifier_list::const_iterator pp = params->begin();
10631 Expression_list::const_iterator pe = this->args_->begin();
10632 if (!is_interface_method && fntype->is_method())
10633 {
10634 fn_args[i] = (*pe)->get_backend(context);
10635 ++pe;
10636 ++i;
10637 }
10638 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
10639 {
10640 go_assert(pp != params->end());
10641 Expression* arg =
10642 Expression::convert_for_assignment(gogo, pp->type(), *pe,
10643 location);
10644 fn_args[i] = arg->get_backend(context);
10645 }
10646 go_assert(pp == params->end());
10647 go_assert(i == nargs);
10648 }
10649
10650 Expression* fn;
10651 Expression* closure = NULL;
10652 if (func != NULL)
10653 {
10654 Named_object* no = func->named_object();
10655 fn = Expression::make_func_code_reference(no, location);
10656 if (has_closure)
10657 closure = func->closure();
10658 }
10659 else if (!is_interface_method)
10660 {
10661 closure = this->fn_;
10662
10663 // The backend representation of this function type is a pointer
10664 // to a struct whose first field is the actual function to call.
10665 Type* pfntype =
10666 Type::make_pointer_type(
10667 Type::make_pointer_type(Type::make_void_type()));
10668 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
10669 fn = Expression::make_dereference(fn, NIL_CHECK_NOT_NEEDED, location);
10670 }
10671 else
10672 {
10673 Expression* first_arg;
10674 fn = this->interface_method_function(interface_method, &first_arg,
10675 location);
10676 fn_args[0] = first_arg->get_backend(context);
10677 }
10678
10679 Bexpression* bclosure = NULL;
10680 if (has_closure_arg)
10681 bclosure = closure->get_backend(context);
10682 else
10683 go_assert(closure == NULL);
10684
10685 Bexpression* bfn = fn->get_backend(context);
10686
10687 // When not calling a named function directly, use a type conversion
10688 // in case the type of the function is a recursive type which refers
10689 // to itself. We don't do this for an interface method because 1)
10690 // an interface method never refers to itself, so we always have a
10691 // function type here; 2) we pass an extra first argument to an
10692 // interface method, so fntype is not correct.
10693 if (func == NULL && !is_interface_method)
10694 {
10695 Btype* bft = fntype->get_backend_fntype(gogo);
10696 bfn = gogo->backend()->convert_expression(bft, bfn, location);
10697 }
10698
10699 Bfunction* bfunction = NULL;
10700 if (context->function())
10701 bfunction = context->function()->func_value()->get_decl();
10702 Bexpression* call = gogo->backend()->call_expression(bfunction, bfn,
10703 fn_args, bclosure,
10704 location);
10705
10706 if (this->call_temp_ != NULL)
10707 {
10708 // This case occurs when the call returns multiple results.
10709
10710 Expression* ref = Expression::make_temporary_reference(this->call_temp_,
10711 location);
10712 Bexpression* bref = ref->get_backend(context);
10713 Bstatement* bassn = gogo->backend()->assignment_statement(bfunction,
10714 bref, call,
10715 location);
10716
10717 ref = Expression::make_temporary_reference(this->call_temp_, location);
10718 this->call_ = ref->get_backend(context);
10719
10720 return gogo->backend()->compound_expression(bassn, this->call_,
10721 location);
10722 }
10723
10724 this->call_ = call;
10725 return this->call_;
10726 }
10727
10728 // Dump ast representation for a call expressin.
10729
10730 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10731 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
10732 {
10733 this->fn_->dump_expression(ast_dump_context);
10734 ast_dump_context->ostream() << "(";
10735 if (args_ != NULL)
10736 ast_dump_context->dump_expression_list(this->args_);
10737
10738 ast_dump_context->ostream() << ") ";
10739 }
10740
10741 // Make a call expression.
10742
10743 Call_expression*
make_call(Expression * fn,Expression_list * args,bool is_varargs,Location location)10744 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
10745 Location location)
10746 {
10747 return new Call_expression(fn, args, is_varargs, location);
10748 }
10749
10750 // Class Call_result_expression.
10751
10752 // Traverse a call result.
10753
10754 int
do_traverse(Traverse * traverse)10755 Call_result_expression::do_traverse(Traverse* traverse)
10756 {
10757 if (traverse->remember_expression(this->call_))
10758 {
10759 // We have already traversed the call expression.
10760 return TRAVERSE_CONTINUE;
10761 }
10762 return Expression::traverse(&this->call_, traverse);
10763 }
10764
10765 // Get the type.
10766
10767 Type*
do_type()10768 Call_result_expression::do_type()
10769 {
10770 if (this->classification() == EXPRESSION_ERROR)
10771 return Type::make_error_type();
10772
10773 // THIS->CALL_ can be replaced with a temporary reference due to
10774 // Call_expression::do_must_eval_in_order when there is an error.
10775 Call_expression* ce = this->call_->call_expression();
10776 if (ce == NULL)
10777 {
10778 this->set_is_error();
10779 return Type::make_error_type();
10780 }
10781 Function_type* fntype = ce->get_function_type();
10782 if (fntype == NULL)
10783 {
10784 if (ce->issue_error())
10785 {
10786 if (!ce->fn()->type()->is_error())
10787 this->report_error(_("expected function"));
10788 }
10789 this->set_is_error();
10790 return Type::make_error_type();
10791 }
10792 const Typed_identifier_list* results = fntype->results();
10793 if (results == NULL || results->size() < 2)
10794 {
10795 if (ce->issue_error())
10796 this->report_error(_("number of results does not match "
10797 "number of values"));
10798 return Type::make_error_type();
10799 }
10800 Typed_identifier_list::const_iterator pr = results->begin();
10801 for (unsigned int i = 0; i < this->index_; ++i)
10802 {
10803 if (pr == results->end())
10804 break;
10805 ++pr;
10806 }
10807 if (pr == results->end())
10808 {
10809 if (ce->issue_error())
10810 this->report_error(_("number of results does not match "
10811 "number of values"));
10812 return Type::make_error_type();
10813 }
10814 return pr->type();
10815 }
10816
10817 // Check the type. Just make sure that we trigger the warning in
10818 // do_type.
10819
10820 void
do_check_types(Gogo *)10821 Call_result_expression::do_check_types(Gogo*)
10822 {
10823 this->type();
10824 }
10825
10826 // Determine the type. We have nothing to do here, but the 0 result
10827 // needs to pass down to the caller.
10828
10829 void
do_determine_type(const Type_context *)10830 Call_result_expression::do_determine_type(const Type_context*)
10831 {
10832 this->call_->determine_type_no_context();
10833 }
10834
10835 // Return the backend representation. We just refer to the temporary set by the
10836 // call expression. We don't do this at lowering time because it makes it
10837 // hard to evaluate the call at the right time.
10838
10839 Bexpression*
do_get_backend(Translate_context * context)10840 Call_result_expression::do_get_backend(Translate_context* context)
10841 {
10842 Call_expression* ce = this->call_->call_expression();
10843 if (ce == NULL)
10844 {
10845 go_assert(this->call_->is_error_expression());
10846 return context->backend()->error_expression();
10847 }
10848 Temporary_statement* ts = ce->results();
10849 if (ts == NULL)
10850 {
10851 go_assert(saw_errors());
10852 return context->backend()->error_expression();
10853 }
10854 Expression* ref = Expression::make_temporary_reference(ts, this->location());
10855 ref = Expression::make_field_reference(ref, this->index_, this->location());
10856 return ref->get_backend(context);
10857 }
10858
10859 // Dump ast representation for a call result expression.
10860
10861 void
do_dump_expression(Ast_dump_context * ast_dump_context) const10862 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10863 const
10864 {
10865 // FIXME: Wouldn't it be better if the call is assigned to a temporary
10866 // (struct) and the fields are referenced instead.
10867 ast_dump_context->ostream() << this->index_ << "@(";
10868 ast_dump_context->dump_expression(this->call_);
10869 ast_dump_context->ostream() << ")";
10870 }
10871
10872 // Make a reference to a single result of a call which returns
10873 // multiple results.
10874
10875 Expression*
make_call_result(Call_expression * call,unsigned int index)10876 Expression::make_call_result(Call_expression* call, unsigned int index)
10877 {
10878 return new Call_result_expression(call, index);
10879 }
10880
10881 // Class Index_expression.
10882
10883 // Traversal.
10884
10885 int
do_traverse(Traverse * traverse)10886 Index_expression::do_traverse(Traverse* traverse)
10887 {
10888 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
10889 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
10890 || (this->end_ != NULL
10891 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10892 || (this->cap_ != NULL
10893 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
10894 return TRAVERSE_EXIT;
10895 return TRAVERSE_CONTINUE;
10896 }
10897
10898 // Lower an index expression. This converts the generic index
10899 // expression into an array index, a string index, or a map index.
10900
10901 Expression*
do_lower(Gogo *,Named_object *,Statement_inserter *,int)10902 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
10903 {
10904 Location location = this->location();
10905 Expression* left = this->left_;
10906 Expression* start = this->start_;
10907 Expression* end = this->end_;
10908 Expression* cap = this->cap_;
10909
10910 Type* type = left->type();
10911 if (type->is_error())
10912 {
10913 go_assert(saw_errors());
10914 return Expression::make_error(location);
10915 }
10916 else if (left->is_type_expression())
10917 {
10918 go_error_at(location, "attempt to index type expression");
10919 return Expression::make_error(location);
10920 }
10921 else if (type->array_type() != NULL)
10922 return Expression::make_array_index(left, start, end, cap, location);
10923 else if (type->points_to() != NULL
10924 && type->points_to()->array_type() != NULL
10925 && !type->points_to()->is_slice_type())
10926 {
10927 Expression* deref =
10928 Expression::make_dereference(left, NIL_CHECK_DEFAULT, location);
10929
10930 // For an ordinary index into the array, the pointer will be
10931 // dereferenced. For a slice it will not--the resulting slice
10932 // will simply reuse the pointer, which is incorrect if that
10933 // pointer is nil.
10934 if (end != NULL || cap != NULL)
10935 deref->issue_nil_check();
10936
10937 return Expression::make_array_index(deref, start, end, cap, location);
10938 }
10939 else if (type->is_string_type())
10940 {
10941 if (cap != NULL)
10942 {
10943 go_error_at(location, "invalid 3-index slice of string");
10944 return Expression::make_error(location);
10945 }
10946 return Expression::make_string_index(left, start, end, location);
10947 }
10948 else if (type->map_type() != NULL)
10949 {
10950 if (end != NULL || cap != NULL)
10951 {
10952 go_error_at(location, "invalid slice of map");
10953 return Expression::make_error(location);
10954 }
10955 return Expression::make_map_index(left, start, location);
10956 }
10957 else if (cap != NULL)
10958 {
10959 go_error_at(location,
10960 "invalid 3-index slice of object that is not a slice");
10961 return Expression::make_error(location);
10962 }
10963 else if (end != NULL)
10964 {
10965 go_error_at(location,
10966 ("attempt to slice object that is not "
10967 "array, slice, or string"));
10968 return Expression::make_error(location);
10969 }
10970 else
10971 {
10972 go_error_at(location,
10973 ("attempt to index object that is not "
10974 "array, slice, string, or map"));
10975 return Expression::make_error(location);
10976 }
10977 }
10978
10979 // Write an indexed expression
10980 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
10981
10982 void
dump_index_expression(Ast_dump_context * ast_dump_context,const Expression * expr,const Expression * start,const Expression * end,const Expression * cap)10983 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
10984 const Expression* expr,
10985 const Expression* start,
10986 const Expression* end,
10987 const Expression* cap)
10988 {
10989 expr->dump_expression(ast_dump_context);
10990 ast_dump_context->ostream() << "[";
10991 start->dump_expression(ast_dump_context);
10992 if (end != NULL)
10993 {
10994 ast_dump_context->ostream() << ":";
10995 end->dump_expression(ast_dump_context);
10996 }
10997 if (cap != NULL)
10998 {
10999 ast_dump_context->ostream() << ":";
11000 cap->dump_expression(ast_dump_context);
11001 }
11002 ast_dump_context->ostream() << "]";
11003 }
11004
11005 // Dump ast representation for an index expression.
11006
11007 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11008 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11009 const
11010 {
11011 Index_expression::dump_index_expression(ast_dump_context, this->left_,
11012 this->start_, this->end_, this->cap_);
11013 }
11014
11015 // Make an index expression.
11016
11017 Expression*
make_index(Expression * left,Expression * start,Expression * end,Expression * cap,Location location)11018 Expression::make_index(Expression* left, Expression* start, Expression* end,
11019 Expression* cap, Location location)
11020 {
11021 return new Index_expression(left, start, end, cap, location);
11022 }
11023
11024 // Class Array_index_expression.
11025
11026 // Array index traversal.
11027
11028 int
do_traverse(Traverse * traverse)11029 Array_index_expression::do_traverse(Traverse* traverse)
11030 {
11031 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
11032 return TRAVERSE_EXIT;
11033 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11034 return TRAVERSE_EXIT;
11035 if (this->end_ != NULL)
11036 {
11037 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11038 return TRAVERSE_EXIT;
11039 }
11040 if (this->cap_ != NULL)
11041 {
11042 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
11043 return TRAVERSE_EXIT;
11044 }
11045 return TRAVERSE_CONTINUE;
11046 }
11047
11048 // Return the type of an array index.
11049
11050 Type*
do_type()11051 Array_index_expression::do_type()
11052 {
11053 if (this->type_ == NULL)
11054 {
11055 Array_type* type = this->array_->type()->array_type();
11056 if (type == NULL)
11057 this->type_ = Type::make_error_type();
11058 else if (this->end_ == NULL)
11059 this->type_ = type->element_type();
11060 else if (type->is_slice_type())
11061 {
11062 // A slice of a slice has the same type as the original
11063 // slice.
11064 this->type_ = this->array_->type()->deref();
11065 }
11066 else
11067 {
11068 // A slice of an array is a slice.
11069 this->type_ = Type::make_array_type(type->element_type(), NULL);
11070 }
11071 }
11072 return this->type_;
11073 }
11074
11075 // Set the type of an array index.
11076
11077 void
do_determine_type(const Type_context *)11078 Array_index_expression::do_determine_type(const Type_context*)
11079 {
11080 this->array_->determine_type_no_context();
11081
11082 Type_context index_context(Type::lookup_integer_type("int"), false);
11083 if (this->start_->is_constant())
11084 this->start_->determine_type(&index_context);
11085 else
11086 this->start_->determine_type_no_context();
11087 if (this->end_ != NULL)
11088 {
11089 if (this->end_->is_constant())
11090 this->end_->determine_type(&index_context);
11091 else
11092 this->end_->determine_type_no_context();
11093 }
11094 if (this->cap_ != NULL)
11095 {
11096 if (this->cap_->is_constant())
11097 this->cap_->determine_type(&index_context);
11098 else
11099 this->cap_->determine_type_no_context();
11100 }
11101 }
11102
11103 // Check types of an array index.
11104
11105 void
do_check_types(Gogo *)11106 Array_index_expression::do_check_types(Gogo*)
11107 {
11108 Numeric_constant nc;
11109 unsigned long v;
11110 if (this->start_->type()->integer_type() == NULL
11111 && !this->start_->type()->is_error()
11112 && (!this->start_->numeric_constant_value(&nc)
11113 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11114 this->report_error(_("index must be integer"));
11115 if (this->end_ != NULL
11116 && this->end_->type()->integer_type() == NULL
11117 && !this->end_->type()->is_error()
11118 && !this->end_->is_nil_expression()
11119 && !this->end_->is_error_expression()
11120 && (!this->end_->numeric_constant_value(&nc)
11121 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11122 this->report_error(_("slice end must be integer"));
11123 if (this->cap_ != NULL
11124 && this->cap_->type()->integer_type() == NULL
11125 && !this->cap_->type()->is_error()
11126 && !this->cap_->is_nil_expression()
11127 && !this->cap_->is_error_expression()
11128 && (!this->cap_->numeric_constant_value(&nc)
11129 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11130 this->report_error(_("slice capacity must be integer"));
11131
11132 Array_type* array_type = this->array_->type()->array_type();
11133 if (array_type == NULL)
11134 {
11135 go_assert(this->array_->type()->is_error());
11136 return;
11137 }
11138
11139 unsigned int int_bits =
11140 Type::lookup_integer_type("int")->integer_type()->bits();
11141
11142 Numeric_constant lvalnc;
11143 mpz_t lval;
11144 bool lval_valid = (array_type->length() != NULL
11145 && array_type->length()->numeric_constant_value(&lvalnc)
11146 && lvalnc.to_int(&lval));
11147 Numeric_constant inc;
11148 mpz_t ival;
11149 bool ival_valid = false;
11150 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11151 {
11152 ival_valid = true;
11153 if (mpz_sgn(ival) < 0
11154 || mpz_sizeinbase(ival, 2) >= int_bits
11155 || (lval_valid
11156 && (this->end_ == NULL
11157 ? mpz_cmp(ival, lval) >= 0
11158 : mpz_cmp(ival, lval) > 0)))
11159 {
11160 go_error_at(this->start_->location(), "array index out of bounds");
11161 this->set_is_error();
11162 }
11163 }
11164 if (this->end_ != NULL && !this->end_->is_nil_expression())
11165 {
11166 Numeric_constant enc;
11167 mpz_t eval;
11168 bool eval_valid = false;
11169 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11170 {
11171 eval_valid = true;
11172 if (mpz_sgn(eval) < 0
11173 || mpz_sizeinbase(eval, 2) >= int_bits
11174 || (lval_valid && mpz_cmp(eval, lval) > 0))
11175 {
11176 go_error_at(this->end_->location(), "array index out of bounds");
11177 this->set_is_error();
11178 }
11179 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11180 this->report_error(_("inverted slice range"));
11181 }
11182
11183 Numeric_constant cnc;
11184 mpz_t cval;
11185 if (this->cap_ != NULL
11186 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
11187 {
11188 if (mpz_sgn(cval) < 0
11189 || mpz_sizeinbase(cval, 2) >= int_bits
11190 || (lval_valid && mpz_cmp(cval, lval) > 0))
11191 {
11192 go_error_at(this->cap_->location(), "array index out of bounds");
11193 this->set_is_error();
11194 }
11195 else if (ival_valid && mpz_cmp(ival, cval) > 0)
11196 {
11197 go_error_at(this->cap_->location(),
11198 "invalid slice index: capacity less than start");
11199 this->set_is_error();
11200 }
11201 else if (eval_valid && mpz_cmp(eval, cval) > 0)
11202 {
11203 go_error_at(this->cap_->location(),
11204 "invalid slice index: capacity less than length");
11205 this->set_is_error();
11206 }
11207 mpz_clear(cval);
11208 }
11209
11210 if (eval_valid)
11211 mpz_clear(eval);
11212 }
11213 if (ival_valid)
11214 mpz_clear(ival);
11215 if (lval_valid)
11216 mpz_clear(lval);
11217
11218 // A slice of an array requires an addressable array. A slice of a
11219 // slice is always possible.
11220 if (this->end_ != NULL && !array_type->is_slice_type())
11221 {
11222 if (!this->array_->is_addressable())
11223 this->report_error(_("slice of unaddressable value"));
11224 else
11225 // Set the array address taken but not escape. The escape
11226 // analysis will make it escape to heap when needed.
11227 this->array_->address_taken(false);
11228 }
11229 }
11230
11231 // The subexpressions of an array index must be evaluated in order.
11232 // If this is indexing into an array, rather than a slice, then only
11233 // the index should be evaluated. Since this is called for values on
11234 // the left hand side of an assigment, evaluating the array, meaning
11235 // copying the array, will cause a different array to be modified.
11236
11237 bool
do_must_eval_subexpressions_in_order(int * skip) const11238 Array_index_expression::do_must_eval_subexpressions_in_order(
11239 int* skip) const
11240 {
11241 *skip = this->array_->type()->is_slice_type() ? 0 : 1;
11242 return true;
11243 }
11244
11245 // Flatten array indexing by using temporary variables for slices and indexes.
11246
11247 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)11248 Array_index_expression::do_flatten(Gogo*, Named_object*,
11249 Statement_inserter* inserter)
11250 {
11251 Location loc = this->location();
11252 Expression* array = this->array_;
11253 Expression* start = this->start_;
11254 Expression* end = this->end_;
11255 Expression* cap = this->cap_;
11256 if (array->is_error_expression()
11257 || array->type()->is_error_type()
11258 || start->is_error_expression()
11259 || start->type()->is_error_type()
11260 || (end != NULL
11261 && (end->is_error_expression() || end->type()->is_error_type()))
11262 || (cap != NULL
11263 && (cap->is_error_expression() || cap->type()->is_error_type())))
11264 {
11265 go_assert(saw_errors());
11266 return Expression::make_error(loc);
11267 }
11268
11269 Temporary_statement* temp;
11270 if (array->type()->is_slice_type() && !array->is_variable())
11271 {
11272 temp = Statement::make_temporary(NULL, array, loc);
11273 inserter->insert(temp);
11274 this->array_ = Expression::make_temporary_reference(temp, loc);
11275 }
11276 if (!start->is_variable())
11277 {
11278 temp = Statement::make_temporary(NULL, start, loc);
11279 inserter->insert(temp);
11280 this->start_ = Expression::make_temporary_reference(temp, loc);
11281 }
11282 if (end != NULL
11283 && !end->is_nil_expression()
11284 && !end->is_variable())
11285 {
11286 temp = Statement::make_temporary(NULL, end, loc);
11287 inserter->insert(temp);
11288 this->end_ = Expression::make_temporary_reference(temp, loc);
11289 }
11290 if (cap != NULL && !cap->is_variable())
11291 {
11292 temp = Statement::make_temporary(NULL, cap, loc);
11293 inserter->insert(temp);
11294 this->cap_ = Expression::make_temporary_reference(temp, loc);
11295 }
11296
11297 return this;
11298 }
11299
11300 // Return whether this expression is addressable.
11301
11302 bool
do_is_addressable() const11303 Array_index_expression::do_is_addressable() const
11304 {
11305 // A slice expression is not addressable.
11306 if (this->end_ != NULL)
11307 return false;
11308
11309 // An index into a slice is addressable.
11310 if (this->array_->type()->is_slice_type())
11311 return true;
11312
11313 // An index into an array is addressable if the array is
11314 // addressable.
11315 return this->array_->is_addressable();
11316 }
11317
11318 void
do_address_taken(bool escapes)11319 Array_index_expression::do_address_taken(bool escapes)
11320 {
11321 // In &x[0], if x is a slice, then x's address is not taken.
11322 if (!this->array_->type()->is_slice_type())
11323 this->array_->address_taken(escapes);
11324 }
11325
11326 // Get the backend representation for an array index.
11327
11328 Bexpression*
do_get_backend(Translate_context * context)11329 Array_index_expression::do_get_backend(Translate_context* context)
11330 {
11331 Array_type* array_type = this->array_->type()->array_type();
11332 if (array_type == NULL)
11333 {
11334 go_assert(this->array_->type()->is_error());
11335 return context->backend()->error_expression();
11336 }
11337 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
11338
11339 Location loc = this->location();
11340 Gogo* gogo = context->gogo();
11341
11342 Type* int_type = Type::lookup_integer_type("int");
11343 Btype* int_btype = int_type->get_backend(gogo);
11344
11345 // We need to convert the length and capacity to the Go "int" type here
11346 // because the length of a fixed-length array could be of type "uintptr"
11347 // and gimple disallows binary operations between "uintptr" and other
11348 // integer types. FIXME.
11349 Bexpression* length = NULL;
11350 if (this->end_ == NULL || this->end_->is_nil_expression())
11351 {
11352 Expression* len = array_type->get_length(gogo, this->array_);
11353 length = len->get_backend(context);
11354 length = gogo->backend()->convert_expression(int_btype, length, loc);
11355 }
11356
11357 Bexpression* capacity = NULL;
11358 if (this->end_ != NULL)
11359 {
11360 Expression* cap = array_type->get_capacity(gogo, this->array_);
11361 capacity = cap->get_backend(context);
11362 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
11363 }
11364
11365 Bexpression* cap_arg = capacity;
11366 if (this->cap_ != NULL)
11367 {
11368 cap_arg = this->cap_->get_backend(context);
11369 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11370 }
11371
11372 if (length == NULL)
11373 length = cap_arg;
11374
11375 if (this->start_->type()->integer_type() == NULL
11376 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11377 {
11378 go_assert(saw_errors());
11379 return context->backend()->error_expression();
11380 }
11381
11382 Bexpression* start = this->start_->get_backend(context);
11383 start = gogo->backend()->convert_expression(int_btype, start, loc);
11384
11385 Bexpression* crash = NULL;
11386 Bexpression* bad_index = NULL;
11387 if (this->needs_bounds_check_)
11388 {
11389 int code = (array_type->length() != NULL
11390 ? (this->end_ == NULL
11391 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
11392 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
11393 : (this->end_ == NULL
11394 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
11395 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
11396 crash = gogo->runtime_error(code, loc)->get_backend(context);
11397 bad_index = Expression::check_bounds(this->start_, loc)->get_backend(context);
11398 Bexpression* start_too_large =
11399 gogo->backend()->binary_expression((this->end_ == NULL
11400 ? OPERATOR_GE
11401 : OPERATOR_GT),
11402 start,
11403 (this->end_ == NULL
11404 ? length
11405 : capacity),
11406 loc);
11407 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR,
11408 start_too_large,
11409 bad_index, loc);
11410 }
11411
11412
11413 Bfunction* bfn = context->function()->func_value()->get_decl();
11414 if (this->end_ == NULL)
11415 {
11416 // Simple array indexing. This has to return an l-value, so
11417 // wrap the index check into START.
11418 if (this->needs_bounds_check_)
11419 start =
11420 gogo->backend()->conditional_expression(bfn, int_btype, bad_index,
11421 crash, start, loc);
11422
11423 Bexpression* ret;
11424 if (array_type->length() != NULL)
11425 {
11426 Bexpression* array = this->array_->get_backend(context);
11427 ret = gogo->backend()->array_index_expression(array, start, loc);
11428 }
11429 else
11430 {
11431 // Slice.
11432 Expression* valptr =
11433 array_type->get_value_pointer(gogo, this->array_,
11434 this->is_lvalue_);
11435 Bexpression* ptr = valptr->get_backend(context);
11436 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
11437
11438 Type* ele_type = this->array_->type()->array_type()->element_type();
11439 Btype* ele_btype = ele_type->get_backend(gogo);
11440 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
11441 }
11442 return ret;
11443 }
11444
11445 // Array slice.
11446
11447 if (this->cap_ != NULL)
11448 {
11449 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
11450
11451 if (this->needs_bounds_check_)
11452 {
11453 Bexpression* bounds_bcheck =
11454 Expression::check_bounds(this->cap_, loc)->get_backend(context);
11455 bad_index =
11456 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11457 bad_index, loc);
11458
11459 Bexpression* cap_too_small =
11460 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
11461 Bexpression* cap_too_large =
11462 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
11463 Bexpression* bad_cap =
11464 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
11465 cap_too_large, loc);
11466 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
11467 bad_index, loc);
11468 }
11469 }
11470
11471 Bexpression* end;
11472 if (this->end_->is_nil_expression())
11473 end = length;
11474 else
11475 {
11476 end = this->end_->get_backend(context);
11477 end = gogo->backend()->convert_expression(int_btype, end, loc);
11478 if (this->needs_bounds_check_)
11479 {
11480 Bexpression* bounds_bcheck =
11481 Expression::check_bounds(this->end_, loc)->get_backend(context);
11482 bad_index =
11483 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
11484 bad_index, loc);
11485
11486 Bexpression* end_too_small =
11487 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
11488 Bexpression* end_too_large =
11489 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
11490 Bexpression* bad_end =
11491 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
11492 end_too_large, loc);
11493 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
11494 bad_index, loc);
11495 }
11496 }
11497
11498 Bexpression* result_length =
11499 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
11500
11501 Bexpression* result_capacity =
11502 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
11503
11504 // If the new capacity is zero, don't change val. Otherwise we can
11505 // get a pointer to the next object in memory, keeping it live
11506 // unnecessarily. When the capacity is zero, the actual pointer
11507 // value doesn't matter.
11508 Bexpression* zero =
11509 Expression::make_integer_ul(0, int_type, loc)->get_backend(context);
11510 Bexpression* cond =
11511 gogo->backend()->binary_expression(OPERATOR_EQEQ, result_capacity, zero,
11512 loc);
11513 Bexpression* offset = gogo->backend()->conditional_expression(bfn, int_btype,
11514 cond, zero,
11515 start, loc);
11516 Expression* valptr = array_type->get_value_pointer(gogo, this->array_,
11517 this->is_lvalue_);
11518 Bexpression* val = valptr->get_backend(context);
11519 val = gogo->backend()->pointer_offset_expression(val, offset, loc);
11520
11521 Btype* struct_btype = this->type()->get_backend(gogo);
11522 std::vector<Bexpression*> init;
11523 init.push_back(val);
11524 init.push_back(result_length);
11525 init.push_back(result_capacity);
11526
11527 Bexpression* ret =
11528 gogo->backend()->constructor_expression(struct_btype, init, loc);
11529 if (this->needs_bounds_check_)
11530 ret = gogo->backend()->conditional_expression(bfn, struct_btype, bad_index,
11531 crash, ret, loc);
11532 return ret;
11533 }
11534
11535 // Dump ast representation for an array index expression.
11536
11537 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11538 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11539 const
11540 {
11541 Index_expression::dump_index_expression(ast_dump_context, this->array_,
11542 this->start_, this->end_, this->cap_);
11543 }
11544
11545 // Make an array index expression. END and CAP may be NULL.
11546
11547 Expression*
make_array_index(Expression * array,Expression * start,Expression * end,Expression * cap,Location location)11548 Expression::make_array_index(Expression* array, Expression* start,
11549 Expression* end, Expression* cap,
11550 Location location)
11551 {
11552 return new Array_index_expression(array, start, end, cap, location);
11553 }
11554
11555 // Class String_index_expression.
11556
11557 // String index traversal.
11558
11559 int
do_traverse(Traverse * traverse)11560 String_index_expression::do_traverse(Traverse* traverse)
11561 {
11562 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
11563 return TRAVERSE_EXIT;
11564 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
11565 return TRAVERSE_EXIT;
11566 if (this->end_ != NULL)
11567 {
11568 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
11569 return TRAVERSE_EXIT;
11570 }
11571 return TRAVERSE_CONTINUE;
11572 }
11573
11574 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)11575 String_index_expression::do_flatten(Gogo*, Named_object*,
11576 Statement_inserter* inserter)
11577 {
11578 Location loc = this->location();
11579 Expression* string = this->string_;
11580 Expression* start = this->start_;
11581 Expression* end = this->end_;
11582 if (string->is_error_expression()
11583 || string->type()->is_error_type()
11584 || start->is_error_expression()
11585 || start->type()->is_error_type()
11586 || (end != NULL
11587 && (end->is_error_expression() || end->type()->is_error_type())))
11588 {
11589 go_assert(saw_errors());
11590 return Expression::make_error(loc);
11591 }
11592
11593 Temporary_statement* temp;
11594 if (!this->string_->is_variable())
11595 {
11596 temp = Statement::make_temporary(NULL, this->string_, loc);
11597 inserter->insert(temp);
11598 this->string_ = Expression::make_temporary_reference(temp, loc);
11599 }
11600 if (!this->start_->is_variable())
11601 {
11602 temp = Statement::make_temporary(NULL, this->start_, loc);
11603 inserter->insert(temp);
11604 this->start_ = Expression::make_temporary_reference(temp, loc);
11605 }
11606 if (this->end_ != NULL
11607 && !this->end_->is_nil_expression()
11608 && !this->end_->is_variable())
11609 {
11610 temp = Statement::make_temporary(NULL, this->end_, loc);
11611 inserter->insert(temp);
11612 this->end_ = Expression::make_temporary_reference(temp, loc);
11613 }
11614
11615 return this;
11616 }
11617
11618 // Return the type of a string index.
11619
11620 Type*
do_type()11621 String_index_expression::do_type()
11622 {
11623 if (this->end_ == NULL)
11624 return Type::lookup_integer_type("uint8");
11625 else
11626 return this->string_->type();
11627 }
11628
11629 // Determine the type of a string index.
11630
11631 void
do_determine_type(const Type_context *)11632 String_index_expression::do_determine_type(const Type_context*)
11633 {
11634 this->string_->determine_type_no_context();
11635
11636 Type_context index_context(Type::lookup_integer_type("int"), false);
11637 if (this->start_->is_constant())
11638 this->start_->determine_type(&index_context);
11639 else
11640 this->start_->determine_type_no_context();
11641 if (this->end_ != NULL)
11642 {
11643 if (this->end_->is_constant())
11644 this->end_->determine_type(&index_context);
11645 else
11646 this->end_->determine_type_no_context();
11647 }
11648 }
11649
11650 // Check types of a string index.
11651
11652 void
do_check_types(Gogo *)11653 String_index_expression::do_check_types(Gogo*)
11654 {
11655 Numeric_constant nc;
11656 unsigned long v;
11657 if (this->start_->type()->integer_type() == NULL
11658 && !this->start_->type()->is_error()
11659 && (!this->start_->numeric_constant_value(&nc)
11660 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11661 this->report_error(_("index must be integer"));
11662 if (this->end_ != NULL
11663 && this->end_->type()->integer_type() == NULL
11664 && !this->end_->type()->is_error()
11665 && !this->end_->is_nil_expression()
11666 && !this->end_->is_error_expression()
11667 && (!this->end_->numeric_constant_value(&nc)
11668 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
11669 this->report_error(_("slice end must be integer"));
11670
11671 std::string sval;
11672 bool sval_valid = this->string_->string_constant_value(&sval);
11673
11674 Numeric_constant inc;
11675 mpz_t ival;
11676 bool ival_valid = false;
11677 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
11678 {
11679 ival_valid = true;
11680 if (mpz_sgn(ival) < 0
11681 || (sval_valid
11682 && (this->end_ == NULL
11683 ? mpz_cmp_ui(ival, sval.length()) >= 0
11684 : mpz_cmp_ui(ival, sval.length()) > 0)))
11685 {
11686 go_error_at(this->start_->location(), "string index out of bounds");
11687 this->set_is_error();
11688 }
11689 }
11690 if (this->end_ != NULL && !this->end_->is_nil_expression())
11691 {
11692 Numeric_constant enc;
11693 mpz_t eval;
11694 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
11695 {
11696 if (mpz_sgn(eval) < 0
11697 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
11698 {
11699 go_error_at(this->end_->location(), "string index out of bounds");
11700 this->set_is_error();
11701 }
11702 else if (ival_valid && mpz_cmp(ival, eval) > 0)
11703 this->report_error(_("inverted slice range"));
11704 mpz_clear(eval);
11705 }
11706 }
11707 if (ival_valid)
11708 mpz_clear(ival);
11709 }
11710
11711 // Get the backend representation for a string index.
11712
11713 Bexpression*
do_get_backend(Translate_context * context)11714 String_index_expression::do_get_backend(Translate_context* context)
11715 {
11716 Location loc = this->location();
11717 Expression* string_arg = this->string_;
11718 if (this->string_->type()->points_to() != NULL)
11719 string_arg = Expression::make_dereference(this->string_,
11720 NIL_CHECK_NOT_NEEDED, loc);
11721
11722 Expression* bad_index = Expression::check_bounds(this->start_, loc);
11723
11724 int code = (this->end_ == NULL
11725 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
11726 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
11727
11728 Gogo* gogo = context->gogo();
11729 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
11730
11731 Type* int_type = Type::lookup_integer_type("int");
11732
11733 // It is possible that an error occurred earlier because the start index
11734 // cannot be represented as an integer type. In this case, we shouldn't
11735 // try casting the starting index into an integer since
11736 // Type_conversion_expression will fail to get the backend representation.
11737 // FIXME.
11738 if (this->start_->type()->integer_type() == NULL
11739 && !Type::are_convertible(int_type, this->start_->type(), NULL))
11740 {
11741 go_assert(saw_errors());
11742 return context->backend()->error_expression();
11743 }
11744
11745 Expression* start = Expression::make_cast(int_type, this->start_, loc);
11746 Bfunction* bfn = context->function()->func_value()->get_decl();
11747
11748 if (this->end_ == NULL)
11749 {
11750 Expression* length =
11751 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
11752
11753 Expression* start_too_large =
11754 Expression::make_binary(OPERATOR_GE, start, length, loc);
11755 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
11756 bad_index, loc);
11757 Expression* bytes =
11758 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
11759
11760 Bexpression* bstart = start->get_backend(context);
11761 Bexpression* ptr = bytes->get_backend(context);
11762 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
11763 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
11764 Bexpression* index =
11765 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
11766
11767 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
11768 Bexpression* index_error = bad_index->get_backend(context);
11769 return gogo->backend()->conditional_expression(bfn, byte_btype,
11770 index_error, crash,
11771 index, loc);
11772 }
11773
11774 Expression* end = NULL;
11775 if (this->end_->is_nil_expression())
11776 end = Expression::make_integer_sl(-1, int_type, loc);
11777 else
11778 {
11779 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
11780 bad_index =
11781 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
11782 end = Expression::make_cast(int_type, this->end_, loc);
11783 }
11784
11785 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
11786 string_arg, start, end);
11787 Bexpression* bstrslice = strslice->get_backend(context);
11788
11789 Btype* str_btype = strslice->type()->get_backend(gogo);
11790 Bexpression* index_error = bad_index->get_backend(context);
11791 return gogo->backend()->conditional_expression(bfn, str_btype, index_error,
11792 crash, bstrslice, loc);
11793 }
11794
11795 // Dump ast representation for a string index expression.
11796
11797 void
do_dump_expression(Ast_dump_context * ast_dump_context) const11798 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11799 const
11800 {
11801 Index_expression::dump_index_expression(ast_dump_context, this->string_,
11802 this->start_, this->end_, NULL);
11803 }
11804
11805 // Make a string index expression. END may be NULL.
11806
11807 Expression*
make_string_index(Expression * string,Expression * start,Expression * end,Location location)11808 Expression::make_string_index(Expression* string, Expression* start,
11809 Expression* end, Location location)
11810 {
11811 return new String_index_expression(string, start, end, location);
11812 }
11813
11814 // Class Map_index.
11815
11816 // Get the type of the map.
11817
11818 Map_type*
get_map_type() const11819 Map_index_expression::get_map_type() const
11820 {
11821 Map_type* mt = this->map_->type()->map_type();
11822 if (mt == NULL)
11823 go_assert(saw_errors());
11824 return mt;
11825 }
11826
11827 // Map index traversal.
11828
11829 int
do_traverse(Traverse * traverse)11830 Map_index_expression::do_traverse(Traverse* traverse)
11831 {
11832 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
11833 return TRAVERSE_EXIT;
11834 return Expression::traverse(&this->index_, traverse);
11835 }
11836
11837 // We need to pass in a pointer to the key, so flatten the index into a
11838 // temporary variable if it isn't already. The value pointer will be
11839 // dereferenced and checked for nil, so flatten into a temporary to avoid
11840 // recomputation.
11841
11842 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)11843 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
11844 Statement_inserter* inserter)
11845 {
11846 Location loc = this->location();
11847 Map_type* mt = this->get_map_type();
11848 if (this->index()->is_error_expression()
11849 || this->index()->type()->is_error_type()
11850 || mt->is_error_type())
11851 {
11852 go_assert(saw_errors());
11853 return Expression::make_error(loc);
11854 }
11855
11856 if (!Type::are_identical(mt->key_type(), this->index_->type(),
11857 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
11858 NULL))
11859 {
11860 if (this->index_->type()->interface_type() != NULL
11861 && !this->index_->is_variable())
11862 {
11863 Temporary_statement* temp =
11864 Statement::make_temporary(NULL, this->index_, loc);
11865 inserter->insert(temp);
11866 this->index_ = Expression::make_temporary_reference(temp, loc);
11867 }
11868 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
11869 this->index_, loc);
11870 }
11871
11872 if (!this->index_->is_variable())
11873 {
11874 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
11875 loc);
11876 inserter->insert(temp);
11877 this->index_ = Expression::make_temporary_reference(temp, loc);
11878 }
11879
11880 if (this->value_pointer_ == NULL)
11881 this->get_value_pointer(gogo);
11882 if (this->value_pointer_->is_error_expression()
11883 || this->value_pointer_->type()->is_error_type())
11884 return Expression::make_error(loc);
11885 if (!this->value_pointer_->is_variable())
11886 {
11887 Temporary_statement* temp =
11888 Statement::make_temporary(NULL, this->value_pointer_, loc);
11889 inserter->insert(temp);
11890 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
11891 }
11892
11893 return this;
11894 }
11895
11896 // Return the type of a map index.
11897
11898 Type*
do_type()11899 Map_index_expression::do_type()
11900 {
11901 Map_type* mt = this->get_map_type();
11902 if (mt == NULL)
11903 return Type::make_error_type();
11904 return mt->val_type();
11905 }
11906
11907 // Fix the type of a map index.
11908
11909 void
do_determine_type(const Type_context *)11910 Map_index_expression::do_determine_type(const Type_context*)
11911 {
11912 this->map_->determine_type_no_context();
11913 Map_type* mt = this->get_map_type();
11914 Type* key_type = mt == NULL ? NULL : mt->key_type();
11915 Type_context subcontext(key_type, false);
11916 this->index_->determine_type(&subcontext);
11917 }
11918
11919 // Check types of a map index.
11920
11921 void
do_check_types(Gogo *)11922 Map_index_expression::do_check_types(Gogo*)
11923 {
11924 std::string reason;
11925 Map_type* mt = this->get_map_type();
11926 if (mt == NULL)
11927 return;
11928 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
11929 {
11930 if (reason.empty())
11931 this->report_error(_("incompatible type for map index"));
11932 else
11933 {
11934 go_error_at(this->location(), "incompatible type for map index (%s)",
11935 reason.c_str());
11936 this->set_is_error();
11937 }
11938 }
11939 }
11940
11941 // Get the backend representation for a map index.
11942
11943 Bexpression*
do_get_backend(Translate_context * context)11944 Map_index_expression::do_get_backend(Translate_context* context)
11945 {
11946 Map_type* type = this->get_map_type();
11947 if (type == NULL)
11948 {
11949 go_assert(saw_errors());
11950 return context->backend()->error_expression();
11951 }
11952
11953 go_assert(this->value_pointer_ != NULL
11954 && this->value_pointer_->is_variable());
11955
11956 Expression* val = Expression::make_dereference(this->value_pointer_,
11957 NIL_CHECK_NOT_NEEDED,
11958 this->location());
11959 return val->get_backend(context);
11960 }
11961
11962 // Get an expression for the map index. This returns an expression
11963 // that evaluates to a pointer to a value. If the key is not in the
11964 // map, the pointer will point to a zero value.
11965
11966 Expression*
get_value_pointer(Gogo * gogo)11967 Map_index_expression::get_value_pointer(Gogo* gogo)
11968 {
11969 if (this->value_pointer_ == NULL)
11970 {
11971 Map_type* type = this->get_map_type();
11972 if (type == NULL)
11973 {
11974 go_assert(saw_errors());
11975 return Expression::make_error(this->location());
11976 }
11977
11978 Location loc = this->location();
11979 Expression* map_ref = this->map_;
11980
11981 Expression* index_ptr = Expression::make_unary(OPERATOR_AND,
11982 this->index_,
11983 loc);
11984
11985 Expression* zero = type->fat_zero_value(gogo);
11986
11987 Expression* map_index;
11988
11989 if (zero == NULL)
11990 map_index =
11991 Runtime::make_call(Runtime::MAPACCESS1, loc, 3,
11992 Expression::make_type_descriptor(type, loc),
11993 map_ref, index_ptr);
11994 else
11995 map_index =
11996 Runtime::make_call(Runtime::MAPACCESS1_FAT, loc, 4,
11997 Expression::make_type_descriptor(type, loc),
11998 map_ref, index_ptr, zero);
11999
12000 Type* val_type = type->val_type();
12001 this->value_pointer_ =
12002 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
12003 map_index, this->location());
12004 }
12005
12006 return this->value_pointer_;
12007 }
12008
12009 // Dump ast representation for a map index expression
12010
12011 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12012 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12013 const
12014 {
12015 Index_expression::dump_index_expression(ast_dump_context, this->map_,
12016 this->index_, NULL, NULL);
12017 }
12018
12019 // Make a map index expression.
12020
12021 Map_index_expression*
make_map_index(Expression * map,Expression * index,Location location)12022 Expression::make_map_index(Expression* map, Expression* index,
12023 Location location)
12024 {
12025 return new Map_index_expression(map, index, location);
12026 }
12027
12028 // Class Field_reference_expression.
12029
12030 // Lower a field reference expression. There is nothing to lower, but
12031 // this is where we generate the tracking information for fields with
12032 // the magic go:"track" tag.
12033
12034 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)12035 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
12036 Statement_inserter* inserter, int)
12037 {
12038 Struct_type* struct_type = this->expr_->type()->struct_type();
12039 if (struct_type == NULL)
12040 {
12041 // Error will be reported elsewhere.
12042 return this;
12043 }
12044 const Struct_field* field = struct_type->field(this->field_index_);
12045 if (field == NULL)
12046 return this;
12047 if (!field->has_tag())
12048 return this;
12049 if (field->tag().find("go:\"track\"") == std::string::npos)
12050 return this;
12051
12052 // References from functions generated by the compiler don't count.
12053 if (function != NULL && function->func_value()->is_type_specific_function())
12054 return this;
12055
12056 // We have found a reference to a tracked field. Build a call to
12057 // the runtime function __go_fieldtrack with a string that describes
12058 // the field. FIXME: We should only call this once per referenced
12059 // field per function, not once for each reference to the field.
12060
12061 if (this->called_fieldtrack_)
12062 return this;
12063 this->called_fieldtrack_ = true;
12064
12065 Location loc = this->location();
12066
12067 std::string s = "fieldtrack \"";
12068 Named_type* nt = this->expr_->type()->unalias()->named_type();
12069 if (nt == NULL || nt->named_object()->package() == NULL)
12070 s.append(gogo->pkgpath());
12071 else
12072 s.append(nt->named_object()->package()->pkgpath());
12073 s.push_back('.');
12074 if (nt != NULL)
12075 s.append(Gogo::unpack_hidden_name(nt->name()));
12076 s.push_back('.');
12077 s.append(field->field_name());
12078 s.push_back('"');
12079
12080 // We can't use a string here, because internally a string holds a
12081 // pointer to the actual bytes; when the linker garbage collects the
12082 // string, it won't garbage collect the bytes. So we use a
12083 // [...]byte.
12084
12085 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
12086
12087 Type* byte_type = gogo->lookup_global("byte")->type_value();
12088 Array_type* array_type = Type::make_array_type(byte_type, length_expr);
12089 array_type->set_is_array_incomparable();
12090
12091 Expression_list* bytes = new Expression_list();
12092 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
12093 {
12094 unsigned char c = static_cast<unsigned char>(*p);
12095 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
12096 }
12097
12098 Expression* e = Expression::make_composite_literal(array_type, 0, false,
12099 bytes, false, loc);
12100
12101 Variable* var = new Variable(array_type, e, true, false, false, loc);
12102
12103 static int count;
12104 char buf[50];
12105 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
12106 ++count;
12107
12108 Named_object* no = gogo->add_variable(buf, var);
12109 e = Expression::make_var_reference(no, loc);
12110 e = Expression::make_unary(OPERATOR_AND, e, loc);
12111
12112 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
12113 gogo->lower_expression(function, inserter, &call);
12114 inserter->insert(Statement::make_statement(call, false));
12115
12116 // Put this function, and the global variable we just created, into
12117 // unique sections. This will permit the linker to garbage collect
12118 // them if they are not referenced. The effect is that the only
12119 // strings, indicating field references, that will wind up in the
12120 // executable will be those for functions that are actually needed.
12121 if (function != NULL)
12122 function->func_value()->set_in_unique_section();
12123 var->set_in_unique_section();
12124
12125 return this;
12126 }
12127
12128 // Return the type of a field reference.
12129
12130 Type*
do_type()12131 Field_reference_expression::do_type()
12132 {
12133 Type* type = this->expr_->type();
12134 if (type->is_error())
12135 return type;
12136 Struct_type* struct_type = type->struct_type();
12137 go_assert(struct_type != NULL);
12138 return struct_type->field(this->field_index_)->type();
12139 }
12140
12141 // Check the types for a field reference.
12142
12143 void
do_check_types(Gogo *)12144 Field_reference_expression::do_check_types(Gogo*)
12145 {
12146 Type* type = this->expr_->type();
12147 if (type->is_error())
12148 return;
12149 Struct_type* struct_type = type->struct_type();
12150 go_assert(struct_type != NULL);
12151 go_assert(struct_type->field(this->field_index_) != NULL);
12152 }
12153
12154 // Get the backend representation for a field reference.
12155
12156 Bexpression*
do_get_backend(Translate_context * context)12157 Field_reference_expression::do_get_backend(Translate_context* context)
12158 {
12159 Bexpression* bstruct = this->expr_->get_backend(context);
12160 return context->gogo()->backend()->struct_field_expression(bstruct,
12161 this->field_index_,
12162 this->location());
12163 }
12164
12165 // Dump ast representation for a field reference expression.
12166
12167 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12168 Field_reference_expression::do_dump_expression(
12169 Ast_dump_context* ast_dump_context) const
12170 {
12171 this->expr_->dump_expression(ast_dump_context);
12172 ast_dump_context->ostream() << "." << this->field_index_;
12173 }
12174
12175 // Make a reference to a qualified identifier in an expression.
12176
12177 Field_reference_expression*
make_field_reference(Expression * expr,unsigned int field_index,Location location)12178 Expression::make_field_reference(Expression* expr, unsigned int field_index,
12179 Location location)
12180 {
12181 return new Field_reference_expression(expr, field_index, location);
12182 }
12183
12184 // Class Interface_field_reference_expression.
12185
12186 // Return an expression for the pointer to the function to call.
12187
12188 Expression*
get_function()12189 Interface_field_reference_expression::get_function()
12190 {
12191 Expression* ref = this->expr_;
12192 Location loc = this->location();
12193 if (ref->type()->points_to() != NULL)
12194 ref = Expression::make_dereference(ref, NIL_CHECK_DEFAULT, loc);
12195
12196 Expression* mtable =
12197 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
12198 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
12199
12200 std::string name = Gogo::unpack_hidden_name(this->name_);
12201 unsigned int index;
12202 const Struct_field* field = mtable_type->find_local_field(name, &index);
12203 go_assert(field != NULL);
12204
12205 mtable = Expression::make_dereference(mtable, NIL_CHECK_NOT_NEEDED, loc);
12206 return Expression::make_field_reference(mtable, index, loc);
12207 }
12208
12209 // Return an expression for the first argument to pass to the interface
12210 // function.
12211
12212 Expression*
get_underlying_object()12213 Interface_field_reference_expression::get_underlying_object()
12214 {
12215 Expression* expr = this->expr_;
12216 if (expr->type()->points_to() != NULL)
12217 expr = Expression::make_dereference(expr, NIL_CHECK_DEFAULT,
12218 this->location());
12219 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
12220 this->location());
12221 }
12222
12223 // Traversal.
12224
12225 int
do_traverse(Traverse * traverse)12226 Interface_field_reference_expression::do_traverse(Traverse* traverse)
12227 {
12228 return Expression::traverse(&this->expr_, traverse);
12229 }
12230
12231 // Lower the expression. If this expression is not called, we need to
12232 // evaluate the expression twice when converting to the backend
12233 // interface. So introduce a temporary variable if necessary.
12234
12235 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)12236 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
12237 Statement_inserter* inserter)
12238 {
12239 if (this->expr_->is_error_expression()
12240 || this->expr_->type()->is_error_type())
12241 {
12242 go_assert(saw_errors());
12243 return Expression::make_error(this->location());
12244 }
12245
12246 if (!this->expr_->is_variable())
12247 {
12248 Temporary_statement* temp =
12249 Statement::make_temporary(NULL, this->expr_, this->location());
12250 inserter->insert(temp);
12251 this->expr_ = Expression::make_temporary_reference(temp, this->location());
12252 }
12253 return this;
12254 }
12255
12256 // Return the type of an interface field reference.
12257
12258 Type*
do_type()12259 Interface_field_reference_expression::do_type()
12260 {
12261 Type* expr_type = this->expr_->type();
12262
12263 Type* points_to = expr_type->points_to();
12264 if (points_to != NULL)
12265 expr_type = points_to;
12266
12267 Interface_type* interface_type = expr_type->interface_type();
12268 if (interface_type == NULL)
12269 return Type::make_error_type();
12270
12271 const Typed_identifier* method = interface_type->find_method(this->name_);
12272 if (method == NULL)
12273 return Type::make_error_type();
12274
12275 return method->type();
12276 }
12277
12278 // Determine types.
12279
12280 void
do_determine_type(const Type_context *)12281 Interface_field_reference_expression::do_determine_type(const Type_context*)
12282 {
12283 this->expr_->determine_type_no_context();
12284 }
12285
12286 // Check the types for an interface field reference.
12287
12288 void
do_check_types(Gogo *)12289 Interface_field_reference_expression::do_check_types(Gogo*)
12290 {
12291 Type* type = this->expr_->type();
12292
12293 Type* points_to = type->points_to();
12294 if (points_to != NULL)
12295 type = points_to;
12296
12297 Interface_type* interface_type = type->interface_type();
12298 if (interface_type == NULL)
12299 {
12300 if (!type->is_error_type())
12301 this->report_error(_("expected interface or pointer to interface"));
12302 }
12303 else
12304 {
12305 const Typed_identifier* method =
12306 interface_type->find_method(this->name_);
12307 if (method == NULL)
12308 {
12309 go_error_at(this->location(), "method %qs not in interface",
12310 Gogo::message_name(this->name_).c_str());
12311 this->set_is_error();
12312 }
12313 }
12314 }
12315
12316 // If an interface field reference is not simply called, then it is
12317 // represented as a closure. The closure will hold a single variable,
12318 // the value of the interface on which the method should be called.
12319 // The function will be a simple thunk that pulls the value from the
12320 // closure and calls the method with the remaining arguments.
12321
12322 // Because method values are not common, we don't build all thunks for
12323 // all possible interface methods, but instead only build them as we
12324 // need them. In particular, we even build them on demand for
12325 // interface methods defined in other packages.
12326
12327 Interface_field_reference_expression::Interface_method_thunks
12328 Interface_field_reference_expression::interface_method_thunks;
12329
12330 // Find or create the thunk to call method NAME on TYPE.
12331
12332 Named_object*
create_thunk(Gogo * gogo,Interface_type * type,const std::string & name)12333 Interface_field_reference_expression::create_thunk(Gogo* gogo,
12334 Interface_type* type,
12335 const std::string& name)
12336 {
12337 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
12338 std::pair<Interface_method_thunks::iterator, bool> ins =
12339 Interface_field_reference_expression::interface_method_thunks.insert(val);
12340 if (ins.second)
12341 {
12342 // This is the first time we have seen this interface.
12343 ins.first->second = new Method_thunks();
12344 }
12345
12346 for (Method_thunks::const_iterator p = ins.first->second->begin();
12347 p != ins.first->second->end();
12348 p++)
12349 if (p->first == name)
12350 return p->second;
12351
12352 Location loc = type->location();
12353
12354 const Typed_identifier* method_id = type->find_method(name);
12355 if (method_id == NULL)
12356 return Named_object::make_erroneous_name(gogo->thunk_name());
12357
12358 Function_type* orig_fntype = method_id->type()->function_type();
12359 if (orig_fntype == NULL)
12360 return Named_object::make_erroneous_name(gogo->thunk_name());
12361
12362 Struct_field_list* sfl = new Struct_field_list();
12363 // The type here is wrong--it should be the C function type. But it
12364 // doesn't really matter.
12365 Type* vt = Type::make_pointer_type(Type::make_void_type());
12366 sfl->push_back(Struct_field(Typed_identifier("fn", vt, loc)));
12367 sfl->push_back(Struct_field(Typed_identifier("val", type, loc)));
12368 Struct_type* st = Type::make_struct_type(sfl, loc);
12369 st->set_is_struct_incomparable();
12370 Type* closure_type = Type::make_pointer_type(st);
12371
12372 Function_type* new_fntype = orig_fntype->copy_with_names();
12373
12374 std::string thunk_name = gogo->thunk_name();
12375 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
12376 false, loc);
12377
12378 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
12379 cvar->set_is_used();
12380 cvar->set_is_closure();
12381 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
12382 NULL, cvar);
12383 new_no->func_value()->set_closure_var(cp);
12384
12385 gogo->start_block(loc);
12386
12387 // Field 0 of the closure is the function code pointer, field 1 is
12388 // the value on which to invoke the method.
12389 Expression* arg = Expression::make_var_reference(cp, loc);
12390 arg = Expression::make_dereference(arg, NIL_CHECK_NOT_NEEDED, loc);
12391 arg = Expression::make_field_reference(arg, 1, loc);
12392
12393 Expression *ifre = Expression::make_interface_field_reference(arg, name,
12394 loc);
12395
12396 const Typed_identifier_list* orig_params = orig_fntype->parameters();
12397 Expression_list* args;
12398 if (orig_params == NULL || orig_params->empty())
12399 args = NULL;
12400 else
12401 {
12402 const Typed_identifier_list* new_params = new_fntype->parameters();
12403 args = new Expression_list();
12404 for (Typed_identifier_list::const_iterator p = new_params->begin();
12405 p != new_params->end();
12406 ++p)
12407 {
12408 Named_object* p_no = gogo->lookup(p->name(), NULL);
12409 go_assert(p_no != NULL
12410 && p_no->is_variable()
12411 && p_no->var_value()->is_parameter());
12412 args->push_back(Expression::make_var_reference(p_no, loc));
12413 }
12414 }
12415
12416 Call_expression* call = Expression::make_call(ifre, args,
12417 orig_fntype->is_varargs(),
12418 loc);
12419 call->set_varargs_are_lowered();
12420
12421 Statement* s = Statement::make_return_from_call(call, loc);
12422 gogo->add_statement(s);
12423 Block* b = gogo->finish_block(loc);
12424 gogo->add_block(b, loc);
12425 gogo->lower_block(new_no, b);
12426 gogo->flatten_block(new_no, b);
12427 gogo->finish_function(loc);
12428
12429 ins.first->second->push_back(std::make_pair(name, new_no));
12430 return new_no;
12431 }
12432
12433 // Get the backend representation for a method value.
12434
12435 Bexpression*
do_get_backend(Translate_context * context)12436 Interface_field_reference_expression::do_get_backend(Translate_context* context)
12437 {
12438 Interface_type* type = this->expr_->type()->interface_type();
12439 if (type == NULL)
12440 {
12441 go_assert(saw_errors());
12442 return context->backend()->error_expression();
12443 }
12444
12445 Named_object* thunk =
12446 Interface_field_reference_expression::create_thunk(context->gogo(),
12447 type, this->name_);
12448 if (thunk->is_erroneous())
12449 {
12450 go_assert(saw_errors());
12451 return context->backend()->error_expression();
12452 }
12453
12454 // FIXME: We should lower this earlier, but we can't it lower it in
12455 // the lowering pass because at that point we don't know whether we
12456 // need to create the thunk or not. If the expression is called, we
12457 // don't need the thunk.
12458
12459 Location loc = this->location();
12460
12461 Struct_field_list* fields = new Struct_field_list();
12462 fields->push_back(Struct_field(Typed_identifier("fn",
12463 thunk->func_value()->type(),
12464 loc)));
12465 fields->push_back(Struct_field(Typed_identifier("val",
12466 this->expr_->type(),
12467 loc)));
12468 Struct_type* st = Type::make_struct_type(fields, loc);
12469 st->set_is_struct_incomparable();
12470
12471 Expression_list* vals = new Expression_list();
12472 vals->push_back(Expression::make_func_code_reference(thunk, loc));
12473 vals->push_back(this->expr_);
12474
12475 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
12476 Bexpression* bclosure =
12477 Expression::make_heap_expression(expr, loc)->get_backend(context);
12478
12479 Gogo* gogo = context->gogo();
12480 Btype* btype = this->type()->get_backend(gogo);
12481 bclosure = gogo->backend()->convert_expression(btype, bclosure, loc);
12482
12483 Expression* nil_check =
12484 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
12485 Expression::make_nil(loc), loc);
12486 Bexpression* bnil_check = nil_check->get_backend(context);
12487
12488 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
12489 loc)->get_backend(context);
12490
12491 Bfunction* bfn = context->function()->func_value()->get_decl();
12492 Bexpression* bcond =
12493 gogo->backend()->conditional_expression(bfn, NULL,
12494 bnil_check, bcrash, NULL, loc);
12495 Bfunction* bfunction = context->function()->func_value()->get_decl();
12496 Bstatement* cond_statement =
12497 gogo->backend()->expression_statement(bfunction, bcond);
12498 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
12499 }
12500
12501 // Dump ast representation for an interface field reference.
12502
12503 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12504 Interface_field_reference_expression::do_dump_expression(
12505 Ast_dump_context* ast_dump_context) const
12506 {
12507 this->expr_->dump_expression(ast_dump_context);
12508 ast_dump_context->ostream() << "." << this->name_;
12509 }
12510
12511 // Make a reference to a field in an interface.
12512
12513 Expression*
make_interface_field_reference(Expression * expr,const std::string & field,Location location)12514 Expression::make_interface_field_reference(Expression* expr,
12515 const std::string& field,
12516 Location location)
12517 {
12518 return new Interface_field_reference_expression(expr, field, location);
12519 }
12520
12521 // A general selector. This is a Parser_expression for LEFT.NAME. It
12522 // is lowered after we know the type of the left hand side.
12523
12524 class Selector_expression : public Parser_expression
12525 {
12526 public:
Selector_expression(Expression * left,const std::string & name,Location location)12527 Selector_expression(Expression* left, const std::string& name,
12528 Location location)
12529 : Parser_expression(EXPRESSION_SELECTOR, location),
12530 left_(left), name_(name)
12531 { }
12532
12533 protected:
12534 int
do_traverse(Traverse * traverse)12535 do_traverse(Traverse* traverse)
12536 { return Expression::traverse(&this->left_, traverse); }
12537
12538 Expression*
12539 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12540
12541 Expression*
do_copy()12542 do_copy()
12543 {
12544 return new Selector_expression(this->left_->copy(), this->name_,
12545 this->location());
12546 }
12547
12548 void
12549 do_dump_expression(Ast_dump_context* ast_dump_context) const;
12550
12551 private:
12552 Expression*
12553 lower_method_expression(Gogo*);
12554
12555 // The expression on the left hand side.
12556 Expression* left_;
12557 // The name on the right hand side.
12558 std::string name_;
12559 };
12560
12561 // Lower a selector expression once we know the real type of the left
12562 // hand side.
12563
12564 Expression*
do_lower(Gogo * gogo,Named_object *,Statement_inserter *,int)12565 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
12566 int)
12567 {
12568 Expression* left = this->left_;
12569 if (left->is_type_expression())
12570 return this->lower_method_expression(gogo);
12571 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
12572 this->location());
12573 }
12574
12575 // Lower a method expression T.M or (*T).M. We turn this into a
12576 // function literal.
12577
12578 Expression*
lower_method_expression(Gogo * gogo)12579 Selector_expression::lower_method_expression(Gogo* gogo)
12580 {
12581 Location location = this->location();
12582 Type* left_type = this->left_->type();
12583 Type* type = left_type;
12584 const std::string& name(this->name_);
12585
12586 bool is_pointer;
12587 if (type->points_to() == NULL)
12588 is_pointer = false;
12589 else
12590 {
12591 is_pointer = true;
12592 type = type->points_to();
12593 }
12594 Named_type* nt = type->named_type();
12595 if (nt == NULL)
12596 {
12597 go_error_at(location,
12598 ("method expression requires named type or "
12599 "pointer to named type"));
12600 return Expression::make_error(location);
12601 }
12602
12603 bool is_ambiguous;
12604 Method* method = nt->method_function(name, &is_ambiguous);
12605 const Typed_identifier* imethod = NULL;
12606 if (method == NULL && !is_pointer)
12607 {
12608 Interface_type* it = nt->interface_type();
12609 if (it != NULL)
12610 imethod = it->find_method(name);
12611 }
12612
12613 if ((method == NULL && imethod == NULL)
12614 || (left_type->named_type() != NULL && left_type->points_to() != NULL))
12615 {
12616 if (!is_ambiguous)
12617 go_error_at(location, "type %<%s%s%> has no method %<%s%>",
12618 is_pointer ? "*" : "",
12619 nt->message_name().c_str(),
12620 Gogo::message_name(name).c_str());
12621 else
12622 go_error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
12623 Gogo::message_name(name).c_str(),
12624 is_pointer ? "*" : "",
12625 nt->message_name().c_str());
12626 return Expression::make_error(location);
12627 }
12628
12629 if (method != NULL && !is_pointer && !method->is_value_method())
12630 {
12631 go_error_at(location, "method requires pointer (use %<(*%s).%s%>)",
12632 nt->message_name().c_str(),
12633 Gogo::message_name(name).c_str());
12634 return Expression::make_error(location);
12635 }
12636
12637 // Build a new function type in which the receiver becomes the first
12638 // argument.
12639 Function_type* method_type;
12640 if (method != NULL)
12641 {
12642 method_type = method->type();
12643 go_assert(method_type->is_method());
12644 }
12645 else
12646 {
12647 method_type = imethod->type()->function_type();
12648 go_assert(method_type != NULL && !method_type->is_method());
12649 }
12650
12651 const char* const receiver_name = "$this";
12652 Typed_identifier_list* parameters = new Typed_identifier_list();
12653 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
12654 location));
12655
12656 const Typed_identifier_list* method_parameters = method_type->parameters();
12657 if (method_parameters != NULL)
12658 {
12659 int i = 0;
12660 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
12661 p != method_parameters->end();
12662 ++p, ++i)
12663 {
12664 if (!p->name().empty())
12665 parameters->push_back(*p);
12666 else
12667 {
12668 char buf[20];
12669 snprintf(buf, sizeof buf, "$param%d", i);
12670 parameters->push_back(Typed_identifier(buf, p->type(),
12671 p->location()));
12672 }
12673 }
12674 }
12675
12676 const Typed_identifier_list* method_results = method_type->results();
12677 Typed_identifier_list* results;
12678 if (method_results == NULL)
12679 results = NULL;
12680 else
12681 {
12682 results = new Typed_identifier_list();
12683 for (Typed_identifier_list::const_iterator p = method_results->begin();
12684 p != method_results->end();
12685 ++p)
12686 results->push_back(*p);
12687 }
12688
12689 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
12690 location);
12691 if (method_type->is_varargs())
12692 fntype->set_is_varargs();
12693
12694 // We generate methods which always takes a pointer to the receiver
12695 // as their first argument. If this is for a pointer type, we can
12696 // simply reuse the existing function. We use an internal hack to
12697 // get the right type.
12698 // FIXME: This optimization is disabled because it doesn't yet work
12699 // with function descriptors when the method expression is not
12700 // directly called.
12701 if (method != NULL && is_pointer && false)
12702 {
12703 Named_object* mno = (method->needs_stub_method()
12704 ? method->stub_object()
12705 : method->named_object());
12706 Expression* f = Expression::make_func_reference(mno, NULL, location);
12707 f = Expression::make_cast(fntype, f, location);
12708 Type_conversion_expression* tce =
12709 static_cast<Type_conversion_expression*>(f);
12710 tce->set_may_convert_function_types();
12711 return f;
12712 }
12713
12714 Named_object* no = gogo->start_function(gogo->thunk_name(), fntype, false,
12715 location);
12716
12717 Named_object* vno = gogo->lookup(receiver_name, NULL);
12718 go_assert(vno != NULL);
12719 Expression* ve = Expression::make_var_reference(vno, location);
12720 Expression* bm;
12721 if (method != NULL)
12722 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
12723 else
12724 bm = Expression::make_interface_field_reference(ve, name, location);
12725
12726 // Even though we found the method above, if it has an error type we
12727 // may see an error here.
12728 if (bm->is_error_expression())
12729 {
12730 gogo->finish_function(location);
12731 return bm;
12732 }
12733
12734 Expression_list* args;
12735 if (parameters->size() <= 1)
12736 args = NULL;
12737 else
12738 {
12739 args = new Expression_list();
12740 Typed_identifier_list::const_iterator p = parameters->begin();
12741 ++p;
12742 for (; p != parameters->end(); ++p)
12743 {
12744 vno = gogo->lookup(p->name(), NULL);
12745 go_assert(vno != NULL);
12746 args->push_back(Expression::make_var_reference(vno, location));
12747 }
12748 }
12749
12750 gogo->start_block(location);
12751
12752 Call_expression* call = Expression::make_call(bm, args,
12753 method_type->is_varargs(),
12754 location);
12755
12756 Statement* s = Statement::make_return_from_call(call, location);
12757 gogo->add_statement(s);
12758
12759 Block* b = gogo->finish_block(location);
12760
12761 gogo->add_block(b, location);
12762
12763 // Lower the call in case there are multiple results.
12764 gogo->lower_block(no, b);
12765 gogo->flatten_block(no, b);
12766
12767 gogo->finish_function(location);
12768
12769 return Expression::make_func_reference(no, NULL, location);
12770 }
12771
12772 // Dump the ast for a selector expression.
12773
12774 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12775 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12776 const
12777 {
12778 ast_dump_context->dump_expression(this->left_);
12779 ast_dump_context->ostream() << ".";
12780 ast_dump_context->ostream() << this->name_;
12781 }
12782
12783 // Make a selector expression.
12784
12785 Expression*
make_selector(Expression * left,const std::string & name,Location location)12786 Expression::make_selector(Expression* left, const std::string& name,
12787 Location location)
12788 {
12789 return new Selector_expression(left, name, location);
12790 }
12791
12792 // Class Allocation_expression.
12793
12794 int
do_traverse(Traverse * traverse)12795 Allocation_expression::do_traverse(Traverse* traverse)
12796 {
12797 return Type::traverse(this->type_, traverse);
12798 }
12799
12800 Type*
do_type()12801 Allocation_expression::do_type()
12802 {
12803 return Type::make_pointer_type(this->type_);
12804 }
12805
12806 void
do_check_types(Gogo *)12807 Allocation_expression::do_check_types(Gogo*)
12808 {
12809 if (!this->type_->in_heap())
12810 go_error_at(this->location(), "can't heap allocate go:notinheap type");
12811 }
12812
12813 // Make a copy of an allocation expression.
12814
12815 Expression*
do_copy()12816 Allocation_expression::do_copy()
12817 {
12818 Allocation_expression* alloc =
12819 new Allocation_expression(this->type_->copy_expressions(),
12820 this->location());
12821 if (this->allocate_on_stack_)
12822 alloc->set_allocate_on_stack();
12823 return alloc;
12824 }
12825
12826 // Return the backend representation for an allocation expression.
12827
12828 Bexpression*
do_get_backend(Translate_context * context)12829 Allocation_expression::do_get_backend(Translate_context* context)
12830 {
12831 Gogo* gogo = context->gogo();
12832 Location loc = this->location();
12833 Btype* btype = this->type_->get_backend(gogo);
12834
12835 if (this->allocate_on_stack_)
12836 {
12837 int64_t size;
12838 bool ok = this->type_->backend_type_size(gogo, &size);
12839 if (!ok)
12840 {
12841 go_assert(saw_errors());
12842 return gogo->backend()->error_expression();
12843 }
12844 Bstatement* decl;
12845 Named_object* fn = context->function();
12846 go_assert(fn != NULL);
12847 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
12848 Bexpression* zero = gogo->backend()->zero_expression(btype);
12849 Bvariable* temp =
12850 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
12851 zero, true, loc, &decl);
12852 Bexpression* ret = gogo->backend()->var_expression(temp, loc);
12853 ret = gogo->backend()->address_expression(ret, loc);
12854 ret = gogo->backend()->compound_expression(decl, ret, loc);
12855 return ret;
12856 }
12857
12858 Bexpression* space =
12859 gogo->allocate_memory(this->type_, loc)->get_backend(context);
12860 Btype* pbtype = gogo->backend()->pointer_type(btype);
12861 return gogo->backend()->convert_expression(pbtype, space, loc);
12862 }
12863
12864 // Dump ast representation for an allocation expression.
12865
12866 void
do_dump_expression(Ast_dump_context * ast_dump_context) const12867 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
12868 const
12869 {
12870 ast_dump_context->ostream() << "new(";
12871 ast_dump_context->dump_type(this->type_);
12872 ast_dump_context->ostream() << ")";
12873 }
12874
12875 // Make an allocation expression.
12876
12877 Expression*
make_allocation(Type * type,Location location)12878 Expression::make_allocation(Type* type, Location location)
12879 {
12880 return new Allocation_expression(type, location);
12881 }
12882
12883 // Class Ordered_value_list.
12884
12885 int
traverse_vals(Traverse * traverse)12886 Ordered_value_list::traverse_vals(Traverse* traverse)
12887 {
12888 if (this->vals_ != NULL)
12889 {
12890 if (this->traverse_order_ == NULL)
12891 {
12892 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12893 return TRAVERSE_EXIT;
12894 }
12895 else
12896 {
12897 for (std::vector<unsigned long>::const_iterator p =
12898 this->traverse_order_->begin();
12899 p != this->traverse_order_->end();
12900 ++p)
12901 {
12902 if (Expression::traverse(&this->vals_->at(*p), traverse)
12903 == TRAVERSE_EXIT)
12904 return TRAVERSE_EXIT;
12905 }
12906 }
12907 }
12908 return TRAVERSE_CONTINUE;
12909 }
12910
12911 // Class Struct_construction_expression.
12912
12913 // Traversal.
12914
12915 int
do_traverse(Traverse * traverse)12916 Struct_construction_expression::do_traverse(Traverse* traverse)
12917 {
12918 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
12919 return TRAVERSE_EXIT;
12920 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12921 return TRAVERSE_EXIT;
12922 return TRAVERSE_CONTINUE;
12923 }
12924
12925 // Return whether this is a constant initializer.
12926
12927 bool
is_constant_struct() const12928 Struct_construction_expression::is_constant_struct() const
12929 {
12930 if (this->vals() == NULL)
12931 return true;
12932 for (Expression_list::const_iterator pv = this->vals()->begin();
12933 pv != this->vals()->end();
12934 ++pv)
12935 {
12936 if (*pv != NULL
12937 && !(*pv)->is_constant()
12938 && (!(*pv)->is_composite_literal()
12939 || (*pv)->is_nonconstant_composite_literal()))
12940 return false;
12941 }
12942
12943 const Struct_field_list* fields = this->type_->struct_type()->fields();
12944 for (Struct_field_list::const_iterator pf = fields->begin();
12945 pf != fields->end();
12946 ++pf)
12947 {
12948 // There are no constant constructors for interfaces.
12949 if (pf->type()->interface_type() != NULL)
12950 return false;
12951 }
12952
12953 return true;
12954 }
12955
12956 // Return whether this struct can be used as a constant initializer.
12957
12958 bool
do_is_static_initializer() const12959 Struct_construction_expression::do_is_static_initializer() const
12960 {
12961 if (this->vals() == NULL)
12962 return true;
12963 for (Expression_list::const_iterator pv = this->vals()->begin();
12964 pv != this->vals()->end();
12965 ++pv)
12966 {
12967 if (*pv != NULL && !(*pv)->is_static_initializer())
12968 return false;
12969 }
12970
12971 const Struct_field_list* fields = this->type_->struct_type()->fields();
12972 for (Struct_field_list::const_iterator pf = fields->begin();
12973 pf != fields->end();
12974 ++pf)
12975 {
12976 // There are no constant constructors for interfaces.
12977 if (pf->type()->interface_type() != NULL)
12978 return false;
12979 }
12980
12981 return true;
12982 }
12983
12984 // Final type determination.
12985
12986 void
do_determine_type(const Type_context *)12987 Struct_construction_expression::do_determine_type(const Type_context*)
12988 {
12989 if (this->vals() == NULL)
12990 return;
12991 const Struct_field_list* fields = this->type_->struct_type()->fields();
12992 Expression_list::const_iterator pv = this->vals()->begin();
12993 for (Struct_field_list::const_iterator pf = fields->begin();
12994 pf != fields->end();
12995 ++pf, ++pv)
12996 {
12997 if (pv == this->vals()->end())
12998 return;
12999 if (*pv != NULL)
13000 {
13001 Type_context subcontext(pf->type(), false);
13002 (*pv)->determine_type(&subcontext);
13003 }
13004 }
13005 // Extra values are an error we will report elsewhere; we still want
13006 // to determine the type to avoid knockon errors.
13007 for (; pv != this->vals()->end(); ++pv)
13008 (*pv)->determine_type_no_context();
13009 }
13010
13011 // Check types.
13012
13013 void
do_check_types(Gogo *)13014 Struct_construction_expression::do_check_types(Gogo*)
13015 {
13016 if (this->vals() == NULL)
13017 return;
13018
13019 Struct_type* st = this->type_->struct_type();
13020 if (this->vals()->size() > st->field_count())
13021 {
13022 this->report_error(_("too many expressions for struct"));
13023 return;
13024 }
13025
13026 const Struct_field_list* fields = st->fields();
13027 Expression_list::const_iterator pv = this->vals()->begin();
13028 int i = 0;
13029 for (Struct_field_list::const_iterator pf = fields->begin();
13030 pf != fields->end();
13031 ++pf, ++pv, ++i)
13032 {
13033 if (pv == this->vals()->end())
13034 {
13035 this->report_error(_("too few expressions for struct"));
13036 break;
13037 }
13038
13039 if (*pv == NULL)
13040 continue;
13041
13042 std::string reason;
13043 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
13044 {
13045 if (reason.empty())
13046 go_error_at((*pv)->location(),
13047 "incompatible type for field %d in struct construction",
13048 i + 1);
13049 else
13050 go_error_at((*pv)->location(),
13051 ("incompatible type for field %d in "
13052 "struct construction (%s)"),
13053 i + 1, reason.c_str());
13054 this->set_is_error();
13055 }
13056 }
13057 go_assert(pv == this->vals()->end());
13058 }
13059
13060 // Copy.
13061
13062 Expression*
do_copy()13063 Struct_construction_expression::do_copy()
13064 {
13065 Struct_construction_expression* ret =
13066 new Struct_construction_expression(this->type_->copy_expressions(),
13067 (this->vals() == NULL
13068 ? NULL
13069 : this->vals()->copy()),
13070 this->location());
13071 if (this->traverse_order() != NULL)
13072 ret->set_traverse_order(this->traverse_order());
13073 return ret;
13074 }
13075
13076 // Flatten a struct construction expression. Store the values into
13077 // temporaries in case they need interface conversion.
13078
13079 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13080 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
13081 Statement_inserter* inserter)
13082 {
13083 if (this->vals() == NULL)
13084 return this;
13085
13086 // If this is a constant struct, we don't need temporaries.
13087 if (this->is_constant_struct() || this->is_static_initializer())
13088 return this;
13089
13090 Location loc = this->location();
13091 for (Expression_list::iterator pv = this->vals()->begin();
13092 pv != this->vals()->end();
13093 ++pv)
13094 {
13095 if (*pv != NULL)
13096 {
13097 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
13098 {
13099 go_assert(saw_errors());
13100 return Expression::make_error(loc);
13101 }
13102 if (!(*pv)->is_variable())
13103 {
13104 Temporary_statement* temp =
13105 Statement::make_temporary(NULL, *pv, loc);
13106 inserter->insert(temp);
13107 *pv = Expression::make_temporary_reference(temp, loc);
13108 }
13109 }
13110 }
13111 return this;
13112 }
13113
13114 // Return the backend representation for constructing a struct.
13115
13116 Bexpression*
do_get_backend(Translate_context * context)13117 Struct_construction_expression::do_get_backend(Translate_context* context)
13118 {
13119 Gogo* gogo = context->gogo();
13120
13121 Btype* btype = this->type_->get_backend(gogo);
13122 if (this->vals() == NULL)
13123 return gogo->backend()->zero_expression(btype);
13124
13125 const Struct_field_list* fields = this->type_->struct_type()->fields();
13126 Expression_list::const_iterator pv = this->vals()->begin();
13127 std::vector<Bexpression*> init;
13128 for (Struct_field_list::const_iterator pf = fields->begin();
13129 pf != fields->end();
13130 ++pf)
13131 {
13132 Btype* fbtype = pf->type()->get_backend(gogo);
13133 if (pv == this->vals()->end())
13134 init.push_back(gogo->backend()->zero_expression(fbtype));
13135 else if (*pv == NULL)
13136 {
13137 init.push_back(gogo->backend()->zero_expression(fbtype));
13138 ++pv;
13139 }
13140 else
13141 {
13142 Expression* val =
13143 Expression::convert_for_assignment(gogo, pf->type(),
13144 *pv, this->location());
13145 init.push_back(val->get_backend(context));
13146 ++pv;
13147 }
13148 }
13149 if (this->type_->struct_type()->has_padding())
13150 {
13151 // Feed an extra value if there is a padding field.
13152 Btype *fbtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
13153 init.push_back(gogo->backend()->zero_expression(fbtype));
13154 }
13155 return gogo->backend()->constructor_expression(btype, init, this->location());
13156 }
13157
13158 // Export a struct construction.
13159
13160 void
do_export(Export_function_body * efb) const13161 Struct_construction_expression::do_export(Export_function_body* efb) const
13162 {
13163 efb->write_c_string("$convert(");
13164 efb->write_type(this->type_);
13165 for (Expression_list::const_iterator pv = this->vals()->begin();
13166 pv != this->vals()->end();
13167 ++pv)
13168 {
13169 efb->write_c_string(", ");
13170 if (*pv != NULL)
13171 (*pv)->export_expression(efb);
13172 }
13173 efb->write_c_string(")");
13174 }
13175
13176 // Dump ast representation of a struct construction expression.
13177
13178 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13179 Struct_construction_expression::do_dump_expression(
13180 Ast_dump_context* ast_dump_context) const
13181 {
13182 ast_dump_context->dump_type(this->type_);
13183 ast_dump_context->ostream() << "{";
13184 ast_dump_context->dump_expression_list(this->vals());
13185 ast_dump_context->ostream() << "}";
13186 }
13187
13188 // Make a struct composite literal. This used by the thunk code.
13189
13190 Expression*
make_struct_composite_literal(Type * type,Expression_list * vals,Location location)13191 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
13192 Location location)
13193 {
13194 go_assert(type->struct_type() != NULL);
13195 return new Struct_construction_expression(type, vals, location);
13196 }
13197
13198 // Class Array_construction_expression.
13199
13200 // Traversal.
13201
13202 int
do_traverse(Traverse * traverse)13203 Array_construction_expression::do_traverse(Traverse* traverse)
13204 {
13205 if (this->traverse_vals(traverse) == TRAVERSE_EXIT)
13206 return TRAVERSE_EXIT;
13207 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13208 return TRAVERSE_EXIT;
13209 return TRAVERSE_CONTINUE;
13210 }
13211
13212 // Return whether this is a constant initializer.
13213
13214 bool
is_constant_array() const13215 Array_construction_expression::is_constant_array() const
13216 {
13217 if (this->vals() == NULL)
13218 return true;
13219
13220 // There are no constant constructors for interfaces.
13221 if (this->type_->array_type()->element_type()->interface_type() != NULL)
13222 return false;
13223
13224 for (Expression_list::const_iterator pv = this->vals()->begin();
13225 pv != this->vals()->end();
13226 ++pv)
13227 {
13228 if (*pv != NULL
13229 && !(*pv)->is_constant()
13230 && (!(*pv)->is_composite_literal()
13231 || (*pv)->is_nonconstant_composite_literal()))
13232 return false;
13233 }
13234 return true;
13235 }
13236
13237 // Return whether this can be used a constant initializer.
13238
13239 bool
do_is_static_initializer() const13240 Array_construction_expression::do_is_static_initializer() const
13241 {
13242 if (this->vals() == NULL)
13243 return true;
13244
13245 // There are no constant constructors for interfaces.
13246 if (this->type_->array_type()->element_type()->interface_type() != NULL)
13247 return false;
13248
13249 for (Expression_list::const_iterator pv = this->vals()->begin();
13250 pv != this->vals()->end();
13251 ++pv)
13252 {
13253 if (*pv != NULL && !(*pv)->is_static_initializer())
13254 return false;
13255 }
13256 return true;
13257 }
13258
13259 // Final type determination.
13260
13261 void
do_determine_type(const Type_context *)13262 Array_construction_expression::do_determine_type(const Type_context*)
13263 {
13264 if (this->vals() == NULL)
13265 return;
13266 Type_context subcontext(this->type_->array_type()->element_type(), false);
13267 for (Expression_list::const_iterator pv = this->vals()->begin();
13268 pv != this->vals()->end();
13269 ++pv)
13270 {
13271 if (*pv != NULL)
13272 (*pv)->determine_type(&subcontext);
13273 }
13274 }
13275
13276 // Check types.
13277
13278 void
do_check_types(Gogo *)13279 Array_construction_expression::do_check_types(Gogo*)
13280 {
13281 if (this->vals() == NULL)
13282 return;
13283
13284 Array_type* at = this->type_->array_type();
13285 int i = 0;
13286 Type* element_type = at->element_type();
13287 for (Expression_list::const_iterator pv = this->vals()->begin();
13288 pv != this->vals()->end();
13289 ++pv, ++i)
13290 {
13291 if (*pv != NULL
13292 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
13293 {
13294 go_error_at((*pv)->location(),
13295 "incompatible type for element %d in composite literal",
13296 i + 1);
13297 this->set_is_error();
13298 }
13299 }
13300 }
13301
13302 // Flatten an array construction expression. Store the values into
13303 // temporaries in case they need interface conversion.
13304
13305 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)13306 Array_construction_expression::do_flatten(Gogo*, Named_object*,
13307 Statement_inserter* inserter)
13308 {
13309 if (this->vals() == NULL)
13310 return this;
13311
13312 // If this is a constant array, we don't need temporaries.
13313 if (this->is_constant_array() || this->is_static_initializer())
13314 return this;
13315
13316 Location loc = this->location();
13317 for (Expression_list::iterator pv = this->vals()->begin();
13318 pv != this->vals()->end();
13319 ++pv)
13320 {
13321 if (*pv != NULL)
13322 {
13323 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
13324 {
13325 go_assert(saw_errors());
13326 return Expression::make_error(loc);
13327 }
13328 if (!(*pv)->is_variable())
13329 {
13330 Temporary_statement* temp =
13331 Statement::make_temporary(NULL, *pv, loc);
13332 inserter->insert(temp);
13333 *pv = Expression::make_temporary_reference(temp, loc);
13334 }
13335 }
13336 }
13337 return this;
13338 }
13339
13340 // Get a constructor expression for the array values.
13341
13342 Bexpression*
get_constructor(Translate_context * context,Btype * array_btype)13343 Array_construction_expression::get_constructor(Translate_context* context,
13344 Btype* array_btype)
13345 {
13346 Type* element_type = this->type_->array_type()->element_type();
13347
13348 std::vector<unsigned long> indexes;
13349 std::vector<Bexpression*> vals;
13350 Gogo* gogo = context->gogo();
13351 if (this->vals() != NULL)
13352 {
13353 size_t i = 0;
13354 std::vector<unsigned long>::const_iterator pi;
13355 if (this->indexes_ != NULL)
13356 pi = this->indexes_->begin();
13357 for (Expression_list::const_iterator pv = this->vals()->begin();
13358 pv != this->vals()->end();
13359 ++pv, ++i)
13360 {
13361 if (this->indexes_ != NULL)
13362 go_assert(pi != this->indexes_->end());
13363
13364 if (this->indexes_ == NULL)
13365 indexes.push_back(i);
13366 else
13367 indexes.push_back(*pi);
13368 if (*pv == NULL)
13369 {
13370 Btype* ebtype = element_type->get_backend(gogo);
13371 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
13372 vals.push_back(zv);
13373 }
13374 else
13375 {
13376 Expression* val_expr =
13377 Expression::convert_for_assignment(gogo, element_type, *pv,
13378 this->location());
13379 vals.push_back(val_expr->get_backend(context));
13380 }
13381 if (this->indexes_ != NULL)
13382 ++pi;
13383 }
13384 if (this->indexes_ != NULL)
13385 go_assert(pi == this->indexes_->end());
13386 }
13387 return gogo->backend()->array_constructor_expression(array_btype, indexes,
13388 vals, this->location());
13389 }
13390
13391 // Export an array construction.
13392
13393 void
do_export(Export_function_body * efb) const13394 Array_construction_expression::do_export(Export_function_body* efb) const
13395 {
13396 efb->write_c_string("$convert(");
13397 efb->write_type(this->type_);
13398 if (this->vals() != NULL)
13399 {
13400 std::vector<unsigned long>::const_iterator pi;
13401 if (this->indexes_ != NULL)
13402 pi = this->indexes_->begin();
13403 for (Expression_list::const_iterator pv = this->vals()->begin();
13404 pv != this->vals()->end();
13405 ++pv)
13406 {
13407 efb->write_c_string(", ");
13408
13409 if (this->indexes_ != NULL)
13410 {
13411 char buf[100];
13412 snprintf(buf, sizeof buf, "%lu", *pi);
13413 efb->write_c_string(buf);
13414 efb->write_c_string(":");
13415 }
13416
13417 if (*pv != NULL)
13418 (*pv)->export_expression(efb);
13419
13420 if (this->indexes_ != NULL)
13421 ++pi;
13422 }
13423 }
13424 efb->write_c_string(")");
13425 }
13426
13427 // Dump ast representation of an array construction expression.
13428
13429 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13430 Array_construction_expression::do_dump_expression(
13431 Ast_dump_context* ast_dump_context) const
13432 {
13433 Expression* length = this->type_->array_type()->length();
13434
13435 ast_dump_context->ostream() << "[" ;
13436 if (length != NULL)
13437 {
13438 ast_dump_context->dump_expression(length);
13439 }
13440 ast_dump_context->ostream() << "]" ;
13441 ast_dump_context->dump_type(this->type_);
13442 this->dump_slice_storage_expression(ast_dump_context);
13443 ast_dump_context->ostream() << "{" ;
13444 if (this->indexes_ == NULL)
13445 ast_dump_context->dump_expression_list(this->vals());
13446 else
13447 {
13448 Expression_list::const_iterator pv = this->vals()->begin();
13449 for (std::vector<unsigned long>::const_iterator pi =
13450 this->indexes_->begin();
13451 pi != this->indexes_->end();
13452 ++pi, ++pv)
13453 {
13454 if (pi != this->indexes_->begin())
13455 ast_dump_context->ostream() << ", ";
13456 ast_dump_context->ostream() << *pi << ':';
13457 ast_dump_context->dump_expression(*pv);
13458 }
13459 }
13460 ast_dump_context->ostream() << "}" ;
13461
13462 }
13463
13464 // Class Fixed_array_construction_expression.
13465
Fixed_array_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)13466 Fixed_array_construction_expression::Fixed_array_construction_expression(
13467 Type* type, const std::vector<unsigned long>* indexes,
13468 Expression_list* vals, Location location)
13469 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
13470 type, indexes, vals, location)
13471 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
13472
13473
13474 // Copy.
13475
13476 Expression*
do_copy()13477 Fixed_array_construction_expression::do_copy()
13478 {
13479 Type* t = this->type()->copy_expressions();
13480 return new Fixed_array_construction_expression(t, this->indexes(),
13481 (this->vals() == NULL
13482 ? NULL
13483 : this->vals()->copy()),
13484 this->location());
13485 }
13486
13487 // Return the backend representation for constructing a fixed array.
13488
13489 Bexpression*
do_get_backend(Translate_context * context)13490 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
13491 {
13492 Type* type = this->type();
13493 Btype* btype = type->get_backend(context->gogo());
13494 return this->get_constructor(context, btype);
13495 }
13496
13497 Expression*
make_array_composite_literal(Type * type,Expression_list * vals,Location location)13498 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
13499 Location location)
13500 {
13501 go_assert(type->array_type() != NULL && !type->is_slice_type());
13502 return new Fixed_array_construction_expression(type, NULL, vals, location);
13503 }
13504
13505 // Class Slice_construction_expression.
13506
Slice_construction_expression(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals,Location location)13507 Slice_construction_expression::Slice_construction_expression(
13508 Type* type, const std::vector<unsigned long>* indexes,
13509 Expression_list* vals, Location location)
13510 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
13511 type, indexes, vals, location),
13512 valtype_(NULL), array_val_(NULL), slice_storage_(NULL),
13513 storage_escapes_(true)
13514 {
13515 go_assert(type->is_slice_type());
13516
13517 unsigned long lenval;
13518 Expression* length;
13519 if (vals == NULL || vals->empty())
13520 lenval = 0;
13521 else
13522 {
13523 if (this->indexes() == NULL)
13524 lenval = vals->size();
13525 else
13526 lenval = indexes->back() + 1;
13527 }
13528 Type* int_type = Type::lookup_integer_type("int");
13529 length = Expression::make_integer_ul(lenval, int_type, location);
13530 Type* element_type = type->array_type()->element_type();
13531 Array_type* array_type = Type::make_array_type(element_type, length);
13532 array_type->set_is_array_incomparable();
13533 this->valtype_ = array_type;
13534 }
13535
13536 // Traversal.
13537
13538 int
do_traverse(Traverse * traverse)13539 Slice_construction_expression::do_traverse(Traverse* traverse)
13540 {
13541 if (this->Array_construction_expression::do_traverse(traverse)
13542 == TRAVERSE_EXIT)
13543 return TRAVERSE_EXIT;
13544 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
13545 return TRAVERSE_EXIT;
13546 if (this->array_val_ != NULL
13547 && Expression::traverse(&this->array_val_, traverse) == TRAVERSE_EXIT)
13548 return TRAVERSE_EXIT;
13549 if (this->slice_storage_ != NULL
13550 && Expression::traverse(&this->slice_storage_, traverse) == TRAVERSE_EXIT)
13551 return TRAVERSE_EXIT;
13552 return TRAVERSE_CONTINUE;
13553 }
13554
13555 // Helper routine to create fixed array value underlying the slice literal.
13556 // May be called during flattening, or later during do_get_backend().
13557
13558 Expression*
create_array_val()13559 Slice_construction_expression::create_array_val()
13560 {
13561 Array_type* array_type = this->type()->array_type();
13562 if (array_type == NULL)
13563 {
13564 go_assert(this->type()->is_error());
13565 return NULL;
13566 }
13567
13568 Location loc = this->location();
13569 go_assert(this->valtype_ != NULL);
13570
13571 Expression_list* vals = this->vals();
13572 return new Fixed_array_construction_expression(
13573 this->valtype_, this->indexes(), vals, loc);
13574 }
13575
13576 // If we're previous established that the slice storage does not
13577 // escape, then create a separate array temp val here for it. We
13578 // need to do this as part of flattening so as to be able to insert
13579 // the new temp statement.
13580
13581 Expression*
do_flatten(Gogo * gogo,Named_object * no,Statement_inserter * inserter)13582 Slice_construction_expression::do_flatten(Gogo* gogo, Named_object* no,
13583 Statement_inserter* inserter)
13584 {
13585 if (this->type()->array_type() == NULL)
13586 return NULL;
13587
13588 // Base class flattening first
13589 this->Array_construction_expression::do_flatten(gogo, no, inserter);
13590
13591 // Create a stack-allocated storage temp if storage won't escape
13592 if (!this->storage_escapes_
13593 && this->slice_storage_ == NULL
13594 && this->element_count() > 0)
13595 {
13596 Location loc = this->location();
13597 this->array_val_ = this->create_array_val();
13598 go_assert(this->array_val_);
13599 Temporary_statement* temp =
13600 Statement::make_temporary(this->valtype_, this->array_val_, loc);
13601 inserter->insert(temp);
13602 this->slice_storage_ = Expression::make_temporary_reference(temp, loc);
13603 }
13604 return this;
13605 }
13606
13607 // When dumping a slice construction expression that has an explicit
13608 // storeage temp, emit the temp here (if we don't do this the storage
13609 // temp appears unused in the AST dump).
13610
13611 void
13612 Slice_construction_expression::
dump_slice_storage_expression(Ast_dump_context * ast_dump_context) const13613 dump_slice_storage_expression(Ast_dump_context* ast_dump_context) const
13614 {
13615 if (this->slice_storage_ == NULL)
13616 return;
13617 ast_dump_context->ostream() << "storage=" ;
13618 ast_dump_context->dump_expression(this->slice_storage_);
13619 }
13620
13621 // Copy.
13622
13623 Expression*
do_copy()13624 Slice_construction_expression::do_copy()
13625 {
13626 return new Slice_construction_expression(this->type()->copy_expressions(),
13627 this->indexes(),
13628 (this->vals() == NULL
13629 ? NULL
13630 : this->vals()->copy()),
13631 this->location());
13632 }
13633
13634 // Return the backend representation for constructing a slice.
13635
13636 Bexpression*
do_get_backend(Translate_context * context)13637 Slice_construction_expression::do_get_backend(Translate_context* context)
13638 {
13639 if (this->array_val_ == NULL)
13640 this->array_val_ = this->create_array_val();
13641 if (this->array_val_ == NULL)
13642 {
13643 go_assert(this->type()->is_error());
13644 return context->backend()->error_expression();
13645 }
13646
13647 Location loc = this->location();
13648
13649 bool is_static_initializer = this->array_val_->is_static_initializer();
13650
13651 // We have to copy the initial values into heap memory if we are in
13652 // a function or if the values are not constants.
13653 bool copy_to_heap = context->function() != NULL || !is_static_initializer;
13654
13655 Expression* space;
13656
13657 if (this->slice_storage_ != NULL)
13658 {
13659 go_assert(!this->storage_escapes_);
13660 space = Expression::make_unary(OPERATOR_AND, this->slice_storage_, loc);
13661 }
13662 else if (!copy_to_heap)
13663 {
13664 // The initializer will only run once.
13665 space = Expression::make_unary(OPERATOR_AND, this->array_val_, loc);
13666 space->unary_expression()->set_is_slice_init();
13667 }
13668 else
13669 {
13670 go_assert(this->storage_escapes_ || this->element_count() == 0);
13671 space = Expression::make_heap_expression(this->array_val_, loc);
13672 }
13673 Array_type* at = this->valtype_->array_type();
13674 Type* et = at->element_type();
13675 space = Expression::make_unsafe_cast(Type::make_pointer_type(et),
13676 space, loc);
13677
13678 // Build a constructor for the slice.
13679 Expression* len = at->length();
13680 Expression* slice_val =
13681 Expression::make_slice_value(this->type(), space, len, len, loc);
13682 return slice_val->get_backend(context);
13683 }
13684
13685 // Make a slice composite literal. This is used by the type
13686 // descriptor code.
13687
13688 Slice_construction_expression*
make_slice_composite_literal(Type * type,Expression_list * vals,Location location)13689 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
13690 Location location)
13691 {
13692 go_assert(type->is_slice_type());
13693 return new Slice_construction_expression(type, NULL, vals, location);
13694 }
13695
13696 // Class Map_construction_expression.
13697
13698 // Traversal.
13699
13700 int
do_traverse(Traverse * traverse)13701 Map_construction_expression::do_traverse(Traverse* traverse)
13702 {
13703 if (this->vals_ != NULL
13704 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
13705 return TRAVERSE_EXIT;
13706 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13707 return TRAVERSE_EXIT;
13708 return TRAVERSE_CONTINUE;
13709 }
13710
13711 // Flatten constructor initializer into a temporary variable since
13712 // we need to take its address for __go_construct_map.
13713
13714 Expression*
do_flatten(Gogo * gogo,Named_object *,Statement_inserter * inserter)13715 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
13716 Statement_inserter* inserter)
13717 {
13718 if (!this->is_error_expression()
13719 && this->vals_ != NULL
13720 && !this->vals_->empty()
13721 && this->constructor_temp_ == NULL)
13722 {
13723 Map_type* mt = this->type_->map_type();
13724 Type* key_type = mt->key_type();
13725 Type* val_type = mt->val_type();
13726 this->element_type_ = Type::make_builtin_struct_type(2,
13727 "__key", key_type,
13728 "__val", val_type);
13729
13730 Expression_list* value_pairs = new Expression_list();
13731 Location loc = this->location();
13732
13733 size_t i = 0;
13734 for (Expression_list::const_iterator pv = this->vals_->begin();
13735 pv != this->vals_->end();
13736 ++pv, ++i)
13737 {
13738 Expression_list* key_value_pair = new Expression_list();
13739 Expression* key = *pv;
13740 if (key->is_error_expression() || key->type()->is_error_type())
13741 {
13742 go_assert(saw_errors());
13743 return Expression::make_error(loc);
13744 }
13745 if (key->type()->interface_type() != NULL && !key->is_variable())
13746 {
13747 Temporary_statement* temp =
13748 Statement::make_temporary(NULL, key, loc);
13749 inserter->insert(temp);
13750 key = Expression::make_temporary_reference(temp, loc);
13751 }
13752 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
13753
13754 ++pv;
13755 Expression* val = *pv;
13756 if (val->is_error_expression() || val->type()->is_error_type())
13757 {
13758 go_assert(saw_errors());
13759 return Expression::make_error(loc);
13760 }
13761 if (val->type()->interface_type() != NULL && !val->is_variable())
13762 {
13763 Temporary_statement* temp =
13764 Statement::make_temporary(NULL, val, loc);
13765 inserter->insert(temp);
13766 val = Expression::make_temporary_reference(temp, loc);
13767 }
13768 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
13769
13770 key_value_pair->push_back(key);
13771 key_value_pair->push_back(val);
13772 value_pairs->push_back(
13773 Expression::make_struct_composite_literal(this->element_type_,
13774 key_value_pair, loc));
13775 }
13776
13777 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
13778 Array_type* ctor_type =
13779 Type::make_array_type(this->element_type_, element_count);
13780 ctor_type->set_is_array_incomparable();
13781 Expression* constructor =
13782 new Fixed_array_construction_expression(ctor_type, NULL,
13783 value_pairs, loc);
13784
13785 this->constructor_temp_ =
13786 Statement::make_temporary(NULL, constructor, loc);
13787 constructor->issue_nil_check();
13788 this->constructor_temp_->set_is_address_taken();
13789 inserter->insert(this->constructor_temp_);
13790 }
13791
13792 return this;
13793 }
13794
13795 // Final type determination.
13796
13797 void
do_determine_type(const Type_context *)13798 Map_construction_expression::do_determine_type(const Type_context*)
13799 {
13800 if (this->vals_ == NULL)
13801 return;
13802
13803 Map_type* mt = this->type_->map_type();
13804 Type_context key_context(mt->key_type(), false);
13805 Type_context val_context(mt->val_type(), false);
13806 for (Expression_list::const_iterator pv = this->vals_->begin();
13807 pv != this->vals_->end();
13808 ++pv)
13809 {
13810 (*pv)->determine_type(&key_context);
13811 ++pv;
13812 (*pv)->determine_type(&val_context);
13813 }
13814 }
13815
13816 // Check types.
13817
13818 void
do_check_types(Gogo *)13819 Map_construction_expression::do_check_types(Gogo*)
13820 {
13821 if (this->vals_ == NULL)
13822 return;
13823
13824 Map_type* mt = this->type_->map_type();
13825 int i = 0;
13826 Type* key_type = mt->key_type();
13827 Type* val_type = mt->val_type();
13828 for (Expression_list::const_iterator pv = this->vals_->begin();
13829 pv != this->vals_->end();
13830 ++pv, ++i)
13831 {
13832 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
13833 {
13834 go_error_at((*pv)->location(),
13835 "incompatible type for element %d key in map construction",
13836 i + 1);
13837 this->set_is_error();
13838 }
13839 ++pv;
13840 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
13841 {
13842 go_error_at((*pv)->location(),
13843 ("incompatible type for element %d value "
13844 "in map construction"),
13845 i + 1);
13846 this->set_is_error();
13847 }
13848 }
13849 }
13850
13851 // Copy.
13852
13853 Expression*
do_copy()13854 Map_construction_expression::do_copy()
13855 {
13856 return new Map_construction_expression(this->type_->copy_expressions(),
13857 (this->vals_ == NULL
13858 ? NULL
13859 : this->vals_->copy()),
13860 this->location());
13861 }
13862
13863 // Return the backend representation for constructing a map.
13864
13865 Bexpression*
do_get_backend(Translate_context * context)13866 Map_construction_expression::do_get_backend(Translate_context* context)
13867 {
13868 if (this->is_error_expression())
13869 return context->backend()->error_expression();
13870 Location loc = this->location();
13871
13872 size_t i = 0;
13873 Expression* ventries;
13874 if (this->vals_ == NULL || this->vals_->empty())
13875 ventries = Expression::make_nil(loc);
13876 else
13877 {
13878 go_assert(this->constructor_temp_ != NULL);
13879 i = this->vals_->size() / 2;
13880
13881 Expression* ctor_ref =
13882 Expression::make_temporary_reference(this->constructor_temp_, loc);
13883 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
13884 }
13885
13886 Map_type* mt = this->type_->map_type();
13887 if (this->element_type_ == NULL)
13888 this->element_type_ =
13889 Type::make_builtin_struct_type(2,
13890 "__key", mt->key_type(),
13891 "__val", mt->val_type());
13892 Expression* descriptor = Expression::make_type_descriptor(mt, loc);
13893
13894 Type* uintptr_t = Type::lookup_integer_type("uintptr");
13895 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
13896
13897 Expression* entry_size =
13898 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
13899
13900 unsigned int field_index;
13901 const Struct_field* valfield =
13902 this->element_type_->find_local_field("__val", &field_index);
13903 Expression* val_offset =
13904 Expression::make_struct_field_offset(this->element_type_, valfield);
13905
13906 Expression* map_ctor =
13907 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 5, descriptor, count,
13908 entry_size, val_offset, ventries);
13909 return map_ctor->get_backend(context);
13910 }
13911
13912 // Export an array construction.
13913
13914 void
do_export(Export_function_body * efb) const13915 Map_construction_expression::do_export(Export_function_body* efb) const
13916 {
13917 efb->write_c_string("$convert(");
13918 efb->write_type(this->type_);
13919 for (Expression_list::const_iterator pv = this->vals_->begin();
13920 pv != this->vals_->end();
13921 ++pv)
13922 {
13923 efb->write_c_string(", ");
13924 (*pv)->export_expression(efb);
13925 }
13926 efb->write_c_string(")");
13927 }
13928
13929 // Dump ast representation for a map construction expression.
13930
13931 void
do_dump_expression(Ast_dump_context * ast_dump_context) const13932 Map_construction_expression::do_dump_expression(
13933 Ast_dump_context* ast_dump_context) const
13934 {
13935 ast_dump_context->ostream() << "{" ;
13936 ast_dump_context->dump_expression_list(this->vals_, true);
13937 ast_dump_context->ostream() << "}";
13938 }
13939
13940 // Class Composite_literal_expression.
13941
13942 // Traversal.
13943
13944 int
do_traverse(Traverse * traverse)13945 Composite_literal_expression::do_traverse(Traverse* traverse)
13946 {
13947 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13948 return TRAVERSE_EXIT;
13949
13950 // If this is a struct composite literal with keys, then the keys
13951 // are field names, not expressions. We don't want to traverse them
13952 // in that case. If we do, we can give an erroneous error "variable
13953 // initializer refers to itself." See bug482.go in the testsuite.
13954 if (this->has_keys_ && this->vals_ != NULL)
13955 {
13956 // The type may not be resolvable at this point.
13957 Type* type = this->type_;
13958
13959 for (int depth = 0; depth < this->depth_; ++depth)
13960 {
13961 if (type->array_type() != NULL)
13962 type = type->array_type()->element_type();
13963 else if (type->map_type() != NULL)
13964 {
13965 if (this->key_path_[depth])
13966 type = type->map_type()->key_type();
13967 else
13968 type = type->map_type()->val_type();
13969 }
13970 else
13971 {
13972 // This error will be reported during lowering.
13973 return TRAVERSE_CONTINUE;
13974 }
13975 }
13976
13977 while (true)
13978 {
13979 if (type->classification() == Type::TYPE_NAMED)
13980 type = type->named_type()->real_type();
13981 else if (type->classification() == Type::TYPE_FORWARD)
13982 {
13983 Type* t = type->forwarded();
13984 if (t == type)
13985 break;
13986 type = t;
13987 }
13988 else
13989 break;
13990 }
13991
13992 if (type->classification() == Type::TYPE_STRUCT)
13993 {
13994 Expression_list::iterator p = this->vals_->begin();
13995 while (p != this->vals_->end())
13996 {
13997 // Skip key.
13998 ++p;
13999 go_assert(p != this->vals_->end());
14000 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
14001 return TRAVERSE_EXIT;
14002 ++p;
14003 }
14004 return TRAVERSE_CONTINUE;
14005 }
14006 }
14007
14008 if (this->vals_ != NULL)
14009 return this->vals_->traverse(traverse);
14010
14011 return TRAVERSE_CONTINUE;
14012 }
14013
14014 // Lower a generic composite literal into a specific version based on
14015 // the type.
14016
14017 Expression*
do_lower(Gogo * gogo,Named_object * function,Statement_inserter * inserter,int)14018 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
14019 Statement_inserter* inserter, int)
14020 {
14021 Type* type = this->type_;
14022
14023 for (int depth = 0; depth < this->depth_; ++depth)
14024 {
14025 type = type->deref();
14026 if (type->array_type() != NULL)
14027 type = type->array_type()->element_type();
14028 else if (type->map_type() != NULL)
14029 {
14030 if (this->key_path_[depth])
14031 type = type->map_type()->key_type();
14032 else
14033 type = type->map_type()->val_type();
14034 }
14035 else
14036 {
14037 if (!type->is_error())
14038 go_error_at(this->location(),
14039 ("may only omit types within composite literals "
14040 "of slice, array, or map type"));
14041 return Expression::make_error(this->location());
14042 }
14043 }
14044
14045 Type *pt = type->points_to();
14046 bool is_pointer = false;
14047 if (pt != NULL)
14048 {
14049 is_pointer = true;
14050 type = pt;
14051 }
14052
14053 Expression* ret;
14054 if (type->is_error())
14055 return Expression::make_error(this->location());
14056 else if (type->struct_type() != NULL)
14057 ret = this->lower_struct(gogo, type);
14058 else if (type->array_type() != NULL)
14059 ret = this->lower_array(type);
14060 else if (type->map_type() != NULL)
14061 ret = this->lower_map(gogo, function, inserter, type);
14062 else
14063 {
14064 go_error_at(this->location(),
14065 ("expected struct, slice, array, or map type "
14066 "for composite literal"));
14067 return Expression::make_error(this->location());
14068 }
14069
14070 if (is_pointer)
14071 ret = Expression::make_heap_expression(ret, this->location());
14072
14073 return ret;
14074 }
14075
14076 // Lower a struct composite literal.
14077
14078 Expression*
lower_struct(Gogo * gogo,Type * type)14079 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
14080 {
14081 Location location = this->location();
14082 Struct_type* st = type->struct_type();
14083 if (this->vals_ == NULL || !this->has_keys_)
14084 {
14085 if (this->vals_ != NULL
14086 && !this->vals_->empty()
14087 && type->named_type() != NULL
14088 && type->named_type()->named_object()->package() != NULL)
14089 {
14090 for (Struct_field_list::const_iterator pf = st->fields()->begin();
14091 pf != st->fields()->end();
14092 ++pf)
14093 {
14094 if (Gogo::is_hidden_name(pf->field_name())
14095 || pf->is_embedded_builtin(gogo))
14096 go_error_at(this->location(),
14097 "assignment of unexported field %qs in %qs literal",
14098 Gogo::message_name(pf->field_name()).c_str(),
14099 type->named_type()->message_name().c_str());
14100 }
14101 }
14102
14103 return new Struct_construction_expression(type, this->vals_, location);
14104 }
14105
14106 size_t field_count = st->field_count();
14107 std::vector<Expression*> vals(field_count);
14108 std::vector<unsigned long>* traverse_order = new(std::vector<unsigned long>);
14109 Expression_list::const_iterator p = this->vals_->begin();
14110 Expression* external_expr = NULL;
14111 const Named_object* external_no = NULL;
14112 while (p != this->vals_->end())
14113 {
14114 Expression* name_expr = *p;
14115
14116 ++p;
14117 go_assert(p != this->vals_->end());
14118 Expression* val = *p;
14119
14120 ++p;
14121
14122 if (name_expr == NULL)
14123 {
14124 go_error_at(val->location(),
14125 "mixture of field and value initializers");
14126 return Expression::make_error(location);
14127 }
14128
14129 bool bad_key = false;
14130 std::string name;
14131 const Named_object* no = NULL;
14132 switch (name_expr->classification())
14133 {
14134 case EXPRESSION_UNKNOWN_REFERENCE:
14135 name = name_expr->unknown_expression()->name();
14136 if (type->named_type() != NULL)
14137 {
14138 // If the named object found for this field name comes from a
14139 // different package than the struct it is a part of, do not count
14140 // this incorrect lookup as a usage of the object's package.
14141 no = name_expr->unknown_expression()->named_object();
14142 if (no->package() != NULL
14143 && no->package() != type->named_type()->named_object()->package())
14144 no->package()->forget_usage(name_expr);
14145 }
14146 break;
14147
14148 case EXPRESSION_CONST_REFERENCE:
14149 no = static_cast<Const_expression*>(name_expr)->named_object();
14150 break;
14151
14152 case EXPRESSION_TYPE:
14153 {
14154 Type* t = name_expr->type();
14155 Named_type* nt = t->named_type();
14156 if (nt == NULL)
14157 bad_key = true;
14158 else
14159 no = nt->named_object();
14160 }
14161 break;
14162
14163 case EXPRESSION_VAR_REFERENCE:
14164 no = name_expr->var_expression()->named_object();
14165 break;
14166
14167 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14168 no = name_expr->enclosed_var_expression()->variable();
14169 break;
14170
14171 case EXPRESSION_FUNC_REFERENCE:
14172 no = name_expr->func_expression()->named_object();
14173 break;
14174
14175 default:
14176 bad_key = true;
14177 break;
14178 }
14179 if (bad_key)
14180 {
14181 go_error_at(name_expr->location(), "expected struct field name");
14182 return Expression::make_error(location);
14183 }
14184
14185 if (no != NULL)
14186 {
14187 if (no->package() != NULL && external_expr == NULL)
14188 {
14189 external_expr = name_expr;
14190 external_no = no;
14191 }
14192
14193 name = no->name();
14194
14195 // A predefined name won't be packed. If it starts with a
14196 // lower case letter we need to check for that case, because
14197 // the field name will be packed. FIXME.
14198 if (!Gogo::is_hidden_name(name)
14199 && name[0] >= 'a'
14200 && name[0] <= 'z')
14201 {
14202 Named_object* gno = gogo->lookup_global(name.c_str());
14203 if (gno == no)
14204 name = gogo->pack_hidden_name(name, false);
14205 }
14206 }
14207
14208 unsigned int index;
14209 const Struct_field* sf = st->find_local_field(name, &index);
14210 if (sf == NULL)
14211 {
14212 go_error_at(name_expr->location(), "unknown field %qs in %qs",
14213 Gogo::message_name(name).c_str(),
14214 (type->named_type() != NULL
14215 ? type->named_type()->message_name().c_str()
14216 : "unnamed struct"));
14217 return Expression::make_error(location);
14218 }
14219 if (vals[index] != NULL)
14220 {
14221 go_error_at(name_expr->location(),
14222 "duplicate value for field %qs in %qs",
14223 Gogo::message_name(name).c_str(),
14224 (type->named_type() != NULL
14225 ? type->named_type()->message_name().c_str()
14226 : "unnamed struct"));
14227 return Expression::make_error(location);
14228 }
14229
14230 if (type->named_type() != NULL
14231 && type->named_type()->named_object()->package() != NULL
14232 && (Gogo::is_hidden_name(sf->field_name())
14233 || sf->is_embedded_builtin(gogo)))
14234 go_error_at(name_expr->location(),
14235 "assignment of unexported field %qs in %qs literal",
14236 Gogo::message_name(sf->field_name()).c_str(),
14237 type->named_type()->message_name().c_str());
14238
14239 vals[index] = val;
14240 traverse_order->push_back(static_cast<unsigned long>(index));
14241 }
14242
14243 if (!this->all_are_names_)
14244 {
14245 // This is a weird case like bug462 in the testsuite.
14246 if (external_expr == NULL)
14247 go_error_at(this->location(), "unknown field in %qs literal",
14248 (type->named_type() != NULL
14249 ? type->named_type()->message_name().c_str()
14250 : "unnamed struct"));
14251 else
14252 go_error_at(external_expr->location(), "unknown field %qs in %qs",
14253 external_no->message_name().c_str(),
14254 (type->named_type() != NULL
14255 ? type->named_type()->message_name().c_str()
14256 : "unnamed struct"));
14257 return Expression::make_error(location);
14258 }
14259
14260 Expression_list* list = new Expression_list;
14261 list->reserve(field_count);
14262 for (size_t i = 0; i < field_count; ++i)
14263 list->push_back(vals[i]);
14264
14265 Struct_construction_expression* ret =
14266 new Struct_construction_expression(type, list, location);
14267 ret->set_traverse_order(traverse_order);
14268 return ret;
14269 }
14270
14271 // Index/value/traversal-order triple.
14272
14273 struct IVT_triple {
14274 unsigned long index;
14275 unsigned long traversal_order;
14276 Expression* expr;
IVT_tripleIVT_triple14277 IVT_triple(unsigned long i, unsigned long to, Expression *e)
14278 : index(i), traversal_order(to), expr(e) { }
operator <IVT_triple14279 bool operator<(const IVT_triple& other) const
14280 { return this->index < other.index; }
14281 };
14282
14283 // Lower an array composite literal.
14284
14285 Expression*
lower_array(Type * type)14286 Composite_literal_expression::lower_array(Type* type)
14287 {
14288 Location location = this->location();
14289 if (this->vals_ == NULL || !this->has_keys_)
14290 return this->make_array(type, NULL, this->vals_);
14291
14292 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
14293 indexes->reserve(this->vals_->size());
14294 bool indexes_out_of_order = false;
14295 Expression_list* vals = new Expression_list();
14296 vals->reserve(this->vals_->size());
14297 unsigned long index = 0;
14298 Expression_list::const_iterator p = this->vals_->begin();
14299 while (p != this->vals_->end())
14300 {
14301 Expression* index_expr = *p;
14302
14303 ++p;
14304 go_assert(p != this->vals_->end());
14305 Expression* val = *p;
14306
14307 ++p;
14308
14309 if (index_expr == NULL)
14310 {
14311 if (std::find(indexes->begin(), indexes->end(), index)
14312 != indexes->end())
14313 {
14314 go_error_at(val->location(),
14315 "duplicate value for index %lu", index);
14316 return Expression::make_error(location);
14317 }
14318 if (!indexes->empty())
14319 indexes->push_back(index);
14320 }
14321 else
14322 {
14323 if (indexes->empty() && !vals->empty())
14324 {
14325 for (size_t i = 0; i < vals->size(); ++i)
14326 indexes->push_back(i);
14327 }
14328
14329 Numeric_constant nc;
14330 if (!index_expr->numeric_constant_value(&nc))
14331 {
14332 go_error_at(index_expr->location(),
14333 "index expression is not integer constant");
14334 return Expression::make_error(location);
14335 }
14336
14337 switch (nc.to_unsigned_long(&index))
14338 {
14339 case Numeric_constant::NC_UL_VALID:
14340 break;
14341 case Numeric_constant::NC_UL_NOTINT:
14342 go_error_at(index_expr->location(),
14343 "index expression is not integer constant");
14344 return Expression::make_error(location);
14345 case Numeric_constant::NC_UL_NEGATIVE:
14346 go_error_at(index_expr->location(),
14347 "index expression is negative");
14348 return Expression::make_error(location);
14349 case Numeric_constant::NC_UL_BIG:
14350 go_error_at(index_expr->location(), "index value overflow");
14351 return Expression::make_error(location);
14352 default:
14353 go_unreachable();
14354 }
14355
14356 Named_type* ntype = Type::lookup_integer_type("int");
14357 Integer_type* inttype = ntype->integer_type();
14358 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
14359 && index >> (inttype->bits() - 1) != 0)
14360 {
14361 go_error_at(index_expr->location(), "index value overflow");
14362 return Expression::make_error(location);
14363 }
14364
14365 if (std::find(indexes->begin(), indexes->end(), index)
14366 != indexes->end())
14367 {
14368 go_error_at(index_expr->location(),
14369 "duplicate value for index %lu",
14370 index);
14371 return Expression::make_error(location);
14372 }
14373
14374 if (!indexes->empty() && index < indexes->back())
14375 indexes_out_of_order = true;
14376
14377 indexes->push_back(index);
14378 }
14379
14380 vals->push_back(val);
14381
14382 ++index;
14383 }
14384
14385 if (indexes->empty())
14386 {
14387 delete indexes;
14388 indexes = NULL;
14389 }
14390
14391 std::vector<unsigned long>* traverse_order = NULL;
14392 if (indexes_out_of_order)
14393 {
14394 typedef std::vector<IVT_triple> V;
14395
14396 V v;
14397 v.reserve(indexes->size());
14398 std::vector<unsigned long>::const_iterator pi = indexes->begin();
14399 unsigned long torder = 0;
14400 for (Expression_list::const_iterator pe = vals->begin();
14401 pe != vals->end();
14402 ++pe, ++pi, ++torder)
14403 v.push_back(IVT_triple(*pi, torder, *pe));
14404
14405 std::sort(v.begin(), v.end());
14406
14407 delete indexes;
14408 delete vals;
14409
14410 indexes = new std::vector<unsigned long>();
14411 indexes->reserve(v.size());
14412 vals = new Expression_list();
14413 vals->reserve(v.size());
14414 traverse_order = new std::vector<unsigned long>();
14415 traverse_order->reserve(v.size());
14416
14417 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
14418 {
14419 indexes->push_back(p->index);
14420 vals->push_back(p->expr);
14421 traverse_order->push_back(p->traversal_order);
14422 }
14423 }
14424
14425 Expression* ret = this->make_array(type, indexes, vals);
14426 Array_construction_expression* ace = ret->array_literal();
14427 if (ace != NULL && traverse_order != NULL)
14428 ace->set_traverse_order(traverse_order);
14429 return ret;
14430 }
14431
14432 // Actually build the array composite literal. This handles
14433 // [...]{...}.
14434
14435 Expression*
make_array(Type * type,const std::vector<unsigned long> * indexes,Expression_list * vals)14436 Composite_literal_expression::make_array(
14437 Type* type,
14438 const std::vector<unsigned long>* indexes,
14439 Expression_list* vals)
14440 {
14441 Location location = this->location();
14442 Array_type* at = type->array_type();
14443
14444 if (at->length() != NULL && at->length()->is_nil_expression())
14445 {
14446 size_t size;
14447 if (vals == NULL)
14448 size = 0;
14449 else if (indexes != NULL)
14450 size = indexes->back() + 1;
14451 else
14452 {
14453 size = vals->size();
14454 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
14455 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
14456 && size >> (it->bits() - 1) != 0)
14457 {
14458 go_error_at(location, "too many elements in composite literal");
14459 return Expression::make_error(location);
14460 }
14461 }
14462
14463 Expression* elen = Expression::make_integer_ul(size, NULL, location);
14464 at = Type::make_array_type(at->element_type(), elen);
14465 type = at;
14466 }
14467 else if (at->length() != NULL
14468 && !at->length()->is_error_expression()
14469 && this->vals_ != NULL)
14470 {
14471 Numeric_constant nc;
14472 unsigned long val;
14473 if (at->length()->numeric_constant_value(&nc)
14474 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
14475 {
14476 if (indexes == NULL)
14477 {
14478 if (this->vals_->size() > val)
14479 {
14480 go_error_at(location,
14481 "too many elements in composite literal");
14482 return Expression::make_error(location);
14483 }
14484 }
14485 else
14486 {
14487 unsigned long max = indexes->back();
14488 if (max >= val)
14489 {
14490 go_error_at(location,
14491 ("some element keys in composite literal "
14492 "are out of range"));
14493 return Expression::make_error(location);
14494 }
14495 }
14496 }
14497 }
14498
14499 if (at->length() != NULL)
14500 return new Fixed_array_construction_expression(type, indexes, vals,
14501 location);
14502 else
14503 return new Slice_construction_expression(type, indexes, vals, location);
14504 }
14505
14506 // Lower a map composite literal.
14507
14508 Expression*
lower_map(Gogo * gogo,Named_object * function,Statement_inserter * inserter,Type * type)14509 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
14510 Statement_inserter* inserter,
14511 Type* type)
14512 {
14513 Location location = this->location();
14514 Unordered_map(unsigned int, std::vector<Expression*>) st;
14515 Unordered_map(unsigned int, std::vector<Expression*>) nt;
14516 if (this->vals_ != NULL)
14517 {
14518 if (!this->has_keys_)
14519 {
14520 go_error_at(location, "map composite literal must have keys");
14521 return Expression::make_error(location);
14522 }
14523
14524 for (Expression_list::iterator p = this->vals_->begin();
14525 p != this->vals_->end();
14526 p += 2)
14527 {
14528 if (*p == NULL)
14529 {
14530 ++p;
14531 go_error_at((*p)->location(),
14532 ("map composite literal must "
14533 "have keys for every value"));
14534 return Expression::make_error(location);
14535 }
14536 // Make sure we have lowered the key; it may not have been
14537 // lowered in order to handle keys for struct composite
14538 // literals. Lower it now to get the right error message.
14539 if ((*p)->unknown_expression() != NULL)
14540 {
14541 (*p)->unknown_expression()->clear_is_composite_literal_key();
14542 gogo->lower_expression(function, inserter, &*p);
14543 go_assert((*p)->is_error_expression());
14544 return Expression::make_error(location);
14545 }
14546 // Check if there are duplicate constant keys.
14547 if (!(*p)->is_constant())
14548 continue;
14549 std::string sval;
14550 Numeric_constant nval;
14551 if ((*p)->string_constant_value(&sval)) // Check string keys.
14552 {
14553 unsigned int h = Gogo::hash_string(sval, 0);
14554 // Search the index h in the hash map.
14555 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
14556 mit = st.find(h);
14557 if (mit == st.end())
14558 {
14559 // No duplicate since h is a new index.
14560 // Create a new vector indexed by h and add it to the hash map.
14561 std::vector<Expression*> l;
14562 l.push_back(*p);
14563 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
14564 st.insert(val);
14565 }
14566 else
14567 {
14568 // Do further check since index h already exists.
14569 for (std::vector<Expression*>::iterator lit =
14570 mit->second.begin();
14571 lit != mit->second.end();
14572 lit++)
14573 {
14574 std::string s;
14575 bool ok = (*lit)->string_constant_value(&s);
14576 go_assert(ok);
14577 if (s == sval)
14578 {
14579 go_error_at((*p)->location(), ("duplicate key "
14580 "in map literal"));
14581 return Expression::make_error(location);
14582 }
14583 }
14584 // Add this new string key to the vector indexed by h.
14585 mit->second.push_back(*p);
14586 }
14587 }
14588 else if ((*p)->numeric_constant_value(&nval)) // Check numeric keys.
14589 {
14590 unsigned int h = nval.hash(0);
14591 Unordered_map(unsigned int, std::vector<Expression*>)::iterator mit;
14592 mit = nt.find(h);
14593 if (mit == nt.end())
14594 {
14595 // No duplicate since h is a new code.
14596 // Create a new vector indexed by h and add it to the hash map.
14597 std::vector<Expression*> l;
14598 l.push_back(*p);
14599 std::pair<unsigned int, std::vector<Expression*> > val(h, l);
14600 nt.insert(val);
14601 }
14602 else
14603 {
14604 // Do further check since h already exists.
14605 for (std::vector<Expression*>::iterator lit =
14606 mit->second.begin();
14607 lit != mit->second.end();
14608 lit++)
14609 {
14610 Numeric_constant rval;
14611 bool ok = (*lit)->numeric_constant_value(&rval);
14612 go_assert(ok);
14613 if (nval.equals(rval))
14614 {
14615 go_error_at((*p)->location(),
14616 "duplicate key in map literal");
14617 return Expression::make_error(location);
14618 }
14619 }
14620 // Add this new numeric key to the vector indexed by h.
14621 mit->second.push_back(*p);
14622 }
14623 }
14624 }
14625 }
14626
14627 return new Map_construction_expression(type, this->vals_, location);
14628 }
14629
14630 // Copy.
14631
14632 Expression*
do_copy()14633 Composite_literal_expression::do_copy()
14634 {
14635 Composite_literal_expression* ret =
14636 new Composite_literal_expression(this->type_->copy_expressions(),
14637 this->depth_, this->has_keys_,
14638 (this->vals_ == NULL
14639 ? NULL
14640 : this->vals_->copy()),
14641 this->all_are_names_,
14642 this->location());
14643 ret->key_path_ = this->key_path_;
14644 return ret;
14645 }
14646
14647 // Dump ast representation for a composite literal expression.
14648
14649 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14650 Composite_literal_expression::do_dump_expression(
14651 Ast_dump_context* ast_dump_context) const
14652 {
14653 ast_dump_context->ostream() << "composite(";
14654 ast_dump_context->dump_type(this->type_);
14655 ast_dump_context->ostream() << ", {";
14656 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
14657 ast_dump_context->ostream() << "})";
14658 }
14659
14660 // Make a composite literal expression.
14661
14662 Expression*
make_composite_literal(Type * type,int depth,bool has_keys,Expression_list * vals,bool all_are_names,Location location)14663 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
14664 Expression_list* vals, bool all_are_names,
14665 Location location)
14666 {
14667 return new Composite_literal_expression(type, depth, has_keys, vals,
14668 all_are_names, location);
14669 }
14670
14671 // Return whether this expression is a composite literal.
14672
14673 bool
is_composite_literal() const14674 Expression::is_composite_literal() const
14675 {
14676 switch (this->classification_)
14677 {
14678 case EXPRESSION_COMPOSITE_LITERAL:
14679 case EXPRESSION_STRUCT_CONSTRUCTION:
14680 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14681 case EXPRESSION_SLICE_CONSTRUCTION:
14682 case EXPRESSION_MAP_CONSTRUCTION:
14683 return true;
14684 default:
14685 return false;
14686 }
14687 }
14688
14689 // Return whether this expression is a composite literal which is not
14690 // constant.
14691
14692 bool
is_nonconstant_composite_literal() const14693 Expression::is_nonconstant_composite_literal() const
14694 {
14695 switch (this->classification_)
14696 {
14697 case EXPRESSION_STRUCT_CONSTRUCTION:
14698 {
14699 const Struct_construction_expression *psce =
14700 static_cast<const Struct_construction_expression*>(this);
14701 return !psce->is_constant_struct();
14702 }
14703 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
14704 {
14705 const Fixed_array_construction_expression *pace =
14706 static_cast<const Fixed_array_construction_expression*>(this);
14707 return !pace->is_constant_array();
14708 }
14709 case EXPRESSION_SLICE_CONSTRUCTION:
14710 {
14711 const Slice_construction_expression *pace =
14712 static_cast<const Slice_construction_expression*>(this);
14713 return !pace->is_constant_array();
14714 }
14715 case EXPRESSION_MAP_CONSTRUCTION:
14716 return true;
14717 default:
14718 return false;
14719 }
14720 }
14721
14722 // Return true if this is a variable or temporary_variable.
14723
14724 bool
is_variable() const14725 Expression::is_variable() const
14726 {
14727 switch (this->classification_)
14728 {
14729 case EXPRESSION_VAR_REFERENCE:
14730 case EXPRESSION_TEMPORARY_REFERENCE:
14731 case EXPRESSION_SET_AND_USE_TEMPORARY:
14732 case EXPRESSION_ENCLOSED_VAR_REFERENCE:
14733 return true;
14734 default:
14735 return false;
14736 }
14737 }
14738
14739 // Return true if this is a reference to a local variable.
14740
14741 bool
is_local_variable() const14742 Expression::is_local_variable() const
14743 {
14744 const Var_expression* ve = this->var_expression();
14745 if (ve == NULL)
14746 return false;
14747 const Named_object* no = ve->named_object();
14748 return (no->is_result_variable()
14749 || (no->is_variable() && !no->var_value()->is_global()));
14750 }
14751
14752 // Class Type_guard_expression.
14753
14754 // Traversal.
14755
14756 int
do_traverse(Traverse * traverse)14757 Type_guard_expression::do_traverse(Traverse* traverse)
14758 {
14759 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
14760 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14761 return TRAVERSE_EXIT;
14762 return TRAVERSE_CONTINUE;
14763 }
14764
14765 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)14766 Type_guard_expression::do_flatten(Gogo*, Named_object*,
14767 Statement_inserter* inserter)
14768 {
14769 if (this->expr_->is_error_expression()
14770 || this->expr_->type()->is_error_type())
14771 {
14772 go_assert(saw_errors());
14773 return Expression::make_error(this->location());
14774 }
14775
14776 if (!this->expr_->is_variable())
14777 {
14778 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
14779 this->location());
14780 inserter->insert(temp);
14781 this->expr_ =
14782 Expression::make_temporary_reference(temp, this->location());
14783 }
14784 return this;
14785 }
14786
14787 // Check types of a type guard expression. The expression must have
14788 // an interface type, but the actual type conversion is checked at run
14789 // time.
14790
14791 void
do_check_types(Gogo *)14792 Type_guard_expression::do_check_types(Gogo*)
14793 {
14794 Type* expr_type = this->expr_->type();
14795 if (expr_type->interface_type() == NULL)
14796 {
14797 if (!expr_type->is_error() && !this->type_->is_error())
14798 this->report_error(_("type assertion only valid for interface types"));
14799 this->set_is_error();
14800 }
14801 else if (this->type_->interface_type() == NULL)
14802 {
14803 std::string reason;
14804 if (!expr_type->interface_type()->implements_interface(this->type_,
14805 &reason))
14806 {
14807 if (!this->type_->is_error())
14808 {
14809 if (reason.empty())
14810 this->report_error(_("impossible type assertion: "
14811 "type does not implement interface"));
14812 else
14813 go_error_at(this->location(),
14814 ("impossible type assertion: "
14815 "type does not implement interface (%s)"),
14816 reason.c_str());
14817 }
14818 this->set_is_error();
14819 }
14820 }
14821 }
14822
14823 // Copy.
14824
14825 Expression*
do_copy()14826 Type_guard_expression::do_copy()
14827 {
14828 return new Type_guard_expression(this->expr_->copy(),
14829 this->type_->copy_expressions(),
14830 this->location());
14831 }
14832
14833 // Return the backend representation for a type guard expression.
14834
14835 Bexpression*
do_get_backend(Translate_context * context)14836 Type_guard_expression::do_get_backend(Translate_context* context)
14837 {
14838 Expression* conversion;
14839 if (this->type_->interface_type() != NULL)
14840 conversion =
14841 Expression::convert_interface_to_interface(this->type_, this->expr_,
14842 true, this->location());
14843 else
14844 conversion =
14845 Expression::convert_for_assignment(context->gogo(), this->type_,
14846 this->expr_, this->location());
14847
14848 Gogo* gogo = context->gogo();
14849 Btype* bt = this->type_->get_backend(gogo);
14850 Bexpression* bexpr = conversion->get_backend(context);
14851 return gogo->backend()->convert_expression(bt, bexpr, this->location());
14852 }
14853
14854 // Dump ast representation for a type guard expression.
14855
14856 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14857 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
14858 const
14859 {
14860 this->expr_->dump_expression(ast_dump_context);
14861 ast_dump_context->ostream() << ".";
14862 ast_dump_context->dump_type(this->type_);
14863 }
14864
14865 // Make a type guard expression.
14866
14867 Expression*
make_type_guard(Expression * expr,Type * type,Location location)14868 Expression::make_type_guard(Expression* expr, Type* type,
14869 Location location)
14870 {
14871 return new Type_guard_expression(expr, type, location);
14872 }
14873
14874 // Class Heap_expression.
14875
14876 // Return the type of the expression stored on the heap.
14877
14878 Type*
do_type()14879 Heap_expression::do_type()
14880 { return Type::make_pointer_type(this->expr_->type()); }
14881
14882 // Return the backend representation for allocating an expression on the heap.
14883
14884 Bexpression*
do_get_backend(Translate_context * context)14885 Heap_expression::do_get_backend(Translate_context* context)
14886 {
14887 Type* etype = this->expr_->type();
14888 if (this->expr_->is_error_expression() || etype->is_error())
14889 return context->backend()->error_expression();
14890
14891 Location loc = this->location();
14892 Gogo* gogo = context->gogo();
14893 Btype* btype = this->type()->get_backend(gogo);
14894
14895 Expression* alloc = Expression::make_allocation(etype, loc);
14896 if (this->allocate_on_stack_)
14897 alloc->allocation_expression()->set_allocate_on_stack();
14898 Bexpression* space = alloc->get_backend(context);
14899
14900 Bstatement* decl;
14901 Named_object* fn = context->function();
14902 go_assert(fn != NULL);
14903 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
14904 Bvariable* space_temp =
14905 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
14906 space, true, loc, &decl);
14907 Btype* expr_btype = etype->get_backend(gogo);
14908
14909 Bexpression* bexpr = this->expr_->get_backend(context);
14910
14911 // If this assignment needs a write barrier, call typedmemmove. We
14912 // don't do this in the write barrier pass because in some cases
14913 // backend conversion can introduce new Heap_expression values.
14914 Bstatement* assn;
14915 if (!etype->has_pointer() || this->allocate_on_stack_)
14916 {
14917 space = gogo->backend()->var_expression(space_temp, loc);
14918 Bexpression* ref =
14919 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
14920 assn = gogo->backend()->assignment_statement(fndecl, ref, bexpr, loc);
14921 }
14922 else
14923 {
14924 Bstatement* edecl;
14925 Bvariable* btemp =
14926 gogo->backend()->temporary_variable(fndecl, context->bblock(),
14927 expr_btype, bexpr, true, loc,
14928 &edecl);
14929 Bexpression* btempref = gogo->backend()->var_expression(btemp,
14930 loc);
14931 Bexpression* addr = gogo->backend()->address_expression(btempref, loc);
14932
14933 Expression* td = Expression::make_type_descriptor(etype, loc);
14934 Type* etype_ptr = Type::make_pointer_type(etype);
14935 space = gogo->backend()->var_expression(space_temp, loc);
14936 Expression* elhs = Expression::make_backend(space, etype_ptr, loc);
14937 Expression* erhs = Expression::make_backend(addr, etype_ptr, loc);
14938 Expression* call = Runtime::make_call(Runtime::TYPEDMEMMOVE, loc, 3,
14939 td, elhs, erhs);
14940 Bexpression* bcall = call->get_backend(context);
14941 Bstatement* s = gogo->backend()->expression_statement(fndecl, bcall);
14942 assn = gogo->backend()->compound_statement(edecl, s);
14943 }
14944 decl = gogo->backend()->compound_statement(decl, assn);
14945 space = gogo->backend()->var_expression(space_temp, loc);
14946 return gogo->backend()->compound_expression(decl, space, loc);
14947 }
14948
14949 // Dump ast representation for a heap expression.
14950
14951 void
do_dump_expression(Ast_dump_context * ast_dump_context) const14952 Heap_expression::do_dump_expression(
14953 Ast_dump_context* ast_dump_context) const
14954 {
14955 ast_dump_context->ostream() << "&(";
14956 ast_dump_context->dump_expression(this->expr_);
14957 ast_dump_context->ostream() << ")";
14958 }
14959
14960 // Allocate an expression on the heap.
14961
14962 Expression*
make_heap_expression(Expression * expr,Location location)14963 Expression::make_heap_expression(Expression* expr, Location location)
14964 {
14965 return new Heap_expression(expr, location);
14966 }
14967
14968 // Class Receive_expression.
14969
14970 // Return the type of a receive expression.
14971
14972 Type*
do_type()14973 Receive_expression::do_type()
14974 {
14975 if (this->is_error_expression())
14976 return Type::make_error_type();
14977 Channel_type* channel_type = this->channel_->type()->channel_type();
14978 if (channel_type == NULL)
14979 {
14980 this->report_error(_("expected channel"));
14981 return Type::make_error_type();
14982 }
14983 return channel_type->element_type();
14984 }
14985
14986 // Check types for a receive expression.
14987
14988 void
do_check_types(Gogo *)14989 Receive_expression::do_check_types(Gogo*)
14990 {
14991 Type* type = this->channel_->type();
14992 if (type->is_error())
14993 {
14994 go_assert(saw_errors());
14995 this->set_is_error();
14996 return;
14997 }
14998 if (type->channel_type() == NULL)
14999 {
15000 this->report_error(_("expected channel"));
15001 return;
15002 }
15003 if (!type->channel_type()->may_receive())
15004 {
15005 this->report_error(_("invalid receive on send-only channel"));
15006 return;
15007 }
15008 }
15009
15010 // Flattening for receive expressions creates a temporary variable to store
15011 // received data in for receives.
15012
15013 Expression*
do_flatten(Gogo *,Named_object *,Statement_inserter * inserter)15014 Receive_expression::do_flatten(Gogo*, Named_object*,
15015 Statement_inserter* inserter)
15016 {
15017 Channel_type* channel_type = this->channel_->type()->channel_type();
15018 if (channel_type == NULL)
15019 {
15020 go_assert(saw_errors());
15021 return this;
15022 }
15023 else if (this->channel_->is_error_expression())
15024 {
15025 go_assert(saw_errors());
15026 return Expression::make_error(this->location());
15027 }
15028
15029 Type* element_type = channel_type->element_type();
15030 if (this->temp_receiver_ == NULL)
15031 {
15032 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
15033 this->location());
15034 this->temp_receiver_->set_is_address_taken();
15035 inserter->insert(this->temp_receiver_);
15036 }
15037
15038 return this;
15039 }
15040
15041 // Get the backend representation for a receive expression.
15042
15043 Bexpression*
do_get_backend(Translate_context * context)15044 Receive_expression::do_get_backend(Translate_context* context)
15045 {
15046 Location loc = this->location();
15047
15048 Channel_type* channel_type = this->channel_->type()->channel_type();
15049 if (channel_type == NULL)
15050 {
15051 go_assert(this->channel_->type()->is_error());
15052 return context->backend()->error_expression();
15053 }
15054
15055 Expression* recv_ref =
15056 Expression::make_temporary_reference(this->temp_receiver_, loc);
15057 Expression* recv_addr =
15058 Expression::make_temporary_reference(this->temp_receiver_, loc);
15059 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
15060 Expression* recv = Runtime::make_call(Runtime::CHANRECV1, loc, 2,
15061 this->channel_, recv_addr);
15062 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
15063 }
15064
15065 // Dump ast representation for a receive expression.
15066
15067 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15068 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
15069 {
15070 ast_dump_context->ostream() << " <- " ;
15071 ast_dump_context->dump_expression(channel_);
15072 }
15073
15074 // Make a receive expression.
15075
15076 Receive_expression*
make_receive(Expression * channel,Location location)15077 Expression::make_receive(Expression* channel, Location location)
15078 {
15079 return new Receive_expression(channel, location);
15080 }
15081
15082 // An expression which evaluates to a pointer to the type descriptor
15083 // of a type.
15084
15085 class Type_descriptor_expression : public Expression
15086 {
15087 public:
Type_descriptor_expression(Type * type,Location location)15088 Type_descriptor_expression(Type* type, Location location)
15089 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
15090 type_(type)
15091 { }
15092
15093 protected:
15094 int
15095 do_traverse(Traverse*);
15096
15097 Type*
do_type()15098 do_type()
15099 { return Type::make_type_descriptor_ptr_type(); }
15100
15101 bool
do_is_static_initializer() const15102 do_is_static_initializer() const
15103 { return true; }
15104
15105 void
do_determine_type(const Type_context *)15106 do_determine_type(const Type_context*)
15107 { }
15108
15109 Expression*
do_copy()15110 do_copy()
15111 { return this; }
15112
15113 Bexpression*
do_get_backend(Translate_context * context)15114 do_get_backend(Translate_context* context)
15115 {
15116 return this->type_->type_descriptor_pointer(context->gogo(),
15117 this->location());
15118 }
15119
15120 void
15121 do_dump_expression(Ast_dump_context*) const;
15122
15123 private:
15124 // The type for which this is the descriptor.
15125 Type* type_;
15126 };
15127
15128 int
do_traverse(Traverse * traverse)15129 Type_descriptor_expression::do_traverse(Traverse* traverse)
15130 {
15131 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15132 return TRAVERSE_EXIT;
15133 return TRAVERSE_CONTINUE;
15134 }
15135
15136 // Dump ast representation for a type descriptor expression.
15137
15138 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15139 Type_descriptor_expression::do_dump_expression(
15140 Ast_dump_context* ast_dump_context) const
15141 {
15142 ast_dump_context->dump_type(this->type_);
15143 }
15144
15145 // Make a type descriptor expression.
15146
15147 Expression*
make_type_descriptor(Type * type,Location location)15148 Expression::make_type_descriptor(Type* type, Location location)
15149 {
15150 return new Type_descriptor_expression(type, location);
15151 }
15152
15153 // An expression which evaluates to a pointer to the Garbage Collection symbol
15154 // of a type.
15155
15156 class GC_symbol_expression : public Expression
15157 {
15158 public:
GC_symbol_expression(Type * type)15159 GC_symbol_expression(Type* type)
15160 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
15161 type_(type)
15162 {}
15163
15164 protected:
15165 Type*
do_type()15166 do_type()
15167 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
15168
15169 bool
do_is_static_initializer() const15170 do_is_static_initializer() const
15171 { return true; }
15172
15173 void
do_determine_type(const Type_context *)15174 do_determine_type(const Type_context*)
15175 { }
15176
15177 Expression*
do_copy()15178 do_copy()
15179 { return this; }
15180
15181 Bexpression*
do_get_backend(Translate_context * context)15182 do_get_backend(Translate_context* context)
15183 { return this->type_->gc_symbol_pointer(context->gogo()); }
15184
15185 void
15186 do_dump_expression(Ast_dump_context*) const;
15187
15188 private:
15189 // The type which this gc symbol describes.
15190 Type* type_;
15191 };
15192
15193 // Dump ast representation for a gc symbol expression.
15194
15195 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15196 GC_symbol_expression::do_dump_expression(
15197 Ast_dump_context* ast_dump_context) const
15198 {
15199 ast_dump_context->ostream() << "gcdata(";
15200 ast_dump_context->dump_type(this->type_);
15201 ast_dump_context->ostream() << ")";
15202 }
15203
15204 // Make a gc symbol expression.
15205
15206 Expression*
make_gc_symbol(Type * type)15207 Expression::make_gc_symbol(Type* type)
15208 {
15209 return new GC_symbol_expression(type);
15210 }
15211
15212 // An expression that evaluates to a pointer to a symbol holding the
15213 // ptrmask data of a type.
15214
15215 class Ptrmask_symbol_expression : public Expression
15216 {
15217 public:
Ptrmask_symbol_expression(Type * type)15218 Ptrmask_symbol_expression(Type* type)
15219 : Expression(EXPRESSION_PTRMASK_SYMBOL, Linemap::predeclared_location()),
15220 type_(type)
15221 {}
15222
15223 protected:
15224 Type*
do_type()15225 do_type()
15226 { return Type::make_pointer_type(Type::lookup_integer_type("uint8")); }
15227
15228 bool
do_is_static_initializer() const15229 do_is_static_initializer() const
15230 { return true; }
15231
15232 void
do_determine_type(const Type_context *)15233 do_determine_type(const Type_context*)
15234 { }
15235
15236 Expression*
do_copy()15237 do_copy()
15238 { return this; }
15239
15240 Bexpression*
15241 do_get_backend(Translate_context*);
15242
15243 void
15244 do_dump_expression(Ast_dump_context*) const;
15245
15246 private:
15247 // The type that this ptrmask symbol describes.
15248 Type* type_;
15249 };
15250
15251 // Return the ptrmask variable.
15252
15253 Bexpression*
do_get_backend(Translate_context * context)15254 Ptrmask_symbol_expression::do_get_backend(Translate_context* context)
15255 {
15256 Gogo* gogo = context->gogo();
15257
15258 // If this type does not need a gcprog, then we can use the standard
15259 // GC symbol.
15260 int64_t ptrsize, ptrdata;
15261 if (!this->type_->needs_gcprog(gogo, &ptrsize, &ptrdata))
15262 return this->type_->gc_symbol_pointer(gogo);
15263
15264 // Otherwise we have to build a ptrmask variable, and return a
15265 // pointer to it.
15266
15267 Bvariable* bvar = this->type_->gc_ptrmask_var(gogo, ptrsize, ptrdata);
15268 Location bloc = Linemap::predeclared_location();
15269 Bexpression* bref = gogo->backend()->var_expression(bvar, bloc);
15270 Bexpression* baddr = gogo->backend()->address_expression(bref, bloc);
15271
15272 Type* uint8_type = Type::lookup_integer_type("uint8");
15273 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
15274 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
15275 return gogo->backend()->convert_expression(ubtype, baddr, bloc);
15276 }
15277
15278 // Dump AST for a ptrmask symbol expression.
15279
15280 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15281 Ptrmask_symbol_expression::do_dump_expression(
15282 Ast_dump_context* ast_dump_context) const
15283 {
15284 ast_dump_context->ostream() << "ptrmask(";
15285 ast_dump_context->dump_type(this->type_);
15286 ast_dump_context->ostream() << ")";
15287 }
15288
15289 // Make a ptrmask symbol expression.
15290
15291 Expression*
make_ptrmask_symbol(Type * type)15292 Expression::make_ptrmask_symbol(Type* type)
15293 {
15294 return new Ptrmask_symbol_expression(type);
15295 }
15296
15297 // An expression which evaluates to some characteristic of a type.
15298 // This is only used to initialize fields of a type descriptor. Using
15299 // a new expression class is slightly inefficient but gives us a good
15300 // separation between the frontend and the middle-end with regard to
15301 // how types are laid out.
15302
15303 class Type_info_expression : public Expression
15304 {
15305 public:
Type_info_expression(Type * type,Type_info type_info)15306 Type_info_expression(Type* type, Type_info type_info)
15307 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
15308 type_(type), type_info_(type_info)
15309 { }
15310
15311 protected:
15312 bool
do_is_static_initializer() const15313 do_is_static_initializer() const
15314 { return true; }
15315
15316 Type*
15317 do_type();
15318
15319 void
do_determine_type(const Type_context *)15320 do_determine_type(const Type_context*)
15321 { }
15322
15323 Expression*
do_copy()15324 do_copy()
15325 { return this; }
15326
15327 Bexpression*
15328 do_get_backend(Translate_context* context);
15329
15330 void
15331 do_dump_expression(Ast_dump_context*) const;
15332
15333 private:
15334 // The type for which we are getting information.
15335 Type* type_;
15336 // What information we want.
15337 Type_info type_info_;
15338 };
15339
15340 // The type is chosen to match what the type descriptor struct
15341 // expects.
15342
15343 Type*
do_type()15344 Type_info_expression::do_type()
15345 {
15346 switch (this->type_info_)
15347 {
15348 case TYPE_INFO_SIZE:
15349 case TYPE_INFO_BACKEND_PTRDATA:
15350 case TYPE_INFO_DESCRIPTOR_PTRDATA:
15351 return Type::lookup_integer_type("uintptr");
15352 case TYPE_INFO_ALIGNMENT:
15353 case TYPE_INFO_FIELD_ALIGNMENT:
15354 return Type::lookup_integer_type("uint8");
15355 default:
15356 go_unreachable();
15357 }
15358 }
15359
15360 // Return the backend representation for type information.
15361
15362 Bexpression*
do_get_backend(Translate_context * context)15363 Type_info_expression::do_get_backend(Translate_context* context)
15364 {
15365 Gogo* gogo = context->gogo();
15366 bool ok = true;
15367 int64_t val;
15368 switch (this->type_info_)
15369 {
15370 case TYPE_INFO_SIZE:
15371 ok = this->type_->backend_type_size(gogo, &val);
15372 break;
15373 case TYPE_INFO_ALIGNMENT:
15374 ok = this->type_->backend_type_align(gogo, &val);
15375 break;
15376 case TYPE_INFO_FIELD_ALIGNMENT:
15377 ok = this->type_->backend_type_field_align(gogo, &val);
15378 break;
15379 case TYPE_INFO_BACKEND_PTRDATA:
15380 ok = this->type_->backend_type_ptrdata(gogo, &val);
15381 break;
15382 case TYPE_INFO_DESCRIPTOR_PTRDATA:
15383 ok = this->type_->descriptor_ptrdata(gogo, &val);
15384 break;
15385 default:
15386 go_unreachable();
15387 }
15388 if (!ok)
15389 {
15390 go_assert(saw_errors());
15391 return gogo->backend()->error_expression();
15392 }
15393 Expression* e = Expression::make_integer_int64(val, this->type(),
15394 this->location());
15395 return e->get_backend(context);
15396 }
15397
15398 // Dump ast representation for a type info expression.
15399
15400 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15401 Type_info_expression::do_dump_expression(
15402 Ast_dump_context* ast_dump_context) const
15403 {
15404 ast_dump_context->ostream() << "typeinfo(";
15405 ast_dump_context->dump_type(this->type_);
15406 ast_dump_context->ostream() << ",";
15407 ast_dump_context->ostream() <<
15408 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
15409 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
15410 : this->type_info_ == TYPE_INFO_SIZE ? "size"
15411 : this->type_info_ == TYPE_INFO_BACKEND_PTRDATA ? "backend_ptrdata"
15412 : this->type_info_ == TYPE_INFO_DESCRIPTOR_PTRDATA ? "descriptor_ptrdata"
15413 : "unknown");
15414 ast_dump_context->ostream() << ")";
15415 }
15416
15417 // Make a type info expression.
15418
15419 Expression*
make_type_info(Type * type,Type_info type_info)15420 Expression::make_type_info(Type* type, Type_info type_info)
15421 {
15422 return new Type_info_expression(type, type_info);
15423 }
15424
15425 // An expression that evaluates to some characteristic of a slice.
15426 // This is used when indexing, bound-checking, or nil checking a slice.
15427
15428 class Slice_info_expression : public Expression
15429 {
15430 public:
Slice_info_expression(Expression * slice,Slice_info slice_info,Location location)15431 Slice_info_expression(Expression* slice, Slice_info slice_info,
15432 Location location)
15433 : Expression(EXPRESSION_SLICE_INFO, location),
15434 slice_(slice), slice_info_(slice_info)
15435 { }
15436
15437 protected:
15438 Type*
15439 do_type();
15440
15441 void
do_determine_type(const Type_context *)15442 do_determine_type(const Type_context*)
15443 { }
15444
15445 Expression*
do_copy()15446 do_copy()
15447 {
15448 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
15449 this->location());
15450 }
15451
15452 Bexpression*
15453 do_get_backend(Translate_context* context);
15454
15455 void
15456 do_dump_expression(Ast_dump_context*) const;
15457
15458 void
do_issue_nil_check()15459 do_issue_nil_check()
15460 { this->slice_->issue_nil_check(); }
15461
15462 private:
15463 // The slice for which we are getting information.
15464 Expression* slice_;
15465 // What information we want.
15466 Slice_info slice_info_;
15467 };
15468
15469 // Return the type of the slice info.
15470
15471 Type*
do_type()15472 Slice_info_expression::do_type()
15473 {
15474 switch (this->slice_info_)
15475 {
15476 case SLICE_INFO_VALUE_POINTER:
15477 return Type::make_pointer_type(
15478 this->slice_->type()->array_type()->element_type());
15479 case SLICE_INFO_LENGTH:
15480 case SLICE_INFO_CAPACITY:
15481 return Type::lookup_integer_type("int");
15482 default:
15483 go_unreachable();
15484 }
15485 }
15486
15487 // Return the backend information for slice information.
15488
15489 Bexpression*
do_get_backend(Translate_context * context)15490 Slice_info_expression::do_get_backend(Translate_context* context)
15491 {
15492 Gogo* gogo = context->gogo();
15493 Bexpression* bslice = this->slice_->get_backend(context);
15494 switch (this->slice_info_)
15495 {
15496 case SLICE_INFO_VALUE_POINTER:
15497 case SLICE_INFO_LENGTH:
15498 case SLICE_INFO_CAPACITY:
15499 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
15500 this->location());
15501 break;
15502 default:
15503 go_unreachable();
15504 }
15505 }
15506
15507 // Dump ast representation for a type info expression.
15508
15509 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15510 Slice_info_expression::do_dump_expression(
15511 Ast_dump_context* ast_dump_context) const
15512 {
15513 ast_dump_context->ostream() << "sliceinfo(";
15514 this->slice_->dump_expression(ast_dump_context);
15515 ast_dump_context->ostream() << ",";
15516 ast_dump_context->ostream() <<
15517 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
15518 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
15519 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
15520 : "unknown");
15521 ast_dump_context->ostream() << ")";
15522 }
15523
15524 // Make a slice info expression.
15525
15526 Expression*
make_slice_info(Expression * slice,Slice_info slice_info,Location location)15527 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
15528 Location location)
15529 {
15530 return new Slice_info_expression(slice, slice_info, location);
15531 }
15532
15533 // Class Slice_value_expression.
15534
15535 int
do_traverse(Traverse * traverse)15536 Slice_value_expression::do_traverse(Traverse* traverse)
15537 {
15538 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
15539 || Expression::traverse(&this->valmem_, traverse) == TRAVERSE_EXIT
15540 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
15541 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
15542 return TRAVERSE_EXIT;
15543 return TRAVERSE_CONTINUE;
15544 }
15545
15546 Expression*
do_copy()15547 Slice_value_expression::do_copy()
15548 {
15549 return new Slice_value_expression(this->type_->copy_expressions(),
15550 this->valmem_->copy(),
15551 this->len_->copy(), this->cap_->copy(),
15552 this->location());
15553 }
15554
15555 Bexpression*
do_get_backend(Translate_context * context)15556 Slice_value_expression::do_get_backend(Translate_context* context)
15557 {
15558 std::vector<Bexpression*> vals(3);
15559 vals[0] = this->valmem_->get_backend(context);
15560 vals[1] = this->len_->get_backend(context);
15561 vals[2] = this->cap_->get_backend(context);
15562
15563 Gogo* gogo = context->gogo();
15564 Btype* btype = this->type_->get_backend(gogo);
15565 return gogo->backend()->constructor_expression(btype, vals, this->location());
15566 }
15567
15568 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15569 Slice_value_expression::do_dump_expression(
15570 Ast_dump_context* ast_dump_context) const
15571 {
15572 ast_dump_context->ostream() << "slicevalue(";
15573 ast_dump_context->ostream() << "values: ";
15574 this->valmem_->dump_expression(ast_dump_context);
15575 ast_dump_context->ostream() << ", length: ";
15576 this->len_->dump_expression(ast_dump_context);
15577 ast_dump_context->ostream() << ", capacity: ";
15578 this->cap_->dump_expression(ast_dump_context);
15579 ast_dump_context->ostream() << ")";
15580 }
15581
15582 Expression*
make_slice_value(Type * at,Expression * valmem,Expression * len,Expression * cap,Location location)15583 Expression::make_slice_value(Type* at, Expression* valmem, Expression* len,
15584 Expression* cap, Location location)
15585 {
15586 go_assert(at->is_slice_type());
15587 go_assert(valmem->is_nil_expression()
15588 || (at->array_type()->element_type()
15589 == valmem->type()->points_to()));
15590 return new Slice_value_expression(at, valmem, len, cap, location);
15591 }
15592
15593 // An expression that evaluates to some characteristic of a non-empty interface.
15594 // This is used to access the method table or underlying object of an interface.
15595
15596 class Interface_info_expression : public Expression
15597 {
15598 public:
Interface_info_expression(Expression * iface,Interface_info iface_info,Location location)15599 Interface_info_expression(Expression* iface, Interface_info iface_info,
15600 Location location)
15601 : Expression(EXPRESSION_INTERFACE_INFO, location),
15602 iface_(iface), iface_info_(iface_info)
15603 { }
15604
15605 protected:
15606 Type*
15607 do_type();
15608
15609 void
do_determine_type(const Type_context *)15610 do_determine_type(const Type_context*)
15611 { }
15612
15613 Expression*
do_copy()15614 do_copy()
15615 {
15616 return new Interface_info_expression(this->iface_->copy(),
15617 this->iface_info_, this->location());
15618 }
15619
15620 Bexpression*
15621 do_get_backend(Translate_context* context);
15622
15623 void
15624 do_dump_expression(Ast_dump_context*) const;
15625
15626 void
do_issue_nil_check()15627 do_issue_nil_check()
15628 { this->iface_->issue_nil_check(); }
15629
15630 private:
15631 // The interface for which we are getting information.
15632 Expression* iface_;
15633 // What information we want.
15634 Interface_info iface_info_;
15635 };
15636
15637 // Return the type of the interface info.
15638
15639 Type*
do_type()15640 Interface_info_expression::do_type()
15641 {
15642 switch (this->iface_info_)
15643 {
15644 case INTERFACE_INFO_METHODS:
15645 {
15646 typedef Unordered_map(Interface_type*, Type*) Hashtable;
15647 static Hashtable result_types;
15648
15649 Interface_type* itype = this->iface_->type()->interface_type();
15650
15651 Hashtable::const_iterator p = result_types.find(itype);
15652 if (p != result_types.end())
15653 return p->second;
15654
15655 Type* pdt = Type::make_type_descriptor_ptr_type();
15656 if (itype->is_empty())
15657 {
15658 result_types[itype] = pdt;
15659 return pdt;
15660 }
15661
15662 Location loc = this->location();
15663 Struct_field_list* sfl = new Struct_field_list();
15664 sfl->push_back(
15665 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
15666
15667 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
15668 p != itype->methods()->end();
15669 ++p)
15670 {
15671 Function_type* ft = p->type()->function_type();
15672 go_assert(ft->receiver() == NULL);
15673
15674 const Typed_identifier_list* params = ft->parameters();
15675 Typed_identifier_list* mparams = new Typed_identifier_list();
15676 if (params != NULL)
15677 mparams->reserve(params->size() + 1);
15678 Type* vt = Type::make_pointer_type(Type::make_void_type());
15679 mparams->push_back(Typed_identifier("", vt, ft->location()));
15680 if (params != NULL)
15681 {
15682 for (Typed_identifier_list::const_iterator pp = params->begin();
15683 pp != params->end();
15684 ++pp)
15685 mparams->push_back(*pp);
15686 }
15687
15688 Typed_identifier_list* mresults = (ft->results() == NULL
15689 ? NULL
15690 : ft->results()->copy());
15691 Backend_function_type* mft =
15692 Type::make_backend_function_type(NULL, mparams, mresults,
15693 ft->location());
15694
15695 std::string fname = Gogo::unpack_hidden_name(p->name());
15696 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
15697 }
15698
15699 Struct_type* st = Type::make_struct_type(sfl, loc);
15700 st->set_is_struct_incomparable();
15701 Pointer_type *pt = Type::make_pointer_type(st);
15702 result_types[itype] = pt;
15703 return pt;
15704 }
15705 case INTERFACE_INFO_OBJECT:
15706 return Type::make_pointer_type(Type::make_void_type());
15707 default:
15708 go_unreachable();
15709 }
15710 }
15711
15712 // Return the backend representation for interface information.
15713
15714 Bexpression*
do_get_backend(Translate_context * context)15715 Interface_info_expression::do_get_backend(Translate_context* context)
15716 {
15717 Gogo* gogo = context->gogo();
15718 Bexpression* biface = this->iface_->get_backend(context);
15719 switch (this->iface_info_)
15720 {
15721 case INTERFACE_INFO_METHODS:
15722 case INTERFACE_INFO_OBJECT:
15723 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
15724 this->location());
15725 break;
15726 default:
15727 go_unreachable();
15728 }
15729 }
15730
15731 // Dump ast representation for an interface info expression.
15732
15733 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15734 Interface_info_expression::do_dump_expression(
15735 Ast_dump_context* ast_dump_context) const
15736 {
15737 bool is_empty = this->iface_->type()->interface_type()->is_empty();
15738 ast_dump_context->ostream() << "interfaceinfo(";
15739 this->iface_->dump_expression(ast_dump_context);
15740 ast_dump_context->ostream() << ",";
15741 ast_dump_context->ostream() <<
15742 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
15743 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
15744 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
15745 : "unknown");
15746 ast_dump_context->ostream() << ")";
15747 }
15748
15749 // Make an interface info expression.
15750
15751 Expression*
make_interface_info(Expression * iface,Interface_info iface_info,Location location)15752 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
15753 Location location)
15754 {
15755 return new Interface_info_expression(iface, iface_info, location);
15756 }
15757
15758 // An expression that represents an interface value. The first field is either
15759 // a type descriptor for an empty interface or a pointer to the interface method
15760 // table for a non-empty interface. The second field is always the object.
15761
15762 class Interface_value_expression : public Expression
15763 {
15764 public:
Interface_value_expression(Type * type,Expression * first_field,Expression * obj,Location location)15765 Interface_value_expression(Type* type, Expression* first_field,
15766 Expression* obj, Location location)
15767 : Expression(EXPRESSION_INTERFACE_VALUE, location),
15768 type_(type), first_field_(first_field), obj_(obj)
15769 { }
15770
15771 protected:
15772 int
15773 do_traverse(Traverse*);
15774
15775 Type*
do_type()15776 do_type()
15777 { return this->type_; }
15778
15779 void
do_determine_type(const Type_context *)15780 do_determine_type(const Type_context*)
15781 { go_unreachable(); }
15782
15783 Expression*
do_copy()15784 do_copy()
15785 {
15786 return new Interface_value_expression(this->type_->copy_expressions(),
15787 this->first_field_->copy(),
15788 this->obj_->copy(), this->location());
15789 }
15790
15791 Bexpression*
15792 do_get_backend(Translate_context* context);
15793
15794 void
15795 do_dump_expression(Ast_dump_context*) const;
15796
15797 private:
15798 // The type of the interface value.
15799 Type* type_;
15800 // The first field of the interface (either a type descriptor or a pointer
15801 // to the method table.
15802 Expression* first_field_;
15803 // The underlying object of the interface.
15804 Expression* obj_;
15805 };
15806
15807 int
do_traverse(Traverse * traverse)15808 Interface_value_expression::do_traverse(Traverse* traverse)
15809 {
15810 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
15811 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
15812 return TRAVERSE_EXIT;
15813 return TRAVERSE_CONTINUE;
15814 }
15815
15816 Bexpression*
do_get_backend(Translate_context * context)15817 Interface_value_expression::do_get_backend(Translate_context* context)
15818 {
15819 std::vector<Bexpression*> vals(2);
15820 vals[0] = this->first_field_->get_backend(context);
15821 vals[1] = this->obj_->get_backend(context);
15822
15823 Gogo* gogo = context->gogo();
15824 Btype* btype = this->type_->get_backend(gogo);
15825 return gogo->backend()->constructor_expression(btype, vals, this->location());
15826 }
15827
15828 void
do_dump_expression(Ast_dump_context * ast_dump_context) const15829 Interface_value_expression::do_dump_expression(
15830 Ast_dump_context* ast_dump_context) const
15831 {
15832 ast_dump_context->ostream() << "interfacevalue(";
15833 ast_dump_context->ostream() <<
15834 (this->type_->interface_type()->is_empty()
15835 ? "type_descriptor: "
15836 : "methods: ");
15837 this->first_field_->dump_expression(ast_dump_context);
15838 ast_dump_context->ostream() << ", object: ";
15839 this->obj_->dump_expression(ast_dump_context);
15840 ast_dump_context->ostream() << ")";
15841 }
15842
15843 Expression*
make_interface_value(Type * type,Expression * first_value,Expression * object,Location location)15844 Expression::make_interface_value(Type* type, Expression* first_value,
15845 Expression* object, Location location)
15846 {
15847 return new Interface_value_expression(type, first_value, object, location);
15848 }
15849
15850 // An interface method table for a pair of types: an interface type and a type
15851 // that implements that interface.
15852
15853 class Interface_mtable_expression : public Expression
15854 {
15855 public:
Interface_mtable_expression(Interface_type * itype,Type * type,bool is_pointer,Location location)15856 Interface_mtable_expression(Interface_type* itype, Type* type,
15857 bool is_pointer, Location location)
15858 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
15859 itype_(itype), type_(type), is_pointer_(is_pointer),
15860 method_table_type_(NULL), bvar_(NULL)
15861 { }
15862
15863 protected:
15864 int
15865 do_traverse(Traverse*);
15866
15867 Type*
15868 do_type();
15869
15870 bool
do_is_static_initializer() const15871 do_is_static_initializer() const
15872 { return true; }
15873
15874 void
do_determine_type(const Type_context *)15875 do_determine_type(const Type_context*)
15876 { go_unreachable(); }
15877
15878 Expression*
do_copy()15879 do_copy()
15880 {
15881 Interface_type* itype = this->itype_->copy_expressions()->interface_type();
15882 return new Interface_mtable_expression(itype,
15883 this->type_->copy_expressions(),
15884 this->is_pointer_, this->location());
15885 }
15886
15887 bool
do_is_addressable() const15888 do_is_addressable() const
15889 { return true; }
15890
15891 Bexpression*
15892 do_get_backend(Translate_context* context);
15893
15894 void
15895 do_dump_expression(Ast_dump_context*) const;
15896
15897 private:
15898 // The interface type for which the methods are defined.
15899 Interface_type* itype_;
15900 // The type to construct the interface method table for.
15901 Type* type_;
15902 // Whether this table contains the method set for the receiver type or the
15903 // pointer receiver type.
15904 bool is_pointer_;
15905 // The type of the method table.
15906 Type* method_table_type_;
15907 // The backend variable that refers to the interface method table.
15908 Bvariable* bvar_;
15909 };
15910
15911 int
do_traverse(Traverse * traverse)15912 Interface_mtable_expression::do_traverse(Traverse* traverse)
15913 {
15914 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
15915 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
15916 return TRAVERSE_EXIT;
15917 return TRAVERSE_CONTINUE;
15918 }
15919
15920 Type*
do_type()15921 Interface_mtable_expression::do_type()
15922 {
15923 if (this->method_table_type_ != NULL)
15924 return this->method_table_type_;
15925
15926 const Typed_identifier_list* interface_methods = this->itype_->methods();
15927 go_assert(!interface_methods->empty());
15928
15929 Struct_field_list* sfl = new Struct_field_list;
15930 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
15931 this->location());
15932 sfl->push_back(Struct_field(tid));
15933 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
15934 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15935 p != interface_methods->end();
15936 ++p)
15937 {
15938 // We want C function pointers here, not func descriptors; model
15939 // using void* pointers.
15940 Typed_identifier method(p->name(), unsafe_ptr_type, p->location());
15941 sfl->push_back(Struct_field(method));
15942 }
15943 Struct_type* st = Type::make_struct_type(sfl, this->location());
15944 st->set_is_struct_incomparable();
15945 this->method_table_type_ = st;
15946 return this->method_table_type_;
15947 }
15948
15949 Bexpression*
do_get_backend(Translate_context * context)15950 Interface_mtable_expression::do_get_backend(Translate_context* context)
15951 {
15952 Gogo* gogo = context->gogo();
15953 Location loc = Linemap::predeclared_location();
15954 if (this->bvar_ != NULL)
15955 return gogo->backend()->var_expression(this->bvar_, this->location());
15956
15957 const Typed_identifier_list* interface_methods = this->itype_->methods();
15958 go_assert(!interface_methods->empty());
15959
15960 std::string mangled_name =
15961 gogo->interface_method_table_name(this->itype_, this->type_,
15962 this->is_pointer_);
15963
15964 // Set is_public if we are converting a named type to an interface
15965 // type that is defined in the same package as the named type, and
15966 // the interface has hidden methods. In that case the interface
15967 // method table will be defined by the package that defines the
15968 // types.
15969 bool is_public = false;
15970 if (this->type_->named_type() != NULL
15971 && (this->type_->named_type()->named_object()->package()
15972 == this->itype_->package()))
15973 {
15974 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
15975 p != interface_methods->end();
15976 ++p)
15977 {
15978 if (Gogo::is_hidden_name(p->name()))
15979 {
15980 is_public = true;
15981 break;
15982 }
15983 }
15984 }
15985
15986 if (is_public
15987 && this->type_->named_type()->named_object()->package() != NULL)
15988 {
15989 // The interface conversion table is defined elsewhere.
15990 Btype* btype = this->type()->get_backend(gogo);
15991 std::string asm_name(go_selectively_encode_id(mangled_name));
15992 this->bvar_ =
15993 gogo->backend()->immutable_struct_reference(mangled_name, asm_name,
15994 btype, loc);
15995 return gogo->backend()->var_expression(this->bvar_, this->location());
15996 }
15997
15998 // The first element is the type descriptor.
15999 Type* td_type;
16000 if (!this->is_pointer_)
16001 td_type = this->type_;
16002 else
16003 td_type = Type::make_pointer_type(this->type_);
16004
16005 std::vector<Backend::Btyped_identifier> bstructfields;
16006
16007 // Build an interface method table for a type: a type descriptor followed by a
16008 // list of function pointers, one for each interface method. This is used for
16009 // interfaces.
16010 Expression_list* svals = new Expression_list();
16011 Expression* tdescriptor = Expression::make_type_descriptor(td_type, loc);
16012 svals->push_back(tdescriptor);
16013
16014 Btype* tdesc_btype = tdescriptor->type()->get_backend(gogo);
16015 Backend::Btyped_identifier btd("_type", tdesc_btype, loc);
16016 bstructfields.push_back(btd);
16017
16018 Named_type* nt = this->type_->named_type();
16019 Struct_type* st = this->type_->struct_type();
16020 go_assert(nt != NULL || st != NULL);
16021
16022 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
16023 p != interface_methods->end();
16024 ++p)
16025 {
16026 bool is_ambiguous;
16027 Method* m;
16028 if (nt != NULL)
16029 m = nt->method_function(p->name(), &is_ambiguous);
16030 else
16031 m = st->method_function(p->name(), &is_ambiguous);
16032 go_assert(m != NULL);
16033 Named_object* no = m->named_object();
16034
16035 go_assert(no->is_function() || no->is_function_declaration());
16036
16037 Btype* fcn_btype = m->type()->get_backend_fntype(gogo);
16038 Backend::Btyped_identifier bmtype(p->name(), fcn_btype, loc);
16039 bstructfields.push_back(bmtype);
16040
16041 svals->push_back(Expression::make_func_code_reference(no, loc));
16042 }
16043
16044 Btype *btype = gogo->backend()->struct_type(bstructfields);
16045 std::vector<Bexpression*> ctor_bexprs;
16046 for (Expression_list::const_iterator pe = svals->begin();
16047 pe != svals->end();
16048 ++pe)
16049 {
16050 ctor_bexprs.push_back((*pe)->get_backend(context));
16051 }
16052 Bexpression* ctor =
16053 gogo->backend()->constructor_expression(btype, ctor_bexprs, loc);
16054
16055 std::string asm_name(go_selectively_encode_id(mangled_name));
16056 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, asm_name, false,
16057 !is_public, btype, loc);
16058 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
16059 !is_public, btype, loc, ctor);
16060 return gogo->backend()->var_expression(this->bvar_, loc);
16061 }
16062
16063 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16064 Interface_mtable_expression::do_dump_expression(
16065 Ast_dump_context* ast_dump_context) const
16066 {
16067 ast_dump_context->ostream() << "__go_"
16068 << (this->is_pointer_ ? "pimt__" : "imt_");
16069 ast_dump_context->dump_type(this->itype_);
16070 ast_dump_context->ostream() << "__";
16071 ast_dump_context->dump_type(this->type_);
16072 }
16073
16074 Expression*
make_interface_mtable_ref(Interface_type * itype,Type * type,bool is_pointer,Location location)16075 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
16076 bool is_pointer, Location location)
16077 {
16078 return new Interface_mtable_expression(itype, type, is_pointer, location);
16079 }
16080
16081 // An expression which evaluates to the offset of a field within a
16082 // struct. This, like Type_info_expression, q.v., is only used to
16083 // initialize fields of a type descriptor.
16084
16085 class Struct_field_offset_expression : public Expression
16086 {
16087 public:
Struct_field_offset_expression(Struct_type * type,const Struct_field * field)16088 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
16089 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
16090 Linemap::predeclared_location()),
16091 type_(type), field_(field)
16092 { }
16093
16094 protected:
16095 bool
do_is_static_initializer() const16096 do_is_static_initializer() const
16097 { return true; }
16098
16099 Type*
do_type()16100 do_type()
16101 { return Type::lookup_integer_type("uintptr"); }
16102
16103 void
do_determine_type(const Type_context *)16104 do_determine_type(const Type_context*)
16105 { }
16106
16107 Expression*
do_copy()16108 do_copy()
16109 { return this; }
16110
16111 Bexpression*
16112 do_get_backend(Translate_context* context);
16113
16114 void
16115 do_dump_expression(Ast_dump_context*) const;
16116
16117 private:
16118 // The type of the struct.
16119 Struct_type* type_;
16120 // The field.
16121 const Struct_field* field_;
16122 };
16123
16124 // Return the backend representation for a struct field offset.
16125
16126 Bexpression*
do_get_backend(Translate_context * context)16127 Struct_field_offset_expression::do_get_backend(Translate_context* context)
16128 {
16129 const Struct_field_list* fields = this->type_->fields();
16130 Struct_field_list::const_iterator p;
16131 unsigned i = 0;
16132 for (p = fields->begin();
16133 p != fields->end();
16134 ++p, ++i)
16135 if (&*p == this->field_)
16136 break;
16137 go_assert(&*p == this->field_);
16138
16139 Gogo* gogo = context->gogo();
16140 Btype* btype = this->type_->get_backend(gogo);
16141
16142 int64_t offset = gogo->backend()->type_field_offset(btype, i);
16143 Type* uptr_type = Type::lookup_integer_type("uintptr");
16144 Expression* ret =
16145 Expression::make_integer_int64(offset, uptr_type,
16146 Linemap::predeclared_location());
16147 return ret->get_backend(context);
16148 }
16149
16150 // Dump ast representation for a struct field offset expression.
16151
16152 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16153 Struct_field_offset_expression::do_dump_expression(
16154 Ast_dump_context* ast_dump_context) const
16155 {
16156 ast_dump_context->ostream() << "unsafe.Offsetof(";
16157 ast_dump_context->dump_type(this->type_);
16158 ast_dump_context->ostream() << '.';
16159 ast_dump_context->ostream() <<
16160 Gogo::message_name(this->field_->field_name());
16161 ast_dump_context->ostream() << ")";
16162 }
16163
16164 // Make an expression for a struct field offset.
16165
16166 Expression*
make_struct_field_offset(Struct_type * type,const Struct_field * field)16167 Expression::make_struct_field_offset(Struct_type* type,
16168 const Struct_field* field)
16169 {
16170 return new Struct_field_offset_expression(type, field);
16171 }
16172
16173 // An expression which evaluates to the address of an unnamed label.
16174
16175 class Label_addr_expression : public Expression
16176 {
16177 public:
Label_addr_expression(Label * label,Location location)16178 Label_addr_expression(Label* label, Location location)
16179 : Expression(EXPRESSION_LABEL_ADDR, location),
16180 label_(label)
16181 { }
16182
16183 protected:
16184 Type*
do_type()16185 do_type()
16186 { return Type::make_pointer_type(Type::make_void_type()); }
16187
16188 void
do_determine_type(const Type_context *)16189 do_determine_type(const Type_context*)
16190 { }
16191
16192 Expression*
do_copy()16193 do_copy()
16194 { return new Label_addr_expression(this->label_, this->location()); }
16195
16196 Bexpression*
do_get_backend(Translate_context * context)16197 do_get_backend(Translate_context* context)
16198 { return this->label_->get_addr(context, this->location()); }
16199
16200 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16201 do_dump_expression(Ast_dump_context* ast_dump_context) const
16202 { ast_dump_context->ostream() << this->label_->name(); }
16203
16204 private:
16205 // The label whose address we are taking.
16206 Label* label_;
16207 };
16208
16209 // Make an expression for the address of an unnamed label.
16210
16211 Expression*
make_label_addr(Label * label,Location location)16212 Expression::make_label_addr(Label* label, Location location)
16213 {
16214 return new Label_addr_expression(label, location);
16215 }
16216
16217 // Class Conditional_expression.
16218
16219 // Traversal.
16220
16221 int
do_traverse(Traverse * traverse)16222 Conditional_expression::do_traverse(Traverse* traverse)
16223 {
16224 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
16225 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
16226 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
16227 return TRAVERSE_EXIT;
16228 return TRAVERSE_CONTINUE;
16229 }
16230
16231 // Return the type of the conditional expression.
16232
16233 Type*
do_type()16234 Conditional_expression::do_type()
16235 {
16236 Type* result_type = Type::make_void_type();
16237 if (Type::are_identical(this->then_->type(), this->else_->type(),
16238 Type::COMPARE_ERRORS | Type::COMPARE_TAGS,
16239 NULL))
16240 result_type = this->then_->type();
16241 else if (this->then_->is_nil_expression()
16242 || this->else_->is_nil_expression())
16243 result_type = (!this->then_->is_nil_expression()
16244 ? this->then_->type()
16245 : this->else_->type());
16246 return result_type;
16247 }
16248
16249 // Determine type for a conditional expression.
16250
16251 void
do_determine_type(const Type_context * context)16252 Conditional_expression::do_determine_type(const Type_context* context)
16253 {
16254 this->cond_->determine_type_no_context();
16255 this->then_->determine_type(context);
16256 this->else_->determine_type(context);
16257 }
16258
16259 // Get the backend representation of a conditional expression.
16260
16261 Bexpression*
do_get_backend(Translate_context * context)16262 Conditional_expression::do_get_backend(Translate_context* context)
16263 {
16264 Gogo* gogo = context->gogo();
16265 Btype* result_btype = this->type()->get_backend(gogo);
16266 Bexpression* cond = this->cond_->get_backend(context);
16267 Bexpression* then = this->then_->get_backend(context);
16268 Bexpression* belse = this->else_->get_backend(context);
16269 Bfunction* bfn = context->function()->func_value()->get_decl();
16270 return gogo->backend()->conditional_expression(bfn, result_btype, cond, then,
16271 belse, this->location());
16272 }
16273
16274 // Dump ast representation of a conditional expression.
16275
16276 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16277 Conditional_expression::do_dump_expression(
16278 Ast_dump_context* ast_dump_context) const
16279 {
16280 ast_dump_context->ostream() << "(";
16281 ast_dump_context->dump_expression(this->cond_);
16282 ast_dump_context->ostream() << " ? ";
16283 ast_dump_context->dump_expression(this->then_);
16284 ast_dump_context->ostream() << " : ";
16285 ast_dump_context->dump_expression(this->else_);
16286 ast_dump_context->ostream() << ") ";
16287 }
16288
16289 // Make a conditional expression.
16290
16291 Expression*
make_conditional(Expression * cond,Expression * then,Expression * else_expr,Location location)16292 Expression::make_conditional(Expression* cond, Expression* then,
16293 Expression* else_expr, Location location)
16294 {
16295 return new Conditional_expression(cond, then, else_expr, location);
16296 }
16297
16298 // Class Compound_expression.
16299
16300 // Traversal.
16301
16302 int
do_traverse(Traverse * traverse)16303 Compound_expression::do_traverse(Traverse* traverse)
16304 {
16305 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
16306 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
16307 return TRAVERSE_EXIT;
16308 return TRAVERSE_CONTINUE;
16309 }
16310
16311 // Return the type of the compound expression.
16312
16313 Type*
do_type()16314 Compound_expression::do_type()
16315 {
16316 return this->expr_->type();
16317 }
16318
16319 // Determine type for a compound expression.
16320
16321 void
do_determine_type(const Type_context * context)16322 Compound_expression::do_determine_type(const Type_context* context)
16323 {
16324 this->init_->determine_type_no_context();
16325 this->expr_->determine_type(context);
16326 }
16327
16328 // Get the backend representation of a compound expression.
16329
16330 Bexpression*
do_get_backend(Translate_context * context)16331 Compound_expression::do_get_backend(Translate_context* context)
16332 {
16333 Gogo* gogo = context->gogo();
16334 Bexpression* binit = this->init_->get_backend(context);
16335 Bfunction* bfunction = context->function()->func_value()->get_decl();
16336 Bstatement* init_stmt = gogo->backend()->expression_statement(bfunction,
16337 binit);
16338 Bexpression* bexpr = this->expr_->get_backend(context);
16339 return gogo->backend()->compound_expression(init_stmt, bexpr,
16340 this->location());
16341 }
16342
16343 // Dump ast representation of a conditional expression.
16344
16345 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16346 Compound_expression::do_dump_expression(
16347 Ast_dump_context* ast_dump_context) const
16348 {
16349 ast_dump_context->ostream() << "(";
16350 ast_dump_context->dump_expression(this->init_);
16351 ast_dump_context->ostream() << ",";
16352 ast_dump_context->dump_expression(this->expr_);
16353 ast_dump_context->ostream() << ") ";
16354 }
16355
16356 // Make a compound expression.
16357
16358 Expression*
make_compound(Expression * init,Expression * expr,Location location)16359 Expression::make_compound(Expression* init, Expression* expr, Location location)
16360 {
16361 return new Compound_expression(init, expr, location);
16362 }
16363
16364 // Class Backend_expression.
16365
16366 int
do_traverse(Traverse *)16367 Backend_expression::do_traverse(Traverse*)
16368 {
16369 return TRAVERSE_CONTINUE;
16370 }
16371
16372 Expression*
do_copy()16373 Backend_expression::do_copy()
16374 {
16375 return new Backend_expression(this->bexpr_, this->type_->copy_expressions(),
16376 this->location());
16377 }
16378
16379 void
do_dump_expression(Ast_dump_context * ast_dump_context) const16380 Backend_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
16381 {
16382 ast_dump_context->ostream() << "backend_expression<";
16383 ast_dump_context->dump_type(this->type_);
16384 ast_dump_context->ostream() << ">";
16385 }
16386
16387 Expression*
make_backend(Bexpression * bexpr,Type * type,Location location)16388 Expression::make_backend(Bexpression* bexpr, Type* type, Location location)
16389 {
16390 return new Backend_expression(bexpr, type, location);
16391 }
16392
16393 // Import an expression. This comes at the end in order to see the
16394 // various class definitions.
16395
16396 Expression*
import_expression(Import_expression * imp,Location loc)16397 Expression::import_expression(Import_expression* imp, Location loc)
16398 {
16399 int c = imp->peek_char();
16400 if (c == '+' || c == '-' || c == '!' || c == '^' || c == '&' || c == '*')
16401 return Unary_expression::do_import(imp, loc);
16402 else if (c == '(')
16403 return Binary_expression::do_import(imp, loc);
16404 else if (imp->match_c_string("$true")
16405 || imp->match_c_string("$false")
16406 || (imp->version() < EXPORT_FORMAT_V3
16407 && (imp->match_c_string("true")
16408 || imp->match_c_string("false"))))
16409 return Boolean_expression::do_import(imp, loc);
16410 else if (c == '"')
16411 return String_expression::do_import(imp, loc);
16412 else if (c == '-' || (c >= '0' && c <= '9'))
16413 {
16414 // This handles integers, floats and complex constants.
16415 return Integer_expression::do_import(imp, loc);
16416 }
16417 else if (imp->match_c_string("$nil")
16418 || (imp->version() < EXPORT_FORMAT_V3
16419 && imp->match_c_string("nil")))
16420 return Nil_expression::do_import(imp, loc);
16421 else if (imp->match_c_string("$convert")
16422 || (imp->version() < EXPORT_FORMAT_V3
16423 && imp->match_c_string("convert")))
16424 return Type_conversion_expression::do_import(imp, loc);
16425
16426 Import_function_body* ifb = imp->ifb();
16427 if (ifb == NULL)
16428 {
16429 go_error_at(imp->location(), "import error: expected expression");
16430 return Expression::make_error(loc);
16431 }
16432 if (ifb->saw_error())
16433 return Expression::make_error(loc);
16434 std::string id = ifb->read_identifier();
16435 if (id.empty())
16436 {
16437 if (!ifb->saw_error())
16438 go_error_at(imp->location(),
16439 "import error: expected identifier at %lu",
16440 static_cast<unsigned long>(ifb->off()));
16441 ifb->set_saw_error();
16442 return Expression::make_error(loc);
16443 }
16444 Named_object* var = ifb->block()->bindings()->lookup(id);
16445 if (var == NULL)
16446 {
16447 if (!ifb->saw_error())
16448 go_error_at(imp->location(), "import error: lookup of %qs failed",
16449 id.c_str());
16450 ifb->set_saw_error();
16451 return Expression::make_error(loc);
16452 }
16453 return Expression::make_var_reference(var, loc);
16454 }
16455
16456 // Class Expression_list.
16457
16458 // Traverse the list.
16459
16460 int
traverse(Traverse * traverse)16461 Expression_list::traverse(Traverse* traverse)
16462 {
16463 for (Expression_list::iterator p = this->begin();
16464 p != this->end();
16465 ++p)
16466 {
16467 if (*p != NULL)
16468 {
16469 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
16470 return TRAVERSE_EXIT;
16471 }
16472 }
16473 return TRAVERSE_CONTINUE;
16474 }
16475
16476 // Copy the list.
16477
16478 Expression_list*
copy()16479 Expression_list::copy()
16480 {
16481 Expression_list* ret = new Expression_list();
16482 for (Expression_list::iterator p = this->begin();
16483 p != this->end();
16484 ++p)
16485 {
16486 if (*p == NULL)
16487 ret->push_back(NULL);
16488 else
16489 ret->push_back((*p)->copy());
16490 }
16491 return ret;
16492 }
16493
16494 // Return whether an expression list has an error expression.
16495
16496 bool
contains_error() const16497 Expression_list::contains_error() const
16498 {
16499 for (Expression_list::const_iterator p = this->begin();
16500 p != this->end();
16501 ++p)
16502 if (*p != NULL && (*p)->is_error_expression())
16503 return true;
16504 return false;
16505 }
16506
16507 // Class Numeric_constant.
16508
16509 // Destructor.
16510
~Numeric_constant()16511 Numeric_constant::~Numeric_constant()
16512 {
16513 this->clear();
16514 }
16515
16516 // Copy constructor.
16517
Numeric_constant(const Numeric_constant & a)16518 Numeric_constant::Numeric_constant(const Numeric_constant& a)
16519 : classification_(a.classification_), type_(a.type_)
16520 {
16521 switch (a.classification_)
16522 {
16523 case NC_INVALID:
16524 break;
16525 case NC_INT:
16526 case NC_RUNE:
16527 mpz_init_set(this->u_.int_val, a.u_.int_val);
16528 break;
16529 case NC_FLOAT:
16530 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16531 break;
16532 case NC_COMPLEX:
16533 mpc_init2(this->u_.complex_val, mpc_precision);
16534 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16535 break;
16536 default:
16537 go_unreachable();
16538 }
16539 }
16540
16541 // Assignment operator.
16542
16543 Numeric_constant&
operator =(const Numeric_constant & a)16544 Numeric_constant::operator=(const Numeric_constant& a)
16545 {
16546 this->clear();
16547 this->classification_ = a.classification_;
16548 this->type_ = a.type_;
16549 switch (a.classification_)
16550 {
16551 case NC_INVALID:
16552 break;
16553 case NC_INT:
16554 case NC_RUNE:
16555 mpz_init_set(this->u_.int_val, a.u_.int_val);
16556 break;
16557 case NC_FLOAT:
16558 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
16559 break;
16560 case NC_COMPLEX:
16561 mpc_init2(this->u_.complex_val, mpc_precision);
16562 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
16563 break;
16564 default:
16565 go_unreachable();
16566 }
16567 return *this;
16568 }
16569
16570 // Check equality with another numeric constant.
16571
16572 bool
equals(const Numeric_constant & a) const16573 Numeric_constant::equals(const Numeric_constant& a) const
16574 {
16575 if (this->classification_ != a.classification_)
16576 return false;
16577
16578 if (this->type_ != NULL && a.type_ != NULL
16579 && !Type::are_identical(this->type_, a.type_,
16580 Type::COMPARE_ALIASES, NULL))
16581 return false;
16582
16583 switch (a.classification_)
16584 {
16585 case NC_INVALID:
16586 break;
16587 case NC_INT:
16588 case NC_RUNE:
16589 return mpz_cmp(this->u_.int_val, a.u_.int_val) == 0;
16590 case NC_FLOAT:
16591 return mpfr_cmp(this->u_.float_val, a.u_.float_val) == 0;
16592 case NC_COMPLEX:
16593 return mpc_cmp(this->u_.complex_val, a.u_.complex_val) == 0;
16594 default:
16595 go_unreachable();
16596 }
16597 return false;
16598 }
16599
16600 // Clear the contents.
16601
16602 void
clear()16603 Numeric_constant::clear()
16604 {
16605 switch (this->classification_)
16606 {
16607 case NC_INVALID:
16608 break;
16609 case NC_INT:
16610 case NC_RUNE:
16611 mpz_clear(this->u_.int_val);
16612 break;
16613 case NC_FLOAT:
16614 mpfr_clear(this->u_.float_val);
16615 break;
16616 case NC_COMPLEX:
16617 mpc_clear(this->u_.complex_val);
16618 break;
16619 default:
16620 go_unreachable();
16621 }
16622 this->classification_ = NC_INVALID;
16623 }
16624
16625 // Set to an unsigned long value.
16626
16627 void
set_unsigned_long(Type * type,unsigned long val)16628 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
16629 {
16630 this->clear();
16631 this->classification_ = NC_INT;
16632 this->type_ = type;
16633 mpz_init_set_ui(this->u_.int_val, val);
16634 }
16635
16636 // Set to an integer value.
16637
16638 void
set_int(Type * type,const mpz_t val)16639 Numeric_constant::set_int(Type* type, const mpz_t val)
16640 {
16641 this->clear();
16642 this->classification_ = NC_INT;
16643 this->type_ = type;
16644 mpz_init_set(this->u_.int_val, val);
16645 }
16646
16647 // Set to a rune value.
16648
16649 void
set_rune(Type * type,const mpz_t val)16650 Numeric_constant::set_rune(Type* type, const mpz_t val)
16651 {
16652 this->clear();
16653 this->classification_ = NC_RUNE;
16654 this->type_ = type;
16655 mpz_init_set(this->u_.int_val, val);
16656 }
16657
16658 // Set to a floating point value.
16659
16660 void
set_float(Type * type,const mpfr_t val)16661 Numeric_constant::set_float(Type* type, const mpfr_t val)
16662 {
16663 this->clear();
16664 this->classification_ = NC_FLOAT;
16665 this->type_ = type;
16666
16667 // Numeric constants do not have negative zero values, so remove
16668 // them here. They also don't have infinity or NaN values, but we
16669 // should never see them here.
16670 int bits = 0;
16671 if (type != NULL
16672 && type->float_type() != NULL
16673 && !type->float_type()->is_abstract())
16674 bits = type->float_type()->bits();
16675 if (Numeric_constant::is_float_neg_zero(val, bits))
16676 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
16677 else
16678 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
16679 }
16680
16681 // Set to a complex value.
16682
16683 void
set_complex(Type * type,const mpc_t val)16684 Numeric_constant::set_complex(Type* type, const mpc_t val)
16685 {
16686 this->clear();
16687 this->classification_ = NC_COMPLEX;
16688 this->type_ = type;
16689
16690 // Avoid negative zero as in set_float.
16691 int bits = 0;
16692 if (type != NULL
16693 && type->complex_type() != NULL
16694 && !type->complex_type()->is_abstract())
16695 bits = type->complex_type()->bits() / 2;
16696
16697 mpfr_t real;
16698 mpfr_init_set(real, mpc_realref(val), GMP_RNDN);
16699 if (Numeric_constant::is_float_neg_zero(real, bits))
16700 mpfr_set_ui(real, 0, GMP_RNDN);
16701
16702 mpfr_t imag;
16703 mpfr_init_set(imag, mpc_imagref(val), GMP_RNDN);
16704 if (Numeric_constant::is_float_neg_zero(imag, bits))
16705 mpfr_set_ui(imag, 0, GMP_RNDN);
16706
16707 mpc_init2(this->u_.complex_val, mpc_precision);
16708 mpc_set_fr_fr(this->u_.complex_val, real, imag, MPC_RNDNN);
16709
16710 mpfr_clear(real);
16711 mpfr_clear(imag);
16712 }
16713
16714 // Return whether VAL, at a precision of BITS, is a negative zero.
16715 // BITS may be zero in which case it is ignored.
16716
16717 bool
is_float_neg_zero(const mpfr_t val,int bits)16718 Numeric_constant::is_float_neg_zero(const mpfr_t val, int bits)
16719 {
16720 if (!mpfr_signbit(val))
16721 return false;
16722 if (mpfr_zero_p(val))
16723 return true;
16724 mp_exp_t min_exp;
16725 switch (bits)
16726 {
16727 case 0:
16728 return false;
16729 case 32:
16730 // In a denormalized float32 the exponent is -126, and there are
16731 // 24 bits of which at least the last must be 1, so the smallest
16732 // representable non-zero exponent is -126 - (24 - 1) == -149.
16733 min_exp = -149;
16734 break;
16735 case 64:
16736 // Minimum exponent is -1022, there are 53 bits.
16737 min_exp = -1074;
16738 break;
16739 default:
16740 go_unreachable();
16741 }
16742 return mpfr_get_exp(val) < min_exp;
16743 }
16744
16745 // Get an int value.
16746
16747 void
get_int(mpz_t * val) const16748 Numeric_constant::get_int(mpz_t* val) const
16749 {
16750 go_assert(this->is_int());
16751 mpz_init_set(*val, this->u_.int_val);
16752 }
16753
16754 // Get a rune value.
16755
16756 void
get_rune(mpz_t * val) const16757 Numeric_constant::get_rune(mpz_t* val) const
16758 {
16759 go_assert(this->is_rune());
16760 mpz_init_set(*val, this->u_.int_val);
16761 }
16762
16763 // Get a floating point value.
16764
16765 void
get_float(mpfr_t * val) const16766 Numeric_constant::get_float(mpfr_t* val) const
16767 {
16768 go_assert(this->is_float());
16769 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16770 }
16771
16772 // Get a complex value.
16773
16774 void
get_complex(mpc_t * val) const16775 Numeric_constant::get_complex(mpc_t* val) const
16776 {
16777 go_assert(this->is_complex());
16778 mpc_init2(*val, mpc_precision);
16779 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16780 }
16781
16782 // Express value as unsigned long if possible.
16783
16784 Numeric_constant::To_unsigned_long
to_unsigned_long(unsigned long * val) const16785 Numeric_constant::to_unsigned_long(unsigned long* val) const
16786 {
16787 switch (this->classification_)
16788 {
16789 case NC_INT:
16790 case NC_RUNE:
16791 return this->mpz_to_unsigned_long(this->u_.int_val, val);
16792 case NC_FLOAT:
16793 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
16794 case NC_COMPLEX:
16795 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16796 return NC_UL_NOTINT;
16797 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
16798 val);
16799 default:
16800 go_unreachable();
16801 }
16802 }
16803
16804 // Express integer value as unsigned long if possible.
16805
16806 Numeric_constant::To_unsigned_long
mpz_to_unsigned_long(const mpz_t ival,unsigned long * val) const16807 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
16808 unsigned long *val) const
16809 {
16810 if (mpz_sgn(ival) < 0)
16811 return NC_UL_NEGATIVE;
16812 unsigned long ui = mpz_get_ui(ival);
16813 if (mpz_cmp_ui(ival, ui) != 0)
16814 return NC_UL_BIG;
16815 *val = ui;
16816 return NC_UL_VALID;
16817 }
16818
16819 // Express floating point value as unsigned long if possible.
16820
16821 Numeric_constant::To_unsigned_long
mpfr_to_unsigned_long(const mpfr_t fval,unsigned long * val) const16822 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
16823 unsigned long *val) const
16824 {
16825 if (!mpfr_integer_p(fval))
16826 return NC_UL_NOTINT;
16827 mpz_t ival;
16828 mpz_init(ival);
16829 mpfr_get_z(ival, fval, GMP_RNDN);
16830 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
16831 mpz_clear(ival);
16832 return ret;
16833 }
16834
16835 // Express value as memory size if possible.
16836
16837 bool
to_memory_size(int64_t * val) const16838 Numeric_constant::to_memory_size(int64_t* val) const
16839 {
16840 switch (this->classification_)
16841 {
16842 case NC_INT:
16843 case NC_RUNE:
16844 return this->mpz_to_memory_size(this->u_.int_val, val);
16845 case NC_FLOAT:
16846 return this->mpfr_to_memory_size(this->u_.float_val, val);
16847 case NC_COMPLEX:
16848 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16849 return false;
16850 return this->mpfr_to_memory_size(mpc_realref(this->u_.complex_val), val);
16851 default:
16852 go_unreachable();
16853 }
16854 }
16855
16856 // Express integer as memory size if possible.
16857
16858 bool
mpz_to_memory_size(const mpz_t ival,int64_t * val) const16859 Numeric_constant::mpz_to_memory_size(const mpz_t ival, int64_t* val) const
16860 {
16861 if (mpz_sgn(ival) < 0)
16862 return false;
16863 if (mpz_fits_slong_p(ival))
16864 {
16865 *val = static_cast<int64_t>(mpz_get_si(ival));
16866 return true;
16867 }
16868
16869 // Test >= 64, not > 64, because an int64_t can hold 63 bits of a
16870 // positive value.
16871 if (mpz_sizeinbase(ival, 2) >= 64)
16872 return false;
16873
16874 mpz_t q, r;
16875 mpz_init(q);
16876 mpz_init(r);
16877 mpz_tdiv_q_2exp(q, ival, 32);
16878 mpz_tdiv_r_2exp(r, ival, 32);
16879 go_assert(mpz_fits_ulong_p(q) && mpz_fits_ulong_p(r));
16880 *val = ((static_cast<int64_t>(mpz_get_ui(q)) << 32)
16881 + static_cast<int64_t>(mpz_get_ui(r)));
16882 mpz_clear(r);
16883 mpz_clear(q);
16884 return true;
16885 }
16886
16887 // Express floating point value as memory size if possible.
16888
16889 bool
mpfr_to_memory_size(const mpfr_t fval,int64_t * val) const16890 Numeric_constant::mpfr_to_memory_size(const mpfr_t fval, int64_t* val) const
16891 {
16892 if (!mpfr_integer_p(fval))
16893 return false;
16894 mpz_t ival;
16895 mpz_init(ival);
16896 mpfr_get_z(ival, fval, GMP_RNDN);
16897 bool ret = this->mpz_to_memory_size(ival, val);
16898 mpz_clear(ival);
16899 return ret;
16900 }
16901
16902 // Convert value to integer if possible.
16903
16904 bool
to_int(mpz_t * val) const16905 Numeric_constant::to_int(mpz_t* val) const
16906 {
16907 switch (this->classification_)
16908 {
16909 case NC_INT:
16910 case NC_RUNE:
16911 mpz_init_set(*val, this->u_.int_val);
16912 return true;
16913 case NC_FLOAT:
16914 if (!mpfr_integer_p(this->u_.float_val))
16915 return false;
16916 mpz_init(*val);
16917 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
16918 return true;
16919 case NC_COMPLEX:
16920 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
16921 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
16922 return false;
16923 mpz_init(*val);
16924 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16925 return true;
16926 default:
16927 go_unreachable();
16928 }
16929 }
16930
16931 // Convert value to floating point if possible.
16932
16933 bool
to_float(mpfr_t * val) const16934 Numeric_constant::to_float(mpfr_t* val) const
16935 {
16936 switch (this->classification_)
16937 {
16938 case NC_INT:
16939 case NC_RUNE:
16940 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
16941 return true;
16942 case NC_FLOAT:
16943 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
16944 return true;
16945 case NC_COMPLEX:
16946 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
16947 return false;
16948 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
16949 return true;
16950 default:
16951 go_unreachable();
16952 }
16953 }
16954
16955 // Convert value to complex.
16956
16957 bool
to_complex(mpc_t * val) const16958 Numeric_constant::to_complex(mpc_t* val) const
16959 {
16960 mpc_init2(*val, mpc_precision);
16961 switch (this->classification_)
16962 {
16963 case NC_INT:
16964 case NC_RUNE:
16965 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
16966 return true;
16967 case NC_FLOAT:
16968 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
16969 return true;
16970 case NC_COMPLEX:
16971 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
16972 return true;
16973 default:
16974 go_unreachable();
16975 }
16976 }
16977
16978 // Get the type.
16979
16980 Type*
type() const16981 Numeric_constant::type() const
16982 {
16983 if (this->type_ != NULL)
16984 return this->type_;
16985 switch (this->classification_)
16986 {
16987 case NC_INT:
16988 return Type::make_abstract_integer_type();
16989 case NC_RUNE:
16990 return Type::make_abstract_character_type();
16991 case NC_FLOAT:
16992 return Type::make_abstract_float_type();
16993 case NC_COMPLEX:
16994 return Type::make_abstract_complex_type();
16995 default:
16996 go_unreachable();
16997 }
16998 }
16999
17000 // If the constant can be expressed in TYPE, then set the type of the
17001 // constant to TYPE and return true. Otherwise return false, and, if
17002 // ISSUE_ERROR is true, report an appropriate error message.
17003
17004 bool
set_type(Type * type,bool issue_error,Location loc)17005 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
17006 {
17007 bool ret;
17008 if (type == NULL || type->is_error())
17009 ret = true;
17010 else if (type->integer_type() != NULL)
17011 ret = this->check_int_type(type->integer_type(), issue_error, loc);
17012 else if (type->float_type() != NULL)
17013 ret = this->check_float_type(type->float_type(), issue_error, loc);
17014 else if (type->complex_type() != NULL)
17015 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
17016 else
17017 {
17018 ret = false;
17019 if (issue_error)
17020 go_assert(saw_errors());
17021 }
17022 if (ret)
17023 this->type_ = type;
17024 return ret;
17025 }
17026
17027 // Check whether the constant can be expressed in an integer type.
17028
17029 bool
check_int_type(Integer_type * type,bool issue_error,Location location)17030 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
17031 Location location)
17032 {
17033 mpz_t val;
17034 switch (this->classification_)
17035 {
17036 case NC_INT:
17037 case NC_RUNE:
17038 mpz_init_set(val, this->u_.int_val);
17039 break;
17040
17041 case NC_FLOAT:
17042 if (!mpfr_integer_p(this->u_.float_val))
17043 {
17044 if (issue_error)
17045 {
17046 go_error_at(location,
17047 "floating point constant truncated to integer");
17048 this->set_invalid();
17049 }
17050 return false;
17051 }
17052 mpz_init(val);
17053 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
17054 break;
17055
17056 case NC_COMPLEX:
17057 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
17058 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
17059 {
17060 if (issue_error)
17061 {
17062 go_error_at(location, "complex constant truncated to integer");
17063 this->set_invalid();
17064 }
17065 return false;
17066 }
17067 mpz_init(val);
17068 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
17069 break;
17070
17071 default:
17072 go_unreachable();
17073 }
17074
17075 bool ret;
17076 if (type->is_abstract())
17077 ret = true;
17078 else
17079 {
17080 int bits = mpz_sizeinbase(val, 2);
17081 if (type->is_unsigned())
17082 {
17083 // For an unsigned type we can only accept a nonnegative
17084 // number, and we must be able to represents at least BITS.
17085 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
17086 }
17087 else
17088 {
17089 // For a signed type we need an extra bit to indicate the
17090 // sign. We have to handle the most negative integer
17091 // specially.
17092 ret = (bits + 1 <= type->bits()
17093 || (bits <= type->bits()
17094 && mpz_sgn(val) < 0
17095 && (mpz_scan1(val, 0)
17096 == static_cast<unsigned long>(type->bits() - 1))
17097 && mpz_scan0(val, type->bits()) == ULONG_MAX));
17098 }
17099 }
17100
17101 if (!ret && issue_error)
17102 {
17103 go_error_at(location, "integer constant overflow");
17104 this->set_invalid();
17105 }
17106
17107 return ret;
17108 }
17109
17110 // Check whether the constant can be expressed in a floating point
17111 // type.
17112
17113 bool
check_float_type(Float_type * type,bool issue_error,Location location)17114 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
17115 Location location)
17116 {
17117 mpfr_t val;
17118 switch (this->classification_)
17119 {
17120 case NC_INT:
17121 case NC_RUNE:
17122 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
17123 break;
17124
17125 case NC_FLOAT:
17126 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
17127 break;
17128
17129 case NC_COMPLEX:
17130 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
17131 {
17132 if (issue_error)
17133 {
17134 this->set_invalid();
17135 go_error_at(location, "complex constant truncated to float");
17136 }
17137 return false;
17138 }
17139 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
17140 break;
17141
17142 default:
17143 go_unreachable();
17144 }
17145
17146 bool ret;
17147 if (type->is_abstract())
17148 ret = true;
17149 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
17150 {
17151 // A NaN or Infinity always fits in the range of the type.
17152 ret = true;
17153 }
17154 else
17155 {
17156 mp_exp_t exp = mpfr_get_exp(val);
17157 mp_exp_t max_exp;
17158 switch (type->bits())
17159 {
17160 case 32:
17161 max_exp = 128;
17162 break;
17163 case 64:
17164 max_exp = 1024;
17165 break;
17166 default:
17167 go_unreachable();
17168 }
17169
17170 ret = exp <= max_exp;
17171
17172 if (ret)
17173 {
17174 // Round the constant to the desired type.
17175 mpfr_t t;
17176 mpfr_init(t);
17177 switch (type->bits())
17178 {
17179 case 32:
17180 mpfr_set_prec(t, 24);
17181 break;
17182 case 64:
17183 mpfr_set_prec(t, 53);
17184 break;
17185 default:
17186 go_unreachable();
17187 }
17188 mpfr_set(t, val, GMP_RNDN);
17189 mpfr_set(val, t, GMP_RNDN);
17190 mpfr_clear(t);
17191
17192 this->set_float(type, val);
17193 }
17194 }
17195
17196 mpfr_clear(val);
17197
17198 if (!ret && issue_error)
17199 {
17200 go_error_at(location, "floating point constant overflow");
17201 this->set_invalid();
17202 }
17203
17204 return ret;
17205 }
17206
17207 // Check whether the constant can be expressed in a complex type.
17208
17209 bool
check_complex_type(Complex_type * type,bool issue_error,Location location)17210 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
17211 Location location)
17212 {
17213 if (type->is_abstract())
17214 return true;
17215
17216 mp_exp_t max_exp;
17217 switch (type->bits())
17218 {
17219 case 64:
17220 max_exp = 128;
17221 break;
17222 case 128:
17223 max_exp = 1024;
17224 break;
17225 default:
17226 go_unreachable();
17227 }
17228
17229 mpc_t val;
17230 mpc_init2(val, mpc_precision);
17231 switch (this->classification_)
17232 {
17233 case NC_INT:
17234 case NC_RUNE:
17235 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
17236 break;
17237
17238 case NC_FLOAT:
17239 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
17240 break;
17241
17242 case NC_COMPLEX:
17243 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
17244 break;
17245
17246 default:
17247 go_unreachable();
17248 }
17249
17250 bool ret = true;
17251 if (!mpfr_nan_p(mpc_realref(val))
17252 && !mpfr_inf_p(mpc_realref(val))
17253 && !mpfr_zero_p(mpc_realref(val))
17254 && mpfr_get_exp(mpc_realref(val)) > max_exp)
17255 {
17256 if (issue_error)
17257 {
17258 go_error_at(location, "complex real part overflow");
17259 this->set_invalid();
17260 }
17261 ret = false;
17262 }
17263
17264 if (!mpfr_nan_p(mpc_imagref(val))
17265 && !mpfr_inf_p(mpc_imagref(val))
17266 && !mpfr_zero_p(mpc_imagref(val))
17267 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
17268 {
17269 if (issue_error)
17270 {
17271 go_error_at(location, "complex imaginary part overflow");
17272 this->set_invalid();
17273 }
17274 ret = false;
17275 }
17276
17277 if (ret)
17278 {
17279 // Round the constant to the desired type.
17280 mpc_t t;
17281 switch (type->bits())
17282 {
17283 case 64:
17284 mpc_init2(t, 24);
17285 break;
17286 case 128:
17287 mpc_init2(t, 53);
17288 break;
17289 default:
17290 go_unreachable();
17291 }
17292 mpc_set(t, val, MPC_RNDNN);
17293 mpc_set(val, t, MPC_RNDNN);
17294 mpc_clear(t);
17295
17296 this->set_complex(type, val);
17297 }
17298
17299 mpc_clear(val);
17300
17301 return ret;
17302 }
17303
17304 // Return an Expression for this value.
17305
17306 Expression*
expression(Location loc) const17307 Numeric_constant::expression(Location loc) const
17308 {
17309 switch (this->classification_)
17310 {
17311 case NC_INT:
17312 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
17313 case NC_RUNE:
17314 return Expression::make_character(&this->u_.int_val, this->type_, loc);
17315 case NC_FLOAT:
17316 return Expression::make_float(&this->u_.float_val, this->type_, loc);
17317 case NC_COMPLEX:
17318 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
17319 case NC_INVALID:
17320 go_assert(saw_errors());
17321 return Expression::make_error(loc);
17322 default:
17323 go_unreachable();
17324 }
17325 }
17326
17327 // Calculate a hash code with a given seed.
17328
17329 unsigned int
hash(unsigned int seed) const17330 Numeric_constant::hash(unsigned int seed) const
17331 {
17332 unsigned long val;
17333 const unsigned int PRIME = 97;
17334 long e = 0;
17335 double f = 1.0;
17336 mpfr_t m;
17337
17338 switch (this->classification_)
17339 {
17340 case NC_INVALID:
17341 return PRIME;
17342 case NC_INT:
17343 case NC_RUNE:
17344 val = mpz_get_ui(this->u_.int_val);
17345 break;
17346 case NC_COMPLEX:
17347 mpfr_init(m);
17348 mpc_abs(m, this->u_.complex_val, GMP_RNDN);
17349 val = mpfr_get_ui(m, GMP_RNDN);
17350 mpfr_clear(m);
17351 break;
17352 case NC_FLOAT:
17353 f = mpfr_get_d_2exp(&e, this->u_.float_val, GMP_RNDN) * 4294967295.0;
17354 val = static_cast<unsigned long>(e + static_cast<long>(f));
17355 break;
17356 default:
17357 go_unreachable();
17358 }
17359
17360 return (static_cast<unsigned int>(val) + seed) * PRIME;
17361 }
17362
17363