]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/go/gofrontend/expressions.cc
Daily bump.
[thirdparty/gcc.git] / gcc / go / gofrontend / expressions.cc
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 "types.h"
14 #include "export.h"
15 #include "import.h"
16 #include "statements.h"
17 #include "lex.h"
18 #include "runtime.h"
19 #include "backend.h"
20 #include "expressions.h"
21 #include "ast-dump.h"
22
23 // Class Expression.
24
25 Expression::Expression(Expression_classification classification,
26 Location location)
27 : classification_(classification), location_(location)
28 {
29 }
30
31 Expression::~Expression()
32 {
33 }
34
35 // Traverse the expressions.
36
37 int
38 Expression::traverse(Expression** pexpr, Traverse* traverse)
39 {
40 Expression* expr = *pexpr;
41 if ((traverse->traverse_mask() & Traverse::traverse_expressions) != 0)
42 {
43 int t = traverse->expression(pexpr);
44 if (t == TRAVERSE_EXIT)
45 return TRAVERSE_EXIT;
46 else if (t == TRAVERSE_SKIP_COMPONENTS)
47 return TRAVERSE_CONTINUE;
48 }
49 return expr->do_traverse(traverse);
50 }
51
52 // Traverse subexpressions of this expression.
53
54 int
55 Expression::traverse_subexpressions(Traverse* traverse)
56 {
57 return this->do_traverse(traverse);
58 }
59
60 // Default implementation for do_traverse for child classes.
61
62 int
63 Expression::do_traverse(Traverse*)
64 {
65 return TRAVERSE_CONTINUE;
66 }
67
68 // This virtual function is called by the parser if the value of this
69 // expression is being discarded. By default, we give an error.
70 // Expressions with side effects override.
71
72 bool
73 Expression::do_discarding_value()
74 {
75 this->unused_value_error();
76 return false;
77 }
78
79 // This virtual function is called to export expressions. This will
80 // only be used by expressions which may be constant.
81
82 void
83 Expression::do_export(Export*) const
84 {
85 go_unreachable();
86 }
87
88 // Give an error saying that the value of the expression is not used.
89
90 void
91 Expression::unused_value_error()
92 {
93 this->report_error(_("value computed is not used"));
94 }
95
96 // Note that this expression is an error. This is called by children
97 // when they discover an error.
98
99 void
100 Expression::set_is_error()
101 {
102 this->classification_ = EXPRESSION_ERROR;
103 }
104
105 // For children to call to report an error conveniently.
106
107 void
108 Expression::report_error(const char* msg)
109 {
110 error_at(this->location_, "%s", msg);
111 this->set_is_error();
112 }
113
114 // Set types of variables and constants. This is implemented by the
115 // child class.
116
117 void
118 Expression::determine_type(const Type_context* context)
119 {
120 this->do_determine_type(context);
121 }
122
123 // Set types when there is no context.
124
125 void
126 Expression::determine_type_no_context()
127 {
128 Type_context context;
129 this->do_determine_type(&context);
130 }
131
132 // Return an expression handling any conversions which must be done during
133 // assignment.
134
135 Expression*
136 Expression::convert_for_assignment(Gogo*, Type* lhs_type,
137 Expression* rhs, Location location)
138 {
139 Type* rhs_type = rhs->type();
140 if (lhs_type->is_error()
141 || rhs_type->is_error()
142 || rhs->is_error_expression())
143 return Expression::make_error(location);
144
145 if (lhs_type->forwarded() != rhs_type->forwarded()
146 && lhs_type->interface_type() != NULL)
147 {
148 if (rhs_type->interface_type() == NULL)
149 return Expression::convert_type_to_interface(lhs_type, rhs, location);
150 else
151 return Expression::convert_interface_to_interface(lhs_type, rhs, false,
152 location);
153 }
154 else if (lhs_type->forwarded() != rhs_type->forwarded()
155 && rhs_type->interface_type() != NULL)
156 return Expression::convert_interface_to_type(lhs_type, rhs, location);
157 else if (lhs_type->is_slice_type() && rhs_type->is_nil_type())
158 {
159 // Assigning nil to a slice.
160 Expression* nil = Expression::make_nil(location);
161 Expression* zero = Expression::make_integer_ul(0, NULL, location);
162 return Expression::make_slice_value(lhs_type, nil, zero, zero, location);
163 }
164 else if (rhs_type->is_nil_type())
165 return Expression::make_nil(location);
166 else if (Type::are_identical(lhs_type, rhs_type, false, NULL))
167 {
168 // No conversion is needed.
169 return rhs;
170 }
171 else if (lhs_type->points_to() != NULL)
172 return Expression::make_unsafe_cast(lhs_type, rhs, location);
173 else if (lhs_type->is_numeric_type())
174 return Expression::make_cast(lhs_type, rhs, location);
175 else if ((lhs_type->struct_type() != NULL
176 && rhs_type->struct_type() != NULL)
177 || (lhs_type->array_type() != NULL
178 && rhs_type->array_type() != NULL))
179 {
180 // This conversion must be permitted by Go, or we wouldn't have
181 // gotten here.
182 return Expression::make_unsafe_cast(lhs_type, rhs, location);
183 }
184 else
185 return rhs;
186 }
187
188 // Return an expression for a conversion from a non-interface type to an
189 // interface type.
190
191 Expression*
192 Expression::convert_type_to_interface(Type* lhs_type, Expression* rhs,
193 Location location)
194 {
195 Interface_type* lhs_interface_type = lhs_type->interface_type();
196 bool lhs_is_empty = lhs_interface_type->is_empty();
197
198 // Since RHS_TYPE is a static type, we can create the interface
199 // method table at compile time.
200
201 // When setting an interface to nil, we just set both fields to
202 // NULL.
203 Type* rhs_type = rhs->type();
204 if (rhs_type->is_nil_type())
205 {
206 Expression* nil = Expression::make_nil(location);
207 return Expression::make_interface_value(lhs_type, nil, nil, location);
208 }
209
210 // This should have been checked already.
211 go_assert(lhs_interface_type->implements_interface(rhs_type, NULL));
212
213 // An interface is a tuple. If LHS_TYPE is an empty interface type,
214 // then the first field is the type descriptor for RHS_TYPE.
215 // Otherwise it is the interface method table for RHS_TYPE.
216 Expression* first_field;
217 if (lhs_is_empty)
218 first_field = Expression::make_type_descriptor(rhs_type, location);
219 else
220 {
221 // Build the interface method table for this interface and this
222 // object type: a list of function pointers for each interface
223 // method.
224 Named_type* rhs_named_type = rhs_type->named_type();
225 Struct_type* rhs_struct_type = rhs_type->struct_type();
226 bool is_pointer = false;
227 if (rhs_named_type == NULL && rhs_struct_type == NULL)
228 {
229 rhs_named_type = rhs_type->deref()->named_type();
230 rhs_struct_type = rhs_type->deref()->struct_type();
231 is_pointer = true;
232 }
233 if (rhs_named_type != NULL)
234 first_field =
235 rhs_named_type->interface_method_table(lhs_interface_type,
236 is_pointer);
237 else if (rhs_struct_type != NULL)
238 first_field =
239 rhs_struct_type->interface_method_table(lhs_interface_type,
240 is_pointer);
241 else
242 first_field = Expression::make_nil(location);
243 }
244
245 Expression* obj;
246 if (rhs_type->points_to() != NULL)
247 {
248 // We are assigning a pointer to the interface; the interface
249 // holds the pointer itself.
250 obj = rhs;
251 }
252 else
253 {
254 // We are assigning a non-pointer value to the interface; the
255 // interface gets a copy of the value in the heap.
256 obj = Expression::make_heap_expression(rhs, location);
257 }
258
259 return Expression::make_interface_value(lhs_type, first_field, obj, location);
260 }
261
262 // Return an expression for the type descriptor of RHS.
263
264 Expression*
265 Expression::get_interface_type_descriptor(Expression* rhs)
266 {
267 go_assert(rhs->type()->interface_type() != NULL);
268 Location location = rhs->location();
269
270 // The type descriptor is the first field of an empty interface.
271 if (rhs->type()->interface_type()->is_empty())
272 return Expression::make_interface_info(rhs, INTERFACE_INFO_TYPE_DESCRIPTOR,
273 location);
274
275 Expression* mtable =
276 Expression::make_interface_info(rhs, INTERFACE_INFO_METHODS, location);
277
278 Expression* descriptor =
279 Expression::make_unary(OPERATOR_MULT, mtable, location);
280 descriptor = Expression::make_field_reference(descriptor, 0, location);
281 Expression* nil = Expression::make_nil(location);
282
283 Expression* eq =
284 Expression::make_binary(OPERATOR_EQEQ, mtable, nil, location);
285 return Expression::make_conditional(eq, nil, descriptor, location);
286 }
287
288 // Return an expression for the conversion of an interface type to an
289 // interface type.
290
291 Expression*
292 Expression::convert_interface_to_interface(Type *lhs_type, Expression* rhs,
293 bool for_type_guard,
294 Location location)
295 {
296 if (Type::are_identical(lhs_type, rhs->type(), false, NULL))
297 return rhs;
298
299 Interface_type* lhs_interface_type = lhs_type->interface_type();
300 bool lhs_is_empty = lhs_interface_type->is_empty();
301
302 // In the general case this requires runtime examination of the type
303 // method table to match it up with the interface methods.
304
305 // FIXME: If all of the methods in the right hand side interface
306 // also appear in the left hand side interface, then we don't need
307 // to do a runtime check, although we still need to build a new
308 // method table.
309
310 // We are going to evaluate RHS multiple times.
311 go_assert(rhs->is_variable());
312
313 // Get the type descriptor for the right hand side. This will be
314 // NULL for a nil interface.
315 Expression* rhs_type_expr = Expression::get_interface_type_descriptor(rhs);
316 Expression* lhs_type_expr =
317 Expression::make_type_descriptor(lhs_type, location);
318
319 Expression* first_field;
320 if (for_type_guard)
321 {
322 // A type assertion fails when converting a nil interface.
323 first_field =
324 Runtime::make_call(Runtime::ASSERT_INTERFACE, location, 2,
325 lhs_type_expr, rhs_type_expr);
326 }
327 else if (lhs_is_empty)
328 {
329 // A conversion to an empty interface always succeeds, and the
330 // first field is just the type descriptor of the object.
331 first_field = rhs_type_expr;
332 }
333 else
334 {
335 // A conversion to a non-empty interface may fail, but unlike a
336 // type assertion converting nil will always succeed.
337 first_field =
338 Runtime::make_call(Runtime::CONVERT_INTERFACE, location, 2,
339 lhs_type_expr, rhs_type_expr);
340 }
341
342 // The second field is simply the object pointer.
343 Expression* obj =
344 Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT, location);
345 return Expression::make_interface_value(lhs_type, first_field, obj, location);
346 }
347
348 // Return an expression for the conversion of an interface type to a
349 // non-interface type.
350
351 Expression*
352 Expression::convert_interface_to_type(Type *lhs_type, Expression* rhs,
353 Location location)
354 {
355 // We are going to evaluate RHS multiple times.
356 go_assert(rhs->is_variable());
357
358 // Call a function to check that the type is valid. The function
359 // will panic with an appropriate runtime type error if the type is
360 // not valid.
361 Expression* lhs_type_expr = Expression::make_type_descriptor(lhs_type,
362 location);
363 Expression* rhs_descriptor =
364 Expression::get_interface_type_descriptor(rhs);
365
366 Type* rhs_type = rhs->type();
367 Expression* rhs_inter_expr = Expression::make_type_descriptor(rhs_type,
368 location);
369
370 Expression* check_iface = Runtime::make_call(Runtime::CHECK_INTERFACE_TYPE,
371 location, 3, lhs_type_expr,
372 rhs_descriptor, rhs_inter_expr);
373
374 // If the call succeeds, pull out the value.
375 Expression* obj = Expression::make_interface_info(rhs, INTERFACE_INFO_OBJECT,
376 location);
377
378 // If the value is a pointer, then it is the value we want.
379 // Otherwise it points to the value.
380 if (lhs_type->points_to() == NULL)
381 {
382 obj = Expression::make_unsafe_cast(Type::make_pointer_type(lhs_type), obj,
383 location);
384 obj = Expression::make_unary(OPERATOR_MULT, obj, location);
385 }
386 return Expression::make_compound(check_iface, obj, location);
387 }
388
389 // Convert an expression to its backend representation. This is implemented by
390 // the child class. Not that it is not in general safe to call this multiple
391 // times for a single expression, but that we don't catch such errors.
392
393 Bexpression*
394 Expression::get_backend(Translate_context* context)
395 {
396 // The child may have marked this expression as having an error.
397 if (this->classification_ == EXPRESSION_ERROR)
398 return context->backend()->error_expression();
399
400 return this->do_get_backend(context);
401 }
402
403 // Return a backend expression for VAL.
404 Bexpression*
405 Expression::backend_numeric_constant_expression(Translate_context* context,
406 Numeric_constant* val)
407 {
408 Gogo* gogo = context->gogo();
409 Type* type = val->type();
410 if (type == NULL)
411 return gogo->backend()->error_expression();
412
413 Btype* btype = type->get_backend(gogo);
414 Bexpression* ret;
415 if (type->integer_type() != NULL)
416 {
417 mpz_t ival;
418 if (!val->to_int(&ival))
419 {
420 go_assert(saw_errors());
421 return gogo->backend()->error_expression();
422 }
423 ret = gogo->backend()->integer_constant_expression(btype, ival);
424 mpz_clear(ival);
425 }
426 else if (type->float_type() != NULL)
427 {
428 mpfr_t fval;
429 if (!val->to_float(&fval))
430 {
431 go_assert(saw_errors());
432 return gogo->backend()->error_expression();
433 }
434 ret = gogo->backend()->float_constant_expression(btype, fval);
435 mpfr_clear(fval);
436 }
437 else if (type->complex_type() != NULL)
438 {
439 mpc_t cval;
440 if (!val->to_complex(&cval))
441 {
442 go_assert(saw_errors());
443 return gogo->backend()->error_expression();
444 }
445 ret = gogo->backend()->complex_constant_expression(btype, cval);
446 mpc_clear(cval);
447 }
448 else
449 go_unreachable();
450
451 return ret;
452 }
453
454 // Return an expression which evaluates to true if VAL, of arbitrary integer
455 // type, is negative or is more than the maximum value of the Go type "int".
456
457 Expression*
458 Expression::check_bounds(Expression* val, Location loc)
459 {
460 Type* val_type = val->type();
461 Type* bound_type = Type::lookup_integer_type("int");
462
463 int val_type_size;
464 bool val_is_unsigned = false;
465 if (val_type->integer_type() != NULL)
466 {
467 val_type_size = val_type->integer_type()->bits();
468 val_is_unsigned = val_type->integer_type()->is_unsigned();
469 }
470 else
471 {
472 if (!val_type->is_numeric_type()
473 || !Type::are_convertible(bound_type, val_type, NULL))
474 {
475 go_assert(saw_errors());
476 return Expression::make_boolean(true, loc);
477 }
478
479 if (val_type->complex_type() != NULL)
480 val_type_size = val_type->complex_type()->bits();
481 else
482 val_type_size = val_type->float_type()->bits();
483 }
484
485 Expression* negative_index = Expression::make_boolean(false, loc);
486 Expression* index_overflows = Expression::make_boolean(false, loc);
487 if (!val_is_unsigned)
488 {
489 Expression* zero = Expression::make_integer_ul(0, val_type, loc);
490 negative_index = Expression::make_binary(OPERATOR_LT, val, zero, loc);
491 }
492
493 int bound_type_size = bound_type->integer_type()->bits();
494 if (val_type_size > bound_type_size
495 || (val_type_size == bound_type_size
496 && val_is_unsigned))
497 {
498 mpz_t one;
499 mpz_init_set_ui(one, 1UL);
500
501 // maxval = 2^(bound_type_size - 1) - 1
502 mpz_t maxval;
503 mpz_init(maxval);
504 mpz_mul_2exp(maxval, one, bound_type_size - 1);
505 mpz_sub_ui(maxval, maxval, 1);
506 Expression* max = Expression::make_integer_z(&maxval, val_type, loc);
507 mpz_clear(one);
508 mpz_clear(maxval);
509
510 index_overflows = Expression::make_binary(OPERATOR_GT, val, max, loc);
511 }
512
513 return Expression::make_binary(OPERATOR_OROR, negative_index, index_overflows,
514 loc);
515 }
516
517 void
518 Expression::dump_expression(Ast_dump_context* ast_dump_context) const
519 {
520 this->do_dump_expression(ast_dump_context);
521 }
522
523 // Error expressions. This are used to avoid cascading errors.
524
525 class Error_expression : public Expression
526 {
527 public:
528 Error_expression(Location location)
529 : Expression(EXPRESSION_ERROR, location)
530 { }
531
532 protected:
533 bool
534 do_is_constant() const
535 { return true; }
536
537 bool
538 do_is_immutable() const
539 { return true; }
540
541 bool
542 do_numeric_constant_value(Numeric_constant* nc) const
543 {
544 nc->set_unsigned_long(NULL, 0);
545 return true;
546 }
547
548 bool
549 do_discarding_value()
550 { return true; }
551
552 Type*
553 do_type()
554 { return Type::make_error_type(); }
555
556 void
557 do_determine_type(const Type_context*)
558 { }
559
560 Expression*
561 do_copy()
562 { return this; }
563
564 bool
565 do_is_addressable() const
566 { return true; }
567
568 Bexpression*
569 do_get_backend(Translate_context* context)
570 { return context->backend()->error_expression(); }
571
572 void
573 do_dump_expression(Ast_dump_context*) const;
574 };
575
576 // Dump the ast representation for an error expression to a dump context.
577
578 void
579 Error_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
580 {
581 ast_dump_context->ostream() << "_Error_" ;
582 }
583
584 Expression*
585 Expression::make_error(Location location)
586 {
587 return new Error_expression(location);
588 }
589
590 // An expression which is really a type. This is used during parsing.
591 // It is an error if these survive after lowering.
592
593 class
594 Type_expression : public Expression
595 {
596 public:
597 Type_expression(Type* type, Location location)
598 : Expression(EXPRESSION_TYPE, location),
599 type_(type)
600 { }
601
602 protected:
603 int
604 do_traverse(Traverse* traverse)
605 { return Type::traverse(this->type_, traverse); }
606
607 Type*
608 do_type()
609 { return this->type_; }
610
611 void
612 do_determine_type(const Type_context*)
613 { }
614
615 void
616 do_check_types(Gogo*)
617 { this->report_error(_("invalid use of type")); }
618
619 Expression*
620 do_copy()
621 { return this; }
622
623 Bexpression*
624 do_get_backend(Translate_context*)
625 { go_unreachable(); }
626
627 void do_dump_expression(Ast_dump_context*) const;
628
629 private:
630 // The type which we are representing as an expression.
631 Type* type_;
632 };
633
634 void
635 Type_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
636 {
637 ast_dump_context->dump_type(this->type_);
638 }
639
640 Expression*
641 Expression::make_type(Type* type, Location location)
642 {
643 return new Type_expression(type, location);
644 }
645
646 // Class Parser_expression.
647
648 Type*
649 Parser_expression::do_type()
650 {
651 // We should never really ask for the type of a Parser_expression.
652 // However, it can happen, at least when we have an invalid const
653 // whose initializer refers to the const itself. In that case we
654 // may ask for the type when lowering the const itself.
655 go_assert(saw_errors());
656 return Type::make_error_type();
657 }
658
659 // Class Var_expression.
660
661 // Lower a variable expression. Here we just make sure that the
662 // initialization expression of the variable has been lowered. This
663 // ensures that we will be able to determine the type of the variable
664 // if necessary.
665
666 Expression*
667 Var_expression::do_lower(Gogo* gogo, Named_object* function,
668 Statement_inserter* inserter, int)
669 {
670 if (this->variable_->is_variable())
671 {
672 Variable* var = this->variable_->var_value();
673 // This is either a local variable or a global variable. A
674 // reference to a variable which is local to an enclosing
675 // function will be a reference to a field in a closure.
676 if (var->is_global())
677 {
678 function = NULL;
679 inserter = NULL;
680 }
681 var->lower_init_expression(gogo, function, inserter);
682 }
683 return this;
684 }
685
686 // Return the type of a reference to a variable.
687
688 Type*
689 Var_expression::do_type()
690 {
691 if (this->variable_->is_variable())
692 return this->variable_->var_value()->type();
693 else if (this->variable_->is_result_variable())
694 return this->variable_->result_var_value()->type();
695 else
696 go_unreachable();
697 }
698
699 // Determine the type of a reference to a variable.
700
701 void
702 Var_expression::do_determine_type(const Type_context*)
703 {
704 if (this->variable_->is_variable())
705 this->variable_->var_value()->determine_type();
706 }
707
708 // Something takes the address of this variable. This means that we
709 // may want to move the variable onto the heap.
710
711 void
712 Var_expression::do_address_taken(bool escapes)
713 {
714 if (!escapes)
715 {
716 if (this->variable_->is_variable())
717 this->variable_->var_value()->set_non_escaping_address_taken();
718 else if (this->variable_->is_result_variable())
719 this->variable_->result_var_value()->set_non_escaping_address_taken();
720 else
721 go_unreachable();
722 }
723 else
724 {
725 if (this->variable_->is_variable())
726 this->variable_->var_value()->set_address_taken();
727 else if (this->variable_->is_result_variable())
728 this->variable_->result_var_value()->set_address_taken();
729 else
730 go_unreachable();
731 }
732 }
733
734 // Get the backend representation for a reference to a variable.
735
736 Bexpression*
737 Var_expression::do_get_backend(Translate_context* context)
738 {
739 Bvariable* bvar = this->variable_->get_backend_variable(context->gogo(),
740 context->function());
741 bool is_in_heap;
742 Location loc = this->location();
743 Btype* btype;
744 Gogo* gogo = context->gogo();
745 if (this->variable_->is_variable())
746 {
747 is_in_heap = this->variable_->var_value()->is_in_heap();
748 btype = this->variable_->var_value()->type()->get_backend(gogo);
749 }
750 else if (this->variable_->is_result_variable())
751 {
752 is_in_heap = this->variable_->result_var_value()->is_in_heap();
753 btype = this->variable_->result_var_value()->type()->get_backend(gogo);
754 }
755 else
756 go_unreachable();
757
758 Bexpression* ret = context->backend()->var_expression(bvar, loc);
759 if (is_in_heap)
760 ret = context->backend()->indirect_expression(btype, ret, true, loc);
761 return ret;
762 }
763
764 // Ast dump for variable expression.
765
766 void
767 Var_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
768 {
769 ast_dump_context->ostream() << this->variable_->name() ;
770 }
771
772 // Make a reference to a variable in an expression.
773
774 Expression*
775 Expression::make_var_reference(Named_object* var, Location location)
776 {
777 if (var->is_sink())
778 return Expression::make_sink(location);
779
780 // FIXME: Creating a new object for each reference to a variable is
781 // wasteful.
782 return new Var_expression(var, location);
783 }
784
785 // Class Temporary_reference_expression.
786
787 // The type.
788
789 Type*
790 Temporary_reference_expression::do_type()
791 {
792 return this->statement_->type();
793 }
794
795 // Called if something takes the address of this temporary variable.
796 // We never have to move temporary variables to the heap, but we do
797 // need to know that they must live in the stack rather than in a
798 // register.
799
800 void
801 Temporary_reference_expression::do_address_taken(bool)
802 {
803 this->statement_->set_is_address_taken();
804 }
805
806 // Get a backend expression referring to the variable.
807
808 Bexpression*
809 Temporary_reference_expression::do_get_backend(Translate_context* context)
810 {
811 Gogo* gogo = context->gogo();
812 Bvariable* bvar = this->statement_->get_backend_variable(context);
813 Bexpression* ret = gogo->backend()->var_expression(bvar, this->location());
814
815 // The backend can't always represent the same set of recursive types
816 // that the Go frontend can. In some cases this means that a
817 // temporary variable won't have the right backend type. Correct
818 // that here by adding a type cast. We need to use base() to push
819 // the circularity down one level.
820 Type* stype = this->statement_->type();
821 if (!this->is_lvalue_
822 && stype->has_pointer()
823 && stype->deref()->is_void_type())
824 {
825 Btype* btype = this->type()->base()->get_backend(gogo);
826 ret = gogo->backend()->convert_expression(btype, ret, this->location());
827 }
828 return ret;
829 }
830
831 // Ast dump for temporary reference.
832
833 void
834 Temporary_reference_expression::do_dump_expression(
835 Ast_dump_context* ast_dump_context) const
836 {
837 ast_dump_context->dump_temp_variable_name(this->statement_);
838 }
839
840 // Make a reference to a temporary variable.
841
842 Temporary_reference_expression*
843 Expression::make_temporary_reference(Temporary_statement* statement,
844 Location location)
845 {
846 return new Temporary_reference_expression(statement, location);
847 }
848
849 // Class Set_and_use_temporary_expression.
850
851 // Return the type.
852
853 Type*
854 Set_and_use_temporary_expression::do_type()
855 {
856 return this->statement_->type();
857 }
858
859 // Determine the type of the expression.
860
861 void
862 Set_and_use_temporary_expression::do_determine_type(
863 const Type_context* context)
864 {
865 this->expr_->determine_type(context);
866 }
867
868 // Take the address.
869
870 void
871 Set_and_use_temporary_expression::do_address_taken(bool)
872 {
873 this->statement_->set_is_address_taken();
874 }
875
876 // Return the backend representation.
877
878 Bexpression*
879 Set_and_use_temporary_expression::do_get_backend(Translate_context* context)
880 {
881 Location loc = this->location();
882 Gogo* gogo = context->gogo();
883 Bvariable* bvar = this->statement_->get_backend_variable(context);
884 Bexpression* var_ref = gogo->backend()->var_expression(bvar, loc);
885
886 Bexpression* bexpr = this->expr_->get_backend(context);
887 Bstatement* set = gogo->backend()->assignment_statement(var_ref, bexpr, loc);
888 var_ref = gogo->backend()->var_expression(bvar, loc);
889 Bexpression* ret = gogo->backend()->compound_expression(set, var_ref, loc);
890 return ret;
891 }
892
893 // Dump.
894
895 void
896 Set_and_use_temporary_expression::do_dump_expression(
897 Ast_dump_context* ast_dump_context) const
898 {
899 ast_dump_context->ostream() << '(';
900 ast_dump_context->dump_temp_variable_name(this->statement_);
901 ast_dump_context->ostream() << " = ";
902 this->expr_->dump_expression(ast_dump_context);
903 ast_dump_context->ostream() << ')';
904 }
905
906 // Make a set-and-use temporary.
907
908 Set_and_use_temporary_expression*
909 Expression::make_set_and_use_temporary(Temporary_statement* statement,
910 Expression* expr, Location location)
911 {
912 return new Set_and_use_temporary_expression(statement, expr, location);
913 }
914
915 // A sink expression--a use of the blank identifier _.
916
917 class Sink_expression : public Expression
918 {
919 public:
920 Sink_expression(Location location)
921 : Expression(EXPRESSION_SINK, location),
922 type_(NULL), bvar_(NULL)
923 { }
924
925 protected:
926 bool
927 do_discarding_value()
928 { return true; }
929
930 Type*
931 do_type();
932
933 void
934 do_determine_type(const Type_context*);
935
936 Expression*
937 do_copy()
938 { return new Sink_expression(this->location()); }
939
940 Bexpression*
941 do_get_backend(Translate_context*);
942
943 void
944 do_dump_expression(Ast_dump_context*) const;
945
946 private:
947 // The type of this sink variable.
948 Type* type_;
949 // The temporary variable we generate.
950 Bvariable* bvar_;
951 };
952
953 // Return the type of a sink expression.
954
955 Type*
956 Sink_expression::do_type()
957 {
958 if (this->type_ == NULL)
959 return Type::make_sink_type();
960 return this->type_;
961 }
962
963 // Determine the type of a sink expression.
964
965 void
966 Sink_expression::do_determine_type(const Type_context* context)
967 {
968 if (context->type != NULL)
969 this->type_ = context->type;
970 }
971
972 // Return a temporary variable for a sink expression. This will
973 // presumably be a write-only variable which the middle-end will drop.
974
975 Bexpression*
976 Sink_expression::do_get_backend(Translate_context* context)
977 {
978 Location loc = this->location();
979 Gogo* gogo = context->gogo();
980 if (this->bvar_ == NULL)
981 {
982 go_assert(this->type_ != NULL && !this->type_->is_sink_type());
983 Named_object* fn = context->function();
984 go_assert(fn != NULL);
985 Bfunction* fn_ctx = fn->func_value()->get_or_make_decl(gogo, fn);
986 Btype* bt = this->type_->get_backend(context->gogo());
987 Bstatement* decl;
988 this->bvar_ =
989 gogo->backend()->temporary_variable(fn_ctx, context->bblock(), bt, NULL,
990 false, loc, &decl);
991 Bexpression* var_ref = gogo->backend()->var_expression(this->bvar_, loc);
992 var_ref = gogo->backend()->compound_expression(decl, var_ref, loc);
993 return var_ref;
994 }
995 return gogo->backend()->var_expression(this->bvar_, loc);
996 }
997
998 // Ast dump for sink expression.
999
1000 void
1001 Sink_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1002 {
1003 ast_dump_context->ostream() << "_" ;
1004 }
1005
1006 // Make a sink expression.
1007
1008 Expression*
1009 Expression::make_sink(Location location)
1010 {
1011 return new Sink_expression(location);
1012 }
1013
1014 // Class Func_expression.
1015
1016 // FIXME: Can a function expression appear in a constant expression?
1017 // The value is unchanging. Initializing a constant to the address of
1018 // a function seems like it could work, though there might be little
1019 // point to it.
1020
1021 // Traversal.
1022
1023 int
1024 Func_expression::do_traverse(Traverse* traverse)
1025 {
1026 return (this->closure_ == NULL
1027 ? TRAVERSE_CONTINUE
1028 : Expression::traverse(&this->closure_, traverse));
1029 }
1030
1031 // Return the type of a function expression.
1032
1033 Type*
1034 Func_expression::do_type()
1035 {
1036 if (this->function_->is_function())
1037 return this->function_->func_value()->type();
1038 else if (this->function_->is_function_declaration())
1039 return this->function_->func_declaration_value()->type();
1040 else
1041 go_unreachable();
1042 }
1043
1044 // Get the backend representation for the code of a function expression.
1045
1046 Bexpression*
1047 Func_expression::get_code_pointer(Gogo* gogo, Named_object* no, Location loc)
1048 {
1049 Function_type* fntype;
1050 if (no->is_function())
1051 fntype = no->func_value()->type();
1052 else if (no->is_function_declaration())
1053 fntype = no->func_declaration_value()->type();
1054 else
1055 go_unreachable();
1056
1057 // Builtin functions are handled specially by Call_expression. We
1058 // can't take their address.
1059 if (fntype->is_builtin())
1060 {
1061 error_at(loc,
1062 "invalid use of special builtin function %qs; must be called",
1063 no->message_name().c_str());
1064 return gogo->backend()->error_expression();
1065 }
1066
1067 Bfunction* fndecl;
1068 if (no->is_function())
1069 fndecl = no->func_value()->get_or_make_decl(gogo, no);
1070 else if (no->is_function_declaration())
1071 fndecl = no->func_declaration_value()->get_or_make_decl(gogo, no);
1072 else
1073 go_unreachable();
1074
1075 return gogo->backend()->function_code_expression(fndecl, loc);
1076 }
1077
1078 // Get the backend representation for a function expression. This is used when
1079 // we take the address of a function rather than simply calling it. A func
1080 // value is represented as a pointer to a block of memory. The first
1081 // word of that memory is a pointer to the function code. The
1082 // remaining parts of that memory are the addresses of variables that
1083 // the function closes over.
1084
1085 Bexpression*
1086 Func_expression::do_get_backend(Translate_context* context)
1087 {
1088 // If there is no closure, just use the function descriptor.
1089 if (this->closure_ == NULL)
1090 {
1091 Gogo* gogo = context->gogo();
1092 Named_object* no = this->function_;
1093 Expression* descriptor;
1094 if (no->is_function())
1095 descriptor = no->func_value()->descriptor(gogo, no);
1096 else if (no->is_function_declaration())
1097 {
1098 if (no->func_declaration_value()->type()->is_builtin())
1099 {
1100 error_at(this->location(),
1101 ("invalid use of special builtin function %qs; "
1102 "must be called"),
1103 no->message_name().c_str());
1104 return gogo->backend()->error_expression();
1105 }
1106 descriptor = no->func_declaration_value()->descriptor(gogo, no);
1107 }
1108 else
1109 go_unreachable();
1110
1111 Bexpression* bdesc = descriptor->get_backend(context);
1112 return gogo->backend()->address_expression(bdesc, this->location());
1113 }
1114
1115 go_assert(this->function_->func_value()->enclosing() != NULL);
1116
1117 // If there is a closure, then the closure is itself the function
1118 // expression. It is a pointer to a struct whose first field points
1119 // to the function code and whose remaining fields are the addresses
1120 // of the closed-over variables.
1121 return this->closure_->get_backend(context);
1122 }
1123
1124 // Ast dump for function.
1125
1126 void
1127 Func_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1128 {
1129 ast_dump_context->ostream() << this->function_->name();
1130 if (this->closure_ != NULL)
1131 {
1132 ast_dump_context->ostream() << " {closure = ";
1133 this->closure_->dump_expression(ast_dump_context);
1134 ast_dump_context->ostream() << "}";
1135 }
1136 }
1137
1138 // Make a reference to a function in an expression.
1139
1140 Expression*
1141 Expression::make_func_reference(Named_object* function, Expression* closure,
1142 Location location)
1143 {
1144 return new Func_expression(function, closure, location);
1145 }
1146
1147 // Class Func_descriptor_expression.
1148
1149 // Constructor.
1150
1151 Func_descriptor_expression::Func_descriptor_expression(Named_object* fn)
1152 : Expression(EXPRESSION_FUNC_DESCRIPTOR, fn->location()),
1153 fn_(fn), dvar_(NULL)
1154 {
1155 go_assert(!fn->is_function() || !fn->func_value()->needs_closure());
1156 }
1157
1158 // Traversal.
1159
1160 int
1161 Func_descriptor_expression::do_traverse(Traverse*)
1162 {
1163 return TRAVERSE_CONTINUE;
1164 }
1165
1166 // All function descriptors have the same type.
1167
1168 Type* Func_descriptor_expression::descriptor_type;
1169
1170 void
1171 Func_descriptor_expression::make_func_descriptor_type()
1172 {
1173 if (Func_descriptor_expression::descriptor_type != NULL)
1174 return;
1175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1176 Type* struct_type = Type::make_builtin_struct_type(1, "code", uintptr_type);
1177 Func_descriptor_expression::descriptor_type =
1178 Type::make_builtin_named_type("functionDescriptor", struct_type);
1179 }
1180
1181 Type*
1182 Func_descriptor_expression::do_type()
1183 {
1184 Func_descriptor_expression::make_func_descriptor_type();
1185 return Func_descriptor_expression::descriptor_type;
1186 }
1187
1188 // The backend representation for a function descriptor.
1189
1190 Bexpression*
1191 Func_descriptor_expression::do_get_backend(Translate_context* context)
1192 {
1193 Named_object* no = this->fn_;
1194 Location loc = no->location();
1195 if (this->dvar_ != NULL)
1196 return context->backend()->var_expression(this->dvar_, loc);
1197
1198 Gogo* gogo = context->gogo();
1199 std::string var_name;
1200 if (no->package() == NULL)
1201 var_name = gogo->pkgpath_symbol();
1202 else
1203 var_name = no->package()->pkgpath_symbol();
1204 var_name.push_back('.');
1205 var_name.append(Gogo::unpack_hidden_name(no->name()));
1206 var_name.append("$descriptor");
1207
1208 Btype* btype = this->type()->get_backend(gogo);
1209
1210 Bvariable* bvar;
1211 if (no->package() != NULL
1212 || Linemap::is_predeclared_location(no->location()))
1213 bvar = context->backend()->immutable_struct_reference(var_name, btype,
1214 loc);
1215 else
1216 {
1217 Location bloc = Linemap::predeclared_location();
1218 bool is_hidden = ((no->is_function()
1219 && no->func_value()->enclosing() != NULL)
1220 || Gogo::is_thunk(no));
1221 bvar = context->backend()->immutable_struct(var_name, is_hidden, false,
1222 btype, bloc);
1223 Expression_list* vals = new Expression_list();
1224 vals->push_back(Expression::make_func_code_reference(this->fn_, bloc));
1225 Expression* init =
1226 Expression::make_struct_composite_literal(this->type(), vals, bloc);
1227 Translate_context bcontext(gogo, NULL, NULL, NULL);
1228 bcontext.set_is_const();
1229 Bexpression* binit = init->get_backend(&bcontext);
1230 context->backend()->immutable_struct_set_init(bvar, var_name, is_hidden,
1231 false, btype, bloc, binit);
1232 }
1233
1234 this->dvar_ = bvar;
1235 return gogo->backend()->var_expression(bvar, loc);
1236 }
1237
1238 // Print a function descriptor expression.
1239
1240 void
1241 Func_descriptor_expression::do_dump_expression(Ast_dump_context* context) const
1242 {
1243 context->ostream() << "[descriptor " << this->fn_->name() << "]";
1244 }
1245
1246 // Make a function descriptor expression.
1247
1248 Func_descriptor_expression*
1249 Expression::make_func_descriptor(Named_object* fn)
1250 {
1251 return new Func_descriptor_expression(fn);
1252 }
1253
1254 // Make the function descriptor type, so that it can be converted.
1255
1256 void
1257 Expression::make_func_descriptor_type()
1258 {
1259 Func_descriptor_expression::make_func_descriptor_type();
1260 }
1261
1262 // A reference to just the code of a function.
1263
1264 class Func_code_reference_expression : public Expression
1265 {
1266 public:
1267 Func_code_reference_expression(Named_object* function, Location location)
1268 : Expression(EXPRESSION_FUNC_CODE_REFERENCE, location),
1269 function_(function)
1270 { }
1271
1272 protected:
1273 int
1274 do_traverse(Traverse*)
1275 { return TRAVERSE_CONTINUE; }
1276
1277 bool
1278 do_is_immutable() const
1279 { return true; }
1280
1281 Type*
1282 do_type()
1283 { return Type::make_pointer_type(Type::make_void_type()); }
1284
1285 void
1286 do_determine_type(const Type_context*)
1287 { }
1288
1289 Expression*
1290 do_copy()
1291 {
1292 return Expression::make_func_code_reference(this->function_,
1293 this->location());
1294 }
1295
1296 Bexpression*
1297 do_get_backend(Translate_context*);
1298
1299 void
1300 do_dump_expression(Ast_dump_context* context) const
1301 { context->ostream() << "[raw " << this->function_->name() << "]" ; }
1302
1303 private:
1304 // The function.
1305 Named_object* function_;
1306 };
1307
1308 // Get the backend representation for a reference to function code.
1309
1310 Bexpression*
1311 Func_code_reference_expression::do_get_backend(Translate_context* context)
1312 {
1313 return Func_expression::get_code_pointer(context->gogo(), this->function_,
1314 this->location());
1315 }
1316
1317 // Make a reference to the code of a function.
1318
1319 Expression*
1320 Expression::make_func_code_reference(Named_object* function, Location location)
1321 {
1322 return new Func_code_reference_expression(function, location);
1323 }
1324
1325 // Class Unknown_expression.
1326
1327 // Return the name of an unknown expression.
1328
1329 const std::string&
1330 Unknown_expression::name() const
1331 {
1332 return this->named_object_->name();
1333 }
1334
1335 // Lower a reference to an unknown name.
1336
1337 Expression*
1338 Unknown_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
1339 {
1340 Location location = this->location();
1341 Named_object* no = this->named_object_;
1342 Named_object* real;
1343 if (!no->is_unknown())
1344 real = no;
1345 else
1346 {
1347 real = no->unknown_value()->real_named_object();
1348 if (real == NULL)
1349 {
1350 if (this->is_composite_literal_key_)
1351 return this;
1352 if (!this->no_error_message_)
1353 error_at(location, "reference to undefined name %qs",
1354 this->named_object_->message_name().c_str());
1355 return Expression::make_error(location);
1356 }
1357 }
1358 switch (real->classification())
1359 {
1360 case Named_object::NAMED_OBJECT_CONST:
1361 return Expression::make_const_reference(real, location);
1362 case Named_object::NAMED_OBJECT_TYPE:
1363 return Expression::make_type(real->type_value(), location);
1364 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
1365 if (this->is_composite_literal_key_)
1366 return this;
1367 if (!this->no_error_message_)
1368 error_at(location, "reference to undefined type %qs",
1369 real->message_name().c_str());
1370 return Expression::make_error(location);
1371 case Named_object::NAMED_OBJECT_VAR:
1372 real->var_value()->set_is_used();
1373 return Expression::make_var_reference(real, location);
1374 case Named_object::NAMED_OBJECT_FUNC:
1375 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
1376 return Expression::make_func_reference(real, NULL, location);
1377 case Named_object::NAMED_OBJECT_PACKAGE:
1378 if (this->is_composite_literal_key_)
1379 return this;
1380 if (!this->no_error_message_)
1381 error_at(location, "unexpected reference to package");
1382 return Expression::make_error(location);
1383 default:
1384 go_unreachable();
1385 }
1386 }
1387
1388 // Dump the ast representation for an unknown expression to a dump context.
1389
1390 void
1391 Unknown_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1392 {
1393 ast_dump_context->ostream() << "_Unknown_(" << this->named_object_->name()
1394 << ")";
1395 }
1396
1397 // Make a reference to an unknown name.
1398
1399 Unknown_expression*
1400 Expression::make_unknown_reference(Named_object* no, Location location)
1401 {
1402 return new Unknown_expression(no, location);
1403 }
1404
1405 // A boolean expression.
1406
1407 class Boolean_expression : public Expression
1408 {
1409 public:
1410 Boolean_expression(bool val, Location location)
1411 : Expression(EXPRESSION_BOOLEAN, location),
1412 val_(val), type_(NULL)
1413 { }
1414
1415 static Expression*
1416 do_import(Import*);
1417
1418 protected:
1419 bool
1420 do_is_constant() const
1421 { return true; }
1422
1423 bool
1424 do_is_immutable() const
1425 { return true; }
1426
1427 Type*
1428 do_type();
1429
1430 void
1431 do_determine_type(const Type_context*);
1432
1433 Expression*
1434 do_copy()
1435 { return this; }
1436
1437 Bexpression*
1438 do_get_backend(Translate_context* context)
1439 { return context->backend()->boolean_constant_expression(this->val_); }
1440
1441 void
1442 do_export(Export* exp) const
1443 { exp->write_c_string(this->val_ ? "true" : "false"); }
1444
1445 void
1446 do_dump_expression(Ast_dump_context* ast_dump_context) const
1447 { ast_dump_context->ostream() << (this->val_ ? "true" : "false"); }
1448
1449 private:
1450 // The constant.
1451 bool val_;
1452 // The type as determined by context.
1453 Type* type_;
1454 };
1455
1456 // Get the type.
1457
1458 Type*
1459 Boolean_expression::do_type()
1460 {
1461 if (this->type_ == NULL)
1462 this->type_ = Type::make_boolean_type();
1463 return this->type_;
1464 }
1465
1466 // Set the type from the context.
1467
1468 void
1469 Boolean_expression::do_determine_type(const Type_context* context)
1470 {
1471 if (this->type_ != NULL && !this->type_->is_abstract())
1472 ;
1473 else if (context->type != NULL && context->type->is_boolean_type())
1474 this->type_ = context->type;
1475 else if (!context->may_be_abstract)
1476 this->type_ = Type::lookup_bool_type();
1477 }
1478
1479 // Import a boolean constant.
1480
1481 Expression*
1482 Boolean_expression::do_import(Import* imp)
1483 {
1484 if (imp->peek_char() == 't')
1485 {
1486 imp->require_c_string("true");
1487 return Expression::make_boolean(true, imp->location());
1488 }
1489 else
1490 {
1491 imp->require_c_string("false");
1492 return Expression::make_boolean(false, imp->location());
1493 }
1494 }
1495
1496 // Make a boolean expression.
1497
1498 Expression*
1499 Expression::make_boolean(bool val, Location location)
1500 {
1501 return new Boolean_expression(val, location);
1502 }
1503
1504 // Class String_expression.
1505
1506 // Get the type.
1507
1508 Type*
1509 String_expression::do_type()
1510 {
1511 if (this->type_ == NULL)
1512 this->type_ = Type::make_string_type();
1513 return this->type_;
1514 }
1515
1516 // Set the type from the context.
1517
1518 void
1519 String_expression::do_determine_type(const Type_context* context)
1520 {
1521 if (this->type_ != NULL && !this->type_->is_abstract())
1522 ;
1523 else if (context->type != NULL && context->type->is_string_type())
1524 this->type_ = context->type;
1525 else if (!context->may_be_abstract)
1526 this->type_ = Type::lookup_string_type();
1527 }
1528
1529 // Build a string constant.
1530
1531 Bexpression*
1532 String_expression::do_get_backend(Translate_context* context)
1533 {
1534 Gogo* gogo = context->gogo();
1535 Btype* btype = Type::make_string_type()->get_backend(gogo);
1536
1537 Location loc = this->location();
1538 std::vector<Bexpression*> init(2);
1539 Bexpression* str_cst =
1540 gogo->backend()->string_constant_expression(this->val_);
1541 init[0] = gogo->backend()->address_expression(str_cst, loc);
1542
1543 Btype* int_btype = Type::lookup_integer_type("int")->get_backend(gogo);
1544 mpz_t lenval;
1545 mpz_init_set_ui(lenval, this->val_.length());
1546 init[1] = gogo->backend()->integer_constant_expression(int_btype, lenval);
1547 mpz_clear(lenval);
1548
1549 return gogo->backend()->constructor_expression(btype, init, loc);
1550 }
1551
1552 // Write string literal to string dump.
1553
1554 void
1555 String_expression::export_string(String_dump* exp,
1556 const String_expression* str)
1557 {
1558 std::string s;
1559 s.reserve(str->val_.length() * 4 + 2);
1560 s += '"';
1561 for (std::string::const_iterator p = str->val_.begin();
1562 p != str->val_.end();
1563 ++p)
1564 {
1565 if (*p == '\\' || *p == '"')
1566 {
1567 s += '\\';
1568 s += *p;
1569 }
1570 else if (*p >= 0x20 && *p < 0x7f)
1571 s += *p;
1572 else if (*p == '\n')
1573 s += "\\n";
1574 else if (*p == '\t')
1575 s += "\\t";
1576 else
1577 {
1578 s += "\\x";
1579 unsigned char c = *p;
1580 unsigned int dig = c >> 4;
1581 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1582 dig = c & 0xf;
1583 s += dig < 10 ? '0' + dig : 'A' + dig - 10;
1584 }
1585 }
1586 s += '"';
1587 exp->write_string(s);
1588 }
1589
1590 // Export a string expression.
1591
1592 void
1593 String_expression::do_export(Export* exp) const
1594 {
1595 String_expression::export_string(exp, this);
1596 }
1597
1598 // Import a string expression.
1599
1600 Expression*
1601 String_expression::do_import(Import* imp)
1602 {
1603 imp->require_c_string("\"");
1604 std::string val;
1605 while (true)
1606 {
1607 int c = imp->get_char();
1608 if (c == '"' || c == -1)
1609 break;
1610 if (c != '\\')
1611 val += static_cast<char>(c);
1612 else
1613 {
1614 c = imp->get_char();
1615 if (c == '\\' || c == '"')
1616 val += static_cast<char>(c);
1617 else if (c == 'n')
1618 val += '\n';
1619 else if (c == 't')
1620 val += '\t';
1621 else if (c == 'x')
1622 {
1623 c = imp->get_char();
1624 unsigned int vh = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1625 c = imp->get_char();
1626 unsigned int vl = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
1627 char v = (vh << 4) | vl;
1628 val += v;
1629 }
1630 else
1631 {
1632 error_at(imp->location(), "bad string constant");
1633 return Expression::make_error(imp->location());
1634 }
1635 }
1636 }
1637 return Expression::make_string(val, imp->location());
1638 }
1639
1640 // Ast dump for string expression.
1641
1642 void
1643 String_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
1644 {
1645 String_expression::export_string(ast_dump_context, this);
1646 }
1647
1648 // Make a string expression.
1649
1650 Expression*
1651 Expression::make_string(const std::string& val, Location location)
1652 {
1653 return new String_expression(val, location);
1654 }
1655
1656 // An expression that evaluates to some characteristic of a string.
1657 // This is used when indexing, bound-checking, or nil checking a string.
1658
1659 class String_info_expression : public Expression
1660 {
1661 public:
1662 String_info_expression(Expression* string, String_info string_info,
1663 Location location)
1664 : Expression(EXPRESSION_STRING_INFO, location),
1665 string_(string), string_info_(string_info)
1666 { }
1667
1668 protected:
1669 Type*
1670 do_type();
1671
1672 void
1673 do_determine_type(const Type_context*)
1674 { go_unreachable(); }
1675
1676 Expression*
1677 do_copy()
1678 {
1679 return new String_info_expression(this->string_->copy(), this->string_info_,
1680 this->location());
1681 }
1682
1683 Bexpression*
1684 do_get_backend(Translate_context* context);
1685
1686 void
1687 do_dump_expression(Ast_dump_context*) const;
1688
1689 void
1690 do_issue_nil_check()
1691 { this->string_->issue_nil_check(); }
1692
1693 private:
1694 // The string for which we are getting information.
1695 Expression* string_;
1696 // What information we want.
1697 String_info string_info_;
1698 };
1699
1700 // Return the type of the string info.
1701
1702 Type*
1703 String_info_expression::do_type()
1704 {
1705 switch (this->string_info_)
1706 {
1707 case STRING_INFO_DATA:
1708 {
1709 Type* byte_type = Type::lookup_integer_type("uint8");
1710 return Type::make_pointer_type(byte_type);
1711 }
1712 case STRING_INFO_LENGTH:
1713 return Type::lookup_integer_type("int");
1714 default:
1715 go_unreachable();
1716 }
1717 }
1718
1719 // Return string information in GENERIC.
1720
1721 Bexpression*
1722 String_info_expression::do_get_backend(Translate_context* context)
1723 {
1724 Gogo* gogo = context->gogo();
1725
1726 Bexpression* bstring = this->string_->get_backend(context);
1727 switch (this->string_info_)
1728 {
1729 case STRING_INFO_DATA:
1730 case STRING_INFO_LENGTH:
1731 return gogo->backend()->struct_field_expression(bstring,
1732 this->string_info_,
1733 this->location());
1734 break;
1735 default:
1736 go_unreachable();
1737 }
1738 }
1739
1740 // Dump ast representation for a type info expression.
1741
1742 void
1743 String_info_expression::do_dump_expression(
1744 Ast_dump_context* ast_dump_context) const
1745 {
1746 ast_dump_context->ostream() << "stringinfo(";
1747 this->string_->dump_expression(ast_dump_context);
1748 ast_dump_context->ostream() << ",";
1749 ast_dump_context->ostream() <<
1750 (this->string_info_ == STRING_INFO_DATA ? "data"
1751 : this->string_info_ == STRING_INFO_LENGTH ? "length"
1752 : "unknown");
1753 ast_dump_context->ostream() << ")";
1754 }
1755
1756 // Make a string info expression.
1757
1758 Expression*
1759 Expression::make_string_info(Expression* string, String_info string_info,
1760 Location location)
1761 {
1762 return new String_info_expression(string, string_info, location);
1763 }
1764
1765 // Make an integer expression.
1766
1767 class Integer_expression : public Expression
1768 {
1769 public:
1770 Integer_expression(const mpz_t* val, Type* type, bool is_character_constant,
1771 Location location)
1772 : Expression(EXPRESSION_INTEGER, location),
1773 type_(type), is_character_constant_(is_character_constant)
1774 { mpz_init_set(this->val_, *val); }
1775
1776 static Expression*
1777 do_import(Import*);
1778
1779 // Write VAL to string dump.
1780 static void
1781 export_integer(String_dump* exp, const mpz_t val);
1782
1783 // Write VAL to dump context.
1784 static void
1785 dump_integer(Ast_dump_context* ast_dump_context, const mpz_t val);
1786
1787 protected:
1788 bool
1789 do_is_constant() const
1790 { return true; }
1791
1792 bool
1793 do_is_immutable() const
1794 { return true; }
1795
1796 bool
1797 do_numeric_constant_value(Numeric_constant* nc) const;
1798
1799 Type*
1800 do_type();
1801
1802 void
1803 do_determine_type(const Type_context* context);
1804
1805 void
1806 do_check_types(Gogo*);
1807
1808 Bexpression*
1809 do_get_backend(Translate_context*);
1810
1811 Expression*
1812 do_copy()
1813 {
1814 if (this->is_character_constant_)
1815 return Expression::make_character(&this->val_, this->type_,
1816 this->location());
1817 else
1818 return Expression::make_integer_z(&this->val_, this->type_,
1819 this->location());
1820 }
1821
1822 void
1823 do_export(Export*) const;
1824
1825 void
1826 do_dump_expression(Ast_dump_context*) const;
1827
1828 private:
1829 // The integer value.
1830 mpz_t val_;
1831 // The type so far.
1832 Type* type_;
1833 // Whether this is a character constant.
1834 bool is_character_constant_;
1835 };
1836
1837 // Return a numeric constant for this expression. We have to mark
1838 // this as a character when appropriate.
1839
1840 bool
1841 Integer_expression::do_numeric_constant_value(Numeric_constant* nc) const
1842 {
1843 if (this->is_character_constant_)
1844 nc->set_rune(this->type_, this->val_);
1845 else
1846 nc->set_int(this->type_, this->val_);
1847 return true;
1848 }
1849
1850 // Return the current type. If we haven't set the type yet, we return
1851 // an abstract integer type.
1852
1853 Type*
1854 Integer_expression::do_type()
1855 {
1856 if (this->type_ == NULL)
1857 {
1858 if (this->is_character_constant_)
1859 this->type_ = Type::make_abstract_character_type();
1860 else
1861 this->type_ = Type::make_abstract_integer_type();
1862 }
1863 return this->type_;
1864 }
1865
1866 // Set the type of the integer value. Here we may switch from an
1867 // abstract type to a real type.
1868
1869 void
1870 Integer_expression::do_determine_type(const Type_context* context)
1871 {
1872 if (this->type_ != NULL && !this->type_->is_abstract())
1873 ;
1874 else if (context->type != NULL && context->type->is_numeric_type())
1875 this->type_ = context->type;
1876 else if (!context->may_be_abstract)
1877 {
1878 if (this->is_character_constant_)
1879 this->type_ = Type::lookup_integer_type("int32");
1880 else
1881 this->type_ = Type::lookup_integer_type("int");
1882 }
1883 }
1884
1885 // Check the type of an integer constant.
1886
1887 void
1888 Integer_expression::do_check_types(Gogo*)
1889 {
1890 Type* type = this->type_;
1891 if (type == NULL)
1892 return;
1893 Numeric_constant nc;
1894 if (this->is_character_constant_)
1895 nc.set_rune(NULL, this->val_);
1896 else
1897 nc.set_int(NULL, this->val_);
1898 if (!nc.set_type(type, true, this->location()))
1899 this->set_is_error();
1900 }
1901
1902 // Get the backend representation for an integer constant.
1903
1904 Bexpression*
1905 Integer_expression::do_get_backend(Translate_context* context)
1906 {
1907 Type* resolved_type = NULL;
1908 if (this->type_ != NULL && !this->type_->is_abstract())
1909 resolved_type = this->type_;
1910 else if (this->type_ != NULL && this->type_->float_type() != NULL)
1911 {
1912 // We are converting to an abstract floating point type.
1913 resolved_type = Type::lookup_float_type("float64");
1914 }
1915 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
1916 {
1917 // We are converting to an abstract complex type.
1918 resolved_type = Type::lookup_complex_type("complex128");
1919 }
1920 else
1921 {
1922 // If we still have an abstract type here, then this is being
1923 // used in a constant expression which didn't get reduced for
1924 // some reason. Use a type which will fit the value. We use <,
1925 // not <=, because we need an extra bit for the sign bit.
1926 int bits = mpz_sizeinbase(this->val_, 2);
1927 Type* int_type = Type::lookup_integer_type("int");
1928 if (bits < int_type->integer_type()->bits())
1929 resolved_type = int_type;
1930 else if (bits < 64)
1931 resolved_type = Type::lookup_integer_type("int64");
1932 else
1933 {
1934 if (!saw_errors())
1935 error_at(this->location(),
1936 "unknown type for large integer constant");
1937 return context->gogo()->backend()->error_expression();
1938 }
1939 }
1940 Numeric_constant nc;
1941 nc.set_int(resolved_type, this->val_);
1942 return Expression::backend_numeric_constant_expression(context, &nc);
1943 }
1944
1945 // Write VAL to export data.
1946
1947 void
1948 Integer_expression::export_integer(String_dump* exp, const mpz_t val)
1949 {
1950 char* s = mpz_get_str(NULL, 10, val);
1951 exp->write_c_string(s);
1952 free(s);
1953 }
1954
1955 // Export an integer in a constant expression.
1956
1957 void
1958 Integer_expression::do_export(Export* exp) const
1959 {
1960 Integer_expression::export_integer(exp, this->val_);
1961 if (this->is_character_constant_)
1962 exp->write_c_string("'");
1963 // A trailing space lets us reliably identify the end of the number.
1964 exp->write_c_string(" ");
1965 }
1966
1967 // Import an integer, floating point, or complex value. This handles
1968 // all these types because they all start with digits.
1969
1970 Expression*
1971 Integer_expression::do_import(Import* imp)
1972 {
1973 std::string num = imp->read_identifier();
1974 imp->require_c_string(" ");
1975 if (!num.empty() && num[num.length() - 1] == 'i')
1976 {
1977 mpfr_t real;
1978 size_t plus_pos = num.find('+', 1);
1979 size_t minus_pos = num.find('-', 1);
1980 size_t pos;
1981 if (plus_pos == std::string::npos)
1982 pos = minus_pos;
1983 else if (minus_pos == std::string::npos)
1984 pos = plus_pos;
1985 else
1986 {
1987 error_at(imp->location(), "bad number in import data: %qs",
1988 num.c_str());
1989 return Expression::make_error(imp->location());
1990 }
1991 if (pos == std::string::npos)
1992 mpfr_set_ui(real, 0, GMP_RNDN);
1993 else
1994 {
1995 std::string real_str = num.substr(0, pos);
1996 if (mpfr_init_set_str(real, real_str.c_str(), 10, GMP_RNDN) != 0)
1997 {
1998 error_at(imp->location(), "bad number in import data: %qs",
1999 real_str.c_str());
2000 return Expression::make_error(imp->location());
2001 }
2002 }
2003
2004 std::string imag_str;
2005 if (pos == std::string::npos)
2006 imag_str = num;
2007 else
2008 imag_str = num.substr(pos);
2009 imag_str = imag_str.substr(0, imag_str.size() - 1);
2010 mpfr_t imag;
2011 if (mpfr_init_set_str(imag, imag_str.c_str(), 10, GMP_RNDN) != 0)
2012 {
2013 error_at(imp->location(), "bad number in import data: %qs",
2014 imag_str.c_str());
2015 return Expression::make_error(imp->location());
2016 }
2017 mpc_t cval;
2018 mpc_init2(cval, mpc_precision);
2019 mpc_set_fr_fr(cval, real, imag, MPC_RNDNN);
2020 mpfr_clear(real);
2021 mpfr_clear(imag);
2022 Expression* ret = Expression::make_complex(&cval, NULL, imp->location());
2023 mpc_clear(cval);
2024 return ret;
2025 }
2026 else if (num.find('.') == std::string::npos
2027 && num.find('E') == std::string::npos)
2028 {
2029 bool is_character_constant = (!num.empty()
2030 && num[num.length() - 1] == '\'');
2031 if (is_character_constant)
2032 num = num.substr(0, num.length() - 1);
2033 mpz_t val;
2034 if (mpz_init_set_str(val, num.c_str(), 10) != 0)
2035 {
2036 error_at(imp->location(), "bad number in import data: %qs",
2037 num.c_str());
2038 return Expression::make_error(imp->location());
2039 }
2040 Expression* ret;
2041 if (is_character_constant)
2042 ret = Expression::make_character(&val, NULL, imp->location());
2043 else
2044 ret = Expression::make_integer_z(&val, NULL, imp->location());
2045 mpz_clear(val);
2046 return ret;
2047 }
2048 else
2049 {
2050 mpfr_t val;
2051 if (mpfr_init_set_str(val, num.c_str(), 10, GMP_RNDN) != 0)
2052 {
2053 error_at(imp->location(), "bad number in import data: %qs",
2054 num.c_str());
2055 return Expression::make_error(imp->location());
2056 }
2057 Expression* ret = Expression::make_float(&val, NULL, imp->location());
2058 mpfr_clear(val);
2059 return ret;
2060 }
2061 }
2062 // Ast dump for integer expression.
2063
2064 void
2065 Integer_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2066 {
2067 if (this->is_character_constant_)
2068 ast_dump_context->ostream() << '\'';
2069 Integer_expression::export_integer(ast_dump_context, this->val_);
2070 if (this->is_character_constant_)
2071 ast_dump_context->ostream() << '\'';
2072 }
2073
2074 // Build a new integer value from a multi-precision integer.
2075
2076 Expression*
2077 Expression::make_integer_z(const mpz_t* val, Type* type, Location location)
2078 {
2079 return new Integer_expression(val, type, false, location);
2080 }
2081
2082 // Build a new integer value from an unsigned long.
2083
2084 Expression*
2085 Expression::make_integer_ul(unsigned long val, Type *type, Location location)
2086 {
2087 mpz_t zval;
2088 mpz_init_set_ui(zval, val);
2089 Expression* ret = Expression::make_integer_z(&zval, type, location);
2090 mpz_clear(zval);
2091 return ret;
2092 }
2093
2094 // Build a new integer value from a signed long.
2095
2096 Expression*
2097 Expression::make_integer_sl(long val, Type *type, Location location)
2098 {
2099 mpz_t zval;
2100 mpz_init_set_si(zval, val);
2101 Expression* ret = Expression::make_integer_z(&zval, type, location);
2102 mpz_clear(zval);
2103 return ret;
2104 }
2105
2106 // Store an int64_t in an uninitialized mpz_t.
2107
2108 static void
2109 set_mpz_from_int64(mpz_t* zval, int64_t val)
2110 {
2111 if (val >= 0)
2112 {
2113 unsigned long ul = static_cast<unsigned long>(val);
2114 if (static_cast<int64_t>(ul) == val)
2115 {
2116 mpz_init_set_ui(*zval, ul);
2117 return;
2118 }
2119 }
2120 uint64_t uv;
2121 if (val >= 0)
2122 uv = static_cast<uint64_t>(val);
2123 else
2124 uv = static_cast<uint64_t>(- val);
2125 unsigned long ul = uv & 0xffffffffUL;
2126 mpz_init_set_ui(*zval, ul);
2127 mpz_t hval;
2128 mpz_init_set_ui(hval, static_cast<unsigned long>(uv >> 32));
2129 mpz_mul_2exp(hval, hval, 32);
2130 mpz_add(*zval, *zval, hval);
2131 mpz_clear(hval);
2132 if (val < 0)
2133 mpz_neg(*zval, *zval);
2134 }
2135
2136 // Build a new integer value from an int64_t.
2137
2138 Expression*
2139 Expression::make_integer_int64(int64_t val, Type* type, Location location)
2140 {
2141 mpz_t zval;
2142 set_mpz_from_int64(&zval, val);
2143 Expression* ret = Expression::make_integer_z(&zval, type, location);
2144 mpz_clear(zval);
2145 return ret;
2146 }
2147
2148 // Build a new character constant value.
2149
2150 Expression*
2151 Expression::make_character(const mpz_t* val, Type* type, Location location)
2152 {
2153 return new Integer_expression(val, type, true, location);
2154 }
2155
2156 // Floats.
2157
2158 class Float_expression : public Expression
2159 {
2160 public:
2161 Float_expression(const mpfr_t* val, Type* type, Location location)
2162 : Expression(EXPRESSION_FLOAT, location),
2163 type_(type)
2164 {
2165 mpfr_init_set(this->val_, *val, GMP_RNDN);
2166 }
2167
2168 // Write VAL to export data.
2169 static void
2170 export_float(String_dump* exp, const mpfr_t val);
2171
2172 // Write VAL to dump file.
2173 static void
2174 dump_float(Ast_dump_context* ast_dump_context, const mpfr_t val);
2175
2176 protected:
2177 bool
2178 do_is_constant() const
2179 { return true; }
2180
2181 bool
2182 do_is_immutable() const
2183 { return true; }
2184
2185 bool
2186 do_numeric_constant_value(Numeric_constant* nc) const
2187 {
2188 nc->set_float(this->type_, this->val_);
2189 return true;
2190 }
2191
2192 Type*
2193 do_type();
2194
2195 void
2196 do_determine_type(const Type_context*);
2197
2198 void
2199 do_check_types(Gogo*);
2200
2201 Expression*
2202 do_copy()
2203 { return Expression::make_float(&this->val_, this->type_,
2204 this->location()); }
2205
2206 Bexpression*
2207 do_get_backend(Translate_context*);
2208
2209 void
2210 do_export(Export*) const;
2211
2212 void
2213 do_dump_expression(Ast_dump_context*) const;
2214
2215 private:
2216 // The floating point value.
2217 mpfr_t val_;
2218 // The type so far.
2219 Type* type_;
2220 };
2221
2222 // Return the current type. If we haven't set the type yet, we return
2223 // an abstract float type.
2224
2225 Type*
2226 Float_expression::do_type()
2227 {
2228 if (this->type_ == NULL)
2229 this->type_ = Type::make_abstract_float_type();
2230 return this->type_;
2231 }
2232
2233 // Set the type of the float value. Here we may switch from an
2234 // abstract type to a real type.
2235
2236 void
2237 Float_expression::do_determine_type(const Type_context* context)
2238 {
2239 if (this->type_ != NULL && !this->type_->is_abstract())
2240 ;
2241 else if (context->type != NULL
2242 && (context->type->integer_type() != NULL
2243 || context->type->float_type() != NULL
2244 || context->type->complex_type() != NULL))
2245 this->type_ = context->type;
2246 else if (!context->may_be_abstract)
2247 this->type_ = Type::lookup_float_type("float64");
2248 }
2249
2250 // Check the type of a float value.
2251
2252 void
2253 Float_expression::do_check_types(Gogo*)
2254 {
2255 Type* type = this->type_;
2256 if (type == NULL)
2257 return;
2258 Numeric_constant nc;
2259 nc.set_float(NULL, this->val_);
2260 if (!nc.set_type(this->type_, true, this->location()))
2261 this->set_is_error();
2262 }
2263
2264 // Get the backend representation for a float constant.
2265
2266 Bexpression*
2267 Float_expression::do_get_backend(Translate_context* context)
2268 {
2269 Type* resolved_type;
2270 if (this->type_ != NULL && !this->type_->is_abstract())
2271 resolved_type = this->type_;
2272 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2273 {
2274 // We have an abstract integer type. We just hope for the best.
2275 resolved_type = Type::lookup_integer_type("int");
2276 }
2277 else if (this->type_ != NULL && this->type_->complex_type() != NULL)
2278 {
2279 // We are converting to an abstract complex type.
2280 resolved_type = Type::lookup_complex_type("complex128");
2281 }
2282 else
2283 {
2284 // If we still have an abstract type here, then this is being
2285 // used in a constant expression which didn't get reduced. We
2286 // just use float64 and hope for the best.
2287 resolved_type = Type::lookup_float_type("float64");
2288 }
2289
2290 Numeric_constant nc;
2291 nc.set_float(resolved_type, this->val_);
2292 return Expression::backend_numeric_constant_expression(context, &nc);
2293 }
2294
2295 // Write a floating point number to a string dump.
2296
2297 void
2298 Float_expression::export_float(String_dump *exp, const mpfr_t val)
2299 {
2300 mp_exp_t exponent;
2301 char* s = mpfr_get_str(NULL, &exponent, 10, 0, val, GMP_RNDN);
2302 if (*s == '-')
2303 exp->write_c_string("-");
2304 exp->write_c_string("0.");
2305 exp->write_c_string(*s == '-' ? s + 1 : s);
2306 mpfr_free_str(s);
2307 char buf[30];
2308 snprintf(buf, sizeof buf, "E%ld", exponent);
2309 exp->write_c_string(buf);
2310 }
2311
2312 // Export a floating point number in a constant expression.
2313
2314 void
2315 Float_expression::do_export(Export* exp) const
2316 {
2317 Float_expression::export_float(exp, this->val_);
2318 // A trailing space lets us reliably identify the end of the number.
2319 exp->write_c_string(" ");
2320 }
2321
2322 // Dump a floating point number to the dump file.
2323
2324 void
2325 Float_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2326 {
2327 Float_expression::export_float(ast_dump_context, this->val_);
2328 }
2329
2330 // Make a float expression.
2331
2332 Expression*
2333 Expression::make_float(const mpfr_t* val, Type* type, Location location)
2334 {
2335 return new Float_expression(val, type, location);
2336 }
2337
2338 // Complex numbers.
2339
2340 class Complex_expression : public Expression
2341 {
2342 public:
2343 Complex_expression(const mpc_t* val, Type* type, Location location)
2344 : Expression(EXPRESSION_COMPLEX, location),
2345 type_(type)
2346 {
2347 mpc_init2(this->val_, mpc_precision);
2348 mpc_set(this->val_, *val, MPC_RNDNN);
2349 }
2350
2351 // Write VAL to string dump.
2352 static void
2353 export_complex(String_dump* exp, const mpc_t val);
2354
2355 // Write REAL/IMAG to dump context.
2356 static void
2357 dump_complex(Ast_dump_context* ast_dump_context, const mpc_t val);
2358
2359 protected:
2360 bool
2361 do_is_constant() const
2362 { return true; }
2363
2364 bool
2365 do_is_immutable() const
2366 { return true; }
2367
2368 bool
2369 do_numeric_constant_value(Numeric_constant* nc) const
2370 {
2371 nc->set_complex(this->type_, this->val_);
2372 return true;
2373 }
2374
2375 Type*
2376 do_type();
2377
2378 void
2379 do_determine_type(const Type_context*);
2380
2381 void
2382 do_check_types(Gogo*);
2383
2384 Expression*
2385 do_copy()
2386 {
2387 return Expression::make_complex(&this->val_, this->type_,
2388 this->location());
2389 }
2390
2391 Bexpression*
2392 do_get_backend(Translate_context*);
2393
2394 void
2395 do_export(Export*) const;
2396
2397 void
2398 do_dump_expression(Ast_dump_context*) const;
2399
2400 private:
2401 // The complex value.
2402 mpc_t val_;
2403 // The type if known.
2404 Type* type_;
2405 };
2406
2407 // Return the current type. If we haven't set the type yet, we return
2408 // an abstract complex type.
2409
2410 Type*
2411 Complex_expression::do_type()
2412 {
2413 if (this->type_ == NULL)
2414 this->type_ = Type::make_abstract_complex_type();
2415 return this->type_;
2416 }
2417
2418 // Set the type of the complex value. Here we may switch from an
2419 // abstract type to a real type.
2420
2421 void
2422 Complex_expression::do_determine_type(const Type_context* context)
2423 {
2424 if (this->type_ != NULL && !this->type_->is_abstract())
2425 ;
2426 else if (context->type != NULL && context->type->is_numeric_type())
2427 this->type_ = context->type;
2428 else if (!context->may_be_abstract)
2429 this->type_ = Type::lookup_complex_type("complex128");
2430 }
2431
2432 // Check the type of a complex value.
2433
2434 void
2435 Complex_expression::do_check_types(Gogo*)
2436 {
2437 Type* type = this->type_;
2438 if (type == NULL)
2439 return;
2440 Numeric_constant nc;
2441 nc.set_complex(NULL, this->val_);
2442 if (!nc.set_type(this->type_, true, this->location()))
2443 this->set_is_error();
2444 }
2445
2446 // Get the backend representation for a complex constant.
2447
2448 Bexpression*
2449 Complex_expression::do_get_backend(Translate_context* context)
2450 {
2451 Type* resolved_type;
2452 if (this->type_ != NULL && !this->type_->is_abstract())
2453 resolved_type = this->type_;
2454 else if (this->type_ != NULL && this->type_->integer_type() != NULL)
2455 {
2456 // We are converting to an abstract integer type.
2457 resolved_type = Type::lookup_integer_type("int");
2458 }
2459 else if (this->type_ != NULL && this->type_->float_type() != NULL)
2460 {
2461 // We are converting to an abstract float type.
2462 resolved_type = Type::lookup_float_type("float64");
2463 }
2464 else
2465 {
2466 // If we still have an abstract type here, this is being
2467 // used in a constant expression which didn't get reduced. We
2468 // just use complex128 and hope for the best.
2469 resolved_type = Type::lookup_complex_type("complex128");
2470 }
2471
2472 Numeric_constant nc;
2473 nc.set_complex(resolved_type, this->val_);
2474 return Expression::backend_numeric_constant_expression(context, &nc);
2475 }
2476
2477 // Write REAL/IMAG to export data.
2478
2479 void
2480 Complex_expression::export_complex(String_dump* exp, const mpc_t val)
2481 {
2482 if (!mpfr_zero_p(mpc_realref(val)))
2483 {
2484 Float_expression::export_float(exp, mpc_realref(val));
2485 if (mpfr_sgn(mpc_imagref(val)) >= 0)
2486 exp->write_c_string("+");
2487 }
2488 Float_expression::export_float(exp, mpc_imagref(val));
2489 exp->write_c_string("i");
2490 }
2491
2492 // Export a complex number in a constant expression.
2493
2494 void
2495 Complex_expression::do_export(Export* exp) const
2496 {
2497 Complex_expression::export_complex(exp, this->val_);
2498 // A trailing space lets us reliably identify the end of the number.
2499 exp->write_c_string(" ");
2500 }
2501
2502 // Dump a complex expression to the dump file.
2503
2504 void
2505 Complex_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2506 {
2507 Complex_expression::export_complex(ast_dump_context, this->val_);
2508 }
2509
2510 // Make a complex expression.
2511
2512 Expression*
2513 Expression::make_complex(const mpc_t* val, Type* type, Location location)
2514 {
2515 return new Complex_expression(val, type, location);
2516 }
2517
2518 // Find a named object in an expression.
2519
2520 class Find_named_object : public Traverse
2521 {
2522 public:
2523 Find_named_object(Named_object* no)
2524 : Traverse(traverse_expressions),
2525 no_(no), found_(false)
2526 { }
2527
2528 // Whether we found the object.
2529 bool
2530 found() const
2531 { return this->found_; }
2532
2533 protected:
2534 int
2535 expression(Expression**);
2536
2537 private:
2538 // The object we are looking for.
2539 Named_object* no_;
2540 // Whether we found it.
2541 bool found_;
2542 };
2543
2544 // A reference to a const in an expression.
2545
2546 class Const_expression : public Expression
2547 {
2548 public:
2549 Const_expression(Named_object* constant, Location location)
2550 : Expression(EXPRESSION_CONST_REFERENCE, location),
2551 constant_(constant), type_(NULL), seen_(false)
2552 { }
2553
2554 Named_object*
2555 named_object()
2556 { return this->constant_; }
2557
2558 // Check that the initializer does not refer to the constant itself.
2559 void
2560 check_for_init_loop();
2561
2562 protected:
2563 int
2564 do_traverse(Traverse*);
2565
2566 Expression*
2567 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
2568
2569 bool
2570 do_is_constant() const
2571 { return true; }
2572
2573 bool
2574 do_is_immutable() const
2575 { return true; }
2576
2577 bool
2578 do_numeric_constant_value(Numeric_constant* nc) const;
2579
2580 bool
2581 do_string_constant_value(std::string* val) const;
2582
2583 Type*
2584 do_type();
2585
2586 // The type of a const is set by the declaration, not the use.
2587 void
2588 do_determine_type(const Type_context*);
2589
2590 void
2591 do_check_types(Gogo*);
2592
2593 Expression*
2594 do_copy()
2595 { return this; }
2596
2597 Bexpression*
2598 do_get_backend(Translate_context* context);
2599
2600 // When exporting a reference to a const as part of a const
2601 // expression, we export the value. We ignore the fact that it has
2602 // a name.
2603 void
2604 do_export(Export* exp) const
2605 { this->constant_->const_value()->expr()->export_expression(exp); }
2606
2607 void
2608 do_dump_expression(Ast_dump_context*) const;
2609
2610 private:
2611 // The constant.
2612 Named_object* constant_;
2613 // The type of this reference. This is used if the constant has an
2614 // abstract type.
2615 Type* type_;
2616 // Used to prevent infinite recursion when a constant incorrectly
2617 // refers to itself.
2618 mutable bool seen_;
2619 };
2620
2621 // Traversal.
2622
2623 int
2624 Const_expression::do_traverse(Traverse* traverse)
2625 {
2626 if (this->type_ != NULL)
2627 return Type::traverse(this->type_, traverse);
2628 return TRAVERSE_CONTINUE;
2629 }
2630
2631 // Lower a constant expression. This is where we convert the
2632 // predeclared constant iota into an integer value.
2633
2634 Expression*
2635 Const_expression::do_lower(Gogo* gogo, Named_object*,
2636 Statement_inserter*, int iota_value)
2637 {
2638 if (this->constant_->const_value()->expr()->classification()
2639 == EXPRESSION_IOTA)
2640 {
2641 if (iota_value == -1)
2642 {
2643 error_at(this->location(),
2644 "iota is only defined in const declarations");
2645 iota_value = 0;
2646 }
2647 return Expression::make_integer_ul(iota_value, NULL, this->location());
2648 }
2649
2650 // Make sure that the constant itself has been lowered.
2651 gogo->lower_constant(this->constant_);
2652
2653 return this;
2654 }
2655
2656 // Return a numeric constant value.
2657
2658 bool
2659 Const_expression::do_numeric_constant_value(Numeric_constant* nc) const
2660 {
2661 if (this->seen_)
2662 return false;
2663
2664 Expression* e = this->constant_->const_value()->expr();
2665
2666 this->seen_ = true;
2667
2668 bool r = e->numeric_constant_value(nc);
2669
2670 this->seen_ = false;
2671
2672 Type* ctype;
2673 if (this->type_ != NULL)
2674 ctype = this->type_;
2675 else
2676 ctype = this->constant_->const_value()->type();
2677 if (r && ctype != NULL)
2678 {
2679 if (!nc->set_type(ctype, false, this->location()))
2680 return false;
2681 }
2682
2683 return r;
2684 }
2685
2686 bool
2687 Const_expression::do_string_constant_value(std::string* val) const
2688 {
2689 if (this->seen_)
2690 return false;
2691
2692 Expression* e = this->constant_->const_value()->expr();
2693
2694 this->seen_ = true;
2695 bool ok = e->string_constant_value(val);
2696 this->seen_ = false;
2697
2698 return ok;
2699 }
2700
2701 // Return the type of the const reference.
2702
2703 Type*
2704 Const_expression::do_type()
2705 {
2706 if (this->type_ != NULL)
2707 return this->type_;
2708
2709 Named_constant* nc = this->constant_->const_value();
2710
2711 if (this->seen_ || nc->lowering())
2712 {
2713 this->report_error(_("constant refers to itself"));
2714 this->type_ = Type::make_error_type();
2715 return this->type_;
2716 }
2717
2718 this->seen_ = true;
2719
2720 Type* ret = nc->type();
2721
2722 if (ret != NULL)
2723 {
2724 this->seen_ = false;
2725 return ret;
2726 }
2727
2728 // During parsing, a named constant may have a NULL type, but we
2729 // must not return a NULL type here.
2730 ret = nc->expr()->type();
2731
2732 this->seen_ = false;
2733
2734 return ret;
2735 }
2736
2737 // Set the type of the const reference.
2738
2739 void
2740 Const_expression::do_determine_type(const Type_context* context)
2741 {
2742 Type* ctype = this->constant_->const_value()->type();
2743 Type* cetype = (ctype != NULL
2744 ? ctype
2745 : this->constant_->const_value()->expr()->type());
2746 if (ctype != NULL && !ctype->is_abstract())
2747 ;
2748 else if (context->type != NULL
2749 && context->type->is_numeric_type()
2750 && cetype->is_numeric_type())
2751 this->type_ = context->type;
2752 else if (context->type != NULL
2753 && context->type->is_string_type()
2754 && cetype->is_string_type())
2755 this->type_ = context->type;
2756 else if (context->type != NULL
2757 && context->type->is_boolean_type()
2758 && cetype->is_boolean_type())
2759 this->type_ = context->type;
2760 else if (!context->may_be_abstract)
2761 {
2762 if (cetype->is_abstract())
2763 cetype = cetype->make_non_abstract_type();
2764 this->type_ = cetype;
2765 }
2766 }
2767
2768 // Check for a loop in which the initializer of a constant refers to
2769 // the constant itself.
2770
2771 void
2772 Const_expression::check_for_init_loop()
2773 {
2774 if (this->type_ != NULL && this->type_->is_error())
2775 return;
2776
2777 if (this->seen_)
2778 {
2779 this->report_error(_("constant refers to itself"));
2780 this->type_ = Type::make_error_type();
2781 return;
2782 }
2783
2784 Expression* init = this->constant_->const_value()->expr();
2785 Find_named_object find_named_object(this->constant_);
2786
2787 this->seen_ = true;
2788 Expression::traverse(&init, &find_named_object);
2789 this->seen_ = false;
2790
2791 if (find_named_object.found())
2792 {
2793 if (this->type_ == NULL || !this->type_->is_error())
2794 {
2795 this->report_error(_("constant refers to itself"));
2796 this->type_ = Type::make_error_type();
2797 }
2798 return;
2799 }
2800 }
2801
2802 // Check types of a const reference.
2803
2804 void
2805 Const_expression::do_check_types(Gogo*)
2806 {
2807 if (this->type_ != NULL && this->type_->is_error())
2808 return;
2809
2810 this->check_for_init_loop();
2811
2812 // Check that numeric constant fits in type.
2813 if (this->type_ != NULL && this->type_->is_numeric_type())
2814 {
2815 Numeric_constant nc;
2816 if (this->constant_->const_value()->expr()->numeric_constant_value(&nc))
2817 {
2818 if (!nc.set_type(this->type_, true, this->location()))
2819 this->set_is_error();
2820 }
2821 }
2822 }
2823
2824 // Return the backend representation for a const reference.
2825
2826 Bexpression*
2827 Const_expression::do_get_backend(Translate_context* context)
2828 {
2829 if (this->type_ != NULL && this->type_->is_error())
2830 return context->backend()->error_expression();
2831
2832 // If the type has been set for this expression, but the underlying
2833 // object is an abstract int or float, we try to get the abstract
2834 // value. Otherwise we may lose something in the conversion.
2835 Expression* expr = this->constant_->const_value()->expr();
2836 if (this->type_ != NULL
2837 && this->type_->is_numeric_type()
2838 && (this->constant_->const_value()->type() == NULL
2839 || this->constant_->const_value()->type()->is_abstract()))
2840 {
2841 Numeric_constant nc;
2842 if (expr->numeric_constant_value(&nc)
2843 && nc.set_type(this->type_, false, this->location()))
2844 {
2845 Expression* e = nc.expression(this->location());
2846 return e->get_backend(context);
2847 }
2848 }
2849
2850 if (this->type_ != NULL)
2851 expr = Expression::make_cast(this->type_, expr, this->location());
2852 return expr->get_backend(context);
2853 }
2854
2855 // Dump ast representation for constant expression.
2856
2857 void
2858 Const_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
2859 {
2860 ast_dump_context->ostream() << this->constant_->name();
2861 }
2862
2863 // Make a reference to a constant in an expression.
2864
2865 Expression*
2866 Expression::make_const_reference(Named_object* constant,
2867 Location location)
2868 {
2869 return new Const_expression(constant, location);
2870 }
2871
2872 // Find a named object in an expression.
2873
2874 int
2875 Find_named_object::expression(Expression** pexpr)
2876 {
2877 switch ((*pexpr)->classification())
2878 {
2879 case Expression::EXPRESSION_CONST_REFERENCE:
2880 {
2881 Const_expression* ce = static_cast<Const_expression*>(*pexpr);
2882 if (ce->named_object() == this->no_)
2883 break;
2884
2885 // We need to check a constant initializer explicitly, as
2886 // loops here will not be caught by the loop checking for
2887 // variable initializers.
2888 ce->check_for_init_loop();
2889
2890 return TRAVERSE_CONTINUE;
2891 }
2892
2893 case Expression::EXPRESSION_VAR_REFERENCE:
2894 if ((*pexpr)->var_expression()->named_object() == this->no_)
2895 break;
2896 return TRAVERSE_CONTINUE;
2897 case Expression::EXPRESSION_FUNC_REFERENCE:
2898 if ((*pexpr)->func_expression()->named_object() == this->no_)
2899 break;
2900 return TRAVERSE_CONTINUE;
2901 default:
2902 return TRAVERSE_CONTINUE;
2903 }
2904 this->found_ = true;
2905 return TRAVERSE_EXIT;
2906 }
2907
2908 // The nil value.
2909
2910 class Nil_expression : public Expression
2911 {
2912 public:
2913 Nil_expression(Location location)
2914 : Expression(EXPRESSION_NIL, location)
2915 { }
2916
2917 static Expression*
2918 do_import(Import*);
2919
2920 protected:
2921 bool
2922 do_is_constant() const
2923 { return true; }
2924
2925 bool
2926 do_is_immutable() const
2927 { return true; }
2928
2929 Type*
2930 do_type()
2931 { return Type::make_nil_type(); }
2932
2933 void
2934 do_determine_type(const Type_context*)
2935 { }
2936
2937 Expression*
2938 do_copy()
2939 { return this; }
2940
2941 Bexpression*
2942 do_get_backend(Translate_context* context)
2943 { return context->backend()->nil_pointer_expression(); }
2944
2945 void
2946 do_export(Export* exp) const
2947 { exp->write_c_string("nil"); }
2948
2949 void
2950 do_dump_expression(Ast_dump_context* ast_dump_context) const
2951 { ast_dump_context->ostream() << "nil"; }
2952 };
2953
2954 // Import a nil expression.
2955
2956 Expression*
2957 Nil_expression::do_import(Import* imp)
2958 {
2959 imp->require_c_string("nil");
2960 return Expression::make_nil(imp->location());
2961 }
2962
2963 // Make a nil expression.
2964
2965 Expression*
2966 Expression::make_nil(Location location)
2967 {
2968 return new Nil_expression(location);
2969 }
2970
2971 // The value of the predeclared constant iota. This is little more
2972 // than a marker. This will be lowered to an integer in
2973 // Const_expression::do_lower, which is where we know the value that
2974 // it should have.
2975
2976 class Iota_expression : public Parser_expression
2977 {
2978 public:
2979 Iota_expression(Location location)
2980 : Parser_expression(EXPRESSION_IOTA, location)
2981 { }
2982
2983 protected:
2984 Expression*
2985 do_lower(Gogo*, Named_object*, Statement_inserter*, int)
2986 { go_unreachable(); }
2987
2988 // There should only ever be one of these.
2989 Expression*
2990 do_copy()
2991 { go_unreachable(); }
2992
2993 void
2994 do_dump_expression(Ast_dump_context* ast_dump_context) const
2995 { ast_dump_context->ostream() << "iota"; }
2996 };
2997
2998 // Make an iota expression. This is only called for one case: the
2999 // value of the predeclared constant iota.
3000
3001 Expression*
3002 Expression::make_iota()
3003 {
3004 static Iota_expression iota_expression(Linemap::unknown_location());
3005 return &iota_expression;
3006 }
3007
3008 // Class Type_conversion_expression.
3009
3010 // Traversal.
3011
3012 int
3013 Type_conversion_expression::do_traverse(Traverse* traverse)
3014 {
3015 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3016 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3017 return TRAVERSE_EXIT;
3018 return TRAVERSE_CONTINUE;
3019 }
3020
3021 // Convert to a constant at lowering time.
3022
3023 Expression*
3024 Type_conversion_expression::do_lower(Gogo*, Named_object*,
3025 Statement_inserter*, int)
3026 {
3027 Type* type = this->type_;
3028 Expression* val = this->expr_;
3029 Location location = this->location();
3030
3031 if (type->is_numeric_type())
3032 {
3033 Numeric_constant nc;
3034 if (val->numeric_constant_value(&nc))
3035 {
3036 if (!nc.set_type(type, true, location))
3037 return Expression::make_error(location);
3038 return nc.expression(location);
3039 }
3040 }
3041
3042 if (type->is_slice_type())
3043 {
3044 Type* element_type = type->array_type()->element_type()->forwarded();
3045 bool is_byte = (element_type->integer_type() != NULL
3046 && element_type->integer_type()->is_byte());
3047 bool is_rune = (element_type->integer_type() != NULL
3048 && element_type->integer_type()->is_rune());
3049 if (is_byte || is_rune)
3050 {
3051 std::string s;
3052 if (val->string_constant_value(&s))
3053 {
3054 Expression_list* vals = new Expression_list();
3055 if (is_byte)
3056 {
3057 for (std::string::const_iterator p = s.begin();
3058 p != s.end();
3059 p++)
3060 {
3061 unsigned char c = static_cast<unsigned char>(*p);
3062 vals->push_back(Expression::make_integer_ul(c,
3063 element_type,
3064 location));
3065 }
3066 }
3067 else
3068 {
3069 const char *p = s.data();
3070 const char *pend = s.data() + s.length();
3071 while (p < pend)
3072 {
3073 unsigned int c;
3074 int adv = Lex::fetch_char(p, &c);
3075 if (adv == 0)
3076 {
3077 warning_at(this->location(), 0,
3078 "invalid UTF-8 encoding");
3079 adv = 1;
3080 }
3081 p += adv;
3082 vals->push_back(Expression::make_integer_ul(c,
3083 element_type,
3084 location));
3085 }
3086 }
3087
3088 return Expression::make_slice_composite_literal(type, vals,
3089 location);
3090 }
3091 }
3092 }
3093
3094 return this;
3095 }
3096
3097 // Flatten a type conversion by using a temporary variable for the slice
3098 // in slice to string conversions.
3099
3100 Expression*
3101 Type_conversion_expression::do_flatten(Gogo*, Named_object*,
3102 Statement_inserter* inserter)
3103 {
3104 if (this->type()->is_error_type() || this->expr_->is_error_expression())
3105 {
3106 go_assert(saw_errors());
3107 return Expression::make_error(this->location());
3108 }
3109
3110 if (((this->type()->is_string_type()
3111 && this->expr_->type()->is_slice_type())
3112 || this->expr_->type()->interface_type() != NULL)
3113 && !this->expr_->is_variable())
3114 {
3115 Temporary_statement* temp =
3116 Statement::make_temporary(NULL, this->expr_, this->location());
3117 inserter->insert(temp);
3118 this->expr_ = Expression::make_temporary_reference(temp, this->location());
3119 }
3120 return this;
3121 }
3122
3123 // Return whether a type conversion is a constant.
3124
3125 bool
3126 Type_conversion_expression::do_is_constant() const
3127 {
3128 if (!this->expr_->is_constant())
3129 return false;
3130
3131 // A conversion to a type that may not be used as a constant is not
3132 // a constant. For example, []byte(nil).
3133 Type* type = this->type_;
3134 if (type->integer_type() == NULL
3135 && type->float_type() == NULL
3136 && type->complex_type() == NULL
3137 && !type->is_boolean_type()
3138 && !type->is_string_type())
3139 return false;
3140
3141 return true;
3142 }
3143
3144 // Return whether a type conversion is immutable.
3145
3146 bool
3147 Type_conversion_expression::do_is_immutable() const
3148 {
3149 Type* type = this->type_;
3150 Type* expr_type = this->expr_->type();
3151
3152 if (type->interface_type() != NULL
3153 || expr_type->interface_type() != NULL)
3154 return false;
3155
3156 if (!this->expr_->is_immutable())
3157 return false;
3158
3159 if (Type::are_identical(type, expr_type, false, NULL))
3160 return true;
3161
3162 return type->is_basic_type() && expr_type->is_basic_type();
3163 }
3164
3165 // Return the constant numeric value if there is one.
3166
3167 bool
3168 Type_conversion_expression::do_numeric_constant_value(
3169 Numeric_constant* nc) const
3170 {
3171 if (!this->type_->is_numeric_type())
3172 return false;
3173 if (!this->expr_->numeric_constant_value(nc))
3174 return false;
3175 return nc->set_type(this->type_, false, this->location());
3176 }
3177
3178 // Return the constant string value if there is one.
3179
3180 bool
3181 Type_conversion_expression::do_string_constant_value(std::string* val) const
3182 {
3183 if (this->type_->is_string_type()
3184 && this->expr_->type()->integer_type() != NULL)
3185 {
3186 Numeric_constant nc;
3187 if (this->expr_->numeric_constant_value(&nc))
3188 {
3189 unsigned long ival;
3190 if (nc.to_unsigned_long(&ival) == Numeric_constant::NC_UL_VALID)
3191 {
3192 val->clear();
3193 Lex::append_char(ival, true, val, this->location());
3194 return true;
3195 }
3196 }
3197 }
3198
3199 // FIXME: Could handle conversion from const []int here.
3200
3201 return false;
3202 }
3203
3204 // Determine the resulting type of the conversion.
3205
3206 void
3207 Type_conversion_expression::do_determine_type(const Type_context*)
3208 {
3209 Type_context subcontext(this->type_, false);
3210 this->expr_->determine_type(&subcontext);
3211 }
3212
3213 // Check that types are convertible.
3214
3215 void
3216 Type_conversion_expression::do_check_types(Gogo*)
3217 {
3218 Type* type = this->type_;
3219 Type* expr_type = this->expr_->type();
3220 std::string reason;
3221
3222 if (type->is_error() || expr_type->is_error())
3223 {
3224 this->set_is_error();
3225 return;
3226 }
3227
3228 if (this->may_convert_function_types_
3229 && type->function_type() != NULL
3230 && expr_type->function_type() != NULL)
3231 return;
3232
3233 if (Type::are_convertible(type, expr_type, &reason))
3234 return;
3235
3236 error_at(this->location(), "%s", reason.c_str());
3237 this->set_is_error();
3238 }
3239
3240 // Get the backend representation for a type conversion.
3241
3242 Bexpression*
3243 Type_conversion_expression::do_get_backend(Translate_context* context)
3244 {
3245 Type* type = this->type_;
3246 Type* expr_type = this->expr_->type();
3247
3248 Gogo* gogo = context->gogo();
3249 Btype* btype = type->get_backend(gogo);
3250 Bexpression* bexpr = this->expr_->get_backend(context);
3251 Location loc = this->location();
3252
3253 if (Type::are_identical(type, expr_type, false, NULL))
3254 return gogo->backend()->convert_expression(btype, bexpr, loc);
3255 else if (type->interface_type() != NULL
3256 || expr_type->interface_type() != NULL)
3257 {
3258 Expression* conversion =
3259 Expression::convert_for_assignment(gogo, type, this->expr_,
3260 this->location());
3261 return conversion->get_backend(context);
3262 }
3263 else if (type->is_string_type()
3264 && expr_type->integer_type() != NULL)
3265 {
3266 mpz_t intval;
3267 Numeric_constant nc;
3268 if (this->expr_->numeric_constant_value(&nc)
3269 && nc.to_int(&intval)
3270 && mpz_fits_ushort_p(intval))
3271 {
3272 std::string s;
3273 Lex::append_char(mpz_get_ui(intval), true, &s, loc);
3274 mpz_clear(intval);
3275 Expression* se = Expression::make_string(s, loc);
3276 return se->get_backend(context);
3277 }
3278
3279 Expression* i2s_expr =
3280 Runtime::make_call(Runtime::INT_TO_STRING, loc, 1, this->expr_);
3281 return Expression::make_cast(type, i2s_expr, loc)->get_backend(context);
3282 }
3283 else if (type->is_string_type() && expr_type->is_slice_type())
3284 {
3285 Array_type* a = expr_type->array_type();
3286 Type* e = a->element_type()->forwarded();
3287 go_assert(e->integer_type() != NULL);
3288 go_assert(this->expr_->is_variable());
3289
3290 Runtime::Function code;
3291 if (e->integer_type()->is_byte())
3292 code = Runtime::BYTE_ARRAY_TO_STRING;
3293 else
3294 {
3295 go_assert(e->integer_type()->is_rune());
3296 code = Runtime::INT_ARRAY_TO_STRING;
3297 }
3298 Expression* valptr = a->get_value_pointer(gogo, this->expr_);
3299 Expression* len = a->get_length(gogo, this->expr_);
3300 return Runtime::make_call(code, loc, 2, valptr,
3301 len)->get_backend(context);
3302 }
3303 else if (type->is_slice_type() && expr_type->is_string_type())
3304 {
3305 Type* e = type->array_type()->element_type()->forwarded();
3306 go_assert(e->integer_type() != NULL);
3307
3308 Runtime::Function code;
3309 if (e->integer_type()->is_byte())
3310 code = Runtime::STRING_TO_BYTE_ARRAY;
3311 else
3312 {
3313 go_assert(e->integer_type()->is_rune());
3314 code = Runtime::STRING_TO_INT_ARRAY;
3315 }
3316 Expression* s2a = Runtime::make_call(code, loc, 1, this->expr_);
3317 return Expression::make_unsafe_cast(type, s2a, loc)->get_backend(context);
3318 }
3319 else if (type->is_numeric_type())
3320 {
3321 go_assert(Type::are_convertible(type, expr_type, NULL));
3322 return gogo->backend()->convert_expression(btype, bexpr, loc);
3323 }
3324 else if ((type->is_unsafe_pointer_type()
3325 && (expr_type->points_to() != NULL
3326 || expr_type->integer_type()))
3327 || (expr_type->is_unsafe_pointer_type()
3328 && type->points_to() != NULL)
3329 || (this->may_convert_function_types_
3330 && type->function_type() != NULL
3331 && expr_type->function_type() != NULL))
3332 return gogo->backend()->convert_expression(btype, bexpr, loc);
3333 else
3334 {
3335 Expression* conversion =
3336 Expression::convert_for_assignment(gogo, type, this->expr_, loc);
3337 return conversion->get_backend(context);
3338 }
3339 }
3340
3341 // Output a type conversion in a constant expression.
3342
3343 void
3344 Type_conversion_expression::do_export(Export* exp) const
3345 {
3346 exp->write_c_string("convert(");
3347 exp->write_type(this->type_);
3348 exp->write_c_string(", ");
3349 this->expr_->export_expression(exp);
3350 exp->write_c_string(")");
3351 }
3352
3353 // Import a type conversion or a struct construction.
3354
3355 Expression*
3356 Type_conversion_expression::do_import(Import* imp)
3357 {
3358 imp->require_c_string("convert(");
3359 Type* type = imp->read_type();
3360 imp->require_c_string(", ");
3361 Expression* val = Expression::import_expression(imp);
3362 imp->require_c_string(")");
3363 return Expression::make_cast(type, val, imp->location());
3364 }
3365
3366 // Dump ast representation for a type conversion expression.
3367
3368 void
3369 Type_conversion_expression::do_dump_expression(
3370 Ast_dump_context* ast_dump_context) const
3371 {
3372 ast_dump_context->dump_type(this->type_);
3373 ast_dump_context->ostream() << "(";
3374 ast_dump_context->dump_expression(this->expr_);
3375 ast_dump_context->ostream() << ") ";
3376 }
3377
3378 // Make a type cast expression.
3379
3380 Expression*
3381 Expression::make_cast(Type* type, Expression* val, Location location)
3382 {
3383 if (type->is_error_type() || val->is_error_expression())
3384 return Expression::make_error(location);
3385 return new Type_conversion_expression(type, val, location);
3386 }
3387
3388 // Class Unsafe_type_conversion_expression.
3389
3390 // Traversal.
3391
3392 int
3393 Unsafe_type_conversion_expression::do_traverse(Traverse* traverse)
3394 {
3395 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
3396 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3397 return TRAVERSE_EXIT;
3398 return TRAVERSE_CONTINUE;
3399 }
3400
3401 // Return whether an unsafe type conversion is immutable.
3402
3403 bool
3404 Unsafe_type_conversion_expression::do_is_immutable() const
3405 {
3406 Type* type = this->type_;
3407 Type* expr_type = this->expr_->type();
3408
3409 if (type->interface_type() != NULL
3410 || expr_type->interface_type() != NULL)
3411 return false;
3412
3413 if (!this->expr_->is_immutable())
3414 return false;
3415
3416 if (Type::are_convertible(type, expr_type, NULL))
3417 return true;
3418
3419 return type->is_basic_type() && expr_type->is_basic_type();
3420 }
3421
3422 // Convert to backend representation.
3423
3424 Bexpression*
3425 Unsafe_type_conversion_expression::do_get_backend(Translate_context* context)
3426 {
3427 // We are only called for a limited number of cases.
3428
3429 Type* t = this->type_;
3430 Type* et = this->expr_->type();
3431 if (t->array_type() != NULL)
3432 go_assert(et->array_type() != NULL
3433 && t->is_slice_type() == et->is_slice_type());
3434 else if (t->struct_type() != NULL)
3435 {
3436 if (t->named_type() != NULL
3437 && et->named_type() != NULL
3438 && !Type::are_convertible(t, et, NULL))
3439 {
3440 go_assert(saw_errors());
3441 return context->backend()->error_expression();
3442 }
3443
3444 go_assert(et->struct_type() != NULL
3445 && Type::are_convertible(t, et, NULL));
3446 }
3447 else if (t->map_type() != NULL)
3448 go_assert(et->map_type() != NULL);
3449 else if (t->channel_type() != NULL)
3450 go_assert(et->channel_type() != NULL);
3451 else if (t->points_to() != NULL)
3452 go_assert(et->points_to() != NULL
3453 || et->channel_type() != NULL
3454 || et->map_type() != NULL
3455 || et->function_type() != NULL
3456 || et->is_nil_type());
3457 else if (et->is_unsafe_pointer_type())
3458 go_assert(t->points_to() != NULL);
3459 else if (t->interface_type() != NULL)
3460 {
3461 bool empty_iface = t->interface_type()->is_empty();
3462 go_assert(et->interface_type() != NULL
3463 && et->interface_type()->is_empty() == empty_iface);
3464 }
3465 else if (t->integer_type() != NULL)
3466 go_assert(et->is_boolean_type()
3467 || et->integer_type() != NULL
3468 || et->function_type() != NULL
3469 || et->points_to() != NULL
3470 || et->map_type() != NULL
3471 || et->channel_type() != NULL
3472 || et->is_nil_type());
3473 else
3474 go_unreachable();
3475
3476 Gogo* gogo = context->gogo();
3477 Btype* btype = t->get_backend(gogo);
3478 Bexpression* bexpr = this->expr_->get_backend(context);
3479 Location loc = this->location();
3480 return gogo->backend()->convert_expression(btype, bexpr, loc);
3481 }
3482
3483 // Dump ast representation for an unsafe type conversion expression.
3484
3485 void
3486 Unsafe_type_conversion_expression::do_dump_expression(
3487 Ast_dump_context* ast_dump_context) const
3488 {
3489 ast_dump_context->dump_type(this->type_);
3490 ast_dump_context->ostream() << "(";
3491 ast_dump_context->dump_expression(this->expr_);
3492 ast_dump_context->ostream() << ") ";
3493 }
3494
3495 // Make an unsafe type conversion expression.
3496
3497 Expression*
3498 Expression::make_unsafe_cast(Type* type, Expression* expr,
3499 Location location)
3500 {
3501 return new Unsafe_type_conversion_expression(type, expr, location);
3502 }
3503
3504 // Class Unary_expression.
3505
3506 // If we are taking the address of a composite literal, and the
3507 // contents are not constant, then we want to make a heap expression
3508 // instead.
3509
3510 Expression*
3511 Unary_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
3512 {
3513 Location loc = this->location();
3514 Operator op = this->op_;
3515 Expression* expr = this->expr_;
3516
3517 if (op == OPERATOR_MULT && expr->is_type_expression())
3518 return Expression::make_type(Type::make_pointer_type(expr->type()), loc);
3519
3520 // *&x simplifies to x. *(*T)(unsafe.Pointer)(&x) does not require
3521 // moving x to the heap. FIXME: Is it worth doing a real escape
3522 // analysis here? This case is found in math/unsafe.go and is
3523 // therefore worth special casing.
3524 if (op == OPERATOR_MULT)
3525 {
3526 Expression* e = expr;
3527 while (e->classification() == EXPRESSION_CONVERSION)
3528 {
3529 Type_conversion_expression* te
3530 = static_cast<Type_conversion_expression*>(e);
3531 e = te->expr();
3532 }
3533
3534 if (e->classification() == EXPRESSION_UNARY)
3535 {
3536 Unary_expression* ue = static_cast<Unary_expression*>(e);
3537 if (ue->op_ == OPERATOR_AND)
3538 {
3539 if (e == expr)
3540 {
3541 // *&x == x.
3542 if (!ue->expr_->is_addressable() && !ue->create_temp_)
3543 {
3544 error_at(ue->location(),
3545 "invalid operand for unary %<&%>");
3546 this->set_is_error();
3547 }
3548 return ue->expr_;
3549 }
3550 ue->set_does_not_escape();
3551 }
3552 }
3553 }
3554
3555 // Catching an invalid indirection of unsafe.Pointer here avoid
3556 // having to deal with TYPE_VOID in other places.
3557 if (op == OPERATOR_MULT && expr->type()->is_unsafe_pointer_type())
3558 {
3559 error_at(this->location(), "invalid indirect of %<unsafe.Pointer%>");
3560 return Expression::make_error(this->location());
3561 }
3562
3563 // Check for an invalid pointer dereference. We need to do this
3564 // here because Unary_expression::do_type will return an error type
3565 // in this case. That can cause code to appear erroneous, and
3566 // therefore disappear at lowering time, without any error message.
3567 if (op == OPERATOR_MULT && expr->type()->points_to() == NULL)
3568 {
3569 this->report_error(_("expected pointer"));
3570 return Expression::make_error(this->location());
3571 }
3572
3573 if (op == OPERATOR_PLUS || op == OPERATOR_MINUS || op == OPERATOR_XOR)
3574 {
3575 Numeric_constant nc;
3576 if (expr->numeric_constant_value(&nc))
3577 {
3578 Numeric_constant result;
3579 if (Unary_expression::eval_constant(op, &nc, loc, &result))
3580 return result.expression(loc);
3581 }
3582 }
3583
3584 return this;
3585 }
3586
3587 // Flatten expression if a nil check must be performed and create temporary
3588 // variables if necessary.
3589
3590 Expression*
3591 Unary_expression::do_flatten(Gogo* gogo, Named_object*,
3592 Statement_inserter* inserter)
3593 {
3594 if (this->is_error_expression()
3595 || this->expr_->is_error_expression()
3596 || this->expr_->type()->is_error_type())
3597 {
3598 go_assert(saw_errors());
3599 return Expression::make_error(this->location());
3600 }
3601
3602 Location location = this->location();
3603 if (this->op_ == OPERATOR_MULT
3604 && !this->expr_->is_variable())
3605 {
3606 go_assert(this->expr_->type()->points_to() != NULL);
3607 Type* ptype = this->expr_->type()->points_to();
3608 if (!ptype->is_void_type())
3609 {
3610 Btype* pbtype = ptype->get_backend(gogo);
3611 int64_t s = gogo->backend()->type_size(pbtype);
3612 if (s >= 4096 || this->issue_nil_check_)
3613 {
3614 Temporary_statement* temp =
3615 Statement::make_temporary(NULL, this->expr_, location);
3616 inserter->insert(temp);
3617 this->expr_ =
3618 Expression::make_temporary_reference(temp, location);
3619 }
3620 }
3621 }
3622
3623 if (this->op_ == OPERATOR_AND)
3624 {
3625 // If this->escapes_ is false at this point, then it was set to
3626 // false by an explicit call to set_does_not_escape, and the
3627 // value does not escape. If this->escapes_ is true, we may be
3628 // able to set it to false if taking the address of a variable
3629 // that does not escape.
3630 if (this->escapes_ && this->expr_->var_expression() != NULL)
3631 {
3632 Named_object* var = this->expr_->var_expression()->named_object();
3633 if (var->is_variable())
3634 this->escapes_ = var->var_value()->escapes();
3635 if (var->is_result_variable())
3636 this->escapes_ = var->result_var_value()->escapes();
3637 }
3638 this->expr_->address_taken(this->escapes_);
3639 }
3640
3641 if (this->create_temp_ && !this->expr_->is_variable())
3642 {
3643 Temporary_statement* temp =
3644 Statement::make_temporary(NULL, this->expr_, location);
3645 inserter->insert(temp);
3646 this->expr_ = Expression::make_temporary_reference(temp, location);
3647 }
3648
3649 return this;
3650 }
3651
3652 // Return whether a unary expression is a constant.
3653
3654 bool
3655 Unary_expression::do_is_constant() const
3656 {
3657 if (this->op_ == OPERATOR_MULT)
3658 {
3659 // Indirecting through a pointer is only constant if the object
3660 // to which the expression points is constant, but we currently
3661 // have no way to determine that.
3662 return false;
3663 }
3664 else if (this->op_ == OPERATOR_AND)
3665 {
3666 // Taking the address of a variable is constant if it is a
3667 // global variable, not constant otherwise. In other cases taking the
3668 // address is probably not a constant.
3669 Var_expression* ve = this->expr_->var_expression();
3670 if (ve != NULL)
3671 {
3672 Named_object* no = ve->named_object();
3673 return no->is_variable() && no->var_value()->is_global();
3674 }
3675 return false;
3676 }
3677 else
3678 return this->expr_->is_constant();
3679 }
3680
3681 // Apply unary opcode OP to UNC, setting NC. Return true if this
3682 // could be done, false if not. Issue errors for overflow.
3683
3684 bool
3685 Unary_expression::eval_constant(Operator op, const Numeric_constant* unc,
3686 Location location, Numeric_constant* nc)
3687 {
3688 switch (op)
3689 {
3690 case OPERATOR_PLUS:
3691 *nc = *unc;
3692 return true;
3693
3694 case OPERATOR_MINUS:
3695 if (unc->is_int() || unc->is_rune())
3696 break;
3697 else if (unc->is_float())
3698 {
3699 mpfr_t uval;
3700 unc->get_float(&uval);
3701 mpfr_t val;
3702 mpfr_init(val);
3703 mpfr_neg(val, uval, GMP_RNDN);
3704 nc->set_float(unc->type(), val);
3705 mpfr_clear(uval);
3706 mpfr_clear(val);
3707 return true;
3708 }
3709 else if (unc->is_complex())
3710 {
3711 mpc_t uval;
3712 unc->get_complex(&uval);
3713 mpc_t val;
3714 mpc_init2(val, mpc_precision);
3715 mpc_neg(val, uval, MPC_RNDNN);
3716 nc->set_complex(unc->type(), val);
3717 mpc_clear(uval);
3718 mpc_clear(val);
3719 return true;
3720 }
3721 else
3722 go_unreachable();
3723
3724 case OPERATOR_XOR:
3725 break;
3726
3727 case OPERATOR_NOT:
3728 case OPERATOR_AND:
3729 case OPERATOR_MULT:
3730 return false;
3731
3732 default:
3733 go_unreachable();
3734 }
3735
3736 if (!unc->is_int() && !unc->is_rune())
3737 return false;
3738
3739 mpz_t uval;
3740 if (unc->is_rune())
3741 unc->get_rune(&uval);
3742 else
3743 unc->get_int(&uval);
3744 mpz_t val;
3745 mpz_init(val);
3746
3747 switch (op)
3748 {
3749 case OPERATOR_MINUS:
3750 mpz_neg(val, uval);
3751 break;
3752
3753 case OPERATOR_NOT:
3754 mpz_set_ui(val, mpz_cmp_si(uval, 0) == 0 ? 1 : 0);
3755 break;
3756
3757 case OPERATOR_XOR:
3758 {
3759 Type* utype = unc->type();
3760 if (utype->integer_type() == NULL
3761 || utype->integer_type()->is_abstract())
3762 mpz_com(val, uval);
3763 else
3764 {
3765 // The number of HOST_WIDE_INTs that it takes to represent
3766 // UVAL.
3767 size_t count = ((mpz_sizeinbase(uval, 2)
3768 + HOST_BITS_PER_WIDE_INT
3769 - 1)
3770 / HOST_BITS_PER_WIDE_INT);
3771
3772 unsigned HOST_WIDE_INT* phwi = new unsigned HOST_WIDE_INT[count];
3773 memset(phwi, 0, count * sizeof(HOST_WIDE_INT));
3774
3775 size_t obits = utype->integer_type()->bits();
3776
3777 if (!utype->integer_type()->is_unsigned() && mpz_sgn(uval) < 0)
3778 {
3779 mpz_t adj;
3780 mpz_init_set_ui(adj, 1);
3781 mpz_mul_2exp(adj, adj, obits);
3782 mpz_add(uval, uval, adj);
3783 mpz_clear(adj);
3784 }
3785
3786 size_t ecount;
3787 mpz_export(phwi, &ecount, -1, sizeof(HOST_WIDE_INT), 0, 0, uval);
3788 go_assert(ecount <= count);
3789
3790 // Trim down to the number of words required by the type.
3791 size_t ocount = ((obits + HOST_BITS_PER_WIDE_INT - 1)
3792 / HOST_BITS_PER_WIDE_INT);
3793 go_assert(ocount <= count);
3794
3795 for (size_t i = 0; i < ocount; ++i)
3796 phwi[i] = ~phwi[i];
3797
3798 size_t clearbits = ocount * HOST_BITS_PER_WIDE_INT - obits;
3799 if (clearbits != 0)
3800 phwi[ocount - 1] &= (((unsigned HOST_WIDE_INT) (HOST_WIDE_INT) -1)
3801 >> clearbits);
3802
3803 mpz_import(val, ocount, -1, sizeof(HOST_WIDE_INT), 0, 0, phwi);
3804
3805 if (!utype->integer_type()->is_unsigned()
3806 && mpz_tstbit(val, obits - 1))
3807 {
3808 mpz_t adj;
3809 mpz_init_set_ui(adj, 1);
3810 mpz_mul_2exp(adj, adj, obits);
3811 mpz_sub(val, val, adj);
3812 mpz_clear(adj);
3813 }
3814
3815 delete[] phwi;
3816 }
3817 }
3818 break;
3819
3820 default:
3821 go_unreachable();
3822 }
3823
3824 if (unc->is_rune())
3825 nc->set_rune(NULL, val);
3826 else
3827 nc->set_int(NULL, val);
3828
3829 mpz_clear(uval);
3830 mpz_clear(val);
3831
3832 return nc->set_type(unc->type(), true, location);
3833 }
3834
3835 // Return the integral constant value of a unary expression, if it has one.
3836
3837 bool
3838 Unary_expression::do_numeric_constant_value(Numeric_constant* nc) const
3839 {
3840 Numeric_constant unc;
3841 if (!this->expr_->numeric_constant_value(&unc))
3842 return false;
3843 return Unary_expression::eval_constant(this->op_, &unc, this->location(),
3844 nc);
3845 }
3846
3847 // Return the type of a unary expression.
3848
3849 Type*
3850 Unary_expression::do_type()
3851 {
3852 switch (this->op_)
3853 {
3854 case OPERATOR_PLUS:
3855 case OPERATOR_MINUS:
3856 case OPERATOR_NOT:
3857 case OPERATOR_XOR:
3858 return this->expr_->type();
3859
3860 case OPERATOR_AND:
3861 return Type::make_pointer_type(this->expr_->type());
3862
3863 case OPERATOR_MULT:
3864 {
3865 Type* subtype = this->expr_->type();
3866 Type* points_to = subtype->points_to();
3867 if (points_to == NULL)
3868 return Type::make_error_type();
3869 return points_to;
3870 }
3871
3872 default:
3873 go_unreachable();
3874 }
3875 }
3876
3877 // Determine abstract types for a unary expression.
3878
3879 void
3880 Unary_expression::do_determine_type(const Type_context* context)
3881 {
3882 switch (this->op_)
3883 {
3884 case OPERATOR_PLUS:
3885 case OPERATOR_MINUS:
3886 case OPERATOR_NOT:
3887 case OPERATOR_XOR:
3888 this->expr_->determine_type(context);
3889 break;
3890
3891 case OPERATOR_AND:
3892 // Taking the address of something.
3893 {
3894 Type* subtype = (context->type == NULL
3895 ? NULL
3896 : context->type->points_to());
3897 Type_context subcontext(subtype, false);
3898 this->expr_->determine_type(&subcontext);
3899 }
3900 break;
3901
3902 case OPERATOR_MULT:
3903 // Indirecting through a pointer.
3904 {
3905 Type* subtype = (context->type == NULL
3906 ? NULL
3907 : Type::make_pointer_type(context->type));
3908 Type_context subcontext(subtype, false);
3909 this->expr_->determine_type(&subcontext);
3910 }
3911 break;
3912
3913 default:
3914 go_unreachable();
3915 }
3916 }
3917
3918 // Check types for a unary expression.
3919
3920 void
3921 Unary_expression::do_check_types(Gogo*)
3922 {
3923 Type* type = this->expr_->type();
3924 if (type->is_error())
3925 {
3926 this->set_is_error();
3927 return;
3928 }
3929
3930 switch (this->op_)
3931 {
3932 case OPERATOR_PLUS:
3933 case OPERATOR_MINUS:
3934 if (type->integer_type() == NULL
3935 && type->float_type() == NULL
3936 && type->complex_type() == NULL)
3937 this->report_error(_("expected numeric type"));
3938 break;
3939
3940 case OPERATOR_NOT:
3941 if (!type->is_boolean_type())
3942 this->report_error(_("expected boolean type"));
3943 break;
3944
3945 case OPERATOR_XOR:
3946 if (type->integer_type() == NULL)
3947 this->report_error(_("expected integer"));
3948 break;
3949
3950 case OPERATOR_AND:
3951 if (!this->expr_->is_addressable())
3952 {
3953 if (!this->create_temp_)
3954 {
3955 error_at(this->location(), "invalid operand for unary %<&%>");
3956 this->set_is_error();
3957 }
3958 }
3959 else
3960 this->expr_->issue_nil_check();
3961 break;
3962
3963 case OPERATOR_MULT:
3964 // Indirecting through a pointer.
3965 if (type->points_to() == NULL)
3966 this->report_error(_("expected pointer"));
3967 if (type->points_to()->is_error())
3968 this->set_is_error();
3969 break;
3970
3971 default:
3972 go_unreachable();
3973 }
3974 }
3975
3976 // Get the backend representation for a unary expression.
3977
3978 Bexpression*
3979 Unary_expression::do_get_backend(Translate_context* context)
3980 {
3981 Gogo* gogo = context->gogo();
3982 Location loc = this->location();
3983
3984 // Taking the address of a set-and-use-temporary expression requires
3985 // setting the temporary and then taking the address.
3986 if (this->op_ == OPERATOR_AND)
3987 {
3988 Set_and_use_temporary_expression* sut =
3989 this->expr_->set_and_use_temporary_expression();
3990 if (sut != NULL)
3991 {
3992 Temporary_statement* temp = sut->temporary();
3993 Bvariable* bvar = temp->get_backend_variable(context);
3994 Bexpression* bvar_expr = gogo->backend()->var_expression(bvar, loc);
3995 Bexpression* bval = sut->expression()->get_backend(context);
3996
3997 Bstatement* bassign =
3998 gogo->backend()->assignment_statement(bvar_expr, bval, loc);
3999 Bexpression* bvar_addr =
4000 gogo->backend()->address_expression(bvar_expr, loc);
4001 return gogo->backend()->compound_expression(bassign, bvar_addr, loc);
4002 }
4003 }
4004
4005 Bexpression* ret;
4006 Bexpression* bexpr = this->expr_->get_backend(context);
4007 Btype* btype = this->expr_->type()->get_backend(gogo);
4008 switch (this->op_)
4009 {
4010 case OPERATOR_PLUS:
4011 ret = bexpr;
4012 break;
4013
4014 case OPERATOR_MINUS:
4015 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4016 ret = gogo->backend()->convert_expression(btype, ret, loc);
4017 break;
4018
4019 case OPERATOR_NOT:
4020 case OPERATOR_XOR:
4021 ret = gogo->backend()->unary_expression(this->op_, bexpr, loc);
4022 break;
4023
4024 case OPERATOR_AND:
4025 if (!this->create_temp_)
4026 {
4027 // We should not see a non-constant constructor here; cases
4028 // where we would see one should have been moved onto the
4029 // heap at parse time. Taking the address of a nonconstant
4030 // constructor will not do what the programmer expects.
4031
4032 go_assert(!this->expr_->is_composite_literal()
4033 || this->expr_->is_immutable());
4034 if (this->expr_->classification() == EXPRESSION_UNARY)
4035 {
4036 Unary_expression* ue =
4037 static_cast<Unary_expression*>(this->expr_);
4038 go_assert(ue->op() != OPERATOR_AND);
4039 }
4040 }
4041
4042 static unsigned int counter;
4043 char buf[100];
4044 if (this->is_gc_root_ || this->is_slice_init_)
4045 {
4046 bool copy_to_heap = false;
4047 if (this->is_gc_root_)
4048 {
4049 // Build a decl for a GC root variable. GC roots are mutable, so
4050 // they cannot be represented as an immutable_struct in the
4051 // backend.
4052 static unsigned int root_counter;
4053 snprintf(buf, sizeof buf, "gc%u", root_counter);
4054 ++root_counter;
4055 }
4056 else
4057 {
4058 // Build a decl for a slice value initializer. An immutable slice
4059 // value initializer may have to be copied to the heap if it
4060 // contains pointers in a non-constant context.
4061 snprintf(buf, sizeof buf, "C%u", counter);
4062 ++counter;
4063
4064 Array_type* at = this->expr_->type()->array_type();
4065 go_assert(at != NULL);
4066
4067 // If we are not copying the value to the heap, we will only
4068 // initialize the value once, so we can use this directly
4069 // rather than copying it. In that case we can't make it
4070 // read-only, because the program is permitted to change it.
4071 copy_to_heap = (at->element_type()->has_pointer()
4072 && !context->is_const());
4073 }
4074 Bvariable* implicit =
4075 gogo->backend()->implicit_variable(buf, btype, true, copy_to_heap,
4076 false, 0);
4077 gogo->backend()->implicit_variable_set_init(implicit, buf, btype,
4078 true, copy_to_heap, false,
4079 bexpr);
4080 bexpr = gogo->backend()->var_expression(implicit, loc);
4081 }
4082 else if ((this->expr_->is_composite_literal()
4083 || this->expr_->string_expression() != NULL)
4084 && this->expr_->is_immutable())
4085 {
4086 // Build a decl for a constant constructor.
4087 snprintf(buf, sizeof buf, "C%u", counter);
4088 ++counter;
4089
4090 Bvariable* decl =
4091 gogo->backend()->immutable_struct(buf, true, false, btype, loc);
4092 gogo->backend()->immutable_struct_set_init(decl, buf, true, false,
4093 btype, loc, bexpr);
4094 bexpr = gogo->backend()->var_expression(decl, loc);
4095 }
4096
4097 go_assert(!this->create_temp_ || this->expr_->is_variable());
4098 ret = gogo->backend()->address_expression(bexpr, loc);
4099 break;
4100
4101 case OPERATOR_MULT:
4102 {
4103 go_assert(this->expr_->type()->points_to() != NULL);
4104
4105 // If we are dereferencing the pointer to a large struct, we
4106 // need to check for nil. We don't bother to check for small
4107 // structs because we expect the system to crash on a nil
4108 // pointer dereference. However, if we know the address of this
4109 // expression is being taken, we must always check for nil.
4110
4111 Type* ptype = this->expr_->type()->points_to();
4112 Btype* pbtype = ptype->get_backend(gogo);
4113 if (!ptype->is_void_type())
4114 {
4115 int64_t s = gogo->backend()->type_size(pbtype);
4116 if (s >= 4096 || this->issue_nil_check_)
4117 {
4118 go_assert(this->expr_->is_variable());
4119 Bexpression* nil =
4120 Expression::make_nil(loc)->get_backend(context);
4121 Bexpression* compare =
4122 gogo->backend()->binary_expression(OPERATOR_EQEQ, bexpr,
4123 nil, loc);
4124 Bexpression* crash =
4125 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
4126 loc)->get_backend(context);
4127 bexpr = gogo->backend()->conditional_expression(btype, compare,
4128 crash, bexpr,
4129 loc);
4130
4131 }
4132 }
4133 ret = gogo->backend()->indirect_expression(pbtype, bexpr, false, loc);
4134 }
4135 break;
4136
4137 default:
4138 go_unreachable();
4139 }
4140
4141 return ret;
4142 }
4143
4144 // Export a unary expression.
4145
4146 void
4147 Unary_expression::do_export(Export* exp) const
4148 {
4149 switch (this->op_)
4150 {
4151 case OPERATOR_PLUS:
4152 exp->write_c_string("+ ");
4153 break;
4154 case OPERATOR_MINUS:
4155 exp->write_c_string("- ");
4156 break;
4157 case OPERATOR_NOT:
4158 exp->write_c_string("! ");
4159 break;
4160 case OPERATOR_XOR:
4161 exp->write_c_string("^ ");
4162 break;
4163 case OPERATOR_AND:
4164 case OPERATOR_MULT:
4165 default:
4166 go_unreachable();
4167 }
4168 this->expr_->export_expression(exp);
4169 }
4170
4171 // Import a unary expression.
4172
4173 Expression*
4174 Unary_expression::do_import(Import* imp)
4175 {
4176 Operator op;
4177 switch (imp->get_char())
4178 {
4179 case '+':
4180 op = OPERATOR_PLUS;
4181 break;
4182 case '-':
4183 op = OPERATOR_MINUS;
4184 break;
4185 case '!':
4186 op = OPERATOR_NOT;
4187 break;
4188 case '^':
4189 op = OPERATOR_XOR;
4190 break;
4191 default:
4192 go_unreachable();
4193 }
4194 imp->require_c_string(" ");
4195 Expression* expr = Expression::import_expression(imp);
4196 return Expression::make_unary(op, expr, imp->location());
4197 }
4198
4199 // Dump ast representation of an unary expression.
4200
4201 void
4202 Unary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
4203 {
4204 ast_dump_context->dump_operator(this->op_);
4205 ast_dump_context->ostream() << "(";
4206 ast_dump_context->dump_expression(this->expr_);
4207 ast_dump_context->ostream() << ") ";
4208 }
4209
4210 // Make a unary expression.
4211
4212 Expression*
4213 Expression::make_unary(Operator op, Expression* expr, Location location)
4214 {
4215 return new Unary_expression(op, expr, location);
4216 }
4217
4218 // If this is an indirection through a pointer, return the expression
4219 // being pointed through. Otherwise return this.
4220
4221 Expression*
4222 Expression::deref()
4223 {
4224 if (this->classification_ == EXPRESSION_UNARY)
4225 {
4226 Unary_expression* ue = static_cast<Unary_expression*>(this);
4227 if (ue->op() == OPERATOR_MULT)
4228 return ue->operand();
4229 }
4230 return this;
4231 }
4232
4233 // Class Binary_expression.
4234
4235 // Traversal.
4236
4237 int
4238 Binary_expression::do_traverse(Traverse* traverse)
4239 {
4240 int t = Expression::traverse(&this->left_, traverse);
4241 if (t == TRAVERSE_EXIT)
4242 return TRAVERSE_EXIT;
4243 return Expression::traverse(&this->right_, traverse);
4244 }
4245
4246 // Return the type to use for a binary operation on operands of
4247 // LEFT_TYPE and RIGHT_TYPE. These are the types of constants and as
4248 // such may be NULL or abstract.
4249
4250 bool
4251 Binary_expression::operation_type(Operator op, Type* left_type,
4252 Type* right_type, Type** result_type)
4253 {
4254 if (left_type != right_type
4255 && !left_type->is_abstract()
4256 && !right_type->is_abstract()
4257 && left_type->base() != right_type->base()
4258 && op != OPERATOR_LSHIFT
4259 && op != OPERATOR_RSHIFT)
4260 {
4261 // May be a type error--let it be diagnosed elsewhere.
4262 return false;
4263 }
4264
4265 if (op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT)
4266 {
4267 if (left_type->integer_type() != NULL)
4268 *result_type = left_type;
4269 else
4270 *result_type = Type::make_abstract_integer_type();
4271 }
4272 else if (!left_type->is_abstract() && left_type->named_type() != NULL)
4273 *result_type = left_type;
4274 else if (!right_type->is_abstract() && right_type->named_type() != NULL)
4275 *result_type = right_type;
4276 else if (!left_type->is_abstract())
4277 *result_type = left_type;
4278 else if (!right_type->is_abstract())
4279 *result_type = right_type;
4280 else if (left_type->complex_type() != NULL)
4281 *result_type = left_type;
4282 else if (right_type->complex_type() != NULL)
4283 *result_type = right_type;
4284 else if (left_type->float_type() != NULL)
4285 *result_type = left_type;
4286 else if (right_type->float_type() != NULL)
4287 *result_type = right_type;
4288 else if (left_type->integer_type() != NULL
4289 && left_type->integer_type()->is_rune())
4290 *result_type = left_type;
4291 else if (right_type->integer_type() != NULL
4292 && right_type->integer_type()->is_rune())
4293 *result_type = right_type;
4294 else
4295 *result_type = left_type;
4296
4297 return true;
4298 }
4299
4300 // Convert an integer comparison code and an operator to a boolean
4301 // value.
4302
4303 bool
4304 Binary_expression::cmp_to_bool(Operator op, int cmp)
4305 {
4306 switch (op)
4307 {
4308 case OPERATOR_EQEQ:
4309 return cmp == 0;
4310 break;
4311 case OPERATOR_NOTEQ:
4312 return cmp != 0;
4313 break;
4314 case OPERATOR_LT:
4315 return cmp < 0;
4316 break;
4317 case OPERATOR_LE:
4318 return cmp <= 0;
4319 case OPERATOR_GT:
4320 return cmp > 0;
4321 case OPERATOR_GE:
4322 return cmp >= 0;
4323 default:
4324 go_unreachable();
4325 }
4326 }
4327
4328 // Compare constants according to OP.
4329
4330 bool
4331 Binary_expression::compare_constant(Operator op, Numeric_constant* left_nc,
4332 Numeric_constant* right_nc,
4333 Location location, bool* result)
4334 {
4335 Type* left_type = left_nc->type();
4336 Type* right_type = right_nc->type();
4337
4338 Type* type;
4339 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4340 return false;
4341
4342 // When comparing an untyped operand to a typed operand, we are
4343 // effectively coercing the untyped operand to the other operand's
4344 // type, so make sure that is valid.
4345 if (!left_nc->set_type(type, true, location)
4346 || !right_nc->set_type(type, true, location))
4347 return false;
4348
4349 bool ret;
4350 int cmp;
4351 if (type->complex_type() != NULL)
4352 {
4353 if (op != OPERATOR_EQEQ && op != OPERATOR_NOTEQ)
4354 return false;
4355 ret = Binary_expression::compare_complex(left_nc, right_nc, &cmp);
4356 }
4357 else if (type->float_type() != NULL)
4358 ret = Binary_expression::compare_float(left_nc, right_nc, &cmp);
4359 else
4360 ret = Binary_expression::compare_integer(left_nc, right_nc, &cmp);
4361
4362 if (ret)
4363 *result = Binary_expression::cmp_to_bool(op, cmp);
4364
4365 return ret;
4366 }
4367
4368 // Compare integer constants.
4369
4370 bool
4371 Binary_expression::compare_integer(const Numeric_constant* left_nc,
4372 const Numeric_constant* right_nc,
4373 int* cmp)
4374 {
4375 mpz_t left_val;
4376 if (!left_nc->to_int(&left_val))
4377 return false;
4378 mpz_t right_val;
4379 if (!right_nc->to_int(&right_val))
4380 {
4381 mpz_clear(left_val);
4382 return false;
4383 }
4384
4385 *cmp = mpz_cmp(left_val, right_val);
4386
4387 mpz_clear(left_val);
4388 mpz_clear(right_val);
4389
4390 return true;
4391 }
4392
4393 // Compare floating point constants.
4394
4395 bool
4396 Binary_expression::compare_float(const Numeric_constant* left_nc,
4397 const Numeric_constant* right_nc,
4398 int* cmp)
4399 {
4400 mpfr_t left_val;
4401 if (!left_nc->to_float(&left_val))
4402 return false;
4403 mpfr_t right_val;
4404 if (!right_nc->to_float(&right_val))
4405 {
4406 mpfr_clear(left_val);
4407 return false;
4408 }
4409
4410 // We already coerced both operands to the same type. If that type
4411 // is not an abstract type, we need to round the values accordingly.
4412 Type* type = left_nc->type();
4413 if (!type->is_abstract() && type->float_type() != NULL)
4414 {
4415 int bits = type->float_type()->bits();
4416 mpfr_prec_round(left_val, bits, GMP_RNDN);
4417 mpfr_prec_round(right_val, bits, GMP_RNDN);
4418 }
4419
4420 *cmp = mpfr_cmp(left_val, right_val);
4421
4422 mpfr_clear(left_val);
4423 mpfr_clear(right_val);
4424
4425 return true;
4426 }
4427
4428 // Compare complex constants. Complex numbers may only be compared
4429 // for equality.
4430
4431 bool
4432 Binary_expression::compare_complex(const Numeric_constant* left_nc,
4433 const Numeric_constant* right_nc,
4434 int* cmp)
4435 {
4436 mpc_t left_val;
4437 if (!left_nc->to_complex(&left_val))
4438 return false;
4439 mpc_t right_val;
4440 if (!right_nc->to_complex(&right_val))
4441 {
4442 mpc_clear(left_val);
4443 return false;
4444 }
4445
4446 // We already coerced both operands to the same type. If that type
4447 // is not an abstract type, we need to round the values accordingly.
4448 Type* type = left_nc->type();
4449 if (!type->is_abstract() && type->complex_type() != NULL)
4450 {
4451 int bits = type->complex_type()->bits();
4452 mpfr_prec_round(mpc_realref(left_val), bits / 2, GMP_RNDN);
4453 mpfr_prec_round(mpc_imagref(left_val), bits / 2, GMP_RNDN);
4454 mpfr_prec_round(mpc_realref(right_val), bits / 2, GMP_RNDN);
4455 mpfr_prec_round(mpc_imagref(right_val), bits / 2, GMP_RNDN);
4456 }
4457
4458 *cmp = mpc_cmp(left_val, right_val) != 0;
4459
4460 mpc_clear(left_val);
4461 mpc_clear(right_val);
4462
4463 return true;
4464 }
4465
4466 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC. Return
4467 // true if this could be done, false if not. Issue errors at LOCATION
4468 // as appropriate.
4469
4470 bool
4471 Binary_expression::eval_constant(Operator op, Numeric_constant* left_nc,
4472 Numeric_constant* right_nc,
4473 Location location, Numeric_constant* nc)
4474 {
4475 switch (op)
4476 {
4477 case OPERATOR_OROR:
4478 case OPERATOR_ANDAND:
4479 case OPERATOR_EQEQ:
4480 case OPERATOR_NOTEQ:
4481 case OPERATOR_LT:
4482 case OPERATOR_LE:
4483 case OPERATOR_GT:
4484 case OPERATOR_GE:
4485 // These return boolean values, not numeric.
4486 return false;
4487 default:
4488 break;
4489 }
4490
4491 Type* left_type = left_nc->type();
4492 Type* right_type = right_nc->type();
4493
4494 Type* type;
4495 if (!Binary_expression::operation_type(op, left_type, right_type, &type))
4496 return false;
4497
4498 bool is_shift = op == OPERATOR_LSHIFT || op == OPERATOR_RSHIFT;
4499
4500 // When combining an untyped operand with a typed operand, we are
4501 // effectively coercing the untyped operand to the other operand's
4502 // type, so make sure that is valid.
4503 if (!left_nc->set_type(type, true, location))
4504 return false;
4505 if (!is_shift && !right_nc->set_type(type, true, location))
4506 return false;
4507
4508 bool r;
4509 if (type->complex_type() != NULL)
4510 r = Binary_expression::eval_complex(op, left_nc, right_nc, location, nc);
4511 else if (type->float_type() != NULL)
4512 r = Binary_expression::eval_float(op, left_nc, right_nc, location, nc);
4513 else
4514 r = Binary_expression::eval_integer(op, left_nc, right_nc, location, nc);
4515
4516 if (r)
4517 r = nc->set_type(type, true, location);
4518
4519 return r;
4520 }
4521
4522 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4523 // integer operations. Return true if this could be done, false if
4524 // not.
4525
4526 bool
4527 Binary_expression::eval_integer(Operator op, const Numeric_constant* left_nc,
4528 const Numeric_constant* right_nc,
4529 Location location, Numeric_constant* nc)
4530 {
4531 mpz_t left_val;
4532 if (!left_nc->to_int(&left_val))
4533 return false;
4534 mpz_t right_val;
4535 if (!right_nc->to_int(&right_val))
4536 {
4537 mpz_clear(left_val);
4538 return false;
4539 }
4540
4541 mpz_t val;
4542 mpz_init(val);
4543
4544 switch (op)
4545 {
4546 case OPERATOR_PLUS:
4547 mpz_add(val, left_val, right_val);
4548 if (mpz_sizeinbase(val, 2) > 0x100000)
4549 {
4550 error_at(location, "constant addition overflow");
4551 mpz_set_ui(val, 1);
4552 }
4553 break;
4554 case OPERATOR_MINUS:
4555 mpz_sub(val, left_val, right_val);
4556 if (mpz_sizeinbase(val, 2) > 0x100000)
4557 {
4558 error_at(location, "constant subtraction overflow");
4559 mpz_set_ui(val, 1);
4560 }
4561 break;
4562 case OPERATOR_OR:
4563 mpz_ior(val, left_val, right_val);
4564 break;
4565 case OPERATOR_XOR:
4566 mpz_xor(val, left_val, right_val);
4567 break;
4568 case OPERATOR_MULT:
4569 mpz_mul(val, left_val, right_val);
4570 if (mpz_sizeinbase(val, 2) > 0x100000)
4571 {
4572 error_at(location, "constant multiplication overflow");
4573 mpz_set_ui(val, 1);
4574 }
4575 break;
4576 case OPERATOR_DIV:
4577 if (mpz_sgn(right_val) != 0)
4578 mpz_tdiv_q(val, left_val, right_val);
4579 else
4580 {
4581 error_at(location, "division by zero");
4582 mpz_set_ui(val, 0);
4583 }
4584 break;
4585 case OPERATOR_MOD:
4586 if (mpz_sgn(right_val) != 0)
4587 mpz_tdiv_r(val, left_val, right_val);
4588 else
4589 {
4590 error_at(location, "division by zero");
4591 mpz_set_ui(val, 0);
4592 }
4593 break;
4594 case OPERATOR_LSHIFT:
4595 {
4596 unsigned long shift = mpz_get_ui(right_val);
4597 if (mpz_cmp_ui(right_val, shift) == 0 && shift <= 0x100000)
4598 mpz_mul_2exp(val, left_val, shift);
4599 else
4600 {
4601 error_at(location, "shift count overflow");
4602 mpz_set_ui(val, 1);
4603 }
4604 break;
4605 }
4606 break;
4607 case OPERATOR_RSHIFT:
4608 {
4609 unsigned long shift = mpz_get_ui(right_val);
4610 if (mpz_cmp_ui(right_val, shift) != 0)
4611 {
4612 error_at(location, "shift count overflow");
4613 mpz_set_ui(val, 1);
4614 }
4615 else
4616 {
4617 if (mpz_cmp_ui(left_val, 0) >= 0)
4618 mpz_tdiv_q_2exp(val, left_val, shift);
4619 else
4620 mpz_fdiv_q_2exp(val, left_val, shift);
4621 }
4622 break;
4623 }
4624 break;
4625 case OPERATOR_AND:
4626 mpz_and(val, left_val, right_val);
4627 break;
4628 case OPERATOR_BITCLEAR:
4629 {
4630 mpz_t tval;
4631 mpz_init(tval);
4632 mpz_com(tval, right_val);
4633 mpz_and(val, left_val, tval);
4634 mpz_clear(tval);
4635 }
4636 break;
4637 default:
4638 go_unreachable();
4639 }
4640
4641 mpz_clear(left_val);
4642 mpz_clear(right_val);
4643
4644 if (left_nc->is_rune()
4645 || (op != OPERATOR_LSHIFT
4646 && op != OPERATOR_RSHIFT
4647 && right_nc->is_rune()))
4648 nc->set_rune(NULL, val);
4649 else
4650 nc->set_int(NULL, val);
4651
4652 mpz_clear(val);
4653
4654 return true;
4655 }
4656
4657 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4658 // floating point operations. Return true if this could be done,
4659 // false if not.
4660
4661 bool
4662 Binary_expression::eval_float(Operator op, const Numeric_constant* left_nc,
4663 const Numeric_constant* right_nc,
4664 Location location, Numeric_constant* nc)
4665 {
4666 mpfr_t left_val;
4667 if (!left_nc->to_float(&left_val))
4668 return false;
4669 mpfr_t right_val;
4670 if (!right_nc->to_float(&right_val))
4671 {
4672 mpfr_clear(left_val);
4673 return false;
4674 }
4675
4676 mpfr_t val;
4677 mpfr_init(val);
4678
4679 bool ret = true;
4680 switch (op)
4681 {
4682 case OPERATOR_PLUS:
4683 mpfr_add(val, left_val, right_val, GMP_RNDN);
4684 break;
4685 case OPERATOR_MINUS:
4686 mpfr_sub(val, left_val, right_val, GMP_RNDN);
4687 break;
4688 case OPERATOR_OR:
4689 case OPERATOR_XOR:
4690 case OPERATOR_AND:
4691 case OPERATOR_BITCLEAR:
4692 case OPERATOR_MOD:
4693 case OPERATOR_LSHIFT:
4694 case OPERATOR_RSHIFT:
4695 mpfr_set_ui(val, 0, GMP_RNDN);
4696 ret = false;
4697 break;
4698 case OPERATOR_MULT:
4699 mpfr_mul(val, left_val, right_val, GMP_RNDN);
4700 break;
4701 case OPERATOR_DIV:
4702 if (!mpfr_zero_p(right_val))
4703 mpfr_div(val, left_val, right_val, GMP_RNDN);
4704 else
4705 {
4706 error_at(location, "division by zero");
4707 mpfr_set_ui(val, 0, GMP_RNDN);
4708 }
4709 break;
4710 default:
4711 go_unreachable();
4712 }
4713
4714 mpfr_clear(left_val);
4715 mpfr_clear(right_val);
4716
4717 nc->set_float(NULL, val);
4718 mpfr_clear(val);
4719
4720 return ret;
4721 }
4722
4723 // Apply binary opcode OP to LEFT_NC and RIGHT_NC, setting NC, using
4724 // complex operations. Return true if this could be done, false if
4725 // not.
4726
4727 bool
4728 Binary_expression::eval_complex(Operator op, const Numeric_constant* left_nc,
4729 const Numeric_constant* right_nc,
4730 Location location, Numeric_constant* nc)
4731 {
4732 mpc_t left_val;
4733 if (!left_nc->to_complex(&left_val))
4734 return false;
4735 mpc_t right_val;
4736 if (!right_nc->to_complex(&right_val))
4737 {
4738 mpc_clear(left_val);
4739 return false;
4740 }
4741
4742 mpc_t val;
4743 mpc_init2(val, mpc_precision);
4744
4745 bool ret = true;
4746 switch (op)
4747 {
4748 case OPERATOR_PLUS:
4749 mpc_add(val, left_val, right_val, MPC_RNDNN);
4750 break;
4751 case OPERATOR_MINUS:
4752 mpc_sub(val, left_val, right_val, MPC_RNDNN);
4753 break;
4754 case OPERATOR_OR:
4755 case OPERATOR_XOR:
4756 case OPERATOR_AND:
4757 case OPERATOR_BITCLEAR:
4758 case OPERATOR_MOD:
4759 case OPERATOR_LSHIFT:
4760 case OPERATOR_RSHIFT:
4761 mpc_set_ui(val, 0, MPC_RNDNN);
4762 ret = false;
4763 break;
4764 case OPERATOR_MULT:
4765 mpc_mul(val, left_val, right_val, MPC_RNDNN);
4766 break;
4767 case OPERATOR_DIV:
4768 if (mpc_cmp_si(right_val, 0) == 0)
4769 {
4770 error_at(location, "division by zero");
4771 mpc_set_ui(val, 0, MPC_RNDNN);
4772 break;
4773 }
4774 mpc_div(val, left_val, right_val, MPC_RNDNN);
4775 break;
4776 default:
4777 go_unreachable();
4778 }
4779
4780 mpc_clear(left_val);
4781 mpc_clear(right_val);
4782
4783 nc->set_complex(NULL, val);
4784 mpc_clear(val);
4785
4786 return ret;
4787 }
4788
4789 // Lower a binary expression. We have to evaluate constant
4790 // expressions now, in order to implement Go's unlimited precision
4791 // constants.
4792
4793 Expression*
4794 Binary_expression::do_lower(Gogo* gogo, Named_object*,
4795 Statement_inserter* inserter, int)
4796 {
4797 Location location = this->location();
4798 Operator op = this->op_;
4799 Expression* left = this->left_;
4800 Expression* right = this->right_;
4801
4802 const bool is_comparison = (op == OPERATOR_EQEQ
4803 || op == OPERATOR_NOTEQ
4804 || op == OPERATOR_LT
4805 || op == OPERATOR_LE
4806 || op == OPERATOR_GT
4807 || op == OPERATOR_GE);
4808
4809 // Numeric constant expressions.
4810 {
4811 Numeric_constant left_nc;
4812 Numeric_constant right_nc;
4813 if (left->numeric_constant_value(&left_nc)
4814 && right->numeric_constant_value(&right_nc))
4815 {
4816 if (is_comparison)
4817 {
4818 bool result;
4819 if (!Binary_expression::compare_constant(op, &left_nc,
4820 &right_nc, location,
4821 &result))
4822 return this;
4823 return Expression::make_cast(Type::make_boolean_type(),
4824 Expression::make_boolean(result,
4825 location),
4826 location);
4827 }
4828 else
4829 {
4830 Numeric_constant nc;
4831 if (!Binary_expression::eval_constant(op, &left_nc, &right_nc,
4832 location, &nc))
4833 return this;
4834 return nc.expression(location);
4835 }
4836 }
4837 }
4838
4839 // String constant expressions.
4840 if (left->type()->is_string_type() && right->type()->is_string_type())
4841 {
4842 std::string left_string;
4843 std::string right_string;
4844 if (left->string_constant_value(&left_string)
4845 && right->string_constant_value(&right_string))
4846 {
4847 if (op == OPERATOR_PLUS)
4848 return Expression::make_string(left_string + right_string,
4849 location);
4850 else if (is_comparison)
4851 {
4852 int cmp = left_string.compare(right_string);
4853 bool r = Binary_expression::cmp_to_bool(op, cmp);
4854 return Expression::make_boolean(r, location);
4855 }
4856 }
4857 }
4858
4859 // Lower struct, array, and some interface comparisons.
4860 if (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ)
4861 {
4862 if (left->type()->struct_type() != NULL
4863 && right->type()->struct_type() != NULL)
4864 return this->lower_struct_comparison(gogo, inserter);
4865 else if (left->type()->array_type() != NULL
4866 && !left->type()->is_slice_type()
4867 && right->type()->array_type() != NULL
4868 && !right->type()->is_slice_type())
4869 return this->lower_array_comparison(gogo, inserter);
4870 else if ((left->type()->interface_type() != NULL
4871 && right->type()->interface_type() == NULL)
4872 || (left->type()->interface_type() == NULL
4873 && right->type()->interface_type() != NULL))
4874 return this->lower_interface_value_comparison(gogo, inserter);
4875 }
4876
4877 return this;
4878 }
4879
4880 // Lower a struct comparison.
4881
4882 Expression*
4883 Binary_expression::lower_struct_comparison(Gogo* gogo,
4884 Statement_inserter* inserter)
4885 {
4886 Struct_type* st = this->left_->type()->struct_type();
4887 Struct_type* st2 = this->right_->type()->struct_type();
4888 if (st2 == NULL)
4889 return this;
4890 if (st != st2 && !Type::are_identical(st, st2, false, NULL))
4891 return this;
4892 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
4893 this->right_->type(), NULL))
4894 return this;
4895
4896 // See if we can compare using memcmp. As a heuristic, we use
4897 // memcmp rather than field references and comparisons if there are
4898 // more than two fields.
4899 if (st->compare_is_identity(gogo) && st->total_field_count() > 2)
4900 return this->lower_compare_to_memcmp(gogo, inserter);
4901
4902 Location loc = this->location();
4903
4904 Expression* left = this->left_;
4905 Temporary_statement* left_temp = NULL;
4906 if (left->var_expression() == NULL
4907 && left->temporary_reference_expression() == NULL)
4908 {
4909 left_temp = Statement::make_temporary(left->type(), NULL, loc);
4910 inserter->insert(left_temp);
4911 left = Expression::make_set_and_use_temporary(left_temp, left, loc);
4912 }
4913
4914 Expression* right = this->right_;
4915 Temporary_statement* right_temp = NULL;
4916 if (right->var_expression() == NULL
4917 && right->temporary_reference_expression() == NULL)
4918 {
4919 right_temp = Statement::make_temporary(right->type(), NULL, loc);
4920 inserter->insert(right_temp);
4921 right = Expression::make_set_and_use_temporary(right_temp, right, loc);
4922 }
4923
4924 Expression* ret = Expression::make_boolean(true, loc);
4925 const Struct_field_list* fields = st->fields();
4926 unsigned int field_index = 0;
4927 for (Struct_field_list::const_iterator pf = fields->begin();
4928 pf != fields->end();
4929 ++pf, ++field_index)
4930 {
4931 if (Gogo::is_sink_name(pf->field_name()))
4932 continue;
4933
4934 if (field_index > 0)
4935 {
4936 if (left_temp == NULL)
4937 left = left->copy();
4938 else
4939 left = Expression::make_temporary_reference(left_temp, loc);
4940 if (right_temp == NULL)
4941 right = right->copy();
4942 else
4943 right = Expression::make_temporary_reference(right_temp, loc);
4944 }
4945 Expression* f1 = Expression::make_field_reference(left, field_index,
4946 loc);
4947 Expression* f2 = Expression::make_field_reference(right, field_index,
4948 loc);
4949 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, f1, f2, loc);
4950 ret = Expression::make_binary(OPERATOR_ANDAND, ret, cond, loc);
4951 }
4952
4953 if (this->op_ == OPERATOR_NOTEQ)
4954 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
4955
4956 return ret;
4957 }
4958
4959 // Lower an array comparison.
4960
4961 Expression*
4962 Binary_expression::lower_array_comparison(Gogo* gogo,
4963 Statement_inserter* inserter)
4964 {
4965 Array_type* at = this->left_->type()->array_type();
4966 Array_type* at2 = this->right_->type()->array_type();
4967 if (at2 == NULL)
4968 return this;
4969 if (at != at2 && !Type::are_identical(at, at2, false, NULL))
4970 return this;
4971 if (!Type::are_compatible_for_comparison(true, this->left_->type(),
4972 this->right_->type(), NULL))
4973 return this;
4974
4975 // Call memcmp directly if possible. This may let the middle-end
4976 // optimize the call.
4977 if (at->compare_is_identity(gogo))
4978 return this->lower_compare_to_memcmp(gogo, inserter);
4979
4980 // Call the array comparison function.
4981 Named_object* hash_fn;
4982 Named_object* equal_fn;
4983 at->type_functions(gogo, this->left_->type()->named_type(), NULL, NULL,
4984 &hash_fn, &equal_fn);
4985
4986 Location loc = this->location();
4987
4988 Expression* func = Expression::make_func_reference(equal_fn, NULL, loc);
4989
4990 Expression_list* args = new Expression_list();
4991 args->push_back(this->operand_address(inserter, this->left_));
4992 args->push_back(this->operand_address(inserter, this->right_));
4993 args->push_back(Expression::make_type_info(at, TYPE_INFO_SIZE));
4994
4995 Expression* ret = Expression::make_call(func, args, false, loc);
4996
4997 if (this->op_ == OPERATOR_NOTEQ)
4998 ret = Expression::make_unary(OPERATOR_NOT, ret, loc);
4999
5000 return ret;
5001 }
5002
5003 // Lower an interface to value comparison.
5004
5005 Expression*
5006 Binary_expression::lower_interface_value_comparison(Gogo*,
5007 Statement_inserter* inserter)
5008 {
5009 Type* left_type = this->left_->type();
5010 Type* right_type = this->right_->type();
5011 Interface_type* ift;
5012 if (left_type->interface_type() != NULL)
5013 {
5014 ift = left_type->interface_type();
5015 if (!ift->implements_interface(right_type, NULL))
5016 return this;
5017 }
5018 else
5019 {
5020 ift = right_type->interface_type();
5021 if (!ift->implements_interface(left_type, NULL))
5022 return this;
5023 }
5024 if (!Type::are_compatible_for_comparison(true, left_type, right_type, NULL))
5025 return this;
5026
5027 Location loc = this->location();
5028
5029 if (left_type->interface_type() == NULL
5030 && left_type->points_to() == NULL
5031 && !this->left_->is_addressable())
5032 {
5033 Temporary_statement* temp =
5034 Statement::make_temporary(left_type, NULL, loc);
5035 inserter->insert(temp);
5036 this->left_ =
5037 Expression::make_set_and_use_temporary(temp, this->left_, loc);
5038 }
5039
5040 if (right_type->interface_type() == NULL
5041 && right_type->points_to() == NULL
5042 && !this->right_->is_addressable())
5043 {
5044 Temporary_statement* temp =
5045 Statement::make_temporary(right_type, NULL, loc);
5046 inserter->insert(temp);
5047 this->right_ =
5048 Expression::make_set_and_use_temporary(temp, this->right_, loc);
5049 }
5050
5051 return this;
5052 }
5053
5054 // Lower a struct or array comparison to a call to memcmp.
5055
5056 Expression*
5057 Binary_expression::lower_compare_to_memcmp(Gogo*, Statement_inserter* inserter)
5058 {
5059 Location loc = this->location();
5060
5061 Expression* a1 = this->operand_address(inserter, this->left_);
5062 Expression* a2 = this->operand_address(inserter, this->right_);
5063 Expression* len = Expression::make_type_info(this->left_->type(),
5064 TYPE_INFO_SIZE);
5065
5066 Expression* call = Runtime::make_call(Runtime::MEMCMP, loc, 3, a1, a2, len);
5067 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
5068 return Expression::make_binary(this->op_, call, zero, loc);
5069 }
5070
5071 Expression*
5072 Binary_expression::do_flatten(Gogo* gogo, Named_object*,
5073 Statement_inserter* inserter)
5074 {
5075 Location loc = this->location();
5076 if (this->left_->type()->is_error_type()
5077 || this->right_->type()->is_error_type()
5078 || this->left_->is_error_expression()
5079 || this->right_->is_error_expression())
5080 {
5081 go_assert(saw_errors());
5082 return Expression::make_error(loc);
5083 }
5084
5085 Temporary_statement* temp;
5086 if (this->left_->type()->is_string_type()
5087 && this->op_ == OPERATOR_PLUS)
5088 {
5089 if (!this->left_->is_variable()
5090 && !this->left_->is_constant())
5091 {
5092 temp = Statement::make_temporary(NULL, this->left_, loc);
5093 inserter->insert(temp);
5094 this->left_ = Expression::make_temporary_reference(temp, loc);
5095 }
5096 if (!this->right_->is_variable()
5097 && !this->right_->is_constant())
5098 {
5099 temp =
5100 Statement::make_temporary(this->left_->type(), this->right_, loc);
5101 this->right_ = Expression::make_temporary_reference(temp, loc);
5102 inserter->insert(temp);
5103 }
5104 }
5105
5106 Type* left_type = this->left_->type();
5107 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5108 || this->op_ == OPERATOR_RSHIFT);
5109 bool is_idiv_op = ((this->op_ == OPERATOR_DIV &&
5110 left_type->integer_type() != NULL)
5111 || this->op_ == OPERATOR_MOD);
5112
5113 if (is_shift_op
5114 || (is_idiv_op
5115 && (gogo->check_divide_by_zero() || gogo->check_divide_overflow())))
5116 {
5117 if (!this->left_->is_variable())
5118 {
5119 temp = Statement::make_temporary(NULL, this->left_, loc);
5120 inserter->insert(temp);
5121 this->left_ = Expression::make_temporary_reference(temp, loc);
5122 }
5123 if (!this->right_->is_variable())
5124 {
5125 temp =
5126 Statement::make_temporary(NULL, this->right_, loc);
5127 this->right_ = Expression::make_temporary_reference(temp, loc);
5128 inserter->insert(temp);
5129 }
5130 }
5131 return this;
5132 }
5133
5134
5135 // Return the address of EXPR, cast to unsafe.Pointer.
5136
5137 Expression*
5138 Binary_expression::operand_address(Statement_inserter* inserter,
5139 Expression* expr)
5140 {
5141 Location loc = this->location();
5142
5143 if (!expr->is_addressable())
5144 {
5145 Temporary_statement* temp = Statement::make_temporary(expr->type(), NULL,
5146 loc);
5147 inserter->insert(temp);
5148 expr = Expression::make_set_and_use_temporary(temp, expr, loc);
5149 }
5150 expr = Expression::make_unary(OPERATOR_AND, expr, loc);
5151 static_cast<Unary_expression*>(expr)->set_does_not_escape();
5152 Type* void_type = Type::make_void_type();
5153 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
5154 return Expression::make_cast(unsafe_pointer_type, expr, loc);
5155 }
5156
5157 // Return the numeric constant value, if it has one.
5158
5159 bool
5160 Binary_expression::do_numeric_constant_value(Numeric_constant* nc) const
5161 {
5162 Numeric_constant left_nc;
5163 if (!this->left_->numeric_constant_value(&left_nc))
5164 return false;
5165 Numeric_constant right_nc;
5166 if (!this->right_->numeric_constant_value(&right_nc))
5167 return false;
5168 return Binary_expression::eval_constant(this->op_, &left_nc, &right_nc,
5169 this->location(), nc);
5170 }
5171
5172 // Note that the value is being discarded.
5173
5174 bool
5175 Binary_expression::do_discarding_value()
5176 {
5177 if (this->op_ == OPERATOR_OROR || this->op_ == OPERATOR_ANDAND)
5178 return this->right_->discarding_value();
5179 else
5180 {
5181 this->unused_value_error();
5182 return false;
5183 }
5184 }
5185
5186 // Get type.
5187
5188 Type*
5189 Binary_expression::do_type()
5190 {
5191 if (this->classification() == EXPRESSION_ERROR)
5192 return Type::make_error_type();
5193
5194 switch (this->op_)
5195 {
5196 case OPERATOR_EQEQ:
5197 case OPERATOR_NOTEQ:
5198 case OPERATOR_LT:
5199 case OPERATOR_LE:
5200 case OPERATOR_GT:
5201 case OPERATOR_GE:
5202 if (this->type_ == NULL)
5203 this->type_ = Type::make_boolean_type();
5204 return this->type_;
5205
5206 case OPERATOR_PLUS:
5207 case OPERATOR_MINUS:
5208 case OPERATOR_OR:
5209 case OPERATOR_XOR:
5210 case OPERATOR_MULT:
5211 case OPERATOR_DIV:
5212 case OPERATOR_MOD:
5213 case OPERATOR_AND:
5214 case OPERATOR_BITCLEAR:
5215 case OPERATOR_OROR:
5216 case OPERATOR_ANDAND:
5217 {
5218 Type* type;
5219 if (!Binary_expression::operation_type(this->op_,
5220 this->left_->type(),
5221 this->right_->type(),
5222 &type))
5223 return Type::make_error_type();
5224 return type;
5225 }
5226
5227 case OPERATOR_LSHIFT:
5228 case OPERATOR_RSHIFT:
5229 return this->left_->type();
5230
5231 default:
5232 go_unreachable();
5233 }
5234 }
5235
5236 // Set type for a binary expression.
5237
5238 void
5239 Binary_expression::do_determine_type(const Type_context* context)
5240 {
5241 Type* tleft = this->left_->type();
5242 Type* tright = this->right_->type();
5243
5244 // Both sides should have the same type, except for the shift
5245 // operations. For a comparison, we should ignore the incoming
5246 // type.
5247
5248 bool is_shift_op = (this->op_ == OPERATOR_LSHIFT
5249 || this->op_ == OPERATOR_RSHIFT);
5250
5251 bool is_comparison = (this->op_ == OPERATOR_EQEQ
5252 || this->op_ == OPERATOR_NOTEQ
5253 || this->op_ == OPERATOR_LT
5254 || this->op_ == OPERATOR_LE
5255 || this->op_ == OPERATOR_GT
5256 || this->op_ == OPERATOR_GE);
5257
5258 Type_context subcontext(*context);
5259
5260 if (is_comparison)
5261 {
5262 // In a comparison, the context does not determine the types of
5263 // the operands.
5264 subcontext.type = NULL;
5265 }
5266
5267 // Set the context for the left hand operand.
5268 if (is_shift_op)
5269 {
5270 // The right hand operand of a shift plays no role in
5271 // determining the type of the left hand operand.
5272 }
5273 else if (!tleft->is_abstract())
5274 subcontext.type = tleft;
5275 else if (!tright->is_abstract())
5276 subcontext.type = tright;
5277 else if (subcontext.type == NULL)
5278 {
5279 if ((tleft->integer_type() != NULL && tright->integer_type() != NULL)
5280 || (tleft->float_type() != NULL && tright->float_type() != NULL)
5281 || (tleft->complex_type() != NULL && tright->complex_type() != NULL))
5282 {
5283 // Both sides have an abstract integer, abstract float, or
5284 // abstract complex type. Just let CONTEXT determine
5285 // whether they may remain abstract or not.
5286 }
5287 else if (tleft->complex_type() != NULL)
5288 subcontext.type = tleft;
5289 else if (tright->complex_type() != NULL)
5290 subcontext.type = tright;
5291 else if (tleft->float_type() != NULL)
5292 subcontext.type = tleft;
5293 else if (tright->float_type() != NULL)
5294 subcontext.type = tright;
5295 else
5296 subcontext.type = tleft;
5297
5298 if (subcontext.type != NULL && !context->may_be_abstract)
5299 subcontext.type = subcontext.type->make_non_abstract_type();
5300 }
5301
5302 this->left_->determine_type(&subcontext);
5303
5304 if (is_shift_op)
5305 {
5306 // We may have inherited an unusable type for the shift operand.
5307 // Give a useful error if that happened.
5308 if (tleft->is_abstract()
5309 && subcontext.type != NULL
5310 && !subcontext.may_be_abstract
5311 && subcontext.type->interface_type() == NULL
5312 && subcontext.type->integer_type() == NULL)
5313 this->report_error(("invalid context-determined non-integer type "
5314 "for left operand of shift"));
5315
5316 // The context for the right hand operand is the same as for the
5317 // left hand operand, except for a shift operator.
5318 subcontext.type = Type::lookup_integer_type("uint");
5319 subcontext.may_be_abstract = false;
5320 }
5321
5322 this->right_->determine_type(&subcontext);
5323
5324 if (is_comparison)
5325 {
5326 if (this->type_ != NULL && !this->type_->is_abstract())
5327 ;
5328 else if (context->type != NULL && context->type->is_boolean_type())
5329 this->type_ = context->type;
5330 else if (!context->may_be_abstract)
5331 this->type_ = Type::lookup_bool_type();
5332 }
5333 }
5334
5335 // Report an error if the binary operator OP does not support TYPE.
5336 // OTYPE is the type of the other operand. Return whether the
5337 // operation is OK. This should not be used for shift.
5338
5339 bool
5340 Binary_expression::check_operator_type(Operator op, Type* type, Type* otype,
5341 Location location)
5342 {
5343 switch (op)
5344 {
5345 case OPERATOR_OROR:
5346 case OPERATOR_ANDAND:
5347 if (!type->is_boolean_type())
5348 {
5349 error_at(location, "expected boolean type");
5350 return false;
5351 }
5352 break;
5353
5354 case OPERATOR_EQEQ:
5355 case OPERATOR_NOTEQ:
5356 {
5357 std::string reason;
5358 if (!Type::are_compatible_for_comparison(true, type, otype, &reason))
5359 {
5360 error_at(location, "%s", reason.c_str());
5361 return false;
5362 }
5363 }
5364 break;
5365
5366 case OPERATOR_LT:
5367 case OPERATOR_LE:
5368 case OPERATOR_GT:
5369 case OPERATOR_GE:
5370 {
5371 std::string reason;
5372 if (!Type::are_compatible_for_comparison(false, type, otype, &reason))
5373 {
5374 error_at(location, "%s", reason.c_str());
5375 return false;
5376 }
5377 }
5378 break;
5379
5380 case OPERATOR_PLUS:
5381 case OPERATOR_PLUSEQ:
5382 if (type->integer_type() == NULL
5383 && type->float_type() == NULL
5384 && type->complex_type() == NULL
5385 && !type->is_string_type())
5386 {
5387 error_at(location,
5388 "expected integer, floating, complex, or string type");
5389 return false;
5390 }
5391 break;
5392
5393 case OPERATOR_MINUS:
5394 case OPERATOR_MINUSEQ:
5395 case OPERATOR_MULT:
5396 case OPERATOR_MULTEQ:
5397 case OPERATOR_DIV:
5398 case OPERATOR_DIVEQ:
5399 if (type->integer_type() == NULL
5400 && type->float_type() == NULL
5401 && type->complex_type() == NULL)
5402 {
5403 error_at(location, "expected integer, floating, or complex type");
5404 return false;
5405 }
5406 break;
5407
5408 case OPERATOR_MOD:
5409 case OPERATOR_MODEQ:
5410 case OPERATOR_OR:
5411 case OPERATOR_OREQ:
5412 case OPERATOR_AND:
5413 case OPERATOR_ANDEQ:
5414 case OPERATOR_XOR:
5415 case OPERATOR_XOREQ:
5416 case OPERATOR_BITCLEAR:
5417 case OPERATOR_BITCLEAREQ:
5418 if (type->integer_type() == NULL)
5419 {
5420 error_at(location, "expected integer type");
5421 return false;
5422 }
5423 break;
5424
5425 default:
5426 go_unreachable();
5427 }
5428
5429 return true;
5430 }
5431
5432 // Check types.
5433
5434 void
5435 Binary_expression::do_check_types(Gogo*)
5436 {
5437 if (this->classification() == EXPRESSION_ERROR)
5438 return;
5439
5440 Type* left_type = this->left_->type();
5441 Type* right_type = this->right_->type();
5442 if (left_type->is_error() || right_type->is_error())
5443 {
5444 this->set_is_error();
5445 return;
5446 }
5447
5448 if (this->op_ == OPERATOR_EQEQ
5449 || this->op_ == OPERATOR_NOTEQ
5450 || this->op_ == OPERATOR_LT
5451 || this->op_ == OPERATOR_LE
5452 || this->op_ == OPERATOR_GT
5453 || this->op_ == OPERATOR_GE)
5454 {
5455 if (left_type->is_nil_type() && right_type->is_nil_type())
5456 {
5457 this->report_error(_("invalid comparison of nil with nil"));
5458 return;
5459 }
5460 if (!Type::are_assignable(left_type, right_type, NULL)
5461 && !Type::are_assignable(right_type, left_type, NULL))
5462 {
5463 this->report_error(_("incompatible types in binary expression"));
5464 return;
5465 }
5466 if (!Binary_expression::check_operator_type(this->op_, left_type,
5467 right_type,
5468 this->location())
5469 || !Binary_expression::check_operator_type(this->op_, right_type,
5470 left_type,
5471 this->location()))
5472 {
5473 this->set_is_error();
5474 return;
5475 }
5476 }
5477 else if (this->op_ != OPERATOR_LSHIFT && this->op_ != OPERATOR_RSHIFT)
5478 {
5479 if (!Type::are_compatible_for_binop(left_type, right_type))
5480 {
5481 this->report_error(_("incompatible types in binary expression"));
5482 return;
5483 }
5484 if (!Binary_expression::check_operator_type(this->op_, left_type,
5485 right_type,
5486 this->location()))
5487 {
5488 this->set_is_error();
5489 return;
5490 }
5491 if (this->op_ == OPERATOR_DIV || this->op_ == OPERATOR_MOD)
5492 {
5493 // Division by a zero integer constant is an error.
5494 Numeric_constant rconst;
5495 unsigned long rval;
5496 if (left_type->integer_type() != NULL
5497 && this->right_->numeric_constant_value(&rconst)
5498 && rconst.to_unsigned_long(&rval) == Numeric_constant::NC_UL_VALID
5499 && rval == 0)
5500 {
5501 this->report_error(_("integer division by zero"));
5502 return;
5503 }
5504 }
5505 }
5506 else
5507 {
5508 if (left_type->integer_type() == NULL)
5509 this->report_error(_("shift of non-integer operand"));
5510
5511 if (!right_type->is_abstract()
5512 && (right_type->integer_type() == NULL
5513 || !right_type->integer_type()->is_unsigned()))
5514 this->report_error(_("shift count not unsigned integer"));
5515 else
5516 {
5517 Numeric_constant nc;
5518 if (this->right_->numeric_constant_value(&nc))
5519 {
5520 mpz_t val;
5521 if (!nc.to_int(&val))
5522 this->report_error(_("shift count not unsigned integer"));
5523 else
5524 {
5525 if (mpz_sgn(val) < 0)
5526 {
5527 this->report_error(_("negative shift count"));
5528 Location rloc = this->right_->location();
5529 this->right_ = Expression::make_integer_ul(0, right_type,
5530 rloc);
5531 }
5532 mpz_clear(val);
5533 }
5534 }
5535 }
5536 }
5537 }
5538
5539 // Get the backend representation for a binary expression.
5540
5541 Bexpression*
5542 Binary_expression::do_get_backend(Translate_context* context)
5543 {
5544 Gogo* gogo = context->gogo();
5545 Location loc = this->location();
5546 Type* left_type = this->left_->type();
5547 Type* right_type = this->right_->type();
5548
5549 bool use_left_type = true;
5550 bool is_shift_op = false;
5551 bool is_idiv_op = false;
5552 switch (this->op_)
5553 {
5554 case OPERATOR_EQEQ:
5555 case OPERATOR_NOTEQ:
5556 case OPERATOR_LT:
5557 case OPERATOR_LE:
5558 case OPERATOR_GT:
5559 case OPERATOR_GE:
5560 return Expression::comparison(context, this->type_, this->op_,
5561 this->left_, this->right_, loc);
5562
5563 case OPERATOR_OROR:
5564 case OPERATOR_ANDAND:
5565 use_left_type = false;
5566 break;
5567 case OPERATOR_PLUS:
5568 case OPERATOR_MINUS:
5569 case OPERATOR_OR:
5570 case OPERATOR_XOR:
5571 case OPERATOR_MULT:
5572 break;
5573 case OPERATOR_DIV:
5574 if (left_type->float_type() != NULL || left_type->complex_type() != NULL)
5575 break;
5576 case OPERATOR_MOD:
5577 is_idiv_op = true;
5578 break;
5579 case OPERATOR_LSHIFT:
5580 case OPERATOR_RSHIFT:
5581 is_shift_op = true;
5582 break;
5583 case OPERATOR_BITCLEAR:
5584 this->right_ = Expression::make_unary(OPERATOR_XOR, this->right_, loc);
5585 case OPERATOR_AND:
5586 break;
5587 default:
5588 go_unreachable();
5589 }
5590
5591 if (left_type->is_string_type())
5592 {
5593 go_assert(this->op_ == OPERATOR_PLUS);
5594 Expression* string_plus =
5595 Runtime::make_call(Runtime::STRING_PLUS, loc, 2,
5596 this->left_, this->right_);
5597 return string_plus->get_backend(context);
5598 }
5599
5600 // For complex division Go might want slightly different results than the
5601 // backend implementation provides, so we have our own runtime routine.
5602 if (this->op_ == OPERATOR_DIV && this->left_->type()->complex_type() != NULL)
5603 {
5604 Runtime::Function complex_code;
5605 switch (this->left_->type()->complex_type()->bits())
5606 {
5607 case 64:
5608 complex_code = Runtime::COMPLEX64_DIV;
5609 break;
5610 case 128:
5611 complex_code = Runtime::COMPLEX128_DIV;
5612 break;
5613 default:
5614 go_unreachable();
5615 }
5616 Expression* complex_div =
5617 Runtime::make_call(complex_code, loc, 2, this->left_, this->right_);
5618 return complex_div->get_backend(context);
5619 }
5620
5621 Bexpression* left = this->left_->get_backend(context);
5622 Bexpression* right = this->right_->get_backend(context);
5623
5624 Type* type = use_left_type ? left_type : right_type;
5625 Btype* btype = type->get_backend(gogo);
5626
5627 Bexpression* ret =
5628 gogo->backend()->binary_expression(this->op_, left, right, loc);
5629 ret = gogo->backend()->convert_expression(btype, ret, loc);
5630
5631 // Initialize overflow constants.
5632 Bexpression* overflow;
5633 mpz_t zero;
5634 mpz_init_set_ui(zero, 0UL);
5635 mpz_t one;
5636 mpz_init_set_ui(one, 1UL);
5637 mpz_t neg_one;
5638 mpz_init_set_si(neg_one, -1);
5639
5640 Btype* left_btype = left_type->get_backend(gogo);
5641 Btype* right_btype = right_type->get_backend(gogo);
5642
5643 // In Go, a shift larger than the size of the type is well-defined.
5644 // This is not true in C, so we need to insert a conditional.
5645 if (is_shift_op)
5646 {
5647 go_assert(left_type->integer_type() != NULL);
5648
5649 mpz_t bitsval;
5650 int bits = left_type->integer_type()->bits();
5651 mpz_init_set_ui(bitsval, bits);
5652 Bexpression* bits_expr =
5653 gogo->backend()->integer_constant_expression(right_btype, bitsval);
5654 Bexpression* compare =
5655 gogo->backend()->binary_expression(OPERATOR_LT,
5656 right, bits_expr, loc);
5657
5658 Bexpression* zero_expr =
5659 gogo->backend()->integer_constant_expression(left_btype, zero);
5660 overflow = zero_expr;
5661 if (this->op_ == OPERATOR_RSHIFT
5662 && !left_type->integer_type()->is_unsigned())
5663 {
5664 Bexpression* neg_expr =
5665 gogo->backend()->binary_expression(OPERATOR_LT, left,
5666 zero_expr, loc);
5667 Bexpression* neg_one_expr =
5668 gogo->backend()->integer_constant_expression(left_btype, neg_one);
5669 overflow = gogo->backend()->conditional_expression(btype, neg_expr,
5670 neg_one_expr,
5671 zero_expr, loc);
5672 }
5673 ret = gogo->backend()->conditional_expression(btype, compare, ret,
5674 overflow, loc);
5675 mpz_clear(bitsval);
5676 }
5677
5678 // Add checks for division by zero and division overflow as needed.
5679 if (is_idiv_op)
5680 {
5681 if (gogo->check_divide_by_zero())
5682 {
5683 // right == 0
5684 Bexpression* zero_expr =
5685 gogo->backend()->integer_constant_expression(right_btype, zero);
5686 Bexpression* check =
5687 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5688 right, zero_expr, loc);
5689
5690 // __go_runtime_error(RUNTIME_ERROR_DIVISION_BY_ZERO)
5691 int errcode = RUNTIME_ERROR_DIVISION_BY_ZERO;
5692 Bexpression* crash = gogo->runtime_error(errcode,
5693 loc)->get_backend(context);
5694
5695 // right == 0 ? (__go_runtime_error(...), 0) : ret
5696 ret = gogo->backend()->conditional_expression(btype, check, crash,
5697 ret, loc);
5698 }
5699
5700 if (gogo->check_divide_overflow())
5701 {
5702 // right == -1
5703 // FIXME: It would be nice to say that this test is expected
5704 // to return false.
5705
5706 Bexpression* neg_one_expr =
5707 gogo->backend()->integer_constant_expression(right_btype, neg_one);
5708 Bexpression* check =
5709 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5710 right, neg_one_expr, loc);
5711
5712 Bexpression* zero_expr =
5713 gogo->backend()->integer_constant_expression(btype, zero);
5714 Bexpression* one_expr =
5715 gogo->backend()->integer_constant_expression(btype, one);
5716
5717 if (type->integer_type()->is_unsigned())
5718 {
5719 // An unsigned -1 is the largest possible number, so
5720 // dividing is always 1 or 0.
5721
5722 Bexpression* cmp =
5723 gogo->backend()->binary_expression(OPERATOR_EQEQ,
5724 left, right, loc);
5725 if (this->op_ == OPERATOR_DIV)
5726 overflow =
5727 gogo->backend()->conditional_expression(btype, cmp,
5728 one_expr, zero_expr,
5729 loc);
5730 else
5731 overflow =
5732 gogo->backend()->conditional_expression(btype, cmp,
5733 zero_expr, left,
5734 loc);
5735 }
5736 else
5737 {
5738 // Computing left / -1 is the same as computing - left,
5739 // which does not overflow since Go sets -fwrapv.
5740 if (this->op_ == OPERATOR_DIV)
5741 {
5742 Expression* negate_expr =
5743 Expression::make_unary(OPERATOR_MINUS, this->left_, loc);
5744 overflow = negate_expr->get_backend(context);
5745 }
5746 else
5747 overflow = zero_expr;
5748 }
5749 overflow = gogo->backend()->convert_expression(btype, overflow, loc);
5750
5751 // right == -1 ? - left : ret
5752 ret = gogo->backend()->conditional_expression(btype, check, overflow,
5753 ret, loc);
5754 }
5755 }
5756
5757 mpz_clear(zero);
5758 mpz_clear(one);
5759 mpz_clear(neg_one);
5760 return ret;
5761 }
5762
5763 // Export a binary expression.
5764
5765 void
5766 Binary_expression::do_export(Export* exp) const
5767 {
5768 exp->write_c_string("(");
5769 this->left_->export_expression(exp);
5770 switch (this->op_)
5771 {
5772 case OPERATOR_OROR:
5773 exp->write_c_string(" || ");
5774 break;
5775 case OPERATOR_ANDAND:
5776 exp->write_c_string(" && ");
5777 break;
5778 case OPERATOR_EQEQ:
5779 exp->write_c_string(" == ");
5780 break;
5781 case OPERATOR_NOTEQ:
5782 exp->write_c_string(" != ");
5783 break;
5784 case OPERATOR_LT:
5785 exp->write_c_string(" < ");
5786 break;
5787 case OPERATOR_LE:
5788 exp->write_c_string(" <= ");
5789 break;
5790 case OPERATOR_GT:
5791 exp->write_c_string(" > ");
5792 break;
5793 case OPERATOR_GE:
5794 exp->write_c_string(" >= ");
5795 break;
5796 case OPERATOR_PLUS:
5797 exp->write_c_string(" + ");
5798 break;
5799 case OPERATOR_MINUS:
5800 exp->write_c_string(" - ");
5801 break;
5802 case OPERATOR_OR:
5803 exp->write_c_string(" | ");
5804 break;
5805 case OPERATOR_XOR:
5806 exp->write_c_string(" ^ ");
5807 break;
5808 case OPERATOR_MULT:
5809 exp->write_c_string(" * ");
5810 break;
5811 case OPERATOR_DIV:
5812 exp->write_c_string(" / ");
5813 break;
5814 case OPERATOR_MOD:
5815 exp->write_c_string(" % ");
5816 break;
5817 case OPERATOR_LSHIFT:
5818 exp->write_c_string(" << ");
5819 break;
5820 case OPERATOR_RSHIFT:
5821 exp->write_c_string(" >> ");
5822 break;
5823 case OPERATOR_AND:
5824 exp->write_c_string(" & ");
5825 break;
5826 case OPERATOR_BITCLEAR:
5827 exp->write_c_string(" &^ ");
5828 break;
5829 default:
5830 go_unreachable();
5831 }
5832 this->right_->export_expression(exp);
5833 exp->write_c_string(")");
5834 }
5835
5836 // Import a binary expression.
5837
5838 Expression*
5839 Binary_expression::do_import(Import* imp)
5840 {
5841 imp->require_c_string("(");
5842
5843 Expression* left = Expression::import_expression(imp);
5844
5845 Operator op;
5846 if (imp->match_c_string(" || "))
5847 {
5848 op = OPERATOR_OROR;
5849 imp->advance(4);
5850 }
5851 else if (imp->match_c_string(" && "))
5852 {
5853 op = OPERATOR_ANDAND;
5854 imp->advance(4);
5855 }
5856 else if (imp->match_c_string(" == "))
5857 {
5858 op = OPERATOR_EQEQ;
5859 imp->advance(4);
5860 }
5861 else if (imp->match_c_string(" != "))
5862 {
5863 op = OPERATOR_NOTEQ;
5864 imp->advance(4);
5865 }
5866 else if (imp->match_c_string(" < "))
5867 {
5868 op = OPERATOR_LT;
5869 imp->advance(3);
5870 }
5871 else if (imp->match_c_string(" <= "))
5872 {
5873 op = OPERATOR_LE;
5874 imp->advance(4);
5875 }
5876 else if (imp->match_c_string(" > "))
5877 {
5878 op = OPERATOR_GT;
5879 imp->advance(3);
5880 }
5881 else if (imp->match_c_string(" >= "))
5882 {
5883 op = OPERATOR_GE;
5884 imp->advance(4);
5885 }
5886 else if (imp->match_c_string(" + "))
5887 {
5888 op = OPERATOR_PLUS;
5889 imp->advance(3);
5890 }
5891 else if (imp->match_c_string(" - "))
5892 {
5893 op = OPERATOR_MINUS;
5894 imp->advance(3);
5895 }
5896 else if (imp->match_c_string(" | "))
5897 {
5898 op = OPERATOR_OR;
5899 imp->advance(3);
5900 }
5901 else if (imp->match_c_string(" ^ "))
5902 {
5903 op = OPERATOR_XOR;
5904 imp->advance(3);
5905 }
5906 else if (imp->match_c_string(" * "))
5907 {
5908 op = OPERATOR_MULT;
5909 imp->advance(3);
5910 }
5911 else if (imp->match_c_string(" / "))
5912 {
5913 op = OPERATOR_DIV;
5914 imp->advance(3);
5915 }
5916 else if (imp->match_c_string(" % "))
5917 {
5918 op = OPERATOR_MOD;
5919 imp->advance(3);
5920 }
5921 else if (imp->match_c_string(" << "))
5922 {
5923 op = OPERATOR_LSHIFT;
5924 imp->advance(4);
5925 }
5926 else if (imp->match_c_string(" >> "))
5927 {
5928 op = OPERATOR_RSHIFT;
5929 imp->advance(4);
5930 }
5931 else if (imp->match_c_string(" & "))
5932 {
5933 op = OPERATOR_AND;
5934 imp->advance(3);
5935 }
5936 else if (imp->match_c_string(" &^ "))
5937 {
5938 op = OPERATOR_BITCLEAR;
5939 imp->advance(4);
5940 }
5941 else
5942 {
5943 error_at(imp->location(), "unrecognized binary operator");
5944 return Expression::make_error(imp->location());
5945 }
5946
5947 Expression* right = Expression::import_expression(imp);
5948
5949 imp->require_c_string(")");
5950
5951 return Expression::make_binary(op, left, right, imp->location());
5952 }
5953
5954 // Dump ast representation of a binary expression.
5955
5956 void
5957 Binary_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
5958 {
5959 ast_dump_context->ostream() << "(";
5960 ast_dump_context->dump_expression(this->left_);
5961 ast_dump_context->ostream() << " ";
5962 ast_dump_context->dump_operator(this->op_);
5963 ast_dump_context->ostream() << " ";
5964 ast_dump_context->dump_expression(this->right_);
5965 ast_dump_context->ostream() << ") ";
5966 }
5967
5968 // Make a binary expression.
5969
5970 Expression*
5971 Expression::make_binary(Operator op, Expression* left, Expression* right,
5972 Location location)
5973 {
5974 return new Binary_expression(op, left, right, location);
5975 }
5976
5977 // Implement a comparison.
5978
5979 Bexpression*
5980 Expression::comparison(Translate_context* context, Type* result_type,
5981 Operator op, Expression* left, Expression* right,
5982 Location location)
5983 {
5984 Type* left_type = left->type();
5985 Type* right_type = right->type();
5986
5987 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
5988
5989 if (left_type->is_string_type() && right_type->is_string_type())
5990 {
5991 left = Runtime::make_call(Runtime::STRCMP, location, 2,
5992 left, right);
5993 right = zexpr;
5994 }
5995 else if ((left_type->interface_type() != NULL
5996 && right_type->interface_type() == NULL
5997 && !right_type->is_nil_type())
5998 || (left_type->interface_type() == NULL
5999 && !left_type->is_nil_type()
6000 && right_type->interface_type() != NULL))
6001 {
6002 // Comparing an interface value to a non-interface value.
6003 if (left_type->interface_type() == NULL)
6004 {
6005 std::swap(left_type, right_type);
6006 std::swap(left, right);
6007 }
6008
6009 // The right operand is not an interface. We need to take its
6010 // address if it is not a pointer.
6011 Expression* pointer_arg = NULL;
6012 if (right_type->points_to() != NULL)
6013 pointer_arg = right;
6014 else
6015 {
6016 go_assert(right->is_addressable());
6017 pointer_arg = Expression::make_unary(OPERATOR_AND, right,
6018 location);
6019 }
6020
6021 Expression* descriptor =
6022 Expression::make_type_descriptor(right_type, location);
6023 left =
6024 Runtime::make_call((left_type->interface_type()->is_empty()
6025 ? Runtime::EMPTY_INTERFACE_VALUE_COMPARE
6026 : Runtime::INTERFACE_VALUE_COMPARE),
6027 location, 3, left, descriptor,
6028 pointer_arg);
6029 right = zexpr;
6030 }
6031 else if (left_type->interface_type() != NULL
6032 && right_type->interface_type() != NULL)
6033 {
6034 Runtime::Function compare_function;
6035 if (left_type->interface_type()->is_empty()
6036 && right_type->interface_type()->is_empty())
6037 compare_function = Runtime::EMPTY_INTERFACE_COMPARE;
6038 else if (!left_type->interface_type()->is_empty()
6039 && !right_type->interface_type()->is_empty())
6040 compare_function = Runtime::INTERFACE_COMPARE;
6041 else
6042 {
6043 if (left_type->interface_type()->is_empty())
6044 {
6045 go_assert(op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ);
6046 std::swap(left_type, right_type);
6047 std::swap(left, right);
6048 }
6049 go_assert(!left_type->interface_type()->is_empty());
6050 go_assert(right_type->interface_type()->is_empty());
6051 compare_function = Runtime::INTERFACE_EMPTY_COMPARE;
6052 }
6053
6054 left = Runtime::make_call(compare_function, location, 2, left, right);
6055 right = zexpr;
6056 }
6057
6058 if (left_type->is_nil_type()
6059 && (op == OPERATOR_EQEQ || op == OPERATOR_NOTEQ))
6060 {
6061 std::swap(left_type, right_type);
6062 std::swap(left, right);
6063 }
6064
6065 if (right_type->is_nil_type())
6066 {
6067 right = Expression::make_nil(location);
6068 if (left_type->array_type() != NULL
6069 && left_type->array_type()->length() == NULL)
6070 {
6071 Array_type* at = left_type->array_type();
6072 left = at->get_value_pointer(context->gogo(), left);
6073 }
6074 else if (left_type->interface_type() != NULL)
6075 {
6076 // An interface is nil if the first field is nil.
6077 left = Expression::make_field_reference(left, 0, location);
6078 }
6079 }
6080
6081 Bexpression* left_bexpr = left->get_backend(context);
6082 Bexpression* right_bexpr = right->get_backend(context);
6083
6084 Gogo* gogo = context->gogo();
6085 Bexpression* ret = gogo->backend()->binary_expression(op, left_bexpr,
6086 right_bexpr, location);
6087 if (result_type != NULL)
6088 ret = gogo->backend()->convert_expression(result_type->get_backend(gogo),
6089 ret, location);
6090 return ret;
6091 }
6092
6093 // Class Bound_method_expression.
6094
6095 // Traversal.
6096
6097 int
6098 Bound_method_expression::do_traverse(Traverse* traverse)
6099 {
6100 return Expression::traverse(&this->expr_, traverse);
6101 }
6102
6103 // Lower the expression. If this is a method value rather than being
6104 // called, and the method is accessed via a pointer, we may need to
6105 // add nil checks. Introduce a temporary variable so that those nil
6106 // checks do not cause multiple evaluation.
6107
6108 Expression*
6109 Bound_method_expression::do_lower(Gogo*, Named_object*,
6110 Statement_inserter* inserter, int)
6111 {
6112 // For simplicity we use a temporary for every call to an embedded
6113 // method, even though some of them might be pure value methods and
6114 // not require a temporary.
6115 if (this->expr_->var_expression() == NULL
6116 && this->expr_->temporary_reference_expression() == NULL
6117 && this->expr_->set_and_use_temporary_expression() == NULL
6118 && (this->method_->field_indexes() != NULL
6119 || (this->method_->is_value_method()
6120 && this->expr_->type()->points_to() != NULL)))
6121 {
6122 Temporary_statement* temp =
6123 Statement::make_temporary(this->expr_->type(), NULL, this->location());
6124 inserter->insert(temp);
6125 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
6126 this->location());
6127 }
6128 return this;
6129 }
6130
6131 // Return the type of a bound method expression. The type of this
6132 // object is simply the type of the method with no receiver.
6133
6134 Type*
6135 Bound_method_expression::do_type()
6136 {
6137 Named_object* fn = this->method_->named_object();
6138 Function_type* fntype;
6139 if (fn->is_function())
6140 fntype = fn->func_value()->type();
6141 else if (fn->is_function_declaration())
6142 fntype = fn->func_declaration_value()->type();
6143 else
6144 return Type::make_error_type();
6145 return fntype->copy_without_receiver();
6146 }
6147
6148 // Determine the types of a method expression.
6149
6150 void
6151 Bound_method_expression::do_determine_type(const Type_context*)
6152 {
6153 Named_object* fn = this->method_->named_object();
6154 Function_type* fntype;
6155 if (fn->is_function())
6156 fntype = fn->func_value()->type();
6157 else if (fn->is_function_declaration())
6158 fntype = fn->func_declaration_value()->type();
6159 else
6160 fntype = NULL;
6161 if (fntype == NULL || !fntype->is_method())
6162 this->expr_->determine_type_no_context();
6163 else
6164 {
6165 Type_context subcontext(fntype->receiver()->type(), false);
6166 this->expr_->determine_type(&subcontext);
6167 }
6168 }
6169
6170 // Check the types of a method expression.
6171
6172 void
6173 Bound_method_expression::do_check_types(Gogo*)
6174 {
6175 Named_object* fn = this->method_->named_object();
6176 if (!fn->is_function() && !fn->is_function_declaration())
6177 {
6178 this->report_error(_("object is not a method"));
6179 return;
6180 }
6181
6182 Function_type* fntype;
6183 if (fn->is_function())
6184 fntype = fn->func_value()->type();
6185 else if (fn->is_function_declaration())
6186 fntype = fn->func_declaration_value()->type();
6187 else
6188 go_unreachable();
6189 Type* rtype = fntype->receiver()->type()->deref();
6190 Type* etype = (this->expr_type_ != NULL
6191 ? this->expr_type_
6192 : this->expr_->type());
6193 etype = etype->deref();
6194 if (!Type::are_identical(rtype, etype, true, NULL))
6195 this->report_error(_("method type does not match object type"));
6196 }
6197
6198 // If a bound method expression is not simply called, then it is
6199 // represented as a closure. The closure will hold a single variable,
6200 // the receiver to pass to the method. The function will be a simple
6201 // thunk that pulls that value from the closure and calls the method
6202 // with the remaining arguments.
6203 //
6204 // Because method values are not common, we don't build all thunks for
6205 // every methods, but instead only build them as we need them. In
6206 // particular, we even build them on demand for methods defined in
6207 // other packages.
6208
6209 Bound_method_expression::Method_value_thunks
6210 Bound_method_expression::method_value_thunks;
6211
6212 // Find or create the thunk for METHOD.
6213
6214 Named_object*
6215 Bound_method_expression::create_thunk(Gogo* gogo, const Method* method,
6216 Named_object* fn)
6217 {
6218 std::pair<Named_object*, Named_object*> val(fn, NULL);
6219 std::pair<Method_value_thunks::iterator, bool> ins =
6220 Bound_method_expression::method_value_thunks.insert(val);
6221 if (!ins.second)
6222 {
6223 // We have seen this method before.
6224 go_assert(ins.first->second != NULL);
6225 return ins.first->second;
6226 }
6227
6228 Location loc = fn->location();
6229
6230 Function_type* orig_fntype;
6231 if (fn->is_function())
6232 orig_fntype = fn->func_value()->type();
6233 else if (fn->is_function_declaration())
6234 orig_fntype = fn->func_declaration_value()->type();
6235 else
6236 orig_fntype = NULL;
6237
6238 if (orig_fntype == NULL || !orig_fntype->is_method())
6239 {
6240 ins.first->second = Named_object::make_erroneous_name(Gogo::thunk_name());
6241 return ins.first->second;
6242 }
6243
6244 Struct_field_list* sfl = new Struct_field_list();
6245 // The type here is wrong--it should be the C function type. But it
6246 // doesn't really matter.
6247 Type* vt = Type::make_pointer_type(Type::make_void_type());
6248 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
6249 sfl->push_back(Struct_field(Typed_identifier("val.1",
6250 orig_fntype->receiver()->type(),
6251 loc)));
6252 Type* closure_type = Type::make_struct_type(sfl, loc);
6253 closure_type = Type::make_pointer_type(closure_type);
6254
6255 Function_type* new_fntype = orig_fntype->copy_with_names();
6256
6257 std::string thunk_name = Gogo::thunk_name();
6258 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
6259 false, loc);
6260
6261 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
6262 cvar->set_is_used();
6263 cvar->set_is_closure();
6264 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
6265 NULL, cvar);
6266 new_no->func_value()->set_closure_var(cp);
6267
6268 gogo->start_block(loc);
6269
6270 // Field 0 of the closure is the function code pointer, field 1 is
6271 // the value on which to invoke the method.
6272 Expression* arg = Expression::make_var_reference(cp, loc);
6273 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
6274 arg = Expression::make_field_reference(arg, 1, loc);
6275
6276 Expression* bme = Expression::make_bound_method(arg, method, fn, loc);
6277
6278 const Typed_identifier_list* orig_params = orig_fntype->parameters();
6279 Expression_list* args;
6280 if (orig_params == NULL || orig_params->empty())
6281 args = NULL;
6282 else
6283 {
6284 const Typed_identifier_list* new_params = new_fntype->parameters();
6285 args = new Expression_list();
6286 for (Typed_identifier_list::const_iterator p = new_params->begin();
6287 p != new_params->end();
6288 ++p)
6289 {
6290 Named_object* p_no = gogo->lookup(p->name(), NULL);
6291 go_assert(p_no != NULL
6292 && p_no->is_variable()
6293 && p_no->var_value()->is_parameter());
6294 args->push_back(Expression::make_var_reference(p_no, loc));
6295 }
6296 }
6297
6298 Call_expression* call = Expression::make_call(bme, args,
6299 orig_fntype->is_varargs(),
6300 loc);
6301 call->set_varargs_are_lowered();
6302
6303 Statement* s = Statement::make_return_from_call(call, loc);
6304 gogo->add_statement(s);
6305 Block* b = gogo->finish_block(loc);
6306 gogo->add_block(b, loc);
6307 gogo->lower_block(new_no, b);
6308 gogo->flatten_block(new_no, b);
6309 gogo->finish_function(loc);
6310
6311 ins.first->second = new_no;
6312 return new_no;
6313 }
6314
6315 // Return an expression to check *REF for nil while dereferencing
6316 // according to FIELD_INDEXES. Update *REF to build up the field
6317 // reference. This is a static function so that we don't have to
6318 // worry about declaring Field_indexes in expressions.h.
6319
6320 static Expression*
6321 bme_check_nil(const Method::Field_indexes* field_indexes, Location loc,
6322 Expression** ref)
6323 {
6324 if (field_indexes == NULL)
6325 return Expression::make_boolean(false, loc);
6326 Expression* cond = bme_check_nil(field_indexes->next, loc, ref);
6327 Struct_type* stype = (*ref)->type()->deref()->struct_type();
6328 go_assert(stype != NULL
6329 && field_indexes->field_index < stype->field_count());
6330 if ((*ref)->type()->struct_type() == NULL)
6331 {
6332 go_assert((*ref)->type()->points_to() != NULL);
6333 Expression* n = Expression::make_binary(OPERATOR_EQEQ, *ref,
6334 Expression::make_nil(loc),
6335 loc);
6336 cond = Expression::make_binary(OPERATOR_OROR, cond, n, loc);
6337 *ref = Expression::make_unary(OPERATOR_MULT, *ref, loc);
6338 go_assert((*ref)->type()->struct_type() == stype);
6339 }
6340 *ref = Expression::make_field_reference(*ref, field_indexes->field_index,
6341 loc);
6342 return cond;
6343 }
6344
6345 // Get the backend representation for a method value.
6346
6347 Bexpression*
6348 Bound_method_expression::do_get_backend(Translate_context* context)
6349 {
6350 Named_object* thunk = Bound_method_expression::create_thunk(context->gogo(),
6351 this->method_,
6352 this->function_);
6353 if (thunk->is_erroneous())
6354 {
6355 go_assert(saw_errors());
6356 return context->backend()->error_expression();
6357 }
6358
6359 // FIXME: We should lower this earlier, but we can't lower it in the
6360 // lowering pass because at that point we don't know whether we need
6361 // to create the thunk or not. If the expression is called, we
6362 // don't need the thunk.
6363
6364 Location loc = this->location();
6365
6366 // If the method expects a value, and we have a pointer, we need to
6367 // dereference the pointer.
6368
6369 Named_object* fn = this->method_->named_object();
6370 Function_type* fntype;
6371 if (fn->is_function())
6372 fntype = fn->func_value()->type();
6373 else if (fn->is_function_declaration())
6374 fntype = fn->func_declaration_value()->type();
6375 else
6376 go_unreachable();
6377
6378 Expression* val = this->expr_;
6379 if (fntype->receiver()->type()->points_to() == NULL
6380 && val->type()->points_to() != NULL)
6381 val = Expression::make_unary(OPERATOR_MULT, val, loc);
6382
6383 // Note that we are ignoring this->expr_type_ here. The thunk will
6384 // expect a closure whose second field has type this->expr_type_ (if
6385 // that is not NULL). We are going to pass it a closure whose
6386 // second field has type this->expr_->type(). Since
6387 // this->expr_type_ is only not-NULL for pointer types, we can get
6388 // away with this.
6389
6390 Struct_field_list* fields = new Struct_field_list();
6391 fields->push_back(Struct_field(Typed_identifier("fn.0",
6392 thunk->func_value()->type(),
6393 loc)));
6394 fields->push_back(Struct_field(Typed_identifier("val.1", val->type(), loc)));
6395 Struct_type* st = Type::make_struct_type(fields, loc);
6396
6397 Expression_list* vals = new Expression_list();
6398 vals->push_back(Expression::make_func_code_reference(thunk, loc));
6399 vals->push_back(val);
6400
6401 Expression* ret = Expression::make_struct_composite_literal(st, vals, loc);
6402 ret = Expression::make_heap_expression(ret, loc);
6403
6404 // See whether the expression or any embedded pointers are nil.
6405
6406 Expression* nil_check = NULL;
6407 Expression* expr = this->expr_;
6408 if (this->method_->field_indexes() != NULL)
6409 {
6410 // Note that we are evaluating this->expr_ twice, but that is OK
6411 // because in the lowering pass we forced it into a temporary
6412 // variable.
6413 Expression* ref = expr;
6414 nil_check = bme_check_nil(this->method_->field_indexes(), loc, &ref);
6415 expr = ref;
6416 }
6417
6418 if (this->method_->is_value_method() && expr->type()->points_to() != NULL)
6419 {
6420 Expression* n = Expression::make_binary(OPERATOR_EQEQ, expr,
6421 Expression::make_nil(loc),
6422 loc);
6423 if (nil_check == NULL)
6424 nil_check = n;
6425 else
6426 nil_check = Expression::make_binary(OPERATOR_OROR, nil_check, n, loc);
6427 }
6428
6429 Bexpression* bme = ret->get_backend(context);
6430 if (nil_check != NULL)
6431 {
6432 Gogo* gogo = context->gogo();
6433 Bexpression* crash =
6434 gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
6435 loc)->get_backend(context);
6436 Btype* btype = ret->type()->get_backend(gogo);
6437 Bexpression* bcheck = nil_check->get_backend(context);
6438 bme = gogo->backend()->conditional_expression(btype, bcheck, crash,
6439 bme, loc);
6440 }
6441 return bme;
6442 }
6443
6444 // Dump ast representation of a bound method expression.
6445
6446 void
6447 Bound_method_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
6448 const
6449 {
6450 if (this->expr_type_ != NULL)
6451 ast_dump_context->ostream() << "(";
6452 ast_dump_context->dump_expression(this->expr_);
6453 if (this->expr_type_ != NULL)
6454 {
6455 ast_dump_context->ostream() << ":";
6456 ast_dump_context->dump_type(this->expr_type_);
6457 ast_dump_context->ostream() << ")";
6458 }
6459
6460 ast_dump_context->ostream() << "." << this->function_->name();
6461 }
6462
6463 // Make a method expression.
6464
6465 Bound_method_expression*
6466 Expression::make_bound_method(Expression* expr, const Method* method,
6467 Named_object* function, Location location)
6468 {
6469 return new Bound_method_expression(expr, method, function, location);
6470 }
6471
6472 // Class Builtin_call_expression. This is used for a call to a
6473 // builtin function.
6474
6475 class Builtin_call_expression : public Call_expression
6476 {
6477 public:
6478 Builtin_call_expression(Gogo* gogo, Expression* fn, Expression_list* args,
6479 bool is_varargs, Location location);
6480
6481 protected:
6482 // This overrides Call_expression::do_lower.
6483 Expression*
6484 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
6485
6486 Expression*
6487 do_flatten(Gogo*, Named_object*, Statement_inserter*);
6488
6489 bool
6490 do_is_constant() const;
6491
6492 bool
6493 do_numeric_constant_value(Numeric_constant*) const;
6494
6495 bool
6496 do_discarding_value();
6497
6498 Type*
6499 do_type();
6500
6501 void
6502 do_determine_type(const Type_context*);
6503
6504 void
6505 do_check_types(Gogo*);
6506
6507 Expression*
6508 do_copy();
6509
6510 Bexpression*
6511 do_get_backend(Translate_context*);
6512
6513 void
6514 do_export(Export*) const;
6515
6516 virtual bool
6517 do_is_recover_call() const;
6518
6519 virtual void
6520 do_set_recover_arg(Expression*);
6521
6522 private:
6523 // The builtin functions.
6524 enum Builtin_function_code
6525 {
6526 BUILTIN_INVALID,
6527
6528 // Predeclared builtin functions.
6529 BUILTIN_APPEND,
6530 BUILTIN_CAP,
6531 BUILTIN_CLOSE,
6532 BUILTIN_COMPLEX,
6533 BUILTIN_COPY,
6534 BUILTIN_DELETE,
6535 BUILTIN_IMAG,
6536 BUILTIN_LEN,
6537 BUILTIN_MAKE,
6538 BUILTIN_NEW,
6539 BUILTIN_PANIC,
6540 BUILTIN_PRINT,
6541 BUILTIN_PRINTLN,
6542 BUILTIN_REAL,
6543 BUILTIN_RECOVER,
6544
6545 // Builtin functions from the unsafe package.
6546 BUILTIN_ALIGNOF,
6547 BUILTIN_OFFSETOF,
6548 BUILTIN_SIZEOF
6549 };
6550
6551 Expression*
6552 one_arg() const;
6553
6554 bool
6555 check_one_arg();
6556
6557 static Type*
6558 real_imag_type(Type*);
6559
6560 static Type*
6561 complex_type(Type*);
6562
6563 Expression*
6564 lower_make();
6565
6566 bool
6567 check_int_value(Expression*, bool is_length);
6568
6569 // A pointer back to the general IR structure. This avoids a global
6570 // variable, or passing it around everywhere.
6571 Gogo* gogo_;
6572 // The builtin function being called.
6573 Builtin_function_code code_;
6574 // Used to stop endless loops when the length of an array uses len
6575 // or cap of the array itself.
6576 mutable bool seen_;
6577 // Whether the argument is set for calls to BUILTIN_RECOVER.
6578 bool recover_arg_is_set_;
6579 };
6580
6581 Builtin_call_expression::Builtin_call_expression(Gogo* gogo,
6582 Expression* fn,
6583 Expression_list* args,
6584 bool is_varargs,
6585 Location location)
6586 : Call_expression(fn, args, is_varargs, location),
6587 gogo_(gogo), code_(BUILTIN_INVALID), seen_(false),
6588 recover_arg_is_set_(false)
6589 {
6590 Func_expression* fnexp = this->fn()->func_expression();
6591 go_assert(fnexp != NULL);
6592 const std::string& name(fnexp->named_object()->name());
6593 if (name == "append")
6594 this->code_ = BUILTIN_APPEND;
6595 else if (name == "cap")
6596 this->code_ = BUILTIN_CAP;
6597 else if (name == "close")
6598 this->code_ = BUILTIN_CLOSE;
6599 else if (name == "complex")
6600 this->code_ = BUILTIN_COMPLEX;
6601 else if (name == "copy")
6602 this->code_ = BUILTIN_COPY;
6603 else if (name == "delete")
6604 this->code_ = BUILTIN_DELETE;
6605 else if (name == "imag")
6606 this->code_ = BUILTIN_IMAG;
6607 else if (name == "len")
6608 this->code_ = BUILTIN_LEN;
6609 else if (name == "make")
6610 this->code_ = BUILTIN_MAKE;
6611 else if (name == "new")
6612 this->code_ = BUILTIN_NEW;
6613 else if (name == "panic")
6614 this->code_ = BUILTIN_PANIC;
6615 else if (name == "print")
6616 this->code_ = BUILTIN_PRINT;
6617 else if (name == "println")
6618 this->code_ = BUILTIN_PRINTLN;
6619 else if (name == "real")
6620 this->code_ = BUILTIN_REAL;
6621 else if (name == "recover")
6622 this->code_ = BUILTIN_RECOVER;
6623 else if (name == "Alignof")
6624 this->code_ = BUILTIN_ALIGNOF;
6625 else if (name == "Offsetof")
6626 this->code_ = BUILTIN_OFFSETOF;
6627 else if (name == "Sizeof")
6628 this->code_ = BUILTIN_SIZEOF;
6629 else
6630 go_unreachable();
6631 }
6632
6633 // Return whether this is a call to recover. This is a virtual
6634 // function called from the parent class.
6635
6636 bool
6637 Builtin_call_expression::do_is_recover_call() const
6638 {
6639 if (this->classification() == EXPRESSION_ERROR)
6640 return false;
6641 return this->code_ == BUILTIN_RECOVER;
6642 }
6643
6644 // Set the argument for a call to recover.
6645
6646 void
6647 Builtin_call_expression::do_set_recover_arg(Expression* arg)
6648 {
6649 const Expression_list* args = this->args();
6650 go_assert(args == NULL || args->empty());
6651 Expression_list* new_args = new Expression_list();
6652 new_args->push_back(arg);
6653 this->set_args(new_args);
6654 this->recover_arg_is_set_ = true;
6655 }
6656
6657 // Lower a builtin call expression. This turns new and make into
6658 // specific expressions. We also convert to a constant if we can.
6659
6660 Expression*
6661 Builtin_call_expression::do_lower(Gogo* gogo, Named_object* function,
6662 Statement_inserter* inserter, int)
6663 {
6664 if (this->classification() == EXPRESSION_ERROR)
6665 return this;
6666
6667 Location loc = this->location();
6668
6669 if (this->is_varargs() && this->code_ != BUILTIN_APPEND)
6670 {
6671 this->report_error(_("invalid use of %<...%> with builtin function"));
6672 return Expression::make_error(loc);
6673 }
6674
6675 if (this->code_ == BUILTIN_OFFSETOF)
6676 {
6677 Expression* arg = this->one_arg();
6678
6679 if (arg->bound_method_expression() != NULL
6680 || arg->interface_field_reference_expression() != NULL)
6681 {
6682 this->report_error(_("invalid use of method value as argument "
6683 "of Offsetof"));
6684 return this;
6685 }
6686
6687 Field_reference_expression* farg = arg->field_reference_expression();
6688 while (farg != NULL)
6689 {
6690 if (!farg->implicit())
6691 break;
6692 // When the selector refers to an embedded field,
6693 // it must not be reached through pointer indirections.
6694 if (farg->expr()->deref() != farg->expr())
6695 {
6696 this->report_error(_("argument of Offsetof implies "
6697 "indirection of an embedded field"));
6698 return this;
6699 }
6700 // Go up until we reach the original base.
6701 farg = farg->expr()->field_reference_expression();
6702 }
6703 }
6704
6705 if (this->is_constant())
6706 {
6707 Numeric_constant nc;
6708 if (this->numeric_constant_value(&nc))
6709 return nc.expression(loc);
6710 }
6711
6712 switch (this->code_)
6713 {
6714 default:
6715 break;
6716
6717 case BUILTIN_NEW:
6718 {
6719 const Expression_list* args = this->args();
6720 if (args == NULL || args->size() < 1)
6721 this->report_error(_("not enough arguments"));
6722 else if (args->size() > 1)
6723 this->report_error(_("too many arguments"));
6724 else
6725 {
6726 Expression* arg = args->front();
6727 if (!arg->is_type_expression())
6728 {
6729 error_at(arg->location(), "expected type");
6730 this->set_is_error();
6731 }
6732 else
6733 return Expression::make_allocation(arg->type(), loc);
6734 }
6735 }
6736 break;
6737
6738 case BUILTIN_MAKE:
6739 return this->lower_make();
6740
6741 case BUILTIN_RECOVER:
6742 if (function != NULL)
6743 function->func_value()->set_calls_recover();
6744 else
6745 {
6746 // Calling recover outside of a function always returns the
6747 // nil empty interface.
6748 Type* eface = Type::make_empty_interface_type(loc);
6749 return Expression::make_cast(eface, Expression::make_nil(loc), loc);
6750 }
6751 break;
6752
6753 case BUILTIN_APPEND:
6754 {
6755 // Lower the varargs.
6756 const Expression_list* args = this->args();
6757 if (args == NULL || args->empty())
6758 return this;
6759 Type* slice_type = args->front()->type();
6760 if (!slice_type->is_slice_type())
6761 {
6762 if (slice_type->is_nil_type())
6763 error_at(args->front()->location(), "use of untyped nil");
6764 else
6765 error_at(args->front()->location(),
6766 "argument 1 must be a slice");
6767 this->set_is_error();
6768 return this;
6769 }
6770 Type* element_type = slice_type->array_type()->element_type();
6771 this->lower_varargs(gogo, function, inserter,
6772 Type::make_array_type(element_type, NULL),
6773 2);
6774 }
6775 break;
6776
6777 case BUILTIN_DELETE:
6778 {
6779 // Lower to a runtime function call.
6780 const Expression_list* args = this->args();
6781 if (args == NULL || args->size() < 2)
6782 this->report_error(_("not enough arguments"));
6783 else if (args->size() > 2)
6784 this->report_error(_("too many arguments"));
6785 else if (args->front()->type()->map_type() == NULL)
6786 this->report_error(_("argument 1 must be a map"));
6787 else
6788 {
6789 // Since this function returns no value it must appear in
6790 // a statement by itself, so we don't have to worry about
6791 // order of evaluation of values around it. Evaluate the
6792 // map first to get order of evaluation right.
6793 Map_type* mt = args->front()->type()->map_type();
6794 Temporary_statement* map_temp =
6795 Statement::make_temporary(mt, args->front(), loc);
6796 inserter->insert(map_temp);
6797
6798 Temporary_statement* key_temp =
6799 Statement::make_temporary(mt->key_type(), args->back(), loc);
6800 inserter->insert(key_temp);
6801
6802 Expression* e1 = Expression::make_temporary_reference(map_temp,
6803 loc);
6804 Expression* e2 = Expression::make_temporary_reference(key_temp,
6805 loc);
6806 e2 = Expression::make_unary(OPERATOR_AND, e2, loc);
6807 return Runtime::make_call(Runtime::MAPDELETE, this->location(),
6808 2, e1, e2);
6809 }
6810 }
6811 break;
6812 }
6813
6814 return this;
6815 }
6816
6817 // Flatten a builtin call expression. This turns the arguments of copy and
6818 // append into temporary expressions.
6819
6820 Expression*
6821 Builtin_call_expression::do_flatten(Gogo*, Named_object*,
6822 Statement_inserter* inserter)
6823 {
6824 Location loc = this->location();
6825 if (this->is_erroneous_call())
6826 {
6827 go_assert(saw_errors());
6828 return Expression::make_error(loc);
6829 }
6830
6831 switch (this->code_)
6832 {
6833 default:
6834 break;
6835
6836 case BUILTIN_APPEND:
6837 case BUILTIN_COPY:
6838 {
6839 Type* at = this->args()->front()->type();
6840 for (Expression_list::iterator pa = this->args()->begin();
6841 pa != this->args()->end();
6842 ++pa)
6843 {
6844 if ((*pa)->is_nil_expression())
6845 {
6846 Expression* nil = Expression::make_nil(loc);
6847 Expression* zero = Expression::make_integer_ul(0, NULL, loc);
6848 *pa = Expression::make_slice_value(at, nil, zero, zero, loc);
6849 }
6850 if (!(*pa)->is_variable())
6851 {
6852 Temporary_statement* temp =
6853 Statement::make_temporary(NULL, *pa, loc);
6854 inserter->insert(temp);
6855 *pa = Expression::make_temporary_reference(temp, loc);
6856 }
6857 }
6858 }
6859 break;
6860
6861 case BUILTIN_PANIC:
6862 for (Expression_list::iterator pa = this->args()->begin();
6863 pa != this->args()->end();
6864 ++pa)
6865 {
6866 if (!(*pa)->is_variable() && (*pa)->type()->interface_type() != NULL)
6867 {
6868 Temporary_statement* temp =
6869 Statement::make_temporary(NULL, *pa, loc);
6870 inserter->insert(temp);
6871 *pa = Expression::make_temporary_reference(temp, loc);
6872 }
6873 }
6874 }
6875
6876 return this;
6877 }
6878
6879 // Lower a make expression.
6880
6881 Expression*
6882 Builtin_call_expression::lower_make()
6883 {
6884 Location loc = this->location();
6885
6886 const Expression_list* args = this->args();
6887 if (args == NULL || args->size() < 1)
6888 {
6889 this->report_error(_("not enough arguments"));
6890 return Expression::make_error(this->location());
6891 }
6892
6893 Expression_list::const_iterator parg = args->begin();
6894
6895 Expression* first_arg = *parg;
6896 if (!first_arg->is_type_expression())
6897 {
6898 error_at(first_arg->location(), "expected type");
6899 this->set_is_error();
6900 return Expression::make_error(this->location());
6901 }
6902 Type* type = first_arg->type();
6903
6904 bool is_slice = false;
6905 bool is_map = false;
6906 bool is_chan = false;
6907 if (type->is_slice_type())
6908 is_slice = true;
6909 else if (type->map_type() != NULL)
6910 is_map = true;
6911 else if (type->channel_type() != NULL)
6912 is_chan = true;
6913 else
6914 {
6915 this->report_error(_("invalid type for make function"));
6916 return Expression::make_error(this->location());
6917 }
6918
6919 bool have_big_args = false;
6920 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6921 int uintptr_bits = uintptr_type->integer_type()->bits();
6922
6923 Type_context int_context(Type::lookup_integer_type("int"), false);
6924
6925 ++parg;
6926 Expression* len_arg;
6927 if (parg == args->end())
6928 {
6929 if (is_slice)
6930 {
6931 this->report_error(_("length required when allocating a slice"));
6932 return Expression::make_error(this->location());
6933 }
6934 len_arg = Expression::make_integer_ul(0, NULL, loc);
6935 }
6936 else
6937 {
6938 len_arg = *parg;
6939 len_arg->determine_type(&int_context);
6940 if (!this->check_int_value(len_arg, true))
6941 return Expression::make_error(this->location());
6942 if (len_arg->type()->integer_type() != NULL
6943 && len_arg->type()->integer_type()->bits() > uintptr_bits)
6944 have_big_args = true;
6945 ++parg;
6946 }
6947
6948 Expression* cap_arg = NULL;
6949 if (is_slice && parg != args->end())
6950 {
6951 cap_arg = *parg;
6952 cap_arg->determine_type(&int_context);
6953 if (!this->check_int_value(cap_arg, false))
6954 return Expression::make_error(this->location());
6955
6956 Numeric_constant nclen;
6957 Numeric_constant nccap;
6958 unsigned long vlen;
6959 unsigned long vcap;
6960 if (len_arg->numeric_constant_value(&nclen)
6961 && cap_arg->numeric_constant_value(&nccap)
6962 && nclen.to_unsigned_long(&vlen) == Numeric_constant::NC_UL_VALID
6963 && nccap.to_unsigned_long(&vcap) == Numeric_constant::NC_UL_VALID
6964 && vlen > vcap)
6965 {
6966 this->report_error(_("len larger than cap"));
6967 return Expression::make_error(this->location());
6968 }
6969
6970 if (cap_arg->type()->integer_type() != NULL
6971 && cap_arg->type()->integer_type()->bits() > uintptr_bits)
6972 have_big_args = true;
6973 ++parg;
6974 }
6975
6976 if (parg != args->end())
6977 {
6978 this->report_error(_("too many arguments to make"));
6979 return Expression::make_error(this->location());
6980 }
6981
6982 Location type_loc = first_arg->location();
6983 Expression* type_arg;
6984 if (is_slice || is_chan)
6985 type_arg = Expression::make_type_descriptor(type, type_loc);
6986 else if (is_map)
6987 type_arg = Expression::make_map_descriptor(type->map_type(), type_loc);
6988 else
6989 go_unreachable();
6990
6991 Expression* call;
6992 if (is_slice)
6993 {
6994 if (cap_arg == NULL)
6995 call = Runtime::make_call((have_big_args
6996 ? Runtime::MAKESLICE1BIG
6997 : Runtime::MAKESLICE1),
6998 loc, 2, type_arg, len_arg);
6999 else
7000 call = Runtime::make_call((have_big_args
7001 ? Runtime::MAKESLICE2BIG
7002 : Runtime::MAKESLICE2),
7003 loc, 3, type_arg, len_arg, cap_arg);
7004 }
7005 else if (is_map)
7006 call = Runtime::make_call((have_big_args
7007 ? Runtime::MAKEMAPBIG
7008 : Runtime::MAKEMAP),
7009 loc, 2, type_arg, len_arg);
7010 else if (is_chan)
7011 call = Runtime::make_call((have_big_args
7012 ? Runtime::MAKECHANBIG
7013 : Runtime::MAKECHAN),
7014 loc, 2, type_arg, len_arg);
7015 else
7016 go_unreachable();
7017
7018 return Expression::make_unsafe_cast(type, call, loc);
7019 }
7020
7021 // Return whether an expression has an integer value. Report an error
7022 // if not. This is used when handling calls to the predeclared make
7023 // function.
7024
7025 bool
7026 Builtin_call_expression::check_int_value(Expression* e, bool is_length)
7027 {
7028 Numeric_constant nc;
7029 if (e->numeric_constant_value(&nc))
7030 {
7031 unsigned long v;
7032 switch (nc.to_unsigned_long(&v))
7033 {
7034 case Numeric_constant::NC_UL_VALID:
7035 break;
7036 case Numeric_constant::NC_UL_NOTINT:
7037 error_at(e->location(), "non-integer %s argument to make",
7038 is_length ? "len" : "cap");
7039 return false;
7040 case Numeric_constant::NC_UL_NEGATIVE:
7041 error_at(e->location(), "negative %s argument to make",
7042 is_length ? "len" : "cap");
7043 return false;
7044 case Numeric_constant::NC_UL_BIG:
7045 // We don't want to give a compile-time error for a 64-bit
7046 // value on a 32-bit target.
7047 break;
7048 }
7049
7050 mpz_t val;
7051 if (!nc.to_int(&val))
7052 go_unreachable();
7053 int bits = mpz_sizeinbase(val, 2);
7054 mpz_clear(val);
7055 Type* int_type = Type::lookup_integer_type("int");
7056 if (bits >= int_type->integer_type()->bits())
7057 {
7058 error_at(e->location(), "%s argument too large for make",
7059 is_length ? "len" : "cap");
7060 return false;
7061 }
7062
7063 return true;
7064 }
7065
7066 if (e->type()->integer_type() != NULL)
7067 return true;
7068
7069 error_at(e->location(), "non-integer %s argument to make",
7070 is_length ? "len" : "cap");
7071 return false;
7072 }
7073
7074 // Return the type of the real or imag functions, given the type of
7075 // the argument. We need to map complex64 to float32 and complex128
7076 // to float64, so it has to be done by name. This returns NULL if it
7077 // can't figure out the type.
7078
7079 Type*
7080 Builtin_call_expression::real_imag_type(Type* arg_type)
7081 {
7082 if (arg_type == NULL || arg_type->is_abstract())
7083 return NULL;
7084 Named_type* nt = arg_type->named_type();
7085 if (nt == NULL)
7086 return NULL;
7087 while (nt->real_type()->named_type() != NULL)
7088 nt = nt->real_type()->named_type();
7089 if (nt->name() == "complex64")
7090 return Type::lookup_float_type("float32");
7091 else if (nt->name() == "complex128")
7092 return Type::lookup_float_type("float64");
7093 else
7094 return NULL;
7095 }
7096
7097 // Return the type of the complex function, given the type of one of the
7098 // argments. Like real_imag_type, we have to map by name.
7099
7100 Type*
7101 Builtin_call_expression::complex_type(Type* arg_type)
7102 {
7103 if (arg_type == NULL || arg_type->is_abstract())
7104 return NULL;
7105 Named_type* nt = arg_type->named_type();
7106 if (nt == NULL)
7107 return NULL;
7108 while (nt->real_type()->named_type() != NULL)
7109 nt = nt->real_type()->named_type();
7110 if (nt->name() == "float32")
7111 return Type::lookup_complex_type("complex64");
7112 else if (nt->name() == "float64")
7113 return Type::lookup_complex_type("complex128");
7114 else
7115 return NULL;
7116 }
7117
7118 // Return a single argument, or NULL if there isn't one.
7119
7120 Expression*
7121 Builtin_call_expression::one_arg() const
7122 {
7123 const Expression_list* args = this->args();
7124 if (args == NULL || args->size() != 1)
7125 return NULL;
7126 return args->front();
7127 }
7128
7129 // A traversal class which looks for a call or receive expression.
7130
7131 class Find_call_expression : public Traverse
7132 {
7133 public:
7134 Find_call_expression()
7135 : Traverse(traverse_expressions),
7136 found_(false)
7137 { }
7138
7139 int
7140 expression(Expression**);
7141
7142 bool
7143 found()
7144 { return this->found_; }
7145
7146 private:
7147 bool found_;
7148 };
7149
7150 int
7151 Find_call_expression::expression(Expression** pexpr)
7152 {
7153 if ((*pexpr)->call_expression() != NULL
7154 || (*pexpr)->receive_expression() != NULL)
7155 {
7156 this->found_ = true;
7157 return TRAVERSE_EXIT;
7158 }
7159 return TRAVERSE_CONTINUE;
7160 }
7161
7162 // Return whether this is constant: len of a string constant, or len
7163 // or cap of an array, or unsafe.Sizeof, unsafe.Offsetof,
7164 // unsafe.Alignof.
7165
7166 bool
7167 Builtin_call_expression::do_is_constant() const
7168 {
7169 if (this->is_error_expression())
7170 return true;
7171 switch (this->code_)
7172 {
7173 case BUILTIN_LEN:
7174 case BUILTIN_CAP:
7175 {
7176 if (this->seen_)
7177 return false;
7178
7179 Expression* arg = this->one_arg();
7180 if (arg == NULL)
7181 return false;
7182 Type* arg_type = arg->type();
7183
7184 if (arg_type->points_to() != NULL
7185 && arg_type->points_to()->array_type() != NULL
7186 && !arg_type->points_to()->is_slice_type())
7187 arg_type = arg_type->points_to();
7188
7189 // The len and cap functions are only constant if there are no
7190 // function calls or channel operations in the arguments.
7191 // Otherwise we have to make the call.
7192 if (!arg->is_constant())
7193 {
7194 Find_call_expression find_call;
7195 Expression::traverse(&arg, &find_call);
7196 if (find_call.found())
7197 return false;
7198 }
7199
7200 if (arg_type->array_type() != NULL
7201 && arg_type->array_type()->length() != NULL)
7202 return true;
7203
7204 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7205 {
7206 this->seen_ = true;
7207 bool ret = arg->is_constant();
7208 this->seen_ = false;
7209 return ret;
7210 }
7211 }
7212 break;
7213
7214 case BUILTIN_SIZEOF:
7215 case BUILTIN_ALIGNOF:
7216 return this->one_arg() != NULL;
7217
7218 case BUILTIN_OFFSETOF:
7219 {
7220 Expression* arg = this->one_arg();
7221 if (arg == NULL)
7222 return false;
7223 return arg->field_reference_expression() != NULL;
7224 }
7225
7226 case BUILTIN_COMPLEX:
7227 {
7228 const Expression_list* args = this->args();
7229 if (args != NULL && args->size() == 2)
7230 return args->front()->is_constant() && args->back()->is_constant();
7231 }
7232 break;
7233
7234 case BUILTIN_REAL:
7235 case BUILTIN_IMAG:
7236 {
7237 Expression* arg = this->one_arg();
7238 return arg != NULL && arg->is_constant();
7239 }
7240
7241 default:
7242 break;
7243 }
7244
7245 return false;
7246 }
7247
7248 // Return a numeric constant if possible.
7249
7250 bool
7251 Builtin_call_expression::do_numeric_constant_value(Numeric_constant* nc) const
7252 {
7253 if (this->code_ == BUILTIN_LEN
7254 || this->code_ == BUILTIN_CAP)
7255 {
7256 Expression* arg = this->one_arg();
7257 if (arg == NULL)
7258 return false;
7259 Type* arg_type = arg->type();
7260
7261 if (this->code_ == BUILTIN_LEN && arg_type->is_string_type())
7262 {
7263 std::string sval;
7264 if (arg->string_constant_value(&sval))
7265 {
7266 nc->set_unsigned_long(Type::lookup_integer_type("int"),
7267 sval.length());
7268 return true;
7269 }
7270 }
7271
7272 if (arg_type->points_to() != NULL
7273 && arg_type->points_to()->array_type() != NULL
7274 && !arg_type->points_to()->is_slice_type())
7275 arg_type = arg_type->points_to();
7276
7277 if (arg_type->array_type() != NULL
7278 && arg_type->array_type()->length() != NULL)
7279 {
7280 if (this->seen_)
7281 return false;
7282 Expression* e = arg_type->array_type()->length();
7283 this->seen_ = true;
7284 bool r = e->numeric_constant_value(nc);
7285 this->seen_ = false;
7286 if (r)
7287 {
7288 if (!nc->set_type(Type::lookup_integer_type("int"), false,
7289 this->location()))
7290 r = false;
7291 }
7292 return r;
7293 }
7294 }
7295 else if (this->code_ == BUILTIN_SIZEOF
7296 || this->code_ == BUILTIN_ALIGNOF)
7297 {
7298 Expression* arg = this->one_arg();
7299 if (arg == NULL)
7300 return false;
7301 Type* arg_type = arg->type();
7302 if (arg_type->is_error())
7303 return false;
7304 if (arg_type->is_abstract())
7305 return false;
7306 if (this->seen_)
7307 return false;
7308
7309 int64_t ret;
7310 if (this->code_ == BUILTIN_SIZEOF)
7311 {
7312 this->seen_ = true;
7313 bool ok = arg_type->backend_type_size(this->gogo_, &ret);
7314 this->seen_ = false;
7315 if (!ok)
7316 return false;
7317 }
7318 else if (this->code_ == BUILTIN_ALIGNOF)
7319 {
7320 bool ok;
7321 this->seen_ = true;
7322 if (arg->field_reference_expression() == NULL)
7323 ok = arg_type->backend_type_align(this->gogo_, &ret);
7324 else
7325 {
7326 // Calling unsafe.Alignof(s.f) returns the alignment of
7327 // the type of f when it is used as a field in a struct.
7328 ok = arg_type->backend_type_field_align(this->gogo_, &ret);
7329 }
7330 this->seen_ = false;
7331 if (!ok)
7332 return false;
7333 }
7334 else
7335 go_unreachable();
7336
7337 mpz_t zval;
7338 set_mpz_from_int64(&zval, ret);
7339 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7340 mpz_clear(zval);
7341 return true;
7342 }
7343 else if (this->code_ == BUILTIN_OFFSETOF)
7344 {
7345 Expression* arg = this->one_arg();
7346 if (arg == NULL)
7347 return false;
7348 Field_reference_expression* farg = arg->field_reference_expression();
7349 if (farg == NULL)
7350 return false;
7351 if (this->seen_)
7352 return false;
7353
7354 int64_t total_offset = 0;
7355 while (true)
7356 {
7357 Expression* struct_expr = farg->expr();
7358 Type* st = struct_expr->type();
7359 if (st->struct_type() == NULL)
7360 return false;
7361 if (st->named_type() != NULL)
7362 st->named_type()->convert(this->gogo_);
7363 int64_t offset;
7364 this->seen_ = true;
7365 bool ok = st->struct_type()->backend_field_offset(this->gogo_,
7366 farg->field_index(),
7367 &offset);
7368 this->seen_ = false;
7369 if (!ok)
7370 return false;
7371 total_offset += offset;
7372 if (farg->implicit() && struct_expr->field_reference_expression() != NULL)
7373 {
7374 // Go up until we reach the original base.
7375 farg = struct_expr->field_reference_expression();
7376 continue;
7377 }
7378 break;
7379 }
7380 mpz_t zval;
7381 set_mpz_from_int64(&zval, total_offset);
7382 nc->set_int(Type::lookup_integer_type("uintptr"), zval);
7383 mpz_clear(zval);
7384 return true;
7385 }
7386 else if (this->code_ == BUILTIN_REAL || this->code_ == BUILTIN_IMAG)
7387 {
7388 Expression* arg = this->one_arg();
7389 if (arg == NULL)
7390 return false;
7391
7392 Numeric_constant argnc;
7393 if (!arg->numeric_constant_value(&argnc))
7394 return false;
7395
7396 mpc_t val;
7397 if (!argnc.to_complex(&val))
7398 return false;
7399
7400 Type* type = Builtin_call_expression::real_imag_type(argnc.type());
7401 if (this->code_ == BUILTIN_REAL)
7402 nc->set_float(type, mpc_realref(val));
7403 else
7404 nc->set_float(type, mpc_imagref(val));
7405 mpc_clear(val);
7406 return true;
7407 }
7408 else if (this->code_ == BUILTIN_COMPLEX)
7409 {
7410 const Expression_list* args = this->args();
7411 if (args == NULL || args->size() != 2)
7412 return false;
7413
7414 Numeric_constant rnc;
7415 if (!args->front()->numeric_constant_value(&rnc))
7416 return false;
7417 Numeric_constant inc;
7418 if (!args->back()->numeric_constant_value(&inc))
7419 return false;
7420
7421 if (rnc.type() != NULL
7422 && !rnc.type()->is_abstract()
7423 && inc.type() != NULL
7424 && !inc.type()->is_abstract()
7425 && !Type::are_identical(rnc.type(), inc.type(), false, NULL))
7426 return false;
7427
7428 mpfr_t r;
7429 if (!rnc.to_float(&r))
7430 return false;
7431 mpfr_t i;
7432 if (!inc.to_float(&i))
7433 {
7434 mpfr_clear(r);
7435 return false;
7436 }
7437
7438 Type* arg_type = rnc.type();
7439 if (arg_type == NULL || arg_type->is_abstract())
7440 arg_type = inc.type();
7441
7442 mpc_t val;
7443 mpc_init2(val, mpc_precision);
7444 mpc_set_fr_fr(val, r, i, MPC_RNDNN);
7445 mpfr_clear(r);
7446 mpfr_clear(i);
7447
7448 Type* type = Builtin_call_expression::complex_type(arg_type);
7449 nc->set_complex(type, val);
7450
7451 mpc_clear(val);
7452
7453 return true;
7454 }
7455
7456 return false;
7457 }
7458
7459 // Give an error if we are discarding the value of an expression which
7460 // should not normally be discarded. We don't give an error for
7461 // discarding the value of an ordinary function call, but we do for
7462 // builtin functions, purely for consistency with the gc compiler.
7463
7464 bool
7465 Builtin_call_expression::do_discarding_value()
7466 {
7467 switch (this->code_)
7468 {
7469 case BUILTIN_INVALID:
7470 default:
7471 go_unreachable();
7472
7473 case BUILTIN_APPEND:
7474 case BUILTIN_CAP:
7475 case BUILTIN_COMPLEX:
7476 case BUILTIN_IMAG:
7477 case BUILTIN_LEN:
7478 case BUILTIN_MAKE:
7479 case BUILTIN_NEW:
7480 case BUILTIN_REAL:
7481 case BUILTIN_ALIGNOF:
7482 case BUILTIN_OFFSETOF:
7483 case BUILTIN_SIZEOF:
7484 this->unused_value_error();
7485 return false;
7486
7487 case BUILTIN_CLOSE:
7488 case BUILTIN_COPY:
7489 case BUILTIN_DELETE:
7490 case BUILTIN_PANIC:
7491 case BUILTIN_PRINT:
7492 case BUILTIN_PRINTLN:
7493 case BUILTIN_RECOVER:
7494 return true;
7495 }
7496 }
7497
7498 // Return the type.
7499
7500 Type*
7501 Builtin_call_expression::do_type()
7502 {
7503 switch (this->code_)
7504 {
7505 case BUILTIN_INVALID:
7506 default:
7507 go_unreachable();
7508
7509 case BUILTIN_NEW:
7510 case BUILTIN_MAKE:
7511 {
7512 const Expression_list* args = this->args();
7513 if (args == NULL || args->empty())
7514 return Type::make_error_type();
7515 return Type::make_pointer_type(args->front()->type());
7516 }
7517
7518 case BUILTIN_CAP:
7519 case BUILTIN_COPY:
7520 case BUILTIN_LEN:
7521 return Type::lookup_integer_type("int");
7522
7523 case BUILTIN_ALIGNOF:
7524 case BUILTIN_OFFSETOF:
7525 case BUILTIN_SIZEOF:
7526 return Type::lookup_integer_type("uintptr");
7527
7528 case BUILTIN_CLOSE:
7529 case BUILTIN_DELETE:
7530 case BUILTIN_PANIC:
7531 case BUILTIN_PRINT:
7532 case BUILTIN_PRINTLN:
7533 return Type::make_void_type();
7534
7535 case BUILTIN_RECOVER:
7536 return Type::make_empty_interface_type(Linemap::predeclared_location());
7537
7538 case BUILTIN_APPEND:
7539 {
7540 const Expression_list* args = this->args();
7541 if (args == NULL || args->empty())
7542 return Type::make_error_type();
7543 Type *ret = args->front()->type();
7544 if (!ret->is_slice_type())
7545 return Type::make_error_type();
7546 return ret;
7547 }
7548
7549 case BUILTIN_REAL:
7550 case BUILTIN_IMAG:
7551 {
7552 Expression* arg = this->one_arg();
7553 if (arg == NULL)
7554 return Type::make_error_type();
7555 Type* t = arg->type();
7556 if (t->is_abstract())
7557 t = t->make_non_abstract_type();
7558 t = Builtin_call_expression::real_imag_type(t);
7559 if (t == NULL)
7560 t = Type::make_error_type();
7561 return t;
7562 }
7563
7564 case BUILTIN_COMPLEX:
7565 {
7566 const Expression_list* args = this->args();
7567 if (args == NULL || args->size() != 2)
7568 return Type::make_error_type();
7569 Type* t = args->front()->type();
7570 if (t->is_abstract())
7571 {
7572 t = args->back()->type();
7573 if (t->is_abstract())
7574 t = t->make_non_abstract_type();
7575 }
7576 t = Builtin_call_expression::complex_type(t);
7577 if (t == NULL)
7578 t = Type::make_error_type();
7579 return t;
7580 }
7581 }
7582 }
7583
7584 // Determine the type.
7585
7586 void
7587 Builtin_call_expression::do_determine_type(const Type_context* context)
7588 {
7589 if (!this->determining_types())
7590 return;
7591
7592 this->fn()->determine_type_no_context();
7593
7594 const Expression_list* args = this->args();
7595
7596 bool is_print;
7597 Type* arg_type = NULL;
7598 switch (this->code_)
7599 {
7600 case BUILTIN_PRINT:
7601 case BUILTIN_PRINTLN:
7602 // Do not force a large integer constant to "int".
7603 is_print = true;
7604 break;
7605
7606 case BUILTIN_REAL:
7607 case BUILTIN_IMAG:
7608 arg_type = Builtin_call_expression::complex_type(context->type);
7609 if (arg_type == NULL)
7610 arg_type = Type::lookup_complex_type("complex128");
7611 is_print = false;
7612 break;
7613
7614 case BUILTIN_COMPLEX:
7615 {
7616 // For the complex function the type of one operand can
7617 // determine the type of the other, as in a binary expression.
7618 arg_type = Builtin_call_expression::real_imag_type(context->type);
7619 if (arg_type == NULL)
7620 arg_type = Type::lookup_float_type("float64");
7621 if (args != NULL && args->size() == 2)
7622 {
7623 Type* t1 = args->front()->type();
7624 Type* t2 = args->back()->type();
7625 if (!t1->is_abstract())
7626 arg_type = t1;
7627 else if (!t2->is_abstract())
7628 arg_type = t2;
7629 }
7630 is_print = false;
7631 }
7632 break;
7633
7634 default:
7635 is_print = false;
7636 break;
7637 }
7638
7639 if (args != NULL)
7640 {
7641 for (Expression_list::const_iterator pa = args->begin();
7642 pa != args->end();
7643 ++pa)
7644 {
7645 Type_context subcontext;
7646 subcontext.type = arg_type;
7647
7648 if (is_print)
7649 {
7650 // We want to print large constants, we so can't just
7651 // use the appropriate nonabstract type. Use uint64 for
7652 // an integer if we know it is nonnegative, otherwise
7653 // use int64 for a integer, otherwise use float64 for a
7654 // float or complex128 for a complex.
7655 Type* want_type = NULL;
7656 Type* atype = (*pa)->type();
7657 if (atype->is_abstract())
7658 {
7659 if (atype->integer_type() != NULL)
7660 {
7661 Numeric_constant nc;
7662 if (this->numeric_constant_value(&nc))
7663 {
7664 mpz_t val;
7665 if (nc.to_int(&val))
7666 {
7667 if (mpz_sgn(val) >= 0)
7668 want_type = Type::lookup_integer_type("uint64");
7669 mpz_clear(val);
7670 }
7671 }
7672 if (want_type == NULL)
7673 want_type = Type::lookup_integer_type("int64");
7674 }
7675 else if (atype->float_type() != NULL)
7676 want_type = Type::lookup_float_type("float64");
7677 else if (atype->complex_type() != NULL)
7678 want_type = Type::lookup_complex_type("complex128");
7679 else if (atype->is_abstract_string_type())
7680 want_type = Type::lookup_string_type();
7681 else if (atype->is_abstract_boolean_type())
7682 want_type = Type::lookup_bool_type();
7683 else
7684 go_unreachable();
7685 subcontext.type = want_type;
7686 }
7687 }
7688
7689 (*pa)->determine_type(&subcontext);
7690 }
7691 }
7692 }
7693
7694 // If there is exactly one argument, return true. Otherwise give an
7695 // error message and return false.
7696
7697 bool
7698 Builtin_call_expression::check_one_arg()
7699 {
7700 const Expression_list* args = this->args();
7701 if (args == NULL || args->size() < 1)
7702 {
7703 this->report_error(_("not enough arguments"));
7704 return false;
7705 }
7706 else if (args->size() > 1)
7707 {
7708 this->report_error(_("too many arguments"));
7709 return false;
7710 }
7711 if (args->front()->is_error_expression()
7712 || args->front()->type()->is_error())
7713 {
7714 this->set_is_error();
7715 return false;
7716 }
7717 return true;
7718 }
7719
7720 // Check argument types for a builtin function.
7721
7722 void
7723 Builtin_call_expression::do_check_types(Gogo*)
7724 {
7725 if (this->is_error_expression())
7726 return;
7727 switch (this->code_)
7728 {
7729 case BUILTIN_INVALID:
7730 case BUILTIN_NEW:
7731 case BUILTIN_MAKE:
7732 case BUILTIN_DELETE:
7733 return;
7734
7735 case BUILTIN_LEN:
7736 case BUILTIN_CAP:
7737 {
7738 // The single argument may be either a string or an array or a
7739 // map or a channel, or a pointer to a closed array.
7740 if (this->check_one_arg())
7741 {
7742 Type* arg_type = this->one_arg()->type();
7743 if (arg_type->points_to() != NULL
7744 && arg_type->points_to()->array_type() != NULL
7745 && !arg_type->points_to()->is_slice_type())
7746 arg_type = arg_type->points_to();
7747 if (this->code_ == BUILTIN_CAP)
7748 {
7749 if (!arg_type->is_error()
7750 && arg_type->array_type() == NULL
7751 && arg_type->channel_type() == NULL)
7752 this->report_error(_("argument must be array or slice "
7753 "or channel"));
7754 }
7755 else
7756 {
7757 if (!arg_type->is_error()
7758 && !arg_type->is_string_type()
7759 && arg_type->array_type() == NULL
7760 && arg_type->map_type() == NULL
7761 && arg_type->channel_type() == NULL)
7762 this->report_error(_("argument must be string or "
7763 "array or slice or map or channel"));
7764 }
7765 }
7766 }
7767 break;
7768
7769 case BUILTIN_PRINT:
7770 case BUILTIN_PRINTLN:
7771 {
7772 const Expression_list* args = this->args();
7773 if (args == NULL)
7774 {
7775 if (this->code_ == BUILTIN_PRINT)
7776 warning_at(this->location(), 0,
7777 "no arguments for builtin function %<%s%>",
7778 (this->code_ == BUILTIN_PRINT
7779 ? "print"
7780 : "println"));
7781 }
7782 else
7783 {
7784 for (Expression_list::const_iterator p = args->begin();
7785 p != args->end();
7786 ++p)
7787 {
7788 Type* type = (*p)->type();
7789 if (type->is_error()
7790 || type->is_string_type()
7791 || type->integer_type() != NULL
7792 || type->float_type() != NULL
7793 || type->complex_type() != NULL
7794 || type->is_boolean_type()
7795 || type->points_to() != NULL
7796 || type->interface_type() != NULL
7797 || type->channel_type() != NULL
7798 || type->map_type() != NULL
7799 || type->function_type() != NULL
7800 || type->is_slice_type())
7801 ;
7802 else if ((*p)->is_type_expression())
7803 {
7804 // If this is a type expression it's going to give
7805 // an error anyhow, so we don't need one here.
7806 }
7807 else
7808 this->report_error(_("unsupported argument type to "
7809 "builtin function"));
7810 }
7811 }
7812 }
7813 break;
7814
7815 case BUILTIN_CLOSE:
7816 if (this->check_one_arg())
7817 {
7818 if (this->one_arg()->type()->channel_type() == NULL)
7819 this->report_error(_("argument must be channel"));
7820 else if (!this->one_arg()->type()->channel_type()->may_send())
7821 this->report_error(_("cannot close receive-only channel"));
7822 }
7823 break;
7824
7825 case BUILTIN_PANIC:
7826 case BUILTIN_SIZEOF:
7827 case BUILTIN_ALIGNOF:
7828 this->check_one_arg();
7829 break;
7830
7831 case BUILTIN_RECOVER:
7832 if (this->args() != NULL
7833 && !this->args()->empty()
7834 && !this->recover_arg_is_set_)
7835 this->report_error(_("too many arguments"));
7836 break;
7837
7838 case BUILTIN_OFFSETOF:
7839 if (this->check_one_arg())
7840 {
7841 Expression* arg = this->one_arg();
7842 if (arg->field_reference_expression() == NULL)
7843 this->report_error(_("argument must be a field reference"));
7844 }
7845 break;
7846
7847 case BUILTIN_COPY:
7848 {
7849 const Expression_list* args = this->args();
7850 if (args == NULL || args->size() < 2)
7851 {
7852 this->report_error(_("not enough arguments"));
7853 break;
7854 }
7855 else if (args->size() > 2)
7856 {
7857 this->report_error(_("too many arguments"));
7858 break;
7859 }
7860 Type* arg1_type = args->front()->type();
7861 Type* arg2_type = args->back()->type();
7862 if (arg1_type->is_error() || arg2_type->is_error())
7863 {
7864 this->set_is_error();
7865 break;
7866 }
7867
7868 Type* e1;
7869 if (arg1_type->is_slice_type())
7870 e1 = arg1_type->array_type()->element_type();
7871 else
7872 {
7873 this->report_error(_("left argument must be a slice"));
7874 break;
7875 }
7876
7877 if (arg2_type->is_slice_type())
7878 {
7879 Type* e2 = arg2_type->array_type()->element_type();
7880 if (!Type::are_identical(e1, e2, true, NULL))
7881 this->report_error(_("element types must be the same"));
7882 }
7883 else if (arg2_type->is_string_type())
7884 {
7885 if (e1->integer_type() == NULL || !e1->integer_type()->is_byte())
7886 this->report_error(_("first argument must be []byte"));
7887 }
7888 else
7889 this->report_error(_("second argument must be slice or string"));
7890 }
7891 break;
7892
7893 case BUILTIN_APPEND:
7894 {
7895 const Expression_list* args = this->args();
7896 if (args == NULL || args->size() < 2)
7897 {
7898 this->report_error(_("not enough arguments"));
7899 break;
7900 }
7901 if (args->size() > 2)
7902 {
7903 this->report_error(_("too many arguments"));
7904 break;
7905 }
7906 if (args->front()->type()->is_error()
7907 || args->back()->type()->is_error())
7908 {
7909 this->set_is_error();
7910 break;
7911 }
7912
7913 Array_type* at = args->front()->type()->array_type();
7914 Type* e = at->element_type();
7915
7916 // The language permits appending a string to a []byte, as a
7917 // special case.
7918 if (args->back()->type()->is_string_type())
7919 {
7920 if (e->integer_type() != NULL && e->integer_type()->is_byte())
7921 break;
7922 }
7923
7924 // The language says that the second argument must be
7925 // assignable to a slice of the element type of the first
7926 // argument. We already know the first argument is a slice
7927 // type.
7928 Type* arg2_type = Type::make_array_type(e, NULL);
7929 std::string reason;
7930 if (!Type::are_assignable(arg2_type, args->back()->type(), &reason))
7931 {
7932 if (reason.empty())
7933 this->report_error(_("argument 2 has invalid type"));
7934 else
7935 {
7936 error_at(this->location(), "argument 2 has invalid type (%s)",
7937 reason.c_str());
7938 this->set_is_error();
7939 }
7940 }
7941 break;
7942 }
7943
7944 case BUILTIN_REAL:
7945 case BUILTIN_IMAG:
7946 if (this->check_one_arg())
7947 {
7948 if (this->one_arg()->type()->complex_type() == NULL)
7949 this->report_error(_("argument must have complex type"));
7950 }
7951 break;
7952
7953 case BUILTIN_COMPLEX:
7954 {
7955 const Expression_list* args = this->args();
7956 if (args == NULL || args->size() < 2)
7957 this->report_error(_("not enough arguments"));
7958 else if (args->size() > 2)
7959 this->report_error(_("too many arguments"));
7960 else if (args->front()->is_error_expression()
7961 || args->front()->type()->is_error()
7962 || args->back()->is_error_expression()
7963 || args->back()->type()->is_error())
7964 this->set_is_error();
7965 else if (!Type::are_identical(args->front()->type(),
7966 args->back()->type(), true, NULL))
7967 this->report_error(_("complex arguments must have identical types"));
7968 else if (args->front()->type()->float_type() == NULL)
7969 this->report_error(_("complex arguments must have "
7970 "floating-point type"));
7971 }
7972 break;
7973
7974 default:
7975 go_unreachable();
7976 }
7977 }
7978
7979 Expression*
7980 Builtin_call_expression::do_copy()
7981 {
7982 Call_expression* bce =
7983 new Builtin_call_expression(this->gogo_, this->fn()->copy(),
7984 (this->args() == NULL
7985 ? NULL
7986 : this->args()->copy()),
7987 this->is_varargs(),
7988 this->location());
7989
7990 if (this->varargs_are_lowered())
7991 bce->set_varargs_are_lowered();
7992 return bce;
7993 }
7994
7995 // Return the backend representation for a builtin function.
7996
7997 Bexpression*
7998 Builtin_call_expression::do_get_backend(Translate_context* context)
7999 {
8000 Gogo* gogo = context->gogo();
8001 Location location = this->location();
8002 switch (this->code_)
8003 {
8004 case BUILTIN_INVALID:
8005 case BUILTIN_NEW:
8006 case BUILTIN_MAKE:
8007 go_unreachable();
8008
8009 case BUILTIN_LEN:
8010 case BUILTIN_CAP:
8011 {
8012 const Expression_list* args = this->args();
8013 go_assert(args != NULL && args->size() == 1);
8014 Expression* arg = args->front();
8015 Type* arg_type = arg->type();
8016
8017 if (this->seen_)
8018 {
8019 go_assert(saw_errors());
8020 return context->backend()->error_expression();
8021 }
8022 this->seen_ = true;
8023 this->seen_ = false;
8024 if (arg_type->points_to() != NULL)
8025 {
8026 arg_type = arg_type->points_to();
8027 go_assert(arg_type->array_type() != NULL
8028 && !arg_type->is_slice_type());
8029 arg = Expression::make_unary(OPERATOR_MULT, arg, location);
8030 }
8031
8032 Type* int_type = Type::lookup_integer_type("int");
8033 Expression* val;
8034 if (this->code_ == BUILTIN_LEN)
8035 {
8036 if (arg_type->is_string_type())
8037 val = Expression::make_string_info(arg, STRING_INFO_LENGTH,
8038 location);
8039 else if (arg_type->array_type() != NULL)
8040 {
8041 if (this->seen_)
8042 {
8043 go_assert(saw_errors());
8044 return context->backend()->error_expression();
8045 }
8046 this->seen_ = true;
8047 val = arg_type->array_type()->get_length(gogo, arg);
8048 this->seen_ = false;
8049 }
8050 else if (arg_type->map_type() != NULL)
8051 val = Runtime::make_call(Runtime::MAP_LEN, location, 1, arg);
8052 else if (arg_type->channel_type() != NULL)
8053 val = Runtime::make_call(Runtime::CHAN_LEN, location, 1, arg);
8054 else
8055 go_unreachable();
8056 }
8057 else
8058 {
8059 if (arg_type->array_type() != NULL)
8060 {
8061 if (this->seen_)
8062 {
8063 go_assert(saw_errors());
8064 return context->backend()->error_expression();
8065 }
8066 this->seen_ = true;
8067 val = arg_type->array_type()->get_capacity(gogo, arg);
8068 this->seen_ = false;
8069 }
8070 else if (arg_type->channel_type() != NULL)
8071 val = Runtime::make_call(Runtime::CHAN_CAP, location, 1, arg);
8072 else
8073 go_unreachable();
8074 }
8075
8076 return Expression::make_cast(int_type, val,
8077 location)->get_backend(context);
8078 }
8079
8080 case BUILTIN_PRINT:
8081 case BUILTIN_PRINTLN:
8082 {
8083 const bool is_ln = this->code_ == BUILTIN_PRINTLN;
8084 Expression* print_stmts = NULL;
8085
8086 const Expression_list* call_args = this->args();
8087 if (call_args != NULL)
8088 {
8089 for (Expression_list::const_iterator p = call_args->begin();
8090 p != call_args->end();
8091 ++p)
8092 {
8093 if (is_ln && p != call_args->begin())
8094 {
8095 Expression* print_space =
8096 Runtime::make_call(Runtime::PRINT_SPACE,
8097 this->location(), 0);
8098
8099 print_stmts =
8100 Expression::make_compound(print_stmts, print_space,
8101 location);
8102 }
8103
8104 Expression* arg = *p;
8105 Type* type = arg->type();
8106 Runtime::Function code;
8107 if (type->is_string_type())
8108 code = Runtime::PRINT_STRING;
8109 else if (type->integer_type() != NULL
8110 && type->integer_type()->is_unsigned())
8111 {
8112 Type* itype = Type::lookup_integer_type("uint64");
8113 arg = Expression::make_cast(itype, arg, location);
8114 code = Runtime::PRINT_UINT64;
8115 }
8116 else if (type->integer_type() != NULL)
8117 {
8118 Type* itype = Type::lookup_integer_type("int64");
8119 arg = Expression::make_cast(itype, arg, location);
8120 code = Runtime::PRINT_INT64;
8121 }
8122 else if (type->float_type() != NULL)
8123 {
8124 Type* dtype = Type::lookup_float_type("float64");
8125 arg = Expression::make_cast(dtype, arg, location);
8126 code = Runtime::PRINT_DOUBLE;
8127 }
8128 else if (type->complex_type() != NULL)
8129 {
8130 Type* ctype = Type::lookup_complex_type("complex128");
8131 arg = Expression::make_cast(ctype, arg, location);
8132 code = Runtime::PRINT_COMPLEX;
8133 }
8134 else if (type->is_boolean_type())
8135 code = Runtime::PRINT_BOOL;
8136 else if (type->points_to() != NULL
8137 || type->channel_type() != NULL
8138 || type->map_type() != NULL
8139 || type->function_type() != NULL)
8140 {
8141 arg = Expression::make_cast(type, arg, location);
8142 code = Runtime::PRINT_POINTER;
8143 }
8144 else if (type->interface_type() != NULL)
8145 {
8146 if (type->interface_type()->is_empty())
8147 code = Runtime::PRINT_EMPTY_INTERFACE;
8148 else
8149 code = Runtime::PRINT_INTERFACE;
8150 }
8151 else if (type->is_slice_type())
8152 code = Runtime::PRINT_SLICE;
8153 else
8154 {
8155 go_assert(saw_errors());
8156 return context->backend()->error_expression();
8157 }
8158
8159 Expression* call = Runtime::make_call(code, location, 1, arg);
8160 if (print_stmts == NULL)
8161 print_stmts = call;
8162 else
8163 print_stmts = Expression::make_compound(print_stmts, call,
8164 location);
8165 }
8166 }
8167
8168 if (is_ln)
8169 {
8170 Expression* print_nl =
8171 Runtime::make_call(Runtime::PRINT_NL, location, 0);
8172 if (print_stmts == NULL)
8173 print_stmts = print_nl;
8174 else
8175 print_stmts = Expression::make_compound(print_stmts, print_nl,
8176 location);
8177 }
8178
8179 // There aren't any arguments to the print builtin. The compiler
8180 // issues a warning for this so we should avoid getting the backend
8181 // representation for this call. Instead, perform a no-op.
8182 if (print_stmts == NULL)
8183 return context->backend()->boolean_constant_expression(false);
8184
8185 return print_stmts->get_backend(context);
8186 }
8187
8188 case BUILTIN_PANIC:
8189 {
8190 const Expression_list* args = this->args();
8191 go_assert(args != NULL && args->size() == 1);
8192 Expression* arg = args->front();
8193 Type *empty =
8194 Type::make_empty_interface_type(Linemap::predeclared_location());
8195 arg = Expression::convert_for_assignment(gogo, empty, arg, location);
8196
8197 Expression* panic =
8198 Runtime::make_call(Runtime::PANIC, location, 1, arg);
8199 return panic->get_backend(context);
8200 }
8201
8202 case BUILTIN_RECOVER:
8203 {
8204 // The argument is set when building recover thunks. It's a
8205 // boolean value which is true if we can recover a value now.
8206 const Expression_list* args = this->args();
8207 go_assert(args != NULL && args->size() == 1);
8208 Expression* arg = args->front();
8209 Type *empty =
8210 Type::make_empty_interface_type(Linemap::predeclared_location());
8211
8212 Expression* nil = Expression::make_nil(location);
8213 nil = Expression::convert_for_assignment(gogo, empty, nil, location);
8214
8215 // We need to handle a deferred call to recover specially,
8216 // because it changes whether it can recover a panic or not.
8217 // See test7 in test/recover1.go.
8218 Expression* recover = Runtime::make_call((this->is_deferred()
8219 ? Runtime::DEFERRED_RECOVER
8220 : Runtime::RECOVER),
8221 location, 0);
8222 Expression* cond =
8223 Expression::make_conditional(arg, recover, nil, location);
8224 return cond->get_backend(context);
8225 }
8226
8227 case BUILTIN_CLOSE:
8228 {
8229 const Expression_list* args = this->args();
8230 go_assert(args != NULL && args->size() == 1);
8231 Expression* arg = args->front();
8232 Expression* close = Runtime::make_call(Runtime::CLOSE, location,
8233 1, arg);
8234 return close->get_backend(context);
8235 }
8236
8237 case BUILTIN_SIZEOF:
8238 case BUILTIN_OFFSETOF:
8239 case BUILTIN_ALIGNOF:
8240 {
8241 Numeric_constant nc;
8242 unsigned long val;
8243 if (!this->numeric_constant_value(&nc)
8244 || nc.to_unsigned_long(&val) != Numeric_constant::NC_UL_VALID)
8245 {
8246 go_assert(saw_errors());
8247 return context->backend()->error_expression();
8248 }
8249 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8250 mpz_t ival;
8251 nc.get_int(&ival);
8252 Expression* int_cst =
8253 Expression::make_integer_z(&ival, uintptr_type, location);
8254 mpz_clear(ival);
8255 return int_cst->get_backend(context);
8256 }
8257
8258 case BUILTIN_COPY:
8259 {
8260 const Expression_list* args = this->args();
8261 go_assert(args != NULL && args->size() == 2);
8262 Expression* arg1 = args->front();
8263 Expression* arg2 = args->back();
8264
8265 Type* arg1_type = arg1->type();
8266 Array_type* at = arg1_type->array_type();
8267 go_assert(arg1->is_variable());
8268 Expression* arg1_val = at->get_value_pointer(gogo, arg1);
8269 Expression* arg1_len = at->get_length(gogo, arg1);
8270
8271 Type* arg2_type = arg2->type();
8272 go_assert(arg2->is_variable());
8273 Expression* arg2_val;
8274 Expression* arg2_len;
8275 if (arg2_type->is_slice_type())
8276 {
8277 at = arg2_type->array_type();
8278 arg2_val = at->get_value_pointer(gogo, arg2);
8279 arg2_len = at->get_length(gogo, arg2);
8280 }
8281 else
8282 {
8283 go_assert(arg2->is_variable());
8284 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8285 location);
8286 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8287 location);
8288 }
8289 Expression* cond =
8290 Expression::make_binary(OPERATOR_LT, arg1_len, arg2_len, location);
8291 Expression* length =
8292 Expression::make_conditional(cond, arg1_len, arg2_len, location);
8293
8294 Type* element_type = at->element_type();
8295 Btype* element_btype = element_type->get_backend(gogo);
8296 int64_t element_size = gogo->backend()->type_size(element_btype);
8297 Expression* size_expr = Expression::make_integer_int64(element_size,
8298 length->type(),
8299 location);
8300 Expression* bytecount =
8301 Expression::make_binary(OPERATOR_MULT, size_expr, length, location);
8302 Expression* copy = Runtime::make_call(Runtime::COPY, location, 3,
8303 arg1_val, arg2_val, bytecount);
8304
8305 Expression* compound = Expression::make_compound(copy, length, location);
8306 return compound->get_backend(context);
8307 }
8308
8309 case BUILTIN_APPEND:
8310 {
8311 const Expression_list* args = this->args();
8312 go_assert(args != NULL && args->size() == 2);
8313 Expression* arg1 = args->front();
8314 Expression* arg2 = args->back();
8315
8316 Array_type* at = arg1->type()->array_type();
8317 Type* element_type = at->element_type()->forwarded();
8318
8319 go_assert(arg2->is_variable());
8320 Expression* arg2_val;
8321 Expression* arg2_len;
8322 int64_t size;
8323 if (arg2->type()->is_string_type()
8324 && element_type->integer_type() != NULL
8325 && element_type->integer_type()->is_byte())
8326 {
8327 arg2_val = Expression::make_string_info(arg2, STRING_INFO_DATA,
8328 location);
8329 arg2_len = Expression::make_string_info(arg2, STRING_INFO_LENGTH,
8330 location);
8331 size = 1;
8332 }
8333 else
8334 {
8335 arg2_val = at->get_value_pointer(gogo, arg2);
8336 arg2_len = at->get_length(gogo, arg2);
8337 Btype* element_btype = element_type->get_backend(gogo);
8338 size = gogo->backend()->type_size(element_btype);
8339 }
8340 Expression* element_size =
8341 Expression::make_integer_int64(size, NULL, location);
8342
8343 Expression* append = Runtime::make_call(Runtime::APPEND, location, 4,
8344 arg1, arg2_val, arg2_len,
8345 element_size);
8346 append = Expression::make_unsafe_cast(arg1->type(), append, location);
8347 return append->get_backend(context);
8348 }
8349
8350 case BUILTIN_REAL:
8351 case BUILTIN_IMAG:
8352 {
8353 const Expression_list* args = this->args();
8354 go_assert(args != NULL && args->size() == 1);
8355
8356 Bexpression* ret;
8357 Bexpression* bcomplex = args->front()->get_backend(context);
8358 if (this->code_ == BUILTIN_REAL)
8359 ret = gogo->backend()->real_part_expression(bcomplex, location);
8360 else
8361 ret = gogo->backend()->imag_part_expression(bcomplex, location);
8362 return ret;
8363 }
8364
8365 case BUILTIN_COMPLEX:
8366 {
8367 const Expression_list* args = this->args();
8368 go_assert(args != NULL && args->size() == 2);
8369 Bexpression* breal = args->front()->get_backend(context);
8370 Bexpression* bimag = args->back()->get_backend(context);
8371 return gogo->backend()->complex_expression(breal, bimag, location);
8372 }
8373
8374 default:
8375 go_unreachable();
8376 }
8377 }
8378
8379 // We have to support exporting a builtin call expression, because
8380 // code can set a constant to the result of a builtin expression.
8381
8382 void
8383 Builtin_call_expression::do_export(Export* exp) const
8384 {
8385 Numeric_constant nc;
8386 if (!this->numeric_constant_value(&nc))
8387 {
8388 error_at(this->location(), "value is not constant");
8389 return;
8390 }
8391
8392 if (nc.is_int())
8393 {
8394 mpz_t val;
8395 nc.get_int(&val);
8396 Integer_expression::export_integer(exp, val);
8397 mpz_clear(val);
8398 }
8399 else if (nc.is_float())
8400 {
8401 mpfr_t fval;
8402 nc.get_float(&fval);
8403 Float_expression::export_float(exp, fval);
8404 mpfr_clear(fval);
8405 }
8406 else if (nc.is_complex())
8407 {
8408 mpc_t cval;
8409 nc.get_complex(&cval);
8410 Complex_expression::export_complex(exp, cval);
8411 mpc_clear(cval);
8412 }
8413 else
8414 go_unreachable();
8415
8416 // A trailing space lets us reliably identify the end of the number.
8417 exp->write_c_string(" ");
8418 }
8419
8420 // Class Call_expression.
8421
8422 // A Go function can be viewed in a couple of different ways. The
8423 // code of a Go function becomes a backend function with parameters
8424 // whose types are simply the backend representation of the Go types.
8425 // If there are multiple results, they are returned as a backend
8426 // struct.
8427
8428 // However, when Go code refers to a function other than simply
8429 // calling it, the backend type of that function is actually a struct.
8430 // The first field of the struct points to the Go function code
8431 // (sometimes a wrapper as described below). The remaining fields
8432 // hold addresses of closed-over variables. This struct is called a
8433 // closure.
8434
8435 // There are a few cases to consider.
8436
8437 // A direct function call of a known function in package scope. In
8438 // this case there are no closed-over variables, and we know the name
8439 // of the function code. We can simply produce a backend call to the
8440 // function directly, and not worry about the closure.
8441
8442 // A direct function call of a known function literal. In this case
8443 // we know the function code and we know the closure. We generate the
8444 // function code such that it expects an additional final argument of
8445 // the closure type. We pass the closure as the last argument, after
8446 // the other arguments.
8447
8448 // An indirect function call. In this case we have a closure. We
8449 // load the pointer to the function code from the first field of the
8450 // closure. We pass the address of the closure as the last argument.
8451
8452 // A call to a method of an interface. Type methods are always at
8453 // package scope, so we call the function directly, and don't worry
8454 // about the closure.
8455
8456 // This means that for a function at package scope we have two cases.
8457 // One is the direct call, which has no closure. The other is the
8458 // indirect call, which does have a closure. We can't simply ignore
8459 // the closure, even though it is the last argument, because that will
8460 // fail on targets where the function pops its arguments. So when
8461 // generating a closure for a package-scope function we set the
8462 // function code pointer in the closure to point to a wrapper
8463 // function. This wrapper function accepts a final argument that
8464 // points to the closure, ignores it, and calls the real function as a
8465 // direct function call. This wrapper will normally be efficient, and
8466 // can often simply be a tail call to the real function.
8467
8468 // We don't use GCC's static chain pointer because 1) we don't need
8469 // it; 2) GCC only permits using a static chain to call a known
8470 // function, so we can't use it for an indirect call anyhow. Since we
8471 // can't use it for an indirect call, we may as well not worry about
8472 // using it for a direct call either.
8473
8474 // We pass the closure last rather than first because it means that
8475 // the function wrapper we put into a closure for a package-scope
8476 // function can normally just be a tail call to the real function.
8477
8478 // For method expressions we generate a wrapper that loads the
8479 // receiver from the closure and then calls the method. This
8480 // unfortunately forces reshuffling the arguments, since there is a
8481 // new first argument, but we can't avoid reshuffling either for
8482 // method expressions or for indirect calls of package-scope
8483 // functions, and since the latter are more common we reshuffle for
8484 // method expressions.
8485
8486 // Note that the Go code retains the Go types. The extra final
8487 // argument only appears when we convert to the backend
8488 // representation.
8489
8490 // Traversal.
8491
8492 int
8493 Call_expression::do_traverse(Traverse* traverse)
8494 {
8495 if (Expression::traverse(&this->fn_, traverse) == TRAVERSE_EXIT)
8496 return TRAVERSE_EXIT;
8497 if (this->args_ != NULL)
8498 {
8499 if (this->args_->traverse(traverse) == TRAVERSE_EXIT)
8500 return TRAVERSE_EXIT;
8501 }
8502 return TRAVERSE_CONTINUE;
8503 }
8504
8505 // Lower a call statement.
8506
8507 Expression*
8508 Call_expression::do_lower(Gogo* gogo, Named_object* function,
8509 Statement_inserter* inserter, int)
8510 {
8511 Location loc = this->location();
8512
8513 // A type cast can look like a function call.
8514 if (this->fn_->is_type_expression()
8515 && this->args_ != NULL
8516 && this->args_->size() == 1)
8517 return Expression::make_cast(this->fn_->type(), this->args_->front(),
8518 loc);
8519
8520 // Because do_type will return an error type and thus prevent future
8521 // errors, check for that case now to ensure that the error gets
8522 // reported.
8523 Function_type* fntype = this->get_function_type();
8524 if (fntype == NULL)
8525 {
8526 if (!this->fn_->type()->is_error())
8527 this->report_error(_("expected function"));
8528 this->set_is_error();
8529 return this;
8530 }
8531
8532 // Handle an argument which is a call to a function which returns
8533 // multiple results.
8534 if (this->args_ != NULL
8535 && this->args_->size() == 1
8536 && this->args_->front()->call_expression() != NULL)
8537 {
8538 size_t rc = this->args_->front()->call_expression()->result_count();
8539 if (rc > 1
8540 && ((fntype->parameters() != NULL
8541 && (fntype->parameters()->size() == rc
8542 || (fntype->is_varargs()
8543 && fntype->parameters()->size() - 1 <= rc)))
8544 || fntype->is_builtin()))
8545 {
8546 Call_expression* call = this->args_->front()->call_expression();
8547 call->set_is_multi_value_arg();
8548 if (this->is_varargs_)
8549 {
8550 // It is not clear which result of a multiple result call
8551 // the ellipsis operator should be applied to. If we unpack the
8552 // the call into its individual results here, the ellipsis will be
8553 // applied to the last result.
8554 error_at(call->location(),
8555 _("multiple-value argument in single-value context"));
8556 return Expression::make_error(call->location());
8557 }
8558
8559 Expression_list* args = new Expression_list;
8560 for (size_t i = 0; i < rc; ++i)
8561 args->push_back(Expression::make_call_result(call, i));
8562 // We can't return a new call expression here, because this
8563 // one may be referenced by Call_result expressions. We
8564 // also can't delete the old arguments, because we may still
8565 // traverse them somewhere up the call stack. FIXME.
8566 this->args_ = args;
8567 }
8568 }
8569
8570 // Recognize a call to a builtin function.
8571 if (fntype->is_builtin())
8572 return new Builtin_call_expression(gogo, this->fn_, this->args_,
8573 this->is_varargs_, loc);
8574
8575 // If this call returns multiple results, create a temporary
8576 // variable for each result.
8577 size_t rc = this->result_count();
8578 if (rc > 1 && this->results_ == NULL)
8579 {
8580 std::vector<Temporary_statement*>* temps =
8581 new std::vector<Temporary_statement*>;
8582 temps->reserve(rc);
8583 const Typed_identifier_list* results = fntype->results();
8584 for (Typed_identifier_list::const_iterator p = results->begin();
8585 p != results->end();
8586 ++p)
8587 {
8588 Temporary_statement* temp = Statement::make_temporary(p->type(),
8589 NULL, loc);
8590 inserter->insert(temp);
8591 temps->push_back(temp);
8592 }
8593 this->results_ = temps;
8594 }
8595
8596 // Handle a call to a varargs function by packaging up the extra
8597 // parameters.
8598 if (fntype->is_varargs())
8599 {
8600 const Typed_identifier_list* parameters = fntype->parameters();
8601 go_assert(parameters != NULL && !parameters->empty());
8602 Type* varargs_type = parameters->back().type();
8603 this->lower_varargs(gogo, function, inserter, varargs_type,
8604 parameters->size());
8605 }
8606
8607 // If this is call to a method, call the method directly passing the
8608 // object as the first parameter.
8609 Bound_method_expression* bme = this->fn_->bound_method_expression();
8610 if (bme != NULL)
8611 {
8612 Named_object* methodfn = bme->function();
8613 Expression* first_arg = bme->first_argument();
8614
8615 // We always pass a pointer when calling a method.
8616 if (first_arg->type()->points_to() == NULL
8617 && !first_arg->type()->is_error())
8618 {
8619 first_arg = Expression::make_unary(OPERATOR_AND, first_arg, loc);
8620 // We may need to create a temporary variable so that we can
8621 // take the address. We can't do that here because it will
8622 // mess up the order of evaluation.
8623 Unary_expression* ue = static_cast<Unary_expression*>(first_arg);
8624 ue->set_create_temp();
8625 }
8626
8627 // If we are calling a method which was inherited from an
8628 // embedded struct, and the method did not get a stub, then the
8629 // first type may be wrong.
8630 Type* fatype = bme->first_argument_type();
8631 if (fatype != NULL)
8632 {
8633 if (fatype->points_to() == NULL)
8634 fatype = Type::make_pointer_type(fatype);
8635 first_arg = Expression::make_unsafe_cast(fatype, first_arg, loc);
8636 }
8637
8638 Expression_list* new_args = new Expression_list();
8639 new_args->push_back(first_arg);
8640 if (this->args_ != NULL)
8641 {
8642 for (Expression_list::const_iterator p = this->args_->begin();
8643 p != this->args_->end();
8644 ++p)
8645 new_args->push_back(*p);
8646 }
8647
8648 // We have to change in place because this structure may be
8649 // referenced by Call_result_expressions. We can't delete the
8650 // old arguments, because we may be traversing them up in some
8651 // caller. FIXME.
8652 this->args_ = new_args;
8653 this->fn_ = Expression::make_func_reference(methodfn, NULL,
8654 bme->location());
8655 }
8656
8657 return this;
8658 }
8659
8660 // Lower a call to a varargs function. FUNCTION is the function in
8661 // which the call occurs--it's not the function we are calling.
8662 // VARARGS_TYPE is the type of the varargs parameter, a slice type.
8663 // PARAM_COUNT is the number of parameters of the function we are
8664 // calling; the last of these parameters will be the varargs
8665 // parameter.
8666
8667 void
8668 Call_expression::lower_varargs(Gogo* gogo, Named_object* function,
8669 Statement_inserter* inserter,
8670 Type* varargs_type, size_t param_count)
8671 {
8672 if (this->varargs_are_lowered_)
8673 return;
8674
8675 Location loc = this->location();
8676
8677 go_assert(param_count > 0);
8678 go_assert(varargs_type->is_slice_type());
8679
8680 size_t arg_count = this->args_ == NULL ? 0 : this->args_->size();
8681 if (arg_count < param_count - 1)
8682 {
8683 // Not enough arguments; will be caught in check_types.
8684 return;
8685 }
8686
8687 Expression_list* old_args = this->args_;
8688 Expression_list* new_args = new Expression_list();
8689 bool push_empty_arg = false;
8690 if (old_args == NULL || old_args->empty())
8691 {
8692 go_assert(param_count == 1);
8693 push_empty_arg = true;
8694 }
8695 else
8696 {
8697 Expression_list::const_iterator pa;
8698 int i = 1;
8699 for (pa = old_args->begin(); pa != old_args->end(); ++pa, ++i)
8700 {
8701 if (static_cast<size_t>(i) == param_count)
8702 break;
8703 new_args->push_back(*pa);
8704 }
8705
8706 // We have reached the varargs parameter.
8707
8708 bool issued_error = false;
8709 if (pa == old_args->end())
8710 push_empty_arg = true;
8711 else if (pa + 1 == old_args->end() && this->is_varargs_)
8712 new_args->push_back(*pa);
8713 else if (this->is_varargs_)
8714 {
8715 if ((*pa)->type()->is_slice_type())
8716 this->report_error(_("too many arguments"));
8717 else
8718 {
8719 error_at(this->location(),
8720 _("invalid use of %<...%> with non-slice"));
8721 this->set_is_error();
8722 }
8723 return;
8724 }
8725 else
8726 {
8727 Type* element_type = varargs_type->array_type()->element_type();
8728 Expression_list* vals = new Expression_list;
8729 for (; pa != old_args->end(); ++pa, ++i)
8730 {
8731 // Check types here so that we get a better message.
8732 Type* patype = (*pa)->type();
8733 Location paloc = (*pa)->location();
8734 if (!this->check_argument_type(i, element_type, patype,
8735 paloc, issued_error))
8736 continue;
8737 vals->push_back(*pa);
8738 }
8739 Expression* val =
8740 Expression::make_slice_composite_literal(varargs_type, vals, loc);
8741 gogo->lower_expression(function, inserter, &val);
8742 new_args->push_back(val);
8743 }
8744 }
8745
8746 if (push_empty_arg)
8747 new_args->push_back(Expression::make_nil(loc));
8748
8749 // We can't return a new call expression here, because this one may
8750 // be referenced by Call_result expressions. FIXME. We can't
8751 // delete OLD_ARGS because we may have both a Call_expression and a
8752 // Builtin_call_expression which refer to them. FIXME.
8753 this->args_ = new_args;
8754 this->varargs_are_lowered_ = true;
8755 }
8756
8757 // Flatten a call with multiple results into a temporary.
8758
8759 Expression*
8760 Call_expression::do_flatten(Gogo* gogo, Named_object*,
8761 Statement_inserter* inserter)
8762 {
8763 if (this->is_erroneous_call())
8764 {
8765 go_assert(saw_errors());
8766 return Expression::make_error(this->location());
8767 }
8768
8769 if (this->is_flattened_)
8770 return this;
8771 this->is_flattened_ = true;
8772
8773 // Add temporary variables for all arguments that require type
8774 // conversion.
8775 Function_type* fntype = this->get_function_type();
8776 if (fntype == NULL)
8777 {
8778 go_assert(saw_errors());
8779 return this;
8780 }
8781 if (this->args_ != NULL && !this->args_->empty()
8782 && fntype->parameters() != NULL && !fntype->parameters()->empty())
8783 {
8784 bool is_interface_method =
8785 this->fn_->interface_field_reference_expression() != NULL;
8786
8787 Expression_list *args = new Expression_list();
8788 Typed_identifier_list::const_iterator pp = fntype->parameters()->begin();
8789 Expression_list::const_iterator pa = this->args_->begin();
8790 if (!is_interface_method && fntype->is_method())
8791 {
8792 // The receiver argument.
8793 args->push_back(*pa);
8794 ++pa;
8795 }
8796 for (; pa != this->args_->end(); ++pa, ++pp)
8797 {
8798 go_assert(pp != fntype->parameters()->end());
8799 if (Type::are_identical(pp->type(), (*pa)->type(), true, NULL))
8800 args->push_back(*pa);
8801 else
8802 {
8803 Location loc = (*pa)->location();
8804 Expression* arg = *pa;
8805 if (!arg->is_variable())
8806 {
8807 Temporary_statement *temp =
8808 Statement::make_temporary(NULL, arg, loc);
8809 inserter->insert(temp);
8810 arg = Expression::make_temporary_reference(temp, loc);
8811 }
8812 arg = Expression::convert_for_assignment(gogo, pp->type(), arg,
8813 loc);
8814 args->push_back(arg);
8815 }
8816 }
8817 delete this->args_;
8818 this->args_ = args;
8819 }
8820
8821 size_t rc = this->result_count();
8822 if (rc > 1 && this->call_temp_ == NULL)
8823 {
8824 Struct_field_list* sfl = new Struct_field_list();
8825 Function_type* fntype = this->get_function_type();
8826 const Typed_identifier_list* results = fntype->results();
8827 Location loc = this->location();
8828
8829 int i = 0;
8830 char buf[10];
8831 for (Typed_identifier_list::const_iterator p = results->begin();
8832 p != results->end();
8833 ++p, ++i)
8834 {
8835 snprintf(buf, sizeof buf, "res%d", i);
8836 sfl->push_back(Struct_field(Typed_identifier(buf, p->type(), loc)));
8837 }
8838
8839 Struct_type* st = Type::make_struct_type(sfl, loc);
8840 this->call_temp_ = Statement::make_temporary(st, NULL, loc);
8841 inserter->insert(this->call_temp_);
8842 }
8843
8844 return this;
8845 }
8846
8847 // Get the function type. This can return NULL in error cases.
8848
8849 Function_type*
8850 Call_expression::get_function_type() const
8851 {
8852 return this->fn_->type()->function_type();
8853 }
8854
8855 // Return the number of values which this call will return.
8856
8857 size_t
8858 Call_expression::result_count() const
8859 {
8860 const Function_type* fntype = this->get_function_type();
8861 if (fntype == NULL)
8862 return 0;
8863 if (fntype->results() == NULL)
8864 return 0;
8865 return fntype->results()->size();
8866 }
8867
8868 // Return the temporary which holds a result.
8869
8870 Temporary_statement*
8871 Call_expression::result(size_t i) const
8872 {
8873 if (this->results_ == NULL || this->results_->size() <= i)
8874 {
8875 go_assert(saw_errors());
8876 return NULL;
8877 }
8878 return (*this->results_)[i];
8879 }
8880
8881 // Set the number of results expected from a call expression.
8882
8883 void
8884 Call_expression::set_expected_result_count(size_t count)
8885 {
8886 go_assert(this->expected_result_count_ == 0);
8887 this->expected_result_count_ = count;
8888 }
8889
8890 // Return whether this is a call to the predeclared function recover.
8891
8892 bool
8893 Call_expression::is_recover_call() const
8894 {
8895 return this->do_is_recover_call();
8896 }
8897
8898 // Set the argument to the recover function.
8899
8900 void
8901 Call_expression::set_recover_arg(Expression* arg)
8902 {
8903 this->do_set_recover_arg(arg);
8904 }
8905
8906 // Virtual functions also implemented by Builtin_call_expression.
8907
8908 bool
8909 Call_expression::do_is_recover_call() const
8910 {
8911 return false;
8912 }
8913
8914 void
8915 Call_expression::do_set_recover_arg(Expression*)
8916 {
8917 go_unreachable();
8918 }
8919
8920 // We have found an error with this call expression; return true if
8921 // we should report it.
8922
8923 bool
8924 Call_expression::issue_error()
8925 {
8926 if (this->issued_error_)
8927 return false;
8928 else
8929 {
8930 this->issued_error_ = true;
8931 return true;
8932 }
8933 }
8934
8935 // Whether or not this call contains errors, either in the call or the
8936 // arguments to the call.
8937
8938 bool
8939 Call_expression::is_erroneous_call()
8940 {
8941 if (this->is_error_expression() || this->fn()->is_error_expression())
8942 return true;
8943
8944 if (this->args() == NULL)
8945 return false;
8946 for (Expression_list::iterator pa = this->args()->begin();
8947 pa != this->args()->end();
8948 ++pa)
8949 {
8950 if ((*pa)->type()->is_error_type() || (*pa)->is_error_expression())
8951 return true;
8952 }
8953 return false;
8954 }
8955
8956 // Get the type.
8957
8958 Type*
8959 Call_expression::do_type()
8960 {
8961 if (this->type_ != NULL)
8962 return this->type_;
8963
8964 Type* ret;
8965 Function_type* fntype = this->get_function_type();
8966 if (fntype == NULL)
8967 return Type::make_error_type();
8968
8969 const Typed_identifier_list* results = fntype->results();
8970 if (results == NULL)
8971 ret = Type::make_void_type();
8972 else if (results->size() == 1)
8973 ret = results->begin()->type();
8974 else
8975 ret = Type::make_call_multiple_result_type(this);
8976
8977 this->type_ = ret;
8978
8979 return this->type_;
8980 }
8981
8982 // Determine types for a call expression. We can use the function
8983 // parameter types to set the types of the arguments.
8984
8985 void
8986 Call_expression::do_determine_type(const Type_context*)
8987 {
8988 if (!this->determining_types())
8989 return;
8990
8991 this->fn_->determine_type_no_context();
8992 Function_type* fntype = this->get_function_type();
8993 const Typed_identifier_list* parameters = NULL;
8994 if (fntype != NULL)
8995 parameters = fntype->parameters();
8996 if (this->args_ != NULL)
8997 {
8998 Typed_identifier_list::const_iterator pt;
8999 if (parameters != NULL)
9000 pt = parameters->begin();
9001 bool first = true;
9002 for (Expression_list::const_iterator pa = this->args_->begin();
9003 pa != this->args_->end();
9004 ++pa)
9005 {
9006 if (first)
9007 {
9008 first = false;
9009 // If this is a method, the first argument is the
9010 // receiver.
9011 if (fntype != NULL && fntype->is_method())
9012 {
9013 Type* rtype = fntype->receiver()->type();
9014 // The receiver is always passed as a pointer.
9015 if (rtype->points_to() == NULL)
9016 rtype = Type::make_pointer_type(rtype);
9017 Type_context subcontext(rtype, false);
9018 (*pa)->determine_type(&subcontext);
9019 continue;
9020 }
9021 }
9022
9023 if (parameters != NULL && pt != parameters->end())
9024 {
9025 Type_context subcontext(pt->type(), false);
9026 (*pa)->determine_type(&subcontext);
9027 ++pt;
9028 }
9029 else
9030 (*pa)->determine_type_no_context();
9031 }
9032 }
9033 }
9034
9035 // Called when determining types for a Call_expression. Return true
9036 // if we should go ahead, false if they have already been determined.
9037
9038 bool
9039 Call_expression::determining_types()
9040 {
9041 if (this->types_are_determined_)
9042 return false;
9043 else
9044 {
9045 this->types_are_determined_ = true;
9046 return true;
9047 }
9048 }
9049
9050 // Check types for parameter I.
9051
9052 bool
9053 Call_expression::check_argument_type(int i, const Type* parameter_type,
9054 const Type* argument_type,
9055 Location argument_location,
9056 bool issued_error)
9057 {
9058 std::string reason;
9059 if (!Type::are_assignable(parameter_type, argument_type, &reason))
9060 {
9061 if (!issued_error)
9062 {
9063 if (reason.empty())
9064 error_at(argument_location, "argument %d has incompatible type", i);
9065 else
9066 error_at(argument_location,
9067 "argument %d has incompatible type (%s)",
9068 i, reason.c_str());
9069 }
9070 this->set_is_error();
9071 return false;
9072 }
9073 return true;
9074 }
9075
9076 // Check types.
9077
9078 void
9079 Call_expression::do_check_types(Gogo*)
9080 {
9081 if (this->classification() == EXPRESSION_ERROR)
9082 return;
9083
9084 Function_type* fntype = this->get_function_type();
9085 if (fntype == NULL)
9086 {
9087 if (!this->fn_->type()->is_error())
9088 this->report_error(_("expected function"));
9089 return;
9090 }
9091
9092 if (this->expected_result_count_ != 0
9093 && this->expected_result_count_ != this->result_count())
9094 {
9095 if (this->issue_error())
9096 this->report_error(_("function result count mismatch"));
9097 this->set_is_error();
9098 return;
9099 }
9100
9101 bool is_method = fntype->is_method();
9102 if (is_method)
9103 {
9104 go_assert(this->args_ != NULL && !this->args_->empty());
9105 Type* rtype = fntype->receiver()->type();
9106 Expression* first_arg = this->args_->front();
9107 // We dereference the values since receivers are always passed
9108 // as pointers.
9109 std::string reason;
9110 if (!Type::are_assignable(rtype->deref(), first_arg->type()->deref(),
9111 &reason))
9112 {
9113 if (reason.empty())
9114 this->report_error(_("incompatible type for receiver"));
9115 else
9116 {
9117 error_at(this->location(),
9118 "incompatible type for receiver (%s)",
9119 reason.c_str());
9120 this->set_is_error();
9121 }
9122 }
9123 }
9124
9125 // Note that varargs was handled by the lower_varargs() method, so
9126 // we don't have to worry about it here unless something is wrong.
9127 if (this->is_varargs_ && !this->varargs_are_lowered_)
9128 {
9129 if (!fntype->is_varargs())
9130 {
9131 error_at(this->location(),
9132 _("invalid use of %<...%> calling non-variadic function"));
9133 this->set_is_error();
9134 return;
9135 }
9136 }
9137
9138 const Typed_identifier_list* parameters = fntype->parameters();
9139 if (this->args_ == NULL)
9140 {
9141 if (parameters != NULL && !parameters->empty())
9142 this->report_error(_("not enough arguments"));
9143 }
9144 else if (parameters == NULL)
9145 {
9146 if (!is_method || this->args_->size() > 1)
9147 this->report_error(_("too many arguments"));
9148 }
9149 else if (this->args_->size() == 1
9150 && this->args_->front()->call_expression() != NULL
9151 && this->args_->front()->call_expression()->result_count() > 1)
9152 {
9153 // This is F(G()) when G returns more than one result. If the
9154 // results can be matched to parameters, it would have been
9155 // lowered in do_lower. If we get here we know there is a
9156 // mismatch.
9157 if (this->args_->front()->call_expression()->result_count()
9158 < parameters->size())
9159 this->report_error(_("not enough arguments"));
9160 else
9161 this->report_error(_("too many arguments"));
9162 }
9163 else
9164 {
9165 int i = 0;
9166 Expression_list::const_iterator pa = this->args_->begin();
9167 if (is_method)
9168 ++pa;
9169 for (Typed_identifier_list::const_iterator pt = parameters->begin();
9170 pt != parameters->end();
9171 ++pt, ++pa, ++i)
9172 {
9173 if (pa == this->args_->end())
9174 {
9175 this->report_error(_("not enough arguments"));
9176 return;
9177 }
9178 this->check_argument_type(i + 1, pt->type(), (*pa)->type(),
9179 (*pa)->location(), false);
9180 }
9181 if (pa != this->args_->end())
9182 this->report_error(_("too many arguments"));
9183 }
9184 }
9185
9186 Expression*
9187 Call_expression::do_copy()
9188 {
9189 Call_expression* call =
9190 Expression::make_call(this->fn_->copy(),
9191 (this->args_ == NULL
9192 ? NULL
9193 : this->args_->copy()),
9194 this->is_varargs_, this->location());
9195
9196 if (this->varargs_are_lowered_)
9197 call->set_varargs_are_lowered();
9198 return call;
9199 }
9200
9201 // Return whether we have to use a temporary variable to ensure that
9202 // we evaluate this call expression in order. If the call returns no
9203 // results then it will inevitably be executed last.
9204
9205 bool
9206 Call_expression::do_must_eval_in_order() const
9207 {
9208 return this->result_count() > 0;
9209 }
9210
9211 // Get the function and the first argument to use when calling an
9212 // interface method.
9213
9214 Expression*
9215 Call_expression::interface_method_function(
9216 Interface_field_reference_expression* interface_method,
9217 Expression** first_arg_ptr)
9218 {
9219 *first_arg_ptr = interface_method->get_underlying_object();
9220 return interface_method->get_function();
9221 }
9222
9223 // Build the call expression.
9224
9225 Bexpression*
9226 Call_expression::do_get_backend(Translate_context* context)
9227 {
9228 if (this->call_ != NULL)
9229 return this->call_;
9230
9231 Function_type* fntype = this->get_function_type();
9232 if (fntype == NULL)
9233 return context->backend()->error_expression();
9234
9235 if (this->fn_->is_error_expression())
9236 return context->backend()->error_expression();
9237
9238 Gogo* gogo = context->gogo();
9239 Location location = this->location();
9240
9241 Func_expression* func = this->fn_->func_expression();
9242 Interface_field_reference_expression* interface_method =
9243 this->fn_->interface_field_reference_expression();
9244 const bool has_closure = func != NULL && func->closure() != NULL;
9245 const bool is_interface_method = interface_method != NULL;
9246
9247 bool has_closure_arg;
9248 if (has_closure)
9249 has_closure_arg = true;
9250 else if (func != NULL)
9251 has_closure_arg = false;
9252 else if (is_interface_method)
9253 has_closure_arg = false;
9254 else
9255 has_closure_arg = true;
9256
9257 int nargs;
9258 std::vector<Bexpression*> fn_args;
9259 if (this->args_ == NULL || this->args_->empty())
9260 {
9261 nargs = is_interface_method ? 1 : 0;
9262 if (nargs > 0)
9263 fn_args.resize(1);
9264 }
9265 else if (fntype->parameters() == NULL || fntype->parameters()->empty())
9266 {
9267 // Passing a receiver parameter.
9268 go_assert(!is_interface_method
9269 && fntype->is_method()
9270 && this->args_->size() == 1);
9271 nargs = 1;
9272 fn_args.resize(1);
9273 fn_args[0] = this->args_->front()->get_backend(context);
9274 }
9275 else
9276 {
9277 const Typed_identifier_list* params = fntype->parameters();
9278
9279 nargs = this->args_->size();
9280 int i = is_interface_method ? 1 : 0;
9281 nargs += i;
9282 fn_args.resize(nargs);
9283
9284 Typed_identifier_list::const_iterator pp = params->begin();
9285 Expression_list::const_iterator pe = this->args_->begin();
9286 if (!is_interface_method && fntype->is_method())
9287 {
9288 fn_args[i] = (*pe)->get_backend(context);
9289 ++pe;
9290 ++i;
9291 }
9292 for (; pe != this->args_->end(); ++pe, ++pp, ++i)
9293 {
9294 go_assert(pp != params->end());
9295 Expression* arg =
9296 Expression::convert_for_assignment(gogo, pp->type(), *pe,
9297 location);
9298 fn_args[i] = arg->get_backend(context);
9299 }
9300 go_assert(pp == params->end());
9301 go_assert(i == nargs);
9302 }
9303
9304 Expression* fn;
9305 Expression* closure = NULL;
9306 if (func != NULL)
9307 {
9308 Named_object* no = func->named_object();
9309 fn = Expression::make_func_code_reference(no, location);
9310 if (has_closure)
9311 closure = func->closure();
9312 }
9313 else if (!is_interface_method)
9314 {
9315 closure = this->fn_;
9316
9317 // The backend representation of this function type is a pointer
9318 // to a struct whose first field is the actual function to call.
9319 Type* pfntype =
9320 Type::make_pointer_type(
9321 Type::make_pointer_type(Type::make_void_type()));
9322 fn = Expression::make_unsafe_cast(pfntype, this->fn_, location);
9323 fn = Expression::make_unary(OPERATOR_MULT, fn, location);
9324 }
9325 else
9326 {
9327 Expression* first_arg;
9328 fn = this->interface_method_function(interface_method, &first_arg);
9329 fn_args[0] = first_arg->get_backend(context);
9330 }
9331
9332 Bexpression* bclosure = NULL;
9333 if (has_closure_arg)
9334 bclosure = closure->get_backend(context);
9335 else
9336 go_assert(closure == NULL);
9337
9338 Bexpression* bfn = fn->get_backend(context);
9339
9340 // When not calling a named function directly, use a type conversion
9341 // in case the type of the function is a recursive type which refers
9342 // to itself. We don't do this for an interface method because 1)
9343 // an interface method never refers to itself, so we always have a
9344 // function type here; 2) we pass an extra first argument to an
9345 // interface method, so fntype is not correct.
9346 if (func == NULL && !is_interface_method)
9347 {
9348 Btype* bft = fntype->get_backend_fntype(gogo);
9349 bfn = gogo->backend()->convert_expression(bft, bfn, location);
9350 }
9351
9352 Bexpression* call = gogo->backend()->call_expression(bfn, fn_args,
9353 bclosure, location);
9354
9355 if (this->results_ != NULL)
9356 {
9357 go_assert(this->call_temp_ != NULL);
9358 Expression* call_ref =
9359 Expression::make_temporary_reference(this->call_temp_, location);
9360 Bexpression* bcall_ref = call_ref->get_backend(context);
9361 Bstatement* assn_stmt =
9362 gogo->backend()->assignment_statement(bcall_ref, call, location);
9363
9364 this->call_ = this->set_results(context, bcall_ref);
9365
9366 Bexpression* set_and_call =
9367 gogo->backend()->compound_expression(assn_stmt, this->call_,
9368 location);
9369 return set_and_call;
9370 }
9371
9372 this->call_ = call;
9373 return this->call_;
9374 }
9375
9376 // Set the result variables if this call returns multiple results.
9377
9378 Bexpression*
9379 Call_expression::set_results(Translate_context* context, Bexpression* call)
9380 {
9381 Gogo* gogo = context->gogo();
9382
9383 Bexpression* results = NULL;
9384 Location loc = this->location();
9385
9386 size_t rc = this->result_count();
9387 for (size_t i = 0; i < rc; ++i)
9388 {
9389 Temporary_statement* temp = this->result(i);
9390 if (temp == NULL)
9391 {
9392 go_assert(saw_errors());
9393 return gogo->backend()->error_expression();
9394 }
9395 Temporary_reference_expression* ref =
9396 Expression::make_temporary_reference(temp, loc);
9397 ref->set_is_lvalue();
9398
9399 Bexpression* result_ref = ref->get_backend(context);
9400 Bexpression* call_result =
9401 gogo->backend()->struct_field_expression(call, i, loc);
9402 Bstatement* assn_stmt =
9403 gogo->backend()->assignment_statement(result_ref, call_result, loc);
9404
9405 Bexpression* result =
9406 gogo->backend()->compound_expression(assn_stmt, call_result, loc);
9407
9408 if (results == NULL)
9409 results = result;
9410 else
9411 {
9412 Bstatement* expr_stmt = gogo->backend()->expression_statement(result);
9413 results =
9414 gogo->backend()->compound_expression(expr_stmt, results, loc);
9415 }
9416 }
9417 return results;
9418 }
9419
9420 // Dump ast representation for a call expressin.
9421
9422 void
9423 Call_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
9424 {
9425 this->fn_->dump_expression(ast_dump_context);
9426 ast_dump_context->ostream() << "(";
9427 if (args_ != NULL)
9428 ast_dump_context->dump_expression_list(this->args_);
9429
9430 ast_dump_context->ostream() << ") ";
9431 }
9432
9433 // Make a call expression.
9434
9435 Call_expression*
9436 Expression::make_call(Expression* fn, Expression_list* args, bool is_varargs,
9437 Location location)
9438 {
9439 return new Call_expression(fn, args, is_varargs, location);
9440 }
9441
9442 // Class Call_result_expression.
9443
9444 // Traverse a call result.
9445
9446 int
9447 Call_result_expression::do_traverse(Traverse* traverse)
9448 {
9449 if (traverse->remember_expression(this->call_))
9450 {
9451 // We have already traversed the call expression.
9452 return TRAVERSE_CONTINUE;
9453 }
9454 return Expression::traverse(&this->call_, traverse);
9455 }
9456
9457 // Get the type.
9458
9459 Type*
9460 Call_result_expression::do_type()
9461 {
9462 if (this->classification() == EXPRESSION_ERROR)
9463 return Type::make_error_type();
9464
9465 // THIS->CALL_ can be replaced with a temporary reference due to
9466 // Call_expression::do_must_eval_in_order when there is an error.
9467 Call_expression* ce = this->call_->call_expression();
9468 if (ce == NULL)
9469 {
9470 this->set_is_error();
9471 return Type::make_error_type();
9472 }
9473 Function_type* fntype = ce->get_function_type();
9474 if (fntype == NULL)
9475 {
9476 if (ce->issue_error())
9477 {
9478 if (!ce->fn()->type()->is_error())
9479 this->report_error(_("expected function"));
9480 }
9481 this->set_is_error();
9482 return Type::make_error_type();
9483 }
9484 const Typed_identifier_list* results = fntype->results();
9485 if (results == NULL || results->size() < 2)
9486 {
9487 if (ce->issue_error())
9488 this->report_error(_("number of results does not match "
9489 "number of values"));
9490 return Type::make_error_type();
9491 }
9492 Typed_identifier_list::const_iterator pr = results->begin();
9493 for (unsigned int i = 0; i < this->index_; ++i)
9494 {
9495 if (pr == results->end())
9496 break;
9497 ++pr;
9498 }
9499 if (pr == results->end())
9500 {
9501 if (ce->issue_error())
9502 this->report_error(_("number of results does not match "
9503 "number of values"));
9504 return Type::make_error_type();
9505 }
9506 return pr->type();
9507 }
9508
9509 // Check the type. Just make sure that we trigger the warning in
9510 // do_type.
9511
9512 void
9513 Call_result_expression::do_check_types(Gogo*)
9514 {
9515 this->type();
9516 }
9517
9518 // Determine the type. We have nothing to do here, but the 0 result
9519 // needs to pass down to the caller.
9520
9521 void
9522 Call_result_expression::do_determine_type(const Type_context*)
9523 {
9524 this->call_->determine_type_no_context();
9525 }
9526
9527 // Return the backend representation. We just refer to the temporary set by the
9528 // call expression. We don't do this at lowering time because it makes it
9529 // hard to evaluate the call at the right time.
9530
9531 Bexpression*
9532 Call_result_expression::do_get_backend(Translate_context* context)
9533 {
9534 Call_expression* ce = this->call_->call_expression();
9535 if (ce == NULL)
9536 {
9537 go_assert(this->call_->is_error_expression());
9538 return context->backend()->error_expression();
9539 }
9540 Temporary_statement* ts = ce->result(this->index_);
9541 if (ts == NULL)
9542 {
9543 go_assert(saw_errors());
9544 return context->backend()->error_expression();
9545 }
9546 Expression* ref = Expression::make_temporary_reference(ts, this->location());
9547 return ref->get_backend(context);
9548 }
9549
9550 // Dump ast representation for a call result expression.
9551
9552 void
9553 Call_result_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9554 const
9555 {
9556 // FIXME: Wouldn't it be better if the call is assigned to a temporary
9557 // (struct) and the fields are referenced instead.
9558 ast_dump_context->ostream() << this->index_ << "@(";
9559 ast_dump_context->dump_expression(this->call_);
9560 ast_dump_context->ostream() << ")";
9561 }
9562
9563 // Make a reference to a single result of a call which returns
9564 // multiple results.
9565
9566 Expression*
9567 Expression::make_call_result(Call_expression* call, unsigned int index)
9568 {
9569 return new Call_result_expression(call, index);
9570 }
9571
9572 // Class Index_expression.
9573
9574 // Traversal.
9575
9576 int
9577 Index_expression::do_traverse(Traverse* traverse)
9578 {
9579 if (Expression::traverse(&this->left_, traverse) == TRAVERSE_EXIT
9580 || Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT
9581 || (this->end_ != NULL
9582 && Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9583 || (this->cap_ != NULL
9584 && Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT))
9585 return TRAVERSE_EXIT;
9586 return TRAVERSE_CONTINUE;
9587 }
9588
9589 // Lower an index expression. This converts the generic index
9590 // expression into an array index, a string index, or a map index.
9591
9592 Expression*
9593 Index_expression::do_lower(Gogo*, Named_object*, Statement_inserter*, int)
9594 {
9595 Location location = this->location();
9596 Expression* left = this->left_;
9597 Expression* start = this->start_;
9598 Expression* end = this->end_;
9599 Expression* cap = this->cap_;
9600
9601 Type* type = left->type();
9602 if (type->is_error())
9603 {
9604 go_assert(saw_errors());
9605 return Expression::make_error(location);
9606 }
9607 else if (left->is_type_expression())
9608 {
9609 error_at(location, "attempt to index type expression");
9610 return Expression::make_error(location);
9611 }
9612 else if (type->array_type() != NULL)
9613 return Expression::make_array_index(left, start, end, cap, location);
9614 else if (type->points_to() != NULL
9615 && type->points_to()->array_type() != NULL
9616 && !type->points_to()->is_slice_type())
9617 {
9618 Expression* deref = Expression::make_unary(OPERATOR_MULT, left,
9619 location);
9620
9621 // For an ordinary index into the array, the pointer will be
9622 // dereferenced. For a slice it will not--the resulting slice
9623 // will simply reuse the pointer, which is incorrect if that
9624 // pointer is nil.
9625 if (end != NULL || cap != NULL)
9626 deref->issue_nil_check();
9627
9628 return Expression::make_array_index(deref, start, end, cap, location);
9629 }
9630 else if (type->is_string_type())
9631 {
9632 if (cap != NULL)
9633 {
9634 error_at(location, "invalid 3-index slice of string");
9635 return Expression::make_error(location);
9636 }
9637 return Expression::make_string_index(left, start, end, location);
9638 }
9639 else if (type->map_type() != NULL)
9640 {
9641 if (end != NULL || cap != NULL)
9642 {
9643 error_at(location, "invalid slice of map");
9644 return Expression::make_error(location);
9645 }
9646 Map_index_expression* ret = Expression::make_map_index(left, start,
9647 location);
9648 if (this->is_lvalue_)
9649 ret->set_is_lvalue();
9650 return ret;
9651 }
9652 else
9653 {
9654 error_at(location,
9655 "attempt to index object which is not array, string, or map");
9656 return Expression::make_error(location);
9657 }
9658 }
9659
9660 // Write an indexed expression
9661 // (expr[expr:expr:expr], expr[expr:expr] or expr[expr]) to a dump context.
9662
9663 void
9664 Index_expression::dump_index_expression(Ast_dump_context* ast_dump_context,
9665 const Expression* expr,
9666 const Expression* start,
9667 const Expression* end,
9668 const Expression* cap)
9669 {
9670 expr->dump_expression(ast_dump_context);
9671 ast_dump_context->ostream() << "[";
9672 start->dump_expression(ast_dump_context);
9673 if (end != NULL)
9674 {
9675 ast_dump_context->ostream() << ":";
9676 end->dump_expression(ast_dump_context);
9677 }
9678 if (cap != NULL)
9679 {
9680 ast_dump_context->ostream() << ":";
9681 cap->dump_expression(ast_dump_context);
9682 }
9683 ast_dump_context->ostream() << "]";
9684 }
9685
9686 // Dump ast representation for an index expression.
9687
9688 void
9689 Index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
9690 const
9691 {
9692 Index_expression::dump_index_expression(ast_dump_context, this->left_,
9693 this->start_, this->end_, this->cap_);
9694 }
9695
9696 // Make an index expression.
9697
9698 Expression*
9699 Expression::make_index(Expression* left, Expression* start, Expression* end,
9700 Expression* cap, Location location)
9701 {
9702 return new Index_expression(left, start, end, cap, location);
9703 }
9704
9705 // Class Array_index_expression.
9706
9707 // Array index traversal.
9708
9709 int
9710 Array_index_expression::do_traverse(Traverse* traverse)
9711 {
9712 if (Expression::traverse(&this->array_, traverse) == TRAVERSE_EXIT)
9713 return TRAVERSE_EXIT;
9714 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
9715 return TRAVERSE_EXIT;
9716 if (this->end_ != NULL)
9717 {
9718 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
9719 return TRAVERSE_EXIT;
9720 }
9721 if (this->cap_ != NULL)
9722 {
9723 if (Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
9724 return TRAVERSE_EXIT;
9725 }
9726 return TRAVERSE_CONTINUE;
9727 }
9728
9729 // Return the type of an array index.
9730
9731 Type*
9732 Array_index_expression::do_type()
9733 {
9734 if (this->type_ == NULL)
9735 {
9736 Array_type* type = this->array_->type()->array_type();
9737 if (type == NULL)
9738 this->type_ = Type::make_error_type();
9739 else if (this->end_ == NULL)
9740 this->type_ = type->element_type();
9741 else if (type->is_slice_type())
9742 {
9743 // A slice of a slice has the same type as the original
9744 // slice.
9745 this->type_ = this->array_->type()->deref();
9746 }
9747 else
9748 {
9749 // A slice of an array is a slice.
9750 this->type_ = Type::make_array_type(type->element_type(), NULL);
9751 }
9752 }
9753 return this->type_;
9754 }
9755
9756 // Set the type of an array index.
9757
9758 void
9759 Array_index_expression::do_determine_type(const Type_context*)
9760 {
9761 this->array_->determine_type_no_context();
9762 this->start_->determine_type_no_context();
9763 if (this->end_ != NULL)
9764 this->end_->determine_type_no_context();
9765 if (this->cap_ != NULL)
9766 this->cap_->determine_type_no_context();
9767 }
9768
9769 // Check types of an array index.
9770
9771 void
9772 Array_index_expression::do_check_types(Gogo*)
9773 {
9774 Numeric_constant nc;
9775 unsigned long v;
9776 if (this->start_->type()->integer_type() == NULL
9777 && !this->start_->type()->is_error()
9778 && (!this->start_->numeric_constant_value(&nc)
9779 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9780 this->report_error(_("index must be integer"));
9781 if (this->end_ != NULL
9782 && this->end_->type()->integer_type() == NULL
9783 && !this->end_->type()->is_error()
9784 && !this->end_->is_nil_expression()
9785 && !this->end_->is_error_expression()
9786 && (!this->end_->numeric_constant_value(&nc)
9787 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9788 this->report_error(_("slice end must be integer"));
9789 if (this->cap_ != NULL
9790 && this->cap_->type()->integer_type() == NULL
9791 && !this->cap_->type()->is_error()
9792 && !this->cap_->is_nil_expression()
9793 && !this->cap_->is_error_expression()
9794 && (!this->cap_->numeric_constant_value(&nc)
9795 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
9796 this->report_error(_("slice capacity must be integer"));
9797
9798 Array_type* array_type = this->array_->type()->array_type();
9799 if (array_type == NULL)
9800 {
9801 go_assert(this->array_->type()->is_error());
9802 return;
9803 }
9804
9805 unsigned int int_bits =
9806 Type::lookup_integer_type("int")->integer_type()->bits();
9807
9808 Numeric_constant lvalnc;
9809 mpz_t lval;
9810 bool lval_valid = (array_type->length() != NULL
9811 && array_type->length()->numeric_constant_value(&lvalnc)
9812 && lvalnc.to_int(&lval));
9813 Numeric_constant inc;
9814 mpz_t ival;
9815 bool ival_valid = false;
9816 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
9817 {
9818 ival_valid = true;
9819 if (mpz_sgn(ival) < 0
9820 || mpz_sizeinbase(ival, 2) >= int_bits
9821 || (lval_valid
9822 && (this->end_ == NULL
9823 ? mpz_cmp(ival, lval) >= 0
9824 : mpz_cmp(ival, lval) > 0)))
9825 {
9826 error_at(this->start_->location(), "array index out of bounds");
9827 this->set_is_error();
9828 }
9829 }
9830 if (this->end_ != NULL && !this->end_->is_nil_expression())
9831 {
9832 Numeric_constant enc;
9833 mpz_t eval;
9834 bool eval_valid = false;
9835 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
9836 {
9837 eval_valid = true;
9838 if (mpz_sgn(eval) < 0
9839 || mpz_sizeinbase(eval, 2) >= int_bits
9840 || (lval_valid && mpz_cmp(eval, lval) > 0))
9841 {
9842 error_at(this->end_->location(), "array index out of bounds");
9843 this->set_is_error();
9844 }
9845 else if (ival_valid && mpz_cmp(ival, eval) > 0)
9846 this->report_error(_("inverted slice range"));
9847 }
9848
9849 Numeric_constant cnc;
9850 mpz_t cval;
9851 if (this->cap_ != NULL
9852 && this->cap_->numeric_constant_value(&cnc) && cnc.to_int(&cval))
9853 {
9854 if (mpz_sgn(cval) < 0
9855 || mpz_sizeinbase(cval, 2) >= int_bits
9856 || (lval_valid && mpz_cmp(cval, lval) > 0))
9857 {
9858 error_at(this->cap_->location(), "array index out of bounds");
9859 this->set_is_error();
9860 }
9861 else if (ival_valid && mpz_cmp(ival, cval) > 0)
9862 {
9863 error_at(this->cap_->location(),
9864 "invalid slice index: capacity less than start");
9865 this->set_is_error();
9866 }
9867 else if (eval_valid && mpz_cmp(eval, cval) > 0)
9868 {
9869 error_at(this->cap_->location(),
9870 "invalid slice index: capacity less than length");
9871 this->set_is_error();
9872 }
9873 mpz_clear(cval);
9874 }
9875
9876 if (eval_valid)
9877 mpz_clear(eval);
9878 }
9879 if (ival_valid)
9880 mpz_clear(ival);
9881 if (lval_valid)
9882 mpz_clear(lval);
9883
9884 // A slice of an array requires an addressable array. A slice of a
9885 // slice is always possible.
9886 if (this->end_ != NULL && !array_type->is_slice_type())
9887 {
9888 if (!this->array_->is_addressable())
9889 this->report_error(_("slice of unaddressable value"));
9890 else
9891 this->array_->address_taken(true);
9892 }
9893 }
9894
9895 // Flatten array indexing by using temporary variables for slices and indexes.
9896
9897 Expression*
9898 Array_index_expression::do_flatten(Gogo*, Named_object*,
9899 Statement_inserter* inserter)
9900 {
9901 Location loc = this->location();
9902 Expression* array = this->array_;
9903 Expression* start = this->start_;
9904 Expression* end = this->end_;
9905 Expression* cap = this->cap_;
9906 if (array->is_error_expression()
9907 || array->type()->is_error_type()
9908 || start->is_error_expression()
9909 || start->type()->is_error_type()
9910 || (end != NULL
9911 && (end->is_error_expression() || end->type()->is_error_type()))
9912 || (cap != NULL
9913 && (cap->is_error_expression() || cap->type()->is_error_type())))
9914 {
9915 go_assert(saw_errors());
9916 return Expression::make_error(loc);
9917 }
9918
9919 Temporary_statement* temp;
9920 if (array->type()->is_slice_type() && !array->is_variable())
9921 {
9922 temp = Statement::make_temporary(NULL, array, loc);
9923 inserter->insert(temp);
9924 this->array_ = Expression::make_temporary_reference(temp, loc);
9925 }
9926 if (!start->is_variable())
9927 {
9928 temp = Statement::make_temporary(NULL, start, loc);
9929 inserter->insert(temp);
9930 this->start_ = Expression::make_temporary_reference(temp, loc);
9931 }
9932 if (end != NULL
9933 && !end->is_nil_expression()
9934 && !end->is_variable())
9935 {
9936 temp = Statement::make_temporary(NULL, end, loc);
9937 inserter->insert(temp);
9938 this->end_ = Expression::make_temporary_reference(temp, loc);
9939 }
9940 if (cap!= NULL && !cap->is_variable())
9941 {
9942 temp = Statement::make_temporary(NULL, cap, loc);
9943 inserter->insert(temp);
9944 this->cap_ = Expression::make_temporary_reference(temp, loc);
9945 }
9946
9947 return this;
9948 }
9949
9950 // Return whether this expression is addressable.
9951
9952 bool
9953 Array_index_expression::do_is_addressable() const
9954 {
9955 // A slice expression is not addressable.
9956 if (this->end_ != NULL)
9957 return false;
9958
9959 // An index into a slice is addressable.
9960 if (this->array_->type()->is_slice_type())
9961 return true;
9962
9963 // An index into an array is addressable if the array is
9964 // addressable.
9965 return this->array_->is_addressable();
9966 }
9967
9968 // Get the backend representation for an array index.
9969
9970 Bexpression*
9971 Array_index_expression::do_get_backend(Translate_context* context)
9972 {
9973 Array_type* array_type = this->array_->type()->array_type();
9974 if (array_type == NULL)
9975 {
9976 go_assert(this->array_->type()->is_error());
9977 return context->backend()->error_expression();
9978 }
9979 go_assert(!array_type->is_slice_type() || this->array_->is_variable());
9980
9981 Location loc = this->location();
9982 Gogo* gogo = context->gogo();
9983
9984 Type* int_type = Type::lookup_integer_type("int");
9985 Btype* int_btype = int_type->get_backend(gogo);
9986
9987 // We need to convert the length and capacity to the Go "int" type here
9988 // because the length of a fixed-length array could be of type "uintptr"
9989 // and gimple disallows binary operations between "uintptr" and other
9990 // integer types. FIXME.
9991 Bexpression* length = NULL;
9992 if (this->end_ == NULL || this->end_->is_nil_expression())
9993 {
9994 Expression* len = array_type->get_length(gogo, this->array_);
9995 length = len->get_backend(context);
9996 length = gogo->backend()->convert_expression(int_btype, length, loc);
9997 }
9998
9999 Bexpression* capacity = NULL;
10000 if (this->end_ != NULL)
10001 {
10002 Expression* cap = array_type->get_capacity(gogo, this->array_);
10003 capacity = cap->get_backend(context);
10004 capacity = gogo->backend()->convert_expression(int_btype, capacity, loc);
10005 }
10006
10007 Bexpression* cap_arg = capacity;
10008 if (this->cap_ != NULL)
10009 {
10010 cap_arg = this->cap_->get_backend(context);
10011 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10012 }
10013
10014 if (length == NULL)
10015 length = cap_arg;
10016
10017 int code = (array_type->length() != NULL
10018 ? (this->end_ == NULL
10019 ? RUNTIME_ERROR_ARRAY_INDEX_OUT_OF_BOUNDS
10020 : RUNTIME_ERROR_ARRAY_SLICE_OUT_OF_BOUNDS)
10021 : (this->end_ == NULL
10022 ? RUNTIME_ERROR_SLICE_INDEX_OUT_OF_BOUNDS
10023 : RUNTIME_ERROR_SLICE_SLICE_OUT_OF_BOUNDS));
10024 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10025
10026 if (this->start_->type()->integer_type() == NULL
10027 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10028 {
10029 go_assert(saw_errors());
10030 return context->backend()->error_expression();
10031 }
10032
10033 Bexpression* bad_index =
10034 Expression::check_bounds(this->start_, loc)->get_backend(context);
10035
10036 Bexpression* start = this->start_->get_backend(context);
10037 start = gogo->backend()->convert_expression(int_btype, start, loc);
10038 Bexpression* start_too_large =
10039 gogo->backend()->binary_expression((this->end_ == NULL
10040 ? OPERATOR_GE
10041 : OPERATOR_GT),
10042 start,
10043 (this->end_ == NULL
10044 ? length
10045 : capacity),
10046 loc);
10047 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, start_too_large,
10048 bad_index, loc);
10049
10050 if (this->end_ == NULL)
10051 {
10052 // Simple array indexing. This has to return an l-value, so
10053 // wrap the index check into START.
10054 start =
10055 gogo->backend()->conditional_expression(int_btype, bad_index,
10056 crash, start, loc);
10057
10058 Bexpression* ret;
10059 if (array_type->length() != NULL)
10060 {
10061 Bexpression* array = this->array_->get_backend(context);
10062 ret = gogo->backend()->array_index_expression(array, start, loc);
10063 }
10064 else
10065 {
10066 // Slice.
10067 Expression* valptr =
10068 array_type->get_value_pointer(gogo, this->array_);
10069 Bexpression* ptr = valptr->get_backend(context);
10070 ptr = gogo->backend()->pointer_offset_expression(ptr, start, loc);
10071
10072 Type* ele_type = this->array_->type()->array_type()->element_type();
10073 Btype* ele_btype = ele_type->get_backend(gogo);
10074 ret = gogo->backend()->indirect_expression(ele_btype, ptr, true, loc);
10075 }
10076 return ret;
10077 }
10078
10079 // Array slice.
10080
10081 if (this->cap_ != NULL)
10082 {
10083 Bexpression* bounds_bcheck =
10084 Expression::check_bounds(this->cap_, loc)->get_backend(context);
10085 bad_index =
10086 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10087 bad_index, loc);
10088 cap_arg = gogo->backend()->convert_expression(int_btype, cap_arg, loc);
10089
10090 Bexpression* cap_too_small =
10091 gogo->backend()->binary_expression(OPERATOR_LT, cap_arg, start, loc);
10092 Bexpression* cap_too_large =
10093 gogo->backend()->binary_expression(OPERATOR_GT, cap_arg, capacity, loc);
10094 Bexpression* bad_cap =
10095 gogo->backend()->binary_expression(OPERATOR_OROR, cap_too_small,
10096 cap_too_large, loc);
10097 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_cap,
10098 bad_index, loc);
10099 }
10100
10101 Bexpression* end;
10102 if (this->end_->is_nil_expression())
10103 end = length;
10104 else
10105 {
10106 Bexpression* bounds_bcheck =
10107 Expression::check_bounds(this->end_, loc)->get_backend(context);
10108
10109 bad_index =
10110 gogo->backend()->binary_expression(OPERATOR_OROR, bounds_bcheck,
10111 bad_index, loc);
10112
10113 end = this->end_->get_backend(context);
10114 end = gogo->backend()->convert_expression(int_btype, end, loc);
10115 Bexpression* end_too_small =
10116 gogo->backend()->binary_expression(OPERATOR_LT, end, start, loc);
10117 Bexpression* end_too_large =
10118 gogo->backend()->binary_expression(OPERATOR_GT, end, cap_arg, loc);
10119 Bexpression* bad_end =
10120 gogo->backend()->binary_expression(OPERATOR_OROR, end_too_small,
10121 end_too_large, loc);
10122 bad_index = gogo->backend()->binary_expression(OPERATOR_OROR, bad_end,
10123 bad_index, loc);
10124 }
10125
10126 Expression* valptr = array_type->get_value_pointer(gogo, this->array_);
10127 Bexpression* val = valptr->get_backend(context);
10128 val = gogo->backend()->pointer_offset_expression(val, start, loc);
10129
10130 Bexpression* result_length =
10131 gogo->backend()->binary_expression(OPERATOR_MINUS, end, start, loc);
10132
10133 Bexpression* result_capacity =
10134 gogo->backend()->binary_expression(OPERATOR_MINUS, cap_arg, start, loc);
10135
10136 Btype* struct_btype = this->type()->get_backend(gogo);
10137 std::vector<Bexpression*> init;
10138 init.push_back(val);
10139 init.push_back(result_length);
10140 init.push_back(result_capacity);
10141
10142 Bexpression* ctor =
10143 gogo->backend()->constructor_expression(struct_btype, init, loc);
10144 return gogo->backend()->conditional_expression(struct_btype, bad_index,
10145 crash, ctor, loc);
10146 }
10147
10148 // Dump ast representation for an array index expression.
10149
10150 void
10151 Array_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10152 const
10153 {
10154 Index_expression::dump_index_expression(ast_dump_context, this->array_,
10155 this->start_, this->end_, this->cap_);
10156 }
10157
10158 // Make an array index expression. END and CAP may be NULL.
10159
10160 Expression*
10161 Expression::make_array_index(Expression* array, Expression* start,
10162 Expression* end, Expression* cap,
10163 Location location)
10164 {
10165 return new Array_index_expression(array, start, end, cap, location);
10166 }
10167
10168 // A string index. This is used for both indexing and slicing.
10169
10170 class String_index_expression : public Expression
10171 {
10172 public:
10173 String_index_expression(Expression* string, Expression* start,
10174 Expression* end, Location location)
10175 : Expression(EXPRESSION_STRING_INDEX, location),
10176 string_(string), start_(start), end_(end)
10177 { }
10178
10179 protected:
10180 int
10181 do_traverse(Traverse*);
10182
10183 Expression*
10184 do_flatten(Gogo*, Named_object*, Statement_inserter*);
10185
10186 Type*
10187 do_type();
10188
10189 void
10190 do_determine_type(const Type_context*);
10191
10192 void
10193 do_check_types(Gogo*);
10194
10195 Expression*
10196 do_copy()
10197 {
10198 return Expression::make_string_index(this->string_->copy(),
10199 this->start_->copy(),
10200 (this->end_ == NULL
10201 ? NULL
10202 : this->end_->copy()),
10203 this->location());
10204 }
10205
10206 bool
10207 do_must_eval_subexpressions_in_order(int* skip) const
10208 {
10209 *skip = 1;
10210 return true;
10211 }
10212
10213 Bexpression*
10214 do_get_backend(Translate_context*);
10215
10216 void
10217 do_dump_expression(Ast_dump_context*) const;
10218
10219 private:
10220 // The string we are getting a value from.
10221 Expression* string_;
10222 // The start or only index.
10223 Expression* start_;
10224 // The end index of a slice. This may be NULL for a single index,
10225 // or it may be a nil expression for the length of the string.
10226 Expression* end_;
10227 };
10228
10229 // String index traversal.
10230
10231 int
10232 String_index_expression::do_traverse(Traverse* traverse)
10233 {
10234 if (Expression::traverse(&this->string_, traverse) == TRAVERSE_EXIT)
10235 return TRAVERSE_EXIT;
10236 if (Expression::traverse(&this->start_, traverse) == TRAVERSE_EXIT)
10237 return TRAVERSE_EXIT;
10238 if (this->end_ != NULL)
10239 {
10240 if (Expression::traverse(&this->end_, traverse) == TRAVERSE_EXIT)
10241 return TRAVERSE_EXIT;
10242 }
10243 return TRAVERSE_CONTINUE;
10244 }
10245
10246 Expression*
10247 String_index_expression::do_flatten(Gogo*, Named_object*,
10248 Statement_inserter* inserter)
10249 {
10250 Location loc = this->location();
10251 Expression* string = this->string_;
10252 Expression* start = this->start_;
10253 Expression* end = this->end_;
10254 if (string->is_error_expression()
10255 || string->type()->is_error_type()
10256 || start->is_error_expression()
10257 || start->type()->is_error_type()
10258 || (end != NULL
10259 && (end->is_error_expression() || end->type()->is_error_type())))
10260 {
10261 go_assert(saw_errors());
10262 return Expression::make_error(loc);
10263 }
10264
10265 Temporary_statement* temp;
10266 if (!this->string_->is_variable())
10267 {
10268 temp = Statement::make_temporary(NULL, this->string_, loc);
10269 inserter->insert(temp);
10270 this->string_ = Expression::make_temporary_reference(temp, loc);
10271 }
10272 if (!this->start_->is_variable())
10273 {
10274 temp = Statement::make_temporary(NULL, this->start_, loc);
10275 inserter->insert(temp);
10276 this->start_ = Expression::make_temporary_reference(temp, loc);
10277 }
10278 if (this->end_ != NULL
10279 && !this->end_->is_nil_expression()
10280 && !this->end_->is_variable())
10281 {
10282 temp = Statement::make_temporary(NULL, this->end_, loc);
10283 inserter->insert(temp);
10284 this->end_ = Expression::make_temporary_reference(temp, loc);
10285 }
10286
10287 return this;
10288 }
10289
10290 // Return the type of a string index.
10291
10292 Type*
10293 String_index_expression::do_type()
10294 {
10295 if (this->end_ == NULL)
10296 return Type::lookup_integer_type("uint8");
10297 else
10298 return this->string_->type();
10299 }
10300
10301 // Determine the type of a string index.
10302
10303 void
10304 String_index_expression::do_determine_type(const Type_context*)
10305 {
10306 this->string_->determine_type_no_context();
10307 this->start_->determine_type_no_context();
10308 if (this->end_ != NULL)
10309 this->end_->determine_type_no_context();
10310 }
10311
10312 // Check types of a string index.
10313
10314 void
10315 String_index_expression::do_check_types(Gogo*)
10316 {
10317 Numeric_constant nc;
10318 unsigned long v;
10319 if (this->start_->type()->integer_type() == NULL
10320 && !this->start_->type()->is_error()
10321 && (!this->start_->numeric_constant_value(&nc)
10322 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10323 this->report_error(_("index must be integer"));
10324 if (this->end_ != NULL
10325 && this->end_->type()->integer_type() == NULL
10326 && !this->end_->type()->is_error()
10327 && !this->end_->is_nil_expression()
10328 && !this->end_->is_error_expression()
10329 && (!this->end_->numeric_constant_value(&nc)
10330 || nc.to_unsigned_long(&v) == Numeric_constant::NC_UL_NOTINT))
10331 this->report_error(_("slice end must be integer"));
10332
10333 std::string sval;
10334 bool sval_valid = this->string_->string_constant_value(&sval);
10335
10336 Numeric_constant inc;
10337 mpz_t ival;
10338 bool ival_valid = false;
10339 if (this->start_->numeric_constant_value(&inc) && inc.to_int(&ival))
10340 {
10341 ival_valid = true;
10342 if (mpz_sgn(ival) < 0
10343 || (sval_valid
10344 && (this->end_ == NULL
10345 ? mpz_cmp_ui(ival, sval.length()) >= 0
10346 : mpz_cmp_ui(ival, sval.length()) > 0)))
10347 {
10348 error_at(this->start_->location(), "string index out of bounds");
10349 this->set_is_error();
10350 }
10351 }
10352 if (this->end_ != NULL && !this->end_->is_nil_expression())
10353 {
10354 Numeric_constant enc;
10355 mpz_t eval;
10356 if (this->end_->numeric_constant_value(&enc) && enc.to_int(&eval))
10357 {
10358 if (mpz_sgn(eval) < 0
10359 || (sval_valid && mpz_cmp_ui(eval, sval.length()) > 0))
10360 {
10361 error_at(this->end_->location(), "string index out of bounds");
10362 this->set_is_error();
10363 }
10364 else if (ival_valid && mpz_cmp(ival, eval) > 0)
10365 this->report_error(_("inverted slice range"));
10366 mpz_clear(eval);
10367 }
10368 }
10369 if (ival_valid)
10370 mpz_clear(ival);
10371 }
10372
10373 // Get the backend representation for a string index.
10374
10375 Bexpression*
10376 String_index_expression::do_get_backend(Translate_context* context)
10377 {
10378 Location loc = this->location();
10379 Expression* string_arg = this->string_;
10380 if (this->string_->type()->points_to() != NULL)
10381 string_arg = Expression::make_unary(OPERATOR_MULT, this->string_, loc);
10382
10383 Expression* bad_index = Expression::check_bounds(this->start_, loc);
10384
10385 int code = (this->end_ == NULL
10386 ? RUNTIME_ERROR_STRING_INDEX_OUT_OF_BOUNDS
10387 : RUNTIME_ERROR_STRING_SLICE_OUT_OF_BOUNDS);
10388
10389 Gogo* gogo = context->gogo();
10390 Bexpression* crash = gogo->runtime_error(code, loc)->get_backend(context);
10391
10392 Type* int_type = Type::lookup_integer_type("int");
10393
10394 // It is possible that an error occurred earlier because the start index
10395 // cannot be represented as an integer type. In this case, we shouldn't
10396 // try casting the starting index into an integer since
10397 // Type_conversion_expression will fail to get the backend representation.
10398 // FIXME.
10399 if (this->start_->type()->integer_type() == NULL
10400 && !Type::are_convertible(int_type, this->start_->type(), NULL))
10401 {
10402 go_assert(saw_errors());
10403 return context->backend()->error_expression();
10404 }
10405
10406 Expression* start = Expression::make_cast(int_type, this->start_, loc);
10407
10408 if (this->end_ == NULL)
10409 {
10410 Expression* length =
10411 Expression::make_string_info(this->string_, STRING_INFO_LENGTH, loc);
10412
10413 Expression* start_too_large =
10414 Expression::make_binary(OPERATOR_GE, start, length, loc);
10415 bad_index = Expression::make_binary(OPERATOR_OROR, start_too_large,
10416 bad_index, loc);
10417 Expression* bytes =
10418 Expression::make_string_info(this->string_, STRING_INFO_DATA, loc);
10419
10420 Bexpression* bstart = start->get_backend(context);
10421 Bexpression* ptr = bytes->get_backend(context);
10422 ptr = gogo->backend()->pointer_offset_expression(ptr, bstart, loc);
10423 Btype* ubtype = Type::lookup_integer_type("uint8")->get_backend(gogo);
10424 Bexpression* index =
10425 gogo->backend()->indirect_expression(ubtype, ptr, true, loc);
10426
10427 Btype* byte_btype = bytes->type()->points_to()->get_backend(gogo);
10428 Bexpression* index_error = bad_index->get_backend(context);
10429 return gogo->backend()->conditional_expression(byte_btype, index_error,
10430 crash, index, loc);
10431 }
10432
10433 Expression* end = NULL;
10434 if (this->end_->is_nil_expression())
10435 end = Expression::make_integer_sl(-1, int_type, loc);
10436 else
10437 {
10438 Expression* bounds_check = Expression::check_bounds(this->end_, loc);
10439 bad_index =
10440 Expression::make_binary(OPERATOR_OROR, bounds_check, bad_index, loc);
10441 end = Expression::make_cast(int_type, this->end_, loc);
10442 }
10443
10444 Expression* strslice = Runtime::make_call(Runtime::STRING_SLICE, loc, 3,
10445 string_arg, start, end);
10446 Bexpression* bstrslice = strslice->get_backend(context);
10447
10448 Btype* str_btype = strslice->type()->get_backend(gogo);
10449 Bexpression* index_error = bad_index->get_backend(context);
10450 return gogo->backend()->conditional_expression(str_btype, index_error,
10451 crash, bstrslice, loc);
10452 }
10453
10454 // Dump ast representation for a string index expression.
10455
10456 void
10457 String_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10458 const
10459 {
10460 Index_expression::dump_index_expression(ast_dump_context, this->string_,
10461 this->start_, this->end_, NULL);
10462 }
10463
10464 // Make a string index expression. END may be NULL.
10465
10466 Expression*
10467 Expression::make_string_index(Expression* string, Expression* start,
10468 Expression* end, Location location)
10469 {
10470 return new String_index_expression(string, start, end, location);
10471 }
10472
10473 // Class Map_index.
10474
10475 // Get the type of the map.
10476
10477 Map_type*
10478 Map_index_expression::get_map_type() const
10479 {
10480 Map_type* mt = this->map_->type()->deref()->map_type();
10481 if (mt == NULL)
10482 go_assert(saw_errors());
10483 return mt;
10484 }
10485
10486 // Map index traversal.
10487
10488 int
10489 Map_index_expression::do_traverse(Traverse* traverse)
10490 {
10491 if (Expression::traverse(&this->map_, traverse) == TRAVERSE_EXIT)
10492 return TRAVERSE_EXIT;
10493 return Expression::traverse(&this->index_, traverse);
10494 }
10495
10496 // We need to pass in a pointer to the key, so flatten the index into a
10497 // temporary variable if it isn't already. The value pointer will be
10498 // dereferenced and checked for nil, so flatten into a temporary to avoid
10499 // recomputation.
10500
10501 Expression*
10502 Map_index_expression::do_flatten(Gogo* gogo, Named_object*,
10503 Statement_inserter* inserter)
10504 {
10505 Location loc = this->location();
10506 Map_type* mt = this->get_map_type();
10507 if (this->index()->is_error_expression()
10508 || this->index()->type()->is_error_type()
10509 || mt->is_error_type())
10510 {
10511 go_assert(saw_errors());
10512 return Expression::make_error(loc);
10513 }
10514
10515 if (!Type::are_identical(mt->key_type(), this->index_->type(), false, NULL))
10516 {
10517 if (this->index_->type()->interface_type() != NULL
10518 && !this->index_->is_variable())
10519 {
10520 Temporary_statement* temp =
10521 Statement::make_temporary(NULL, this->index_, loc);
10522 inserter->insert(temp);
10523 this->index_ = Expression::make_temporary_reference(temp, loc);
10524 }
10525 this->index_ = Expression::convert_for_assignment(gogo, mt->key_type(),
10526 this->index_, loc);
10527 }
10528
10529 if (!this->index_->is_variable())
10530 {
10531 Temporary_statement* temp = Statement::make_temporary(NULL, this->index_,
10532 loc);
10533 inserter->insert(temp);
10534 this->index_ = Expression::make_temporary_reference(temp, loc);
10535 }
10536
10537 if (this->value_pointer_ == NULL)
10538 this->get_value_pointer(this->is_lvalue_);
10539 if (this->value_pointer_->is_error_expression()
10540 || this->value_pointer_->type()->is_error_type())
10541 return Expression::make_error(loc);
10542 if (!this->value_pointer_->is_variable())
10543 {
10544 Temporary_statement* temp =
10545 Statement::make_temporary(NULL, this->value_pointer_, loc);
10546 inserter->insert(temp);
10547 this->value_pointer_ = Expression::make_temporary_reference(temp, loc);
10548 }
10549
10550 return this;
10551 }
10552
10553 // Return the type of a map index.
10554
10555 Type*
10556 Map_index_expression::do_type()
10557 {
10558 Map_type* mt = this->get_map_type();
10559 if (mt == NULL)
10560 return Type::make_error_type();
10561 Type* type = mt->val_type();
10562 // If this map index is in a tuple assignment, we actually return a
10563 // pointer to the value type. Tuple_map_assignment_statement is
10564 // responsible for handling this correctly. We need to get the type
10565 // right in case this gets assigned to a temporary variable.
10566 if (this->is_in_tuple_assignment_)
10567 type = Type::make_pointer_type(type);
10568 return type;
10569 }
10570
10571 // Fix the type of a map index.
10572
10573 void
10574 Map_index_expression::do_determine_type(const Type_context*)
10575 {
10576 this->map_->determine_type_no_context();
10577 Map_type* mt = this->get_map_type();
10578 Type* key_type = mt == NULL ? NULL : mt->key_type();
10579 Type_context subcontext(key_type, false);
10580 this->index_->determine_type(&subcontext);
10581 }
10582
10583 // Check types of a map index.
10584
10585 void
10586 Map_index_expression::do_check_types(Gogo*)
10587 {
10588 std::string reason;
10589 Map_type* mt = this->get_map_type();
10590 if (mt == NULL)
10591 return;
10592 if (!Type::are_assignable(mt->key_type(), this->index_->type(), &reason))
10593 {
10594 if (reason.empty())
10595 this->report_error(_("incompatible type for map index"));
10596 else
10597 {
10598 error_at(this->location(), "incompatible type for map index (%s)",
10599 reason.c_str());
10600 this->set_is_error();
10601 }
10602 }
10603 }
10604
10605 // Get the backend representation for a map index.
10606
10607 Bexpression*
10608 Map_index_expression::do_get_backend(Translate_context* context)
10609 {
10610 Map_type* type = this->get_map_type();
10611 if (type == NULL)
10612 {
10613 go_assert(saw_errors());
10614 return context->backend()->error_expression();
10615 }
10616
10617 go_assert(this->value_pointer_ != NULL
10618 && this->value_pointer_->is_variable());
10619
10620 Bexpression* ret;
10621 if (this->is_lvalue_)
10622 {
10623 Expression* val =
10624 Expression::make_unary(OPERATOR_MULT, this->value_pointer_,
10625 this->location());
10626 ret = val->get_backend(context);
10627 }
10628 else if (this->is_in_tuple_assignment_)
10629 {
10630 // Tuple_map_assignment_statement is responsible for using this
10631 // appropriately.
10632 ret = this->value_pointer_->get_backend(context);
10633 }
10634 else
10635 {
10636 Location loc = this->location();
10637
10638 Expression* nil_check =
10639 Expression::make_binary(OPERATOR_EQEQ, this->value_pointer_,
10640 Expression::make_nil(loc), loc);
10641 Bexpression* bnil_check = nil_check->get_backend(context);
10642 Expression* val =
10643 Expression::make_unary(OPERATOR_MULT, this->value_pointer_, loc);
10644 Bexpression* bval = val->get_backend(context);
10645
10646 Gogo* gogo = context->gogo();
10647 Btype* val_btype = type->val_type()->get_backend(gogo);
10648 Bexpression* val_zero = gogo->backend()->zero_expression(val_btype);
10649 ret = gogo->backend()->conditional_expression(val_btype, bnil_check,
10650 val_zero, bval, loc);
10651 }
10652 return ret;
10653 }
10654
10655 // Get an expression for the map index. This returns an expression which
10656 // evaluates to a pointer to a value. The pointer will be NULL if the key is
10657 // not in the map.
10658
10659 Expression*
10660 Map_index_expression::get_value_pointer(bool insert)
10661 {
10662 if (this->value_pointer_ == NULL)
10663 {
10664 Map_type* type = this->get_map_type();
10665 if (type == NULL)
10666 {
10667 go_assert(saw_errors());
10668 return Expression::make_error(this->location());
10669 }
10670
10671 Location loc = this->location();
10672 Expression* map_ref = this->map_;
10673 if (this->map_->type()->points_to() != NULL)
10674 map_ref = Expression::make_unary(OPERATOR_MULT, map_ref, loc);
10675
10676 Expression* index_ptr = Expression::make_unary(OPERATOR_AND, this->index_,
10677 loc);
10678 Expression* map_index =
10679 Runtime::make_call(Runtime::MAP_INDEX, loc, 3,
10680 map_ref, index_ptr,
10681 Expression::make_boolean(insert, loc));
10682
10683 Type* val_type = type->val_type();
10684 this->value_pointer_ =
10685 Expression::make_unsafe_cast(Type::make_pointer_type(val_type),
10686 map_index, this->location());
10687 }
10688 return this->value_pointer_;
10689 }
10690
10691 // Dump ast representation for a map index expression
10692
10693 void
10694 Map_index_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
10695 const
10696 {
10697 Index_expression::dump_index_expression(ast_dump_context, this->map_,
10698 this->index_, NULL, NULL);
10699 }
10700
10701 // Make a map index expression.
10702
10703 Map_index_expression*
10704 Expression::make_map_index(Expression* map, Expression* index,
10705 Location location)
10706 {
10707 return new Map_index_expression(map, index, location);
10708 }
10709
10710 // Class Field_reference_expression.
10711
10712 // Lower a field reference expression. There is nothing to lower, but
10713 // this is where we generate the tracking information for fields with
10714 // the magic go:"track" tag.
10715
10716 Expression*
10717 Field_reference_expression::do_lower(Gogo* gogo, Named_object* function,
10718 Statement_inserter* inserter, int)
10719 {
10720 Struct_type* struct_type = this->expr_->type()->struct_type();
10721 if (struct_type == NULL)
10722 {
10723 // Error will be reported elsewhere.
10724 return this;
10725 }
10726 const Struct_field* field = struct_type->field(this->field_index_);
10727 if (field == NULL)
10728 return this;
10729 if (!field->has_tag())
10730 return this;
10731 if (field->tag().find("go:\"track\"") == std::string::npos)
10732 return this;
10733
10734 // References from functions generated by the compiler don't count.
10735 if (function != NULL && function->func_value()->is_type_specific_function())
10736 return this;
10737
10738 // We have found a reference to a tracked field. Build a call to
10739 // the runtime function __go_fieldtrack with a string that describes
10740 // the field. FIXME: We should only call this once per referenced
10741 // field per function, not once for each reference to the field.
10742
10743 if (this->called_fieldtrack_)
10744 return this;
10745 this->called_fieldtrack_ = true;
10746
10747 Location loc = this->location();
10748
10749 std::string s = "fieldtrack \"";
10750 Named_type* nt = this->expr_->type()->named_type();
10751 if (nt == NULL || nt->named_object()->package() == NULL)
10752 s.append(gogo->pkgpath());
10753 else
10754 s.append(nt->named_object()->package()->pkgpath());
10755 s.push_back('.');
10756 if (nt != NULL)
10757 s.append(Gogo::unpack_hidden_name(nt->name()));
10758 s.push_back('.');
10759 s.append(field->field_name());
10760 s.push_back('"');
10761
10762 // We can't use a string here, because internally a string holds a
10763 // pointer to the actual bytes; when the linker garbage collects the
10764 // string, it won't garbage collect the bytes. So we use a
10765 // [...]byte.
10766
10767 Expression* length_expr = Expression::make_integer_ul(s.length(), NULL, loc);
10768
10769 Type* byte_type = gogo->lookup_global("byte")->type_value();
10770 Type* array_type = Type::make_array_type(byte_type, length_expr);
10771
10772 Expression_list* bytes = new Expression_list();
10773 for (std::string::const_iterator p = s.begin(); p != s.end(); p++)
10774 {
10775 unsigned char c = static_cast<unsigned char>(*p);
10776 bytes->push_back(Expression::make_integer_ul(c, NULL, loc));
10777 }
10778
10779 Expression* e = Expression::make_composite_literal(array_type, 0, false,
10780 bytes, false, loc);
10781
10782 Variable* var = new Variable(array_type, e, true, false, false, loc);
10783
10784 static int count;
10785 char buf[50];
10786 snprintf(buf, sizeof buf, "fieldtrack.%d", count);
10787 ++count;
10788
10789 Named_object* no = gogo->add_variable(buf, var);
10790 e = Expression::make_var_reference(no, loc);
10791 e = Expression::make_unary(OPERATOR_AND, e, loc);
10792
10793 Expression* call = Runtime::make_call(Runtime::FIELDTRACK, loc, 1, e);
10794 gogo->lower_expression(function, inserter, &call);
10795 inserter->insert(Statement::make_statement(call, false));
10796
10797 // Put this function, and the global variable we just created, into
10798 // unique sections. This will permit the linker to garbage collect
10799 // them if they are not referenced. The effect is that the only
10800 // strings, indicating field references, that will wind up in the
10801 // executable will be those for functions that are actually needed.
10802 if (function != NULL)
10803 function->func_value()->set_in_unique_section();
10804 var->set_in_unique_section();
10805
10806 return this;
10807 }
10808
10809 // Return the type of a field reference.
10810
10811 Type*
10812 Field_reference_expression::do_type()
10813 {
10814 Type* type = this->expr_->type();
10815 if (type->is_error())
10816 return type;
10817 Struct_type* struct_type = type->struct_type();
10818 go_assert(struct_type != NULL);
10819 return struct_type->field(this->field_index_)->type();
10820 }
10821
10822 // Check the types for a field reference.
10823
10824 void
10825 Field_reference_expression::do_check_types(Gogo*)
10826 {
10827 Type* type = this->expr_->type();
10828 if (type->is_error())
10829 return;
10830 Struct_type* struct_type = type->struct_type();
10831 go_assert(struct_type != NULL);
10832 go_assert(struct_type->field(this->field_index_) != NULL);
10833 }
10834
10835 // Get the backend representation for a field reference.
10836
10837 Bexpression*
10838 Field_reference_expression::do_get_backend(Translate_context* context)
10839 {
10840 Bexpression* bstruct = this->expr_->get_backend(context);
10841 return context->gogo()->backend()->struct_field_expression(bstruct,
10842 this->field_index_,
10843 this->location());
10844 }
10845
10846 // Dump ast representation for a field reference expression.
10847
10848 void
10849 Field_reference_expression::do_dump_expression(
10850 Ast_dump_context* ast_dump_context) const
10851 {
10852 this->expr_->dump_expression(ast_dump_context);
10853 ast_dump_context->ostream() << "." << this->field_index_;
10854 }
10855
10856 // Make a reference to a qualified identifier in an expression.
10857
10858 Field_reference_expression*
10859 Expression::make_field_reference(Expression* expr, unsigned int field_index,
10860 Location location)
10861 {
10862 return new Field_reference_expression(expr, field_index, location);
10863 }
10864
10865 // Class Interface_field_reference_expression.
10866
10867 // Return an expression for the pointer to the function to call.
10868
10869 Expression*
10870 Interface_field_reference_expression::get_function()
10871 {
10872 Expression* ref = this->expr_;
10873 Location loc = this->location();
10874 if (ref->type()->points_to() != NULL)
10875 ref = Expression::make_unary(OPERATOR_MULT, ref, loc);
10876
10877 Expression* mtable =
10878 Expression::make_interface_info(ref, INTERFACE_INFO_METHODS, loc);
10879 Struct_type* mtable_type = mtable->type()->points_to()->struct_type();
10880
10881 std::string name = Gogo::unpack_hidden_name(this->name_);
10882 unsigned int index;
10883 const Struct_field* field = mtable_type->find_local_field(name, &index);
10884 go_assert(field != NULL);
10885 mtable = Expression::make_unary(OPERATOR_MULT, mtable, loc);
10886 return Expression::make_field_reference(mtable, index, loc);
10887 }
10888
10889 // Return an expression for the first argument to pass to the interface
10890 // function.
10891
10892 Expression*
10893 Interface_field_reference_expression::get_underlying_object()
10894 {
10895 Expression* expr = this->expr_;
10896 if (expr->type()->points_to() != NULL)
10897 expr = Expression::make_unary(OPERATOR_MULT, expr, this->location());
10898 return Expression::make_interface_info(expr, INTERFACE_INFO_OBJECT,
10899 this->location());
10900 }
10901
10902 // Traversal.
10903
10904 int
10905 Interface_field_reference_expression::do_traverse(Traverse* traverse)
10906 {
10907 return Expression::traverse(&this->expr_, traverse);
10908 }
10909
10910 // Lower the expression. If this expression is not called, we need to
10911 // evaluate the expression twice when converting to the backend
10912 // interface. So introduce a temporary variable if necessary.
10913
10914 Expression*
10915 Interface_field_reference_expression::do_flatten(Gogo*, Named_object*,
10916 Statement_inserter* inserter)
10917 {
10918 if (this->expr_->is_error_expression()
10919 || this->expr_->type()->is_error_type())
10920 {
10921 go_assert(saw_errors());
10922 return Expression::make_error(this->location());
10923 }
10924
10925 if (!this->expr_->is_variable())
10926 {
10927 Temporary_statement* temp =
10928 Statement::make_temporary(this->expr_->type(), NULL, this->location());
10929 inserter->insert(temp);
10930 this->expr_ = Expression::make_set_and_use_temporary(temp, this->expr_,
10931 this->location());
10932 }
10933 return this;
10934 }
10935
10936 // Return the type of an interface field reference.
10937
10938 Type*
10939 Interface_field_reference_expression::do_type()
10940 {
10941 Type* expr_type = this->expr_->type();
10942
10943 Type* points_to = expr_type->points_to();
10944 if (points_to != NULL)
10945 expr_type = points_to;
10946
10947 Interface_type* interface_type = expr_type->interface_type();
10948 if (interface_type == NULL)
10949 return Type::make_error_type();
10950
10951 const Typed_identifier* method = interface_type->find_method(this->name_);
10952 if (method == NULL)
10953 return Type::make_error_type();
10954
10955 return method->type();
10956 }
10957
10958 // Determine types.
10959
10960 void
10961 Interface_field_reference_expression::do_determine_type(const Type_context*)
10962 {
10963 this->expr_->determine_type_no_context();
10964 }
10965
10966 // Check the types for an interface field reference.
10967
10968 void
10969 Interface_field_reference_expression::do_check_types(Gogo*)
10970 {
10971 Type* type = this->expr_->type();
10972
10973 Type* points_to = type->points_to();
10974 if (points_to != NULL)
10975 type = points_to;
10976
10977 Interface_type* interface_type = type->interface_type();
10978 if (interface_type == NULL)
10979 {
10980 if (!type->is_error_type())
10981 this->report_error(_("expected interface or pointer to interface"));
10982 }
10983 else
10984 {
10985 const Typed_identifier* method =
10986 interface_type->find_method(this->name_);
10987 if (method == NULL)
10988 {
10989 error_at(this->location(), "method %qs not in interface",
10990 Gogo::message_name(this->name_).c_str());
10991 this->set_is_error();
10992 }
10993 }
10994 }
10995
10996 // If an interface field reference is not simply called, then it is
10997 // represented as a closure. The closure will hold a single variable,
10998 // the value of the interface on which the method should be called.
10999 // The function will be a simple thunk that pulls the value from the
11000 // closure and calls the method with the remaining arguments.
11001
11002 // Because method values are not common, we don't build all thunks for
11003 // all possible interface methods, but instead only build them as we
11004 // need them. In particular, we even build them on demand for
11005 // interface methods defined in other packages.
11006
11007 Interface_field_reference_expression::Interface_method_thunks
11008 Interface_field_reference_expression::interface_method_thunks;
11009
11010 // Find or create the thunk to call method NAME on TYPE.
11011
11012 Named_object*
11013 Interface_field_reference_expression::create_thunk(Gogo* gogo,
11014 Interface_type* type,
11015 const std::string& name)
11016 {
11017 std::pair<Interface_type*, Method_thunks*> val(type, NULL);
11018 std::pair<Interface_method_thunks::iterator, bool> ins =
11019 Interface_field_reference_expression::interface_method_thunks.insert(val);
11020 if (ins.second)
11021 {
11022 // This is the first time we have seen this interface.
11023 ins.first->second = new Method_thunks();
11024 }
11025
11026 for (Method_thunks::const_iterator p = ins.first->second->begin();
11027 p != ins.first->second->end();
11028 p++)
11029 if (p->first == name)
11030 return p->second;
11031
11032 Location loc = type->location();
11033
11034 const Typed_identifier* method_id = type->find_method(name);
11035 if (method_id == NULL)
11036 return Named_object::make_erroneous_name(Gogo::thunk_name());
11037
11038 Function_type* orig_fntype = method_id->type()->function_type();
11039 if (orig_fntype == NULL)
11040 return Named_object::make_erroneous_name(Gogo::thunk_name());
11041
11042 Struct_field_list* sfl = new Struct_field_list();
11043 // The type here is wrong--it should be the C function type. But it
11044 // doesn't really matter.
11045 Type* vt = Type::make_pointer_type(Type::make_void_type());
11046 sfl->push_back(Struct_field(Typed_identifier("fn.0", vt, loc)));
11047 sfl->push_back(Struct_field(Typed_identifier("val.1", type, loc)));
11048 Type* closure_type = Type::make_struct_type(sfl, loc);
11049 closure_type = Type::make_pointer_type(closure_type);
11050
11051 Function_type* new_fntype = orig_fntype->copy_with_names();
11052
11053 std::string thunk_name = Gogo::thunk_name();
11054 Named_object* new_no = gogo->start_function(thunk_name, new_fntype,
11055 false, loc);
11056
11057 Variable* cvar = new Variable(closure_type, NULL, false, false, false, loc);
11058 cvar->set_is_used();
11059 cvar->set_is_closure();
11060 Named_object* cp = Named_object::make_variable("$closure" + thunk_name,
11061 NULL, cvar);
11062 new_no->func_value()->set_closure_var(cp);
11063
11064 gogo->start_block(loc);
11065
11066 // Field 0 of the closure is the function code pointer, field 1 is
11067 // the value on which to invoke the method.
11068 Expression* arg = Expression::make_var_reference(cp, loc);
11069 arg = Expression::make_unary(OPERATOR_MULT, arg, loc);
11070 arg = Expression::make_field_reference(arg, 1, loc);
11071
11072 Expression *ifre = Expression::make_interface_field_reference(arg, name,
11073 loc);
11074
11075 const Typed_identifier_list* orig_params = orig_fntype->parameters();
11076 Expression_list* args;
11077 if (orig_params == NULL || orig_params->empty())
11078 args = NULL;
11079 else
11080 {
11081 const Typed_identifier_list* new_params = new_fntype->parameters();
11082 args = new Expression_list();
11083 for (Typed_identifier_list::const_iterator p = new_params->begin();
11084 p != new_params->end();
11085 ++p)
11086 {
11087 Named_object* p_no = gogo->lookup(p->name(), NULL);
11088 go_assert(p_no != NULL
11089 && p_no->is_variable()
11090 && p_no->var_value()->is_parameter());
11091 args->push_back(Expression::make_var_reference(p_no, loc));
11092 }
11093 }
11094
11095 Call_expression* call = Expression::make_call(ifre, args,
11096 orig_fntype->is_varargs(),
11097 loc);
11098 call->set_varargs_are_lowered();
11099
11100 Statement* s = Statement::make_return_from_call(call, loc);
11101 gogo->add_statement(s);
11102 Block* b = gogo->finish_block(loc);
11103 gogo->add_block(b, loc);
11104 gogo->lower_block(new_no, b);
11105 gogo->flatten_block(new_no, b);
11106 gogo->finish_function(loc);
11107
11108 ins.first->second->push_back(std::make_pair(name, new_no));
11109 return new_no;
11110 }
11111
11112 // Get the backend representation for a method value.
11113
11114 Bexpression*
11115 Interface_field_reference_expression::do_get_backend(Translate_context* context)
11116 {
11117 Interface_type* type = this->expr_->type()->interface_type();
11118 if (type == NULL)
11119 {
11120 go_assert(saw_errors());
11121 return context->backend()->error_expression();
11122 }
11123
11124 Named_object* thunk =
11125 Interface_field_reference_expression::create_thunk(context->gogo(),
11126 type, this->name_);
11127 if (thunk->is_erroneous())
11128 {
11129 go_assert(saw_errors());
11130 return context->backend()->error_expression();
11131 }
11132
11133 // FIXME: We should lower this earlier, but we can't it lower it in
11134 // the lowering pass because at that point we don't know whether we
11135 // need to create the thunk or not. If the expression is called, we
11136 // don't need the thunk.
11137
11138 Location loc = this->location();
11139
11140 Struct_field_list* fields = new Struct_field_list();
11141 fields->push_back(Struct_field(Typed_identifier("fn.0",
11142 thunk->func_value()->type(),
11143 loc)));
11144 fields->push_back(Struct_field(Typed_identifier("val.1",
11145 this->expr_->type(),
11146 loc)));
11147 Struct_type* st = Type::make_struct_type(fields, loc);
11148
11149 Expression_list* vals = new Expression_list();
11150 vals->push_back(Expression::make_func_code_reference(thunk, loc));
11151 vals->push_back(this->expr_);
11152
11153 Expression* expr = Expression::make_struct_composite_literal(st, vals, loc);
11154 Bexpression* bclosure =
11155 Expression::make_heap_expression(expr, loc)->get_backend(context);
11156
11157 Expression* nil_check =
11158 Expression::make_binary(OPERATOR_EQEQ, this->expr_,
11159 Expression::make_nil(loc), loc);
11160 Bexpression* bnil_check = nil_check->get_backend(context);
11161
11162 Gogo* gogo = context->gogo();
11163 Bexpression* bcrash = gogo->runtime_error(RUNTIME_ERROR_NIL_DEREFERENCE,
11164 loc)->get_backend(context);
11165
11166 Bexpression* bcond =
11167 gogo->backend()->conditional_expression(NULL, bnil_check, bcrash, NULL, loc);
11168 Bstatement* cond_statement = gogo->backend()->expression_statement(bcond);
11169 return gogo->backend()->compound_expression(cond_statement, bclosure, loc);
11170 }
11171
11172 // Dump ast representation for an interface field reference.
11173
11174 void
11175 Interface_field_reference_expression::do_dump_expression(
11176 Ast_dump_context* ast_dump_context) const
11177 {
11178 this->expr_->dump_expression(ast_dump_context);
11179 ast_dump_context->ostream() << "." << this->name_;
11180 }
11181
11182 // Make a reference to a field in an interface.
11183
11184 Expression*
11185 Expression::make_interface_field_reference(Expression* expr,
11186 const std::string& field,
11187 Location location)
11188 {
11189 return new Interface_field_reference_expression(expr, field, location);
11190 }
11191
11192 // A general selector. This is a Parser_expression for LEFT.NAME. It
11193 // is lowered after we know the type of the left hand side.
11194
11195 class Selector_expression : public Parser_expression
11196 {
11197 public:
11198 Selector_expression(Expression* left, const std::string& name,
11199 Location location)
11200 : Parser_expression(EXPRESSION_SELECTOR, location),
11201 left_(left), name_(name)
11202 { }
11203
11204 protected:
11205 int
11206 do_traverse(Traverse* traverse)
11207 { return Expression::traverse(&this->left_, traverse); }
11208
11209 Expression*
11210 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
11211
11212 Expression*
11213 do_copy()
11214 {
11215 return new Selector_expression(this->left_->copy(), this->name_,
11216 this->location());
11217 }
11218
11219 void
11220 do_dump_expression(Ast_dump_context* ast_dump_context) const;
11221
11222 private:
11223 Expression*
11224 lower_method_expression(Gogo*);
11225
11226 // The expression on the left hand side.
11227 Expression* left_;
11228 // The name on the right hand side.
11229 std::string name_;
11230 };
11231
11232 // Lower a selector expression once we know the real type of the left
11233 // hand side.
11234
11235 Expression*
11236 Selector_expression::do_lower(Gogo* gogo, Named_object*, Statement_inserter*,
11237 int)
11238 {
11239 Expression* left = this->left_;
11240 if (left->is_type_expression())
11241 return this->lower_method_expression(gogo);
11242 return Type::bind_field_or_method(gogo, left->type(), left, this->name_,
11243 this->location());
11244 }
11245
11246 // Lower a method expression T.M or (*T).M. We turn this into a
11247 // function literal.
11248
11249 Expression*
11250 Selector_expression::lower_method_expression(Gogo* gogo)
11251 {
11252 Location location = this->location();
11253 Type* type = this->left_->type();
11254 const std::string& name(this->name_);
11255
11256 bool is_pointer;
11257 if (type->points_to() == NULL)
11258 is_pointer = false;
11259 else
11260 {
11261 is_pointer = true;
11262 type = type->points_to();
11263 }
11264 Named_type* nt = type->named_type();
11265 if (nt == NULL)
11266 {
11267 error_at(location,
11268 ("method expression requires named type or "
11269 "pointer to named type"));
11270 return Expression::make_error(location);
11271 }
11272
11273 bool is_ambiguous;
11274 Method* method = nt->method_function(name, &is_ambiguous);
11275 const Typed_identifier* imethod = NULL;
11276 if (method == NULL && !is_pointer)
11277 {
11278 Interface_type* it = nt->interface_type();
11279 if (it != NULL)
11280 imethod = it->find_method(name);
11281 }
11282
11283 if (method == NULL && imethod == NULL)
11284 {
11285 if (!is_ambiguous)
11286 error_at(location, "type %<%s%s%> has no method %<%s%>",
11287 is_pointer ? "*" : "",
11288 nt->message_name().c_str(),
11289 Gogo::message_name(name).c_str());
11290 else
11291 error_at(location, "method %<%s%s%> is ambiguous in type %<%s%>",
11292 Gogo::message_name(name).c_str(),
11293 is_pointer ? "*" : "",
11294 nt->message_name().c_str());
11295 return Expression::make_error(location);
11296 }
11297
11298 if (method != NULL && !is_pointer && !method->is_value_method())
11299 {
11300 error_at(location, "method requires pointer (use %<(*%s).%s)%>",
11301 nt->message_name().c_str(),
11302 Gogo::message_name(name).c_str());
11303 return Expression::make_error(location);
11304 }
11305
11306 // Build a new function type in which the receiver becomes the first
11307 // argument.
11308 Function_type* method_type;
11309 if (method != NULL)
11310 {
11311 method_type = method->type();
11312 go_assert(method_type->is_method());
11313 }
11314 else
11315 {
11316 method_type = imethod->type()->function_type();
11317 go_assert(method_type != NULL && !method_type->is_method());
11318 }
11319
11320 const char* const receiver_name = "$this";
11321 Typed_identifier_list* parameters = new Typed_identifier_list();
11322 parameters->push_back(Typed_identifier(receiver_name, this->left_->type(),
11323 location));
11324
11325 const Typed_identifier_list* method_parameters = method_type->parameters();
11326 if (method_parameters != NULL)
11327 {
11328 int i = 0;
11329 for (Typed_identifier_list::const_iterator p = method_parameters->begin();
11330 p != method_parameters->end();
11331 ++p, ++i)
11332 {
11333 if (!p->name().empty())
11334 parameters->push_back(*p);
11335 else
11336 {
11337 char buf[20];
11338 snprintf(buf, sizeof buf, "$param%d", i);
11339 parameters->push_back(Typed_identifier(buf, p->type(),
11340 p->location()));
11341 }
11342 }
11343 }
11344
11345 const Typed_identifier_list* method_results = method_type->results();
11346 Typed_identifier_list* results;
11347 if (method_results == NULL)
11348 results = NULL;
11349 else
11350 {
11351 results = new Typed_identifier_list();
11352 for (Typed_identifier_list::const_iterator p = method_results->begin();
11353 p != method_results->end();
11354 ++p)
11355 results->push_back(*p);
11356 }
11357
11358 Function_type* fntype = Type::make_function_type(NULL, parameters, results,
11359 location);
11360 if (method_type->is_varargs())
11361 fntype->set_is_varargs();
11362
11363 // We generate methods which always takes a pointer to the receiver
11364 // as their first argument. If this is for a pointer type, we can
11365 // simply reuse the existing function. We use an internal hack to
11366 // get the right type.
11367 // FIXME: This optimization is disabled because it doesn't yet work
11368 // with function descriptors when the method expression is not
11369 // directly called.
11370 if (method != NULL && is_pointer && false)
11371 {
11372 Named_object* mno = (method->needs_stub_method()
11373 ? method->stub_object()
11374 : method->named_object());
11375 Expression* f = Expression::make_func_reference(mno, NULL, location);
11376 f = Expression::make_cast(fntype, f, location);
11377 Type_conversion_expression* tce =
11378 static_cast<Type_conversion_expression*>(f);
11379 tce->set_may_convert_function_types();
11380 return f;
11381 }
11382
11383 Named_object* no = gogo->start_function(Gogo::thunk_name(), fntype, false,
11384 location);
11385
11386 Named_object* vno = gogo->lookup(receiver_name, NULL);
11387 go_assert(vno != NULL);
11388 Expression* ve = Expression::make_var_reference(vno, location);
11389 Expression* bm;
11390 if (method != NULL)
11391 bm = Type::bind_field_or_method(gogo, nt, ve, name, location);
11392 else
11393 bm = Expression::make_interface_field_reference(ve, name, location);
11394
11395 // Even though we found the method above, if it has an error type we
11396 // may see an error here.
11397 if (bm->is_error_expression())
11398 {
11399 gogo->finish_function(location);
11400 return bm;
11401 }
11402
11403 Expression_list* args;
11404 if (parameters->size() <= 1)
11405 args = NULL;
11406 else
11407 {
11408 args = new Expression_list();
11409 Typed_identifier_list::const_iterator p = parameters->begin();
11410 ++p;
11411 for (; p != parameters->end(); ++p)
11412 {
11413 vno = gogo->lookup(p->name(), NULL);
11414 go_assert(vno != NULL);
11415 args->push_back(Expression::make_var_reference(vno, location));
11416 }
11417 }
11418
11419 gogo->start_block(location);
11420
11421 Call_expression* call = Expression::make_call(bm, args,
11422 method_type->is_varargs(),
11423 location);
11424
11425 Statement* s = Statement::make_return_from_call(call, location);
11426 gogo->add_statement(s);
11427
11428 Block* b = gogo->finish_block(location);
11429
11430 gogo->add_block(b, location);
11431
11432 // Lower the call in case there are multiple results.
11433 gogo->lower_block(no, b);
11434 gogo->flatten_block(no, b);
11435
11436 gogo->finish_function(location);
11437
11438 return Expression::make_func_reference(no, NULL, location);
11439 }
11440
11441 // Dump the ast for a selector expression.
11442
11443 void
11444 Selector_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11445 const
11446 {
11447 ast_dump_context->dump_expression(this->left_);
11448 ast_dump_context->ostream() << ".";
11449 ast_dump_context->ostream() << this->name_;
11450 }
11451
11452 // Make a selector expression.
11453
11454 Expression*
11455 Expression::make_selector(Expression* left, const std::string& name,
11456 Location location)
11457 {
11458 return new Selector_expression(left, name, location);
11459 }
11460
11461 // Class Allocation_expression.
11462
11463 int
11464 Allocation_expression::do_traverse(Traverse* traverse)
11465 {
11466 return Type::traverse(this->type_, traverse);
11467 }
11468
11469 Type*
11470 Allocation_expression::do_type()
11471 {
11472 return Type::make_pointer_type(this->type_);
11473 }
11474
11475 // Make a copy of an allocation expression.
11476
11477 Expression*
11478 Allocation_expression::do_copy()
11479 {
11480 Allocation_expression* alloc =
11481 new Allocation_expression(this->type_, this->location());
11482 if (this->allocate_on_stack_)
11483 alloc->set_allocate_on_stack();
11484 return alloc;
11485 }
11486
11487 // Return the backend representation for an allocation expression.
11488
11489 Bexpression*
11490 Allocation_expression::do_get_backend(Translate_context* context)
11491 {
11492 Gogo* gogo = context->gogo();
11493 Location loc = this->location();
11494
11495 Btype* btype = this->type_->get_backend(gogo);
11496 if (this->allocate_on_stack_)
11497 {
11498 int64_t size = gogo->backend()->type_size(btype);
11499 return gogo->backend()->stack_allocation_expression(size, loc);
11500 }
11501
11502 Bexpression* space =
11503 gogo->allocate_memory(this->type_, loc)->get_backend(context);
11504 Btype* pbtype = gogo->backend()->pointer_type(btype);
11505 return gogo->backend()->convert_expression(pbtype, space, loc);
11506 }
11507
11508 // Dump ast representation for an allocation expression.
11509
11510 void
11511 Allocation_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
11512 const
11513 {
11514 ast_dump_context->ostream() << "new(";
11515 ast_dump_context->dump_type(this->type_);
11516 ast_dump_context->ostream() << ")";
11517 }
11518
11519 // Make an allocation expression.
11520
11521 Expression*
11522 Expression::make_allocation(Type* type, Location location)
11523 {
11524 return new Allocation_expression(type, location);
11525 }
11526
11527 // Class Struct_construction_expression.
11528
11529 // Traversal.
11530
11531 int
11532 Struct_construction_expression::do_traverse(Traverse* traverse)
11533 {
11534 if (this->vals_ != NULL)
11535 {
11536 if (this->traverse_order_ == NULL)
11537 {
11538 if (this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11539 return TRAVERSE_EXIT;
11540 }
11541 else
11542 {
11543 for (std::vector<int>::const_iterator p =
11544 this->traverse_order_->begin();
11545 p != this->traverse_order_->end();
11546 ++p)
11547 {
11548 if (Expression::traverse(&this->vals_->at(*p), traverse)
11549 == TRAVERSE_EXIT)
11550 return TRAVERSE_EXIT;
11551 }
11552 }
11553 }
11554 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11555 return TRAVERSE_EXIT;
11556 return TRAVERSE_CONTINUE;
11557 }
11558
11559 // Return whether this is a constant initializer.
11560
11561 bool
11562 Struct_construction_expression::is_constant_struct() const
11563 {
11564 if (this->vals_ == NULL)
11565 return true;
11566 for (Expression_list::const_iterator pv = this->vals_->begin();
11567 pv != this->vals_->end();
11568 ++pv)
11569 {
11570 if (*pv != NULL
11571 && !(*pv)->is_constant()
11572 && (!(*pv)->is_composite_literal()
11573 || (*pv)->is_nonconstant_composite_literal()))
11574 return false;
11575 }
11576
11577 const Struct_field_list* fields = this->type_->struct_type()->fields();
11578 for (Struct_field_list::const_iterator pf = fields->begin();
11579 pf != fields->end();
11580 ++pf)
11581 {
11582 // There are no constant constructors for interfaces.
11583 if (pf->type()->interface_type() != NULL)
11584 return false;
11585 }
11586
11587 return true;
11588 }
11589
11590 // Return whether this struct is immutable.
11591
11592 bool
11593 Struct_construction_expression::do_is_immutable() const
11594 {
11595 if (this->vals_ == NULL)
11596 return true;
11597 for (Expression_list::const_iterator pv = this->vals_->begin();
11598 pv != this->vals_->end();
11599 ++pv)
11600 {
11601 if (*pv != NULL && !(*pv)->is_immutable())
11602 return false;
11603 }
11604 return true;
11605 }
11606
11607 // Final type determination.
11608
11609 void
11610 Struct_construction_expression::do_determine_type(const Type_context*)
11611 {
11612 if (this->vals_ == NULL)
11613 return;
11614 const Struct_field_list* fields = this->type_->struct_type()->fields();
11615 Expression_list::const_iterator pv = this->vals_->begin();
11616 for (Struct_field_list::const_iterator pf = fields->begin();
11617 pf != fields->end();
11618 ++pf, ++pv)
11619 {
11620 if (pv == this->vals_->end())
11621 return;
11622 if (*pv != NULL)
11623 {
11624 Type_context subcontext(pf->type(), false);
11625 (*pv)->determine_type(&subcontext);
11626 }
11627 }
11628 // Extra values are an error we will report elsewhere; we still want
11629 // to determine the type to avoid knockon errors.
11630 for (; pv != this->vals_->end(); ++pv)
11631 (*pv)->determine_type_no_context();
11632 }
11633
11634 // Check types.
11635
11636 void
11637 Struct_construction_expression::do_check_types(Gogo*)
11638 {
11639 if (this->vals_ == NULL)
11640 return;
11641
11642 Struct_type* st = this->type_->struct_type();
11643 if (this->vals_->size() > st->field_count())
11644 {
11645 this->report_error(_("too many expressions for struct"));
11646 return;
11647 }
11648
11649 const Struct_field_list* fields = st->fields();
11650 Expression_list::const_iterator pv = this->vals_->begin();
11651 int i = 0;
11652 for (Struct_field_list::const_iterator pf = fields->begin();
11653 pf != fields->end();
11654 ++pf, ++pv, ++i)
11655 {
11656 if (pv == this->vals_->end())
11657 {
11658 this->report_error(_("too few expressions for struct"));
11659 break;
11660 }
11661
11662 if (*pv == NULL)
11663 continue;
11664
11665 std::string reason;
11666 if (!Type::are_assignable(pf->type(), (*pv)->type(), &reason))
11667 {
11668 if (reason.empty())
11669 error_at((*pv)->location(),
11670 "incompatible type for field %d in struct construction",
11671 i + 1);
11672 else
11673 error_at((*pv)->location(),
11674 ("incompatible type for field %d in "
11675 "struct construction (%s)"),
11676 i + 1, reason.c_str());
11677 this->set_is_error();
11678 }
11679 }
11680 go_assert(pv == this->vals_->end());
11681 }
11682
11683 // Flatten a struct construction expression. Store the values into
11684 // temporaries in case they need interface conversion.
11685
11686 Expression*
11687 Struct_construction_expression::do_flatten(Gogo*, Named_object*,
11688 Statement_inserter* inserter)
11689 {
11690 if (this->vals_ == NULL)
11691 return this;
11692
11693 // If this is a constant struct, we don't need temporaries.
11694 if (this->is_constant_struct())
11695 return this;
11696
11697 Location loc = this->location();
11698 for (Expression_list::iterator pv = this->vals_->begin();
11699 pv != this->vals_->end();
11700 ++pv)
11701 {
11702 if (*pv != NULL)
11703 {
11704 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
11705 {
11706 go_assert(saw_errors());
11707 return Expression::make_error(loc);
11708 }
11709 if (!(*pv)->is_variable())
11710 {
11711 Temporary_statement* temp =
11712 Statement::make_temporary(NULL, *pv, loc);
11713 inserter->insert(temp);
11714 *pv = Expression::make_temporary_reference(temp, loc);
11715 }
11716 }
11717 }
11718 return this;
11719 }
11720
11721 // Return the backend representation for constructing a struct.
11722
11723 Bexpression*
11724 Struct_construction_expression::do_get_backend(Translate_context* context)
11725 {
11726 Gogo* gogo = context->gogo();
11727
11728 Btype* btype = this->type_->get_backend(gogo);
11729 if (this->vals_ == NULL)
11730 return gogo->backend()->zero_expression(btype);
11731
11732 const Struct_field_list* fields = this->type_->struct_type()->fields();
11733 Expression_list::const_iterator pv = this->vals_->begin();
11734 std::vector<Bexpression*> init;
11735 for (Struct_field_list::const_iterator pf = fields->begin();
11736 pf != fields->end();
11737 ++pf)
11738 {
11739 Btype* fbtype = pf->type()->get_backend(gogo);
11740 if (pv == this->vals_->end())
11741 init.push_back(gogo->backend()->zero_expression(fbtype));
11742 else if (*pv == NULL)
11743 {
11744 init.push_back(gogo->backend()->zero_expression(fbtype));
11745 ++pv;
11746 }
11747 else
11748 {
11749 Expression* val =
11750 Expression::convert_for_assignment(gogo, pf->type(),
11751 *pv, this->location());
11752 init.push_back(val->get_backend(context));
11753 ++pv;
11754 }
11755 }
11756 return gogo->backend()->constructor_expression(btype, init, this->location());
11757 }
11758
11759 // Export a struct construction.
11760
11761 void
11762 Struct_construction_expression::do_export(Export* exp) const
11763 {
11764 exp->write_c_string("convert(");
11765 exp->write_type(this->type_);
11766 for (Expression_list::const_iterator pv = this->vals_->begin();
11767 pv != this->vals_->end();
11768 ++pv)
11769 {
11770 exp->write_c_string(", ");
11771 if (*pv != NULL)
11772 (*pv)->export_expression(exp);
11773 }
11774 exp->write_c_string(")");
11775 }
11776
11777 // Dump ast representation of a struct construction expression.
11778
11779 void
11780 Struct_construction_expression::do_dump_expression(
11781 Ast_dump_context* ast_dump_context) const
11782 {
11783 ast_dump_context->dump_type(this->type_);
11784 ast_dump_context->ostream() << "{";
11785 ast_dump_context->dump_expression_list(this->vals_);
11786 ast_dump_context->ostream() << "}";
11787 }
11788
11789 // Make a struct composite literal. This used by the thunk code.
11790
11791 Expression*
11792 Expression::make_struct_composite_literal(Type* type, Expression_list* vals,
11793 Location location)
11794 {
11795 go_assert(type->struct_type() != NULL);
11796 return new Struct_construction_expression(type, vals, location);
11797 }
11798
11799 // Class Array_construction_expression.
11800
11801 // Traversal.
11802
11803 int
11804 Array_construction_expression::do_traverse(Traverse* traverse)
11805 {
11806 if (this->vals_ != NULL
11807 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
11808 return TRAVERSE_EXIT;
11809 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
11810 return TRAVERSE_EXIT;
11811 return TRAVERSE_CONTINUE;
11812 }
11813
11814 // Return whether this is a constant initializer.
11815
11816 bool
11817 Array_construction_expression::is_constant_array() const
11818 {
11819 if (this->vals_ == NULL)
11820 return true;
11821
11822 // There are no constant constructors for interfaces.
11823 if (this->type_->array_type()->element_type()->interface_type() != NULL)
11824 return false;
11825
11826 for (Expression_list::const_iterator pv = this->vals_->begin();
11827 pv != this->vals_->end();
11828 ++pv)
11829 {
11830 if (*pv != NULL
11831 && !(*pv)->is_constant()
11832 && (!(*pv)->is_composite_literal()
11833 || (*pv)->is_nonconstant_composite_literal()))
11834 return false;
11835 }
11836 return true;
11837 }
11838
11839 // Return whether this is an immutable array initializer.
11840
11841 bool
11842 Array_construction_expression::do_is_immutable() const
11843 {
11844 if (this->vals_ == NULL)
11845 return true;
11846 for (Expression_list::const_iterator pv = this->vals_->begin();
11847 pv != this->vals_->end();
11848 ++pv)
11849 {
11850 if (*pv != NULL && !(*pv)->is_immutable())
11851 return false;
11852 }
11853 return true;
11854 }
11855
11856 // Final type determination.
11857
11858 void
11859 Array_construction_expression::do_determine_type(const Type_context*)
11860 {
11861 if (this->vals_ == NULL)
11862 return;
11863 Type_context subcontext(this->type_->array_type()->element_type(), false);
11864 for (Expression_list::const_iterator pv = this->vals_->begin();
11865 pv != this->vals_->end();
11866 ++pv)
11867 {
11868 if (*pv != NULL)
11869 (*pv)->determine_type(&subcontext);
11870 }
11871 }
11872
11873 // Check types.
11874
11875 void
11876 Array_construction_expression::do_check_types(Gogo*)
11877 {
11878 if (this->vals_ == NULL)
11879 return;
11880
11881 Array_type* at = this->type_->array_type();
11882 int i = 0;
11883 Type* element_type = at->element_type();
11884 for (Expression_list::const_iterator pv = this->vals_->begin();
11885 pv != this->vals_->end();
11886 ++pv, ++i)
11887 {
11888 if (*pv != NULL
11889 && !Type::are_assignable(element_type, (*pv)->type(), NULL))
11890 {
11891 error_at((*pv)->location(),
11892 "incompatible type for element %d in composite literal",
11893 i + 1);
11894 this->set_is_error();
11895 }
11896 }
11897 }
11898
11899 // Flatten an array construction expression. Store the values into
11900 // temporaries in case they need interface conversion.
11901
11902 Expression*
11903 Array_construction_expression::do_flatten(Gogo*, Named_object*,
11904 Statement_inserter* inserter)
11905 {
11906 if (this->vals_ == NULL)
11907 return this;
11908
11909 // If this is a constant array, we don't need temporaries.
11910 if (this->is_constant_array())
11911 return this;
11912
11913 Location loc = this->location();
11914 for (Expression_list::iterator pv = this->vals_->begin();
11915 pv != this->vals_->end();
11916 ++pv)
11917 {
11918 if (*pv != NULL)
11919 {
11920 if ((*pv)->is_error_expression() || (*pv)->type()->is_error_type())
11921 {
11922 go_assert(saw_errors());
11923 return Expression::make_error(loc);
11924 }
11925 if (!(*pv)->is_variable())
11926 {
11927 Temporary_statement* temp =
11928 Statement::make_temporary(NULL, *pv, loc);
11929 inserter->insert(temp);
11930 *pv = Expression::make_temporary_reference(temp, loc);
11931 }
11932 }
11933 }
11934 return this;
11935 }
11936
11937 // Get a constructor expression for the array values.
11938
11939 Bexpression*
11940 Array_construction_expression::get_constructor(Translate_context* context,
11941 Btype* array_btype)
11942 {
11943 Type* element_type = this->type_->array_type()->element_type();
11944
11945 std::vector<unsigned long> indexes;
11946 std::vector<Bexpression*> vals;
11947 Gogo* gogo = context->gogo();
11948 if (this->vals_ != NULL)
11949 {
11950 size_t i = 0;
11951 std::vector<unsigned long>::const_iterator pi;
11952 if (this->indexes_ != NULL)
11953 pi = this->indexes_->begin();
11954 for (Expression_list::const_iterator pv = this->vals_->begin();
11955 pv != this->vals_->end();
11956 ++pv, ++i)
11957 {
11958 if (this->indexes_ != NULL)
11959 go_assert(pi != this->indexes_->end());
11960
11961 if (this->indexes_ == NULL)
11962 indexes.push_back(i);
11963 else
11964 indexes.push_back(*pi);
11965 if (*pv == NULL)
11966 {
11967 Btype* ebtype = element_type->get_backend(gogo);
11968 Bexpression *zv = gogo->backend()->zero_expression(ebtype);
11969 vals.push_back(zv);
11970 }
11971 else
11972 {
11973 Expression* val_expr =
11974 Expression::convert_for_assignment(gogo, element_type, *pv,
11975 this->location());
11976 vals.push_back(val_expr->get_backend(context));
11977 }
11978 if (this->indexes_ != NULL)
11979 ++pi;
11980 }
11981 if (this->indexes_ != NULL)
11982 go_assert(pi == this->indexes_->end());
11983 }
11984 return gogo->backend()->array_constructor_expression(array_btype, indexes,
11985 vals, this->location());
11986 }
11987
11988 // Export an array construction.
11989
11990 void
11991 Array_construction_expression::do_export(Export* exp) const
11992 {
11993 exp->write_c_string("convert(");
11994 exp->write_type(this->type_);
11995 if (this->vals_ != NULL)
11996 {
11997 std::vector<unsigned long>::const_iterator pi;
11998 if (this->indexes_ != NULL)
11999 pi = this->indexes_->begin();
12000 for (Expression_list::const_iterator pv = this->vals_->begin();
12001 pv != this->vals_->end();
12002 ++pv)
12003 {
12004 exp->write_c_string(", ");
12005
12006 if (this->indexes_ != NULL)
12007 {
12008 char buf[100];
12009 snprintf(buf, sizeof buf, "%lu", *pi);
12010 exp->write_c_string(buf);
12011 exp->write_c_string(":");
12012 }
12013
12014 if (*pv != NULL)
12015 (*pv)->export_expression(exp);
12016
12017 if (this->indexes_ != NULL)
12018 ++pi;
12019 }
12020 }
12021 exp->write_c_string(")");
12022 }
12023
12024 // Dump ast representation of an array construction expressin.
12025
12026 void
12027 Array_construction_expression::do_dump_expression(
12028 Ast_dump_context* ast_dump_context) const
12029 {
12030 Expression* length = this->type_->array_type()->length();
12031
12032 ast_dump_context->ostream() << "[" ;
12033 if (length != NULL)
12034 {
12035 ast_dump_context->dump_expression(length);
12036 }
12037 ast_dump_context->ostream() << "]" ;
12038 ast_dump_context->dump_type(this->type_);
12039 ast_dump_context->ostream() << "{" ;
12040 if (this->indexes_ == NULL)
12041 ast_dump_context->dump_expression_list(this->vals_);
12042 else
12043 {
12044 Expression_list::const_iterator pv = this->vals_->begin();
12045 for (std::vector<unsigned long>::const_iterator pi =
12046 this->indexes_->begin();
12047 pi != this->indexes_->end();
12048 ++pi, ++pv)
12049 {
12050 if (pi != this->indexes_->begin())
12051 ast_dump_context->ostream() << ", ";
12052 ast_dump_context->ostream() << *pi << ':';
12053 ast_dump_context->dump_expression(*pv);
12054 }
12055 }
12056 ast_dump_context->ostream() << "}" ;
12057
12058 }
12059
12060 // Class Fixed_array_construction_expression.
12061
12062 Fixed_array_construction_expression::Fixed_array_construction_expression(
12063 Type* type, const std::vector<unsigned long>* indexes,
12064 Expression_list* vals, Location location)
12065 : Array_construction_expression(EXPRESSION_FIXED_ARRAY_CONSTRUCTION,
12066 type, indexes, vals, location)
12067 { go_assert(type->array_type() != NULL && !type->is_slice_type()); }
12068
12069 // Return the backend representation for constructing a fixed array.
12070
12071 Bexpression*
12072 Fixed_array_construction_expression::do_get_backend(Translate_context* context)
12073 {
12074 Type* type = this->type();
12075 Btype* btype = type->get_backend(context->gogo());
12076 return this->get_constructor(context, btype);
12077 }
12078
12079 Expression*
12080 Expression::make_array_composite_literal(Type* type, Expression_list* vals,
12081 Location location)
12082 {
12083 go_assert(type->array_type() != NULL && !type->is_slice_type());
12084 return new Fixed_array_construction_expression(type, NULL, vals, location);
12085 }
12086
12087 // Class Slice_construction_expression.
12088
12089 Slice_construction_expression::Slice_construction_expression(
12090 Type* type, const std::vector<unsigned long>* indexes,
12091 Expression_list* vals, Location location)
12092 : Array_construction_expression(EXPRESSION_SLICE_CONSTRUCTION,
12093 type, indexes, vals, location),
12094 valtype_(NULL)
12095 {
12096 go_assert(type->is_slice_type());
12097
12098 unsigned long lenval;
12099 Expression* length;
12100 if (vals == NULL || vals->empty())
12101 lenval = 0;
12102 else
12103 {
12104 if (this->indexes() == NULL)
12105 lenval = vals->size();
12106 else
12107 lenval = indexes->back() + 1;
12108 }
12109 Type* int_type = Type::lookup_integer_type("int");
12110 length = Expression::make_integer_ul(lenval, int_type, location);
12111 Type* element_type = type->array_type()->element_type();
12112 this->valtype_ = Type::make_array_type(element_type, length);
12113 }
12114
12115
12116 // Traversal.
12117
12118 int
12119 Slice_construction_expression::do_traverse(Traverse* traverse)
12120 {
12121 if (this->Array_construction_expression::do_traverse(traverse)
12122 == TRAVERSE_EXIT)
12123 return TRAVERSE_EXIT;
12124 if (Type::traverse(this->valtype_, traverse) == TRAVERSE_EXIT)
12125 return TRAVERSE_EXIT;
12126 return TRAVERSE_CONTINUE;
12127 }
12128
12129 // Return the backend representation for constructing a slice.
12130
12131 Bexpression*
12132 Slice_construction_expression::do_get_backend(Translate_context* context)
12133 {
12134 Array_type* array_type = this->type()->array_type();
12135 if (array_type == NULL)
12136 {
12137 go_assert(this->type()->is_error());
12138 return context->backend()->error_expression();
12139 }
12140
12141 Location loc = this->location();
12142 Type* element_type = array_type->element_type();
12143 go_assert(this->valtype_ != NULL);
12144
12145 Expression_list* vals = this->vals();
12146 if (this->vals() == NULL || this->vals()->empty())
12147 {
12148 // We need to create a unique value for the empty array literal.
12149 vals = new Expression_list;
12150 vals->push_back(NULL);
12151 }
12152 Expression* array_val =
12153 new Fixed_array_construction_expression(this->valtype_, this->indexes(),
12154 vals, loc);
12155
12156 bool is_constant_initializer = array_val->is_immutable();
12157
12158 // We have to copy the initial values into heap memory if we are in
12159 // a function or if the values are not constants. We also have to
12160 // copy them if they may contain pointers in a non-constant context,
12161 // as otherwise the garbage collector won't see them.
12162 bool copy_to_heap = (context->function() != NULL
12163 || !is_constant_initializer
12164 || (element_type->has_pointer()
12165 && !context->is_const()));
12166
12167 Expression* space;
12168 if (!copy_to_heap)
12169 {
12170 // The initializer will only run once.
12171 space = Expression::make_unary(OPERATOR_AND, array_val, loc);
12172 space->unary_expression()->set_is_slice_init();
12173 }
12174 else
12175 space = Expression::make_heap_expression(array_val, loc);
12176
12177 // Build a constructor for the slice.
12178
12179 Expression* len = this->valtype_->array_type()->length();
12180 Expression* slice_val =
12181 Expression::make_slice_value(this->type(), space, len, len, loc);
12182 return slice_val->get_backend(context);
12183 }
12184
12185 // Make a slice composite literal. This is used by the type
12186 // descriptor code.
12187
12188 Expression*
12189 Expression::make_slice_composite_literal(Type* type, Expression_list* vals,
12190 Location location)
12191 {
12192 go_assert(type->is_slice_type());
12193 return new Slice_construction_expression(type, NULL, vals, location);
12194 }
12195
12196 // Class Map_construction_expression.
12197
12198 // Traversal.
12199
12200 int
12201 Map_construction_expression::do_traverse(Traverse* traverse)
12202 {
12203 if (this->vals_ != NULL
12204 && this->vals_->traverse(traverse) == TRAVERSE_EXIT)
12205 return TRAVERSE_EXIT;
12206 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12207 return TRAVERSE_EXIT;
12208 return TRAVERSE_CONTINUE;
12209 }
12210
12211 // Flatten constructor initializer into a temporary variable since
12212 // we need to take its address for __go_construct_map.
12213
12214 Expression*
12215 Map_construction_expression::do_flatten(Gogo* gogo, Named_object*,
12216 Statement_inserter* inserter)
12217 {
12218 if (!this->is_error_expression()
12219 && this->vals_ != NULL
12220 && !this->vals_->empty()
12221 && this->constructor_temp_ == NULL)
12222 {
12223 Map_type* mt = this->type_->map_type();
12224 Type* key_type = mt->key_type();
12225 Type* val_type = mt->val_type();
12226 this->element_type_ = Type::make_builtin_struct_type(2,
12227 "__key", key_type,
12228 "__val", val_type);
12229
12230 Expression_list* value_pairs = new Expression_list();
12231 Location loc = this->location();
12232
12233 size_t i = 0;
12234 for (Expression_list::const_iterator pv = this->vals_->begin();
12235 pv != this->vals_->end();
12236 ++pv, ++i)
12237 {
12238 Expression_list* key_value_pair = new Expression_list();
12239 Expression* key = *pv;
12240 if (key->is_error_expression() || key->type()->is_error_type())
12241 {
12242 go_assert(saw_errors());
12243 return Expression::make_error(loc);
12244 }
12245 if (key->type()->interface_type() != NULL && !key->is_variable())
12246 {
12247 Temporary_statement* temp =
12248 Statement::make_temporary(NULL, key, loc);
12249 inserter->insert(temp);
12250 key = Expression::make_temporary_reference(temp, loc);
12251 }
12252 key = Expression::convert_for_assignment(gogo, key_type, key, loc);
12253
12254 ++pv;
12255 Expression* val = *pv;
12256 if (val->is_error_expression() || val->type()->is_error_type())
12257 {
12258 go_assert(saw_errors());
12259 return Expression::make_error(loc);
12260 }
12261 if (val->type()->interface_type() != NULL && !val->is_variable())
12262 {
12263 Temporary_statement* temp =
12264 Statement::make_temporary(NULL, val, loc);
12265 inserter->insert(temp);
12266 val = Expression::make_temporary_reference(temp, loc);
12267 }
12268 val = Expression::convert_for_assignment(gogo, val_type, val, loc);
12269
12270 key_value_pair->push_back(key);
12271 key_value_pair->push_back(val);
12272 value_pairs->push_back(
12273 Expression::make_struct_composite_literal(this->element_type_,
12274 key_value_pair, loc));
12275 }
12276
12277 Expression* element_count = Expression::make_integer_ul(i, NULL, loc);
12278 Type* ctor_type =
12279 Type::make_array_type(this->element_type_, element_count);
12280 Expression* constructor =
12281 new Fixed_array_construction_expression(ctor_type, NULL,
12282 value_pairs, loc);
12283
12284 this->constructor_temp_ =
12285 Statement::make_temporary(NULL, constructor, loc);
12286 constructor->issue_nil_check();
12287 this->constructor_temp_->set_is_address_taken();
12288 inserter->insert(this->constructor_temp_);
12289 }
12290
12291 return this;
12292 }
12293
12294 // Final type determination.
12295
12296 void
12297 Map_construction_expression::do_determine_type(const Type_context*)
12298 {
12299 if (this->vals_ == NULL)
12300 return;
12301
12302 Map_type* mt = this->type_->map_type();
12303 Type_context key_context(mt->key_type(), false);
12304 Type_context val_context(mt->val_type(), false);
12305 for (Expression_list::const_iterator pv = this->vals_->begin();
12306 pv != this->vals_->end();
12307 ++pv)
12308 {
12309 (*pv)->determine_type(&key_context);
12310 ++pv;
12311 (*pv)->determine_type(&val_context);
12312 }
12313 }
12314
12315 // Check types.
12316
12317 void
12318 Map_construction_expression::do_check_types(Gogo*)
12319 {
12320 if (this->vals_ == NULL)
12321 return;
12322
12323 Map_type* mt = this->type_->map_type();
12324 int i = 0;
12325 Type* key_type = mt->key_type();
12326 Type* val_type = mt->val_type();
12327 for (Expression_list::const_iterator pv = this->vals_->begin();
12328 pv != this->vals_->end();
12329 ++pv, ++i)
12330 {
12331 if (!Type::are_assignable(key_type, (*pv)->type(), NULL))
12332 {
12333 error_at((*pv)->location(),
12334 "incompatible type for element %d key in map construction",
12335 i + 1);
12336 this->set_is_error();
12337 }
12338 ++pv;
12339 if (!Type::are_assignable(val_type, (*pv)->type(), NULL))
12340 {
12341 error_at((*pv)->location(),
12342 ("incompatible type for element %d value "
12343 "in map construction"),
12344 i + 1);
12345 this->set_is_error();
12346 }
12347 }
12348 }
12349
12350 // Return the backend representation for constructing a map.
12351
12352 Bexpression*
12353 Map_construction_expression::do_get_backend(Translate_context* context)
12354 {
12355 if (this->is_error_expression())
12356 return context->backend()->error_expression();
12357 Location loc = this->location();
12358
12359 size_t i = 0;
12360 Expression* ventries;
12361 if (this->vals_ == NULL || this->vals_->empty())
12362 ventries = Expression::make_nil(loc);
12363 else
12364 {
12365 go_assert(this->constructor_temp_ != NULL);
12366 i = this->vals_->size() / 2;
12367
12368 Expression* ctor_ref =
12369 Expression::make_temporary_reference(this->constructor_temp_, loc);
12370 ventries = Expression::make_unary(OPERATOR_AND, ctor_ref, loc);
12371 }
12372
12373 Map_type* mt = this->type_->map_type();
12374 if (this->element_type_ == NULL)
12375 this->element_type_ =
12376 Type::make_builtin_struct_type(2,
12377 "__key", mt->key_type(),
12378 "__val", mt->val_type());
12379 Expression* descriptor = Expression::make_map_descriptor(mt, loc);
12380
12381 Type* uintptr_t = Type::lookup_integer_type("uintptr");
12382 Expression* count = Expression::make_integer_ul(i, uintptr_t, loc);
12383
12384 Expression* entry_size =
12385 Expression::make_type_info(this->element_type_, TYPE_INFO_SIZE);
12386
12387 unsigned int field_index;
12388 const Struct_field* valfield =
12389 this->element_type_->find_local_field("__val", &field_index);
12390 Expression* val_offset =
12391 Expression::make_struct_field_offset(this->element_type_, valfield);
12392 Expression* val_size =
12393 Expression::make_type_info(mt->val_type(), TYPE_INFO_SIZE);
12394
12395 Expression* map_ctor =
12396 Runtime::make_call(Runtime::CONSTRUCT_MAP, loc, 6, descriptor, count,
12397 entry_size, val_offset, val_size, ventries);
12398 return map_ctor->get_backend(context);
12399 }
12400
12401 // Export an array construction.
12402
12403 void
12404 Map_construction_expression::do_export(Export* exp) const
12405 {
12406 exp->write_c_string("convert(");
12407 exp->write_type(this->type_);
12408 for (Expression_list::const_iterator pv = this->vals_->begin();
12409 pv != this->vals_->end();
12410 ++pv)
12411 {
12412 exp->write_c_string(", ");
12413 (*pv)->export_expression(exp);
12414 }
12415 exp->write_c_string(")");
12416 }
12417
12418 // Dump ast representation for a map construction expression.
12419
12420 void
12421 Map_construction_expression::do_dump_expression(
12422 Ast_dump_context* ast_dump_context) const
12423 {
12424 ast_dump_context->ostream() << "{" ;
12425 ast_dump_context->dump_expression_list(this->vals_, true);
12426 ast_dump_context->ostream() << "}";
12427 }
12428
12429 // A general composite literal. This is lowered to a type specific
12430 // version.
12431
12432 class Composite_literal_expression : public Parser_expression
12433 {
12434 public:
12435 Composite_literal_expression(Type* type, int depth, bool has_keys,
12436 Expression_list* vals, bool all_are_names,
12437 Location location)
12438 : Parser_expression(EXPRESSION_COMPOSITE_LITERAL, location),
12439 type_(type), depth_(depth), vals_(vals), has_keys_(has_keys),
12440 all_are_names_(all_are_names)
12441 { }
12442
12443 protected:
12444 int
12445 do_traverse(Traverse* traverse);
12446
12447 Expression*
12448 do_lower(Gogo*, Named_object*, Statement_inserter*, int);
12449
12450 Expression*
12451 do_copy()
12452 {
12453 return new Composite_literal_expression(this->type_, this->depth_,
12454 this->has_keys_,
12455 (this->vals_ == NULL
12456 ? NULL
12457 : this->vals_->copy()),
12458 this->all_are_names_,
12459 this->location());
12460 }
12461
12462 void
12463 do_dump_expression(Ast_dump_context*) const;
12464
12465 private:
12466 Expression*
12467 lower_struct(Gogo*, Type*);
12468
12469 Expression*
12470 lower_array(Type*);
12471
12472 Expression*
12473 make_array(Type*, const std::vector<unsigned long>*, Expression_list*);
12474
12475 Expression*
12476 lower_map(Gogo*, Named_object*, Statement_inserter*, Type*);
12477
12478 // The type of the composite literal.
12479 Type* type_;
12480 // The depth within a list of composite literals within a composite
12481 // literal, when the type is omitted.
12482 int depth_;
12483 // The values to put in the composite literal.
12484 Expression_list* vals_;
12485 // If this is true, then VALS_ is a list of pairs: a key and a
12486 // value. In an array initializer, a missing key will be NULL.
12487 bool has_keys_;
12488 // If this is true, then HAS_KEYS_ is true, and every key is a
12489 // simple identifier.
12490 bool all_are_names_;
12491 };
12492
12493 // Traversal.
12494
12495 int
12496 Composite_literal_expression::do_traverse(Traverse* traverse)
12497 {
12498 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
12499 return TRAVERSE_EXIT;
12500
12501 // If this is a struct composite literal with keys, then the keys
12502 // are field names, not expressions. We don't want to traverse them
12503 // in that case. If we do, we can give an erroneous error "variable
12504 // initializer refers to itself." See bug482.go in the testsuite.
12505 if (this->has_keys_ && this->vals_ != NULL)
12506 {
12507 // The type may not be resolvable at this point.
12508 Type* type = this->type_;
12509
12510 for (int depth = this->depth_; depth > 0; --depth)
12511 {
12512 if (type->array_type() != NULL)
12513 type = type->array_type()->element_type();
12514 else if (type->map_type() != NULL)
12515 type = type->map_type()->val_type();
12516 else
12517 {
12518 // This error will be reported during lowering.
12519 return TRAVERSE_CONTINUE;
12520 }
12521 }
12522
12523 while (true)
12524 {
12525 if (type->classification() == Type::TYPE_NAMED)
12526 type = type->named_type()->real_type();
12527 else if (type->classification() == Type::TYPE_FORWARD)
12528 {
12529 Type* t = type->forwarded();
12530 if (t == type)
12531 break;
12532 type = t;
12533 }
12534 else
12535 break;
12536 }
12537
12538 if (type->classification() == Type::TYPE_STRUCT)
12539 {
12540 Expression_list::iterator p = this->vals_->begin();
12541 while (p != this->vals_->end())
12542 {
12543 // Skip key.
12544 ++p;
12545 go_assert(p != this->vals_->end());
12546 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
12547 return TRAVERSE_EXIT;
12548 ++p;
12549 }
12550 return TRAVERSE_CONTINUE;
12551 }
12552 }
12553
12554 if (this->vals_ != NULL)
12555 return this->vals_->traverse(traverse);
12556
12557 return TRAVERSE_CONTINUE;
12558 }
12559
12560 // Lower a generic composite literal into a specific version based on
12561 // the type.
12562
12563 Expression*
12564 Composite_literal_expression::do_lower(Gogo* gogo, Named_object* function,
12565 Statement_inserter* inserter, int)
12566 {
12567 Type* type = this->type_;
12568
12569 for (int depth = this->depth_; depth > 0; --depth)
12570 {
12571 if (type->array_type() != NULL)
12572 type = type->array_type()->element_type();
12573 else if (type->map_type() != NULL)
12574 type = type->map_type()->val_type();
12575 else
12576 {
12577 if (!type->is_error())
12578 error_at(this->location(),
12579 ("may only omit types within composite literals "
12580 "of slice, array, or map type"));
12581 return Expression::make_error(this->location());
12582 }
12583 }
12584
12585 Type *pt = type->points_to();
12586 bool is_pointer = false;
12587 if (pt != NULL)
12588 {
12589 is_pointer = true;
12590 type = pt;
12591 }
12592
12593 Expression* ret;
12594 if (type->is_error())
12595 return Expression::make_error(this->location());
12596 else if (type->struct_type() != NULL)
12597 ret = this->lower_struct(gogo, type);
12598 else if (type->array_type() != NULL)
12599 ret = this->lower_array(type);
12600 else if (type->map_type() != NULL)
12601 ret = this->lower_map(gogo, function, inserter, type);
12602 else
12603 {
12604 error_at(this->location(),
12605 ("expected struct, slice, array, or map type "
12606 "for composite literal"));
12607 return Expression::make_error(this->location());
12608 }
12609
12610 if (is_pointer)
12611 ret = Expression::make_heap_expression(ret, this->location());
12612
12613 return ret;
12614 }
12615
12616 // Lower a struct composite literal.
12617
12618 Expression*
12619 Composite_literal_expression::lower_struct(Gogo* gogo, Type* type)
12620 {
12621 Location location = this->location();
12622 Struct_type* st = type->struct_type();
12623 if (this->vals_ == NULL || !this->has_keys_)
12624 {
12625 if (this->vals_ != NULL
12626 && !this->vals_->empty()
12627 && type->named_type() != NULL
12628 && type->named_type()->named_object()->package() != NULL)
12629 {
12630 for (Struct_field_list::const_iterator pf = st->fields()->begin();
12631 pf != st->fields()->end();
12632 ++pf)
12633 {
12634 if (Gogo::is_hidden_name(pf->field_name())
12635 || pf->is_embedded_builtin(gogo))
12636 error_at(this->location(),
12637 "assignment of unexported field %qs in %qs literal",
12638 Gogo::message_name(pf->field_name()).c_str(),
12639 type->named_type()->message_name().c_str());
12640 }
12641 }
12642
12643 return new Struct_construction_expression(type, this->vals_, location);
12644 }
12645
12646 size_t field_count = st->field_count();
12647 std::vector<Expression*> vals(field_count);
12648 std::vector<int>* traverse_order = new(std::vector<int>);
12649 Expression_list::const_iterator p = this->vals_->begin();
12650 Expression* external_expr = NULL;
12651 const Named_object* external_no = NULL;
12652 while (p != this->vals_->end())
12653 {
12654 Expression* name_expr = *p;
12655
12656 ++p;
12657 go_assert(p != this->vals_->end());
12658 Expression* val = *p;
12659
12660 ++p;
12661
12662 if (name_expr == NULL)
12663 {
12664 error_at(val->location(), "mixture of field and value initializers");
12665 return Expression::make_error(location);
12666 }
12667
12668 bool bad_key = false;
12669 std::string name;
12670 const Named_object* no = NULL;
12671 switch (name_expr->classification())
12672 {
12673 case EXPRESSION_UNKNOWN_REFERENCE:
12674 name = name_expr->unknown_expression()->name();
12675 if (type->named_type() != NULL)
12676 {
12677 // If the named object found for this field name comes from a
12678 // different package than the struct it is a part of, do not count
12679 // this incorrect lookup as a usage of the object's package.
12680 no = name_expr->unknown_expression()->named_object();
12681 if (no->package() != NULL
12682 && no->package() != type->named_type()->named_object()->package())
12683 no->package()->forget_usage(name_expr);
12684 }
12685 break;
12686
12687 case EXPRESSION_CONST_REFERENCE:
12688 no = static_cast<Const_expression*>(name_expr)->named_object();
12689 break;
12690
12691 case EXPRESSION_TYPE:
12692 {
12693 Type* t = name_expr->type();
12694 Named_type* nt = t->named_type();
12695 if (nt == NULL)
12696 bad_key = true;
12697 else
12698 no = nt->named_object();
12699 }
12700 break;
12701
12702 case EXPRESSION_VAR_REFERENCE:
12703 no = name_expr->var_expression()->named_object();
12704 break;
12705
12706 case EXPRESSION_FUNC_REFERENCE:
12707 no = name_expr->func_expression()->named_object();
12708 break;
12709
12710 case EXPRESSION_UNARY:
12711 // If there is a local variable around with the same name as
12712 // the field, and this occurs in the closure, then the
12713 // parser may turn the field reference into an indirection
12714 // through the closure. FIXME: This is a mess.
12715 {
12716 bad_key = true;
12717 Unary_expression* ue = static_cast<Unary_expression*>(name_expr);
12718 if (ue->op() == OPERATOR_MULT)
12719 {
12720 Field_reference_expression* fre =
12721 ue->operand()->field_reference_expression();
12722 if (fre != NULL)
12723 {
12724 Struct_type* st =
12725 fre->expr()->type()->deref()->struct_type();
12726 if (st != NULL)
12727 {
12728 const Struct_field* sf = st->field(fre->field_index());
12729 name = sf->field_name();
12730
12731 // See below. FIXME.
12732 if (!Gogo::is_hidden_name(name)
12733 && name[0] >= 'a'
12734 && name[0] <= 'z')
12735 {
12736 if (gogo->lookup_global(name.c_str()) != NULL)
12737 name = gogo->pack_hidden_name(name, false);
12738 }
12739
12740 char buf[20];
12741 snprintf(buf, sizeof buf, "%u", fre->field_index());
12742 size_t buflen = strlen(buf);
12743 if (name.compare(name.length() - buflen, buflen, buf)
12744 == 0)
12745 {
12746 name = name.substr(0, name.length() - buflen);
12747 bad_key = false;
12748 }
12749 }
12750 }
12751 }
12752 }
12753 break;
12754
12755 default:
12756 bad_key = true;
12757 break;
12758 }
12759 if (bad_key)
12760 {
12761 error_at(name_expr->location(), "expected struct field name");
12762 return Expression::make_error(location);
12763 }
12764
12765 if (no != NULL)
12766 {
12767 if (no->package() != NULL && external_expr == NULL)
12768 {
12769 external_expr = name_expr;
12770 external_no = no;
12771 }
12772
12773 name = no->name();
12774
12775 // A predefined name won't be packed. If it starts with a
12776 // lower case letter we need to check for that case, because
12777 // the field name will be packed. FIXME.
12778 if (!Gogo::is_hidden_name(name)
12779 && name[0] >= 'a'
12780 && name[0] <= 'z')
12781 {
12782 Named_object* gno = gogo->lookup_global(name.c_str());
12783 if (gno == no)
12784 name = gogo->pack_hidden_name(name, false);
12785 }
12786 }
12787
12788 unsigned int index;
12789 const Struct_field* sf = st->find_local_field(name, &index);
12790 if (sf == NULL)
12791 {
12792 error_at(name_expr->location(), "unknown field %qs in %qs",
12793 Gogo::message_name(name).c_str(),
12794 (type->named_type() != NULL
12795 ? type->named_type()->message_name().c_str()
12796 : "unnamed struct"));
12797 return Expression::make_error(location);
12798 }
12799 if (vals[index] != NULL)
12800 {
12801 error_at(name_expr->location(),
12802 "duplicate value for field %qs in %qs",
12803 Gogo::message_name(name).c_str(),
12804 (type->named_type() != NULL
12805 ? type->named_type()->message_name().c_str()
12806 : "unnamed struct"));
12807 return Expression::make_error(location);
12808 }
12809
12810 if (type->named_type() != NULL
12811 && type->named_type()->named_object()->package() != NULL
12812 && (Gogo::is_hidden_name(sf->field_name())
12813 || sf->is_embedded_builtin(gogo)))
12814 error_at(name_expr->location(),
12815 "assignment of unexported field %qs in %qs literal",
12816 Gogo::message_name(sf->field_name()).c_str(),
12817 type->named_type()->message_name().c_str());
12818
12819 vals[index] = val;
12820 traverse_order->push_back(index);
12821 }
12822
12823 if (!this->all_are_names_)
12824 {
12825 // This is a weird case like bug462 in the testsuite.
12826 if (external_expr == NULL)
12827 error_at(this->location(), "unknown field in %qs literal",
12828 (type->named_type() != NULL
12829 ? type->named_type()->message_name().c_str()
12830 : "unnamed struct"));
12831 else
12832 error_at(external_expr->location(), "unknown field %qs in %qs",
12833 external_no->message_name().c_str(),
12834 (type->named_type() != NULL
12835 ? type->named_type()->message_name().c_str()
12836 : "unnamed struct"));
12837 return Expression::make_error(location);
12838 }
12839
12840 Expression_list* list = new Expression_list;
12841 list->reserve(field_count);
12842 for (size_t i = 0; i < field_count; ++i)
12843 list->push_back(vals[i]);
12844
12845 Struct_construction_expression* ret =
12846 new Struct_construction_expression(type, list, location);
12847 ret->set_traverse_order(traverse_order);
12848 return ret;
12849 }
12850
12851 // Used to sort an index/value array.
12852
12853 class Index_value_compare
12854 {
12855 public:
12856 bool
12857 operator()(const std::pair<unsigned long, Expression*>& a,
12858 const std::pair<unsigned long, Expression*>& b)
12859 { return a.first < b.first; }
12860 };
12861
12862 // Lower an array composite literal.
12863
12864 Expression*
12865 Composite_literal_expression::lower_array(Type* type)
12866 {
12867 Location location = this->location();
12868 if (this->vals_ == NULL || !this->has_keys_)
12869 return this->make_array(type, NULL, this->vals_);
12870
12871 std::vector<unsigned long>* indexes = new std::vector<unsigned long>;
12872 indexes->reserve(this->vals_->size());
12873 bool indexes_out_of_order = false;
12874 Expression_list* vals = new Expression_list();
12875 vals->reserve(this->vals_->size());
12876 unsigned long index = 0;
12877 Expression_list::const_iterator p = this->vals_->begin();
12878 while (p != this->vals_->end())
12879 {
12880 Expression* index_expr = *p;
12881
12882 ++p;
12883 go_assert(p != this->vals_->end());
12884 Expression* val = *p;
12885
12886 ++p;
12887
12888 if (index_expr == NULL)
12889 {
12890 if (!indexes->empty())
12891 indexes->push_back(index);
12892 }
12893 else
12894 {
12895 if (indexes->empty() && !vals->empty())
12896 {
12897 for (size_t i = 0; i < vals->size(); ++i)
12898 indexes->push_back(i);
12899 }
12900
12901 Numeric_constant nc;
12902 if (!index_expr->numeric_constant_value(&nc))
12903 {
12904 error_at(index_expr->location(),
12905 "index expression is not integer constant");
12906 return Expression::make_error(location);
12907 }
12908
12909 switch (nc.to_unsigned_long(&index))
12910 {
12911 case Numeric_constant::NC_UL_VALID:
12912 break;
12913 case Numeric_constant::NC_UL_NOTINT:
12914 error_at(index_expr->location(),
12915 "index expression is not integer constant");
12916 return Expression::make_error(location);
12917 case Numeric_constant::NC_UL_NEGATIVE:
12918 error_at(index_expr->location(), "index expression is negative");
12919 return Expression::make_error(location);
12920 case Numeric_constant::NC_UL_BIG:
12921 error_at(index_expr->location(), "index value overflow");
12922 return Expression::make_error(location);
12923 default:
12924 go_unreachable();
12925 }
12926
12927 Named_type* ntype = Type::lookup_integer_type("int");
12928 Integer_type* inttype = ntype->integer_type();
12929 if (sizeof(index) <= static_cast<size_t>(inttype->bits() * 8)
12930 && index >> (inttype->bits() - 1) != 0)
12931 {
12932 error_at(index_expr->location(), "index value overflow");
12933 return Expression::make_error(location);
12934 }
12935
12936 if (std::find(indexes->begin(), indexes->end(), index)
12937 != indexes->end())
12938 {
12939 error_at(index_expr->location(), "duplicate value for index %lu",
12940 index);
12941 return Expression::make_error(location);
12942 }
12943
12944 if (!indexes->empty() && index < indexes->back())
12945 indexes_out_of_order = true;
12946
12947 indexes->push_back(index);
12948 }
12949
12950 vals->push_back(val);
12951
12952 ++index;
12953 }
12954
12955 if (indexes->empty())
12956 {
12957 delete indexes;
12958 indexes = NULL;
12959 }
12960
12961 if (indexes_out_of_order)
12962 {
12963 typedef std::vector<std::pair<unsigned long, Expression*> > V;
12964
12965 V v;
12966 v.reserve(indexes->size());
12967 std::vector<unsigned long>::const_iterator pi = indexes->begin();
12968 for (Expression_list::const_iterator pe = vals->begin();
12969 pe != vals->end();
12970 ++pe, ++pi)
12971 v.push_back(std::make_pair(*pi, *pe));
12972
12973 std::sort(v.begin(), v.end(), Index_value_compare());
12974
12975 delete indexes;
12976 delete vals;
12977 indexes = new std::vector<unsigned long>();
12978 indexes->reserve(v.size());
12979 vals = new Expression_list();
12980 vals->reserve(v.size());
12981
12982 for (V::const_iterator p = v.begin(); p != v.end(); ++p)
12983 {
12984 indexes->push_back(p->first);
12985 vals->push_back(p->second);
12986 }
12987 }
12988
12989 return this->make_array(type, indexes, vals);
12990 }
12991
12992 // Actually build the array composite literal. This handles
12993 // [...]{...}.
12994
12995 Expression*
12996 Composite_literal_expression::make_array(
12997 Type* type,
12998 const std::vector<unsigned long>* indexes,
12999 Expression_list* vals)
13000 {
13001 Location location = this->location();
13002 Array_type* at = type->array_type();
13003
13004 if (at->length() != NULL && at->length()->is_nil_expression())
13005 {
13006 size_t size;
13007 if (vals == NULL)
13008 size = 0;
13009 else if (indexes != NULL)
13010 size = indexes->back() + 1;
13011 else
13012 {
13013 size = vals->size();
13014 Integer_type* it = Type::lookup_integer_type("int")->integer_type();
13015 if (sizeof(size) <= static_cast<size_t>(it->bits() * 8)
13016 && size >> (it->bits() - 1) != 0)
13017 {
13018 error_at(location, "too many elements in composite literal");
13019 return Expression::make_error(location);
13020 }
13021 }
13022
13023 Expression* elen = Expression::make_integer_ul(size, NULL, location);
13024 at = Type::make_array_type(at->element_type(), elen);
13025 type = at;
13026 }
13027 else if (at->length() != NULL
13028 && !at->length()->is_error_expression()
13029 && this->vals_ != NULL)
13030 {
13031 Numeric_constant nc;
13032 unsigned long val;
13033 if (at->length()->numeric_constant_value(&nc)
13034 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
13035 {
13036 if (indexes == NULL)
13037 {
13038 if (this->vals_->size() > val)
13039 {
13040 error_at(location, "too many elements in composite literal");
13041 return Expression::make_error(location);
13042 }
13043 }
13044 else
13045 {
13046 unsigned long max = indexes->back();
13047 if (max >= val)
13048 {
13049 error_at(location,
13050 ("some element keys in composite literal "
13051 "are out of range"));
13052 return Expression::make_error(location);
13053 }
13054 }
13055 }
13056 }
13057
13058 if (at->length() != NULL)
13059 return new Fixed_array_construction_expression(type, indexes, vals,
13060 location);
13061 else
13062 return new Slice_construction_expression(type, indexes, vals, location);
13063 }
13064
13065 // Lower a map composite literal.
13066
13067 Expression*
13068 Composite_literal_expression::lower_map(Gogo* gogo, Named_object* function,
13069 Statement_inserter* inserter,
13070 Type* type)
13071 {
13072 Location location = this->location();
13073 if (this->vals_ != NULL)
13074 {
13075 if (!this->has_keys_)
13076 {
13077 error_at(location, "map composite literal must have keys");
13078 return Expression::make_error(location);
13079 }
13080
13081 for (Expression_list::iterator p = this->vals_->begin();
13082 p != this->vals_->end();
13083 p += 2)
13084 {
13085 if (*p == NULL)
13086 {
13087 ++p;
13088 error_at((*p)->location(),
13089 "map composite literal must have keys for every value");
13090 return Expression::make_error(location);
13091 }
13092 // Make sure we have lowered the key; it may not have been
13093 // lowered in order to handle keys for struct composite
13094 // literals. Lower it now to get the right error message.
13095 if ((*p)->unknown_expression() != NULL)
13096 {
13097 (*p)->unknown_expression()->clear_is_composite_literal_key();
13098 gogo->lower_expression(function, inserter, &*p);
13099 go_assert((*p)->is_error_expression());
13100 return Expression::make_error(location);
13101 }
13102 }
13103 }
13104
13105 return new Map_construction_expression(type, this->vals_, location);
13106 }
13107
13108 // Dump ast representation for a composite literal expression.
13109
13110 void
13111 Composite_literal_expression::do_dump_expression(
13112 Ast_dump_context* ast_dump_context) const
13113 {
13114 ast_dump_context->ostream() << "composite(";
13115 ast_dump_context->dump_type(this->type_);
13116 ast_dump_context->ostream() << ", {";
13117 ast_dump_context->dump_expression_list(this->vals_, this->has_keys_);
13118 ast_dump_context->ostream() << "})";
13119 }
13120
13121 // Make a composite literal expression.
13122
13123 Expression*
13124 Expression::make_composite_literal(Type* type, int depth, bool has_keys,
13125 Expression_list* vals, bool all_are_names,
13126 Location location)
13127 {
13128 return new Composite_literal_expression(type, depth, has_keys, vals,
13129 all_are_names, location);
13130 }
13131
13132 // Return whether this expression is a composite literal.
13133
13134 bool
13135 Expression::is_composite_literal() const
13136 {
13137 switch (this->classification_)
13138 {
13139 case EXPRESSION_COMPOSITE_LITERAL:
13140 case EXPRESSION_STRUCT_CONSTRUCTION:
13141 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13142 case EXPRESSION_SLICE_CONSTRUCTION:
13143 case EXPRESSION_MAP_CONSTRUCTION:
13144 return true;
13145 default:
13146 return false;
13147 }
13148 }
13149
13150 // Return whether this expression is a composite literal which is not
13151 // constant.
13152
13153 bool
13154 Expression::is_nonconstant_composite_literal() const
13155 {
13156 switch (this->classification_)
13157 {
13158 case EXPRESSION_STRUCT_CONSTRUCTION:
13159 {
13160 const Struct_construction_expression *psce =
13161 static_cast<const Struct_construction_expression*>(this);
13162 return !psce->is_constant_struct();
13163 }
13164 case EXPRESSION_FIXED_ARRAY_CONSTRUCTION:
13165 {
13166 const Fixed_array_construction_expression *pace =
13167 static_cast<const Fixed_array_construction_expression*>(this);
13168 return !pace->is_constant_array();
13169 }
13170 case EXPRESSION_SLICE_CONSTRUCTION:
13171 {
13172 const Slice_construction_expression *pace =
13173 static_cast<const Slice_construction_expression*>(this);
13174 return !pace->is_constant_array();
13175 }
13176 case EXPRESSION_MAP_CONSTRUCTION:
13177 return true;
13178 default:
13179 return false;
13180 }
13181 }
13182
13183 // Return true if this is a variable or temporary_variable.
13184
13185 bool
13186 Expression::is_variable() const
13187 {
13188 switch (this->classification_)
13189 {
13190 case EXPRESSION_VAR_REFERENCE:
13191 case EXPRESSION_TEMPORARY_REFERENCE:
13192 case EXPRESSION_SET_AND_USE_TEMPORARY:
13193 return true;
13194 default:
13195 return false;
13196 }
13197 }
13198
13199 // Return true if this is a reference to a local variable.
13200
13201 bool
13202 Expression::is_local_variable() const
13203 {
13204 const Var_expression* ve = this->var_expression();
13205 if (ve == NULL)
13206 return false;
13207 const Named_object* no = ve->named_object();
13208 return (no->is_result_variable()
13209 || (no->is_variable() && !no->var_value()->is_global()));
13210 }
13211
13212 // Class Type_guard_expression.
13213
13214 // Traversal.
13215
13216 int
13217 Type_guard_expression::do_traverse(Traverse* traverse)
13218 {
13219 if (Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT
13220 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13221 return TRAVERSE_EXIT;
13222 return TRAVERSE_CONTINUE;
13223 }
13224
13225 Expression*
13226 Type_guard_expression::do_flatten(Gogo*, Named_object*,
13227 Statement_inserter* inserter)
13228 {
13229 if (this->expr_->is_error_expression()
13230 || this->expr_->type()->is_error_type())
13231 {
13232 go_assert(saw_errors());
13233 return Expression::make_error(this->location());
13234 }
13235
13236 if (!this->expr_->is_variable())
13237 {
13238 Temporary_statement* temp = Statement::make_temporary(NULL, this->expr_,
13239 this->location());
13240 inserter->insert(temp);
13241 this->expr_ =
13242 Expression::make_temporary_reference(temp, this->location());
13243 }
13244 return this;
13245 }
13246
13247 // Check types of a type guard expression. The expression must have
13248 // an interface type, but the actual type conversion is checked at run
13249 // time.
13250
13251 void
13252 Type_guard_expression::do_check_types(Gogo*)
13253 {
13254 Type* expr_type = this->expr_->type();
13255 if (expr_type->interface_type() == NULL)
13256 {
13257 if (!expr_type->is_error() && !this->type_->is_error())
13258 this->report_error(_("type assertion only valid for interface types"));
13259 this->set_is_error();
13260 }
13261 else if (this->type_->interface_type() == NULL)
13262 {
13263 std::string reason;
13264 if (!expr_type->interface_type()->implements_interface(this->type_,
13265 &reason))
13266 {
13267 if (!this->type_->is_error())
13268 {
13269 if (reason.empty())
13270 this->report_error(_("impossible type assertion: "
13271 "type does not implement interface"));
13272 else
13273 error_at(this->location(),
13274 ("impossible type assertion: "
13275 "type does not implement interface (%s)"),
13276 reason.c_str());
13277 }
13278 this->set_is_error();
13279 }
13280 }
13281 }
13282
13283 // Return the backend representation for a type guard expression.
13284
13285 Bexpression*
13286 Type_guard_expression::do_get_backend(Translate_context* context)
13287 {
13288 Expression* conversion;
13289 if (this->type_->interface_type() != NULL)
13290 conversion =
13291 Expression::convert_interface_to_interface(this->type_, this->expr_,
13292 true, this->location());
13293 else
13294 conversion =
13295 Expression::convert_for_assignment(context->gogo(), this->type_,
13296 this->expr_, this->location());
13297
13298 return conversion->get_backend(context);
13299 }
13300
13301 // Dump ast representation for a type guard expression.
13302
13303 void
13304 Type_guard_expression::do_dump_expression(Ast_dump_context* ast_dump_context)
13305 const
13306 {
13307 this->expr_->dump_expression(ast_dump_context);
13308 ast_dump_context->ostream() << ".";
13309 ast_dump_context->dump_type(this->type_);
13310 }
13311
13312 // Make a type guard expression.
13313
13314 Expression*
13315 Expression::make_type_guard(Expression* expr, Type* type,
13316 Location location)
13317 {
13318 return new Type_guard_expression(expr, type, location);
13319 }
13320
13321 // Class Heap_expression.
13322
13323 // Return the type of the expression stored on the heap.
13324
13325 Type*
13326 Heap_expression::do_type()
13327 { return Type::make_pointer_type(this->expr_->type()); }
13328
13329 // Return the backend representation for allocating an expression on the heap.
13330
13331 Bexpression*
13332 Heap_expression::do_get_backend(Translate_context* context)
13333 {
13334 if (this->expr_->is_error_expression() || this->expr_->type()->is_error())
13335 return context->backend()->error_expression();
13336
13337 Location loc = this->location();
13338 Gogo* gogo = context->gogo();
13339 Btype* btype = this->type()->get_backend(gogo);
13340 Bexpression* space = Expression::make_allocation(this->expr_->type(),
13341 loc)->get_backend(context);
13342
13343 Bstatement* decl;
13344 Named_object* fn = context->function();
13345 go_assert(fn != NULL);
13346 Bfunction* fndecl = fn->func_value()->get_or_make_decl(gogo, fn);
13347 Bvariable* space_temp =
13348 gogo->backend()->temporary_variable(fndecl, context->bblock(), btype,
13349 space, true, loc, &decl);
13350 space = gogo->backend()->var_expression(space_temp, loc);
13351 Btype* expr_btype = this->expr_->type()->get_backend(gogo);
13352 Bexpression* ref =
13353 gogo->backend()->indirect_expression(expr_btype, space, true, loc);
13354
13355 Bexpression* bexpr = this->expr_->get_backend(context);
13356 Bstatement* assn = gogo->backend()->assignment_statement(ref, bexpr, loc);
13357 decl = gogo->backend()->compound_statement(decl, assn);
13358 space = gogo->backend()->var_expression(space_temp, loc);
13359 return gogo->backend()->compound_expression(decl, space, loc);
13360 }
13361
13362 // Dump ast representation for a heap expression.
13363
13364 void
13365 Heap_expression::do_dump_expression(
13366 Ast_dump_context* ast_dump_context) const
13367 {
13368 ast_dump_context->ostream() << "&(";
13369 ast_dump_context->dump_expression(this->expr_);
13370 ast_dump_context->ostream() << ")";
13371 }
13372
13373 // Allocate an expression on the heap.
13374
13375 Expression*
13376 Expression::make_heap_expression(Expression* expr, Location location)
13377 {
13378 return new Heap_expression(expr, location);
13379 }
13380
13381 // Class Receive_expression.
13382
13383 // Return the type of a receive expression.
13384
13385 Type*
13386 Receive_expression::do_type()
13387 {
13388 Channel_type* channel_type = this->channel_->type()->channel_type();
13389 if (channel_type == NULL)
13390 return Type::make_error_type();
13391 return channel_type->element_type();
13392 }
13393
13394 // Check types for a receive expression.
13395
13396 void
13397 Receive_expression::do_check_types(Gogo*)
13398 {
13399 Type* type = this->channel_->type();
13400 if (type->is_error())
13401 {
13402 this->set_is_error();
13403 return;
13404 }
13405 if (type->channel_type() == NULL)
13406 {
13407 this->report_error(_("expected channel"));
13408 return;
13409 }
13410 if (!type->channel_type()->may_receive())
13411 {
13412 this->report_error(_("invalid receive on send-only channel"));
13413 return;
13414 }
13415 }
13416
13417 // Flattening for receive expressions creates a temporary variable to store
13418 // received data in for receives.
13419
13420 Expression*
13421 Receive_expression::do_flatten(Gogo*, Named_object*,
13422 Statement_inserter* inserter)
13423 {
13424 Channel_type* channel_type = this->channel_->type()->channel_type();
13425 if (channel_type == NULL)
13426 {
13427 go_assert(saw_errors());
13428 return this;
13429 }
13430 else if (this->channel_->is_error_expression())
13431 {
13432 go_assert(saw_errors());
13433 return Expression::make_error(this->location());
13434 }
13435
13436 Type* element_type = channel_type->element_type();
13437 if (this->temp_receiver_ == NULL)
13438 {
13439 this->temp_receiver_ = Statement::make_temporary(element_type, NULL,
13440 this->location());
13441 this->temp_receiver_->set_is_address_taken();
13442 inserter->insert(this->temp_receiver_);
13443 }
13444
13445 return this;
13446 }
13447
13448 // Get the backend representation for a receive expression.
13449
13450 Bexpression*
13451 Receive_expression::do_get_backend(Translate_context* context)
13452 {
13453 Location loc = this->location();
13454
13455 Channel_type* channel_type = this->channel_->type()->channel_type();
13456 if (channel_type == NULL)
13457 {
13458 go_assert(this->channel_->type()->is_error());
13459 return context->backend()->error_expression();
13460 }
13461 Expression* td = Expression::make_type_descriptor(channel_type, loc);
13462
13463 Expression* recv_ref =
13464 Expression::make_temporary_reference(this->temp_receiver_, loc);
13465 Expression* recv_addr =
13466 Expression::make_temporary_reference(this->temp_receiver_, loc);
13467 recv_addr = Expression::make_unary(OPERATOR_AND, recv_addr, loc);
13468 Expression* recv =
13469 Runtime::make_call(Runtime::RECEIVE, loc, 3,
13470 td, this->channel_, recv_addr);
13471 return Expression::make_compound(recv, recv_ref, loc)->get_backend(context);
13472 }
13473
13474 // Dump ast representation for a receive expression.
13475
13476 void
13477 Receive_expression::do_dump_expression(Ast_dump_context* ast_dump_context) const
13478 {
13479 ast_dump_context->ostream() << " <- " ;
13480 ast_dump_context->dump_expression(channel_);
13481 }
13482
13483 // Make a receive expression.
13484
13485 Receive_expression*
13486 Expression::make_receive(Expression* channel, Location location)
13487 {
13488 return new Receive_expression(channel, location);
13489 }
13490
13491 // An expression which evaluates to a pointer to the type descriptor
13492 // of a type.
13493
13494 class Type_descriptor_expression : public Expression
13495 {
13496 public:
13497 Type_descriptor_expression(Type* type, Location location)
13498 : Expression(EXPRESSION_TYPE_DESCRIPTOR, location),
13499 type_(type)
13500 { }
13501
13502 protected:
13503 int
13504 do_traverse(Traverse*);
13505
13506 Type*
13507 do_type()
13508 { return Type::make_type_descriptor_ptr_type(); }
13509
13510 bool
13511 do_is_immutable() const
13512 { return true; }
13513
13514 void
13515 do_determine_type(const Type_context*)
13516 { }
13517
13518 Expression*
13519 do_copy()
13520 { return this; }
13521
13522 Bexpression*
13523 do_get_backend(Translate_context* context)
13524 {
13525 return this->type_->type_descriptor_pointer(context->gogo(),
13526 this->location());
13527 }
13528
13529 void
13530 do_dump_expression(Ast_dump_context*) const;
13531
13532 private:
13533 // The type for which this is the descriptor.
13534 Type* type_;
13535 };
13536
13537 int
13538 Type_descriptor_expression::do_traverse(Traverse* traverse)
13539 {
13540 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
13541 return TRAVERSE_EXIT;
13542 return TRAVERSE_CONTINUE;
13543 }
13544
13545 // Dump ast representation for a type descriptor expression.
13546
13547 void
13548 Type_descriptor_expression::do_dump_expression(
13549 Ast_dump_context* ast_dump_context) const
13550 {
13551 ast_dump_context->dump_type(this->type_);
13552 }
13553
13554 // Make a type descriptor expression.
13555
13556 Expression*
13557 Expression::make_type_descriptor(Type* type, Location location)
13558 {
13559 return new Type_descriptor_expression(type, location);
13560 }
13561
13562 // An expression which evaluates to a pointer to the Garbage Collection symbol
13563 // of a type.
13564
13565 class GC_symbol_expression : public Expression
13566 {
13567 public:
13568 GC_symbol_expression(Type* type)
13569 : Expression(EXPRESSION_GC_SYMBOL, Linemap::predeclared_location()),
13570 type_(type)
13571 {}
13572
13573 protected:
13574 Type*
13575 do_type()
13576 { return Type::lookup_integer_type("uintptr"); }
13577
13578 bool
13579 do_is_immutable() const
13580 { return true; }
13581
13582 void
13583 do_determine_type(const Type_context*)
13584 { }
13585
13586 Expression*
13587 do_copy()
13588 { return this; }
13589
13590 Bexpression*
13591 do_get_backend(Translate_context* context)
13592 { return this->type_->gc_symbol_pointer(context->gogo()); }
13593
13594 void
13595 do_dump_expression(Ast_dump_context*) const;
13596
13597 private:
13598 // The type which this gc symbol describes.
13599 Type* type_;
13600 };
13601
13602 // Dump ast representation for a gc symbol expression.
13603
13604 void
13605 GC_symbol_expression::do_dump_expression(
13606 Ast_dump_context* ast_dump_context) const
13607 {
13608 ast_dump_context->ostream() << "gcdata(";
13609 ast_dump_context->dump_type(this->type_);
13610 ast_dump_context->ostream() << ")";
13611 }
13612
13613 // Make a gc symbol expression.
13614
13615 Expression*
13616 Expression::make_gc_symbol(Type* type)
13617 {
13618 return new GC_symbol_expression(type);
13619 }
13620
13621 // An expression which evaluates to some characteristic of a type.
13622 // This is only used to initialize fields of a type descriptor. Using
13623 // a new expression class is slightly inefficient but gives us a good
13624 // separation between the frontend and the middle-end with regard to
13625 // how types are laid out.
13626
13627 class Type_info_expression : public Expression
13628 {
13629 public:
13630 Type_info_expression(Type* type, Type_info type_info)
13631 : Expression(EXPRESSION_TYPE_INFO, Linemap::predeclared_location()),
13632 type_(type), type_info_(type_info)
13633 { }
13634
13635 protected:
13636 bool
13637 do_is_immutable() const
13638 { return true; }
13639
13640 Type*
13641 do_type();
13642
13643 void
13644 do_determine_type(const Type_context*)
13645 { }
13646
13647 Expression*
13648 do_copy()
13649 { return this; }
13650
13651 Bexpression*
13652 do_get_backend(Translate_context* context);
13653
13654 void
13655 do_dump_expression(Ast_dump_context*) const;
13656
13657 private:
13658 // The type for which we are getting information.
13659 Type* type_;
13660 // What information we want.
13661 Type_info type_info_;
13662 };
13663
13664 // The type is chosen to match what the type descriptor struct
13665 // expects.
13666
13667 Type*
13668 Type_info_expression::do_type()
13669 {
13670 switch (this->type_info_)
13671 {
13672 case TYPE_INFO_SIZE:
13673 return Type::lookup_integer_type("uintptr");
13674 case TYPE_INFO_ALIGNMENT:
13675 case TYPE_INFO_FIELD_ALIGNMENT:
13676 return Type::lookup_integer_type("uint8");
13677 default:
13678 go_unreachable();
13679 }
13680 }
13681
13682 // Return the backend representation for type information.
13683
13684 Bexpression*
13685 Type_info_expression::do_get_backend(Translate_context* context)
13686 {
13687 Btype* btype = this->type_->get_backend(context->gogo());
13688 Gogo* gogo = context->gogo();
13689 int64_t val;
13690 switch (this->type_info_)
13691 {
13692 case TYPE_INFO_SIZE:
13693 val = gogo->backend()->type_size(btype);
13694 break;
13695 case TYPE_INFO_ALIGNMENT:
13696 val = gogo->backend()->type_alignment(btype);
13697 break;
13698 case TYPE_INFO_FIELD_ALIGNMENT:
13699 val = gogo->backend()->type_field_alignment(btype);
13700 break;
13701 default:
13702 go_unreachable();
13703 }
13704 Expression* e = Expression::make_integer_int64(val, this->type(),
13705 this->location());
13706 return e->get_backend(context);
13707 }
13708
13709 // Dump ast representation for a type info expression.
13710
13711 void
13712 Type_info_expression::do_dump_expression(
13713 Ast_dump_context* ast_dump_context) const
13714 {
13715 ast_dump_context->ostream() << "typeinfo(";
13716 ast_dump_context->dump_type(this->type_);
13717 ast_dump_context->ostream() << ",";
13718 ast_dump_context->ostream() <<
13719 (this->type_info_ == TYPE_INFO_ALIGNMENT ? "alignment"
13720 : this->type_info_ == TYPE_INFO_FIELD_ALIGNMENT ? "field alignment"
13721 : this->type_info_ == TYPE_INFO_SIZE ? "size "
13722 : "unknown");
13723 ast_dump_context->ostream() << ")";
13724 }
13725
13726 // Make a type info expression.
13727
13728 Expression*
13729 Expression::make_type_info(Type* type, Type_info type_info)
13730 {
13731 return new Type_info_expression(type, type_info);
13732 }
13733
13734 // An expression that evaluates to some characteristic of a slice.
13735 // This is used when indexing, bound-checking, or nil checking a slice.
13736
13737 class Slice_info_expression : public Expression
13738 {
13739 public:
13740 Slice_info_expression(Expression* slice, Slice_info slice_info,
13741 Location location)
13742 : Expression(EXPRESSION_SLICE_INFO, location),
13743 slice_(slice), slice_info_(slice_info)
13744 { }
13745
13746 protected:
13747 Type*
13748 do_type();
13749
13750 void
13751 do_determine_type(const Type_context*)
13752 { }
13753
13754 Expression*
13755 do_copy()
13756 {
13757 return new Slice_info_expression(this->slice_->copy(), this->slice_info_,
13758 this->location());
13759 }
13760
13761 Bexpression*
13762 do_get_backend(Translate_context* context);
13763
13764 void
13765 do_dump_expression(Ast_dump_context*) const;
13766
13767 void
13768 do_issue_nil_check()
13769 { this->slice_->issue_nil_check(); }
13770
13771 private:
13772 // The slice for which we are getting information.
13773 Expression* slice_;
13774 // What information we want.
13775 Slice_info slice_info_;
13776 };
13777
13778 // Return the type of the slice info.
13779
13780 Type*
13781 Slice_info_expression::do_type()
13782 {
13783 switch (this->slice_info_)
13784 {
13785 case SLICE_INFO_VALUE_POINTER:
13786 return Type::make_pointer_type(
13787 this->slice_->type()->array_type()->element_type());
13788 case SLICE_INFO_LENGTH:
13789 case SLICE_INFO_CAPACITY:
13790 return Type::lookup_integer_type("int");
13791 default:
13792 go_unreachable();
13793 }
13794 }
13795
13796 // Return the backend information for slice information.
13797
13798 Bexpression*
13799 Slice_info_expression::do_get_backend(Translate_context* context)
13800 {
13801 Gogo* gogo = context->gogo();
13802 Bexpression* bslice = this->slice_->get_backend(context);
13803 switch (this->slice_info_)
13804 {
13805 case SLICE_INFO_VALUE_POINTER:
13806 case SLICE_INFO_LENGTH:
13807 case SLICE_INFO_CAPACITY:
13808 return gogo->backend()->struct_field_expression(bslice, this->slice_info_,
13809 this->location());
13810 break;
13811 default:
13812 go_unreachable();
13813 }
13814 }
13815
13816 // Dump ast representation for a type info expression.
13817
13818 void
13819 Slice_info_expression::do_dump_expression(
13820 Ast_dump_context* ast_dump_context) const
13821 {
13822 ast_dump_context->ostream() << "sliceinfo(";
13823 this->slice_->dump_expression(ast_dump_context);
13824 ast_dump_context->ostream() << ",";
13825 ast_dump_context->ostream() <<
13826 (this->slice_info_ == SLICE_INFO_VALUE_POINTER ? "values"
13827 : this->slice_info_ == SLICE_INFO_LENGTH ? "length"
13828 : this->slice_info_ == SLICE_INFO_CAPACITY ? "capacity "
13829 : "unknown");
13830 ast_dump_context->ostream() << ")";
13831 }
13832
13833 // Make a slice info expression.
13834
13835 Expression*
13836 Expression::make_slice_info(Expression* slice, Slice_info slice_info,
13837 Location location)
13838 {
13839 return new Slice_info_expression(slice, slice_info, location);
13840 }
13841
13842 // An expression that represents a slice value: a struct with value pointer,
13843 // length, and capacity fields.
13844
13845 class Slice_value_expression : public Expression
13846 {
13847 public:
13848 Slice_value_expression(Type* type, Expression* valptr, Expression* len,
13849 Expression* cap, Location location)
13850 : Expression(EXPRESSION_SLICE_VALUE, location),
13851 type_(type), valptr_(valptr), len_(len), cap_(cap)
13852 { }
13853
13854 protected:
13855 int
13856 do_traverse(Traverse*);
13857
13858 Type*
13859 do_type()
13860 { return this->type_; }
13861
13862 void
13863 do_determine_type(const Type_context*)
13864 { go_unreachable(); }
13865
13866 Expression*
13867 do_copy()
13868 {
13869 return new Slice_value_expression(this->type_, this->valptr_->copy(),
13870 this->len_->copy(), this->cap_->copy(),
13871 this->location());
13872 }
13873
13874 Bexpression*
13875 do_get_backend(Translate_context* context);
13876
13877 void
13878 do_dump_expression(Ast_dump_context*) const;
13879
13880 private:
13881 // The type of the slice value.
13882 Type* type_;
13883 // The pointer to the values in the slice.
13884 Expression* valptr_;
13885 // The length of the slice.
13886 Expression* len_;
13887 // The capacity of the slice.
13888 Expression* cap_;
13889 };
13890
13891 int
13892 Slice_value_expression::do_traverse(Traverse* traverse)
13893 {
13894 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT
13895 || Expression::traverse(&this->valptr_, traverse) == TRAVERSE_EXIT
13896 || Expression::traverse(&this->len_, traverse) == TRAVERSE_EXIT
13897 || Expression::traverse(&this->cap_, traverse) == TRAVERSE_EXIT)
13898 return TRAVERSE_EXIT;
13899 return TRAVERSE_CONTINUE;
13900 }
13901
13902 Bexpression*
13903 Slice_value_expression::do_get_backend(Translate_context* context)
13904 {
13905 std::vector<Bexpression*> vals(3);
13906 vals[0] = this->valptr_->get_backend(context);
13907 vals[1] = this->len_->get_backend(context);
13908 vals[2] = this->cap_->get_backend(context);
13909
13910 Gogo* gogo = context->gogo();
13911 Btype* btype = this->type_->get_backend(gogo);
13912 return gogo->backend()->constructor_expression(btype, vals, this->location());
13913 }
13914
13915 void
13916 Slice_value_expression::do_dump_expression(
13917 Ast_dump_context* ast_dump_context) const
13918 {
13919 ast_dump_context->ostream() << "slicevalue(";
13920 ast_dump_context->ostream() << "values: ";
13921 this->valptr_->dump_expression(ast_dump_context);
13922 ast_dump_context->ostream() << ", length: ";
13923 this->len_->dump_expression(ast_dump_context);
13924 ast_dump_context->ostream() << ", capacity: ";
13925 this->cap_->dump_expression(ast_dump_context);
13926 ast_dump_context->ostream() << ")";
13927 }
13928
13929 Expression*
13930 Expression::make_slice_value(Type* at, Expression* valptr, Expression* len,
13931 Expression* cap, Location location)
13932 {
13933 go_assert(at->is_slice_type());
13934 return new Slice_value_expression(at, valptr, len, cap, location);
13935 }
13936
13937 // An expression that evaluates to some characteristic of a non-empty interface.
13938 // This is used to access the method table or underlying object of an interface.
13939
13940 class Interface_info_expression : public Expression
13941 {
13942 public:
13943 Interface_info_expression(Expression* iface, Interface_info iface_info,
13944 Location location)
13945 : Expression(EXPRESSION_INTERFACE_INFO, location),
13946 iface_(iface), iface_info_(iface_info)
13947 { }
13948
13949 protected:
13950 Type*
13951 do_type();
13952
13953 void
13954 do_determine_type(const Type_context*)
13955 { }
13956
13957 Expression*
13958 do_copy()
13959 {
13960 return new Interface_info_expression(this->iface_->copy(),
13961 this->iface_info_, this->location());
13962 }
13963
13964 Bexpression*
13965 do_get_backend(Translate_context* context);
13966
13967 void
13968 do_dump_expression(Ast_dump_context*) const;
13969
13970 void
13971 do_issue_nil_check()
13972 { this->iface_->issue_nil_check(); }
13973
13974 private:
13975 // The interface for which we are getting information.
13976 Expression* iface_;
13977 // What information we want.
13978 Interface_info iface_info_;
13979 };
13980
13981 // Return the type of the interface info.
13982
13983 Type*
13984 Interface_info_expression::do_type()
13985 {
13986 switch (this->iface_info_)
13987 {
13988 case INTERFACE_INFO_METHODS:
13989 {
13990 Type* pdt = Type::make_type_descriptor_ptr_type();
13991 if (this->iface_->type()->interface_type()->is_empty())
13992 return pdt;
13993
13994 Location loc = this->location();
13995 Struct_field_list* sfl = new Struct_field_list();
13996 sfl->push_back(
13997 Struct_field(Typed_identifier("__type_descriptor", pdt, loc)));
13998
13999 Interface_type* itype = this->iface_->type()->interface_type();
14000 for (Typed_identifier_list::const_iterator p = itype->methods()->begin();
14001 p != itype->methods()->end();
14002 ++p)
14003 {
14004 Function_type* ft = p->type()->function_type();
14005 go_assert(ft->receiver() == NULL);
14006
14007 const Typed_identifier_list* params = ft->parameters();
14008 Typed_identifier_list* mparams = new Typed_identifier_list();
14009 if (params != NULL)
14010 mparams->reserve(params->size() + 1);
14011 Type* vt = Type::make_pointer_type(Type::make_void_type());
14012 mparams->push_back(Typed_identifier("", vt, ft->location()));
14013 if (params != NULL)
14014 {
14015 for (Typed_identifier_list::const_iterator pp = params->begin();
14016 pp != params->end();
14017 ++pp)
14018 mparams->push_back(*pp);
14019 }
14020
14021 Typed_identifier_list* mresults = (ft->results() == NULL
14022 ? NULL
14023 : ft->results()->copy());
14024 Backend_function_type* mft =
14025 Type::make_backend_function_type(NULL, mparams, mresults,
14026 ft->location());
14027
14028 std::string fname = Gogo::unpack_hidden_name(p->name());
14029 sfl->push_back(Struct_field(Typed_identifier(fname, mft, loc)));
14030 }
14031
14032 return Type::make_pointer_type(Type::make_struct_type(sfl, loc));
14033 }
14034 case INTERFACE_INFO_OBJECT:
14035 return Type::make_pointer_type(Type::make_void_type());
14036 default:
14037 go_unreachable();
14038 }
14039 }
14040
14041 // Return the backend representation for interface information.
14042
14043 Bexpression*
14044 Interface_info_expression::do_get_backend(Translate_context* context)
14045 {
14046 Gogo* gogo = context->gogo();
14047 Bexpression* biface = this->iface_->get_backend(context);
14048 switch (this->iface_info_)
14049 {
14050 case INTERFACE_INFO_METHODS:
14051 case INTERFACE_INFO_OBJECT:
14052 return gogo->backend()->struct_field_expression(biface, this->iface_info_,
14053 this->location());
14054 break;
14055 default:
14056 go_unreachable();
14057 }
14058 }
14059
14060 // Dump ast representation for an interface info expression.
14061
14062 void
14063 Interface_info_expression::do_dump_expression(
14064 Ast_dump_context* ast_dump_context) const
14065 {
14066 bool is_empty = this->iface_->type()->interface_type()->is_empty();
14067 ast_dump_context->ostream() << "interfaceinfo(";
14068 this->iface_->dump_expression(ast_dump_context);
14069 ast_dump_context->ostream() << ",";
14070 ast_dump_context->ostream() <<
14071 (this->iface_info_ == INTERFACE_INFO_METHODS && !is_empty ? "methods"
14072 : this->iface_info_ == INTERFACE_INFO_TYPE_DESCRIPTOR ? "type_descriptor"
14073 : this->iface_info_ == INTERFACE_INFO_OBJECT ? "object"
14074 : "unknown");
14075 ast_dump_context->ostream() << ")";
14076 }
14077
14078 // Make an interface info expression.
14079
14080 Expression*
14081 Expression::make_interface_info(Expression* iface, Interface_info iface_info,
14082 Location location)
14083 {
14084 return new Interface_info_expression(iface, iface_info, location);
14085 }
14086
14087 // An expression that represents an interface value. The first field is either
14088 // a type descriptor for an empty interface or a pointer to the interface method
14089 // table for a non-empty interface. The second field is always the object.
14090
14091 class Interface_value_expression : public Expression
14092 {
14093 public:
14094 Interface_value_expression(Type* type, Expression* first_field,
14095 Expression* obj, Location location)
14096 : Expression(EXPRESSION_INTERFACE_VALUE, location),
14097 type_(type), first_field_(first_field), obj_(obj)
14098 { }
14099
14100 protected:
14101 int
14102 do_traverse(Traverse*);
14103
14104 Type*
14105 do_type()
14106 { return this->type_; }
14107
14108 void
14109 do_determine_type(const Type_context*)
14110 { go_unreachable(); }
14111
14112 Expression*
14113 do_copy()
14114 {
14115 return new Interface_value_expression(this->type_,
14116 this->first_field_->copy(),
14117 this->obj_->copy(), this->location());
14118 }
14119
14120 Bexpression*
14121 do_get_backend(Translate_context* context);
14122
14123 void
14124 do_dump_expression(Ast_dump_context*) const;
14125
14126 private:
14127 // The type of the interface value.
14128 Type* type_;
14129 // The first field of the interface (either a type descriptor or a pointer
14130 // to the method table.
14131 Expression* first_field_;
14132 // The underlying object of the interface.
14133 Expression* obj_;
14134 };
14135
14136 int
14137 Interface_value_expression::do_traverse(Traverse* traverse)
14138 {
14139 if (Expression::traverse(&this->first_field_, traverse) == TRAVERSE_EXIT
14140 || Expression::traverse(&this->obj_, traverse) == TRAVERSE_EXIT)
14141 return TRAVERSE_EXIT;
14142 return TRAVERSE_CONTINUE;
14143 }
14144
14145 Bexpression*
14146 Interface_value_expression::do_get_backend(Translate_context* context)
14147 {
14148 std::vector<Bexpression*> vals(2);
14149 vals[0] = this->first_field_->get_backend(context);
14150 vals[1] = this->obj_->get_backend(context);
14151
14152 Gogo* gogo = context->gogo();
14153 Btype* btype = this->type_->get_backend(gogo);
14154 return gogo->backend()->constructor_expression(btype, vals, this->location());
14155 }
14156
14157 void
14158 Interface_value_expression::do_dump_expression(
14159 Ast_dump_context* ast_dump_context) const
14160 {
14161 ast_dump_context->ostream() << "interfacevalue(";
14162 ast_dump_context->ostream() <<
14163 (this->type_->interface_type()->is_empty()
14164 ? "type_descriptor: "
14165 : "methods: ");
14166 this->first_field_->dump_expression(ast_dump_context);
14167 ast_dump_context->ostream() << ", object: ";
14168 this->obj_->dump_expression(ast_dump_context);
14169 ast_dump_context->ostream() << ")";
14170 }
14171
14172 Expression*
14173 Expression::make_interface_value(Type* type, Expression* first_value,
14174 Expression* object, Location location)
14175 {
14176 return new Interface_value_expression(type, first_value, object, location);
14177 }
14178
14179 // An interface method table for a pair of types: an interface type and a type
14180 // that implements that interface.
14181
14182 class Interface_mtable_expression : public Expression
14183 {
14184 public:
14185 Interface_mtable_expression(Interface_type* itype, Type* type,
14186 bool is_pointer, Location location)
14187 : Expression(EXPRESSION_INTERFACE_MTABLE, location),
14188 itype_(itype), type_(type), is_pointer_(is_pointer),
14189 method_table_type_(NULL), bvar_(NULL)
14190 { }
14191
14192 protected:
14193 int
14194 do_traverse(Traverse*);
14195
14196 Type*
14197 do_type();
14198
14199 bool
14200 is_immutable() const
14201 { return true; }
14202
14203 void
14204 do_determine_type(const Type_context*)
14205 { go_unreachable(); }
14206
14207 Expression*
14208 do_copy()
14209 {
14210 return new Interface_mtable_expression(this->itype_, this->type_,
14211 this->is_pointer_, this->location());
14212 }
14213
14214 bool
14215 do_is_addressable() const
14216 { return true; }
14217
14218 Bexpression*
14219 do_get_backend(Translate_context* context);
14220
14221 void
14222 do_dump_expression(Ast_dump_context*) const;
14223
14224 private:
14225 // The interface type for which the methods are defined.
14226 Interface_type* itype_;
14227 // The type to construct the interface method table for.
14228 Type* type_;
14229 // Whether this table contains the method set for the receiver type or the
14230 // pointer receiver type.
14231 bool is_pointer_;
14232 // The type of the method table.
14233 Type* method_table_type_;
14234 // The backend variable that refers to the interface method table.
14235 Bvariable* bvar_;
14236 };
14237
14238 int
14239 Interface_mtable_expression::do_traverse(Traverse* traverse)
14240 {
14241 if (Type::traverse(this->itype_, traverse) == TRAVERSE_EXIT
14242 || Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
14243 return TRAVERSE_EXIT;
14244 return TRAVERSE_CONTINUE;
14245 }
14246
14247 Type*
14248 Interface_mtable_expression::do_type()
14249 {
14250 if (this->method_table_type_ != NULL)
14251 return this->method_table_type_;
14252
14253 const Typed_identifier_list* interface_methods = this->itype_->methods();
14254 go_assert(!interface_methods->empty());
14255
14256 Struct_field_list* sfl = new Struct_field_list;
14257 Typed_identifier tid("__type_descriptor", Type::make_type_descriptor_ptr_type(),
14258 this->location());
14259 sfl->push_back(Struct_field(tid));
14260 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14261 p != interface_methods->end();
14262 ++p)
14263 sfl->push_back(Struct_field(*p));
14264 this->method_table_type_ = Type::make_struct_type(sfl, this->location());
14265 return this->method_table_type_;
14266 }
14267
14268 Bexpression*
14269 Interface_mtable_expression::do_get_backend(Translate_context* context)
14270 {
14271 Gogo* gogo = context->gogo();
14272 Location loc = Linemap::predeclared_location();
14273 if (this->bvar_ != NULL)
14274 return gogo->backend()->var_expression(this->bvar_, this->location());
14275
14276 const Typed_identifier_list* interface_methods = this->itype_->methods();
14277 go_assert(!interface_methods->empty());
14278
14279 std::string mangled_name = ((this->is_pointer_ ? "__go_pimt__" : "__go_imt_")
14280 + this->itype_->mangled_name(gogo)
14281 + "__"
14282 + this->type_->mangled_name(gogo));
14283
14284 // See whether this interface has any hidden methods.
14285 bool has_hidden_methods = false;
14286 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14287 p != interface_methods->end();
14288 ++p)
14289 {
14290 if (Gogo::is_hidden_name(p->name()))
14291 {
14292 has_hidden_methods = true;
14293 break;
14294 }
14295 }
14296
14297 // We already know that the named type is convertible to the
14298 // interface. If the interface has hidden methods, and the named
14299 // type is defined in a different package, then the interface
14300 // conversion table will be defined by that other package.
14301 if (has_hidden_methods
14302 && this->type_->named_type() != NULL
14303 && this->type_->named_type()->named_object()->package() != NULL)
14304 {
14305 Btype* btype = this->type()->get_backend(gogo);
14306 this->bvar_ =
14307 gogo->backend()->immutable_struct_reference(mangled_name, btype, loc);
14308 return gogo->backend()->var_expression(this->bvar_, this->location());
14309 }
14310
14311 // The first element is the type descriptor.
14312 Type* td_type;
14313 if (!this->is_pointer_)
14314 td_type = this->type_;
14315 else
14316 td_type = Type::make_pointer_type(this->type_);
14317
14318 // Build an interface method table for a type: a type descriptor followed by a
14319 // list of function pointers, one for each interface method. This is used for
14320 // interfaces.
14321 Expression_list* svals = new Expression_list();
14322 svals->push_back(Expression::make_type_descriptor(td_type, loc));
14323
14324 Named_type* nt = this->type_->named_type();
14325 Struct_type* st = this->type_->struct_type();
14326 go_assert(nt != NULL || st != NULL);
14327
14328 for (Typed_identifier_list::const_iterator p = interface_methods->begin();
14329 p != interface_methods->end();
14330 ++p)
14331 {
14332 bool is_ambiguous;
14333 Method* m;
14334 if (nt != NULL)
14335 m = nt->method_function(p->name(), &is_ambiguous);
14336 else
14337 m = st->method_function(p->name(), &is_ambiguous);
14338 go_assert(m != NULL);
14339 Named_object* no = m->named_object();
14340
14341 go_assert(no->is_function() || no->is_function_declaration());
14342 svals->push_back(Expression::make_func_code_reference(no, loc));
14343 }
14344
14345 Btype* btype = this->type()->get_backend(gogo);
14346 Expression* mtable = Expression::make_struct_composite_literal(this->type(),
14347 svals, loc);
14348 Bexpression* ctor = mtable->get_backend(context);
14349
14350 bool is_public = has_hidden_methods && this->type_->named_type() != NULL;
14351 this->bvar_ = gogo->backend()->immutable_struct(mangled_name, false,
14352 !is_public, btype, loc);
14353 gogo->backend()->immutable_struct_set_init(this->bvar_, mangled_name, false,
14354 !is_public, btype, loc, ctor);
14355 return gogo->backend()->var_expression(this->bvar_, loc);
14356 }
14357
14358 void
14359 Interface_mtable_expression::do_dump_expression(
14360 Ast_dump_context* ast_dump_context) const
14361 {
14362 ast_dump_context->ostream() << "__go_"
14363 << (this->is_pointer_ ? "pimt__" : "imt_");
14364 ast_dump_context->dump_type(this->itype_);
14365 ast_dump_context->ostream() << "__";
14366 ast_dump_context->dump_type(this->type_);
14367 }
14368
14369 Expression*
14370 Expression::make_interface_mtable_ref(Interface_type* itype, Type* type,
14371 bool is_pointer, Location location)
14372 {
14373 return new Interface_mtable_expression(itype, type, is_pointer, location);
14374 }
14375
14376 // An expression which evaluates to the offset of a field within a
14377 // struct. This, like Type_info_expression, q.v., is only used to
14378 // initialize fields of a type descriptor.
14379
14380 class Struct_field_offset_expression : public Expression
14381 {
14382 public:
14383 Struct_field_offset_expression(Struct_type* type, const Struct_field* field)
14384 : Expression(EXPRESSION_STRUCT_FIELD_OFFSET,
14385 Linemap::predeclared_location()),
14386 type_(type), field_(field)
14387 { }
14388
14389 protected:
14390 bool
14391 do_is_immutable() const
14392 { return true; }
14393
14394 Type*
14395 do_type()
14396 { return Type::lookup_integer_type("uintptr"); }
14397
14398 void
14399 do_determine_type(const Type_context*)
14400 { }
14401
14402 Expression*
14403 do_copy()
14404 { return this; }
14405
14406 Bexpression*
14407 do_get_backend(Translate_context* context);
14408
14409 void
14410 do_dump_expression(Ast_dump_context*) const;
14411
14412 private:
14413 // The type of the struct.
14414 Struct_type* type_;
14415 // The field.
14416 const Struct_field* field_;
14417 };
14418
14419 // Return the backend representation for a struct field offset.
14420
14421 Bexpression*
14422 Struct_field_offset_expression::do_get_backend(Translate_context* context)
14423 {
14424 const Struct_field_list* fields = this->type_->fields();
14425 Struct_field_list::const_iterator p;
14426 unsigned i = 0;
14427 for (p = fields->begin();
14428 p != fields->end();
14429 ++p, ++i)
14430 if (&*p == this->field_)
14431 break;
14432 go_assert(&*p == this->field_);
14433
14434 Gogo* gogo = context->gogo();
14435 Btype* btype = this->type_->get_backend(gogo);
14436
14437 int64_t offset = gogo->backend()->type_field_offset(btype, i);
14438 Type* uptr_type = Type::lookup_integer_type("uintptr");
14439 Expression* ret =
14440 Expression::make_integer_int64(offset, uptr_type,
14441 Linemap::predeclared_location());
14442 return ret->get_backend(context);
14443 }
14444
14445 // Dump ast representation for a struct field offset expression.
14446
14447 void
14448 Struct_field_offset_expression::do_dump_expression(
14449 Ast_dump_context* ast_dump_context) const
14450 {
14451 ast_dump_context->ostream() << "unsafe.Offsetof(";
14452 ast_dump_context->dump_type(this->type_);
14453 ast_dump_context->ostream() << '.';
14454 ast_dump_context->ostream() <<
14455 Gogo::message_name(this->field_->field_name());
14456 ast_dump_context->ostream() << ")";
14457 }
14458
14459 // Make an expression for a struct field offset.
14460
14461 Expression*
14462 Expression::make_struct_field_offset(Struct_type* type,
14463 const Struct_field* field)
14464 {
14465 return new Struct_field_offset_expression(type, field);
14466 }
14467
14468 // An expression which evaluates to a pointer to the map descriptor of
14469 // a map type.
14470
14471 class Map_descriptor_expression : public Expression
14472 {
14473 public:
14474 Map_descriptor_expression(Map_type* type, Location location)
14475 : Expression(EXPRESSION_MAP_DESCRIPTOR, location),
14476 type_(type)
14477 { }
14478
14479 protected:
14480 Type*
14481 do_type()
14482 { return Type::make_pointer_type(Map_type::make_map_descriptor_type()); }
14483
14484 void
14485 do_determine_type(const Type_context*)
14486 { }
14487
14488 Expression*
14489 do_copy()
14490 { return this; }
14491
14492 Bexpression*
14493 do_get_backend(Translate_context* context)
14494 {
14495 return this->type_->map_descriptor_pointer(context->gogo(),
14496 this->location());
14497 }
14498
14499 void
14500 do_dump_expression(Ast_dump_context*) const;
14501
14502 private:
14503 // The type for which this is the descriptor.
14504 Map_type* type_;
14505 };
14506
14507 // Dump ast representation for a map descriptor expression.
14508
14509 void
14510 Map_descriptor_expression::do_dump_expression(
14511 Ast_dump_context* ast_dump_context) const
14512 {
14513 ast_dump_context->ostream() << "map_descriptor(";
14514 ast_dump_context->dump_type(this->type_);
14515 ast_dump_context->ostream() << ")";
14516 }
14517
14518 // Make a map descriptor expression.
14519
14520 Expression*
14521 Expression::make_map_descriptor(Map_type* type, Location location)
14522 {
14523 return new Map_descriptor_expression(type, location);
14524 }
14525
14526 // An expression which evaluates to the address of an unnamed label.
14527
14528 class Label_addr_expression : public Expression
14529 {
14530 public:
14531 Label_addr_expression(Label* label, Location location)
14532 : Expression(EXPRESSION_LABEL_ADDR, location),
14533 label_(label)
14534 { }
14535
14536 protected:
14537 Type*
14538 do_type()
14539 { return Type::make_pointer_type(Type::make_void_type()); }
14540
14541 void
14542 do_determine_type(const Type_context*)
14543 { }
14544
14545 Expression*
14546 do_copy()
14547 { return new Label_addr_expression(this->label_, this->location()); }
14548
14549 Bexpression*
14550 do_get_backend(Translate_context* context)
14551 { return this->label_->get_addr(context, this->location()); }
14552
14553 void
14554 do_dump_expression(Ast_dump_context* ast_dump_context) const
14555 { ast_dump_context->ostream() << this->label_->name(); }
14556
14557 private:
14558 // The label whose address we are taking.
14559 Label* label_;
14560 };
14561
14562 // Make an expression for the address of an unnamed label.
14563
14564 Expression*
14565 Expression::make_label_addr(Label* label, Location location)
14566 {
14567 return new Label_addr_expression(label, location);
14568 }
14569
14570 // Class Conditional_expression.
14571
14572 // Traversal.
14573
14574 int
14575 Conditional_expression::do_traverse(Traverse* traverse)
14576 {
14577 if (Expression::traverse(&this->cond_, traverse) == TRAVERSE_EXIT
14578 || Expression::traverse(&this->then_, traverse) == TRAVERSE_EXIT
14579 || Expression::traverse(&this->else_, traverse) == TRAVERSE_EXIT)
14580 return TRAVERSE_EXIT;
14581 return TRAVERSE_CONTINUE;
14582 }
14583
14584 // Return the type of the conditional expression.
14585
14586 Type*
14587 Conditional_expression::do_type()
14588 {
14589 Type* result_type = Type::make_void_type();
14590 if (Type::are_identical(this->then_->type(), this->else_->type(), false,
14591 NULL))
14592 result_type = this->then_->type();
14593 else if (this->then_->is_nil_expression()
14594 || this->else_->is_nil_expression())
14595 result_type = (!this->then_->is_nil_expression()
14596 ? this->then_->type()
14597 : this->else_->type());
14598 return result_type;
14599 }
14600
14601 // Determine type for a conditional expression.
14602
14603 void
14604 Conditional_expression::do_determine_type(const Type_context* context)
14605 {
14606 this->cond_->determine_type_no_context();
14607 this->then_->determine_type(context);
14608 this->else_->determine_type(context);
14609 }
14610
14611 // Get the backend representation of a conditional expression.
14612
14613 Bexpression*
14614 Conditional_expression::do_get_backend(Translate_context* context)
14615 {
14616 Gogo* gogo = context->gogo();
14617 Btype* result_btype = this->type()->get_backend(gogo);
14618 Bexpression* cond = this->cond_->get_backend(context);
14619 Bexpression* then = this->then_->get_backend(context);
14620 Bexpression* belse = this->else_->get_backend(context);
14621 return gogo->backend()->conditional_expression(result_btype, cond, then,
14622 belse, this->location());
14623 }
14624
14625 // Dump ast representation of a conditional expression.
14626
14627 void
14628 Conditional_expression::do_dump_expression(
14629 Ast_dump_context* ast_dump_context) const
14630 {
14631 ast_dump_context->ostream() << "(";
14632 ast_dump_context->dump_expression(this->cond_);
14633 ast_dump_context->ostream() << " ? ";
14634 ast_dump_context->dump_expression(this->then_);
14635 ast_dump_context->ostream() << " : ";
14636 ast_dump_context->dump_expression(this->else_);
14637 ast_dump_context->ostream() << ") ";
14638 }
14639
14640 // Make a conditional expression.
14641
14642 Expression*
14643 Expression::make_conditional(Expression* cond, Expression* then,
14644 Expression* else_expr, Location location)
14645 {
14646 return new Conditional_expression(cond, then, else_expr, location);
14647 }
14648
14649 // Class Compound_expression.
14650
14651 // Traversal.
14652
14653 int
14654 Compound_expression::do_traverse(Traverse* traverse)
14655 {
14656 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT
14657 || Expression::traverse(&this->expr_, traverse) == TRAVERSE_EXIT)
14658 return TRAVERSE_EXIT;
14659 return TRAVERSE_CONTINUE;
14660 }
14661
14662 // Return the type of the compound expression.
14663
14664 Type*
14665 Compound_expression::do_type()
14666 {
14667 return this->expr_->type();
14668 }
14669
14670 // Determine type for a compound expression.
14671
14672 void
14673 Compound_expression::do_determine_type(const Type_context* context)
14674 {
14675 this->init_->determine_type_no_context();
14676 this->expr_->determine_type(context);
14677 }
14678
14679 // Get the backend representation of a compound expression.
14680
14681 Bexpression*
14682 Compound_expression::do_get_backend(Translate_context* context)
14683 {
14684 Gogo* gogo = context->gogo();
14685 Bexpression* binit = this->init_->get_backend(context);
14686 Bstatement* init_stmt = gogo->backend()->expression_statement(binit);
14687 Bexpression* bexpr = this->expr_->get_backend(context);
14688 return gogo->backend()->compound_expression(init_stmt, bexpr,
14689 this->location());
14690 }
14691
14692 // Dump ast representation of a conditional expression.
14693
14694 void
14695 Compound_expression::do_dump_expression(
14696 Ast_dump_context* ast_dump_context) const
14697 {
14698 ast_dump_context->ostream() << "(";
14699 ast_dump_context->dump_expression(this->init_);
14700 ast_dump_context->ostream() << ",";
14701 ast_dump_context->dump_expression(this->expr_);
14702 ast_dump_context->ostream() << ") ";
14703 }
14704
14705 // Make a compound expression.
14706
14707 Expression*
14708 Expression::make_compound(Expression* init, Expression* expr, Location location)
14709 {
14710 return new Compound_expression(init, expr, location);
14711 }
14712
14713 // Import an expression. This comes at the end in order to see the
14714 // various class definitions.
14715
14716 Expression*
14717 Expression::import_expression(Import* imp)
14718 {
14719 int c = imp->peek_char();
14720 if (imp->match_c_string("- ")
14721 || imp->match_c_string("! ")
14722 || imp->match_c_string("^ "))
14723 return Unary_expression::do_import(imp);
14724 else if (c == '(')
14725 return Binary_expression::do_import(imp);
14726 else if (imp->match_c_string("true")
14727 || imp->match_c_string("false"))
14728 return Boolean_expression::do_import(imp);
14729 else if (c == '"')
14730 return String_expression::do_import(imp);
14731 else if (c == '-' || (c >= '0' && c <= '9'))
14732 {
14733 // This handles integers, floats and complex constants.
14734 return Integer_expression::do_import(imp);
14735 }
14736 else if (imp->match_c_string("nil"))
14737 return Nil_expression::do_import(imp);
14738 else if (imp->match_c_string("convert"))
14739 return Type_conversion_expression::do_import(imp);
14740 else
14741 {
14742 error_at(imp->location(), "import error: expected expression");
14743 return Expression::make_error(imp->location());
14744 }
14745 }
14746
14747 // Class Expression_list.
14748
14749 // Traverse the list.
14750
14751 int
14752 Expression_list::traverse(Traverse* traverse)
14753 {
14754 for (Expression_list::iterator p = this->begin();
14755 p != this->end();
14756 ++p)
14757 {
14758 if (*p != NULL)
14759 {
14760 if (Expression::traverse(&*p, traverse) == TRAVERSE_EXIT)
14761 return TRAVERSE_EXIT;
14762 }
14763 }
14764 return TRAVERSE_CONTINUE;
14765 }
14766
14767 // Copy the list.
14768
14769 Expression_list*
14770 Expression_list::copy()
14771 {
14772 Expression_list* ret = new Expression_list();
14773 for (Expression_list::iterator p = this->begin();
14774 p != this->end();
14775 ++p)
14776 {
14777 if (*p == NULL)
14778 ret->push_back(NULL);
14779 else
14780 ret->push_back((*p)->copy());
14781 }
14782 return ret;
14783 }
14784
14785 // Return whether an expression list has an error expression.
14786
14787 bool
14788 Expression_list::contains_error() const
14789 {
14790 for (Expression_list::const_iterator p = this->begin();
14791 p != this->end();
14792 ++p)
14793 if (*p != NULL && (*p)->is_error_expression())
14794 return true;
14795 return false;
14796 }
14797
14798 // Class Numeric_constant.
14799
14800 // Destructor.
14801
14802 Numeric_constant::~Numeric_constant()
14803 {
14804 this->clear();
14805 }
14806
14807 // Copy constructor.
14808
14809 Numeric_constant::Numeric_constant(const Numeric_constant& a)
14810 : classification_(a.classification_), type_(a.type_)
14811 {
14812 switch (a.classification_)
14813 {
14814 case NC_INVALID:
14815 break;
14816 case NC_INT:
14817 case NC_RUNE:
14818 mpz_init_set(this->u_.int_val, a.u_.int_val);
14819 break;
14820 case NC_FLOAT:
14821 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14822 break;
14823 case NC_COMPLEX:
14824 mpc_init2(this->u_.complex_val, mpc_precision);
14825 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
14826 break;
14827 default:
14828 go_unreachable();
14829 }
14830 }
14831
14832 // Assignment operator.
14833
14834 Numeric_constant&
14835 Numeric_constant::operator=(const Numeric_constant& a)
14836 {
14837 this->clear();
14838 this->classification_ = a.classification_;
14839 this->type_ = a.type_;
14840 switch (a.classification_)
14841 {
14842 case NC_INVALID:
14843 break;
14844 case NC_INT:
14845 case NC_RUNE:
14846 mpz_init_set(this->u_.int_val, a.u_.int_val);
14847 break;
14848 case NC_FLOAT:
14849 mpfr_init_set(this->u_.float_val, a.u_.float_val, GMP_RNDN);
14850 break;
14851 case NC_COMPLEX:
14852 mpc_init2(this->u_.complex_val, mpc_precision);
14853 mpc_set(this->u_.complex_val, a.u_.complex_val, MPC_RNDNN);
14854 break;
14855 default:
14856 go_unreachable();
14857 }
14858 return *this;
14859 }
14860
14861 // Clear the contents.
14862
14863 void
14864 Numeric_constant::clear()
14865 {
14866 switch (this->classification_)
14867 {
14868 case NC_INVALID:
14869 break;
14870 case NC_INT:
14871 case NC_RUNE:
14872 mpz_clear(this->u_.int_val);
14873 break;
14874 case NC_FLOAT:
14875 mpfr_clear(this->u_.float_val);
14876 break;
14877 case NC_COMPLEX:
14878 mpc_clear(this->u_.complex_val);
14879 break;
14880 default:
14881 go_unreachable();
14882 }
14883 this->classification_ = NC_INVALID;
14884 }
14885
14886 // Set to an unsigned long value.
14887
14888 void
14889 Numeric_constant::set_unsigned_long(Type* type, unsigned long val)
14890 {
14891 this->clear();
14892 this->classification_ = NC_INT;
14893 this->type_ = type;
14894 mpz_init_set_ui(this->u_.int_val, val);
14895 }
14896
14897 // Set to an integer value.
14898
14899 void
14900 Numeric_constant::set_int(Type* type, const mpz_t val)
14901 {
14902 this->clear();
14903 this->classification_ = NC_INT;
14904 this->type_ = type;
14905 mpz_init_set(this->u_.int_val, val);
14906 }
14907
14908 // Set to a rune value.
14909
14910 void
14911 Numeric_constant::set_rune(Type* type, const mpz_t val)
14912 {
14913 this->clear();
14914 this->classification_ = NC_RUNE;
14915 this->type_ = type;
14916 mpz_init_set(this->u_.int_val, val);
14917 }
14918
14919 // Set to a floating point value.
14920
14921 void
14922 Numeric_constant::set_float(Type* type, const mpfr_t val)
14923 {
14924 this->clear();
14925 this->classification_ = NC_FLOAT;
14926 this->type_ = type;
14927 // Numeric constants do not have negative zero values, so remove
14928 // them here. They also don't have infinity or NaN values, but we
14929 // should never see them here.
14930 if (mpfr_zero_p(val))
14931 mpfr_init_set_ui(this->u_.float_val, 0, GMP_RNDN);
14932 else
14933 mpfr_init_set(this->u_.float_val, val, GMP_RNDN);
14934 }
14935
14936 // Set to a complex value.
14937
14938 void
14939 Numeric_constant::set_complex(Type* type, const mpc_t val)
14940 {
14941 this->clear();
14942 this->classification_ = NC_COMPLEX;
14943 this->type_ = type;
14944 mpc_init2(this->u_.complex_val, mpc_precision);
14945 mpc_set(this->u_.complex_val, val, MPC_RNDNN);
14946 }
14947
14948 // Get an int value.
14949
14950 void
14951 Numeric_constant::get_int(mpz_t* val) const
14952 {
14953 go_assert(this->is_int());
14954 mpz_init_set(*val, this->u_.int_val);
14955 }
14956
14957 // Get a rune value.
14958
14959 void
14960 Numeric_constant::get_rune(mpz_t* val) const
14961 {
14962 go_assert(this->is_rune());
14963 mpz_init_set(*val, this->u_.int_val);
14964 }
14965
14966 // Get a floating point value.
14967
14968 void
14969 Numeric_constant::get_float(mpfr_t* val) const
14970 {
14971 go_assert(this->is_float());
14972 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
14973 }
14974
14975 // Get a complex value.
14976
14977 void
14978 Numeric_constant::get_complex(mpc_t* val) const
14979 {
14980 go_assert(this->is_complex());
14981 mpc_init2(*val, mpc_precision);
14982 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
14983 }
14984
14985 // Express value as unsigned long if possible.
14986
14987 Numeric_constant::To_unsigned_long
14988 Numeric_constant::to_unsigned_long(unsigned long* val) const
14989 {
14990 switch (this->classification_)
14991 {
14992 case NC_INT:
14993 case NC_RUNE:
14994 return this->mpz_to_unsigned_long(this->u_.int_val, val);
14995 case NC_FLOAT:
14996 return this->mpfr_to_unsigned_long(this->u_.float_val, val);
14997 case NC_COMPLEX:
14998 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
14999 return NC_UL_NOTINT;
15000 return this->mpfr_to_unsigned_long(mpc_realref(this->u_.complex_val),
15001 val);
15002 default:
15003 go_unreachable();
15004 }
15005 }
15006
15007 // Express integer value as unsigned long if possible.
15008
15009 Numeric_constant::To_unsigned_long
15010 Numeric_constant::mpz_to_unsigned_long(const mpz_t ival,
15011 unsigned long *val) const
15012 {
15013 if (mpz_sgn(ival) < 0)
15014 return NC_UL_NEGATIVE;
15015 unsigned long ui = mpz_get_ui(ival);
15016 if (mpz_cmp_ui(ival, ui) != 0)
15017 return NC_UL_BIG;
15018 *val = ui;
15019 return NC_UL_VALID;
15020 }
15021
15022 // Express floating point value as unsigned long if possible.
15023
15024 Numeric_constant::To_unsigned_long
15025 Numeric_constant::mpfr_to_unsigned_long(const mpfr_t fval,
15026 unsigned long *val) const
15027 {
15028 if (!mpfr_integer_p(fval))
15029 return NC_UL_NOTINT;
15030 mpz_t ival;
15031 mpz_init(ival);
15032 mpfr_get_z(ival, fval, GMP_RNDN);
15033 To_unsigned_long ret = this->mpz_to_unsigned_long(ival, val);
15034 mpz_clear(ival);
15035 return ret;
15036 }
15037
15038 // Convert value to integer if possible.
15039
15040 bool
15041 Numeric_constant::to_int(mpz_t* val) const
15042 {
15043 switch (this->classification_)
15044 {
15045 case NC_INT:
15046 case NC_RUNE:
15047 mpz_init_set(*val, this->u_.int_val);
15048 return true;
15049 case NC_FLOAT:
15050 if (!mpfr_integer_p(this->u_.float_val))
15051 return false;
15052 mpz_init(*val);
15053 mpfr_get_z(*val, this->u_.float_val, GMP_RNDN);
15054 return true;
15055 case NC_COMPLEX:
15056 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val))
15057 || !mpfr_integer_p(mpc_realref(this->u_.complex_val)))
15058 return false;
15059 mpz_init(*val);
15060 mpfr_get_z(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15061 return true;
15062 default:
15063 go_unreachable();
15064 }
15065 }
15066
15067 // Convert value to floating point if possible.
15068
15069 bool
15070 Numeric_constant::to_float(mpfr_t* val) const
15071 {
15072 switch (this->classification_)
15073 {
15074 case NC_INT:
15075 case NC_RUNE:
15076 mpfr_init_set_z(*val, this->u_.int_val, GMP_RNDN);
15077 return true;
15078 case NC_FLOAT:
15079 mpfr_init_set(*val, this->u_.float_val, GMP_RNDN);
15080 return true;
15081 case NC_COMPLEX:
15082 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15083 return false;
15084 mpfr_init_set(*val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15085 return true;
15086 default:
15087 go_unreachable();
15088 }
15089 }
15090
15091 // Convert value to complex.
15092
15093 bool
15094 Numeric_constant::to_complex(mpc_t* val) const
15095 {
15096 mpc_init2(*val, mpc_precision);
15097 switch (this->classification_)
15098 {
15099 case NC_INT:
15100 case NC_RUNE:
15101 mpc_set_z(*val, this->u_.int_val, MPC_RNDNN);
15102 return true;
15103 case NC_FLOAT:
15104 mpc_set_fr(*val, this->u_.float_val, MPC_RNDNN);
15105 return true;
15106 case NC_COMPLEX:
15107 mpc_set(*val, this->u_.complex_val, MPC_RNDNN);
15108 return true;
15109 default:
15110 go_unreachable();
15111 }
15112 }
15113
15114 // Get the type.
15115
15116 Type*
15117 Numeric_constant::type() const
15118 {
15119 if (this->type_ != NULL)
15120 return this->type_;
15121 switch (this->classification_)
15122 {
15123 case NC_INT:
15124 return Type::make_abstract_integer_type();
15125 case NC_RUNE:
15126 return Type::make_abstract_character_type();
15127 case NC_FLOAT:
15128 return Type::make_abstract_float_type();
15129 case NC_COMPLEX:
15130 return Type::make_abstract_complex_type();
15131 default:
15132 go_unreachable();
15133 }
15134 }
15135
15136 // If the constant can be expressed in TYPE, then set the type of the
15137 // constant to TYPE and return true. Otherwise return false, and, if
15138 // ISSUE_ERROR is true, report an appropriate error message.
15139
15140 bool
15141 Numeric_constant::set_type(Type* type, bool issue_error, Location loc)
15142 {
15143 bool ret;
15144 if (type == NULL || type->is_error())
15145 ret = true;
15146 else if (type->integer_type() != NULL)
15147 ret = this->check_int_type(type->integer_type(), issue_error, loc);
15148 else if (type->float_type() != NULL)
15149 ret = this->check_float_type(type->float_type(), issue_error, loc);
15150 else if (type->complex_type() != NULL)
15151 ret = this->check_complex_type(type->complex_type(), issue_error, loc);
15152 else
15153 {
15154 ret = false;
15155 if (issue_error)
15156 go_assert(saw_errors());
15157 }
15158 if (ret)
15159 this->type_ = type;
15160 return ret;
15161 }
15162
15163 // Check whether the constant can be expressed in an integer type.
15164
15165 bool
15166 Numeric_constant::check_int_type(Integer_type* type, bool issue_error,
15167 Location location) const
15168 {
15169 mpz_t val;
15170 switch (this->classification_)
15171 {
15172 case NC_INT:
15173 case NC_RUNE:
15174 mpz_init_set(val, this->u_.int_val);
15175 break;
15176
15177 case NC_FLOAT:
15178 if (!mpfr_integer_p(this->u_.float_val))
15179 {
15180 if (issue_error)
15181 error_at(location, "floating point constant truncated to integer");
15182 return false;
15183 }
15184 mpz_init(val);
15185 mpfr_get_z(val, this->u_.float_val, GMP_RNDN);
15186 break;
15187
15188 case NC_COMPLEX:
15189 if (!mpfr_integer_p(mpc_realref(this->u_.complex_val))
15190 || !mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15191 {
15192 if (issue_error)
15193 error_at(location, "complex constant truncated to integer");
15194 return false;
15195 }
15196 mpz_init(val);
15197 mpfr_get_z(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15198 break;
15199
15200 default:
15201 go_unreachable();
15202 }
15203
15204 bool ret;
15205 if (type->is_abstract())
15206 ret = true;
15207 else
15208 {
15209 int bits = mpz_sizeinbase(val, 2);
15210 if (type->is_unsigned())
15211 {
15212 // For an unsigned type we can only accept a nonnegative
15213 // number, and we must be able to represents at least BITS.
15214 ret = mpz_sgn(val) >= 0 && bits <= type->bits();
15215 }
15216 else
15217 {
15218 // For a signed type we need an extra bit to indicate the
15219 // sign. We have to handle the most negative integer
15220 // specially.
15221 ret = (bits + 1 <= type->bits()
15222 || (bits <= type->bits()
15223 && mpz_sgn(val) < 0
15224 && (mpz_scan1(val, 0)
15225 == static_cast<unsigned long>(type->bits() - 1))
15226 && mpz_scan0(val, type->bits()) == ULONG_MAX));
15227 }
15228 }
15229
15230 if (!ret && issue_error)
15231 error_at(location, "integer constant overflow");
15232
15233 return ret;
15234 }
15235
15236 // Check whether the constant can be expressed in a floating point
15237 // type.
15238
15239 bool
15240 Numeric_constant::check_float_type(Float_type* type, bool issue_error,
15241 Location location)
15242 {
15243 mpfr_t val;
15244 switch (this->classification_)
15245 {
15246 case NC_INT:
15247 case NC_RUNE:
15248 mpfr_init_set_z(val, this->u_.int_val, GMP_RNDN);
15249 break;
15250
15251 case NC_FLOAT:
15252 mpfr_init_set(val, this->u_.float_val, GMP_RNDN);
15253 break;
15254
15255 case NC_COMPLEX:
15256 if (!mpfr_zero_p(mpc_imagref(this->u_.complex_val)))
15257 {
15258 if (issue_error)
15259 error_at(location, "complex constant truncated to float");
15260 return false;
15261 }
15262 mpfr_init_set(val, mpc_realref(this->u_.complex_val), GMP_RNDN);
15263 break;
15264
15265 default:
15266 go_unreachable();
15267 }
15268
15269 bool ret;
15270 if (type->is_abstract())
15271 ret = true;
15272 else if (mpfr_nan_p(val) || mpfr_inf_p(val) || mpfr_zero_p(val))
15273 {
15274 // A NaN or Infinity always fits in the range of the type.
15275 ret = true;
15276 }
15277 else
15278 {
15279 mp_exp_t exp = mpfr_get_exp(val);
15280 mp_exp_t max_exp;
15281 switch (type->bits())
15282 {
15283 case 32:
15284 max_exp = 128;
15285 break;
15286 case 64:
15287 max_exp = 1024;
15288 break;
15289 default:
15290 go_unreachable();
15291 }
15292
15293 ret = exp <= max_exp;
15294
15295 if (ret)
15296 {
15297 // Round the constant to the desired type.
15298 mpfr_t t;
15299 mpfr_init(t);
15300 switch (type->bits())
15301 {
15302 case 32:
15303 mpfr_set_prec(t, 24);
15304 break;
15305 case 64:
15306 mpfr_set_prec(t, 53);
15307 break;
15308 default:
15309 go_unreachable();
15310 }
15311 mpfr_set(t, val, GMP_RNDN);
15312 mpfr_set(val, t, GMP_RNDN);
15313 mpfr_clear(t);
15314
15315 this->set_float(type, val);
15316 }
15317 }
15318
15319 mpfr_clear(val);
15320
15321 if (!ret && issue_error)
15322 error_at(location, "floating point constant overflow");
15323
15324 return ret;
15325 }
15326
15327 // Check whether the constant can be expressed in a complex type.
15328
15329 bool
15330 Numeric_constant::check_complex_type(Complex_type* type, bool issue_error,
15331 Location location)
15332 {
15333 if (type->is_abstract())
15334 return true;
15335
15336 mp_exp_t max_exp;
15337 switch (type->bits())
15338 {
15339 case 64:
15340 max_exp = 128;
15341 break;
15342 case 128:
15343 max_exp = 1024;
15344 break;
15345 default:
15346 go_unreachable();
15347 }
15348
15349 mpc_t val;
15350 mpc_init2(val, mpc_precision);
15351 switch (this->classification_)
15352 {
15353 case NC_INT:
15354 case NC_RUNE:
15355 mpc_set_z(val, this->u_.int_val, MPC_RNDNN);
15356 break;
15357
15358 case NC_FLOAT:
15359 mpc_set_fr(val, this->u_.float_val, MPC_RNDNN);
15360 break;
15361
15362 case NC_COMPLEX:
15363 mpc_set(val, this->u_.complex_val, MPC_RNDNN);
15364 break;
15365
15366 default:
15367 go_unreachable();
15368 }
15369
15370 bool ret = true;
15371 if (!mpfr_nan_p(mpc_realref(val))
15372 && !mpfr_inf_p(mpc_realref(val))
15373 && !mpfr_zero_p(mpc_realref(val))
15374 && mpfr_get_exp(mpc_realref(val)) > max_exp)
15375 {
15376 if (issue_error)
15377 error_at(location, "complex real part overflow");
15378 ret = false;
15379 }
15380
15381 if (!mpfr_nan_p(mpc_imagref(val))
15382 && !mpfr_inf_p(mpc_imagref(val))
15383 && !mpfr_zero_p(mpc_imagref(val))
15384 && mpfr_get_exp(mpc_imagref(val)) > max_exp)
15385 {
15386 if (issue_error)
15387 error_at(location, "complex imaginary part overflow");
15388 ret = false;
15389 }
15390
15391 if (ret)
15392 {
15393 // Round the constant to the desired type.
15394 mpc_t t;
15395 switch (type->bits())
15396 {
15397 case 64:
15398 mpc_init2(t, 24);
15399 break;
15400 case 128:
15401 mpc_init2(t, 53);
15402 break;
15403 default:
15404 go_unreachable();
15405 }
15406 mpc_set(t, val, MPC_RNDNN);
15407 mpc_set(val, t, MPC_RNDNN);
15408 mpc_clear(t);
15409
15410 this->set_complex(type, val);
15411 }
15412
15413 mpc_clear(val);
15414
15415 return ret;
15416 }
15417
15418 // Return an Expression for this value.
15419
15420 Expression*
15421 Numeric_constant::expression(Location loc) const
15422 {
15423 switch (this->classification_)
15424 {
15425 case NC_INT:
15426 return Expression::make_integer_z(&this->u_.int_val, this->type_, loc);
15427 case NC_RUNE:
15428 return Expression::make_character(&this->u_.int_val, this->type_, loc);
15429 case NC_FLOAT:
15430 return Expression::make_float(&this->u_.float_val, this->type_, loc);
15431 case NC_COMPLEX:
15432 return Expression::make_complex(&this->u_.complex_val, this->type_, loc);
15433 default:
15434 go_unreachable();
15435 }
15436 }