* gcc-interface/trans.c (node_has_volatile_full_access) <N_Identifier>:
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob11924e6e224f027ecee12be8372cd6c23ae4345a
1 // types.cc -- Go frontend types.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include <ostream>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "operator.h"
16 #include "expressions.h"
17 #include "statements.h"
18 #include "export.h"
19 #include "import.h"
20 #include "backend.h"
21 #include "types.h"
23 // Forward declarations so that we don't have to make types.h #include
24 // backend.h.
26 static void
27 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
28 bool use_placeholder,
29 std::vector<Backend::Btyped_identifier>* bfields);
31 static void
32 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
33 std::vector<Backend::Btyped_identifier>* bfields);
35 static void
36 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
37 bool use_placeholder,
38 std::vector<Backend::Btyped_identifier>* bfields);
40 // Class Type.
42 Type::Type(Type_classification classification)
43 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
44 gc_symbol_var_(NULL)
48 Type::~Type()
52 // Get the base type for a type--skip names and forward declarations.
54 Type*
55 Type::base()
57 switch (this->classification_)
59 case TYPE_NAMED:
60 return this->named_type()->named_base();
61 case TYPE_FORWARD:
62 return this->forward_declaration_type()->real_type()->base();
63 default:
64 return this;
68 const Type*
69 Type::base() const
71 switch (this->classification_)
73 case TYPE_NAMED:
74 return this->named_type()->named_base();
75 case TYPE_FORWARD:
76 return this->forward_declaration_type()->real_type()->base();
77 default:
78 return this;
82 // Skip defined forward declarations.
84 Type*
85 Type::forwarded()
87 Type* t = this;
88 Forward_declaration_type* ftype = t->forward_declaration_type();
89 while (ftype != NULL && ftype->is_defined())
91 t = ftype->real_type();
92 ftype = t->forward_declaration_type();
94 return t;
97 const Type*
98 Type::forwarded() const
100 const Type* t = this;
101 const Forward_declaration_type* ftype = t->forward_declaration_type();
102 while (ftype != NULL && ftype->is_defined())
104 t = ftype->real_type();
105 ftype = t->forward_declaration_type();
107 return t;
110 // Skip alias definitions.
112 Type*
113 Type::unalias()
115 Type* t = this->forwarded();
116 Named_type* nt = t->named_type();
117 while (nt != NULL && nt->is_alias())
119 t = nt->real_type()->forwarded();
120 nt = t->named_type();
122 return t;
125 const Type*
126 Type::unalias() const
128 const Type* t = this->forwarded();
129 const Named_type* nt = t->named_type();
130 while (nt != NULL && nt->is_alias())
132 t = nt->real_type()->forwarded();
133 nt = t->named_type();
135 return t;
138 // If this is a named type, return it. Otherwise, return NULL.
140 Named_type*
141 Type::named_type()
143 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
146 const Named_type*
147 Type::named_type() const
149 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
152 // Return true if this type is not defined.
154 bool
155 Type::is_undefined() const
157 return this->forwarded()->forward_declaration_type() != NULL;
160 // Return true if this is a basic type: a type which is not composed
161 // of other types, and is not void.
163 bool
164 Type::is_basic_type() const
166 switch (this->classification_)
168 case TYPE_INTEGER:
169 case TYPE_FLOAT:
170 case TYPE_COMPLEX:
171 case TYPE_BOOLEAN:
172 case TYPE_STRING:
173 case TYPE_NIL:
174 return true;
176 case TYPE_ERROR:
177 case TYPE_VOID:
178 case TYPE_FUNCTION:
179 case TYPE_POINTER:
180 case TYPE_STRUCT:
181 case TYPE_ARRAY:
182 case TYPE_MAP:
183 case TYPE_CHANNEL:
184 case TYPE_INTERFACE:
185 return false;
187 case TYPE_NAMED:
188 case TYPE_FORWARD:
189 return this->base()->is_basic_type();
191 default:
192 go_unreachable();
196 // Return true if this is an abstract type.
198 bool
199 Type::is_abstract() const
201 switch (this->classification())
203 case TYPE_INTEGER:
204 return this->integer_type()->is_abstract();
205 case TYPE_FLOAT:
206 return this->float_type()->is_abstract();
207 case TYPE_COMPLEX:
208 return this->complex_type()->is_abstract();
209 case TYPE_STRING:
210 return this->is_abstract_string_type();
211 case TYPE_BOOLEAN:
212 return this->is_abstract_boolean_type();
213 default:
214 return false;
218 // Return a non-abstract version of an abstract type.
220 Type*
221 Type::make_non_abstract_type()
223 go_assert(this->is_abstract());
224 switch (this->classification())
226 case TYPE_INTEGER:
227 if (this->integer_type()->is_rune())
228 return Type::lookup_integer_type("int32");
229 else
230 return Type::lookup_integer_type("int");
231 case TYPE_FLOAT:
232 return Type::lookup_float_type("float64");
233 case TYPE_COMPLEX:
234 return Type::lookup_complex_type("complex128");
235 case TYPE_STRING:
236 return Type::lookup_string_type();
237 case TYPE_BOOLEAN:
238 return Type::lookup_bool_type();
239 default:
240 go_unreachable();
244 // Return true if this is an error type. Don't give an error if we
245 // try to dereference an undefined forwarding type, as this is called
246 // in the parser when the type may legitimately be undefined.
248 bool
249 Type::is_error_type() const
251 const Type* t = this->forwarded();
252 // Note that we return false for an undefined forward type.
253 switch (t->classification_)
255 case TYPE_ERROR:
256 return true;
257 case TYPE_NAMED:
258 return t->named_type()->is_named_error_type();
259 default:
260 return false;
264 // If this is a pointer type, return the type to which it points.
265 // Otherwise, return NULL.
267 Type*
268 Type::points_to() const
270 const Pointer_type* ptype = this->convert<const Pointer_type,
271 TYPE_POINTER>();
272 return ptype == NULL ? NULL : ptype->points_to();
275 // Return whether this is a slice type.
277 bool
278 Type::is_slice_type() const
280 return this->array_type() != NULL && this->array_type()->length() == NULL;
283 // Return whether this is the predeclared constant nil being used as a
284 // type.
286 bool
287 Type::is_nil_constant_as_type() const
289 const Type* t = this->forwarded();
290 if (t->forward_declaration_type() != NULL)
292 const Named_object* no = t->forward_declaration_type()->named_object();
293 if (no->is_unknown())
294 no = no->unknown_value()->real_named_object();
295 if (no != NULL
296 && no->is_const()
297 && no->const_value()->expr()->is_nil_expression())
298 return true;
300 return false;
303 // Traverse a type.
306 Type::traverse(Type* type, Traverse* traverse)
308 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
309 || (traverse->traverse_mask()
310 & Traverse::traverse_expressions) != 0);
311 if (traverse->remember_type(type))
313 // We have already traversed this type.
314 return TRAVERSE_CONTINUE;
316 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
318 int t = traverse->type(type);
319 if (t == TRAVERSE_EXIT)
320 return TRAVERSE_EXIT;
321 else if (t == TRAVERSE_SKIP_COMPONENTS)
322 return TRAVERSE_CONTINUE;
324 // An array type has an expression which we need to traverse if
325 // traverse_expressions is set.
326 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
327 return TRAVERSE_EXIT;
328 return TRAVERSE_CONTINUE;
331 // Default implementation for do_traverse for child class.
334 Type::do_traverse(Traverse*)
336 return TRAVERSE_CONTINUE;
339 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
340 // then return true for all erroneous types; this is used to avoid
341 // cascading errors. If REASON is not NULL, optionally set *REASON to
342 // the reason the types are not identical.
344 bool
345 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
346 std::string* reason)
348 return Type::are_identical_cmp_tags(t1, t2, COMPARE_TAGS,
349 errors_are_identical, reason);
352 // Like are_identical, but with a CMP_TAGS parameter.
354 bool
355 Type::are_identical_cmp_tags(const Type* t1, const Type* t2, Cmp_tags cmp_tags,
356 bool errors_are_identical, std::string* reason)
358 if (t1 == NULL || t2 == NULL)
360 // Something is wrong.
361 return errors_are_identical ? true : t1 == t2;
364 // Skip defined forward declarations. Ignore aliases.
365 t1 = t1->unalias();
366 t2 = t2->unalias();
368 if (t1 == t2)
369 return true;
371 // An undefined forward declaration is an error.
372 if (t1->forward_declaration_type() != NULL
373 || t2->forward_declaration_type() != NULL)
374 return errors_are_identical;
376 // Avoid cascading errors with error types.
377 if (t1->is_error_type() || t2->is_error_type())
379 if (errors_are_identical)
380 return true;
381 return t1->is_error_type() && t2->is_error_type();
384 // Get a good reason for the sink type. Note that the sink type on
385 // the left hand side of an assignment is handled in are_assignable.
386 if (t1->is_sink_type() || t2->is_sink_type())
388 if (reason != NULL)
389 *reason = "invalid use of _";
390 return false;
393 // A named type is only identical to itself.
394 if (t1->named_type() != NULL || t2->named_type() != NULL)
395 return false;
397 // Check type shapes.
398 if (t1->classification() != t2->classification())
399 return false;
401 switch (t1->classification())
403 case TYPE_VOID:
404 case TYPE_BOOLEAN:
405 case TYPE_STRING:
406 case TYPE_NIL:
407 // These types are always identical.
408 return true;
410 case TYPE_INTEGER:
411 return t1->integer_type()->is_identical(t2->integer_type());
413 case TYPE_FLOAT:
414 return t1->float_type()->is_identical(t2->float_type());
416 case TYPE_COMPLEX:
417 return t1->complex_type()->is_identical(t2->complex_type());
419 case TYPE_FUNCTION:
420 return t1->function_type()->is_identical(t2->function_type(),
421 false,
422 cmp_tags,
423 errors_are_identical,
424 reason);
426 case TYPE_POINTER:
427 return Type::are_identical_cmp_tags(t1->points_to(), t2->points_to(),
428 cmp_tags, errors_are_identical,
429 reason);
431 case TYPE_STRUCT:
432 return t1->struct_type()->is_identical(t2->struct_type(), cmp_tags,
433 errors_are_identical);
435 case TYPE_ARRAY:
436 return t1->array_type()->is_identical(t2->array_type(), cmp_tags,
437 errors_are_identical);
439 case TYPE_MAP:
440 return t1->map_type()->is_identical(t2->map_type(), cmp_tags,
441 errors_are_identical);
443 case TYPE_CHANNEL:
444 return t1->channel_type()->is_identical(t2->channel_type(), cmp_tags,
445 errors_are_identical);
447 case TYPE_INTERFACE:
448 return t1->interface_type()->is_identical(t2->interface_type(), cmp_tags,
449 errors_are_identical);
451 case TYPE_CALL_MULTIPLE_RESULT:
452 if (reason != NULL)
453 *reason = "invalid use of multiple-value function call";
454 return false;
456 default:
457 go_unreachable();
461 // Return true if it's OK to have a binary operation with types LHS
462 // and RHS. This is not used for shifts or comparisons.
464 bool
465 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
467 if (Type::are_identical(lhs, rhs, true, NULL))
468 return true;
470 // A constant of abstract bool type may be mixed with any bool type.
471 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
472 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
473 return true;
475 // A constant of abstract string type may be mixed with any string
476 // type.
477 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
478 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
479 return true;
481 lhs = lhs->base();
482 rhs = rhs->base();
484 // A constant of abstract integer, float, or complex type may be
485 // mixed with an integer, float, or complex type.
486 if ((rhs->is_abstract()
487 && (rhs->integer_type() != NULL
488 || rhs->float_type() != NULL
489 || rhs->complex_type() != NULL)
490 && (lhs->integer_type() != NULL
491 || lhs->float_type() != NULL
492 || lhs->complex_type() != NULL))
493 || (lhs->is_abstract()
494 && (lhs->integer_type() != NULL
495 || lhs->float_type() != NULL
496 || lhs->complex_type() != NULL)
497 && (rhs->integer_type() != NULL
498 || rhs->float_type() != NULL
499 || rhs->complex_type() != NULL)))
500 return true;
502 // The nil type may be compared to a pointer, an interface type, a
503 // slice type, a channel type, a map type, or a function type.
504 if (lhs->is_nil_type()
505 && (rhs->points_to() != NULL
506 || rhs->interface_type() != NULL
507 || rhs->is_slice_type()
508 || rhs->map_type() != NULL
509 || rhs->channel_type() != NULL
510 || rhs->function_type() != NULL))
511 return true;
512 if (rhs->is_nil_type()
513 && (lhs->points_to() != NULL
514 || lhs->interface_type() != NULL
515 || lhs->is_slice_type()
516 || lhs->map_type() != NULL
517 || lhs->channel_type() != NULL
518 || lhs->function_type() != NULL))
519 return true;
521 return false;
524 // Return true if a value with type T1 may be compared with a value of
525 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
527 bool
528 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
529 const Type *t2, std::string *reason)
531 if (t1 != t2
532 && !Type::are_assignable(t1, t2, NULL)
533 && !Type::are_assignable(t2, t1, NULL))
535 if (reason != NULL)
536 *reason = "incompatible types in binary expression";
537 return false;
540 if (!is_equality_op)
542 if (t1->integer_type() == NULL
543 && t1->float_type() == NULL
544 && !t1->is_string_type())
546 if (reason != NULL)
547 *reason = _("invalid comparison of non-ordered type");
548 return false;
551 else if (t1->is_slice_type()
552 || t1->map_type() != NULL
553 || t1->function_type() != NULL
554 || t2->is_slice_type()
555 || t2->map_type() != NULL
556 || t2->function_type() != NULL)
558 if (!t1->is_nil_type() && !t2->is_nil_type())
560 if (reason != NULL)
562 if (t1->is_slice_type() || t2->is_slice_type())
563 *reason = _("slice can only be compared to nil");
564 else if (t1->map_type() != NULL || t2->map_type() != NULL)
565 *reason = _("map can only be compared to nil");
566 else
567 *reason = _("func can only be compared to nil");
569 // Match 6g error messages.
570 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
572 char buf[200];
573 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
574 reason->c_str());
575 *reason = buf;
578 return false;
581 else
583 if (!t1->is_boolean_type()
584 && t1->integer_type() == NULL
585 && t1->float_type() == NULL
586 && t1->complex_type() == NULL
587 && !t1->is_string_type()
588 && t1->points_to() == NULL
589 && t1->channel_type() == NULL
590 && t1->interface_type() == NULL
591 && t1->struct_type() == NULL
592 && t1->array_type() == NULL
593 && !t1->is_nil_type())
595 if (reason != NULL)
596 *reason = _("invalid comparison of non-comparable type");
597 return false;
600 if (t1->unalias()->named_type() != NULL)
601 return t1->unalias()->named_type()->named_type_is_comparable(reason);
602 else if (t2->unalias()->named_type() != NULL)
603 return t2->unalias()->named_type()->named_type_is_comparable(reason);
604 else if (t1->struct_type() != NULL)
606 if (t1->struct_type()->is_struct_incomparable())
608 if (reason != NULL)
609 *reason = _("invalid comparison of generated struct");
610 return false;
612 const Struct_field_list* fields = t1->struct_type()->fields();
613 for (Struct_field_list::const_iterator p = fields->begin();
614 p != fields->end();
615 ++p)
617 if (!p->type()->is_comparable())
619 if (reason != NULL)
620 *reason = _("invalid comparison of non-comparable struct");
621 return false;
625 else if (t1->array_type() != NULL)
627 if (t1->array_type()->is_array_incomparable())
629 if (reason != NULL)
630 *reason = _("invalid comparison of generated array");
631 return false;
633 if (t1->array_type()->length()->is_nil_expression()
634 || !t1->array_type()->element_type()->is_comparable())
636 if (reason != NULL)
637 *reason = _("invalid comparison of non-comparable array");
638 return false;
643 return true;
646 // Return true if a value with type RHS may be assigned to a variable
647 // with type LHS. If REASON is not NULL, set *REASON to the reason
648 // the types are not assignable.
650 bool
651 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
653 // Do some checks first. Make sure the types are defined.
654 if (rhs != NULL && !rhs->is_undefined())
656 if (rhs->is_void_type())
658 if (reason != NULL)
659 *reason = "non-value used as value";
660 return false;
662 if (rhs->is_call_multiple_result_type())
664 if (reason != NULL)
665 reason->assign(_("multiple-value function call in "
666 "single-value context"));
667 return false;
671 // Any value may be assigned to the blank identifier.
672 if (lhs != NULL
673 && !lhs->is_undefined()
674 && lhs->is_sink_type())
675 return true;
677 // Identical types are assignable.
678 if (Type::are_identical(lhs, rhs, true, reason))
679 return true;
681 // Ignore aliases, except for error messages.
682 const Type* lhs_orig = lhs;
683 const Type* rhs_orig = rhs;
684 lhs = lhs->unalias();
685 rhs = rhs->unalias();
687 // The types are assignable if they have identical underlying types
688 // and either LHS or RHS is not a named type.
689 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
690 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
691 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
692 return true;
694 // The types are assignable if LHS is an interface type and RHS
695 // implements the required methods.
696 const Interface_type* lhs_interface_type = lhs->interface_type();
697 if (lhs_interface_type != NULL)
699 if (lhs_interface_type->implements_interface(rhs, reason))
700 return true;
701 const Interface_type* rhs_interface_type = rhs->interface_type();
702 if (rhs_interface_type != NULL
703 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
704 reason))
705 return true;
708 // The type are assignable if RHS is a bidirectional channel type,
709 // LHS is a channel type, they have identical element types, and
710 // either LHS or RHS is not a named type.
711 if (lhs->channel_type() != NULL
712 && rhs->channel_type() != NULL
713 && rhs->channel_type()->may_send()
714 && rhs->channel_type()->may_receive()
715 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
716 && Type::are_identical(lhs->channel_type()->element_type(),
717 rhs->channel_type()->element_type(),
718 true,
719 reason))
720 return true;
722 // The nil type may be assigned to a pointer, function, slice, map,
723 // channel, or interface type.
724 if (rhs->is_nil_type()
725 && (lhs->points_to() != NULL
726 || lhs->function_type() != NULL
727 || lhs->is_slice_type()
728 || lhs->map_type() != NULL
729 || lhs->channel_type() != NULL
730 || lhs->interface_type() != NULL))
731 return true;
733 // An untyped numeric constant may be assigned to a numeric type if
734 // it is representable in that type.
735 if ((rhs->is_abstract()
736 && (rhs->integer_type() != NULL
737 || rhs->float_type() != NULL
738 || rhs->complex_type() != NULL))
739 && (lhs->integer_type() != NULL
740 || lhs->float_type() != NULL
741 || lhs->complex_type() != NULL))
742 return true;
744 // Give some better error messages.
745 if (reason != NULL && reason->empty())
747 if (rhs->interface_type() != NULL)
748 reason->assign(_("need explicit conversion"));
749 else if (lhs_orig->named_type() != NULL
750 && rhs_orig->named_type() != NULL)
752 size_t len = (lhs_orig->named_type()->name().length()
753 + rhs_orig->named_type()->name().length()
754 + 100);
755 char* buf = new char[len];
756 snprintf(buf, len, _("cannot use type %s as type %s"),
757 rhs_orig->named_type()->message_name().c_str(),
758 lhs_orig->named_type()->message_name().c_str());
759 reason->assign(buf);
760 delete[] buf;
764 return false;
767 // Return true if a value with type RHS may be converted to type LHS.
768 // If REASON is not NULL, set *REASON to the reason the types are not
769 // convertible.
771 bool
772 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
774 // The types are convertible if they are assignable.
775 if (Type::are_assignable(lhs, rhs, reason))
776 return true;
778 // Ignore aliases.
779 lhs = lhs->unalias();
780 rhs = rhs->unalias();
782 // A pointer to a regular type may not be converted to a pointer to
783 // a type that may not live in the heap, except when converting from
784 // unsafe.Pointer.
785 if (lhs->points_to() != NULL
786 && rhs->points_to() != NULL
787 && !lhs->points_to()->in_heap()
788 && rhs->points_to()->in_heap()
789 && !rhs->is_unsafe_pointer_type())
791 if (reason != NULL)
792 reason->assign(_("conversion from normal type to notinheap type"));
793 return false;
796 // The types are convertible if they have identical underlying
797 // types, ignoring struct field tags.
798 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
799 && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
800 true, reason))
801 return true;
803 // The types are convertible if they are both unnamed pointer types
804 // and their pointer base types have identical underlying types,
805 // ignoring struct field tags.
806 if (lhs->named_type() == NULL
807 && rhs->named_type() == NULL
808 && lhs->points_to() != NULL
809 && rhs->points_to() != NULL
810 && (lhs->points_to()->named_type() != NULL
811 || rhs->points_to()->named_type() != NULL)
812 && Type::are_identical_cmp_tags(lhs->points_to()->base(),
813 rhs->points_to()->base(),
814 IGNORE_TAGS,
815 true,
816 reason))
817 return true;
819 // Integer and floating point types are convertible to each other.
820 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
821 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
822 return true;
824 // Complex types are convertible to each other.
825 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
826 return true;
828 // An integer, or []byte, or []rune, may be converted to a string.
829 if (lhs->is_string_type())
831 if (rhs->integer_type() != NULL)
832 return true;
833 if (rhs->is_slice_type())
835 const Type* e = rhs->array_type()->element_type()->forwarded();
836 if (e->integer_type() != NULL
837 && (e->integer_type()->is_byte()
838 || e->integer_type()->is_rune()))
839 return true;
843 // A string may be converted to []byte or []rune.
844 if (rhs->is_string_type() && lhs->is_slice_type())
846 const Type* e = lhs->array_type()->element_type()->forwarded();
847 if (e->integer_type() != NULL
848 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
849 return true;
852 // An unsafe.Pointer type may be converted to any pointer type or to
853 // a type whose underlying type is uintptr, and vice-versa.
854 if (lhs->is_unsafe_pointer_type()
855 && (rhs->points_to() != NULL
856 || (rhs->integer_type() != NULL
857 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
858 return true;
859 if (rhs->is_unsafe_pointer_type()
860 && (lhs->points_to() != NULL
861 || (lhs->integer_type() != NULL
862 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
863 return true;
865 // Give a better error message.
866 if (reason != NULL)
868 if (reason->empty())
869 *reason = "invalid type conversion";
870 else
872 std::string s = "invalid type conversion (";
873 s += *reason;
874 s += ')';
875 *reason = s;
879 return false;
882 // Copy expressions if it may change the size.
884 // The only type that has an expression is an array type. The only
885 // types whose size can be changed by the size of an array type are an
886 // array type itself, or a struct type with an array field.
887 Type*
888 Type::copy_expressions()
890 // This is run during parsing, so types may not be valid yet.
891 // We only have to worry about array type literals.
892 switch (this->classification_)
894 default:
895 return this;
897 case TYPE_ARRAY:
899 Array_type* at = this->array_type();
900 if (at->length() == NULL)
901 return this;
902 Expression* len = at->length()->copy();
903 if (at->length() == len)
904 return this;
905 return Type::make_array_type(at->element_type(), len);
908 case TYPE_STRUCT:
910 Struct_type* st = this->struct_type();
911 const Struct_field_list* sfl = st->fields();
912 if (sfl == NULL)
913 return this;
914 bool changed = false;
915 Struct_field_list *nsfl = new Struct_field_list();
916 for (Struct_field_list::const_iterator pf = sfl->begin();
917 pf != sfl->end();
918 ++pf)
920 Type* ft = pf->type()->copy_expressions();
921 Struct_field nf(Typed_identifier((pf->is_anonymous()
922 ? ""
923 : pf->field_name()),
925 pf->location()));
926 if (pf->has_tag())
927 nf.set_tag(pf->tag());
928 nsfl->push_back(nf);
929 if (ft != pf->type())
930 changed = true;
932 if (!changed)
934 delete(nsfl);
935 return this;
937 return Type::make_struct_type(nsfl, st->location());
941 go_unreachable();
944 // Return a hash code for the type to be used for method lookup.
946 unsigned int
947 Type::hash_for_method(Gogo* gogo) const
949 if (this->named_type() != NULL && this->named_type()->is_alias())
950 return this->named_type()->real_type()->hash_for_method(gogo);
951 unsigned int ret = 0;
952 if (this->classification_ != TYPE_FORWARD)
953 ret += this->classification_;
954 return ret + this->do_hash_for_method(gogo);
957 // Default implementation of do_hash_for_method. This is appropriate
958 // for types with no subfields.
960 unsigned int
961 Type::do_hash_for_method(Gogo*) const
963 return 0;
966 // Return a hash code for a string, given a starting hash.
968 unsigned int
969 Type::hash_string(const std::string& s, unsigned int h)
971 const char* p = s.data();
972 size_t len = s.length();
973 for (; len > 0; --len)
975 h ^= *p++;
976 h*= 16777619;
978 return h;
981 // A hash table mapping unnamed types to the backend representation of
982 // those types.
984 Type::Type_btypes Type::type_btypes;
986 // Return the backend representation for this type.
988 Btype*
989 Type::get_backend(Gogo* gogo)
991 if (this->btype_ != NULL)
992 return this->btype_;
994 if (this->forward_declaration_type() != NULL
995 || this->named_type() != NULL)
996 return this->get_btype_without_hash(gogo);
998 if (this->is_error_type())
999 return gogo->backend()->error_type();
1001 // To avoid confusing the backend, translate all identical Go types
1002 // to the same backend representation. We use a hash table to do
1003 // that. There is no need to use the hash table for named types, as
1004 // named types are only identical to themselves.
1006 std::pair<Type*, Type_btype_entry> val;
1007 val.first = this;
1008 val.second.btype = NULL;
1009 val.second.is_placeholder = false;
1010 std::pair<Type_btypes::iterator, bool> ins =
1011 Type::type_btypes.insert(val);
1012 if (!ins.second && ins.first->second.btype != NULL)
1014 // Note that GOGO can be NULL here, but only when the GCC
1015 // middle-end is asking for a frontend type. That will only
1016 // happen for simple types, which should never require
1017 // placeholders.
1018 if (!ins.first->second.is_placeholder)
1019 this->btype_ = ins.first->second.btype;
1020 else if (gogo->named_types_are_converted())
1022 this->finish_backend(gogo, ins.first->second.btype);
1023 ins.first->second.is_placeholder = false;
1026 return ins.first->second.btype;
1029 Btype* bt = this->get_btype_without_hash(gogo);
1031 if (ins.first->second.btype == NULL)
1033 ins.first->second.btype = bt;
1034 ins.first->second.is_placeholder = false;
1036 else
1038 // We have already created a backend representation for this
1039 // type. This can happen when an unnamed type is defined using
1040 // a named type which in turns uses an identical unnamed type.
1041 // Use the representation we created earlier and ignore the one we just
1042 // built.
1043 if (this->btype_ == bt)
1044 this->btype_ = ins.first->second.btype;
1045 bt = ins.first->second.btype;
1048 return bt;
1051 // Return the backend representation for a type without looking in the
1052 // hash table for identical types. This is used for named types,
1053 // since a named type is never identical to any other type.
1055 Btype*
1056 Type::get_btype_without_hash(Gogo* gogo)
1058 if (this->btype_ == NULL)
1060 Btype* bt = this->do_get_backend(gogo);
1062 // For a recursive function or pointer type, we will temporarily
1063 // return a circular pointer type during the recursion. We
1064 // don't want to record that for a forwarding type, as it may
1065 // confuse us later.
1066 if (this->forward_declaration_type() != NULL
1067 && gogo->backend()->is_circular_pointer_type(bt))
1068 return bt;
1070 if (gogo == NULL || !gogo->named_types_are_converted())
1071 return bt;
1073 this->btype_ = bt;
1075 return this->btype_;
1078 // Get the backend representation of a type without forcing the
1079 // creation of the backend representation of all supporting types.
1080 // This will return a backend type that has the correct size but may
1081 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1082 // and will not contain the final representation of the type to which
1083 // it points. This is used while converting all named types to the
1084 // backend representation, to avoid problems with indirect references
1085 // to types which are not yet complete. When this is called, the
1086 // sizes of all direct references (e.g., a struct field) should be
1087 // known, but the sizes of indirect references (e.g., the type to
1088 // which a pointer points) may not.
1090 Btype*
1091 Type::get_backend_placeholder(Gogo* gogo)
1093 if (gogo->named_types_are_converted())
1094 return this->get_backend(gogo);
1095 if (this->btype_ != NULL)
1096 return this->btype_;
1098 Btype* bt;
1099 switch (this->classification_)
1101 case TYPE_ERROR:
1102 case TYPE_VOID:
1103 case TYPE_BOOLEAN:
1104 case TYPE_INTEGER:
1105 case TYPE_FLOAT:
1106 case TYPE_COMPLEX:
1107 case TYPE_STRING:
1108 case TYPE_NIL:
1109 // These are simple types that can just be created directly.
1110 return this->get_backend(gogo);
1112 case TYPE_MAP:
1113 case TYPE_CHANNEL:
1114 // All maps and channels have the same backend representation.
1115 return this->get_backend(gogo);
1117 case TYPE_NAMED:
1118 case TYPE_FORWARD:
1119 // Named types keep track of their own dependencies and manage
1120 // their own placeholders.
1121 return this->get_backend(gogo);
1123 case TYPE_INTERFACE:
1124 if (this->interface_type()->is_empty())
1125 return Interface_type::get_backend_empty_interface_type(gogo);
1126 break;
1128 default:
1129 break;
1132 std::pair<Type*, Type_btype_entry> val;
1133 val.first = this;
1134 val.second.btype = NULL;
1135 val.second.is_placeholder = false;
1136 std::pair<Type_btypes::iterator, bool> ins =
1137 Type::type_btypes.insert(val);
1138 if (!ins.second && ins.first->second.btype != NULL)
1139 return ins.first->second.btype;
1141 switch (this->classification_)
1143 case TYPE_FUNCTION:
1145 // A Go function type is a pointer to a struct type.
1146 Location loc = this->function_type()->location();
1147 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1149 break;
1151 case TYPE_POINTER:
1153 Location loc = Linemap::unknown_location();
1154 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1155 Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1156 Type::placeholder_pointers.push_back(pt);
1158 break;
1160 case TYPE_STRUCT:
1161 // We don't have to make the struct itself be a placeholder. We
1162 // are promised that we know the sizes of the struct fields.
1163 // But we may have to use a placeholder for any particular
1164 // struct field.
1166 std::vector<Backend::Btyped_identifier> bfields;
1167 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1168 true, &bfields);
1169 bt = gogo->backend()->struct_type(bfields);
1171 break;
1173 case TYPE_ARRAY:
1174 if (this->is_slice_type())
1176 std::vector<Backend::Btyped_identifier> bfields;
1177 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1178 bt = gogo->backend()->struct_type(bfields);
1180 else
1182 Btype* element = this->array_type()->get_backend_element(gogo, true);
1183 Bexpression* len = this->array_type()->get_backend_length(gogo);
1184 bt = gogo->backend()->array_type(element, len);
1186 break;
1188 case TYPE_INTERFACE:
1190 go_assert(!this->interface_type()->is_empty());
1191 std::vector<Backend::Btyped_identifier> bfields;
1192 get_backend_interface_fields(gogo, this->interface_type(), true,
1193 &bfields);
1194 bt = gogo->backend()->struct_type(bfields);
1196 break;
1198 case TYPE_SINK:
1199 case TYPE_CALL_MULTIPLE_RESULT:
1200 /* Note that various classifications were handled in the earlier
1201 switch. */
1202 default:
1203 go_unreachable();
1206 if (ins.first->second.btype == NULL)
1208 ins.first->second.btype = bt;
1209 ins.first->second.is_placeholder = true;
1211 else
1213 // A placeholder for this type got created along the way. Use
1214 // that one and ignore the one we just built.
1215 bt = ins.first->second.btype;
1218 return bt;
1221 // Complete the backend representation. This is called for a type
1222 // using a placeholder type.
1224 void
1225 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1227 switch (this->classification_)
1229 case TYPE_ERROR:
1230 case TYPE_VOID:
1231 case TYPE_BOOLEAN:
1232 case TYPE_INTEGER:
1233 case TYPE_FLOAT:
1234 case TYPE_COMPLEX:
1235 case TYPE_STRING:
1236 case TYPE_NIL:
1237 go_unreachable();
1239 case TYPE_FUNCTION:
1241 Btype* bt = this->do_get_backend(gogo);
1242 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1243 go_assert(saw_errors());
1245 break;
1247 case TYPE_POINTER:
1249 Btype* bt = this->do_get_backend(gogo);
1250 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1251 go_assert(saw_errors());
1253 break;
1255 case TYPE_STRUCT:
1256 // The struct type itself is done, but we have to make sure that
1257 // all the field types are converted.
1258 this->struct_type()->finish_backend_fields(gogo);
1259 break;
1261 case TYPE_ARRAY:
1262 // The array type itself is done, but make sure the element type
1263 // is converted.
1264 this->array_type()->finish_backend_element(gogo);
1265 break;
1267 case TYPE_MAP:
1268 case TYPE_CHANNEL:
1269 go_unreachable();
1271 case TYPE_INTERFACE:
1272 // The interface type itself is done, but make sure the method
1273 // types are converted.
1274 this->interface_type()->finish_backend_methods(gogo);
1275 break;
1277 case TYPE_NAMED:
1278 case TYPE_FORWARD:
1279 go_unreachable();
1281 case TYPE_SINK:
1282 case TYPE_CALL_MULTIPLE_RESULT:
1283 default:
1284 go_unreachable();
1287 this->btype_ = placeholder;
1290 // Return a pointer to the type descriptor for this type.
1292 Bexpression*
1293 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1295 Type* t = this->unalias();
1296 if (t->type_descriptor_var_ == NULL)
1298 t->make_type_descriptor_var(gogo);
1299 go_assert(t->type_descriptor_var_ != NULL);
1301 Bexpression* var_expr =
1302 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1303 Bexpression* var_addr =
1304 gogo->backend()->address_expression(var_expr, location);
1305 Type* td_type = Type::make_type_descriptor_type();
1306 Btype* td_btype = td_type->get_backend(gogo);
1307 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1308 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1311 // A mapping from unnamed types to type descriptor variables.
1313 Type::Type_descriptor_vars Type::type_descriptor_vars;
1315 // Build the type descriptor for this type.
1317 void
1318 Type::make_type_descriptor_var(Gogo* gogo)
1320 go_assert(this->type_descriptor_var_ == NULL);
1322 Named_type* nt = this->named_type();
1324 // We can have multiple instances of unnamed types, but we only want
1325 // to emit the type descriptor once. We use a hash table. This is
1326 // not necessary for named types, as they are unique, and we store
1327 // the type descriptor in the type itself.
1328 Bvariable** phash = NULL;
1329 if (nt == NULL)
1331 Bvariable* bvnull = NULL;
1332 std::pair<Type_descriptor_vars::iterator, bool> ins =
1333 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1334 if (!ins.second)
1336 // We've already built a type descriptor for this type.
1337 this->type_descriptor_var_ = ins.first->second;
1338 return;
1340 phash = &ins.first->second;
1343 // The type descriptor symbol for the unsafe.Pointer type is defined in
1344 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1345 // symbol if necessary.
1346 if (this->is_unsafe_pointer_type())
1348 Location bloc = Linemap::predeclared_location();
1350 Type* td_type = Type::make_type_descriptor_type();
1351 Btype* td_btype = td_type->get_backend(gogo);
1352 std::string name = gogo->type_descriptor_name(this, nt);
1353 std::string asm_name(go_selectively_encode_id(name));
1354 this->type_descriptor_var_ =
1355 gogo->backend()->immutable_struct_reference(name, asm_name,
1356 td_btype,
1357 bloc);
1359 if (phash != NULL)
1360 *phash = this->type_descriptor_var_;
1361 return;
1364 std::string var_name = gogo->type_descriptor_name(this, nt);
1366 // Build the contents of the type descriptor.
1367 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1369 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1371 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1373 const Package* dummy;
1374 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1376 std::string asm_name(go_selectively_encode_id(var_name));
1377 this->type_descriptor_var_ =
1378 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1379 initializer_btype,
1380 loc);
1381 if (phash != NULL)
1382 *phash = this->type_descriptor_var_;
1383 return;
1386 // See if this type descriptor can appear in multiple packages.
1387 bool is_common = false;
1388 if (nt != NULL)
1390 // We create the descriptor for a builtin type whenever we need
1391 // it.
1392 is_common = nt->is_builtin();
1394 else
1396 // This is an unnamed type. The descriptor could be defined in
1397 // any package where it is needed, and the linker will pick one
1398 // descriptor to keep.
1399 is_common = true;
1402 // We are going to build the type descriptor in this package. We
1403 // must create the variable before we convert the initializer to the
1404 // backend representation, because the initializer may refer to the
1405 // type descriptor of this type. By setting type_descriptor_var_ we
1406 // ensure that type_descriptor_pointer will work if called while
1407 // converting INITIALIZER.
1409 std::string asm_name(go_selectively_encode_id(var_name));
1410 this->type_descriptor_var_ =
1411 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1412 initializer_btype, loc);
1413 if (phash != NULL)
1414 *phash = this->type_descriptor_var_;
1416 Translate_context context(gogo, NULL, NULL, NULL);
1417 context.set_is_const();
1418 Bexpression* binitializer = initializer->get_backend(&context);
1420 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1421 var_name, false, is_common,
1422 initializer_btype, loc,
1423 binitializer);
1426 // Return true if this type descriptor is defined in a different
1427 // package. If this returns true it sets *PACKAGE to the package.
1429 bool
1430 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1431 const Package** package)
1433 if (nt != NULL)
1435 if (nt->named_object()->package() != NULL)
1437 // This is a named type defined in a different package. The
1438 // type descriptor should be defined in that package.
1439 *package = nt->named_object()->package();
1440 return true;
1443 else
1445 if (this->points_to() != NULL
1446 && this->points_to()->named_type() != NULL
1447 && this->points_to()->named_type()->named_object()->package() != NULL)
1449 // This is an unnamed pointer to a named type defined in a
1450 // different package. The descriptor should be defined in
1451 // that package.
1452 *package = this->points_to()->named_type()->named_object()->package();
1453 return true;
1456 return false;
1459 // Return a composite literal for a type descriptor.
1461 Expression*
1462 Type::type_descriptor(Gogo* gogo, Type* type)
1464 return type->do_type_descriptor(gogo, NULL);
1467 // Return a composite literal for a type descriptor with a name.
1469 Expression*
1470 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1472 go_assert(name != NULL && type->named_type() != name);
1473 return type->do_type_descriptor(gogo, name);
1476 // Make a builtin struct type from a list of fields. The fields are
1477 // pairs of a name and a type.
1479 Struct_type*
1480 Type::make_builtin_struct_type(int nfields, ...)
1482 va_list ap;
1483 va_start(ap, nfields);
1485 Location bloc = Linemap::predeclared_location();
1486 Struct_field_list* sfl = new Struct_field_list();
1487 for (int i = 0; i < nfields; i++)
1489 const char* field_name = va_arg(ap, const char *);
1490 Type* type = va_arg(ap, Type*);
1491 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1494 va_end(ap);
1496 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1497 ret->set_is_struct_incomparable();
1498 return ret;
1501 // A list of builtin named types.
1503 std::vector<Named_type*> Type::named_builtin_types;
1505 // Make a builtin named type.
1507 Named_type*
1508 Type::make_builtin_named_type(const char* name, Type* type)
1510 Location bloc = Linemap::predeclared_location();
1511 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1512 Named_type* ret = no->type_value();
1513 Type::named_builtin_types.push_back(ret);
1514 return ret;
1517 // Convert the named builtin types.
1519 void
1520 Type::convert_builtin_named_types(Gogo* gogo)
1522 for (std::vector<Named_type*>::const_iterator p =
1523 Type::named_builtin_types.begin();
1524 p != Type::named_builtin_types.end();
1525 ++p)
1527 bool r = (*p)->verify();
1528 go_assert(r);
1529 (*p)->convert(gogo);
1533 // Return the type of a type descriptor. We should really tie this to
1534 // runtime.Type rather than copying it. This must match the struct "_type"
1535 // declared in libgo/go/runtime/type.go.
1537 Type*
1538 Type::make_type_descriptor_type()
1540 static Type* ret;
1541 if (ret == NULL)
1543 Location bloc = Linemap::predeclared_location();
1545 Type* uint8_type = Type::lookup_integer_type("uint8");
1546 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1547 Type* uint32_type = Type::lookup_integer_type("uint32");
1548 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1549 Type* string_type = Type::lookup_string_type();
1550 Type* pointer_string_type = Type::make_pointer_type(string_type);
1552 // This is an unnamed version of unsafe.Pointer. Perhaps we
1553 // should use the named version instead, although that would
1554 // require us to create the unsafe package if it has not been
1555 // imported. It probably doesn't matter.
1556 Type* void_type = Type::make_void_type();
1557 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1559 Typed_identifier_list *params = new Typed_identifier_list();
1560 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1561 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1563 Typed_identifier_list* results = new Typed_identifier_list();
1564 results->push_back(Typed_identifier("", uintptr_type, bloc));
1566 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1567 bloc);
1569 params = new Typed_identifier_list();
1570 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1571 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1573 results = new Typed_identifier_list();
1574 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1576 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1577 bloc);
1579 // Forward declaration for the type descriptor type.
1580 Named_object* named_type_descriptor_type =
1581 Named_object::make_type_declaration("_type", NULL, bloc);
1582 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1583 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1585 // The type of a method on a concrete type.
1586 Struct_type* method_type =
1587 Type::make_builtin_struct_type(5,
1588 "name", pointer_string_type,
1589 "pkgPath", pointer_string_type,
1590 "mtyp", pointer_type_descriptor_type,
1591 "typ", pointer_type_descriptor_type,
1592 "tfn", unsafe_pointer_type);
1593 Named_type* named_method_type =
1594 Type::make_builtin_named_type("method", method_type);
1596 // Information for types with a name or methods.
1597 Type* slice_named_method_type =
1598 Type::make_array_type(named_method_type, NULL);
1599 Struct_type* uncommon_type =
1600 Type::make_builtin_struct_type(3,
1601 "name", pointer_string_type,
1602 "pkgPath", pointer_string_type,
1603 "methods", slice_named_method_type);
1604 Named_type* named_uncommon_type =
1605 Type::make_builtin_named_type("uncommonType", uncommon_type);
1607 Type* pointer_uncommon_type =
1608 Type::make_pointer_type(named_uncommon_type);
1610 // The type descriptor type.
1612 Struct_type* type_descriptor_type =
1613 Type::make_builtin_struct_type(12,
1614 "size", uintptr_type,
1615 "ptrdata", uintptr_type,
1616 "hash", uint32_type,
1617 "kind", uint8_type,
1618 "align", uint8_type,
1619 "fieldAlign", uint8_type,
1620 "hashfn", hash_fntype,
1621 "equalfn", equal_fntype,
1622 "gcdata", pointer_uint8_type,
1623 "string", pointer_string_type,
1624 "", pointer_uncommon_type,
1625 "ptrToThis",
1626 pointer_type_descriptor_type);
1628 Named_type* named = Type::make_builtin_named_type("_type",
1629 type_descriptor_type);
1631 named_type_descriptor_type->set_type_value(named);
1633 ret = named;
1636 return ret;
1639 // Make the type of a pointer to a type descriptor as represented in
1640 // Go.
1642 Type*
1643 Type::make_type_descriptor_ptr_type()
1645 static Type* ret;
1646 if (ret == NULL)
1647 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1648 return ret;
1651 // Return the alignment required by the memequalN function. N is a
1652 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1653 // in libgo/go/runtime/alg.go.
1655 int64_t
1656 Type::memequal_align(Gogo* gogo, int size)
1658 const char* tn;
1659 switch (size)
1661 case 16:
1662 tn = "int16";
1663 break;
1664 case 32:
1665 tn = "int32";
1666 break;
1667 case 64:
1668 tn = "int64";
1669 break;
1670 case 128:
1671 // The code uses [2]int64, which must have the same alignment as
1672 // int64.
1673 tn = "int64";
1674 break;
1675 default:
1676 go_unreachable();
1679 Type* t = Type::lookup_integer_type(tn);
1681 int64_t ret;
1682 if (!t->backend_type_align(gogo, &ret))
1683 go_unreachable();
1684 return ret;
1687 // Return whether this type needs specially built type functions.
1688 // This returns true for types that are comparable and either can not
1689 // use an identity comparison, or are a non-standard size.
1691 bool
1692 Type::needs_specific_type_functions(Gogo* gogo)
1694 Named_type* nt = this->named_type();
1695 if (nt != NULL && nt->is_alias())
1696 return false;
1697 if (!this->is_comparable())
1698 return false;
1699 if (!this->compare_is_identity(gogo))
1700 return true;
1702 // We create a few predeclared types for type descriptors; they are
1703 // really just for the backend and don't need hash or equality
1704 // functions.
1705 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1706 return false;
1708 int64_t size, align;
1709 if (!this->backend_type_size(gogo, &size)
1710 || !this->backend_type_align(gogo, &align))
1712 go_assert(saw_errors());
1713 return false;
1715 // This switch matches the one in Type::type_functions.
1716 switch (size)
1718 case 0:
1719 case 1:
1720 case 2:
1721 return align < Type::memequal_align(gogo, 16);
1722 case 4:
1723 return align < Type::memequal_align(gogo, 32);
1724 case 8:
1725 return align < Type::memequal_align(gogo, 64);
1726 case 16:
1727 return align < Type::memequal_align(gogo, 128);
1728 default:
1729 return true;
1733 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1734 // hash code for this type and which compare whether two values of
1735 // this type are equal. If NAME is not NULL it is the name of this
1736 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1737 // functions, for convenience; they may be NULL.
1739 void
1740 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1741 Function_type* equal_fntype, Named_object** hash_fn,
1742 Named_object** equal_fn)
1744 // If the unaliased type is not a named type, then the type does not
1745 // have a name after all.
1746 if (name != NULL)
1747 name = name->unalias()->named_type();
1749 if (!this->is_comparable())
1751 *hash_fn = NULL;
1752 *equal_fn = NULL;
1753 return;
1756 if (hash_fntype == NULL || equal_fntype == NULL)
1758 Location bloc = Linemap::predeclared_location();
1760 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1761 Type* void_type = Type::make_void_type();
1762 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1764 if (hash_fntype == NULL)
1766 Typed_identifier_list* params = new Typed_identifier_list();
1767 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1768 bloc));
1769 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1771 Typed_identifier_list* results = new Typed_identifier_list();
1772 results->push_back(Typed_identifier("", uintptr_type, bloc));
1774 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1776 if (equal_fntype == NULL)
1778 Typed_identifier_list* params = new Typed_identifier_list();
1779 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1780 bloc));
1781 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1782 bloc));
1784 Typed_identifier_list* results = new Typed_identifier_list();
1785 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1786 bloc));
1788 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1792 const char* hash_fnname;
1793 const char* equal_fnname;
1794 if (this->compare_is_identity(gogo))
1796 int64_t size, align;
1797 if (!this->backend_type_size(gogo, &size)
1798 || !this->backend_type_align(gogo, &align))
1800 go_assert(saw_errors());
1801 return;
1803 bool build_functions = false;
1804 // This switch matches the one in Type::needs_specific_type_functions.
1805 // The alignment tests are because of the memequal functions,
1806 // which assume that the values are aligned as required for an
1807 // integer of that size.
1808 switch (size)
1810 case 0:
1811 hash_fnname = "runtime.memhash0";
1812 equal_fnname = "runtime.memequal0";
1813 break;
1814 case 1:
1815 hash_fnname = "runtime.memhash8";
1816 equal_fnname = "runtime.memequal8";
1817 break;
1818 case 2:
1819 if (align < Type::memequal_align(gogo, 16))
1820 build_functions = true;
1821 else
1823 hash_fnname = "runtime.memhash16";
1824 equal_fnname = "runtime.memequal16";
1826 break;
1827 case 4:
1828 if (align < Type::memequal_align(gogo, 32))
1829 build_functions = true;
1830 else
1832 hash_fnname = "runtime.memhash32";
1833 equal_fnname = "runtime.memequal32";
1835 break;
1836 case 8:
1837 if (align < Type::memequal_align(gogo, 64))
1838 build_functions = true;
1839 else
1841 hash_fnname = "runtime.memhash64";
1842 equal_fnname = "runtime.memequal64";
1844 break;
1845 case 16:
1846 if (align < Type::memequal_align(gogo, 128))
1847 build_functions = true;
1848 else
1850 hash_fnname = "runtime.memhash128";
1851 equal_fnname = "runtime.memequal128";
1853 break;
1854 default:
1855 build_functions = true;
1856 break;
1858 if (build_functions)
1860 // We don't have a built-in function for a type of this size
1861 // and alignment. Build a function to use that calls the
1862 // generic hash/equality functions for identity, passing the size.
1863 this->specific_type_functions(gogo, name, size, hash_fntype,
1864 equal_fntype, hash_fn, equal_fn);
1865 return;
1868 else
1870 switch (this->base()->classification())
1872 case Type::TYPE_ERROR:
1873 case Type::TYPE_VOID:
1874 case Type::TYPE_NIL:
1875 case Type::TYPE_FUNCTION:
1876 case Type::TYPE_MAP:
1877 // For these types is_comparable should have returned false.
1878 go_unreachable();
1880 case Type::TYPE_BOOLEAN:
1881 case Type::TYPE_INTEGER:
1882 case Type::TYPE_POINTER:
1883 case Type::TYPE_CHANNEL:
1884 // For these types compare_is_identity should have returned true.
1885 go_unreachable();
1887 case Type::TYPE_FLOAT:
1888 switch (this->float_type()->bits())
1890 case 32:
1891 hash_fnname = "runtime.f32hash";
1892 equal_fnname = "runtime.f32equal";
1893 break;
1894 case 64:
1895 hash_fnname = "runtime.f64hash";
1896 equal_fnname = "runtime.f64equal";
1897 break;
1898 default:
1899 go_unreachable();
1901 break;
1903 case Type::TYPE_COMPLEX:
1904 switch (this->complex_type()->bits())
1906 case 64:
1907 hash_fnname = "runtime.c64hash";
1908 equal_fnname = "runtime.c64equal";
1909 break;
1910 case 128:
1911 hash_fnname = "runtime.c128hash";
1912 equal_fnname = "runtime.c128equal";
1913 break;
1914 default:
1915 go_unreachable();
1917 break;
1919 case Type::TYPE_STRING:
1920 hash_fnname = "runtime.strhash";
1921 equal_fnname = "runtime.strequal";
1922 break;
1924 case Type::TYPE_STRUCT:
1926 // This is a struct which can not be compared using a
1927 // simple identity function. We need to build a function
1928 // for comparison.
1929 this->specific_type_functions(gogo, name, -1, hash_fntype,
1930 equal_fntype, hash_fn, equal_fn);
1931 return;
1934 case Type::TYPE_ARRAY:
1935 if (this->is_slice_type())
1937 // Type::is_compatible_for_comparison should have
1938 // returned false.
1939 go_unreachable();
1941 else
1943 // This is an array which can not be compared using a
1944 // simple identity function. We need to build a
1945 // function for comparison.
1946 this->specific_type_functions(gogo, name, -1, hash_fntype,
1947 equal_fntype, hash_fn, equal_fn);
1948 return;
1950 break;
1952 case Type::TYPE_INTERFACE:
1953 if (this->interface_type()->is_empty())
1955 hash_fnname = "runtime.nilinterhash";
1956 equal_fnname = "runtime.nilinterequal";
1958 else
1960 hash_fnname = "runtime.interhash";
1961 equal_fnname = "runtime.interequal";
1963 break;
1965 case Type::TYPE_NAMED:
1966 case Type::TYPE_FORWARD:
1967 go_unreachable();
1969 default:
1970 go_unreachable();
1975 Location bloc = Linemap::predeclared_location();
1976 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1977 hash_fntype, bloc);
1978 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1979 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1980 equal_fntype, bloc);
1981 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1984 // A hash table mapping types to the specific hash functions.
1986 Type::Type_functions Type::type_functions_table;
1988 // Handle a type function which is specific to a type: if SIZE == -1,
1989 // this is a struct or array that can not use an identity comparison.
1990 // Otherwise, it is a type that uses an identity comparison but is not
1991 // one of the standard supported sizes.
1993 void
1994 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1995 Function_type* hash_fntype,
1996 Function_type* equal_fntype,
1997 Named_object** hash_fn,
1998 Named_object** equal_fn)
2000 Hash_equal_fn fnull(NULL, NULL);
2001 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
2002 std::pair<Type_functions::iterator, bool> ins =
2003 Type::type_functions_table.insert(val);
2004 if (!ins.second)
2006 // We already have functions for this type
2007 *hash_fn = ins.first->second.first;
2008 *equal_fn = ins.first->second.second;
2009 return;
2012 std::string hash_name;
2013 std::string equal_name;
2014 gogo->specific_type_function_names(this, name, &hash_name, &equal_name);
2016 Location bloc = Linemap::predeclared_location();
2018 const Package* package = NULL;
2019 bool is_defined_elsewhere =
2020 this->type_descriptor_defined_elsewhere(name, &package);
2021 if (is_defined_elsewhere)
2023 *hash_fn = Named_object::make_function_declaration(hash_name, package,
2024 hash_fntype, bloc);
2025 *equal_fn = Named_object::make_function_declaration(equal_name, package,
2026 equal_fntype, bloc);
2028 else
2030 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2031 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2032 bloc);
2035 ins.first->second.first = *hash_fn;
2036 ins.first->second.second = *equal_fn;
2038 if (!is_defined_elsewhere)
2040 if (gogo->in_global_scope())
2041 this->write_specific_type_functions(gogo, name, size, hash_name,
2042 hash_fntype, equal_name,
2043 equal_fntype);
2044 else
2045 gogo->queue_specific_type_function(this, name, size, hash_name,
2046 hash_fntype, equal_name,
2047 equal_fntype);
2051 // Write the hash and equality functions for a type which needs to be
2052 // written specially.
2054 void
2055 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2056 const std::string& hash_name,
2057 Function_type* hash_fntype,
2058 const std::string& equal_name,
2059 Function_type* equal_fntype)
2061 Location bloc = Linemap::predeclared_location();
2063 if (gogo->specific_type_functions_are_written())
2065 go_assert(saw_errors());
2066 return;
2069 go_assert(this->is_comparable());
2071 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2072 bloc);
2073 hash_fn->func_value()->set_is_type_specific_function();
2074 gogo->start_block(bloc);
2076 if (size != -1)
2077 this->write_identity_hash(gogo, size);
2078 else if (name != NULL && name->real_type()->named_type() != NULL)
2079 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2080 else if (this->struct_type() != NULL)
2081 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2082 equal_fntype);
2083 else if (this->array_type() != NULL)
2084 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2085 equal_fntype);
2086 else
2087 go_unreachable();
2089 Block* b = gogo->finish_block(bloc);
2090 gogo->add_block(b, bloc);
2091 gogo->lower_block(hash_fn, b);
2092 gogo->finish_function(bloc);
2094 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2095 false, bloc);
2096 equal_fn->func_value()->set_is_type_specific_function();
2097 gogo->start_block(bloc);
2099 if (size != -1)
2100 this->write_identity_equal(gogo, size);
2101 else if (name != NULL && name->real_type()->named_type() != NULL)
2102 this->write_named_equal(gogo, name);
2103 else if (this->struct_type() != NULL)
2104 this->struct_type()->write_equal_function(gogo, name);
2105 else if (this->array_type() != NULL)
2106 this->array_type()->write_equal_function(gogo, name);
2107 else
2108 go_unreachable();
2110 b = gogo->finish_block(bloc);
2111 gogo->add_block(b, bloc);
2112 gogo->lower_block(equal_fn, b);
2113 gogo->finish_function(bloc);
2115 // Build the function descriptors for the type descriptor to refer to.
2116 hash_fn->func_value()->descriptor(gogo, hash_fn);
2117 equal_fn->func_value()->descriptor(gogo, equal_fn);
2120 // Write a hash function for a type that can use an identity hash but
2121 // is not one of the standard supported sizes. For example, this
2122 // would be used for the type [3]byte. This builds a return statement
2123 // that returns a call to the memhash function, passing the key and
2124 // seed from the function arguments (already constructed before this
2125 // is called), and the constant size.
2127 void
2128 Type::write_identity_hash(Gogo* gogo, int64_t size)
2130 Location bloc = Linemap::predeclared_location();
2132 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2133 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2135 Typed_identifier_list* params = new Typed_identifier_list();
2136 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2137 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2138 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2140 Typed_identifier_list* results = new Typed_identifier_list();
2141 results->push_back(Typed_identifier("", uintptr_type, bloc));
2143 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2144 results, bloc);
2146 Named_object* memhash =
2147 Named_object::make_function_declaration("runtime.memhash", NULL,
2148 memhash_fntype, bloc);
2149 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2151 Named_object* key_arg = gogo->lookup("key", NULL);
2152 go_assert(key_arg != NULL);
2153 Named_object* seed_arg = gogo->lookup("seed", NULL);
2154 go_assert(seed_arg != NULL);
2156 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2157 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2158 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2159 bloc);
2160 Expression_list* args = new Expression_list();
2161 args->push_back(key_ref);
2162 args->push_back(seed_ref);
2163 args->push_back(size_arg);
2164 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2165 Expression* call = Expression::make_call(func, args, false, bloc);
2167 Expression_list* vals = new Expression_list();
2168 vals->push_back(call);
2169 Statement* s = Statement::make_return_statement(vals, bloc);
2170 gogo->add_statement(s);
2173 // Write an equality function for a type that can use an identity
2174 // equality comparison but is not one of the standard supported sizes.
2175 // For example, this would be used for the type [3]byte. This builds
2176 // a return statement that returns a call to the memequal function,
2177 // passing the two keys from the function arguments (already
2178 // constructed before this is called), and the constant size.
2180 void
2181 Type::write_identity_equal(Gogo* gogo, int64_t size)
2183 Location bloc = Linemap::predeclared_location();
2185 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2186 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2188 Typed_identifier_list* params = new Typed_identifier_list();
2189 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2190 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2191 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2193 Typed_identifier_list* results = new Typed_identifier_list();
2194 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2196 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2197 results, bloc);
2199 Named_object* memequal =
2200 Named_object::make_function_declaration("runtime.memequal", NULL,
2201 memequal_fntype, bloc);
2202 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2204 Named_object* key1_arg = gogo->lookup("key1", NULL);
2205 go_assert(key1_arg != NULL);
2206 Named_object* key2_arg = gogo->lookup("key2", NULL);
2207 go_assert(key2_arg != NULL);
2209 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2210 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2211 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2212 bloc);
2213 Expression_list* args = new Expression_list();
2214 args->push_back(key1_ref);
2215 args->push_back(key2_ref);
2216 args->push_back(size_arg);
2217 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2218 Expression* call = Expression::make_call(func, args, false, bloc);
2220 Expression_list* vals = new Expression_list();
2221 vals->push_back(call);
2222 Statement* s = Statement::make_return_statement(vals, bloc);
2223 gogo->add_statement(s);
2226 // Write a hash function that simply calls the hash function for a
2227 // named type. This is used when one named type is defined as
2228 // another. This ensures that this case works when the other named
2229 // type is defined in another package and relies on calling hash
2230 // functions defined only in that package.
2232 void
2233 Type::write_named_hash(Gogo* gogo, Named_type* name,
2234 Function_type* hash_fntype, Function_type* equal_fntype)
2236 Location bloc = Linemap::predeclared_location();
2238 Named_type* base_type = name->real_type()->named_type();
2239 while (base_type->is_alias())
2241 base_type = base_type->real_type()->named_type();
2242 go_assert(base_type != NULL);
2244 go_assert(base_type != NULL);
2246 // The pointer to the type we are going to hash. This is an
2247 // unsafe.Pointer.
2248 Named_object* key_arg = gogo->lookup("key", NULL);
2249 go_assert(key_arg != NULL);
2251 // The seed argument to the hash function.
2252 Named_object* seed_arg = gogo->lookup("seed", NULL);
2253 go_assert(seed_arg != NULL);
2255 Named_object* hash_fn;
2256 Named_object* equal_fn;
2257 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2258 &hash_fn, &equal_fn);
2260 // Call the hash function for the base type.
2261 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2262 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2263 Expression_list* args = new Expression_list();
2264 args->push_back(key_ref);
2265 args->push_back(seed_ref);
2266 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2267 Expression* call = Expression::make_call(func, args, false, bloc);
2269 // Return the hash of the base type.
2270 Expression_list* vals = new Expression_list();
2271 vals->push_back(call);
2272 Statement* s = Statement::make_return_statement(vals, bloc);
2273 gogo->add_statement(s);
2276 // Write an equality function that simply calls the equality function
2277 // for a named type. This is used when one named type is defined as
2278 // another. This ensures that this case works when the other named
2279 // type is defined in another package and relies on calling equality
2280 // functions defined only in that package.
2282 void
2283 Type::write_named_equal(Gogo* gogo, Named_type* name)
2285 Location bloc = Linemap::predeclared_location();
2287 // The pointers to the types we are going to compare. These have
2288 // type unsafe.Pointer.
2289 Named_object* key1_arg = gogo->lookup("key1", NULL);
2290 Named_object* key2_arg = gogo->lookup("key2", NULL);
2291 go_assert(key1_arg != NULL && key2_arg != NULL);
2293 Named_type* base_type = name->real_type()->named_type();
2294 go_assert(base_type != NULL);
2296 // Build temporaries with the base type.
2297 Type* pt = Type::make_pointer_type(base_type);
2299 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2300 ref = Expression::make_cast(pt, ref, bloc);
2301 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2302 gogo->add_statement(p1);
2304 ref = Expression::make_var_reference(key2_arg, bloc);
2305 ref = Expression::make_cast(pt, ref, bloc);
2306 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2307 gogo->add_statement(p2);
2309 // Compare the values for equality.
2310 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2311 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2313 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2314 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2316 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2318 // Return the equality comparison.
2319 Expression_list* vals = new Expression_list();
2320 vals->push_back(cond);
2321 Statement* s = Statement::make_return_statement(vals, bloc);
2322 gogo->add_statement(s);
2325 // Return a composite literal for the type descriptor for a plain type
2326 // of kind RUNTIME_TYPE_KIND named NAME.
2328 Expression*
2329 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2330 Named_type* name, const Methods* methods,
2331 bool only_value_methods)
2333 Location bloc = Linemap::predeclared_location();
2335 Type* td_type = Type::make_type_descriptor_type();
2336 const Struct_field_list* fields = td_type->struct_type()->fields();
2338 Expression_list* vals = new Expression_list();
2339 vals->reserve(12);
2341 if (!this->has_pointer())
2342 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2343 if (this->points_to() != NULL)
2344 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2345 int64_t ptrsize;
2346 int64_t ptrdata;
2347 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2348 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2350 Struct_field_list::const_iterator p = fields->begin();
2351 go_assert(p->is_field_name("size"));
2352 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2353 vals->push_back(Expression::make_type_info(this, type_info));
2355 ++p;
2356 go_assert(p->is_field_name("ptrdata"));
2357 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2358 vals->push_back(Expression::make_type_info(this, type_info));
2360 ++p;
2361 go_assert(p->is_field_name("hash"));
2362 unsigned int h;
2363 if (name != NULL)
2364 h = name->hash_for_method(gogo);
2365 else
2366 h = this->hash_for_method(gogo);
2367 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2369 ++p;
2370 go_assert(p->is_field_name("kind"));
2371 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2372 bloc));
2374 ++p;
2375 go_assert(p->is_field_name("align"));
2376 type_info = Expression::TYPE_INFO_ALIGNMENT;
2377 vals->push_back(Expression::make_type_info(this, type_info));
2379 ++p;
2380 go_assert(p->is_field_name("fieldAlign"));
2381 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2382 vals->push_back(Expression::make_type_info(this, type_info));
2384 ++p;
2385 go_assert(p->is_field_name("hashfn"));
2386 Function_type* hash_fntype = p->type()->function_type();
2388 ++p;
2389 go_assert(p->is_field_name("equalfn"));
2390 Function_type* equal_fntype = p->type()->function_type();
2392 Named_object* hash_fn;
2393 Named_object* equal_fn;
2394 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2395 &equal_fn);
2396 if (hash_fn == NULL)
2397 vals->push_back(Expression::make_cast(hash_fntype,
2398 Expression::make_nil(bloc),
2399 bloc));
2400 else
2401 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2402 if (equal_fn == NULL)
2403 vals->push_back(Expression::make_cast(equal_fntype,
2404 Expression::make_nil(bloc),
2405 bloc));
2406 else
2407 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2409 ++p;
2410 go_assert(p->is_field_name("gcdata"));
2411 vals->push_back(Expression::make_gc_symbol(this));
2413 ++p;
2414 go_assert(p->is_field_name("string"));
2415 Expression* s = Expression::make_string((name != NULL
2416 ? name->reflection(gogo)
2417 : this->reflection(gogo)),
2418 bloc);
2419 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2421 ++p;
2422 go_assert(p->is_field_name("uncommonType"));
2423 if (name == NULL && methods == NULL)
2424 vals->push_back(Expression::make_nil(bloc));
2425 else
2427 if (methods == NULL)
2428 methods = name->methods();
2429 vals->push_back(this->uncommon_type_constructor(gogo,
2430 p->type()->deref(),
2431 name, methods,
2432 only_value_methods));
2435 ++p;
2436 go_assert(p->is_field_name("ptrToThis"));
2437 if (name == NULL && methods == NULL)
2438 vals->push_back(Expression::make_nil(bloc));
2439 else
2441 Type* pt;
2442 if (name != NULL)
2443 pt = Type::make_pointer_type(name);
2444 else
2445 pt = Type::make_pointer_type(this);
2446 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2449 ++p;
2450 go_assert(p == fields->end());
2452 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2455 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2456 // length used by the gc toolchain, and also appears in
2457 // libgo/go/reflect/type.go.
2459 static const int64_t max_ptrmask_bytes = 2048;
2461 // Return a pointer to the Garbage Collection information for this type.
2463 Bexpression*
2464 Type::gc_symbol_pointer(Gogo* gogo)
2466 Type* t = this->unalias();
2468 if (!t->has_pointer())
2469 return gogo->backend()->nil_pointer_expression();
2471 if (t->gc_symbol_var_ == NULL)
2473 t->make_gc_symbol_var(gogo);
2474 go_assert(t->gc_symbol_var_ != NULL);
2476 Location bloc = Linemap::predeclared_location();
2477 Bexpression* var_expr =
2478 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2479 Bexpression* addr_expr =
2480 gogo->backend()->address_expression(var_expr, bloc);
2482 Type* uint8_type = Type::lookup_integer_type("uint8");
2483 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2484 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2485 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2488 // A mapping from unnamed types to GC symbol variables.
2490 Type::GC_symbol_vars Type::gc_symbol_vars;
2492 // Build the GC symbol for this type.
2494 void
2495 Type::make_gc_symbol_var(Gogo* gogo)
2497 go_assert(this->gc_symbol_var_ == NULL);
2499 Named_type* nt = this->named_type();
2501 // We can have multiple instances of unnamed types and similar to type
2502 // descriptors, we only want to the emit the GC data once, so we use a
2503 // hash table.
2504 Bvariable** phash = NULL;
2505 if (nt == NULL)
2507 Bvariable* bvnull = NULL;
2508 std::pair<GC_symbol_vars::iterator, bool> ins =
2509 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2510 if (!ins.second)
2512 // We've already built a gc symbol for this type.
2513 this->gc_symbol_var_ = ins.first->second;
2514 return;
2516 phash = &ins.first->second;
2519 int64_t ptrsize;
2520 int64_t ptrdata;
2521 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2523 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2524 if (phash != NULL)
2525 *phash = this->gc_symbol_var_;
2526 return;
2529 std::string sym_name = gogo->gc_symbol_name(this);
2531 // Build the contents of the gc symbol.
2532 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2533 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2535 // If the type descriptor for this type is defined somewhere else, so is the
2536 // GC symbol.
2537 const Package* dummy;
2538 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2540 std::string asm_name(go_selectively_encode_id(sym_name));
2541 this->gc_symbol_var_ =
2542 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2543 sym_btype);
2544 if (phash != NULL)
2545 *phash = this->gc_symbol_var_;
2546 return;
2549 // See if this gc symbol can appear in multiple packages.
2550 bool is_common = false;
2551 if (nt != NULL)
2553 // We create the symbol for a builtin type whenever we need
2554 // it.
2555 is_common = nt->is_builtin();
2557 else
2559 // This is an unnamed type. The descriptor could be defined in
2560 // any package where it is needed, and the linker will pick one
2561 // descriptor to keep.
2562 is_common = true;
2565 // Since we are building the GC symbol in this package, we must create the
2566 // variable before converting the initializer to its backend representation
2567 // because the initializer may refer to the GC symbol for this type.
2568 std::string asm_name(go_selectively_encode_id(sym_name));
2569 this->gc_symbol_var_ =
2570 gogo->backend()->implicit_variable(sym_name, asm_name,
2571 sym_btype, false, true, is_common, 0);
2572 if (phash != NULL)
2573 *phash = this->gc_symbol_var_;
2575 Translate_context context(gogo, NULL, NULL, NULL);
2576 context.set_is_const();
2577 Bexpression* sym_binit = sym_init->get_backend(&context);
2578 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2579 sym_btype, false, true, is_common,
2580 sym_binit);
2583 // Return whether this type needs a GC program, and set *PTRDATA to
2584 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2585 // pointer.
2587 bool
2588 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2590 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2591 if (!voidptr->backend_type_size(gogo, ptrsize))
2592 go_unreachable();
2594 if (!this->backend_type_ptrdata(gogo, ptrdata))
2596 go_assert(saw_errors());
2597 return false;
2600 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2603 // A simple class used to build a GC ptrmask for a type.
2605 class Ptrmask
2607 public:
2608 Ptrmask(size_t count)
2609 : bits_((count + 7) / 8, 0)
2612 void
2613 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2615 std::string
2616 symname() const;
2618 Expression*
2619 constructor(Gogo* gogo) const;
2621 private:
2622 void
2623 set(size_t index)
2624 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2626 // The actual bits.
2627 std::vector<unsigned char> bits_;
2630 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2631 // counts in bytes. PTRSIZE is the size of a pointer on the target
2632 // system.
2634 void
2635 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2637 switch (type->base()->classification())
2639 default:
2640 case Type::TYPE_NIL:
2641 case Type::TYPE_CALL_MULTIPLE_RESULT:
2642 case Type::TYPE_NAMED:
2643 case Type::TYPE_FORWARD:
2644 go_unreachable();
2646 case Type::TYPE_ERROR:
2647 case Type::TYPE_VOID:
2648 case Type::TYPE_BOOLEAN:
2649 case Type::TYPE_INTEGER:
2650 case Type::TYPE_FLOAT:
2651 case Type::TYPE_COMPLEX:
2652 case Type::TYPE_SINK:
2653 break;
2655 case Type::TYPE_FUNCTION:
2656 case Type::TYPE_POINTER:
2657 case Type::TYPE_MAP:
2658 case Type::TYPE_CHANNEL:
2659 // These types are all a single pointer.
2660 go_assert((offset % ptrsize) == 0);
2661 this->set(offset / ptrsize);
2662 break;
2664 case Type::TYPE_STRING:
2665 // A string starts with a single pointer.
2666 go_assert((offset % ptrsize) == 0);
2667 this->set(offset / ptrsize);
2668 break;
2670 case Type::TYPE_INTERFACE:
2671 // An interface is two pointers.
2672 go_assert((offset % ptrsize) == 0);
2673 this->set(offset / ptrsize);
2674 this->set((offset / ptrsize) + 1);
2675 break;
2677 case Type::TYPE_STRUCT:
2679 if (!type->has_pointer())
2680 return;
2682 const Struct_field_list* fields = type->struct_type()->fields();
2683 int64_t soffset = 0;
2684 for (Struct_field_list::const_iterator pf = fields->begin();
2685 pf != fields->end();
2686 ++pf)
2688 int64_t field_align;
2689 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2691 go_assert(saw_errors());
2692 return;
2694 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2696 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2698 int64_t field_size;
2699 if (!pf->type()->backend_type_size(gogo, &field_size))
2701 go_assert(saw_errors());
2702 return;
2704 soffset += field_size;
2707 break;
2709 case Type::TYPE_ARRAY:
2710 if (type->is_slice_type())
2712 // A slice starts with a single pointer.
2713 go_assert((offset % ptrsize) == 0);
2714 this->set(offset / ptrsize);
2715 break;
2717 else
2719 if (!type->has_pointer())
2720 return;
2722 int64_t len;
2723 if (!type->array_type()->int_length(&len))
2725 go_assert(saw_errors());
2726 return;
2729 Type* element_type = type->array_type()->element_type();
2730 int64_t ele_size;
2731 if (!element_type->backend_type_size(gogo, &ele_size))
2733 go_assert(saw_errors());
2734 return;
2737 int64_t eoffset = 0;
2738 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2739 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2740 break;
2745 // Return a symbol name for this ptrmask. This is used to coalesce
2746 // identical ptrmasks, which are common. The symbol name must use
2747 // only characters that are valid in symbols. It's nice if it's
2748 // short. We convert it to a string that uses only 32 characters,
2749 // avoiding digits and u and U.
2751 std::string
2752 Ptrmask::symname() const
2754 const char chars[33] = "abcdefghijklmnopqrstvwxyzABCDEFG";
2755 go_assert(chars[32] == '\0');
2756 std::string ret;
2757 unsigned int b = 0;
2758 int remaining = 0;
2759 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2760 p != this->bits_.end();
2761 ++p)
2763 b |= *p << remaining;
2764 remaining += 8;
2765 while (remaining >= 5)
2767 ret += chars[b & 0x1f];
2768 b >>= 5;
2769 remaining -= 5;
2772 while (remaining > 0)
2774 ret += chars[b & 0x1f];
2775 b >>= 5;
2776 remaining -= 5;
2778 return ret;
2781 // Return a constructor for this ptrmask. This will be used to
2782 // initialize the runtime ptrmask value.
2784 Expression*
2785 Ptrmask::constructor(Gogo* gogo) const
2787 Location bloc = Linemap::predeclared_location();
2788 Type* byte_type = gogo->lookup_global("byte")->type_value();
2789 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2790 bloc);
2791 Array_type* at = Type::make_array_type(byte_type, len);
2792 Expression_list* vals = new Expression_list();
2793 vals->reserve(this->bits_.size());
2794 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2795 p != this->bits_.end();
2796 ++p)
2797 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2798 return Expression::make_array_composite_literal(at, vals, bloc);
2801 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2802 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2804 // Return a ptrmask variable for a type. For a type descriptor this
2805 // is only used for variables that are small enough to not need a
2806 // gcprog, but for a global variable this is used for a variable of
2807 // any size. PTRDATA is the number of bytes of the type that contain
2808 // pointer data. PTRSIZE is the size of a pointer on the target
2809 // system.
2811 Bvariable*
2812 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2814 Ptrmask ptrmask(ptrdata / ptrsize);
2815 if (ptrdata >= ptrsize)
2816 ptrmask.set_from(gogo, this, ptrsize, 0);
2817 else
2819 // This can happen in error cases. Just build an empty gcbits.
2820 go_assert(saw_errors());
2823 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2824 Bvariable* bvnull = NULL;
2825 std::pair<GC_gcbits_vars::iterator, bool> ins =
2826 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2827 if (!ins.second)
2829 // We've already built a GC symbol for this set of gcbits.
2830 return ins.first->second;
2833 Expression* val = ptrmask.constructor(gogo);
2834 Translate_context context(gogo, NULL, NULL, NULL);
2835 context.set_is_const();
2836 Bexpression* bval = val->get_backend(&context);
2838 std::string asm_name(go_selectively_encode_id(sym_name));
2839 Btype *btype = val->type()->get_backend(gogo);
2840 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2841 btype, false, true,
2842 true, 0);
2843 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2844 true, true, bval);
2845 ins.first->second = ret;
2846 return ret;
2849 // A GCProg is used to build a program for the garbage collector.
2850 // This is used for types with a lot of pointer data, to reduce the
2851 // size of the data in the compiled program. The program is expanded
2852 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2854 class GCProg
2856 public:
2857 GCProg()
2858 : bytes_(), index_(0), nb_(0)
2861 // The number of bits described so far.
2862 int64_t
2863 bit_index() const
2864 { return this->index_; }
2866 void
2867 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2869 void
2870 end();
2872 Expression*
2873 constructor(Gogo* gogo) const;
2875 private:
2876 void
2877 ptr(int64_t);
2879 bool
2880 should_repeat(int64_t, int64_t);
2882 void
2883 repeat(int64_t, int64_t);
2885 void
2886 zero_until(int64_t);
2888 void
2889 lit(unsigned char);
2891 void
2892 varint(int64_t);
2894 void
2895 flushlit();
2897 // Add a byte to the program.
2898 void
2899 byte(unsigned char x)
2900 { this->bytes_.push_back(x); }
2902 // The maximum number of bytes of literal bits.
2903 static const int max_literal = 127;
2905 // The program.
2906 std::vector<unsigned char> bytes_;
2907 // The index of the last bit described.
2908 int64_t index_;
2909 // The current set of literal bits.
2910 unsigned char b_[max_literal];
2911 // The current number of literal bits.
2912 int nb_;
2915 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2916 // counts in bytes. PTRSIZE is the size of a pointer on the target
2917 // system.
2919 void
2920 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2922 switch (type->base()->classification())
2924 default:
2925 case Type::TYPE_NIL:
2926 case Type::TYPE_CALL_MULTIPLE_RESULT:
2927 case Type::TYPE_NAMED:
2928 case Type::TYPE_FORWARD:
2929 go_unreachable();
2931 case Type::TYPE_ERROR:
2932 case Type::TYPE_VOID:
2933 case Type::TYPE_BOOLEAN:
2934 case Type::TYPE_INTEGER:
2935 case Type::TYPE_FLOAT:
2936 case Type::TYPE_COMPLEX:
2937 case Type::TYPE_SINK:
2938 break;
2940 case Type::TYPE_FUNCTION:
2941 case Type::TYPE_POINTER:
2942 case Type::TYPE_MAP:
2943 case Type::TYPE_CHANNEL:
2944 // These types are all a single pointer.
2945 go_assert((offset % ptrsize) == 0);
2946 this->ptr(offset / ptrsize);
2947 break;
2949 case Type::TYPE_STRING:
2950 // A string starts with a single pointer.
2951 go_assert((offset % ptrsize) == 0);
2952 this->ptr(offset / ptrsize);
2953 break;
2955 case Type::TYPE_INTERFACE:
2956 // An interface is two pointers.
2957 go_assert((offset % ptrsize) == 0);
2958 this->ptr(offset / ptrsize);
2959 this->ptr((offset / ptrsize) + 1);
2960 break;
2962 case Type::TYPE_STRUCT:
2964 if (!type->has_pointer())
2965 return;
2967 const Struct_field_list* fields = type->struct_type()->fields();
2968 int64_t soffset = 0;
2969 for (Struct_field_list::const_iterator pf = fields->begin();
2970 pf != fields->end();
2971 ++pf)
2973 int64_t field_align;
2974 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2976 go_assert(saw_errors());
2977 return;
2979 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2981 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2983 int64_t field_size;
2984 if (!pf->type()->backend_type_size(gogo, &field_size))
2986 go_assert(saw_errors());
2987 return;
2989 soffset += field_size;
2992 break;
2994 case Type::TYPE_ARRAY:
2995 if (type->is_slice_type())
2997 // A slice starts with a single pointer.
2998 go_assert((offset % ptrsize) == 0);
2999 this->ptr(offset / ptrsize);
3000 break;
3002 else
3004 if (!type->has_pointer())
3005 return;
3007 int64_t len;
3008 if (!type->array_type()->int_length(&len))
3010 go_assert(saw_errors());
3011 return;
3014 Type* element_type = type->array_type()->element_type();
3016 // Flatten array of array to a big array by multiplying counts.
3017 while (element_type->array_type() != NULL
3018 && !element_type->is_slice_type())
3020 int64_t ele_len;
3021 if (!element_type->array_type()->int_length(&ele_len))
3023 go_assert(saw_errors());
3024 return;
3027 len *= ele_len;
3028 element_type = element_type->array_type()->element_type();
3031 int64_t ele_size;
3032 if (!element_type->backend_type_size(gogo, &ele_size))
3034 go_assert(saw_errors());
3035 return;
3038 go_assert(len > 0 && ele_size > 0);
3040 if (!this->should_repeat(ele_size / ptrsize, len))
3042 // Cheaper to just emit the bits.
3043 int64_t eoffset = 0;
3044 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3045 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3047 else
3049 go_assert((offset % ptrsize) == 0);
3050 go_assert((ele_size % ptrsize) == 0);
3051 this->set_from(gogo, element_type, ptrsize, offset);
3052 this->zero_until((offset + ele_size) / ptrsize);
3053 this->repeat(ele_size / ptrsize, len - 1);
3056 break;
3061 // Emit a 1 into the bit stream of a GC program at the given bit index.
3063 void
3064 GCProg::ptr(int64_t index)
3066 go_assert(index >= this->index_);
3067 this->zero_until(index);
3068 this->lit(1);
3071 // Return whether it is worthwhile to use a repeat to describe c
3072 // elements of n bits each, compared to just emitting c copies of the
3073 // n-bit description.
3075 bool
3076 GCProg::should_repeat(int64_t n, int64_t c)
3078 // Repeat if there is more than 1 item and if the total data doesn't
3079 // fit into four bytes.
3080 return c > 1 && c * n > 4 * 8;
3083 // Emit an instruction to repeat the description of the last n words c
3084 // times (including the initial description, so c + 1 times in total).
3086 void
3087 GCProg::repeat(int64_t n, int64_t c)
3089 if (n == 0 || c == 0)
3090 return;
3091 this->flushlit();
3092 if (n < 128)
3093 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3094 else
3096 this->byte(0x80);
3097 this->varint(n);
3099 this->varint(c);
3100 this->index_ += n * c;
3103 // Add zeros to the bit stream up to the given index.
3105 void
3106 GCProg::zero_until(int64_t index)
3108 go_assert(index >= this->index_);
3109 int64_t skip = index - this->index_;
3110 if (skip == 0)
3111 return;
3112 if (skip < 4 * 8)
3114 for (int64_t i = 0; i < skip; ++i)
3115 this->lit(0);
3116 return;
3118 this->lit(0);
3119 this->flushlit();
3120 this->repeat(1, skip - 1);
3123 // Add a single literal bit to the program.
3125 void
3126 GCProg::lit(unsigned char x)
3128 if (this->nb_ == GCProg::max_literal)
3129 this->flushlit();
3130 this->b_[this->nb_] = x;
3131 ++this->nb_;
3132 ++this->index_;
3135 // Emit the varint encoding of x.
3137 void
3138 GCProg::varint(int64_t x)
3140 go_assert(x >= 0);
3141 while (x >= 0x80)
3143 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3144 x >>= 7;
3146 this->byte(static_cast<unsigned char>(x & 0x7f));
3149 // Flush any pending literal bits.
3151 void
3152 GCProg::flushlit()
3154 if (this->nb_ == 0)
3155 return;
3156 this->byte(static_cast<unsigned char>(this->nb_));
3157 unsigned char bits = 0;
3158 for (int i = 0; i < this->nb_; ++i)
3160 bits |= this->b_[i] << (i % 8);
3161 if ((i + 1) % 8 == 0)
3163 this->byte(bits);
3164 bits = 0;
3167 if (this->nb_ % 8 != 0)
3168 this->byte(bits);
3169 this->nb_ = 0;
3172 // Mark the end of a GC program.
3174 void
3175 GCProg::end()
3177 this->flushlit();
3178 this->byte(0);
3181 // Return an Expression for the bytes in a GC program.
3183 Expression*
3184 GCProg::constructor(Gogo* gogo) const
3186 Location bloc = Linemap::predeclared_location();
3188 // The first four bytes are the length of the program in target byte
3189 // order. Build a struct whose first type is uint32 to make this
3190 // work.
3192 Type* uint32_type = Type::lookup_integer_type("uint32");
3194 Type* byte_type = gogo->lookup_global("byte")->type_value();
3195 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3196 bloc);
3197 Array_type* at = Type::make_array_type(byte_type, len);
3199 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3200 "bytes", at);
3202 Expression_list* vals = new Expression_list();
3203 vals->reserve(this->bytes_.size());
3204 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3205 p != this->bytes_.end();
3206 ++p)
3207 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3208 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3210 vals = new Expression_list();
3211 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3212 bloc));
3213 vals->push_back(bytes);
3215 return Expression::make_struct_composite_literal(st, vals, bloc);
3218 // Return a composite literal for the garbage collection program for
3219 // this type. This is only used for types that are too large to use a
3220 // ptrmask.
3222 Expression*
3223 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3225 Location bloc = Linemap::predeclared_location();
3227 GCProg prog;
3228 prog.set_from(gogo, this, ptrsize, 0);
3229 int64_t offset = prog.bit_index() * ptrsize;
3230 prog.end();
3232 int64_t type_size;
3233 if (!this->backend_type_size(gogo, &type_size))
3235 go_assert(saw_errors());
3236 return Expression::make_error(bloc);
3239 go_assert(offset >= ptrdata && offset <= type_size);
3241 return prog.constructor(gogo);
3244 // Return a composite literal for the uncommon type information for
3245 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3246 // struct. If name is not NULL, it is the name of the type. If
3247 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3248 // is true if only value methods should be included. At least one of
3249 // NAME and METHODS must not be NULL.
3251 Expression*
3252 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3253 Named_type* name, const Methods* methods,
3254 bool only_value_methods) const
3256 Location bloc = Linemap::predeclared_location();
3258 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3260 Expression_list* vals = new Expression_list();
3261 vals->reserve(3);
3263 Struct_field_list::const_iterator p = fields->begin();
3264 go_assert(p->is_field_name("name"));
3266 ++p;
3267 go_assert(p->is_field_name("pkgPath"));
3269 if (name == NULL)
3271 vals->push_back(Expression::make_nil(bloc));
3272 vals->push_back(Expression::make_nil(bloc));
3274 else
3276 Named_object* no = name->named_object();
3277 std::string n = Gogo::unpack_hidden_name(no->name());
3278 Expression* s = Expression::make_string(n, bloc);
3279 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3281 if (name->is_builtin())
3282 vals->push_back(Expression::make_nil(bloc));
3283 else
3285 const Package* package = no->package();
3286 const std::string& pkgpath(package == NULL
3287 ? gogo->pkgpath()
3288 : package->pkgpath());
3289 s = Expression::make_string(pkgpath, bloc);
3290 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3294 ++p;
3295 go_assert(p->is_field_name("methods"));
3296 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3297 only_value_methods));
3299 ++p;
3300 go_assert(p == fields->end());
3302 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3303 vals, bloc);
3304 return Expression::make_unary(OPERATOR_AND, r, bloc);
3307 // Sort methods by name.
3309 class Sort_methods
3311 public:
3312 bool
3313 operator()(const std::pair<std::string, const Method*>& m1,
3314 const std::pair<std::string, const Method*>& m2) const
3316 return (Gogo::unpack_hidden_name(m1.first)
3317 < Gogo::unpack_hidden_name(m2.first));
3321 // Return a composite literal for the type method table for this type.
3322 // METHODS_TYPE is the type of the table, and is a slice type.
3323 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3324 // then only value methods are used.
3326 Expression*
3327 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3328 const Methods* methods,
3329 bool only_value_methods) const
3331 Location bloc = Linemap::predeclared_location();
3333 std::vector<std::pair<std::string, const Method*> > smethods;
3334 if (methods != NULL)
3336 smethods.reserve(methods->count());
3337 for (Methods::const_iterator p = methods->begin();
3338 p != methods->end();
3339 ++p)
3341 if (p->second->is_ambiguous())
3342 continue;
3343 if (only_value_methods && !p->second->is_value_method())
3344 continue;
3346 // This is where we implement the magic //go:nointerface
3347 // comment. If we saw that comment, we don't add this
3348 // method to the type descriptor.
3349 if (p->second->nointerface())
3350 continue;
3352 smethods.push_back(std::make_pair(p->first, p->second));
3356 if (smethods.empty())
3357 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3359 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3361 Type* method_type = methods_type->array_type()->element_type();
3363 Expression_list* vals = new Expression_list();
3364 vals->reserve(smethods.size());
3365 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3366 = smethods.begin();
3367 p != smethods.end();
3368 ++p)
3369 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3370 p->second, only_value_methods));
3372 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3375 // Return a composite literal for a single method. METHOD_TYPE is the
3376 // type of the entry. METHOD_NAME is the name of the method and M is
3377 // the method information.
3379 Expression*
3380 Type::method_constructor(Gogo*, Type* method_type,
3381 const std::string& method_name,
3382 const Method* m,
3383 bool only_value_methods) const
3385 Location bloc = Linemap::predeclared_location();
3387 const Struct_field_list* fields = method_type->struct_type()->fields();
3389 Expression_list* vals = new Expression_list();
3390 vals->reserve(5);
3392 Struct_field_list::const_iterator p = fields->begin();
3393 go_assert(p->is_field_name("name"));
3394 const std::string n = Gogo::unpack_hidden_name(method_name);
3395 Expression* s = Expression::make_string(n, bloc);
3396 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3398 ++p;
3399 go_assert(p->is_field_name("pkgPath"));
3400 if (!Gogo::is_hidden_name(method_name))
3401 vals->push_back(Expression::make_nil(bloc));
3402 else
3404 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3405 bloc);
3406 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3409 Named_object* no = (m->needs_stub_method()
3410 ? m->stub_object()
3411 : m->named_object());
3413 Function_type* mtype;
3414 if (no->is_function())
3415 mtype = no->func_value()->type();
3416 else
3417 mtype = no->func_declaration_value()->type();
3418 go_assert(mtype->is_method());
3419 Type* nonmethod_type = mtype->copy_without_receiver();
3421 ++p;
3422 go_assert(p->is_field_name("mtyp"));
3423 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3425 ++p;
3426 go_assert(p->is_field_name("typ"));
3427 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3428 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3429 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3431 ++p;
3432 go_assert(p->is_field_name("tfn"));
3433 vals->push_back(Expression::make_func_code_reference(no, bloc));
3435 ++p;
3436 go_assert(p == fields->end());
3438 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3441 // Return a composite literal for the type descriptor of a plain type.
3442 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3443 // NULL, it is the name to use as well as the list of methods.
3445 Expression*
3446 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3447 Named_type* name)
3449 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3450 name, NULL, true);
3453 // Return the type reflection string for this type.
3455 std::string
3456 Type::reflection(Gogo* gogo) const
3458 std::string ret;
3460 // The do_reflection virtual function should set RET to the
3461 // reflection string.
3462 this->do_reflection(gogo, &ret);
3464 return ret;
3467 // Return whether the backend size of the type is known.
3469 bool
3470 Type::is_backend_type_size_known(Gogo* gogo)
3472 switch (this->classification_)
3474 case TYPE_ERROR:
3475 case TYPE_VOID:
3476 case TYPE_BOOLEAN:
3477 case TYPE_INTEGER:
3478 case TYPE_FLOAT:
3479 case TYPE_COMPLEX:
3480 case TYPE_STRING:
3481 case TYPE_FUNCTION:
3482 case TYPE_POINTER:
3483 case TYPE_NIL:
3484 case TYPE_MAP:
3485 case TYPE_CHANNEL:
3486 case TYPE_INTERFACE:
3487 return true;
3489 case TYPE_STRUCT:
3491 const Struct_field_list* fields = this->struct_type()->fields();
3492 for (Struct_field_list::const_iterator pf = fields->begin();
3493 pf != fields->end();
3494 ++pf)
3495 if (!pf->type()->is_backend_type_size_known(gogo))
3496 return false;
3497 return true;
3500 case TYPE_ARRAY:
3502 const Array_type* at = this->array_type();
3503 if (at->length() == NULL)
3504 return true;
3505 else
3507 Numeric_constant nc;
3508 if (!at->length()->numeric_constant_value(&nc))
3509 return false;
3510 mpz_t ival;
3511 if (!nc.to_int(&ival))
3512 return false;
3513 mpz_clear(ival);
3514 return at->element_type()->is_backend_type_size_known(gogo);
3518 case TYPE_NAMED:
3519 this->named_type()->convert(gogo);
3520 return this->named_type()->is_named_backend_type_size_known();
3522 case TYPE_FORWARD:
3524 Forward_declaration_type* fdt = this->forward_declaration_type();
3525 return fdt->real_type()->is_backend_type_size_known(gogo);
3528 case TYPE_SINK:
3529 case TYPE_CALL_MULTIPLE_RESULT:
3530 go_unreachable();
3532 default:
3533 go_unreachable();
3537 // If the size of the type can be determined, set *PSIZE to the size
3538 // in bytes and return true. Otherwise, return false. This queries
3539 // the backend.
3541 bool
3542 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3544 if (!this->is_backend_type_size_known(gogo))
3545 return false;
3546 if (this->is_error_type())
3547 return false;
3548 Btype* bt = this->get_backend_placeholder(gogo);
3549 *psize = gogo->backend()->type_size(bt);
3550 if (*psize == -1)
3552 if (this->named_type() != NULL)
3553 go_error_at(this->named_type()->location(),
3554 "type %s larger than address space",
3555 Gogo::message_name(this->named_type()->name()).c_str());
3556 else
3557 go_error_at(Linemap::unknown_location(),
3558 "type %s larger than address space",
3559 this->reflection(gogo).c_str());
3561 // Make this an error type to avoid knock-on errors.
3562 this->classification_ = TYPE_ERROR;
3563 return false;
3565 return true;
3568 // If the alignment of the type can be determined, set *PALIGN to
3569 // the alignment in bytes and return true. Otherwise, return false.
3571 bool
3572 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3574 if (!this->is_backend_type_size_known(gogo))
3575 return false;
3576 Btype* bt = this->get_backend_placeholder(gogo);
3577 *palign = gogo->backend()->type_alignment(bt);
3578 return true;
3581 // Like backend_type_align, but return the alignment when used as a
3582 // field.
3584 bool
3585 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3587 if (!this->is_backend_type_size_known(gogo))
3588 return false;
3589 Btype* bt = this->get_backend_placeholder(gogo);
3590 *palign = gogo->backend()->type_field_alignment(bt);
3591 return true;
3594 // Get the ptrdata value for a type. This is the size of the prefix
3595 // of the type that contains all pointers. Store the ptrdata in
3596 // *PPTRDATA and return whether we found it.
3598 bool
3599 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3601 *pptrdata = 0;
3603 if (!this->has_pointer())
3604 return true;
3606 if (!this->is_backend_type_size_known(gogo))
3607 return false;
3609 switch (this->classification_)
3611 case TYPE_ERROR:
3612 return true;
3614 case TYPE_FUNCTION:
3615 case TYPE_POINTER:
3616 case TYPE_MAP:
3617 case TYPE_CHANNEL:
3618 // These types are nothing but a pointer.
3619 return this->backend_type_size(gogo, pptrdata);
3621 case TYPE_INTERFACE:
3622 // An interface is a struct of two pointers.
3623 return this->backend_type_size(gogo, pptrdata);
3625 case TYPE_STRING:
3627 // A string is a struct whose first field is a pointer, and
3628 // whose second field is not.
3629 Type* uint8_type = Type::lookup_integer_type("uint8");
3630 Type* ptr = Type::make_pointer_type(uint8_type);
3631 return ptr->backend_type_size(gogo, pptrdata);
3634 case TYPE_NAMED:
3635 case TYPE_FORWARD:
3636 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3638 case TYPE_STRUCT:
3640 const Struct_field_list* fields = this->struct_type()->fields();
3641 int64_t offset = 0;
3642 const Struct_field *ptr = NULL;
3643 int64_t ptr_offset = 0;
3644 for (Struct_field_list::const_iterator pf = fields->begin();
3645 pf != fields->end();
3646 ++pf)
3648 int64_t field_align;
3649 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3650 return false;
3651 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3653 if (pf->type()->has_pointer())
3655 ptr = &*pf;
3656 ptr_offset = offset;
3659 int64_t field_size;
3660 if (!pf->type()->backend_type_size(gogo, &field_size))
3661 return false;
3662 offset += field_size;
3665 if (ptr != NULL)
3667 int64_t ptr_ptrdata;
3668 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3669 return false;
3670 *pptrdata = ptr_offset + ptr_ptrdata;
3672 return true;
3675 case TYPE_ARRAY:
3676 if (this->is_slice_type())
3678 // A slice is a struct whose first field is a pointer, and
3679 // whose remaining fields are not.
3680 Type* element_type = this->array_type()->element_type();
3681 Type* ptr = Type::make_pointer_type(element_type);
3682 return ptr->backend_type_size(gogo, pptrdata);
3684 else
3686 Numeric_constant nc;
3687 if (!this->array_type()->length()->numeric_constant_value(&nc))
3688 return false;
3689 int64_t len;
3690 if (!nc.to_memory_size(&len))
3691 return false;
3693 Type* element_type = this->array_type()->element_type();
3694 int64_t ele_size;
3695 int64_t ele_ptrdata;
3696 if (!element_type->backend_type_size(gogo, &ele_size)
3697 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3698 return false;
3699 go_assert(ele_size > 0 && ele_ptrdata > 0);
3701 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3702 return true;
3705 default:
3706 case TYPE_VOID:
3707 case TYPE_BOOLEAN:
3708 case TYPE_INTEGER:
3709 case TYPE_FLOAT:
3710 case TYPE_COMPLEX:
3711 case TYPE_SINK:
3712 case TYPE_NIL:
3713 case TYPE_CALL_MULTIPLE_RESULT:
3714 go_unreachable();
3718 // Get the ptrdata value to store in a type descriptor. This is
3719 // normally the same as backend_type_ptrdata, but for a type that is
3720 // large enough to use a gcprog we may need to store a different value
3721 // if it ends with an array. If the gcprog uses a repeat descriptor
3722 // for the array, and if the array element ends with non-pointer data,
3723 // then the gcprog will produce a value that describes the complete
3724 // array where the backend ptrdata will omit the non-pointer elements
3725 // of the final array element. This is a subtle difference but the
3726 // run time code checks it to verify that it has expanded a gcprog as
3727 // expected.
3729 bool
3730 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3732 int64_t backend_ptrdata;
3733 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3734 return false;
3736 int64_t ptrsize;
3737 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3739 *pptrdata = backend_ptrdata;
3740 return true;
3743 GCProg prog;
3744 prog.set_from(gogo, this, ptrsize, 0);
3745 int64_t offset = prog.bit_index() * ptrsize;
3747 go_assert(offset >= backend_ptrdata);
3748 *pptrdata = offset;
3749 return true;
3752 // Default function to export a type.
3754 void
3755 Type::do_export(Export*) const
3757 go_unreachable();
3760 // Import a type.
3762 Type*
3763 Type::import_type(Import* imp)
3765 if (imp->match_c_string("("))
3766 return Function_type::do_import(imp);
3767 else if (imp->match_c_string("*"))
3768 return Pointer_type::do_import(imp);
3769 else if (imp->match_c_string("struct "))
3770 return Struct_type::do_import(imp);
3771 else if (imp->match_c_string("["))
3772 return Array_type::do_import(imp);
3773 else if (imp->match_c_string("map "))
3774 return Map_type::do_import(imp);
3775 else if (imp->match_c_string("chan "))
3776 return Channel_type::do_import(imp);
3777 else if (imp->match_c_string("interface"))
3778 return Interface_type::do_import(imp);
3779 else
3781 go_error_at(imp->location(), "import error: expected type");
3782 return Type::make_error_type();
3786 // Class Error_type.
3788 // Return the backend representation of an Error type.
3790 Btype*
3791 Error_type::do_get_backend(Gogo* gogo)
3793 return gogo->backend()->error_type();
3796 // Return an expression for the type descriptor for an error type.
3799 Expression*
3800 Error_type::do_type_descriptor(Gogo*, Named_type*)
3802 return Expression::make_error(Linemap::predeclared_location());
3805 // We should not be asked for the reflection string for an error type.
3807 void
3808 Error_type::do_reflection(Gogo*, std::string*) const
3810 go_assert(saw_errors());
3813 Type*
3814 Type::make_error_type()
3816 static Error_type singleton_error_type;
3817 return &singleton_error_type;
3820 // Class Void_type.
3822 // Get the backend representation of a void type.
3824 Btype*
3825 Void_type::do_get_backend(Gogo* gogo)
3827 return gogo->backend()->void_type();
3830 Type*
3831 Type::make_void_type()
3833 static Void_type singleton_void_type;
3834 return &singleton_void_type;
3837 // Class Boolean_type.
3839 // Return the backend representation of the boolean type.
3841 Btype*
3842 Boolean_type::do_get_backend(Gogo* gogo)
3844 return gogo->backend()->bool_type();
3847 // Make the type descriptor.
3849 Expression*
3850 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3852 if (name != NULL)
3853 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3854 else
3856 Named_object* no = gogo->lookup_global("bool");
3857 go_assert(no != NULL);
3858 return Type::type_descriptor(gogo, no->type_value());
3862 Type*
3863 Type::make_boolean_type()
3865 static Boolean_type boolean_type;
3866 return &boolean_type;
3869 // The named type "bool".
3871 static Named_type* named_bool_type;
3873 // Get the named type "bool".
3875 Named_type*
3876 Type::lookup_bool_type()
3878 return named_bool_type;
3881 // Make the named type "bool".
3883 Named_type*
3884 Type::make_named_bool_type()
3886 Type* bool_type = Type::make_boolean_type();
3887 Named_object* named_object =
3888 Named_object::make_type("bool", NULL, bool_type,
3889 Linemap::predeclared_location());
3890 Named_type* named_type = named_object->type_value();
3891 named_bool_type = named_type;
3892 return named_type;
3895 // Class Integer_type.
3897 Integer_type::Named_integer_types Integer_type::named_integer_types;
3899 // Create a new integer type. Non-abstract integer types always have
3900 // names.
3902 Named_type*
3903 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3904 int bits, int runtime_type_kind)
3906 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3907 runtime_type_kind);
3908 std::string sname(name);
3909 Named_object* named_object =
3910 Named_object::make_type(sname, NULL, integer_type,
3911 Linemap::predeclared_location());
3912 Named_type* named_type = named_object->type_value();
3913 std::pair<Named_integer_types::iterator, bool> ins =
3914 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3915 go_assert(ins.second);
3916 return named_type;
3919 // Look up an existing integer type.
3921 Named_type*
3922 Integer_type::lookup_integer_type(const char* name)
3924 Named_integer_types::const_iterator p =
3925 Integer_type::named_integer_types.find(name);
3926 go_assert(p != Integer_type::named_integer_types.end());
3927 return p->second;
3930 // Create a new abstract integer type.
3932 Integer_type*
3933 Integer_type::create_abstract_integer_type()
3935 static Integer_type* abstract_type;
3936 if (abstract_type == NULL)
3938 Type* int_type = Type::lookup_integer_type("int");
3939 abstract_type = new Integer_type(true, false,
3940 int_type->integer_type()->bits(),
3941 RUNTIME_TYPE_KIND_INT);
3943 return abstract_type;
3946 // Create a new abstract character type.
3948 Integer_type*
3949 Integer_type::create_abstract_character_type()
3951 static Integer_type* abstract_type;
3952 if (abstract_type == NULL)
3954 abstract_type = new Integer_type(true, false, 32,
3955 RUNTIME_TYPE_KIND_INT32);
3956 abstract_type->set_is_rune();
3958 return abstract_type;
3961 // Integer type compatibility.
3963 bool
3964 Integer_type::is_identical(const Integer_type* t) const
3966 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
3967 return false;
3968 return this->is_abstract_ == t->is_abstract_;
3971 // Hash code.
3973 unsigned int
3974 Integer_type::do_hash_for_method(Gogo*) const
3976 return ((this->bits_ << 4)
3977 + ((this->is_unsigned_ ? 1 : 0) << 8)
3978 + ((this->is_abstract_ ? 1 : 0) << 9));
3981 // Convert an Integer_type to the backend representation.
3983 Btype*
3984 Integer_type::do_get_backend(Gogo* gogo)
3986 if (this->is_abstract_)
3988 go_assert(saw_errors());
3989 return gogo->backend()->error_type();
3991 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
3994 // The type descriptor for an integer type. Integer types are always
3995 // named.
3997 Expression*
3998 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4000 go_assert(name != NULL || saw_errors());
4001 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4004 // We should not be asked for the reflection string of a basic type.
4006 void
4007 Integer_type::do_reflection(Gogo*, std::string*) const
4009 go_assert(saw_errors());
4012 // Make an integer type.
4014 Named_type*
4015 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4016 int runtime_type_kind)
4018 return Integer_type::create_integer_type(name, is_unsigned, bits,
4019 runtime_type_kind);
4022 // Make an abstract integer type.
4024 Integer_type*
4025 Type::make_abstract_integer_type()
4027 return Integer_type::create_abstract_integer_type();
4030 // Make an abstract character type.
4032 Integer_type*
4033 Type::make_abstract_character_type()
4035 return Integer_type::create_abstract_character_type();
4038 // Look up an integer type.
4040 Named_type*
4041 Type::lookup_integer_type(const char* name)
4043 return Integer_type::lookup_integer_type(name);
4046 // Class Float_type.
4048 Float_type::Named_float_types Float_type::named_float_types;
4050 // Create a new float type. Non-abstract float types always have
4051 // names.
4053 Named_type*
4054 Float_type::create_float_type(const char* name, int bits,
4055 int runtime_type_kind)
4057 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4058 std::string sname(name);
4059 Named_object* named_object =
4060 Named_object::make_type(sname, NULL, float_type,
4061 Linemap::predeclared_location());
4062 Named_type* named_type = named_object->type_value();
4063 std::pair<Named_float_types::iterator, bool> ins =
4064 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4065 go_assert(ins.second);
4066 return named_type;
4069 // Look up an existing float type.
4071 Named_type*
4072 Float_type::lookup_float_type(const char* name)
4074 Named_float_types::const_iterator p =
4075 Float_type::named_float_types.find(name);
4076 go_assert(p != Float_type::named_float_types.end());
4077 return p->second;
4080 // Create a new abstract float type.
4082 Float_type*
4083 Float_type::create_abstract_float_type()
4085 static Float_type* abstract_type;
4086 if (abstract_type == NULL)
4087 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4088 return abstract_type;
4091 // Whether this type is identical with T.
4093 bool
4094 Float_type::is_identical(const Float_type* t) const
4096 if (this->bits_ != t->bits_)
4097 return false;
4098 return this->is_abstract_ == t->is_abstract_;
4101 // Hash code.
4103 unsigned int
4104 Float_type::do_hash_for_method(Gogo*) const
4106 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4109 // Convert to the backend representation.
4111 Btype*
4112 Float_type::do_get_backend(Gogo* gogo)
4114 return gogo->backend()->float_type(this->bits_);
4117 // The type descriptor for a float type. Float types are always named.
4119 Expression*
4120 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4122 go_assert(name != NULL || saw_errors());
4123 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4126 // We should not be asked for the reflection string of a basic type.
4128 void
4129 Float_type::do_reflection(Gogo*, std::string*) const
4131 go_assert(saw_errors());
4134 // Make a floating point type.
4136 Named_type*
4137 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4139 return Float_type::create_float_type(name, bits, runtime_type_kind);
4142 // Make an abstract float type.
4144 Float_type*
4145 Type::make_abstract_float_type()
4147 return Float_type::create_abstract_float_type();
4150 // Look up a float type.
4152 Named_type*
4153 Type::lookup_float_type(const char* name)
4155 return Float_type::lookup_float_type(name);
4158 // Class Complex_type.
4160 Complex_type::Named_complex_types Complex_type::named_complex_types;
4162 // Create a new complex type. Non-abstract complex types always have
4163 // names.
4165 Named_type*
4166 Complex_type::create_complex_type(const char* name, int bits,
4167 int runtime_type_kind)
4169 Complex_type* complex_type = new Complex_type(false, bits,
4170 runtime_type_kind);
4171 std::string sname(name);
4172 Named_object* named_object =
4173 Named_object::make_type(sname, NULL, complex_type,
4174 Linemap::predeclared_location());
4175 Named_type* named_type = named_object->type_value();
4176 std::pair<Named_complex_types::iterator, bool> ins =
4177 Complex_type::named_complex_types.insert(std::make_pair(sname,
4178 named_type));
4179 go_assert(ins.second);
4180 return named_type;
4183 // Look up an existing complex type.
4185 Named_type*
4186 Complex_type::lookup_complex_type(const char* name)
4188 Named_complex_types::const_iterator p =
4189 Complex_type::named_complex_types.find(name);
4190 go_assert(p != Complex_type::named_complex_types.end());
4191 return p->second;
4194 // Create a new abstract complex type.
4196 Complex_type*
4197 Complex_type::create_abstract_complex_type()
4199 static Complex_type* abstract_type;
4200 if (abstract_type == NULL)
4201 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4202 return abstract_type;
4205 // Whether this type is identical with T.
4207 bool
4208 Complex_type::is_identical(const Complex_type *t) const
4210 if (this->bits_ != t->bits_)
4211 return false;
4212 return this->is_abstract_ == t->is_abstract_;
4215 // Hash code.
4217 unsigned int
4218 Complex_type::do_hash_for_method(Gogo*) const
4220 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4223 // Convert to the backend representation.
4225 Btype*
4226 Complex_type::do_get_backend(Gogo* gogo)
4228 return gogo->backend()->complex_type(this->bits_);
4231 // The type descriptor for a complex type. Complex types are always
4232 // named.
4234 Expression*
4235 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4237 go_assert(name != NULL || saw_errors());
4238 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4241 // We should not be asked for the reflection string of a basic type.
4243 void
4244 Complex_type::do_reflection(Gogo*, std::string*) const
4246 go_assert(saw_errors());
4249 // Make a complex type.
4251 Named_type*
4252 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4254 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4257 // Make an abstract complex type.
4259 Complex_type*
4260 Type::make_abstract_complex_type()
4262 return Complex_type::create_abstract_complex_type();
4265 // Look up a complex type.
4267 Named_type*
4268 Type::lookup_complex_type(const char* name)
4270 return Complex_type::lookup_complex_type(name);
4273 // Class String_type.
4275 // Convert String_type to the backend representation. A string is a
4276 // struct with two fields: a pointer to the characters and a length.
4278 Btype*
4279 String_type::do_get_backend(Gogo* gogo)
4281 static Btype* backend_string_type;
4282 if (backend_string_type == NULL)
4284 std::vector<Backend::Btyped_identifier> fields(2);
4286 Type* b = gogo->lookup_global("byte")->type_value();
4287 Type* pb = Type::make_pointer_type(b);
4289 // We aren't going to get back to this field to finish the
4290 // backend representation, so force it to be finished now.
4291 if (!gogo->named_types_are_converted())
4293 Btype* bt = pb->get_backend_placeholder(gogo);
4294 pb->finish_backend(gogo, bt);
4297 fields[0].name = "__data";
4298 fields[0].btype = pb->get_backend(gogo);
4299 fields[0].location = Linemap::predeclared_location();
4301 Type* int_type = Type::lookup_integer_type("int");
4302 fields[1].name = "__length";
4303 fields[1].btype = int_type->get_backend(gogo);
4304 fields[1].location = fields[0].location;
4306 backend_string_type = gogo->backend()->struct_type(fields);
4308 return backend_string_type;
4311 // The type descriptor for the string type.
4313 Expression*
4314 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4316 if (name != NULL)
4317 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4318 else
4320 Named_object* no = gogo->lookup_global("string");
4321 go_assert(no != NULL);
4322 return Type::type_descriptor(gogo, no->type_value());
4326 // We should not be asked for the reflection string of a basic type.
4328 void
4329 String_type::do_reflection(Gogo*, std::string* ret) const
4331 ret->append("string");
4334 // Make a string type.
4336 Type*
4337 Type::make_string_type()
4339 static String_type string_type;
4340 return &string_type;
4343 // The named type "string".
4345 static Named_type* named_string_type;
4347 // Get the named type "string".
4349 Named_type*
4350 Type::lookup_string_type()
4352 return named_string_type;
4355 // Make the named type string.
4357 Named_type*
4358 Type::make_named_string_type()
4360 Type* string_type = Type::make_string_type();
4361 Named_object* named_object =
4362 Named_object::make_type("string", NULL, string_type,
4363 Linemap::predeclared_location());
4364 Named_type* named_type = named_object->type_value();
4365 named_string_type = named_type;
4366 return named_type;
4369 // The sink type. This is the type of the blank identifier _. Any
4370 // type may be assigned to it.
4372 class Sink_type : public Type
4374 public:
4375 Sink_type()
4376 : Type(TYPE_SINK)
4379 protected:
4380 bool
4381 do_compare_is_identity(Gogo*)
4382 { return false; }
4384 Btype*
4385 do_get_backend(Gogo*)
4386 { go_unreachable(); }
4388 Expression*
4389 do_type_descriptor(Gogo*, Named_type*)
4390 { go_unreachable(); }
4392 void
4393 do_reflection(Gogo*, std::string*) const
4394 { go_unreachable(); }
4396 void
4397 do_mangled_name(Gogo*, std::string*) const
4398 { go_unreachable(); }
4401 // Make the sink type.
4403 Type*
4404 Type::make_sink_type()
4406 static Sink_type sink_type;
4407 return &sink_type;
4410 // Class Function_type.
4412 // Traversal.
4415 Function_type::do_traverse(Traverse* traverse)
4417 if (this->receiver_ != NULL
4418 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4419 return TRAVERSE_EXIT;
4420 if (this->parameters_ != NULL
4421 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4422 return TRAVERSE_EXIT;
4423 if (this->results_ != NULL
4424 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4425 return TRAVERSE_EXIT;
4426 return TRAVERSE_CONTINUE;
4429 // Returns whether T is a valid redeclaration of this type. If this
4430 // returns false, and REASON is not NULL, *REASON may be set to a
4431 // brief explanation of why it returned false.
4433 bool
4434 Function_type::is_valid_redeclaration(const Function_type* t,
4435 std::string* reason) const
4437 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4438 return false;
4440 // A redeclaration of a function is required to use the same names
4441 // for the receiver and parameters.
4442 if (this->receiver() != NULL
4443 && this->receiver()->name() != t->receiver()->name())
4445 if (reason != NULL)
4446 *reason = "receiver name changed";
4447 return false;
4450 const Typed_identifier_list* parms1 = this->parameters();
4451 const Typed_identifier_list* parms2 = t->parameters();
4452 if (parms1 != NULL)
4454 Typed_identifier_list::const_iterator p1 = parms1->begin();
4455 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4456 p2 != parms2->end();
4457 ++p2, ++p1)
4459 if (p1->name() != p2->name())
4461 if (reason != NULL)
4462 *reason = "parameter name changed";
4463 return false;
4466 // This is called at parse time, so we may have unknown
4467 // types.
4468 Type* t1 = p1->type()->forwarded();
4469 Type* t2 = p2->type()->forwarded();
4470 if (t1 != t2
4471 && t1->forward_declaration_type() != NULL
4472 && (t2->forward_declaration_type() == NULL
4473 || (t1->forward_declaration_type()->named_object()
4474 != t2->forward_declaration_type()->named_object())))
4475 return false;
4479 const Typed_identifier_list* results1 = this->results();
4480 const Typed_identifier_list* results2 = t->results();
4481 if (results1 != NULL)
4483 Typed_identifier_list::const_iterator res1 = results1->begin();
4484 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4485 res2 != results2->end();
4486 ++res2, ++res1)
4488 if (res1->name() != res2->name())
4490 if (reason != NULL)
4491 *reason = "result name changed";
4492 return false;
4495 // This is called at parse time, so we may have unknown
4496 // types.
4497 Type* t1 = res1->type()->forwarded();
4498 Type* t2 = res2->type()->forwarded();
4499 if (t1 != t2
4500 && t1->forward_declaration_type() != NULL
4501 && (t2->forward_declaration_type() == NULL
4502 || (t1->forward_declaration_type()->named_object()
4503 != t2->forward_declaration_type()->named_object())))
4504 return false;
4508 return true;
4511 // Check whether T is the same as this type.
4513 bool
4514 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4515 Cmp_tags cmp_tags, bool errors_are_identical,
4516 std::string* reason) const
4518 if (this->is_backend_function_type() != t->is_backend_function_type())
4519 return false;
4521 if (!ignore_receiver)
4523 const Typed_identifier* r1 = this->receiver();
4524 const Typed_identifier* r2 = t->receiver();
4525 if ((r1 != NULL) != (r2 != NULL))
4527 if (reason != NULL)
4528 *reason = _("different receiver types");
4529 return false;
4531 if (r1 != NULL)
4533 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4534 errors_are_identical, reason))
4536 if (reason != NULL && !reason->empty())
4537 *reason = "receiver: " + *reason;
4538 return false;
4543 const Typed_identifier_list* parms1 = this->parameters();
4544 if (parms1 != NULL && parms1->empty())
4545 parms1 = NULL;
4546 const Typed_identifier_list* parms2 = t->parameters();
4547 if (parms2 != NULL && parms2->empty())
4548 parms2 = NULL;
4549 if ((parms1 != NULL) != (parms2 != NULL))
4551 if (reason != NULL)
4552 *reason = _("different number of parameters");
4553 return false;
4555 if (parms1 != NULL)
4557 Typed_identifier_list::const_iterator p1 = parms1->begin();
4558 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4559 p2 != parms2->end();
4560 ++p2, ++p1)
4562 if (p1 == parms1->end())
4564 if (reason != NULL)
4565 *reason = _("different number of parameters");
4566 return false;
4569 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4570 errors_are_identical, NULL))
4572 if (reason != NULL)
4573 *reason = _("different parameter types");
4574 return false;
4577 if (p1 != parms1->end())
4579 if (reason != NULL)
4580 *reason = _("different number of parameters");
4581 return false;
4585 if (this->is_varargs() != t->is_varargs())
4587 if (reason != NULL)
4588 *reason = _("different varargs");
4589 return false;
4592 const Typed_identifier_list* results1 = this->results();
4593 if (results1 != NULL && results1->empty())
4594 results1 = NULL;
4595 const Typed_identifier_list* results2 = t->results();
4596 if (results2 != NULL && results2->empty())
4597 results2 = NULL;
4598 if ((results1 != NULL) != (results2 != NULL))
4600 if (reason != NULL)
4601 *reason = _("different number of results");
4602 return false;
4604 if (results1 != NULL)
4606 Typed_identifier_list::const_iterator res1 = results1->begin();
4607 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4608 res2 != results2->end();
4609 ++res2, ++res1)
4611 if (res1 == results1->end())
4613 if (reason != NULL)
4614 *reason = _("different number of results");
4615 return false;
4618 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4619 cmp_tags, errors_are_identical,
4620 NULL))
4622 if (reason != NULL)
4623 *reason = _("different result types");
4624 return false;
4627 if (res1 != results1->end())
4629 if (reason != NULL)
4630 *reason = _("different number of results");
4631 return false;
4635 return true;
4638 // Hash code.
4640 unsigned int
4641 Function_type::do_hash_for_method(Gogo* gogo) const
4643 unsigned int ret = 0;
4644 // We ignore the receiver type for hash codes, because we need to
4645 // get the same hash code for a method in an interface and a method
4646 // declared for a type. The former will not have a receiver.
4647 if (this->parameters_ != NULL)
4649 int shift = 1;
4650 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4651 p != this->parameters_->end();
4652 ++p, ++shift)
4653 ret += p->type()->hash_for_method(gogo) << shift;
4655 if (this->results_ != NULL)
4657 int shift = 2;
4658 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4659 p != this->results_->end();
4660 ++p, ++shift)
4661 ret += p->type()->hash_for_method(gogo) << shift;
4663 if (this->is_varargs_)
4664 ret += 1;
4665 ret <<= 4;
4666 return ret;
4669 // Hash result parameters.
4671 unsigned int
4672 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4674 unsigned int hash = 0;
4675 for (Typed_identifier_list::const_iterator p = t->begin();
4676 p != t->end();
4677 ++p)
4679 hash <<= 2;
4680 hash = Type::hash_string(p->name(), hash);
4681 hash += p->type()->hash_for_method(NULL);
4683 return hash;
4686 // Compare result parameters so that can map identical result
4687 // parameters to a single struct type.
4689 bool
4690 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4691 const Typed_identifier_list* b) const
4693 if (a->size() != b->size())
4694 return false;
4695 Typed_identifier_list::const_iterator pa = a->begin();
4696 for (Typed_identifier_list::const_iterator pb = b->begin();
4697 pb != b->end();
4698 ++pa, ++pb)
4700 if (pa->name() != pb->name()
4701 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4702 return false;
4704 return true;
4707 // Hash from results to a backend struct type.
4709 Function_type::Results_structs Function_type::results_structs;
4711 // Get the backend representation for a function type.
4713 Btype*
4714 Function_type::get_backend_fntype(Gogo* gogo)
4716 if (this->fnbtype_ == NULL)
4718 Backend::Btyped_identifier breceiver;
4719 if (this->receiver_ != NULL)
4721 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4723 // We always pass the address of the receiver parameter, in
4724 // order to make interface calls work with unknown types.
4725 Type* rtype = this->receiver_->type();
4726 if (rtype->points_to() == NULL)
4727 rtype = Type::make_pointer_type(rtype);
4728 breceiver.btype = rtype->get_backend(gogo);
4729 breceiver.location = this->receiver_->location();
4732 std::vector<Backend::Btyped_identifier> bparameters;
4733 if (this->parameters_ != NULL)
4735 bparameters.resize(this->parameters_->size());
4736 size_t i = 0;
4737 for (Typed_identifier_list::const_iterator p =
4738 this->parameters_->begin(); p != this->parameters_->end();
4739 ++p, ++i)
4741 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4742 bparameters[i].btype = p->type()->get_backend(gogo);
4743 bparameters[i].location = p->location();
4745 go_assert(i == bparameters.size());
4748 std::vector<Backend::Btyped_identifier> bresults;
4749 Btype* bresult_struct = NULL;
4750 if (this->results_ != NULL)
4752 bresults.resize(this->results_->size());
4753 size_t i = 0;
4754 for (Typed_identifier_list::const_iterator p =
4755 this->results_->begin();
4756 p != this->results_->end();
4757 ++p, ++i)
4759 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4760 bresults[i].btype = p->type()->get_backend(gogo);
4761 bresults[i].location = p->location();
4763 go_assert(i == bresults.size());
4765 if (this->results_->size() > 1)
4767 // Use the same results struct for all functions that
4768 // return the same set of results. This is useful to
4769 // unify calls to interface methods with other calls.
4770 std::pair<Typed_identifier_list*, Btype*> val;
4771 val.first = this->results_;
4772 val.second = NULL;
4773 std::pair<Results_structs::iterator, bool> ins =
4774 Function_type::results_structs.insert(val);
4775 if (ins.second)
4777 // Build a new struct type.
4778 Struct_field_list* sfl = new Struct_field_list;
4779 for (Typed_identifier_list::const_iterator p =
4780 this->results_->begin();
4781 p != this->results_->end();
4782 ++p)
4784 Typed_identifier tid = *p;
4785 if (tid.name().empty())
4786 tid = Typed_identifier("UNNAMED", tid.type(),
4787 tid.location());
4788 sfl->push_back(Struct_field(tid));
4790 Struct_type* st = Type::make_struct_type(sfl,
4791 this->location());
4792 st->set_is_struct_incomparable();
4793 ins.first->second = st->get_backend(gogo);
4795 bresult_struct = ins.first->second;
4799 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4800 bresults, bresult_struct,
4801 this->location());
4805 return this->fnbtype_;
4808 // Get the backend representation for a Go function type.
4810 Btype*
4811 Function_type::do_get_backend(Gogo* gogo)
4813 // When we do anything with a function value other than call it, it
4814 // is represented as a pointer to a struct whose first field is the
4815 // actual function. So that is what we return as the type of a Go
4816 // function.
4818 Location loc = this->location();
4819 Btype* struct_type =
4820 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4821 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4823 std::vector<Backend::Btyped_identifier> fields(1);
4824 fields[0].name = "code";
4825 fields[0].btype = this->get_backend_fntype(gogo);
4826 fields[0].location = loc;
4827 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4828 return gogo->backend()->error_type();
4829 return ptr_struct_type;
4832 // The type of a function type descriptor.
4834 Type*
4835 Function_type::make_function_type_descriptor_type()
4837 static Type* ret;
4838 if (ret == NULL)
4840 Type* tdt = Type::make_type_descriptor_type();
4841 Type* ptdt = Type::make_type_descriptor_ptr_type();
4843 Type* bool_type = Type::lookup_bool_type();
4845 Type* slice_type = Type::make_array_type(ptdt, NULL);
4847 Struct_type* s = Type::make_builtin_struct_type(4,
4848 "", tdt,
4849 "dotdotdot", bool_type,
4850 "in", slice_type,
4851 "out", slice_type);
4853 ret = Type::make_builtin_named_type("FuncType", s);
4856 return ret;
4859 // The type descriptor for a function type.
4861 Expression*
4862 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4864 Location bloc = Linemap::predeclared_location();
4866 Type* ftdt = Function_type::make_function_type_descriptor_type();
4868 const Struct_field_list* fields = ftdt->struct_type()->fields();
4870 Expression_list* vals = new Expression_list();
4871 vals->reserve(4);
4873 Struct_field_list::const_iterator p = fields->begin();
4874 go_assert(p->is_field_name("_type"));
4875 vals->push_back(this->type_descriptor_constructor(gogo,
4876 RUNTIME_TYPE_KIND_FUNC,
4877 name, NULL, true));
4879 ++p;
4880 go_assert(p->is_field_name("dotdotdot"));
4881 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4883 ++p;
4884 go_assert(p->is_field_name("in"));
4885 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4886 this->parameters()));
4888 ++p;
4889 go_assert(p->is_field_name("out"));
4890 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4891 this->results()));
4893 ++p;
4894 go_assert(p == fields->end());
4896 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4899 // Return a composite literal for the parameters or results of a type
4900 // descriptor.
4902 Expression*
4903 Function_type::type_descriptor_params(Type* params_type,
4904 const Typed_identifier* receiver,
4905 const Typed_identifier_list* params)
4907 Location bloc = Linemap::predeclared_location();
4909 if (receiver == NULL && params == NULL)
4910 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
4912 Expression_list* vals = new Expression_list();
4913 vals->reserve((params == NULL ? 0 : params->size())
4914 + (receiver != NULL ? 1 : 0));
4916 if (receiver != NULL)
4917 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
4919 if (params != NULL)
4921 for (Typed_identifier_list::const_iterator p = params->begin();
4922 p != params->end();
4923 ++p)
4924 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
4927 return Expression::make_slice_composite_literal(params_type, vals, bloc);
4930 // The reflection string.
4932 void
4933 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
4935 // FIXME: Turn this off until we straighten out the type of the
4936 // struct field used in a go statement which calls a method.
4937 // go_assert(this->receiver_ == NULL);
4939 ret->append("func");
4941 if (this->receiver_ != NULL)
4943 ret->push_back('(');
4944 this->append_reflection(this->receiver_->type(), gogo, ret);
4945 ret->push_back(')');
4948 ret->push_back('(');
4949 const Typed_identifier_list* params = this->parameters();
4950 if (params != NULL)
4952 bool is_varargs = this->is_varargs_;
4953 for (Typed_identifier_list::const_iterator p = params->begin();
4954 p != params->end();
4955 ++p)
4957 if (p != params->begin())
4958 ret->append(", ");
4959 if (!is_varargs || p + 1 != params->end())
4960 this->append_reflection(p->type(), gogo, ret);
4961 else
4963 ret->append("...");
4964 this->append_reflection(p->type()->array_type()->element_type(),
4965 gogo, ret);
4969 ret->push_back(')');
4971 const Typed_identifier_list* results = this->results();
4972 if (results != NULL && !results->empty())
4974 if (results->size() == 1)
4975 ret->push_back(' ');
4976 else
4977 ret->append(" (");
4978 for (Typed_identifier_list::const_iterator p = results->begin();
4979 p != results->end();
4980 ++p)
4982 if (p != results->begin())
4983 ret->append(", ");
4984 this->append_reflection(p->type(), gogo, ret);
4986 if (results->size() > 1)
4987 ret->push_back(')');
4991 // Export a function type.
4993 void
4994 Function_type::do_export(Export* exp) const
4996 // We don't write out the receiver. The only function types which
4997 // should have a receiver are the ones associated with explicitly
4998 // defined methods. For those the receiver type is written out by
4999 // Function::export_func.
5001 exp->write_c_string("(");
5002 bool first = true;
5003 if (this->parameters_ != NULL)
5005 bool is_varargs = this->is_varargs_;
5006 for (Typed_identifier_list::const_iterator p =
5007 this->parameters_->begin();
5008 p != this->parameters_->end();
5009 ++p)
5011 if (first)
5012 first = false;
5013 else
5014 exp->write_c_string(", ");
5015 exp->write_name(p->name());
5016 exp->write_c_string(" ");
5017 if (!is_varargs || p + 1 != this->parameters_->end())
5018 exp->write_type(p->type());
5019 else
5021 exp->write_c_string("...");
5022 exp->write_type(p->type()->array_type()->element_type());
5026 exp->write_c_string(")");
5028 const Typed_identifier_list* results = this->results_;
5029 if (results != NULL)
5031 exp->write_c_string(" ");
5032 if (results->size() == 1 && results->begin()->name().empty())
5033 exp->write_type(results->begin()->type());
5034 else
5036 first = true;
5037 exp->write_c_string("(");
5038 for (Typed_identifier_list::const_iterator p = results->begin();
5039 p != results->end();
5040 ++p)
5042 if (first)
5043 first = false;
5044 else
5045 exp->write_c_string(", ");
5046 exp->write_name(p->name());
5047 exp->write_c_string(" ");
5048 exp->write_type(p->type());
5050 exp->write_c_string(")");
5055 // Import a function type.
5057 Function_type*
5058 Function_type::do_import(Import* imp)
5060 imp->require_c_string("(");
5061 Typed_identifier_list* parameters;
5062 bool is_varargs = false;
5063 if (imp->peek_char() == ')')
5064 parameters = NULL;
5065 else
5067 parameters = new Typed_identifier_list();
5068 while (true)
5070 std::string name = imp->read_name();
5071 imp->require_c_string(" ");
5073 if (imp->match_c_string("..."))
5075 imp->advance(3);
5076 is_varargs = true;
5079 Type* ptype = imp->read_type();
5080 if (is_varargs)
5081 ptype = Type::make_array_type(ptype, NULL);
5082 parameters->push_back(Typed_identifier(name, ptype,
5083 imp->location()));
5084 if (imp->peek_char() != ',')
5085 break;
5086 go_assert(!is_varargs);
5087 imp->require_c_string(", ");
5090 imp->require_c_string(")");
5092 Typed_identifier_list* results;
5093 if (imp->peek_char() != ' ')
5094 results = NULL;
5095 else
5097 imp->advance(1);
5098 results = new Typed_identifier_list;
5099 if (imp->peek_char() != '(')
5101 Type* rtype = imp->read_type();
5102 results->push_back(Typed_identifier("", rtype, imp->location()));
5104 else
5106 imp->advance(1);
5107 while (true)
5109 std::string name = imp->read_name();
5110 imp->require_c_string(" ");
5111 Type* rtype = imp->read_type();
5112 results->push_back(Typed_identifier(name, rtype,
5113 imp->location()));
5114 if (imp->peek_char() != ',')
5115 break;
5116 imp->require_c_string(", ");
5118 imp->require_c_string(")");
5122 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5123 imp->location());
5124 if (is_varargs)
5125 ret->set_is_varargs();
5126 return ret;
5129 // Make a copy of a function type without a receiver.
5131 Function_type*
5132 Function_type::copy_without_receiver() const
5134 go_assert(this->is_method());
5135 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5136 this->results_,
5137 this->location_);
5138 if (this->is_varargs())
5139 ret->set_is_varargs();
5140 if (this->is_builtin())
5141 ret->set_is_builtin();
5142 return ret;
5145 // Make a copy of a function type with a receiver.
5147 Function_type*
5148 Function_type::copy_with_receiver(Type* receiver_type) const
5150 go_assert(!this->is_method());
5151 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5152 this->location_);
5153 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5154 this->results_,
5155 this->location_);
5156 if (this->is_varargs_)
5157 ret->set_is_varargs();
5158 return ret;
5161 // Make a copy of a function type with the receiver as the first
5162 // parameter.
5164 Function_type*
5165 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5167 go_assert(this->is_method());
5168 Typed_identifier_list* new_params = new Typed_identifier_list();
5169 Type* rtype = this->receiver_->type();
5170 if (want_pointer_receiver)
5171 rtype = Type::make_pointer_type(rtype);
5172 Typed_identifier receiver(this->receiver_->name(), rtype,
5173 this->receiver_->location());
5174 new_params->push_back(receiver);
5175 const Typed_identifier_list* orig_params = this->parameters_;
5176 if (orig_params != NULL && !orig_params->empty())
5178 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5179 p != orig_params->end();
5180 ++p)
5181 new_params->push_back(*p);
5183 return Type::make_function_type(NULL, new_params, this->results_,
5184 this->location_);
5187 // Make a copy of a function type ignoring any receiver and adding a
5188 // closure parameter.
5190 Function_type*
5191 Function_type::copy_with_names() const
5193 Typed_identifier_list* new_params = new Typed_identifier_list();
5194 const Typed_identifier_list* orig_params = this->parameters_;
5195 if (orig_params != NULL && !orig_params->empty())
5197 static int count;
5198 char buf[50];
5199 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5200 p != orig_params->end();
5201 ++p)
5203 snprintf(buf, sizeof buf, "pt.%u", count);
5204 ++count;
5205 new_params->push_back(Typed_identifier(buf, p->type(),
5206 p->location()));
5210 const Typed_identifier_list* orig_results = this->results_;
5211 Typed_identifier_list* new_results;
5212 if (orig_results == NULL || orig_results->empty())
5213 new_results = NULL;
5214 else
5216 new_results = new Typed_identifier_list();
5217 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5218 p != orig_results->end();
5219 ++p)
5220 new_results->push_back(Typed_identifier("", p->type(),
5221 p->location()));
5224 return Type::make_function_type(NULL, new_params, new_results,
5225 this->location());
5228 // Make a function type.
5230 Function_type*
5231 Type::make_function_type(Typed_identifier* receiver,
5232 Typed_identifier_list* parameters,
5233 Typed_identifier_list* results,
5234 Location location)
5236 return new Function_type(receiver, parameters, results, location);
5239 // Make a backend function type.
5241 Backend_function_type*
5242 Type::make_backend_function_type(Typed_identifier* receiver,
5243 Typed_identifier_list* parameters,
5244 Typed_identifier_list* results,
5245 Location location)
5247 return new Backend_function_type(receiver, parameters, results, location);
5250 // Class Pointer_type.
5252 // Traversal.
5255 Pointer_type::do_traverse(Traverse* traverse)
5257 return Type::traverse(this->to_type_, traverse);
5260 // Hash code.
5262 unsigned int
5263 Pointer_type::do_hash_for_method(Gogo* gogo) const
5265 return this->to_type_->hash_for_method(gogo) << 4;
5268 // Get the backend representation for a pointer type.
5270 Btype*
5271 Pointer_type::do_get_backend(Gogo* gogo)
5273 Btype* to_btype = this->to_type_->get_backend(gogo);
5274 return gogo->backend()->pointer_type(to_btype);
5277 // The type of a pointer type descriptor.
5279 Type*
5280 Pointer_type::make_pointer_type_descriptor_type()
5282 static Type* ret;
5283 if (ret == NULL)
5285 Type* tdt = Type::make_type_descriptor_type();
5286 Type* ptdt = Type::make_type_descriptor_ptr_type();
5288 Struct_type* s = Type::make_builtin_struct_type(2,
5289 "", tdt,
5290 "elem", ptdt);
5292 ret = Type::make_builtin_named_type("PtrType", s);
5295 return ret;
5298 // The type descriptor for a pointer type.
5300 Expression*
5301 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5303 if (this->is_unsafe_pointer_type())
5305 go_assert(name != NULL);
5306 return this->plain_type_descriptor(gogo,
5307 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5308 name);
5310 else
5312 Location bloc = Linemap::predeclared_location();
5314 const Methods* methods;
5315 Type* deref = this->points_to();
5316 if (deref->named_type() != NULL)
5317 methods = deref->named_type()->methods();
5318 else if (deref->struct_type() != NULL)
5319 methods = deref->struct_type()->methods();
5320 else
5321 methods = NULL;
5323 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5325 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5327 Expression_list* vals = new Expression_list();
5328 vals->reserve(2);
5330 Struct_field_list::const_iterator p = fields->begin();
5331 go_assert(p->is_field_name("_type"));
5332 vals->push_back(this->type_descriptor_constructor(gogo,
5333 RUNTIME_TYPE_KIND_PTR,
5334 name, methods, false));
5336 ++p;
5337 go_assert(p->is_field_name("elem"));
5338 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5340 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5344 // Reflection string.
5346 void
5347 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5349 ret->push_back('*');
5350 this->append_reflection(this->to_type_, gogo, ret);
5353 // Export.
5355 void
5356 Pointer_type::do_export(Export* exp) const
5358 exp->write_c_string("*");
5359 if (this->is_unsafe_pointer_type())
5360 exp->write_c_string("any");
5361 else
5362 exp->write_type(this->to_type_);
5365 // Import.
5367 Pointer_type*
5368 Pointer_type::do_import(Import* imp)
5370 imp->require_c_string("*");
5371 if (imp->match_c_string("any"))
5373 imp->advance(3);
5374 return Type::make_pointer_type(Type::make_void_type());
5376 Type* to = imp->read_type();
5377 return Type::make_pointer_type(to);
5380 // Cache of pointer types. Key is "to" type, value is pointer type
5381 // that points to key.
5383 Type::Pointer_type_table Type::pointer_types;
5385 // A list of placeholder pointer types. We keep this so we can ensure
5386 // they are finalized.
5388 std::vector<Pointer_type*> Type::placeholder_pointers;
5390 // Make a pointer type.
5392 Pointer_type*
5393 Type::make_pointer_type(Type* to_type)
5395 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5396 if (p != pointer_types.end())
5397 return p->second;
5398 Pointer_type* ret = new Pointer_type(to_type);
5399 pointer_types[to_type] = ret;
5400 return ret;
5403 // This helper is invoked immediately after named types have been
5404 // converted, to clean up any unresolved pointer types remaining in
5405 // the pointer type cache.
5407 // The motivation for this routine: occasionally the compiler creates
5408 // some specific pointer type as part of a lowering operation (ex:
5409 // pointer-to-void), then Type::backend_type_size() is invoked on the
5410 // type (which creates a Btype placeholder for it), that placeholder
5411 // passed somewhere along the line to the back end, but since there is
5412 // no reference to the type in user code, there is never a call to
5413 // Type::finish_backend for the type (hence the Btype remains as an
5414 // unresolved placeholder). Calling this routine will clean up such
5415 // instances.
5417 void
5418 Type::finish_pointer_types(Gogo* gogo)
5420 // We don't use begin() and end() because it is possible to add new
5421 // placeholder pointer types as we finalized existing ones.
5422 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5424 Pointer_type* pt = Type::placeholder_pointers[i];
5425 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5426 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5428 pt->finish_backend(gogo, tbti->second.btype);
5429 tbti->second.is_placeholder = false;
5434 // Class Nil_type.
5436 // Get the backend representation of a nil type. FIXME: Is this ever
5437 // actually called?
5439 Btype*
5440 Nil_type::do_get_backend(Gogo* gogo)
5442 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5445 // Make the nil type.
5447 Type*
5448 Type::make_nil_type()
5450 static Nil_type singleton_nil_type;
5451 return &singleton_nil_type;
5454 // The type of a function call which returns multiple values. This is
5455 // really a struct, but we don't want to confuse a function call which
5456 // returns a struct with a function call which returns multiple
5457 // values.
5459 class Call_multiple_result_type : public Type
5461 public:
5462 Call_multiple_result_type(Call_expression* call)
5463 : Type(TYPE_CALL_MULTIPLE_RESULT),
5464 call_(call)
5467 protected:
5468 bool
5469 do_has_pointer() const
5470 { return false; }
5472 bool
5473 do_compare_is_identity(Gogo*)
5474 { return false; }
5476 Btype*
5477 do_get_backend(Gogo* gogo)
5479 go_assert(saw_errors());
5480 return gogo->backend()->error_type();
5483 Expression*
5484 do_type_descriptor(Gogo*, Named_type*)
5486 go_assert(saw_errors());
5487 return Expression::make_error(Linemap::unknown_location());
5490 void
5491 do_reflection(Gogo*, std::string*) const
5492 { go_assert(saw_errors()); }
5494 void
5495 do_mangled_name(Gogo*, std::string*) const
5496 { go_assert(saw_errors()); }
5498 private:
5499 // The expression being called.
5500 Call_expression* call_;
5503 // Make a call result type.
5505 Type*
5506 Type::make_call_multiple_result_type(Call_expression* call)
5508 return new Call_multiple_result_type(call);
5511 // Class Struct_field.
5513 // Get the name of a field.
5515 const std::string&
5516 Struct_field::field_name() const
5518 const std::string& name(this->typed_identifier_.name());
5519 if (!name.empty())
5520 return name;
5521 else
5523 // This is called during parsing, before anything is lowered, so
5524 // we have to be pretty careful to avoid dereferencing an
5525 // unknown type name.
5526 Type* t = this->typed_identifier_.type();
5527 Type* dt = t;
5528 if (t->classification() == Type::TYPE_POINTER)
5530 // Very ugly.
5531 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5532 dt = ptype->points_to();
5534 if (dt->forward_declaration_type() != NULL)
5535 return dt->forward_declaration_type()->name();
5536 else if (dt->named_type() != NULL)
5538 // Note that this can be an alias name.
5539 return dt->named_type()->name();
5541 else if (t->is_error_type() || dt->is_error_type())
5543 static const std::string error_string = "*error*";
5544 return error_string;
5546 else
5548 // Avoid crashing in the erroneous case where T is named but
5549 // DT is not.
5550 go_assert(t != dt);
5551 if (t->forward_declaration_type() != NULL)
5552 return t->forward_declaration_type()->name();
5553 else if (t->named_type() != NULL)
5554 return t->named_type()->name();
5555 else
5556 go_unreachable();
5561 // Return whether this field is named NAME.
5563 bool
5564 Struct_field::is_field_name(const std::string& name) const
5566 const std::string& me(this->typed_identifier_.name());
5567 if (!me.empty())
5568 return me == name;
5569 else
5571 Type* t = this->typed_identifier_.type();
5572 if (t->points_to() != NULL)
5573 t = t->points_to();
5574 Named_type* nt = t->named_type();
5575 if (nt != NULL && nt->name() == name)
5576 return true;
5578 // This is a horrible hack caused by the fact that we don't pack
5579 // the names of builtin types. FIXME.
5580 if (!this->is_imported_
5581 && nt != NULL
5582 && nt->is_builtin()
5583 && nt->name() == Gogo::unpack_hidden_name(name))
5584 return true;
5586 return false;
5590 // Return whether this field is an unexported field named NAME.
5592 bool
5593 Struct_field::is_unexported_field_name(Gogo* gogo,
5594 const std::string& name) const
5596 const std::string& field_name(this->field_name());
5597 if (Gogo::is_hidden_name(field_name)
5598 && name == Gogo::unpack_hidden_name(field_name)
5599 && gogo->pack_hidden_name(name, false) != field_name)
5600 return true;
5602 // Check for the name of a builtin type. This is like the test in
5603 // is_field_name, only there we return false if this->is_imported_,
5604 // and here we return true.
5605 if (this->is_imported_ && this->is_anonymous())
5607 Type* t = this->typed_identifier_.type();
5608 if (t->points_to() != NULL)
5609 t = t->points_to();
5610 Named_type* nt = t->named_type();
5611 if (nt != NULL
5612 && nt->is_builtin()
5613 && nt->name() == Gogo::unpack_hidden_name(name))
5614 return true;
5617 return false;
5620 // Return whether this field is an embedded built-in type.
5622 bool
5623 Struct_field::is_embedded_builtin(Gogo* gogo) const
5625 const std::string& name(this->field_name());
5626 // We know that a field is an embedded type if it is anonymous.
5627 // We can decide if it is a built-in type by checking to see if it is
5628 // registered globally under the field's name.
5629 // This allows us to distinguish between embedded built-in types and
5630 // embedded types that are aliases to built-in types.
5631 return (this->is_anonymous()
5632 && !Gogo::is_hidden_name(name)
5633 && gogo->lookup_global(name.c_str()) != NULL);
5636 // Class Struct_type.
5638 // A hash table used to find identical unnamed structs so that they
5639 // share method tables.
5641 Struct_type::Identical_structs Struct_type::identical_structs;
5643 // A hash table used to merge method sets for identical unnamed
5644 // structs.
5646 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5648 // Traversal.
5651 Struct_type::do_traverse(Traverse* traverse)
5653 Struct_field_list* fields = this->fields_;
5654 if (fields != NULL)
5656 for (Struct_field_list::iterator p = fields->begin();
5657 p != fields->end();
5658 ++p)
5660 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5661 return TRAVERSE_EXIT;
5664 return TRAVERSE_CONTINUE;
5667 // Verify that the struct type is complete and valid.
5669 bool
5670 Struct_type::do_verify()
5672 Struct_field_list* fields = this->fields_;
5673 if (fields == NULL)
5674 return true;
5675 for (Struct_field_list::iterator p = fields->begin();
5676 p != fields->end();
5677 ++p)
5679 Type* t = p->type();
5680 if (p->is_anonymous())
5682 if ((t->named_type() != NULL && t->points_to() != NULL)
5683 || (t->named_type() == NULL && t->points_to() != NULL
5684 && t->points_to()->points_to() != NULL))
5686 go_error_at(p->location(), "embedded type may not be a pointer");
5687 p->set_type(Type::make_error_type());
5689 else if (t->points_to() != NULL
5690 && t->points_to()->interface_type() != NULL)
5692 go_error_at(p->location(),
5693 "embedded type may not be pointer to interface");
5694 p->set_type(Type::make_error_type());
5698 return true;
5701 // Whether this contains a pointer.
5703 bool
5704 Struct_type::do_has_pointer() const
5706 const Struct_field_list* fields = this->fields();
5707 if (fields == NULL)
5708 return false;
5709 for (Struct_field_list::const_iterator p = fields->begin();
5710 p != fields->end();
5711 ++p)
5713 if (p->type()->has_pointer())
5714 return true;
5716 return false;
5719 // Whether this type is identical to T.
5721 bool
5722 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5723 bool errors_are_identical) const
5725 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5726 return false;
5727 const Struct_field_list* fields1 = this->fields();
5728 const Struct_field_list* fields2 = t->fields();
5729 if (fields1 == NULL || fields2 == NULL)
5730 return fields1 == fields2;
5731 Struct_field_list::const_iterator pf2 = fields2->begin();
5732 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5733 pf1 != fields1->end();
5734 ++pf1, ++pf2)
5736 if (pf2 == fields2->end())
5737 return false;
5738 if (pf1->field_name() != pf2->field_name())
5739 return false;
5740 if (pf1->is_anonymous() != pf2->is_anonymous()
5741 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5742 errors_are_identical, NULL))
5743 return false;
5744 if (cmp_tags == COMPARE_TAGS)
5746 if (!pf1->has_tag())
5748 if (pf2->has_tag())
5749 return false;
5751 else
5753 if (!pf2->has_tag())
5754 return false;
5755 if (pf1->tag() != pf2->tag())
5756 return false;
5760 if (pf2 != fields2->end())
5761 return false;
5762 return true;
5765 // Whether comparisons of this struct type are simple identity
5766 // comparisons.
5768 bool
5769 Struct_type::do_compare_is_identity(Gogo* gogo)
5771 const Struct_field_list* fields = this->fields_;
5772 if (fields == NULL)
5773 return true;
5774 int64_t offset = 0;
5775 for (Struct_field_list::const_iterator pf = fields->begin();
5776 pf != fields->end();
5777 ++pf)
5779 if (Gogo::is_sink_name(pf->field_name()))
5780 return false;
5782 if (!pf->type()->compare_is_identity(gogo))
5783 return false;
5785 int64_t field_align;
5786 if (!pf->type()->backend_type_align(gogo, &field_align))
5787 return false;
5788 if ((offset & (field_align - 1)) != 0)
5790 // This struct has padding. We don't guarantee that that
5791 // padding is zero-initialized for a stack variable, so we
5792 // can't use memcmp to compare struct values.
5793 return false;
5796 int64_t field_size;
5797 if (!pf->type()->backend_type_size(gogo, &field_size))
5798 return false;
5799 offset += field_size;
5802 int64_t struct_size;
5803 if (!this->backend_type_size(gogo, &struct_size))
5804 return false;
5805 if (offset != struct_size)
5807 // Trailing padding may not be zero when on the stack.
5808 return false;
5811 return true;
5814 // Return whether this struct type is reflexive--whether a value of
5815 // this type is always equal to itself.
5817 bool
5818 Struct_type::do_is_reflexive()
5820 const Struct_field_list* fields = this->fields_;
5821 if (fields == NULL)
5822 return true;
5823 for (Struct_field_list::const_iterator pf = fields->begin();
5824 pf != fields->end();
5825 ++pf)
5827 if (!pf->type()->is_reflexive())
5828 return false;
5830 return true;
5833 // Return whether this struct type needs a key update when used as a
5834 // map key.
5836 bool
5837 Struct_type::do_needs_key_update()
5839 const Struct_field_list* fields = this->fields_;
5840 if (fields == NULL)
5841 return false;
5842 for (Struct_field_list::const_iterator pf = fields->begin();
5843 pf != fields->end();
5844 ++pf)
5846 if (pf->type()->needs_key_update())
5847 return true;
5849 return false;
5852 // Return whether this struct type is permitted to be in the heap.
5854 bool
5855 Struct_type::do_in_heap()
5857 const Struct_field_list* fields = this->fields_;
5858 if (fields == NULL)
5859 return true;
5860 for (Struct_field_list::const_iterator pf = fields->begin();
5861 pf != fields->end();
5862 ++pf)
5864 if (!pf->type()->in_heap())
5865 return false;
5867 return true;
5870 // Build identity and hash functions for this struct.
5872 // Hash code.
5874 unsigned int
5875 Struct_type::do_hash_for_method(Gogo* gogo) const
5877 unsigned int ret = 0;
5878 if (this->fields() != NULL)
5880 for (Struct_field_list::const_iterator pf = this->fields()->begin();
5881 pf != this->fields()->end();
5882 ++pf)
5883 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
5885 ret <<= 2;
5886 if (this->is_struct_incomparable_)
5887 ret <<= 1;
5888 return ret;
5891 // Find the local field NAME.
5893 const Struct_field*
5894 Struct_type::find_local_field(const std::string& name,
5895 unsigned int *pindex) const
5897 const Struct_field_list* fields = this->fields_;
5898 if (fields == NULL)
5899 return NULL;
5900 unsigned int i = 0;
5901 for (Struct_field_list::const_iterator pf = fields->begin();
5902 pf != fields->end();
5903 ++pf, ++i)
5905 if (pf->is_field_name(name))
5907 if (pindex != NULL)
5908 *pindex = i;
5909 return &*pf;
5912 return NULL;
5915 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
5917 Field_reference_expression*
5918 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
5919 Location location) const
5921 unsigned int depth;
5922 return this->field_reference_depth(struct_expr, name, location, NULL,
5923 &depth);
5926 // Return an expression for a field, along with the depth at which it
5927 // was found.
5929 Field_reference_expression*
5930 Struct_type::field_reference_depth(Expression* struct_expr,
5931 const std::string& name,
5932 Location location,
5933 Saw_named_type* saw,
5934 unsigned int* depth) const
5936 const Struct_field_list* fields = this->fields_;
5937 if (fields == NULL)
5938 return NULL;
5940 // Look for a field with this name.
5941 unsigned int i = 0;
5942 for (Struct_field_list::const_iterator pf = fields->begin();
5943 pf != fields->end();
5944 ++pf, ++i)
5946 if (pf->is_field_name(name))
5948 *depth = 0;
5949 return Expression::make_field_reference(struct_expr, i, location);
5953 // Look for an anonymous field which contains a field with this
5954 // name.
5955 unsigned int found_depth = 0;
5956 Field_reference_expression* ret = NULL;
5957 i = 0;
5958 for (Struct_field_list::const_iterator pf = fields->begin();
5959 pf != fields->end();
5960 ++pf, ++i)
5962 if (!pf->is_anonymous())
5963 continue;
5965 Struct_type* st = pf->type()->deref()->struct_type();
5966 if (st == NULL)
5967 continue;
5969 Saw_named_type* hold_saw = saw;
5970 Saw_named_type saw_here;
5971 Named_type* nt = pf->type()->named_type();
5972 if (nt == NULL)
5973 nt = pf->type()->deref()->named_type();
5974 if (nt != NULL)
5976 Saw_named_type* q;
5977 for (q = saw; q != NULL; q = q->next)
5979 if (q->nt == nt)
5981 // If this is an error, it will be reported
5982 // elsewhere.
5983 break;
5986 if (q != NULL)
5987 continue;
5988 saw_here.next = saw;
5989 saw_here.nt = nt;
5990 saw = &saw_here;
5993 // Look for a reference using a NULL struct expression. If we
5994 // find one, fill in the struct expression with a reference to
5995 // this field.
5996 unsigned int subdepth;
5997 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5998 location,
5999 saw,
6000 &subdepth);
6002 saw = hold_saw;
6004 if (sub == NULL)
6005 continue;
6007 if (ret == NULL || subdepth < found_depth)
6009 if (ret != NULL)
6010 delete ret;
6011 ret = sub;
6012 found_depth = subdepth;
6013 Expression* here = Expression::make_field_reference(struct_expr, i,
6014 location);
6015 if (pf->type()->points_to() != NULL)
6016 here = Expression::make_dereference(here,
6017 Expression::NIL_CHECK_DEFAULT,
6018 location);
6019 while (sub->expr() != NULL)
6021 sub = sub->expr()->deref()->field_reference_expression();
6022 go_assert(sub != NULL);
6024 sub->set_struct_expression(here);
6025 sub->set_implicit(true);
6027 else if (subdepth > found_depth)
6028 delete sub;
6029 else
6031 // We do not handle ambiguity here--it should be handled by
6032 // Type::bind_field_or_method.
6033 delete sub;
6034 found_depth = 0;
6035 ret = NULL;
6039 if (ret != NULL)
6040 *depth = found_depth + 1;
6042 return ret;
6045 // Return the total number of fields, including embedded fields.
6047 unsigned int
6048 Struct_type::total_field_count() const
6050 if (this->fields_ == NULL)
6051 return 0;
6052 unsigned int ret = 0;
6053 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6054 pf != this->fields_->end();
6055 ++pf)
6057 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6058 ++ret;
6059 else
6060 ret += pf->type()->struct_type()->total_field_count();
6062 return ret;
6065 // Return whether NAME is an unexported field, for better error reporting.
6067 bool
6068 Struct_type::is_unexported_local_field(Gogo* gogo,
6069 const std::string& name) const
6071 const Struct_field_list* fields = this->fields_;
6072 if (fields != NULL)
6074 for (Struct_field_list::const_iterator pf = fields->begin();
6075 pf != fields->end();
6076 ++pf)
6077 if (pf->is_unexported_field_name(gogo, name))
6078 return true;
6080 return false;
6083 // Finalize the methods of an unnamed struct.
6085 void
6086 Struct_type::finalize_methods(Gogo* gogo)
6088 if (this->all_methods_ != NULL)
6089 return;
6091 // It is possible to have multiple identical structs that have
6092 // methods. We want them to share method tables. Otherwise we will
6093 // emit identical methods more than once, which is bad since they
6094 // will even have the same names.
6095 std::pair<Identical_structs::iterator, bool> ins =
6096 Struct_type::identical_structs.insert(std::make_pair(this, this));
6097 if (!ins.second)
6099 // An identical struct was already entered into the hash table.
6100 // Note that finalize_methods is, fortunately, not recursive.
6101 this->all_methods_ = ins.first->second->all_methods_;
6102 return;
6105 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6108 // Return the method NAME, or NULL if there isn't one or if it is
6109 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6110 // ambiguous.
6112 Method*
6113 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6115 return Type::method_function(this->all_methods_, name, is_ambiguous);
6118 // Return a pointer to the interface method table for this type for
6119 // the interface INTERFACE. IS_POINTER is true if this is for a
6120 // pointer to THIS.
6122 Expression*
6123 Struct_type::interface_method_table(Interface_type* interface,
6124 bool is_pointer)
6126 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6127 val(this, NULL);
6128 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6129 Struct_type::struct_method_tables.insert(val);
6131 Struct_method_table_pair* smtp;
6132 if (!ins.second)
6133 smtp = ins.first->second;
6134 else
6136 smtp = new Struct_method_table_pair();
6137 smtp->first = NULL;
6138 smtp->second = NULL;
6139 ins.first->second = smtp;
6142 return Type::interface_method_table(this, interface, is_pointer,
6143 &smtp->first, &smtp->second);
6146 // Convert struct fields to the backend representation. This is not
6147 // declared in types.h so that types.h doesn't have to #include
6148 // backend.h.
6150 static void
6151 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6152 bool use_placeholder,
6153 std::vector<Backend::Btyped_identifier>* bfields)
6155 bfields->resize(fields->size());
6156 size_t i = 0;
6157 for (Struct_field_list::const_iterator p = fields->begin();
6158 p != fields->end();
6159 ++p, ++i)
6161 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6162 (*bfields)[i].btype = (use_placeholder
6163 ? p->type()->get_backend_placeholder(gogo)
6164 : p->type()->get_backend(gogo));
6165 (*bfields)[i].location = p->location();
6167 go_assert(i == fields->size());
6170 // Get the backend representation for a struct type.
6172 Btype*
6173 Struct_type::do_get_backend(Gogo* gogo)
6175 std::vector<Backend::Btyped_identifier> bfields;
6176 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6177 return gogo->backend()->struct_type(bfields);
6180 // Finish the backend representation of the fields of a struct.
6182 void
6183 Struct_type::finish_backend_fields(Gogo* gogo)
6185 const Struct_field_list* fields = this->fields_;
6186 if (fields != NULL)
6188 for (Struct_field_list::const_iterator p = fields->begin();
6189 p != fields->end();
6190 ++p)
6191 p->type()->get_backend(gogo);
6195 // The type of a struct type descriptor.
6197 Type*
6198 Struct_type::make_struct_type_descriptor_type()
6200 static Type* ret;
6201 if (ret == NULL)
6203 Type* tdt = Type::make_type_descriptor_type();
6204 Type* ptdt = Type::make_type_descriptor_ptr_type();
6206 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6207 Type* string_type = Type::lookup_string_type();
6208 Type* pointer_string_type = Type::make_pointer_type(string_type);
6210 Struct_type* sf =
6211 Type::make_builtin_struct_type(5,
6212 "name", pointer_string_type,
6213 "pkgPath", pointer_string_type,
6214 "typ", ptdt,
6215 "tag", pointer_string_type,
6216 "offsetAnon", uintptr_type);
6217 Type* nsf = Type::make_builtin_named_type("structField", sf);
6219 Type* slice_type = Type::make_array_type(nsf, NULL);
6221 Struct_type* s = Type::make_builtin_struct_type(2,
6222 "", tdt,
6223 "fields", slice_type);
6225 ret = Type::make_builtin_named_type("StructType", s);
6228 return ret;
6231 // Build a type descriptor for a struct type.
6233 Expression*
6234 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6236 Location bloc = Linemap::predeclared_location();
6238 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6240 const Struct_field_list* fields = stdt->struct_type()->fields();
6242 Expression_list* vals = new Expression_list();
6243 vals->reserve(2);
6245 const Methods* methods = this->methods();
6246 // A named struct should not have methods--the methods should attach
6247 // to the named type.
6248 go_assert(methods == NULL || name == NULL);
6250 Struct_field_list::const_iterator ps = fields->begin();
6251 go_assert(ps->is_field_name("_type"));
6252 vals->push_back(this->type_descriptor_constructor(gogo,
6253 RUNTIME_TYPE_KIND_STRUCT,
6254 name, methods, true));
6256 ++ps;
6257 go_assert(ps->is_field_name("fields"));
6259 Expression_list* elements = new Expression_list();
6260 elements->reserve(this->fields_->size());
6261 Type* element_type = ps->type()->array_type()->element_type();
6262 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6263 pf != this->fields_->end();
6264 ++pf)
6266 const Struct_field_list* f = element_type->struct_type()->fields();
6268 Expression_list* fvals = new Expression_list();
6269 fvals->reserve(5);
6271 Struct_field_list::const_iterator q = f->begin();
6272 go_assert(q->is_field_name("name"));
6273 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6274 Expression* s = Expression::make_string(n, bloc);
6275 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6277 ++q;
6278 go_assert(q->is_field_name("pkgPath"));
6279 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6280 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6281 fvals->push_back(Expression::make_nil(bloc));
6282 else
6284 std::string n;
6285 if (is_embedded_builtin)
6286 n = gogo->package_name();
6287 else
6288 n = Gogo::hidden_name_pkgpath(pf->field_name());
6289 Expression* s = Expression::make_string(n, bloc);
6290 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6293 ++q;
6294 go_assert(q->is_field_name("typ"));
6295 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6297 ++q;
6298 go_assert(q->is_field_name("tag"));
6299 if (!pf->has_tag())
6300 fvals->push_back(Expression::make_nil(bloc));
6301 else
6303 Expression* s = Expression::make_string(pf->tag(), bloc);
6304 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6307 ++q;
6308 go_assert(q->is_field_name("offsetAnon"));
6309 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6310 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6311 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6312 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6313 int av = pf->is_anonymous() ? 1 : 0;
6314 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6315 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6316 fvals->push_back(o);
6318 Expression* v = Expression::make_struct_composite_literal(element_type,
6319 fvals, bloc);
6320 elements->push_back(v);
6323 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6324 elements, bloc));
6326 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6329 // Write the hash function for a struct which can not use the identity
6330 // function.
6332 void
6333 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6334 Function_type* hash_fntype,
6335 Function_type* equal_fntype)
6337 Location bloc = Linemap::predeclared_location();
6339 // The pointer to the struct that we are going to hash. This is an
6340 // argument to the hash function we are implementing here.
6341 Named_object* key_arg = gogo->lookup("key", NULL);
6342 go_assert(key_arg != NULL);
6343 Type* key_arg_type = key_arg->var_value()->type();
6345 // The seed argument to the hash function.
6346 Named_object* seed_arg = gogo->lookup("seed", NULL);
6347 go_assert(seed_arg != NULL);
6349 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6351 // Make a temporary to hold the return value, initialized to the seed.
6352 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6353 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6354 bloc);
6355 gogo->add_statement(retval);
6357 // Make a temporary to hold the key as a uintptr.
6358 ref = Expression::make_var_reference(key_arg, bloc);
6359 ref = Expression::make_cast(uintptr_type, ref, bloc);
6360 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6361 bloc);
6362 gogo->add_statement(key);
6364 // Loop over the struct fields.
6365 const Struct_field_list* fields = this->fields_;
6366 for (Struct_field_list::const_iterator pf = fields->begin();
6367 pf != fields->end();
6368 ++pf)
6370 if (Gogo::is_sink_name(pf->field_name()))
6371 continue;
6373 // Get a pointer to the value of this field.
6374 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6375 ref = Expression::make_temporary_reference(key, bloc);
6376 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6377 bloc);
6378 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6380 // Get the hash function to use for the type of this field.
6381 Named_object* hash_fn;
6382 Named_object* equal_fn;
6383 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6384 equal_fntype, &hash_fn, &equal_fn);
6386 // Call the hash function for the field, passing retval as the seed.
6387 ref = Expression::make_temporary_reference(retval, bloc);
6388 Expression_list* args = new Expression_list();
6389 args->push_back(subkey);
6390 args->push_back(ref);
6391 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6392 Expression* call = Expression::make_call(func, args, false, bloc);
6394 // Set retval to the result.
6395 Temporary_reference_expression* tref =
6396 Expression::make_temporary_reference(retval, bloc);
6397 tref->set_is_lvalue();
6398 Statement* s = Statement::make_assignment(tref, call, bloc);
6399 gogo->add_statement(s);
6402 // Return retval to the caller of the hash function.
6403 Expression_list* vals = new Expression_list();
6404 ref = Expression::make_temporary_reference(retval, bloc);
6405 vals->push_back(ref);
6406 Statement* s = Statement::make_return_statement(vals, bloc);
6407 gogo->add_statement(s);
6410 // Write the equality function for a struct which can not use the
6411 // identity function.
6413 void
6414 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6416 Location bloc = Linemap::predeclared_location();
6418 // The pointers to the structs we are going to compare.
6419 Named_object* key1_arg = gogo->lookup("key1", NULL);
6420 Named_object* key2_arg = gogo->lookup("key2", NULL);
6421 go_assert(key1_arg != NULL && key2_arg != NULL);
6423 // Build temporaries with the right types.
6424 Type* pt = Type::make_pointer_type(name != NULL
6425 ? static_cast<Type*>(name)
6426 : static_cast<Type*>(this));
6428 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6429 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6430 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6431 gogo->add_statement(p1);
6433 ref = Expression::make_var_reference(key2_arg, bloc);
6434 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6435 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6436 gogo->add_statement(p2);
6438 const Struct_field_list* fields = this->fields_;
6439 unsigned int field_index = 0;
6440 for (Struct_field_list::const_iterator pf = fields->begin();
6441 pf != fields->end();
6442 ++pf, ++field_index)
6444 if (Gogo::is_sink_name(pf->field_name()))
6445 continue;
6447 // Compare one field in both P1 and P2.
6448 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6449 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6450 bloc);
6451 f1 = Expression::make_field_reference(f1, field_index, bloc);
6453 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6454 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6455 bloc);
6456 f2 = Expression::make_field_reference(f2, field_index, bloc);
6458 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6460 // If the values are not equal, return false.
6461 gogo->start_block(bloc);
6462 Expression_list* vals = new Expression_list();
6463 vals->push_back(Expression::make_boolean(false, bloc));
6464 Statement* s = Statement::make_return_statement(vals, bloc);
6465 gogo->add_statement(s);
6466 Block* then_block = gogo->finish_block(bloc);
6468 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6469 gogo->add_statement(s);
6472 // All the fields are equal, so return true.
6473 Expression_list* vals = new Expression_list();
6474 vals->push_back(Expression::make_boolean(true, bloc));
6475 Statement* s = Statement::make_return_statement(vals, bloc);
6476 gogo->add_statement(s);
6479 // Reflection string.
6481 void
6482 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6484 ret->append("struct {");
6486 for (Struct_field_list::const_iterator p = this->fields_->begin();
6487 p != this->fields_->end();
6488 ++p)
6490 if (p != this->fields_->begin())
6491 ret->push_back(';');
6492 ret->push_back(' ');
6493 if (!p->is_anonymous())
6495 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6496 ret->push_back(' ');
6498 if (p->is_anonymous()
6499 && p->type()->named_type() != NULL
6500 && p->type()->named_type()->is_alias())
6501 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6502 else
6503 this->append_reflection(p->type(), gogo, ret);
6505 if (p->has_tag())
6507 const std::string& tag(p->tag());
6508 ret->append(" \"");
6509 for (std::string::const_iterator p = tag.begin();
6510 p != tag.end();
6511 ++p)
6513 if (*p == '\0')
6514 ret->append("\\x00");
6515 else if (*p == '\n')
6516 ret->append("\\n");
6517 else if (*p == '\t')
6518 ret->append("\\t");
6519 else if (*p == '"')
6520 ret->append("\\\"");
6521 else if (*p == '\\')
6522 ret->append("\\\\");
6523 else
6524 ret->push_back(*p);
6526 ret->push_back('"');
6530 if (!this->fields_->empty())
6531 ret->push_back(' ');
6533 ret->push_back('}');
6536 // If the offset of field INDEX in the backend implementation can be
6537 // determined, set *POFFSET to the offset in bytes and return true.
6538 // Otherwise, return false.
6540 bool
6541 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6542 int64_t* poffset)
6544 if (!this->is_backend_type_size_known(gogo))
6545 return false;
6546 Btype* bt = this->get_backend_placeholder(gogo);
6547 *poffset = gogo->backend()->type_field_offset(bt, index);
6548 return true;
6551 // Export.
6553 void
6554 Struct_type::do_export(Export* exp) const
6556 exp->write_c_string("struct { ");
6557 const Struct_field_list* fields = this->fields_;
6558 go_assert(fields != NULL);
6559 for (Struct_field_list::const_iterator p = fields->begin();
6560 p != fields->end();
6561 ++p)
6563 if (p->is_anonymous())
6564 exp->write_string("? ");
6565 else
6567 exp->write_string(p->field_name());
6568 exp->write_c_string(" ");
6570 exp->write_type(p->type());
6572 if (p->has_tag())
6574 exp->write_c_string(" ");
6575 Expression* expr =
6576 Expression::make_string(p->tag(), Linemap::predeclared_location());
6577 expr->export_expression(exp);
6578 delete expr;
6581 exp->write_c_string("; ");
6583 exp->write_c_string("}");
6586 // Import.
6588 Struct_type*
6589 Struct_type::do_import(Import* imp)
6591 imp->require_c_string("struct { ");
6592 Struct_field_list* fields = new Struct_field_list;
6593 if (imp->peek_char() != '}')
6595 while (true)
6597 std::string name;
6598 if (imp->match_c_string("? "))
6599 imp->advance(2);
6600 else
6602 name = imp->read_identifier();
6603 imp->require_c_string(" ");
6605 Type* ftype = imp->read_type();
6607 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6608 sf.set_is_imported();
6610 if (imp->peek_char() == ' ')
6612 imp->advance(1);
6613 Expression* expr = Expression::import_expression(imp);
6614 String_expression* sexpr = expr->string_expression();
6615 go_assert(sexpr != NULL);
6616 sf.set_tag(sexpr->val());
6617 delete sexpr;
6620 imp->require_c_string("; ");
6621 fields->push_back(sf);
6622 if (imp->peek_char() == '}')
6623 break;
6626 imp->require_c_string("}");
6628 return Type::make_struct_type(fields, imp->location());
6631 // Whether we can write this struct type to a C header file.
6632 // We can't if any of the fields are structs defined in a different package.
6634 bool
6635 Struct_type::can_write_to_c_header(
6636 std::vector<const Named_object*>* requires,
6637 std::vector<const Named_object*>* declare) const
6639 const Struct_field_list* fields = this->fields_;
6640 if (fields == NULL || fields->empty())
6641 return false;
6642 int sinks = 0;
6643 for (Struct_field_list::const_iterator p = fields->begin();
6644 p != fields->end();
6645 ++p)
6647 if (p->is_anonymous())
6648 return false;
6649 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6650 return false;
6651 if (Gogo::message_name(p->field_name()) == "_")
6652 sinks++;
6654 if (sinks > 1)
6655 return false;
6656 return true;
6659 // Whether we can write the type T to a C header file.
6661 bool
6662 Struct_type::can_write_type_to_c_header(
6663 const Type* t,
6664 std::vector<const Named_object*>* requires,
6665 std::vector<const Named_object*>* declare) const
6667 t = t->forwarded();
6668 switch (t->classification())
6670 case TYPE_ERROR:
6671 case TYPE_FORWARD:
6672 return false;
6674 case TYPE_VOID:
6675 case TYPE_BOOLEAN:
6676 case TYPE_INTEGER:
6677 case TYPE_FLOAT:
6678 case TYPE_COMPLEX:
6679 case TYPE_STRING:
6680 case TYPE_FUNCTION:
6681 case TYPE_MAP:
6682 case TYPE_CHANNEL:
6683 case TYPE_INTERFACE:
6684 return true;
6686 case TYPE_POINTER:
6687 // Don't try to handle a pointer to an array.
6688 if (t->points_to()->array_type() != NULL
6689 && !t->points_to()->is_slice_type())
6690 return false;
6692 if (t->points_to()->named_type() != NULL
6693 && t->points_to()->struct_type() != NULL)
6694 declare->push_back(t->points_to()->named_type()->named_object());
6695 return true;
6697 case TYPE_STRUCT:
6698 return t->struct_type()->can_write_to_c_header(requires, declare);
6700 case TYPE_ARRAY:
6701 if (t->is_slice_type())
6702 return true;
6703 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6704 requires, declare);
6706 case TYPE_NAMED:
6708 const Named_object* no = t->named_type()->named_object();
6709 if (no->package() != NULL)
6711 if (t->is_unsafe_pointer_type())
6712 return true;
6713 return false;
6715 if (t->struct_type() != NULL)
6717 requires->push_back(no);
6718 return t->struct_type()->can_write_to_c_header(requires, declare);
6720 return this->can_write_type_to_c_header(t->base(), requires, declare);
6723 case TYPE_CALL_MULTIPLE_RESULT:
6724 case TYPE_NIL:
6725 case TYPE_SINK:
6726 default:
6727 go_unreachable();
6731 // Write this struct to a C header file.
6733 void
6734 Struct_type::write_to_c_header(std::ostream& os) const
6736 const Struct_field_list* fields = this->fields_;
6737 for (Struct_field_list::const_iterator p = fields->begin();
6738 p != fields->end();
6739 ++p)
6741 os << '\t';
6742 this->write_field_to_c_header(os, p->field_name(), p->type());
6743 os << ';' << std::endl;
6747 // Write the type of a struct field to a C header file.
6749 void
6750 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6751 const Type *t) const
6753 bool print_name = true;
6754 t = t->forwarded();
6755 switch (t->classification())
6757 case TYPE_VOID:
6758 os << "void";
6759 break;
6761 case TYPE_BOOLEAN:
6762 os << "_Bool";
6763 break;
6765 case TYPE_INTEGER:
6767 const Integer_type* it = t->integer_type();
6768 if (it->is_unsigned())
6769 os << 'u';
6770 os << "int" << it->bits() << "_t";
6772 break;
6774 case TYPE_FLOAT:
6775 switch (t->float_type()->bits())
6777 case 32:
6778 os << "float";
6779 break;
6780 case 64:
6781 os << "double";
6782 break;
6783 default:
6784 go_unreachable();
6786 break;
6788 case TYPE_COMPLEX:
6789 switch (t->complex_type()->bits())
6791 case 64:
6792 os << "float _Complex";
6793 break;
6794 case 128:
6795 os << "double _Complex";
6796 break;
6797 default:
6798 go_unreachable();
6800 break;
6802 case TYPE_STRING:
6803 os << "String";
6804 break;
6806 case TYPE_FUNCTION:
6807 os << "FuncVal*";
6808 break;
6810 case TYPE_POINTER:
6812 std::vector<const Named_object*> requires;
6813 std::vector<const Named_object*> declare;
6814 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
6815 &declare))
6816 os << "void*";
6817 else
6819 this->write_field_to_c_header(os, "", t->points_to());
6820 os << '*';
6823 break;
6825 case TYPE_MAP:
6826 os << "Map*";
6827 break;
6829 case TYPE_CHANNEL:
6830 os << "Chan*";
6831 break;
6833 case TYPE_INTERFACE:
6834 if (t->interface_type()->is_empty())
6835 os << "Eface";
6836 else
6837 os << "Iface";
6838 break;
6840 case TYPE_STRUCT:
6841 os << "struct {" << std::endl;
6842 t->struct_type()->write_to_c_header(os);
6843 os << "\t}";
6844 break;
6846 case TYPE_ARRAY:
6847 if (t->is_slice_type())
6848 os << "Slice";
6849 else
6851 const Type *ele = t;
6852 std::vector<const Type*> array_types;
6853 while (ele->array_type() != NULL && !ele->is_slice_type())
6855 array_types.push_back(ele);
6856 ele = ele->array_type()->element_type();
6858 this->write_field_to_c_header(os, "", ele);
6859 os << ' ' << Gogo::message_name(name);
6860 print_name = false;
6861 while (!array_types.empty())
6863 ele = array_types.back();
6864 array_types.pop_back();
6865 os << '[';
6866 Numeric_constant nc;
6867 if (!ele->array_type()->length()->numeric_constant_value(&nc))
6868 go_unreachable();
6869 mpz_t val;
6870 if (!nc.to_int(&val))
6871 go_unreachable();
6872 char* s = mpz_get_str(NULL, 10, val);
6873 os << s;
6874 free(s);
6875 mpz_clear(val);
6876 os << ']';
6879 break;
6881 case TYPE_NAMED:
6883 const Named_object* no = t->named_type()->named_object();
6884 if (t->struct_type() != NULL)
6885 os << "struct " << no->message_name();
6886 else if (t->is_unsafe_pointer_type())
6887 os << "void*";
6888 else if (t == Type::lookup_integer_type("uintptr"))
6889 os << "uintptr_t";
6890 else
6892 this->write_field_to_c_header(os, name, t->base());
6893 print_name = false;
6896 break;
6898 case TYPE_ERROR:
6899 case TYPE_FORWARD:
6900 case TYPE_CALL_MULTIPLE_RESULT:
6901 case TYPE_NIL:
6902 case TYPE_SINK:
6903 default:
6904 go_unreachable();
6907 if (print_name && !name.empty())
6908 os << ' ' << Gogo::message_name(name);
6911 // Make a struct type.
6913 Struct_type*
6914 Type::make_struct_type(Struct_field_list* fields,
6915 Location location)
6917 return new Struct_type(fields, location);
6920 // Class Array_type.
6922 // Store the length of an array as an int64_t into *PLEN. Return
6923 // false if the length can not be determined. This will assert if
6924 // called for a slice.
6926 bool
6927 Array_type::int_length(int64_t* plen)
6929 go_assert(this->length_ != NULL);
6930 Numeric_constant nc;
6931 if (!this->length_->numeric_constant_value(&nc))
6932 return false;
6933 return nc.to_memory_size(plen);
6936 // Whether two array types are identical.
6938 bool
6939 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
6940 bool errors_are_identical) const
6942 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
6943 cmp_tags, errors_are_identical, NULL))
6944 return false;
6946 if (this->is_array_incomparable_ != t->is_array_incomparable_)
6947 return false;
6949 Expression* l1 = this->length();
6950 Expression* l2 = t->length();
6952 // Slices of the same element type are identical.
6953 if (l1 == NULL && l2 == NULL)
6954 return true;
6956 // Arrays of the same element type are identical if they have the
6957 // same length.
6958 if (l1 != NULL && l2 != NULL)
6960 if (l1 == l2)
6961 return true;
6963 // Try to determine the lengths. If we can't, assume the arrays
6964 // are not identical.
6965 bool ret = false;
6966 Numeric_constant nc1, nc2;
6967 if (l1->numeric_constant_value(&nc1)
6968 && l2->numeric_constant_value(&nc2))
6970 mpz_t v1;
6971 if (nc1.to_int(&v1))
6973 mpz_t v2;
6974 if (nc2.to_int(&v2))
6976 ret = mpz_cmp(v1, v2) == 0;
6977 mpz_clear(v2);
6979 mpz_clear(v1);
6982 return ret;
6985 // Otherwise the arrays are not identical.
6986 return false;
6989 // Traversal.
6992 Array_type::do_traverse(Traverse* traverse)
6994 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
6995 return TRAVERSE_EXIT;
6996 if (this->length_ != NULL
6997 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
6998 return TRAVERSE_EXIT;
6999 return TRAVERSE_CONTINUE;
7002 // Check that the length is valid.
7004 bool
7005 Array_type::verify_length()
7007 if (this->length_ == NULL)
7008 return true;
7010 Type_context context(Type::lookup_integer_type("int"), false);
7011 this->length_->determine_type(&context);
7013 if (!this->length_->is_constant())
7015 go_error_at(this->length_->location(), "array bound is not constant");
7016 return false;
7019 Numeric_constant nc;
7020 if (!this->length_->numeric_constant_value(&nc))
7022 if (this->length_->type()->integer_type() != NULL
7023 || this->length_->type()->float_type() != NULL)
7024 go_error_at(this->length_->location(), "array bound is not constant");
7025 else
7026 go_error_at(this->length_->location(), "array bound is not numeric");
7027 return false;
7030 Type* int_type = Type::lookup_integer_type("int");
7031 unsigned int tbits = int_type->integer_type()->bits();
7032 unsigned long val;
7033 switch (nc.to_unsigned_long(&val))
7035 case Numeric_constant::NC_UL_VALID:
7036 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7038 go_error_at(this->length_->location(), "array bound overflows");
7039 return false;
7041 break;
7042 case Numeric_constant::NC_UL_NOTINT:
7043 go_error_at(this->length_->location(), "array bound truncated to integer");
7044 return false;
7045 case Numeric_constant::NC_UL_NEGATIVE:
7046 go_error_at(this->length_->location(), "negative array bound");
7047 return false;
7048 case Numeric_constant::NC_UL_BIG:
7050 mpz_t val;
7051 if (!nc.to_int(&val))
7052 go_unreachable();
7053 unsigned int bits = mpz_sizeinbase(val, 2);
7054 mpz_clear(val);
7055 if (bits >= tbits)
7057 go_error_at(this->length_->location(), "array bound overflows");
7058 return false;
7061 break;
7062 default:
7063 go_unreachable();
7066 return true;
7069 // Verify the type.
7071 bool
7072 Array_type::do_verify()
7074 if (this->element_type()->is_error_type())
7075 return false;
7076 if (!this->verify_length())
7077 this->length_ = Expression::make_error(this->length_->location());
7078 return true;
7081 // Whether the type contains pointers. This is always true for a
7082 // slice. For an array it is true if the element type has pointers
7083 // and the length is greater than zero.
7085 bool
7086 Array_type::do_has_pointer() const
7088 if (this->length_ == NULL)
7089 return true;
7090 if (!this->element_type_->has_pointer())
7091 return false;
7093 Numeric_constant nc;
7094 if (!this->length_->numeric_constant_value(&nc))
7096 // Error reported elsewhere.
7097 return false;
7100 unsigned long val;
7101 switch (nc.to_unsigned_long(&val))
7103 case Numeric_constant::NC_UL_VALID:
7104 return val > 0;
7105 case Numeric_constant::NC_UL_BIG:
7106 return true;
7107 default:
7108 // Error reported elsewhere.
7109 return false;
7113 // Whether we can use memcmp to compare this array.
7115 bool
7116 Array_type::do_compare_is_identity(Gogo* gogo)
7118 if (this->length_ == NULL)
7119 return false;
7121 // Check for [...], which indicates that this is not a real type.
7122 if (this->length_->is_nil_expression())
7123 return false;
7125 if (!this->element_type_->compare_is_identity(gogo))
7126 return false;
7128 // If there is any padding, then we can't use memcmp.
7129 int64_t size;
7130 int64_t align;
7131 if (!this->element_type_->backend_type_size(gogo, &size)
7132 || !this->element_type_->backend_type_align(gogo, &align))
7133 return false;
7134 if ((size & (align - 1)) != 0)
7135 return false;
7137 return true;
7140 // Array type hash code.
7142 unsigned int
7143 Array_type::do_hash_for_method(Gogo* gogo) const
7145 unsigned int ret;
7147 // There is no very convenient way to get a hash code for the
7148 // length.
7149 ret = this->element_type_->hash_for_method(gogo) + 1;
7150 if (this->is_array_incomparable_)
7151 ret <<= 1;
7152 return ret;
7155 // Write the hash function for an array which can not use the identify
7156 // function.
7158 void
7159 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7160 Function_type* hash_fntype,
7161 Function_type* equal_fntype)
7163 Location bloc = Linemap::predeclared_location();
7165 // The pointer to the array that we are going to hash. This is an
7166 // argument to the hash function we are implementing here.
7167 Named_object* key_arg = gogo->lookup("key", NULL);
7168 go_assert(key_arg != NULL);
7169 Type* key_arg_type = key_arg->var_value()->type();
7171 // The seed argument to the hash function.
7172 Named_object* seed_arg = gogo->lookup("seed", NULL);
7173 go_assert(seed_arg != NULL);
7175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7177 // Make a temporary to hold the return value, initialized to the seed.
7178 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7179 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7180 bloc);
7181 gogo->add_statement(retval);
7183 // Make a temporary to hold the key as a uintptr.
7184 ref = Expression::make_var_reference(key_arg, bloc);
7185 ref = Expression::make_cast(uintptr_type, ref, bloc);
7186 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7187 bloc);
7188 gogo->add_statement(key);
7190 // Loop over the array elements.
7191 // for i = range a
7192 Type* int_type = Type::lookup_integer_type("int");
7193 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7194 gogo->add_statement(index);
7196 Expression* iref = Expression::make_temporary_reference(index, bloc);
7197 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7198 Type* pt = Type::make_pointer_type(name != NULL
7199 ? static_cast<Type*>(name)
7200 : static_cast<Type*>(this));
7201 aref = Expression::make_cast(pt, aref, bloc);
7202 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7203 NULL,
7204 aref,
7205 bloc);
7207 gogo->start_block(bloc);
7209 // Get the hash function for the element type.
7210 Named_object* hash_fn;
7211 Named_object* equal_fn;
7212 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7213 hash_fntype, equal_fntype, &hash_fn,
7214 &equal_fn);
7216 // Get a pointer to this element in the loop.
7217 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7218 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7220 // Get the size of each element.
7221 Expression* ele_size = Expression::make_type_info(this->element_type_,
7222 Expression::TYPE_INFO_SIZE);
7224 // Get the hash of this element, passing retval as the seed.
7225 ref = Expression::make_temporary_reference(retval, bloc);
7226 Expression_list* args = new Expression_list();
7227 args->push_back(subkey);
7228 args->push_back(ref);
7229 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7230 Expression* call = Expression::make_call(func, args, false, bloc);
7232 // Set retval to the result.
7233 Temporary_reference_expression* tref =
7234 Expression::make_temporary_reference(retval, bloc);
7235 tref->set_is_lvalue();
7236 Statement* s = Statement::make_assignment(tref, call, bloc);
7237 gogo->add_statement(s);
7239 // Increase the element pointer.
7240 tref = Expression::make_temporary_reference(key, bloc);
7241 tref->set_is_lvalue();
7242 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7243 bloc);
7244 Block* statements = gogo->finish_block(bloc);
7246 for_range->add_statements(statements);
7247 gogo->add_statement(for_range);
7249 // Return retval to the caller of the hash function.
7250 Expression_list* vals = new Expression_list();
7251 ref = Expression::make_temporary_reference(retval, bloc);
7252 vals->push_back(ref);
7253 s = Statement::make_return_statement(vals, bloc);
7254 gogo->add_statement(s);
7257 // Write the equality function for an array which can not use the
7258 // identity function.
7260 void
7261 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7263 Location bloc = Linemap::predeclared_location();
7265 // The pointers to the arrays we are going to compare.
7266 Named_object* key1_arg = gogo->lookup("key1", NULL);
7267 Named_object* key2_arg = gogo->lookup("key2", NULL);
7268 go_assert(key1_arg != NULL && key2_arg != NULL);
7270 // Build temporaries for the keys with the right types.
7271 Type* pt = Type::make_pointer_type(name != NULL
7272 ? static_cast<Type*>(name)
7273 : static_cast<Type*>(this));
7275 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7276 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7277 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7278 gogo->add_statement(p1);
7280 ref = Expression::make_var_reference(key2_arg, bloc);
7281 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7282 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7283 gogo->add_statement(p2);
7285 // Loop over the array elements.
7286 // for i = range a
7287 Type* int_type = Type::lookup_integer_type("int");
7288 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7289 gogo->add_statement(index);
7291 Expression* iref = Expression::make_temporary_reference(index, bloc);
7292 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7293 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7294 NULL,
7295 aref,
7296 bloc);
7298 gogo->start_block(bloc);
7300 // Compare element in P1 and P2.
7301 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7302 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7303 ref = Expression::make_temporary_reference(index, bloc);
7304 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7306 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7307 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7308 ref = Expression::make_temporary_reference(index, bloc);
7309 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7311 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7313 // If the elements are not equal, return false.
7314 gogo->start_block(bloc);
7315 Expression_list* vals = new Expression_list();
7316 vals->push_back(Expression::make_boolean(false, bloc));
7317 Statement* s = Statement::make_return_statement(vals, bloc);
7318 gogo->add_statement(s);
7319 Block* then_block = gogo->finish_block(bloc);
7321 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7322 gogo->add_statement(s);
7324 Block* statements = gogo->finish_block(bloc);
7326 for_range->add_statements(statements);
7327 gogo->add_statement(for_range);
7329 // All the elements are equal, so return true.
7330 vals = new Expression_list();
7331 vals->push_back(Expression::make_boolean(true, bloc));
7332 s = Statement::make_return_statement(vals, bloc);
7333 gogo->add_statement(s);
7336 // Get the backend representation of the fields of a slice. This is
7337 // not declared in types.h so that types.h doesn't have to #include
7338 // backend.h.
7340 // We use int for the count and capacity fields. This matches 6g.
7341 // The language more or less assumes that we can't allocate space of a
7342 // size which does not fit in int.
7344 static void
7345 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7346 std::vector<Backend::Btyped_identifier>* bfields)
7348 bfields->resize(3);
7350 Type* pet = Type::make_pointer_type(type->element_type());
7351 Btype* pbet = (use_placeholder
7352 ? pet->get_backend_placeholder(gogo)
7353 : pet->get_backend(gogo));
7354 Location ploc = Linemap::predeclared_location();
7356 Backend::Btyped_identifier* p = &(*bfields)[0];
7357 p->name = "__values";
7358 p->btype = pbet;
7359 p->location = ploc;
7361 Type* int_type = Type::lookup_integer_type("int");
7363 p = &(*bfields)[1];
7364 p->name = "__count";
7365 p->btype = int_type->get_backend(gogo);
7366 p->location = ploc;
7368 p = &(*bfields)[2];
7369 p->name = "__capacity";
7370 p->btype = int_type->get_backend(gogo);
7371 p->location = ploc;
7374 // Get the backend representation for the type of this array. A fixed array is
7375 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7376 // just like an array in C. An open array is a struct with three
7377 // fields: a data pointer, the length, and the capacity.
7379 Btype*
7380 Array_type::do_get_backend(Gogo* gogo)
7382 if (this->length_ == NULL)
7384 std::vector<Backend::Btyped_identifier> bfields;
7385 get_backend_slice_fields(gogo, this, false, &bfields);
7386 return gogo->backend()->struct_type(bfields);
7388 else
7390 Btype* element = this->get_backend_element(gogo, false);
7391 Bexpression* len = this->get_backend_length(gogo);
7392 return gogo->backend()->array_type(element, len);
7396 // Return the backend representation of the element type.
7398 Btype*
7399 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7401 if (use_placeholder)
7402 return this->element_type_->get_backend_placeholder(gogo);
7403 else
7404 return this->element_type_->get_backend(gogo);
7407 // Return the backend representation of the length. The length may be
7408 // computed using a function call, so we must only evaluate it once.
7410 Bexpression*
7411 Array_type::get_backend_length(Gogo* gogo)
7413 go_assert(this->length_ != NULL);
7414 if (this->blength_ == NULL)
7416 if (this->length_->is_error_expression())
7418 this->blength_ = gogo->backend()->error_expression();
7419 return this->blength_;
7421 Numeric_constant nc;
7422 mpz_t val;
7423 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7425 if (mpz_sgn(val) < 0)
7427 this->blength_ = gogo->backend()->error_expression();
7428 return this->blength_;
7430 Type* t = nc.type();
7431 if (t == NULL)
7432 t = Type::lookup_integer_type("int");
7433 else if (t->is_abstract())
7434 t = t->make_non_abstract_type();
7435 Btype* btype = t->get_backend(gogo);
7436 this->blength_ =
7437 gogo->backend()->integer_constant_expression(btype, val);
7438 mpz_clear(val);
7440 else
7442 // Make up a translation context for the array length
7443 // expression. FIXME: This won't work in general.
7444 Translate_context context(gogo, NULL, NULL, NULL);
7445 this->blength_ = this->length_->get_backend(&context);
7447 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7448 this->blength_ =
7449 gogo->backend()->convert_expression(ibtype, this->blength_,
7450 this->length_->location());
7453 return this->blength_;
7456 // Finish backend representation of the array.
7458 void
7459 Array_type::finish_backend_element(Gogo* gogo)
7461 Type* et = this->array_type()->element_type();
7462 et->get_backend(gogo);
7463 if (this->is_slice_type())
7465 // This relies on the fact that we always use the same
7466 // structure for a pointer to any given type.
7467 Type* pet = Type::make_pointer_type(et);
7468 pet->get_backend(gogo);
7472 // Return an expression for a pointer to the values in ARRAY.
7474 Expression*
7475 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7477 if (this->length() != NULL)
7479 // Fixed array.
7480 go_assert(array->type()->array_type() != NULL);
7481 Type* etype = array->type()->array_type()->element_type();
7482 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7483 return Expression::make_cast(Type::make_pointer_type(etype), array,
7484 array->location());
7487 // Slice.
7489 if (is_lvalue)
7491 Temporary_reference_expression* tref =
7492 array->temporary_reference_expression();
7493 Var_expression* ve = array->var_expression();
7494 if (tref != NULL)
7496 tref = tref->copy()->temporary_reference_expression();
7497 tref->set_is_lvalue();
7498 array = tref;
7500 else if (ve != NULL)
7502 ve = new Var_expression(ve->named_object(), ve->location());
7503 array = ve;
7507 return Expression::make_slice_info(array,
7508 Expression::SLICE_INFO_VALUE_POINTER,
7509 array->location());
7512 // Return an expression for the length of the array ARRAY which has this
7513 // type.
7515 Expression*
7516 Array_type::get_length(Gogo*, Expression* array) const
7518 if (this->length_ != NULL)
7519 return this->length_;
7521 // This is a slice. We need to read the length field.
7522 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7523 array->location());
7526 // Return an expression for the capacity of the array ARRAY which has this
7527 // type.
7529 Expression*
7530 Array_type::get_capacity(Gogo*, Expression* array) const
7532 if (this->length_ != NULL)
7533 return this->length_;
7535 // This is a slice. We need to read the capacity field.
7536 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7537 array->location());
7540 // Export.
7542 void
7543 Array_type::do_export(Export* exp) const
7545 exp->write_c_string("[");
7546 if (this->length_ != NULL)
7547 this->length_->export_expression(exp);
7548 exp->write_c_string("] ");
7549 exp->write_type(this->element_type_);
7552 // Import.
7554 Array_type*
7555 Array_type::do_import(Import* imp)
7557 imp->require_c_string("[");
7558 Expression* length;
7559 if (imp->peek_char() == ']')
7560 length = NULL;
7561 else
7562 length = Expression::import_expression(imp);
7563 imp->require_c_string("] ");
7564 Type* element_type = imp->read_type();
7565 return Type::make_array_type(element_type, length);
7568 // The type of an array type descriptor.
7570 Type*
7571 Array_type::make_array_type_descriptor_type()
7573 static Type* ret;
7574 if (ret == NULL)
7576 Type* tdt = Type::make_type_descriptor_type();
7577 Type* ptdt = Type::make_type_descriptor_ptr_type();
7579 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7581 Struct_type* sf =
7582 Type::make_builtin_struct_type(4,
7583 "", tdt,
7584 "elem", ptdt,
7585 "slice", ptdt,
7586 "len", uintptr_type);
7588 ret = Type::make_builtin_named_type("ArrayType", sf);
7591 return ret;
7594 // The type of an slice type descriptor.
7596 Type*
7597 Array_type::make_slice_type_descriptor_type()
7599 static Type* ret;
7600 if (ret == NULL)
7602 Type* tdt = Type::make_type_descriptor_type();
7603 Type* ptdt = Type::make_type_descriptor_ptr_type();
7605 Struct_type* sf =
7606 Type::make_builtin_struct_type(2,
7607 "", tdt,
7608 "elem", ptdt);
7610 ret = Type::make_builtin_named_type("SliceType", sf);
7613 return ret;
7616 // Build a type descriptor for an array/slice type.
7618 Expression*
7619 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7621 if (this->length_ != NULL)
7622 return this->array_type_descriptor(gogo, name);
7623 else
7624 return this->slice_type_descriptor(gogo, name);
7627 // Build a type descriptor for an array type.
7629 Expression*
7630 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7632 Location bloc = Linemap::predeclared_location();
7634 Type* atdt = Array_type::make_array_type_descriptor_type();
7636 const Struct_field_list* fields = atdt->struct_type()->fields();
7638 Expression_list* vals = new Expression_list();
7639 vals->reserve(3);
7641 Struct_field_list::const_iterator p = fields->begin();
7642 go_assert(p->is_field_name("_type"));
7643 vals->push_back(this->type_descriptor_constructor(gogo,
7644 RUNTIME_TYPE_KIND_ARRAY,
7645 name, NULL, true));
7647 ++p;
7648 go_assert(p->is_field_name("elem"));
7649 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7651 ++p;
7652 go_assert(p->is_field_name("slice"));
7653 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7654 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7656 ++p;
7657 go_assert(p->is_field_name("len"));
7658 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7660 ++p;
7661 go_assert(p == fields->end());
7663 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7666 // Build a type descriptor for a slice type.
7668 Expression*
7669 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7671 Location bloc = Linemap::predeclared_location();
7673 Type* stdt = Array_type::make_slice_type_descriptor_type();
7675 const Struct_field_list* fields = stdt->struct_type()->fields();
7677 Expression_list* vals = new Expression_list();
7678 vals->reserve(2);
7680 Struct_field_list::const_iterator p = fields->begin();
7681 go_assert(p->is_field_name("_type"));
7682 vals->push_back(this->type_descriptor_constructor(gogo,
7683 RUNTIME_TYPE_KIND_SLICE,
7684 name, NULL, true));
7686 ++p;
7687 go_assert(p->is_field_name("elem"));
7688 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7690 ++p;
7691 go_assert(p == fields->end());
7693 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7696 // Reflection string.
7698 void
7699 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7701 ret->push_back('[');
7702 if (this->length_ != NULL)
7704 Numeric_constant nc;
7705 if (!this->length_->numeric_constant_value(&nc))
7707 go_assert(saw_errors());
7708 return;
7710 mpz_t val;
7711 if (!nc.to_int(&val))
7713 go_assert(saw_errors());
7714 return;
7716 char* s = mpz_get_str(NULL, 10, val);
7717 ret->append(s);
7718 free(s);
7719 mpz_clear(val);
7721 ret->push_back(']');
7723 this->append_reflection(this->element_type_, gogo, ret);
7726 // Make an array type.
7728 Array_type*
7729 Type::make_array_type(Type* element_type, Expression* length)
7731 return new Array_type(element_type, length);
7734 // Class Map_type.
7736 Named_object* Map_type::zero_value;
7737 int64_t Map_type::zero_value_size;
7738 int64_t Map_type::zero_value_align;
7740 // If this map requires the "fat" functions, return the pointer to
7741 // pass as the zero value to those functions. Otherwise, in the
7742 // normal case, return NULL. The map requires the "fat" functions if
7743 // the value size is larger than max_zero_size bytes. max_zero_size
7744 // must match maxZero in libgo/go/runtime/hashmap.go.
7746 Expression*
7747 Map_type::fat_zero_value(Gogo* gogo)
7749 int64_t valsize;
7750 if (!this->val_type_->backend_type_size(gogo, &valsize))
7752 go_assert(saw_errors());
7753 return NULL;
7755 if (valsize <= Map_type::max_zero_size)
7756 return NULL;
7758 if (Map_type::zero_value_size < valsize)
7759 Map_type::zero_value_size = valsize;
7761 int64_t valalign;
7762 if (!this->val_type_->backend_type_align(gogo, &valalign))
7764 go_assert(saw_errors());
7765 return NULL;
7768 if (Map_type::zero_value_align < valalign)
7769 Map_type::zero_value_align = valalign;
7771 Location bloc = Linemap::predeclared_location();
7773 if (Map_type::zero_value == NULL)
7775 // The final type will be set in backend_zero_value.
7776 Type* uint8_type = Type::lookup_integer_type("uint8");
7777 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7778 Array_type* array_type = Type::make_array_type(uint8_type, size);
7779 array_type->set_is_array_incomparable();
7780 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7781 std::string name = gogo->map_zero_value_name();
7782 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
7785 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7786 z = Expression::make_unary(OPERATOR_AND, z, bloc);
7787 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7788 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7789 return z;
7792 // Return whether VAR is the map zero value.
7794 bool
7795 Map_type::is_zero_value(Variable* var)
7797 return (Map_type::zero_value != NULL
7798 && Map_type::zero_value->var_value() == var);
7801 // Return the backend representation for the zero value.
7803 Bvariable*
7804 Map_type::backend_zero_value(Gogo* gogo)
7806 Location bloc = Linemap::predeclared_location();
7808 go_assert(Map_type::zero_value != NULL);
7810 Type* uint8_type = Type::lookup_integer_type("uint8");
7811 Btype* buint8_type = uint8_type->get_backend(gogo);
7813 Type* int_type = Type::lookup_integer_type("int");
7815 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7816 int_type, bloc);
7817 Translate_context context(gogo, NULL, NULL, NULL);
7818 Bexpression* blength = e->get_backend(&context);
7820 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7822 std::string zname = Map_type::zero_value->name();
7823 std::string asm_name(go_selectively_encode_id(zname));
7824 Bvariable* zvar =
7825 gogo->backend()->implicit_variable(zname, asm_name,
7826 barray_type, false, false, true,
7827 Map_type::zero_value_align);
7828 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7829 false, false, true, NULL);
7830 return zvar;
7833 // Traversal.
7836 Map_type::do_traverse(Traverse* traverse)
7838 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7839 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7840 return TRAVERSE_EXIT;
7841 return TRAVERSE_CONTINUE;
7844 // Check that the map type is OK.
7846 bool
7847 Map_type::do_verify()
7849 // The runtime support uses "map[void]void".
7850 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7851 go_error_at(this->location_, "invalid map key type");
7852 if (!this->key_type_->in_heap())
7853 go_error_at(this->location_, "go:notinheap map key not allowed");
7854 if (!this->val_type_->in_heap())
7855 go_error_at(this->location_, "go:notinheap map value not allowed");
7856 return true;
7859 // Whether two map types are identical.
7861 bool
7862 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
7863 bool errors_are_identical) const
7865 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
7866 cmp_tags, errors_are_identical, NULL)
7867 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
7868 cmp_tags, errors_are_identical,
7869 NULL));
7872 // Hash code.
7874 unsigned int
7875 Map_type::do_hash_for_method(Gogo* gogo) const
7877 return (this->key_type_->hash_for_method(gogo)
7878 + this->val_type_->hash_for_method(gogo)
7879 + 2);
7882 // Get the backend representation for a map type. A map type is
7883 // represented as a pointer to a struct. The struct is hmap in
7884 // runtime/hashmap.go.
7886 Btype*
7887 Map_type::do_get_backend(Gogo* gogo)
7889 static Btype* backend_map_type;
7890 if (backend_map_type == NULL)
7892 std::vector<Backend::Btyped_identifier> bfields(9);
7894 Location bloc = Linemap::predeclared_location();
7896 Type* int_type = Type::lookup_integer_type("int");
7897 bfields[0].name = "count";
7898 bfields[0].btype = int_type->get_backend(gogo);
7899 bfields[0].location = bloc;
7901 Type* uint8_type = Type::lookup_integer_type("uint8");
7902 bfields[1].name = "flags";
7903 bfields[1].btype = uint8_type->get_backend(gogo);
7904 bfields[1].location = bloc;
7906 bfields[2].name = "B";
7907 bfields[2].btype = bfields[1].btype;
7908 bfields[2].location = bloc;
7910 Type* uint16_type = Type::lookup_integer_type("uint16");
7911 bfields[3].name = "noverflow";
7912 bfields[3].btype = uint16_type->get_backend(gogo);
7913 bfields[3].location = bloc;
7915 Type* uint32_type = Type::lookup_integer_type("uint32");
7916 bfields[4].name = "hash0";
7917 bfields[4].btype = uint32_type->get_backend(gogo);
7918 bfields[4].location = bloc;
7920 Btype* bvt = gogo->backend()->void_type();
7921 Btype* bpvt = gogo->backend()->pointer_type(bvt);
7922 bfields[5].name = "buckets";
7923 bfields[5].btype = bpvt;
7924 bfields[5].location = bloc;
7926 bfields[6].name = "oldbuckets";
7927 bfields[6].btype = bpvt;
7928 bfields[6].location = bloc;
7930 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7931 bfields[7].name = "nevacuate";
7932 bfields[7].btype = uintptr_type->get_backend(gogo);
7933 bfields[7].location = bloc;
7935 bfields[8].name = "extra";
7936 bfields[8].btype = bpvt;
7937 bfields[8].location = bloc;
7939 Btype *bt = gogo->backend()->struct_type(bfields);
7940 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7941 backend_map_type = gogo->backend()->pointer_type(bt);
7943 return backend_map_type;
7946 // The type of a map type descriptor.
7948 Type*
7949 Map_type::make_map_type_descriptor_type()
7951 static Type* ret;
7952 if (ret == NULL)
7954 Type* tdt = Type::make_type_descriptor_type();
7955 Type* ptdt = Type::make_type_descriptor_ptr_type();
7956 Type* uint8_type = Type::lookup_integer_type("uint8");
7957 Type* uint16_type = Type::lookup_integer_type("uint16");
7958 Type* bool_type = Type::lookup_bool_type();
7960 Struct_type* sf =
7961 Type::make_builtin_struct_type(12,
7962 "", tdt,
7963 "key", ptdt,
7964 "elem", ptdt,
7965 "bucket", ptdt,
7966 "hmap", ptdt,
7967 "keysize", uint8_type,
7968 "indirectkey", bool_type,
7969 "valuesize", uint8_type,
7970 "indirectvalue", bool_type,
7971 "bucketsize", uint16_type,
7972 "reflexivekey", bool_type,
7973 "needkeyupdate", bool_type);
7975 ret = Type::make_builtin_named_type("MapType", sf);
7978 return ret;
7981 // Build a type descriptor for a map type.
7983 Expression*
7984 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7986 Location bloc = Linemap::predeclared_location();
7988 Type* mtdt = Map_type::make_map_type_descriptor_type();
7989 Type* uint8_type = Type::lookup_integer_type("uint8");
7990 Type* uint16_type = Type::lookup_integer_type("uint16");
7992 int64_t keysize;
7993 if (!this->key_type_->backend_type_size(gogo, &keysize))
7995 go_error_at(this->location_, "error determining map key type size");
7996 return Expression::make_error(this->location_);
7999 int64_t valsize;
8000 if (!this->val_type_->backend_type_size(gogo, &valsize))
8002 go_error_at(this->location_, "error determining map value type size");
8003 return Expression::make_error(this->location_);
8006 int64_t ptrsize;
8007 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8009 go_assert(saw_errors());
8010 return Expression::make_error(this->location_);
8013 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8014 if (bucket_type == NULL)
8016 go_assert(saw_errors());
8017 return Expression::make_error(this->location_);
8020 int64_t bucketsize;
8021 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8023 go_assert(saw_errors());
8024 return Expression::make_error(this->location_);
8027 const Struct_field_list* fields = mtdt->struct_type()->fields();
8029 Expression_list* vals = new Expression_list();
8030 vals->reserve(12);
8032 Struct_field_list::const_iterator p = fields->begin();
8033 go_assert(p->is_field_name("_type"));
8034 vals->push_back(this->type_descriptor_constructor(gogo,
8035 RUNTIME_TYPE_KIND_MAP,
8036 name, NULL, true));
8038 ++p;
8039 go_assert(p->is_field_name("key"));
8040 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8042 ++p;
8043 go_assert(p->is_field_name("elem"));
8044 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8046 ++p;
8047 go_assert(p->is_field_name("bucket"));
8048 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8050 ++p;
8051 go_assert(p->is_field_name("hmap"));
8052 Type* hmap_type = this->hmap_type(bucket_type);
8053 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
8055 ++p;
8056 go_assert(p->is_field_name("keysize"));
8057 if (keysize > Map_type::max_key_size)
8058 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8059 else
8060 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8062 ++p;
8063 go_assert(p->is_field_name("indirectkey"));
8064 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8065 bloc));
8067 ++p;
8068 go_assert(p->is_field_name("valuesize"));
8069 if (valsize > Map_type::max_val_size)
8070 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8071 else
8072 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8074 ++p;
8075 go_assert(p->is_field_name("indirectvalue"));
8076 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8077 bloc));
8079 ++p;
8080 go_assert(p->is_field_name("bucketsize"));
8081 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8082 bloc));
8084 ++p;
8085 go_assert(p->is_field_name("reflexivekey"));
8086 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8087 bloc));
8089 ++p;
8090 go_assert(p->is_field_name("needkeyupdate"));
8091 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8092 bloc));
8094 ++p;
8095 go_assert(p == fields->end());
8097 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8100 // Return the bucket type to use for a map type. This must correspond
8101 // to libgo/go/runtime/hashmap.go.
8103 Type*
8104 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8106 if (this->bucket_type_ != NULL)
8107 return this->bucket_type_;
8109 Type* key_type = this->key_type_;
8110 if (keysize > Map_type::max_key_size)
8111 key_type = Type::make_pointer_type(key_type);
8113 Type* val_type = this->val_type_;
8114 if (valsize > Map_type::max_val_size)
8115 val_type = Type::make_pointer_type(val_type);
8117 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8118 NULL, this->location_);
8120 Type* uint8_type = Type::lookup_integer_type("uint8");
8121 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8122 topbits_type->set_is_array_incomparable();
8123 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8124 keys_type->set_is_array_incomparable();
8125 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8126 values_type->set_is_array_incomparable();
8128 // If keys and values have no pointers, the map implementation can
8129 // keep a list of overflow pointers on the side so that buckets can
8130 // be marked as having no pointers. Arrange for the bucket to have
8131 // no pointers by changing the type of the overflow field to uintptr
8132 // in this case. See comment on the hmap.overflow field in
8133 // libgo/go/runtime/hashmap.go.
8134 Type* overflow_type;
8135 if (!key_type->has_pointer() && !val_type->has_pointer())
8136 overflow_type = Type::lookup_integer_type("uintptr");
8137 else
8139 // This should really be a pointer to the bucket type itself,
8140 // but that would require us to construct a Named_type for it to
8141 // give it a way to refer to itself. Since nothing really cares
8142 // (except perhaps for someone using a debugger) just use an
8143 // unsafe pointer.
8144 overflow_type = Type::make_pointer_type(Type::make_void_type());
8147 // Make sure the overflow pointer is the last memory in the struct,
8148 // because the runtime assumes it can use size-ptrSize as the offset
8149 // of the overflow pointer. We double-check that property below
8150 // once the offsets and size are computed.
8152 int64_t topbits_field_size, topbits_field_align;
8153 int64_t keys_field_size, keys_field_align;
8154 int64_t values_field_size, values_field_align;
8155 int64_t overflow_field_size, overflow_field_align;
8156 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8157 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8158 || !keys_type->backend_type_size(gogo, &keys_field_size)
8159 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8160 || !values_type->backend_type_size(gogo, &values_field_size)
8161 || !values_type->backend_type_field_align(gogo, &values_field_align)
8162 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8163 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8165 go_assert(saw_errors());
8166 return NULL;
8169 Struct_type* ret;
8170 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8171 values_field_align);
8172 if (max_align <= overflow_field_align)
8173 ret = make_builtin_struct_type(4,
8174 "topbits", topbits_type,
8175 "keys", keys_type,
8176 "values", values_type,
8177 "overflow", overflow_type);
8178 else
8180 size_t off = topbits_field_size;
8181 off = ((off + keys_field_align - 1)
8182 &~ static_cast<size_t>(keys_field_align - 1));
8183 off += keys_field_size;
8184 off = ((off + values_field_align - 1)
8185 &~ static_cast<size_t>(values_field_align - 1));
8186 off += values_field_size;
8188 int64_t padded_overflow_field_size =
8189 ((overflow_field_size + max_align - 1)
8190 &~ static_cast<size_t>(max_align - 1));
8192 size_t ovoff = off;
8193 ovoff = ((ovoff + max_align - 1)
8194 &~ static_cast<size_t>(max_align - 1));
8195 size_t pad = (ovoff - off
8196 + padded_overflow_field_size - overflow_field_size);
8198 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8199 this->location_);
8200 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8201 pad_type->set_is_array_incomparable();
8203 ret = make_builtin_struct_type(5,
8204 "topbits", topbits_type,
8205 "keys", keys_type,
8206 "values", values_type,
8207 "pad", pad_type,
8208 "overflow", overflow_type);
8211 // Verify that the overflow field is just before the end of the
8212 // bucket type.
8214 Btype* btype = ret->get_backend(gogo);
8215 int64_t offset = gogo->backend()->type_field_offset(btype,
8216 ret->field_count() - 1);
8217 int64_t size;
8218 if (!ret->backend_type_size(gogo, &size))
8220 go_assert(saw_errors());
8221 return NULL;
8224 int64_t ptr_size;
8225 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8227 go_assert(saw_errors());
8228 return NULL;
8231 go_assert(offset + ptr_size == size);
8233 ret->set_is_struct_incomparable();
8235 this->bucket_type_ = ret;
8236 return ret;
8239 // Return the hashmap type for a map type.
8241 Type*
8242 Map_type::hmap_type(Type* bucket_type)
8244 if (this->hmap_type_ != NULL)
8245 return this->hmap_type_;
8247 Type* int_type = Type::lookup_integer_type("int");
8248 Type* uint8_type = Type::lookup_integer_type("uint8");
8249 Type* uint16_type = Type::lookup_integer_type("uint16");
8250 Type* uint32_type = Type::lookup_integer_type("uint32");
8251 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8252 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8254 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8256 Struct_type* ret = make_builtin_struct_type(9,
8257 "count", int_type,
8258 "flags", uint8_type,
8259 "B", uint8_type,
8260 "noverflow", uint16_type,
8261 "hash0", uint32_type,
8262 "buckets", ptr_bucket_type,
8263 "oldbuckets", ptr_bucket_type,
8264 "nevacuate", uintptr_type,
8265 "extra", void_ptr_type);
8266 ret->set_is_struct_incomparable();
8267 this->hmap_type_ = ret;
8268 return ret;
8271 // Return the iterator type for a map type. This is the type of the
8272 // value used when doing a range over a map.
8274 Type*
8275 Map_type::hiter_type(Gogo* gogo)
8277 if (this->hiter_type_ != NULL)
8278 return this->hiter_type_;
8280 int64_t keysize, valsize;
8281 if (!this->key_type_->backend_type_size(gogo, &keysize)
8282 || !this->val_type_->backend_type_size(gogo, &valsize))
8284 go_assert(saw_errors());
8285 return NULL;
8288 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8289 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8290 Type* uint8_type = Type::lookup_integer_type("uint8");
8291 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8292 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8293 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8294 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8295 Type* hmap_type = this->hmap_type(bucket_type);
8296 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8297 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8298 Type* bool_type = Type::lookup_bool_type();
8300 Struct_type* ret = make_builtin_struct_type(15,
8301 "key", key_ptr_type,
8302 "val", val_ptr_type,
8303 "t", uint8_ptr_type,
8304 "h", hmap_ptr_type,
8305 "buckets", bucket_ptr_type,
8306 "bptr", bucket_ptr_type,
8307 "overflow", void_ptr_type,
8308 "oldoverflow", void_ptr_type,
8309 "startBucket", uintptr_type,
8310 "offset", uint8_type,
8311 "wrapped", bool_type,
8312 "B", uint8_type,
8313 "i", uint8_type,
8314 "bucket", uintptr_type,
8315 "checkBucket", uintptr_type);
8316 ret->set_is_struct_incomparable();
8317 this->hiter_type_ = ret;
8318 return ret;
8321 // Reflection string for a map.
8323 void
8324 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8326 ret->append("map[");
8327 this->append_reflection(this->key_type_, gogo, ret);
8328 ret->append("]");
8329 this->append_reflection(this->val_type_, gogo, ret);
8332 // Export a map type.
8334 void
8335 Map_type::do_export(Export* exp) const
8337 exp->write_c_string("map [");
8338 exp->write_type(this->key_type_);
8339 exp->write_c_string("] ");
8340 exp->write_type(this->val_type_);
8343 // Import a map type.
8345 Map_type*
8346 Map_type::do_import(Import* imp)
8348 imp->require_c_string("map [");
8349 Type* key_type = imp->read_type();
8350 imp->require_c_string("] ");
8351 Type* val_type = imp->read_type();
8352 return Type::make_map_type(key_type, val_type, imp->location());
8355 // Make a map type.
8357 Map_type*
8358 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8360 return new Map_type(key_type, val_type, location);
8363 // Class Channel_type.
8365 // Verify.
8367 bool
8368 Channel_type::do_verify()
8370 // We have no location for this error, but this is not something the
8371 // ordinary user will see.
8372 if (!this->element_type_->in_heap())
8373 go_error_at(Linemap::unknown_location(),
8374 "chan of go:notinheap type not allowed");
8375 return true;
8378 // Hash code.
8380 unsigned int
8381 Channel_type::do_hash_for_method(Gogo* gogo) const
8383 unsigned int ret = 0;
8384 if (this->may_send_)
8385 ret += 1;
8386 if (this->may_receive_)
8387 ret += 2;
8388 if (this->element_type_ != NULL)
8389 ret += this->element_type_->hash_for_method(gogo) << 2;
8390 return ret << 3;
8393 // Whether this type is the same as T.
8395 bool
8396 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8397 bool errors_are_identical) const
8399 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8400 cmp_tags, errors_are_identical, NULL))
8401 return false;
8402 return (this->may_send_ == t->may_send_
8403 && this->may_receive_ == t->may_receive_);
8406 // Return the backend representation for a channel type. A channel is a pointer
8407 // to a __go_channel struct. The __go_channel struct is defined in
8408 // libgo/runtime/channel.h.
8410 Btype*
8411 Channel_type::do_get_backend(Gogo* gogo)
8413 static Btype* backend_channel_type;
8414 if (backend_channel_type == NULL)
8416 std::vector<Backend::Btyped_identifier> bfields;
8417 Btype* bt = gogo->backend()->struct_type(bfields);
8418 bt = gogo->backend()->named_type("__go_channel", bt,
8419 Linemap::predeclared_location());
8420 backend_channel_type = gogo->backend()->pointer_type(bt);
8422 return backend_channel_type;
8425 // Build a type descriptor for a channel type.
8427 Type*
8428 Channel_type::make_chan_type_descriptor_type()
8430 static Type* ret;
8431 if (ret == NULL)
8433 Type* tdt = Type::make_type_descriptor_type();
8434 Type* ptdt = Type::make_type_descriptor_ptr_type();
8436 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8438 Struct_type* sf =
8439 Type::make_builtin_struct_type(3,
8440 "", tdt,
8441 "elem", ptdt,
8442 "dir", uintptr_type);
8444 ret = Type::make_builtin_named_type("ChanType", sf);
8447 return ret;
8450 // Build a type descriptor for a map type.
8452 Expression*
8453 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8455 Location bloc = Linemap::predeclared_location();
8457 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8459 const Struct_field_list* fields = ctdt->struct_type()->fields();
8461 Expression_list* vals = new Expression_list();
8462 vals->reserve(3);
8464 Struct_field_list::const_iterator p = fields->begin();
8465 go_assert(p->is_field_name("_type"));
8466 vals->push_back(this->type_descriptor_constructor(gogo,
8467 RUNTIME_TYPE_KIND_CHAN,
8468 name, NULL, true));
8470 ++p;
8471 go_assert(p->is_field_name("elem"));
8472 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8474 ++p;
8475 go_assert(p->is_field_name("dir"));
8476 // These bits must match the ones in libgo/runtime/go-type.h.
8477 int val = 0;
8478 if (this->may_receive_)
8479 val |= 1;
8480 if (this->may_send_)
8481 val |= 2;
8482 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8484 ++p;
8485 go_assert(p == fields->end());
8487 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8490 // Reflection string.
8492 void
8493 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8495 if (!this->may_send_)
8496 ret->append("<-");
8497 ret->append("chan");
8498 if (!this->may_receive_)
8499 ret->append("<-");
8500 ret->push_back(' ');
8501 this->append_reflection(this->element_type_, gogo, ret);
8504 // Export.
8506 void
8507 Channel_type::do_export(Export* exp) const
8509 exp->write_c_string("chan ");
8510 if (this->may_send_ && !this->may_receive_)
8511 exp->write_c_string("-< ");
8512 else if (this->may_receive_ && !this->may_send_)
8513 exp->write_c_string("<- ");
8514 exp->write_type(this->element_type_);
8517 // Import.
8519 Channel_type*
8520 Channel_type::do_import(Import* imp)
8522 imp->require_c_string("chan ");
8524 bool may_send;
8525 bool may_receive;
8526 if (imp->match_c_string("-< "))
8528 imp->advance(3);
8529 may_send = true;
8530 may_receive = false;
8532 else if (imp->match_c_string("<- "))
8534 imp->advance(3);
8535 may_receive = true;
8536 may_send = false;
8538 else
8540 may_send = true;
8541 may_receive = true;
8544 Type* element_type = imp->read_type();
8546 return Type::make_channel_type(may_send, may_receive, element_type);
8549 // Return the type to manage a select statement with ncases case
8550 // statements. A value of this type is allocated on the stack. This
8551 // must match the type hselect in libgo/go/runtime/select.go.
8553 Type*
8554 Channel_type::select_type(int ncases)
8556 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8557 Type* uint16_type = Type::lookup_integer_type("uint16");
8559 static Struct_type* scase_type;
8560 if (scase_type == NULL)
8562 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8563 Type* uint64_type = Type::lookup_integer_type("uint64");
8564 scase_type =
8565 Type::make_builtin_struct_type(7,
8566 "elem", unsafe_pointer_type,
8567 "chan", unsafe_pointer_type,
8568 "pc", uintptr_type,
8569 "kind", uint16_type,
8570 "index", uint16_type,
8571 "receivedp", unsafe_pointer_type,
8572 "releasetime", uint64_type);
8573 scase_type->set_is_struct_incomparable();
8576 Expression* ncases_expr =
8577 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8578 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8579 scases->set_is_array_incomparable();
8580 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8581 order->set_is_array_incomparable();
8583 Struct_type* ret =
8584 Type::make_builtin_struct_type(7,
8585 "tcase", uint16_type,
8586 "ncase", uint16_type,
8587 "pollorder", unsafe_pointer_type,
8588 "lockorder", unsafe_pointer_type,
8589 "scase", scases,
8590 "lockorderarr", order,
8591 "pollorderarr", order);
8592 ret->set_is_struct_incomparable();
8593 return ret;
8596 // Make a new channel type.
8598 Channel_type*
8599 Type::make_channel_type(bool send, bool receive, Type* element_type)
8601 return new Channel_type(send, receive, element_type);
8604 // Class Interface_type.
8606 // Return the list of methods.
8608 const Typed_identifier_list*
8609 Interface_type::methods() const
8611 go_assert(this->methods_are_finalized_ || saw_errors());
8612 return this->all_methods_;
8615 // Return the number of methods.
8617 size_t
8618 Interface_type::method_count() const
8620 go_assert(this->methods_are_finalized_ || saw_errors());
8621 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8624 // Traversal.
8627 Interface_type::do_traverse(Traverse* traverse)
8629 Typed_identifier_list* methods = (this->methods_are_finalized_
8630 ? this->all_methods_
8631 : this->parse_methods_);
8632 if (methods == NULL)
8633 return TRAVERSE_CONTINUE;
8634 return methods->traverse(traverse);
8637 // Finalize the methods. This handles interface inheritance.
8639 void
8640 Interface_type::finalize_methods()
8642 if (this->methods_are_finalized_)
8643 return;
8644 this->methods_are_finalized_ = true;
8645 if (this->parse_methods_ == NULL)
8646 return;
8648 this->all_methods_ = new Typed_identifier_list();
8649 this->all_methods_->reserve(this->parse_methods_->size());
8650 Typed_identifier_list inherit;
8651 for (Typed_identifier_list::const_iterator pm =
8652 this->parse_methods_->begin();
8653 pm != this->parse_methods_->end();
8654 ++pm)
8656 const Typed_identifier* p = &*pm;
8657 if (p->name().empty())
8658 inherit.push_back(*p);
8659 else if (this->find_method(p->name()) == NULL)
8660 this->all_methods_->push_back(*p);
8661 else
8662 go_error_at(p->location(), "duplicate method %qs",
8663 Gogo::message_name(p->name()).c_str());
8666 std::vector<Named_type*> seen;
8667 seen.reserve(inherit.size());
8668 bool issued_recursive_error = false;
8669 while (!inherit.empty())
8671 Type* t = inherit.back().type();
8672 Location tl = inherit.back().location();
8673 inherit.pop_back();
8675 Interface_type* it = t->interface_type();
8676 if (it == NULL)
8678 if (!t->is_error())
8679 go_error_at(tl, "interface contains embedded non-interface");
8680 continue;
8682 if (it == this)
8684 if (!issued_recursive_error)
8686 go_error_at(tl, "invalid recursive interface");
8687 issued_recursive_error = true;
8689 continue;
8692 Named_type* nt = t->named_type();
8693 if (nt != NULL && it->parse_methods_ != NULL)
8695 std::vector<Named_type*>::const_iterator q;
8696 for (q = seen.begin(); q != seen.end(); ++q)
8698 if (*q == nt)
8700 go_error_at(tl, "inherited interface loop");
8701 break;
8704 if (q != seen.end())
8705 continue;
8706 seen.push_back(nt);
8709 const Typed_identifier_list* imethods = it->parse_methods_;
8710 if (imethods == NULL)
8711 continue;
8712 for (Typed_identifier_list::const_iterator q = imethods->begin();
8713 q != imethods->end();
8714 ++q)
8716 if (q->name().empty())
8717 inherit.push_back(*q);
8718 else if (this->find_method(q->name()) == NULL)
8719 this->all_methods_->push_back(Typed_identifier(q->name(),
8720 q->type(), tl));
8721 else
8722 go_error_at(tl, "inherited method %qs is ambiguous",
8723 Gogo::message_name(q->name()).c_str());
8727 if (!this->all_methods_->empty())
8728 this->all_methods_->sort_by_name();
8729 else
8731 delete this->all_methods_;
8732 this->all_methods_ = NULL;
8736 // Return the method NAME, or NULL.
8738 const Typed_identifier*
8739 Interface_type::find_method(const std::string& name) const
8741 go_assert(this->methods_are_finalized_);
8742 if (this->all_methods_ == NULL)
8743 return NULL;
8744 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8745 p != this->all_methods_->end();
8746 ++p)
8747 if (p->name() == name)
8748 return &*p;
8749 return NULL;
8752 // Return the method index.
8754 size_t
8755 Interface_type::method_index(const std::string& name) const
8757 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
8758 size_t ret = 0;
8759 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8760 p != this->all_methods_->end();
8761 ++p, ++ret)
8762 if (p->name() == name)
8763 return ret;
8764 go_unreachable();
8767 // Return whether NAME is an unexported method, for better error
8768 // reporting.
8770 bool
8771 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
8773 go_assert(this->methods_are_finalized_);
8774 if (this->all_methods_ == NULL)
8775 return false;
8776 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8777 p != this->all_methods_->end();
8778 ++p)
8780 const std::string& method_name(p->name());
8781 if (Gogo::is_hidden_name(method_name)
8782 && name == Gogo::unpack_hidden_name(method_name)
8783 && gogo->pack_hidden_name(name, false) != method_name)
8784 return true;
8786 return false;
8789 // Whether this type is identical with T.
8791 bool
8792 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
8793 bool errors_are_identical) const
8795 // If methods have not been finalized, then we are asking whether
8796 // func redeclarations are the same. This is an error, so for
8797 // simplicity we say they are never the same.
8798 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
8799 return false;
8801 // We require the same methods with the same types. The methods
8802 // have already been sorted.
8803 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
8804 return this->all_methods_ == t->all_methods_;
8806 if (this->assume_identical(this, t) || t->assume_identical(t, this))
8807 return true;
8809 Assume_identical* hold_ai = this->assume_identical_;
8810 Assume_identical ai;
8811 ai.t1 = this;
8812 ai.t2 = t;
8813 ai.next = hold_ai;
8814 this->assume_identical_ = &ai;
8816 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
8817 Typed_identifier_list::const_iterator p2;
8818 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
8820 if (p1 == this->all_methods_->end())
8821 break;
8822 if (p1->name() != p2->name()
8823 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
8824 errors_are_identical, NULL))
8825 break;
8828 this->assume_identical_ = hold_ai;
8830 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
8833 // Return true if T1 and T2 are assumed to be identical during a type
8834 // comparison.
8836 bool
8837 Interface_type::assume_identical(const Interface_type* t1,
8838 const Interface_type* t2) const
8840 for (Assume_identical* p = this->assume_identical_;
8841 p != NULL;
8842 p = p->next)
8843 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
8844 return true;
8845 return false;
8848 // Whether we can assign the interface type T to this type. The types
8849 // are known to not be identical. An interface assignment is only
8850 // permitted if T is known to implement all methods in THIS.
8851 // Otherwise a type guard is required.
8853 bool
8854 Interface_type::is_compatible_for_assign(const Interface_type* t,
8855 std::string* reason) const
8857 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
8858 if (this->all_methods_ == NULL)
8859 return true;
8860 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8861 p != this->all_methods_->end();
8862 ++p)
8864 const Typed_identifier* m = t->find_method(p->name());
8865 if (m == NULL)
8867 if (reason != NULL)
8869 char buf[200];
8870 snprintf(buf, sizeof buf,
8871 _("need explicit conversion; missing method %s%s%s"),
8872 go_open_quote(), Gogo::message_name(p->name()).c_str(),
8873 go_close_quote());
8874 reason->assign(buf);
8876 return false;
8879 std::string subreason;
8880 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
8882 if (reason != NULL)
8884 std::string n = Gogo::message_name(p->name());
8885 size_t len = 100 + n.length() + subreason.length();
8886 char* buf = new char[len];
8887 if (subreason.empty())
8888 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8889 go_open_quote(), n.c_str(), go_close_quote());
8890 else
8891 snprintf(buf, len,
8892 _("incompatible type for method %s%s%s (%s)"),
8893 go_open_quote(), n.c_str(), go_close_quote(),
8894 subreason.c_str());
8895 reason->assign(buf);
8896 delete[] buf;
8898 return false;
8902 return true;
8905 // Hash code.
8907 unsigned int
8908 Interface_type::do_hash_for_method(Gogo*) const
8910 go_assert(this->methods_are_finalized_);
8911 unsigned int ret = 0;
8912 if (this->all_methods_ != NULL)
8914 for (Typed_identifier_list::const_iterator p =
8915 this->all_methods_->begin();
8916 p != this->all_methods_->end();
8917 ++p)
8919 ret = Type::hash_string(p->name(), ret);
8920 // We don't use the method type in the hash, to avoid
8921 // infinite recursion if an interface method uses a type
8922 // which is an interface which inherits from the interface
8923 // itself.
8924 // type T interface { F() interface {T}}
8925 ret <<= 1;
8928 return ret;
8931 // Return true if T implements the interface. If it does not, and
8932 // REASON is not NULL, set *REASON to a useful error message.
8934 bool
8935 Interface_type::implements_interface(const Type* t, std::string* reason) const
8937 go_assert(this->methods_are_finalized_);
8938 if (this->all_methods_ == NULL)
8939 return true;
8941 bool is_pointer = false;
8942 const Named_type* nt = t->named_type();
8943 const Struct_type* st = t->struct_type();
8944 // If we start with a named type, we don't dereference it to find
8945 // methods.
8946 if (nt == NULL)
8948 const Type* pt = t->points_to();
8949 if (pt != NULL)
8951 // If T is a pointer to a named type, then we need to look at
8952 // the type to which it points.
8953 is_pointer = true;
8954 nt = pt->named_type();
8955 st = pt->struct_type();
8959 // If we have a named type, get the methods from it rather than from
8960 // any struct type.
8961 if (nt != NULL)
8962 st = NULL;
8964 // Only named and struct types have methods.
8965 if (nt == NULL && st == NULL)
8967 if (reason != NULL)
8969 if (t->points_to() != NULL
8970 && t->points_to()->interface_type() != NULL)
8971 reason->assign(_("pointer to interface type has no methods"));
8972 else
8973 reason->assign(_("type has no methods"));
8975 return false;
8978 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
8980 if (reason != NULL)
8982 if (t->points_to() != NULL
8983 && t->points_to()->interface_type() != NULL)
8984 reason->assign(_("pointer to interface type has no methods"));
8985 else
8986 reason->assign(_("type has no methods"));
8988 return false;
8991 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8992 p != this->all_methods_->end();
8993 ++p)
8995 bool is_ambiguous = false;
8996 Method* m = (nt != NULL
8997 ? nt->method_function(p->name(), &is_ambiguous)
8998 : st->method_function(p->name(), &is_ambiguous));
8999 if (m == NULL)
9001 if (reason != NULL)
9003 std::string n = Gogo::message_name(p->name());
9004 size_t len = n.length() + 100;
9005 char* buf = new char[len];
9006 if (is_ambiguous)
9007 snprintf(buf, len, _("ambiguous method %s%s%s"),
9008 go_open_quote(), n.c_str(), go_close_quote());
9009 else
9010 snprintf(buf, len, _("missing method %s%s%s"),
9011 go_open_quote(), n.c_str(), go_close_quote());
9012 reason->assign(buf);
9013 delete[] buf;
9015 return false;
9018 Function_type *p_fn_type = p->type()->function_type();
9019 Function_type* m_fn_type = m->type()->function_type();
9020 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9021 std::string subreason;
9022 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
9023 &subreason))
9025 if (reason != NULL)
9027 std::string n = Gogo::message_name(p->name());
9028 size_t len = 100 + n.length() + subreason.length();
9029 char* buf = new char[len];
9030 if (subreason.empty())
9031 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9032 go_open_quote(), n.c_str(), go_close_quote());
9033 else
9034 snprintf(buf, len,
9035 _("incompatible type for method %s%s%s (%s)"),
9036 go_open_quote(), n.c_str(), go_close_quote(),
9037 subreason.c_str());
9038 reason->assign(buf);
9039 delete[] buf;
9041 return false;
9044 if (!is_pointer && !m->is_value_method())
9046 if (reason != NULL)
9048 std::string n = Gogo::message_name(p->name());
9049 size_t len = 100 + n.length();
9050 char* buf = new char[len];
9051 snprintf(buf, len,
9052 _("method %s%s%s requires a pointer receiver"),
9053 go_open_quote(), n.c_str(), go_close_quote());
9054 reason->assign(buf);
9055 delete[] buf;
9057 return false;
9060 // If the magic //go:nointerface comment was used, the method
9061 // may not be used to implement interfaces.
9062 if (m->nointerface())
9064 if (reason != NULL)
9066 std::string n = Gogo::message_name(p->name());
9067 size_t len = 100 + n.length();
9068 char* buf = new char[len];
9069 snprintf(buf, len,
9070 _("method %s%s%s is marked go:nointerface"),
9071 go_open_quote(), n.c_str(), go_close_quote());
9072 reason->assign(buf);
9073 delete[] buf;
9075 return false;
9079 return true;
9082 // Return the backend representation of the empty interface type. We
9083 // use the same struct for all empty interfaces.
9085 Btype*
9086 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9088 static Btype* empty_interface_type;
9089 if (empty_interface_type == NULL)
9091 std::vector<Backend::Btyped_identifier> bfields(2);
9093 Location bloc = Linemap::predeclared_location();
9095 Type* pdt = Type::make_type_descriptor_ptr_type();
9096 bfields[0].name = "__type_descriptor";
9097 bfields[0].btype = pdt->get_backend(gogo);
9098 bfields[0].location = bloc;
9100 Type* vt = Type::make_pointer_type(Type::make_void_type());
9101 bfields[1].name = "__object";
9102 bfields[1].btype = vt->get_backend(gogo);
9103 bfields[1].location = bloc;
9105 empty_interface_type = gogo->backend()->struct_type(bfields);
9107 return empty_interface_type;
9110 Interface_type::Bmethods_map Interface_type::bmethods_map;
9112 // Return a pointer to the backend representation of the method table.
9114 Btype*
9115 Interface_type::get_backend_methods(Gogo* gogo)
9117 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9118 return this->bmethods_;
9120 std::pair<Interface_type*, Bmethods_map_entry> val;
9121 val.first = this;
9122 val.second.btype = NULL;
9123 val.second.is_placeholder = false;
9124 std::pair<Bmethods_map::iterator, bool> ins =
9125 Interface_type::bmethods_map.insert(val);
9126 if (!ins.second
9127 && ins.first->second.btype != NULL
9128 && !ins.first->second.is_placeholder)
9130 this->bmethods_ = ins.first->second.btype;
9131 this->bmethods_is_placeholder_ = false;
9132 return this->bmethods_;
9135 Location loc = this->location();
9137 std::vector<Backend::Btyped_identifier>
9138 mfields(this->all_methods_->size() + 1);
9140 Type* pdt = Type::make_type_descriptor_ptr_type();
9141 mfields[0].name = "__type_descriptor";
9142 mfields[0].btype = pdt->get_backend(gogo);
9143 mfields[0].location = loc;
9145 std::string last_name = "";
9146 size_t i = 1;
9147 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9148 p != this->all_methods_->end();
9149 ++p, ++i)
9151 // The type of the method in Go only includes the parameters.
9152 // The actual method also has a receiver, which is always a
9153 // pointer. We need to add that pointer type here in order to
9154 // generate the correct type for the backend.
9155 Function_type* ft = p->type()->function_type();
9156 go_assert(ft->receiver() == NULL);
9158 const Typed_identifier_list* params = ft->parameters();
9159 Typed_identifier_list* mparams = new Typed_identifier_list();
9160 if (params != NULL)
9161 mparams->reserve(params->size() + 1);
9162 Type* vt = Type::make_pointer_type(Type::make_void_type());
9163 mparams->push_back(Typed_identifier("", vt, ft->location()));
9164 if (params != NULL)
9166 for (Typed_identifier_list::const_iterator pp = params->begin();
9167 pp != params->end();
9168 ++pp)
9169 mparams->push_back(*pp);
9172 Typed_identifier_list* mresults = (ft->results() == NULL
9173 ? NULL
9174 : ft->results()->copy());
9175 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9176 ft->location());
9178 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9179 mfields[i].btype = mft->get_backend_fntype(gogo);
9180 mfields[i].location = loc;
9182 // Sanity check: the names should be sorted.
9183 go_assert(Gogo::unpack_hidden_name(p->name())
9184 > Gogo::unpack_hidden_name(last_name));
9185 last_name = p->name();
9188 Btype* st = gogo->backend()->struct_type(mfields);
9189 Btype* ret = gogo->backend()->pointer_type(st);
9191 if (ins.first->second.btype != NULL
9192 && ins.first->second.is_placeholder)
9193 gogo->backend()->set_placeholder_pointer_type(ins.first->second.btype,
9194 ret);
9195 this->bmethods_ = ret;
9196 ins.first->second.btype = ret;
9197 this->bmethods_is_placeholder_ = false;
9198 ins.first->second.is_placeholder = false;
9199 return ret;
9202 // Return a placeholder for the pointer to the backend methods table.
9204 Btype*
9205 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9207 if (this->bmethods_ == NULL)
9209 std::pair<Interface_type*, Bmethods_map_entry> val;
9210 val.first = this;
9211 val.second.btype = NULL;
9212 val.second.is_placeholder = false;
9213 std::pair<Bmethods_map::iterator, bool> ins =
9214 Interface_type::bmethods_map.insert(val);
9215 if (!ins.second && ins.first->second.btype != NULL)
9217 this->bmethods_ = ins.first->second.btype;
9218 this->bmethods_is_placeholder_ = ins.first->second.is_placeholder;
9219 return this->bmethods_;
9222 Location loc = this->location();
9223 Btype* bt = gogo->backend()->placeholder_pointer_type("", loc, false);
9224 this->bmethods_ = bt;
9225 ins.first->second.btype = bt;
9226 this->bmethods_is_placeholder_ = true;
9227 ins.first->second.is_placeholder = true;
9229 return this->bmethods_;
9232 // Return the fields of a non-empty interface type. This is not
9233 // declared in types.h so that types.h doesn't have to #include
9234 // backend.h.
9236 static void
9237 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9238 bool use_placeholder,
9239 std::vector<Backend::Btyped_identifier>* bfields)
9241 Location loc = type->location();
9243 bfields->resize(2);
9245 (*bfields)[0].name = "__methods";
9246 (*bfields)[0].btype = (use_placeholder
9247 ? type->get_backend_methods_placeholder(gogo)
9248 : type->get_backend_methods(gogo));
9249 (*bfields)[0].location = loc;
9251 Type* vt = Type::make_pointer_type(Type::make_void_type());
9252 (*bfields)[1].name = "__object";
9253 (*bfields)[1].btype = vt->get_backend(gogo);
9254 (*bfields)[1].location = Linemap::predeclared_location();
9257 // Return the backend representation for an interface type. An interface is a
9258 // pointer to a struct. The struct has three fields. The first field is a
9259 // pointer to the type descriptor for the dynamic type of the object.
9260 // The second field is a pointer to a table of methods for the
9261 // interface to be used with the object. The third field is the value
9262 // of the object itself.
9264 Btype*
9265 Interface_type::do_get_backend(Gogo* gogo)
9267 if (this->is_empty())
9268 return Interface_type::get_backend_empty_interface_type(gogo);
9269 else
9271 if (this->interface_btype_ != NULL)
9272 return this->interface_btype_;
9273 this->interface_btype_ =
9274 gogo->backend()->placeholder_struct_type("", this->location_);
9275 std::vector<Backend::Btyped_identifier> bfields;
9276 get_backend_interface_fields(gogo, this, false, &bfields);
9277 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9278 bfields))
9279 this->interface_btype_ = gogo->backend()->error_type();
9280 return this->interface_btype_;
9284 // Finish the backend representation of the methods.
9286 void
9287 Interface_type::finish_backend_methods(Gogo* gogo)
9289 if (!this->is_empty())
9291 const Typed_identifier_list* methods = this->methods();
9292 if (methods != NULL)
9294 for (Typed_identifier_list::const_iterator p = methods->begin();
9295 p != methods->end();
9296 ++p)
9297 p->type()->get_backend(gogo);
9300 // Getting the backend methods now will set the placeholder
9301 // pointer.
9302 this->get_backend_methods(gogo);
9306 // The type of an interface type descriptor.
9308 Type*
9309 Interface_type::make_interface_type_descriptor_type()
9311 static Type* ret;
9312 if (ret == NULL)
9314 Type* tdt = Type::make_type_descriptor_type();
9315 Type* ptdt = Type::make_type_descriptor_ptr_type();
9317 Type* string_type = Type::lookup_string_type();
9318 Type* pointer_string_type = Type::make_pointer_type(string_type);
9320 Struct_type* sm =
9321 Type::make_builtin_struct_type(3,
9322 "name", pointer_string_type,
9323 "pkgPath", pointer_string_type,
9324 "typ", ptdt);
9326 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9328 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9330 Struct_type* s = Type::make_builtin_struct_type(2,
9331 "", tdt,
9332 "methods", slice_nsm);
9334 ret = Type::make_builtin_named_type("InterfaceType", s);
9337 return ret;
9340 // Build a type descriptor for an interface type.
9342 Expression*
9343 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9345 Location bloc = Linemap::predeclared_location();
9347 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9349 const Struct_field_list* ifields = itdt->struct_type()->fields();
9351 Expression_list* ivals = new Expression_list();
9352 ivals->reserve(2);
9354 Struct_field_list::const_iterator pif = ifields->begin();
9355 go_assert(pif->is_field_name("_type"));
9356 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9357 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9358 true));
9360 ++pif;
9361 go_assert(pif->is_field_name("methods"));
9363 Expression_list* methods = new Expression_list();
9364 if (this->all_methods_ != NULL)
9366 Type* elemtype = pif->type()->array_type()->element_type();
9368 methods->reserve(this->all_methods_->size());
9369 for (Typed_identifier_list::const_iterator pm =
9370 this->all_methods_->begin();
9371 pm != this->all_methods_->end();
9372 ++pm)
9374 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9376 Expression_list* mvals = new Expression_list();
9377 mvals->reserve(3);
9379 Struct_field_list::const_iterator pmf = mfields->begin();
9380 go_assert(pmf->is_field_name("name"));
9381 std::string s = Gogo::unpack_hidden_name(pm->name());
9382 Expression* e = Expression::make_string(s, bloc);
9383 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9385 ++pmf;
9386 go_assert(pmf->is_field_name("pkgPath"));
9387 if (!Gogo::is_hidden_name(pm->name()))
9388 mvals->push_back(Expression::make_nil(bloc));
9389 else
9391 s = Gogo::hidden_name_pkgpath(pm->name());
9392 e = Expression::make_string(s, bloc);
9393 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9396 ++pmf;
9397 go_assert(pmf->is_field_name("typ"));
9398 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9400 ++pmf;
9401 go_assert(pmf == mfields->end());
9403 e = Expression::make_struct_composite_literal(elemtype, mvals,
9404 bloc);
9405 methods->push_back(e);
9409 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9410 methods, bloc));
9412 ++pif;
9413 go_assert(pif == ifields->end());
9415 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9418 // Reflection string.
9420 void
9421 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9423 ret->append("interface {");
9424 const Typed_identifier_list* methods = this->parse_methods_;
9425 if (methods != NULL)
9427 ret->push_back(' ');
9428 for (Typed_identifier_list::const_iterator p = methods->begin();
9429 p != methods->end();
9430 ++p)
9432 if (p != methods->begin())
9433 ret->append("; ");
9434 if (p->name().empty())
9435 this->append_reflection(p->type(), gogo, ret);
9436 else
9438 if (!Gogo::is_hidden_name(p->name()))
9439 ret->append(p->name());
9440 else if (gogo->pkgpath_from_option())
9441 ret->append(p->name().substr(1));
9442 else
9444 // If no -fgo-pkgpath option, backward compatibility
9445 // for how this used to work before -fgo-pkgpath was
9446 // introduced.
9447 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9448 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9449 ret->push_back('.');
9450 ret->append(Gogo::unpack_hidden_name(p->name()));
9452 std::string sub = p->type()->reflection(gogo);
9453 go_assert(sub.compare(0, 4, "func") == 0);
9454 sub = sub.substr(4);
9455 ret->append(sub);
9458 ret->push_back(' ');
9460 ret->append("}");
9463 // Export.
9465 void
9466 Interface_type::do_export(Export* exp) const
9468 exp->write_c_string("interface { ");
9470 const Typed_identifier_list* methods = this->parse_methods_;
9471 if (methods != NULL)
9473 for (Typed_identifier_list::const_iterator pm = methods->begin();
9474 pm != methods->end();
9475 ++pm)
9477 if (pm->name().empty())
9479 exp->write_c_string("? ");
9480 exp->write_type(pm->type());
9482 else
9484 exp->write_string(pm->name());
9485 exp->write_c_string(" (");
9487 const Function_type* fntype = pm->type()->function_type();
9489 bool first = true;
9490 const Typed_identifier_list* parameters = fntype->parameters();
9491 if (parameters != NULL)
9493 bool is_varargs = fntype->is_varargs();
9494 for (Typed_identifier_list::const_iterator pp =
9495 parameters->begin();
9496 pp != parameters->end();
9497 ++pp)
9499 if (first)
9500 first = false;
9501 else
9502 exp->write_c_string(", ");
9503 exp->write_name(pp->name());
9504 exp->write_c_string(" ");
9505 if (!is_varargs || pp + 1 != parameters->end())
9506 exp->write_type(pp->type());
9507 else
9509 exp->write_c_string("...");
9510 Type *pptype = pp->type();
9511 exp->write_type(pptype->array_type()->element_type());
9516 exp->write_c_string(")");
9518 const Typed_identifier_list* results = fntype->results();
9519 if (results != NULL)
9521 exp->write_c_string(" ");
9522 if (results->size() == 1 && results->begin()->name().empty())
9523 exp->write_type(results->begin()->type());
9524 else
9526 first = true;
9527 exp->write_c_string("(");
9528 for (Typed_identifier_list::const_iterator p =
9529 results->begin();
9530 p != results->end();
9531 ++p)
9533 if (first)
9534 first = false;
9535 else
9536 exp->write_c_string(", ");
9537 exp->write_name(p->name());
9538 exp->write_c_string(" ");
9539 exp->write_type(p->type());
9541 exp->write_c_string(")");
9546 exp->write_c_string("; ");
9550 exp->write_c_string("}");
9553 // Import an interface type.
9555 Interface_type*
9556 Interface_type::do_import(Import* imp)
9558 imp->require_c_string("interface { ");
9560 Typed_identifier_list* methods = new Typed_identifier_list;
9561 while (imp->peek_char() != '}')
9563 std::string name = imp->read_identifier();
9565 if (name == "?")
9567 imp->require_c_string(" ");
9568 Type* t = imp->read_type();
9569 methods->push_back(Typed_identifier("", t, imp->location()));
9570 imp->require_c_string("; ");
9571 continue;
9574 imp->require_c_string(" (");
9576 Typed_identifier_list* parameters;
9577 bool is_varargs = false;
9578 if (imp->peek_char() == ')')
9579 parameters = NULL;
9580 else
9582 parameters = new Typed_identifier_list;
9583 while (true)
9585 std::string name = imp->read_name();
9586 imp->require_c_string(" ");
9588 if (imp->match_c_string("..."))
9590 imp->advance(3);
9591 is_varargs = true;
9594 Type* ptype = imp->read_type();
9595 if (is_varargs)
9596 ptype = Type::make_array_type(ptype, NULL);
9597 parameters->push_back(Typed_identifier(name, ptype,
9598 imp->location()));
9599 if (imp->peek_char() != ',')
9600 break;
9601 go_assert(!is_varargs);
9602 imp->require_c_string(", ");
9605 imp->require_c_string(")");
9607 Typed_identifier_list* results;
9608 if (imp->peek_char() != ' ')
9609 results = NULL;
9610 else
9612 results = new Typed_identifier_list;
9613 imp->advance(1);
9614 if (imp->peek_char() != '(')
9616 Type* rtype = imp->read_type();
9617 results->push_back(Typed_identifier("", rtype, imp->location()));
9619 else
9621 imp->advance(1);
9622 while (true)
9624 std::string name = imp->read_name();
9625 imp->require_c_string(" ");
9626 Type* rtype = imp->read_type();
9627 results->push_back(Typed_identifier(name, rtype,
9628 imp->location()));
9629 if (imp->peek_char() != ',')
9630 break;
9631 imp->require_c_string(", ");
9633 imp->require_c_string(")");
9637 Function_type* fntype = Type::make_function_type(NULL, parameters,
9638 results,
9639 imp->location());
9640 if (is_varargs)
9641 fntype->set_is_varargs();
9642 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9644 imp->require_c_string("; ");
9647 imp->require_c_string("}");
9649 if (methods->empty())
9651 delete methods;
9652 methods = NULL;
9655 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9656 ret->package_ = imp->package();
9657 return ret;
9660 // Make an interface type.
9662 Interface_type*
9663 Type::make_interface_type(Typed_identifier_list* methods,
9664 Location location)
9666 return new Interface_type(methods, location);
9669 // Make an empty interface type.
9671 Interface_type*
9672 Type::make_empty_interface_type(Location location)
9674 Interface_type* ret = new Interface_type(NULL, location);
9675 ret->finalize_methods();
9676 return ret;
9679 // Class Method.
9681 // Bind a method to an object.
9683 Expression*
9684 Method::bind_method(Expression* expr, Location location) const
9686 if (this->stub_ == NULL)
9688 // When there is no stub object, the binding is determined by
9689 // the child class.
9690 return this->do_bind_method(expr, location);
9692 return Expression::make_bound_method(expr, this, this->stub_, location);
9695 // Return the named object associated with a method. This may only be
9696 // called after methods are finalized.
9698 Named_object*
9699 Method::named_object() const
9701 if (this->stub_ != NULL)
9702 return this->stub_;
9703 return this->do_named_object();
9706 // Class Named_method.
9708 // The type of the method.
9710 Function_type*
9711 Named_method::do_type() const
9713 if (this->named_object_->is_function())
9714 return this->named_object_->func_value()->type();
9715 else if (this->named_object_->is_function_declaration())
9716 return this->named_object_->func_declaration_value()->type();
9717 else
9718 go_unreachable();
9721 // Return the location of the method receiver.
9723 Location
9724 Named_method::do_receiver_location() const
9726 return this->do_type()->receiver()->location();
9729 // Bind a method to an object.
9731 Expression*
9732 Named_method::do_bind_method(Expression* expr, Location location) const
9734 Named_object* no = this->named_object_;
9735 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9736 no, location);
9737 // If this is not a local method, and it does not use a stub, then
9738 // the real method expects a different type. We need to cast the
9739 // first argument.
9740 if (this->depth() > 0 && !this->needs_stub_method())
9742 Function_type* ftype = this->do_type();
9743 go_assert(ftype->is_method());
9744 Type* frtype = ftype->receiver()->type();
9745 bme->set_first_argument_type(frtype);
9747 return bme;
9750 // Return whether this method should not participate in interfaces.
9752 bool
9753 Named_method::do_nointerface() const
9755 Named_object* no = this->named_object_;
9756 if (no->is_function())
9757 return no->func_value()->nointerface();
9758 else if (no->is_function_declaration())
9759 return no->func_declaration_value()->nointerface();
9760 else
9761 go_unreachable();
9764 // Class Interface_method.
9766 // Bind a method to an object.
9768 Expression*
9769 Interface_method::do_bind_method(Expression* expr,
9770 Location location) const
9772 return Expression::make_interface_field_reference(expr, this->name_,
9773 location);
9776 // Class Methods.
9778 // Insert a new method. Return true if it was inserted, false
9779 // otherwise.
9781 bool
9782 Methods::insert(const std::string& name, Method* m)
9784 std::pair<Method_map::iterator, bool> ins =
9785 this->methods_.insert(std::make_pair(name, m));
9786 if (ins.second)
9787 return true;
9788 else
9790 Method* old_method = ins.first->second;
9791 if (m->depth() < old_method->depth())
9793 delete old_method;
9794 ins.first->second = m;
9795 return true;
9797 else
9799 if (m->depth() == old_method->depth())
9800 old_method->set_is_ambiguous();
9801 return false;
9806 // Return the number of unambiguous methods.
9808 size_t
9809 Methods::count() const
9811 size_t ret = 0;
9812 for (Method_map::const_iterator p = this->methods_.begin();
9813 p != this->methods_.end();
9814 ++p)
9815 if (!p->second->is_ambiguous())
9816 ++ret;
9817 return ret;
9820 // Class Named_type.
9822 // Return the name of the type.
9824 const std::string&
9825 Named_type::name() const
9827 return this->named_object_->name();
9830 // Return the name of the type to use in an error message.
9832 std::string
9833 Named_type::message_name() const
9835 return this->named_object_->message_name();
9838 // Return the base type for this type. We have to be careful about
9839 // circular type definitions, which are invalid but may be seen here.
9841 Type*
9842 Named_type::named_base()
9844 if (this->seen_)
9845 return this;
9846 this->seen_ = true;
9847 Type* ret = this->type_->base();
9848 this->seen_ = false;
9849 return ret;
9852 const Type*
9853 Named_type::named_base() const
9855 if (this->seen_)
9856 return this;
9857 this->seen_ = true;
9858 const Type* ret = this->type_->base();
9859 this->seen_ = false;
9860 return ret;
9863 // Return whether this is an error type. We have to be careful about
9864 // circular type definitions, which are invalid but may be seen here.
9866 bool
9867 Named_type::is_named_error_type() const
9869 if (this->seen_)
9870 return false;
9871 this->seen_ = true;
9872 bool ret = this->type_->is_error_type();
9873 this->seen_ = false;
9874 return ret;
9877 // Whether this type is comparable. We have to be careful about
9878 // circular type definitions.
9880 bool
9881 Named_type::named_type_is_comparable(std::string* reason) const
9883 if (this->seen_)
9884 return false;
9885 this->seen_ = true;
9886 bool ret = Type::are_compatible_for_comparison(true, this->type_,
9887 this->type_, reason);
9888 this->seen_ = false;
9889 return ret;
9892 // Add a method to this type.
9894 Named_object*
9895 Named_type::add_method(const std::string& name, Function* function)
9897 go_assert(!this->is_alias_);
9898 if (this->local_methods_ == NULL)
9899 this->local_methods_ = new Bindings(NULL);
9900 return this->local_methods_->add_function(name, NULL, function);
9903 // Add a method declaration to this type.
9905 Named_object*
9906 Named_type::add_method_declaration(const std::string& name, Package* package,
9907 Function_type* type,
9908 Location location)
9910 go_assert(!this->is_alias_);
9911 if (this->local_methods_ == NULL)
9912 this->local_methods_ = new Bindings(NULL);
9913 return this->local_methods_->add_function_declaration(name, package, type,
9914 location);
9917 // Add an existing method to this type.
9919 void
9920 Named_type::add_existing_method(Named_object* no)
9922 go_assert(!this->is_alias_);
9923 if (this->local_methods_ == NULL)
9924 this->local_methods_ = new Bindings(NULL);
9925 this->local_methods_->add_named_object(no);
9928 // Look for a local method NAME, and returns its named object, or NULL
9929 // if not there.
9931 Named_object*
9932 Named_type::find_local_method(const std::string& name) const
9934 if (this->is_error_)
9935 return NULL;
9936 if (this->is_alias_)
9938 Named_type* nt = this->type_->named_type();
9939 if (nt != NULL)
9941 if (this->seen_alias_)
9942 return NULL;
9943 this->seen_alias_ = true;
9944 Named_object* ret = nt->find_local_method(name);
9945 this->seen_alias_ = false;
9946 return ret;
9948 return NULL;
9950 if (this->local_methods_ == NULL)
9951 return NULL;
9952 return this->local_methods_->lookup(name);
9955 // Return the list of local methods.
9957 const Bindings*
9958 Named_type::local_methods() const
9960 if (this->is_error_)
9961 return NULL;
9962 if (this->is_alias_)
9964 Named_type* nt = this->type_->named_type();
9965 if (nt != NULL)
9967 if (this->seen_alias_)
9968 return NULL;
9969 this->seen_alias_ = true;
9970 const Bindings* ret = nt->local_methods();
9971 this->seen_alias_ = false;
9972 return ret;
9974 return NULL;
9976 return this->local_methods_;
9979 // Return whether NAME is an unexported field or method, for better
9980 // error reporting.
9982 bool
9983 Named_type::is_unexported_local_method(Gogo* gogo,
9984 const std::string& name) const
9986 if (this->is_error_)
9987 return false;
9988 if (this->is_alias_)
9990 Named_type* nt = this->type_->named_type();
9991 if (nt != NULL)
9993 if (this->seen_alias_)
9994 return false;
9995 this->seen_alias_ = true;
9996 bool ret = nt->is_unexported_local_method(gogo, name);
9997 this->seen_alias_ = false;
9998 return ret;
10000 return false;
10002 Bindings* methods = this->local_methods_;
10003 if (methods != NULL)
10005 for (Bindings::const_declarations_iterator p =
10006 methods->begin_declarations();
10007 p != methods->end_declarations();
10008 ++p)
10010 if (Gogo::is_hidden_name(p->first)
10011 && name == Gogo::unpack_hidden_name(p->first)
10012 && gogo->pack_hidden_name(name, false) != p->first)
10013 return true;
10016 return false;
10019 // Build the complete list of methods for this type, which means
10020 // recursively including all methods for anonymous fields. Create all
10021 // stub methods.
10023 void
10024 Named_type::finalize_methods(Gogo* gogo)
10026 if (this->is_alias_)
10027 return;
10028 if (this->all_methods_ != NULL)
10029 return;
10031 if (this->local_methods_ != NULL
10032 && (this->points_to() != NULL || this->interface_type() != NULL))
10034 const Bindings* lm = this->local_methods_;
10035 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10036 p != lm->end_declarations();
10037 ++p)
10038 go_error_at(p->second->location(),
10039 "invalid pointer or interface receiver type");
10040 delete this->local_methods_;
10041 this->local_methods_ = NULL;
10042 return;
10045 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10048 // Return whether this type has any methods.
10050 bool
10051 Named_type::has_any_methods() const
10053 if (this->is_error_)
10054 return false;
10055 if (this->is_alias_)
10057 if (this->type_->named_type() != NULL)
10059 if (this->seen_alias_)
10060 return false;
10061 this->seen_alias_ = true;
10062 bool ret = this->type_->named_type()->has_any_methods();
10063 this->seen_alias_ = false;
10064 return ret;
10066 if (this->type_->struct_type() != NULL)
10067 return this->type_->struct_type()->has_any_methods();
10068 return false;
10070 return this->all_methods_ != NULL;
10073 // Return the methods for this type.
10075 const Methods*
10076 Named_type::methods() const
10078 if (this->is_error_)
10079 return NULL;
10080 if (this->is_alias_)
10082 if (this->type_->named_type() != NULL)
10084 if (this->seen_alias_)
10085 return NULL;
10086 this->seen_alias_ = true;
10087 const Methods* ret = this->type_->named_type()->methods();
10088 this->seen_alias_ = false;
10089 return ret;
10091 if (this->type_->struct_type() != NULL)
10092 return this->type_->struct_type()->methods();
10093 return NULL;
10095 return this->all_methods_;
10098 // Return the method NAME, or NULL if there isn't one or if it is
10099 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10100 // ambiguous.
10102 Method*
10103 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10105 if (this->is_error_)
10106 return NULL;
10107 if (this->is_alias_)
10109 if (is_ambiguous != NULL)
10110 *is_ambiguous = false;
10111 if (this->type_->named_type() != NULL)
10113 if (this->seen_alias_)
10114 return NULL;
10115 this->seen_alias_ = true;
10116 Named_type* nt = this->type_->named_type();
10117 Method* ret = nt->method_function(name, is_ambiguous);
10118 this->seen_alias_ = false;
10119 return ret;
10121 if (this->type_->struct_type() != NULL)
10122 return this->type_->struct_type()->method_function(name, is_ambiguous);
10123 return NULL;
10125 return Type::method_function(this->all_methods_, name, is_ambiguous);
10128 // Return a pointer to the interface method table for this type for
10129 // the interface INTERFACE. IS_POINTER is true if this is for a
10130 // pointer to THIS.
10132 Expression*
10133 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10135 if (this->is_error_)
10136 return Expression::make_error(this->location_);
10137 if (this->is_alias_)
10139 if (this->type_->named_type() != NULL)
10141 if (this->seen_alias_)
10142 return Expression::make_error(this->location_);
10143 this->seen_alias_ = true;
10144 Named_type* nt = this->type_->named_type();
10145 Expression* ret = nt->interface_method_table(interface, is_pointer);
10146 this->seen_alias_ = false;
10147 return ret;
10149 if (this->type_->struct_type() != NULL)
10150 return this->type_->struct_type()->interface_method_table(interface,
10151 is_pointer);
10152 go_unreachable();
10154 return Type::interface_method_table(this, interface, is_pointer,
10155 &this->interface_method_tables_,
10156 &this->pointer_interface_method_tables_);
10159 // Look for a use of a complete type within another type. This is
10160 // used to check that we don't try to use a type within itself.
10162 class Find_type_use : public Traverse
10164 public:
10165 Find_type_use(Named_type* find_type)
10166 : Traverse(traverse_types),
10167 find_type_(find_type), found_(false)
10170 // Whether we found the type.
10171 bool
10172 found() const
10173 { return this->found_; }
10175 protected:
10177 type(Type*);
10179 private:
10180 // The type we are looking for.
10181 Named_type* find_type_;
10182 // Whether we found the type.
10183 bool found_;
10186 // Check for FIND_TYPE in TYPE.
10189 Find_type_use::type(Type* type)
10191 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10193 this->found_ = true;
10194 return TRAVERSE_EXIT;
10197 // It's OK if we see a reference to the type in any type which is
10198 // essentially a pointer: a pointer, a slice, a function, a map, or
10199 // a channel.
10200 if (type->points_to() != NULL
10201 || type->is_slice_type()
10202 || type->function_type() != NULL
10203 || type->map_type() != NULL
10204 || type->channel_type() != NULL)
10205 return TRAVERSE_SKIP_COMPONENTS;
10207 // For an interface, a reference to the type in a method type should
10208 // be ignored, but we have to consider direct inheritance. When
10209 // this is called, there may be cases of direct inheritance
10210 // represented as a method with no name.
10211 if (type->interface_type() != NULL)
10213 const Typed_identifier_list* methods = type->interface_type()->methods();
10214 if (methods != NULL)
10216 for (Typed_identifier_list::const_iterator p = methods->begin();
10217 p != methods->end();
10218 ++p)
10220 if (p->name().empty())
10222 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10223 return TRAVERSE_EXIT;
10227 return TRAVERSE_SKIP_COMPONENTS;
10230 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10231 // to convert TYPE to the backend representation before we convert
10232 // FIND_TYPE_.
10233 if (type->named_type() != NULL)
10235 switch (type->base()->classification())
10237 case Type::TYPE_ERROR:
10238 case Type::TYPE_BOOLEAN:
10239 case Type::TYPE_INTEGER:
10240 case Type::TYPE_FLOAT:
10241 case Type::TYPE_COMPLEX:
10242 case Type::TYPE_STRING:
10243 case Type::TYPE_NIL:
10244 break;
10246 case Type::TYPE_ARRAY:
10247 case Type::TYPE_STRUCT:
10248 this->find_type_->add_dependency(type->named_type());
10249 break;
10251 case Type::TYPE_NAMED:
10252 case Type::TYPE_FORWARD:
10253 go_assert(saw_errors());
10254 break;
10256 case Type::TYPE_VOID:
10257 case Type::TYPE_SINK:
10258 case Type::TYPE_FUNCTION:
10259 case Type::TYPE_POINTER:
10260 case Type::TYPE_CALL_MULTIPLE_RESULT:
10261 case Type::TYPE_MAP:
10262 case Type::TYPE_CHANNEL:
10263 case Type::TYPE_INTERFACE:
10264 default:
10265 go_unreachable();
10269 return TRAVERSE_CONTINUE;
10272 // Look for a circular reference of an alias.
10274 class Find_alias : public Traverse
10276 public:
10277 Find_alias(Named_type* find_type)
10278 : Traverse(traverse_types),
10279 find_type_(find_type), found_(false)
10282 // Whether we found the type.
10283 bool
10284 found() const
10285 { return this->found_; }
10287 protected:
10289 type(Type*);
10291 private:
10292 // The type we are looking for.
10293 Named_type* find_type_;
10294 // Whether we found the type.
10295 bool found_;
10299 Find_alias::type(Type* type)
10301 Named_type* nt = type->named_type();
10302 if (nt != NULL)
10304 if (nt == this->find_type_)
10306 this->found_ = true;
10307 return TRAVERSE_EXIT;
10310 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10311 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10312 // an alias itself, it's OK if whatever T2 is defined as refers
10313 // to T1.
10314 if (!nt->is_alias())
10315 return TRAVERSE_SKIP_COMPONENTS;
10318 return TRAVERSE_CONTINUE;
10321 // Verify that a named type does not refer to itself.
10323 bool
10324 Named_type::do_verify()
10326 if (this->is_verified_)
10327 return true;
10328 this->is_verified_ = true;
10330 if (this->is_error_)
10331 return false;
10333 if (this->is_alias_)
10335 Find_alias find(this);
10336 Type::traverse(this->type_, &find);
10337 if (find.found())
10339 go_error_at(this->location_, "invalid recursive alias %qs",
10340 this->message_name().c_str());
10341 this->is_error_ = true;
10342 return false;
10346 Find_type_use find(this);
10347 Type::traverse(this->type_, &find);
10348 if (find.found())
10350 go_error_at(this->location_, "invalid recursive type %qs",
10351 this->message_name().c_str());
10352 this->is_error_ = true;
10353 return false;
10356 // Check whether any of the local methods overloads an existing
10357 // struct field or interface method. We don't need to check the
10358 // list of methods against itself: that is handled by the Bindings
10359 // code.
10360 if (this->local_methods_ != NULL)
10362 Struct_type* st = this->type_->struct_type();
10363 if (st != NULL)
10365 for (Bindings::const_declarations_iterator p =
10366 this->local_methods_->begin_declarations();
10367 p != this->local_methods_->end_declarations();
10368 ++p)
10370 const std::string& name(p->first);
10371 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10373 go_error_at(p->second->location(),
10374 "method %qs redeclares struct field name",
10375 Gogo::message_name(name).c_str());
10381 return true;
10384 // Return whether this type is or contains a pointer.
10386 bool
10387 Named_type::do_has_pointer() const
10389 if (this->seen_)
10390 return false;
10391 this->seen_ = true;
10392 bool ret = this->type_->has_pointer();
10393 this->seen_ = false;
10394 return ret;
10397 // Return whether comparisons for this type can use the identity
10398 // function.
10400 bool
10401 Named_type::do_compare_is_identity(Gogo* gogo)
10403 // We don't use this->seen_ here because compare_is_identity may
10404 // call base() later, and that will mess up if seen_ is set here.
10405 if (this->seen_in_compare_is_identity_)
10406 return false;
10407 this->seen_in_compare_is_identity_ = true;
10408 bool ret = this->type_->compare_is_identity(gogo);
10409 this->seen_in_compare_is_identity_ = false;
10410 return ret;
10413 // Return whether this type is reflexive--whether it is always equal
10414 // to itself.
10416 bool
10417 Named_type::do_is_reflexive()
10419 if (this->seen_in_compare_is_identity_)
10420 return false;
10421 this->seen_in_compare_is_identity_ = true;
10422 bool ret = this->type_->is_reflexive();
10423 this->seen_in_compare_is_identity_ = false;
10424 return ret;
10427 // Return whether this type needs a key update when used as a map key.
10429 bool
10430 Named_type::do_needs_key_update()
10432 if (this->seen_in_compare_is_identity_)
10433 return true;
10434 this->seen_in_compare_is_identity_ = true;
10435 bool ret = this->type_->needs_key_update();
10436 this->seen_in_compare_is_identity_ = false;
10437 return ret;
10440 // Return a hash code. This is used for method lookup. We simply
10441 // hash on the name itself.
10443 unsigned int
10444 Named_type::do_hash_for_method(Gogo* gogo) const
10446 if (this->is_error_)
10447 return 0;
10449 // Aliases are handled in Type::hash_for_method.
10450 go_assert(!this->is_alias_);
10452 const std::string& name(this->named_object()->name());
10453 unsigned int ret = Type::hash_string(name, 0);
10455 // GOGO will be NULL here when called from Type_hash_identical.
10456 // That is OK because that is only used for internal hash tables
10457 // where we are going to be comparing named types for equality. In
10458 // other cases, which are cases where the runtime is going to
10459 // compare hash codes to see if the types are the same, we need to
10460 // include the pkgpath in the hash.
10461 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10463 const Package* package = this->named_object()->package();
10464 if (package == NULL)
10465 ret = Type::hash_string(gogo->pkgpath(), ret);
10466 else
10467 ret = Type::hash_string(package->pkgpath(), ret);
10470 return ret;
10473 // Convert a named type to the backend representation. In order to
10474 // get dependencies right, we fill in a dummy structure for this type,
10475 // then convert all the dependencies, then complete this type. When
10476 // this function is complete, the size of the type is known.
10478 void
10479 Named_type::convert(Gogo* gogo)
10481 if (this->is_error_ || this->is_converted_)
10482 return;
10484 this->create_placeholder(gogo);
10486 // If we are called to turn unsafe.Sizeof into a constant, we may
10487 // not have verified the type yet. We have to make sure it is
10488 // verified, since that sets the list of dependencies.
10489 this->verify();
10491 // Convert all the dependencies. If they refer indirectly back to
10492 // this type, they will pick up the intermediate representation we just
10493 // created.
10494 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10495 p != this->dependencies_.end();
10496 ++p)
10497 (*p)->convert(gogo);
10499 // Complete this type.
10500 Btype* bt = this->named_btype_;
10501 Type* base = this->type_->base();
10502 switch (base->classification())
10504 case TYPE_VOID:
10505 case TYPE_BOOLEAN:
10506 case TYPE_INTEGER:
10507 case TYPE_FLOAT:
10508 case TYPE_COMPLEX:
10509 case TYPE_STRING:
10510 case TYPE_NIL:
10511 break;
10513 case TYPE_MAP:
10514 case TYPE_CHANNEL:
10515 break;
10517 case TYPE_FUNCTION:
10518 case TYPE_POINTER:
10519 // The size of these types is already correct. We don't worry
10520 // about filling them in until later, when we also track
10521 // circular references.
10522 break;
10524 case TYPE_STRUCT:
10526 std::vector<Backend::Btyped_identifier> bfields;
10527 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10528 true, &bfields);
10529 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10530 bt = gogo->backend()->error_type();
10532 break;
10534 case TYPE_ARRAY:
10535 // Slice types were completed in create_placeholder.
10536 if (!base->is_slice_type())
10538 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10539 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10540 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10541 bt = gogo->backend()->error_type();
10543 break;
10545 case TYPE_INTERFACE:
10546 // Interface types were completed in create_placeholder.
10547 break;
10549 case TYPE_ERROR:
10550 return;
10552 default:
10553 case TYPE_SINK:
10554 case TYPE_CALL_MULTIPLE_RESULT:
10555 case TYPE_NAMED:
10556 case TYPE_FORWARD:
10557 go_unreachable();
10560 this->named_btype_ = bt;
10561 this->is_converted_ = true;
10562 this->is_placeholder_ = false;
10565 // Create the placeholder for a named type. This is the first step in
10566 // converting to the backend representation.
10568 void
10569 Named_type::create_placeholder(Gogo* gogo)
10571 if (this->is_error_)
10572 this->named_btype_ = gogo->backend()->error_type();
10574 if (this->named_btype_ != NULL)
10575 return;
10577 // Create the structure for this type. Note that because we call
10578 // base() here, we don't attempt to represent a named type defined
10579 // as another named type. Instead both named types will point to
10580 // different base representations.
10581 Type* base = this->type_->base();
10582 Btype* bt;
10583 bool set_name = true;
10584 switch (base->classification())
10586 case TYPE_ERROR:
10587 this->is_error_ = true;
10588 this->named_btype_ = gogo->backend()->error_type();
10589 return;
10591 case TYPE_VOID:
10592 case TYPE_BOOLEAN:
10593 case TYPE_INTEGER:
10594 case TYPE_FLOAT:
10595 case TYPE_COMPLEX:
10596 case TYPE_STRING:
10597 case TYPE_NIL:
10598 // These are simple basic types, we can just create them
10599 // directly.
10600 bt = Type::get_named_base_btype(gogo, base);
10601 break;
10603 case TYPE_MAP:
10604 case TYPE_CHANNEL:
10605 // All maps and channels have the same backend representation.
10606 bt = Type::get_named_base_btype(gogo, base);
10607 break;
10609 case TYPE_FUNCTION:
10610 case TYPE_POINTER:
10612 bool for_function = base->classification() == TYPE_FUNCTION;
10613 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10614 this->location_,
10615 for_function);
10616 set_name = false;
10618 break;
10620 case TYPE_STRUCT:
10621 bt = gogo->backend()->placeholder_struct_type(this->name(),
10622 this->location_);
10623 this->is_placeholder_ = true;
10624 set_name = false;
10625 break;
10627 case TYPE_ARRAY:
10628 if (base->is_slice_type())
10629 bt = gogo->backend()->placeholder_struct_type(this->name(),
10630 this->location_);
10631 else
10633 bt = gogo->backend()->placeholder_array_type(this->name(),
10634 this->location_);
10635 this->is_placeholder_ = true;
10637 set_name = false;
10638 break;
10640 case TYPE_INTERFACE:
10641 if (base->interface_type()->is_empty())
10642 bt = Interface_type::get_backend_empty_interface_type(gogo);
10643 else
10645 bt = gogo->backend()->placeholder_struct_type(this->name(),
10646 this->location_);
10647 set_name = false;
10649 break;
10651 default:
10652 case TYPE_SINK:
10653 case TYPE_CALL_MULTIPLE_RESULT:
10654 case TYPE_NAMED:
10655 case TYPE_FORWARD:
10656 go_unreachable();
10659 if (set_name)
10660 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10662 this->named_btype_ = bt;
10664 if (base->is_slice_type())
10666 // We do not record slices as dependencies of other types,
10667 // because we can fill them in completely here with the final
10668 // size.
10669 std::vector<Backend::Btyped_identifier> bfields;
10670 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10671 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10672 this->named_btype_ = gogo->backend()->error_type();
10674 else if (base->interface_type() != NULL
10675 && !base->interface_type()->is_empty())
10677 // We do not record interfaces as dependencies of other types,
10678 // because we can fill them in completely here with the final
10679 // size.
10680 std::vector<Backend::Btyped_identifier> bfields;
10681 get_backend_interface_fields(gogo, base->interface_type(), true,
10682 &bfields);
10683 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10684 this->named_btype_ = gogo->backend()->error_type();
10688 // Get the backend representation for a named type.
10690 Btype*
10691 Named_type::do_get_backend(Gogo* gogo)
10693 if (this->is_error_)
10694 return gogo->backend()->error_type();
10696 Btype* bt = this->named_btype_;
10698 if (!gogo->named_types_are_converted())
10700 // We have not completed converting named types. NAMED_BTYPE_
10701 // is a placeholder and we shouldn't do anything further.
10702 if (bt != NULL)
10703 return bt;
10705 // We don't build dependencies for types whose sizes do not
10706 // change or are not relevant, so we may see them here while
10707 // converting types.
10708 this->create_placeholder(gogo);
10709 bt = this->named_btype_;
10710 go_assert(bt != NULL);
10711 return bt;
10714 // We are not converting types. This should only be called if the
10715 // type has already been converted.
10716 if (!this->is_converted_)
10718 go_assert(saw_errors());
10719 return gogo->backend()->error_type();
10722 go_assert(bt != NULL);
10724 // Complete the backend representation.
10725 Type* base = this->type_->base();
10726 Btype* bt1;
10727 switch (base->classification())
10729 case TYPE_ERROR:
10730 return gogo->backend()->error_type();
10732 case TYPE_VOID:
10733 case TYPE_BOOLEAN:
10734 case TYPE_INTEGER:
10735 case TYPE_FLOAT:
10736 case TYPE_COMPLEX:
10737 case TYPE_STRING:
10738 case TYPE_NIL:
10739 case TYPE_MAP:
10740 case TYPE_CHANNEL:
10741 return bt;
10743 case TYPE_STRUCT:
10744 if (!this->seen_in_get_backend_)
10746 this->seen_in_get_backend_ = true;
10747 base->struct_type()->finish_backend_fields(gogo);
10748 this->seen_in_get_backend_ = false;
10750 return bt;
10752 case TYPE_ARRAY:
10753 if (!this->seen_in_get_backend_)
10755 this->seen_in_get_backend_ = true;
10756 base->array_type()->finish_backend_element(gogo);
10757 this->seen_in_get_backend_ = false;
10759 return bt;
10761 case TYPE_INTERFACE:
10762 if (!this->seen_in_get_backend_)
10764 this->seen_in_get_backend_ = true;
10765 base->interface_type()->finish_backend_methods(gogo);
10766 this->seen_in_get_backend_ = false;
10768 return bt;
10770 case TYPE_FUNCTION:
10771 // Don't build a circular data structure. GENERIC can't handle
10772 // it.
10773 if (this->seen_in_get_backend_)
10775 this->is_circular_ = true;
10776 return gogo->backend()->circular_pointer_type(bt, true);
10778 this->seen_in_get_backend_ = true;
10779 bt1 = Type::get_named_base_btype(gogo, base);
10780 this->seen_in_get_backend_ = false;
10781 if (this->is_circular_)
10782 bt1 = gogo->backend()->circular_pointer_type(bt, true);
10783 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10784 bt = gogo->backend()->error_type();
10785 return bt;
10787 case TYPE_POINTER:
10788 // Don't build a circular data structure. GENERIC can't handle
10789 // it.
10790 if (this->seen_in_get_backend_)
10792 this->is_circular_ = true;
10793 return gogo->backend()->circular_pointer_type(bt, false);
10795 this->seen_in_get_backend_ = true;
10796 bt1 = Type::get_named_base_btype(gogo, base);
10797 this->seen_in_get_backend_ = false;
10798 if (this->is_circular_)
10799 bt1 = gogo->backend()->circular_pointer_type(bt, false);
10800 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10801 bt = gogo->backend()->error_type();
10802 return bt;
10804 default:
10805 case TYPE_SINK:
10806 case TYPE_CALL_MULTIPLE_RESULT:
10807 case TYPE_NAMED:
10808 case TYPE_FORWARD:
10809 go_unreachable();
10812 go_unreachable();
10815 // Build a type descriptor for a named type.
10817 Expression*
10818 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10820 if (this->is_error_)
10821 return Expression::make_error(this->location_);
10822 if (name == NULL && this->is_alias_)
10824 if (this->seen_alias_)
10825 return Expression::make_error(this->location_);
10826 this->seen_alias_ = true;
10827 Expression* ret = this->type_->type_descriptor(gogo, NULL);
10828 this->seen_alias_ = false;
10829 return ret;
10832 // If NAME is not NULL, then we don't really want the type
10833 // descriptor for this type; we want the descriptor for the
10834 // underlying type, giving it the name NAME.
10835 return this->named_type_descriptor(gogo, this->type_,
10836 name == NULL ? this : name);
10839 // Add to the reflection string. This is used mostly for the name of
10840 // the type used in a type descriptor, not for actual reflection
10841 // strings.
10843 void
10844 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
10846 this->append_reflection_type_name(gogo, false, ret);
10849 // Add to the reflection string. For an alias we normally use the
10850 // real name, but if USE_ALIAS is true we use the alias name itself.
10852 void
10853 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
10854 std::string* ret) const
10856 if (this->is_error_)
10857 return;
10858 if (this->is_alias_ && !use_alias)
10860 if (this->seen_alias_)
10861 return;
10862 this->seen_alias_ = true;
10863 this->append_reflection(this->type_, gogo, ret);
10864 this->seen_alias_ = false;
10865 return;
10867 if (!this->is_builtin())
10869 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
10870 // make a unique reflection string, so that the type
10871 // canonicalization in the reflect package will work. In order
10872 // to be compatible with the gc compiler, we put tabs into the
10873 // package path, so that the reflect methods can discard it.
10874 const Package* package = this->named_object_->package();
10875 ret->push_back('\t');
10876 ret->append(package != NULL
10877 ? package->pkgpath_symbol()
10878 : gogo->pkgpath_symbol());
10879 ret->push_back('\t');
10880 ret->append(package != NULL
10881 ? package->package_name()
10882 : gogo->package_name());
10883 ret->push_back('.');
10885 if (this->in_function_ != NULL)
10887 ret->push_back('\t');
10888 const Typed_identifier* rcvr =
10889 this->in_function_->func_value()->type()->receiver();
10890 if (rcvr != NULL)
10892 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
10893 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
10894 ret->push_back('.');
10896 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
10897 ret->push_back('$');
10898 if (this->in_function_index_ > 0)
10900 char buf[30];
10901 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
10902 ret->append(buf);
10903 ret->push_back('$');
10905 ret->push_back('\t');
10907 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
10910 // Export the type. This is called to export a global type.
10912 void
10913 Named_type::export_named_type(Export* exp, const std::string&) const
10915 // We don't need to write the name of the type here, because it will
10916 // be written by Export::write_type anyhow.
10917 exp->write_c_string("type ");
10918 exp->write_type(this);
10919 exp->write_c_string(";\n");
10922 // Import a named type.
10924 void
10925 Named_type::import_named_type(Import* imp, Named_type** ptype)
10927 imp->require_c_string("type ");
10928 Type *type = imp->read_type();
10929 *ptype = type->named_type();
10930 go_assert(*ptype != NULL);
10931 imp->require_c_string(";\n");
10934 // Export the type when it is referenced by another type. In this
10935 // case Export::export_type will already have issued the name.
10937 void
10938 Named_type::do_export(Export* exp) const
10940 exp->write_type(this->type_);
10942 // To save space, we only export the methods directly attached to
10943 // this type.
10944 Bindings* methods = this->local_methods_;
10945 if (methods == NULL)
10946 return;
10948 exp->write_c_string("\n");
10949 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10950 p != methods->end_definitions();
10951 ++p)
10953 exp->write_c_string(" ");
10954 (*p)->export_named_object(exp);
10957 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10958 p != methods->end_declarations();
10959 ++p)
10961 if (p->second->is_function_declaration())
10963 exp->write_c_string(" ");
10964 p->second->export_named_object(exp);
10969 // Make a named type.
10971 Named_type*
10972 Type::make_named_type(Named_object* named_object, Type* type,
10973 Location location)
10975 return new Named_type(named_object, type, location);
10978 // Finalize the methods for TYPE. It will be a named type or a struct
10979 // type. This sets *ALL_METHODS to the list of methods, and builds
10980 // all required stubs.
10982 void
10983 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10984 Methods** all_methods)
10986 *all_methods = new Methods();
10987 std::vector<const Named_type*> seen;
10988 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10989 if ((*all_methods)->empty())
10991 delete *all_methods;
10992 *all_methods = NULL;
10994 Type::build_stub_methods(gogo, type, *all_methods, location);
10997 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
10998 // build up the struct field indexes as we go. DEPTH is the depth of
10999 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11000 // adding these methods for an anonymous field with pointer type.
11001 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11002 // calls the real method. TYPES_SEEN is used to avoid infinite
11003 // recursion.
11005 void
11006 Type::add_methods_for_type(const Type* type,
11007 const Method::Field_indexes* field_indexes,
11008 unsigned int depth,
11009 bool is_embedded_pointer,
11010 bool needs_stub_method,
11011 std::vector<const Named_type*>* seen,
11012 Methods* methods)
11014 // Pointer types may not have methods.
11015 if (type->points_to() != NULL)
11016 return;
11018 const Named_type* nt = type->named_type();
11019 if (nt != NULL)
11021 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11022 p != seen->end();
11023 ++p)
11025 if (*p == nt)
11026 return;
11029 seen->push_back(nt);
11031 Type::add_local_methods_for_type(nt, field_indexes, depth,
11032 is_embedded_pointer, needs_stub_method,
11033 methods);
11036 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11037 is_embedded_pointer, needs_stub_method,
11038 seen, methods);
11040 // If we are called with depth > 0, then we are looking at an
11041 // anonymous field of a struct. If such a field has interface type,
11042 // then we need to add the interface methods. We don't want to add
11043 // them when depth == 0, because we will already handle them
11044 // following the usual rules for an interface type.
11045 if (depth > 0)
11046 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11048 if (nt != NULL)
11049 seen->pop_back();
11052 // Add the local methods for the named type NT to *METHODS. The
11053 // parameters are as for add_methods_to_type.
11055 void
11056 Type::add_local_methods_for_type(const Named_type* nt,
11057 const Method::Field_indexes* field_indexes,
11058 unsigned int depth,
11059 bool is_embedded_pointer,
11060 bool needs_stub_method,
11061 Methods* methods)
11063 const Bindings* local_methods = nt->local_methods();
11064 if (local_methods == NULL)
11065 return;
11067 for (Bindings::const_declarations_iterator p =
11068 local_methods->begin_declarations();
11069 p != local_methods->end_declarations();
11070 ++p)
11072 Named_object* no = p->second;
11073 bool is_value_method = (is_embedded_pointer
11074 || !Type::method_expects_pointer(no));
11075 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11076 (needs_stub_method || depth > 0));
11077 if (!methods->insert(no->name(), m))
11078 delete m;
11082 // Add the embedded methods for TYPE to *METHODS. These are the
11083 // methods attached to anonymous fields. The parameters are as for
11084 // add_methods_to_type.
11086 void
11087 Type::add_embedded_methods_for_type(const Type* type,
11088 const Method::Field_indexes* field_indexes,
11089 unsigned int depth,
11090 bool is_embedded_pointer,
11091 bool needs_stub_method,
11092 std::vector<const Named_type*>* seen,
11093 Methods* methods)
11095 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11096 // struct.
11097 const Struct_type* st = type->struct_type();
11098 if (st == NULL)
11099 return;
11101 const Struct_field_list* fields = st->fields();
11102 if (fields == NULL)
11103 return;
11105 unsigned int i = 0;
11106 for (Struct_field_list::const_iterator pf = fields->begin();
11107 pf != fields->end();
11108 ++pf, ++i)
11110 if (!pf->is_anonymous())
11111 continue;
11113 Type* ftype = pf->type();
11114 bool is_pointer = false;
11115 if (ftype->points_to() != NULL)
11117 ftype = ftype->points_to();
11118 is_pointer = true;
11120 Named_type* fnt = ftype->named_type();
11121 if (fnt == NULL)
11123 // This is an error, but it will be diagnosed elsewhere.
11124 continue;
11127 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11128 sub_field_indexes->next = field_indexes;
11129 sub_field_indexes->field_index = i;
11131 Methods tmp_methods;
11132 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11133 (is_embedded_pointer || is_pointer),
11134 (needs_stub_method
11135 || is_pointer
11136 || i > 0),
11137 seen,
11138 &tmp_methods);
11139 // Check if there are promoted methods that conflict with field names and
11140 // don't add them to the method map.
11141 for (Methods::const_iterator p = tmp_methods.begin();
11142 p != tmp_methods.end();
11143 ++p)
11145 bool found = false;
11146 for (Struct_field_list::const_iterator fp = fields->begin();
11147 fp != fields->end();
11148 ++fp)
11150 if (fp->field_name() == p->first)
11152 found = true;
11153 break;
11156 if (!found &&
11157 !methods->insert(p->first, p->second))
11158 delete p->second;
11163 // If TYPE is an interface type, then add its method to *METHODS.
11164 // This is for interface methods attached to an anonymous field. The
11165 // parameters are as for add_methods_for_type.
11167 void
11168 Type::add_interface_methods_for_type(const Type* type,
11169 const Method::Field_indexes* field_indexes,
11170 unsigned int depth,
11171 Methods* methods)
11173 const Interface_type* it = type->interface_type();
11174 if (it == NULL)
11175 return;
11177 const Typed_identifier_list* imethods = it->methods();
11178 if (imethods == NULL)
11179 return;
11181 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11182 pm != imethods->end();
11183 ++pm)
11185 Function_type* fntype = pm->type()->function_type();
11186 if (fntype == NULL)
11188 // This is an error, but it should be reported elsewhere
11189 // when we look at the methods for IT.
11190 continue;
11192 go_assert(!fntype->is_method());
11193 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11194 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11195 field_indexes, depth);
11196 if (!methods->insert(pm->name(), m))
11197 delete m;
11201 // Build stub methods for TYPE as needed. METHODS is the set of
11202 // methods for the type. A stub method may be needed when a type
11203 // inherits a method from an anonymous field. When we need the
11204 // address of the method, as in a type descriptor, we need to build a
11205 // little stub which does the required field dereferences and jumps to
11206 // the real method. LOCATION is the location of the type definition.
11208 void
11209 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11210 Location location)
11212 if (methods == NULL)
11213 return;
11214 for (Methods::const_iterator p = methods->begin();
11215 p != methods->end();
11216 ++p)
11218 Method* m = p->second;
11219 if (m->is_ambiguous() || !m->needs_stub_method())
11220 continue;
11222 const std::string& name(p->first);
11224 // Build a stub method.
11226 const Function_type* fntype = m->type();
11228 static unsigned int counter;
11229 char buf[100];
11230 snprintf(buf, sizeof buf, "$this%u", counter);
11231 ++counter;
11233 Type* receiver_type = const_cast<Type*>(type);
11234 if (!m->is_value_method())
11235 receiver_type = Type::make_pointer_type(receiver_type);
11236 Location receiver_location = m->receiver_location();
11237 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11238 receiver_location);
11240 const Typed_identifier_list* fnparams = fntype->parameters();
11241 Typed_identifier_list* stub_params;
11242 if (fnparams == NULL || fnparams->empty())
11243 stub_params = NULL;
11244 else
11246 // We give each stub parameter a unique name.
11247 stub_params = new Typed_identifier_list();
11248 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11249 pp != fnparams->end();
11250 ++pp)
11252 char pbuf[100];
11253 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11254 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11255 pp->location()));
11256 ++counter;
11260 const Typed_identifier_list* fnresults = fntype->results();
11261 Typed_identifier_list* stub_results;
11262 if (fnresults == NULL || fnresults->empty())
11263 stub_results = NULL;
11264 else
11266 // We create the result parameters without any names, since
11267 // we won't refer to them.
11268 stub_results = new Typed_identifier_list();
11269 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11270 pr != fnresults->end();
11271 ++pr)
11272 stub_results->push_back(Typed_identifier("", pr->type(),
11273 pr->location()));
11276 Function_type* stub_type = Type::make_function_type(receiver,
11277 stub_params,
11278 stub_results,
11279 fntype->location());
11280 if (fntype->is_varargs())
11281 stub_type->set_is_varargs();
11283 // We only create the function in the package which creates the
11284 // type.
11285 const Package* package;
11286 if (type->named_type() == NULL)
11287 package = NULL;
11288 else
11289 package = type->named_type()->named_object()->package();
11290 std::string stub_name = gogo->stub_method_name(package, name);
11291 Named_object* stub;
11292 if (package != NULL)
11293 stub = Named_object::make_function_declaration(stub_name, package,
11294 stub_type, location);
11295 else
11297 stub = gogo->start_function(stub_name, stub_type, false,
11298 fntype->location());
11299 Type::build_one_stub_method(gogo, m, buf, stub_params,
11300 fntype->is_varargs(), location);
11301 gogo->finish_function(fntype->location());
11303 if (type->named_type() == NULL && stub->is_function())
11304 stub->func_value()->set_is_unnamed_type_stub_method();
11305 if (m->nointerface() && stub->is_function())
11306 stub->func_value()->set_nointerface();
11309 m->set_stub_object(stub);
11313 // Build a stub method which adjusts the receiver as required to call
11314 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11315 // PARAMS is the list of function parameters.
11317 void
11318 Type::build_one_stub_method(Gogo* gogo, Method* method,
11319 const char* receiver_name,
11320 const Typed_identifier_list* params,
11321 bool is_varargs,
11322 Location location)
11324 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11325 go_assert(receiver_object != NULL);
11327 Expression* expr = Expression::make_var_reference(receiver_object, location);
11328 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11329 if (expr->type()->points_to() == NULL)
11330 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11332 Expression_list* arguments;
11333 if (params == NULL || params->empty())
11334 arguments = NULL;
11335 else
11337 arguments = new Expression_list();
11338 for (Typed_identifier_list::const_iterator p = params->begin();
11339 p != params->end();
11340 ++p)
11342 Named_object* param = gogo->lookup(p->name(), NULL);
11343 go_assert(param != NULL);
11344 Expression* param_ref = Expression::make_var_reference(param,
11345 location);
11346 arguments->push_back(param_ref);
11350 Expression* func = method->bind_method(expr, location);
11351 go_assert(func != NULL);
11352 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11353 location);
11355 gogo->add_statement(Statement::make_return_from_call(call, location));
11358 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11359 // in reverse order.
11361 Expression*
11362 Type::apply_field_indexes(Expression* expr,
11363 const Method::Field_indexes* field_indexes,
11364 Location location)
11366 if (field_indexes == NULL)
11367 return expr;
11368 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11369 Struct_type* stype = expr->type()->deref()->struct_type();
11370 go_assert(stype != NULL
11371 && field_indexes->field_index < stype->field_count());
11372 if (expr->type()->struct_type() == NULL)
11374 go_assert(expr->type()->points_to() != NULL);
11375 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11376 location);
11377 go_assert(expr->type()->struct_type() == stype);
11379 return Expression::make_field_reference(expr, field_indexes->field_index,
11380 location);
11383 // Return whether NO is a method for which the receiver is a pointer.
11385 bool
11386 Type::method_expects_pointer(const Named_object* no)
11388 const Function_type *fntype;
11389 if (no->is_function())
11390 fntype = no->func_value()->type();
11391 else if (no->is_function_declaration())
11392 fntype = no->func_declaration_value()->type();
11393 else
11394 go_unreachable();
11395 return fntype->receiver()->type()->points_to() != NULL;
11398 // Given a set of methods for a type, METHODS, return the method NAME,
11399 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11400 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11401 // but is ambiguous (and return NULL).
11403 Method*
11404 Type::method_function(const Methods* methods, const std::string& name,
11405 bool* is_ambiguous)
11407 if (is_ambiguous != NULL)
11408 *is_ambiguous = false;
11409 if (methods == NULL)
11410 return NULL;
11411 Methods::const_iterator p = methods->find(name);
11412 if (p == methods->end())
11413 return NULL;
11414 Method* m = p->second;
11415 if (m->is_ambiguous())
11417 if (is_ambiguous != NULL)
11418 *is_ambiguous = true;
11419 return NULL;
11421 return m;
11424 // Return a pointer to the interface method table for TYPE for the
11425 // interface INTERFACE.
11427 Expression*
11428 Type::interface_method_table(Type* type,
11429 Interface_type *interface,
11430 bool is_pointer,
11431 Interface_method_tables** method_tables,
11432 Interface_method_tables** pointer_tables)
11434 go_assert(!interface->is_empty());
11436 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11438 if (*pimt == NULL)
11439 *pimt = new Interface_method_tables(5);
11441 std::pair<Interface_type*, Expression*> val(interface, NULL);
11442 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11444 Location loc = Linemap::predeclared_location();
11445 if (ins.second)
11447 // This is a new entry in the hash table.
11448 go_assert(ins.first->second == NULL);
11449 ins.first->second =
11450 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11452 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11455 // Look for field or method NAME for TYPE. Return an Expression for
11456 // the field or method bound to EXPR. If there is no such field or
11457 // method, give an appropriate error and return an error expression.
11459 Expression*
11460 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11461 const std::string& name,
11462 Location location)
11464 if (type->deref()->is_error_type())
11465 return Expression::make_error(location);
11467 const Named_type* nt = type->deref()->named_type();
11468 const Struct_type* st = type->deref()->struct_type();
11469 const Interface_type* it = type->interface_type();
11471 // If this is a pointer to a pointer, then it is possible that the
11472 // pointed-to type has methods.
11473 bool dereferenced = false;
11474 if (nt == NULL
11475 && st == NULL
11476 && it == NULL
11477 && type->points_to() != NULL
11478 && type->points_to()->points_to() != NULL)
11480 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11481 location);
11482 type = type->points_to();
11483 if (type->deref()->is_error_type())
11484 return Expression::make_error(location);
11485 nt = type->points_to()->named_type();
11486 st = type->points_to()->struct_type();
11487 dereferenced = true;
11490 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11491 || expr->is_addressable());
11492 std::vector<const Named_type*> seen;
11493 bool is_method = false;
11494 bool found_pointer_method = false;
11495 std::string ambig1;
11496 std::string ambig2;
11497 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11498 &seen, NULL, &is_method,
11499 &found_pointer_method, &ambig1, &ambig2))
11501 Expression* ret;
11502 if (!is_method)
11504 go_assert(st != NULL);
11505 if (type->struct_type() == NULL)
11507 if (dereferenced)
11509 go_error_at(location, "pointer type has no field %qs",
11510 Gogo::message_name(name).c_str());
11511 return Expression::make_error(location);
11513 go_assert(type->points_to() != NULL);
11514 expr = Expression::make_dereference(expr,
11515 Expression::NIL_CHECK_DEFAULT,
11516 location);
11517 go_assert(expr->type()->struct_type() == st);
11519 ret = st->field_reference(expr, name, location);
11520 if (ret == NULL)
11522 go_error_at(location, "type has no field %qs",
11523 Gogo::message_name(name).c_str());
11524 return Expression::make_error(location);
11527 else if (it != NULL && it->find_method(name) != NULL)
11528 ret = Expression::make_interface_field_reference(expr, name,
11529 location);
11530 else
11532 Method* m;
11533 if (nt != NULL)
11534 m = nt->method_function(name, NULL);
11535 else if (st != NULL)
11536 m = st->method_function(name, NULL);
11537 else
11538 go_unreachable();
11539 go_assert(m != NULL);
11540 if (dereferenced)
11542 go_error_at(location,
11543 "calling method %qs requires explicit dereference",
11544 Gogo::message_name(name).c_str());
11545 return Expression::make_error(location);
11547 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11548 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11549 ret = m->bind_method(expr, location);
11551 go_assert(ret != NULL);
11552 return ret;
11554 else
11556 if (Gogo::is_erroneous_name(name))
11558 // An error was already reported.
11560 else if (!ambig1.empty())
11561 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11562 Gogo::message_name(name).c_str(), ambig1.c_str(),
11563 ambig2.c_str());
11564 else if (found_pointer_method)
11565 go_error_at(location, "method requires a pointer receiver");
11566 else if (nt == NULL && st == NULL && it == NULL)
11567 go_error_at(location,
11568 ("reference to field %qs in object which "
11569 "has no fields or methods"),
11570 Gogo::message_name(name).c_str());
11571 else
11573 bool is_unexported;
11574 // The test for 'a' and 'z' is to handle builtin names,
11575 // which are not hidden.
11576 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11577 is_unexported = false;
11578 else
11580 std::string unpacked = Gogo::unpack_hidden_name(name);
11581 seen.clear();
11582 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11583 unpacked,
11584 &seen);
11586 if (is_unexported)
11587 go_error_at(location, "reference to unexported field or method %qs",
11588 Gogo::message_name(name).c_str());
11589 else
11590 go_error_at(location, "reference to undefined field or method %qs",
11591 Gogo::message_name(name).c_str());
11593 return Expression::make_error(location);
11597 // Look in TYPE for a field or method named NAME, return true if one
11598 // is found. This looks through embedded anonymous fields and handles
11599 // ambiguity. If a method is found, sets *IS_METHOD to true;
11600 // otherwise, if a field is found, set it to false. If
11601 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11602 // whose address can not be taken. SEEN is used to avoid infinite
11603 // recursion on invalid types.
11605 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11606 // method we couldn't use because it requires a pointer. LEVEL is
11607 // used for recursive calls, and can be NULL for a non-recursive call.
11608 // When this function returns false because it finds that the name is
11609 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11610 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11611 // will be unchanged.
11613 // This function just returns whether or not there is a field or
11614 // method, and whether it is a field or method. It doesn't build an
11615 // expression to refer to it. If it is a method, we then look in the
11616 // list of all methods for the type. If it is a field, the search has
11617 // to be done again, looking only for fields, and building up the
11618 // expression as we go.
11620 bool
11621 Type::find_field_or_method(const Type* type,
11622 const std::string& name,
11623 bool receiver_can_be_pointer,
11624 std::vector<const Named_type*>* seen,
11625 int* level,
11626 bool* is_method,
11627 bool* found_pointer_method,
11628 std::string* ambig1,
11629 std::string* ambig2)
11631 // Named types can have locally defined methods.
11632 const Named_type* nt = type->unalias()->named_type();
11633 if (nt == NULL && type->points_to() != NULL)
11634 nt = type->points_to()->unalias()->named_type();
11635 if (nt != NULL)
11637 Named_object* no = nt->find_local_method(name);
11638 if (no != NULL)
11640 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11642 *is_method = true;
11643 return true;
11646 // Record that we have found a pointer method in order to
11647 // give a better error message if we don't find anything
11648 // else.
11649 *found_pointer_method = true;
11652 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11653 p != seen->end();
11654 ++p)
11656 if (*p == nt)
11658 // We've already seen this type when searching for methods.
11659 return false;
11664 // Interface types can have methods.
11665 const Interface_type* it = type->interface_type();
11666 if (it != NULL && it->find_method(name) != NULL)
11668 *is_method = true;
11669 return true;
11672 // Struct types can have fields. They can also inherit fields and
11673 // methods from anonymous fields.
11674 const Struct_type* st = type->deref()->struct_type();
11675 if (st == NULL)
11676 return false;
11677 const Struct_field_list* fields = st->fields();
11678 if (fields == NULL)
11679 return false;
11681 if (nt != NULL)
11682 seen->push_back(nt);
11684 int found_level = 0;
11685 bool found_is_method = false;
11686 std::string found_ambig1;
11687 std::string found_ambig2;
11688 const Struct_field* found_parent = NULL;
11689 for (Struct_field_list::const_iterator pf = fields->begin();
11690 pf != fields->end();
11691 ++pf)
11693 if (pf->is_field_name(name))
11695 *is_method = false;
11696 if (nt != NULL)
11697 seen->pop_back();
11698 return true;
11701 if (!pf->is_anonymous())
11702 continue;
11704 if (pf->type()->deref()->is_error_type()
11705 || pf->type()->deref()->is_undefined())
11706 continue;
11708 Named_type* fnt = pf->type()->named_type();
11709 if (fnt == NULL)
11710 fnt = pf->type()->deref()->named_type();
11711 go_assert(fnt != NULL);
11713 // Methods with pointer receivers on embedded field are
11714 // inherited by the pointer to struct, and also by the struct
11715 // type if the field itself is a pointer.
11716 bool can_be_pointer = (receiver_can_be_pointer
11717 || pf->type()->points_to() != NULL);
11718 int sublevel = level == NULL ? 1 : *level + 1;
11719 bool sub_is_method;
11720 std::string subambig1;
11721 std::string subambig2;
11722 bool subfound = Type::find_field_or_method(fnt,
11723 name,
11724 can_be_pointer,
11725 seen,
11726 &sublevel,
11727 &sub_is_method,
11728 found_pointer_method,
11729 &subambig1,
11730 &subambig2);
11731 if (!subfound)
11733 if (!subambig1.empty())
11735 // The name was found via this field, but is ambiguous.
11736 // if the ambiguity is lower or at the same level as
11737 // anything else we have already found, then we want to
11738 // pass the ambiguity back to the caller.
11739 if (found_level == 0 || sublevel <= found_level)
11741 found_ambig1 = (Gogo::message_name(pf->field_name())
11742 + '.' + subambig1);
11743 found_ambig2 = (Gogo::message_name(pf->field_name())
11744 + '.' + subambig2);
11745 found_level = sublevel;
11749 else
11751 // The name was found via this field. Use the level to see
11752 // if we want to use this one, or whether it introduces an
11753 // ambiguity.
11754 if (found_level == 0 || sublevel < found_level)
11756 found_level = sublevel;
11757 found_is_method = sub_is_method;
11758 found_ambig1.clear();
11759 found_ambig2.clear();
11760 found_parent = &*pf;
11762 else if (sublevel > found_level)
11764 else if (found_ambig1.empty())
11766 // We found an ambiguity.
11767 go_assert(found_parent != NULL);
11768 found_ambig1 = Gogo::message_name(found_parent->field_name());
11769 found_ambig2 = Gogo::message_name(pf->field_name());
11771 else
11773 // We found an ambiguity, but we already know of one.
11774 // Just report the earlier one.
11779 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
11780 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
11781 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
11782 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
11784 if (nt != NULL)
11785 seen->pop_back();
11787 if (found_level == 0)
11788 return false;
11789 else if (found_is_method
11790 && type->named_type() != NULL
11791 && type->points_to() != NULL)
11793 // If this is a method inherited from a struct field in a named pointer
11794 // type, it is invalid to automatically dereference the pointer to the
11795 // struct to find this method.
11796 if (level != NULL)
11797 *level = found_level;
11798 *is_method = true;
11799 return false;
11801 else if (!found_ambig1.empty())
11803 go_assert(!found_ambig1.empty());
11804 ambig1->assign(found_ambig1);
11805 ambig2->assign(found_ambig2);
11806 if (level != NULL)
11807 *level = found_level;
11808 return false;
11810 else
11812 if (level != NULL)
11813 *level = found_level;
11814 *is_method = found_is_method;
11815 return true;
11819 // Return whether NAME is an unexported field or method for TYPE.
11821 bool
11822 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
11823 const std::string& name,
11824 std::vector<const Named_type*>* seen)
11826 const Named_type* nt = type->named_type();
11827 if (nt == NULL)
11828 nt = type->deref()->named_type();
11829 if (nt != NULL)
11831 if (nt->is_unexported_local_method(gogo, name))
11832 return true;
11834 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11835 p != seen->end();
11836 ++p)
11838 if (*p == nt)
11840 // We've already seen this type.
11841 return false;
11846 const Interface_type* it = type->interface_type();
11847 if (it != NULL && it->is_unexported_method(gogo, name))
11848 return true;
11850 type = type->deref();
11852 const Struct_type* st = type->struct_type();
11853 if (st != NULL && st->is_unexported_local_field(gogo, name))
11854 return true;
11856 if (st == NULL)
11857 return false;
11859 const Struct_field_list* fields = st->fields();
11860 if (fields == NULL)
11861 return false;
11863 if (nt != NULL)
11864 seen->push_back(nt);
11866 for (Struct_field_list::const_iterator pf = fields->begin();
11867 pf != fields->end();
11868 ++pf)
11870 if (pf->is_anonymous()
11871 && !pf->type()->deref()->is_error_type()
11872 && !pf->type()->deref()->is_undefined())
11874 Named_type* subtype = pf->type()->named_type();
11875 if (subtype == NULL)
11876 subtype = pf->type()->deref()->named_type();
11877 if (subtype == NULL)
11879 // This is an error, but it will be diagnosed elsewhere.
11880 continue;
11882 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
11884 if (nt != NULL)
11885 seen->pop_back();
11886 return true;
11891 if (nt != NULL)
11892 seen->pop_back();
11894 return false;
11897 // Class Forward_declaration.
11899 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
11900 : Type(TYPE_FORWARD),
11901 named_object_(named_object->resolve()), warned_(false)
11903 go_assert(this->named_object_->is_unknown()
11904 || this->named_object_->is_type_declaration());
11907 // Return the named object.
11909 Named_object*
11910 Forward_declaration_type::named_object()
11912 return this->named_object_->resolve();
11915 const Named_object*
11916 Forward_declaration_type::named_object() const
11918 return this->named_object_->resolve();
11921 // Return the name of the forward declared type.
11923 const std::string&
11924 Forward_declaration_type::name() const
11926 return this->named_object()->name();
11929 // Warn about a use of a type which has been declared but not defined.
11931 void
11932 Forward_declaration_type::warn() const
11934 Named_object* no = this->named_object_->resolve();
11935 if (no->is_unknown())
11937 // The name was not defined anywhere.
11938 if (!this->warned_)
11940 go_error_at(this->named_object_->location(),
11941 "use of undefined type %qs",
11942 no->message_name().c_str());
11943 this->warned_ = true;
11946 else if (no->is_type_declaration())
11948 // The name was seen as a type, but the type was never defined.
11949 if (no->type_declaration_value()->using_type())
11951 go_error_at(this->named_object_->location(),
11952 "use of undefined type %qs",
11953 no->message_name().c_str());
11954 this->warned_ = true;
11957 else
11959 // The name was defined, but not as a type.
11960 if (!this->warned_)
11962 go_error_at(this->named_object_->location(), "expected type");
11963 this->warned_ = true;
11968 // Get the base type of a declaration. This gives an error if the
11969 // type has not yet been defined.
11971 Type*
11972 Forward_declaration_type::real_type()
11974 if (this->is_defined())
11976 Named_type* nt = this->named_object()->type_value();
11977 if (!nt->is_valid())
11978 return Type::make_error_type();
11979 return this->named_object()->type_value();
11981 else
11983 this->warn();
11984 return Type::make_error_type();
11988 const Type*
11989 Forward_declaration_type::real_type() const
11991 if (this->is_defined())
11993 const Named_type* nt = this->named_object()->type_value();
11994 if (!nt->is_valid())
11995 return Type::make_error_type();
11996 return this->named_object()->type_value();
11998 else
12000 this->warn();
12001 return Type::make_error_type();
12005 // Return whether the base type is defined.
12007 bool
12008 Forward_declaration_type::is_defined() const
12010 return this->named_object()->is_type();
12013 // Add a method. This is used when methods are defined before the
12014 // type.
12016 Named_object*
12017 Forward_declaration_type::add_method(const std::string& name,
12018 Function* function)
12020 Named_object* no = this->named_object();
12021 if (no->is_unknown())
12022 no->declare_as_type();
12023 return no->type_declaration_value()->add_method(name, function);
12026 // Add a method declaration. This is used when methods are declared
12027 // before the type.
12029 Named_object*
12030 Forward_declaration_type::add_method_declaration(const std::string& name,
12031 Package* package,
12032 Function_type* type,
12033 Location location)
12035 Named_object* no = this->named_object();
12036 if (no->is_unknown())
12037 no->declare_as_type();
12038 Type_declaration* td = no->type_declaration_value();
12039 return td->add_method_declaration(name, package, type, location);
12042 // Add an already created object as a method.
12044 void
12045 Forward_declaration_type::add_existing_method(Named_object* nom)
12047 Named_object* no = this->named_object();
12048 if (no->is_unknown())
12049 no->declare_as_type();
12050 no->type_declaration_value()->add_existing_method(nom);
12053 // Traversal.
12056 Forward_declaration_type::do_traverse(Traverse* traverse)
12058 if (this->is_defined()
12059 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12060 return TRAVERSE_EXIT;
12061 return TRAVERSE_CONTINUE;
12064 // Verify the type.
12066 bool
12067 Forward_declaration_type::do_verify()
12069 if (!this->is_defined() && !this->is_nil_constant_as_type())
12071 this->warn();
12072 return false;
12074 return true;
12077 // Get the backend representation for the type.
12079 Btype*
12080 Forward_declaration_type::do_get_backend(Gogo* gogo)
12082 if (this->is_defined())
12083 return Type::get_named_base_btype(gogo, this->real_type());
12085 if (this->warned_)
12086 return gogo->backend()->error_type();
12088 // We represent an undefined type as a struct with no fields. That
12089 // should work fine for the backend, since the same case can arise
12090 // in C.
12091 std::vector<Backend::Btyped_identifier> fields;
12092 Btype* bt = gogo->backend()->struct_type(fields);
12093 return gogo->backend()->named_type(this->name(), bt,
12094 this->named_object()->location());
12097 // Build a type descriptor for a forwarded type.
12099 Expression*
12100 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12102 Location ploc = Linemap::predeclared_location();
12103 if (!this->is_defined())
12104 return Expression::make_error(ploc);
12105 else
12107 Type* t = this->real_type();
12108 if (name != NULL)
12109 return this->named_type_descriptor(gogo, t, name);
12110 else
12111 return Expression::make_error(this->named_object_->location());
12115 // The reflection string.
12117 void
12118 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12120 this->append_reflection(this->real_type(), gogo, ret);
12123 // Export a forward declaration. This can happen when a defined type
12124 // refers to a type which is only declared (and is presumably defined
12125 // in some other file in the same package).
12127 void
12128 Forward_declaration_type::do_export(Export*) const
12130 // If there is a base type, that should be exported instead of this.
12131 go_assert(!this->is_defined());
12133 // We don't output anything.
12136 // Make a forward declaration.
12138 Type*
12139 Type::make_forward_declaration(Named_object* named_object)
12141 return new Forward_declaration_type(named_object);
12144 // Class Typed_identifier_list.
12146 // Sort the entries by name.
12148 struct Typed_identifier_list_sort
12150 public:
12151 bool
12152 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12154 return (Gogo::unpack_hidden_name(t1.name())
12155 < Gogo::unpack_hidden_name(t2.name()));
12159 void
12160 Typed_identifier_list::sort_by_name()
12162 std::sort(this->entries_.begin(), this->entries_.end(),
12163 Typed_identifier_list_sort());
12166 // Traverse types.
12169 Typed_identifier_list::traverse(Traverse* traverse)
12171 for (Typed_identifier_list::const_iterator p = this->begin();
12172 p != this->end();
12173 ++p)
12175 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12176 return TRAVERSE_EXIT;
12178 return TRAVERSE_CONTINUE;
12181 // Copy the list.
12183 Typed_identifier_list*
12184 Typed_identifier_list::copy() const
12186 Typed_identifier_list* ret = new Typed_identifier_list();
12187 for (Typed_identifier_list::const_iterator p = this->begin();
12188 p != this->end();
12189 ++p)
12190 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12191 return ret;